blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
05b44d16263ca33b022b412e3d1816fe02384bf1 | 4f515d43b685715f0c9f1ed7e24554b539dd76d3 | /src/DsG4Scintillation.cc | b25d4b2fa6115e802f11b316fde8e3a491150483 | [] | no_license | WenjieWu-Sci/simjuno | 8ca365fd9c3041df83a2bb150edd91714740a27c | 1cc6e7bb4926bde7e1d020b7efff7d96b85d3dad | refs/heads/master | 2021-08-26T09:26:24.970843 | 2017-09-30T06:31:08 | 2017-09-30T06:31:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,711 | cc | //
// ********************************************************************
// * DISCLAIMER *
// * *
// * The following disclaimer summarizes all the specific disclaimers *
// * of contributors to this software. The specific disclaimers,which *
// * govern, are listed with their locations in: *
// * http://cern.ch/geant4/license *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. *
// * *
// * This code implementation is the intellectual property of the *
// * GEANT4 collaboration. *
// * By copying, distributing or modifying the Program (or any work *
// * based on the Program) you indicate your acceptance of this *
// * statement, and all its terms. *
// ********************************************************************
//
//
//
// //////////////////////////////////////////////////////////////////////
// Scintillation Light Class Implementation
// //////////////////////////////////////////////////////////////////////
//
// File: G4Scintillation.cc
// Description: RestDiscrete Process - Generation of Scintillation Photons
// Version: 1.0
// Created: 1998-11-07
// Author: Peter Gumplinger
// Updated: 2005-08-17 by Peter Gumplinger
// > change variable name MeanNumPhotons -> MeanNumberOfPhotons
// 2005-07-28 by Peter Gumplinger
// > add G4ProcessType to constructor
// 2004-08-05 by Peter Gumplinger
// > changed StronglyForced back to Forced in GetMeanLifeTime
// 2002-11-21 by Peter Gumplinger
// > change to use G4Poisson for small MeanNumberOfPhotons
// 2002-11-07 by Peter Gumplinger
// > now allow for fast and slow scintillation component
// 2002-11-05 by Peter Gumplinger
// > now use scintillation constants from G4Material
// 2002-05-09 by Peter Gumplinger
// > use only the PostStepPoint location for the origin of
// scintillation photons when energy is lost to the medium
// by a neutral particle
// 2000-09-18 by Peter Gumplinger
// > change: aSecondaryPosition=x0+rand*aStep.GetDeltaPosition();
// aSecondaryTrack->SetTouchable(0);
// 2001-09-17, migration of Materials to pure STL (mma)
// 2003-06-03, V.Ivanchenko fix compilation warnings
//
//mail: gum@triumf.ca
//
//////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------
// DsG4Scintillation is a class modified from G4Scintillation
// Birks' law is implemented
// Author: Liang Zhan, 2006/01/27
// Added weighted photon track method based on GLG4Scint. Jianglai 09/05/2006
// Modified: bv@bnl.gov, 2008/4/16 for DetSim
//--------------------------------------------------------------------
//
//#include <boost/python.hpp>
#include "DsG4Scintillation.h"
#include "G4UnitsTable.hh"
#include "G4LossTableManager.hh"
#include "G4MaterialCutsCouple.hh"
#include "G4Gamma.hh"
#include "G4Electron.hh"
#include "globals.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
//#include "DsPhotonTrackInfo.h"
//#include "G4DataHelpers/G4CompositeTrackInfo.h"
///////////////////////////////////////////////////////////////////
using namespace std;
/////////////////////////
// Class Implementation
/////////////////////////
//////////////
// Operators
//////////////
// DsG4Scintillation::operator=(const DsG4Scintillation &right)
// {
// }
/////////////////
// Constructors
/////////////////
DsG4Scintillation::DsG4Scintillation(const G4String& processName,
G4ProcessType type)
: G4VRestDiscreteProcess(processName, type)
, doReemission(true)
, doBothProcess(true)
, doReemissionOnly(false)
, fEnableQuenching(true)
, slowerTimeConstant(0) , slowerRatio(0)
, gammaSlowerTime(0) , gammaSlowerRatio(0)
, neutronSlowerTime(0) , neutronSlowerRatio(0)
, alphaSlowerTime(0) , alphaSlowerRatio(0)
, flagDecayTimeFast(true), flagDecayTimeSlow(true)
, fPhotonWeight(1.0)
, fApplyPreQE(false)
, fPreQE(1.)
, m_noop(false)
{
SetProcessSubType(fScintillation);
fTrackSecondariesFirst = false;
YieldFactor = 1.0;
ExcitationRatio = 1.0;
theFastIntegralTable = NULL;
theSlowIntegralTable = NULL;
theReemissionIntegralTable = NULL;
verboseLevel = 2;
G4cout << " DsG4Scintillation set verboseLevel by hand to " << verboseLevel << G4endl;
if (verboseLevel > 0) {
G4cout << GetProcessName() << " is created " << G4endl;
}
BuildThePhysicsTable();
}
////////////////
// Destructors
////////////////
DsG4Scintillation::~DsG4Scintillation()
{
if (theFastIntegralTable != NULL) {
theFastIntegralTable->clearAndDestroy();
delete theFastIntegralTable;
}
if (theSlowIntegralTable != NULL) {
theSlowIntegralTable->clearAndDestroy();
delete theSlowIntegralTable;
}
if (theReemissionIntegralTable != NULL) {
theReemissionIntegralTable->clearAndDestroy();
delete theReemissionIntegralTable;
}
}
////////////
// Methods
////////////
// AtRestDoIt
// ----------
//
G4VParticleChange*
DsG4Scintillation::AtRestDoIt(const G4Track& aTrack, const G4Step& aStep)
// This routine simply calls the equivalent PostStepDoIt since all the
// necessary information resides in aStep.GetTotalEnergyDeposit()
{
return DsG4Scintillation::PostStepDoIt(aTrack, aStep);
}
// PostStepDoIt
// -------------
//
G4VParticleChange*
DsG4Scintillation::PostStepDoIt(const G4Track& aTrack, const G4Step& aStep)
// This routine is called for each tracking step of a charged particle
// in a scintillator. A Poisson/Gauss-distributed number of photons is
// generated according to the scintillation yield formula, distributed
// evenly along the track segment and uniformly into 4pi.
{
aParticleChange.Initialize(aTrack);
if (m_noop) { // do nothing, bail
aParticleChange.SetNumberOfSecondaries(0);
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
G4String pname= "";
G4ThreeVector vertpos;
G4double vertenergy=0.0;
G4double reem_d=0.0;
G4bool flagReemission= false;
//DsPhotonTrackInfo* reemittedTI=0;
if (aTrack.GetDefinition() == G4OpticalPhoton::OpticalPhoton()) {
G4Track* track= aStep.GetTrack();
//G4CompositeTrackInfo* composite=dynamic_cast<G4CompositeTrackInfo*>(track->GetUserInformation());
//reemittedTI = composite?dynamic_cast<DsPhotonTrackInfo*>( composite->GetPhotonTrackInfo() ):0;
//const G4VProcess* process = track->GetCreatorProcess();
//if(process) pname = process->GetProcessName();
const G4VProcess* process;
if (track->GetParentID()==0) {
process= aStep.GetPostStepPoint()->GetProcessDefinedStep();
} else {
process= track->GetCreatorProcess();
}
if(process) pname = process->GetProcessName();
if (verboseLevel > 0) {
G4cout<<"Optical photon. Process name is " << pname <<G4endl;
}
if(doBothProcess) {
flagReemission= doReemission
&& aTrack.GetTrackStatus() == fStopAndKill
&& aStep.GetPostStepPoint()->GetStepStatus() != fGeomBoundary;
}
else{
flagReemission= doReemission
&& aTrack.GetTrackStatus() == fStopAndKill
&& aStep.GetPostStepPoint()->GetStepStatus() != fGeomBoundary
&& pname=="Cerenkov";
}
if(verboseLevel > 0) {
G4cout<<"flag of Reemission is "<<flagReemission<<"!!"<<G4endl;
}
if (!flagReemission) {
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
}
G4double TotalEnergyDeposit = aStep.GetTotalEnergyDeposit();
if (verboseLevel > 0 ) {
G4cout << " TotalEnergyDeposit: " << TotalEnergyDeposit
<< " material: " << aTrack.GetMaterial()->GetName() << G4endl;
}
if (TotalEnergyDeposit <= 0.0 && !flagReemission) {
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
const G4DynamicParticle* aParticle = aTrack.GetDynamicParticle();
const G4String aParticleName = aParticle->GetDefinition()->GetParticleName();
const G4Material* aMaterial = aTrack.GetMaterial();
G4MaterialPropertiesTable* aMaterialPropertiesTable= aMaterial->GetMaterialPropertiesTable();
//aMaterialPropertiesTable-> DumpTable();
if (!aMaterialPropertiesTable)
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
G4String FastTimeConstant = "FASTTIMECONSTANT";
G4String SlowTimeConstant = "SLOWTIMECONSTANT";
G4String strYieldRatio = "YIELDRATIO";
// reset the slower time constant and ratio
slowerTimeConstant = 0.0;
slowerRatio = 0.0;
if (aParticleName == "opticalphoton") {
FastTimeConstant = "ReemissionFASTTIMECONSTANT";
SlowTimeConstant = "ReemissionSLOWTIMECONSTANT";
strYieldRatio = "ReemissionYIELDRATIO";
}
else if(aParticleName == "gamma" || aParticleName == "e+" || aParticleName == "e-") {
FastTimeConstant = "GammaFASTTIMECONSTANT";
SlowTimeConstant = "GammaSLOWTIMECONSTANT";
strYieldRatio = "GammaYIELDRATIO";
slowerTimeConstant = gammaSlowerTime;
slowerRatio = gammaSlowerRatio;
}
else if(aParticleName == "alpha") {
FastTimeConstant = "AlphaFASTTIMECONSTANT";
SlowTimeConstant = "AlphaSLOWTIMECONSTANT";
strYieldRatio = "AlphaYIELDRATIO";
slowerTimeConstant = alphaSlowerTime;
slowerRatio = alphaSlowerRatio;
}
else {
FastTimeConstant = "NeutronFASTTIMECONSTANT";
SlowTimeConstant = "NeutronSLOWTIMECONSTANT";
strYieldRatio = "NeutronYIELDRATIO";
slowerTimeConstant = neutronSlowerTime;
slowerRatio = neutronSlowerRatio;
}
const G4MaterialPropertyVector* Fast_Intensity= aMaterialPropertiesTable->GetProperty("FASTCOMPONENT");
const G4MaterialPropertyVector* Slow_Intensity= aMaterialPropertiesTable->GetProperty("SLOWCOMPONENT");
const G4MaterialPropertyVector* Reemission_Prob= aMaterialPropertiesTable->GetProperty("REEMISSIONPROB");
if (verboseLevel > 0 ) {
G4cout << " MaterialPropertyVectors: Fast_Intensity " << Fast_Intensity
<< " Slow_Intensity " << Slow_Intensity
<< " Reemission_Prob " << Reemission_Prob << G4endl;
}
if (!Fast_Intensity && !Slow_Intensity )
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
G4int nscnt = 1;
if (Fast_Intensity && Slow_Intensity) nscnt = 2;
if ( verboseLevel > 0) {
G4cout << " Fast_Intensity " << Fast_Intensity
<< " Slow_Intensity " << Slow_Intensity
<< " nscnt " << nscnt << G4endl;
}
G4StepPoint* pPreStepPoint = aStep.GetPreStepPoint();
G4StepPoint* pPostStepPoint = aStep.GetPostStepPoint();
G4ThreeVector x0 = pPreStepPoint->GetPosition();
G4ThreeVector p0 = aStep.GetDeltaPosition().unit();
G4double t0 = pPreStepPoint->GetGlobalTime();
//Replace NumPhotons by NumTracks
G4int NumTracks=0;
G4double weight=1.0;
if (flagReemission) {
if(verboseLevel > 0){
G4cout<<"the process name is "<<pname<<"!!"<<G4endl;}
if ( Reemission_Prob == 0)
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
G4double p_reemission= Reemission_Prob->Value(aTrack.GetKineticEnergy());
if (G4UniformRand() >= p_reemission)
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
NumTracks= 1;
weight= aTrack.GetWeight();
if (verboseLevel > 0 ) {
G4cout << " flagReemission " << flagReemission << " weight " << weight << G4endl;}
}
else {
//////////////////////////////////// Birks' law ////////////////////////
// J.B.Birks. The theory and practice of Scintillation Counting.
// Pergamon Press, 1964.
// For particles with energy much smaller than minimum ionization
// energy, the scintillation response is non-linear because of quenching
// effect. The light output is reduced by a parametric factor:
// 1/(1 + birk1*delta + birk2* delta^2).
// Delta is the energy loss per unit mass thickness. birk1 and birk2
// were measured for several organic scintillators.
// Here we use birk1 = 0.0125*g/cm2/MeV and ignore birk2.
// R.L.Craun and D.L.Smith. Nucl. Inst. and Meth., 80:239-244, 1970.
// Liang Zhan 01/27/2006
// /////////////////////////////////////////////////////////////////////
G4double ScintillationYield = 0;
{// Yield. Material must have this or we lack raisins dayetras
// const G4MaterialPropertyVector* ptable = aMaterialPropertiesTable->GetConstProperty("SCINTILLATIONYIELD");
const G4double ptable = aMaterialPropertiesTable->GetConstProperty("SCINTILLATIONYIELD");
if (!ptable) {
G4cout << "ConstProperty: failed to get SCINTILLATIONYIELD"
<< G4endl;
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
ScintillationYield = ptable;
G4cout << "Scintillation yield is : " << ScintillationYield << G4endl;
}
G4double ResolutionScale = 1;
{// Resolution Scale
// const G4MaterialPropertyVector* ptable = aMaterialPropertiesTable->GetProperty("RESOLUTIONSCALE");
const G4double ptable = aMaterialPropertiesTable->GetConstProperty("RESOLUTIONSCALE");
if (ptable)
ResolutionScale = ptable;
}
G4double dE = TotalEnergyDeposit;
G4double dx = aStep.GetStepLength();
G4double dE_dx = dE/dx;
if(aTrack.GetDefinition() == G4Gamma::Gamma() && dE > 0)
{
G4LossTableManager* manager = G4LossTableManager::Instance();
dE_dx = dE/manager->GetRange(G4Electron::Electron(), dE, aTrack.GetMaterialCutsCouple());
//G4cout<<"gamma dE_dx = "<<dE_dx/(MeV/mm)<<"MeV/mm"<<G4endl;
}
G4double delta = dE_dx/aMaterial->GetDensity();//get scintillator density
//G4double birk1 = 0.0125*g/cm2/MeV;
G4double birk1 = birksConstant1;
if(abs(aParticle->GetCharge())>1.5)//for particle charge greater than 1.
birk1 = 0.57*birk1;
G4double birk2 = 0;
//birk2 = (0.0031*g/MeV/cm2)*(0.0031*g/MeV/cm2);
birk2 = birksConstant2;
G4double QuenchedTotalEnergyDeposit = TotalEnergyDeposit;
// if quenching is enabled, apply the birks law
if (fEnableQuenching) {
QuenchedTotalEnergyDeposit
= TotalEnergyDeposit/(1+birk1*delta+birk2*delta*delta);
}
//Add 300ns trick for muon simuation, by Haoqi Jan 27, 2011
if(FastMu300nsTrick) {
// cout<<"GlobalTime ="<<aStep.GetTrack()->GetGlobalTime()/ns<<endl;
if(aStep.GetTrack()->GetGlobalTime()/ns>300) {
ScintillationYield = YieldFactor * ScintillationYield;
}
else{
ScintillationYield=0.;
}
}
else {
ScintillationYield = YieldFactor * ScintillationYield;
}
G4double MeanNumberOfPhotons= ScintillationYield * QuenchedTotalEnergyDeposit;
// Implemented the fast simulation method from GLG4Scint
// Jianglai 09-05-2006
// randomize number of TRACKS (not photons)
// this gets statistics right for number of PE after applying
// boolean random choice to final absorbed track (change from
// old method of applying binomial random choice to final absorbed
// track, which did want poissonian number of photons divided
// as evenly as possible into tracks)
// Note for weight=1, there's no difference between tracks and photons.
G4double MeanNumberOfTracks= MeanNumberOfPhotons/fPhotonWeight;
if ( fApplyPreQE ) {
MeanNumberOfTracks*=fPreQE;
}
if (MeanNumberOfTracks > 10.) {
G4double sigma = ResolutionScale * sqrt(MeanNumberOfTracks);
NumTracks = G4int(G4RandGauss::shoot(MeanNumberOfTracks,sigma)+0.5);
}
else {
NumTracks = G4int(G4Poisson(MeanNumberOfTracks));
}
if ( verboseLevel > 0 ) {
G4cout << " Generated " << NumTracks << " scint photons. mean(scint photons) = " << MeanNumberOfTracks << G4endl;
}
}
weight*=fPhotonWeight;
if ( verboseLevel > 0 ) {
G4cout << " set scint photon weight to " << weight << " after multiplying original weight by fPhotonWeight " << fPhotonWeight
<< " NumTracks = " << NumTracks
<< G4endl;
}
// G4cerr<<"Scint weight is "<<weight<<G4endl;
if (NumTracks <= 0) {
// return unchanged particle and no secondaries
aParticleChange.SetNumberOfSecondaries(0);
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
////////////////////////////////////////////////////////////////
aParticleChange.SetNumberOfSecondaries(NumTracks);
if (fTrackSecondariesFirst) {
if (!flagReemission)
if (aTrack.GetTrackStatus() == fAlive )
aParticleChange.ProposeTrackStatus(fSuspend);
}
////////////////////////////////////////////////////////////////
G4int materialIndex = aMaterial->GetIndex();
G4PhysicsOrderedFreeVector* ReemissionIntegral = NULL;
ReemissionIntegral =
(G4PhysicsOrderedFreeVector*)((*theReemissionIntegralTable)(materialIndex));
// Retrieve the Scintillation Integral for this material
// new G4PhysicsOrderedFreeVector allocated to hold CII's
G4int Num = NumTracks; //# tracks is now the loop control
G4double fastTimeConstant = 0.0;
if (flagDecayTimeFast) { // Fast Time Constant
// const G4MaterialPropertyVector* ptable= aMaterialPropertiesTable->GetConstProperty(FastTimeConstant.c_str());
G4double ptable;
if (aMaterialPropertiesTable->ConstPropertyExists(FastTimeConstant.c_str())) {
ptable= aMaterialPropertiesTable->GetConstProperty(FastTimeConstant.c_str());
} else if (aMaterialPropertiesTable->ConstPropertyExists("FASTTIMECONSTANT")) {
ptable= aMaterialPropertiesTable->GetConstProperty("FASTTIMECONSTANT");
}
if (verboseLevel > 0) {
G4cout << " MaterialPropertyVector table " << ptable << " for FASTTIMECONSTANT"<<G4endl;
}
if (ptable) {
fastTimeConstant = ptable;
// if (verboseLevel > 0) {
// G4cout << " dump fast time constant table " << G4endl;
// const_cast <G4MaterialPropertyVector*>(ptable)->DumpValues();
// }
}
}
G4double slowTimeConstant = 0.0;
if (flagDecayTimeSlow) { // Slow Time Constant
// const G4MaterialPropertyVector* ptable = aMaterialPropertiesTable->GetProperty(SlowTimeConstant.c_str());
G4double ptable;
if (aMaterialPropertiesTable->ConstPropertyExists(SlowTimeConstant.c_str())) {
ptable= aMaterialPropertiesTable->GetConstProperty(SlowTimeConstant.c_str());
} else if (aMaterialPropertiesTable->ConstPropertyExists("SLOWTIMECONSTANT")) {
ptable = aMaterialPropertiesTable->GetConstProperty("SLOWTIMECONSTANT");
}
if (verboseLevel > 0) {
G4cout << " MaterialPropertyVector table " << ptable << " for SLOWTIMECONSTANT"<<G4endl;
}
if (ptable){
slowTimeConstant = ptable;
// if (verboseLevel > 0) {
// G4cout << " dump slow time constant table " << G4endl;
// const_cast <G4MaterialPropertyVector*>(ptable)->DumpVector();
// }
}
}
G4double YieldRatio = 0.0;
{
G4double ptable;
if (aMaterialPropertiesTable->ConstPropertyExists(strYieldRatio.c_str())) {
ptable = aMaterialPropertiesTable->GetConstProperty(strYieldRatio.c_str());
} else if (aMaterialPropertiesTable->ConstPropertyExists("YIELDRATIO")) {
ptable = aMaterialPropertiesTable->GetConstProperty("YIELDRATIO");
}
if (ptable) {
YieldRatio = ptable;
if (verboseLevel > 0) {
G4cout << " YieldRatio = "<< YieldRatio << " (yield ratio = fast/(fast+slow): " << G4endl;
// const_cast <G4MaterialPropertyVector*>(ptable)->DumpVector();
}
}
}
//loop over fast/slow scintillations
for (G4int scnt = 1; scnt <= nscnt; scnt++) {
G4double ScintillationTime = 0.*ns;
G4PhysicsOrderedFreeVector* ScintillationIntegral = NULL;
if (scnt == 1) {//fast
if (nscnt == 1) {
if(Fast_Intensity){
ScintillationTime = fastTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theFastIntegralTable)(materialIndex));
}
if(Slow_Intensity){
ScintillationTime = slowTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theSlowIntegralTable)(materialIndex));
}
}
else {
if ( ExcitationRatio == 1.0 ) {
Num = G4int( 0.5 + (min(YieldRatio,1.0) * NumTracks) ); // round off, not truncation
}
else {
Num = G4int( 0.5 + (min(ExcitationRatio,1.0) * NumTracks));
}
if ( verboseLevel>1 ){
G4cout << "Generate Num " << Num << " optical photons with fast component using NumTracks "
<< NumTracks << " YieldRatio " << YieldRatio << " ExcitationRatio " << ExcitationRatio
<< " min(YieldRatio,1.)*NumTracks = " << min(YieldRatio,1.)*NumTracks
<< " min(ExcitationRatio,1.)*NumTracks = " << min(ExcitationRatio,1.)*NumTracks
<< G4endl;
}
ScintillationTime = fastTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theFastIntegralTable)(materialIndex));
}
}
else {//slow
Num = NumTracks - Num;
ScintillationTime = slowTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theSlowIntegralTable)(materialIndex));
}
if (verboseLevel > 0) {
G4cout << "generate " << Num << " optical photons with scintTime " << ScintillationTime
<< " slowTimeConstant " << slowTimeConstant << " fastTimeConstant " << fastTimeConstant << G4endl;
}
if (!ScintillationIntegral) continue;
// Max Scintillation Integral
for (G4int i = 0; i < Num; i++) { //Num is # of 2ndary tracks now
// Determine photon energy
if(scnt == 2) {
ScintillationTime = slowTimeConstant;
if(flagDecayTimeSlow && G4UniformRand() < slowerRatio && (!flagReemission)) ScintillationTime = slowerTimeConstant;
}
G4double sampledEnergy;
if ( !flagReemission ) {
// normal scintillation
G4double CIIvalue = G4UniformRand()*ScintillationIntegral->GetMaxValue();
sampledEnergy= ScintillationIntegral->GetEnergy(CIIvalue);
if (verboseLevel>1)
{
G4cout << "sampledEnergy = " << sampledEnergy << G4endl;
G4cout << "CIIvalue = " << CIIvalue << G4endl;
}
}
else {
// reemission, the sample method need modification
G4double CIIvalue = G4UniformRand()*
ScintillationIntegral->GetMaxValue();
if (CIIvalue == 0.0) {
// return unchanged particle and no secondaries
aParticleChange.SetNumberOfSecondaries(0);
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
sampledEnergy=
ScintillationIntegral->GetEnergy(CIIvalue);
if (verboseLevel>1) {
G4cout << "oldEnergy = " <<aTrack.GetKineticEnergy() << G4endl;
G4cout << "reemittedSampledEnergy = " << sampledEnergy
<< "\nreemittedCIIvalue = " << CIIvalue << G4endl;
}
}
// Generate random photon direction
G4double cost = 1. - 2.*G4UniformRand();
G4double sint = sqrt((1.-cost)*(1.+cost));
G4double phi = twopi*G4UniformRand();
G4double sinp = sin(phi);
G4double cosp = cos(phi);
G4double px = sint*cosp;
G4double py = sint*sinp;
G4double pz = cost;
// Create photon momentum direction vector
G4ParticleMomentum photonMomentum(px, py, pz);
// Determine polarization of new photon
G4double sx = cost*cosp;
G4double sy = cost*sinp;
G4double sz = -sint;
G4ThreeVector photonPolarization(sx, sy, sz);
G4ThreeVector perp = photonMomentum.cross(photonPolarization);
phi = twopi*G4UniformRand();
sinp = sin(phi);
cosp = cos(phi);
photonPolarization = cosp * photonPolarization + sinp * perp;
photonPolarization = photonPolarization.unit();
// Generate a new photon:
G4DynamicParticle* aScintillationPhoton =
new G4DynamicParticle(G4OpticalPhoton::OpticalPhoton(),
photonMomentum);
aScintillationPhoton->SetPolarization
(photonPolarization.x(),
photonPolarization.y(),
photonPolarization.z());
aScintillationPhoton->SetKineticEnergy(sampledEnergy);
// Generate new G4Track object:
G4double rand=0;
G4ThreeVector aSecondaryPosition;
G4double deltaTime;
if (flagReemission) {
deltaTime= pPostStepPoint->GetGlobalTime() - t0
-ScintillationTime * log( G4UniformRand() );
aSecondaryPosition= pPostStepPoint->GetPosition();
vertpos = aTrack.GetVertexPosition();
vertenergy = aTrack.GetKineticEnergy();
reem_d =
sqrt( pow( aSecondaryPosition.x()-vertpos.x(), 2)
+ pow( aSecondaryPosition.y()-vertpos.y(), 2)
+ pow( aSecondaryPosition.z()-vertpos.z(), 2) );
}
else {
if (aParticle->GetDefinition()->GetPDGCharge() != 0)
{
rand = G4UniformRand();
}
else
{
rand = 1.0;
}
G4double delta = rand * aStep.GetStepLength();
deltaTime = delta /
((pPreStepPoint->GetVelocity()+
pPostStepPoint->GetVelocity())/2.);
deltaTime = deltaTime -
ScintillationTime * log( G4UniformRand() );
aSecondaryPosition =
x0 + rand * aStep.GetDeltaPosition();
}
G4double aSecondaryTime = t0 + deltaTime;
if ( verboseLevel>1 ){
G4cout << "Generate " << i << "th scintillation photon at relative time(ns) " << deltaTime
<< " with ScintillationTime " << ScintillationTime << " flagReemission " << flagReemission << G4endl;
}
G4Track* aSecondaryTrack =
new G4Track(aScintillationPhoton,aSecondaryTime,aSecondaryPosition);
//G4CompositeTrackInfo* comp=new G4CompositeTrackInfo();
//DsPhotonTrackInfo* trackinf=new DsPhotonTrackInfo();
//if ( flagReemission ){
// if ( reemittedTI ) *trackinf = *reemittedTI;
// trackinf->SetReemitted();
//}
//else if ( fApplyPreQE ) {
// trackinf->SetMode(DsPhotonTrackInfo::kQEPreScale);
// trackinf->SetQE(fPreQE);
//}
//comp->SetPhotonTrackInfo(trackinf);
//aSecondaryTrack->SetUserInformation(comp);
aSecondaryTrack->SetWeight( weight );
aSecondaryTrack->SetTouchableHandle(aStep.GetPreStepPoint()->GetTouchableHandle());
// aSecondaryTrack->SetTouchableHandle((G4VTouchable*)0);//this is wrong
aSecondaryTrack->SetParentID(aTrack.GetTrackID());
// add the secondary to the ParticleChange object
aParticleChange.SetSecondaryWeightByProcess( true ); // recommended
aParticleChange.AddSecondary(aSecondaryTrack);
aSecondaryTrack->SetWeight( weight );
if ( verboseLevel > 0 ) {
G4cout << " aSecondaryTrack->SetWeight( " << weight
<< " ) ; aSecondaryTrack->GetWeight() = " << aSecondaryTrack->GetWeight()
<< G4endl;
}
// The above line is necessary because AddSecondary()
// overrides our setting of the secondary track weight,
// in Geant4.3.1 & earlier. (and also later, at least
// until Geant4.7 (and beyond?)
// -- maybe not required if SetWeightByProcess(true) called,
// but we do both, just to be sure)
}
} // end loop over fast/slow scints
if (verboseLevel > 0) {
G4cout << "\n Exiting from G4Scintillation::DoIt -- NumberOfSecondaries = "
<< aParticleChange.GetNumberOfSecondaries() << G4endl;
}
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
// BuildThePhysicsTable for the scintillation process
// --------------------------------------------------
//
void DsG4Scintillation::BuildThePhysicsTable()
{
if (theFastIntegralTable && theSlowIntegralTable && theReemissionIntegralTable) return;
const G4MaterialTable* theMaterialTable= G4Material::GetMaterialTable();
G4int numOfMaterials= G4Material::GetNumberOfMaterials();
// create new physics table
if (verboseLevel > 0) {
G4cout << G4endl;
G4cout << " theFastIntegralTable " << theFastIntegralTable
<< " theSlowIntegralTable " << theSlowIntegralTable
<< " theReemissionIntegralTable " << theReemissionIntegralTable << G4endl;
}
if(!theFastIntegralTable) theFastIntegralTable = new G4PhysicsTable(numOfMaterials);
if(!theSlowIntegralTable) theSlowIntegralTable = new G4PhysicsTable(numOfMaterials);
if(!theReemissionIntegralTable) theReemissionIntegralTable
= new G4PhysicsTable(numOfMaterials);
if (verboseLevel > 0) {
G4cout << " building the physics tables for the scintillation process " << G4endl;
}
// loop for materials
for (G4int i=0 ; i < numOfMaterials; i++) {
G4PhysicsOrderedFreeVector* aPhysicsOrderedFreeVector =
new G4PhysicsOrderedFreeVector();
G4PhysicsOrderedFreeVector* bPhysicsOrderedFreeVector =
new G4PhysicsOrderedFreeVector();
G4PhysicsOrderedFreeVector* cPhysicsOrderedFreeVector =
new G4PhysicsOrderedFreeVector();
// Retrieve vector of scintillation wavelength intensity for
// the material from the material's optical properties table.
G4Material* aMaterial = (*theMaterialTable)[i];
G4cout << " material : " << aMaterial->GetName() << G4endl;
G4MaterialPropertiesTable* aMaterialPropertiesTable =
aMaterial->GetMaterialPropertiesTable();
if (aMaterialPropertiesTable) {
G4MaterialPropertyVector* theFastLightVector =
aMaterialPropertiesTable->GetProperty("FASTCOMPONENT");
if (theFastLightVector) {
if (verboseLevel > 0) {
G4cout << " Building the material properties table for FASTCOMPONENT" << G4endl;
}
// Retrieve the first intensity point in vector
// of (photon energy, intensity) pairs
// theFastLightVector->ResetIterator();
// ++(*theFastLightVector); // advance to 1st entry
G4double currentIN= (*theFastLightVector)[0];
if (currentIN >= 0.0) {
// Create first (photon energy, Scintillation
// Integral pair
G4double currentPM= theFastLightVector->Energy(0);
G4double currentCII = 0.0;
aPhysicsOrderedFreeVector->InsertValues(currentPM , currentCII);
// Set previous values to current ones prior to loop
G4double prevPM = currentPM;
G4double prevCII = currentCII;
G4double prevIN = currentIN;
// loop over all (photon energy, intensity)
// pairs stored for this material
for (size_t ii= 1;
ii< theFastLightVector->GetVectorLength();
++ii)
{
currentPM= theFastLightVector->Energy(ii);
currentIN= (*theFastLightVector)[ii];
currentCII = 0.5 * (prevIN + currentIN);
currentCII = prevCII +
(currentPM - prevPM) * currentCII;
aPhysicsOrderedFreeVector->
InsertValues(currentPM, currentCII);
prevPM = currentPM;
prevCII = currentCII;
prevIN = currentIN;
}
}
}
G4MaterialPropertyVector* theSlowLightVector =
aMaterialPropertiesTable->GetProperty("SLOWCOMPONENT");
if (theSlowLightVector) {
if (verboseLevel > 0) {
G4cout << " Building the material properties table for SLOWCOMPONENT" << G4endl;
}
// Retrieve the first intensity point in vector
// of (photon energy, intensity) pairs
// theSlowLightVector->ResetIterator();
// ++(*theSlowLightVector); // advance to 1st entry
G4double currentIN = (*theSlowLightVector)[0];
if (currentIN >= 0.0) {
// Create first (photon energy, Scintillation
// Integral pair
G4double currentPM = theSlowLightVector->Energy(0);
G4double currentCII = 0.0;
bPhysicsOrderedFreeVector->InsertValues(currentPM , currentCII);
// Set previous values to current ones prior to loop
G4double prevPM = currentPM;
G4double prevCII = currentCII;
G4double prevIN = currentIN;
// loop over all (photon energy, intensity)
// pairs stored for this material
for (size_t ii= 1;
ii< theSlowLightVector->GetVectorLength();
++ii)
{
currentPM= theSlowLightVector->Energy(ii);
currentIN= (*theSlowLightVector)[ii];
currentCII = 0.5 * (prevIN + currentIN);
currentCII = prevCII +
(currentPM - prevPM) * currentCII;
bPhysicsOrderedFreeVector->
InsertValues(currentPM, currentCII);
prevPM = currentPM;
prevCII = currentCII;
prevIN = currentIN;
}
}
}
G4MaterialPropertyVector* theReemissionVector =
aMaterialPropertiesTable->GetProperty("REEMISSIONPROB");
if (theReemissionVector) {
if (verboseLevel > 0) {
G4cout << " Building the material properties table for REEMISSIONPROB" << G4endl;
}
// Retrieve the first intensity point in vector
// of (photon energy, intensity) pairs
// theReemissionVector->ResetIterator();
// ++(*theReemissionVector); // advance to 1st entry
G4double currentIN = (*theReemissionVector)[0];
if (currentIN >= 0.0) {
// Create first (photon energy, Scintillation
// Integral pair
G4double currentPM = theReemissionVector->Energy(0);
G4double currentCII = 0.0;
cPhysicsOrderedFreeVector->
InsertValues(currentPM , currentCII);
// Set previous values to current ones prior to loop
G4double prevPM = currentPM;
G4double prevCII = currentCII;
G4double prevIN = currentIN;
// loop over all (photon energy, intensity)
// pairs stored for this material
for (size_t ii= 1;
ii< theReemissionVector->GetVectorLength();
++ii)
{
currentPM= theReemissionVector->Energy(ii);
currentIN= (*theReemissionVector)[ii];
currentCII = 0.5 * (prevIN + currentIN);
currentCII = prevCII +
(currentPM - prevPM) * currentCII;
cPhysicsOrderedFreeVector->
InsertValues(currentPM, currentCII);
prevPM = currentPM;
prevCII = currentCII;
prevIN = currentIN;
}
}
}
}
// The scintillation integral(s) for a given material
// will be inserted in the table(s) according to the
// position of the material in the material table.
theFastIntegralTable->insertAt(i,aPhysicsOrderedFreeVector);
theSlowIntegralTable->insertAt(i,bPhysicsOrderedFreeVector);
theReemissionIntegralTable->insertAt(i,cPhysicsOrderedFreeVector);
}
}
// GetMeanFreePath
// ---------------
//
G4double DsG4Scintillation::GetMeanFreePath(const G4Track&,
G4double ,
G4ForceCondition* condition)
{
*condition = StronglyForced;
return DBL_MAX;
}
// GetMeanLifeTime
// ---------------
//
G4double DsG4Scintillation::GetMeanLifeTime(const G4Track&,
G4ForceCondition* condition)
{
*condition = Forced;
return DBL_MAX;
}
| [
"whuwenjie@gmail.com"
] | whuwenjie@gmail.com |
c771b9baea0b1e4c4a77d530c22ecd5f57e00db5 | 92943b7e6d203b23e15d746186567532d5613307 | /Home work/19.02.19/19.02.19/Source.cpp | 08d2a738e3de79cb4c4d2fdb88c45efda792708f | [] | no_license | Zabehalin/C-Plus-Plus | 15d14820cd8084ce4bd4d2ebacbac991d56cfa3a | 2c26bb033d66cdc3ed8f83901ed51ce31ec6c57f | refs/heads/master | 2020-04-18T07:11:32.952399 | 2019-05-14T11:17:53 | 2019-05-14T11:17:53 | 167,352,012 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,796 | cpp | #include <iostream>
#include <ctime>
using namespace std;
/*1. Дано цілочисельний одновимірний масив. Заповнити його, вивести на екран у прямому та зворотньому порядку та порахувати суму елементів з використанням вказівників.*/
/*void Zap(int arr[], const int ROW);
void Vyvid(int arr[], const int ROW);
int main()
{
srand(unsigned(time(NULL)));
const int ROW = 10;
int arr[ROW];
Zap(arr, ROW);
Vyvid(arr, ROW);
system("pause");
return 0;
}
void Zap(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
arr[i] = rand() % 20;
}
}
void Vyvid(int arr[], const int ROW)
{
int sum = 0;
cout << "============ Pramyi =============" << endl;
for (int i = 0; i < ROW; i++)
{
sum += arr[i];
cout << "arr[" << i << "] = " << arr[i] << endl;
}
cout << "\n\tSUMA arr = " << sum << endl;
cout << "============ Zvorot =============" << endl;
for (int i = ROW-1; i >-1; i--)
{
cout << "arr[" << i << "] = " << arr[i] << endl;
}
}*/
/*2. Дано одновимірний масив. Знайти найбільше та найменше значення у масиві та поміняти їх у масиві місцями. Вивести перетворений масив на екран з використанням вказівників.*/
/*void Zap(int arr[], const int ROW);
void Vyvid(int arr[], const int ROW);
void SortBuble(int arr2[], const int ROW);
void Perevirca(int arr[], int arr2[], const int ROW);
int main()
{
srand(unsigned(time(NULL)));
const int ROW = 10;
int arr[ROW];
int arr2[ROW];
Zap(arr, ROW);
Vyvid(arr, ROW);
for (int i = 0; i < ROW; i++)
{
arr2[i] = arr[i];
}
SortBuble(arr2, ROW);
cout << endl;
Perevirca(arr, arr2, ROW);
cout << "Zmina MIN >< MAX" << endl;
Vyvid(arr, ROW);
system("pause");
return 0;
}
void Zap(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
arr[i] = rand() % 20;
}
}
void Vyvid(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
cout << arr[i] << "\t";
}
cout << endl;
}
void SortBuble(int arr2[], const int ROW)
{
for (int i = ROW - 1; i >= 1; i--)
{
for (int j = 0; j < i; j++)
{
if (arr2[j] > arr2[j + 1])
{
int tmp = arr2[j];
arr2[j] = arr2[j + 1];
arr2[j + 1] = tmp;
}
}
}
}
void Perevirca(int arr[], int arr2[], const int ROW)
{
int m = 0, b = 0,z = 0;
for (int i = 0; i < ROW; i++)
{
if (arr[i] == arr2[0])
{
m = i;
}
else if (arr[i] == arr2[ROW-1])
{
b = i;
}
}
cout << "Minim = " << arr[m] <<"===="<< m << endl;
cout << "Max = " << arr[b] <<"===="<< b << endl;
z = arr[m];
arr[m] = arr[b];
arr[b] = z;
}*/
/*3. Дано одновимірний масив. Поміняти місцями дві його половини(якщо масив має непарну довжину, то центральний елемент залишається на місці з використанням вказівників*/
void Zap(int arr[], const int ROW);
void Vyvid(int arr[], const int ROW);
void Zmina(int arr[], const int ROW);
int main()
{
const int ROW = 11;
int arr[ROW];
Zap(arr, ROW);
Vyvid(arr, ROW);
Zmina(arr, ROW);
system("pause");
return 0;
}
void Zap(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
arr[i] = rand() % 20;
}
}
void Vyvid(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
cout << arr[i] << "\t";
}
cout << endl;
}
void Zmina(int arr[], const int ROW)
{
int s = 0, z = 0;
s = ROW / 2;
for (int i = 0; i < ROW; i++)
{
if (s <= ROW -1 )
{
cout << arr[s] << "\t";
s++;
}
else if (s >= ROW)
{
cout << arr[z] << "\t";
z++;
}
}
cout << endl;
}
| [
"z380966645657@gmail.com"
] | z380966645657@gmail.com |
f5d6ff01751adc38596c32372922a7f2d4ddf3fe | 27698cb6fc1a958c772f3439166b8f109ac27e4d | /models/ideal_am.cpp | 67cb74f77c84c7bb923aa5e1719a5bd1b70200b3 | [] | no_license | gxhen/WirelessModelCPP | 321177b3dfa736ae1289a48c12e3c04fbe6749f6 | 67983fdebfe24710db023711d0fff58b49a4dc7d | refs/heads/master | 2023-05-29T04:57:23.448902 | 2015-09-19T18:28:03 | 2015-09-19T18:28:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | cpp | //
// File = ideal_am.cpp
//
#include <stdlib.h>
#include <fstream>
#include "parmfile.h"
#include "ideal_am.h"
#include "model_graph.h"
//#include "uni_rand.h"
extern ParmFile *ParmInput;
//======================================================
IdealAmplitudeModulator::IdealAmplitudeModulator( char* instance_name,
PracSimModel* outer_model,
Signal<float>* carrier_sig,
Signal<float>* mod_sig,
Signal<float>* out_sig )
:PracSimModel(instance_name,
outer_model)
{
MODEL_NAME(IdealAmplitudeModulator);
//ENABLE_MULTIRATE;
//---------------------------------------
// Read model config parms
OPEN_PARM_BLOCK;
GET_DOUBLE_PARM( Modulation_Index );
//--------------------------------------
// Connect input and output signals
Carrier_Sig = carrier_sig;
Mod_Sig = mod_sig;
Out_Sig = out_sig;
MAKE_OUTPUT( Out_Sig );
MAKE_INPUT( Carrier_Sig );
MAKE_INPUT( Mod_Sig );
}
//======================================
IdealAmplitudeModulator::~IdealAmplitudeModulator( void ){ };
//=======================================
void IdealAmplitudeModulator::Initialize(void)
{
//------------------
double samp_intvl = Out_Sig->GetSampIntvl();
Out_Avg_Block_Size = Out_Sig->GetBlockSize();
}
//=======================================================
int IdealAmplitudeModulator::Execute()
{
float *out_sig_ptr;
float out_sig_val;
float *carrier_sig_ptr;
float *mod_sig_ptr;
int is;
int block_size;
out_sig_ptr = GET_OUTPUT_PTR( Out_Sig );
carrier_sig_ptr = GET_INPUT_PTR( Carrier_Sig );
mod_sig_ptr = GET_INPUT_PTR( Mod_Sig );
block_size = Mod_Sig->GetValidBlockSize();
Out_Sig->SetValidBlockSize(block_size);
for (is=0; is<block_size; is++) {
out_sig_val = (1.0 + Modulation_Index*(*mod_sig_ptr++))
* (*carrier_sig_ptr++);
*out_sig_ptr++ = out_sig_val;
}
return(_MES_AOK);
}
| [
"410090357@qq.com"
] | 410090357@qq.com |
0b3ab25185408b8541ce311244a78afe64ff5a00 | e3ef6ff25d8322cf479210846ebc677702e8edab | /necrodancer/weapon_bow_basic.h | cfab545dcbf9e9fccc2f560339fed6af748a0163 | [] | no_license | dongnamyoooooooooon/yoOoOoOon | 885dbfe0c982ddc3c79eca8b129a2b11bbfd53c5 | 8a1e84a053bcf752532fb102d54fe5d810ce255b | refs/heads/master | 2020-05-01T14:05:27.437184 | 2019-04-09T08:44:05 | 2019-04-09T08:44:05 | 177,509,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | h | #pragma once
#include "item.h"
class weapon_bow_basic : public item
{
private:
bool _isLong;
public:
weapon_bow_basic();
~weapon_bow_basic();
HRESULT init(string imgName, int idxX, int idxY, ITEM_TYPE type);
void release();
void update();
void render();
void drawHint();
bool useItem(int idxX, int idxY, int way);
};
| [
"46731689+dongnamyoooooooooon@users.noreply.github.com"
] | 46731689+dongnamyoooooooooon@users.noreply.github.com |
ef77374d7b29a90bd26fa7bbc7f5026765643c34 | b193a4bf6ab67851256cca7f2f3259a5c57d7180 | /ZSUM.cpp | 2de45bedfc78f74bc3ed660d0cc3afc44691ac5a | [] | no_license | kaushik12048/Spoj_Solutions | ec133fb82bd6b1e9fe20a156183d111d42b21f07 | 20a893fd5ea9bd108ec367ddce71d3092ab63a4c | refs/heads/master | 2016-08-10T11:56:05.796740 | 2015-05-25T06:56:24 | 2015-05-25T06:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include<bits/stdc++.h>
using namespace std;
#define m 10000007
long long int mod(long long int x,long long int y){
long long int ans=1;
long long int t=x;
while(y>0)
{
if(y%2==1)
ans=(ans*t)%m;
y=y>>1;
t=(t*t)%m;
}
return ans;
}
int main()
{
while(1){
long long int n,k,ans;
scanf("%lld %lld",&n,&k);
if(n==0 && k==0)
break;
ans=(mod(n,k)%m)+(mod(n,n)%m)+2*(mod(n-1,k)%m)+2*(mod(n-1,n-1)%m);
printf("%lld\n",ans%m);
}
return 0;
}
| [
"kaushik12048@iiitd.ac.in"
] | kaushik12048@iiitd.ac.in |
90ce9e138bf5805d32267874f2b0a1004a23b17c | 48eb7edd9acb951db2b7b088977cf56ebac5987c | /DIC_Labor_1.2/src/main.cpp | 3b9461df427a5d9bea48908c6bdef100bdf397be | [] | no_license | Weesy1712/platformIoProjects | 3cb6f504fbe2e60ee65bebc1bc1b2e045a352622 | 1f43d0ba272dc0dc2a6548ea8ff145f6bd764c27 | refs/heads/main | 2023-02-02T19:55:11.933045 | 2020-12-17T15:04:52 | 2020-12-17T15:04:52 | 322,327,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | cpp | #include <Arduino.h>
int ledr = 3;
void setup() {
Serial.begin(9600);
pinMode(ledr, OUTPUT);
Serial.println("Zum Steuern müssen Sie in diesem Format eingeben!" );
Serial.println("Zum Einschalten: ");
Serial.println("switch.on");
Serial.println("switch.off");
}
void loop() {
int fadingState;
if(Serial.available()){
if(Serial.read() == "switch.on"){
fadingState = 1;
}
if(Serial.read() == "h"){
fadingState = 0;
}
}
if(fadingState == 1){
fading();
}
}
int millis2;
void fading(){
for (int i = 0; i <= 255; i++)
{millis2 = millis()+ 5;
//delay(5);
if(millis()>= millis2){
analogWrite(ledr,i);
}
}
for (int i = 255; i >= 0; i--)
{
//delay(5);
millis2 = millis()+ 5;
//delay(5);
if(millis()>= millis2){
analogWrite(ledr,i);
}
}
}
| [
"karim.tayari@htl-klu.at"
] | karim.tayari@htl-klu.at |
af637682100426d51140e248394fa4b975862726 | 66daa8fdb9aecce0dc4df5b0e1ea10fb983705a8 | /WatSat_arduino_code/sensor_shield_code/mux2/mux2.ino | 385cfe3cf92866392deb8f229d1e7b6ad6d668c1 | [
"MIT"
] | permissive | cjski/Arduino-ish | 7e964e77b866d3e777c6b1ff06de491765e32978 | b9c6612a2ee971f05d913fbcd5d136d4f3fdec65 | refs/heads/master | 2021-01-21T05:20:58.088739 | 2016-12-01T00:27:58 | 2016-12-01T00:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | ino | // 74HC4067 demultiplexer demonstration (1 to 16)
// control pins output table in array form
// see truth table on page 2 of TI 74HC4067 data sheet
// connect 74HC4067 S0~S3 to Arduino D7~D4 respectively
// 5V to 74HC4067 pin 1 to power the LEDs :)
byte controlPins[] = {B00000000,
B10000000,
B01000000,
B11000000,
B00100000,
B10100000,
B01100000,
B11100000,
B00010000,
B10010000,
B01010000,
B11010000,
B00110000,
B10110000,
B01110000,
B11110000 };
void setup()
{
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void setPin(int outputPin)
// function to select pin on 74HC4067
{
PORTD = controlPins[outputPin];
}
void loop()
{
for (int i = 0; i < 16; i++)
{
setPin(i);
delay(250);
}
}
| [
"herman.stubeda@outlook.com"
] | herman.stubeda@outlook.com |
81b9b48ef557ff8d7424698e7aed8620600efc37 | 16a753af9647c88408e7854dd04cef1a6183e2c4 | /CC3k/src/things/character/pc/decorator/wdDecorator.cc | 8f8c59b0cadb2a3fee9063b181a84b34f913acbf | [] | no_license | pfryerda/project-IMDD | a8c88f15ed43c55b34a1439b777686a347adc757 | e2e56ed78043f148d799fd48bba1e318b158e932 | refs/heads/master | 2016-09-06T18:18:54.252083 | 2013-12-16T17:04:12 | 2013-12-16T17:04:12 | 14,460,137 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | cc | #include "wdDecorator.h"
using namespace std;
wdDecorator::wdDecorator(PC* pc):Decorator(pc) {}
unsigned int wdDecorator::getDef() const {
if ((pc->getDef() - 5) < 0) return 0;
else return (pc->getDef() - 5);
}
| [
"Luke.Michael.Brown@gmail.com"
] | Luke.Michael.Brown@gmail.com |
21af0c478474880ed18fa6183185392b5c617a69 | 8cd626538767888c92a94d2db5ef6b6713dbeef6 | /cpp_d13_2018/ex05/Picture.cpp | 585a1f7552a3fac9d92e6f0a4f261f44b28360e7 | [] | no_license | simonprovost/cppPool | e3be0746e1a3e67d739a8effa67ce9a676af6213 | 8d604708d2dfe0778b95c8a510f6efdcc54b6c61 | refs/heads/master | 2020-05-19T13:03:00.318979 | 2019-05-14T09:42:12 | 2019-05-14T09:42:12 | 185,029,336 | 12 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | /*
** EPITECH PROJECT, 2018
** //name_project
** File description:
** //todo
*/
#include <fstream>
#include <sstream>
#include <cstring>
#include "Picture.hpp"
bool Picture::getPictureFromFile(const std::string &file)
{
std::ifstream PicFile(file.data());
if (PicFile.is_open()) {
std::stringstream buff;
buff << PicFile.rdbuf();
this->data = buff.str();
PicFile.close();
return (true);
}
this->data = "ERROR";
return (false);
}
Picture::Picture(const std::string &file)
{
if (strcmp(file.data(), "") == 0)
this->data = "";
else
this->getPictureFromFile(file);
}
const std::string &Picture::getData() const
{
return data;
}
Picture::~Picture()
{
}
Picture &Picture::operator=(const Picture &obj)
{
this->data = obj.getData();
return *this;
}
Picture::Picture(const Picture &obj)
{
this->data = obj.getData();
}
Picture::Picture()
{
this->data = "";
}
void Picture::setData(const std::string &data)
{
Picture::data = data;
}
| [
"simon1.provost@epitech.eu"
] | simon1.provost@epitech.eu |
c929d3ea98a71c12d07ae37cd8353cf42bbde8b5 | 03d3231478373089a3de04db162f61b79a388fd3 | /l2detect/ConfigIni.h | ed6c015d21824129fa479d4b9209630775070b85 | [] | no_license | minlexx/l2-unlegits | f4b0e9d70afe2a0a26f81daa16123eb2fe31cc13 | fc189ca35edf14439a5eeac81359b30112496b80 | refs/heads/master | 2021-01-17T05:35:09.738039 | 2015-06-28T09:16:13 | 2015-06-28T09:16:13 | 38,192,499 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h | #ifndef CONFIGINI_H_
#define CONFIGINI_H_
class CConfig
{
public:
CConfig();
virtual ~CConfig();
public:
bool ReadConfig( const char *szConfigFileName );
bool ReadConfig( const wchar_t *szConfigFilename );
bool SaveConfig();
void SetDefault();
protected:
void _initNull();
public:
char szCfgFileName[256];
bool isInGameMode;
int L2_version;
int L2_client_version;
// Listen port setup
char FakeListenLoginIP[32];
int FakeListenLoginPort;
char FakeListenGameIP[32];
int FakeListenGamePort;
// Forward connection to
char RealLoginServerIP[128];
int RealLoginServerPort;
// Catch game server traffic
//int PlayGameServerNo; // removed!
char ForceGameServerIP[32];
int ForceGameServerPort;
int IngameGameServerPort;
// Logging setup
int LogGamePackets;
char LogGameFileNamePrefix[128];
int WarnUnknownPacketsToStdout;
int DumpUnknownToStdout;
int WarnMessageLevel;
// hacks
int EnableModifyGameTraffic; // enable or disable game protocol-level hacks
int OverrideGameProtocolVersion;
int ReplyL2JGameGuardQuery;
int GraciaEpilogueProtocol_148_hacks;
int TeonPvP_hacks;
// L2Walker fixes
int L2Walker_DropRequestGMList;
int L2Walker_FixMoveBackwardToLocation;
int L2Walker_FixChangeWaitType2;
int L2Walker_InjectStatusUpdate;
// tweaks
int ThreadProirityRaiseEnable;
// invis GM detection
int InvisGMTrackEnable;
int InvisGMSpeed;
};
#endif /* CONFIGINI_H_ */
| [
"alexey.min@gmail.com"
] | alexey.min@gmail.com |
23928343da043ac8061eb177addd7a2099c891f5 | 13f44a504648dc91869dfa9027c2f699949bae53 | /db/compaction.cpp | 584468b3255868526dc8a96ccd20061829d4789e | [
"BSD-3-Clause"
] | permissive | sarthakdadhakar/power-of-d | e90d8fb951d4350baf41506940c32bafa5718770 | 6c4be0a1b1242f267a92df24db407b1feffaa2a4 | refs/heads/main | 2023-01-21T08:45:02.069191 | 2020-11-18T03:28:40 | 2020-11-18T03:28:40 | 310,158,009 | 0 | 0 | BSD-3-Clause | 2020-11-05T01:23:05 | 2020-11-05T01:23:04 | null | UTF-8 | C++ | false | false | 23,009 | cpp |
//
// Created by Haoyu Huang on 5/4/20.
// Copyright (c) 2020 University of Southern California. All rights reserved.
//
#include "compaction.h"
#include "filename.h"
namespace leveldb {
void
FetchMetadataFilesInParallel(const std::vector<const FileMetaData *> &files,
const std::string &dbname,
const Options &options,
StoCBlockClient *client,
Env *env) {
uint32_t fetched_files = 0;
std::vector<const FileMetaData *> batch;
for (int i = 0; i < files.size(); i++) {
if (batch.size() == FETCH_METADATA_BATCH_SIZE &&
files.size() - i > FETCH_METADATA_BATCH_SIZE) {
fetched_files += batch.size();
FetchMetadataFiles(batch, dbname, options, client, env);
batch.clear();
}
batch.push_back(files[i]);
}
if (!batch.empty()) {
fetched_files += batch.size();
FetchMetadataFiles(batch, dbname, options, client, env);
}
NOVA_ASSERT(fetched_files == files.size());
}
void
FetchMetadataFiles(const std::vector<const FileMetaData *> &files,
const std::string &dbname, const Options &options,
StoCBlockClient *client, Env *env) {
// Fetch all metadata files in parallel.
char *backing_mems[files.size() * nova::NovaConfig::config->number_of_sstable_metadata_replicas];
int index = 0;
for (int i = 0; i < files.size(); i++) {
auto meta = files[i];
for (int replica_id = 0; replica_id < meta->block_replica_handles.size(); replica_id++) {
std::string filename = TableFileName(dbname, meta->number, FileInternalType::kFileMetadata, replica_id);
const StoCBlockHandle &meta_handle = meta->block_replica_handles[replica_id].meta_block_handle;
uint32_t backing_scid = options.mem_manager->slabclassid(0, meta_handle.size);
char *backing_buf = options.mem_manager->ItemAlloc(0, backing_scid);
memset(backing_buf, 0, meta_handle.size);
NOVA_LOG(rdmaio::DEBUG)
<< fmt::format("Fetch metadata blocks {} handle:{}", filename, meta->DebugString());
uint32_t req_id = client->InitiateReadDataBlock(meta_handle, 0, meta_handle.size, backing_buf,
meta_handle.size, "", false);
backing_mems[index] = backing_buf;
index++;
}
}
for (int i = 0; i < files.size(); i++) {
auto meta = files[i];
for (int replica_id = 0; replica_id < meta->block_replica_handles.size(); replica_id++) {
client->Wait();
}
}
index = 0;
for (int i = 0; i < files.size(); i++) {
auto meta = files[i];
for (int replica_id = 0; replica_id < meta->block_replica_handles.size(); replica_id++) {
char *backing_buf = backing_mems[index];
const StoCBlockHandle &meta_handle = meta->block_replica_handles[replica_id].meta_block_handle;
uint32_t backing_scid = options.mem_manager->slabclassid(0, meta_handle.size);
WritableFile *writable_file;
EnvFileMetadata env_meta = {};
auto sstablename = TableFileName(dbname, meta->number, FileInternalType::kFileData, replica_id);
Status s = env->NewWritableFile(sstablename, env_meta, &writable_file);
NOVA_ASSERT(s.ok());
Slice sstable_meta(backing_buf, meta_handle.size);
s = writable_file->Append(sstable_meta);
NOVA_ASSERT(s.ok());
s = writable_file->Flush();
NOVA_ASSERT(s.ok());
s = writable_file->Sync();
NOVA_ASSERT(s.ok());
s = writable_file->Close();
NOVA_ASSERT(s.ok());
delete writable_file;
writable_file = nullptr;
options.mem_manager->FreeItem(0, backing_buf, backing_scid);
index++;
}
}
}
Compaction::Compaction(VersionFileMap *input_version,
const InternalKeyComparator *icmp,
const Options *options, int level, int target_level)
: level_(level),
target_level_(target_level),
icmp_(icmp),
options_(options),
max_output_file_size_(options->max_file_size),
input_version_(input_version),
grandparent_index_(0),
seen_key_(false),
overlapped_bytes_(0) {
is_completed_ = false;
level_ptrs_.resize(options->level);
for (int i = 0; i < options->level; i++) {
level_ptrs_[i] = 0;
}
}
std::string Compaction::DebugString(const Comparator *user_comparator) {
Slice smallest = {};
Slice largest = {};
std::string files;
for (int which = 0; which < 2; which++) {
for (auto file : inputs_[which]) {
if (smallest.empty() ||
user_comparator->Compare(file->smallest.user_key(),
smallest) < 0) {
smallest = file->smallest.user_key();
}
if (largest.empty() ||
user_comparator->Compare(file->largest.user_key(),
largest) > 0) {
largest = file->largest.user_key();
}
files += file->ShortDebugString();
files += ",";
}
}
std::string debug = fmt::format("{}@{} + {}@{} s:{} l:{} {} {}",
inputs_[0].size(), level_,
inputs_[1].size(), target_level_,
smallest.ToString(), largest.ToString(),
files, grandparents_.size());
return debug;
}
bool Compaction::IsTrivialMove() const {
// Avoid a move if there is lots of overlapping grandparent data.
// Otherwise, the move could create a parent file that will require
// a very expensive merge later on.
return (num_input_files(0) == 1 && num_input_files(1) == 0 &&
level_ != target_level_);
// &&
// TotalFileSize(grandparents_) <=
// MaxGrandParentOverlapBytes(options_));
}
void Compaction::AddInputDeletions(VersionEdit *edit) {
for (int which = 0; which < 2; which++) {
for (size_t i = 0; i < inputs_[which].size(); i++) {
int delete_level = level_ + which;
auto *f = inputs_[which][i];
edit->DeleteFile(delete_level, f->number);
}
}
}
bool Compaction::ShouldStopBefore(const Slice &internal_key) {
// Scan to find earliest grandparent file that contains key.
while (grandparent_index_ < grandparents_.size() &&
icmp_->Compare(internal_key,
grandparents_[grandparent_index_]->largest.Encode()) >
0) {
if (seen_key_) {
overlapped_bytes_ += 1; //grandparents_[grandparent_index_]->file_size;
}
grandparent_index_++;
}
seen_key_ = true;
int max_overlap = 5;
max_overlap = std::min(max_overlap, (int) grandparents_.size() / 4);
max_overlap = std::max(max_overlap, 1);
if (overlapped_bytes_ >= max_overlap) {
// Too much overlap for current output; start new output
overlapped_bytes_ = 0;
return true;
} else {
return false;
}
}
CompactionStats CompactionState::BuildStats() {
CompactionStats stats;
stats.input_source.num_files = compaction->num_input_files(0);
stats.input_source.level = compaction->level();
stats.input_source.file_size = compaction->num_input_file_sizes(0);
stats.input_target.num_files = compaction->num_input_files(1);
stats.input_target.level = compaction->target_level();
stats.input_target.file_size = compaction->num_input_file_sizes(1);
return stats;
}
CompactionJob::CompactionJob(std::function<uint64_t(void)> &fn_generator,
leveldb::Env *env, const std::string &dbname,
const leveldb::Comparator *user_comparator,
const leveldb::Options &options,
EnvBGThread *bg_thread,
TableCache *table_cache)
: fn_generator_(fn_generator), env_(env), dbname_(dbname),
user_comparator_(
user_comparator), options_(options),
bg_thread_(bg_thread), table_cache_(table_cache) {
}
Status CompactionJob::OpenCompactionOutputFile(CompactionState *compact) {
assert(compact != nullptr);
assert(compact->builder == nullptr);
uint64_t file_number;
{
file_number = fn_generator_();
FileMetaData out;
if (file_number == 0) {
std::string str;
if (compact->compaction) {
str = compact->compaction->DebugString(user_comparator_);
}
NOVA_ASSERT(false) << str;
}
out.number = file_number;
out.smallest.Clear();
out.largest.Clear();
compact->outputs.push_back(out);
}
// Make the output file
MemManager *mem_manager = bg_thread_->mem_manager();
std::string filename = TableFileName(dbname_, file_number, FileInternalType::kFileData, 0);
StoCWritableFileClient *stoc_writable_file = new StoCWritableFileClient(
options_.env,
options_,
file_number,
mem_manager,
bg_thread_->stoc_client(),
dbname_,
bg_thread_->thread_id(),
options_.max_stoc_file_size,
bg_thread_->rand_seed(),
filename);
compact->outfile = new MemWritableFile(stoc_writable_file);
compact->builder = new TableBuilder(options_, compact->outfile);
return Status::OK();
}
Status
CompactionJob::FinishCompactionOutputFile(const ParsedInternalKey &ik,
CompactionState *compact,
Iterator *input) {
assert(compact != nullptr);
assert(compact->outfile != nullptr);
assert(compact->builder != nullptr);
const uint64_t output_number = compact->current_output()->number;
assert(output_number != 0);
// Check for iterator errors
Status s = input->status();
if (s.ok()) {
s = compact->builder->Finish();
} else {
compact->builder->Abandon();
}
const uint64_t current_entries = compact->builder->NumEntries();
const uint64_t current_data_blocks = compact->builder->NumDataBlocks();
const uint64_t current_bytes = compact->builder->FileSize();
compact->current_output()->file_size = current_bytes;
compact->total_bytes += current_bytes;
delete compact->builder;
compact->builder = nullptr;
NOVA_LOG(rdmaio::DEBUG)
<< fmt::format("Close table-{} at {} bytes", output_number,
current_bytes);
FileMetaData meta;
meta.number = output_number;
meta.file_size = current_bytes;
meta.smallest = compact->current_output()->smallest;
meta.largest = compact->current_output()->largest;
// Set meta in order to flush to the corresponding DC node.
StoCWritableFileClient *mem_file = static_cast<StoCWritableFileClient *>(compact->outfile->mem_file());
mem_file->set_meta(meta);
mem_file->set_num_data_blocks(current_data_blocks);
// Finish and check for file errors
NOVA_ASSERT(s.ok()) << s.ToString();
s = compact->outfile->Sync();
s = compact->outfile->Close();
mem_file->WaitForPersistingDataBlocks();
{
FileMetaData *output = compact->current_output();
output->converted_file_size = mem_file->Finalize();
output->block_replica_handles = mem_file->replicas();
output->parity_block_handle = mem_file->parity_block_handle();
mem_file->Validate(output->block_replica_handles, output->parity_block_handle);
delete mem_file;
mem_file = nullptr;
delete compact->outfile;
compact->outfile = nullptr;
}
return s;
}
Status
CompactionJob::CompactTables(CompactionState *compact,
Iterator *input,
CompactionStats *stats, bool drop_duplicates,
CompactInputType input_type,
CompactOutputType output_type,
const std::function<void(
const ParsedInternalKey &ikey,
const Slice &value)> &add_to_memtable) {
const uint64_t start_micros = env_->NowMicros();
std::string output;
if (input_type == CompactInputType::kCompactInputMemTables) {
output = fmt::format(
"bg[{}] Flushing {} memtables",
bg_thread_->thread_id(),
stats->input_source.num_files);
} else {
output = fmt::format(
"bg[{}] Major Compacting {}@{} + {}@{} files",
bg_thread_->thread_id(),
stats->input_source.num_files,
stats->input_source.level,
stats->input_target.num_files,
stats->input_target.level);
Log(options_.info_log, "%s", output.c_str());
NOVA_LOG(rdmaio::INFO) << output;
}
assert(compact->builder == nullptr);
assert(compact->outfile == nullptr);
assert(compact->outputs.empty());
input->SeekToFirst();
Status status;
ParsedInternalKey ikey;
std::string current_user_key;
bool has_current_user_key = false;
SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
std::vector<std::string> keys;
uint64_t memtable_size = 0;
while (input->Valid()) {
Slice key = input->key();
NOVA_ASSERT(ParseInternalKey(key, &ikey));
if (output_type == kCompactOutputSSTables &&
compact->ShouldStopBefore(key, user_comparator_) &&
compact->builder != nullptr &&
compact->builder->NumEntries() > 0) {
status = FinishCompactionOutputFile(ikey, compact, input);
if (!status.ok()) {
break;
}
}
// Handle key/value, add to state, etc.
bool drop = false;
if (!has_current_user_key ||
user_comparator_->Compare(ikey.user_key,
Slice(current_user_key)) !=
0) {
// First occurrence of this user key
current_user_key.assign(ikey.user_key.data(),
ikey.user_key.size());
has_current_user_key = true;
last_sequence_for_key = kMaxSequenceNumber;
}
if (last_sequence_for_key <= compact->smallest_snapshot) {
// Hidden by an newer entry for same user key
drop = true; // (A)
}
last_sequence_for_key = ikey.sequence;
#if 0
Log(options_.info_log,
" Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
"%d smallest_snapshot: %d",
ikey.user_key.ToString().c_str(),
(int)ikey.sequence, ikey.type, kTypeValue, drop,
compact->compaction->IsBaseLevelForKey(ikey.user_key),
(int)last_sequence_for_key, (int)compact->smallest_snapshot);
#endif
if (drop && drop_duplicates) {
// RDMA_LOG(rdmaio::DEBUG)
// << fmt::format("drop key-{}", ikey.FullDebugString());
input->Next();
continue;
} else {
// Open output file if necessary
if (output_type == kCompactOutputSSTables &&
compact->builder == nullptr) {
status = OpenCompactionOutputFile(compact);
if (!status.ok()) {
break;
}
}
if (output_type == kCompactOutputSSTables &&
compact->builder->NumEntries() == 0) {
compact->current_output()->smallest.DecodeFrom(key);
}
// RDMA_LOG(rdmaio::DEBUG)
// << fmt::format("add key-{}", ikey.FullDebugString());
// keys.push_back(ikey.DebugString());
if (output_type == kCompactOutputSSTables) {
compact->current_output()->largest.DecodeFrom(key);
if (!compact->builder->Add(key, input->value())) {
std::string added_keys;
for (auto &k : keys) {
added_keys += k;
added_keys += "\n";
}
NOVA_ASSERT(false) << fmt::format("{}\n {}",
compact->compaction->DebugString(
user_comparator_),
added_keys);
}
} else {
NOVA_ASSERT(output_type == kCompactOutputMemTables);
add_to_memtable(ikey, input->value());
memtable_size +=
input->key().size() + input->value().size();
}
// Close output file if it is big enough
if (output_type == kCompactOutputSSTables &&
compact->builder->FileSize() >= options_.max_file_size) {
status = FinishCompactionOutputFile(ikey, compact, input);
if (!status.ok()) {
break;
}
}
}
input->Next();
}
if (output_type == kCompactOutputSSTables && status.ok() &&
compact->builder != nullptr) {
status = FinishCompactionOutputFile(ikey, compact, input);
}
if (status.ok()) {
status = input->status();
}
delete input;
input = nullptr;
stats->micros = env_->NowMicros() - start_micros;
if (output_type == CompactOutputType::kCompactOutputSSTables) {
for (size_t i = 0; i < compact->outputs.size(); i++) {
stats->output.file_size += compact->outputs[i].file_size;
stats->output.num_files += 1;
}
} else {
stats->output.num_files = 1;
stats->output.file_size = memtable_size;
}
if (input_type == CompactInputType::kCompactInputMemTables) {
output = fmt::format(
"bg[{}] Flushing {} memtables => {} files {} bytes {}",
bg_thread_->thread_id(),
stats->input_source.num_files,
stats->output.num_files,
stats->output.file_size,
output_type == kCompactOutputMemTables ? "memtable"
: "sstable");
} else {
const int src_level = compact->compaction->level();
const int dest_level = compact->compaction->target_level();
output = fmt::format(
"bg[{}]: Major Compacted {}@{} + {}@{} files => {} bytes",
bg_thread_->thread_id(),
compact->compaction->num_input_files(0),
src_level,
compact->compaction->num_input_files(1),
dest_level,
compact->total_bytes);
NOVA_LOG(rdmaio::INFO) << output;
Log(options_.info_log, "%s", output.c_str());
}
if (input_type == CompactInputType::kCompactInputMemTables) {
output = fmt::format(
"Flushing memtables stats,{},{},{},{},{}",
stats->input_source.num_files +
stats->input_target.num_files,
stats->input_source.file_size +
stats->input_target.file_size,
stats->output.num_files, stats->output.file_size,
stats->micros);
} else {
output = fmt::format("Major compaction stats,{},{},{},{},{}",
stats->input_source.num_files +
stats->input_target.num_files,
stats->input_source.file_size +
stats->input_target.file_size,
stats->output.num_files,
stats->output.file_size,
stats->micros);
NOVA_LOG(rdmaio::INFO) << output;
Log(options_.info_log, "%s", output.c_str());
}
// Remove input files from table cache.
if (table_cache_) {
if (compact->compaction) {
for (int which = 0; which < 2; which++) {
for (int i = 0;
i < compact->compaction->inputs_[which].size(); i++) {
auto f = compact->compaction->inputs_[which][i];
table_cache_->Evict(f->number, true);
}
}
}
}
if (compact->compaction) {
compact->compaction->is_completed_ = true;
if (compact->compaction->complete_signal_) {
sem_post(compact->compaction->complete_signal_);
}
}
return status;
}
} | [
"saru.dadkr@gmail.com"
] | saru.dadkr@gmail.com |
6e6c83345c9a86cb4e3793ca8383bd0570ca2b4c | e2bf73db30f6efbe12675b8ed11dbb7e03d7fd44 | /codigo_alfa/codigo_alfa.ino | 7977f765aaa2048900685ebe9b247ec658c85d56 | [
"BSD-3-Clause"
] | permissive | AlejoJamC/Blitz-arduino | edf8c47c8cb5f6770fbe83d0a099838d9cfb61b7 | 96f80efa805b077694cf57ea34da00f91ceca23e | refs/heads/master | 2021-01-22T08:47:20.547547 | 2017-11-10T20:10:46 | 2017-11-10T20:10:46 | 92,631,321 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | ino | // instancio las variables globales y librerias requeridas
#include <SD.h>
File Archivo;
void setup() {
//Se esablece comunicación con el monitor serial para la comprobación de la
//carga de datos.
Serial.begin(9600);
if (!SD.begin(10)) {
return;
}
// Se crear el archivo
Archivo = SD.open("datos.txt", FILE_WRITE);
}
void loop() {
// Lectura del puerto analogo de la señal resultante del filtro de pasabanda
int sensorValue = analogRead(A0);
// Conversion analogo a digital
float voltage = sensorValue * (5.0 / 1023.0);
// Se intenta abrir el archivo
Archivo = SD.open("datos.txt");
if (Archivo) {
//Se muestra por el monitor que la información que va a aparecer es la del
//archivo datos.txt.
Serial.print(voltage);
Serial.println('\n\r');
//Se implementa un bucle que recorrerá el archivo hasta que no encuentre más
//información (Archivo.available()==FALSE).
while (Archivo.available()) {
//Se escribe la información que ha sido leída del archivo.
Serial.write(Archivo.read());
}
//Si todo ha ido bien cierra el archivo para no perder datos.
Archivo.close();
}
else {
// Mensaje en caso de error
Serial.println("El archivo datos.txt no se abrió correctamente");
}
}
| [
"alejandromantilla7@hotmail.com"
] | alejandromantilla7@hotmail.com |
4c5d4d28060f48082ed6929861621d4ff6ec7fc6 | a7e1ea450087be3c6f01daa7d4215239310f6320 | /string_class/String.cpp | 7b4de30fbc50b523e12ed5e3a5e672328a18cfa7 | [] | no_license | lohani2280/c-plus-plus_stuffs | 3b0bfb6e4b7a639311eba4404605913059c4a302 | a18c8f883df23ff541af8d7d962399ecb19970ae | refs/heads/master | 2021-06-08T03:08:26.890932 | 2016-11-14T12:05:52 | 2016-11-14T12:05:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,737 | cpp | #include<iostream>
#include<cstring>
#include"String.h"
String::String()
{
len=0;
str=new char[1];
str[0]='\0';
}
String::String(const char* st)
{
len=std::strlen(st);
str=new char[len+1];
std::strcpy(str,st);
}
String::String(const String &st)
{
len=st.len;
str=new char[len+1];
std::strcpy(str,st.str);
}
int String::length()
{
len=std::strlen(str);
return len;
}
String::~String()
{
delete [] str;
}
const char* String::c_str() const
{
return str;
}
String& String::operator=(const String& st)
{
if(this==&st)
return *this;
delete [] str;
len=st.len;
str=new char[len+1];
std::strcpy(str,st.str);
return *this;//returns a refernce to yoursself(i.e, return refence of the invoking object)
}
String& String::operator=(const char* st)//LHS waala object String object hoga while RHS waala const char* type ka hoga!!!
{
delete [] str;
len=std::strlen(st);
str=new char[len+1];
std::strcpy(str,st);
return *this; //returns a refernce to yoursself(i.e, return refence of the invoking object)
// yahan NOTICE karo ki hum (return *this) kar rahe h naa ki (return str) coz former m ek pointer string
// return hoga while latter m String object return hoga ...an humaare prototyppe k accoording hume return
// invoking String object hi karna h jo ki sirf (*this) se hi ho sakta h.
}
const String& String::operator+=(const String& st)
{
int templen;
templen=st.len+len;
char *temp=new char[templen+1];
std::strcpy(temp,str);
std::strcat(temp,st.str);
*this=temp; // this is operator overloading of = operator of (const char* type)[L.H.S is a str.ing objeect and R.H.S is cons char* type].
return *this;
/*
U can also think this way which is a wrong path
str=temp; // ye nhi ho sakta coz isme str and temp dono ho string pointer h const char* type waale.
Thus, ye dono hi ek hi string ko point karenge.
temp ek temprory variable h and therefore jab iss function ka execution khatm hoga then the block of memory pointed by
temp will get deleted and so str pointer would be pointing smwhere undefined.
*this=temp will invoke const char* type of = overloaded operator which wii work fine.
return str; //ye nhi hoga coz hume ek string object return karna h na ki ek string pointer.
*/
}
bool operator==(const String& st1,const String& st2)
{
return (std::strcmp(st1.str,st2.str)==0);
}
bool operator<(const String& st1, const String& st2)
{
return (std::strcmp(st1.str,st2.str)<0);
}
bool operator>(const String& st1, const String& st2)
{
return (std::strcmp(st1.str,st2.str)>0);
}
char& String::operator[](int i)
{
return str[i];
}
std::ostream& operator<<(std::ostream& os, const String& st)
{
os<<st.str;
return os;
}
std::istream& operator>>(std::istream& is, String& st)//NHI CLEAR HAI!!!!!!!
{
char temp[String::CINMAX];
is.get(temp,String::CINMAX);// why didnt we used getline function here??...if u use getline function here then after input of the string u have to ENTER two times to see the output.
if(is)
st=temp; // shouldnt it be st.str=temp?//this is operator overloading of = operator of (const char* type).[L.H.S is a str.ing objeect and R.H.S is cons char* type
while(is&&is.get()!='\n')// couldnt understand this loop.This loop is basically to remove the strays of character from the input streaam.
continue;
return is;
}
std::istream& getline(std::istream& in, String& st)// NHI CLEAR HAI!!!!
{
char ch;
while(in.get(ch)&&ch!='\n')
st.str+=ch;
return in;
}
| [
"lohani.ayush@gmail.com"
] | lohani.ayush@gmail.com |
3a5d2291822cb44be7b1167ff28a97806225df60 | 0a9efa427df98fc6ce599a929b8b0c137a3d2eb7 | /XML Parser/main.cpp | f1bcdb49660eae350959fff422f56dc8a5342ffa | [] | no_license | jdkizer9/cs540p1 | 1e820a2bffc5e7bf0edc76f2836be88818bdd000 | 16bf7f65da8fba11c9cc08a438d35d0cbc323a31 | refs/heads/master | 2016-09-01T18:28:39.963097 | 2013-12-24T16:52:16 | 2013-12-24T16:52:16 | 30,951,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,704 | cpp | //
// main.cpp
// XML Parser
//
// Created by James Kizer on 2/18/13.
// Copyright (c) 2013 James Kizer. All rights reserved.
//
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <iostream>
#include "Parser.hpp"
#include "Element.hpp"
#include "Text.hpp"
#include "Visitor.hpp"
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <new>
#include <execinfo.h>
#include <stdio.h>
#include <regex.h>
#include <cxxabi.h>
using namespace xml;
using namespace std;
int main(int argc, const char * argv[])
{
char infile[32];
int ec;
// insert code here...
printf("Hello, World!\n");
strncpy(infile, "test.xml", sizeof(infile));
int fd = open(infile, O_RDONLY);
if (fd < 0) {
cerr << "Open file failed : " << strerror(errno) << endl;
return 1;
}
struct stat sb;
ec = fstat(fd, &sb);
if ( ec != 0) {
cerr << "Get file information failed : " << strerror(errno)<<endl;
return 1;
}
const char *doc = (const char *) mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if(doc == MAP_FAILED) {
cerr << "mmap document failed : " << strerror(errno) << endl;
return 1;
}
Parser parser;
const Element *r, *r2;
cout<<"Calling Parser"<<endl;
r = parser.parse(doc, sb.st_size);
cout<<"Returned from Parser\nDeleting Root Node"<<endl;
cout<<"Calling Parser"<<endl;
r2 = parser.parse(doc, sb.st_size);
cout<<"Returned from Parser\nDeleting Root Node"<<endl;
delete r;
return 0;
}
| [
"jk@Jamess-MacBook-Pro.local"
] | jk@Jamess-MacBook-Pro.local |
2d6f9a47d6b8f3560ac1d702577d3920ce83d93c | 711d7074da3939f11b7f56e359ed37ec42795133 | /test/VSidoService/test_gpio.cpp | 38e076973e6c39b4036c70c646c10cb25d051015 | [
"BSD-3-Clause"
] | permissive | Asratec/VSidoConnServer | 6ff9ad346721d6fd9e22fb3b9fe9947bea5241c6 | a465b87e1843b8945b14440c9bd407c562bb3439 | refs/heads/master | 2020-04-25T18:12:34.037523 | 2016-08-12T03:00:57 | 2016-08-12T03:00:57 | 31,400,816 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,959 | cpp | /*
Copyright (c) 2015, Asratec Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VSidoConnServer 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.
*/
#include "cmd_gpio.hpp"
#include "cmd_parser.hpp"
using namespace VSido;
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test.hpp>
#include <typeinfo>
#include "test_dump.hpp"
#include "test_uart.hpp"
BOOST_AUTO_TEST_CASE(test_case_GpioJSONRequest_0)
{
JSONRequestParser parser("{\"cmd\":\"SetGPIOValue\",\"gpio\":[{\"port\":4,\"val\":1},{\"port\":5,\"val\":0},{\"port\":6,\"val\":0},{\"port\":7,\"val\":1}]}}");
/// uart data
list<unsigned char> uartExpectedSend =
{
4,1,
5,0,
6,0,
7,1,
};
GEN_COMMON_SEND_UART('i');
auto request = parser.create();
DUMP_VAR(typeid(request).name());
auto _request = std::dynamic_pointer_cast<GpioJSONRequest>(request);
DUMP_VAR(typeid(_request).name());
BOOST_CHECK(nullptr != _request);
DO_ACK_GOOD_CHECK();
}
BOOST_AUTO_TEST_CASE(test_case_GpioJSONRequest_1)
{
JSONRequestParser parser("{\"cmd\":\"SetGPIOConfig\",\"gpio\":[{\"port\":4,\"val\":0},{\"port\":5,\"val\":1},{\"port\":6,\"val\":1},{\"port\":7,\"val\":0}]}}");
/// uart data
list<unsigned char> uartExpectedSend =
{
4,0,
5,1,
6,1,
7,0,
};
GEN_COMMON_SEND_UART('i');
auto request = parser.create();
DUMP_VAR(typeid(request).name());
auto _request = std::dynamic_pointer_cast<GpioJSONRequest>(request);
DUMP_VAR(typeid(_request).name());
BOOST_CHECK(nullptr != _request);
DO_ACK_GOOD_CHECK();
}
| [
"yma@asratec.co.jp"
] | yma@asratec.co.jp |
2da1706a3ff86cb174a36160d72ba4a9c27a937c | fd944c61dc1a10b7b2cacaccc32d94af0b8c7a0a | /ofxUI/Old/simpleButton.h | 4cfe0be57e29b768cdcdee5220b7d3d4a6d1c987 | [] | no_license | vtron/ofxVtron | 6878af2090c4d4053c2b466e0b4988e409af253b | 23d1c5641b8b7ea8b43b99ed07dfd77c201a8e6a | refs/heads/master | 2016-09-06T16:06:27.322694 | 2011-03-02T02:40:17 | 2011-03-02T02:40:17 | 1,428,337 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | h | /*
* test.h
* openFrameworks
*
* Created by StephenVarga on 10/6/09.
* Copyright 2009. All rights reserved.
*
*/
#ifndef _simpleButton
#define _simpleButton
#include "uiObserver.h"
#include "ofMain.h"
class uiObserver;
class simpleButton {
public:
simpleButton();
virtual ~simpleButton();
uiObserver* ui;
virtual void setup();
virtual void update();
virtual void draw();
virtual void mouseMoved(int x, int y);
virtual void mouseDragged(int x, int y, int button);
virtual void mousePressed(int x, int y, int button);
virtual void mouseReleased(int x, int y, int button);
int x;
int y;
int width;
int height;
bool bDraw;
};
#endif | [
"steve@vargatron.com"
] | steve@vargatron.com |
27bf2721eaa69963019d393585c09f24d4391a6d | a36d39f47661e70148ad5b068baddd26f2d6c68a | /UVMProject/methodCallStack.cpp | cbefea99ee7e39f228f80de87898172ede31ceb7 | [] | no_license | mrthetkhine/UVMForMac | d5203f0de3baf2e7acc9ed431d2e01d3f99c2fc1 | 866baa644f9c1ae111de311b348abb25dd184f51 | refs/heads/master | 2020-05-30T23:22:20.078924 | 2019-06-03T13:57:19 | 2019-06-03T13:57:19 | 190,015,221 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | cpp | #ifndef uvm_h
#include "uvm.h"
#endif
#ifndef methodCallStack_h
#include "methodCallStack.h"
#endif
#include <iostream>
using namespace std;
MethodCallStack* MethodCallStack::methodCallStack = NULL;
MethodCallStack::MethodCallStack()
{
for(int i=0; i< maxNoOfFrame;i++)
{
frames[i] = NULL;
}
top = -1;
currentFrame = NULL;
}
MethodCallStack * MethodCallStack::getMethodCallStack()
{
if( methodCallStack == NULL)
{
methodCallStack = new MethodCallStack();
}
return methodCallStack;
}
MethodFrame* MethodCallStack::getCurrentFrame()
{
///cout<<"ACCESSING "<<currentFrame->theClass->className<<" "<<currentFrame->constantPool<<endl;
return currentFrame;
}
void MethodCallStack::pushAFrame(MethodFrame *newFrame)
{
frames[++top]= newFrame;
currentFrame = newFrame;
///cout<<"PUSH top "<<top<<" "<<newFrame->theClass->className<<" of method "<<newFrame->method->methodName<<" "<<newFrame->constantPool<<endl;
}
void MethodCallStack::popAFrame()
{
///cout<<"POP top "<<top;
top--;
if(top < 0)
{
currentFrame = NULL;
}
else
{
///cout<<" "<< currentFrame->theClass->className<<" of method "<<currentFrame->method->methodName<<" "<< currentFrame->constantPool<<endl;
currentFrame = frames[top];
///cout<<"CURRENT Class "<<currentFrame->theClass->className<<"top "<<top<<endl;
}
}
| [
"mrthetkhine@gmail.com"
] | mrthetkhine@gmail.com |
dc3fc45a2a80b41cb7573ae0d49f23370edd92e8 | 5740ea2c2d9d5fb5626ff5ad651f3789048ae86b | /PlasmaLibraries/Common/Time.cpp | a9e88440be533e8d68d0a384330782bdbb9ad462 | [
"MIT"
] | permissive | donovan680/Plasma | 4945b92b7c6e642a557f12e05c7d53819186de55 | 51d40ef0669b7a3015f95e3c84c6d639d5469b62 | refs/heads/master | 2022-04-15T02:42:26.469268 | 2020-02-26T22:32:12 | 2020-02-26T22:32:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | ///////////////////////////////////////////////////////////////////////////////
///
/// \file Time.cpp
///
/// Authors: Joshua Davis
/// Copyright 2010-2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Plasma
{
TimeType Time::GetTime()
{
return time(0);
}
TimeType Time::Clock()
{
return clock();
}
TimeType Time::GenerateSeed()
{
return clock();
}
CalendarDateTime Time::GetLocalTime(const TimeType& timer)
{
CalendarDateTime result;
tm* lt = localtime(&timer);
result.Seconds = lt->tm_sec;
result.Minutes = lt->tm_min;
result.Hour = lt->tm_hour;
result.Day = lt->tm_mday;
result.Month = lt->tm_mon;
result.Year = lt->tm_year + 1900;
result.Weekday = lt->tm_wday;
result.Yearday = lt->tm_yday;
result.IsDaylightSavings = lt->tm_isdst;
return result;
}
TimeType Time::CalendarDateTimeToTimeType(const CalendarDateTime& time)
{
tm newTime;
newTime.tm_sec = time.Seconds;
newTime.tm_min = time.Minutes;
newTime.tm_hour = time.Hour;
newTime.tm_mday = time.Day;
newTime.tm_mon = time.Month;
newTime.tm_year = time.Year - 1900;
newTime.tm_wday = time.Weekday;
newTime.tm_yday = time.Yearday;
newTime.tm_isdst = time.IsDaylightSavings;
return mktime(&newTime);
}
TimeType Time::ClocksPerSecond()
{
return CLOCKS_PER_SEC;
}
}//namespace Plasma
| [
"dragonCASTjosh@gmail.com"
] | dragonCASTjosh@gmail.com |
a3a45905576b7b28985e8abe2e5f6ca9481ea67a | 81b1e98f8a4b964e4db70d17ca61f2d9fbff2606 | /GameEngine/cGLColourHelper.cpp | f930dd2ae046ae14169bb1876148aa7ac51d9e8e | [] | no_license | niral3737/GameJam | 07f47349341b53dc5c8bc23253c92afd61eb3b97 | f3a9f7fa161770976f21d724a1a7aa683cfc1122 | refs/heads/master | 2020-05-16T06:23:59.768707 | 2019-04-24T00:22:18 | 2019-04-24T00:22:18 | 182,845,158 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,075 | cpp | #include "cGLColourHelper.h"
#include <algorithm>
cGLColourHelper::cColour::cColour( std::string sName, cGLColourHelper::enumColours colourEnum, glm::vec3 initRGB )
{
this->enumName = colourEnum;
this->name = sName;
this->rgb = initRGB;
return;
}
cGLColourHelper::cColour::cColour( std::string sName, cGLColourHelper::enumColours colourEnum, float r, float g, float b )
{
this->enumName = colourEnum;
this->name = sName;
this->rgb.r = r;
this->rgb.g = g;
this->rgb.b = b;
return;
}
//static
cGLColourHelper* cGLColourHelper::m_p_theInstance = 0;
//static
cGLColourHelper* cGLColourHelper::getInstance( void )
{
if ( cGLColourHelper::m_p_theInstance == 0 )
{
cGLColourHelper::m_p_theInstance = new cGLColourHelper();
}
return cGLColourHelper::m_p_theInstance;
}
cGLColourHelper::cGLColourHelper()
{
this->m_mapColours[ ALICE_BLUE ] = cGLColourHelper::cColour( "AliceBlue", ALICE_BLUE, 0.941f, 0.973f, 1.000f);
this->m_mapColours[ ANTIQUE_WHITE ] = cGLColourHelper::cColour( "AntiqueWhite", ANTIQUE_WHITE, 0.980f, 0.922f, 0.843f);
this->m_mapColours[ AQUA ] = cGLColourHelper::cColour( "Aqua", AQUA, 0.000f, 1.000f, 1.000f);
this->m_mapColours[ AQUAMARINE ] = cGLColourHelper::cColour( "Aquamarine", AQUAMARINE, 0.498f, 1.000f, 0.831f);
this->m_mapColours[ AZURE ] = cGLColourHelper::cColour( "Azure", AZURE, 0.941f, 1.000f, 1.000f);
this->m_mapColours[ BEIGE ] = cGLColourHelper::cColour( "Beige", BEIGE, 0.961f, 0.961f, 0.863f);
this->m_mapColours[ BISQUE ] = cGLColourHelper::cColour( "Bisque", BISQUE, 1.000f, 0.894f, 0.769f);
this->m_mapColours[ BLACK ] = cGLColourHelper::cColour( "Black", BLACK, 0.000f, 0.000f, 0.000f);
this->m_mapColours[ BLANCHED_ALMOND ] = cGLColourHelper::cColour( "BlanchedAlmond", BLANCHED_ALMOND, 1.000f, 0.922f, 0.804f);
this->m_mapColours[ BLUE ] = cGLColourHelper::cColour( "Blue", BLUE, 0.000f, 0.000f, 1.000f);
this->m_mapColours[ BLUE_VIOLET ] = cGLColourHelper::cColour( "BlueViolet", BLUE_VIOLET, 0.541f, 0.169f, 0.886f);
this->m_mapColours[ BROWN ] = cGLColourHelper::cColour( "Brown", BROWN, 0.647f, 0.165f, 0.165f);
this->m_mapColours[ BURLY_WOOD ] = cGLColourHelper::cColour( "BurlyWood", BURLY_WOOD, 0.871f, 0.722f, 0.529f);
this->m_mapColours[ CADET_BLUE ] = cGLColourHelper::cColour( "CadetBlue", CADET_BLUE, 0.373f, 0.620f, 0.627f);
this->m_mapColours[ CHARTREUSE ] = cGLColourHelper::cColour( "Chartreuse", CHARTREUSE, 0.498f, 1.000f, 0.000f);
this->m_mapColours[ CHOCOLATE ] = cGLColourHelper::cColour( "Chocolate", CHOCOLATE, 0.824f, 0.412f, 0.118f);
this->m_mapColours[ CORAL ] = cGLColourHelper::cColour( "Coral", CORAL, 1.000f, 0.498f, 0.314f);
this->m_mapColours[ CORNFLOWER_BLUE ] = cGLColourHelper::cColour( "CornflowerBlue", CORNFLOWER_BLUE, 0.392f, 0.584f, 0.929f);
this->m_mapColours[ CORNSILK ] = cGLColourHelper::cColour( "Cornsilk", CORNSILK, 1.000f, 0.973f, 0.863f);
this->m_mapColours[ CRIMSON ] = cGLColourHelper::cColour( "Crimson", CRIMSON, 0.863f, 0.078f, 0.235f);
this->m_mapColours[ CYAN ] = cGLColourHelper::cColour( "Cyan", CYAN, 0.000f, 1.000f, 1.000f);
this->m_mapColours[ DARK_BLUE ] = cGLColourHelper::cColour( "DarkBlue", DARK_BLUE, 0.000f, 0.000f, 0.545f);
this->m_mapColours[ DARK_CYAN ] = cGLColourHelper::cColour( "DarkCyan", DARK_CYAN, 0.000f, 0.545f, 0.545f);
this->m_mapColours[ DARK_GOLDEN_ROD ] = cGLColourHelper::cColour( "DarkGoldenRod", DARK_GOLDEN_ROD, 0.722f, 0.525f, 0.043f);
this->m_mapColours[ DARK_GRAY ] = cGLColourHelper::cColour( "DarkGray", DARK_GRAY, 0.663f, 0.663f, 0.663f);
this->m_mapColours[ DARK_GREEN ] = cGLColourHelper::cColour( "DarkGreen", DARK_GREEN, 0.000f, 0.392f, 0.000f);
this->m_mapColours[ DARK_KHAKI ] = cGLColourHelper::cColour( "DarkKhaki", DARK_KHAKI, 0.741f, 0.718f, 0.420f);
this->m_mapColours[ DARK_MAGENTA ] = cGLColourHelper::cColour( "DarkMagenta", DARK_MAGENTA, 0.545f, 0.000f, 0.545f);
this->m_mapColours[ DARK_OLIVE_GREEN ] = cGLColourHelper::cColour( "DarkOliveGreen", DARK_OLIVE_GREEN, 0.333f, 0.420f, 0.184f);
this->m_mapColours[ DARK_ORANGE ] = cGLColourHelper::cColour( "DarkOrange", DARK_ORANGE, 1.000f, 0.549f, 0.000f);
this->m_mapColours[ DARK_ORCHID ] = cGLColourHelper::cColour( "DarkOrchid", DARK_ORCHID, 0.600f, 0.196f, 0.800f);
this->m_mapColours[ DARK_RED ] = cGLColourHelper::cColour( "DarkRed", DARK_RED, 0.545f, 0.000f, 0.000f);
this->m_mapColours[ DARK_SALMON ] = cGLColourHelper::cColour( "DarkSalmon", DARK_SALMON, 0.914f, 0.588f, 0.478f);
this->m_mapColours[ DARK_SEA_GREEN ] = cGLColourHelper::cColour( "DarkSeaGreen", DARK_SEA_GREEN, 0.561f, 0.737f, 0.561f);
this->m_mapColours[ DARK_SLATE_BLUE ] = cGLColourHelper::cColour( "DarkSlateBlue", DARK_SLATE_BLUE, 0.282f, 0.239f, 0.545f);
this->m_mapColours[ DARK_SLATE_GRAY ] = cGLColourHelper::cColour( "DarkSlateGray", DARK_SLATE_GRAY, 0.184f, 0.310f, 0.310f);
this->m_mapColours[ DARK_TURQUOISE ] = cGLColourHelper::cColour( "DarkTurquoise", DARK_TURQUOISE, 0.000f, 0.808f, 0.820f);
this->m_mapColours[ DARK_VIOLET ] = cGLColourHelper::cColour( "DarkViolet", DARK_VIOLET, 0.580f, 0.000f, 0.827f);
this->m_mapColours[ DEEP_PINK ] = cGLColourHelper::cColour( "DeepPink", DEEP_PINK, 1.000f, 0.078f, 0.576f);
this->m_mapColours[ DEEP_SKY_BLUE ] = cGLColourHelper::cColour( "DeepSkyBlue", DEEP_SKY_BLUE, 0.000f, 0.749f, 1.000f);
this->m_mapColours[ DIM_GRAY ] = cGLColourHelper::cColour( "DimGray", DIM_GRAY, 0.412f, 0.412f, 0.412f);
this->m_mapColours[ DODGER_BLUE ] = cGLColourHelper::cColour( "DodgerBlue", DODGER_BLUE, 0.118f, 0.565f, 1.000f);
this->m_mapColours[ FIRE_BRICK ] = cGLColourHelper::cColour( "FireBrick", FIRE_BRICK, 0.698f, 0.133f, 0.133f);
this->m_mapColours[ FLORAL_WHITE ] = cGLColourHelper::cColour( "FloralWhite", FLORAL_WHITE, 1.000f, 0.980f, 0.941f);
this->m_mapColours[ FOREST_GREEN ] = cGLColourHelper::cColour( "ForestGreen", FOREST_GREEN, 0.133f, 0.545f, 0.133f);
this->m_mapColours[ FUCHSIA ] = cGLColourHelper::cColour( "Fuchsia", FUCHSIA, 1.000f, 0.000f, 1.000f);
this->m_mapColours[ GAINSBORO ] = cGLColourHelper::cColour( "Gainsboro", GAINSBORO, 0.863f, 0.863f, 0.863f);
this->m_mapColours[ GHOST_WHITE ] = cGLColourHelper::cColour( "GhostWhite", GHOST_WHITE, 0.973f, 0.973f, 1.000f);
this->m_mapColours[ GOLD ] = cGLColourHelper::cColour( "Gold", GOLD, 1.000f, 0.843f, 0.000f);
this->m_mapColours[ GOLDEN_ROD ] = cGLColourHelper::cColour( "GoldenRod", GOLDEN_ROD, 0.855f, 0.647f, 0.125f);
this->m_mapColours[ GRAY ] = cGLColourHelper::cColour( "Gray", GRAY, 0.502f, 0.502f, 0.502f);
this->m_mapColours[ GREEN ] = cGLColourHelper::cColour( "Green", GREEN, 0.000f, 0.502f, 0.000f);
this->m_mapColours[ GREEN_YELLOW ] = cGLColourHelper::cColour( "GreenYellow", GREEN_YELLOW, 0.678f, 1.000f, 0.184f);
this->m_mapColours[ HONEY_DEW ] = cGLColourHelper::cColour( "HoneyDew", HONEY_DEW, 0.941f, 1.000f, 0.941f);
this->m_mapColours[ HOT_PINK ] = cGLColourHelper::cColour( "HotPink", HOT_PINK, 1.000f, 0.412f, 0.706f);
this->m_mapColours[ INDIAN_RED ] = cGLColourHelper::cColour( "IndianRed", INDIAN_RED, 0.804f, 0.361f, 0.361f);
this->m_mapColours[ INDIGO ] = cGLColourHelper::cColour( "Indigo", INDIGO, 0.294f, 0.000f, 0.510f);
this->m_mapColours[ IVORY ] = cGLColourHelper::cColour( "Ivory", IVORY, 1.000f, 1.000f, 0.941f);
this->m_mapColours[ KHAKI ] = cGLColourHelper::cColour( "Khaki", KHAKI, 0.941f, 0.902f, 0.549f);
this->m_mapColours[ LAVENDER ] = cGLColourHelper::cColour( "Lavender", LAVENDER, 0.902f, 0.902f, 0.980f);
this->m_mapColours[ LAVENDER_BLUSH ] = cGLColourHelper::cColour( "LavenderBlush", LAVENDER_BLUSH, 1.000f, 0.941f, 0.961f);
this->m_mapColours[ LAWN_GREEN ] = cGLColourHelper::cColour( "LawnGreen", LAWN_GREEN, 0.486f, 0.988f, 0.000f);
this->m_mapColours[ LEMON_CHIFFON ] = cGLColourHelper::cColour( "LemonChiffon", LEMON_CHIFFON, 1.000f, 0.980f, 0.804f);
this->m_mapColours[ LIGHT_BLUE ] = cGLColourHelper::cColour( "LightBlue", LIGHT_BLUE, 0.678f, 0.847f, 0.902f);
this->m_mapColours[ LIGHT_CORAL ] = cGLColourHelper::cColour( "LightCoral", LIGHT_CORAL, 0.941f, 0.502f, 0.502f);
this->m_mapColours[ LIGHT_CYAN ] = cGLColourHelper::cColour( "LightCyan", LIGHT_CYAN, 0.878f, 1.000f, 1.000f);
this->m_mapColours[ LIGHT_GOLDEN_ROD_YELLOW ] = cGLColourHelper::cColour( "LightGoldenRodYellow", LIGHT_GOLDEN_ROD_YELLOW, 0.980f, 0.980f, 0.824f);
this->m_mapColours[ LIGHT_GRAY ] = cGLColourHelper::cColour( "LightGray", LIGHT_GRAY, 0.827f, 0.827f, 0.827f);
this->m_mapColours[ LIGHT_GREEN ] = cGLColourHelper::cColour( "LightGreen", LIGHT_GREEN, 0.565f, 0.933f, 0.565f);
this->m_mapColours[ LIGHT_PINK ] = cGLColourHelper::cColour( "LightPink", LIGHT_PINK, 1.000f, 0.714f, 0.757f);
this->m_mapColours[ LIGHT_SALMON ] = cGLColourHelper::cColour( "LightSalmon", LIGHT_SALMON, 1.000f, 0.627f, 0.478f);
this->m_mapColours[ LIGHT_SEA_GREEN ] = cGLColourHelper::cColour( "LightSeaGreen", LIGHT_SEA_GREEN, 0.125f, 0.698f, 0.667f);
this->m_mapColours[ LIGHT_SKY_BLUE ] = cGLColourHelper::cColour( "LightSkyBlue", LIGHT_SKY_BLUE, 0.529f, 0.808f, 0.980f);
this->m_mapColours[ LIGHT_SLATE_GRAY ] = cGLColourHelper::cColour( "LightSlateGray", LIGHT_SLATE_GRAY, 0.467f, 0.533f, 0.600f);
this->m_mapColours[ LIGHT_STEEL_BLUE ] = cGLColourHelper::cColour( "LightSteelBlue", LIGHT_STEEL_BLUE, 0.690f, 0.769f, 0.871f);
this->m_mapColours[ LIGHT_YELLOW ] = cGLColourHelper::cColour( "LightYellow", LIGHT_YELLOW, 1.000f, 1.000f, 0.878f);
this->m_mapColours[ LIME ] = cGLColourHelper::cColour( "Lime", LIME, 0.000f, 1.000f, 0.000f);
this->m_mapColours[ LIME_GREEN ] = cGLColourHelper::cColour( "LimeGreen", LIME_GREEN, 0.196f, 0.804f, 0.196f);
this->m_mapColours[ LINEN ] = cGLColourHelper::cColour( "Linen", LINEN, 0.980f, 0.941f, 0.902f);
this->m_mapColours[ MAGENTA ] = cGLColourHelper::cColour( "Magenta", MAGENTA, 1.000f, 0.000f, 1.000f);
this->m_mapColours[ MAROON ] = cGLColourHelper::cColour( "Maroon", MAROON, 0.502f, 0.000f, 0.000f);
this->m_mapColours[ MEDIUM_AQUA_MARINE ] = cGLColourHelper::cColour( "MediumAquaMarine", MEDIUM_AQUA_MARINE, 0.400f, 0.804f, 0.667f);
this->m_mapColours[ MEDIUM_BLUE ] = cGLColourHelper::cColour( "MediumBlue", MEDIUM_BLUE, 0.000f, 0.000f, 0.804f);
this->m_mapColours[ MEDIUM_ORCHID ] = cGLColourHelper::cColour( "MediumOrchid", MEDIUM_ORCHID, 0.729f, 0.333f, 0.827f);
this->m_mapColours[ MEDIUM_PURPLE ] = cGLColourHelper::cColour( "MediumPurple", MEDIUM_PURPLE, 0.576f, 0.439f, 0.859f);
this->m_mapColours[ MEDIUM_SEA_GREEN ] = cGLColourHelper::cColour( "MediumSeaGreen", MEDIUM_SEA_GREEN, 0.235f, 0.702f, 0.443f);
this->m_mapColours[ MEDIUM_SLATE_BLUE ] = cGLColourHelper::cColour( "MediumSlateBlue", MEDIUM_SLATE_BLUE, 0.482f, 0.408f, 0.933f);
this->m_mapColours[ MEDIUM_SPRING_GREEN ] = cGLColourHelper::cColour( "MediumSpringGreen", MEDIUM_SPRING_GREEN, 0.000f, 0.980f, 0.604f);
this->m_mapColours[ MEDIUM_TURQUOISE ] = cGLColourHelper::cColour( "MediumTurquoise", MEDIUM_TURQUOISE, 0.282f, 0.820f, 0.800f);
this->m_mapColours[ MEDIUM_VIOLET_RED ] = cGLColourHelper::cColour( "MediumVioletRed", MEDIUM_VIOLET_RED, 0.780f, 0.082f, 0.522f);
this->m_mapColours[ MIDNIGHT_BLUE ] = cGLColourHelper::cColour( "MidnightBlue", MIDNIGHT_BLUE, 0.098f, 0.098f, 0.439f);
this->m_mapColours[ MINT_CREAM ] = cGLColourHelper::cColour( "MintCream", MINT_CREAM, 0.961f, 1.000f, 0.980f);
this->m_mapColours[ MISTY_ROSE ] = cGLColourHelper::cColour( "MistyRose", MISTY_ROSE, 1.000f, 0.894f, 0.882f);
this->m_mapColours[ MOCCASIN ] = cGLColourHelper::cColour( "Moccasin", MOCCASIN, 1.000f, 0.894f, 0.710f);
this->m_mapColours[ NAVAJO_WHITE ] = cGLColourHelper::cColour( "NavajoWhite", NAVAJO_WHITE, 1.000f, 0.871f, 0.678f);
this->m_mapColours[ NAVY ] = cGLColourHelper::cColour( "Navy", NAVY, 0.000f, 0.000f, 0.502f);
this->m_mapColours[ OLD_LACE ] = cGLColourHelper::cColour( "OldLace", OLD_LACE, 0.992f, 0.961f, 0.902f);
this->m_mapColours[ OLIVE ] = cGLColourHelper::cColour( "Olive", OLIVE, 0.502f, 0.502f, 0.000f);
this->m_mapColours[ OLIVE_DRAB ] = cGLColourHelper::cColour( "OliveDrab", OLIVE_DRAB, 0.420f, 0.557f, 0.137f);
this->m_mapColours[ ORANGE ] = cGLColourHelper::cColour( "Orange", ORANGE, 1.000f, 0.647f, 0.000f);
this->m_mapColours[ ORANGE_RED ] = cGLColourHelper::cColour( "OrangeRed", ORANGE_RED, 1.000f, 0.271f, 0.000f);
this->m_mapColours[ ORCHID ] = cGLColourHelper::cColour( "Orchid", ORCHID, 0.855f, 0.439f, 0.839f);
this->m_mapColours[ PALE_GOLDEN_ROD ] = cGLColourHelper::cColour( "PaleGoldenRod", PALE_GOLDEN_ROD, 0.933f, 0.910f, 0.667f);
this->m_mapColours[ PALE_GREEN ] = cGLColourHelper::cColour( "PaleGreen", PALE_GREEN, 0.596f, 0.984f, 0.596f);
this->m_mapColours[ PALE_TURQUOISE ] = cGLColourHelper::cColour( "PaleTurquoise", PALE_TURQUOISE, 0.686f, 0.933f, 0.933f);
this->m_mapColours[ PALE_VIOLET_RED ] = cGLColourHelper::cColour( "PaleVioletRed", PALE_VIOLET_RED, 0.859f, 0.439f, 0.576f);
this->m_mapColours[ PAPAYA_WHIP ] = cGLColourHelper::cColour( "PapayaWhip", PAPAYA_WHIP, 1.000f, 0.937f, 0.835f);
this->m_mapColours[ PEACH_PUFF ] = cGLColourHelper::cColour( "PeachPuff", PEACH_PUFF, 1.000f, 0.855f, 0.725f);
this->m_mapColours[ PERU ] = cGLColourHelper::cColour( "Peru", PERU, 0.804f, 0.522f, 0.247f);
this->m_mapColours[ PINK ] = cGLColourHelper::cColour( "Pink", PINK, 1.000f, 0.753f, 0.796f);
this->m_mapColours[ PLUM ] = cGLColourHelper::cColour( "Plum", PLUM, 0.867f, 0.627f, 0.867f);
this->m_mapColours[ POWDER_BLUE ] = cGLColourHelper::cColour( "PowderBlue", POWDER_BLUE, 0.690f, 0.878f, 0.902f);
this->m_mapColours[ PURPLE ] = cGLColourHelper::cColour( "Purple", PURPLE, 0.502f, 0.000f, 0.502f);
this->m_mapColours[ REBECCA_PURPLE ] = cGLColourHelper::cColour( "RebeccaPurple", REBECCA_PURPLE, 0.400f, 0.200f, 0.600f);
this->m_mapColours[ RED ] = cGLColourHelper::cColour( "Red", RED, 1.000f, 0.000f, 0.000f);
this->m_mapColours[ ROSY_BROWN ] = cGLColourHelper::cColour( "RosyBrown", ROSY_BROWN, 0.737f, 0.561f, 0.561f);
this->m_mapColours[ ROYAL_BLUE ] = cGLColourHelper::cColour( "RoyalBlue", ROYAL_BLUE, 0.255f, 0.412f, 0.882f);
this->m_mapColours[ SADDLE_BROWN ] = cGLColourHelper::cColour( "SaddleBrown", SADDLE_BROWN, 0.545f, 0.271f, 0.075f);
this->m_mapColours[ SALMON ] = cGLColourHelper::cColour( "Salmon", SALMON, 0.980f, 0.502f, 0.447f);
this->m_mapColours[ SANDY_BROWN ] = cGLColourHelper::cColour( "SandyBrown", SANDY_BROWN, 0.957f, 0.643f, 0.376f);
this->m_mapColours[ SEA_GREEN ] = cGLColourHelper::cColour( "SeaGreen", SEA_GREEN, 0.180f, 0.545f, 0.341f);
this->m_mapColours[ SEA_SHELL ] = cGLColourHelper::cColour( "SeaShell", SEA_SHELL, 1.000f, 0.961f, 0.933f);
this->m_mapColours[ SIENNA ] = cGLColourHelper::cColour( "Sienna", SIENNA, 0.627f, 0.322f, 0.176f);
this->m_mapColours[ SILVER ] = cGLColourHelper::cColour( "Silver", SILVER, 0.753f, 0.753f, 0.753f);
this->m_mapColours[ SKY_BLUE ] = cGLColourHelper::cColour( "SkyBlue", SKY_BLUE, 0.529f, 0.808f, 0.922f);
this->m_mapColours[ SLATE_BLUE ] = cGLColourHelper::cColour( "SlateBlue", SLATE_BLUE, 0.416f, 0.353f, 0.804f);
this->m_mapColours[ SLATE_GRAY ] = cGLColourHelper::cColour( "SlateGray", SLATE_GRAY, 0.439f, 0.502f, 0.565f);
this->m_mapColours[ SNOW ] = cGLColourHelper::cColour( "Snow", SNOW, 1.000f, 0.980f, 0.980f);
this->m_mapColours[ SPRING_GREEN ] = cGLColourHelper::cColour( "SpringGreen", SPRING_GREEN, 0.000f, 1.000f, 0.498f);
this->m_mapColours[ STEEL_BLUE ] = cGLColourHelper::cColour( "SteelBlue", STEEL_BLUE, 0.275f, 0.510f, 0.706f);
this->m_mapColours[ TAN ] = cGLColourHelper::cColour( "Tan", TAN, 0.824f, 0.706f, 0.549f);
this->m_mapColours[ TEAL ] = cGLColourHelper::cColour( "Teal", TEAL, 0.000f, 0.502f, 0.502f);
this->m_mapColours[ THISTLE ] = cGLColourHelper::cColour( "Thistle", THISTLE, 0.847f, 0.749f, 0.847f);
this->m_mapColours[ TOMATO ] = cGLColourHelper::cColour( "Tomato", TOMATO, 1.000f, 0.388f, 0.278f);
this->m_mapColours[ TURQUOISE ] = cGLColourHelper::cColour( "Turquoise", TURQUOISE, 0.251f, 0.878f, 0.816f);
this->m_mapColours[ VIOLET ] = cGLColourHelper::cColour( "Violet", VIOLET, 0.933f, 0.510f, 0.933f);
this->m_mapColours[ WHEAT ] = cGLColourHelper::cColour( "Wheat", WHEAT, 0.961f, 0.871f, 0.702f);
this->m_mapColours[ WHITE ] = cGLColourHelper::cColour( "White", WHITE, 1.000f, 1.000f, 1.000f);
this->m_mapColours[ WHITE_SMOKE ] = cGLColourHelper::cColour( "WhiteSmoke", WHITE_SMOKE, 0.961f, 0.961f, 0.961f);
this->m_mapColours[ YELLOW ] = cGLColourHelper::cColour( "Yellow", YELLOW, 1.000f, 1.000f, 0.000f);
this->m_mapColours[ YELLOW_GREEN ] = cGLColourHelper::cColour( "YellowGreen", YELLOW_GREEN, 0.604f, 0.804f, 0.196f);
this->m_mapColourNameToEnum[ "AliceBlue" ] = ALICE_BLUE;
this->m_mapColourNameToEnum[ "AntiqueWhite" ] = ANTIQUE_WHITE;
this->m_mapColourNameToEnum[ "Aqua" ] = AQUA;
this->m_mapColourNameToEnum[ "Aquamarine" ] = AQUAMARINE;
this->m_mapColourNameToEnum[ "Azure" ] = AZURE;
this->m_mapColourNameToEnum[ "Beige" ] = BEIGE;
this->m_mapColourNameToEnum[ "Bisque" ] = BISQUE;
this->m_mapColourNameToEnum[ "Black" ] = BLACK;
this->m_mapColourNameToEnum[ "BlanchedAlmond" ] = BLANCHED_ALMOND;
this->m_mapColourNameToEnum[ "Blue" ] = BLUE;
this->m_mapColourNameToEnum[ "BlueViolet" ] = BLUE_VIOLET;
this->m_mapColourNameToEnum[ "Brown" ] = BROWN;
this->m_mapColourNameToEnum[ "BurlyWood" ] = BURLY_WOOD;
this->m_mapColourNameToEnum[ "CadetBlue" ] = CADET_BLUE;
this->m_mapColourNameToEnum[ "Chartreuse" ] = CHARTREUSE;
this->m_mapColourNameToEnum[ "Chocolate" ] = CHOCOLATE;
this->m_mapColourNameToEnum[ "Coral" ] = CORAL;
this->m_mapColourNameToEnum[ "CornflowerBlue" ] = CORNFLOWER_BLUE;
this->m_mapColourNameToEnum[ "Cornsilk" ] = CORNSILK;
this->m_mapColourNameToEnum[ "Crimson" ] = CRIMSON;
this->m_mapColourNameToEnum[ "Cyan" ] = CYAN;
this->m_mapColourNameToEnum[ "DarkBlue" ] = DARK_BLUE;
this->m_mapColourNameToEnum[ "DarkCyan" ] = DARK_CYAN;
this->m_mapColourNameToEnum[ "DarkGoldenRod" ] = DARK_GOLDEN_ROD;
this->m_mapColourNameToEnum[ "DarkGray" ] = DARK_GRAY;
this->m_mapColourNameToEnum[ "DarkGreen" ] = DARK_GREEN;
this->m_mapColourNameToEnum[ "DarkKhaki" ] = DARK_KHAKI;
this->m_mapColourNameToEnum[ "DarkMagenta" ] = DARK_MAGENTA;
this->m_mapColourNameToEnum[ "DarkOliveGreen" ] = DARK_OLIVE_GREEN;
this->m_mapColourNameToEnum[ "DarkOrange" ] = DARK_ORANGE;
this->m_mapColourNameToEnum[ "DarkOrchid" ] = DARK_ORCHID;
this->m_mapColourNameToEnum[ "DarkRed" ] = DARK_RED;
this->m_mapColourNameToEnum[ "DarkSalmon" ] = DARK_SALMON;
this->m_mapColourNameToEnum[ "DarkSeaGreen" ] = DARK_SEA_GREEN;
this->m_mapColourNameToEnum[ "DarkSlateBlue" ] = DARK_SLATE_BLUE;
this->m_mapColourNameToEnum[ "DarkSlateGray" ] = DARK_SLATE_GRAY;
this->m_mapColourNameToEnum[ "DarkTurquoise" ] = DARK_TURQUOISE;
this->m_mapColourNameToEnum[ "DarkViolet" ] = DARK_VIOLET;
this->m_mapColourNameToEnum[ "DeepPink" ] = DEEP_PINK;
this->m_mapColourNameToEnum[ "DeepSkyBlue" ] = DEEP_SKY_BLUE;
this->m_mapColourNameToEnum[ "DimGray" ] = DIM_GRAY;
this->m_mapColourNameToEnum[ "DodgerBlue" ] = DODGER_BLUE;
this->m_mapColourNameToEnum[ "FireBrick" ] = FIRE_BRICK;
this->m_mapColourNameToEnum[ "FloralWhite" ] = FLORAL_WHITE;
this->m_mapColourNameToEnum[ "ForestGreen" ] = FOREST_GREEN;
this->m_mapColourNameToEnum[ "Fuchsia" ] = FUCHSIA;
this->m_mapColourNameToEnum[ "Gainsboro" ] = GAINSBORO;
this->m_mapColourNameToEnum[ "GhostWhite" ] = GHOST_WHITE;
this->m_mapColourNameToEnum[ "Gold" ] = GOLD;
this->m_mapColourNameToEnum[ "GoldenRod" ] = GOLDEN_ROD;
this->m_mapColourNameToEnum[ "Gray" ] = GRAY;
this->m_mapColourNameToEnum[ "Green" ] = GREEN;
this->m_mapColourNameToEnum[ "GreenYellow" ] = GREEN_YELLOW;
this->m_mapColourNameToEnum[ "HoneyDew" ] = HONEY_DEW;
this->m_mapColourNameToEnum[ "HotPink" ] = HOT_PINK;
this->m_mapColourNameToEnum[ "IndianRed" ] = INDIAN_RED;
this->m_mapColourNameToEnum[ "Indigo" ] = INDIGO;
this->m_mapColourNameToEnum[ "Ivory" ] = IVORY;
this->m_mapColourNameToEnum[ "Khaki" ] = KHAKI;
this->m_mapColourNameToEnum[ "Lavender" ] = LAVENDER;
this->m_mapColourNameToEnum[ "LavenderBlush" ] = LAVENDER_BLUSH;
this->m_mapColourNameToEnum[ "LawnGreen" ] = LAWN_GREEN;
this->m_mapColourNameToEnum[ "LemonChiffon" ] = LEMON_CHIFFON;
this->m_mapColourNameToEnum[ "LightBlue" ] = LIGHT_BLUE;
this->m_mapColourNameToEnum[ "LightCoral" ] = LIGHT_CORAL;
this->m_mapColourNameToEnum[ "LightCyan" ] = LIGHT_CYAN;
this->m_mapColourNameToEnum[ "LightGoldenRodYellow" ] = LIGHT_GOLDEN_ROD_YELLOW;
this->m_mapColourNameToEnum[ "LightGray" ] = LIGHT_GRAY;
this->m_mapColourNameToEnum[ "LightGreen" ] = LIGHT_GREEN;
this->m_mapColourNameToEnum[ "LightPink" ] = LIGHT_PINK;
this->m_mapColourNameToEnum[ "LightSalmon" ] = LIGHT_SALMON;
this->m_mapColourNameToEnum[ "LightSeaGreen" ] = LIGHT_SEA_GREEN;
this->m_mapColourNameToEnum[ "LightSkyBlue" ] = LIGHT_SKY_BLUE;
this->m_mapColourNameToEnum[ "LightSlateGray" ] = LIGHT_SLATE_GRAY;
this->m_mapColourNameToEnum[ "LightSteelBlue" ] = LIGHT_STEEL_BLUE;
this->m_mapColourNameToEnum[ "LightYellow" ] = LIGHT_YELLOW;
this->m_mapColourNameToEnum[ "Lime" ] = LIME;
this->m_mapColourNameToEnum[ "LimeGreen" ] = LIME_GREEN;
this->m_mapColourNameToEnum[ "Linen" ] = LINEN;
this->m_mapColourNameToEnum[ "Magenta" ] = MAGENTA;
this->m_mapColourNameToEnum[ "Maroon" ] = MAROON;
this->m_mapColourNameToEnum[ "MediumAquaMarine" ] = MEDIUM_AQUA_MARINE;
this->m_mapColourNameToEnum[ "MediumBlue" ] = MEDIUM_BLUE;
this->m_mapColourNameToEnum[ "MediumOrchid" ] = MEDIUM_ORCHID;
this->m_mapColourNameToEnum[ "MediumPurple" ] = MEDIUM_PURPLE;
this->m_mapColourNameToEnum[ "MediumSeaGreen" ] = MEDIUM_SEA_GREEN;
this->m_mapColourNameToEnum[ "MediumSlateBlue" ] = MEDIUM_SLATE_BLUE;
this->m_mapColourNameToEnum[ "MediumSpringGreen" ] = MEDIUM_SPRING_GREEN;
this->m_mapColourNameToEnum[ "MediumTurquoise" ] = MEDIUM_TURQUOISE;
this->m_mapColourNameToEnum[ "MediumVioletRed" ] = MEDIUM_VIOLET_RED;
this->m_mapColourNameToEnum[ "MidnightBlue" ] = MIDNIGHT_BLUE;
this->m_mapColourNameToEnum[ "MintCream" ] = MINT_CREAM;
this->m_mapColourNameToEnum[ "MistyRose" ] = MISTY_ROSE;
this->m_mapColourNameToEnum[ "Moccasin" ] = MOCCASIN;
this->m_mapColourNameToEnum[ "NavajoWhite" ] = NAVAJO_WHITE;
this->m_mapColourNameToEnum[ "Navy" ] = NAVY;
this->m_mapColourNameToEnum[ "OldLace" ] = OLD_LACE;
this->m_mapColourNameToEnum[ "Olive" ] = OLIVE;
this->m_mapColourNameToEnum[ "OliveDrab" ] = OLIVE_DRAB;
this->m_mapColourNameToEnum[ "Orange" ] = ORANGE;
this->m_mapColourNameToEnum[ "OrangeRed" ] = ORANGE_RED;
this->m_mapColourNameToEnum[ "Orchid" ] = ORCHID;
this->m_mapColourNameToEnum[ "PaleGoldenRod" ] = PALE_GOLDEN_ROD;
this->m_mapColourNameToEnum[ "PaleGreen" ] = PALE_GREEN;
this->m_mapColourNameToEnum[ "PaleTurquoise" ] = PALE_TURQUOISE;
this->m_mapColourNameToEnum[ "PaleVioletRed" ] = PALE_VIOLET_RED;
this->m_mapColourNameToEnum[ "PapayaWhip" ] = PAPAYA_WHIP;
this->m_mapColourNameToEnum[ "PeachPuff" ] = PEACH_PUFF;
this->m_mapColourNameToEnum[ "Peru" ] = PERU;
this->m_mapColourNameToEnum[ "Pink" ] = PINK;
this->m_mapColourNameToEnum[ "Plum" ] = PLUM;
this->m_mapColourNameToEnum[ "PowderBlue" ] = POWDER_BLUE;
this->m_mapColourNameToEnum[ "Purple" ] = PURPLE;
this->m_mapColourNameToEnum[ "RebeccaPurple" ] = REBECCA_PURPLE;
this->m_mapColourNameToEnum[ "Red" ] = RED;
this->m_mapColourNameToEnum[ "RosyBrown" ] = ROSY_BROWN;
this->m_mapColourNameToEnum[ "RoyalBlue" ] = ROYAL_BLUE;
this->m_mapColourNameToEnum[ "SaddleBrown" ] = SADDLE_BROWN;
this->m_mapColourNameToEnum[ "Salmon" ] = SALMON;
this->m_mapColourNameToEnum[ "SandyBrown" ] = SANDY_BROWN;
this->m_mapColourNameToEnum[ "SeaGreen" ] = SEA_GREEN;
this->m_mapColourNameToEnum[ "SeaShell" ] = SEA_SHELL;
this->m_mapColourNameToEnum[ "Sienna" ] = SIENNA;
this->m_mapColourNameToEnum[ "Silver" ] = SILVER;
this->m_mapColourNameToEnum[ "SkyBlue" ] = SKY_BLUE;
this->m_mapColourNameToEnum[ "SlateBlue" ] = SLATE_BLUE;
this->m_mapColourNameToEnum[ "SlateGray" ] = SLATE_GRAY;
this->m_mapColourNameToEnum[ "Snow" ] = SNOW;
this->m_mapColourNameToEnum[ "SpringGreen" ] = SPRING_GREEN;
this->m_mapColourNameToEnum[ "SteelBlue" ] = STEEL_BLUE;
this->m_mapColourNameToEnum[ "Tan" ] = TAN;
this->m_mapColourNameToEnum[ "Teal" ] = TEAL;
this->m_mapColourNameToEnum[ "Thistle" ] = THISTLE;
this->m_mapColourNameToEnum[ "Tomato" ] = TOMATO;
this->m_mapColourNameToEnum[ "Turquoise" ] = TURQUOISE;
this->m_mapColourNameToEnum[ "Violet" ] = VIOLET;
this->m_mapColourNameToEnum[ "Wheat" ] = WHEAT;
this->m_mapColourNameToEnum[ "White" ] = WHITE;
this->m_mapColourNameToEnum[ "WhiteSmoke" ] = WHITE_SMOKE;
this->m_mapColourNameToEnum[ "Yellow" ] = YELLOW;
this->m_mapColourNameToEnum[ "YellowGreen" ] = YELLOW_GREEN;
// Generate the random lookup
for ( std::map< cGLColourHelper::enumColours, cGLColourHelper::cColour >::iterator itColour = this->m_mapColours.begin();
itColour != this->m_mapColours.end(); itColour++ )
{
this->m_vecRandomColourEnumLookup.push_back( itColour->first );
}
// Scramble them
std::random_shuffle( this->m_vecRandomColourEnumLookup.begin(), this->m_vecRandomColourEnumLookup.begin() );
// Start the 'next' loop up at the start of the vector
this->m_nextRandomIndex = 0;
return;
}
cGLColourHelper::enumColours cGLColourHelper::getRandomColourEnum(void)
{
cGLColourHelper::enumColours randColourEnum = this->m_vecRandomColourEnumLookup[this->m_nextRandomIndex];
this->m_nextRandomIndex++;
if ( this->m_nextRandomIndex >= this->m_vecRandomColourEnumLookup.size() )
{
this->m_nextRandomIndex = 0;
}
return randColourEnum;
}
cGLColourHelper::cColour cGLColourHelper::getRandomColour(void)
{
cColour randColour;
randColour.rgb.r = this->getRand(0.0f, 1.0f);
randColour.rgb.g = this->getRand(0.0f, 1.0f);
randColour.rgb.b = this->getRand(0.0f, 1.0f);
randColour.enumName = CUSTOM;
return randColour;
}
glm::vec3 cGLColourHelper::getRandomColourRGB(void)
{
return this->getRandomColour().rgb;
}
void cGLColourHelper::ShuffleRandomColours(void)
{
std::random_shuffle( this->m_vecRandomColourEnumLookup.begin(), this->m_vecRandomColourEnumLookup.begin() );
return;
}
glm::vec3 cGLColourHelper::getColourRGB( cGLColourHelper::enumColours colourEnum )
{
cColour theColour = this->getColour( colourEnum );
return theColour.rgb;
}
glm::vec3 cGLColourHelper::getColourRGB( std::string colourName )
{
cGLColourHelper::cColour returnColour = this->getColour( colourName );
return returnColour.rgb;
}
cGLColourHelper::cColour cGLColourHelper::getColour( std::string colourName )
{
cGLColourHelper::enumColours colourEnum = this->getColourEnumFromName( colourName );
if ( colourEnum == cGLColourHelper::UNKNOWN )
{ // Didn't find it
return this->m_getUnknownColour();
}
// Look up the colour
cGLColourHelper::cColour returnColour = this->getColour( colourEnum );
return returnColour;
}
cGLColourHelper::cColour cGLColourHelper::getColour( cGLColourHelper::enumColours colourEnum )
{
//
std::map< cGLColourHelper::enumColours, cGLColourHelper::cColour >::iterator itColour = m_mapColours.find( colourEnum );
if ( itColour == this->m_mapColours.end() )
{ // Didn't find a match (should "never" happen as it's an enum... but you could pass an int, I suppose
return this->m_getUnknownColour();
}
// Found it
return itColour->second;
}
cGLColourHelper::cColour cGLColourHelper::m_getUnknownColour(void)
{
cGLColourHelper::cColour unknownColour = cGLColourHelper::cColour();
unknownColour.enumName = UNKNOWN;
unknownColour.name = "Unknown";
unknownColour.rgb = glm::vec3( 0.0f, 0.0f, 0.0f );
return unknownColour;
}
std::string cGLColourHelper::getColourNameFromEnum( cGLColourHelper::enumColours colourEnum )
{
cGLColourHelper::cColour returnColour = this->getColour( colourEnum );
return returnColour.name;
}
cGLColourHelper::enumColours cGLColourHelper::getColourEnumFromName( std::string sColour )
{
std::map< std::string, cGLColourHelper::enumColours >::iterator itColour = this->m_mapColourNameToEnum.find( sColour );
if ( itColour == this->m_mapColourNameToEnum.end() )
{ // Didn't find it
return cGLColourHelper::UNKNOWN;
}
return itColour->second;
}
| [
"niral.eagle100@gmail.com"
] | niral.eagle100@gmail.com |
9e83226a7107d5e67e9129a522871df559e438b1 | ff4055860f0adf927a9401e4019b771d0dfc2d02 | /animaMCMEstimation/animaMCMEstimationPlugin.cpp | 32c2d5bde3d5896e3810a34ecd53daf74883956e | [] | no_license | medInria/medInria-visages | 2b02695f673542a460791ed99f9f93200e3c1bad | a80e69d846c59eb667ad3def8fe42e34104b3503 | refs/heads/master | 2023-01-18T19:13:38.521506 | 2020-11-27T10:01:17 | 2020-11-27T10:01:17 | 9,451,653 | 0 | 2 | null | 2020-11-27T10:01:19 | 2013-04-15T15:20:44 | C++ | UTF-8 | C++ | false | false | 833 | cpp | #include <animaMCMEstimationPlugin.h>
#include <medCore.h>
#include <medWidgets.h>
#include <animaMCMEstimationProcess.h>
#include <animaMCMEstimationProcessPresenter.h>
void animaMCMEstimationPlugin::initialize(void)
{
medCore::diffusionModelEstimation::pluginFactory().record(animaMCMEstimationProcess::staticMetaObject.className(),
animaMCMEstimationProcessCreator);
medWidgets::diffusionModelEstimation::presenterFactory().record(animaMCMEstimationProcess::staticMetaObject.className(),
animaMCMEstimationProcessPresenterCreator);
}
void animaMCMEstimationPlugin::uninitialize(void)
{
}
DTK_DEFINE_PLUGIN(animaMCMEstimationProcess)
DTK_DEFINE_PLUGIN(animaMCMEstimationProcessPresenter)
| [
"olivier.commowick@inria.fr"
] | olivier.commowick@inria.fr |
18658de618a466dd243c8f9b9f42e41971a7f707 | f379e7d99b72f44a71d76066fdf68406ae9187c0 | /GameClient/character.h | 7056376f1c34550475673dba4591aa933e21dcc7 | [] | no_license | Weaver-JS/Redes_UDP_Taller_6 | 09fc962da6204e7ba423b0b3b97fb86c67a05280 | 1660f33cf2a8a30d6f4cc27fe89648aa9aa41018 | refs/heads/master | 2021-01-19T09:10:47.282164 | 2017-04-09T20:11:05 | 2017-04-09T20:11:05 | 87,736,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | h | #include "SFML\System.hpp"
#include "SFML\Graphics.hpp"
#define RADIUS 60
class character
{
private:
sf::Vector2<int16_t> position;
sf::Texture circle_texture;
sf::CircleShape* circle_shape;
//character();
public:
character(int16_t x, int16_t y);
character(sf::Vector2<int16_t> pos);
~character();
sf::Vector2<int16_t> & getPosition();
void setPosition(sf::Vector2<int16_t> & v);
sf::CircleShape* getCircleshape();
}; | [
"josesweaver@gmail.com"
] | josesweaver@gmail.com |
5535ef017b5009e4c3b9832878265c24668c4be2 | f95975d9454984803586de7f0600f3ecf9918f60 | /include/algorithms/pca/pca_batch.h | 42d322025b37407989cd7393bd58b654c960a42b | [
"Intel",
"Apache-2.0"
] | permissive | jjuribe/daal | f4e05656ca5f01e56debdbd2de51eeb2f506ca3d | 242d358db584dd4c9c65826b345fe63313ff8f2a | refs/heads/master | 2020-09-15T01:33:34.752543 | 2019-11-21T08:27:26 | 2019-11-21T08:27:26 | 223,316,648 | 0 | 0 | Apache-2.0 | 2019-11-22T03:33:41 | 2019-11-22T03:33:39 | null | UTF-8 | C++ | false | false | 6,600 | h | /* file: pca_batch.h */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of the interface for the PCA algorithm in the batch processing mode
//--
*/
#ifndef __PCA_BATCH_H__
#define __PCA_BATCH_H__
#include "algorithms/algorithm.h"
#include "data_management/data/numeric_table.h"
#include "services/daal_defines.h"
#include "services/daal_memory.h"
#include "algorithms/pca/pca_types.h"
namespace daal
{
namespace algorithms
{
namespace pca
{
namespace interface3
{
/**
* \brief Contains version 3.0 of Intel(R) Data Analytics Acceleration Library (Intel(R) DAAL) interface.
*/
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCHCONTAINER"></a>
* \brief Class containing methods to compute the results of the PCA algorithm */
template<typename algorithmFPType, Method method, CpuType cpu>
class BatchContainer : public AnalysisContainerIface<batch>
{};
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCHCONTAINER_ALGORITHMFPTYPE_CORRELATIONDENSE_CPU"></a>
* \brief Class containing methods to compute the results of the PCA algorithm */
template<typename algorithmFPType, CpuType cpu>
class BatchContainer<algorithmFPType, correlationDense, cpu> : public AnalysisContainerIface<batch>
{
public:
/**
* Constructs a container for the PCA algorithm with a specified environment
* in the batch processing mode
* \param[in] daalEnv Environment object
*/
BatchContainer(daal::services::Environment::env *daalEnv);
/** Default destructor */
~BatchContainer();
/**
* Computes the result of the PCA algorithm in the batch processing mode
*/
services::Status compute() DAAL_C11_OVERRIDE;
};
/**
* @defgroup pca_batch Batch
* @ingroup pca
* @{
*/
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCHCONTAINER_ALGORITHMFPTYPE_SVDDENSE_CPU"></a>
* \brief Class containing methods to compute the results of the PCA algorithm */
template<typename algorithmFPType, CpuType cpu>
class BatchContainer<algorithmFPType, svdDense, cpu> : public AnalysisContainerIface<batch>
{
public:
/**
* Constructs a container for the PCA algorithm with a specified environment
* in the batch processing mode
* \param[in] daalEnv Environment object
*/
BatchContainer(daal::services::Environment::env *daalEnv);
/** Default destructor */
~BatchContainer();
/**
* Computes the result of the PCA algorithm in the batch processing mode
*/
services::Status compute() DAAL_C11_OVERRIDE;
};
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCH"></a>
* \brief Computes the results of the PCA algorithm
* <!-- \n<a href="DAAL-REF-PCA-ALGORITHM">PCA algorithm description and usage models</a> -->
*
* \tparam algorithmFPType Data type to use in intermediate computations for PCA, double or float
* \tparam method PCA computation method, \ref Method
*
* \par Enumerations
* - \ref Method Computation methods for the algorithm
*/
template<typename algorithmFPType = DAAL_ALGORITHM_FP_TYPE, Method method = correlationDense>
class DAAL_EXPORT Batch : public Analysis<batch>
{
public:
typedef algorithms::pca::Input InputType;
typedef algorithms::pca::BatchParameter<algorithmFPType, method> ParameterType;
typedef algorithms::pca::Result ResultType;
/** Default constructor */
Batch()
{
initialize();
}
/**
* Constructs a PCA algorithm by copying input objects and parameters of another PCA algorithm
* \param[in] other An algorithm to be used as the source to initialize the input objects
* and parameters of the algorithm
*/
Batch(const Batch<algorithmFPType, method> &other) : input(other.input), parameter(other.parameter)
{
initialize();
}
~Batch() {}
/**
* Returns method of the algorithm
* \return Method of the algorithm
*/
virtual int getMethod() const DAAL_C11_OVERRIDE { return method; };
/**
* Registers user-allocated memory to store the results of the PCA algorithm
* \param[in] res Structure for storing the results of the PCA algorithm
*/
services::Status setResult(const ResultPtr& res)
{
DAAL_CHECK(res, services::ErrorNullResult)
_result = res;
_res = _result.get();
return services::Status();
}
/**
* Returns the structure that contains final results of the PCA algorithm
* \return Structure that contains final results of the PCA
*/
ResultPtr getResult() { return _result; }
/**
* Returns a pointer to the newly allocated PCA algorithm
* with a copy of input objects and parameters of this PCA algorithm
* \return Pointer to the newly allocated algorithm
*/
services::SharedPtr<Batch<algorithmFPType, method> > clone() const
{
return services::SharedPtr<Batch<algorithmFPType, method> >(cloneImpl());
}
InputType input; /*!< Input data structure */
BatchParameter<algorithmFPType, method> parameter; /*!< Parameters */
protected:
ResultPtr _result;
virtual Batch<algorithmFPType, method> * cloneImpl() const DAAL_C11_OVERRIDE
{
return new Batch<algorithmFPType, method>(*this);
}
services::Status allocateResult() DAAL_C11_OVERRIDE
{
services::Status s = _result->allocate<algorithmFPType>(&input, ¶meter, method);
_res = _result.get();
return s;
}
void initialize()
{
_ac = new __DAAL_ALGORITHM_CONTAINER(batch, BatchContainer, algorithmFPType, method)(&_env);
_in = &input;
_par = ¶meter;
_result.reset(new ResultType());
}
};
/** @} */
} // namespace interface3
using interface3::BatchContainer;
using interface3::Batch;
} // namespace pca
} // namespace algorithms
} // namespace daal
#endif
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
576ff1b74182d3aa4db3122acf1197fe05607512 | 67a53e3ba09a6b8f83fc1d40b85b5941310702bd | /src/lib/collision_prevention/CollisionPreventionTest.cpp | 0e4940f16e9809f6e3dcac27bf7d11286981be80 | [
"BSD-3-Clause"
] | permissive | Diksha-agg/Firmware_val | f3bd60c7356b2f21b8c8ea4db98955f41d43e848 | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | refs/heads/main | 2023-07-13T11:12:47.831945 | 2021-08-26T02:06:15 | 2021-08-26T02:06:15 | 397,618,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | version https://git-lfs.github.com/spec/v1
oid sha256:f6a2c2503ff0077fd1e33be104473da29d3bd41fe5a428edbbcac3dafd2e99eb
size 44642
| [
"diksha.dtu@gmail.com"
] | diksha.dtu@gmail.com |
85bc6e3e72cad629b2cdcc65e17293a9f5072cf3 | 320660851dc9a8c7a230db6d5388ba0d737572f6 | /win32/include/pthread.h | 0172cb1a3083722319c6b64845fabe30e96629ed | [] | no_license | Vadiza/sage-3.5b | 0e9fb033324c4efd86aa0801c8ab2bd8d3a62ff9 | 5e2af1d1a9838933fe0e60673d74a54408fdb61e | refs/heads/master | 2020-04-09T15:16:17.571400 | 2014-05-09T15:27:17 | 2014-05-09T15:27:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,226 | h | /* This is an implementation of the threads API of POSIX 1003.1-2001.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined( PTHREAD_H )
#define PTHREAD_H
/*
* See the README file for an explanation of the pthreads-win32 version
* numbering scheme and how the DLL is named etc.
*/
#define PTW32_VERSION 2,7,0,0
#define PTW32_VERSION_STRING "2, 7, 0, 0\0"
/* There are three implementations of cancel cleanup.
* Note that pthread.h is included in both application
* compilation units and also internally for the library.
* The code here and within the library aims to work
* for all reasonable combinations of environments.
*
* The three implementations are:
*
* WIN32 SEH
* C
* C++
*
* Please note that exiting a push/pop block via
* "return", "exit", "break", or "continue" will
* lead to different behaviour amongst applications
* depending upon whether the library was built
* using SEH, C++, or C. For example, a library built
* with SEH will call the cleanup routine, while both
* C++ and C built versions will not.
*/
/*
* Define defaults for cleanup code.
* Note: Unless the build explicitly defines one of the following, then
* we default to standard C style cleanup. This style uses setjmp/longjmp
* in the cancelation and thread exit implementations and therefore won't
* do stack unwinding if linked to applications that have it (e.g.
* C++ apps). This is currently consistent with most/all commercial Unix
* POSIX threads implementations.
*/
#if !defined( __CLEANUP_SEH ) && !defined( __CLEANUP_CXX ) && !defined( __CLEANUP_C )
# define __CLEANUP_C
#endif
#if defined( __CLEANUP_SEH ) && ( !defined( _MSC_VER ) && !defined(PTW32_RC_MSC))
#error ERROR [__FILE__, line __LINE__]: SEH is not supported for this compiler.
#endif
/*
* Stop here if we are being included by the resource compiler.
*/
#ifndef RC_INVOKED
#undef PTW32_LEVEL
#if defined(_POSIX_SOURCE)
#define PTW32_LEVEL 0
/* Early POSIX */
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_LEVEL
#define PTW32_LEVEL 1
/* Include 1b, 1c and 1d */
#endif
#if defined(INCLUDE_NP)
#undef PTW32_LEVEL
#define PTW32_LEVEL 2
/* Include Non-Portable extensions */
#endif
#define PTW32_LEVEL_MAX 3
#if !defined(PTW32_LEVEL)
#define PTW32_LEVEL PTW32_LEVEL_MAX
/* Include everything */
#endif
#ifdef _UWIN
# define HAVE_STRUCT_TIMESPEC 1
# define HAVE_SIGNAL_H 1
# undef HAVE_CONFIG_H
# pragma comment(lib, "pthread")
#endif
/*
* -------------------------------------------------------------
*
*
* Module: pthread.h
*
* Purpose:
* Provides an implementation of PThreads based upon the
* standard:
*
* POSIX 1003.1-2001
* and
* The Single Unix Specification version 3
*
* (these two are equivalent)
*
* in order to enhance code portability between Windows,
* various commercial Unix implementations, and Linux.
*
* See the ANNOUNCE file for a full list of conforming
* routines and defined constants, and a list of missing
* routines and constants not defined in this implementation.
*
* Authors:
* There have been many contributors to this library.
* The initial implementation was contributed by
* John Bossom, and several others have provided major
* sections or revisions of parts of the implementation.
* Often significant effort has been contributed to
* find and fix important bugs and other problems to
* improve the reliability of the library, which sometimes
* is not reflected in the amount of code which changed as
* result.
* As much as possible, the contributors are acknowledged
* in the ChangeLog file in the source code distribution
* where their changes are noted in detail.
*
* Contributors are listed in the CONTRIBUTORS file.
*
* As usual, all bouquets go to the contributors, and all
* brickbats go to the project maintainer.
*
* Maintainer:
* The code base for this project is coordinated and
* eventually pre-tested, packaged, and made available by
*
* Ross Johnson <rpj@callisto.canberra.edu.au>
*
* QA Testers:
* Ultimately, the library is tested in the real world by
* a host of competent and demanding scientists and
* engineers who report bugs and/or provide solutions
* which are then fixed or incorporated into subsequent
* versions of the library. Each time a bug is fixed, a
* test case is written to prove the fix and ensure
* that later changes to the code don't reintroduce the
* same error. The number of test cases is slowly growing
* and therefore so is the code reliability.
*
* Compliance:
* See the file ANNOUNCE for the list of implemented
* and not-implemented routines and defined options.
* Of course, these are all defined is this file as well.
*
* Web site:
* The source code and other information about this library
* are available from
*
* http://sources.redhat.com/pthreads-win32/
*
* -------------------------------------------------------------
*/
/* Try to avoid including windows.h */
#if defined(__MINGW32__) && defined(__cplusplus)
#define PTW32_INCLUDE_WINDOWS_H
#endif
#ifdef PTW32_INCLUDE_WINDOWS_H
#include <windows.h>
#endif
#if defined(_MSC_VER) && _MSC_VER < 1300 || defined(__DMC__)
/*
* VC++6.0 or early compiler's header has no DWORD_PTR type.
*/
typedef unsigned long DWORD_PTR;
#endif
/*
* -----------------
* autoconf switches
* -----------------
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifndef NEED_FTIME
#include <time.h>
#else /* NEED_FTIME */
/* use native WIN32 time API */
#endif /* NEED_FTIME */
#if HAVE_SIGNAL_H
#include <signal.h>
#endif /* HAVE_SIGNAL_H */
#include <setjmp.h>
#include <limits.h>
/*
* Boolean values to make us independent of system includes.
*/
enum {
PTW32_FALSE = 0,
PTW32_TRUE = (! PTW32_FALSE)
};
/*
* This is a duplicate of what is in the autoconf config.h,
* which is only used when building the pthread-win32 libraries.
*/
#ifndef PTW32_CONFIG_H
# if defined(WINCE)
# define NEED_ERRNO
# define NEED_SEM
# endif
# if defined(_UWIN) || defined(__MINGW32__)
# define HAVE_MODE_T
# endif
#endif
/*
*
*/
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
#ifdef NEED_ERRNO
#include "need_errno.h"
#else
#include <errno.h>
#endif
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Several systems don't define some error numbers.
*/
#ifndef ENOTSUP
# define ENOTSUP 48 /* This is the value in Solaris. */
#endif
#ifndef ETIMEDOUT
# define ETIMEDOUT 10060 /* This is the value in winsock.h. */
#endif
#ifndef ENOSYS
# define ENOSYS 140 /* Semi-arbitrary value */
#endif
#ifndef EDEADLK
# ifdef EDEADLOCK
# define EDEADLK EDEADLOCK
# else
# define EDEADLK 36 /* This is the value in MSVC. */
# endif
#endif
#include <sched.h>
/*
* To avoid including windows.h we define only those things that we
* actually need from it.
*/
#ifndef PTW32_INCLUDE_WINDOWS_H
#ifndef HANDLE
# define PTW32__HANDLE_DEF
# define HANDLE void *
#endif
#ifndef DWORD
# define PTW32__DWORD_DEF
# define DWORD unsigned long
#endif
#endif
#ifndef HAVE_STRUCT_TIMESPEC
#define HAVE_STRUCT_TIMESPEC 1
struct timespec {
long tv_sec;
long tv_nsec;
};
#endif /* HAVE_STRUCT_TIMESPEC */
#ifndef SIG_BLOCK
#define SIG_BLOCK 0
#endif /* SIG_BLOCK */
#ifndef SIG_UNBLOCK
#define SIG_UNBLOCK 1
#endif /* SIG_UNBLOCK */
#ifndef SIG_SETMASK
#define SIG_SETMASK 2
#endif /* SIG_SETMASK */
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* -------------------------------------------------------------
*
* POSIX 1003.1-2001 Options
* =========================
*
* Options are normally set in <unistd.h>, which is not provided
* with pthreads-win32.
*
* For conformance with the Single Unix Specification (version 3), all of the
* options below are defined, and have a value of either -1 (not supported)
* or 200112L (supported).
*
* These options can neither be left undefined nor have a value of 0, because
* either indicates that sysconf(), which is not implemented, may be used at
* runtime to check the status of the option.
*
* _POSIX_THREADS (== 200112L)
* If == 200112L, you can use threads
*
* _POSIX_THREAD_ATTR_STACKSIZE (== 200112L)
* If == 200112L, you can control the size of a thread's
* stack
* pthread_attr_getstacksize
* pthread_attr_setstacksize
*
* _POSIX_THREAD_ATTR_STACKADDR (== -1)
* If == 200112L, you can allocate and control a thread's
* stack. If not supported, the following functions
* will return ENOSYS, indicating they are not
* supported:
* pthread_attr_getstackaddr
* pthread_attr_setstackaddr
*
* _POSIX_THREAD_PRIORITY_SCHEDULING (== -1)
* If == 200112L, you can use realtime scheduling.
* This option indicates that the behaviour of some
* implemented functions conforms to the additional TPS
* requirements in the standard. E.g. rwlocks favour
* writers over readers when threads have equal priority.
*
* _POSIX_THREAD_PRIO_INHERIT (== -1)
* If == 200112L, you can create priority inheritance
* mutexes.
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PRIO_PROTECT (== -1)
* If == 200112L, you can create priority ceiling mutexes
* Indicates the availability of:
* pthread_mutex_getprioceiling
* pthread_mutex_setprioceiling
* pthread_mutexattr_getprioceiling
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprioceiling
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PROCESS_SHARED (== -1)
* If set, you can create mutexes and condition
* variables that can be shared with another
* process.If set, indicates the availability
* of:
* pthread_mutexattr_getpshared
* pthread_mutexattr_setpshared
* pthread_condattr_getpshared
* pthread_condattr_setpshared
*
* _POSIX_THREAD_SAFE_FUNCTIONS (== 200112L)
* If == 200112L you can use the special *_r library
* functions that provide thread-safe behaviour
*
* _POSIX_READER_WRITER_LOCKS (== 200112L)
* If == 200112L, you can use read/write locks
*
* _POSIX_SPIN_LOCKS (== 200112L)
* If == 200112L, you can use spin locks
*
* _POSIX_BARRIERS (== 200112L)
* If == 200112L, you can use barriers
*
* + These functions provide both 'inherit' and/or
* 'protect' protocol, based upon these macro
* settings.
*
* -------------------------------------------------------------
*/
/*
* POSIX Options
*/
#undef _POSIX_THREADS
#define _POSIX_THREADS 200112L
#undef _POSIX_READER_WRITER_LOCKS
#define _POSIX_READER_WRITER_LOCKS 200112L
#undef _POSIX_SPIN_LOCKS
#define _POSIX_SPIN_LOCKS 200112L
#undef _POSIX_BARRIERS
#define _POSIX_BARRIERS 200112L
#undef _POSIX_THREAD_SAFE_FUNCTIONS
#define _POSIX_THREAD_SAFE_FUNCTIONS 200112L
#undef _POSIX_THREAD_ATTR_STACKSIZE
#define _POSIX_THREAD_ATTR_STACKSIZE 200112L
/*
* The following options are not supported
*/
#undef _POSIX_THREAD_ATTR_STACKADDR
#define _POSIX_THREAD_ATTR_STACKADDR -1
#undef _POSIX_THREAD_PRIO_INHERIT
#define _POSIX_THREAD_PRIO_INHERIT -1
#undef _POSIX_THREAD_PRIO_PROTECT
#define _POSIX_THREAD_PRIO_PROTECT -1
/* TPS is not fully supported. */
#undef _POSIX_THREAD_PRIORITY_SCHEDULING
#define _POSIX_THREAD_PRIORITY_SCHEDULING -1
#undef _POSIX_THREAD_PROCESS_SHARED
#define _POSIX_THREAD_PROCESS_SHARED -1
/*
* POSIX 1003.1-2001 Limits
* ===========================
*
* These limits are normally set in <limits.h>, which is not provided with
* pthreads-win32.
*
* PTHREAD_DESTRUCTOR_ITERATIONS
* Maximum number of attempts to destroy
* a thread's thread-specific data on
* termination (must be at least 4)
*
* PTHREAD_KEYS_MAX
* Maximum number of thread-specific data keys
* available per process (must be at least 128)
*
* PTHREAD_STACK_MIN
* Minimum supported stack size for a thread
*
* PTHREAD_THREADS_MAX
* Maximum number of threads supported per
* process (must be at least 64).
*
* SEM_NSEMS_MAX
* The maximum number of semaphores a process can have.
* (must be at least 256)
*
* SEM_VALUE_MAX
* The maximum value a semaphore can have.
* (must be at least 32767)
*
*/
#undef _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4
#undef PTHREAD_DESTRUCTOR_ITERATIONS
#define PTHREAD_DESTRUCTOR_ITERATIONS _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#undef _POSIX_THREAD_KEYS_MAX
#define _POSIX_THREAD_KEYS_MAX 128
#undef PTHREAD_KEYS_MAX
#define PTHREAD_KEYS_MAX _POSIX_THREAD_KEYS_MAX
#undef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 0
#undef _POSIX_THREAD_THREADS_MAX
#define _POSIX_THREAD_THREADS_MAX 64
/* Arbitrary value */
#undef PTHREAD_THREADS_MAX
#define PTHREAD_THREADS_MAX 2019
#undef _POSIX_SEM_NSEMS_MAX
#define _POSIX_SEM_NSEMS_MAX 256
/* Arbitrary value */
#undef SEM_NSEMS_MAX
#define SEM_NSEMS_MAX 1024
#undef _POSIX_SEM_VALUE_MAX
#define _POSIX_SEM_VALUE_MAX 32767
#undef SEM_VALUE_MAX
#define SEM_VALUE_MAX INT_MAX
#if __GNUC__ && ! defined (__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif
/*
* When building the DLL code, you should define PTW32_BUILD so that
* the variables/functions are exported correctly. When using the DLL,
* do NOT define PTW32_BUILD, and then the variables/functions will
* be imported correctly.
*/
#ifndef PTW32_STATIC_LIB
# ifdef PTW32_BUILD
# define PTW32_DLLPORT __declspec (dllexport)
# else
# define PTW32_DLLPORT __declspec (dllimport)
# endif
#else
# define PTW32_DLLPORT
#endif
/*
* The Open Watcom C/C++ compiler uses a non-standard calling convention
* that passes function args in registers unless __cdecl is explicitly specified
* in exposed function prototypes.
*
* We force all calls to cdecl even though this could slow Watcom code down
* slightly. If you know that the Watcom compiler will be used to build both
* the DLL and application, then you can probably define this as a null string.
* Remember that pthread.h (this file) is used for both the DLL and application builds.
*/
#define PTW32_CDECL __cdecl
#if defined(_UWIN) && PTW32_LEVEL >= PTW32_LEVEL_MAX
# include <sys/types.h>
#else
/*
* Generic handle type - intended to extend uniqueness beyond
* that available with a simple pointer. It should scale for either
* IA-32 or IA-64.
*/
typedef struct {
void * p; /* Pointer to actual object */
unsigned int x; /* Extra information - reuse count etc */
} ptw32_handle_t;
typedef ptw32_handle_t pthread_t;
typedef struct pthread_attr_t_ * pthread_attr_t;
typedef struct pthread_once_t_ pthread_once_t;
typedef struct pthread_key_t_ * pthread_key_t;
typedef struct pthread_mutex_t_ * pthread_mutex_t;
typedef struct pthread_mutexattr_t_ * pthread_mutexattr_t;
typedef struct pthread_cond_t_ * pthread_cond_t;
typedef struct pthread_condattr_t_ * pthread_condattr_t;
#endif
typedef struct pthread_rwlock_t_ * pthread_rwlock_t;
typedef struct pthread_rwlockattr_t_ * pthread_rwlockattr_t;
typedef struct pthread_spinlock_t_ * pthread_spinlock_t;
typedef struct pthread_barrier_t_ * pthread_barrier_t;
typedef struct pthread_barrierattr_t_ * pthread_barrierattr_t;
/*
* ====================
* ====================
* POSIX Threads
* ====================
* ====================
*/
enum {
/*
* pthread_attr_{get,set}detachstate
*/
PTHREAD_CREATE_JOINABLE = 0, /* Default */
PTHREAD_CREATE_DETACHED = 1,
/*
* pthread_attr_{get,set}inheritsched
*/
PTHREAD_INHERIT_SCHED = 0,
PTHREAD_EXPLICIT_SCHED = 1, /* Default */
/*
* pthread_{get,set}scope
*/
PTHREAD_SCOPE_PROCESS = 0,
PTHREAD_SCOPE_SYSTEM = 1, /* Default */
/*
* pthread_setcancelstate paramters
*/
PTHREAD_CANCEL_ENABLE = 0, /* Default */
PTHREAD_CANCEL_DISABLE = 1,
/*
* pthread_setcanceltype parameters
*/
PTHREAD_CANCEL_ASYNCHRONOUS = 0,
PTHREAD_CANCEL_DEFERRED = 1, /* Default */
/*
* pthread_mutexattr_{get,set}pshared
* pthread_condattr_{get,set}pshared
*/
PTHREAD_PROCESS_PRIVATE = 0,
PTHREAD_PROCESS_SHARED = 1,
/*
* pthread_barrier_wait
*/
PTHREAD_BARRIER_SERIAL_THREAD = -1
};
/*
* ====================
* ====================
* Cancelation
* ====================
* ====================
*/
#define PTHREAD_CANCELED ((void *) -1)
/*
* ====================
* ====================
* Once Key
* ====================
* ====================
*/
#define PTHREAD_ONCE_INIT { PTW32_FALSE, 0, 0, 0}
struct pthread_once_t_
{
int done; /* indicates if user function has been executed */
void * lock;
int reserved1;
int reserved2;
};
/*
* ====================
* ====================
* Object initialisers
* ====================
* ====================
*/
#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t) -1)
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER ((pthread_mutex_t) -2)
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER ((pthread_mutex_t) -3)
/*
* Compatibility with LinuxThreads
*/
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP PTHREAD_RECURSIVE_MUTEX_INITIALIZER
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP PTHREAD_ERRORCHECK_MUTEX_INITIALIZER
#define PTHREAD_COND_INITIALIZER ((pthread_cond_t) -1)
#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t) -1)
#define PTHREAD_SPINLOCK_INITIALIZER ((pthread_spinlock_t) -1)
/*
* Mutex types.
*/
enum
{
/* Compatibility with LinuxThreads */
PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_TIMED_NP = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_ADAPTIVE_NP = PTHREAD_MUTEX_FAST_NP,
/* For compatibility with POSIX */
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
};
typedef struct ptw32_cleanup_t ptw32_cleanup_t;
#if defined(_MSC_VER)
/* Disable MSVC 'anachronism used' warning */
#pragma warning( disable : 4229 )
#endif
typedef void (* PTW32_CDECL ptw32_cleanup_callback_t)(void *);
#if defined(_MSC_VER)
#pragma warning( default : 4229 )
#endif
struct ptw32_cleanup_t
{
ptw32_cleanup_callback_t routine;
void *arg;
struct ptw32_cleanup_t *prev;
};
#ifdef __CLEANUP_SEH
/*
* WIN32 SEH version of cancel cleanup.
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
_cleanup.routine = (ptw32_cleanup_callback_t)(_rout); \
_cleanup.arg = (_arg); \
__try \
{ \
#define pthread_cleanup_pop( _execute ) \
} \
__finally \
{ \
if( _execute || AbnormalTermination()) \
{ \
(*(_cleanup.routine))( _cleanup.arg ); \
} \
} \
}
#else /* __CLEANUP_SEH */
#ifdef __CLEANUP_C
/*
* C implementation of PThreads cancel cleanup
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
ptw32_push_cleanup( &_cleanup, (ptw32_cleanup_callback_t) (_rout), (_arg) ); \
#define pthread_cleanup_pop( _execute ) \
(void) ptw32_pop_cleanup( _execute ); \
}
#else /* __CLEANUP_C */
#ifdef __CLEANUP_CXX
/*
* C++ version of cancel cleanup.
* - John E. Bossom.
*/
class PThreadCleanup {
/*
* PThreadCleanup
*
* Purpose
* This class is a C++ helper class that is
* used to implement pthread_cleanup_push/
* pthread_cleanup_pop.
* The destructor of this class automatically
* pops the pushed cleanup routine regardless
* of how the code exits the scope
* (i.e. such as by an exception)
*/
ptw32_cleanup_callback_t cleanUpRout;
void * obj;
int executeIt;
public:
PThreadCleanup() :
cleanUpRout( 0 ),
obj( 0 ),
executeIt( 0 )
/*
* No cleanup performed
*/
{
}
PThreadCleanup(
ptw32_cleanup_callback_t routine,
void * arg ) :
cleanUpRout( routine ),
obj( arg ),
executeIt( 1 )
/*
* Registers a cleanup routine for 'arg'
*/
{
}
~PThreadCleanup()
{
if ( executeIt && ((void *) cleanUpRout != (void *) 0) )
{
(void) (*cleanUpRout)( obj );
}
}
void execute( int exec )
{
executeIt = exec;
}
};
/*
* C++ implementation of PThreads cancel cleanup;
* This implementation takes advantage of a helper
* class who's destructor automatically calls the
* cleanup routine if we exit our scope weirdly
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
PThreadCleanup cleanup((ptw32_cleanup_callback_t)(_rout), \
(void *) (_arg) );
#define pthread_cleanup_pop( _execute ) \
cleanup.execute( _execute ); \
}
#else
#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined.
#endif /* __CLEANUP_CXX */
#endif /* __CLEANUP_C */
#endif /* __CLEANUP_SEH */
/*
* ===============
* ===============
* Methods
* ===============
* ===============
*/
/*
* PThread Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_attr_init (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_destroy (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getdetachstate (const pthread_attr_t * attr,
int *detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstackaddr (const pthread_attr_t * attr,
void **stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstacksize (const pthread_attr_t * attr,
size_t * stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setdetachstate (pthread_attr_t * attr,
int detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstackaddr (pthread_attr_t * attr,
void *stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstacksize (pthread_attr_t * attr,
size_t stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedparam (const pthread_attr_t *attr,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedparam (pthread_attr_t *attr,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedpolicy (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedpolicy (pthread_attr_t *,
int *);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setinheritsched(pthread_attr_t * attr,
int inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getinheritsched(pthread_attr_t * attr,
int * inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setscope (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getscope (const pthread_attr_t *,
int *);
/*
* PThread Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid,
const pthread_attr_t * attr,
void *(*start) (void *),
void *arg);
PTW32_DLLPORT int PTW32_CDECL pthread_detach (pthread_t tid);
PTW32_DLLPORT int PTW32_CDECL pthread_equal (pthread_t t1,
pthread_t t2);
PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr);
PTW32_DLLPORT int PTW32_CDECL pthread_join (pthread_t thread,
void **value_ptr);
PTW32_DLLPORT pthread_t PTW32_CDECL pthread_self (void);
PTW32_DLLPORT int PTW32_CDECL pthread_cancel (pthread_t thread);
PTW32_DLLPORT int PTW32_CDECL pthread_setcancelstate (int state,
int *oldstate);
PTW32_DLLPORT int PTW32_CDECL pthread_setcanceltype (int type,
int *oldtype);
PTW32_DLLPORT void PTW32_CDECL pthread_testcancel (void);
PTW32_DLLPORT int PTW32_CDECL pthread_once (pthread_once_t * once_control,
void (*init_routine) (void));
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
PTW32_DLLPORT ptw32_cleanup_t * PTW32_CDECL ptw32_pop_cleanup (int execute);
PTW32_DLLPORT void PTW32_CDECL ptw32_push_cleanup (ptw32_cleanup_t * cleanup,
void (*routine) (void *),
void *arg);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread Specific Data Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_key_create (pthread_key_t * key,
void (*destructor) (void *));
PTW32_DLLPORT int PTW32_CDECL pthread_key_delete (pthread_key_t key);
PTW32_DLLPORT int PTW32_CDECL pthread_setspecific (pthread_key_t key,
const void *value);
PTW32_DLLPORT void * PTW32_CDECL pthread_getspecific (pthread_key_t key);
/*
* Mutex Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_init (pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_destroy (pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getpshared (const pthread_mutexattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setpshared (pthread_mutexattr_t * attr,
int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_settype (pthread_mutexattr_t * attr, int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_gettype (pthread_mutexattr_t * attr, int *kind);
/*
* Barrier Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_init (pthread_barrierattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_destroy (pthread_barrierattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_getpshared (const pthread_barrierattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_setpshared (pthread_barrierattr_t * attr,
int pshared);
/*
* Mutex Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_init (pthread_mutex_t * mutex,
const pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_destroy (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_lock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_timedlock(pthread_mutex_t *mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_trylock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_unlock (pthread_mutex_t * mutex);
/*
* Spinlock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_spin_init (pthread_spinlock_t * lock, int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_destroy (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_lock (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_trylock (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_unlock (pthread_spinlock_t * lock);
/*
* Barrier Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_init (pthread_barrier_t * barrier,
const pthread_barrierattr_t * attr,
unsigned int count);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_destroy (pthread_barrier_t * barrier);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_wait (pthread_barrier_t * barrier);
/*
* Condition Variable Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_init (pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_destroy (pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_getpshared (const pthread_condattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_setpshared (pthread_condattr_t * attr,
int pshared);
/*
* Condition Variable Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_cond_init (pthread_cond_t * cond,
const pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_destroy (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_wait (pthread_cond_t * cond,
pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_timedwait (pthread_cond_t * cond,
pthread_mutex_t * mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_signal (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_broadcast (pthread_cond_t * cond);
/*
* Scheduling
*/
PTW32_DLLPORT int PTW32_CDECL pthread_setschedparam (pthread_t thread,
int policy,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_getschedparam (pthread_t thread,
int *policy,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_setconcurrency (int);
PTW32_DLLPORT int PTW32_CDECL pthread_getconcurrency (void);
/*
* Read-Write Lock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock,
const pthread_rwlockattr_t *attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_tryrdlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_trywrlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedrdlock(pthread_rwlock_t *lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedwrlock(pthread_rwlock_t *lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_init (pthread_rwlockattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_destroy (pthread_rwlockattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_getpshared (const pthread_rwlockattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_setpshared (pthread_rwlockattr_t * attr,
int pshared);
#if PTW32_LEVEL >= PTW32_LEVEL_MAX - 1
/*
* Signal Functions. Should be defined in <signal.h> but MSVC and MinGW32
* already have signal.h that don't define these.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_kill(pthread_t thread, int sig);
/*
* Non-portable functions
*/
/*
* Compatibility with Linux.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr,
int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr,
int *kind);
/*
* Possibly supported by other POSIX threads implementations
*/
PTW32_DLLPORT int PTW32_CDECL pthread_delay_np (struct timespec * interval);
PTW32_DLLPORT int PTW32_CDECL pthread_num_processors_np(void);
/*
* Useful if an application wants to statically link
* the lib rather than load the DLL at run-time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_detach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_detach_np(void);
/*
* Features that are auto-detected at load/run time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_test_features_np(int);
enum ptw32_features {
PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE = 0x0001, /* System provides it. */
PTW32_ALERTABLE_ASYNC_CANCEL = 0x0002 /* Can cancel blocked threads. */
};
/*
* Register a system time change with the library.
* Causes the library to perform various functions
* in response to the change. Should be called whenever
* the application's top level window receives a
* WM_TIMECHANGE message. It can be passed directly to
* pthread_create() as a new thread if desired.
*/
PTW32_DLLPORT void * PTW32_CDECL pthread_timechange_handler_np(void *);
#endif /*PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 */
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
/*
* Returns the Win32 HANDLE for the POSIX thread.
*/
PTW32_DLLPORT HANDLE PTW32_CDECL pthread_getw32threadhandle_np(pthread_t thread);
/*
* Protected Methods
*
* This function blocks until the given WIN32 handle
* is signaled or pthread_cancel had been called.
* This function allows the caller to hook into the
* PThreads cancel mechanism. It is implemented using
*
* WaitForMultipleObjects
*
* on 'waitHandle' and a manually reset WIN32 Event
* used to implement pthread_cancel. The 'timeout'
* argument to TimedWait is simply passed to
* WaitForMultipleObjects.
*/
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableWait (HANDLE waitHandle);
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableTimedWait (HANDLE waitHandle,
DWORD timeout);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread-Safe C Runtime Library Mappings.
*/
#ifndef _UWIN
# if defined(NEED_ERRNO)
PTW32_DLLPORT int * PTW32_CDECL _errno( void );
# else
# ifndef errno
# if (defined(_MT) || defined(_DLL))
__declspec(dllimport) extern int * __cdecl _errno(void);
# define errno (*_errno())
# endif
# endif
# endif
#endif
/*
* WIN32 C runtime library had been made thread-safe
* without affecting the user interface. Provide
* mappings from the UNIX thread-safe versions to
* the standard C runtime library calls.
* Only provide function mappings for functions that
* actually exist on WIN32.
*/
#if !defined(__MINGW32__)
#define strtok_r( _s, _sep, _lasts ) \
( *(_lasts) = strtok( (_s), (_sep) ) )
#endif /* !__MINGW32__ */
#define asctime_r( _tm, _buf ) \
( strcpy( (_buf), asctime( (_tm) ) ), \
(_buf) )
#define ctime_r( _clock, _buf ) \
( strcpy( (_buf), ctime( (_clock) ) ), \
(_buf) )
#define gmtime_r( _clock, _result ) \
( *(_result) = *gmtime( (_clock) ), \
(_result) )
#define localtime_r( _clock, _result ) \
( *(_result) = *localtime( (_clock) ), \
(_result) )
#define rand_r( _seed ) \
( _seed == _seed? rand() : rand() )
/*
* Some compiler environments don't define some things.
*/
#if defined(__BORLANDC__)
# define _ftime ftime
# define _timeb timeb
#endif
#ifdef __cplusplus
/*
* Internal exceptions
*/
class ptw32_exception {};
class ptw32_exception_cancel : public ptw32_exception {};
class ptw32_exception_exit : public ptw32_exception {};
#endif
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
/* FIXME: This is only required if the library was built using SEH */
/*
* Get internal SEH tag
*/
PTW32_DLLPORT DWORD PTW32_CDECL ptw32_get_exception_services_code(void);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
#ifndef PTW32_BUILD
#ifdef __CLEANUP_SEH
/*
* Redefine the SEH __except keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#define __except( E ) \
__except( ( GetExceptionCode() == ptw32_get_exception_services_code() ) \
? EXCEPTION_CONTINUE_SEARCH : ( E ) )
#endif /* __CLEANUP_SEH */
#ifdef __CLEANUP_CXX
/*
* Redefine the C++ catch keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#ifdef _MSC_VER
/*
* WARNING: Replace any 'catch( ... )' with 'PtW32CatchAll'
* if you want Pthread-Win32 cancelation and pthread_exit to work.
*/
#ifndef PtW32NoCatchWarn
#pragma message("Specify \"/DPtW32NoCatchWarn\" compiler flag to skip this message.")
#pragma message("------------------------------------------------------------------")
#pragma message("When compiling applications with MSVC++ and C++ exception handling:")
#pragma message(" Replace any 'catch( ... )' in routines called from POSIX threads")
#pragma message(" with 'PtW32CatchAll' or 'CATCHALL' if you want POSIX thread")
#pragma message(" cancelation and pthread_exit to work. For example:")
#pragma message("")
#pragma message(" #ifdef PtW32CatchAll")
#pragma message(" PtW32CatchAll")
#pragma message(" #else")
#pragma message(" catch(...)")
#pragma message(" #endif")
#pragma message(" {")
#pragma message(" /* Catchall block processing */")
#pragma message(" }")
#pragma message("------------------------------------------------------------------")
#endif
#define PtW32CatchAll \
catch( ptw32_exception & ) { throw; } \
catch( ... )
#else /* _MSC_VER */
#define catch( E ) \
catch( ptw32_exception & ) { throw; } \
catch( E )
#endif /* _MSC_VER */
#endif /* __CLEANUP_CXX */
#endif /* ! PTW32_BUILD */
#ifdef __cplusplus
} /* End of extern "C" */
#endif /* __cplusplus */
#ifdef PTW32__HANDLE_DEF
# undef HANDLE
#endif
#ifdef PTW32__DWORD_DEF
# undef DWORD
#endif
#undef PTW32_LEVEL
#undef PTW32_LEVEL_MAX
#endif /* ! RC_INVOKED */
#endif /* PTHREAD_H */
| [
"matt@doeringtech.com"
] | matt@doeringtech.com |
adbe0a572c903fa1fa934b5ed54bd2ba47c577e7 | 2624367eff0831094a2f5a76f41f69ee70a7940b | /Stuff/SmartcardWrap.h | 8eb05e0325b5da4e9e245d00011597a0f3807c42 | [
"MIT"
] | permissive | cabralfilho/Omnikey-SyncAPI-NodeJS-Wrapper | 1086b9a628ee037b23a712ecbd4eb7b94eb588c3 | 360c15eaa56bd3b28a417dc6ca2cac24aba3eb24 | refs/heads/master | 2021-04-19T07:08:06.690460 | 2019-05-10T18:55:28 | 2019-05-10T18:55:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | #include <napi.h>
#include "SmartcardClass.h"
class Smartcard : public Napi::ObjectWrap<Smartcard> {
public:
static Napi::Object Init(Napi::Env, Napi::Object exports);
Smartcard(const Napi::CallbackInfo& info);
SmartcardClass* GetInternalInstance();
private:
static Napi::FunctionReference constructor;
Napi::Value read(const Napi::CallbackInfo& info);
Napi::Value write(const Napi::CallbackInfo& info);
Napi::Value reset(const Napi::CallbackInfo& info);
SmartcardClass* candy;
}; | [
"meatdeli97@gmail.com"
] | meatdeli97@gmail.com |
1ae9d895ac0f2b8db1d7f6e4159935369237400b | f8b92dc59e8e7216a31cc7b74714d079d5b4a6a5 | /Rendering/OpenGL2/vtkTextureObject.cxx | 619017bada40ef78c96cc24e6f0855a06bbdb0fc | [
"BSD-3-Clause"
] | permissive | vejmarie/vtk-7 | 6dfef52b090bb4cd34ac80b1b6ff88b2b3ebdb54 | 32025222cd631e758292e28ab72b3655be554dac | refs/heads/master | 2016-09-14T13:39:55.362280 | 2016-05-13T06:42:26 | 2016-05-13T06:42:26 | 58,708,076 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 58,674 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkTextureObject.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkTextureObject.h"
#include "vtk_glew.h"
#include "vtkObjectFactory.h"
#if GL_ES_VERSION_2_0 != 1 || GL_ES_VERSION_3_0 == 1
#include "vtkPixelBufferObject.h"
#endif
#include "vtkNew.h"
#include "vtkOpenGLBufferObject.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLRenderUtilities.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLTexture.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderer.h"
#include "vtkShaderProgram.h"
#include "vtkOpenGLHelper.h"
#include <cassert>
//#define VTK_TO_DEBUG
//#define VTK_TO_TIMING
#ifdef VTK_TO_TIMING
#include "vtkTimerLog.h"
#endif
#include "vtkTextureObjectFS.h"
#include "vtkTextureObjectVS.h" // a pass through shader
#define BUFFER_OFFSET(i) (static_cast<char *>(NULL) + (i))
// Mapping from DepthTextureCompareFunction values to OpenGL values.
//----------------------------------------------------------------------------
static GLint OpenGLDepthTextureCompareFunction[8]=
{
GL_LEQUAL,
GL_GEQUAL,
GL_LESS,
GL_GREATER,
GL_EQUAL,
GL_NOTEQUAL,
GL_ALWAYS,
GL_NEVER
};
//----------------------------------------------------------------------------
static const char *DepthTextureCompareFunctionAsString[8]=
{
"Lequal",
"Gequal",
"Less",
"Greater",
"Equal",
"NotEqual",
"AlwaysTrue",
"Never"
};
// Mapping from Wrap values to OpenGL values
#if GL_ES_VERSION_2_0 != 1
//--------------------------------------------------------------------------
static GLint OpenGLWrap[4]=
{
GL_CLAMP_TO_EDGE,
GL_REPEAT,
GL_MIRRORED_REPEAT,
GL_CLAMP_TO_BORDER
};
//--------------------------------------------------------------------------
static const char *WrapAsString[4]=
{
"ClampToEdge",
"Repeat",
"MirroredRepeat",
"ClampToBorder"
};
//----------------------------------------------------------------------------
static GLenum OpenGLAlphaInternalFormat[5]=
{
GL_R8,
GL_R8,
GL_R16,
GL_R16F,
GL_R32F
};
#else
//--------------------------------------------------------------------------
static GLint OpenGLWrap[3]=
{
GL_CLAMP_TO_EDGE,
GL_REPEAT,
GL_MIRRORED_REPEAT
};
//--------------------------------------------------------------------------
static const char *WrapAsString[3]=
{
"ClampToEdge",
"Repeat",
"MirroredRepeat"
};
//----------------------------------------------------------------------------
// Should be GL_RED but that requires an extension for ES 2.0
static GLenum OpenGLAlphaInternalFormat[5]=
{
GL_LUMINANCE,
GL_LUMINANCE,
GL_LUMINANCE,
GL_LUMINANCE,
GL_LUMINANCE
};
#endif
// Mapping MinificationFilter values to OpenGL values.
//----------------------------------------------------------------------------
static GLint OpenGLMinFilter[6]=
{
GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_LINEAR
};
// Mapping MagnificationFilter values to OpenGL values.
//----------------------------------------------------------------------------
static GLint OpenGLMagFilter[6]=
{
GL_NEAREST,
GL_LINEAR
};
//----------------------------------------------------------------------------
static const char *MinMagFilterAsString[6]=
{
"Nearest",
"Linear",
"NearestMipmapNearest",
"NearestMipmapLinear",
"LinearMipmapNearest",
"LinearMipmapLinear"
};
//----------------------------------------------------------------------------
static GLenum OpenGLDepthInternalFormat[5]=
{
GL_DEPTH_COMPONENT,
GL_DEPTH_COMPONENT16,
#ifdef GL_DEPTH_COMPONENT24
GL_DEPTH_COMPONENT24,
#else
GL_DEPTH_COMPONENT16,
#endif
#ifdef GL_DEPTH_COMPONENT32
GL_DEPTH_COMPONENT32,
#else
GL_DEPTH_COMPONENT16,
#endif
#ifdef GL_DEPTH_COMPONENT32F
GL_DEPTH_COMPONENT32F
#else
GL_DEPTH_COMPONENT16
#endif
};
//----------------------------------------------------------------------------
static GLenum OpenGLDepthInternalFormatType[5]=
{
GL_UNSIGNED_INT,
GL_UNSIGNED_INT,
GL_UNSIGNED_INT,
GL_UNSIGNED_INT,
#ifdef GL_DEPTH_COMPONENT32F
GL_FLOAT
#else
GL_UNSIGNED_INT
#endif
};
/*
static const char *DepthInternalFormatFilterAsString[6]=
{
"Native",
"Fixed16",
"Fixed24",
"Fixed32",
"Float32"
};
*/
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkTextureObject);
//----------------------------------------------------------------------------
vtkTextureObject::vtkTextureObject()
{
this->Context = NULL;
this->Handle = 0;
this->NumberOfDimensions = 0;
this->Target = 0;
this->Components = 0;
this->Width = 0;
this->Height = 0;
this->Depth = 0;
this->RequireTextureInteger = false;
this->SupportsTextureInteger = false;
this->RequireTextureFloat = false;
this->SupportsTextureFloat = false;
this->RequireDepthBufferFloat = false;
this->SupportsDepthBufferFloat = false;
this->AutoParameters = 1;
this->WrapS = Repeat;
this->WrapT = Repeat;
this->WrapR = Repeat;
this->MinificationFilter = Nearest;
this->MagnificationFilter = Nearest;
this->MinLOD = -1000.0f;
this->MaxLOD = 1000.0f;
this->BaseLevel = 0;
this->MaxLevel = 0;
this->DepthTextureCompare = false;
this->DepthTextureCompareFunction = Lequal;
this->GenerateMipmap = false;
this->ShaderProgram = NULL;
this->BorderColor[0] = 0.0f;
this->BorderColor[1] = 0.0f;
this->BorderColor[2] = 0.0f;
this->BorderColor[3] = 0.0f;
this->BufferObject = 0;
this->ResetFormatAndType();
}
//----------------------------------------------------------------------------
vtkTextureObject::~vtkTextureObject()
{
this->DestroyTexture();
if (this->ShaderProgram)
{
delete this->ShaderProgram;
this->ShaderProgram = NULL;
}
}
//----------------------------------------------------------------------------
bool vtkTextureObject::IsSupported(vtkOpenGLRenderWindow* vtkNotUsed(win),
bool requireTexFloat,
bool requireDepthFloat,
bool requireTexInt)
{
#if GL_ES_VERSION_2_0 != 1
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
return true;
}
bool texFloat = true;
if (requireTexFloat)
{
texFloat = (glewIsSupported("GL_ARB_texture_float") != 0
&& glewIsSupported("GL_ARB_texture_rg") != 0);
}
bool depthFloat = true;
if (requireDepthFloat)
{
depthFloat = (glewIsSupported("GL_ARB_depth_buffer_float") != 0);
}
bool texInt = true;
if (requireTexInt)
{
texInt = (glewIsSupported("GL_EXT_texture_integer") != 0);
}
#else
bool texFloat = true;
bool depthFloat = !requireDepthFloat;
bool texInt = !requireTexInt;
#if GL_ES_VERSION_3_0 == 1
texFloat = true;
depthFloat = true; // I think this is the case
texInt = true;
#endif
#endif
return texFloat && depthFloat && texInt;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::LoadRequiredExtensions(vtkOpenGLRenderWindow *renWin)
{
#if GL_ES_VERSION_2_0 != 1
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
this->SupportsTextureInteger = true;
this->SupportsTextureFloat = true;
this->SupportsDepthBufferFloat = true;
}
else
{
this->SupportsTextureInteger =
(glewIsSupported("GL_EXT_texture_integer") != 0);
this->SupportsTextureFloat =
(glewIsSupported("GL_ARB_texture_float") != 0 &&
glewIsSupported("GL_ARB_texture_rg") != 0);
this->SupportsDepthBufferFloat =
(glewIsSupported("GL_ARB_depth_buffer_float") != 0);
}
#else
// some of these may have extensions etc for ES 2.0
// setting to false right now as I do not know
this->SupportsTextureInteger = false;
this->SupportsTextureFloat = true;
this->SupportsDepthBufferFloat = false;
#if GL_ES_VERSION_3_0 == 1
this->SupportsTextureInteger = true;
this->SupportsTextureFloat = true;
this->SupportsDepthBufferFloat = true;
#endif
#endif
return this->IsSupported(renWin,
this->RequireTextureFloat,
this->RequireDepthBufferFloat,
this->RequireTextureInteger);
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetContext(vtkOpenGLRenderWindow* renWin)
{
// avoid pointless reassignment
if (this->Context == renWin)
{
return;
}
// free previous resources
this->DestroyTexture();
this->Context = NULL;
this->Modified();
// all done if assigned null
if (!renWin)
{
return;
}
if (!this->LoadRequiredExtensions(renWin) )
{
vtkErrorMacro("Required OpenGL extensions not supported by the context.");
return;
}
// initialize
this->Context = renWin;
this->Context->MakeCurrent();
}
//----------------------------------------------------------------------------
vtkOpenGLRenderWindow* vtkTextureObject::GetContext()
{
return this->Context;
}
//----------------------------------------------------------------------------
void vtkTextureObject::DestroyTexture()
{
// deactivate it first
this->Deactivate();
// because we don't hold a reference to the render
// context we don't have any control on when it is
// destroyed. In fact it may be destroyed before
// we are(eg smart pointers), in which case we should
// do nothing.
if (this->Context && this->Handle)
{
GLuint tex = this->Handle;
glDeleteTextures(1, &tex);
vtkOpenGLCheckErrorMacro("failed at glDeleteTexture");
}
this->Handle = 0;
this->NumberOfDimensions = 0;
this->Target = 0;
this->Components = 0;
this->Width = this->Height = this->Depth = 0;
this->ResetFormatAndType();
}
//----------------------------------------------------------------------------
void vtkTextureObject::CreateTexture()
{
assert(this->Context);
// reuse the existing handle if we have one
if (!this->Handle)
{
GLuint tex=0;
glGenTextures(1, &tex);
vtkOpenGLCheckErrorMacro("failed at glGenTextures");
this->Handle=tex;
#if defined(GL_TEXTURE_BUFFER)
if (this->Target && this->Target != GL_TEXTURE_BUFFER)
#else
if (this->Target)
#endif
{
glBindTexture(this->Target, this->Handle);
vtkOpenGLCheckErrorMacro("failed at glBindTexture");
// See: http://www.opengl.org/wiki/Common_Mistakes#Creating_a_complete_texture
// turn off mip map filter or set the base and max level correctly. here
// both are done.
glTexParameteri(this->Target, GL_TEXTURE_MIN_FILTER,
this->GetMinificationFilterMode(this->MinificationFilter));
glTexParameteri(this->Target, GL_TEXTURE_MAG_FILTER,
this->GetMagnificationFilterMode(this->MagnificationFilter));
glTexParameteri(this->Target, GL_TEXTURE_WRAP_S,
this->GetWrapSMode(this->WrapS));
glTexParameteri(this->Target, GL_TEXTURE_WRAP_T,
this->GetWrapTMode(this->WrapT));
#if defined(GL_TEXTURE_3D)
if (this->Target == GL_TEXTURE_3D)
{
glTexParameteri(this->Target, GL_TEXTURE_WRAP_R,
this->GetWrapRMode(this->WrapR));
}
#endif
#ifdef GL_TEXTURE_BASE_LEVEL
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
#endif
#ifdef GL_TEXTURE_MAX_LEVEL
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
#endif
glBindTexture(this->Target, 0);
}
}
}
//---------------------------------------------------------------------------
int vtkTextureObject::GetTextureUnit()
{
if (this->Context)
{
return this->Context->GetTextureUnitForTexture(this);
}
return -1;
}
//---------------------------------------------------------------------------
void vtkTextureObject::Activate()
{
// activate a free texture unit for this texture
this->Context->ActivateTexture(this);
this->Bind();
}
//---------------------------------------------------------------------------
void vtkTextureObject::Deactivate()
{
if (this->Context)
{
this->Context->ActivateTexture(this);
this->UnBind();
this->Context->DeactivateTexture(this);
}
}
//---------------------------------------------------------------------------
void vtkTextureObject::ReleaseGraphicsResources(vtkWindow *win)
{
vtkOpenGLRenderWindow *rwin =
vtkOpenGLRenderWindow::SafeDownCast(win);
if (rwin && this->Handle)
{
rwin->MakeCurrent();
rwin->ActivateTexture(this);
this->UnBind();
rwin->DeactivateTexture(this);
GLuint tex = this->Handle;
glDeleteTextures(1, &tex);
this->Handle = 0;
this->NumberOfDimensions = 0;
this->Target =0;
this->InternalFormat = 0;
this->Format = 0;
this->Type = 0;
this->Components = 0;
this->Width = this->Height = this->Depth = 0;
}
if (this->ShaderProgram)
{
this->ShaderProgram->ReleaseGraphicsResources(win);
delete this->ShaderProgram;
this->ShaderProgram = NULL;
}
}
//----------------------------------------------------------------------------
void vtkTextureObject::Bind()
{
assert(this->Context);
assert(this->Handle);
glBindTexture(this->Target, this->Handle);
vtkOpenGLCheckErrorMacro("failed at glBindTexture");
if (this->AutoParameters && (this->GetMTime() > this->SendParametersTime))
{
this->SendParameters();
}
}
//----------------------------------------------------------------------------
void vtkTextureObject::UnBind()
{
if (this->Target)
{
glBindTexture(this->Target, 0);
vtkOpenGLCheckErrorMacro("failed at glBindTexture(0)");
}
}
//----------------------------------------------------------------------------
bool vtkTextureObject::IsBound()
{
bool result=false;
if(this->Context && this->Handle)
{
GLenum target=0; // to avoid warnings.
switch(this->Target)
{
#if defined(GL_TEXTURE_1D) && defined(GL_TEXTURE_BINDING_1D)
case GL_TEXTURE_1D:
target=GL_TEXTURE_BINDING_1D;
break;
#endif
case GL_TEXTURE_2D:
target=GL_TEXTURE_BINDING_2D;
break;
#if defined(GL_TEXTURE_3D) && defined(GL_TEXTURE_BINDING_3D)
case GL_TEXTURE_3D:
target=GL_TEXTURE_BINDING_3D;
break;
#endif
#if defined(GL_TEXTURE_BUFFER) && defined(GL_TEXTURE_BINDING_BUFFER)
case GL_TEXTURE_BUFFER:
target=GL_TEXTURE_BINDING_BUFFER;
break;
#endif
default:
assert("check: impossible case" && 0);
break;
}
GLint objectId;
glGetIntegerv(target,&objectId);
result=static_cast<GLuint>(objectId)==this->Handle;
}
return result;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SendParameters()
{
assert("pre: is_bound" && this->IsBound());
#if defined(GL_TEXTURE_BUFFER)
if (this->Target == GL_TEXTURE_BUFFER)
{
return;
}
#endif
glTexParameteri(this->Target,GL_TEXTURE_WRAP_S, OpenGLWrap[this->WrapS]);
glTexParameteri(this->Target,GL_TEXTURE_WRAP_T, OpenGLWrap[this->WrapT]);
#ifdef GL_TEXTURE_WRAP_R
glTexParameteri(
this->Target,
GL_TEXTURE_WRAP_R,
OpenGLWrap[this->WrapR]);
#endif
glTexParameteri(
this->Target,
GL_TEXTURE_MIN_FILTER,
OpenGLMinFilter[this->MinificationFilter]);
glTexParameteri(
this->Target,
GL_TEXTURE_MAG_FILTER,
OpenGLMagFilter[this->MagnificationFilter]);
#if GL_ES_VERSION_2_0 != 1 || GL_ES_VERSION_3_0 == 1
#if GL_ES_VERSION_3_0 != 1
glTexParameterfv(this->Target, GL_TEXTURE_BORDER_COLOR, this->BorderColor);
if(this->DepthTextureCompare)
{
glTexParameteri(
this->Target,
GL_TEXTURE_COMPARE_MODE,
GL_COMPARE_REF_TO_TEXTURE);
}
else
{
glTexParameteri(
this->Target,
GL_TEXTURE_COMPARE_MODE,
GL_NONE);
}
#endif
glTexParameterf(this->Target, GL_TEXTURE_MIN_LOD, this->MinLOD);
glTexParameterf(this->Target, GL_TEXTURE_MAX_LOD, this->MaxLOD);
glTexParameteri(this->Target, GL_TEXTURE_BASE_LEVEL, this->BaseLevel);
glTexParameteri(this->Target, GL_TEXTURE_MAX_LEVEL, this->MaxLevel);
glTexParameteri(
this->Target,
GL_TEXTURE_COMPARE_FUNC,
OpenGLDepthTextureCompareFunction[this->DepthTextureCompareFunction]);
#endif
vtkOpenGLCheckErrorMacro("failed after SendParameters");
this->SendParametersTime.Modified();
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetInternalFormat(int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
if (this->InternalFormat)
{
return this->InternalFormat;
}
// pre-condition
if(vtktype == VTK_VOID && numComps != 1)
{
vtkErrorMacro("Depth component texture must have 1 component only (" <<
numComps << " requested");
this->InternalFormat = 0;
return this->InternalFormat;
}
this->InternalFormat =
this->GetDefaultInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
if (!this->InternalFormat)
{
vtkDebugMacro("Unable to find suitable internal format for T="
<< vtktype << " NC=" << numComps << " SSTI="
<< shaderSupportsTextureInt);
}
return this->InternalFormat;
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetDefaultInternalFormat(
int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
GLenum result = 0;
// if shader supports int textures try that first
if (shaderSupportsTextureInt)
{
result = this->Context->GetDefaultTextureInternalFormat(
vtktype,numComps,true,false);
if (!result)
{
vtkDebugMacro("Unsupported internal texture type!");
}
return result;
}
// try default next
result = this->Context->GetDefaultTextureInternalFormat(
vtktype,numComps,false,false);
if (result)
{
return result;
}
// try floating point
result = this->Context->GetDefaultTextureInternalFormat(
vtktype,numComps,false,true);
if (!result)
{
vtkDebugMacro("Unsupported internal texture type!");
vtkDebugMacro("Unable to find suitable internal format for T="
<< vtktype << " NC=" << numComps << " SSTI=" << shaderSupportsTextureInt);
}
return result;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetInternalFormat(unsigned int glInternalFormat)
{
if (this->InternalFormat != glInternalFormat)
{
this->InternalFormat = glInternalFormat;
this->Modified();
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetFormat(int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
if (!this->Format)
{
this->Format = this->GetDefaultFormat(vtktype,
numComps, shaderSupportsTextureInt);
}
return this->Format;
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetDefaultFormat(int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
if (vtktype == VTK_VOID)
{
return GL_DEPTH_COMPONENT;
}
#if GL_ES_VERSION_2_0 != 1
if(this->SupportsTextureInteger && shaderSupportsTextureInt
&& (vtktype==VTK_SIGNED_CHAR||vtktype==VTK_UNSIGNED_CHAR||
vtktype==VTK_SHORT||vtktype==VTK_UNSIGNED_SHORT||vtktype==VTK_INT||
vtktype==VTK_UNSIGNED_INT))
{
switch (numComps)
{
case 1:
return GL_RED_INTEGER;
case 2:
return GL_RG_INTEGER;
case 3:
return GL_RGB_INTEGER_EXT;
case 4:
return GL_RGBA_INTEGER_EXT;
}
}
else
{
switch (numComps)
{
case 1:
return GL_RED;
case 2:
return GL_RG;
case 3:
return GL_RGB;
case 4:
return GL_RGBA;
}
#else
{
switch (numComps)
{
#ifdef GL_RED
case 1:
return GL_RED;
case 2:
return GL_RG;
#else
case 1:
return GL_LUMINANCE;
case 2:
return GL_LUMINANCE_ALPHA;
#endif
case 3:
return GL_RGB;
case 4:
return GL_RGBA;
}
#endif
}
return GL_RGB;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetFormat(unsigned int glFormat)
{
if (this->Format != glFormat)
{
this->Format = glFormat;
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkTextureObject::ResetFormatAndType()
{
this->Format = 0;
this->InternalFormat = 0;
this->Type = 0;
}
//----------------------------------------------------------------------------
int vtkTextureObject::GetDefaultDataType(int vtk_scalar_type)
{
// DON'T DEAL with VTK_CHAR as this is platform dependent.
switch (vtk_scalar_type)
{
case VTK_SIGNED_CHAR:
return GL_BYTE;
case VTK_UNSIGNED_CHAR:
return GL_UNSIGNED_BYTE;
case VTK_SHORT:
return GL_SHORT;
case VTK_UNSIGNED_SHORT:
return GL_UNSIGNED_SHORT;
case VTK_INT:
return GL_INT;
case VTK_UNSIGNED_INT:
return GL_UNSIGNED_INT;
case VTK_FLOAT:
case VTK_VOID: // used for depth component textures.
return GL_FLOAT;
}
return 0;
}
//----------------------------------------------------------------------------
static int vtkGetVTKType(GLenum gltype)
{
// DON'T DEAL with VTK_CHAR as this is platform dependent.
switch (gltype)
{
case GL_BYTE:
return VTK_SIGNED_CHAR;
case GL_UNSIGNED_BYTE:
return VTK_UNSIGNED_CHAR;
case GL_SHORT:
return VTK_SHORT;
case GL_UNSIGNED_SHORT:
return VTK_UNSIGNED_SHORT;
case GL_INT:
return VTK_INT;
case GL_UNSIGNED_INT:
return VTK_UNSIGNED_INT;
case GL_FLOAT:
return VTK_FLOAT;
}
return 0;
}
//----------------------------------------------------------------------------
int vtkTextureObject::GetVTKDataType()
{
return ::vtkGetVTKType(this->Type);
}
//----------------------------------------------------------------------------
int vtkTextureObject::GetDataType(int vtk_scalar_type)
{
if (!this->Type)
{
this->Type = this->GetDefaultDataType(vtk_scalar_type);
}
return this->Type;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetDataType(unsigned int glType)
{
if (this->Type != glType)
{
this->Type = glType;
this->Modified();
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetMinificationFilterMode(int vtktype)
{
switch(vtktype)
{
case Nearest:
return GL_NEAREST;
case Linear:
return GL_LINEAR;
case NearestMipmapNearest:
return GL_NEAREST_MIPMAP_NEAREST;
case NearestMipmapLinear:
return GL_NEAREST_MIPMAP_LINEAR;
case LinearMipmapNearest:
return GL_LINEAR_MIPMAP_NEAREST;
case LinearMipmapLinear:
return GL_LINEAR_MIPMAP_LINEAR;
default:
return GL_NEAREST;
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetMagnificationFilterMode(int vtktype)
{
switch(vtktype)
{
case Nearest:
return GL_NEAREST;
case Linear:
return GL_LINEAR;
default:
return GL_NEAREST;
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetWrapSMode(int vtktype)
{
switch(vtktype)
{
case ClampToEdge:
return GL_CLAMP_TO_EDGE;
case Repeat:
return GL_REPEAT;
#ifdef GL_CLAMP_TO_BORDER
case ClampToBorder:
return GL_CLAMP_TO_BORDER;
#endif
case MirroredRepeat:
return GL_MIRRORED_REPEAT;
default:
return GL_CLAMP_TO_EDGE;
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetWrapTMode(int vtktype)
{
return this->GetWrapSMode(vtktype);
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetWrapRMode(int vtktype)
{
return this->GetWrapSMode(vtktype);
}
// 1D textures are not supported in ES 2.0 or 3.0
#if GL_ES_VERSION_2_0 != 1
//----------------------------------------------------------------------------
bool vtkTextureObject::Create1D(int numComps,
vtkPixelBufferObject* pbo,
bool shaderSupportsTextureInt)
{
assert(this->Context);
assert(pbo->GetContext() == this->Context.GetPointer());
GLenum target = GL_TEXTURE_1D;
// Now, detemine texture parameters using the information from the pbo.
// * internalFormat depends on number of components and the data type.
GLenum internalFormat = this->GetInternalFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * format depends on the number of components.
GLenum format = this->GetFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * type if the data type in the pbo
GLenum type = this->GetDefaultDataType(pbo->GetType());
if (!internalFormat || !format || !type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(target, 0, static_cast<GLint>(internalFormat),
static_cast<GLsizei>(pbo->GetSize()/
static_cast<unsigned int>(numComps)),
0, format,
type, BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
pbo->UnBind();
this->Deactivate();
this->Target = target;
this->Format = format;
this->Type = type;
this->Components = numComps;
this->Width = pbo->GetSize();
this->Height = 1;
this->Depth =1;
this->NumberOfDimensions=1;
return true;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create1DFromRaw(unsigned int width, int numComps,
int dataType, void *data)
{
assert(this->Context);
// Now determine the texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to determine texture parameters.");
return false;
}
GLenum target = GL_TEXTURE_1D;
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage1D(this->Target,
0,
this->InternalFormat,
static_cast<GLsizei> (this->Width),
0,
this->Format,
this->Type,
static_cast<const GLvoid *> (data));
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 1D alpha texture using a raw pointer.
// This is a blocking call. If you can, use PBO instead.
bool vtkTextureObject::CreateAlphaFromRaw(unsigned int width,
int internalFormat,
int rawType,
void* raw)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: raw_exists" && raw!=0);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfAlphaFormats);
// Now, detemine texture parameters using the arguments.
this->GetDataType(rawType);
if (!this->InternalFormat)
{
this->InternalFormat
= OpenGLAlphaInternalFormat[internalFormat];
}
if (!this->InternalFormat || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_1D;
this->Format = GL_RED;
this->Width = width;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->Components = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width), 0,
this->Format, this->Type, raw);
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
this->Deactivate();
return true;
}
// Description:
// Create a texture buffer basically a 1D texture that can be
// very large for passing data into the fragment shader
bool vtkTextureObject::CreateTextureBuffer(unsigned int numValues, int numComps,
int dataType, vtkOpenGLBufferObject *bo)
{
assert(this->Context);
// Now, detemine texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_BUFFER;
this->Components = numComps;
this->Width = numValues;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->BufferObject = bo;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
glTexBuffer(
this->Target,
this->InternalFormat,
this->BufferObject->GetHandle());
vtkOpenGLCheckErrorMacro("failed at glTexBuffer");
this->Deactivate();
return true;
}
#else
// Description:
// Create a texture buffer basically a 1D texture that can be
// very large for passing data into the fragment shader
bool vtkTextureObject::CreateTextureBuffer(unsigned int numValues, int numComps,
int dataType, vtkOpenGLBufferObject *bo)
{
assert(this->Context);
vtkErrorMacro("TextureBuffers not supported in OPenGL ES");
// TODO: implement 1D and Texture buffers using 2D textures
return false;
}
#endif // not ES 2.0 or 3.0
#if GL_ES_VERSION_2_0 != 1 || GL_ES_VERSION_3_0 == 1
//----------------------------------------------------------------------------
bool vtkTextureObject::Create2D(unsigned int width, unsigned int height,
int numComps, vtkPixelBufferObject* pbo,
bool shaderSupportsTextureInt)
{
assert(this->Context);
assert(pbo->GetContext() == this->Context.GetPointer());
if (pbo->GetSize() < width*height*static_cast<unsigned int>(numComps))
{
vtkErrorMacro("PBO size must match texture size.");
return false;
}
// Now, detemine texture parameters using the information from the pbo.
// * internalFormat depends on number of components and the data type.
// * format depends on the number of components.
// * type if the data type in the pbo
int vtktype = pbo->GetType();
GLenum type = this->GetDefaultDataType(vtktype);
GLenum internalFormat
= this->GetInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
GLenum format
= this->GetFormat(vtktype, numComps, shaderSupportsTextureInt);
if (!internalFormat || !format || !type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
GLenum target = GL_TEXTURE_2D;
this->Target = target;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(
target,
0,
internalFormat,
static_cast<GLsizei>(width),
static_cast<GLsizei>(height),
0,
format,
type,
BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
pbo->UnBind();
this->Deactivate();
this->Target = target;
this->Format = format;
this->Type = type;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 2D depth texture using a PBO.
bool vtkTextureObject::CreateDepth(unsigned int width,
unsigned int height,
int internalFormat,
vtkPixelBufferObject *pbo)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: pbo_context_exists" && pbo->GetContext()!=0);
assert("pre: context_match" && this->GetContext()==pbo->GetContext());
assert("pre: sizes_match" && pbo->GetSize()==width*height);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfDepthFormats);
GLenum inFormat=OpenGLDepthInternalFormat[internalFormat];
GLenum type = this->GetDefaultDataType(pbo->GetType());
this->Target=GL_TEXTURE_2D;
this->Format=GL_DEPTH_COMPONENT;
this->Type=type;
this->Width=width;
this->Height=height;
this->Depth=1;
this->NumberOfDimensions=2;
this->Components=1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(this->Target, 0, static_cast<GLint>(inFormat),
static_cast<GLsizei>(width), static_cast<GLsizei>(height), 0,
this->Format, this->Type, BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
pbo->UnBind();
this->Deactivate();
return true;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create3D(unsigned int width, unsigned int height,
unsigned int depth, int numComps,
vtkPixelBufferObject* pbo,
bool shaderSupportsTextureInt)
{
#ifdef GL_TEXTURE_3D
assert(this->Context);
assert(this->Context.GetPointer() == pbo->GetContext());
if (pbo->GetSize() != width*height*depth*static_cast<unsigned int>(numComps))
{
vtkErrorMacro("PBO size must match texture size.");
return false;
}
GLenum target = GL_TEXTURE_3D;
// Now, detemine texture parameters using the information from the pbo.
// * internalFormat depends on number of components and the data type.
GLenum internalFormat = this->GetInternalFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * format depends on the number of components.
GLenum format = this->GetFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * type if the data type in the pbo
GLenum type = this->GetDefaultDataType(pbo->GetType());
if (!internalFormat || !format || !type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
// Source texture data from the PBO.
glTexImage3D(target, 0, static_cast<GLint>(internalFormat),
static_cast<GLsizei>(width), static_cast<GLsizei>(height),
static_cast<GLsizei>(depth), 0, format, type,
BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage3D");
pbo->UnBind();
this->Deactivate();
this->Target = target;
this->Format = format;
this->Type = type;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
return true;
#else
return false;
#endif
}
//----------------------------------------------------------------------------
vtkPixelBufferObject* vtkTextureObject::Download()
{
assert(this->Context);
assert(this->Handle);
vtkPixelBufferObject* pbo = vtkPixelBufferObject::New();
pbo->SetContext(this->Context);
int vtktype = ::vtkGetVTKType(this->Type);
if (vtktype == 0)
{
vtkErrorMacro("Failed to determine type.");
return 0;
}
unsigned int size = this->Width* this->Height* this->Depth;
// doesn't matter which Upload*D method we use since we are not really
// uploading any data, simply allocating GPU space.
if (!pbo->Upload1D(vtktype, NULL, size, this->Components, 0))
{
vtkErrorMacro("Could not allocate memory for PBO.");
pbo->Delete();
return 0;
}
pbo->Bind(vtkPixelBufferObject::PACKED_BUFFER);
this->Bind();
#if GL_ES_VERSION_2_0 != 1
glGetTexImage(this->Target, 0, this->Format, this->Type, BUFFER_OFFSET(0));
#else
// you can do something with glReadPixels and binding a texture as a FBO
// I believe for ES 2.0
#endif
vtkOpenGLCheckErrorMacro("failed at glGetTexImage");
this->Deactivate();
pbo->UnBind();
pbo->SetComponents(this->Components);
return pbo;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create3DFromRaw(unsigned int width, unsigned int height,
unsigned int depth, int numComps,
int dataType, void *data)
{
assert(this->Context);
// Now, detemine texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_3D;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage3D(
this->Target,
0,
this->InternalFormat,
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
static_cast<GLsizei>(this->Depth),
0,
this->Format,
this->Type,
static_cast<const GLvoid *>(data));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
#endif
//----------------------------------------------------------------------------
bool vtkTextureObject::Create2DFromRaw(unsigned int width, unsigned int height,
int numComps, int dataType, void *data)
{
assert(this->Context);
// Now determine the texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to determine texture parameters. IF="
<< this->InternalFormat << " F=" << this->Format << " T=" << this->Type);
return false;
}
GLenum target = GL_TEXTURE_2D;
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(
this->Target,
0,
this->InternalFormat,
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0,
this->Format,
this->Type,
static_cast<const GLvoid *>(data));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 2D depth texture using a raw pointer.
// This is a blocking call. If you can, use PBO instead.
bool vtkTextureObject::CreateDepthFromRaw(unsigned int width,
unsigned int height,
int internalFormat,
int rawType,
void *raw)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: raw_exists" && raw!=0);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfDepthFormats);
// Now, detemine texture parameters using the arguments.
this->GetDataType(rawType);
if (!this->InternalFormat)
{
this->InternalFormat
= OpenGLDepthInternalFormat[internalFormat];;
}
if (!this->InternalFormat || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_2D;
this->Format = GL_DEPTH_COMPONENT;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Components = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height), 0,
this->Format, this->Type,raw);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
bool vtkTextureObject::AllocateDepth(unsigned int width, unsigned int height,
int internalFormat)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfDepthFormats);
this->Target = GL_TEXTURE_2D;
this->Format = GL_DEPTH_COMPONENT;
// Try to match vtk type to internal fmt
if (!this->Type)
{
this->Type = OpenGLDepthInternalFormatType[internalFormat];
}
if (!this->InternalFormat)
{
this->InternalFormat = OpenGLDepthInternalFormat[internalFormat];
}
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Components = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage2D(
this->Target,
0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0,
this->Format,
this->Type,
0);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
bool vtkTextureObject::Allocate1D(unsigned int width, int numComps,
int vtkType)
{
#ifdef GL_TEXTURE_1D
assert(this->Context);
this->Target = GL_TEXTURE_1D;
this->GetDataType(vtkType);
this->GetInternalFormat(vtkType, numComps, false);
this->GetFormat(vtkType, numComps, false);
this->Components = numComps;
this->Width = width;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage1D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width), 0, this->Format,
this->Type,0);
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
this->Deactivate();
return true;
#else
return false;
#endif
}
// ----------------------------------------------------------------------------
// Description:
// Create a 2D color texture but does not initialize its values.
// Internal format is deduced from numComps and vtkType.
bool vtkTextureObject::Allocate2D(unsigned int width,unsigned int height,
int numComps, int vtkType)
{
assert(this->Context);
this->Target = GL_TEXTURE_2D;
this->GetDataType(vtkType);
this->GetInternalFormat(vtkType, numComps, false);
this->GetFormat(vtkType, numComps,false);
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth =1;
this->NumberOfDimensions=2;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage2D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0, this->Format, this->Type, 0);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 3D color texture but does not initialize its values.
// Internal format is deduced from numComps and vtkType.
bool vtkTextureObject::Allocate3D(unsigned int width,unsigned int height,
unsigned int depth, int numComps,
int vtkType)
{
#ifdef GL_TEXTURE_3D
this->Target=GL_TEXTURE_3D;
if(this->Context==0)
{
vtkErrorMacro("No context specified. Cannot create texture.");
return false;
}
this->GetInternalFormat(vtkType, numComps, false);
this->GetFormat(vtkType, numComps, false);
this->GetDataType(vtkType);
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage3D(this->Target, 0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
static_cast<GLsizei>(this->Depth), 0,
this->Format, this->Type, 0);
vtkOpenGLCheckErrorMacro("failed at glTexImage3D");
this->Deactivate();
return true;
#else
return false;
#endif
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create2D(unsigned int width, unsigned int height,
int numComps, int vtktype,
bool shaderSupportsTextureInt)
{
assert(this->Context);
GLenum target = GL_TEXTURE_2D;
// Now, detemine texture parameters using the information provided.
this->GetDataType(vtktype);
this->GetInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
this->GetFormat(vtktype, numComps, shaderSupportsTextureInt);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Allocate space for texture, don't upload any data.
glTexImage2D(target, 0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0, this->Format, this->Type, NULL);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create3D(unsigned int width, unsigned int height,
unsigned int depth,
int numComps, int vtktype,
bool shaderSupportsTextureInt)
{
#ifdef GL_TEXTURE_3D
assert(this->Context);
GLenum target = GL_TEXTURE_3D;
// Now, detemine texture parameters using the information provided.
this->GetInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
this->GetFormat(vtktype, numComps, shaderSupportsTextureInt);
this->GetDataType(vtktype);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Allocate space for texture, don't upload any data.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage3D(this->Target, 0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
static_cast<GLsizei>(this->Depth), 0,
this->Format, this->Type, NULL);
vtkOpenGLCheckErrorMacro("falied at glTexImage3D");
this->Deactivate();
return true;
#else
return false;
#endif
}
// ----------------------------------------------------------------------------
void vtkTextureObject::CopyToFrameBuffer(
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
// the following math really only works when texture
// and viewport are of the same dimensions
float minXTexCoord=static_cast<float>(
static_cast<double>(0.5)/this->Width);
float minYTexCoord=static_cast<float>(
static_cast<double>(0.5)/this->Height);
float maxXTexCoord=static_cast<float>(
static_cast<double>(this->Width-0.5)/this->Width);
float maxYTexCoord=static_cast<float>(
static_cast<double>(this->Height-0.5)/this->Height);
float tcoords[] = {
minXTexCoord, minYTexCoord,
maxXTexCoord, minYTexCoord,
maxXTexCoord, maxYTexCoord,
minXTexCoord, maxYTexCoord};
float verts[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f};
this->CopyToFrameBuffer(tcoords, verts, program, vao);
}
// ----------------------------------------------------------------------------
void vtkTextureObject::CopyToFrameBuffer(
int srcXmin, int srcYmin,
int srcXmax, int srcYmax,
int dstXmin, int dstYmin,
int dstSizeX, int dstSizeY,
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
float dstXmax = static_cast<float>(dstXmin+srcXmax-srcXmin);
float dstYmax = static_cast<float>(dstYmin+srcYmax-srcYmin);
this->CopyToFrameBuffer(srcXmin, srcYmin, srcXmax, srcYmax,
dstXmin, dstYmin, dstXmax, dstYmax, dstSizeX, dstSizeY,
program, vao);
}
// ----------------------------------------------------------------------------
void vtkTextureObject::CopyToFrameBuffer(
int srcXmin, int srcYmin,
int srcXmax, int srcYmax,
int dstXmin, int dstYmin,
int dstXmax, int dstYmax,
int dstSizeX, int dstSizeY,
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
assert("pre: positive_srcXmin" && srcXmin>=0);
assert("pre: max_srcXmax" &&
static_cast<unsigned int>(srcXmax)<this->GetWidth());
assert("pre: increasing_x" && srcXmin<=srcXmax);
assert("pre: positive_srcYmin" && srcYmin>=0);
assert("pre: max_srcYmax" &&
static_cast<unsigned int>(srcYmax)<this->GetHeight());
assert("pre: increasing_y" && srcYmin<=srcYmax);
assert("pre: positive_dstXmin" && dstXmin>=0);
assert("pre: positive_dstYmin" && dstYmin>=0);
float minXTexCoord=static_cast<float>(
static_cast<double>(srcXmin+0.5)/this->Width);
float minYTexCoord=static_cast<float>(
static_cast<double>(srcYmin+0.5)/this->Height);
float maxXTexCoord=static_cast<float>(
static_cast<double>(srcXmax+0.5)/this->Width);
float maxYTexCoord=static_cast<float>(
static_cast<double>(srcYmax+0.5)/this->Height);
GLint saved_viewport[4];
glGetIntegerv(GL_VIEWPORT, saved_viewport);
glViewport(0,0,dstSizeX,dstSizeY);
float tcoords[] = {
minXTexCoord, minYTexCoord,
maxXTexCoord, minYTexCoord,
maxXTexCoord, maxYTexCoord,
minXTexCoord, maxYTexCoord};
float verts[] = {
2.0f*dstXmin/dstSizeX-1.0f, 2.0f*dstYmin/dstSizeY-1.0f, 0.0f,
2.0f*(dstXmax+1.0f)/dstSizeX-1.0f, 2.0f*dstYmin/dstSizeY-1.0f, 0.0f,
2.0f*(dstXmax+1.0f)/dstSizeX-1.0f, 2.0f*(dstYmax+1.0f)/dstSizeY-1.0f, 0.0f,
2.0f*dstXmin/dstSizeX-1.0f, 2.0f*(dstYmax+1.0f)/dstSizeY-1.0f, 0.0f};
this->CopyToFrameBuffer(tcoords, verts, program, vao);
glViewport(saved_viewport[0], saved_viewport[1], saved_viewport[2],
saved_viewport[3]);
}
void vtkTextureObject::CopyToFrameBuffer(float *tcoords, float *verts,
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
vtkOpenGLClearErrorMacro();
// if no program or VAO was provided, then use
// a simple pass through program and bind this
// texture to it
if (!program || !vao)
{
if (!this->ShaderProgram)
{
this->ShaderProgram = new vtkOpenGLHelper;
// build the shader source code
std::string VSSource = vtkTextureObjectVS;
std::string FSSource = vtkTextureObjectFS;
std::string GSSource;
// compile and bind it if needed
vtkShaderProgram *newShader =
this->Context->GetShaderCache()->ReadyShaderProgram(
VSSource.c_str(),
FSSource.c_str(),
GSSource.c_str());
// if the shader changed reinitialize the VAO
if (newShader != this->ShaderProgram->Program)
{
this->ShaderProgram->Program = newShader;
this->ShaderProgram->VAO->ShaderProgramChanged(); // reset the VAO as the shader has changed
}
this->ShaderProgram->ShaderSourceTime.Modified();
}
else
{
this->Context->GetShaderCache()->ReadyShaderProgram(
this->ShaderProgram->Program);
}
// bind and activate this texture
this->Activate();
int sourceId = this->GetTextureUnit();
this->ShaderProgram->Program->SetUniformi("source",sourceId);
vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, this->ShaderProgram->Program,
this->ShaderProgram->VAO);
this->Deactivate();
}
else
{
vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, program, vao);
}
vtkOpenGLCheckErrorMacro("failed after CopyToFrameBuffer")
}
//----------------------------------------------------------------------------
// Description:
// Copy a sub-part of a logical buffer of the framebuffer (color or depth)
// to the texture object. src is the framebuffer, dst is the texture.
// (srcXmin,srcYmin) is the location of the lower left corner of the
// rectangle in the framebuffer. (dstXmin,dstYmin) is the location of the
// lower left corner of the rectangle in the texture. width and height
// specifies the size of the rectangle in pixels.
// If the logical buffer is a color buffer, it has to be selected first with
// glReadBuffer().
// \pre is2D: GetNumberOfDimensions()==2
void vtkTextureObject::CopyFromFrameBuffer(int srcXmin,
int srcYmin,
int vtkNotUsed(dstXmin),
int vtkNotUsed(dstYmin),
int width,
int height)
{
assert("pre: is2D" && this->GetNumberOfDimensions()==2);
this->Activate();
glCopyTexImage2D(this->Target,0,this->Format,srcXmin,srcYmin,width,height,0);
vtkOpenGLCheckErrorMacro("failed at glCopyTexImage2D " << this->Format);
}
//----------------------------------------------------------------------------
void vtkTextureObject::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Width: " << this->Width << endl;
os << indent << "Height: " << this->Height << endl;
os << indent << "Depth: " << this->Depth << endl;
os << indent << "Components: " << this->Components << endl;
os << indent << "Handle: " << this->Handle << endl;
os << indent << "Target: ";
switch(this->Target)
{
#ifdef GL_TEXTURE_1D
case GL_TEXTURE_1D:
os << "GL_TEXTURE_1D" << endl;
break;
#endif
case GL_TEXTURE_2D:
os << "GL_TEXTURE_2D" << endl;
break;
#ifdef GL_TEXTURE_3D
case GL_TEXTURE_3D:
os << "GL_TEXTURE_3D" << endl;
break;
#endif
default:
os << "unknown value: 0x" << hex << this->Target << dec <<endl;
break;
}
os << indent << "NumberOfDimensions: " << this->NumberOfDimensions << endl;
os << indent << "WrapS: " << WrapAsString[this->WrapS] << endl;
os << indent << "WrapT: " << WrapAsString[this->WrapT] << endl;
os << indent << "WrapR: " << WrapAsString[this->WrapR] << endl;
os << indent << "MinificationFilter: "
<< MinMagFilterAsString[this->MinificationFilter] << endl;
os << indent << "MagnificationFilter: "
<< MinMagFilterAsString[this->MagnificationFilter] << endl;
os << indent << "MinLOD: " << this->MinLOD << endl;
os << indent << "MaxLOD: " << this->MaxLOD << endl;
os << indent << "BaseLevel: " << this->BaseLevel << endl;
os << indent << "MaxLevel: " << this->MaxLevel << endl;
os << indent << "DepthTextureCompare: " << this->DepthTextureCompare
<< endl;
os << indent << "DepthTextureCompareFunction: "
<< DepthTextureCompareFunctionAsString[this->DepthTextureCompareFunction]
<< endl;
os << indent << "GenerateMipmap: " << this->GenerateMipmap << endl;
}
| [
"vejmarie@ruggedpod.qyshare.com"
] | vejmarie@ruggedpod.qyshare.com |
e1017088228e88f1ab878575d80b67087d678230 | d5adbe2194ef53fa93c2d643398638b302e6c326 | /Procedural-Midi/MidiAsset/Source/ProceduralAudio/Public/ProceduralAudio.h | 17b00c30cf24740f811a5cea6fde2c3eafccc09d | [] | no_license | risooonho/Midi-Unreal | 4fe8f8f036120068624bd2d5f13103f4894d88de | b08b2d5ab1c2f5f01e9cb66f49d80335a716f6fe | refs/heads/main | 2022-11-15T07:20:14.593335 | 2020-06-30T02:28:15 | 2020-06-30T02:28:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | h | // Copyright -> Scott Bishel
#pragma once
#include "Modules/ModuleManager.h"
class FProceduralAudioModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
}; | [
"scott.bishel@yahoo.com"
] | scott.bishel@yahoo.com |
6132857258158331acc820f30497a3cf1a49e1f9 | 5c0a7c7ae18ce37c29f93f2272166fe759569643 | /C-pp/chapter12/12.7.cpp | 5a2a7131d2e4e413419858c3d6be73b28751f4a6 | [] | no_license | liushengxi13689209566/Programming-language-learning | 21a330c257f56f2f3f0ed3525d2faf76bdc0eb31 | fcc6b10a852a0dcc2dce41f0abaa438f92a34a80 | refs/heads/master | 2020-04-07T02:36:00.268533 | 2019-04-15T08:34:29 | 2019-04-15T08:34:29 | 157,982,315 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | cpp | /*************************************************************************
> File Name: 12.6.cpp
> Author:
> Mail:
> Created Time: 2018年02月17日 星期六 19时09分38秒
************************************************************************/
#include<iostream>
#include<vector>
#include<string>
#include<new>
using namespace std;
vector<int> *fun(){
auto vec = new vector<int> ;
return vec ;
}
void input(vector<int> *ptr){
int temp ;
for(int i=0;i< 5 ;++i){
cin >> temp ;
ptr->push_back(temp);
}
}
auto print(vector<int> *ptr) -> ostream & {
for(auto i : *ptr)
cout << i << " ";
return cout ;
}
int main(void){
auto ptr = fun();
input(ptr);
print(ptr) << endl ;
delete ptr ;
return 0 ;
}
| [
"liushengxi13689209566@163.com"
] | liushengxi13689209566@163.com |
b5d7813c37270cae361e3525bb606eccc31f41c1 | 0bcf6cf143f30781288d67d23ef3fa5efdf10b94 | /cs16/lab05/pointsApproxEqualTest.cpp | bb98c90f74bd9bf2bd50a4e5fcbe7e7f367abbe8 | [] | no_license | Gopu2001/ucsb_ccs_labs | e787f2f2a330a512563cd9d1f03b09693c045278 | c02ae4c698bd8e9e1662c8ad09c3ce4a504180d5 | refs/heads/master | 2023-01-29T18:43:20.583703 | 2020-12-14T21:40:22 | 2020-12-14T21:40:22 | 301,958,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | cpp | #include "shapes.h"
#include "shapeFuncs.h"
#include "tddFuncs.h"
int main() {
struct Point p1,p2;
p1.x = 6.0; p1.y = 3.0;
p2.x = 7.0; p2.y = 11.0;
// p1 should be equal to itself
assertTrue(pointsApproxEqual(p1,p1),"pointsApproxEqual(p1,p1)");
// p1 and p2 should not be equal: note the ! meaning "not"
assertFalse(pointsApproxEqual(p1,p2), "pointsApproxEqual(p1,p2)");
assertFalse(pointsApproxEqual(p2,p1), "assertFalse(pointsApproxEqual(p2,p1))");
}
| [
"41317321+Gopu2001@users.noreply.github.com"
] | 41317321+Gopu2001@users.noreply.github.com |
c45beac7cf232d27d0c5124673b2c58c0d4a8d00 | ecb3b5552115c0228239a1bf7edb7a127de57482 | /mytimer.cpp | 575fbf0d8379ac51383b550c5885eb83c49f3478 | [] | no_license | yyyly/l110 | e8edfbab9600e1e154c8cec6d8220ed5ecbf5978 | 3361876192994b5a3ad906c5c0753ddbf19a0362 | refs/heads/master | 2020-09-28T01:58:41.569957 | 2020-08-22T02:16:54 | 2020-08-22T02:16:54 | 226,661,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include"mytimer.h"
myTimer::myTimer(QObject *parent)
:QTimer(parent)
{
}
myTimer::myTimer(LONG h, QObject *parent)
:QTimer(parent),handle(h)
{
connect(this,SIGNAL(timeout()),this,SLOT(finish()));
}
void myTimer::finish()
{
emit timeOut(handle);
}
| [
"1305892681@qq.com"
] | 1305892681@qq.com |
3f4a54b90b8649a932d081461242e2748111de42 | 902c38753580796b38443a48c807db531eb18d60 | /My practice in c++/adapter design pattern.cpp | 0d372209f65725da5051f6bab8cd7eaf732225d9 | [] | no_license | ibadeeCodes/All-About-C-plus | b6b189f4f2fb09b6ca85e2789de8da4a93997d39 | fe286f4cf93ea8a6c091baba8fba7d226e312c25 | refs/heads/master | 2020-04-14T13:29:40.232570 | 2019-01-02T18:32:27 | 2019-01-02T18:32:27 | 163,870,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include <iostream>
using namespace std;
class Circle
{
public:
virtual void draw() = 0;
};
class StandardCircle
{
public:
StandardCircle(double radius)
{
radius_ = radius;
cout << "StandardCircle: create. radius = "<< radius_ << endl;
}
void oldDraw()
{
cout << "StandardCircle: oldDraw. " << radius_ << endl;
}
private:
double radius_ ;
};
class CAdapter : public Circle, private StandardCircle //Adapter Class
{
public:
CAdapter( double diameter)
: StandardCircle(diameter/2)
{
cout << "CAdapter: create. diameter = " << diameter << endl;
}
virtual void draw()
{
cout << "CAdapter: draw." << endl;
oldDraw();
}
};
int main()
{
Circle* c = new CAdapter(14);
c->draw();
}
| [
"ibadeeshaikh@gmail.com"
] | ibadeeshaikh@gmail.com |
caa938368b9860650ac50bd06ea2536aa1e1e5cf | 8134cacd6e7c604a56d854727a68fc95797358de | /src/main/sdl2/rendersurface.hpp | 090300a4edde9aaa18d1622b4255dea3e2e691e2 | [] | no_license | lopespm/cannonball | 03d3d0febc09f9c0e3ea64679d45af8e6bea4f98 | 80d95e88daa82df7a77b615ae3fd1cf7584877f2 | refs/heads/master | 2021-01-21T01:20:23.606677 | 2016-10-03T22:10:18 | 2016-10-03T22:10:18 | 51,142,793 | 11 | 12 | null | 2016-02-05T11:26:58 | 2016-02-05T11:26:58 | null | UTF-8 | C++ | false | false | 1,194 | hpp | /***************************************************************************
SDL2 Hardware Surface Video Rendering.
Known Bugs:
- Software scanlines not implemented because we do hardware post-scaling
using the SDL_RenderCopy() rects from the original bitmap, so would not
look good at all because they would be ruined by magnifying.
Copyright Manuel Alfayate and Chris White.
See license.txt for more details.
***************************************************************************/
#pragma once
#include "renderbase.hpp"
class RenderSurface : public RenderBase
{
public:
RenderSurface();
~RenderSurface();
bool init(int src_width, int src_height,
int scale,
int video_mode,
int scanlines);
void disable();
bool start_frame();
bool finalize_frame();
void draw_frame(uint16_t* pixels);
private:
// SDL2 window
SDL_Window *window;
// SDL2 renderer
SDL_Renderer *renderer;
// SDL2 texture
SDL_Texture *texture;
// SDL2 blitting rects for hw scaling
// ratio correction using SDL_RenderCopy()
SDL_Rect src_rect;
SDL_Rect dst_rect;
};
| [
"redwindwanderer@gmail.com"
] | redwindwanderer@gmail.com |
111555f53c33fdf0713762f962e723c85f73e200 | b7f1b4df5d350e0edf55521172091c81f02f639e | /device/gamepad/gamepad_pad_state_provider.h | 62a8ccacf4a56b98b01e9e7bce2ef1744901eacd | [
"BSD-3-Clause"
] | permissive | blusno1/chromium-1 | f13b84547474da4d2702341228167328d8cd3083 | 9dd22fe142b48f14765a36f69344ed4dbc289eb3 | refs/heads/master | 2023-05-17T23:50:16.605396 | 2018-01-12T19:39:49 | 2018-01-12T19:39:49 | 117,339,342 | 4 | 2 | NOASSERTION | 2020-07-17T07:35:37 | 2018-01-13T11:48:57 | null | UTF-8 | C++ | false | false | 3,259 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_GAMEPAD_GAMEPAD_PAD_STATE_PROVIDER_H_
#define DEVICE_GAMEPAD_GAMEPAD_PAD_STATE_PROVIDER_H_
#include <stdint.h>
#include <limits>
#include <memory>
#include "device/gamepad/gamepad_export.h"
#include "device/gamepad/gamepad_standard_mappings.h"
#include "device/gamepad/public/cpp/gamepad.h"
namespace device {
class GamepadDataFetcher;
enum GamepadSource {
GAMEPAD_SOURCE_NONE = 0,
GAMEPAD_SOURCE_ANDROID,
GAMEPAD_SOURCE_GVR,
GAMEPAD_SOURCE_CARDBOARD,
GAMEPAD_SOURCE_LINUX_UDEV,
GAMEPAD_SOURCE_MAC_GC,
GAMEPAD_SOURCE_MAC_HID,
GAMEPAD_SOURCE_MAC_XBOX,
GAMEPAD_SOURCE_OCULUS,
GAMEPAD_SOURCE_OPENVR,
GAMEPAD_SOURCE_TEST,
GAMEPAD_SOURCE_WIN_XINPUT,
GAMEPAD_SOURCE_WIN_RAW,
};
enum GamepadActiveState {
GAMEPAD_INACTIVE = 0,
GAMEPAD_ACTIVE,
GAMEPAD_NEWLY_ACTIVE,
};
struct PadState {
// Which data fetcher provided this gamepad's data.
GamepadSource source;
// Data fetcher-specific identifier for this gamepad.
int source_id;
// Indicates whether or not the gamepad is actively being updated
GamepadActiveState active_state;
// Gamepad data, unmapped.
Gamepad data;
// Functions to map from device data to standard layout, if available. May
// be null if no mapping is available or needed.
GamepadStandardMappingFunction mapper;
// Sanitization masks
// axis_mask and button_mask are bitfields that represent the reset state of
// each input. If a button or axis has ever reported 0 in the past the
// corresponding bit will be set to 1.
// If we ever increase the max axis count this will need to be updated.
static_assert(Gamepad::kAxesLengthCap <=
std::numeric_limits<uint32_t>::digits,
"axis_mask is not large enough");
uint32_t axis_mask;
// If we ever increase the max button count this will need to be updated.
static_assert(Gamepad::kButtonsLengthCap <=
std::numeric_limits<uint32_t>::digits,
"button_mask is not large enough");
uint32_t button_mask;
};
class DEVICE_GAMEPAD_EXPORT GamepadPadStateProvider {
public:
GamepadPadStateProvider();
virtual ~GamepadPadStateProvider();
// Gets a PadState object for the given source and id. If the device hasn't
// been encountered before one of the remaining slots will be reserved for it.
// If no slots are available will return NULL.
PadState* GetPadState(GamepadSource source, int source_id);
// Gets a PadState object for a connected gamepad by specifying its index in
// the pad_states_ array. Returns NULL if there is no connected gamepad at
// that index.
PadState* GetConnectedPadState(int pad_index);
protected:
void ClearPadState(PadState& state);
void InitializeDataFetcher(GamepadDataFetcher* fetcher);
void MapAndSanitizeGamepadData(PadState* pad_state,
Gamepad* pad,
bool sanitize);
// Tracks the state of each gamepad slot.
std::unique_ptr<PadState[]> pad_states_;
};
} // namespace device
#endif // DEVICE_GAMEPAD_GAMEPAD_PAD_STATE_PROVIDER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
1b38ea63dfdec4dfc200ea79bebe28e655fbb299 | d4edd187959684ffb592510847833f2365f254c8 | /includes/Shapes.h | 1402d76c7c6c1eaa97d4405666712998f8aa9e91 | [] | no_license | costashatz/SimpleRaytracer | 8463d6eb193a408a5fa7892ab34f3afdd50c7f6e | b8f882d635017779989c5fd49e19971f98c3d11e | refs/heads/master | 2021-01-13T02:11:47.620915 | 2014-02-05T09:10:11 | 2014-02-05T09:10:11 | 16,525,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,249 | h | #pragma once
#include "LocalGeo.h"
#include "Ray.h"
//Shape class
class Shape
{
public:
virtual bool intersect(Ray& ray, float* thit, LocalGeo* local) { return false; }
virtual bool intersectP(Ray& ray)
{
float temp;
LocalGeo l;
return intersect(ray,&temp,&l);
}
};
//Triangle
class Triangle : public Shape
{
private:
Point p0,p1,p2;
public:
Triangle() {}
Triangle(Point _p0, Point _p1, Point _p2)
{
p0 = _p0;
p1 = _p1;
p2 = _p2;
}
bool intersect(Ray& ray, float* thit, LocalGeo* local)
{
vec3 e1 = p1-p0, e2 = p2-p0, p, s, q;
float tmp, t, u, v, epsilon = 0.000001;
p = glm::cross(ray.Direction(),e2);
tmp = glm::dot(p,e1);
if(tmp>-epsilon && tmp < epsilon)
return false;
tmp = 1.f/tmp;
s = ray.Position()-p0;
u = tmp*glm::dot(s,p);
if(u<0.0 || u>1.0)
return false;
q = glm::cross(s,e1);
v = tmp*glm::dot(ray.Direction(),q);
if(v<0.0 || u+v>1.0)
return false;
t = tmp*glm::dot(e2,q);
Point P = ray.Position()+t*ray.Direction();
vec3 n = glm::normalize(glm::cross(e1,e2));
if(t<ray.Min() || t>ray.Max())
return false;
*thit = t;
*local = LocalGeo(P, n);
return true;
}
};
//Sphere
class Sphere : public Shape
{
private:
Point center;
float radius;
public:
Sphere():center(Point()),radius(0.0) {}
Sphere(Point c, float r):center(c),radius(r) {}
bool intersect(Ray& ray, float* thit, LocalGeo* local)
{
float a,b,c, discrm, t;
vec3 pMinusC = ray.Position()-center;
a = glm::dot(ray.Direction(),ray.Direction());
b = 2.0*glm::dot(ray.Direction(),pMinusC);
c = glm::dot(pMinusC,pMinusC)-radius*radius;
discrm = b*b-4*a*c;
if(discrm<0.f)
return false;
float t1 = (-b+sqrt(discrm))/(2*a);
float t2 = (-b-sqrt(discrm))/(2*a);
if(t1>=0.0&&t2>=0.0)
{
t = t1;
if(t2<t1)
t = t2;
}
else
{
if(t1>=0.0)
t = t1;
else if(t2>=0.0)
t = t2;
else
return false;
}
if(t<ray.Min() || t>ray.Max())
return false;
Point temp = ray.Position()+t*ray.Direction();
vec3 n = glm::normalize(temp-center);
*thit = t;
*local = LocalGeo(temp, n);
return true;
}
};
//TriangleNormal
class TriangleNormal : public Shape
{
private:
Point p0,p1,p2;
vec3 n0,n1,n2;
public:
TriangleNormal() {}
TriangleNormal(Point _p0, Point _p1, Point _p2, vec3 _n0, vec3 _n1, vec3 _n2)
{
p0 = _p0;
p1 = _p1;
p2 = _p2;
n0 = _n0;
n1 = _n1;
n2 = _n2;
}
bool intersect(Ray& ray, float* thit, LocalGeo* local)
{
vec3 e1 = p1-p0, e2 = p2-p0, p, s, q;
float tmp, t, u, v, epsilon = 0.000001;
p = glm::cross(ray.Direction(),e2);
tmp = glm::dot(p,e1);
if(tmp>-epsilon && tmp < epsilon)
return false;
tmp = 1.f/tmp;
s = ray.Position()-p0;
u = tmp*glm::dot(s,p);
if(u<0.0 || u>1.0)
return false;
q = glm::cross(s,e1);
v = tmp*glm::dot(ray.Direction(),q);
if(v<0.0 || u+v>1.0)
return false;
t = tmp*glm::dot(e2,q);
Point P = ray.Position()+t*ray.Direction();
float w = 1-u-v;
vec3 n = glm::normalize(w*n0+u*n1+v*n2);
if(t<ray.Min() || t>ray.Max())
return false;
*thit = t;
*local = LocalGeo(P, n);
return true;
}
}; | [
"costas@costas-Xubuntu.(none)"
] | costas@costas-Xubuntu.(none) |
a4c738092670555d782242981acc39cf48ad0f2b | aec7485b03ce1883db548f26b71b4fda2555130d | /GLSLCookbook/GLSLProgram.cpp | edbe9e714d7643b2a551f19a12f6a21f858bd85a | [] | no_license | Sunnyoung/OpenGL-Shading-Cookbook | d5d7a6071a21063ca3b068ff26926869fda34fd5 | 0a25c436e2b9948871b3a814eb966eb5121b6c98 | refs/heads/master | 2016-09-11T02:25:49.814410 | 2014-03-02T13:22:33 | 2014-03-02T13:22:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,565 | cpp | #include "GLSLProgram.h"
#include <fstream>
#include <sstream>
using namespace glm;
using namespace std;
GLSLProgram::GLSLProgram(const std::string &vertexfile, const std::string &fragfile) : mIsDebug(true){
mProgram = createProgram(vertexfile, fragfile);
use();
}
GLSLProgram::~GLSLProgram(void){
}
void GLSLProgram::setUniform( const std::string &name, const glm::mat4 &mat ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniformMatrix4fv(loc, 1, GL_FALSE, &mat[0][0]);
}
void GLSLProgram::setUniform( const std::string &name, const glm::mat3 &mat ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniformMatrix3fv(loc, 1, GL_FALSE, &mat[0][0]);
}
void GLSLProgram::setUniform( const std::string &name, const glm::vec4 &vec ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform4fv(loc, 1, &vec[0]);
}
void GLSLProgram::setUniform( const std::string &name, float x, float y, float z, float w ){
setUniform(name, vec4(x, y, z, w));
}
void GLSLProgram::setUniform( const std::string &name, const glm::vec3 &vec ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform3fv(loc, 1, &vec[0]);
}
void GLSLProgram::setUniform( const std::string &name, float x, float y, float z ){
setUniform(name, vec3(x, y, z));
}
void GLSLProgram::setUniform( const std::string &name, float value ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform1f(loc, value);
}
void GLSLProgram::setUniform( const std::string &name, int value ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform1i(loc, value);
}
void GLSLProgram::use(){
glUseProgram(mProgram);
}
GLuint GLSLProgram::createShader( GLenum shadertype, std::string filename ){
ifstream inFile( filename );
if (!inFile) {
fprintf(stderr, "Error opening file : %s \n", filename.c_str() );
exit(1);
}
std::stringstream code;
code << inFile.rdbuf();
inFile.close();
string codeStr(code.str());
GLuint shader = glCreateShader( shadertype );
if (0 == shader) {
fprintf(stderr, "Error creating vertex shader.\n");
exit(EXIT_FAILURE);
}
// Load the source code into the shader object
const GLchar* codeArray[] = {codeStr.c_str()};
glShaderSource(shader, 1, codeArray, NULL);
// Compile the shader
glCompileShader( shader );
// Check compilation status
GLint result;
glGetShaderiv( shader, GL_COMPILE_STATUS, &result );
if( GL_FALSE == result ) {
string type;
GL_VERTEX_SHADER == shadertype ? type = "Vertex Shader" : type = "Fragment Shader";
fprintf( stderr, "%s compilation failed!\n", type.c_str());
GLint logLen;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logLen );
if (logLen > 0) {
char * log = (char *)malloc(logLen);
GLsizei written;
glGetShaderInfoLog(shader, logLen, &written, log);
fprintf(stderr, "Shader log: \n%s", log);
free(log);
}
glDeleteShader(shader);
}
return shader;
}
GLuint GLSLProgram::createProgram( const std::string &vertexfile, const std::string &fragfile ){
GLuint vertexShader = createShader(GL_VERTEX_SHADER, vertexfile);
GLuint fragShader = createShader(GL_FRAGMENT_SHADER, fragfile);
GLuint program = glCreateProgram();
if(0 == program) {
fprintf(stderr, "Error creating program object.\n");
exit(1);
}
// Bind index 0 to the shader input variable "VertexPosition"
//glBindAttribLocation(programHandle, 0, "VertexPosition");
// Bind index 1 to the shader input variable "VertexColor"
//glBindAttribLocation(programHandle, 1, "VertexColor");
// Attach the shaders to the program object
glAttachShader( program, vertexShader );
glAttachShader( program, fragShader );
// Link the program
glLinkProgram( program );
// Check for successful linking
GLint status;
glGetProgramiv( program, GL_LINK_STATUS, &status );
if (GL_FALSE == status) {
fprintf( stderr, "Failed to link shader program!\n" );
GLint logLen;
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLen );
if (logLen > 0) {
char * log = (char *)malloc(logLen);
GLsizei written;
glGetProgramInfoLog(program, logLen, &written, log);
fprintf(stderr, "Program log: \n%s", log);
free(log);
}
glDeleteProgram(program);
}
return program;
}
void GLSLProgram::checkLocation( const std::string &name, int location ){
if(location < 0 && mIsDebug)
fprintf(stderr, "location of %s is not valid. please checkout the %s \n", name.c_str(), name.c_str());
}
| [
"wuqiyang429@gmail.com"
] | wuqiyang429@gmail.com |
fdec1fe99af01d7e9050729f9deb1c1d8125932e | b71f6e948c3a74a6cb9713e61cf4035fb3f6cc79 | /CleanSFML/mission.h | 57c4496870f5114924e6ba3dd9f73d4465a86054 | [] | no_license | LowColor/myfight | 14a10dd30b1bbd38c7aa2e9cfcd4758ea077d1d2 | 9337fb09d8a40b97a377747e59264613a7839c81 | refs/heads/master | 2020-03-19T22:09:51.467400 | 2018-06-11T17:43:51 | 2018-06-11T17:43:51 | 136,961,112 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,750 | h |
///////////////////////////////////НОМЕР МИССИИ//////////////////////////////////
int getCurrentMission(int x)//ф-ция номера миссия, которая меняет номер миссии, в зависимости от координаты игрока Х (сюда будем передавать эту координату)
{
int mission = 0;
if ((x>0) && (x<400)) { mission = 0; } //знакомим игрока с игрой
if (x>400) { mission = 1; } //игрок на первой миссии
if (x>700) { mission = 2; }//2ой
if (x>2200) { mission = 3; }//и тд
return mission;//ф-ция возвращает номер миссии
}
/////////////////////////////////////ТЕКСТ МИССИИ/////////////////////////////////
std::string getTextMission(int currentMission) {
std::string missionText = "";//текст миссии и его инициализация
switch (currentMission)//принимается номер миссии и в зависимости от него переменной missionText присваивается различный текст
{
case 0: missionText = "\nНачальный этап и \nинструкции к игре"; break;
case 1: missionText = "\nMission 1\n\nВот твоя первая\n миссия, на\n этом уровне \nтебе стоит опасаться\n ... бла-бла-бла ..."; break;
case 2: missionText = "\nMission 2\n Необходимо решить\n логическую задачку,\n чтобы пройти дальше "; break;
case 3: missionText = "\nИ так далее \nи тому подобное....."; break;
}
return missionText;//ф-ция возвращает текст
}; | [
"desir7777@gmail.com"
] | desir7777@gmail.com |
d8e06d05484dba9cd164fa3c6b5f69d43bb0d83e | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mameppk/src/emu/bus/a2bus/a2estd80col.h | 0d85af21a8d022ab032bb36e75fc4a2f1a04ea8e | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | h | // license:BSD-3-Clause
// copyright-holders:R. Belmont
/*********************************************************************
a2estd80col.c
Apple IIe Standard 80 Column Card
*********************************************************************/
#ifndef __A2EAUX_STD80COL__
#define __A2EAUX_STD80COL__
#include "emu.h"
#include "a2eauxslot.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
class a2eaux_std80col_device:
public device_t,
public device_a2eauxslot_card_interface
{
public:
// construction/destruction
a2eaux_std80col_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
a2eaux_std80col_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source);
protected:
virtual void device_start();
virtual void device_reset();
virtual UINT8 read_auxram(UINT16 offset);
virtual void write_auxram(UINT16 offset, UINT8 data);
virtual UINT8 *get_vram_ptr();
virtual UINT8 *get_auxbank_ptr();
virtual bool allow_dhr() { return false; } // we don't allow DHR
private:
UINT8 m_ram[2*1024];
};
// device type definition
extern const device_type A2EAUX_STD80COL;
#endif /* __A2EAUX_STD80COL__ */
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
895c81d739b8ff1d1a2f9c7c81697fdd002cabc9 | fc9509b72acc753eaae129a1fcb27cd9f8ee56b0 | /zhengtu/libscenesserver/Trade.cpp | fd6c3b502901013c0e9abf5df6fdcc8d6f873e79 | [] | no_license | edolphin-ydf/hydzhengtu | 25df5567226c5b7533e24631ae3d641ee0182aa9 | 724601751c00702438ffb93c1411226ae21f46a0 | refs/heads/master | 2020-12-31T03:25:48.625000 | 2012-10-24T10:58:00 | 2012-10-24T10:58:00 | 49,243,199 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 69,523 | cpp | #include <zebra/ScenesServer.h>
PrivateStore::PrivateStore() : _step(NONE)
{
}
PrivateStore::~PrivateStore()
{
clear();
_step = NONE;
}
void PrivateStore::step(STEP step_,SceneUser *pUser)
{
_step = step_;
if (_step == BEGIN) {
pUser->setUState(Cmd::USTATE_SITDOWN);
pUser->setUState(Cmd::USTATE_PRIVATE_STORE);
}
if (_step == NONE) {
pUser->clearUState(Cmd::USTATE_PRIVATE_STORE);
pUser->clearUState(Cmd::USTATE_SITDOWN);
clear();
}
}
PrivateStore::STEP PrivateStore::step()
{
return _step;
}
void PrivateStore::clear()
{
_items.clear();
}
void PrivateStore::add(zObject* ob,DWORD money,BYTE x,BYTE y)
{
_items[ob->data.qwThisID] = SellInfo(ob,money,x,y);
}
void PrivateStore::remove(DWORD id)
{
_items.erase(id);
}
void PrivateStore::show(SceneUser* target)
{
#if 0
std::map<DWORD,SellInfo>::iterator it = _items.begin();
for ( ; it!=_items.end(); ++it) {
Cmd::stAddObjectSellUserCmd cmd;
cmd.object = (*it).second.object()->data;
cmd.price = (*it).second.money();
cmd.x = (*it).second.x();
cmd.y = (*it).second.y();
target->sendCmdToMe(&cmd,sizeof(cmd));
}
#else
using namespace Cmd;
std::map<DWORD,SellInfo>::iterator it = _items.begin();
char buffer[zSocket::MAX_USERDATASIZE];
stAddObjectSellListUserCmd *cmd = (stAddObjectSellListUserCmd *)buffer;
constructInPlace(cmd);
for ( ; it!=_items.end(); ++it) {
if (sizeof(stAddObjectSellListUserCmd) + (cmd->num + 1) * sizeof(cmd->list[0])>= zSocket::MAX_USERDATASIZE)
{
target->sendCmdToMe(cmd,sizeof(stAddObjectSellListUserCmd) + cmd->num * sizeof(cmd->list[0]));
cmd->num = 0;
}
cmd->list[cmd->num].object = (*it).second.object()->data;
cmd->list[cmd->num].price = (*it).second.money();
cmd->list[cmd->num].x = (*it).second.x();
cmd->list[cmd->num].y = (*it).second.y();
cmd->num ++;
}
if (cmd->num)
{
target->sendCmdToMe(cmd,sizeof(Cmd::stAddObjectSellListUserCmd) + cmd->num * sizeof(cmd->list[0]));
cmd->num = 0;
}
#endif
Cmd::stSellTradeUserCmd ret;
target->sendCmdToMe(&ret,sizeof(ret));
}
PrivateStore::SellInfo* PrivateStore::sell_ob(DWORD id)
{
std::map<DWORD,SellInfo>::iterator it = _items.find(id);
if (it != _items.end()) {
return &(it->second);
}
return NULL;
}
TradeOrder::TradeOrder(SceneUser* owner) : _me(owner),_target(NULL),_targetid(0),_money(0)
{
finish();
}
TradeOrder::~TradeOrder()
{
reset();
}
void TradeOrder::reset()
{
SceneUser *pUser=_me->scene->getUserByID(_targetid);
if (pUser && (pUser == _target) && _target->tradeorder.target() == _me)
{
_target->tradeorder.finish();
Cmd::stCancelTradeUserCmd cancel;
cancel.dwUserTempID = _target->tempid;
_target->sendCmdToMe(&cancel,sizeof(cancel));
Channel::sendSys(_target,Cmd::INFO_TYPE_FAIL,"交易被取消");
Zebra::logger->info("[交易:玩家<------>玩家]%s取消与%s的交易",_me->name,_target->name);
}
else
{
if (_targetid)
{
Zebra::logger->debug("[交易:玩家<------>玩家]%s取消与%d的交易,但这个人已经不在了",_me->name,_targetid);
}
}
}
void TradeOrder::cancel()
{
// Channel::sendSys(_me,Cmd::INFO_TYPE_FAIL,"交易被取消");
Cmd::stCancelTradeUserCmd cancel;
cancel.dwUserTempID = _me->tempid;
_me->sendCmdToMe(&cancel,sizeof(cancel));
reset();
finish();
}
SceneUser* TradeOrder::target() const
{
return _target;
}
bool TradeOrder::can_trade()
{
if (_target->packs.uom.space(_target) < (int)_items.size() ||!_me->packs.checkMoney( _money) ) {
return false;
}
return true;
}
void TradeOrder::trade()
{
bool changed = false;
for (std::map<DWORD,zObject*>::iterator it=_items.begin(); it!=_items.end(); ++it) {
_me->packs.removeObject(it->second,false,false); //not delete and not notify
if (it->second->data.pos.loc() == Cmd::OBJECTCELLTYPE_EQUIP) {
changed = true;
}
it->second->data.exp = 0;
/*
it->second->data.pos.dwLocation = Cmd::OBJECTCELLTYPE_COMMON;
if (_target->packsaddObject(it->second,true)) {
*/
if (_target->packs.addObject(it->second,true,AUTO_PACK)) {
zObject::logger(it->second->createid,it->second->data.qwThisID,it->second->data.strName,it->second->data.dwNum,it->second->data.dwNum,0,_me->id,_me->name,_target->id,_target->name,"trade_ok",NULL,0,0);
Zebra::logger->info("[交易:玩家<------>玩家]用户%s交易%s给%s成功",_me->name,it->second->data.strName,_target->name);
Cmd::stAddObjectPropertyUserCmd ret;
ret.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&it->second->data,&ret.object,sizeof(ret.object),sizeof(ret.object));
_target->sendCmdToMe(&ret,sizeof(ret));
}else {
zObject::logger(it->second->createid,it->second->data.qwThisID,it->second->data.strName,it->second->data.dwNum,0,0,_me->id,_me->name,_target->id,_target->name,"trade_err",it->second->base,it->second->data.kind,it->second->data.upgrade);
Zebra::logger->info("[交易:玩家<------>玩家]用户%s交易%s给%s失败",_me->name,it->second->data.strName,_target->name);
}
}
if (changed) {
_me->packs.equip.calcAll();
_me->setupCharBase();
Cmd::stMainUserDataUserCmd userinfo;
_me->full_t_MainUserData(userinfo.data);
_me->sendCmdToMe(&userinfo,sizeof(userinfo));
_me->sendMeToNine();
}
/*
zObject* m_gold = _me->packs.getGold();
m_gold->data.dwNum -= _money;
if (_money) {
zObject* t_gold = _target->packs.getGold();
if (t_gold->base->maxnum - t_gold->data.dwNum > (DWORD)_money) {
t_gold->data.dwNum += _money;
}else {
t_gold->data.dwNum = t_gold->base->maxnum;
}
}
*/
if (_money) {
_me->packs.removeMoney(_money,"交易");
_target->packs.addMoney(_money,"交易");
Zebra::logger->info("[交易:玩家<------>玩家]用户%s交易银子%d给%s",_me->name,_money,_target->name);
}
}
bool TradeOrder::canRequest()
{
return (_target == NULL);
}
void TradeOrder::ready(SceneUser* target)
{
_target = target;
_targetid = target->id;
}
bool TradeOrder::canAnswer()
{
return (_target!=NULL && !begined);
}
void TradeOrder::begin()
{
begined = true;
}
bool TradeOrder::hasBegin()
{
return begined;
}
bool TradeOrder::commit()
{
if (begined)
{
commited = true;
return true;
}
return false;
}
void TradeOrder::rollback()
{
commited = false;
}
bool TradeOrder::hasCommit()
{
return commited;
}
void TradeOrder::finish()
{
if (_me->name[0] && _targetid) Zebra::logger->info("[交易:玩家<------>玩家]%s的交易状态完成",_me->name);
_targetid=0;
_target = NULL;
_money = 0;
commited = false;
lastmove= 0;
begined = false;
clear();
}
void TradeOrder::clear()
{
_items.clear();
}
void TradeOrder::add_money(DWORD money)
{
_money = money;
Zebra::logger->info("[交易:玩家<------>玩家]用户%s对%s更改交易银子数量(%d)",_me->name,_target->name,money);
}
void TradeOrder::add(zObject* ob)
{
_items[ob->data.qwThisID] = ob;
Zebra::logger->info("[交易:玩家<------>玩家]用户%s对%s添加交易物品%s(%d)",_me->name,_target->name,ob->data.strName,ob->data.qwThisID);
}
void TradeOrder::remove(DWORD id)
{
std::map<DWORD,zObject*>::iterator it = _items.find(id);
if (it != _items.end()) {
Zebra::logger->info("[交易:玩家<------>玩家]用户%s对%s删除交易物品%s(%d)",_me->name,_target->name,it->second->data.strName,it->second->data.qwThisID);
_items.erase(it);
}
}
bool TradeOrder::in_trade(zObject* ob) const
{
std::map<DWORD,zObject*>::const_iterator it = _items.find(ob->data.qwThisID);
return it != _items.end();
}
#define ISPROPERTY(value) if (ob->data.value!=0) ++num
WORD get_prop_num(zObject* ob)
{
WORD num = 0;
ISPROPERTY(fivepoint);
ISPROPERTY(maxmp);
ISPROPERTY(mvspeed);
ISPROPERTY(bang);
ISPROPERTY(hpr);
ISPROPERTY(mpr);
ISPROPERTY(spr);
ISPROPERTY(akspeed);
ISPROPERTY(pdam);
ISPROPERTY(pdef);
ISPROPERTY(mdam);
ISPROPERTY(mdef);
ISPROPERTY(atrating);
ISPROPERTY(akdodge);
ISPROPERTY(poisondef);
ISPROPERTY(lulldef);
ISPROPERTY(reeldef);
ISPROPERTY(evildef);
ISPROPERTY(bitedef);
ISPROPERTY(chaosdef);
ISPROPERTY(colddef);
ISPROPERTY(petrifydef);
ISPROPERTY(blinddef);
ISPROPERTY(stabledef);
ISPROPERTY(slowdef);
ISPROPERTY(luredef);
ISPROPERTY(skill[0].point);
ISPROPERTY(skills.point);
ISPROPERTY(holy);
ISPROPERTY(hpleech.odds);
ISPROPERTY(mpleech.odds);
ISPROPERTY(hptomp);
ISPROPERTY(dhpp);
ISPROPERTY(dmpp);
ISPROPERTY(incgold);
ISPROPERTY(doublexp);
ISPROPERTY(mf);
ISPROPERTY(dpdam);
ISPROPERTY(dmdam);
ISPROPERTY(bdam);
ISPROPERTY(rdam);
ISPROPERTY(ignoredef);
ISPROPERTY(poison);
ISPROPERTY(lull);
ISPROPERTY(reel);
ISPROPERTY(evil);
ISPROPERTY(bite);
ISPROPERTY(chaos);
ISPROPERTY(cold);
ISPROPERTY(petrify);
ISPROPERTY(blind);
ISPROPERTY(stable);
ISPROPERTY(slow);
ISPROPERTY(lure);
return num;
}
float get_kind_bonus(BYTE kind)
{
float bonus = 0.0f;
if (kind & 0x4)
{
bonus = 2.0f;
}
else if (kind & 0x2)
{
bonus = 1.5f;
}
else if (kind & 0x1)
{
bonus = 1.2f;
}
else
bonus = 1.0f;
return bonus;
}
float get_sell_dur_rate(zObject* ob)
{
if (!ob->data.maxdur) return 1;
return (float)((ob->data.dur+49)/50) / ((ob->base->durability+49)/50) ;
}
float get_repair_dur_rate(zObject* ob)
{
if (!ob->data.maxdur) return 1;
float temp=(float)(((ob->data.maxdur - ob->data.dur)+49)/50) / ((ob->base->durability+49)/50) ;
//Zebra::logger->debug("get_repair_dur_rate=%f",temp);
return temp;
return (float)(((ob->data.maxdur - ob->data.dur)+49)/50) / ((ob->base->durability+49)/50) ;
//return 1 - get_sell_dur_rate(ob);
}
float get_sell_price(zObject* ob)
{
float money = 0;
if (!ob) return money;
money = (0.25*ob->base->price*(1+get_prop_num(ob)*0.1f)*get_kind_bonus(ob->data.kind));
if (money > 0 ) money += 1;
//Zebra::logger->debug("get_sell_price=%f",money);
return money;
}
DWORD get_sell_price_by_dur(zObject* ob)
{
return (DWORD)(get_sell_price(ob)*get_sell_dur_rate(ob));
}
DWORD get_repair_price(zObject* ob)
{
DWORD money = 0;
if (!ob) return money;
money = (DWORD)(2*get_sell_price(ob)*get_repair_dur_rate(ob));
return money;
}
bool SceneUser::do_trade_rs_cmd(const Cmd::stTradeUserCmd *rev,DWORD cmdLen)
{
Cmd::stRequestSellBuyUserCmd* cmd = (Cmd::stRequestSellBuyUserCmd *)rev;
if (cmd->temp_id == tempid) {
return true;
}
SceneUser *target = scene->getUserByTempID(cmd->temp_id);
if (!target || target->privatestore.step() != PrivateStore::BEGIN) {
Zebra::logger->warn("%s(%ld)请求购买摆摊物品的用户不存在或者没有摆摊",name,id);
return true;
}
if (abs((long)(pos.x- target->getPos().x)) > (SCREEN_WIDTH ) || abs((long)(pos.y-target->getPos().y)) > (SCREEN_HEIGHT)) {
return true;
}
PrivateStore::SellInfo* sf = target->privatestore.sell_ob(cmd->object_id);
if (!sf || !sf->object() ) {
Zebra::logger->debug("%s(%ld)请求购买摆摊物品不存在",name,id);
return true;
}
if (packs.uom.space(this) < 1) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"包裹空间不足");
}
if (packs.checkMoney(sf->money()) && target->packs.removeObject(sf->object(),true,false) ) //notify but not delete)
{
packs.addObject(sf->object(),true,AUTO_PACK);
//notify client about add
zObject::logger(sf->object()->createid,sf->object()->data.qwThisID,sf->object()->data.strName,sf->object()->data.dwNum,sf->object()->data.dwNum,0,target->id,target->name,this->id,this->name,"摆摊",NULL,0,0);
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&(sf->object()->data),&ret1.object,sizeof(t_Object),sizeof(ret1.object));
sendCmdToMe(&ret1,sizeof(ret1));
//compute money
target->packs.addMoney(sf->money(),"摆摊");
packs.removeMoney(sf->money(),"摆摊");
//clear from list
target->privatestore.remove(cmd->object_id);
}
return true;
}
bool SceneUser::doTradeCmd(const Cmd::stTradeUserCmd *rev,DWORD cmdLen)
{
using namespace Cmd;
switch(rev->byParam)
{
/// 领赠品品精致升级宝石
case GOLD_GIVE_USERCMD_PARAMETER:
{
Zebra::logger->debug("收到指令");
stGoldGiveTradeUserCmd *rett = ( Cmd::stGoldGiveTradeUserCmd * )rev;
Zebra::logger->debug("%d是收到的类型",rett->type);
if (rett->type == STORN)
{
if (this->charbase.goldgive == 0 && this->Card_num>0)
{
this->Card_num --;
if (this->Card_num > 60000)
this->Card_num = 0;
this->charbase.goldgive += 70;
if (this->charbase.goldgive>70)
this->charbase.goldgive = 70;
}
if (this->charbase.goldgive)
{
if (this->packs.uom.space(this))
{
zObjectB *base = objectbm.get(795);
if (base)
{
zObject *o = zObject::create(base,1);
if (o)
{
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,1,1,0,NULL,this->id,this->name,"赠品",o->base,o->data.kind,o->data.upgrade);
packs.addObject(o,true,AUTO_PACK);
this->charbase.goldgive--;
// if (this->charbase.goldgive > 70)
// this->charbase.goldgive = 0;
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&ret1.object,sizeof(t_Object),sizeof(ret1.object));
sendCmdToMe(&ret1,sizeof(ret1));
stReturnGoldGiveTradeUserCmd ret;
ret.Storn_num=this->charbase.goldgive;
ret.Matarial_num=this->Give_MatarialNum;
ret.Card_num=this->Card_num;
sendCmdToMe(&ret,sizeof(ret));
}
}
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满,领取精致升级宝石失败");
}
}
}
else
{
if (this->Give_MatarialNum == 0 && this->Card_num>0)
{
this->Card_num --;
if (this->Card_num >60000)
this->Card_num = 0;
this->Give_MatarialNum +=6;
if (this->Give_MatarialNum > 6)
this->Give_MatarialNum = 6;
}
if (this->Give_MatarialNum)
{
DWORD Matarial_id = 0;
switch(rett->type){
case SIVER :
{ Matarial_id = 517;}
break;
case SILK :
{ Matarial_id = 507;}
break;
case CRYSTAL:
{ Matarial_id = 527;}
break;
case EBONY :
{ Matarial_id = 537;}
break;
case YINGPI :
{ Matarial_id = 547;}
break;
default :
break;}
if (this->packs.uom.space(this))
{
zObjectB *base = objectbm.get(Matarial_id);
if (base)
{
zObject *o = zObject::create(base,50,0);
if (o)
{
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,1,1,0,NULL,this->id,this->name,"赠品",o->base,o->data.kind,o->data.upgrade);
packs.addObject(o,true,AUTO_PACK);
this->Give_MatarialNum--;
if (this->Give_MatarialNum > 6)
Give_MatarialNum = 0;
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&ret1.object,sizeof(t_Object),sizeof(ret1.object));
sendCmdToMe(&ret1,sizeof(ret1));
stReturnGoldGiveTradeUserCmd ret;
ret.Storn_num=this->charbase.goldgive;
ret.Matarial_num=this->Give_MatarialNum;
ret.Card_num=this->Card_num;
sendCmdToMe(&ret,sizeof(ret));
}
}
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满,领取材料赠品失败");
}
}
}
return true;
}
break;
case REQUEST_GOLD_GIVE_USERCMD_PARAMETER:
{
stReturnGoldGiveTradeUserCmd ret;
ret.Storn_num=this->charbase.goldgive;
ret.Matarial_num=this->Give_MatarialNum;
ret.Card_num=this->Card_num;
sendCmdToMe(&ret,sizeof(ret));
return true;
}
break;
/* ////领赠品 材料
case MATARIAL_GIVE_USERCMD_PARAMETER:
{
if (this->Give_MatarialNum)
{
if (this->packs.uom.space(this))
{
zObjectB *base = objectbm.get(795);
if (base)
{
zObject *o = zObject::create(base,1);
if (o)
{
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data
.dwNum,1,1,0,NULL,this->id,this->name,"赠品",o->base,o->data.kind,o->data.upgrade);
packs.addObject(o,true,AUTO_PACK);
this->Give_MatarialNum--;
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&ret1.object,sizeof(t_Object));
sendCmdToMe(&ret1,sizeof(ret1));
}
}
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满,领取精致升级宝石失败");
}
}
return true;
}
break;
case REQUEST_MATARIAL_GIVE_USERCMD_PARAMETER:
{
stReturnMatarialGiveTradeUserCmd ret;
ret.num=this->Give_MatarialNum;
sendCmdToMe(&ret,sizeof(ret));
return true;
}
break;
*/
case REQUEST_TRADE_USERCMD_PARAMETER:
{
stRequestTradeUserCmd *request=(stRequestTradeUserCmd *)rev;
if (tradeorder.canRequest())
{
if (request->dwAnswerTempID==tempid)
{
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)向自己请求交易",name,id);
return true;
}
SceneUser *pAnswer=scene->getUserByTempID(request->dwAnswerTempID);
if (pAnswer)
{
if (!isset_state(pAnswer->sysSetting,USER_SETTING_TRADE))
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方交易未开启");
return true;
}
if (abs((long)(pos.x- pAnswer->getPos().x)) > (SCREEN_WIDTH >> 1) || abs((long)(pos.y-pAnswer->getPos().y)) > (SCREEN_HEIGHT >> 1)) {
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"距离太远,不能交易!");
return true;
}
if (mask.is_masking() || pAnswer->mask.is_masking()) {
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"蒙面人不可交易 !");
return true;
}
//mask.on_trade();
Zebra::logger->info("[交易:玩家<------>玩家]%s(%ld)请求%s(%ld)交易",name,id,pAnswer->name,pAnswer->id);
if (pAnswer->tradeorder.canRequest())
{
tradeorder.ready(pAnswer);
pAnswer->tradeorder.ready(this);
stRequestTradeUserCmd req;
req.dwAskerTempID = tempid;
req.dwAnswerTempID = pAnswer->tempid;
pAnswer->sendCmdToMe(&req,sizeof(req));
return true;
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不能交易接受你的请求",name);
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不在!");
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)不能请求交易时请求交易",name,id);
return true;
}
break;
case ANSWER_TRADE_USERCMD_PARAMETER:
{
stAnswerTradeUserCmd *answer=(stAnswerTradeUserCmd *)rev;
if (tradeorder.canAnswer())
{
SceneUser *pAsker=tradeorder.target();
if (!pAsker)
{
tradeorder.finish();
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不在了");
return true;
}
if (abs((long)(pos.x- pAsker->getPos().x)) > (SCREEN_WIDTH >> 1) || abs((long)(pos.y-pAsker->getPos().y)) > (SCREEN_HEIGHT >> 1)) {
tradeorder.cancel();
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"距离太远,不能交易!");
return true;
}
Zebra::logger->info("[交易:玩家<------>玩家]%s(%ld)应答%s(%ld)的交易",name,id,pAsker->name,pAsker->id);
if (pAsker->tradeorder.canAnswer() && pAsker->tradeorder.target()==this)
{
if (answer->byAgree)
{
tradeorder.begin();
pAsker->tradeorder.begin();
stBeginTradeUserCmd begin;
begin.dwAskerTempID=pAsker->tempid;
begin.dwAnswerTempID=tempid;
pAsker->sendCmdToMe(&begin,sizeof(begin));
sendCmdToMe(&begin,sizeof(begin));
// 发送现有物品到对方
//packs.trademyself->sendAllToAnother();
//pAsker->packs.trademyself->sendAllToAnother();
}
else
{
tradeorder.finish();
pAsker->tradeorder.finish();
Channel::sendSys(pAsker,Cmd::INFO_TYPE_FAIL,"对方不同意和你交易");
}
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)交易应答另一个用户",name,id);
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)不能应答交易时应答交易",name,id);
return true;
}
break;
case COMMIT_TRADE_USERCMD_PARAMETER:
{
if (tradeorder.commit())
{
SceneUser *pAnother = tradeorder.target();
if (pAnother)
{
if (pAnother->tradeorder.hasCommit())
{
//packs.trade();
//pAnother->packs.trade();
if (tradeorder.can_trade() && pAnother->tradeorder.can_trade() ) {
stFinishTradeUserCmd finish;
pAnother->sendCmdToMe(&finish,sizeof(finish));
sendCmdToMe(&finish,sizeof(finish));
tradeorder.trade();
pAnother->tradeorder.trade();
}else {
stCancelTradeUserCmd cancel;
cancel.dwUserTempID=tempid;
sendCmdToMe(&cancel,sizeof(cancel));
pAnother->sendCmdToMe(&cancel,sizeof(cancel));
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"%s包裹已满或银子不足,交易失败",
tradeorder.can_trade()?name:pAnother->name);
Channel::sendSys(pAnother,Cmd::INFO_TYPE_FAIL,"%s包裹已满或银子不足,交易失败",
tradeorder.can_trade()?name:pAnother->name);
}
pAnother->tradeorder.finish();
tradeorder.finish();
}
else
{
stCommitTradeUserCmd ci;
ci.dwUserTempID=tempid;
pAnother->sendCmdToMe(&ci,sizeof(ci));
sendCmdToMe(&ci,sizeof(ci));
}
}
else
{
tradeorder.finish();
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不在了");
stCancelTradeUserCmd cancel;
cancel.dwUserTempID=tempid;
sendCmdToMe(&cancel,sizeof(cancel));
}
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)不能确定交易时确定交易",name,id);
return true;
}
break;
case CANCEL_TRADE_USERCMD_PARAMETER:
{
SceneUser *pAnother=tradeorder.target();
tradeorder.finish();
stCancelTradeUserCmd cancel;
cancel.dwUserTempID=tempid;
sendCmdToMe(&cancel,sizeof(cancel));
if (pAnother)
{
pAnother->tradeorder.finish();
cancel.dwUserTempID=pAnother->tempid;
pAnother->sendCmdToMe(&cancel,sizeof(cancel));
}
return true;
}
break;
case ADD_OBJECT_TRADE_USERCMD_PARAMETER:
{
stAddObjectTradeUserCmd *cmd = (stAddObjectTradeUserCmd *)rev;
if (!tradeorder.hasBegin() || tradeorder.hasCommit() ) {
return true;
}
if (cmd->x > TradeOrder::WIDTH || cmd->y > TradeOrder::HEIGHT) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)请求交易的物品坐标非法",name,id);
return true;
}
zObject* ob = packs.uom.getObjectByThisID(cmd->object.qwThisID);
if (!ob) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)请求交易的物品不存在",name,id);
return true;
}
if (ob->base->kind == ItemType_Money && cmd->object.dwNum > ob->data.dwNum ){
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)请求交易的物品数量非法",name,id);
return true;
}
if (ob->data.bind || ob->data.dwObjectID == 800 || ob->base->kind == ItemType_Quest) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)用户试图交易不能交易的物品",name,id);
return true;
}
if (ob->data.pos.loc() != Cmd::OBJECTCELLTYPE_COMMON) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)用户试图交易不在主包裹中的物品",name,id);
return true;
}
SceneUser *pAnother=tradeorder.target();
if (pAnother && pAnother->tradeorder.hasBegin() && !pAnother->tradeorder.hasCommit())
{
if (ob->base->kind ==ItemType_Money) {
tradeorder.add_money(cmd->object.dwNum);
}else {
tradeorder.add(ob);
}
stAddObjectTradeUserCmd ret;
ret.user_id = tempid;
memccpy(&ret.object,&(ob->data),sizeof(ret.object),sizeof(ret.object));
ret.x = cmd->x;
ret.y = cmd->y;
if (ob->base->kind == ItemType_Money) {
ret.object.dwNum = cmd->object.dwNum;
}
//this->sendCmdToMe(&ret,sizeof(ret));
pAnother->sendCmdToMe(&ret,sizeof(ret));
}
return true;
}
break;
case REMOVE_OBJECT_TRADE_USERCMD_PARAMETER:
{
stRemoveObjectTradeUserCmd *cmd = (stRemoveObjectTradeUserCmd *)rev;
if (!tradeorder.hasBegin() || tradeorder.hasCommit() ) {
return true;
}
SceneUser *pAnother=tradeorder.target();
if (pAnother && pAnother->tradeorder.hasBegin() && !pAnother->tradeorder.hasCommit())
{
tradeorder.remove(cmd->object_id);
cmd->user_id = tempid;
//this->sendCmdToMe(cmd,sizeof(stRemoveObjectTradeUserCmd));
pAnother->sendCmdToMe(cmd,sizeof(stRemoveObjectTradeUserCmd));
}
return true;
}
break;
case VISITNPC_TRADE_USERCMD_PARAMETER:
{
stVisitNpcTradeUserCmd *ptCmd=(stVisitNpcTradeUserCmd *)rev;
BYTE buf[zSocket::MAX_DATASIZE];
stVisitNpcTradeUserCmd *cmd=(stVisitNpcTradeUserCmd *)buf;
bzero(buf,sizeof(buf));
constructInPlace(cmd);
if( ptCmd->dwNpcTempID == 100000000 )
{
OnVisit event( 5281);
EventTable::instance().execute(*this,event);
int status;
int len = quest_list.get_menu(cmd->menuTxt,status);
if (NpcTrade::getInstance().getNpcMenu( 5281,cmd->menuTxt+len))
{
//Zebra::logger->debug("%ld\n%s",strlen(cmd->menuTxt),cmd->menuTxt);
visitNpc( 5281,100000000 );
cmd->byReturn = 1;
}
}
SceneNpc *sceneNpc = SceneNpcManager::getMe().getNpcByTempID( ptCmd->dwNpcTempID);
if ( (sceneNpc && this->canVisitNpc(sceneNpc)) /*|| ( sceneNpc->id == 5281 )*/ )/*( (sceneNpc->id>=5000&&sceneNpc->id<=6000) || (sceneNpc->scene && (sceneNpc->scene->getCountryID() == charbase.country || changeface)) ) */
{
//TODO 检查Npc是否在同一个场景,并且检查距离
OnVisit event(sceneNpc->id);
EventTable::instance().execute(*this,event);
int status;
int len = quest_list.get_menu(cmd->menuTxt,status);
//Zebra::logger->debug("TODO 检查Npc(%lu)是否在同一个场景,并且检查距离",sceneNpc->id);
if ( (sceneNpc->scene && sceneNpc->scene == this->scene &&
this->scene->zPosShortRange(this->getPos(),sceneNpc->getPos(),SCREEN_WIDTH,SCREEN_HEIGHT)) /*|| ( sceneNpc->id == 5281 )*/ )
{
if (NpcTrade::getInstance().getNpcMenu(sceneNpc->id,cmd->menuTxt+len))
{
//Zebra::logger->debug("%ld\n%s",strlen(cmd->menuTxt),cmd->menuTxt);
visitNpc(sceneNpc->id,sceneNpc->tempid);
cmd->byReturn = 1;
}
if (ScriptQuest::get_instance().has(ScriptQuest::NPC_VISIT,sceneNpc->id)) {
char func_name[32];
sprintf(func_name,"%s_%d","visit",sceneNpc->id);
if (execute_script_event(this,func_name,sceneNpc)) return true;
}
}
else
{
Zebra::logger->warn("用户%s(%d)检查Npc(%lu)距离不合法(%u,%d,%d),(%u,%d,%d)",this->name,this->id,sceneNpc->id,this->scene->id,this->getPos().x,this->getPos().y,sceneNpc->scene->id,sceneNpc->getPos().x,sceneNpc->getPos().y);
}
// Zebra::logger->debug("动态菜单(%s)",cmd->menuTxt);
}
else
Zebra::logger->error("%s(%d)访问不能访问的Npc",this->name,this->id);
sendCmdToMe(cmd,sizeof(stVisitNpcTradeUserCmd) + strlen(cmd->menuTxt));
return true;
}
break;
case BUYOBJECT_NPCTRADE_USERCMD_PARAMETER:
{
stBuyObjectNpcTradeUserCmd *ptCmd=(stBuyObjectNpcTradeUserCmd *)rev;
zObjectB *base = objectbm.get(ptCmd->dwObjectID);
ptCmd->itemLevel = 0;
///如果需要用金币或者积分买
if (base)
{
if (base->cointype & eBuyGold || base->cointype & eBuyTicket)
{
this->npcTradeGold(ptCmd,base,ptCmd->itemLevel);
return true;
}
}
SceneNpc * n = SceneNpcManager::getMe().getNpcByTempID(npc_dwNpcTempID);
if (!n && npc_dwNpcTempID != 100000000 )
{
Zebra::logger->debug("[交易:玩家<------商店]%s 交易时,找不到该npc tempID=%u",name,npc_dwNpcTempID);
return true;
}
if ((getGoodnessState() != Cmd::GOODNESS_6)
|| ((getGoodnessState()==Cmd::GOODNESS_6) && (NPC_TYPE_MOBILETRADE==n->npc->kind)) )
{
if (base)
{
DWORD price = (DWORD )(this->getGoodnessPrice(base->price,true)+0.99f);
if (this->scene->getCountryID() == PUBLIC_COUNTRY)
{//在公共国买东西,价格上涨10%
price = price + (DWORD)(price*0.1);
}
if (ptCmd->dwNum == 0) {
ptCmd->dwNum = 1;
}
if (ptCmd->dwNum > base->maxnum) {
ptCmd->dwNum = base->maxnum;
}
DWORD need = price*ptCmd->dwNum;
int dayssize=packs.store.days;
if (this->charbase.bitmask & CHARBASE_VIP)
{
dayssize=dayssize?(dayssize - 1):dayssize;
}
if (base->kind == ItemType_Store) {
need = price*base->durability;
if (dayssize==1) //the second page
need = 2000;
if (dayssize==2) //the third page
need = 100000;
}
// if (base->kind == ItemType_HORSE && charbase.level<30)
if (base->kind == ItemType_HORSE && charbase.level<2)
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你还没满30级,不能购买马匹");
return true;
}
DWORD taxMoney;
if( npc_dwNpcTempID == 100000000 )
{
taxMoney = (DWORD)((price*ptCmd->dwNum/100.0f)+0.5f);
}
else
taxMoney = (DWORD)((price*ptCmd->dwNum*n->scene->getTax()/100.0f)+0.5f); // 买东西收税
if ((base->kind == ItemType_DoubleExp && this->charbase.honor >= need) ||
(base->kind == ItemType_HORSE && packs.checkMoney(need))||
(base->kind == ItemType_Store && packs.checkMoney(need))||
(base->kind != ItemType_DoubleExp && packs.checkMoney(need+taxMoney)))
{
NpcTrade::NpcItem item;
item.id = base->id;
item.kind = base->kind;
item.lowLevel = 0;
item.level = base->needlevel;
item.itemlevel = ptCmd->itemLevel;
item.action = NpcTrade::NPC_BUY_OBJECT;
if (NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item))
{
if (base->kind == ItemType_HORSE) {
if (horse.horse()) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你已经有马了!");
}
//DWORD taxMoney = (DWORD)((need*n->scene->getTax()/100.0f)+0.5f); // 买东西收税
//need = need + taxMoney;
if (packs.removeMoney(need,"买东西")) {
horse.horse(base->id);
/*
Cmd::Session::t_taxAddCountry_SceneSession send;
send.dwCountryID = n->scene->getCountryID();
send.qwTaxMoney = taxMoney;
sessionClient->sendCmd(&send,sizeof(send));
// */
Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"你得到一匹枣红马");
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买马(%d)花费银子%d",name,id,base->id,need);
}else {
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买马时银子计算错误!",name);
}
return true;
}
/*if (base->kind == ItemType_Store)
{
if (dayssize>1)
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"已经买了两个储物箱了,无法再购买!");
if (packs.removeMoney(need,"买东西") ) {
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买储物箱花费银子%d",name,id,need);
Channel::sendMoney(this,Cmd::INFO_TYPE_GAME,need,"买储物箱花费银子");
packs.store.days.push_back(base->durability);
packs.store.notify(this);
}
else
{
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买储物箱时银子计算错误!",name);
}
return true;
}*/
zObject* o = NULL;
if (base->recast)
{
o = zObject::create(base,ptCmd->dwNum,0);
if (o && ptCmd->itemLevel)
{
do
{
//Upgrade::upgrade(*this,o,100); //must success
}
while (--ptCmd->itemLevel >0);
}
}else
{
o = zObject::create(base,ptCmd->dwNum,ptCmd->itemLevel);
}
if (o)
{
Combination callback(this,o);
packs.main.execEvery(callback);
if (packs.equip.pack(EquipPack::L_PACK)) packs.equip.pack(EquipPack::L_PACK)->execEvery(callback);
if (packs.equip.pack(EquipPack::R_PACK)) packs.equip.pack(EquipPack::R_PACK)->execEvery(callback);
int free = 0;
if (o->data.dwNum) {
if (packs.addObject(o,true,AUTO_PACK)) {
free = o->data.dwNum;
//如果是双倍经验道具和荣誉道具需要绑定
o->checkBind();
Cmd::stAddObjectPropertyUserCmd status;
status.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&status.object,sizeof(t_Object),sizeof(status.object));
sendCmdToMe(&status,sizeof(status));
}
}
if (callback.num() || free) {
//get object
int count = callback.num() + free;
if (base->kind == ItemType_DoubleExp)
{
this->charbase.honor -= price*count;
if ((int)this->charbase.honor <0)
{
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买%s时荣誉点数计算错误!",name,o->base->name);
this->charbase.honor=0;
}
Cmd::stMainUserDataUserCmd userinfo;
full_t_MainUserData(userinfo.data);
sendCmdToMe(&userinfo,sizeof(userinfo));
zObject::logger(0,0,"荣誉值",this->charbase.honor,price*count,0,this->id,this->name,0,NULL,"买东西扣除荣誉值",NULL,0,0);
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,count,1,n->id,n->name,this->id,this->name,"buy_npc",o->base,o->data.kind,o->data.upgrade);
Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"得到物品 %s(%d)个,花费荣誉点数%u",o->name,count,price*count);
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买%s(%d)个花费荣誉点%d",name,id,o->name,count,price*count);
}
else
{
DWORD taxMoney;
if( npc_dwNpcTempID == 100000000 )
{
taxMoney = (DWORD)((price*count/100.0f)+0.5f);
}
else
taxMoney = (DWORD)((price*count*n->scene->getTax()/100.0f)+0.5f); // 买东西收税
if (!packs.removeMoney(price*count+taxMoney,"买东西")) {
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买%s时银子计算错误!",name,o->base->name);
}
Cmd::Session::t_taxAddCountry_SceneSession send;
if( npc_dwNpcTempID == 100000000 )
{
send.dwCountryID = 2;
}
else
{
send.dwCountryID = n->scene->getCountryID();
}
send.qwTaxMoney = taxMoney;
sessionClient->sendCmd(&send,sizeof(send));
if( npc_dwNpcTempID == 100000000 )
{
Zebra::logger->info("[交易:玩家<------随身商店]用户(%s,%u)买%s(%d)个花费银子%d",name,id,o->name,count,price*count+taxMoney);
}
else
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,count,1,n->id,n->name,this->id,this->name,"buy_npc",o->base,o->data.kind,o->data.upgrade);
Channel::sendMoney(this,Cmd::INFO_TYPE_GAME,price*count+taxMoney,"得到物品 %s(%d)个,花费银子",o->name,count);
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买%s(%d)个花费银子%d",name,id,o->name,count,price*count+taxMoney);
}
}
if (!free) { //package is full
//Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满");
zObject::destroy(o);
}
}
}
else
Zebra::logger->error("[交易:玩家<------商店]不能在这里买这样物品 %u,%u,%s",npc_dwNpcDataID,base->id,base->name);
}
else
{
if (base->kind == ItemType_DoubleExp)
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的荣誉点数不够买这件物品");
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的银子不够买这件物品");
}
}
}
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"本人不与大魔头交易");
return true;
}
break;
case SELLOBJECT_NPCTRADE_USERCMD_PARAMETER:
{
stSellObjectNpcTradeUserCmd *ptCmd=(stSellObjectNpcTradeUserCmd *)rev;
zObject *srcobj=packs.uom.getObjectByThisID(ptCmd->qwThisID);
if (srcobj)
{
if (this->getGoodnessState() != Cmd::GOODNESS_6)
{
//交易处理
if (tradeorder.hasBegin() && tradeorder.in_trade(srcobj))
{
return true;
}
if (mask.is_use(srcobj)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"请先解除该蒙面巾!");
}
if (srcobj->base->kind == ItemType_Quest) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"任务物品不可买卖");
};
NpcTrade::NpcItem item;
item.id = srcobj->data.dwObjectID;
item.kind = srcobj->base->kind;
item.lowLevel = 0;
item.level = srcobj->data.needlevel;
item.action = NpcTrade::NPC_SELL_OBJECT;
if (NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item))
{
// 卖东西要收钱
if (srcobj->data.price>0)
{
DWORD price = 0;
DWORD real_price = 0;
if (srcobj->base->id == 655)
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 4000.0f);
}
}
else if (srcobj->base->id == 685) //魔力之源
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 4000.0f);
}
}
else if (srcobj->base->id == 882) // 龙之魔力
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 20000.0f);
}
}
else if (srcobj->base->id == 760) //洗髓宝珠
{
//if (srcobj->base->durability)
//{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 200000.0f);
//}
}
else if (srcobj->base->id == 761) // 易筋宝珠
{
//if (srcobj->base->durability)
//{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 200000.0f);
//}
}
else if (srcobj->base->id == 881)
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 20000.0f);
}
}
else
{
price = get_sell_price_by_dur(srcobj);
if (srcobj->base->maxnum &&
(srcobj->base->kind == ItemType_Arrow/* || srcobj->base->kind == ItemType_Arrow2*/))
{
if (srcobj->base->durability)
{
real_price = (DWORD)(getGoodnessPrice((srcobj->data.dwNum * price
),false));
}
}
else
{
if (srcobj->base->durability)
{
real_price = (DWORD)(getGoodnessPrice((srcobj->data.dwNum * price
),false));
}
else
{
real_price = (DWORD)(getGoodnessPrice((srcobj->data.dwNum * price
),false));
}
}
}
Channel::sendMoney(this,Cmd::INFO_TYPE_GAME,real_price,"卖%s得到银子",srcobj->name );
Zebra::logger->info("[交易:玩家------>商店]用户(%s,%u)卖%s得到银子%d",name,id,srcobj->name,real_price);
packs.addMoney(real_price,"卖东西");
}
if (srcobj->data.exp && srcobj->base->kind != ItemType_Pack ) {
Zebra::logger->info("[交易:玩家------>商店]%s(%u) 卖装备增加经验 %u",name,id,srcobj->data.exp);
addExp(srcobj->data.exp);
}
zObject::logger(srcobj->createid,srcobj->data.qwThisID,srcobj->base->name,srcobj->data.dwNum,srcobj->data.dwNum,0,npc_dwNpcDataID,NULL,this->id,this->name,"sell_npc",srcobj->base,srcobj->data.kind,srcobj->data.upgrade);
packs.removeObject(srcobj); //notify and delete
if (packs.equip.needRecalc)
{
notifyEquipChange();
setupCharBase();
Cmd::stMainUserDataUserCmd userinfo;
full_t_MainUserData(userinfo.data);
sendCmdToMe(&userinfo,sizeof(userinfo));
sendMeToNine();
}
}
else
{
Zebra::logger->warn("[交易:玩家------>商店]不能在这里卖这样物品 %u,%u,%s",
npc_dwNpcDataID,srcobj->data.dwObjectID,srcobj->data.strName);
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对不起,小店不收购%s",srcobj->base->name);
}
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"本人不与大魔头交易");
}
return true;
}
break;
case SELLHORSE_NPCTRADE_USERCMD_PARAMETER:
{
stSellHorseNpcTradeUserCmd *ptCmd=(stSellHorseNpcTradeUserCmd *)rev;
//放逐
if (ptCmd->action) {
if (horse.horse()) {
horse.mount(false);
horse.putAway();
horse.horse(0);
Zebra::logger->info("[卖马]%s 放逐了他的马",name);
}
return true;
}
//卖
if (this->getGoodnessState() != Cmd::GOODNESS_6)
{
if (!horse.horse()) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你还没有马匹,卖什么马?");
}
zObjectB *base = objectbm.get(horse.horse());
if (!base) {
Zebra::logger->warn("[卖马]用户马匹在道具表中不存在,请检查道具基本表!");
return true;
}
NpcTrade::NpcItem item;
item.id = base->id;
item.kind = base->kind;
item.lowLevel = 0;
item.level = base->needlevel;
item.action = NpcTrade::NPC_SELL_OBJECT;
if (NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item)) {
if (base->price>0) {
DWORD price = (DWORD)(getGoodnessPrice(base->price,false)*0.5f + 0.99f);
char info[MAX_CHATINFO];
sprintf(info,"卖%s得到银子",base->name);
Zebra::logger->info("[卖马]用户(%s,%u)卖%s得到银子%d",name,id,base->name,price);
packs.addMoney(price,"卖东西",info);
}
horse.putAway();
//horse.sendData();
horse.mount(false);
horse.horse(0);
}else {
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对不起,小店不收购%s",base->name);
}
}
else Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"本人不与大魔头交易");
return true;
}
break;
case STORE_INFO_NPCTRADE_USERCMD_PARAMETER:
{
/*stStoreInfoNpcTradeUserCmd* cmd = (stStoreInfoNpcTradeUserCmd*)rev;
if ((signed char)cmd->page < 0 || cmd->page >= packs.store.days.size() ) return false;
packs.store.days[cmd->page] += *(BYTE*)(&cmd->day[0]);
packs.store.notify(this);*/
return true;
}
break;
case REPAIROBJECT_GOLD_NPCTRADE_USERCMD_PARAMETER:
{
DWORD price = 0;
stRepairObjectGoldNpcTradeUserCmd *cmd = (stRepairObjectGoldNpcTradeUserCmd *)rev;
if (cmd->id == 0)
{
//compute cost
RepairCost cost;
packs.equip.execEvery(cost);
price = zObject::RepairMoney2RepairGold(cost.cost());
//价格为0时拒绝修里
if (!price)
{
return true;
}
//test money
if (!packs.checkGold(price)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的金子不足,不能全部修理!");
}
//repair equip
RepairEquipUseGold repair(this);
packs.equip.execEvery(repair);
}
else
{
zObject* ob = packs.uom.getObjectByThisID(cmd->id);
if (!ob || !ob->base->recast || /*!ob->data.dur ||// */ !ob->data.maxdur) return false;
price = zObject::RepairMoney2RepairGold(get_repair_price(ob));
//test money
if (!packs.checkGold(price)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的金子子不足,不能修理这件物品!");
}
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
sendCmdToMe(&ret,sizeof(ret));
}
if (!packs.removeGold(price,"修理"))
{
Zebra::logger->fatal("用户(%s)修理装备时金子子计算错误!",name);
}
}
break;
case REPAIROBJECT_NPCTRADE_USERCMD_PARAMETER:
{
DWORD price = 0;
stRepairObjectNpcTradeUserCmd *cmd = (stRepairObjectNpcTradeUserCmd *)rev;
#if 0
NpcTrade::NpcItem item;
item.id = 0 /*base->id*/;
item.kind = 0 /*base->kind*/;
item.lowLevel = 0;
item.level = 0 /*base->needlevel*/;
item.action = NpcTrade::NPC_REPAIR_OBJECT;
if (!NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item)) {
return false;
}
#endif
if (cmd->gem_id)
{
zObject* gem_ob = packs.uom.getObjectByThisID(cmd->gem_id);
if (!gem_ob || gem_ob->base->kind != ItemType_Repair ) return true;
zObject* ob = packs.uom.getObjectByThisID(cmd->id);
if (!ob || !ob->base->recast) return true;
//repair equip
//每次修复两点最大耐久,同时增加当前耐久至最大耐久
ob->data.maxdur += 100;
if (ob->data.maxdur > ob->base->durability)
{
ob->data.maxdur = ob->base->durability;
}
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
sendCmdToMe(&ret,sizeof(ret));
packs.removeObject(gem_ob); //notify and delete
return true;
}
if (cmd->id == 0)
{
//compute cost
RepairCost cost;
packs.equip.execEvery(cost);
price = cost.cost();
//价格为0时拒绝修里
if (!price)
{
return true;
}
//test money
if (!packs.checkMoney(price)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的银子不足,不能全部修理!");
}
//repair equip
RepairEquip repair(this);
packs.equip.execEvery(repair);
}
else
{
zObject* ob = packs.uom.getObjectByThisID(cmd->id);
if (!ob || !ob->base->recast || !ob->data.dur || !ob->data.maxdur) return false;
price = get_repair_price(ob);
if (!price)
{
return true;
}
//test money
if (!packs.checkMoney(price))
{
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的银子不足,不能修理这件物品!");
}
//repair equip
//武器,盾,帽子,衣服,护腕,腰带,靴子,戒指,手镯,项链需要消耗最大耐久
/*
switch(ob->base->kind)
{
case ItemType_ClothBody:
case ItemType_FellBody:
case ItemType_MetalBody:
case ItemType_Blade:
case ItemType_Sword:
case ItemType_Axe:
case ItemType_Hammer:
case ItemType_Staff:
case ItemType_Crossbow:
case ItemType_Fan:
case ItemType_Stick:
case ItemType_Shield:
case ItemType_Helm:
case ItemType_Caestus:
case ItemType_Cuff:
case ItemType_Shoes:
case ItemType_Necklace:
case ItemType_Fing:
case ItemType_FashionBody:
{
//消耗最大耐久公式
DWORD reduce = ((DWORD)((((float)(ob->data.maxdur-ob->data.dur))/ob->base->durability)*10)+1)*5;
if (reduce > ob->data.maxdur)
{
ob->data.maxdur=0;
}
else
{
ob->data.maxdur -=reduce;
}
}
break;
default:
break;
}
// */
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
sendCmdToMe(&ret,sizeof(ret));
}
if (!packs.removeMoney(price,"修理"))
{
Zebra::logger->fatal("用户(%s)修理装备时银子计算错误!",name);
}
/*
else {
Zebra::logger->info("[修理装备]用户(%s)修理装备花费银子(%d)",name,price);
}
// */
}
break;
case START_SELL_USERCMD_PARAMETER:
//by RAY 去掉摆摊
//Channel::sendSys(this, Cmd::INFO_TYPE_FAIL, "摆摊系统开 发中!");
//#if 0
if (this->charbase.level <20)
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"等级低于20,不能摆摊!");
return true;
}
if (this->isSitdown())
{
this->standup();
}
if (privatestore.step() == PrivateStore::NONE)
{
/*
if (!scene->checkZoneType(getPos(),ZoneTypeDef::ZONE_PRIVATE_STORE)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"这里不能摆摊!");
}
*/
Cmd::stCanSellTradeUserCmd cmd;
if (!scene->checkZoneType(getPos(),ZoneTypeDef::ZONE_PRIVATE_STORE))
{
cmd.status = 1;
sendCmdToMe(&cmd,sizeof(cmd));
return true;
}
cmd.status = 0;
privatestore.step(PrivateStore::START,this);
sendCmdToMe(&cmd,sizeof(cmd));
Zebra::logger->info("[交易:玩家------>摆摊]用户(%s)请求开始摆摊",name);
return true;
}
if (privatestore.step() == PrivateStore::START) {
horse.mount(false,false);
privatestore.step(PrivateStore::BEGIN,this);
sendMeToNine();
Zebra::logger->info("[交易:玩家------>摆摊]用户(%s)开始摆摊",name);
return true;
}
//#endif
break;
case FINISH_SELL_USERCMD_PARAMETER:
{
privatestore.step(PrivateStore::NONE,this);
Zebra::logger->info("[交易:玩家------>摆摊]用户(%s)完成摆摊",name);
sendMeToNine();
}
break;
case REQUEST_ADD_OBJECT_SELL_USERCMD_PARAMETER:
{
stRequestAddObjectSellUserCmd *cmd = (stRequestAddObjectSellUserCmd *)rev;
for(int i = 0; i < cmd->num && i < 200; i++)
{
if (privatestore.step() != PrivateStore::START ) {
return true;
}
if (cmd->list[i].x > PrivateStore::WIDTH || cmd->list[i].y > PrivateStore::HEIGHT) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品坐标非法",name,id);
return true;
}
zObject* ob = packs.uom.getObjectByThisID(cmd->list[i].qwThisID);
if (!ob) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品不存在",name,id);
return true;
}
if (mask.is_use(ob)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"请先解除该蒙面巾!");
}
if (ob->data.bind || ob->data.dwObjectID == 800 || ob->base->kind == ItemType_Quest) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图使用不能摆摊的物品",name,id);
return true;
}
if (ob->data.pos.loc() != Cmd::OBJECTCELLTYPE_COMMON && ob->data.pos.loc()!=Cmd::OBJECTCELLTYPE_PACKAGE) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图摆摊不在主副包裹中的物品",name,id);
return true;
}
privatestore.add(ob,cmd->list[i].price,cmd->list[i].x,cmd->list[i].y);
Zebra::logger->info("[交易:玩家------>摆摊]用户%s添加摆摊物品%s(%d)",name,ob->data.strName,ob->data.qwThisID);
}
}
break;
case ADD_OBJECT_SELL_USERCMD_PARAMETER:
{
stAddObjectSellUserCmd *cmd = (stAddObjectSellUserCmd *)rev;
if (privatestore.step() != PrivateStore::START ) {
return true;
}
if (cmd->x > PrivateStore::WIDTH || cmd->y > PrivateStore::HEIGHT) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品坐标非法",name,id);
return true;
}
zObject* ob = packs.uom.getObjectByThisID(cmd->object.qwThisID);
if (!ob) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品不存在",name,id);
return true;
}
/*
if (ob->base->kind == ItemType_Money && cmd->object.dwNum > ob->data.dwNum ){
Zebra::logger->warn("%s(%ld)请求交易的物品数量非法",name,id);
return true;
}
*/
if (mask.is_use(ob)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"请先解除该蒙面巾!");
}
if (ob->data.bind || ob->data.dwObjectID == 800 || ob->base->kind == ItemType_Quest) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图使用不能摆摊的物品",name,id);
return true;
}
if (ob->data.pos.loc() != Cmd::OBJECTCELLTYPE_COMMON && ob->data.pos.loc()!=Cmd::OBJECTCELLTYPE_PACKAGE) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图摆摊不在主副包裹中的物品",name,id);
return true;
}
privatestore.add(ob,cmd->price,cmd->x,cmd->y);
Zebra::logger->info("[交易:玩家------>摆摊]用户%s添加摆摊物品%s(%d)",name,ob->data.strName,ob->data.qwThisID);
}
break;
case REMOVE_OBJECT_SELL_USERCMD_PARAMETER:
{
stRemoveObjectSellUserCmd*cmd = (stRemoveObjectSellUserCmd *)rev;
if (privatestore.step() != PrivateStore::START) {
return true;
}
privatestore.remove(cmd->object_id);
//just for info,it's very ugly
zObject* ob = packs.uom.getObjectByThisID(cmd->object_id);
if (ob) {
Zebra::logger->info("[交易:玩家------>摆摊]用户%s移除摆摊物品%s(%d)",name,ob->data.strName,ob->data.qwThisID);
}
}
break;
case REQUEST_SELL_INFO_USERCMD_PARAMETER:
{
stRequestSellInfoUserCmd *cmd=(stRequestSellInfoUserCmd *)rev;
if (cmd->temp_id == tempid) {
//Zebra::logger->warn("[交易:玩家<------摆摊]%s(%ld)请求自己的摆摊信息",name,id);
return true;
}
SceneUser *target = scene->getUserByTempID(cmd->temp_id);
if (!target || target->privatestore.step() != PrivateStore::BEGIN) {
Zebra::logger->warn("[交易:玩家<------摆摊]%s(%ld)请求摆摊信息的用户不存在或者没有摆摊",name,id);
return true;
}
if (abs((long)(pos.x- target->getPos().x)) > (SCREEN_WIDTH ) || abs((long)(pos.y-target->getPos().y)) > (SCREEN_HEIGHT)) {
return true;
}
//Zebra::logger->info("[交易:玩家<------摆摊]%s(%ld)请求%s(%ld)摆摊信息",name,id,target->name,target->id);
target->privatestore.show(this);
}
break;
case REQUEST_SELL_BUY_USERCMD_PARAMETER:
{
do_trade_rs_cmd(rev,cmdLen);
return true;
}
break;
case UPDATE_STORE_PASS_USERCMD_PARAMETER:
/*
{
stUpdateStorePassUserCmd * cmd = (stUpdateStorePassUserCmd*)rev;
if (strncmp(cmd->oldpass,charbase.pass,sizeof(charbase.pass)) == 0) {
strncpy(charbase.pass,cmd->newpass,sizeof(charbase.pass));
return true;
}
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"密码错误,不能修改密码!")
}
*/
break;
//[Shx Add 发送广告牌更新消息]
case UPDATE_SHOP_ADV_USERCMD_PARAMETER:
{
stUpdateShopAdvcmd* pCmd = (stUpdateShopAdvcmd*)rev;
pCmd->size = 1;
pCmd->Datas[0].dwID = tempid;
pCmd->Datas[0].strShopAdv[MAX_SHOPADV - 1] = '\0';
strncpy(ShopAdv, pCmd->Datas[0].strShopAdv,MAX_SHOPADV);
this->scene->sendCmdToNine(this->getPosI(),pCmd,sizeof(stUpdateShopAdvcmd) + 1 * sizeof(stUpdateShopAdvcmd::stAdv), this->dupIndex);
}
break;
// [Shx Add 转发交易玩家修改金钱数量]
case UPDATE_TRADE_MONEY_USERCMD:
{
stUpdateTradeMoneycmd* pCmd = (stUpdateTradeMoneycmd*)rev;
SceneUser* pTarget = tradeorder.target();
if(pTarget && pCmd->dwMyID == tempid && pCmd->dwOtherID == pTarget->tempid)
{
pTarget->sendCmdToMe(pCmd, cmdLen);
}
}
break;
default:
break;
}
return false;
}
bool RepairCost::exec(zObject* ob)
{
if (!ob || !ob->base->recast || !ob->data.maxdur ) return true;
_cost += get_repair_price(ob);
return true;
}
bool RepairEquipUseGold::exec(zObject* ob)
{
if (!ob || !ob->base->recast || !ob->data.maxdur) return true;
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
_user->sendCmdToMe(&ret,sizeof(ret));
return true;
}
bool RepairEquip::exec(zObject* ob)
{
if (!ob || !ob->base->recast || !ob->data.maxdur) return true;
//武器,盾,帽子,衣服,护腕,腰带,靴子,戒指,手镯,项链需要消耗最大耐久
/*
switch(ob->base->kind)
{
case ItemType_ClothBody:
case ItemType_FellBody:
case ItemType_MetalBody:
case ItemType_Blade:
case ItemType_Sword:
case ItemType_Axe:
case ItemType_Hammer:
case ItemType_Staff:
case ItemType_Crossbow:
case ItemType_Fan:
case ItemType_Stick:
case ItemType_Shield:
case ItemType_Helm:
case ItemType_Caestus:
case ItemType_Cuff:
case ItemType_Shoes:
case ItemType_Necklace:
case ItemType_Fing:
case ItemType_FashionBody:
{
//消耗最大耐久公式
DWORD reduce = ((DWORD)((((float)(ob->data.maxdur-ob->data.dur))/ob->base->durability)*10)+1)*5;
if (reduce > ob->data.maxdur)
{
ob->data.maxdur=0;
}
else
{
ob->data.maxdur -=reduce;
}
}
break;
default:
break;
}
// */
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
_user->sendCmdToMe(&ret,sizeof(ret));
return true;
}
| [
"hyd998877@gmail.com"
] | hyd998877@gmail.com |
d5405675581960556922973604733ba74aa65001 | a6bb89b2ff6c1fc8c45a4f105ef528416100a360 | /contrib/framewave_1.3.1_src/SampleConvert/SRC/process_illusion.cpp | b6d2fb5fa3bf3daca22a590570bade75edffde77 | [
"Apache-2.0"
] | permissive | dudochkin-victor/ngxe | 2c03717c45431b5a88a7ca4f3a70a2f23695cd63 | 34687494bcbb4a9ce8cf0a7327a7296bfa95e68a | refs/heads/master | 2016-09-06T02:28:20.233312 | 2013-01-05T19:59:28 | 2013-01-05T19:59:28 | 7,311,793 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,670 | cpp | /*
Copyright (c) 2006-2009 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<math.h>
#include"process_API.h"
/*!
*************************************************************************************
* \function process_illusion
*
* \brief
* This function processes the illusion effect opertation.
*
*
*************************************************************************************
*/
void
process_illusion(st_API_parameters *p)
{
int api_return_val ;
TIME_START /* Start Timer */
p->spare_roiSize.width = 1 ;
p->spare_roiSize.height = 1 ;
p->srcStep = 1 ;
int k =0 ;
Fw32f *sqrwidth ;
Fw32f *sqrheight ;
Fw32f val = 2 ;
Fw32f threshold ;
sqrwidth = (float*)malloc(4);
sqrheight = (float*)malloc(4);
sqrwidth[0] = (Fw32f)p->bor_width ;
sqrheight[0] = (Fw32f)p->bor_height ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqr_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square of the source data. Result is written back to the source location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqr_32f_C1IR ( sqrwidth , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
api_return_val = fwiSqr_32f_C1IR ( sqrheight , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiAdd_32f_C1IR" : */
/* */
/* This functions steps through an ROI in two source buffers and add the */
/* data in buffer 2 to the data in buffer 1. Result is written back to the */
/* destination location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiAdd_32f_C1IR ( sqrwidth , p->srcStep , sqrheight , p->srcStep ,p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqrt_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square root of the source data. Result is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqrt_32f_C1IR( sqrheight , p->srcStep , p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiDivC_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and divides the */
/* source data by a constant value. The quotient is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiDivC_32f_C1IR( val , sqrheight, p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
float fscale = sqrheight[0] ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiDivC_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and divides the */
/* source data by a constant value. The quotient is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiDivC_32f_C1IR( val , sqrheight, p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
int foffset = (int)sqrheight[0] ;
double xcen, ycen, tmp;
double angle, radius;
Fw32f *cx,*cy;
xcen = p->bor_width / 2.0 ;
ycen = p->bor_height / 2.0 ;
Fw32f *xx, *yy ;
xx = (float*)malloc(4);
yy = (float*)malloc(4);
cx = (float*)malloc(4);
cy = (float*)malloc(4);
for (int j=0 ; j < p->bor_height ; j++)
{
for (int i=0 ; i < p->bor_width ; i++)
{
p->srcStep = 1 ;
cx[0] = (i - xcen) / fscale ;
cy[0] = (j - ycen) / fscale ;
tmp = 3.14159265 / (double)p->field ;
angle = floor (atan2(cy[0],cx[0]) / 2.0 / tmp) * 2.0 * tmp + tmp ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqr_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square of the source data. Result is written back to the source location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqr_32f_C1IR ( cx , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
api_return_val = fwiSqr_32f_C1IR ( cy , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiAdd_32f_C1IR" : */
/* */
/* This functions steps through an ROI in two source buffers and add the */
/* data in buffer 2 to the data in buffer 1. Result is written back to the */
/* destination location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiAdd_32f_C1IR ( cx , p->srcStep , cy , p->srcStep ,p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqrt_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square root of the source data. Result is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqrt_32f_C1IR( cy , p->srcStep , p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
radius = cy[0] ;
xx[0] = (Fw32f)((int)(i - foffset * cos (angle)) );
yy[0] = (Fw32f)((int)(j - foffset * sin (angle)) );
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_GT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* greater than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = (Fw32f)(p->bor_width - 1) ;
api_return_val = fwiThreshold_GT_32f_C1IR ( xx , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_LT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* lesser than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = 0;
api_return_val = fwiThreshold_LT_32f_C1IR ( xx , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_GT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* greater than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = (Fw32f)(p->bor_height - 1) ;
api_return_val = fwiThreshold_GT_32f_C1IR ( yy , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_LT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* lesser than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = 0;
api_return_val = fwiThreshold_LT_32f_C1IR ( yy , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
int a = (int)((yy[0] * p->bor_width * 3 ) + (xx[0] - 1) * 3) ;
p->pSrcDst[k] = p->pSrcDst[k] + (int)(radius * (p->pSrc[a] - p->pSrcDst[k]));
p->pSrcDst[k+1] = p->pSrcDst[k+1] + (int)(radius * (p->pSrc[a+1] - p->pSrcDst[k+1]));
p->pSrcDst[k+2] = p->pSrcDst[k+2] + (int)(radius * (p->pSrc[a+2] - p->pSrcDst[k+2]));
p->srcStep = 3 ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_GT_8u_C3IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* greater than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
p->value[2] = 255 ;
p->value[1] = 255 ;
p->value[0] = 255 ;
api_return_val = fwiThreshold_GT_8u_C3IR ( &p->pSrcDst[0] + k ,p->srcStep , p->spare_roiSize , p->value );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_LT_8u_C3IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* lesser than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
p->value[0] = 0 ;
p->value[1] = 0 ;
p->value[2] = 0 ;
api_return_val = fwiThreshold_LT_8u_C3IR( &p->pSrcDst[0] + k ,p->srcStep , p->spare_roiSize , p->value );
if (api_return_val<0)
throw api_return_val ;
k = k + 3 ;
}
}
free(sqrwidth) ;
free(sqrheight) ;
free(xx) ;
free(yy) ;
free(cx) ;
free(cy) ;
TIME_FINISH(p) /* Stop Timer */
}
| [
"dudochkin.victor@gmail.com"
] | dudochkin.victor@gmail.com |
3faf9d7ffa9e8a101c506b48c02ef669fe615bda | c7bcd0590f52975d3a832e9dfb00763e8702c7ec | /src/IOE/IOEExceptions/IOEExceptionsPCH.cpp | 33b3ed2a9c6c209ffd8b0dc78431a12a3791246f | [] | no_license | stevenhartin/IOE | 656075f502b1e4f39525ec93564ba05c158215fe | d070a2f583aa26632625fe5b8115460d82349ca9 | refs/heads/master | 2020-05-23T09:47:56.408122 | 2019-05-15T22:03:38 | 2019-05-15T22:03:38 | 186,713,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29 | cpp | #include "IOEExceptionsPCH.h" | [
"steven.hartin@googlemail.com"
] | steven.hartin@googlemail.com |
2db79d5ef74797f0c90c48b039a7aaa4c365dda8 | cb6b0770bd3e01f888fc36bb658d8e5a40279408 | /bazel/google_cloud_cpp/generated/bigtable_mock.grpc.pb.h | 12dabc8ca6a3e74d43e7054d52552d4282eb79ee | [] | no_license | cschuet/tfs | 8f572dd49935ca47a05b7c78133198f24ee00b99 | 28bb8b273e6a5d0e07e475b5ff5ba338122b6aca | refs/heads/master | 2020-03-11T11:01:22.236629 | 2018-04-17T20:30:09 | 2018-04-17T20:30:09 | 129,958,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 4,797 | h | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: google/bigtable/v2/bigtable.proto
#include "google/bigtable/v2/bigtable.pb.h"
#include "google/bigtable/v2/bigtable.grpc.pb.h"
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/sync_stream.h>
#include <gmock/gmock.h>
namespace google {
namespace bigtable {
namespace v2 {
class MockBigtableStub : public Bigtable::StubInterface {
public:
MOCK_METHOD2(ReadRowsRaw, ::grpc::ClientReaderInterface< ::google::bigtable::v2::ReadRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadRowsRequest& request));
MOCK_METHOD4(AsyncReadRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::ReadRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadRowsRequest& request, ::grpc::CompletionQueue* cq, void* tag));
MOCK_METHOD3(PrepareAsyncReadRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::ReadRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadRowsRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD2(SampleRowKeysRaw, ::grpc::ClientReaderInterface< ::google::bigtable::v2::SampleRowKeysResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::SampleRowKeysRequest& request));
MOCK_METHOD4(AsyncSampleRowKeysRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::SampleRowKeysResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::SampleRowKeysRequest& request, ::grpc::CompletionQueue* cq, void* tag));
MOCK_METHOD3(PrepareAsyncSampleRowKeysRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::SampleRowKeysResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::SampleRowKeysRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(MutateRow, ::grpc::Status(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowRequest& request, ::google::bigtable::v2::MutateRowResponse* response));
MOCK_METHOD3(AsyncMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::MutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(PrepareAsyncMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::MutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD2(MutateRowsRaw, ::grpc::ClientReaderInterface< ::google::bigtable::v2::MutateRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowsRequest& request));
MOCK_METHOD4(AsyncMutateRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::MutateRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowsRequest& request, ::grpc::CompletionQueue* cq, void* tag));
MOCK_METHOD3(PrepareAsyncMutateRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::MutateRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowsRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(CheckAndMutateRow, ::grpc::Status(::grpc::ClientContext* context, const ::google::bigtable::v2::CheckAndMutateRowRequest& request, ::google::bigtable::v2::CheckAndMutateRowResponse* response));
MOCK_METHOD3(AsyncCheckAndMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::CheckAndMutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::CheckAndMutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(PrepareAsyncCheckAndMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::CheckAndMutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::CheckAndMutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(ReadModifyWriteRow, ::grpc::Status(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadModifyWriteRowRequest& request, ::google::bigtable::v2::ReadModifyWriteRowResponse* response));
MOCK_METHOD3(AsyncReadModifyWriteRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::ReadModifyWriteRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadModifyWriteRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(PrepareAsyncReadModifyWriteRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::ReadModifyWriteRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadModifyWriteRowRequest& request, ::grpc::CompletionQueue* cq));
};
} // namespace google
} // namespace bigtable
} // namespace v2
| [
"cschuet@google.com"
] | cschuet@google.com |
16c624c4e95a5c9a7ef025958af29b3c79285fee | 5390eac0ac54d2c3c1c664ae525881fa988e2cf9 | /include/Pothos/serialization/impl/mpl/vector/vector50_c.hpp | 698d13da92b1addf3d0d5ed3f1313146128e23cf | [
"BSL-1.0"
] | permissive | pothosware/pothos-serialization | 2935b8ab1fe51299a6beba2a3e11611928186849 | c59130f916a3e5b833a32ba415063f9cb306a8dd | refs/heads/master | 2021-08-16T15:22:12.642058 | 2015-12-10T03:32:04 | 2015-12-10T03:32:04 | 19,961,886 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | hpp |
#ifndef POTHOS_MPL_VECTOR_VECTOR50_C_HPP_INCLUDED
#define POTHOS_MPL_VECTOR_VECTOR50_C_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: vector50_c.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#if !defined(POTHOS_MPL_PREPROCESSING_MODE)
# include <Pothos/serialization/impl/mpl/vector/vector40_c.hpp>
# include <Pothos/serialization/impl/mpl/vector/vector50.hpp>
#endif
#include <Pothos/serialization/impl/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(POTHOS_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(POTHOS_MPL_PREPROCESSING_MODE)
# define POTHOS_MPL_PREPROCESSED_HEADER vector50_c.hpp
# include <Pothos/serialization/impl/mpl/vector/aux_/include_preprocessed.hpp>
#else
# include <Pothos/serialization/impl/mpl/aux_/config/typeof.hpp>
# include <Pothos/serialization/impl/mpl/aux_/config/ctps.hpp>
# include <Pothos/serialization/impl/preprocessor/iterate.hpp>
namespace Pothos { namespace mpl {
# define POTHOS_PP_ITERATION_PARAMS_1 \
(3,(41, 50, <boost/mpl/vector/aux_/numbered_c.hpp>))
# include POTHOS_PP_ITERATE()
}}
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_VECTOR_VECTOR50_C_HPP_INCLUDED
| [
"josh@joshknows.com"
] | josh@joshknows.com |
7d059e592d9abd6c393d2fdd4ffbe1f7db4f86e8 | fdb63867d49dcc1e9d83e55197ca8a05baf7484b | /PMBRender/shaders/TriangleFragment0.cpp | 0ea4cd58f24c806783dca1e0ff9ac2e4570ee791 | [
"MIT"
] | permissive | LRLVEC/MarchingCubes | 3ae52235cc248aea4704016ef4bff354492ea724 | 6bcfdf36a057e22aea7a906330d074eb961e2f50 | refs/heads/master | 2023-08-21T13:40:57.600602 | 2021-09-23T15:48:25 | 2021-09-23T15:48:25 | 283,292,748 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #version 450 core
in vec4 in_color;
out vec4 o_color;
void main()
{
o_color = in_color;
} | [
"mjdyx@outlook.com"
] | mjdyx@outlook.com |
1b03d3111889304a9f2629cf71c39fc48334c88d | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/skia/gm/fontmgr.cpp | 9290825e1d9ad60fe48d5433af938bd0b37ab7c7 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 13,435 | cpp | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkFontMetrics.h"
#include "include/core/SkFontMgr.h"
#include "include/core/SkFontStyle.h"
#include "include/core/SkFontTypes.h"
#include "include/core/SkGraphics.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPath.h"
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypeface.h"
#include "include/core/SkTypes.h"
#include "src/core/SkFontPriv.h"
#include "src/utils/SkMetaData.h"
#include "tools/ToolUtils.h"
#include <utility>
// limit this just so we don't take too long to draw
#define MAX_FAMILIES 30
static SkScalar drawString(SkCanvas* canvas, const SkString& text, SkScalar x,
SkScalar y, const SkFont& font) {
canvas->drawString(text, x, y, font, SkPaint());
return x + font.measureText(text.c_str(), text.size(), SkTextEncoding::kUTF8);
}
static SkScalar drawCharacter(SkCanvas* canvas, uint32_t character, SkScalar x,
SkScalar y, const SkFont& origFont, SkFontMgr* fm,
const char* fontName, const char* bcp47[], int bcp47Count,
const SkFontStyle& fontStyle) {
SkFont font = origFont;
// find typeface containing the requested character and draw it
SkString ch;
ch.appendUnichar(character);
sk_sp<SkTypeface> typeface(fm->matchFamilyStyleCharacter(fontName, fontStyle,
bcp47, bcp47Count, character));
font.setTypeface(typeface);
x = drawString(canvas, ch, x, y, font) + 20;
if (nullptr == typeface) {
return x;
}
// repeat the process, but this time use the family name of the typeface
// from the first pass. This emulates the behavior in Blink where it
// it expects to get the same glyph when following this pattern.
SkString familyName;
typeface->getFamilyName(&familyName);
font.setTypeface(fm->legacyMakeTypeface(familyName.c_str(), typeface->fontStyle()));
return drawString(canvas, ch, x, y, font) + 20;
}
static const char* zh = "zh";
static const char* ja = "ja";
class FontMgrGM : public skiagm::GM {
public:
FontMgrGM() {
SkGraphics::SetFontCacheLimit(16 * 1024 * 1024);
fName.set("fontmgr_iter");
fFM = SkFontMgr::RefDefault();
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(1536, 768);
}
void onDraw(SkCanvas* canvas) override {
SkScalar y = 20;
SkFont font;
font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
font.setSubpixel(true);
font.setSize(17);
SkFontMgr* fm = fFM.get();
int count = SkMin32(fm->countFamilies(), MAX_FAMILIES);
for (int i = 0; i < count; ++i) {
SkString familyName;
fm->getFamilyName(i, &familyName);
font.setTypeface(nullptr);
(void)drawString(canvas, familyName, 20, y, font);
SkScalar x = 220;
sk_sp<SkFontStyleSet> set(fm->createStyleSet(i));
for (int j = 0; j < set->count(); ++j) {
SkString sname;
SkFontStyle fs;
set->getStyle(j, &fs, &sname);
sname.appendf(" [%d %d %d]", fs.weight(), fs.width(), fs.slant());
font.setTypeface(sk_sp<SkTypeface>(set->createTypeface(j)));
x = drawString(canvas, sname, x, y, font) + 20;
// check to see that we get different glyphs in japanese and chinese
x = drawCharacter(canvas, 0x5203, x, y, font, fm, familyName.c_str(), &zh, 1, fs);
x = drawCharacter(canvas, 0x5203, x, y, font, fm, familyName.c_str(), &ja, 1, fs);
// check that emoji characters are found
x = drawCharacter(canvas, 0x1f601, x, y, font, fm, familyName.c_str(), nullptr,0, fs);
}
y += 24;
}
}
private:
sk_sp<SkFontMgr> fFM;
SkString fName;
typedef GM INHERITED;
};
class FontMgrMatchGM : public skiagm::GM {
sk_sp<SkFontMgr> fFM;
public:
FontMgrMatchGM() : fFM(SkFontMgr::RefDefault()) {
SkGraphics::SetFontCacheLimit(16 * 1024 * 1024);
}
protected:
SkString onShortName() override {
return SkString("fontmgr_match");
}
SkISize onISize() override {
return SkISize::Make(640, 1024);
}
void iterateFamily(SkCanvas* canvas, const SkFont& font, SkFontStyleSet* fset) {
SkFont f(font);
SkScalar y = 0;
for (int j = 0; j < fset->count(); ++j) {
SkString sname;
SkFontStyle fs;
fset->getStyle(j, &fs, &sname);
sname.appendf(" [%d %d]", fs.weight(), fs.width());
f.setTypeface(sk_sp<SkTypeface>(fset->createTypeface(j)));
(void)drawString(canvas, sname, 0, y, f);
y += 24;
}
}
void exploreFamily(SkCanvas* canvas, const SkFont& font, SkFontStyleSet* fset) {
SkFont f(font);
SkScalar y = 0;
for (int weight = 100; weight <= 900; weight += 200) {
for (int width = 1; width <= 9; width += 2) {
SkFontStyle fs(weight, width, SkFontStyle::kUpright_Slant);
sk_sp<SkTypeface> face(fset->matchStyle(fs));
if (face) {
SkString str;
str.printf("request [%d %d]", fs.weight(), fs.width());
f.setTypeface(std::move(face));
(void)drawString(canvas, str, 0, y, f);
y += 24;
}
}
}
}
DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {
SkFont font;
font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
font.setSubpixel(true);
font.setSize(17);
const char* gNames[] = {
"Helvetica Neue", "Arial", "sans"
};
sk_sp<SkFontStyleSet> fset;
for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) {
fset.reset(fFM->matchFamily(gNames[i]));
if (fset->count() > 0) {
break;
}
}
if (nullptr == fset.get()) {
*errorMsg = "No SkFontStyleSet";
return DrawResult::kFail;
}
canvas->translate(20, 40);
this->exploreFamily(canvas, font, fset.get());
canvas->translate(150, 0);
this->iterateFamily(canvas, font, fset.get());
return DrawResult::kOk;
}
private:
typedef GM INHERITED;
};
class FontMgrBoundsGM : public skiagm::GM {
public:
FontMgrBoundsGM(double scale, double skew)
: fFM(SkFontMgr::RefDefault())
, fName("fontmgr_bounds")
, fScaleX(SkDoubleToScalar(scale))
, fSkewX(SkDoubleToScalar(skew))
, fLabelBounds(false)
{
if (scale != 1 || skew != 0) {
fName.appendf("_%g_%g", scale, skew);
}
}
bool onGetControls(SkMetaData* controls) override {
controls->setBool("Label Bounds", fLabelBounds);
return true;
}
void onSetControls(const SkMetaData& controls) override {
controls.findBool("Label Bounds", &fLabelBounds);
}
static void show_bounds(SkCanvas* canvas, const SkFont& font, SkScalar x, SkScalar y,
SkColor boundsColor, bool labelBounds)
{
SkRect fontBounds = SkFontPriv::GetFontBounds(font).makeOffset(x, y);
SkPaint boundsPaint;
boundsPaint.setAntiAlias(true);
boundsPaint.setColor(boundsColor);
boundsPaint.setStyle(SkPaint::kStroke_Style);
canvas->drawRect(fontBounds, boundsPaint);
SkFontMetrics fm;
font.getMetrics(&fm);
SkPaint metricsPaint(boundsPaint);
metricsPaint.setStyle(SkPaint::kFill_Style);
metricsPaint.setAlphaf(0.25f);
if ((fm.fFlags & SkFontMetrics::kUnderlinePositionIsValid_Flag) &&
(fm.fFlags & SkFontMetrics::kUnderlineThicknessIsValid_Flag))
{
SkRect underline{ fontBounds.fLeft, fm.fUnderlinePosition+y,
fontBounds.fRight, fm.fUnderlinePosition+y + fm.fUnderlineThickness };
canvas->drawRect(underline, metricsPaint);
}
if ((fm.fFlags & SkFontMetrics::kStrikeoutPositionIsValid_Flag) &&
(fm.fFlags & SkFontMetrics::kStrikeoutThicknessIsValid_Flag))
{
SkRect strikeout{ fontBounds.fLeft, fm.fStrikeoutPosition+y - fm.fStrikeoutThickness,
fontBounds.fRight, fm.fStrikeoutPosition+y };
canvas->drawRect(strikeout, metricsPaint);
}
SkGlyphID left = 0, right = 0, top = 0, bottom = 0;
{
int numGlyphs = font.getTypefaceOrDefault()->countGlyphs();
SkRect min = {0, 0, 0, 0};
for (int i = 0; i < numGlyphs; ++i) {
SkGlyphID glyphId = i;
SkRect cur;
font.getBounds(&glyphId, 1, &cur, nullptr);
if (cur.fLeft < min.fLeft ) { min.fLeft = cur.fLeft; left = i; }
if (cur.fTop < min.fTop ) { min.fTop = cur.fTop ; top = i; }
if (min.fRight < cur.fRight ) { min.fRight = cur.fRight; right = i; }
if (min.fBottom < cur.fBottom) { min.fBottom = cur.fBottom; bottom = i; }
}
}
SkGlyphID str[] = { left, right, top, bottom };
SkPoint location[] = {
{fontBounds.left(), fontBounds.centerY()},
{fontBounds.right(), fontBounds.centerY()},
{fontBounds.centerX(), fontBounds.top()},
{fontBounds.centerX(), fontBounds.bottom()}
};
SkFont labelFont;
labelFont.setEdging(SkFont::Edging::kAntiAlias);
labelFont.setTypeface(ToolUtils::create_portable_typeface());
if (labelBounds) {
SkString name;
font.getTypefaceOrDefault()->getFamilyName(&name);
canvas->drawString(name, fontBounds.fLeft, fontBounds.fBottom, labelFont, SkPaint());
}
for (size_t i = 0; i < SK_ARRAY_COUNT(str); ++i) {
SkPath path;
font.getPath(str[i], &path);
path.offset(x, y);
SkPaint::Style style = path.isEmpty() ? SkPaint::kFill_Style : SkPaint::kStroke_Style;
SkPaint glyphPaint;
glyphPaint.setStyle(style);
canvas->drawSimpleText(&str[i], sizeof(str[0]), SkTextEncoding::kGlyphID, x, y, font, glyphPaint);
if (labelBounds) {
SkString glyphStr;
glyphStr.appendS32(str[i]);
canvas->drawString(glyphStr, location[i].fX, location[i].fY, labelFont, SkPaint());
}
}
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(1024, 850);
}
void onDraw(SkCanvas* canvas) override {
SkFont font;
font.setEdging(SkFont::Edging::kAntiAlias);
font.setSubpixel(true);
font.setSize(100);
font.setScaleX(fScaleX);
font.setSkewX(fSkewX);
const SkColor boundsColors[2] = { SK_ColorRED, SK_ColorBLUE };
SkFontMgr* fm = fFM.get();
int count = SkMin32(fm->countFamilies(), 32);
int index = 0;
SkScalar x = 0, y = 0;
canvas->translate(10, 120);
for (int i = 0; i < count; ++i) {
sk_sp<SkFontStyleSet> set(fm->createStyleSet(i));
for (int j = 0; j < set->count() && j < 3; ++j) {
font.setTypeface(sk_sp<SkTypeface>(set->createTypeface(j)));
// Fonts with lots of glyphs are interesting, but can take a long time to find
// the glyphs which make up the maximum extent.
if (font.getTypefaceOrDefault() && font.getTypefaceOrDefault()->countGlyphs() < 1000) {
SkRect fontBounds = SkFontPriv::GetFontBounds(font);
x -= fontBounds.fLeft;
show_bounds(canvas, font, x, y, boundsColors[index & 1], fLabelBounds);
x += fontBounds.fRight + 20;
index += 1;
if (x > 900) {
x = 0;
y += 160;
}
if (y >= 700) {
return;
}
}
}
}
}
private:
const sk_sp<SkFontMgr> fFM;
SkString fName;
const SkScalar fScaleX;
const SkScalar fSkewX;
bool fLabelBounds;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM(return new FontMgrGM;)
DEF_GM(return new FontMgrMatchGM;)
DEF_GM(return new FontMgrBoundsGM(1.0, 0);)
DEF_GM(return new FontMgrBoundsGM(0.75, 0);)
DEF_GM(return new FontMgrBoundsGM(1.0, -0.25);)
| [
"42931768+uzair-jaleel@users.noreply.github.com"
] | 42931768+uzair-jaleel@users.noreply.github.com |
d5e1d0f3219703add4574c51bc6f4a5708d618f6 | 8085f16eaf5133bebb45aeeabb9b172ae3db4176 | /hdoj/hdu2222/hdu2222/main.cpp | 4e6a6c94d5ba9791803ba6f783690dbbbe160883 | [] | no_license | EyciaZhou/acm | ff0dd40971424f338369eca8507e8c339497f946 | 50121929dc658be717b8fa6076ec28dea915ce97 | refs/heads/master | 2020-05-01T08:57:48.118961 | 2015-06-09T06:48:53 | 2015-06-09T06:48:53 | 35,026,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,141 | cpp | //
// main.cpp
// poj3080
//
// Created by eycia on 14/12/5.
// Copyright (c) 2014年 eycia. All rights reserved.
//
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
char s[1000005];
typedef struct node {
int n[26];
int f; //fall
int d; //date
int fa; //fa
int b; //iis
} NODE;
int n;
NODE trie[600000];
int list[600000];
void dof() {
int i, j;
int h = -1, t = 0;
for (i = 0; i <= n; i++) {
if (trie[0].n[i] >= 0) {
trie[trie[0].n[i]].f = 0;
for (j = 0; j <= n; j++) {
if (trie[trie[0].n[i]].n[j] >= 0) {
h = (h + 1) % 600000;
list[h] = trie[trie[0].n[i]].n[j];
}
}
}
}
while ((h + 1) % 600000 != t) {
int p = list[t];
//cout << p << endl;
t = (t + 1) % 600000;
for (i = 0; i <= n; i++) {
if (trie[p].n[i] >= 0) {
h = (h + 1) % 600000;
list[h] = trie[p].n[i];
}
}
int n = trie[p].d;
int q = trie[trie[p].fa].f;
while (true) {
if (trie[q].n[n] >= 0) {
trie[p].f = trie[q].n[n];
//if (trie[trie[q].n[n]].b > 0) {
//trie[p].b += trie[trie[q].n[n]].b;
//trie[trie[q].n[n]].b += trie[p].b;
//}
break;
}else{
if (q == 0) {
trie[p].f = 0;
break;
}
}
q = trie[q].f;
}
}
}
int getnext(int f, int n) {
while (true) {
if (trie[f].n[n] >= 0) {
return trie[f].n[n];
}
if (f == 0) {
return 0;
}
f = trie[f].f;
}
}
void flf(int f, int k) {
while (true) {
if (f == 0) {
return ;
}
trie[f].b -= k;
//cout << trie[f].b << endl;
f = trie[f].f;
}
}
void up(int f) {
cout << "aa" << f << endl;
int k = 0;
while (true) {
if (f == 0) {
return ;
}
k += trie[f].b;
trie[f].b = k;
//cout << trie[f].b << endl;
f = trie[f].f;
}
}
char key[100];
int main(int argc, const char * argv[]) {
int ff;
scanf("%d", &ff);
n = 25;
while (ff--) {
int mem = 0;
memset(trie[0].n, -1, sizeof(trie[0].n));
trie[0].f = -1;
trie[0].fa = -1;
trie[0].d = -1;
trie[0].b = false;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", key);
int sl = strlen(key);
int now = 0;
for (int j = 0; j < sl; j++) {
if (trie[now].n[key[j]-'a'] < 0) {
mem++;
memset(trie[mem].n, -1, sizeof(trie[mem].n));
trie[mem].f = -1;
trie[mem].fa = now;
trie[mem].d = key[j] - 'a';
trie[mem].b = 0;
trie[now].n[key[j]-'a'] = mem;
}
now = trie[now].n[key[j]-'a'];
}
trie[now].b++;
}
dof();
for (int i = 1; i <= mem; i++) {
if (trie[i].n[trie[i].d] < 0) {
up(i);
}
}
scanf("%s", s);
int sl = strlen(s);
int now = 0, ans = 0, re = 0;
for (int i = 0; i < sl; i++) {
re = getnext(now, s[i] - 'a');
ans += trie[re].b;
//trie[re].b = 0;
if (trie[re].b > 0) {
//flf(re, trie[re].b);
cout << endl;
}
now = re;
}
printf("%d\n", ans);
}
}
/*
2
2
sher
he
she
2
sher
he
sher
1
6
she
he
he
say
shr
her
yasherhe
1
6
she
he
he
say
shr
her
yasherhs
10
2
abcdef
bcd
abcdef
1
h
hhhhh
5
bhea
her
he
h
ha
bhera
5
bhea
her
he
h
ha
bhera
*/ | [
"zhou.eycia@gmail.com"
] | zhou.eycia@gmail.com |
5ac91959ff9ba14f2f069715b94ef51f866c6ca6 | 27ef6b50e8d2d388ab0f745e5c402117baedf983 | /03Decorator/DarkRoast.cpp | a54946dc9d1a2cd908eb4ab2ef333f0049f29b4a | [] | no_license | sanqima/HeadFirstDesignPatternsCPP | c7decb6d4af5165ba5ada99e22cd4fe095e4bff3 | 1d8e20d9745610d69fbce92a600125a7ba5e1386 | refs/heads/master | 2023-03-16T18:45:04.567965 | 2020-09-28T13:48:37 | 2020-09-28T13:48:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cpp | #include "DarkRoast.h"
namespace decorator
{
double DarkRoast::cost()
{
return 0.99f;
}
DarkRoast::DarkRoast()
{
description = "Dark Roast Coffee";
}
}
| [
"knapecz.adam@gmail.com"
] | knapecz.adam@gmail.com |
dd2233b2887285734ea8172b079447d56de89279 | fa8bc6a9c08210def6028f124a746da50b16c162 | /Source/Accelerate/AIManager.h | 7f1af4727626aee985d79d5637c68e840933ae2b | [] | no_license | arorabharat144/Accelerate | 661fe183c355a605817fd294c0260d610ce6a440 | 3c2791d093412ea69fa85b69cbe42598b94023b2 | refs/heads/master | 2022-01-05T06:35:47.832941 | 2019-05-11T18:44:38 | 2019-05-11T18:44:38 | 186,170,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,646 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "AICheckpoint.h"
#include <vector>
#include "AIManager.generated.h"
constexpr int MAX_AI = 11;
UENUM()
enum class AIPlayerActions
{
Left UMETA(DisplayName = "Left"),
Right UMETA(DisplayName = "Right"),
Nothing UMETA(DisplayName = "Nothing"),
};
UENUM()
enum class BattleAIStates
{
Patrol UMETA(DisplayName = "Patrol"),
Attack UMETA(DisplayName = "Attack"),
};
class AAcceleratePlayer;
UCLASS()
class ACCELERATE_API AAIManager : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AAIManager();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void Init();
// Race AI Functions
AAICheckpoint* RaceUpdate(FVector playerLocation, AAICheckpoint* currentCheckpoint);
AAICheckpoint* GetCheckpoint(uint32 path, uint32 checkpoint);
// Battle AI Functions
AAICheckpoint* BattleUpdate(AAICheckpoint* currentCheckpoint, FVector currentLocation, int& iterate);
AAcceleratePlayer* GetTarget(FVector currentLocation, float heightDifference);
// Functions for Race and Battle AI
AIPlayerActions GetAction(FVector direction, FVector location, FVector targetLocation) const;
//UPROPERTY(EditAnywhere, Category = "Designer Tools")
float checkpointCollideDistance{ 1500.0f };
private:
bool mInit{ false };
std::vector<std::vector<AAICheckpoint*>> mCheckpoints;
TArray<AAcceleratePlayer*> mPlayers;
};
| [
"arorabharat144@gmail.com"
] | arorabharat144@gmail.com |
7a09b88a2e2987bbdf05305b6da0b6dd4151b388 | 29948885a97f946dd46d25dcce1ae08247affb8a | /Examen2/proxy.cpp | 25e70dd14a2a925f42b5ecbf2751c9f25517e412 | [] | no_license | osanseviero/Software_Engineering | 8c9d573fd8793601d8ee25f827f7295c940a9174 | 396244b0de12275115959ce11c008a1bb08a7db2 | refs/heads/master | 2020-04-12T05:42:19.118305 | 2016-12-08T02:54:55 | 2016-12-08T02:54:58 | 65,292,647 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | class Proxy
{
private:
int id;
News* news;
static int next;
public:
Proxy() {
id = next++;
news = NULL;
}
void publish(std::string pub) {
if(!news) {
news = new News(id);
}
news->publish(pub);
}
};
int Proxy::next = 1; | [
"osanseviero@gmail.com"
] | osanseviero@gmail.com |
d672d244bb65a3d379955d8f7bad5aee00262a84 | 5a8fafefd7712b3730b27c5907ca8f54b567e328 | /neb/inc/com/centreon/engine/logging/broker.hh | f90ee9e3eb2d7bdfe489848db50a01accaad16e1 | [
"Apache-2.0"
] | permissive | joe4568/centreon-broker | 672d831389c17f92f09948704437c4bc9026998d | daf454371520989573c810be1f6dfca40979a75d | refs/heads/master | 2020-04-13T05:11:03.126655 | 2018-12-24T14:53:34 | 2018-12-24T14:53:34 | 162,984,149 | 0 | 0 | Apache-2.0 | 2018-12-24T11:33:05 | 2018-12-24T11:33:04 | null | UTF-8 | C++ | false | false | 2,143 | hh | /*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#ifndef CCE_LOGGING_BROKER_HH
# define CCE_LOGGING_BROKER_HH
# include "com/centreon/concurrency/thread.hh"
# include "com/centreon/engine/namespace.hh"
# include "com/centreon/logging/backend.hh"
CCE_BEGIN()
namespace logging {
/**
* @class broker broker.hh
* @brief Call broker for all logging message.
*
* Call broker for all logging message without debug.
*/
class broker
: public com::centreon::logging::backend {
public:
broker();
broker(broker const& right);
~broker() throw ();
broker& operator=(broker const& right);
void close() throw ();
void log(
unsigned long long types,
unsigned int verbose,
char const* msg,
unsigned int size) throw ();
void open();
void reopen();
void show_pid(bool enable);
void show_timestamp(com::centreon::logging::time_precision val);
void show_thread_id(bool enable);
private:
bool _enable;
concurrency::thread_id _thread;
};
}
CCE_END()
#endif // !CCE_LOGGING_BROKER_HH
| [
"mkermagoret@centreon.com"
] | mkermagoret@centreon.com |
1e820c8a4fc99de24769b8907d28453a22f1601d | 0f46bca9176f453ea28be8a7c91adfdeee4af3e5 | /src/gui/CameraGUI.cpp | 1f9e6fe51ff53bcbd5d70a4577df1de62e9e693b | [] | no_license | PeterZs/RIM | 3181baf1b668c719ae55dbc0448228d233083cd4 | 81639c2f06b969c668f6d187f6cccf5d97a71ba7 | refs/heads/master | 2022-12-01T04:35:23.344641 | 2020-08-06T07:29:16 | 2020-08-06T07:29:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | cpp | #include "common.h"
#include "gui/CameraGUI.h"
#include "managers/TextureManager.h"
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <glm/gtc/type_ptr.hpp>
CameraGUI::CameraGUI(CameraFPS* cam)
{
setCamera(cam);
visible = true;
displayname = "Camera options";
}
CameraGUI::~CameraGUI()
{}
void CameraGUI::setCamera(CameraFPS* cam)
{
this->camptr = cam;
}
void CameraGUI::draw(GLFWwindow* window, int order)
{
if (!camptr) return;
ImVec2 outerSize = ImGui::GetItemRectSize();
bool dirty = false;
if (ImGui::DragFloat3("Position", glm::value_ptr(camptr->position), 0.01f + abs(glm::length(camptr->position) / 100.f ) )) dirty = true;
//if (ImGui::DragFloat3("Orientation", glm::value_ptr(m.gl.diffuse), 0.01f, 0.0f, 1e12f)) dirty = true;
if (ImGui::DragFloat("Vertical FOV", &camptr->verticalFov_deg, 0.05f, 0.0f, 180.f)) dirty = true;
if (ImGui::DragFloat("Near", &camptr->nearplane, 0.0001f + camptr->nearplane / 100.f, 0.00001f, camptr->farplane - 0.0001f)) dirty = true;
if (ImGui::DragFloat("Far", &camptr->farplane, 0.0001f + camptr->farplane / 100.f, camptr->nearplane + 0.0001f, 1e12f)) dirty = true;
if (ImGui::DragFloat("Rotation speed", &camptr->rot_speed, 0.001f, 0.0f, 100.f)) dirty = true;
if (ImGui::DragFloat("Motion speed", &camptr->mov_speed, 0.001f, 0.0f, 100.f)) dirty = true;
} | [
"RotateMe@gmail.com"
] | RotateMe@gmail.com |
9273677cb3cdf6c409910c6fc784c896e48a9a38 | dd1385ee93b0135f53c705f9d89f7936390a8fd8 | /src/glresource/glresource.h | a69df981c54a22482b40926dc953a57ed3b2f99d | [] | no_license | catompiler/celestial-battle | fcceff6d1551398bda97a62930295986d1217281 | 1998c50867317d71326caec54ecbc47749f71445 | refs/heads/master | 2016-09-05T09:51:32.493447 | 2015-05-09T16:47:44 | 2015-05-09T16:47:44 | 35,336,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 338 | h | #ifndef _GLRESOURCE_H
#define _GLRESOURCE_H
#include "opengl/opengl.h"
OPENGL_NAMESPACE_BEGIN
class Resource
{
public:
Resource();
Resource(GLuint id_);
virtual ~Resource();
GLuint id();
operator GLuint();
protected:
GLuint _id;
};
OPENGL_NAMESPACE_END
#endif //_GLRESOURCE_H
| [
"artem.lab@localhost"
] | artem.lab@localhost |
68192a75cf30157f16d1880680a85b52c4f9a021 | 5f3ba1affc395e24a762fe488b72bf9ae219e145 | /ScoreManager.h | ef26d7f65f72953907163f2fa0ec0ffa8f5b9aa0 | [] | no_license | Kawazuini/PurPose | a9e01acc35b6a64e82809d5235dc0c9d58807721 | d019887fc19cb22136dc6c16b14ced2461fa7aa1 | refs/heads/master | 2020-06-22T03:24:03.679572 | 2017-08-21T10:27:48 | 2017-08-21T10:27:48 | 74,759,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | h | /**
* @file ScoreManager.h
* @brief ScoreManager
* @author Maeda Takumi
*/
#ifndef SCOREMANAGER_H
#define SCOREMANAGER_H
#include "GameState.h"
/**
* @brief \~english management of game score
* @brief \~japanese ゲームスコア管理
* @author \~ Maeda Takumi
*/
class ScoreManager final {
private:
/* ランキングファイル名 */ static const String RANK_FILE_NAME;
/* ランキングファイル */ KFile mFile;
/* 得点情報 */
struct Score {
/* 得点 */ int mScore;
/* 名前 */ String mName;
/* 詳細 */ String mBrief;
};
/* スコアランキング */ Vector<Score> mRanking;
public:
ScoreManager();
~ScoreManager() = default;
/**
* \~english
* @brief draw score.
* @param aUI drawing target
* @param aRank rank information
* \~japanese
* @brief 得点を描画します。
* @param aUI 描画対象
* @param aRank 順位情報
*/
void draw(KGLUI& aUI,const int& aRank) const;
/**
* \~english
* @brief add new score
* @param aState game state
* @param aClear clear flag
* @return score rank
* \~japanese
* @brief 新しいスコアを追加します。
* @param aState ゲーム状態
* @param aClear クリアフラグ
* @return 順位
*/
int newScore(const GameState& aState, const bool& aClear = false);
/**
* \~english
* @brief calc score
* @param aState game state
* @return score
* \~japanese
* @brief スコアを計算します。
* @param aState ゲーム状態
* @return スコア
*/
static int calcScore(const GameState& aState);
};
#endif /* SCOREMANAGER_H */
| [
"kawazuini@gmail.com"
] | kawazuini@gmail.com |
db16bc2a02b455eb7d7156bb1a70fda0525593eb | eda7f1e5c79682bf55cfa09582a82ce071ee6cee | /aspects/thermal/network/test/UtThermFileParser.cpp | 11a06931118b688a6e47857b70de4263dea2eee2 | [
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nasa/gunns | 923f4f7218e2ecd0a18213fe5494c2d79a566bb3 | d5455e3eaa8b50599bdb16e4867a880705298f62 | refs/heads/master | 2023-08-30T06:39:08.984844 | 2023-07-27T12:18:42 | 2023-07-27T12:18:42 | 235,422,976 | 34 | 11 | NOASSERTION | 2023-08-30T15:11:41 | 2020-01-21T19:21:16 | C++ | UTF-8 | C++ | false | false | 28,542 | cpp | /************************** TRICK HEADER ***********************************************************
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
LIBRARY DEPENDENCY:
((aspects/thermal/network/ThermFileParser.o))
***************************************************************************************************/
#include "UtThermFileParser.hh"
#include "software/exceptions/TsParseException.hh"
#include "software/exceptions/TsOutOfBoundsException.hh"
#include <iostream>
#include <string>
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details This is the default constructor for the UtThermFileParser class.
////////////////////////////////////////////////////////////////////////////////////////////////////
UtThermFileParser::UtThermFileParser()
:
tTimeStep(),
tTol(),
tNameError(),
tArticle(),
tNodeFile(),
tCondFile(),
tRadFile(),
tHtrFile(),
tPanFile(),
tEtcFile(),
tThermInputFile(),
tNumNodes(),
tNode(),
tNodeName(),
tSpaceNode(),
tNumLinksCap(),
tCap(),
tCapName(),
tCapTemperature(),
tCapCapacitance(),
tCapGroup(),
tNumLinksCond(),
tCond(),
tCondName(),
tCondNode0(),
tCondNode1(),
tCondConductivity(),
tCond2(),
tCond2Name(),
tNumLinksRad(),
tRad(),
tRadName(),
tRadNode0(),
tRadNode1(),
tRadCoefficient(),
tNumLinksHtr(),
tHtrA(),
tHtrAName(),
tHtrAScalar(),
tHtrAPorts(),
tHtrANode0(),
tHtrANode1(),
tHtrANode2(),
tHtrANode3(),
tHtrANode4(),
tHtrANode5(),
tHtrAFrac0(),
tHtrAFrac1(),
tHtrAFrac2(),
tHtrAFrac3(),
tHtrAFrac4(),
tHtrAFrac5(),
tHtrB(),
tHtrBName(),
tHtrBScalar(),
tHtrBPorts(),
tHtrBNode0(),
tHtrBNode1(),
tHtrBNode2(),
tHtrBNode3(),
tHtrBNode4(),
tHtrBNode5(),
tHtrBFrac0(),
tHtrBFrac1(),
tHtrBFrac2(),
tHtrBFrac3(),
tHtrBFrac4(),
tHtrBFrac5(),
tNumLinksPan(),
tPan(),
tPanName(),
tPanPorts(),
tPanNode0(),
tPanNode1(),
tPanArea(),
tPanAbsorptivity(),
tNumLinksPot(),
tPot(),
tPotName(),
tPotNode(),
tPotTemperature(),
tPotConductivity(),
tNumLinksSrc(),
tSrc(),
tSrcName(),
tSrcNode0(),
tSrcNode1(),
tSrcNode2(),
tSrcNode3(),
tSrcFrac0(),
tSrcFrac1(),
tSrcFrac2(),
tSrcFrac3(),
tSrcFlux()
{
//do nothing
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details This is the default destructor for the UtThermFileParser class.
////////////////////////////////////////////////////////////////////////////////////////////////////
UtThermFileParser::~UtThermFileParser()
{
//do nothing
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Executed after each unit test.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::tearDown()
{
/// - Deletes for news in setUp
delete tArticle;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Executed before each unit test.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::setUp()
{
/// - test technical data
tTol = 0.0001;
tTimeStep = 0.1;
tNameError = "(error setting name)";
/// - Declare the config-files.
tNodeFile = "ThermNodes_base.xml";
tCondFile = "ThermLinksCond_base.xml";
tRadFile = "ThermLinksRad_base.xml";
tHtrFile = "HtrRegistry_base.xml";
tPanFile = "ThermLinksPan_base.xml";
tEtcFile = "ThermLinksEtc_base.xml";
/// - Declare the input-files.
tThermInputFile = "ThermInput_base.xml";
/// - nominal node data from the test case
tNumNodes = 22;
tNode = 15;
tNodeName = "CMRCSNR1_20";
tSpaceNode = "SPACE_1";
/// - nominal capacitance link data from the test case
tNumLinksCap = 21;
tCap = 6;
tCapName = "cap_CMBCKSHL_13330";
tCapTemperature = 455;
tCapCapacitance = 4722.05;
tCapGroup = 1;
/// - nominal conduction link data from the test case
tNumLinksCond = 8;
tCond = 5;
tCondNode0 = "CMPRPHYT_2";
tCondNode1 = "CMPRPHYT_20";
tCondName = "cond " + tCondNode0 + " to " + tCondNode1;
tCondConductivity = 0.40;
tCond2 = 6;
tCond2Name = "hydrazine tank bracket";
/// - nominal radiation link data from the test case
tNumLinksRad = 17;
tRad = 7;
tRadNode0 = "CMBCKSHL_13330";
tRadNode1 = "CMHS_62803";
tRadName = "rad " + tRadNode0 + " to " + tRadNode1;
tRadCoefficient = 53.1;
/// - nominal ThermalPanel data from the test case
tNumLinksPan = 3;
tPan = 0;
tPanName = "shell";
tPanPorts = 2;
tPanNode0 = "CMBCKSHL_13330";
tPanNode1 = "CMHS_48233";
tPanArea = 14.531;
tPanAbsorptivity = 0.43;
/// - nominal heater A data from the test case
tNumLinksHtr = 3;
tHtrA = 0;
tHtrAName = "eclss heater";
tHtrAScalar = 0.93;
tHtrAPorts = 3;
tHtrANode0 = "CECLSS_46";
tHtrANode1 = "CECLSS_26";
tHtrANode2 = "CECLSS_161";
tHtrAFrac0 = 0.46;
tHtrAFrac1 = 0.46;
tHtrAFrac2 = 0.08;
/// - nominal heater B data from the test case
tHtrB = 2;
tHtrBName = "tank heater";
tHtrBScalar = 0.99;
tHtrBPorts = 2;
tHtrBNode0 = "CMPRPHET_1";
tHtrBNode1 = "CMPRPHET_100";
tHtrBFrac0 = 0.5;
tHtrBFrac1 = 0.5;
/// - nominal potential link data from the test case
tNumLinksPot = 2;
tPot = 1;
tPotName = "pressure vessel";
tPotNode = "CPV_5380";
tPotTemperature = 318;
tPotConductivity = 1e12;
/// - nominal source link data from the test case
tNumLinksSrc = 2;
tSrc = 1;
tSrcName = "multi-node source";
tSrcNode0 = "CMAFTGUS_30";
tSrcNode1 = "CMAFTGUS_31";
tSrcNode2 = "CRRMECH_200";
tSrcNode3 = "CRRMECH_300";
tSrcFrac0 = 0.3;
tSrcFrac1 = 0.3;
tSrcFrac2 = 0.2;
tSrcFrac3 = 0.2;
tSrcFlux = 100;
/// - Create the test article.
tArticle = new FriendlyThermFileParser();
/// - Simulate the setting of config-files by ThermalNetwork.
tArticle->mNodeFile = tNodeFile;
tArticle->mCondFile = tCondFile;
tArticle->mRadFile = tRadFile;
tArticle->mHtrFile = tHtrFile;
tArticle->mPanFile = tPanFile;
tArticle->mEtcFile = tEtcFile;
/// - Read files!
tArticle->initialize("article_nominal");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for appropriate construction.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testConstruction()
{
std::cout << "\n -----------------------------------------------------------------------------";
std::cout << "\n ThermFileParser 01: Testing default construction ..............";
/// - Default construct an un-initialized test article.
FriendlyThermFileParser article;
/// @test Logistic data
CPPUNIT_ASSERT_EQUAL_MESSAGE("NOT_FOUND", -99, article.NOT_FOUND );
CPPUNIT_ASSERT_EQUAL_MESSAGE("areNodesRegistered", false, article.areNodesRegistered );
CPPUNIT_ASSERT_MESSAGE("mName", "" == article.mName );
/// @test Node data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numNodes", 0, article.numNodes );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vNodeNames", 0, static_cast<int>(article.vNodeNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("mNodeMap", 0, static_cast<int>(article.mNodeMap.size()) );
/// @test Capacitance link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksCap", 0, article.numLinksCap );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCapNames", 0, static_cast<int>(article.vCapNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCapTemperatures", 0, static_cast<int>(article.vCapTemperatures.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCapCapacitances", 0, static_cast<int>(article.vCapCapacitances.size()) );
/// @test Conduction link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksCond", 0, article.numLinksCond );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondNames", 0, static_cast<int>(article.vCondNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondPorts0", 0, static_cast<int>(article.vCondPorts0.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondPorts1", 0, static_cast<int>(article.vCondPorts1.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondConductivities", 0, static_cast<int>(article.vCondConductivities.size()) );
/// @test Radiation link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksRad", 0, article.numLinksRad );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadNames", 0, static_cast<int>(article.vRadNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadPorts0", 0, static_cast<int>(article.vRadPorts0.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadPorts1", 0, static_cast<int>(article.vRadPorts1.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadCoefficients", 0, static_cast<int>(article.vRadCoefficients.size()) );
/// @test Heater link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksHtr", 0, article.numLinksHtr );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrNames", 0, static_cast<int>(article.vHtrNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrScalars", 0, static_cast<int>(article.vHtrScalars.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrPorts", 0, static_cast<int>(article.vHtrPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrFracs", 0, static_cast<int>(article.vHtrFracs.size()) );
/// @test Panel data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksPan", 0, article.numLinksPan );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanNames", 0, static_cast<int>(article.vPanNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanAbsorptivities", 0, static_cast<int>(article.vPanAbsorptivities.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanPorts", 0, static_cast<int>(article.vPanPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanFracs", 0, static_cast<int>(article.vPanFracs.size()) );
/// @test Potential link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksPot", 0, article.numLinksPot );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotNames", 0, static_cast<int>(article.vPotNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotPorts", 0, static_cast<int>(article.vPotPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotTemperatures", 0, static_cast<int>(article.vPotTemperatures.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotConductivities", 0, static_cast<int>(article.vPotConductivities.size()) );
/// @test Source link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksSrc", 0, article.numLinksSrc );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcNames", 0, static_cast<int>(article.vSrcNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcInits", 0, static_cast<int>(article.vSrcInits.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcPorts", 0, static_cast<int>(article.vSrcPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcFracs", 0, static_cast<int>(article.vSrcFracs.size()) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for appropriate handling of off-nominal file parsing.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testParseErrorHandling()
{
std::cout << "\n ThermFileParser 02: Testing off-nominal file parsing...........";
/// - Default construct an un-initialized test article.
FriendlyThermFileParser article;
/// - Create a dummy TiXmlDocument.
TiXmlDocument doc;
std::string noFile = "no_file.net";
std::string nonXmlFile = "main.cpp";
std::string illFormedXml = "ThermNodes_illformed.xml";
/// @test Exception thrown on attempt to build links before nodes.
CPPUNIT_ASSERT_THROW_MESSAGE("file doesn't exist", article.openFile(doc, noFile), TsParseException);
/// @test Exception thrown on article given a random file that has no thermal link info.
CPPUNIT_ASSERT_THROW_MESSAGE("non-XML file", article.openFile(doc, nonXmlFile), TsParseException);
/// @test Exception thrown on article with ill-formed XML
CPPUNIT_ASSERT_THROW_MESSAGE("ill-formed XML", article.openFile(doc, illFormedXml), TsParseException);
/// @test Exception thrown on article with invalid tags
article.mNodeFile = "ThermNodes_nolist.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("no <list>", article.readNodeFile(), TsParseException);
article.mNodeFile = "ThermLinksCond_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("no <node>", article.readNodeFile(), TsParseException);
/// @test Exception NOT thrown on article with empty <name> tag
article.mNodeFile = "ThermNodes_blankname.xml";
CPPUNIT_ASSERT_NO_THROW_MESSAGE("empty <name> tag", article.readNodeFile() );
/// @test Exception NOT thrown on article with no space node (just a warning).
article.mNodeFile = "ThermNodes_nospace.xml";
CPPUNIT_ASSERT_NO_THROW_MESSAGE("no space node", article.readNodeFile() );
/// @test Exception NOT thrown on article with non-numerical info where needed (just warning).
article.mNodeFile = "ThermNodes_nonnumeric.xml";
CPPUNIT_ASSERT_NO_THROW_MESSAGE("non-numerical info", article.readNodeFile() );
/// @test Capacitance link #0 had a string in the <capacitance> tag, so its
/// value should default to 0.0.
CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, article.vCapCapacitances.at(0), tTol);
/// - Successfully read node-file first before executing remaining tests.
article.mNodeFile = tNodeFile;
article.readNodeFile();
/// @test Exception thrown on article given the wrong file by accident.
article.mCondFile = "ThermLinksRad_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("cond-file with no links", article.readCondFile(), TsParseException);
article.mRadFile = "ThermLinksCond_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("rad-file with no links", article.readRadFile(), TsParseException);
article.mHtrFile = "ThermLinksPan_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("htr-file with no links", article.readHtrFile(), TsParseException);
article.mPanFile = "ThermLinksHtr_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("pan-file with no links", article.readPanFile(), TsParseException);
article.mEtcFile = "ThermLinksHtr_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("etc-file with no links", article.readEtcFile(), TsParseException);
/// @test Exception thrown on article initialized without config set in default data.
CPPUNIT_ASSERT_THROW_MESSAGE("initialize without config set", article.initialize(tNameError), TsParseException);
/// - Default construct an un-initialized test article.
FriendlyThermFileParser article1;
/// - Set NodeFile only.
article1.mNodeFile = tNodeFile;
/// @test Exception NOT thrown on article with all files null except for the NodeFile.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("all files null except nodes", article1.initialize(tNameError) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Node data from node-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testNode()
{
std::cout << "\n ThermFileParser 03: Testing node data read from config-file....";
/// @test Node data from the test case was built correctly.
CPPUNIT_ASSERT_EQUAL_MESSAGE("Node amount", tNumNodes, tArticle->numNodes);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Node name", tNodeName, tArticle->vNodeNames.at(tNode) );
/// @test Node map was constructed correctly.
CPPUNIT_ASSERT_EQUAL( 0, tArticle->getMapLocation(tHtrANode1) );
CPPUNIT_ASSERT_EQUAL( 6, tArticle->getMapLocation(tPanNode0) );
CPPUNIT_ASSERT_EQUAL(21, tArticle->getMapLocation(tSpaceNode) );
/// - Declare an invalid node string.
std::string fakeName = "FAKE_123";
/// @test An invalid node name should return NOT_FOUND.
CPPUNIT_ASSERT_EQUAL(ThermFileParser::NOT_FOUND, tArticle->getMapLocation(fakeName));
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Capacitance link data from node-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testCap()
{
std::cout << "\n ThermFileParser 04: Testing capacitance link, index " << tCap
<< " .........";
/// @test capacitance link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap amount", tNumLinksCap, tArticle->numLinksCap);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap name", tCapName, tArticle->vCapNames.at(tCap) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap Port", tCap, tArticle->vCapPorts.at(tCap));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Cap capacitance", tCapCapacitance, tArticle->vCapCapacitances.at(tCap), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Cap temperature", tCapTemperature, tArticle->vCapTemperatures.at(tCap), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap group id", tCapGroup, tArticle->vCapEditGroupIdentifiers.at(tCap) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Conduction link data from cond-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testCond()
{
std::cout << "\n ThermFileParser 05: Testing conduction link, index " << tCond
<< " ..........";
/// @test conduction link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Conduction amount", tNumLinksCond, tArticle->numLinksCond);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond given name", tCondName, tArticle->vCondNames.at(tCond) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Cond conductivity", tCondConductivity, tArticle->vCondConductivities.at(tCond), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond Port 0", tArticle->getMapLocation(tCondNode0), tArticle->vCondPorts0.at(tCond));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond Port 1", tArticle->getMapLocation(tCondNode1), tArticle->vCondPorts1.at(tCond));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond generic name", tCond2Name, tArticle->vCondNames.at(tCond2) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Radiation link data from rad-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testRad()
{
std::cout << "\n ThermFileParser 06: Testing radiation link, index " << tRad
<< " ...........";
/// @test radiation link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad amount", tNumLinksRad, tArticle->numLinksRad);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad name", tRadName, tArticle->vRadNames.at(tRad) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Rad coefficient", tRadCoefficient, tArticle->vRadCoefficients.at(tRad), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad port 0", tArticle->getMapLocation(tRadNode0), tArticle->vRadPorts0.at(tRad));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad port 1", tArticle->getMapLocation(tRadNode1), tArticle->vRadPorts1.at(tRad));
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Heater data from htr-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testHtr()
{
std::cout << "\n ThermFileParser 07: Testing heaters, index "
<< tHtrA << " and "<< tHtrB << " ............";
/// @test heater data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Htr amount", tNumLinksHtr, tArticle->numLinksHtr);
/// @test heater A name
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA name", tHtrAName, tArticle->vHtrNames.at(tHtrA) );
/// @test heater A tuning scalar
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("HtrA scalar", tHtrAScalar, tArticle->vHtrScalars[tHtrA], tTol);
/// @test heater A ports
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA ports", tHtrAPorts, static_cast<int>(tArticle->vHtrFracs.at(tHtrA).size()) );
/// @test heater A port numbers
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port0 node", tArticle->getMapLocation(tHtrANode0), tArticle->vHtrPorts.at(tHtrA).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port1 node", tArticle->getMapLocation(tHtrANode1), tArticle->vHtrPorts.at(tHtrA).at(1) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port2 node", tArticle->getMapLocation(tHtrANode2), tArticle->vHtrPorts.at(tHtrA).at(2) );
/// @test heater A power-draw fractions
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port0 frac", tHtrAFrac0, tArticle->vHtrFracs.at(tHtrA).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port1 frac", tHtrAFrac1, tArticle->vHtrFracs.at(tHtrA).at(1) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port2 frac", tHtrAFrac2, tArticle->vHtrFracs.at(tHtrA).at(2) );
CPPUNIT_ASSERT_THROW_MESSAGE("HtrA port3 frac", tArticle->vHtrFracs.at(tHtrA).at(3), std::out_of_range );
/// @test heater B name
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB name", tHtrBName, tArticle->vHtrNames.at(tHtrB) );
/// @test heater B tuning scalar
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("HtrB scalar", tHtrBScalar, tArticle->vHtrScalars[tHtrB], tTol);
/// @test heater B ports
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB ports", tHtrBPorts, static_cast<int>(tArticle->vHtrFracs.at(tHtrB).size()) );
/// @test heater B port numbers
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port0 node", tArticle->getMapLocation(tHtrBNode0), tArticle->vHtrPorts.at(tHtrB).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port1 node", tArticle->getMapLocation(tHtrBNode1), tArticle->vHtrPorts.at(tHtrB).at(1) );
/// @test heater B power-draw fractions
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port0 frac", tHtrBFrac0, tArticle->vHtrFracs.at(tHtrB).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port1 frac", tHtrBFrac1, tArticle->vHtrFracs.at(tHtrB).at(1) );
CPPUNIT_ASSERT_THROW_MESSAGE("HtrB port2 frac", tArticle->vHtrFracs.at(tHtrB).at(2), std::out_of_range );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of ThermalPanel data from pan-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testPan()
{
std::cout << "\n ThermFileParser 08: Testing thermal panel, index " << tPan
<< " ............";
/// @test heater data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan amount", tNumLinksPan, tArticle->numLinksPan);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan name", tNameError, tArticle->vPanNames.at(2) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan name", tPanName, tArticle->vPanNames.at(tPan) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Pan absorptivity", tPanAbsorptivity, tArticle->vPanAbsorptivities.at(tPan), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Pan area", tPanArea, tArticle->vPanAreas.at(tPan), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan ports", tPanPorts, static_cast<int>(tArticle->vPanFracs.at(tPan).size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan port0", tArticle->getMapLocation(tPanNode0), tArticle->vPanPorts.at(tPan).at(0));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan port1", tArticle->getMapLocation(tPanNode1), tArticle->vPanPorts.at(tPan).at(1));
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Potential link data from etc-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testPot()
{
std::cout << "\n ThermFileParser 10: Testing potential link, index " << tPot
<< " ...........";
/// @test Potential link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot amount", tNumLinksPot, tArticle->numLinksPot);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot name", tPotName, tArticle->vPotNames.at(tPot) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot node", tArticle->getMapLocation(tPotNode), tArticle->vPotPorts.at(tPot));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Pot temperature", tPotTemperature, tArticle->vPotTemperatures.at(tPot), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot conductivity", tPotConductivity, tArticle->vPotConductivities.at(tPot) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Source link data from etc-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testSrc()
{
std::cout << "\n ThermFileParser 11: Testing source link, index " << tSrc
<< " ..............";
/// @test Sources data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src amount", tNumLinksSrc, tArticle->numLinksSrc);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port0", tArticle->getMapLocation(tSrcNode0), tArticle->vSrcPorts.at(tSrc).at(0));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port1", tArticle->getMapLocation(tSrcNode1), tArticle->vSrcPorts.at(tSrc).at(1));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port2", tArticle->getMapLocation(tSrcNode2), tArticle->vSrcPorts.at(tSrc).at(2));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port3", tArticle->getMapLocation(tSrcNode3), tArticle->vSrcPorts.at(tSrc).at(3));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port0 frac", tSrcFrac0, tArticle->vSrcFracs.at(tSrc).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port1 frac", tSrcFrac1, tArticle->vSrcFracs.at(tSrc).at(1) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port2 frac", tSrcFrac2, tArticle->vSrcFracs.at(tSrc).at(2) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port3 frac", tSrcFrac3, tArticle->vSrcFracs.at(tSrc).at(3) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Src flux", tSrcFlux, tArticle->vSrcInits.at(tSrc), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src name", tSrcName, tArticle->vSrcNames.at(tSrc) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct edit of data by reading of ThermInput file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testThermInput()
{
std::cout << "\n ThermFileParser 12: Testing read of ThermInput file............";
/// @test Exception NOT thrown on article with null input file.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("null input file", tArticle->readThermInputFile() );
/// - Set input file to invalid path.
tArticle->mThermInputFile = "calabria.xml";
/// @test Read invalid input file.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("invalid input file", tArticle->readThermInputFile() );
/// - Set input file to valid path.
tArticle->mThermInputFile = tThermInputFile;
/// @test Read valid input file.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("read valid input file", tArticle->readThermInputFile() );
/// @test Temperature overwrites.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Temp override 0", 12.34, tArticle->vCapTemperatures.at(0), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Temp override 1", 56.78, tArticle->vCapTemperatures.at(1), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Temp override 2", 910.0, tArticle->vCapTemperatures.at(2), tTol);
/// @test Do nothing if no override provided.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Should maintain original temperature",
tCapTemperature, tArticle->vCapTemperatures.at(tCap), tTol);
std::cout << " Pass";
}
| [
"jason.l.harvey@nasa.gov"
] | jason.l.harvey@nasa.gov |
f3499e735b65ef62103804675740a1e10e4a1995 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Shapeshifter_Small_functions.cpp | 622a18ac32fa8eb5064273bee990bc3c764a5ffe | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | cpp | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Shapeshifter_Small_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function DinoCharacterStatusComponent_BP_Shapeshifter_Small.DinoCharacterStatusComponent_BP_Shapeshifter_Small_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UDinoCharacterStatusComponent_BP_Shapeshifter_Small_C::ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function DinoCharacterStatusComponent_BP_Shapeshifter_Small.DinoCharacterStatusComponent_BP_Shapeshifter_Small_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small");
UDinoCharacterStatusComponent_BP_Shapeshifter_Small_C_ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
275ebe4d2029b9075693c5dcdf75c7c949d309f5 | c5e1991cee008b77104916da81197ea07c3911d6 | /Problems/EEGSpatioTemporal/Data/DataForEEGSpatioTemporal.cpp | 3c7c7e4ec304fbe0c0f6914c2299195934fae953 | [] | no_license | torms3/hypernetwork | 1be59ae5d077094586a6389a73e85048bac37b29 | 0d30bbcb48373d219fc4a598a79abae2338b246c | refs/heads/master | 2020-08-07T06:36:20.224433 | 2015-03-13T02:40:42 | 2015-03-13T02:40:42 | 32,121,237 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp | //
// Copyright 2011 by
// kslee@bi.snu.ac.kr
// hmlee@bi.snu.ac.kr
//
#include "DataForEEGSpatioTemporal.h"
#include <algorithm>
namespace HN
{
//
// Implementation for Data class
//
EEGData::EEGData(int signal_size, int time_size)
{
m_signal_size = signal_size;
m_time_size = time_size;
}
EEGData::~EEGData()
{
}
} | [
"kisuklee@mit.edu"
] | kisuklee@mit.edu |
fbbfaad6e91852e5b5490df04523b0f1282547e2 | 754cc9e0424740907af49075f7c1eb6c7cbdcf91 | /common/Table/Table_NpcOptionalSkill.h | 6a6b6eabfb5d2ec449f1f20d32e4426fc5407b66 | [] | no_license | zhaojinwei0124/Project-RC_Server | 2d0906bed6406ef02e83cb9260746ccd23c0996e | b9ccb3e0476d7c562a4affb25d247e87c8aed1be | refs/heads/master | 2021-01-21T15:38:14.408311 | 2017-01-26T03:16:29 | 2017-01-26T03:16:29 | 81,521,050 | 0 | 2 | null | 2017-02-10T03:12:07 | 2017-02-10T03:12:07 | null | UTF-8 | C++ | false | false | 1,401 | h | //This code create by CodeEngine,don't modify
#ifndef _NpcOptionalSkillTABLE_H
#define _NpcOptionalSkillTABLE_H
#include "DBCTable.h"
class Table_NpcOptionalSkill:public DBC_Recorder_Loader<Table_NpcOptionalSkill,99999,500>
{
public:
enum _ID
{
INVLAID_INDEX=-1,
ID_SKILLID,
ID_SELETARGETLOGIC=2,
ID_ACTIVATELOGIC,
ID_ACTIVATEPARAM1,
ID_ACTIVATEPARAM2,
ID_TAB_CURCOL_COUNT,
MAX_ID=99999,
MAX_RECORD=500
};
public:
bool __Load(DBC_Loader &loader);
private:
tint32 m_ActivateLogic;
public:
tint32 GetActivateLogic() const { return m_ActivateLogic; }
public:
tint32 getActivateParamCount() const { return 2; }
private:
tint32 m_ActivateParam[2];
public:
tint32 GetActivateParambyIndex(tint32 idx) const
{
if(idx>=0 && idx<2) return m_ActivateParam[idx];
return -1;
}
private:
tint32 m_SeleTargetLogic;
public:
tint32 GetSeleTargetLogic() const { return m_SeleTargetLogic; }
private:
tint32 m_SkillId;
public:
tint32 GetSkillId() const { return m_SkillId; }
};
DECL_TABLE_FUNCTIONS(Table_NpcOptionalSkill);
//bool InitTable_NpcOptionalSkillTable( const tchar* szFileName );
//bool InitTable_NpcOptionalSkillTableFromMemory( const DBCFile& rDB );
//const Table_NpcOptionalSkill* GetTable_NpcOptionalSkillByID(tint32 id);
//const Table_NpcOptionalSkill* GetTable_NpcOptionalSkillByIndex(tint32 index);
//tint32 GetTable_NpcOptionalSkillCount(void);
#endif
| [
"bu213200@gmail.com"
] | bu213200@gmail.com |
5379fec7b306c6831cf2023d1ad04783bf42cadc | 44846a44741833c1887f73b0a0b809f8f327e3d6 | /Greg/MIDIUtils.h | 8762eae40e876a641e9969236f771eafd709224b | [] | no_license | bmelts/greg | 296084da2bedc19f3420a2eb70e3edb91af44756 | a946523f5f5140f8911e6cdc593c5266aef457d2 | refs/heads/master | 2020-05-17T08:02:34.242736 | 2012-05-02T08:48:25 | 2012-05-02T08:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | h | /*
* Greg/MIDIUtils.h
*
* Copyright (c) 2011-2012 Bill Meltsner
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the author 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.
*/
#ifndef Greg_MIDIUtils_h
#define Greg_MIDIUtils_h
#include <string>
struct Note {
uint8_t midiNote;
uint8_t velocity;
uint8_t channel;
double timestamp;
std::string pitch();
Note * copy();
};
double getNoteLength(std::string code);
#endif
| [
"bill@meltsner.com"
] | bill@meltsner.com |
fb5ac67e56adc3ef9d0c7122e919436c200c7ac9 | a14badc58bc6b5871cbd85e91cd8bf636824acec | /Binary Search/WoodCuttingMadeEasy.cpp | bd37fbb5fe60c54130ce295e0a2230af64635d9f | [] | no_license | prashant97sikarwar/Interview-Bit | 693b37c15e70de346c58debfd18e22541aaf7452 | 4b3bf032e30e16b8033e1a47c840fcaa434be429 | refs/heads/master | 2023-07-16T17:02:58.297411 | 2021-08-31T11:35:39 | 2021-08-31T11:35:39 | 353,809,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | //Problem Link:- https://www.interviewbit.com/problems/woodcutting-made-easy/
#include<bits/stdc++.h>
using namespace std;
bool helper(vector<int> &nums,int k,int h){
long long sm = 0;
for(int i=0;i<nums.size();i++){
if (nums[i] > h){
sm += nums[i]-h;
}
}
if (sm >= k){
return true;
}
return false;
}
int solve(vector<int> &nums, int k) {
int left = 0;
int right = *max_element(nums.begin(),nums.end());
int res = INT_MIN;
while (left <= right){
int mid = left + (right-left)/2;
if (helper(nums,k,mid)){
res = max(res,mid);
left = mid+1;
}
else{
right = mid-1;
}
}
return res;
}
| [
"prashant97sikarwar@gmail.com"
] | prashant97sikarwar@gmail.com |
49cc94b37ba61f252668bd58e8ab83adf3fac01c | 0c1da14e754ea8f2c558262e7ae920dca6c0dd9c | /matrix_object/main.cpp | 7399b9f8da150221ab42cf93562eac2f30aff50b | [] | no_license | risentveber/Old-code | 02d10bd3eb041f4ebc300b97732dfa78461e0d74 | 11fae95894891903bf261db7cdf7d8b8e7489880 | refs/heads/master | 2021-01-10T05:14:42.868148 | 2019-11-23T12:16:50 | 2019-11-23T12:16:50 | 45,670,454 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120 | cpp | #include "matrix.h"
int main(){
matrix one;
matrix two;
one.input();
two.input();
one = one*3;
one.output();
}
| [
"risentveber@gmail.com"
] | risentveber@gmail.com |
6b835908aa7e9b9632807ddaca04d4acc4f0b3e8 | 9d8bd24d59ad0fafc84748ca3d74153ee118b41f | /sandbox/planar-arma/include/planar-utils.h | b1049ce52b46a5cf745aafeba65b9398aac94b7e | [] | no_license | ColleyLi/bsp | 2e990254ede7144f88c976e2f69a43258d5a632f | d920b6e687e6167b574cc3716acfebe9b725b5cc | refs/heads/master | 2021-05-27T22:15:25.940929 | 2014-09-14T17:33:31 | 2014-09-14T17:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | h | #ifndef __PLANAR_UTILS_H__
#define __PLANAR_UTILS_H__
#include <Python.h>
#include <map>
#include <boost/python.hpp>
#include <boost/python/numeric.hpp>
#include <boost/python/tuple.hpp>
#include <boost/numpy.hpp>
#include <boost/filesystem.hpp>
namespace py = boost::python;
namespace np = boost::numpy;
#include <armadillo>
using namespace arma;
#include "../../util/Timer.h"
#include "../../util/logging.h"
/**
* Wrapper that tracks multiple timers
*/
class TimerCollection {
public:
void start(const std::string& timer_name);
void stop(const std::string& timer_name);
void print_elapsed(const std::string& timer_name);
void print_all_elapsed();
void clear_all();
private:
std::map<std::string,util::Timer> timer_dict;
std::map<std::string,double> timer_elapsed;
std::map<std::string,bool> timer_running;
};
namespace planar_utils {
inline double uniform(double low, double high) {
return (high - low)*(rand() / double(RAND_MAX)) + low;
}
np::ndarray arma_to_ndarray(mat& m);
}
#endif
| [
"gkahn13@gmail.com"
] | gkahn13@gmail.com |
974fe86b534d4567f685ad4c15dfaad7b9b047f5 | 3b70cb095b5bc18cdb35d1affa5f78235b164dac | /draw/debug/moc_wumian.cpp | 870b3efbd8bbfee840d494dd6c87346aab9b5429 | [] | no_license | GaoYifanGHB/qtP | 2e96ad690e2d1844622847aa705db4fc3880e739 | 60f71804e6899301309e9de5e169d90609cbe000 | refs/heads/master | 2021-04-26T01:31:51.137849 | 2017-11-02T08:53:33 | 2017-11-02T08:53:33 | 107,406,674 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,008 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'wumian.h'
**
** Created: Sun Aug 13 16:22:49 2017
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../model/wumian.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'wumian.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_wumian[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_wumian[] = {
"wumian\0"
};
const QMetaObject wumian::staticMetaObject = {
{ &QGLWidget::staticMetaObject, qt_meta_stringdata_wumian,
qt_meta_data_wumian, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &wumian::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *wumian::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *wumian::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_wumian))
return static_cast<void*>(const_cast< wumian*>(this));
return QGLWidget::qt_metacast(_clname);
}
int wumian::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGLWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"gao_yifan@163.com"
] | gao_yifan@163.com |
c95faa0483328b0d7e87ca8493590f4e994e7039 | c07c34c92e255583fb4d0e5318a47e04db66b0a2 | /sorting_algorithms/sorting_algorithms/Sort.hpp | fc10c36e1fcc984710e773c16ca9e82c19095d8d | [] | no_license | abyesses/calidad_software | 84e246e5ed6e86f2ebb77ebff41e69cd768f99d0 | 4ef352019bf61d2795a02ab8cd42557001a06db2 | refs/heads/master | 2021-01-11T23:02:07.554737 | 2017-02-10T16:04:40 | 2017-02-10T16:04:40 | 78,536,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | hpp | //
// Sort.hpp
// sorting_algorithms
//
// Created by Abraham Esses on 1/24/17.
// Copyright © 2017 Abraham Esses. All rights reserved.
//
#ifndef Sort_hpp
#define Sort_hpp
#define vect_tam 20
#include <stdio.h>
#include <vector>
#include <time.h>
using namespace std;
class Sort{
protected:
//vector<int> * unsorted = new vector<int>(vect_tam);
public:
virtual vector<int>* sort(vector<int>*,int)=0;
};
#endif /* Sort_hpp */
| [
"abraham@Abrahams-MacBook-Pro.local"
] | abraham@Abrahams-MacBook-Pro.local |
4f99c2ea1f2375f0d354ec7714cee924c54371b9 | e983a641073f855fc613e5dc799f83104bd11663 | /binarySortTree/二叉排序树.cpp | f0cbfae4b3beeccf26f16a4ef90e3c9c3749ff85 | [] | no_license | AlbertMP/BinarySortTree | 4c79cea89e8688f7c98f8d0f1ea42d1a5ff627bc | 319f171ef394355a3469c051f6b75301f565fd4d | refs/heads/master | 2020-05-26T12:57:56.107585 | 2019-05-23T14:10:50 | 2019-05-23T14:10:50 | 188,239,609 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,549 | cpp | //
// main.cpp
// binarySortTree
//
// Created by 苗芃 on 2019/3/23.
// Copyright © 2019 苗芃. All rights reserved.
//
//【选做内容】
// (1) 创建一棵二叉排序树;
// (2) 查找二叉排序树中一个指定结点;
// (3) 输出查找指定结点过程中所需比较的次数。
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define TRUE 1
#define OVERFLOW -2
#define FALSE 0
#define ERROR 0
#define MAXSIZE 100
typedef bool Status;
typedef int KeyType;
typedef struct{
KeyType key; // 用于存放编码
}ElemType;
typedef struct BiTNode{
ElemType data; // 结点的数据域
struct BiTNode *lchild, *rchild; // 左右孩子指针
}BiTNode, *BiTree;
int count=0;
BiTree SearchBST(BiTree T, KeyType key){
if ((!T)||(key==T->data.key)){
count++;
printf("查找成功!\n");
printf("查找次数:%d\n",count);
printf("要查找的节点及其后续子节点为:\n");
return T;
}
else if (key<T->data.key){
count++;
return SearchBST(T->lchild, key);
}
else{
count++;
return SearchBST(T->rchild, key);
}
}
Status RSearchBST(BiTree T, KeyType key, BiTree f, BiTree &p){
// 返回插入位置的二叉排序树查找算法
if (!T) {p = f; return FALSE;} // 查找不成功
else if (key == T->data.key){ p=T; return TRUE;} // 查找成功
else if (key < T->data.key) return RSearchBST(T->lchild, key, T, p); // 在左子树中继续查找
else return RSearchBST(T->rchild, key, T, p); // 在右子树中继续查找
}
Status InsertBST(BiTree &T, ElemType e){
// 在二叉排序树中插入关键字值为key, 记录为e的新结点
// 若成功,则返回TRUE;否则返回FAISE
BiTree p,s;
if (!RSearchBST(T, e.key, NULL, p)) {
s=(BiTree)malloc(sizeof(BiTNode));
s->data=e;
s->lchild=s->rchild=NULL;
if (!p) T=s;
else if (e.key<p->data.key) p->lchild=s;
else p->rchild=s;
return TRUE;
}
else
return FALSE;
}
Status CreateBST(BiTree &T, ElemType items[], int n){
for (int i=0; i<n; i++) {
InsertBST(T, items[i]); // 调用二叉排序树的插入算法
}
printf("创建完成!\n");
return OK;
}
void PreRootTraverse(BiTree T){
// 先序遍历
if (T!=NULL) {
printf("%d ",T->data.key);
PreRootTraverse(T->lchild);
PreRootTraverse(T->rchild);
}
}
void InRootTraverse(BiTree T){
// 中序遍历
if (T!=NULL) {
InRootTraverse(T->lchild);
printf("%d ", T->data.key);
InRootTraverse(T->rchild);
}
}
Status IsSame(ElemType array[], int count){
for (int i=0; i<count; i++) {
int temp = array[i].key;
for (int j=i+1; j<count; j++) {
if (temp==array[j].key) {
return TRUE;
}
}
}
return FALSE;
}
int levelOfNode(BiTree T, KeyType key){
int n = 1;
BiTree q;
q=T;
if (T==NULL)
return 0; // 空树
while (q) {
if (key==q->data.key) {
return n;
}else{
if (key<q->data.key)
q=q->lchild;
else
q=q->rchild;
n++;
}
}
return -1; // 不存在,未查询到
}
void Menu(){
printf("-----二叉排序树的操作-----\n");
printf("请选择要进行的操作:(1-5)\n");
printf("1. 生成二叉树\n");
printf("2. 中序遍历二叉树\n");
printf("3. 先序遍历二叉树\n");
printf("4. 查找节点\n");
printf("5. 退出进程\n");
printf("-----------------------\n");
}
int main() {
Menu();
int operation;
while (true) {
BiTree T;
printf("选择你的操作:");
scanf("%d",&operation);
switch (operation) {
case 1:
int count, n;
printf("-----------------------\n");
printf("创建开始,请输入元素个数:");
scanf("%d", &count);
printf("输入元素:\n");
ElemType items[count];
for (int i=0; i<count; i++) {
scanf("%d",&n);
items[i].key=n;
}
if (IsSame(items, count)) {
printf("输入的元素不允许重复!\n");
printf("-----------------------\n");
break;
}
// ElemType items[7]={2,4,1,3,6,7,5};
CreateBST(T, items, count);
printf("-----------------------\n");
break;
case 2:
// if (T==NULL) {
// printf("请先建立二叉排序树!\n");
// printf("-----------------------\n");
// break;
// }
printf("-----------------------\n");
printf("中序遍历:\n");
InRootTraverse(T);
printf("\n");
printf("-----------------------\n");
break;
case 3:
// if (T==NULL) {
// printf("请先建立二叉排序树!\n");
// printf("-----------------------\n");
// break;
// }
printf("-----------------------\n");
printf("先序遍历:\n");
PreRootTraverse(T);
printf("\n");
printf("-----------------------\n");
break;
case 4:
// if (T==NULL) {
// printf("请先建立二叉排序树!\n");
// printf("-----------------------\n");
// break;
// }
printf("-----------------------\n");
printf("请输入要查找的节点:");
int findnum;
scanf("%d",&findnum);
PreRootTraverse(SearchBST(T, findnum));
printf("\n");
printf("该节点位于第%d层。\n",levelOfNode(T, findnum));
printf("-----------------------\n");
break;
case 5:
printf("再会!\n");
return 0;
default:
printf("请输入正确的操作码!\n");
printf("-----------------------\n");
printf("选择你的操作:");
break;
}
}
}
| [
"2570869891@qq.com"
] | 2570869891@qq.com |
d121214d0f4181d2d594c81fa5a527e281adbaff | 6ec2b24683e532193107f1b68f8e648893174dbc | /eos/10/docker/oasis/contracts/Marketplace/Marketplace.cpp | c8c420098ea4f81306ee3adbbf59b9bb49c9417c | [
"Apache-2.0"
] | permissive | AaronZgl/blockchain | dde3f51d520d2b474d2e90f54cc3b90b572751b8 | 7c1b75a5870c13dfbaf11c943a02ff6074604796 | refs/heads/master | 2020-03-27T17:41:53.808466 | 2018-08-31T09:32:36 | 2018-08-31T09:32:36 | 146,867,528 | 0 | 0 | Apache-2.0 | 2018-08-31T08:58:19 | 2018-08-31T08:58:19 | null | UTF-8 | C++ | false | false | 3,796 | cpp | #include "Marketplace.hpp"
#include <eosiolib/asset.hpp>
namespace Oasis {
void Marketplace::buy(account_name buyer, uint64_t productId) {
productIndex products(_self, _self);
print("buy function,self is: ", name{ _self });
auto iterator = products.find(productId);
eosio_assert(iterator != products.end(), "The product not found");
auto product = products.get(productId);
eosio_assert(product.quantity > 0, "The product is out of stock");
print(" | Id: ", product.product_id);
print(" | Name: ", product.name.c_str());
print(" | Power: ", product.power);
print(" | Health: ", product.health);
print(" | Ability: ", product.ability.c_str());
print(" | Level up: ", product.level_up);
print(" | Quantity: ", product.quantity);
print(" | Price: ", product.price);
asset productPrice = asset(product.price, string_to_symbol(4, "OAS"));
action(
permission_level{ buyer, N(active) },
N(token), N(transfer),
std::make_tuple(buyer, _self, productPrice, string("buyTest"))
).send();
action(
permission_level{ buyer, N(active) },
N(player), N(additem),
std::make_tuple(buyer,
product.product_id,
product.name,
product.power,
product.health,
product.ability,
product.level_up
)).send();
update(buyer, product.product_id, -1);
}
void Marketplace::getbyid(uint64_t productId) {
productIndex products(_self, _self);
auto iterator = products.find(productId);
eosio_assert(iterator != products.end(), "Product not found");
auto product = products.get(productId);
print("Id: ", product.product_id);
print(" | Name: ", product.name.c_str());
print(" | Power: ", product.power);
print(" | Health: ", product.health);
print(" | Ability: ", product.ability.c_str());
print(" | Level up: ", product.level_up);
print(" | Quantity: ", product.quantity);
print(" | Price: ", product.price);
}
void Marketplace::add(account_name account, product newProduct) {
require_auth(account);
productIndex products(_self, _self);
auto iterator = products.find(newProduct.product_id);
eosio_assert(iterator == products.end(), "Product for this ID already exists");
products.emplace(account, [&](auto& product) {
product.product_id = newProduct.product_id;
product.name = newProduct.name;
product.power = newProduct.power;
product.health = newProduct.health;
product.ability = newProduct.ability;
product.level_up = newProduct.level_up;
product.quantity = newProduct.quantity;
product.price = newProduct.price;
});
}
void Marketplace::update(account_name account, uint64_t product_id, uint64_t quantity) {
require_auth(account);
productIndex products(_self, _self);
auto iterator = products.find(product_id);
eosio_assert(iterator != products.end(), "Product not found");
//TODO: check the 'product.quantity + quantity > 0'
products.modify(iterator, account, [&](auto& product) {
product.quantity += quantity;
});
}
void Marketplace::remove(account_name account, uint64_t productId) {
require_auth(account);
productIndex products(_self, _self);
auto iterator = products.find(productId);
eosio_assert(iterator != products.end(), "Product not found");
products.erase(iterator);
}
}
| [
"shanlusun@gmail.com"
] | shanlusun@gmail.com |
de82b35c95021f3a2978cd09ae9882f2bd507c0f | 0250600efb84f9f324602934c3fe42e62e67f8f6 | /topcoder/SRM_523/BricksN.cpp | 6fe792a2a7de8803ba1a95d5a41a8b5a378672ef | [] | no_license | bloops/solved | 987b43a4e8b9a2276bf81588a694ed77724fc633 | 2be75bb735b2edc13ba55826fbc9982e403ef8ce | refs/heads/master | 2021-01-01T18:02:40.019170 | 2012-01-19T16:18:38 | 2012-01-19T16:18:38 | 3,089,147 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,612 | cpp | #include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long int lli;
const lli MOD = 1000000007;
class BricksN {
public:
int partitions[55]; // partitions[i][k] = no of ways to make contiguous blocks of length i using 1..k
int count[55][55]; // count[w][h] = # of ways to structures on a base of length w
// with height atmost h (not including base w)
int countStructures(int w, int h, int k) {
partitions[0] = 1;
for (int i = 1; i <= w; i++){
for (int j = 1; j <= k; j++){
if(i-j >= 0){
partitions[i] += partitions[i-j];
partitions[i] %= MOD;
}
}
}
for (int hi = 0; hi <= h; hi++){
for (int wi = 0; wi <= w; wi++){
// find count[wi][hi]
count[wi][hi] = 1; // no blocks at all
for (int i = 1; i <= wi; i++){
for (int j = i; j <= wi; j++){
// put the last block [i..j]
int last = j-i+1;
int multterm = (partitions[last] * (lli)count[last][hi-1]) % MOD;
if( i >= 2 )
multterm = (multterm * (lli)count[i-2][hi]) % MOD;
count[wi][hi] += multterm;
count[wi][hi] %= MOD;
}
}
}
}
return count[w][h];
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, bool hasAnswer, int p3) {
cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2;
cout << "]" << endl;
BricksN *obj;
int answer;
obj = new BricksN();
clock_t startTime = clock();
answer = obj->countStructures(p0, p1, p2);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p3 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p3;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
int p0;
int p1;
int p2;
int p3;
{
// ----- test 0 -----
p0 = 3;
p1 = 1;
p2 = 3;
p3 = 13;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = 3;
p1 = 2;
p2 = 3;
p3 = 83;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = 1;
p1 = 5;
p2 = 1;
p3 = 6;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = 10;
p1 = 10;
p2 = 3;
p3 = 288535435;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| [
"bloopsie@gmail.com"
] | bloopsie@gmail.com |
cb7d2fab916674aca8dd89c4db34bfdbf9808538 | 714405f5edf52445771d680083c6d891b20f02b4 | /ClothApp/UserInteraction.cpp | 8958031318dd65c04c9973d25b81ecdbfcfc0a3e | [] | no_license | PeterZs/FastMassSpring-1 | 5fad64c8ad1d501705e1f69a9d08125a60fea8ab | 180015bdf09d1b70445b0835b4f9da0b485f33b5 | refs/heads/master | 2020-04-11T20:42:09.041378 | 2018-12-16T16:31:58 | 2018-12-16T16:31:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include "UserInteraction.h"
#include <GL/glew.h>
#include <iostream>
#include <cmath>
UserInteraction::UserInteraction(float* vbuff, int n)
: vbuff(vbuff), fixer(vbuff, 3 * n * n), n(n), i(-1) {}
int UserInteraction::colorToIndex(color c) {
if (c[2] != 51) return -1;
int vx = std::round((n - 1) * c[0] / 255.0);
int vy = std::round((n - 1) * c[1] / 255.0);
return 3 * n * vy + 3 * vx;
}
void UserInteraction::grabPoint(int mouse_x, int mouse_y){
// read color
color c(3);
glReadPixels(mouse_x, mouse_y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &c[0]);
i = colorToIndex(c);
fixer.addPoint(i);
}
void UserInteraction::releasePoint() { fixer.removePoint(i); i = -1; }
void UserInteraction::movePoint(vec3 v) {
fixer.removePoint(i);
for(int j = 0; j < 3; j++)
vbuff[i + j] += v[j];
fixer.addPoint(i);
}
void UserInteraction::fixPoints() { fixer.fixPoints(); } | [
"24758349+sam007961@users.noreply.github.com"
] | 24758349+sam007961@users.noreply.github.com |
7221349c9d3ad45499f97bfe605a3557673ab89c | 6956e203caf857ca4e1a64ff4248a5824951a314 | /common_src/Unirse.cpp | c84e1eb1c1418e1763a35847c45f42ecc5a484a9 | [] | no_license | psdimartino/TallerDeProgramacion_TP3 | 431f1bc48bd9ce26aaf8897938edff330125933f | 5ac9f7f1c031fbd74189a337a4396e43238b255e | refs/heads/main | 2023-05-29T01:07:56.307625 | 2021-06-15T20:21:16 | 2021-06-15T20:21:16 | 374,215,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include "../common_src/Unirse.h"
Unirse::Unirse(std::string const nombre) : nombre(nombre) {}
std::string const& Unirse::getNombre() const {
return nombre;
}
void Unirse::ejecutar(MapaDePartidas &partidas,
std::string &nombrePartida, char &jugador) {
if (!partidas.unirse(nombre)) {
result << "La partida no existe o esta llena" << std::endl;
return;
}
jugador = CRUZ;
nombrePartida = std::move(nombre);
partidas[nombrePartida].esperarElTurnoDe(jugador);
result << partidas[nombrePartida];
}
| [
"pdimartino@fi.uba.ar"
] | pdimartino@fi.uba.ar |
b5203eaf4da139e149a5a63d2aef8ed929676ec4 | 31589435071cbff4c5e95b357d8f3fa258f43269 | /PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/natcheck/base/AppBuffer.h | bac1bf86523aaa1dd272e51f86b151073c928397 | [] | no_license | huangyt/MyProjects | 8d94656f41f6fac9ae30f089230f7c4bfb5448ac | cd17f4b0092d19bc752d949737c6ed3a3ef00a86 | refs/heads/master | 2021-01-17T20:19:35.691882 | 2013-05-03T07:19:31 | 2013-05-03T07:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,273 | h | #ifndef _BUFFER_H_
#define _BUFFER_H_
#include "Common.h"
typedef boost::uint8_t byte;
namespace base
{
struct AppBuffer
{
public:
enum { BUF_NORMAL, BUF_SUBPIECE };
private:
boost::shared_array<byte> data_;
protocol::SubPieceContent::pointer subpiece_;
size_t length_;
size_t offset_;
size_t type_;
public:
AppBuffer() :
length_(0), offset_(0), type_(BUF_NORMAL)
{
}
AppBuffer(const AppBuffer& buffer)
{
if (this != &buffer)
{
data_ = buffer.data_;
subpiece_ = buffer.subpiece_;
length_ = buffer.length_;
offset_ = buffer.offset_;
type_ = buffer.type_;
}
}
AppBuffer& operator =(const AppBuffer& buffer)
{
if (this != &buffer)
{
data_ = buffer.data_;
subpiece_ = buffer.subpiece_;
length_ = buffer.length_;
offset_ = buffer.offset_;
type_ = buffer.type_;
}
return *this;
}
explicit AppBuffer(const protocol::SubPieceBuffer& buffer)
{
length_ = buffer.Length();
offset_ = buffer.Offset();
subpiece_ = buffer.GetSubPieceBuffer();
type_ = BUF_SUBPIECE;
}
explicit AppBuffer(size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
}
explicit AppBuffer(size_t length, int val) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memset((void*)data_.get(), val, length);
}
explicit AppBuffer(const string& str)
: data_(new byte[str.length()]), length_(str.length()), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), str.c_str(), length_);
}
AppBuffer(const char* data, size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), data, length);
}
AppBuffer(const byte* data, size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), data, length);
}
AppBuffer(boost::shared_array<byte> data, size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), data.get(), length);
}
bool Add(const byte* data, size_t length)
{
if (offset_ + length >= length_)
{
return false;
}
memcpy(data_.get()+offset_, data, length);
}
inline byte* Data() const
{
if (BUF_NORMAL == type_) {
return &data_[offset_];
}
else if (BUF_SUBPIECE == type_) {
return *subpiece_;
}
return NULL;
}
inline byte* Data(size_t offset) const
{
byte* base_ptr = Data();
if (base_ptr != NULL) {
return base_ptr + offset;
}
return NULL;
}
inline size_t Length() const
{
return length_;
}
size_t Type() const
{
return type_;
}
size_t Offset() const
{
return offset_;
}
void Data(boost::shared_array<byte> data)
{
data_ = data;
type_ = BUF_NORMAL;
}
void Length(size_t length)
{
length_ = length;
}
void Offset(size_t offset)
{
offset_ = offset;
}
AppBuffer SubBuffer(size_t offset) const
{
AppBuffer buffer;
if (offset < length_)
{
buffer.offset_ = offset_ + offset;
buffer.length_ = length_ - offset;
buffer.data_ = data_;
buffer.subpiece_ = subpiece_;
buffer.type_ = type_;
}
return buffer;
}
AppBuffer SubBuffer(size_t offset, size_t length) const
{
AppBuffer buffer;
if (offset + length <= length_)
{
buffer.offset_ = offset_ + offset;
buffer.length_ = length;
buffer.data_ = data_;
buffer.subpiece_ = subpiece_;
buffer.type_ = type_;
}
return buffer;
}
void Malloc(size_t length)
{
length_ = length;
data_ = boost::shared_array<byte>(new byte[length_]);
offset_ = 0;
type_ = BUF_NORMAL;
}
AppBuffer Clone() const
{
return AppBuffer(Data(), length_);
}
void Clear(byte padding = 0)
{
if (length_ > 0)
{
memset(Data(), padding, length_);
}
}
bool operator !() const
{
return length_ == 0;
}
operator bool() const
{
return length_ != 0;
}
bool operator ==(const AppBuffer& buffer) const
{
return data_.get() == buffer.data_.get() && length_ == buffer.length_
&& offset_ == buffer.offset_ && type_ == buffer.type_;
}
bool operator <(const AppBuffer& b2) const
{
if (type_ != b2.type_)
{
return type_ < b2.type_;
}
else if (data_.get() != b2.data_.get())
{
return data_.get() < b2.data_.get();
}
else if (offset_ != b2.offset_)
{
return offset_ < b2.offset_;
}
else
{
return length_ < b2.length_;
}
}
};
struct TempBuffer
{
AppBuffer buffer_;
byte* data_;
size_t length_;
TempBuffer(const AppBuffer& buffer, byte* data, size_t length) :
buffer_(buffer), data_(data), length_(length)
{
assert(buffer);
assert(data >= buffer.Data());
assert(data < buffer.Data() + buffer.Length());
}
TempBuffer(const AppBuffer& buffer, size_t offset, size_t length) :
buffer_(buffer), data_(buffer_.Data() + offset), length_(length)
{
assert(buffer);
assert(offset >= 0);
assert(offset < buffer_.Length());
}
TempBuffer(const AppBuffer& buffer, byte* data) :
buffer_(buffer), data_(data)
{
assert(buffer);
assert(data >= buffer.Data());
assert(data < buffer.Data() + buffer.Length());
length_ = buffer.Length() - (data - buffer.Data());
}
TempBuffer(const AppBuffer& buffer, size_t offset) :
buffer_(buffer), data_(buffer_.Data() + offset), length_(buffer_.Length() - offset)
{
assert(buffer);
assert(offset >= 0);
assert(offset < buffer_.Length());
}
inline byte* Get() const
{
return data_;
}
inline size_t GetLength() const
{
return length_;
}
inline bool operator ==(const TempBuffer& buffer)
{
return buffer_ == buffer.buffer_ && Get() == buffer.Get() && GetLength() == buffer.GetLength();
}
inline AppBuffer ToBuffer()
{
return AppBuffer(Get(), GetLength());
}
};
inline bool operator <(const TempBuffer& b1, const TempBuffer& b2)
{
if (b1.buffer_ == b2.buffer_)
{
if (b1.Get() != b2.Get())
return b1.Get() < b2.Get();
else
return b1.GetLength() < b2.GetLength();
}
else
{
return b1.buffer_ < b2.buffer_;
}
}
}
#endif // _BUFFER_H_
| [
"penneryu@outlook.com"
] | penneryu@outlook.com |
234bea3778dfc2444e01cc32cc0f7c7bb32a1940 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/inetsrv/iis/iisrearc/iisplus/ulatq/wprecycler.cxx | d9486d58044eb0775d21bf592f24263fdd77245e | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,609 | cxx | /*++
Copyright (c) 1998 Microsoft Corporation
Module Name :
wprecycler.cxx
Abstract:
Implementation of WP_RECYCLER. Object handles worker process recycling
- Memory based recycling
- Schedule based recycling
- Elapsed Time based recycling
- Processed Request Count based recycling
Dependencies:
g_pwpContext is used by WP_RECYCLER to be able to send messages
Author:
Jaroslav Dunajsky (JaroslaD) 07-Dec-2000
Environment:
Win32 - User Mode
Project:
W3DT.DLL
--*/
#include "precomp.hxx"
#include "wprecycler.hxx"
#define ONE_DAY_IN_MILLISECONDS (1000 * 60 * 60 * 24)
//
// Static variables
//
CRITICAL_SECTION WP_RECYCLER::sm_CritSec;
//
// Static variables for Memory based recycling
//
HANDLE WP_RECYCLER::sm_hTimerForMemoryBased = NULL;
BOOL WP_RECYCLER::sm_fIsStartedMemoryBased = FALSE;
SIZE_T WP_RECYCLER::sm_MaxValueForMemoryBased = 0;
HANDLE WP_RECYCLER::sm_hCurrentProcess = NULL;
//
// Static variables for Time based recycling
//
HANDLE WP_RECYCLER::sm_hTimerForTimeBased = NULL;
BOOL WP_RECYCLER::sm_fIsStartedTimeBased = FALSE;
//
// Static variables for Schedule based recycling
//
HANDLE WP_RECYCLER::sm_hTimerQueueForScheduleBased = NULL;
BOOL WP_RECYCLER::sm_fIsStartedScheduleBased = FALSE;
//
// Static variables for Request based recycling
//
BOOL WP_RECYCLER::sm_fIsStartedRequestBased = FALSE;
DWORD WP_RECYCLER::sm_dwMaxValueForRequestBased = 0;
LONG WP_RECYCLER::sm_RecyclingMsgSent = 0;
BOOL WP_RECYCLER::sm_fCritSecInit = FALSE;
//
// Static methods for Schedule based recycling
//
//static
HRESULT
WP_RECYCLER::StartScheduleBased(
IN const WCHAR * pwszScheduleTimes
)
/*++
Routine Description:
Start schedule based recycling
Arguments:
pwszScheduleTimes - MULTISZ array of time information
<time>\0<time>\0\0
time is of military format hh:mm
(hh>=0 && hh<=23)
(mm>=0 && hh<=59)
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
BOOL fRet = FALSE;
const WCHAR * pwszCurrentChar = pwszScheduleTimes;
HANDLE hTimer;
WORD wHours = 0;
WORD wMinutes = 0;
WORD wDigitCount = 0;
SYSTEMTIME SystemTime;
FILETIME FileTime;
FILETIME CurrentFileTime;
ULARGE_INTEGER largeintCurrentTime;
ULARGE_INTEGER largeintTime;
DWORD dwDueTime = 0;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartScheduleBased()\n"));
}
DBG_ASSERT( pwszScheduleTimes != NULL );
//
// If scheduler based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedScheduleBased )
{
WP_RECYCLER::TerminateScheduleBased();
}
WP_RECYCLER::sm_hTimerQueueForScheduleBased = CreateTimerQueue();
if ( WP_RECYCLER::sm_hTimerQueueForScheduleBased == NULL )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto Failed;
}
//
// Gets current time
//
GetLocalTime( &SystemTime );
SystemTimeToFileTime( &SystemTime,
&CurrentFileTime );
memcpy( &largeintCurrentTime,
&CurrentFileTime,
sizeof( ULARGE_INTEGER ) );
//
// empty string in MULTISZ indicates the end of MULTISZ
//
while ( *pwszCurrentChar != '\0' )
{
//
// Skip white spaces
//
while ( iswspace( (wint_t) *pwszCurrentChar ) )
{
pwszCurrentChar++;
}
//
// Start of the time info
// Expect military format hh:mm
//
//
// Process hours (up to 2 digits is valid)
//
wHours = 0;
wDigitCount = 0;
while ( iswdigit( *pwszCurrentChar ) )
{
wDigitCount++;
wHours = 10 * wHours + (*pwszCurrentChar - '0');
pwszCurrentChar++;
}
if ( wDigitCount > 2 ||
( wHours > 23 ) )
{
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
//
// Hours - minutes separator
// Be liberal - any character that is not a digit or '\0' is OK
//
if ( *pwszCurrentChar == '\0' )
{
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
pwszCurrentChar++;
//
// Process minutes (must be exactly 2 digits)
//
wMinutes = 0;
wDigitCount = 0;
while ( iswdigit( (wint_t) *pwszCurrentChar ) )
{
wDigitCount++;
wMinutes = 10 * wMinutes + (*pwszCurrentChar - '0');
pwszCurrentChar++;
}
if ( ( wDigitCount != 2 ) ||
( wMinutes > 59 ) )
{
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
//
// Skip white spaces
//
while ( iswspace( (wint_t)*pwszCurrentChar ) )
{
pwszCurrentChar++;
}
//
// Check for terminating zero
//
if ( *pwszCurrentChar != '\0' )
{
//
// Extra characters in the time string
//
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
pwszCurrentChar++;
//
// Convert Hours and Minutes info
//
SystemTime.wHour = wHours;
SystemTime.wMinute = wMinutes;
SystemTime.wSecond = 0;
SystemTime.wMilliseconds = 0;
SystemTimeToFileTime( &SystemTime,
&FileTime );
memcpy( &largeintTime,
&FileTime,
sizeof(ULARGE_INTEGER) );
//
// Issue 12/21/2000 jaroslad:
// This method of setting absolute time with CreateTimerQueueTimer
// is bad since instead of setting absolute time the relative time is
// calculated and used for timer.
// This approach fails badly if someone changes machine
// time. Other Api that enables setting abolute time must be used for proper
// implementation
//
// Get Due Time in milliseconds
//
dwDueTime = static_cast<DWORD>(
( largeintTime.QuadPart - largeintCurrentTime.QuadPart )/ 10000);
if ( largeintTime.QuadPart < largeintCurrentTime.QuadPart)
{
dwDueTime = ONE_DAY_IN_MILLISECONDS - static_cast<DWORD>(
( largeintCurrentTime.QuadPart - largeintTime.QuadPart )/ 10000);
}
else
{
dwDueTime = static_cast<DWORD>(
( largeintTime.QuadPart - largeintCurrentTime.QuadPart )/ 10000);
}
if ( dwDueTime == 0 )
{
//
// this event is to be scheduled for the next day
// one day has 1000 * 60 * 60 * 24 of (100-nanosecond intervals)
//
dwDueTime += ONE_DAY_IN_MILLISECONDS;
}
//
// Schedule event for specified time, repeating once a day
//
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"Schedule recycling for %d:%d (in %d milliseconds)\n",
(int) wHours,
(int) wMinutes,
dwDueTime));
}
fRet = CreateTimerQueueTimer(
&hTimer,
WP_RECYCLER::sm_hTimerQueueForScheduleBased,
WP_RECYCLER::TimerCallbackForScheduleBased,
NULL,
dwDueTime,
// repeat daily (interval in milliseconds)
ONE_DAY_IN_MILLISECONDS,
WT_EXECUTELONGFUNCTION );
if ( !fRet )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto Failed;
}
//
// hTimer will not be stored
// sm_hTimerQueueForScheduleBased is going to be used for cleanup
// DeleteTimerQueueEx() should be able to correctly delete all timers
// in the queue
//
}
WP_RECYCLER::sm_fIsStartedScheduleBased = TRUE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return S_OK;
Failed:
WP_RECYCLER::TerminateScheduleBased();
DBG_ASSERT( FAILED( hr ) );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartScheduleBased() failed with error hr=0x%x\n",
hr ));
}
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateScheduleBased(
VOID
)
/*++
Routine Description:
Stops schedule based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
VOID
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
if( WP_RECYCLER::sm_hTimerQueueForScheduleBased != NULL )
{
if ( !DeleteTimerQueueEx(
WP_RECYCLER::sm_hTimerQueueForScheduleBased,
INVALID_HANDLE_VALUE /* wait for callbacks to complete */
) )
{
DBGPRINTF(( DBG_CONTEXT,
"failed to call DeleteTimerQueueEx(): hr=0x%x\n",
HRESULT_FROM_WIN32(GetLastError()) ));
}
WP_RECYCLER::sm_hTimerQueueForScheduleBased = NULL;
}
WP_RECYCLER::sm_fIsStartedScheduleBased = FALSE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
//static
VOID
WINAPI
WP_RECYCLER::TimerCallbackForScheduleBased(
PVOID pParam,
BOOLEAN TimerOrWaitFired
)
/*++
Routine Description:
Timer callback for Schedule based recycling
It is passed to CreateTimerQueueTimer()
Routine will inform WAS that process is ready to be recycled
because scheduled time has been reached
Arguments:
see the description of WAITORTIMERCALLBACK type in MSDN
Return Value:
none
--*/
{
DBG_ASSERT( WP_RECYCLER::sm_fIsStartedScheduleBased );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::TimerCallbackForScheduleBased()"
" - tell WAS to recycle\n" ));
}
//
// Indicate to WAS that we are ready for recycling
//
WP_RECYCLER::SendRecyclingMsg( IPM_WP_RESTART_SCHEDULED_TIME_REACHED );
}
//
// Static methods for Memory based recycling
//
//static
HRESULT
WP_RECYCLER::StartMemoryBased(
IN DWORD dwMaxVirtualMemoryUsageInKB
)
/*++
Routine Description:
Start virtual memory usage based recycling.
Arguments:
dwMaxVirtualMemoryUsageInKB - If usage of virtual memory reaches this value
worker process is ready for recycling
Note:
VM usage will be checked periodically. See the value of internal constant
CHECK_MEMORY_TIME_PERIOD
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
BOOL fRet = FALSE;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartMemoryBased(%d kB)\n",
dwMaxVirtualMemoryUsageInKB ));
}
//
// If time based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedMemoryBased == TRUE )
{
WP_RECYCLER::TerminateMemoryBased();
}
if ( dwMaxVirtualMemoryUsageInKB == 0 )
{
//
// 0 means not to run memory recycling
//
hr = S_OK;
goto succeeded;
}
fRet = CreateTimerQueueTimer( &WP_RECYCLER::sm_hTimerForMemoryBased,
NULL,
WP_RECYCLER::TimerCallbackForMemoryBased,
NULL,
CHECK_MEMORY_TIME_PERIOD,
CHECK_MEMORY_TIME_PERIOD,
WT_EXECUTELONGFUNCTION );
if ( !fRet )
{
WP_RECYCLER::sm_hTimerForMemoryBased = NULL;
hr = HRESULT_FROM_WIN32( GetLastError() );
goto failed;
}
//
// Get current process handle
// It will be used for NtQueryInformationProcess()
// in the timer callback
// there is no error to check for and handle doesn't need to be closed
// on cleanup
//
sm_hCurrentProcess = GetCurrentProcess();
sm_MaxValueForMemoryBased = 1024 * dwMaxVirtualMemoryUsageInKB;
WP_RECYCLER::sm_fIsStartedMemoryBased = TRUE;
succeeded:
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return S_OK;
failed:
DBG_ASSERT( FAILED( hr ) );
WP_RECYCLER::TerminateMemoryBased();
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartMemoryBased() failed with error hr=0x%x\n",
hr ));
}
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateMemoryBased(
VOID
)
/*++
Routine Description:
Stops virtual memory usage based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
VOID
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
if ( WP_RECYCLER::sm_hTimerForMemoryBased != NULL )
{
if ( !DeleteTimerQueueTimer(
NULL,
WP_RECYCLER::sm_hTimerForMemoryBased,
INVALID_HANDLE_VALUE /* wait for callbacks to complete */
) )
{
DBGPRINTF(( DBG_CONTEXT,
"failed to call DeleteTimerQueueTimer(): hr=0x%x\n",
HRESULT_FROM_WIN32(GetLastError()) ));
}
WP_RECYCLER::sm_hTimerForMemoryBased = NULL;
}
WP_RECYCLER::sm_fIsStartedMemoryBased = FALSE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
//static
VOID
WINAPI
WP_RECYCLER::TimerCallbackForMemoryBased(
PVOID pParam,
BOOLEAN TimerOrWaitFired
)
/*++
Routine Description:
Timer callback for Elapsed time based recycling
This Callback is passed to CreateTimerQueueTimer()
Virtual memory usage will be checked and if limit has been reached
then routine will inform WAS that process is ready to be recycled
Arguments:
see description of WAITORTIMERCALLBACK type in MSDN
Return Value:
none
--*/
{
NTSTATUS Status = 0;
VM_COUNTERS VmCounters;
DBG_ASSERT( WP_RECYCLER::sm_fIsStartedMemoryBased );
Status = NtQueryInformationProcess( sm_hCurrentProcess,
ProcessVmCounters,
&VmCounters,
sizeof(VM_COUNTERS),
NULL );
if ( ! NT_SUCCESS ( Status ) )
{
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"NtQueryInformationProcess failed with Status: %d\n",
Status ));
}
return;
}
if ( VmCounters.VirtualSize >= sm_MaxValueForMemoryBased )
{
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::TimerCallbackForMemoryBased()"
" - current VM:%ld kB, configured max VM:%ld kB"
" - tell WAS to recycle\n",
VmCounters.VirtualSize/1024 ,
sm_MaxValueForMemoryBased/1024 ));
}
//
// we reached Virtual Memory Usage limit
//
WP_RECYCLER::SendRecyclingMsg( IPM_WP_RESTART_MEMORY_LIMIT_REACHED );
}
}
//
// Static methods for Time based recycling
//
//static
HRESULT
WP_RECYCLER::StartTimeBased(
IN DWORD dwPeriodicRestartTimeInMinutes
)
/*++
Routine Description:
Start elapsed time based recycling
Arguments:
dwPeriodicRestartTimeInMinutes - how often to restart (in minutes)
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
BOOL fRet = FALSE;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartTimeBased(%d min)\n" ,
dwPeriodicRestartTimeInMinutes ));
}
//
// If time based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedTimeBased == TRUE )
{
WP_RECYCLER::TerminateTimeBased();
}
if ( dwPeriodicRestartTimeInMinutes == 0 )
{
//
// 0 means not to run time based recycling
//
hr = S_OK;
goto succeeded;
}
fRet = CreateTimerQueueTimer( &WP_RECYCLER::sm_hTimerForTimeBased,
NULL,
WP_RECYCLER::TimerCallbackForTimeBased,
NULL,
dwPeriodicRestartTimeInMinutes * 60000,
// convert to msec
dwPeriodicRestartTimeInMinutes * 60000,
// convert to msec
WT_EXECUTELONGFUNCTION );
if ( !fRet )
{
WP_RECYCLER::sm_hTimerForTimeBased = NULL;
hr = HRESULT_FROM_WIN32( GetLastError() );
goto failed;
}
WP_RECYCLER::sm_fIsStartedTimeBased = TRUE;
succeeded:
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return S_OK;
failed:
DBG_ASSERT( FAILED( hr ) );
WP_RECYCLER::TerminateTimeBased();
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartTimeBased() failed with error hr=0x%x\n",
hr));
}
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateTimeBased(
VOID
)
/*++
Routine Description:
Stops elapsed time based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
if ( WP_RECYCLER::sm_hTimerForTimeBased != NULL )
{
if ( !DeleteTimerQueueTimer(
NULL,
WP_RECYCLER::sm_hTimerForTimeBased,
INVALID_HANDLE_VALUE /* wait for callbacks to complete */
) )
{
DBGPRINTF(( DBG_CONTEXT,
"failed to call DeleteTimerQueueTimer(): hr=0x%x\n",
HRESULT_FROM_WIN32(GetLastError()) ));
}
WP_RECYCLER::sm_hTimerForTimeBased = NULL;
}
WP_RECYCLER::sm_fIsStartedTimeBased = FALSE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
//static
VOID
WINAPI
WP_RECYCLER::TimerCallbackForTimeBased(
PVOID pParam,
BOOLEAN TimerOrWaitFired
)
/*++
Routine Description:
Timer callback for Elapsed time based recycling
This Callback is passed to CreateTimerQueueTimer()
Routine will inform WAS that process is ready to be recycled
because required elapsed time has been reached
Arguments:
see description of WAITORTIMERCALLBACK type in MSDN
Return Value:
none
--*/
{
DBG_ASSERT( WP_RECYCLER::sm_fIsStartedTimeBased );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::TimerCallbackForTimeBased"
" - tell WAS to recycle\n" ));
}
WP_RECYCLER::SendRecyclingMsg( IPM_WP_RESTART_ELAPSED_TIME_REACHED );
}
//
// Static methods for Request based recycling
//
//static
HRESULT
WP_RECYCLER::StartRequestBased(
IN DWORD dwRequests
)
/*++
Routine Description:
Start request based recycling.
Arguments:
dwRequests - If number of requests processed by worker process reaches this value
recycling will be required
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartRequestBased(%d kB)\n" ,
dwRequests ));
}
//
// If time based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedRequestBased == TRUE )
{
WP_RECYCLER::TerminateRequestBased();
}
if ( dwRequests == 0 )
{
//
// 0 means not to run request based recycling
//
hr = S_OK;
goto succeeded;
}
InterlockedExchange(
reinterpret_cast<LONG *>(&sm_dwMaxValueForRequestBased),
dwRequests );
InterlockedExchange(
reinterpret_cast<LONG *>(&WP_RECYCLER::sm_fIsStartedTimeBased),
TRUE );
hr = S_OK;
succeeded:
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateRequestBased(
VOID
)
/*++
Routine Description:
Stops request based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
HRESULT
--*/
{
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
//
// InterlockedExchange is used because Request Based recycling callback
// IsRequestCountLimitReached() is called for each request
// and we don't synchronize it with &WP_RECYCLER::sm_CritSec
//
InterlockedExchange(
reinterpret_cast<LONG *>(&WP_RECYCLER::sm_fIsStartedTimeBased),
FALSE );
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
c48126c2316e1ea6740a8e324283cbc4bbf6918f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_3730_squid-3.5.27.cpp | 1027a95beb16649c8344a86d0b8ecf909e7ffc17 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | cpp | HttpHdrRangeSpec *
HttpHdrRangeSpec::Create(const char *field, int flen)
{
HttpHdrRangeSpec spec;
if (!spec.parseInit(field, flen))
return NULL;
return new HttpHdrRangeSpec(spec);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
7161a782338bbd493a0f853fe7ad69bf828fd956 | 9cb1727433c8da111f08ba139402761ad4169e57 | /SFML Wave function collapse/main.cpp | 028a71a5d8a6469719f435179877c766b4a4e539 | [] | no_license | Diemoonn/SFML-Wave-function-collapse-ESTM- | 661eab7795b85712fc505a25648e6e17404e93d0 | 8c3e2a01e75b2547990ec923236239356947dbd1 | refs/heads/master | 2023-07-14T15:55:06.749909 | 2021-08-10T08:52:11 | 2021-08-10T08:52:11 | 391,181,353 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 10,873 | cpp | #include <SFML/Graphics.hpp>
#include <vector>
#include <algorithm>
using namespace sf;
using namespace std;
struct Tile
{
string name;
Color color;
vector<string> compatible;
float probability;
};
class Cell
{
public:
vector<Tile> domain;
Tile tile;
Cell() {}
Cell(Vector2f position, vector<Tile> tiles)
{
cell.setPosition(position);
cell.setSize(Vector2f(16, 16));
cell.setFillColor(color);
for (unsigned int i = 0; i < tiles.size(); i++) // заполняем домен возможными вариантами тайлов
{
domain.push_back(tiles[i]);
entropia++;
}
decided = false;
}
void decideRandom()
{
int randIndex, randKoef;
float result;
do {
randIndex = rand() % domain.size() + 0;
randKoef = rand() % 10 + 1;
result = randKoef * domain[randIndex].probability;
} while (result < 1);
tile = domain[randIndex];
color = tile.color;
cell.setFillColor(color);
decided = true;
}
void setTile(Tile newTile)
{
tile = newTile;
color = tile.color;
cell.setFillColor(color);
}
bool isDecided() const
{
return decided;
}
int getEntropia() const
{
return entropia;
}
vector<string> getCompatible() const
{
return tile.compatible;
}
void drawCell(RenderWindow &window) const
{
window.draw(cell);
}
private:
RectangleShape cell;
int entropia = 0;
bool decided;
Color color = Color::Green;
};
void initCells(vector<Cell> &map, vector<Tile> tiles)
{
// заполняет карту клетками в суперпозиции
for (int y = 0; y < 256; y += 16)
{
for (int x = 0; x < 256; x += 16)
{
Cell newCell(Vector2f(x, y), tiles);
map.push_back(newCell);
}
}
}
void setNewState(vector<Cell> &map, int index)
{
// выбирает новое состояние для клетки
map[index].decideRandom();
}
/*
void initTiles(int tilesetWidth, int tilesetHeight)
{
// читает данные их config-file и на их основе создаёт тайлы
Texture tileset;
tileset.loadFromFile("resourses/tiles textures/tileset.png");
for (int y = 0; y < tilesetHeight; y+=16)
{
for (int x = 0; x < tilesetWidth; x+=16)
{
Tile newTile;
}
}
}
*/
void findNeighboors(int (&near)[4], int index)
{
// записывает в принимаемый массив индексы смежных с данной клеток
int leftSide[14] = { 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224 };
int rightSide[14] = { 31, 47, 63, 79, 95, 111, 127, 143, 159, 175, 191, 207, 223, 239 };
// проверяем, находится ли элемент с индексом index в углах
switch (index)
{
case 0: // левый верхний
near[0] = index + 1;
near[1] = index + 16; // 16 в данном случае и дальше в функции - кол-во клеток по вертикали и горизонтали. Это изменяемый параметр
break;
case 15: // правый верхний
near[0] = index - 1;
near[1] = index + 16;
break;
case 240: // левый нижний
near[0] = index - 16;
near[1] = index + 1;
break;
case 255: // правый нижний
near[0] = index - 16;
near[1] = index - 1;
}
// проверяем, находится ли клетка в верхнем ряду
if (index >= 1 && index <= 14)
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index + 16;
}
else if (index >= 241 && index <= 254) // проверяем, находится ли клетка в нижнем ряду
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index - 16;
}
// проверяем, находится ли клетка на левой стороне
for (int i = 0; i <= 13; i++)
{
if (leftSide[i] == index)
{
near[0] = index - 16;
near[1] = index + 1;
near[2] = index + 16;
}
}
if (near[0] == -1)
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index - 16;
near[3] = index + 16;
}
// проверяем, находится ли клетка на правой стороне
for (int i = 0; i <= 13; i++)
{
if (rightSide[i] == index)
{
near[0] = index - 16;
near[1] = index - 1;
near[2] = index + 16;
}
}
// проверяем, находится ли клетка во внутреннем квадрате
if (near[0] == -1)
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index - 16;
near[3] = index + 16;
}
}
void extend(vector<Cell> &map, int index)
{
// распространяет ограничения
/*
алгоритм распространения ограничений
взять последнюю решённую клетку
вычислить её соседей
для каждой соседней нерешённой клетки
сравнить домен соседней и возможные варианты текущей
выкинуть из домена соседней клетки, не входящие в варианты текущей
*/
int near[4] = { -1, -1, -1, -1 };
findNeighboors(near, index);
int neighboor;
for (int i = 0; i < 4; i++)
{
if (near[i] == -1)
continue;
neighboor = near[i];
vector<string>::iterator startSearch = map[index].tile.compatible.begin();
vector<string>::iterator finishSearch = map[index].tile.compatible.end();
if (map[neighboor].isDecided() == false) // обрабатываем только нерешённые смежные тайлы
{
/*Для каждого варианта в домене нерешённой ищем соответствующий в вариантах решённой. Если ничего
не нашли - удаляем вариант из домена*/
for (unsigned int i = 0; i < map[neighboor].domain.size(); i++) /*проходим по домену нерешённой клетки*/
{
bool found = false;
/*поиск текущего элемента из домена в возможных вариантах клетки.*/
string searchString = map[neighboor].domain[i].name;
vector<string>::const_iterator tileIter = find(startSearch, finishSearch, searchString);
if (tileIter != map[index].tile.compatible.end())
found = true;
if (found == false)
map[neighboor].domain.erase(map[neighboor].domain.begin() + i);
}
}
}
}
void sandFilter(vector<Cell> &map, Tile filterTile)
{
// заменяет песок на землю, если клетка, содержащая песок, не граничит с водой
int neighboors[4] = { -1, -1, -1, -1 };
int currentNeighboor;
bool hasWater;
for (unsigned int i = 0; i < map.size(); i++) // перебор всей карты
{
if (map[i].tile.name == "sand") // если нашли песок
{
neighboors[0] = -1;
neighboors[1] = -1;
neighboors[2] = -1;
neighboors[3] = -1;
hasWater = false;
findNeighboors(neighboors, i); // ищем соседей
for (int j = 0; j < 4; j++) // перебор соседей
{
currentNeighboor = neighboors[j];
if (currentNeighboor != -1)
{
if (map[currentNeighboor].tile.name == "water") // если сосед - вода
hasWater = true;
}
}
if (hasWater == false)
map[i].setTile(filterTile);
}
}
}
void drawMap(RenderWindow &window, vector<Cell> map)
{
// рисует готовую карту
for (unsigned int i = 0; i < map.size(); i++)
map[i].drawCell(window);
}
int main()
{
RenderWindow window(sf::VideoMode(256, 256), "SFML Wave function collapse");
srand(static_cast<unsigned int> (time(0)));
Tile water, sand, ground;
water.name = "water";
sand.name = "sand";
ground.name = "ground";
water.probability = 0.5;
sand.probability = 0.1;
ground.probability = 0.5;
water.color = Color::Blue;
sand.color = Color::Yellow;
ground.color = Color::Green;
water.compatible.push_back("water");
water.compatible.push_back("sand");
sand.compatible.push_back("water");
sand.compatible.push_back("sand");
sand.compatible.push_back("ground");
ground.compatible.push_back("sand");
ground.compatible.push_back("ground");
vector<Tile> tiles;
tiles.push_back(water);
tiles.push_back(sand);
tiles.push_back(ground);
vector<Cell> map;
// заполнить поверхность клетками в суперпозиции
initCells(map, tiles);
int lastDecided = 0;
for (int i = 0; i < 256; i++)
{
// локально распространить ограничения
extend(map, lastDecided);
// выбор клетки с наименьшей энтропией
int minEntropia = 4;
int minIndex = 0;
for (unsigned int j = 0; j < map.size(); j++)
{
if ((map[j].getEntropia() < minEntropia) && (map[j].isDecided() == false))
{
minEntropia = map[j].getEntropia();
minIndex = j;
}
}
// решение клетки с наименьшей энтропией
setNewState(map, minIndex);
lastDecided = minIndex;
}
sandFilter(map, ground);
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
// drawing;
drawMap(window, map);
window.display();
}
return 0;
} | [
"gordienko.gordienkodima2004@yandex.ru"
] | gordienko.gordienkodima2004@yandex.ru |
9242fa7fc26623e3a845dd9eef457bcaf56392c3 | 76f79c8242b5e68f3fba1afdb134608482aced6d | /DogsMustDie/Classes/BuyScene.h | 6c0c35455862a89101e82b66037b00a561d368c4 | [] | no_license | daoduchai/DogsMustDie | 92a66d978bbcc349b45a635d96c576cad02c8e03 | f07d7cd33d4a66fc4c952ac5d4d3e10d8ae0e644 | refs/heads/master | 2021-01-22T08:40:00.115080 | 2013-05-16T16:00:27 | 2013-05-16T16:00:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | h |
#ifndef BuyScene_h__
#define BuyScene_h__
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#include "SimpleAudioEngine.h"
#include "BuyLayer.h"
class BuyScene : public cocos2d::CCScene
{
public:
BuyScene(void);
~BuyScene(void);
virtual bool init();
CREATE_FUNC(BuyScene);
CC_SYNTHESIZE(BuyLayer*, m_pBuyLayer, BuyLayer);
};
#endif // BuyScene_h__ | [
"25331812a"
] | 25331812a |
caa6d824924cce0c0fb30f7f346ca226c69781cd | ce87d9968abead1aaa084a343f9f18379d666922 | /src/actor/actor_actions/use_skill_action.cpp | a60b22bb73bb57af8e579854e022e7360d19590b | [] | no_license | lonski/amarlon | eec7cbf6da257bbc4d2385e1b3f64631c970536d | fd9abe327f98bd7050aef193803f5d9cba0bf5f1 | refs/heads/master | 2022-01-14T21:32:12.203539 | 2021-12-30T10:28:04 | 2021-12-30T10:28:04 | 24,822,534 | 7 | 3 | null | 2015-05-17T12:08:49 | 2014-10-05T18:18:47 | C++ | UTF-8 | C++ | false | false | 693 | cpp | #include "use_skill_action.h"
#include <skill.h>
namespace amarlon {
UseSkillAction::UseSkillAction(SkillPtr skill, Target target)
: _skill(skill)
, _target(target)
{
}
UseSkillAction::~UseSkillAction()
{
}
ActorActionResult UseSkillAction::perform(ActorPtr user)
{
_user = user;
ActorActionResult r = ActorActionResult::Nok;
if ( _user && _skill )
{
r = _skill->use(_user, _target) ? ActorActionResult::Ok
: ActorActionResult::Nok;
}
return r;
}
ActorActionUPtr UseSkillAction::clone()
{
UseSkillActionUPtr cloned = std::make_unique<UseSkillAction>(_skill, _target);
cloned->_user = _user;
return std::move(cloned);
}
}
| [
"michal@lonski.pl"
] | michal@lonski.pl |
573dd44f707a3e83a1cc3827ac3e2c2b49dfc963 | 759ec1fd0308bcb3471dcddffb3a665a9e9c1479 | /src/Camera_I.hpp | f3c534a70f866fcd6272bb359f6ccdf8502a8722 | [] | no_license | pfriesch/makingOfMoon | 8787644a560d817b10bc7663afd7caac0b445264 | b0916525b81bb0453911559c46f9944df61d4892 | refs/heads/master | 2021-09-04T00:36:53.951178 | 2018-01-11T22:59:02 | 2018-01-11T22:59:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | hpp | #pragma once
#include "common.hpp"
#include "WindowManager.hpp"
class Camera_I : public WindowEventListener {
public:
virtual void onWindowSizeChanged(int width, int height) = 0;
};
| [
"p.friesch@posteo.de"
] | p.friesch@posteo.de |
6070b13c45099e983645c086e468fc7ccc75d9a1 | 4054a250ae5db77119bfc5fd54de94675a3231ca | /test/block_cipher/test_aes_cbc.cpp | 8189a8662fa59a9a3d29070e35bb15eca85dc45d | [
"MIT"
] | permissive | hocktide/v-c-crypto | 21c937421534191e29d152f1e173e7e2dbd40bd0 | 4f3d5f21cc62f4a92c7987abdbcaee2d652781ca | refs/heads/master | 2022-09-10T13:13:25.771967 | 2020-05-14T03:26:13 | 2020-05-29T19:37:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,037 | cpp | /**
* \file test_aes_cbc.cpp
*
* Unit tests for AES CBC Mode.
*
* \copyright 2018 Velo Payments, Inc. All rights reserved.
*/
#include <gtest/gtest.h>
#include <vccrypt/block_cipher.h>
#include <vpr/allocator/malloc_allocator.h>
using namespace std;
class aes_cbc_test : public ::testing::Test {
protected:
void SetUp() override
{
/* register all AES block ciphers. */
vccrypt_block_register_AES_256_CBC_FIPS();
vccrypt_block_register_AES_256_2X_CBC();
vccrypt_block_register_AES_256_3X_CBC();
vccrypt_block_register_AES_256_4X_CBC();
/* set up allocator */
malloc_allocator_options_init(&alloc_opts);
/* set up options for each variant. */
fips_options_init_result =
vccrypt_block_options_init(
&fips_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_CBC_FIPS);
x2_options_init_result =
vccrypt_block_options_init(
&x2_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_2X_CBC);
x3_options_init_result =
vccrypt_block_options_init(
&x3_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_3X_CBC);
x4_options_init_result =
vccrypt_block_options_init(
&x4_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_4X_CBC);
}
void TearDown() override
{
/* tear down options for each variant. */
if (0 == fips_options_init_result)
{
dispose((disposable_t*)&fips_options);
}
if (0 == x2_options_init_result)
{
dispose((disposable_t*)&x2_options);
}
if (0 == x3_options_init_result)
{
dispose((disposable_t*)&x3_options);
}
if (0 == x4_options_init_result)
{
dispose((disposable_t*)&x4_options);
}
dispose((disposable_t*)&alloc_opts);
}
allocator_options_t alloc_opts;
vccrypt_block_options_t fips_options;
vccrypt_block_options_t x2_options;
vccrypt_block_options_t x3_options;
vccrypt_block_options_t x4_options;
int fips_options_init_result;
int x2_options_init_result;
int x3_options_init_result;
int x4_options_init_result;
};
/**
* We should be able to create an options structure for each of the supported
* CBC mode ciphers.
*/
TEST_F(aes_cbc_test, register_options)
{
/* Test FIPS AES-256-CBC options init. */
ASSERT_EQ(0, fips_options_init_result);
EXPECT_NE(nullptr, fips_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, fips_options.alloc_opts);
EXPECT_EQ(32U, fips_options.key_size);
EXPECT_EQ(16U, fips_options.IV_size);
EXPECT_EQ(UINT64_MAX, fips_options.maximum_message_size);
EXPECT_NE(nullptr, fips_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, fips_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, fips_options.vccrypt_block_alg_decrypt);
/* Test AES-256-2X-CBC options init. */
ASSERT_EQ(0, x2_options_init_result);
EXPECT_NE(nullptr, x2_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, x2_options.alloc_opts);
EXPECT_EQ(32U, x2_options.key_size);
EXPECT_EQ(16U, x2_options.IV_size);
EXPECT_EQ(UINT64_MAX, x2_options.maximum_message_size);
EXPECT_NE(nullptr, x2_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, x2_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, x2_options.vccrypt_block_alg_decrypt);
/* Test AES-256-3X-CBC options init. */
ASSERT_EQ(0, x3_options_init_result);
EXPECT_NE(nullptr, x3_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, x3_options.alloc_opts);
EXPECT_EQ(32U, x3_options.key_size);
EXPECT_EQ(16U, x3_options.IV_size);
EXPECT_EQ(UINT64_MAX, x3_options.maximum_message_size);
EXPECT_NE(nullptr, x3_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, x3_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, x3_options.vccrypt_block_alg_decrypt);
/* Test AES-256-4X-CBC options init. */
ASSERT_EQ(0, x4_options_init_result);
EXPECT_NE(nullptr, x4_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, x4_options.alloc_opts);
EXPECT_EQ(32U, x4_options.key_size);
EXPECT_EQ(16U, x4_options.IV_size);
EXPECT_EQ(UINT64_MAX, x4_options.maximum_message_size);
EXPECT_NE(nullptr, x4_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, x4_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, x4_options.vccrypt_block_alg_decrypt);
}
/**
* We should be able to initialize, encrypt, and decrypt using a FIPS compatible
* block cipher. TEST from FIPS-800-38a (F.2.5).
*/
TEST_F(aes_cbc_test, aes_256_cbc_fips_f25)
{
vccrypt_block_context_t ctx;
vccrypt_buffer_t key;
const uint8_t KEY[32] = {
0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe,
0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7,
0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4
};
const uint8_t IV[16] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};
const uint8_t PLAINTEXT[64] = {
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10
};
const uint8_t CIPHERTEXT[64] = {
0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba,
0x77, 0x9e, 0xab, 0xfb, 0x5f, 0x7b, 0xfb, 0xd6,
0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d,
0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d,
0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf,
0xa5, 0x30, 0xe2, 0x63, 0x04, 0x23, 0x14, 0x61,
0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc,
0xda, 0x6c, 0x19, 0x07, 0x8c, 0x6a, 0x9d, 0x1b
};
uint8_t output[64];
uint8_t poutput[64];
/* write junk to the output buffers */
memset(output, 0xFC, sizeof(output));
memset(poutput, 0xFC, sizeof(poutput));
/* create a buffer for the key data. */
ASSERT_EQ(0, vccrypt_buffer_init(&key, &alloc_opts, sizeof(KEY)));
/* read the key into the buffer. */
ASSERT_EQ(0, vccrypt_buffer_read_data(&key, KEY, sizeof(KEY)));
/* create a new block cipher with the given key. */
ASSERT_EQ(0, vccrypt_block_init(&fips_options, &ctx, &key, true));
/* encrypt each plaintext block, writing to output. */
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, IV, PLAINTEXT, output));
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, output, PLAINTEXT + 16, output + 16));
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, output + 16, PLAINTEXT + 32, output + 32));
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, output + 32, PLAINTEXT + 48, output + 48));
/* the encrypted data should match our ciphertext */
ASSERT_EQ(0, memcmp(output, CIPHERTEXT, sizeof(output)));
/* clean up encryption context */
dispose((disposable_t*)&ctx);
/* create a new block cipher with the given key. */
ASSERT_EQ(0, vccrypt_block_init(&fips_options, &ctx, &key, false));
/* decrypt each ciphertext block, writing it to poutput. */
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, IV, CIPHERTEXT, poutput));
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, CIPHERTEXT, CIPHERTEXT + 16, poutput + 16));
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, CIPHERTEXT + 16, CIPHERTEXT + 32, poutput + 32));
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, CIPHERTEXT + 32, CIPHERTEXT + 48, poutput + 48));
/* the decrypted data should match our plaintext */
ASSERT_EQ(0, memcmp(poutput, PLAINTEXT, sizeof(poutput)));
dispose((disposable_t*)&ctx);
dispose((disposable_t*)&key);
}
| [
"nanolith@gmail.com"
] | nanolith@gmail.com |
610098b47f76932e4c841d8d53c9f64079c81a84 | ac62c3107b48aab1267c1e0e75653e9f3ded6e49 | /_COISA/exemplo_console/mysocket.h | b72b10f2323722f8b53c0aed0c798a6af441edb3 | [] | no_license | lariskelmer/programacao-avancada | e61bfd62902efea407f3c44f315ef1da306e2857 | 15c5129d998ff949c3ea0926ee2f5de3fa15c752 | refs/heads/master | 2020-08-30T12:26:37.924282 | 2019-10-30T19:18:44 | 2019-10-30T19:18:44 | 218,379,914 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,148 | h | #ifndef _MYSOCKET_H_
#define _MYSOCKET_H_
#include <iostream>
#include <string>
#include <stdint.h>
/* #############################################################
## ATENCAO: VOCE DEVE DESCOMENTAR UMA DAS LINHAS ABAIXO ##
## PARA PODER COMPILAR NO WINDOWS OU NO LINUX ##
############################################################# */
#define _SOP_WINDOWS_
//#define _SOP_LINUX_
// As linhas necessarias para compilar no Windows
#ifdef _SOP_WINDOWS_
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x501
#endif // _WIN32_WINNT
#include <winsock2.h>
#include <ws2tcpip.h>
#endif // _SOP_WINDOWS_
// As linhas necessarias para compilar no Linux
#ifdef _SOP_LINUX_
typedef int SOCKET;
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#include <sys/socket.h>
#endif // _SOP_LINUX_
typedef int MYSOCKET_STATUS;
#define SOCKET_OK 0
// Valor de retorno quando o outro socket encerrou a conexao corretamente
#define SOCKET_DISCONNECTED -666
// Valor de retorno em caso de timeout
#define SOCKET_TIMEOUT -999
#define TAM_MAX_MSG_STRING 256
// Predefinicao das classes
class mysocket_queue;
class tcp_mysocket;
class tcp_mysocket_server;
/* #############################################################
## A classe base dos sockets ##
############################################################# */
class mysocket
{
private:
SOCKET id;
public:
/// Construtor por default
inline mysocket(): id(INVALID_SOCKET) {}
/// Permuta dois sockets
/// Geralmente, deve ser utilizado ao inves do operador de atribuicao
void swap(mysocket &S);
/// Fecha (caso esteja aberto) um socket
void close();
/// Testa se um socket eh "virgem" ou foi fechado
inline bool closed() const {return id==INVALID_SOCKET;}
/// Testa se um socket estah aberto (aceitando conexoes)
inline bool accepting() const {return !closed();}
/// Testa se um socket estah conectado (pronto para ler e escrever)
inline bool connected() const {return !closed();}
/// Imprime um socket
friend std::ostream& operator<<(std::ostream& os, const mysocket &);
/// As classes amigas
friend class tcp_mysocket;
friend class tcp_mysocket_server;
friend class mysocket_queue;
};
/* #############################################################
## As classes dos sockets orientados a conexao (TCP) ##
############################################################# */
class tcp_mysocket: public mysocket
{
public:
/// Construtor default
inline tcp_mysocket(): mysocket() {}
/// Se conecta a um socket aberto
/// Soh pode ser usado em sockets "virgens" ou explicitamente fechados
/// Retorna SOCKET_OK, se tudo deu certo, ou outro valor, em caso de erro
MYSOCKET_STATUS connect(const char *name, const char *port);
/// Leh de um socket conectado
/// Soh pode ser usado em socket para o qual tenha sido feito um "connect" antes
/// Ou entao em um socket retornado pelo "accept" de um socket servidor
/// O ultimo parametro eh o tempo maximo (em milisegundos) para esperar
/// por dados; se for <0, que eh o default, espera indefinidamente.
/// Retorna:
/// - o numero de bytes lidos (ou seja, len, >0), em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout;
/// - SOCKET_DISCONNECTED, se a conexao foi fechada corretamente; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS read(char *dado, size_t len, long milisec=-1) const;
/// Escreve em um socket conectado
/// Soh pode ser usado em socket para o qual tenha sido feito um "connect" antes
/// Ou entao em um socket retornado pelo "accept" de um socket servidor
/// Retorna:
/// - o numero de bytes enviados (ou seja, len), em caso de sucesso; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS write(const char* dado, size_t len) const;
/// Leh um int32_t de um socket conectado
/// O ultimo parametro eh o tempo maximo (em milisegundos) para esperar
/// por dados; se for <0, que eh o default, espera indefinidamente.
/// Retorna:
/// - o numero de bytes lidos (ou seja, 4), em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout;
/// - SOCKET_DISCONNECTED, se a conexao foi fechada corretamente; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS read_int(int32_t &num, long milisec=-1) const;
/// Escreve um int32_t em um socket conectado
/// Retorna o numero de bytes enviados (ou seja, 4), em caso de sucesso,
/// ou SOCKET_ERRO
MYSOCKET_STATUS write_int(const int32_t num) const;
/// Leh uma string de um socket conectado
/// Primeiro leh o numero de bytes da string (int32_T), depois os caracteres
/// O ultimo parametro eh o tempo maximo (em milisegundos) para esperar
/// por dados; se for <0, que eh o default, espera indefinidamente.
/// Retorna:
/// - o numero de bytes lidos (ou seja, msg.size()), em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout;
/// - SOCKET_DISCONNECTED, se a conexao foi fechada corretamente; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS read_string(std::string &msg, long milisec=-1) const;
/// Escreve uma string em um socket conectado
/// Primeiro escreve o numero de bytes da string (int32_T), depois os caracteres
/// Retorna o numero de bytes enviados (ou seja, msg.size()), em caso de sucesso,
/// ou SOCKET_ERRO
MYSOCKET_STATUS write_string(const std::string &msg) const;
};
class tcp_mysocket_server: public mysocket
{
public:
/// Construtor default
inline tcp_mysocket_server(): mysocket() {}
/// Abre um novo socket para esperar conexoes
/// Soh pode ser usado em sockets "virgens" ou explicitamente fechados
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS listen(const char *port, int nconex=1);
/// Aceita uma conexao que chegou em um socket aberto
/// Soh pode ser usado em socket para o qual tenha sido feito um "listen" antes
/// O socket "a" passado como parametro, em caso de sucesso, estarah conectado
/// (nao-conectado em caso de erro)
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS accept(tcp_mysocket &a) const;
};
/* #############################################################
## A fila de sockets ##
############################################################# */
class mysocket_queue
{
private:
fd_set set;
/// Construtor por copia
/// NUNCA DEVE SER CHAMADO OU UTILIZADO
mysocket_queue(const mysocket_queue &S);
/// Operador de atribuicao
/// NUNCA DEVE SER CHAMADO OU UTILIZADO
void operator=(const mysocket_queue &S);
public:
/// Limpa a lista de sockets
inline void clean() {FD_ZERO(&set);};
/// Construtor e destrutor
inline mysocket_queue() {clean();}
inline ~mysocket_queue() {clean();}
/// Adiciona um socket a uma fila de sockets
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS include(const mysocket &a);
/// Retira um socket de uma fila de sockets
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS exclude(const mysocket &a);
/// Bloqueia ateh haver alguma atividade de leitura em socket da fila
/// Retorna:
/// - o numero de sockets (>0) que tem dados a serem lidos em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS wait_read(long milisec=-1);
/// Bloqueia ateh haver alguma atividade de conexao em socket da fila
/// Retorna:
/// - o numero de sockets (>0) que tem dados a serem lidos em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout; ou
/// - SOCKET_ERRO, em caso de erro
inline MYSOCKET_STATUS wait_connect(long milisec=-1) {return wait_read(milisec);}
/// Bloqueia ateh haver alguma atividade de escrita em socket da fila
/// Retorna:
/// - o numero de sockets (>0) que tem dados a serem lidos em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS wait_write(long milisec=-1);
/// Testa se houve atividade em um socket especifico da fila
bool had_activity(const mysocket &a);
};
#endif
| [
"amc.marcelino.cordeiro@gmail.com"
] | amc.marcelino.cordeiro@gmail.com |
59a2f96238c3ef4c78e821e4cf02189378c9d291 | 7b36063fb05909c9bca723e677b083fb7349ef04 | /algorithm/0258-add-digits/solution.cc | 7d3e0da57a6d997ae199b646c91c356060719171 | [] | no_license | Liam0205/leetcode | c3dff919fbd596ed3bcea514c599c18c66b4a388 | 64c668a8f47a8e649e90a5881a884559c31a1a1c | refs/heads/master | 2022-02-20T19:37:38.492782 | 2022-02-08T10:07:10 | 2022-02-08T10:19:02 | 49,959,125 | 7 | 4 | null | 2018-11-26T01:34:55 | 2016-01-19T14:46:23 | C++ | UTF-8 | C++ | false | false | 120 | cc | class Solution {
public:
int addDigits(int num) {
return (num - (int) (9 * floor((num - 1) / 9)));
}
};
| [
"liamhuang0205@gmail.com"
] | liamhuang0205@gmail.com |
7f225e4572a4b77fd2886bd069462abad2baa9c0 | e7428bcf823db625cdd988f9a2a57e146f3b74d8 | /src/amount.cpp | dd572cd103ba5a82edde7bee51dec9225d304f2c | [
"MIT"
] | permissive | 4XT-Forex-Trading/4xt | bf8ddcc7df0d76f7def4531a3e37b8c16ee0ca50 | ab8d27b4e760281e8e4d974044e1ddca4ae626f0 | refs/heads/master | 2021-05-17T01:32:43.492049 | 2020-03-27T14:34:59 | 2020-03-27T14:34:59 | 250,557,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Copyright (c) 2020 The Forex Trading developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "tinyformat.h"
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize)
{
if (nSize > 0)
nSatoshisPerK = nFeePaid * 1000 / nSize;
else
nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nSize) const
{
CAmount nFee = nSatoshisPerK * nSize / 1000;
if (nFee == 0 && nSatoshisPerK > 0)
nFee = nSatoshisPerK;
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d 4XT/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN);
}
| [
"4XT-Forex-Trading@users.noreply.github.com"
] | 4XT-Forex-Trading@users.noreply.github.com |
84cb8f7a20954b011a38fb0337d0b547327465a5 | 21ede326b6cfcf5347ca6772d392d3acca80cfa0 | /content/renderer/input/input_event_prediction.cc | 72f91539214b2b2c8ee9c893714e4de287f5b3cb | [
"BSD-3-Clause"
] | permissive | csagan5/kiwi | 6eaab0ab4db60468358291956506ad6f889401f8 | eb2015c28925be91b4a3130b3c2bee2f5edc91de | refs/heads/master | 2020-04-04T17:06:54.003121 | 2018-10-24T08:20:01 | 2018-10-24T08:20:01 | 156,107,399 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,915 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/input/input_event_prediction.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "content/public/common/content_features.h"
#include "ui/events/blink/prediction/empty_predictor.h"
#include "ui/events/blink/prediction/least_squares_predictor.h"
using blink::WebInputEvent;
using blink::WebMouseEvent;
using blink::WebPointerEvent;
using blink::WebPointerProperties;
using blink::WebTouchEvent;
namespace content {
namespace {
constexpr char kPredictor[] = "predictor";
constexpr char kInputEventPredictorTypeLsq[] = "lsq";
} // namespace
InputEventPrediction::InputEventPrediction() {
std::string predictor_type_ = GetFieldTrialParamValueByFeature(
features::kResamplingInputEvents, kPredictor);
if (predictor_type_ == kInputEventPredictorTypeLsq)
selected_predictor_type_ = PredictorType::kLsq;
else
selected_predictor_type_ = PredictorType::kEmpty;
mouse_predictor_ = CreatePredictor();
}
InputEventPrediction::~InputEventPrediction() {}
void InputEventPrediction::HandleEvents(
const blink::WebCoalescedInputEvent& coalesced_event,
base::TimeTicks frame_time,
blink::WebInputEvent* event) {
switch (event->GetType()) {
case WebInputEvent::kMouseMove:
case WebInputEvent::kTouchMove:
case WebInputEvent::kPointerMove: {
size_t coalesced_size = coalesced_event.CoalescedEventSize();
for (size_t i = 0; i < coalesced_size; i++)
UpdatePrediction(coalesced_event.CoalescedEvent(i));
ApplyResampling(frame_time, event);
break;
}
case WebInputEvent::kTouchScrollStarted:
case WebInputEvent::kPointerCausedUaAction:
pointer_id_predictor_map_.clear();
break;
default:
ResetPredictor(*event);
}
}
std::unique_ptr<ui::InputPredictor> InputEventPrediction::CreatePredictor()
const {
switch (selected_predictor_type_) {
case PredictorType::kEmpty:
return std::make_unique<ui::EmptyPredictor>();
case PredictorType::kLsq:
return std::make_unique<ui::LeastSquaresPredictor>();
}
}
void InputEventPrediction::UpdatePrediction(const WebInputEvent& event) {
if (WebInputEvent::IsTouchEventType(event.GetType())) {
DCHECK(event.GetType() == WebInputEvent::kTouchMove);
const WebTouchEvent& touch_event = static_cast<const WebTouchEvent&>(event);
for (unsigned i = 0; i < touch_event.touches_length; ++i) {
if (touch_event.touches[i].state == blink::WebTouchPoint::kStateMoved) {
UpdateSinglePointer(touch_event.touches[i], touch_event.TimeStamp());
}
}
} else if (WebInputEvent::IsMouseEventType(event.GetType())) {
DCHECK(event.GetType() == WebInputEvent::kMouseMove);
UpdateSinglePointer(static_cast<const WebMouseEvent&>(event),
event.TimeStamp());
} else if (WebInputEvent::IsPointerEventType(event.GetType())) {
DCHECK(event.GetType() == WebInputEvent::kPointerMove);
UpdateSinglePointer(static_cast<const WebPointerEvent&>(event),
event.TimeStamp());
}
}
void InputEventPrediction::ApplyResampling(base::TimeTicks frame_time,
WebInputEvent* event) {
if (event->GetType() == WebInputEvent::kTouchMove) {
WebTouchEvent* touch_event = static_cast<WebTouchEvent*>(event);
for (unsigned i = 0; i < touch_event->touches_length; ++i) {
if (ResampleSinglePointer(frame_time, &touch_event->touches[i]))
event->SetTimeStamp(frame_time);
}
} else if (event->GetType() == WebInputEvent::kMouseMove) {
if (ResampleSinglePointer(frame_time, static_cast<WebMouseEvent*>(event)))
event->SetTimeStamp(frame_time);
} else if (event->GetType() == WebInputEvent::kPointerMove) {
if (ResampleSinglePointer(frame_time, static_cast<WebPointerEvent*>(event)))
event->SetTimeStamp(frame_time);
}
}
void InputEventPrediction::ResetPredictor(const WebInputEvent& event) {
if (WebInputEvent::IsTouchEventType(event.GetType())) {
const WebTouchEvent& touch_event = static_cast<const WebTouchEvent&>(event);
for (unsigned i = 0; i < touch_event.touches_length; ++i) {
if (touch_event.touches[i].state != blink::WebTouchPoint::kStateMoved &&
touch_event.touches[i].state !=
blink::WebTouchPoint::kStateStationary)
pointer_id_predictor_map_.erase(touch_event.touches[i].id);
}
} else if (WebInputEvent::IsMouseEventType(event.GetType())) {
ResetSinglePredictor(static_cast<const WebMouseEvent&>(event));
} else if (WebInputEvent::IsPointerEventType(event.GetType())) {
ResetSinglePredictor(static_cast<const WebPointerEvent&>(event));
}
}
void InputEventPrediction::UpdateSinglePointer(
const WebPointerProperties& event,
base::TimeTicks event_time) {
ui::InputPredictor::InputData data = {event.PositionInWidget(), event_time};
if (event.pointer_type == WebPointerProperties::PointerType::kMouse)
mouse_predictor_->Update(data);
else {
auto predictor = pointer_id_predictor_map_.find(event.id);
if (predictor != pointer_id_predictor_map_.end()) {
predictor->second->Update(data);
} else {
// Workaround for GLIBC C++ < 7.3 that fails to insert with braces
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82522
auto pair = std::make_pair(event.id, CreatePredictor());
pointer_id_predictor_map_.insert(std::move(pair));
pointer_id_predictor_map_[event.id]->Update(data);
}
}
}
bool InputEventPrediction::ResampleSinglePointer(base::TimeTicks frame_time,
WebPointerProperties* event) {
ui::InputPredictor::InputData predict_result;
if (event->pointer_type == WebPointerProperties::PointerType::kMouse) {
if (mouse_predictor_->HasPrediction() &&
mouse_predictor_->GeneratePrediction(frame_time, &predict_result)) {
event->SetPositionInWidget(predict_result.pos);
return true;
}
} else {
// Reset mouse predictor if pointer type is touch or stylus
mouse_predictor_->Reset();
auto predictor = pointer_id_predictor_map_.find(event->id);
if (predictor != pointer_id_predictor_map_.end() &&
predictor->second->HasPrediction() &&
predictor->second->GeneratePrediction(frame_time, &predict_result)) {
event->SetPositionInWidget(predict_result.pos);
return true;
}
}
return false;
}
void InputEventPrediction::ResetSinglePredictor(
const WebPointerProperties& event) {
if (event.pointer_type == WebPointerProperties::PointerType::kMouse)
mouse_predictor_->Reset();
else
pointer_id_predictor_map_.erase(event.id);
}
} // namespace content
| [
"team@geometry.ee"
] | team@geometry.ee |
9735167e3e5593c888fab2841b95e89e72fdb211 | e53518a04b26c3019d9a3940726c29a1b3bb6c82 | /VC_USB_GPIO_Test/USB_GPIO_Test/USB_GPIO_Test/USB_GPIO_Test.cpp | c3edcf87d113947cdb176718dcf3376218745672 | [] | no_license | viewtool/SPI_Adapter | f4aab07d1617cac9abf9604803b9267df1f01d15 | e8229060805759bee4dd6f974a24251596510b57 | refs/heads/master | 2021-01-21T06:39:24.612496 | 2020-07-06T06:52:43 | 2020-07-06T06:52:43 | 83,263,145 | 6 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,921 | cpp | /*
******************************************************************************
* @file : USB_GPIO_Test.cpp
* @Copyright: ViewTool
* @Revision : ver 1.0
* @Date : 2014/12/19 11:53
* @brief : USB_GPIO_Test demo
******************************************************************************
* @attention
*
* Copyright 2009-2014, ViewTool
* http://www.viewtool.com/
* All Rights Reserved
*
******************************************************************************
*/
#include "stdafx.h"
#include "ControlGPIO.h"
int _tmain(int argc, _TCHAR* argv[])
{
int ret;
// Scan connected device
ret = VGI_ScanDevice(1);
if (ret <= 0)
{
printf("No device connect!\n");
return ret;
}
// Open device
ret = VGI_OpenDevice(VGI_USBGPIO, 0, 0);
if (ret != ERR_SUCCESS)
{
printf("Open device error!\n");
return ret;
}
// Set GPIO_7 and GPIO_8 to output
ret = VGI_SetOutput(VGI_USBGPIO, 0, VGI_GPIO_PIN7 | VGI_GPIO_PIN8);
if (ret != ERR_SUCCESS)
{
printf("Set pin output error!\n");
return ret;
}
// Set GPIO_7 and GPIO_8
ret = VGI_SetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN7 | VGI_GPIO_PIN8);
if (ret != ERR_SUCCESS)
{
printf("Set pin high error!\n");
return ret;
}
// Reset GPIO_7 and GPIO_8
ret = VGI_ResetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN7 | VGI_GPIO_PIN8);
if (ret != ERR_SUCCESS)
{
printf("Set pin low error!\n");
return ret;
}
// Set GPIO_4 and GPIO_5 to input
ret = VGI_SetInput(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin input error!\n");
return ret;
}
// Get GPIO_4 and GPIO_5 status
uint16_t pin_value = 0;
ret = VGI_ReadDatas(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5, &pin_value);
if (ret != ERR_SUCCESS)
{
printf("Get pin data error!\n");
return ret;
}
else
{
if ((pin_value & VGI_GPIO_PIN4) != 0)
{
printf("GPIO_4 is high-level!\n");
}
else
{
printf("GPIO_4 is low-level!\n");
}
if ((pin_value & VGI_GPIO_PIN5) != 0)
{
printf("GPIO_5 is high-level!\n");
}
else
{
printf("GPIO_5 is low-level!\n");
}
}
//将GPIO_4和GPIO_5引脚设置成开漏模式(需加上拉电阻,可当双向口)
ret = VGI_SetOpenDrain(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin open drain error!\n");
return ret;
}
//将GPIO_4和GPIO_5输出高电平
ret = VGI_SetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin high error!\n");
return ret;
}
//将GPIO_4和GPIO_5输出低电平
ret = VGI_ResetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin high error!\n");
return ret;
}
//获取GPIO_4和GPIO_5引脚状态
ret = VGI_ReadDatas(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5, &pin_value);
if (ret != ERR_SUCCESS)
{
printf("Get pin data error!\n");
return ret;
}
else
{
if ((pin_value & VGI_GPIO_PIN4) != 0)
{
printf("GPIO_4 is high-level!\n");
}
else
{
printf("GPIO_4 is low-level!\n");
}
if ((pin_value & VGI_GPIO_PIN5) != 0)
{
printf("GPIO_5 is high-level!\n");
}
else
{
printf("GPIO_5 is low-level!\n");
}
}
//关闭设备
ret = VGI_CloseDevice(VGI_USBGPIO, 0);
if (ret != ERR_SUCCESS)
{
printf("Close device error!\n");
return ret;
}
return 0;
}
| [
"792499568@qq.com"
] | 792499568@qq.com |
40ca0d843b7924ab3c0e8d30880f0d9df6d0a20c | ec68c973b7cd3821dd70ed6787497a0f808e18e1 | /Cpp/SDK/Character_RiftWalker_Clone_Male_AnimBP_parameters.h | 8ea0b46479436b3c7d4fbe63ef233f98784de803 | [] | no_license | Hengle/zRemnant-SDK | 05be5801567a8cf67e8b03c50010f590d4e2599d | be2d99fb54f44a09ca52abc5f898e665964a24cb | refs/heads/main | 2023-07-16T04:44:43.113226 | 2021-08-27T14:26:40 | 2021-08-27T14:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 653 | h | #pragma once
// Name: Remnant, Version: 1.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function Character_RiftWalker_Clone_Male_AnimBP.Character_RiftWalker_Clone_Male_AnimBP_C.ExecuteUbergraph_Character_RiftWalker_Clone_Male_AnimBP
struct UCharacter_RiftWalker_Clone_Male_AnimBP_C_ExecuteUbergraph_Character_RiftWalker_Clone_Male_AnimBP_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
583bf96fcdb0de09d9bf5c85e9072c65e81c4f6f | 91721cafcc790673eb39c99be05bad570aedef74 | /Leetcode practice/260. Single Number III.cpp | 52ea46751904be465f9befb8519d0f87e0ead1f5 | [] | no_license | olee12/Leetcode-practice | 6631d559377d926c480b3115c75b1348be5c55fe | ea4649601af66193da036c4cce6032a22b1a673b | refs/heads/master | 2022-07-09T09:04:26.542487 | 2022-07-02T05:16:10 | 2022-07-02T05:16:10 | 81,569,221 | 0 | 0 | null | 2020-10-13T10:30:13 | 2017-02-10T13:45:44 | C++ | UTF-8 | C++ | false | false | 575 | cpp | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
long long mask = 0;
for(auto n:nums) mask ^= n;
long long diff = mask & (-mask);
long long x = 0;
for(auto n:nums) if(diff & n) x^=n;
return {(int)x, (int)(x^mask)};
}
};
int main(int argc, char const *argv[])
{
vector<int> t1 = {1,2,1,3,2,5};
Solution sol;
for(auto it:sol.singleNumber(t1)) {
cout << it << " ";
}
cout << endl;
return 0;
}
| [
"tahmid.hossain@shopee.com"
] | tahmid.hossain@shopee.com |
9189c35d07bc49c3ba7ac85d1ef74c16ffd8691e | 1c21ea7d49d4d1a6dc96f40bc910496373c0190d | /Valdemar/Metaprogramming/FunctionalProgramming/typelists.cpp | 1e0c85fca7678dbf900f90f43af7d3b766136ceb | [] | no_license | tmoller96/APK | 5fcbc1677e15f6e6a3797a5e15fe72ea7e510e9b | 75d0cfd97b35b874d21656972d40c904900743e7 | refs/heads/master | 2023-02-11T16:05:31.901177 | 2021-01-08T13:27:17 | 2021-01-08T13:27:17 | 292,011,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | #include "at_index.hpp"
#include "contains.hpp"
#include "is_same.hpp"
#include <iostream>
// #define TYPELIST1(T1) TypeList<T1, NullType>;
// #define TYPELIST2(T1, T2) TypeList<T1, T2>;
// #define TYPELIST3(T1, T2, T3) TypeList<T1, TypeList<T2, T3>>;
int main()
{
std::cout << "IsSame <int , int >:: value=" << IsSame<int, int>::value
<< std::endl;
std::cout << "IsSame <int , char >:: value=" << IsSame<int, char>::value
<< std ::endl;
typedef TypeList<int, TypeList<char, TypeList<long, NullType>>> TL;
std::cout << "Contains <TL , int >:: value=" << Contains<TL, int>::value
<< std::endl;
/* Must be false */
std::cout << "Contains <TL , std::string >:: value="
<< Contains<TL, std::string>::value << std::endl;
typedef TypeList<long, TypeList<char, TypeList<int, NullType>>> TL2;
/* Must be true */
std::cout << "IsSame <typename AtIndex <TL , 2>::type , int >:: value"
<< IsSame<typename AtIndex<TL2, 2>::type, int>::value << std::endl;
std::cout << "IsSame <typename AtIndex <TL , 2>::type , char >:: value"
<< IsSame<typename AtIndex<TL2, 2>::type, char>::value << std::endl;
}
| [
"valdemar-tang@hotmail.com"
] | valdemar-tang@hotmail.com |
f8ab8ba26831a6a0c93fff95d7cdf3da714b8860 | 6d90e332ed3e630429e959578df1181967c4bcaa | /AC-Submissions/problems/longest_uploaded_prefix/solution.cpp | 5dcaf09661a35bdae6eefa44d15dddd06ca52fdd | [] | no_license | amir-hosen7/LeetCode | fe27cca877b5ee8c73c00b6553b682b94351e16d | ee13b162c098276abd2f01b0ae4ea6bbe527bfa1 | refs/heads/master | 2023-02-23T04:15:52.250303 | 2023-02-13T12:57:46 | 2023-02-13T12:57:46 | 234,529,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | class LUPrefix {
public:
int bit[200050], N;
void update(int idx, int n) {
while(idx<=n) {
bit[idx]++;
idx+=(idx&-idx);
}
}
int getSum(int idx) {
int sum=0;
while(idx>0) {
sum+=bit[idx];
idx-=(idx&-idx);
}
return sum;
}
LUPrefix(int n) {
N=n;
for(int i=0; i<=N; i++){
bit[i]=0;
}
}
int res;
void upload(int video) {
update(video, N);
//cout<<video<<" "<<getSum(10)<<"\n";
int l=0, r=N;
while(l<=r){
int mid=l+(r-l)/2;
//cout<<mid<<" "<<getSum(mid)<<"\n";
if(mid==getSum(mid)){
res=mid, l=mid+1;
}
else{
r=mid-1;
}
}
}
int longest() {
//cout<<"fahim\n";
return res;
}
};
/**
* Your LUPrefix object will be instantiated and called as such:
* LUPrefix* obj = new LUPrefix(n);
* obj->upload(video);
* int param_2 = obj->longest();
*/ | [
"42311923+amantuamir@users.noreply.github.com"
] | 42311923+amantuamir@users.noreply.github.com |
03ac78f29d1969de2a84999f50ab03e69851897c | 35b929181f587c81ad507c24103d172d004ee911 | /SrcLib/core/fwServices/test/tu/include/ProxyTest.hpp | 4e6e100aba72e324b4cc7c8dda42fffc3759c7dc | [] | no_license | hamalawy/fw4spl | 7853aa46ed5f96660123e88d2ba8b0465bd3f58d | 680376662bf3fad54b9616d1e9d4c043d9d990df | refs/heads/master | 2021-01-10T11:33:53.571504 | 2015-07-23T08:01:59 | 2015-07-23T08:01:59 | 50,699,438 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 797 | hpp | /* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2012.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#ifndef _FWSERVICES_TEST_TU_PROXYTEST_HPP_
#define _FWSERVICES_TEST_TU_PROXYTEST_HPP_
#include <cppunit/extensions/HelperMacros.h>
namespace fwServices
{
namespace ut
{
/// Test ActiveWorkers API
class ProxyTest : public CPPUNIT_NS::TestFixture
{
CPPUNIT_TEST_SUITE( ProxyTest );
CPPUNIT_TEST( basicTest );
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
/// Test using ActiveWorkers API
void basicTest();
};
} //namespace ut
} //namespace fwServices
#endif // _FWSERVICES_TEST_TU_PROXYTEST_HPP_
| [
"fbridault@IRCAD.FR"
] | fbridault@IRCAD.FR |
fde83176d92a265cb0c9c356d5de08aae265ad0b | e9c0ffba62f5bd0c7bc1b3ca6173b40f3ab488f6 | /LeetCode/Maximum-Difference-Between-Node-and-Ancestor.cpp | 83083a9c1fb5fcf74e00b47e85cc750a9c3dac65 | [] | no_license | iiison/technical-interview-prep | 501f15877feef3b6b6e1bf3c1ba8b06b894a923b | 55b91267cdeeb45756fe47e1817cb5f80ed6d368 | refs/heads/master | 2022-11-24T11:21:22.526093 | 2020-08-04T13:49:32 | 2020-08-04T13:49:32 | 285,201,793 | 1 | 0 | null | 2020-08-05T06:33:34 | 2020-08-05T06:33:33 | null | UTF-8 | C++ | false | false | 1,704 | cpp | /* Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.) */
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int maxAncestorDiff(TreeNode* root) {
if (root == NULL)
return 0;
int max_diff = 0;
stack<TreeNode *> st;
map<TreeNode *, int> visited;
st.push(root);
stack<int> max_st, min_st;
max_st.push(0);
min_st.push(INT_MAX);
while (!st.empty()) {
TreeNode *top = st.top();
if (visited[top] == 0) {
if (top->val > max_st.top())
max_st.push(top->val);
else
max_st.push(max_st.top());
if (top->val < min_st.top())
min_st.push(top->val);
else
min_st.push(min_st.top());
}
visited[top] = 1;
if (top->left != NULL && visited[top->left] == 0) {
st.push(top->left);
} else if (top->right != NULL && visited[top->right] == 0) {
st.push(top->right);
} else if (top->left == NULL && top->right == NULL) {
max_diff = max(max_diff, max_st.top() - min_st.top());
}
if ((top->left == NULL || visited[top->left] == 1) && (top->right == NULL || visited[top->right] == 1)) {
st.pop();
max_st.pop();
min_st.pop();
}
}
return max_diff;
}
| [
"le_j6@denison.edu"
] | le_j6@denison.edu |
5984ab9063f56fe7f7445259abdb778b1b2e978a | 119ae639ad591adc341d897df3b0990f75f2c44f | /lib258/tag/20130412/daemon/sysSetting/qt/MySetting/gui/keyclearsetting.cpp | e24f1712483699c371c91f494c6e78f5ef8b90e2 | [] | no_license | scalpovich/openpos | ee584c26c5559b7ea556033bc5b366d07b31e240 | 6280780255970c2ae525233293c2cc2d951b9956 | refs/heads/master | 2021-12-05T22:33:14.425984 | 2015-05-25T12:08:50 | 2015-05-25T12:08:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,345 | cpp | #include "keyclearsetting.h"
extern "C"{
#include "encrypt.h"
#include "osdriver.h"
#include "sand_modules.h"
}
//DRV_IN DrvIn1;
//DRV_OUT DrvOut1;
//DRIVER Drv1;
KeyClearSetting::KeyClearSetting(QWidget *parent) :
BaseForm("KEY CLEAR SETTING",parent)
{
btnAuto = new Button(" Dynamic Key",9);
btnAuto->setFixedSize(160,40);
btnAuto->setObjectName("keyBtn");
labelA = new QLabel;
labelA->setPixmap(QPixmap("/daemon/image/icon/keyA.png"));
layout->addSpacerItem(new QSpacerItem(10, 15+2));
layout->addWidget(labelA);
layout->addWidget(btnAuto);
size = 0;
btnExit->setFocus();
QSettings set("/daemon/conf.ini",QSettings::IniFormat);
childGroups = set.childGroups();
qDebug()<<"childGroups==="<<childGroups;
for(int i=0;i<childGroups.size();i++)
{
set.beginGroup(childGroups.at(i));
int tempid = set.value("ID").toInt();
qDebug()<<"tempid==="<<tempid;
if(tempid>=10){
id[size] = tempid;
qDebug()<<"id[size] size:"<<id[size]<<size;
size++;
}
set.endGroup();
}
qDebug()<<"111size========"<<size;
connect(btnAuto,SIGNAL(clicked()),this,SLOT(slotAuto()));
connect(btnOk,SIGNAL(clicked()),this,SLOT(slotAuto()));
}
KeyClearSetting::~KeyClearSetting()
{
}
void KeyClearSetting::slotAuto()
{
QMessageBox box(QMessageBox::Information,tr(" title "),tr(" ARE YOU SURE TO CLEAR? "));
box.setWindowFlags(Qt::CustomizeWindowHint);
QPushButton *okBtn = new QPushButton(tr("Yes"));
okBtn->setFixedWidth(80);
okBtn->setFixedHeight(25);
box.addButton(okBtn,QMessageBox::YesRole);
QPushButton *noBtn = new QPushButton(tr("No"));
noBtn->setFixedWidth(80);
noBtn->setFixedHeight(25);
box.addButton(noBtn,QMessageBox::NoRole);
box.setDefaultButton(noBtn);
box.exec();
if (box.clickedButton() == noBtn)
return;
KEY_APPID_DATA keyData;
memset(&keyData,0x00,sizeof(KEY_APPID_DATA));
qDebug()<<"size========"<<size;
keyData.appnumber = size;
for(int i=0;i<size;i++)
keyData.appid[i] = id[i];
keyData.delflag = KEY_DEL_PART;
KEY_KeyCheckApp(&keyData);
showInforText("CLEAR SUCCESS!",true,15,185);
QTimer::singleShot(1500,informationBox,SLOT(hide()));
}
| [
"dsand20142014@gmail.com"
] | dsand20142014@gmail.com |
c14919278a659c9f0ca9e65aaafe003fdcc154bf | 18c6a6a5540194165722ac1ab252ce9bb3ca6ad8 | /src/h264_encoder.hpp | 19ab4ef6022640d79509d963c0ff2c51193d15d9 | [
"MIT"
] | permissive | nyamadan/shader_editor | 9e88fcd0d9e1040dfd5ab4357ab4f669602dd0fe | 477aa7165a6f6d721466a4d2fe4d326cf8c9b5df | refs/heads/master | 2021-07-04T07:31:46.691367 | 2020-09-06T07:27:02 | 2020-09-06T07:27:02 | 165,870,082 | 6 | 0 | MIT | 2019-02-21T13:51:12 | 2019-01-15T14:58:39 | C++ | UTF-8 | C++ | false | false | 652 | hpp | #pragma once
namespace h264encoder {
bool LoadEncoderLibrary();
void UnloadEncoderLibrary();
void EncodeFrame(void* pEncoder, mp4_h26x_writer_t* pWriter, uint8_t* data,
int32_t iPicWidth, int32_t iPicHeight, int64_t timestamp);
void Finalize(void* pOpenH264Encoder, MP4E_mux_t* pMP4Muxer,
mp4_h26x_writer_t* pMP4H264Writer);
bool CreateOpenH264Encoder(void** ppEncoder, MP4E_mux_t** pMP4Muxer,
mp4_h26x_writer_t** pMP4H264Writer,
int32_t iPicWidth, int32_t iPicHeight, FILE* fp);
void DestroyOpenH264Encoder(void* pOpenH264Encoder);
} // namespace h264encoder
| [
"nyamadandan@gmail.com"
] | nyamadandan@gmail.com |
cf5c1d7311905a6020390df2343d2bfc3106863e | 732bd48d8fac2ee615ea77345e5b8a992ff36357 | /mods/coreutils/fmt/test/assert-test.cc | eef342eec80b74cf4110b62ff23021c5427843ee | [
"MIT",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"Python-2.0"
] | permissive | sasq64/apone | 133c480d310f29800f79ee889524920fc46963b6 | b6ab1bfdb742d387b7180217f5dc240c5c1d8519 | refs/heads/master | 2020-05-21T22:10:11.672539 | 2019-06-06T21:40:20 | 2019-06-06T21:40:20 | 12,408,282 | 8 | 2 | MIT | 2018-09-13T16:00:24 | 2013-08-27T14:30:10 | C | UTF-8 | C++ | false | false | 1,766 | cc | /*
Assertion tests
Copyright (c) 2015, Victor Zverovich
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 "fmt/format.h"
#include "gtest/gtest.h"
#if GTEST_HAS_DEATH_TEST
# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEBUG_DEATH(statement, regex)
#else
# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
#endif
TEST(AssertTest, Fail) {
EXPECT_DEBUG_DEATH_IF_SUPPORTED(FMT_ASSERT(false, "don't panic!"), "don't panic!");
}
| [
"sasq64@gmail.com"
] | sasq64@gmail.com |
ba924aaafdba7debdb94879726622faa73bcb8e7 | 84f30ef9554af8e67ad66c82b325c3825dc90088 | /src/createJointSystem.cpp | 572bbceb5fad20dd05e5729cb19d1fcdb1c2604b | [
"Apache-2.0"
] | permissive | thishandp7/maya-wing-system | 1fe50bbaf6a9f3de4866766c1c167e41b9b87d80 | 82f6fc37ea988dc8d4692a18866d4ca95ea86f5f | refs/heads/master | 2023-04-08T01:59:50.547106 | 2021-04-01T04:55:08 | 2021-04-01T04:55:08 | 346,257,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,559 | cpp | #include "createJointSystem.h"
CreateJointSystem::CreateJointSystem(MDagPath& shoulderLocator, MDagPath& controlLocator)
{
MStatus status;
MObject shoulderJointObject = dagModifier.createNode("joint", MObject::kNullObj, &status);
jointObjectArray.append(shoulderJointObject);
CHECK_MSTATUS(status);
MObject controlJointObject = dagModifier.createNode("joint", jointObjectArray[0], &status);
jointObjectArray.append(controlJointObject);
CHECK_MSTATUS(status);
dagModifier.doIt();
setJointTransforms(shoulderLocator, controlLocator);
}
CreateJointSystem::~CreateJointSystem()
{
}
void CreateJointSystem::setJointTransforms(MDagPath& shoulderLocator, MDagPath& controlLocator)
{
MStatus status;
MFnIkJoint fnJoint;
MFnTransform fnLocatorTransform;
fnJoint.setObject(jointObjectArray[0]);
fnLocatorTransform.setObject(shoulderLocator);
MVector shoulderLocatorTranslation = fnLocatorTransform.getTranslation(MSpace::kTransform, &status);
CHECK_MSTATUS(status);
status = fnJoint.setTranslation(shoulderLocatorTranslation, MSpace::kTransform);
CHECK_MSTATUS(status);
fnJoint.setObject(jointObjectArray[1]);
fnLocatorTransform.setObject(controlLocator);
MVector controlLocatorTranslation = fnLocatorTransform.getTranslation(MSpace::kTransform, &status);
CHECK_MSTATUS(status);
MVector adjustedOrigin = shoulderLocatorTranslation * -1;
controlLocatorTranslation += adjustedOrigin;
status = fnJoint.setTranslation(controlLocatorTranslation, MSpace::kTransform);
CHECK_MSTATUS(status);
}
| [
"thishandp7@gmail.com"
] | thishandp7@gmail.com |
57b3032f022af9dded66a5d6d62f3f3544ed008d | 2aed63d9aa027419b797e56b508417789a604a8b | /injector2degHex/case_interFoam_3mm/processor5/0.5/uniform/functionObjects/functionObjectProperties | c69c040c27d0c1326024744cd93d80d1200cd49c | [] | no_license | icl-rocketry/injectorCFDModelling | 70137f1c6574240c7202638c3713102a3e1e9fd8 | 96591cf2cf3cd4cbd64536d8ae47ed8080ed9016 | refs/heads/main | 2023-08-25T03:30:59.244137 | 2021-10-09T21:04:45 | 2021-10-09T21:04:45 | 322,369,673 | 3 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 897 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2012 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "0.5/uniform/functionObjects";
object functionObjectProperties;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ************************************************************************* //
| [
"39316550+lucpaoli@users.noreply.github.com"
] | 39316550+lucpaoli@users.noreply.github.com | |
37913b53ce44005d3222d3560f1cd451955a6c53 | b7539d91e63e2fecd8d5308496c492f9fdc08f4e | /ClientMain/ClientRequests.h | 199e31921b972f2035eac16a032e9a7e0c26f547 | [] | no_license | angeloprudentino/MalnatiStorage | b38e3f0dfe3e95f65b3ee7f7f8415b4a1c79d1d6 | 9416fce8e9a663afc015b98d86fd8fc2d3e48381 | refs/heads/master | 2021-01-23T16:52:23.076402 | 2017-09-09T22:52:00 | 2017-09-09T22:52:00 | 102,748,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,124 | h | /*
* Authors: Angelo Prudentino & Daniele Testa
* Date: 16/09/2016
* File: ClientRequests.h
* Description: Objects to interface C++ core dll and WPF gui
*
*/
#pragma once
#include <vcclr.h>
#include <string>
#include <queue>
#include <memory>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/atomic.hpp>
#include "ClientController.h"
using namespace System;
using namespace System::Collections::Generic;
#define NO_ID -1
#define REGISTR_REQ 0
#define LOGIN_REQ 1
#define LOGOUT_REQ 2
#define UPDATE_REQ 3
#define GET_VERSIONS_REQ 4
#define RESTORE_REQ 5
#define PING_REQ 6
//////////////////////////////////
// UserRequest //
//////////////////////////////////
public ref class UserRequest{
protected:
int fID;
public:
UserRequest(){ this->fID = NO_ID; }
//getter
const int getID(){ return this->fID; }
};
//////////////////////////////////
// RegistrRequest //
//////////////////////////////////
public ref class RegistrRequest : public UserRequest{
private:
String^ fUser;
String^ fPass;
String^ fPath;
public:
RegistrRequest(String^ aUser, String^ aPass, String^ aPath);
//getters
String^ getUser() { return this->fUser; }
String^ getPass() { return this->fPass; }
String^ getPath() { return this->fPath; }
};
//////////////////////////////////
// LoginRequest //
//////////////////////////////////
public ref class LoginRequest : public UserRequest{
private:
String^ fUser;
String^ fPass;
public:
LoginRequest(String^ aUser, String^ aPass);
//getters
String^ getUser() { return this->fUser; }
String^ getPass() { return this->fPass; }
};
//////////////////////////////////
// LogoutRequest //
//////////////////////////////////
public ref class LogoutRequest : public UserRequest{
public:
LogoutRequest() { this->fID = LOGOUT_REQ; }
};
//////////////////////////////////
// UpdateRequest //
//////////////////////////////////
public ref class UpdateRequest : public UserRequest{
private:
String^ fUser;
String^ fPass;
String^ fPath;
public:
UpdateRequest(String^ aUser, String^ aPass, String^ aPath);
//getters
String^ getUser() { return this->fUser; }
String^ getPass() { return this->fPass; }
String^ getPath() { return this->fPath; }
};
//////////////////////////////////
// GetVerRequest //
//////////////////////////////////
public ref class GetVerRequest : public UserRequest{
private:
String^ fUser;
String^ fPass;
public:
GetVerRequest(String^ aUser, String^ aPass);
//getters
String^ getUser() { return this->fUser; }
String^ getPass() { return this->fPass; }
};
//////////////////////////////////
// RestoreRequest //
//////////////////////////////////
public ref class RestoreRequest : public UserRequest{
private:
String^ fUser;
String^ fPass;
int fVersion;
String^ fFile;
String^ fDestPath;
public:
RestoreRequest(String^ aUser, String^ aPass, const int aVersion, String^ aFile, String^ aDestPath);
//getters
String^ getUser() { return this->fUser; }
String^ getPass() { return this->fPass; }
const int getVersion() { return this->fVersion; }
String^ getFile() { return this->fFile; }
String^ getDestPath() { return this->fDestPath; }
};
//////////////////////////////////
// PingRequest //
//////////////////////////////////
public ref class PingRequest : public UserRequest{
private:
String^ fToken;
public:
PingRequest(String^ aToken);
//getters
String^ getToken() { return this->fToken; }
};
/////////////////////////////////////
// RequestsQueue //
/////////////////////////////////////
class RequestsQueue{
private:
std::queue<gcroot<UserRequest^>> fQueue;
boost::mutex fMutex;
boost::condition_variable fCond;
boost::atomic<bool> fMustExit;
public:
RequestsQueue();
~RequestsQueue();
RequestsQueue(const RequestsQueue&) = delete; // disable copying
RequestsQueue& operator=(const RequestsQueue&) = delete; // disable assignment
bool isEmpty();
UserRequest^ popRequest();
void pushRequest(UserRequest^ aReq);
}; | [
"12662466+angeloprudentino@users.noreply.github.com"
] | 12662466+angeloprudentino@users.noreply.github.com |
129dc6377f78c7e7a4fcf3b0d5a155e033a3c5ef | ac5442020a5247231ede042926530e500b16b501 | /compilers/new-segmented-backend/src/runtime/communication/comm_buffer.cc | 556ddb59d32641ef4f4c14ac2d02753cf4e3c311 | [] | no_license | MuhammadNurYanhaona/ITandPCubeS | e8a42d8d50f56eb76954bdf2cb786377cb5a8ee5 | 8928c56587db8293f0ec02c7cb030cfb540ce2b4 | refs/heads/master | 2021-01-24T06:22:37.089569 | 2017-04-22T15:57:04 | 2017-04-22T15:57:04 | 15,794,818 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 31,502 | cc | #include "comm_buffer.h"
#include "confinement_mgmt.h"
#include "data_transfer.h"
#include "part_config.h"
#include "../memory-management/allocation.h"
#include "../memory-management/part_tracking.h"
#include "../../../../common-libs/utils/list.h"
#include "../../../../common-libs/utils/binary_search.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <cstring>
using namespace std;
//---------------------------------------------------- Communication Buffer ------------------------------------------------------/
CommBuffer::CommBuffer(DataExchange *exchange, SyncConfig *syncConfig) {
dataExchange = exchange;
senderPartList = syncConfig->getSenderDataParts();
receiverPartList = syncConfig->getReceiverDataParts();
ConfinementConstructionConfig *confinementConfig = syncConfig->getConfinementConfig();
dataDimensions = confinementConfig->getDataDimensions();
elementCount = exchange->getTotalElementsCount();
elementSize = syncConfig->getElementSize();
localSegmentTag = confinementConfig->getLocalSegmentTag();
senderTree = confinementConfig->getSenderPartTree();
receiverTree = confinementConfig->getReceiverPartTree();
senderDataConfig = confinementConfig->getSenderConfig();
receiverDataConfig = confinementConfig->getReceiverConfig();
bufferTag = 0;
}
bool CommBuffer::isSendActivated() {
return dataExchange->getSender()->hasSegmentTag(localSegmentTag);
}
bool CommBuffer::isReceiveActivated() {
return dataExchange->getReceiver()->hasSegmentTag(localSegmentTag);
}
int CommBuffer::compareTo(CommBuffer *other, bool forReceive) {
return dataExchange->compareTo(other->dataExchange, forReceive);
}
void CommBuffer::describe(std::ostream &stream, int indentation) {
std::ostringstream indent;
for (int i = 0; i < indentation; i++) indent << '\t';
stream << indent.str() << "Tag: " << bufferTag << "\n";
stream << indent.str() << "Element Count: " << elementCount << "\n";
dataExchange->describe(indentation, stream);
}
char *CommBuffer::getData() {
std::cout << "buffer content reference is not valid for all communication buffer types";
std::exit(EXIT_FAILURE);
}
void CommBuffer::setData(char *data) {
std::cout << "buffer content reference cannot be set in all communication buffer types";
std::exit(EXIT_FAILURE);
}
void CommBuffer::setBufferTag(int prefix, int digitsForSegment) {
int firstSenderTag = dataExchange->getSender()->getSegmentTags().at(0);
int firstReceiverTag = dataExchange->getReceiver()->getSegmentTags().at(0);
ostringstream ostream;
ostream << prefix;
ostream << std::setfill('0') << std::setw(digitsForSegment) << firstSenderTag;
ostream << std::setfill('0') << std::setw(digitsForSegment) << firstReceiverTag;
istringstream istream(ostream.str());
istream >> this->bufferTag;
}
//---------------------------------------------- Pre-processed Communication Buffer ----------------------------------------------/
PreprocessedCommBuffer::PreprocessedCommBuffer(DataExchange *ex, SyncConfig *sC) : CommBuffer(ex, sC) {
senderTransferMapping = NULL;
receiverTransferMapping = NULL;
if (isSendActivated()) {
senderTransferMapping = new char*[elementCount];
setupMappingBuffer(senderTransferMapping, senderPartList, senderTree, senderDataConfig);
}
if (isReceiveActivated()) {
receiverTransferMapping = new char*[elementCount];
setupMappingBuffer(receiverTransferMapping, receiverPartList, receiverTree, receiverDataConfig);
}
}
PreprocessedCommBuffer::~PreprocessedCommBuffer() {
if (senderTransferMapping != NULL) delete[] senderTransferMapping;
if (receiverTransferMapping != NULL) delete[] receiverTransferMapping;
}
void PreprocessedCommBuffer::setupMappingBuffer(char **buffer,
DataPartsList *dataPartList,
PartIdContainer *partContainerTree,
DataItemConfig *dataConfig) {
DataPartSpec *dataPartSpec = new DataPartSpec(dataPartList->getPartList(), dataConfig);
vector<XformedIndexInfo*> *transformVector = new vector<XformedIndexInfo*>;
transformVector->reserve(dataDimensions);
for (int i = 0; i < dataDimensions; i++) {
transformVector->push_back(new XformedIndexInfo());
}
ExchangeIterator *iterator = getIterator();
long int elementIndex = 0;
TransferLocationSpec *transferSpec = new TransferLocationSpec(elementSize);
while (iterator->hasMoreElements()) {
vector<int> *dataItemIndex = iterator->getNextElement();
dataPartSpec->initPartTraversalReference(dataItemIndex, transformVector);
transferSpec->setBufferLocation(&buffer[elementIndex]);
partContainerTree->transferData(transformVector,
transferSpec, dataPartSpec, false, std::cout);
elementIndex++;
}
delete dataPartSpec;
delete transformVector;
delete transferSpec;
}
//----------------------------------------------- Index-Mapped Communication Buffer ----------------------------------------------/
IndexMappedCommBuffer::IndexMappedCommBuffer(DataExchange *ex, SyncConfig *sC) : CommBuffer(ex, sC) {
senderTransferIndexMapping = NULL;
receiverTransferIndexMapping = NULL;
// If the sender and receiver sides are using the same data parts then their confinement container IDs
// should be used to restrict read/writes to/from specific data parts
bool isIntraSegmentBuffer = ex->isIntraSegmentExchange(localSegmentTag);
bool areBothPartiesShareSameDataParts = sC->getConfinementConfig()->isIntraContrainerSync();
bool usePartsConfinment = isIntraSegmentBuffer && areBothPartiesShareSameDataParts;
if (isSendActivated()) {
TransferIndexSpec *transferSpec = new TransferIndexSpec(elementSize);
if (usePartsConfinment) {
transferSpec->setConfinementContainerId(dataExchange->getReadConfinementId());
}
senderTransferIndexMapping = new DataPartIndexList[elementCount];
setupMappingBuffer(senderTransferIndexMapping,
senderPartList, senderTree, senderDataConfig, transferSpec);
delete transferSpec;
}
if (isReceiveActivated()) {
TransferIndexSpec *transferSpec = new TransferIndexSpec(elementSize);
if (usePartsConfinment) {
transferSpec->setConfinementContainerId(dataExchange->getWriteConfinementId());
}
receiverTransferIndexMapping = new DataPartIndexList[elementCount];
setupMappingBuffer(receiverTransferIndexMapping,
receiverPartList, receiverTree, receiverDataConfig, transferSpec);
delete transferSpec;
}
}
IndexMappedCommBuffer::~IndexMappedCommBuffer() {
if (senderTransferIndexMapping != NULL) {
delete[] senderTransferIndexMapping;
}
if (receiverTransferIndexMapping != NULL) {
delete[] receiverTransferIndexMapping;
}
}
void IndexMappedCommBuffer::setupMappingBuffer(DataPartIndexList *indexMappingBuffer,
DataPartsList *dataPartList,
PartIdContainer *partContainerTree,
DataItemConfig *dataConfig,
TransferIndexSpec *transferSpec) {
DataPartSpec *dataPartSpec = new DataPartSpec(dataPartList->getPartList(), dataConfig);
vector<XformedIndexInfo*> *transformVector = new vector<XformedIndexInfo*>;
transformVector->reserve(dataDimensions);
for (int i = 0; i < dataDimensions; i++) {
transformVector->push_back(new XformedIndexInfo());
}
ExchangeIterator *iterator = getIterator();
long int elementIndex = 0;
while (iterator->hasMoreElements()) {
vector<int> *dataItemIndex = iterator->getNextElement();
dataPartSpec->initPartTraversalReference(dataItemIndex, transformVector);
transferSpec->setPartIndexListReference(&indexMappingBuffer[elementIndex]);
partContainerTree->transferData(transformVector,
transferSpec, dataPartSpec, false, std::cout);
elementIndex++;
}
delete dataPartSpec;
delete transformVector;
}
//------------------------------------------------ Physical Communication Buffer -------------------------------------------------/
PhysicalCommBuffer::PhysicalCommBuffer(DataExchange *e, SyncConfig *s) : CommBuffer(e, s) {
long int bufferSize = elementCount * elementSize;
data = new char[bufferSize];
for (long int i = 0; i < bufferSize; i++) {
data[i] = 0;
}
}
void PhysicalCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
if (isSendActivated()) {
if (loggingEnabled) {
logFile << "start reading data for communication buffer: " << bufferTag << "\n";
}
DataPartSpec *partSpec = new DataPartSpec(senderPartList->getPartList(), senderDataConfig);
TransferSpec *readSpec = new TransferSpec(DATA_PART_TO_COMM_BUFFER, elementSize);
transferData(readSpec, partSpec, senderTree, loggingEnabled, logFile);
delete partSpec;
delete readSpec;
if (loggingEnabled) {
logFile << "reading done for communication buffer: " << bufferTag << "\n";
}
}
}
void PhysicalCommBuffer::writeData(bool loggingEnabled, std::ostream &logFile) {
if (isReceiveActivated()) {
if (loggingEnabled) {
logFile << "start writing data from communication buffer: " << bufferTag << "\n";
}
DataPartSpec *partSpec = new DataPartSpec(receiverPartList->getPartList(), receiverDataConfig);
TransferSpec *writeSpec = new TransferSpec(COMM_BUFFER_TO_DATA_PART, elementSize);
transferData(writeSpec, partSpec, receiverTree, loggingEnabled, logFile);
delete partSpec;
delete writeSpec;
if (loggingEnabled) {
logFile << "writing done for communication buffer: " << bufferTag << "\n";
}
}
}
void PhysicalCommBuffer::transferData(TransferSpec *transferSpec,
DataPartSpec *dataPartSpec,
PartIdContainer *partTree,
bool loggingEnabled, std::ostream &logFile) {
vector<XformedIndexInfo*> *transformVector = new vector<XformedIndexInfo*>;
transformVector->reserve(dataDimensions);
for (int i = 0; i < dataDimensions; i++) {
transformVector->push_back(new XformedIndexInfo());
}
ExchangeIterator *iterator = getIterator();
long int elementIndex = 0;
long int transferRequests = 0;
long int transferCount = 0;
while (iterator->hasMoreElements()) {
vector<int> *dataItemIndex = iterator->getNextElement();
if (loggingEnabled) {
logFile << "\t\tTransfer Request for: (";
for (int i = 0; i < dataItemIndex->size(); i++) {
if (i > 0) logFile << ',';
logFile << dataItemIndex->at(i);
}
logFile << ")\n";
}
dataPartSpec->initPartTraversalReference(dataItemIndex, transformVector);
char *dataLocation = data + elementIndex * elementSize;
transferSpec->setBufferEntry(dataLocation, dataItemIndex);
int elementTransfers = partTree->transferData(transformVector,
transferSpec,
dataPartSpec, loggingEnabled, logFile, 3);
if (loggingEnabled) {
logFile << "\t\tData Transfers for Request: ";
logFile << elementTransfers << "\n";
}
elementIndex++;
transferRequests++;
transferCount += elementTransfers;
}
delete transformVector;
if (loggingEnabled) {
logFile << "\tTotal transfer requests: " << transferRequests << "\n";
logFile << "\tTotal data transfers for those requests: " << transferCount << "\n";
}
}
//------------------------------------------ Pre-processed Physical Communication Buffer -----------------------------------------/
PreprocessedPhysicalCommBuffer::PreprocessedPhysicalCommBuffer(DataExchange *exchange,
SyncConfig *syncConfig) : PreprocessedCommBuffer(exchange, syncConfig) {
long int bufferSize = elementCount * elementSize;
data = new char[bufferSize];
for (long int i = 0; i < bufferSize; i++) {
data[i] = 0;
}
}
void PreprocessedPhysicalCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
for (long int i = 0; i < elementCount; i++) {
char *readLocation = senderTransferMapping[i];
char *writeLocation = data + i * elementSize;
memcpy(writeLocation, readLocation, elementSize);
}
}
void PreprocessedPhysicalCommBuffer::writeData(bool loggingEnabled, std::ostream &logFile) {
for (long int i = 0; i < elementCount; i++) {
char *readLocation = data + i * elementSize;
char *writeLocation = receiverTransferMapping[i];
memcpy(writeLocation, readLocation, elementSize);
}
}
//------------------------------------------- Index-mapped Physical Communication Buffer -----------------------------------------/
IndexMappedPhysicalCommBuffer::IndexMappedPhysicalCommBuffer(DataExchange *exchange,
SyncConfig *syncConfig) : IndexMappedCommBuffer(exchange, syncConfig) {
long int bufferSize = elementCount * elementSize;
data = new char[bufferSize];
for (long int i = 0; i < bufferSize; i++) {
data[i] = 0;
}
}
void IndexMappedPhysicalCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
for (long int i = 0; i < elementCount; i++) {
// Notice that data is read from only the first matched location in the operating memory data part
// storage. This is because, all locations matching a single entry in the communication buffer
// should have identical content.
List<DataPartIndex> *partIndexList = senderTransferIndexMapping[i].getPartIndexList();
char *readLocation = partIndexList->Nth(0).getLocation();
char *writeLocation = data + i * elementSize;
memcpy(writeLocation, readLocation, elementSize);
}
}
void IndexMappedPhysicalCommBuffer::writeData(bool loggingEnabled, std::ostream &logFile) {
for (long int i = 0; i < elementCount; i++) {
char *readLocation = data + i * elementSize;
List<DataPartIndex> *partIndexList = receiverTransferIndexMapping[i].getPartIndexList();
// Unlike in the case for readData, writing should access every single matched location in the data
// parts as we need to ensure that all locations matching a single entry in the communication buffer
// are synchronized with the same update.
for (int j = 0; j < partIndexList->NumElements(); j++) {
char *writeLocation = partIndexList->Nth(j).getLocation();
memcpy(writeLocation, readLocation, elementSize);
}
}
}
//---------------------------------------- Swift-Index-mapped Physical Communication Buffer --------------------------------------/
SwiftIndexMappedPhysicalCommBuffer::SwiftIndexMappedPhysicalCommBuffer(
DataExchange *exchange, SyncConfig *syncConfig)
: IndexMappedPhysicalCommBuffer(exchange, syncConfig) {
senderSwiftIndexMapping = new List<DataPartIndexList*>;
receiverSwiftIndexMapping = new List<DataPartIndexList*>;
if (isSendActivated()) {
setupSwiftIndexMapping(senderTransferIndexMapping, senderSwiftIndexMapping, false);
}
if (isReceiveActivated()) {
setupSwiftIndexMapping(receiverTransferIndexMapping, receiverSwiftIndexMapping, true);
}
}
SwiftIndexMappedPhysicalCommBuffer::~SwiftIndexMappedPhysicalCommBuffer() {
while (senderSwiftIndexMapping->NumElements() > 0) {
DataPartIndexList *entry = senderSwiftIndexMapping->Nth(0);
senderSwiftIndexMapping->RemoveAt(0);
delete entry;
}
delete senderSwiftIndexMapping;
while (receiverSwiftIndexMapping->NumElements() > 0) {
DataPartIndexList *entry = receiverSwiftIndexMapping->Nth(0);
receiverSwiftIndexMapping->RemoveAt(0);
delete entry;
}
delete receiverSwiftIndexMapping;
}
void SwiftIndexMappedPhysicalCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
int index = 0;
for (int i = 0; i < senderSwiftIndexMapping->NumElements(); i++) {
DataPartIndexList *partIndexList = senderSwiftIndexMapping->Nth(i);
char *bufferIndex = data + index * elementSize;
index += partIndexList->read(bufferIndex, elementSize);
}
}
void SwiftIndexMappedPhysicalCommBuffer::writeData(bool loggingEnabled, std::ostream &logFile) {
int index = 0;
for (int i = 0; i < receiverSwiftIndexMapping->NumElements(); i++) {
DataPartIndexList *partIndexList = receiverSwiftIndexMapping->Nth(i);
char *bufferIndex = data + index * elementSize;
index += partIndexList->write(bufferIndex, elementSize);
}
}
void SwiftIndexMappedPhysicalCommBuffer::setupSwiftIndexMapping(DataPartIndexList *transferIndexMapping,
List<DataPartIndexList*> *swiftIndexMapping,
bool allowMultPartIndexesForSameBufferIndex) {
DataPartSwiftIndexList *currSwiftIndex = NULL;
DataPartIndexList *currEntry = new DataPartIndexList();
for (long int i = 0; i < elementCount; i++) {
currEntry->clone(&transferIndexMapping[i]);
List<DataPartIndex> *indexList = currEntry->getPartIndexList();
if (!allowMultPartIndexesForSameBufferIndex || indexList->NumElements() == 1) {
DataPartIndex partIndex = indexList->Nth(0);
if (currSwiftIndex == NULL) {
currSwiftIndex = new DataPartSwiftIndexList(partIndex.getDataPart());
currSwiftIndex->addIndex(partIndex.getIndex());
} else {
if (currSwiftIndex->getDataPart() == partIndex.getDataPart()) {
currSwiftIndex->addIndex(partIndex.getIndex());
} else {
currSwiftIndex->setupIndexArray();
swiftIndexMapping->Append(currSwiftIndex);
currSwiftIndex = new DataPartSwiftIndexList(partIndex.getDataPart());
currSwiftIndex->addIndex(partIndex.getIndex());
}
}
} else {
if (currSwiftIndex != NULL) {
currSwiftIndex->setupIndexArray();
swiftIndexMapping->Append(currSwiftIndex);
DataPartIndexList *cloneEntry = new DataPartIndexList();
cloneEntry->clone(currEntry);
swiftIndexMapping->Append(cloneEntry);
currSwiftIndex = NULL;
} else {
DataPartIndexList *cloneEntry = new DataPartIndexList();
cloneEntry->clone(currEntry);
swiftIndexMapping->Append(cloneEntry);
}
}
}
if (currSwiftIndex != NULL) {
currSwiftIndex->setupIndexArray();
swiftIndexMapping->Append(currSwiftIndex);
}
}
//------------------------------------------------- Virtual Communication Buffer -------------------------------------------------/
void VirtualCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
if (isReceiveActivated()) {
if (loggingEnabled) {
logFile << "start transferring data for communication buffer ";
logFile << bufferTag << "\n";
}
DataPartSpec *readPartSpec = new DataPartSpec(senderPartList->getPartList(), senderDataConfig);
TransferSpec *readTransferSpec = new TransferSpec(DATA_PART_TO_COMM_BUFFER, elementSize);
DataPartSpec *writePartSpec = new DataPartSpec(receiverPartList->getPartList(), receiverDataConfig);
TransferSpec *writeTransferSpec = new TransferSpec(COMM_BUFFER_TO_DATA_PART, elementSize);
Assert(senderDataConfig != receiverDataConfig);
char *dataEntry = new char[elementSize];
vector<XformedIndexInfo*> *transformVector = new vector<XformedIndexInfo*>;
transformVector->reserve(dataDimensions);
for (int i = 0; i < dataDimensions; i++) {
transformVector->push_back(new XformedIndexInfo());
}
long int transferRequests = 0;
long int readCount = 0;
long int writeCount = 0;
ExchangeIterator *iterator = getIterator();
while (iterator->hasMoreElements()) {
// get the next data item index from the iterator
vector<int> *dataItemIndex = iterator->getNextElement();
if (loggingEnabled) {
logFile << "\t\tTransfer Request for: (";
for (int i = 0; i < dataItemIndex->size(); i++) {
if (i > 0) logFile << ',';
logFile << dataItemIndex->at(i);
}
logFile << ")\n";
}
// traverse the sender tree and copy data from appropriate location in the the data-entry
readTransferSpec->setBufferEntry(dataEntry, dataItemIndex);
readPartSpec->initPartTraversalReference(dataItemIndex, transformVector);
int elementsRead = senderTree->transferData(transformVector,
readTransferSpec,
readPartSpec, loggingEnabled, logFile, 3);
if (loggingEnabled) {
logFile << "\t\tElements Read: " << elementsRead << "\n";
}
readCount += elementsRead;
// then write the data-entry in the appropriate location on the other side the same way
writeTransferSpec->setBufferEntry(dataEntry, dataItemIndex);
writePartSpec->initPartTraversalReference(dataItemIndex, transformVector);
int elementsWritten = receiverTree->transferData(transformVector,
writeTransferSpec,
writePartSpec, loggingEnabled, logFile, 3);
if (loggingEnabled) {
logFile << "\t\tElements written: " << elementsWritten << "\n";
}
writeCount += elementsWritten;
transferRequests++;
}
if (loggingEnabled) {
logFile << "\tTotal data transfer requests: " << transferRequests << "\n";
logFile << "\tData reads: " << readCount << "\n";
logFile << "\tData writes: " << writeCount << "\n";
logFile << "data transferring done for communication buffer " << bufferTag << "\n";
}
delete readPartSpec;
delete readTransferSpec;
delete writePartSpec;
delete writeTransferSpec;
delete transformVector;
delete dataEntry;
}
}
//------------------------------------------- Pre-processed Virtual Communication Buffer -----------------------------------------/
void PreprocessedVirtualCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
for (long int i = 0; i < elementCount; i++) {
char *readLocation = senderTransferMapping[i];
char *writeLocation = receiverTransferMapping[i];
memcpy(writeLocation, readLocation, elementSize);
}
}
//-------------------------------------------- Index-mapped Virtual Communication Buffer -----------------------------------------/
void IndexMappedVirtualCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
for (long int i = 0; i < elementCount; i++) {
// data is read from only one location as all matching locations should have the same content
List<DataPartIndex> *sourcePartIndexList = senderTransferIndexMapping[i].getPartIndexList();
char *readLocation = sourcePartIndexList->Nth(0).getLocation();
// update is propagated to all matching locations as they need have equivalent in data content
List<DataPartIndex> *destPartIndexList = receiverTransferIndexMapping[i].getPartIndexList();
for (int j = 0; j < destPartIndexList->NumElements(); j++) {
char *writeLocation = destPartIndexList->Nth(j).getLocation();
memcpy(writeLocation, readLocation, elementSize);
}
}
}
//----------------------------------------- Swift-Index-mapped Virtual Communication Buffer --------------------------------------/
SwiftIndexMappedVirtualCommBuffer::SwiftIndexMappedVirtualCommBuffer(
DataExchange *exchange, SyncConfig *syncConfig)
: IndexMappedVirtualCommBuffer(exchange, syncConfig) {
long int bufferSize = elementCount * elementSize;
data = new char[bufferSize];
for (long int i = 0; i < bufferSize; i++) {
data[i] = 0;
}
generateSwiftIndexMappings();
}
SwiftIndexMappedVirtualCommBuffer::~SwiftIndexMappedVirtualCommBuffer() {
delete[] data;
while (senderSwiftIndexMapping->NumElements() > 0) {
DataPartIndexList *entry = senderSwiftIndexMapping->Nth(0);
senderSwiftIndexMapping->RemoveAt(0);
delete entry;
}
delete senderSwiftIndexMapping;
while (receiverSwiftIndexMapping->NumElements() > 0) {
DataPartIndexList *entry = receiverSwiftIndexMapping->Nth(0);
receiverSwiftIndexMapping->RemoveAt(0);
delete entry;
}
delete receiverSwiftIndexMapping;
}
void SwiftIndexMappedVirtualCommBuffer::readData(bool loggingEnabled, std::ostream &logFile) {
long int index = 0;
for (int i = 0; i < senderSwiftIndexMapping->NumElements(); i++) {
DataPartIndexList *partIndexList = senderSwiftIndexMapping->Nth(i);
char *bufferIndex = data + index * elementSize;
index += partIndexList->read(bufferIndex, elementSize);
}
index = 0;
for (int i = 0; i < receiverSwiftIndexMapping->NumElements(); i++) {
DataPartIndexList *partIndexList = receiverSwiftIndexMapping->Nth(i);
char *bufferIndex = data + index * elementSize;
index += partIndexList->write(bufferIndex, elementSize);
}
}
void SwiftIndexMappedVirtualCommBuffer::generateSwiftIndexMappings() {
// prepare the sender-side swift index mapping
senderSwiftIndexMapping = new List<DataPartIndexList*>;
DataPartSwiftIndexList *currSwiftIndex = NULL;
DataPartIndexList *currSendEntry = new DataPartIndexList();
for (long int i = 0; i < elementCount; i++) {
currSendEntry->clone(&senderTransferIndexMapping[i]);
List<DataPartIndex> *indexList = currSendEntry->getPartIndexList();
DataPartIndex partIndex = indexList->Nth(0);
if (currSwiftIndex == NULL) {
currSwiftIndex = new DataPartSwiftIndexList(partIndex.getDataPart());
currSwiftIndex->addIndex(partIndex.getIndex());
} else {
if (currSwiftIndex->getDataPart() == partIndex.getDataPart()) {
currSwiftIndex->addIndex(partIndex.getIndex());
} else {
currSwiftIndex->setupIndexArray();
senderSwiftIndexMapping->Append(currSwiftIndex);
currSwiftIndex = new DataPartSwiftIndexList(partIndex.getDataPart());
currSwiftIndex->addIndex(partIndex.getIndex());
}
}
}
if (currSwiftIndex != NULL) {
currSwiftIndex->setupIndexArray();
senderSwiftIndexMapping->Append(currSwiftIndex);
}
// prepare the receiver-side swift index mapping
receiverSwiftIndexMapping = new List<DataPartIndexList*>;
currSwiftIndex = NULL;
DataPartIndexList *currRecvEntry = new DataPartIndexList();
List<DataPartIndex> *refIndexList = new List<DataPartIndex>;
for (long int i = 0; i < elementCount; i++) {
currRecvEntry->clone(&receiverTransferIndexMapping[i]);
List<DataPartIndex> *recvIndexList = currRecvEntry->getPartIndexList();
// If there is only one receive index for this communication buffer entry then augment existing or start
// a new swift index mapping.
if (recvIndexList->NumElements() == 1) {
DataPartIndex partIndex = recvIndexList->Nth(0);
DataPart *dataPart = partIndex.getDataPart();
long int index = partIndex.getIndex();
if (currSwiftIndex == NULL) {
currSwiftIndex = new DataPartSwiftIndexList(dataPart);
currSwiftIndex->addIndex(index);
} else {
if (currSwiftIndex->getDataPart() == dataPart) {
currSwiftIndex->addIndex(index);
} else {
currSwiftIndex->setupIndexArray();
receiverSwiftIndexMapping->Append(currSwiftIndex);
currSwiftIndex = new DataPartSwiftIndexList(dataPart);
currSwiftIndex->addIndex(index);
}
}
// If there are more than one receive indices then first we try to avoid sender index being unwittingly
// repeated in the receiver side. After eliminating such redundancy, we may be able to create a new swift
// mapping. Otherwise, just store the original transfer mapping
} else {
// filering receive part indexes
currSendEntry->clone(&senderTransferIndexMapping[i]);
DataPartIndex sendPartIndex = currSendEntry->getPartIndexList()->Nth(0);
refIndexList->clear();
for (int j = 0; j < recvIndexList->NumElements(); j++) {
DataPartIndex recvPartIndex = recvIndexList->Nth(j);
if (sendPartIndex.getDataPart() != recvPartIndex.getDataPart()) {
refIndexList->Append(recvPartIndex);
}
}
// attempt to augment existing or start a new swift index mapping
if (refIndexList->NumElements() == 1) {
DataPartIndex partIndex = refIndexList->Nth(0);
DataPart *dataPart = partIndex.getDataPart();
long int index = partIndex.getIndex();
if (currSwiftIndex == NULL) {
currSwiftIndex = new DataPartSwiftIndexList(dataPart);
currSwiftIndex->addIndex(index);
} else {
if (currSwiftIndex->getDataPart() == dataPart) {
currSwiftIndex->addIndex(index);
} else {
currSwiftIndex->setupIndexArray();
receiverSwiftIndexMapping->Append(currSwiftIndex);
currSwiftIndex = new DataPartSwiftIndexList(dataPart);
currSwiftIndex->addIndex(index);
}
}
// if failed then store the normal index mapping
} else {
if (currSwiftIndex != NULL) {
currSwiftIndex->setupIndexArray();
receiverSwiftIndexMapping->Append(currSwiftIndex);
DataPartIndexList *cloneEntry = new DataPartIndexList();
cloneEntry->clonePartIndexList(refIndexList);
receiverSwiftIndexMapping->Append(cloneEntry);
currSwiftIndex = NULL;
} else {
DataPartIndexList *cloneEntry = new DataPartIndexList();
cloneEntry->clonePartIndexList(refIndexList);
receiverSwiftIndexMapping->Append(cloneEntry);
}
}
}
}
if (currSwiftIndex != NULL) {
currSwiftIndex->setupIndexArray();
receiverSwiftIndexMapping->Append(currSwiftIndex);
}
}
//-------------------------------------------------- Communication Buffer Manager ------------------------------------------------/
CommBufferManager::CommBufferManager(const char *dependencyName) {
this->dependencyName = dependencyName;
commBufferList = new List<CommBuffer*>;
}
CommBufferManager::~CommBufferManager() {
while (commBufferList->NumElements() > 0) {
CommBuffer *buffer = commBufferList->Nth(0);
commBufferList->RemoveAt(0);
delete buffer;
}
delete commBufferList;
}
List<CommBuffer*> *CommBufferManager::getSortedList(bool sortForReceive, List<CommBuffer*> *bufferList) {
List<CommBuffer*> *originalList = commBufferList;
if (bufferList != NULL) {
originalList = bufferList;
}
List<CommBuffer*> *sortedList = new List<CommBuffer*>;
for (int i = 0; i < originalList->NumElements(); i++) {
CommBuffer *buffer = originalList->Nth(i);
if (sortForReceive && !buffer->isReceiveActivated()) continue;
else if (!sortForReceive && !buffer->isSendActivated()) continue;
// local, intra-segment data movement should preceed any inter-segment communication
if (buffer->intraSegmentBufferType()) {
sortedList->InsertAt(buffer, 0);
} else {
int j = 0;
for (; j < sortedList->NumElements(); j++) {
if (sortedList->Nth(j)->compareTo(buffer, sortForReceive) > 0) break;
}
sortedList->InsertAt(buffer, j);
}
}
return sortedList;
}
List<CommBuffer*> *CommBufferManager::getFilteredList(bool filterForReceive, List<CommBuffer*> *bufferList) {
List<CommBuffer*> *originalList = commBufferList;
if (bufferList != NULL) {
originalList = bufferList;
}
List<CommBuffer*> *filteredList = new List<CommBuffer*>;
for (int i = 0; i < originalList->NumElements(); i++) {
CommBuffer *buffer = originalList->Nth(i);
if (filterForReceive && !buffer->isReceiveActivated()) continue;
else if (!filterForReceive && !buffer->isSendActivated()) continue;
filteredList->Append(buffer);
}
return filteredList;
}
void CommBufferManager::seperateLocalAndRemoteBuffers(int localSegmentTag,
List<CommBuffer*> *localBufferList,
List<CommBuffer*> *remoteBufferList) {
for (int i = 0; i < commBufferList->NumElements(); i++) {
CommBuffer *buffer = commBufferList->Nth(i);
DataExchange *exchange = buffer->getExchange();
if (exchange->isIntraSegmentExchange(localSegmentTag)) {
localBufferList->Append(buffer);
} else remoteBufferList->Append(buffer);
}
}
std::vector<int> *CommBufferManager::getParticipantsTags() {
std::vector<int> *participantTags = new std::vector<int>;
for (int i = 0; i < commBufferList->NumElements(); i++) {
CommBuffer *buffer = commBufferList->Nth(i);
DataExchange *exchange = buffer->getExchange();
std::vector<int> senderTags = exchange->getSender()->getSegmentTags();
binsearch::addThoseNotExist(participantTags, &senderTags);
std::vector<int> receiverTags = exchange->getReceiver()->getSegmentTags();
binsearch::addThoseNotExist(participantTags, &receiverTags);
}
return participantTags;
}
| [
"mny9md@virginia.edu"
] | mny9md@virginia.edu |
7dc349b7654227f79f7f326d501a188e3d622cbf | 7be1d3b42af0f28563339d537f9a966d7be13c1f | /src/core/controller/basic_controller.hpp | 5c8184a3f0a1bf6f85a7465ddd3dd11e1a6c3451 | [] | no_license | chakannom/stock-agent | 3144572e6187584a773eb5b93a9632f7a9234023 | 55bd00fccc31c6de2148bccabd08738aca82faaf | refs/heads/master | 2022-12-31T07:12:30.939513 | 2020-10-26T06:36:44 | 2020-10-26T06:36:44 | 280,083,448 | 0 | 0 | null | 2020-10-26T06:36:45 | 2020-07-16T07:21:20 | null | UTF-8 | C++ | false | false | 2,216 | hpp | //
// Created by Ivan Mejia on 12/03/16.
//
// MIT License
//
// Copyright (c) 2016 ivmeroLabs. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#pragma once
#include <string>
#include <cpprest/http_listener.h>
#include <pplx/pplxtasks.h>
#include "controller.hpp"
using namespace web;
using namespace http::experimental::listener;
namespace cfx {
class BasicController {
protected:
http_listener _listener; // main micro service network endpoint
public:
BasicController() {};
~BasicController() {};
void setEndpoint(const std::wstring& value);
utility::string_t endpoint() const;
pplx::task<void> accept();
pplx::task<void> shutdown();
virtual void initRestOpHandlers() {
/* had to be implemented by the child class */
}
utility::string_t requestPath(const http_request& request);
std::vector<utility::string_t> splittedRequestPath(const http_request& request);
utility::string_t requestQuery(const http_request& request);
std::map<utility::string_t, utility::string_t> splittedRequestQuery(const http_request& request);
};
} | [
"genteelson@gmail.com"
] | genteelson@gmail.com |
ac135564c54d44b0c6cd21b62c36e986900996a6 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/webrtc/audio/audio_level.h | 3bbe5fdd20185c9ae1af3e0dd35593766390a34c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-takuya-ooura",
"LicenseRef-scancode-public-domai... | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 1,747 | h | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef AUDIO_AUDIO_LEVEL_H_
#define AUDIO_AUDIO_LEVEL_H_
#include "rtc_base/criticalsection.h"
#include "rtc_base/thread_annotations.h"
namespace webrtc {
class AudioFrame;
namespace voe {
class AudioLevel {
public:
AudioLevel();
~AudioLevel();
// Called on "API thread(s)" from APIs like VoEBase::CreateChannel(),
// VoEBase::StopSend()
int16_t LevelFullRange() const;
void Clear();
// See the description for "totalAudioEnergy" in the WebRTC stats spec
// (https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy)
double TotalEnergy() const;
double TotalDuration() const;
// Called on a native capture audio thread (platform dependent) from the
// AudioTransport::RecordedDataIsAvailable() callback.
// In Chrome, this method is called on the AudioInputDevice thread.
void ComputeLevel(const AudioFrame& audioFrame, double duration);
private:
enum { kUpdateFrequency = 10 };
rtc::CriticalSection crit_sect_;
int16_t abs_max_ RTC_GUARDED_BY(crit_sect_);
int16_t count_ RTC_GUARDED_BY(crit_sect_);
int16_t current_level_full_range_ RTC_GUARDED_BY(crit_sect_);
double total_energy_ RTC_GUARDED_BY(crit_sect_) = 0.0;
double total_duration_ RTC_GUARDED_BY(crit_sect_) = 0.0;
};
} // namespace voe
} // namespace webrtc
#endif // AUDIO_AUDIO_LEVEL_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
dedc437e0053fcae0a317410190a6343c1ca6770 | 795b70ae2bc906a4afa14f2ebc9b3b6529a97fdb | /p2-source/main_window.hpp | a511e6ff223767589302b27dc89b6b69906297ee | [] | no_license | yunfei96/ece3574 | cd33006dfa7450170e18d50580b8da8a53678593 | c2179c64745636fd6c937345eb87f133fd9db859 | refs/heads/master | 2020-12-30T12:11:19.700204 | 2017-05-16T03:20:52 | 2017-05-16T03:20:52 | 91,408,981 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 503 | hpp | #ifndef MAIN
#define MAIN
#include <QWidget>
#include "message_widget.hpp"
#include "repl_widget.hpp"
#include "canvas_widget.hpp"
#include "qt_interpreter.hpp"
class msg;
class repl;
class canvas;
class MainWindow: public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget * parent = nullptr);
MainWindow(std::string filename, QWidget * parent = nullptr);
private:
QString text;
MessageWidget * info;
REPLWidget * input;
CanvasWidget * display;
QtInterpreter * interp;
};
#endif
| [
"yunfei96@vt.edu"
] | yunfei96@vt.edu |
f0c106f9c7f669e56249268872bd755f53f14557 | 5470644b5f0834b9646649da365c96101a2f9b2a | /Sources/Elastos/Frameworks/Droid/Base/Core/src/media/media/CAudioSystemHelper.cpp | 88f3c437a7a3be17cb5a7420f643b15b6b8f867c | [] | no_license | dothithuy/ElastosRDK5_0 | 42372da3c749170581b5ee9b3884f4a27ae81608 | 2cf231e9f09f8b3b8bcacb11080b4a87d047833f | refs/heads/master | 2021-05-13T15:02:22.363934 | 2015-05-25T01:54:38 | 2015-05-25T01:54:38 | 116,755,452 | 1 | 0 | null | 2018-01-09T02:33:06 | 2018-01-09T02:33:06 | null | UTF-8 | C++ | false | false | 4,104 | cpp |
#include "media/CAudioSystemHelper.h"
#include "media/CAudioSystem.h"
namespace Elastos {
namespace Droid {
namespace Media {
ECode CAudioSystemHelper::GetNumStreamTypes(
/* [out] */ Int32* result)
{
return CAudioSystem::GetNumStreamTypes(result);
}
ECode CAudioSystemHelper::MuteMicrophone(
/* [in] */ Boolean on)
{
return CAudioSystem::MuteMicrophone(on);
}
ECode CAudioSystemHelper::IsMicrophoneMuted(
/* [out] */ Boolean* result)
{
return CAudioSystem::IsMicrophoneMuted(result);
}
ECode CAudioSystemHelper::IsStreamActive(
/* [in] */ Int32 stream,
/* [in] */ Int32 inPastMs,
/* [out] */ Boolean* result)
{
return CAudioSystem::IsStreamActive(stream, inPastMs, result);
}
ECode CAudioSystemHelper::IsSourceActive(
/* [in] */ Int32 source,
/* [out] */ Boolean* result)
{
return CAudioSystem::IsSourceActive(source, result);
}
ECode CAudioSystemHelper::SetParameters(
/* [in] */ const String& keyValuePairs)
{
return CAudioSystem::SetParameters(keyValuePairs);
}
ECode CAudioSystemHelper::GetParameters(
/* [in] */ const String& keys,
/* [out] */ String* result)
{
return CAudioSystem::GetParameters(keys, result);
}
ECode CAudioSystemHelper::SetErrorCallback(
/* [in] */ IAudioSystemErrorCallback* cb)
{
return CAudioSystem::SetErrorCallback(cb);
}
ECode CAudioSystemHelper::GetDeviceName(
/* [in] */ Int32 device,
/* [out] */ String* result)
{
return CAudioSystem::GetDeviceName(device, result);
}
ECode CAudioSystemHelper::SetDeviceConnectionState(
/* [in] */ Int32 device,
/* [in] */ Int32 state,
/* [in] */ const String& device_address)
{
return CAudioSystem::SetDeviceConnectionState(device, state, device_address);
}
ECode CAudioSystemHelper::GetDeviceConnectionState(
/* [in] */ Int32 device,
/* [in] */ const String& device_address,
/* [out] */ Int32* result)
{
return CAudioSystem::GetDeviceConnectionState(device, device_address, result);
}
ECode CAudioSystemHelper::SetPhoneState(
/* [in] */ Int32 state)
{
return CAudioSystem::SetPhoneState(state);
}
ECode CAudioSystemHelper::SetForceUse(
/* [in] */ Int32 usage,
/* [in] */ Int32 config)
{
return CAudioSystem::SetForceUse(usage, config);
}
ECode CAudioSystemHelper::GetForceUse(
/* [in] */ Int32 usage,
/* [out] */ Int32* result)
{
return CAudioSystem::GetForceUse(usage, result);
}
ECode CAudioSystemHelper::InitStreamVolume(
/* [in] */ Int32 stream,
/* [in] */ Int32 indexMin,
/* [in] */ Int32 indexMax)
{
return CAudioSystem::InitStreamVolume(stream, indexMin, indexMax);
}
ECode CAudioSystemHelper::SetStreamVolumeIndex(
/* [in] */ Int32 stream,
/* [in] */ Int32 index,
/* [in] */ Int32 device)
{
return CAudioSystem::SetStreamVolumeIndex(stream, index, device);
}
ECode CAudioSystemHelper::GetStreamVolumeIndex(
/* [in] */ Int32 stream,
/* [in] */ Int32 device,
/* [out] */ Int32* result)
{
return CAudioSystem::GetStreamVolumeIndex(stream, device, result);
}
ECode CAudioSystemHelper::SetMasterVolume(
/* [in] */ Float value)
{
return CAudioSystem::SetMasterVolume(value);
}
ECode CAudioSystemHelper::GetMasterVolume(
/* [out] */ Float* result)
{
return CAudioSystem::GetMasterVolume(result);
}
ECode CAudioSystemHelper::SetMasterMute(
/* [in] */ Boolean mute)
{
return CAudioSystem::SetMasterMute(mute);
}
ECode CAudioSystemHelper::GetMasterMute(
/* [out] */ Boolean* result)
{
return CAudioSystem::GetMasterMute(result);
}
ECode CAudioSystemHelper::GetDevicesForStream(
/* [in] */ Int32 stream,
/* [out] */ Int32* result)
{
return CAudioSystem::GetDevicesForStream(stream, result);
}
ECode CAudioSystemHelper::GetPrimaryOutputSamplingRate(
/* [out] */ Int32* result)
{
return CAudioSystem::GetPrimaryOutputSamplingRate(result);
}
ECode CAudioSystemHelper::GetPrimaryOutputFrameCount(
/* [out] */ Int32* result)
{
return CAudioSystem::GetPrimaryOutputFrameCount(result);
}
} // namespace Media
} // namespace Droid
} // namespace Elastos
| [
"chen.yunzhi@kortide.com"
] | chen.yunzhi@kortide.com |
9295092c87bbb799efa2854201a3fb6aaac398ff | 4b924c20f005de2fefceba567ac14002a32a12c3 | /es5.52/src/primitive_less_than.h | 0ad4deee02d08802dff8aedbf76418579efad208 | [] | no_license | jgarte/sicp-exercises | a72df5454cd989178ff246651474b38a9d79095a | 423ae2a1b462078f91e3530b3082f1c1402253a4 | refs/heads/master | 2021-10-26T15:05:56.573869 | 2019-04-13T10:20:30 | 2019-04-13T10:20:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | h | #ifndef PRIMITIVE_LESS_THAN_H
#define PRIMITIVE_LESS_THAN_H
#include "primitive_procedure.h"
class PrimitiveLessThan: public PrimitiveProcedure {
public:
virtual Value* apply(List* arguments);
virtual std::string to_string() const;
};
#endif
| [
"g.sironi@elifesciences.org"
] | g.sironi@elifesciences.org |
60c087eb8083fe263e4d88a894878eb935e3cdfa | be21053e9bc0e3e26833ad416793cdf9df97f21e | /src/OpenRTMPlugin/deprecated/BridgeConf.cpp | 1d27467734e23c5343f25174a5bec5d8df8374bd | [
"MIT",
"IJG",
"Zlib"
] | permissive | MiladShafiee/Surena4HumanoidSimulation-Choreonoid | 2353f715ac126aa4404b57cd0c8c0612539f7c1b | a3d8af2a6ae2e7720bab4a329809507632173177 | refs/heads/master | 2020-04-10T00:46:13.984347 | 2018-12-23T07:08:16 | 2018-12-23T07:08:16 | 160,695,810 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,854 | cpp | /**
\file
\author Shin'ichiro Nakaoka
*/
#include "BridgeConf.h"
#include "../OpenRTMUtil.h"
#include <boost/regex.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
using namespace std;
namespace program_options = boost::program_options;
namespace filesystem = boost::filesystem;
using boost::format;
BridgeConf::BridgeConf() :
options("Allowed options"),
commandLineOptions("Allowed options")
{
isReady_ = true;
}
BridgeConf::~BridgeConf()
{
}
bool BridgeConf::loadConfigFile(const char* confFileName)
{
isReady_ = false;
initOptionsDescription();
initLabelToDataTypeMap();
ifstream ifs(confFileName);
if (ifs.fail()) {
return false;
}
program_options::store(program_options::parse_config_file(ifs, options), vmap);
isProcessingConfigFile = true;
program_options::notify(vmap);
parseOptions();
isReady_ = true;
return true;
}
void BridgeConf::initOptionsDescription()
{
options.add_options()
("name-server",
program_options::value<string>()->default_value("127.0.0.1:2809"),
"Nameserver used by OpenHRP (hostname:port)")
("server-name",
program_options::value<string>()->default_value("ControllerBridge"),
"Name of the OpenHRP controller factory server")
("robot-name",
program_options::value<string>()->default_value(""),
"Name of the virtual robot RTC type")
("module",
program_options::value<vector<string> >(),
"Module filename")
("out-port",
program_options::value<vector<string> >(),
"Set an out-port that transfers data from the simulator to the controller")
("in-port",
program_options::value<vector<string> >(),
"Set an in-port transfers data from the controller to the simulator")
("connection",
program_options::value<vector<string> >(),
"Port connection setting")
("periodic-rate",
program_options::value<vector<string> >(),
"Periodic rate of execution context (INSTANCE_NAME:TIME_RATE[<=1.0])");
commandLineOptions.add(options).add_options()
("config-file",
program_options::value<string>(),
"configuration file of the controller bridge")
("help,h", "Show this help");
}
void BridgeConf::initLabelToDataTypeMap()
{
LabelToDataTypeIdMap& m = labelToDataTypeIdMap;
m["JOINT_VALUE"] = JOINT_VALUE;
m["JOINT_VELOCITY"] = JOINT_VELOCITY;
m["JOINT_ACCELERATION"] = JOINT_ACCELERATION;
m["JOINT_TORQUE"] = JOINT_TORQUE;
m["EXTERNAL_FORCE"] = EXTERNAL_FORCE;
m["ABS_TRANSFORM"] = ABS_TRANSFORM;
m["ABS_VELOCITY"] = ABS_VELOCITY;
m["ABS_ACCELERATION"] = ABS_ACCELERATION;
m["FORCE_SENSOR"] = FORCE_SENSOR;
m["RATE_GYRO_SENSOR"] = RATE_GYRO_SENSOR;
m["ACCELERATION_SENSOR"] = ACCELERATION_SENSOR;
m["RANGE_SENSOR"] = RANGE_SENSOR;
m["CONSTRAINT_FORCE"] = CONSTRAINT_FORCE;
m["RATE_GYRO_SENSOR2"] = RATE_GYRO_SENSOR2;
m["ACCELERATION_SENSOR2"] = ACCELERATION_SENSOR2;
m["ABS_TRANSFORM2"] = ABS_TRANSFORM2;
m["LIGHT"] = LIGHT;
m["CAMERA_IMAGE"] = CAMERA_IMAGE;
m["CAMERA_RANGE"] = CAMERA_RANGE;
}
void BridgeConf::parseCommandLineOptions(int argc, char* argv[])
{
isProcessingConfigFile = false;
program_options::parsed_options parsed =
program_options::command_line_parser(argc, argv).options(commandLineOptions).allow_unregistered().run();
program_options::store(parsed, vmap);
if(vmap.count("help")){
cout << commandLineOptions << endl;
} else {
if(vmap.count("config-file")){
string fileName(vmap["config-file"].as<string>());
ifstream ifs(fileName.c_str());
if (ifs.fail()) {
throw invalid_argument(string("cannot open the config file"));
}
program_options::store(program_options::parse_config_file(ifs, options), vmap);
isProcessingConfigFile = true;
}
program_options::notify(vmap);
parseOptions();
isReady_ = true;
}
}
void BridgeConf::parseOptions()
{
if(vmap.count("module")){
vector<string> values = vmap["module"].as<vector<string> >();
for(size_t i=0; i < values.size(); ++i){
string modulePath( values[i] );
if( filesystem::extension(filesystem::path( modulePath )).empty() )
{
modulePath += string( SUFFIX_SHARED_EXT );
}
addModuleInfo( modulePath );
}
}
if(vmap.count("out-port")){
setPortInfos("out-port", outPortInfos);
}
if(vmap.count("in-port")){
setPortInfos("in-port", inPortInfos);
}
if(vmap.count("connection")){
vector<string> values = vmap["connection"].as<vector<string> >();
for(size_t i=0; i < values.size(); ++i){
addPortConnection(values[i]);
}
}
string server(expandEnvironmentVariables(vmap["name-server"].as<string>()));
nameServerIdentifier = string("corbaloc:iiop:") + server + "/NameService";
controllerName = expandEnvironmentVariables(vmap["server-name"].as<string>());
virtualRobotRtcTypeName = expandEnvironmentVariables(vmap["robot-name"].as<string>());
if(virtualRobotRtcTypeName==""){
virtualRobotRtcTypeName=controllerName;
virtualRobotRtcTypeName.append("(Robot)");
}
if(vmap.count("periodic-rate")){
vector<string> values = vmap["periodic-rate"].as<vector<string> >();
for(size_t i=0; i < values.size(); ++i){
addTimeRateInfo(values[i]);
}
}
}
void BridgeConf::setPortInfos(const char* optionLabel, PortInfoMap& portInfos)
{
vector<string> ports = vmap[optionLabel].as<vector<string> >();
for(size_t i=0; i < ports.size(); ++i){
vector<string> parameters;
extractParameters(ports[i], parameters);
int n = parameters.size();
if(n < 2 || n > 4){
throw invalid_argument(string("invalid in port setting"));
}
PortInfo info;
info.portName = parameters[0];
int j;
for(j=1; j<3; j++){
LabelToDataTypeIdMap::iterator it = labelToDataTypeIdMap.find(parameters[j]);
if(it == labelToDataTypeIdMap.end() ){ // Handle as identification name because it is not a property name
if(j==2) // Error because there is no property name by the third
throw invalid_argument(string("invalid data type"));
string st=parameters[j];
vector<string> owners;
extractParameters(st, owners, ',');
for(size_t i=0; i<owners.size(); i++){
bool digit=true;
for(string::iterator itr=owners[i].begin(); itr!=owners[i].end(); itr++){
if(!isdigit(*itr)){
digit = false;
break;
}
}
if(digit){
// Since the identification name is numeric, it becomes image data.
// If two or more are specified, an error occurs.
info.dataOwnerId = atoi(owners[i].c_str());
info.dataOwnerNames.clear();
if(owners.size() > 1){
throw invalid_argument(string("invalid VisionSensor setting"));
}
}else{ // Identification name is name
info.dataOwnerId = -1;
info.dataOwnerNames.push_back(owners[i]);
}
}
}else{ // Property name
info.dataTypeId = it->second;
j++;
break;
}
}
if(j<n){ // If there is still a parameter, handle it as the sampling time
info.stepTime = atof(parameters[j].c_str());
}else{
info.stepTime = 0;
}
// When the property is CONSTRAINT_FORCE, there must not be two or more identification names
if(info.dataTypeId==CONSTRAINT_FORCE && info.dataOwnerNames.size() > 1 )
throw invalid_argument(string("invalid in port setting"));
portInfos.insert(make_pair(info.portName, info));
}
}
void BridgeConf::addPortConnection(const std::string& value)
{
vector<string> parameters;
extractParameters(value, parameters);
int n = parameters.size();
if(n < 2 || n > 4){
throw std::invalid_argument(string("Invalied port connection"));
}
PortConnection connection;
if(parameters.size() == 2){
connection.PortName[0] = parameters[0];
connection.PortName[1] = parameters[1];
} else if(parameters.size() == 3){
connection.PortName[0] = parameters[0];
connection.InstanceName[1] = parameters[1];
connection.PortName[1] = parameters[2];
}else if(parameters.size() == 4 ){
connection.InstanceName[0] = parameters[0];
connection.PortName[0] = parameters[1];
connection.InstanceName[1] = parameters[2];
connection.PortName[1] = parameters[3];
}
portConnections.push_back(connection);
}
void BridgeConf::setPreLoadModuleInfo()
{
RTC::Manager& rtcManager = RTC::Manager::instance();
std::vector<RTC::RtcBase*> components = rtcManager.getComponents();
for(std::vector<RTC::RtcBase*>::iterator it=components.begin(); it != components.end(); ++it){
ModuleInfo info;
info.componentName = (*it)->get_component_profile()->type_name;
info.fileName = "";
info.initFuncName = "";
info.isLoaded = true;
info.rtcServant = *it;
moduleInfoList.push_back(info);
}
}
void BridgeConf::addModuleInfo(const std::string& value)
{
vector<string> parameters;
extractParameters(value, parameters);
if(parameters.size() == 0 || parameters.size() > 2){
throw std::invalid_argument(std::string("invalid module set"));
} else {
ModuleInfo info;
info.fileName = parameters[0];
info.componentName = filesystem::basename(filesystem::path(info.fileName));
if(parameters.size() == 1){
info.initFuncName = info.componentName + "Init";
} else {
info.initFuncName = parameters[1];
}
info.isLoaded = false;
moduleInfoList.push_back(info);
}
}
void BridgeConf::addTimeRateInfo(const std::string& value)
{
vector<string> parameters;
extractParameters(value, parameters);
if (parameters.size() == 0 || parameters.size() > 2) {
throw std::invalid_argument(std::string("invalid time rate set"));
} else {
timeRateMap.insert( std::map<std::string, double>::value_type(parameters[0], atof(parameters[1].c_str())) );
}
}
void BridgeConf::setupModules()
{
RTC::Manager& rtcManager = RTC::Manager::instance();
ModuleInfoList::iterator moduleInfo = moduleInfoList.begin();
format param("%1%?exec_cxt.periodic.type=ChoreonoidExecutionContext&exec_cxt.periodic.rate=1000000");
while(moduleInfo != moduleInfoList.end()){
if(!moduleInfo->isLoaded){
rtcManager.load(moduleInfo->fileName.c_str(), moduleInfo->initFuncName.c_str());
moduleInfo->isLoaded = true;
moduleInfo->rtcServant = cnoid::createManagedRTC(str(param % moduleInfo->componentName).c_str());
}
++moduleInfo;
}
}
const char* BridgeConf::getOpenHRPNameServerIdentifier()
{
return nameServerIdentifier.c_str();
}
const char* BridgeConf::getControllerName()
{
return controllerName.c_str();
}
const char* BridgeConf::getVirtualRobotRtcTypeName()
{
return virtualRobotRtcTypeName.c_str();
}
void BridgeConf::extractParameters(const std::string& str, std::vector<std::string>& result, const char delimiter)
{
string::size_type sepPos = 0;
string::size_type nowPos = 0;
while (sepPos != string::npos) {
sepPos = str.find(delimiter, nowPos);
if(isProcessingConfigFile){
result.push_back(expandEnvironmentVariables(str.substr(nowPos, sepPos-nowPos)));
} else {
result.push_back(str.substr(nowPos, sepPos-nowPos));
}
nowPos = sepPos+1;
}
}
std::string BridgeConf::expandEnvironmentVariables(const std::string& str)
{
boost::regex variablePattern("\\$([A-z][A-z_0-9]*)");
boost::match_results<string::const_iterator> result;
boost::regex_constants::match_flag_type flags = boost::regex_constants::match_default;
string::const_iterator start, end;
std::string str_(str);
start = str_.begin();
end = str_.end();
int pos = 0;
vector< pair< int, int > > results;
while ( boost::regex_search(start, end, result, variablePattern, flags) ) {
results.push_back(std::make_pair(pos+result.position(1), result.length(1)));
// seek to the remaining part
start = result[0].second;
pos += result.length(0);
flags |= boost::match_prev_avail;
flags |= boost::match_not_bob;
}
// replace the variables in reverse order
while (!results.empty()) {
int begin = results.back().first;
int length = results.back().second;
string envName = str.substr(begin, length);
char* envValue = getenv(envName.c_str());
if(envValue){
str_.replace(begin-1, length+1, string(envValue));
}
results.pop_back();
}
return str_;
}
| [
"shafiee.a@ut.ac.ir"
] | shafiee.a@ut.ac.ir |
a40b71a1a60e31b3ccba064a18fb3138bac92fc9 | 0c0b045a0d3129871eeac1947091bdbaf13ed5ff | /Plugins/LeCorbusier/Source/LeCorbusier/Private/Types/ULCAsset.h | 64043bc4b9985a3fee5d0c07251202040f633d2f | [
"MIT"
] | permissive | carlosjtacon/unreal-lecorbusier-plugin | e16338e76e531cac2bd54bb82d04f528362dbb4b | bc072c69ed59221c2d929bb897db6f1d28139c6b | refs/heads/master | 2020-03-17T19:23:41.448222 | 2019-02-20T20:19:46 | 2019-02-20T20:19:46 | 133,858,577 | 23 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,484 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "ULCAsset.generated.h"
UENUM()
enum class EAssetType : uint8
{
None,
/** Nature related assets */
Tree, Bush, Rock, Cabin, Ruins,
/** City related assets */
Building, Monument //, Streetlight, Vehicle, ThrashBin, Dumpster, Billboard
};
UCLASS()
class ULCAsset : public UObject
{
GENERATED_BODY()
public:
ULCAsset():
bEnable(true),
MaxInstances(0),
Probability(0.7f),
Radius(1),
ScaleXYZ(FFloatInterval(1,1)),
RotationZ(FFloatInterval(0,0)),
TranslationX(FFloatInterval(0,0)),
TranslationY(FFloatInterval(0,0)),
TranslationZ(FFloatInterval(0,0))
{}
UObject* Asset;
// OBJECT TYPE
/** Type of asset */
UPROPERTY(EditAnywhere, Category = Type, meta = (DisplayName = "Type"))
EAssetType AssetType;
// GENERAL SETTINGS
/** Enable this asset */
UPROPERTY(EditAnywhere, Category = Instance, meta = (DisplayName = "Enable"))
bool bEnable;
/** Maximum number of instances generated (zero is unlimited!) */
UPROPERTY(EditAnywhere, Category = Instance, meta = (DisplayName = "Max. Instances", ClampMin = 0))
uint32 MaxInstances;
/** Probability of appearance */
UPROPERTY(EditAnywhere, Category = Instance, meta = (DisplayName = "Probability", ClampMin = 0, ClampMax = 1))
float Probability;
/** Minimum distance between instances (unreal units)*/
UPROPERTY(EditAnywhere, Category = Instance , meta = (DisplayName = "Radius", ClampMin = 1))
float Radius;
// TRANSFORMATION SETTINGS
/** Scale adjustment interval (XYZ) */
UPROPERTY(EditAnywhere, Category = Transformation, meta = (DisplayName = "Scale", UIMin = 0, ClampMin = 0))
FFloatInterval ScaleXYZ;
/** Rotation adjustment interval (Z) */
UPROPERTY(EditAnywhere, Category = Transformation, meta = (DisplayName = "Rotation", UIMin = 0, ClampMin = 0, UIMax = 360, ClampMax = 360))
FFloatInterval RotationZ;
/** Translation offset interval (X) */
UPROPERTY(EditAnywhere, Category = Transformation, meta = (DisplayName = "Translation X"))
FFloatInterval TranslationX;
/** Translation offset interval (Y) */
UPROPERTY(EditAnywhere, Category = Transformation, meta = (DisplayName = "Translation Y"))
FFloatInterval TranslationY;
/** Translation offset interval (Z) */
UPROPERTY(EditAnywhere, Category = Transformation, meta = (DisplayName = "Translation Z"))
FFloatInterval TranslationZ;
};
| [
"carlosjtacon@gmail.com"
] | carlosjtacon@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.