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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1ada7c2c9c6b6a43fddaf97b699fbce94891a426 | 0ab4ac8f0f8b7acaae4321ce0cabd137d28bd04a | /QOL/lagrangian/LaPSO.cpp | f3cdabca205edf9effb7e41cf04e0c50d40fc472 | [] | no_license | guskenny/stpg | 03fdc35d64baa5f3177fba196deae79758c1d915 | ed79acc241bcaec806eec4592e48be84a7315f50 | refs/heads/master | 2022-03-25T04:38:17.558558 | 2019-12-20T01:48:11 | 2019-12-20T01:48:11 | 161,317,511 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,753 | cpp | /// Generic solver for combinatorial optimisation problems using a combination
/// of Wedelin's lagrangian relaxation heuristic and particle swarm
/// optimisation. This header file follows the general pattern of the Volume
/// Algorithm implementation in the COIN-OR library to make it easy to swap
/// algorithms and make comparisons between the two methods.
///
/// The current implementation only allows for binary variables.
///
/// Autor: Andreas Ernst $ Date: January 2010 $ $ Revision: 0.0 $
#include "LaPSO.hpp"
#include "Random.h"
#include <algorithm>
#include <stdlib.h>
#include "anyoption.h"
#include <cstdlib>
#include <time.h>
#ifdef _OPENMP
# include <omp.h>
#else
# include <time.h>
# define omp_get_wtime() (double)time(NULL)
# define omp_set_num_threads(n) // do nothing
#endif
namespace LaPSO {
lagged_fibonacci1279 _randGen;
void Param::parse(int argc,const char **argv)
{
AnyOption parser(100);
parser.setFlag("help");
parser.setFlag("randomSeed");
parser.setOption("subgradFactor");
parser.setOption("subgradFmult");
parser.setOption("subgradFmin");
parser.setOption("perturbFactor");
parser.setOption("velocityFactor");
parser.setOption("globalFactor");
parser.setOption("maxIter");
parser.setOption("maxCPU");
parser.setOption("maxWallTime");
parser.setOption("nParticles");
parser.setOption("printLevel");
parser.setOption("printFreq");
parser.setOption("heurFreq");
parser.setOption("eps");
parser.setOption("absGap");
parser.setOption("relGap");
parser.setOption("nCPU");
if(argc == -1) // abuse of function
parser.processFile(*argv);
else
parser.processCommandArgs(argc,argv);
if(parser.getFlag("help"))
parser.printAutoUsage();
if(parser.getFlag("randomSeed"))
randomSeed = 0; //
if(parser.getValue("subgradFactor"))
subgradFactor = atof(parser.getValue("subgradFactor"));
if(parser.getValue("subgradFmult"))
subgradFmult = atof(parser.getValue("subgradFmult"));
if(parser.getValue("subgradFmin"))
subgradFmin = atof(parser.getValue("subgradFmin"));
if(parser.getValue("perturbFactor"))
perturbFactor = atof(parser.getValue("perturbFactor"));
if(parser.getValue("velocityFactor"))
velocityFactor = atof(parser.getValue("velocityFactor"));
if(parser.getValue("globalFactor"))
globalFactor = atof(parser.getValue("globalFactor"));
if(parser.getValue("maxIter"))
maxIter = atoi(parser.getValue("maxIter"));
if(parser.getValue("maxCPU"))
maxCPU = atof(parser.getValue("maxCPU"));
if(parser.getValue("maxWallTime"))
maxWallTime = atof(parser.getValue("maxWallTime"));
if(parser.getValue("nParticles"))
nParticles = atoi(parser.getValue("nParticles"));
if(parser.getValue("printLevel"))
printLevel = atoi(parser.getValue("printLevel"));
if(parser.getValue("printFreq"))
printFreq = atoi(parser.getValue("printFreq"));
if(parser.getValue("heurFreq"))
heurFreq = atoi(parser.getValue("heurFreq"));
if(parser.getValue("eps"))
eps = atof(parser.getValue("eps"));
if(parser.getValue("absGap"))
absGap = atof(parser.getValue("absGap"));
if(parser.getValue("relGap"))
relGap = atof(parser.getValue("relGap"));
if(parser.getValue("nCPU"))
nCPU = std::max(1,atoi(parser.getValue("nCPU")));
}
void Param::parse(const char *filename){ parse(-1,&filename); }
void Particle::resize(size_t numVar,size_t numConstr){
dual.resize(numConstr,0.0);
perturb.resize(numVar,0.0);
x.resize(numVar,0);
viol.resize(numConstr,0.0);
rc.resize(numVar,0.0);
isFeasible = false;
dVel.resize(numConstr,0.0);
ub = INF;
lb = -INF;
pVel.resize(numVar,0.0);
}
Problem::Problem(int nVar,int nConstr) :
psize(nVar), dsize(nConstr),
dualLB(dsize,-INF), dualUB(dsize,INF),
nIter(-1)
{ best.ub = INF;best.lb=-INF;best.isFeasible=false;
best.perturb.resize(nVar,0.0); best.dual.resize(nConstr,0.0);}
// Main method
void Problem::solve(UserHooks &hooks)
{
const int lbCheckFreq = 10;
initialise(hooks); // set up the swarm
//------------- initial solution for swarm --------------
if( param.printLevel > 1) printf("Initialisation:\n");
DblVec bestLB(param.nParticles);
IntVec bestIter(param.nParticles,0);
std::vector<Uniform> rand(param.nParticles); //
if(param.randomSeed != 0) rand[0].seed(param.randomSeed);
else rand[0].seedTime();
Status status = OK;
# pragma omp parallel for schedule(static,std::max(1,param.nParticles/param.nCPU))
for(int idx =0;idx < param.nParticles;++idx){
ParticleIter p(swarm,idx);
if(p.idx > 0){ // create random see from previous generator
rand[p.idx].seed((uint32_t) rand[p.idx-1](
0,std::numeric_limits<uint32_t>::max()));
}
for(int i=0;i<dsize;++i){ // check initial point is valid
if( p->dual[i] < dualLB[i] ){
if(param.printLevel)
printf("ERROR: initial dual[%d] %.2f below LB %.2f\n",
i,p->dual[i],dualLB[i]);
p->dual[i] = dualLB[i];
}
if(p->dual[i] > dualUB[i] ){
if(param.printLevel)
printf("ERROR: initial dual[%d] %.2f below UB %.2f\n",
i,p->dual[i],dualUB[i]);
p->dual[i] = dualUB[i];
}
}
if( hooks.reducedCost(*p,p->rc) == ABORT){ status = ABORT;}
p->rc += p->perturb;
if( hooks.solveSubproblem(*p) == ABORT ){status = ABORT; }
bestLB[p.idx] = p->lb;
if( param.printLevel > 1){
printf("\tp%02d: LB=%g UB=%g feas=%d viol=%g -- %g\n",
p.idx,p->lb,p->ub,p->isFeasible,
p->viol.min(),p->viol.max());
if(param.printLevel > 2){
printf("\t\tRedCst %g - %g\n",p->rc.min(),p->rc.max());
printf("\t\tdVel %g - %g\n",p->dVel.min(),p->dVel.max());
printf("\t\tpVel %g - %g\n",p->pVel.min(),p->pVel.max());
printf("\t\tdual %g - %g\n",p->dual.min(),p->dual.max());
printf("\t\tpert %g - %g\n",
p->perturb.min(),p->perturb.max());
}
}
p->pVel = 0;
p->dVel = 0;
}
best.x.resize(psize,0);
updateBest(hooks);
if(status == ABORT) return;
DblVec subgradFactor(param.nParticles,param.subgradFactor);
DblVec perturbFactor(param.nParticles,param.perturbFactor);
for(int i=0;i<param.nParticles;++i)
perturbFactor[i] = i*param.perturbFactor/param.nParticles;
if( param.printLevel > 1)
printf("Initial LB=%g UB=%g\n",best.lb,best.ub);
int noImproveIter = 0,nReset=0,maxNoImprove=1000;
for(nIter=1; nIter < param.maxIter && cpuTime() < param.maxCPU &&
wallTime() < param.maxWallTime && status == OK &&
best.lb + param.absGap <= best.ub &&
fabs(best.ub-best.lb/best.ub) > param.relGap;
++nIter){
if(param.printLevel > 1 && nIter % param.printFreq == 0)
printf("Iteration %d --------------------\n",nIter);
# pragma omp parallel for schedule(static,std::max(1,param.nParticles/param.nCPU))
for(int idx =0;idx < param.nParticles;++idx){
ParticleIter p(swarm,idx);
// --------- calculate step size/direction ----------
double norm=0;
for(int i=0;i<dsize;++i) norm += p->viol[i]*p->viol[i];
DblVec perturbDir(psize,0.0);
perturbationDirection(hooks,*p,perturbDir);
double randAscent = rand[p.idx]() ; // 0,1 uniform
double randGlobal = rand[p.idx]() * param.globalFactor;
const double stepSize = rand[p.idx](
subgradFactor[p.idx]/2.0,subgradFactor[p.idx]) *
(best.ub-bestLB[p.idx]) / norm;
// const double stepSize = randAscent * param.subgradFactor *
// (best.ub-best.lb) / norm;
//-------------- update velocity (step) --------------
for(int i=0;i<dsize;++i)
p->dVel[i] = param.velocityFactor * p->dVel[i] +
stepSize * p->viol[i] +
randGlobal * (best.dual[i] - p->dual[i]);
for(int i=0;i<psize;++i)
p->pVel[i] = param.velocityFactor * p->pVel[i] +
randAscent * perturbFactor[p.idx]* //param.perturbFactor *
perturbDir[i] +
perturbFactor[p.idx]* randGlobal * (1-2*best.x[i])+
randGlobal * (best.perturb[i]-p->perturb[i])
;
//---------- make a step ------------------------------
for(int i=0;i<dsize;++i){
p->dual[i] += p->dVel[i];
p->dual[i] = std::max(dualLB[i],std::min(dualUB[i],p->dual[i]));
}
p->perturb *= 0.5;
p->perturb += p->pVel; // add step in perturbation velocity
//---------- solve subproblems -------------------------
if( hooks.reducedCost(*p,p->rc) == ABORT){
status = ABORT; continue;
}
if( nIter % lbCheckFreq != 0){
p->rc += p->perturb; // if we care more about ub than lb
if( hooks.solveSubproblem(*p) == ABORT) status = ABORT;
}else{ // temporarily set pertubation to zero
DblVec zero(p->perturb.size(),0.0);
std::swap(p->perturb,zero);
if( hooks.solveSubproblem(*p) == ABORT) status = ABORT;
std::swap(p->perturb,zero); // swap back
}
if(status == ABORT) continue;
//if( p->isFeasible ){
// // make sure our next step reduces perturbation
// p->pVel = p->perturb;
// p->pVel *= -0.5/param.velocityFactor;
//}
//if( p->lb < bestLB[p.idx]) // downplay current velocity
// p->dVel *= 0.5;
if( nIter % lbCheckFreq == 0){
if( p->lb > bestLB[p.idx] ){
bestLB[p.idx] = p->lb;
bestIter[p.idx] = nIter;
//subgradFactor[p.idx] *= 1.1;
// printf("\tsubgradFactor[%d] increased to %.4f (bestLB = %.2f)\n",
// p.idx,subgradFactor[p.idx],bestLB[p.idx]);
}else { //if( (nIter - bestIter[p.idx]) % 2 == 0 ){
subgradFactor[p.idx] = // slow down
std::max(param.subgradFmin,
param.subgradFmult*subgradFactor[p.idx]);
// printf("\tsubgradFactor[%d] decreased to %.4f\n",
// p.idx,subgradFactor[p.idx]);
}
}
if( param.heurFreq > 0 && nIter % param.heurFreq == 0
&& ! p->isFeasible) // only run heuristic if not alreay feas.
if(hooks.heuristics(*p) == ABORT){status=ABORT; continue;}
if( param.printLevel > 1 && nIter % param.printFreq == 0){
printf("\tp%02d: LB=%g UB=%g feas=%d minViol=%g\n",
p.idx,p->lb,p->ub,p->isFeasible,
p->viol.min());
if(param.printLevel > 2){
printf("\t\tstepSize=%g randGlobal=%g\n",
stepSize,randGlobal);
printf("\t\tRedCst %g - %g\n",p->rc.min(),p->rc.max());
printf("\t\tdVel %g - %g\n",p->dVel.min(),p->dVel.max());
printf("\t\tpDir %g - %g\n",perturbDir.min(),perturbDir.max());
printf("\t\tpVel %g - %g\n",p->pVel.min(),p->pVel.max());
printf("\t\tdual %g - %g\n",p->dual.min(),p->dual.max());
printf("\t\tpert %g - %g\n",
p->perturb.min(),p->perturb.max());
}
}
}
if( updateBest(hooks))
noImproveIter = 0;
else{
if(++noImproveIter > maxNoImprove ){ // reset duals
++nReset;
swarm[0]->dual = 0;
double minLB=INF,maxLB=-INF;
for(int idx=0;idx<param.nParticles;++idx){
if(swarm[idx]->lb < minLB) minLB = swarm[idx]->lb;
if(swarm[idx]->lb > maxLB) maxLB = swarm[idx]->lb;
}
hooks.reducedCost(*swarm[0],swarm[0]->rc);
double maxdual = std::max(0.0,swarm[0]->rc.max()) -
std::min(0.0,swarm[0]->rc.min());
if(maxdual < 1e-9) maxdual=1;
#pragma omp parallel for
for(int idx=0;idx<param.nParticles;++idx){
ParticleIter p(swarm,idx);
for(int j=0;j<dsize;++j){// generate pertubation about
if(p->dual[j] == 0 && rand[idx]() < 2.0/dsize){
p->dual[j] = rand[idx](
std::max(dualLB[j],-maxdual),
std::min(dualUB[j],maxdual));
}else
p->dual[j]= best.dual[j]*rand[idx](
1-0.2/nReset,1 + 0.2/nReset);
p->dual[j] = std::max(
dualLB[j],std::min(dualUB[j],p->dual[j]));
}
p->perturb = 0.0;
p->dVel = 0.0;
p->pVel = 0.0;
for(int i=0;i<psize;++i) // discourage current best
if( rand[idx](0,1) <0.1) // try to get diversity
p->pVel[i] = rand[idx](0,1) *perturbFactor[idx]
*maxdual*(2*best.x[i]-1);
subgradFactor[p.idx] = param.subgradFactor/nReset;
perturbFactor[p.idx] *= 1.1;
if(hooks.reducedCost(*p,p->rc)==ABORT){status=ABORT;}
if(hooks.solveSubproblem(*p) == ABORT){status=ABORT;}
}
param.heurFreq=std::max(param.heurFreq/2,1);
param.subgradFmin *= 0.5;
updateBest(hooks);
noImproveIter = 0;
maxNoImprove += 1000;
if(param.printLevel > 0){
printf("%2d: Reset swarm LBs were %.2f - %.2f now",
nIter,minLB,maxLB);
minLB=INF;maxLB=-INF;
for(int idx=0;idx<param.nParticles;++idx){
if(swarm[idx]->lb < minLB) minLB = swarm[idx]->lb;
if(swarm[idx]->lb > maxLB) maxLB = swarm[idx]->lb;
}
printf(" %.2f - %.2f\n",minLB,maxLB);
}
}
}
if( param.printLevel && nIter % param.printFreq == 0)
printf("%2d: LB=%.2f UB=%.2f\n",nIter,best.lb,best.ub);
}
}
double Problem::swarmRadius() const
{ return 0; } // not yet implemented
double Problem::wallTime() const
{
return omp_get_wtime() - _wallTime;
}
// set up an initial swarm
void Problem::initialise(UserHooks &hooks)
{
nIter = 0;
omp_set_num_threads(param.nCPU);
_wallTime = omp_get_wtime();
timer.reset();
if( swarm.size() >= (size_t)param.nParticles )
return; // all done
// figure out what range of duals makes sense
if(best.dual.size() < (size_t)dsize) best.dual.resize(dsize,0.0);
if(best.perturb.size() < (size_t)psize) best.perturb.resize(psize,0.0);
if(best.rc.size() < (size_t)psize) best.rc.resize(psize,0.0);
hooks.reducedCost(best,best.rc);
// find biggest absolute value reduced cost
const double maxCost = std::max(
*std::max_element(best.rc.begin(),best.rc.end()),
- *std::min_element(best.rc.begin(),best.rc.end()));
swarm.reserve(param.nParticles);
Uniform rand;
if(param.randomSeed == 0) rand.seedTime();
else rand.seed(param.randomSeed);
while(swarm.size() < (size_t)param.nParticles){
Particle *p = new Particle(psize,dsize);
swarm.push_back(p);
for(int j=0;j<dsize;++j) // generate values up to maxCost
p->dual[j] = rand(std::max(dualLB[j],-maxCost),
std::min(dualUB[j],maxCost));
p->perturb = 0.0;
p->dVel = 0.0;
p->pVel = 0.0;
}
}
bool Problem::updateBest(UserHooks &hooks)
{ Particle *bestP = 0;
bool improved = false;
for(ParticleIter p(swarm); ! p.done(); ++p){
if(p->isFeasible && p->ub < best.ub){
best.ub = p->ub;
best.isFeasible = true;
best.x = p->x;
best.perturb = p->perturb; // perturbation gives good feasible
bestP = &(*p);
}
if(p->lb > best.lb){
best.lb = p->lb;
best.dual = p->dual;
best.viol = p->viol;
improved = true;
}
}
if(bestP) // only call once if current swarm improved optimum
hooks.updateBest(*bestP);
return improved || (bestP != 0);
}
/** Calculate a direction for the perturbation that is likely
to lead to more feasible solutions (using hooks.fixConstraint) */
void Problem::perturbationDirection(UserHooks &hooks,const Particle &p,
DblVec &dir) const
{ const double eps = param.eps;
dir = 0.0; // set all to zero
for(int i=0;i<dsize;++i){
if((p.viol[i] > eps && dualLB[i] < -eps) ||
(p.viol[i] < -eps && dualUB[i] > eps)) { // constraint violated
SparseVec feas;
hooks.fixConstraint(i,p,feas);
for(SparseVec::iterator x=feas.begin();x!=feas.end();++x){
if(x->second >= 1) dir[x->first] -= 1;
if(x->second <= 0) dir[x->first] += 1;
}
}
}
}
}; // end namespace
/* Stuff for emacs/xemacs to conform to the "Visual Studio formatting standard"
* Local Variables:
* tab-width: 4
* eval: (c-set-style "stroustrup")
* End:
*/
| [
"guskenny83@gmail.com"
] | guskenny83@gmail.com |
86f2fae318f719feb3a9e59909ab65cda6083690 | ca27b9884af0e8f008ccb032fbd2e6106deced4d | /pointcal.cpp | d487341f863e524c90ce6dfdede483fb73f4f27a | [] | no_license | KimHyung/cpp | 3e32de0acb0593b23582c772921303ceb5970832 | 0c9eb225ef78c3d649c57b1ea907c22cf13e7bc3 | refs/heads/master | 2020-09-12T23:44:49.533428 | 2019-11-19T05:31:43 | 2019-11-19T05:31:43 | 222,595,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | cpp | #include <iostream>
class Point{
private:
int x,y;
public:
Point(int pos_x, int pos_y);
};
class Geometry{
Point **point_array;
public:
Geometry(Point **point_list);
Geometry();
void Add_point(const Point &point);
void Print_Distance();
void Print_Num_meets();
}; | [
"kty5989@gmail.com"
] | kty5989@gmail.com |
f391ada0767e6773d4c105fda9f099fa83c2ca18 | 238e46a903cf7fac4f83fa8681094bf3c417d22d | /VTK/vtk_7.1.1_x64_Release/include/vtk-7.1/vtknetcdf/include/vtk_netcdf_mangle.h | bde4095297427ce7b416db106cf236d4ca47104e | [
"BSD-3-Clause"
] | permissive | baojunli/FastCAE | da1277f90e584084d461590a3699b941d8c4030b | a3f99f6402da564df87fcef30674ce5f44379962 | refs/heads/master | 2023-02-25T20:25:31.815729 | 2021-02-01T03:17:33 | 2021-02-01T03:17:33 | 268,390,180 | 1 | 0 | BSD-3-Clause | 2020-06-01T00:39:31 | 2020-06-01T00:39:31 | null | UTF-8 | C++ | false | false | 45,355 | h | #ifndef vtk_netcdf_mangle_h
#define vtk_netcdf_mangle_h
/*
This header file mangles all symbols exported from the netcdf library.
It is included in all files while building the netcdf library. Due to
namespace pollution, no netcdf headers should be included in .h files in
VTK.
The following command was used to obtain the symbol list:
nm libvtkNetCDF.a |grep " [TRD] "
This is the way to recreate the whole list:
nm bin/libvtkNetCDF.so |grep " [TRD] " | awk '{ print "#define "$3" vtk_netcdf_"$3 }' | \
grep -v vtk_netcdf__fini | grep -v vtk_netcdf__init | sort
Note that _fini and _init should be excluded because they are not functions
implemented by the library but are rather created by the linker and
used when the shared library is loaded/unloaded from an executable.
*/
#define NC3__enddef vtk_netcdf_NC3__enddef
#define NC3_abort vtk_netcdf_NC3_abort
#define NC3_close vtk_netcdf_NC3_close
#define NC3_create vtk_netcdf_NC3_create
#define NC3_def_dim vtk_netcdf_NC3_def_dim
#define NC3_def_var vtk_netcdf_NC3_def_var
#define NC3_del_att vtk_netcdf_NC3_del_att
#define NC3_dispatch_table vtk_netcdf_NC3_dispatch_table
#define NC3_dispatcher vtk_netcdf_NC3_dispatcher
#define NC3_get_att vtk_netcdf_NC3_get_att
#define NC3_get_vara vtk_netcdf_NC3_get_vara
#define NC3_initialize vtk_netcdf_NC3_initialize
#define NC3_inq vtk_netcdf_NC3_inq
#define NC3_inq_att vtk_netcdf_NC3_inq_att
#define NC3_inq_attid vtk_netcdf_NC3_inq_attid
#define NC3_inq_attname vtk_netcdf_NC3_inq_attname
#define NC3_inq_base_pe vtk_netcdf_NC3_inq_base_pe
#define NC3_inq_dim vtk_netcdf_NC3_inq_dim
#define NC3_inq_dimid vtk_netcdf_NC3_inq_dimid
#define NC3_inq_format vtk_netcdf_NC3_inq_format
#define NC3_inq_type vtk_netcdf_NC3_inq_type
#define NC3_inq_unlimdim vtk_netcdf_NC3_inq_unlimdim
#define NC3_inq_var vtk_netcdf_NC3_inq_var
#define NC3_inq_varid vtk_netcdf_NC3_inq_varid
#define NC3_new_nc vtk_netcdf_NC3_new_nc
#define NC3_open vtk_netcdf_NC3_open
#define NC3_put_att vtk_netcdf_NC3_put_att
#define NC3_put_vara vtk_netcdf_NC3_put_vara
#define NC3_redef vtk_netcdf_NC3_redef
#define NC3_rename_att vtk_netcdf_NC3_rename_att
#define NC3_rename_dim vtk_netcdf_NC3_rename_dim
#define NC3_rename_var vtk_netcdf_NC3_rename_var
#define NC3_set_base_pe vtk_netcdf_NC3_set_base_pe
#define NC3_set_fill vtk_netcdf_NC3_set_fill
#define NC3_sync vtk_netcdf_NC3_sync
#define NC4__enddef vtk_netcdf_NC4__enddef
#define NC4_abort vtk_netcdf_NC4_abort
#define NC4_close vtk_netcdf_NC4_close
#define NC4_create vtk_netcdf_NC4_create
#define NC4_def_compound vtk_netcdf_NC4_def_compound
#define NC4_def_dim vtk_netcdf_NC4_def_dim
#define NC4_def_enum vtk_netcdf_NC4_def_enum
#define NC4_def_grp vtk_netcdf_NC4_def_grp
#define NC4_def_opaque vtk_netcdf_NC4_def_opaque
#define NC4_def_var vtk_netcdf_NC4_def_var
#define NC4_def_var_chunking vtk_netcdf_NC4_def_var_chunking
#define NC4_def_var_deflate vtk_netcdf_NC4_def_var_deflate
#define NC4_def_var_endian vtk_netcdf_NC4_def_var_endian
#define NC4_def_var_fill vtk_netcdf_NC4_def_var_fill
#define NC4_def_var_fletcher32 vtk_netcdf_NC4_def_var_fletcher32
#define NC4_def_vlen vtk_netcdf_NC4_def_vlen
#define NC4_del_att vtk_netcdf_NC4_del_att
#define NC4_dispatch_table vtk_netcdf_NC4_dispatch_table
#define NC4_dispatcher vtk_netcdf_NC4_dispatcher
#define NC4_get_att vtk_netcdf_NC4_get_att
#define NC4_get_var_chunk_cache vtk_netcdf_NC4_get_var_chunk_cache
#define NC4_get_vara vtk_netcdf_NC4_get_vara
#define NC4_get_vlen_element vtk_netcdf_NC4_get_vlen_element
#define NC4_initialize vtk_netcdf_NC4_initialize
#define NC4_inq vtk_netcdf_NC4_inq
#define NC4_inq_att vtk_netcdf_NC4_inq_att
#define NC4_inq_attid vtk_netcdf_NC4_inq_attid
#define NC4_inq_attname vtk_netcdf_NC4_inq_attname
#define NC4_inq_base_pe vtk_netcdf_NC4_inq_base_pe
#define NC4_inq_compound_field vtk_netcdf_NC4_inq_compound_field
#define NC4_inq_compound_fieldindex vtk_netcdf_NC4_inq_compound_fieldindex
#define NC4_inq_dim vtk_netcdf_NC4_inq_dim
#define NC4_inq_dimid vtk_netcdf_NC4_inq_dimid
#define NC4_inq_dimids vtk_netcdf_NC4_inq_dimids
#define NC4_inq_enum_ident vtk_netcdf_NC4_inq_enum_ident
#define NC4_inq_enum_member vtk_netcdf_NC4_inq_enum_member
#define NC4_inq_format vtk_netcdf_NC4_inq_format
#define NC4_inq_grp_full_ncid vtk_netcdf_NC4_inq_grp_full_ncid
#define NC4_inq_grp_parent vtk_netcdf_NC4_inq_grp_parent
#define NC4_inq_grpname vtk_netcdf_NC4_inq_grpname
#define NC4_inq_grpname_full vtk_netcdf_NC4_inq_grpname_full
#define NC4_inq_grps vtk_netcdf_NC4_inq_grps
#define NC4_inq_ncid vtk_netcdf_NC4_inq_ncid
#define NC4_inq_type vtk_netcdf_NC4_inq_type
#define NC4_inq_type_equal vtk_netcdf_NC4_inq_type_equal
#define NC4_inq_typeid vtk_netcdf_NC4_inq_typeid
#define NC4_inq_typeids vtk_netcdf_NC4_inq_typeids
#define NC4_inq_unlimdim vtk_netcdf_NC4_inq_unlimdim
#define NC4_inq_unlimdims vtk_netcdf_NC4_inq_unlimdims
#define NC4_inq_user_type vtk_netcdf_NC4_inq_user_type
#define NC4_inq_var_all vtk_netcdf_NC4_inq_var_all
#define NC4_inq_varid vtk_netcdf_NC4_inq_varid
#define NC4_inq_varids vtk_netcdf_NC4_inq_varids
#define NC4_insert_array_compound vtk_netcdf_NC4_insert_array_compound
#define NC4_insert_compound vtk_netcdf_NC4_insert_compound
#define NC4_insert_enum vtk_netcdf_NC4_insert_enum
#define NC4_new_nc vtk_netcdf_NC4_new_nc
#define NC4_open vtk_netcdf_NC4_open
#define NC4_put_att vtk_netcdf_NC4_put_att
#define NC4_put_vara vtk_netcdf_NC4_put_vara
#define NC4_put_vlen_element vtk_netcdf_NC4_put_vlen_element
#define NC4_redef vtk_netcdf_NC4_redef
#define NC4_rename_att vtk_netcdf_NC4_rename_att
#define NC4_rename_dim vtk_netcdf_NC4_rename_dim
#define NC4_rename_var vtk_netcdf_NC4_rename_var
#define NC4_set_base_pe vtk_netcdf_NC4_set_base_pe
#define NC4_set_fill vtk_netcdf_NC4_set_fill
#define NC4_set_var_chunk_cache vtk_netcdf_NC4_set_var_chunk_cache
#define NC4_show_metadata vtk_netcdf_NC4_show_metadata
#define NC4_sync vtk_netcdf_NC4_sync
#define NC4_var_par_access vtk_netcdf_NC4_var_par_access
#define NCDEFAULT_get_varm vtk_netcdf_NCDEFAULT_get_varm
#define NCDEFAULT_get_vars vtk_netcdf_NCDEFAULT_get_vars
#define NCDEFAULT_put_varm vtk_netcdf_NCDEFAULT_put_varm
#define NCDEFAULT_put_vars vtk_netcdf_NCDEFAULT_put_vars
#define NC_atomictypelen vtk_netcdf_NC_atomictypelen
#define NC_atomictypename vtk_netcdf_NC_atomictypename
#define NC_calcsize vtk_netcdf_NC_calcsize
#define NC_check_id vtk_netcdf_NC_check_id
#define NC_check_name vtk_netcdf_NC_check_name
#define NC_check_vlen vtk_netcdf_NC_check_vlen
#define NC_create vtk_netcdf_NC_create
#define NC_dispatch_overlay vtk_netcdf_NC_dispatch_overlay
#define NC_findattr vtk_netcdf_NC_findattr
#define NC_findvar vtk_netcdf_NC_findvar
#define NC_get_dispatch_override vtk_netcdf_NC_get_dispatch_override
#define NC_get_vara vtk_netcdf_NC_get_vara
#define NC_initialize vtk_netcdf_NC_initialize
#define NC_lookupvar vtk_netcdf_NC_lookupvar
#define NC_open vtk_netcdf_NC_open
#define NC_set_dispatch_override vtk_netcdf_NC_set_dispatch_override
#define NC_sync vtk_netcdf_NC_sync
#define NC_testurl vtk_netcdf_NC_testurl
#define NC_urlmodel vtk_netcdf_NC_urlmodel
#define NC_var_shape vtk_netcdf_NC_var_shape
#define add_to_NCList vtk_netcdf_add_to_NCList
#define atomic_name vtk_netcdf_atomic_name
#define count_NCList vtk_netcdf_count_NCList
#define default_create_format vtk_netcdf_default_create_format
#define del_from_NCList vtk_netcdf_del_from_NCList
#define dup_NC_attrarrayV vtk_netcdf_dup_NC_attrarrayV
#define dup_NC_dimarrayV vtk_netcdf_dup_NC_dimarrayV
#define dup_NC_vararrayV vtk_netcdf_dup_NC_vararrayV
#define elem_NC_attrarray vtk_netcdf_elem_NC_attrarray
#define elem_NC_dimarray vtk_netcdf_elem_NC_dimarray
#define fill_NC_var vtk_netcdf_fill_NC_var
#define find_NC_Udim vtk_netcdf_find_NC_Udim
#define find_in_NCList vtk_netcdf_find_in_NCList
#define free_NCList vtk_netcdf_free_NCList
#define free_NC_attr vtk_netcdf_free_NC_attr
#define free_NC_attrarrayV vtk_netcdf_free_NC_attrarrayV
#define free_NC_attrarrayV0 vtk_netcdf_free_NC_attrarrayV0
#define free_NC_dim vtk_netcdf_free_NC_dim
#define free_NC_dimarrayV vtk_netcdf_free_NC_dimarrayV
#define free_NC_dimarrayV0 vtk_netcdf_free_NC_dimarrayV0
#define free_NC_string vtk_netcdf_free_NC_string
#define free_NC_var vtk_netcdf_free_NC_var
#define free_NC_vararrayV vtk_netcdf_free_NC_vararrayV
#define free_NC_vararrayV0 vtk_netcdf_free_NC_vararrayV0
#define hash_fast vtk_netcdf_hash_fast
#define int_cmp vtk_netcdf_int_cmp
#define nc4_adjust_var_cache vtk_netcdf_nc4_adjust_var_cache
#define nc4_att_list_add vtk_netcdf_nc4_att_list_add
#define nc4_att_list_del vtk_netcdf_nc4_att_list_del
#define nc4_check_dup_name vtk_netcdf_nc4_check_dup_name
#define nc4_check_name vtk_netcdf_nc4_check_name
#define nc4_chunk_cache_nelems vtk_netcdf_nc4_chunk_cache_nelems
#define nc4_chunk_cache_preemption vtk_netcdf_nc4_chunk_cache_preemption
#define nc4_chunk_cache_size vtk_netcdf_nc4_chunk_cache_size
#define nc4_convert_type vtk_netcdf_nc4_convert_type
#define nc4_dim_list_add vtk_netcdf_nc4_dim_list_add
#define nc4_dim_list_add2 vtk_netcdf_nc4_dim_list_add2
#define nc4_dim_list_del vtk_netcdf_nc4_dim_list_del
#define nc4_enddef_netcdf4_file vtk_netcdf_nc4_enddef_netcdf4_file
#define nc4_enum_member_add vtk_netcdf_nc4_enum_member_add
#define nc4_field_list_add vtk_netcdf_nc4_field_list_add
#define nc4_file_list_add vtk_netcdf_nc4_file_list_add
#define nc4_file_list_del vtk_netcdf_nc4_file_list_del
#define nc4_file_list_free vtk_netcdf_nc4_file_list_free
#define nc4_find_dim vtk_netcdf_nc4_find_dim
#define nc4_find_dim_len vtk_netcdf_nc4_find_dim_len
#define nc4_find_g_var_nc vtk_netcdf_nc4_find_g_var_nc
#define nc4_find_grp_att vtk_netcdf_nc4_find_grp_att
#define nc4_find_grp_h5 vtk_netcdf_nc4_find_grp_h5
#define nc4_find_nc4_grp vtk_netcdf_nc4_find_nc4_grp
#define nc4_find_nc_att vtk_netcdf_nc4_find_nc_att
#define nc4_find_nc_file vtk_netcdf_nc4_find_nc_file
#define nc4_find_nc_grp_h5 vtk_netcdf_nc4_find_nc_grp_h5
#define nc4_find_type vtk_netcdf_nc4_find_type
#define nc4_get_att vtk_netcdf_nc4_get_att
#define nc4_get_att_tc vtk_netcdf_nc4_get_att_tc
#define nc4_get_default_fill_value vtk_netcdf_nc4_get_default_fill_value
#define nc4_get_hdf4_vara vtk_netcdf_nc4_get_hdf4_vara
#define nc4_get_hdf_typeid vtk_netcdf_nc4_get_hdf_typeid
#define nc4_get_typelen_mem vtk_netcdf_nc4_get_typelen_mem
#define nc4_get_vara vtk_netcdf_nc4_get_vara
#define nc4_grp_list_add vtk_netcdf_nc4_grp_list_add
#define nc4_nc4f_list_add vtk_netcdf_nc4_nc4f_list_add
#define nc4_normalize_name vtk_netcdf_nc4_normalize_name
#define nc4_open_var_grp2 vtk_netcdf_nc4_open_var_grp2
#define nc4_pg_var1 vtk_netcdf_nc4_pg_var1
#define nc4_pg_varm vtk_netcdf_nc4_pg_varm
#define nc4_put_att vtk_netcdf_nc4_put_att
#define nc4_put_att_tc vtk_netcdf_nc4_put_att_tc
#define nc4_put_vara vtk_netcdf_nc4_put_vara
#define nc4_rec_find_grp vtk_netcdf_nc4_rec_find_grp
#define nc4_rec_find_hdf_type vtk_netcdf_nc4_rec_find_hdf_type
#define nc4_rec_find_named_type vtk_netcdf_nc4_rec_find_named_type
#define nc4_rec_find_nc_type vtk_netcdf_nc4_rec_find_nc_type
#define nc4_rec_grp_del vtk_netcdf_nc4_rec_grp_del
#define nc4_rec_match_dimscales vtk_netcdf_nc4_rec_match_dimscales
#define nc4_rec_read_types vtk_netcdf_nc4_rec_read_types
#define nc4_rec_read_vars vtk_netcdf_nc4_rec_read_vars
#define nc4_rec_write_metadata vtk_netcdf_nc4_rec_write_metadata
#define nc4_rec_write_types vtk_netcdf_nc4_rec_write_types
#define nc4_reopen_dataset vtk_netcdf_nc4_reopen_dataset
#define nc4_type_list_add vtk_netcdf_nc4_type_list_add
#define nc4_var_list_add vtk_netcdf_nc4_var_list_add
#define nc4typelen vtk_netcdf_nc4typelen
#define nc__create vtk_netcdf_nc__create
#define nc__create_mp vtk_netcdf_nc__create_mp
#define nc__enddef vtk_netcdf_nc__enddef
#define nc__open vtk_netcdf_nc__open
#define nc__open_mp vtk_netcdf_nc__open_mp
#define nc_abort vtk_netcdf_nc_abort
#define nc_cktype vtk_netcdf_nc_cktype
#define nc_close vtk_netcdf_nc_close
#define nc_copy_att vtk_netcdf_nc_copy_att
#define nc_copy_var vtk_netcdf_nc_copy_var
#define nc_create vtk_netcdf_nc_create
#define nc_create_par vtk_netcdf_nc_create_par
#define nc_create_par_fortran vtk_netcdf_nc_create_par_fortran
#define nc_def_compound vtk_netcdf_nc_def_compound
#define nc_def_dim vtk_netcdf_nc_def_dim
#define nc_def_enum vtk_netcdf_nc_def_enum
#define nc_def_grp vtk_netcdf_nc_def_grp
#define nc_def_opaque vtk_netcdf_nc_def_opaque
#define nc_def_var vtk_netcdf_nc_def_var
#define nc_def_var_chunking vtk_netcdf_nc_def_var_chunking
#define nc_def_var_chunking_ints vtk_netcdf_nc_def_var_chunking_ints
#define nc_def_var_deflate vtk_netcdf_nc_def_var_deflate
#define nc_def_var_endian vtk_netcdf_nc_def_var_endian
#define nc_def_var_fill vtk_netcdf_nc_def_var_fill
#define nc_def_var_fletcher32 vtk_netcdf_nc_def_var_fletcher32
#define nc_def_vlen vtk_netcdf_nc_def_vlen
#define nc_del_att vtk_netcdf_nc_del_att
#define nc_delete vtk_netcdf_nc_delete
#define nc_delete_mp vtk_netcdf_nc_delete_mp
#define nc_enddef vtk_netcdf_nc_enddef
#define nc_free_string vtk_netcdf_nc_free_string
#define nc_free_vlen vtk_netcdf_nc_free_vlen
#define nc_free_vlens vtk_netcdf_nc_free_vlens
#define nc_get_NC vtk_netcdf_nc_get_NC
#define nc_get_att vtk_netcdf_nc_get_att
#define nc_get_att_double vtk_netcdf_nc_get_att_double
#define nc_get_att_float vtk_netcdf_nc_get_att_float
#define nc_get_att_int vtk_netcdf_nc_get_att_int
#define nc_get_att_long vtk_netcdf_nc_get_att_long
#define nc_get_att_longlong vtk_netcdf_nc_get_att_longlong
#define nc_get_att_schar vtk_netcdf_nc_get_att_schar
#define nc_get_att_short vtk_netcdf_nc_get_att_short
#define nc_get_att_string vtk_netcdf_nc_get_att_string
#define nc_get_att_text vtk_netcdf_nc_get_att_text
#define nc_get_att_ubyte vtk_netcdf_nc_get_att_ubyte
#define nc_get_att_uchar vtk_netcdf_nc_get_att_uchar
#define nc_get_att_uint vtk_netcdf_nc_get_att_uint
#define nc_get_att_ulonglong vtk_netcdf_nc_get_att_ulonglong
#define nc_get_att_ushort vtk_netcdf_nc_get_att_ushort
#define nc_get_chunk_cache vtk_netcdf_nc_get_chunk_cache
#define nc_get_chunk_cache_ints vtk_netcdf_nc_get_chunk_cache_ints
#define nc_get_var vtk_netcdf_nc_get_var
#define nc_get_var1 vtk_netcdf_nc_get_var1
#define nc_get_var1_double vtk_netcdf_nc_get_var1_double
#define nc_get_var1_float vtk_netcdf_nc_get_var1_float
#define nc_get_var1_int vtk_netcdf_nc_get_var1_int
#define nc_get_var1_long vtk_netcdf_nc_get_var1_long
#define nc_get_var1_longlong vtk_netcdf_nc_get_var1_longlong
#define nc_get_var1_schar vtk_netcdf_nc_get_var1_schar
#define nc_get_var1_short vtk_netcdf_nc_get_var1_short
#define nc_get_var1_string vtk_netcdf_nc_get_var1_string
#define nc_get_var1_text vtk_netcdf_nc_get_var1_text
#define nc_get_var1_ubyte vtk_netcdf_nc_get_var1_ubyte
#define nc_get_var1_uchar vtk_netcdf_nc_get_var1_uchar
#define nc_get_var1_uint vtk_netcdf_nc_get_var1_uint
#define nc_get_var1_ulonglong vtk_netcdf_nc_get_var1_ulonglong
#define nc_get_var1_ushort vtk_netcdf_nc_get_var1_ushort
#define nc_get_var_chunk_cache vtk_netcdf_nc_get_var_chunk_cache
#define nc_get_var_chunk_cache_ints vtk_netcdf_nc_get_var_chunk_cache_ints
#define nc_get_var_double vtk_netcdf_nc_get_var_double
#define nc_get_var_float vtk_netcdf_nc_get_var_float
#define nc_get_var_int vtk_netcdf_nc_get_var_int
#define nc_get_var_long vtk_netcdf_nc_get_var_long
#define nc_get_var_longlong vtk_netcdf_nc_get_var_longlong
#define nc_get_var_schar vtk_netcdf_nc_get_var_schar
#define nc_get_var_short vtk_netcdf_nc_get_var_short
#define nc_get_var_string vtk_netcdf_nc_get_var_string
#define nc_get_var_text vtk_netcdf_nc_get_var_text
#define nc_get_var_ubyte vtk_netcdf_nc_get_var_ubyte
#define nc_get_var_uchar vtk_netcdf_nc_get_var_uchar
#define nc_get_var_uint vtk_netcdf_nc_get_var_uint
#define nc_get_var_ulonglong vtk_netcdf_nc_get_var_ulonglong
#define nc_get_var_ushort vtk_netcdf_nc_get_var_ushort
#define nc_get_vara vtk_netcdf_nc_get_vara
#define nc_get_vara_double vtk_netcdf_nc_get_vara_double
#define nc_get_vara_float vtk_netcdf_nc_get_vara_float
#define nc_get_vara_int vtk_netcdf_nc_get_vara_int
#define nc_get_vara_long vtk_netcdf_nc_get_vara_long
#define nc_get_vara_longlong vtk_netcdf_nc_get_vara_longlong
#define nc_get_vara_schar vtk_netcdf_nc_get_vara_schar
#define nc_get_vara_short vtk_netcdf_nc_get_vara_short
#define nc_get_vara_string vtk_netcdf_nc_get_vara_string
#define nc_get_vara_text vtk_netcdf_nc_get_vara_text
#define nc_get_vara_ubyte vtk_netcdf_nc_get_vara_ubyte
#define nc_get_vara_uchar vtk_netcdf_nc_get_vara_uchar
#define nc_get_vara_uint vtk_netcdf_nc_get_vara_uint
#define nc_get_vara_ulonglong vtk_netcdf_nc_get_vara_ulonglong
#define nc_get_vara_ushort vtk_netcdf_nc_get_vara_ushort
#define nc_get_varm vtk_netcdf_nc_get_varm
#define nc_get_varm_double vtk_netcdf_nc_get_varm_double
#define nc_get_varm_float vtk_netcdf_nc_get_varm_float
#define nc_get_varm_int vtk_netcdf_nc_get_varm_int
#define nc_get_varm_long vtk_netcdf_nc_get_varm_long
#define nc_get_varm_longlong vtk_netcdf_nc_get_varm_longlong
#define nc_get_varm_schar vtk_netcdf_nc_get_varm_schar
#define nc_get_varm_short vtk_netcdf_nc_get_varm_short
#define nc_get_varm_string vtk_netcdf_nc_get_varm_string
#define nc_get_varm_text vtk_netcdf_nc_get_varm_text
#define nc_get_varm_ubyte vtk_netcdf_nc_get_varm_ubyte
#define nc_get_varm_uchar vtk_netcdf_nc_get_varm_uchar
#define nc_get_varm_uint vtk_netcdf_nc_get_varm_uint
#define nc_get_varm_ulonglong vtk_netcdf_nc_get_varm_ulonglong
#define nc_get_varm_ushort vtk_netcdf_nc_get_varm_ushort
#define nc_get_vars vtk_netcdf_nc_get_vars
#define nc_get_vars_double vtk_netcdf_nc_get_vars_double
#define nc_get_vars_float vtk_netcdf_nc_get_vars_float
#define nc_get_vars_int vtk_netcdf_nc_get_vars_int
#define nc_get_vars_long vtk_netcdf_nc_get_vars_long
#define nc_get_vars_longlong vtk_netcdf_nc_get_vars_longlong
#define nc_get_vars_schar vtk_netcdf_nc_get_vars_schar
#define nc_get_vars_short vtk_netcdf_nc_get_vars_short
#define nc_get_vars_string vtk_netcdf_nc_get_vars_string
#define nc_get_vars_text vtk_netcdf_nc_get_vars_text
#define nc_get_vars_ubyte vtk_netcdf_nc_get_vars_ubyte
#define nc_get_vars_uchar vtk_netcdf_nc_get_vars_uchar
#define nc_get_vars_uint vtk_netcdf_nc_get_vars_uint
#define nc_get_vars_ulonglong vtk_netcdf_nc_get_vars_ulonglong
#define nc_get_vars_ushort vtk_netcdf_nc_get_vars_ushort
#define nc_get_vlen_element vtk_netcdf_nc_get_vlen_element
#define nc_inq vtk_netcdf_nc_inq
#define nc_inq_att vtk_netcdf_nc_inq_att
#define nc_inq_attid vtk_netcdf_nc_inq_attid
#define nc_inq_attlen vtk_netcdf_nc_inq_attlen
#define nc_inq_attname vtk_netcdf_nc_inq_attname
#define nc_inq_atttype vtk_netcdf_nc_inq_atttype
#define nc_inq_base_pe vtk_netcdf_nc_inq_base_pe
#define nc_inq_compound vtk_netcdf_nc_inq_compound
#define nc_inq_compound_field vtk_netcdf_nc_inq_compound_field
#define nc_inq_compound_fielddim_sizes vtk_netcdf_nc_inq_compound_fielddim_sizes
#define nc_inq_compound_fieldindex vtk_netcdf_nc_inq_compound_fieldindex
#define nc_inq_compound_fieldname vtk_netcdf_nc_inq_compound_fieldname
#define nc_inq_compound_fieldndims vtk_netcdf_nc_inq_compound_fieldndims
#define nc_inq_compound_fieldoffset vtk_netcdf_nc_inq_compound_fieldoffset
#define nc_inq_compound_fieldtype vtk_netcdf_nc_inq_compound_fieldtype
#define nc_inq_compound_name vtk_netcdf_nc_inq_compound_name
#define nc_inq_compound_nfields vtk_netcdf_nc_inq_compound_nfields
#define nc_inq_compound_size vtk_netcdf_nc_inq_compound_size
#define nc_inq_dim vtk_netcdf_nc_inq_dim
#define nc_inq_dimid vtk_netcdf_nc_inq_dimid
#define nc_inq_dimids vtk_netcdf_nc_inq_dimids
#define nc_inq_dimlen vtk_netcdf_nc_inq_dimlen
#define nc_inq_dimname vtk_netcdf_nc_inq_dimname
#define nc_inq_enum vtk_netcdf_nc_inq_enum
#define nc_inq_enum_ident vtk_netcdf_nc_inq_enum_ident
#define nc_inq_enum_member vtk_netcdf_nc_inq_enum_member
#define nc_inq_format vtk_netcdf_nc_inq_format
#define nc_inq_grp_full_ncid vtk_netcdf_nc_inq_grp_full_ncid
#define nc_inq_grp_ncid vtk_netcdf_nc_inq_grp_ncid
#define nc_inq_grp_parent vtk_netcdf_nc_inq_grp_parent
#define nc_inq_grpname vtk_netcdf_nc_inq_grpname
#define nc_inq_grpname_full vtk_netcdf_nc_inq_grpname_full
#define nc_inq_grpname_len vtk_netcdf_nc_inq_grpname_len
#define nc_inq_grps vtk_netcdf_nc_inq_grps
#define nc_inq_libvers vtk_netcdf_nc_inq_libvers
#define nc_inq_natts vtk_netcdf_nc_inq_natts
#define nc_inq_ncid vtk_netcdf_nc_inq_ncid
#define nc_inq_ndims vtk_netcdf_nc_inq_ndims
#define nc_inq_nvars vtk_netcdf_nc_inq_nvars
#define nc_inq_opaque vtk_netcdf_nc_inq_opaque
#define nc_inq_path vtk_netcdf_nc_inq_path
#define nc_inq_type vtk_netcdf_nc_inq_type
#define nc_inq_type_equal vtk_netcdf_nc_inq_type_equal
#define nc_inq_typeid vtk_netcdf_nc_inq_typeid
#define nc_inq_typeids vtk_netcdf_nc_inq_typeids
#define nc_inq_unlimdim vtk_netcdf_nc_inq_unlimdim
#define nc_inq_unlimdims vtk_netcdf_nc_inq_unlimdims
#define nc_inq_user_type vtk_netcdf_nc_inq_user_type
#define nc_inq_var vtk_netcdf_nc_inq_var
#define nc_inq_var_chunking vtk_netcdf_nc_inq_var_chunking
#define nc_inq_var_chunking_ints vtk_netcdf_nc_inq_var_chunking_ints
#define nc_inq_var_deflate vtk_netcdf_nc_inq_var_deflate
#define nc_inq_var_endian vtk_netcdf_nc_inq_var_endian
#define nc_inq_var_fill vtk_netcdf_nc_inq_var_fill
#define nc_inq_var_fletcher32 vtk_netcdf_nc_inq_var_fletcher32
#define nc_inq_var_szip vtk_netcdf_nc_inq_var_szip
#define nc_inq_vardimid vtk_netcdf_nc_inq_vardimid
#define nc_inq_varid vtk_netcdf_nc_inq_varid
#define nc_inq_varids vtk_netcdf_nc_inq_varids
#define nc_inq_varname vtk_netcdf_nc_inq_varname
#define nc_inq_varnatts vtk_netcdf_nc_inq_varnatts
#define nc_inq_varndims vtk_netcdf_nc_inq_varndims
#define nc_inq_vartype vtk_netcdf_nc_inq_vartype
#define nc_inq_vlen vtk_netcdf_nc_inq_vlen
#define nc_insert_array_compound vtk_netcdf_nc_insert_array_compound
#define nc_insert_compound vtk_netcdf_nc_insert_compound
#define nc_insert_enum vtk_netcdf_nc_insert_enum
#define nc_open vtk_netcdf_nc_open
#define nc_open_par vtk_netcdf_nc_open_par
#define nc_open_par_fortran vtk_netcdf_nc_open_par_fortran
#define nc_put_att vtk_netcdf_nc_put_att
#define nc_put_att_double vtk_netcdf_nc_put_att_double
#define nc_put_att_float vtk_netcdf_nc_put_att_float
#define nc_put_att_int vtk_netcdf_nc_put_att_int
#define nc_put_att_long vtk_netcdf_nc_put_att_long
#define nc_put_att_longlong vtk_netcdf_nc_put_att_longlong
#define nc_put_att_schar vtk_netcdf_nc_put_att_schar
#define nc_put_att_short vtk_netcdf_nc_put_att_short
#define nc_put_att_string vtk_netcdf_nc_put_att_string
#define nc_put_att_text vtk_netcdf_nc_put_att_text
#define nc_put_att_ubyte vtk_netcdf_nc_put_att_ubyte
#define nc_put_att_uchar vtk_netcdf_nc_put_att_uchar
#define nc_put_att_uint vtk_netcdf_nc_put_att_uint
#define nc_put_att_ulonglong vtk_netcdf_nc_put_att_ulonglong
#define nc_put_att_ushort vtk_netcdf_nc_put_att_ushort
#define nc_put_var vtk_netcdf_nc_put_var
#define nc_put_var1 vtk_netcdf_nc_put_var1
#define nc_put_var1_double vtk_netcdf_nc_put_var1_double
#define nc_put_var1_float vtk_netcdf_nc_put_var1_float
#define nc_put_var1_int vtk_netcdf_nc_put_var1_int
#define nc_put_var1_long vtk_netcdf_nc_put_var1_long
#define nc_put_var1_longlong vtk_netcdf_nc_put_var1_longlong
#define nc_put_var1_schar vtk_netcdf_nc_put_var1_schar
#define nc_put_var1_short vtk_netcdf_nc_put_var1_short
#define nc_put_var1_string vtk_netcdf_nc_put_var1_string
#define nc_put_var1_text vtk_netcdf_nc_put_var1_text
#define nc_put_var1_ubyte vtk_netcdf_nc_put_var1_ubyte
#define nc_put_var1_uchar vtk_netcdf_nc_put_var1_uchar
#define nc_put_var1_uint vtk_netcdf_nc_put_var1_uint
#define nc_put_var1_ulonglong vtk_netcdf_nc_put_var1_ulonglong
#define nc_put_var1_ushort vtk_netcdf_nc_put_var1_ushort
#define nc_put_var_double vtk_netcdf_nc_put_var_double
#define nc_put_var_float vtk_netcdf_nc_put_var_float
#define nc_put_var_int vtk_netcdf_nc_put_var_int
#define nc_put_var_long vtk_netcdf_nc_put_var_long
#define nc_put_var_longlong vtk_netcdf_nc_put_var_longlong
#define nc_put_var_schar vtk_netcdf_nc_put_var_schar
#define nc_put_var_short vtk_netcdf_nc_put_var_short
#define nc_put_var_string vtk_netcdf_nc_put_var_string
#define nc_put_var_text vtk_netcdf_nc_put_var_text
#define nc_put_var_ubyte vtk_netcdf_nc_put_var_ubyte
#define nc_put_var_uchar vtk_netcdf_nc_put_var_uchar
#define nc_put_var_uint vtk_netcdf_nc_put_var_uint
#define nc_put_var_ulonglong vtk_netcdf_nc_put_var_ulonglong
#define nc_put_var_ushort vtk_netcdf_nc_put_var_ushort
#define nc_put_vara vtk_netcdf_nc_put_vara
#define nc_put_vara_double vtk_netcdf_nc_put_vara_double
#define nc_put_vara_float vtk_netcdf_nc_put_vara_float
#define nc_put_vara_int vtk_netcdf_nc_put_vara_int
#define nc_put_vara_long vtk_netcdf_nc_put_vara_long
#define nc_put_vara_longlong vtk_netcdf_nc_put_vara_longlong
#define nc_put_vara_schar vtk_netcdf_nc_put_vara_schar
#define nc_put_vara_short vtk_netcdf_nc_put_vara_short
#define nc_put_vara_string vtk_netcdf_nc_put_vara_string
#define nc_put_vara_text vtk_netcdf_nc_put_vara_text
#define nc_put_vara_ubyte vtk_netcdf_nc_put_vara_ubyte
#define nc_put_vara_uchar vtk_netcdf_nc_put_vara_uchar
#define nc_put_vara_uint vtk_netcdf_nc_put_vara_uint
#define nc_put_vara_ulonglong vtk_netcdf_nc_put_vara_ulonglong
#define nc_put_vara_ushort vtk_netcdf_nc_put_vara_ushort
#define nc_put_varm vtk_netcdf_nc_put_varm
#define nc_put_varm_double vtk_netcdf_nc_put_varm_double
#define nc_put_varm_float vtk_netcdf_nc_put_varm_float
#define nc_put_varm_int vtk_netcdf_nc_put_varm_int
#define nc_put_varm_long vtk_netcdf_nc_put_varm_long
#define nc_put_varm_longlong vtk_netcdf_nc_put_varm_longlong
#define nc_put_varm_schar vtk_netcdf_nc_put_varm_schar
#define nc_put_varm_short vtk_netcdf_nc_put_varm_short
#define nc_put_varm_string vtk_netcdf_nc_put_varm_string
#define nc_put_varm_text vtk_netcdf_nc_put_varm_text
#define nc_put_varm_ubyte vtk_netcdf_nc_put_varm_ubyte
#define nc_put_varm_uchar vtk_netcdf_nc_put_varm_uchar
#define nc_put_varm_uint vtk_netcdf_nc_put_varm_uint
#define nc_put_varm_ulonglong vtk_netcdf_nc_put_varm_ulonglong
#define nc_put_varm_ushort vtk_netcdf_nc_put_varm_ushort
#define nc_put_vars vtk_netcdf_nc_put_vars
#define nc_put_vars_double vtk_netcdf_nc_put_vars_double
#define nc_put_vars_float vtk_netcdf_nc_put_vars_float
#define nc_put_vars_int vtk_netcdf_nc_put_vars_int
#define nc_put_vars_long vtk_netcdf_nc_put_vars_long
#define nc_put_vars_longlong vtk_netcdf_nc_put_vars_longlong
#define nc_put_vars_schar vtk_netcdf_nc_put_vars_schar
#define nc_put_vars_short vtk_netcdf_nc_put_vars_short
#define nc_put_vars_string vtk_netcdf_nc_put_vars_string
#define nc_put_vars_text vtk_netcdf_nc_put_vars_text
#define nc_put_vars_ubyte vtk_netcdf_nc_put_vars_ubyte
#define nc_put_vars_uchar vtk_netcdf_nc_put_vars_uchar
#define nc_put_vars_uint vtk_netcdf_nc_put_vars_uint
#define nc_put_vars_ulonglong vtk_netcdf_nc_put_vars_ulonglong
#define nc_put_vars_ushort vtk_netcdf_nc_put_vars_ushort
#define nc_put_vlen_element vtk_netcdf_nc_put_vlen_element
#define nc_redef vtk_netcdf_nc_redef
#define nc_rename_att vtk_netcdf_nc_rename_att
#define nc_rename_dim vtk_netcdf_nc_rename_dim
#define nc_rename_var vtk_netcdf_nc_rename_var
#define nc_set_base_pe vtk_netcdf_nc_set_base_pe
#define nc_set_chunk_cache vtk_netcdf_nc_set_chunk_cache
#define nc_set_chunk_cache_ints vtk_netcdf_nc_set_chunk_cache_ints
#define nc_set_default_format vtk_netcdf_nc_set_default_format
#define nc_set_fill vtk_netcdf_nc_set_fill
#define nc_set_var_chunk_cache vtk_netcdf_nc_set_var_chunk_cache
#define nc_set_var_chunk_cache_ints vtk_netcdf_nc_set_var_chunk_cache_ints
#define nc_show_metadata vtk_netcdf_nc_show_metadata
#define nc_strerror vtk_netcdf_nc_strerror
#define nc_sync vtk_netcdf_nc_sync
#define nc_urldecodeparams vtk_netcdf_nc_urldecodeparams
#define nc_urlfree vtk_netcdf_nc_urlfree
#define nc_urllookup vtk_netcdf_nc_urllookup
#define nc_urllookupvalue vtk_netcdf_nc_urllookupvalue
#define nc_urlparse vtk_netcdf_nc_urlparse
#define nc_urlsetconstraints vtk_netcdf_nc_urlsetconstraints
#define nc_urlsetprotocol vtk_netcdf_nc_urlsetprotocol
#define nc_var_par_access vtk_netcdf_nc_var_par_access
#define ncbytesappend vtk_netcdf_ncbytesappend
#define ncbytesappendn vtk_netcdf_ncbytesappendn
#define ncbytescat vtk_netcdf_ncbytescat
#define ncbytesdup vtk_netcdf_ncbytesdup
#define ncbytesextract vtk_netcdf_ncbytesextract
#define ncbytesfill vtk_netcdf_ncbytesfill
#define ncbytesfree vtk_netcdf_ncbytesfree
#define ncbytesget vtk_netcdf_ncbytesget
#define ncbytesnew vtk_netcdf_ncbytesnew
#define ncbytesnull vtk_netcdf_ncbytesnull
#define ncbytesprepend vtk_netcdf_ncbytesprepend
#define ncbytesset vtk_netcdf_ncbytesset
#define ncbytessetalloc vtk_netcdf_ncbytessetalloc
#define ncbytessetcontents vtk_netcdf_ncbytessetcontents
#define ncbytessetlength vtk_netcdf_ncbytessetlength
#define ncio_close vtk_netcdf_ncio_close
#define ncio_create vtk_netcdf_ncio_create
#define ncio_filesize vtk_netcdf_ncio_filesize
#define ncio_open vtk_netcdf_ncio_open
#define ncio_pad_length vtk_netcdf_ncio_pad_length
#define nclistclone vtk_netcdf_nclistclone
#define nclistcontains vtk_netcdf_nclistcontains
#define nclistdup vtk_netcdf_nclistdup
#define nclistfree vtk_netcdf_nclistfree
#define nclistget vtk_netcdf_nclistget
#define nclistinsert vtk_netcdf_nclistinsert
#define nclistnew vtk_netcdf_nclistnew
#define nclistnull vtk_netcdf_nclistnull
#define nclistpop vtk_netcdf_nclistpop
#define nclistpush vtk_netcdf_nclistpush
#define nclistremove vtk_netcdf_nclistremove
#define nclistset vtk_netcdf_nclistset
#define nclistsetalloc vtk_netcdf_nclistsetalloc
#define nclistsetlength vtk_netcdf_nclistsetlength
#define nclisttop vtk_netcdf_nclisttop
#define nclistunique vtk_netcdf_nclistunique
#define nctypelen vtk_netcdf_nctypelen
#define ncx_get_double_double vtk_netcdf_ncx_get_double_double
#define ncx_get_double_float vtk_netcdf_ncx_get_double_float
#define ncx_get_double_int vtk_netcdf_ncx_get_double_int
#define ncx_get_double_longlong vtk_netcdf_ncx_get_double_longlong
#define ncx_get_double_schar vtk_netcdf_ncx_get_double_schar
#define ncx_get_double_short vtk_netcdf_ncx_get_double_short
#define ncx_get_double_uchar vtk_netcdf_ncx_get_double_uchar
#define ncx_get_double_uint vtk_netcdf_ncx_get_double_uint
#define ncx_get_double_ulonglong vtk_netcdf_ncx_get_double_ulonglong
#define ncx_get_float_double vtk_netcdf_ncx_get_float_double
#define ncx_get_float_float vtk_netcdf_ncx_get_float_float
#define ncx_get_float_int vtk_netcdf_ncx_get_float_int
#define ncx_get_float_longlong vtk_netcdf_ncx_get_float_longlong
#define ncx_get_float_schar vtk_netcdf_ncx_get_float_schar
#define ncx_get_float_short vtk_netcdf_ncx_get_float_short
#define ncx_get_float_uchar vtk_netcdf_ncx_get_float_uchar
#define ncx_get_float_uint vtk_netcdf_ncx_get_float_uint
#define ncx_get_float_ulonglong vtk_netcdf_ncx_get_float_ulonglong
#define ncx_get_int_double vtk_netcdf_ncx_get_int_double
#define ncx_get_int_float vtk_netcdf_ncx_get_int_float
#define ncx_get_int_int vtk_netcdf_ncx_get_int_int
#define ncx_get_int_longlong vtk_netcdf_ncx_get_int_longlong
#define ncx_get_int_schar vtk_netcdf_ncx_get_int_schar
#define ncx_get_int_short vtk_netcdf_ncx_get_int_short
#define ncx_get_int_uchar vtk_netcdf_ncx_get_int_uchar
#define ncx_get_int_uint vtk_netcdf_ncx_get_int_uint
#define ncx_get_int_ulonglong vtk_netcdf_ncx_get_int_ulonglong
#define ncx_get_off_t vtk_netcdf_ncx_get_off_t
#define ncx_get_short_double vtk_netcdf_ncx_get_short_double
#define ncx_get_short_float vtk_netcdf_ncx_get_short_float
#define ncx_get_short_int vtk_netcdf_ncx_get_short_int
#define ncx_get_short_longlong vtk_netcdf_ncx_get_short_longlong
#define ncx_get_short_schar vtk_netcdf_ncx_get_short_schar
#define ncx_get_short_short vtk_netcdf_ncx_get_short_short
#define ncx_get_short_uchar vtk_netcdf_ncx_get_short_uchar
#define ncx_get_short_uint vtk_netcdf_ncx_get_short_uint
#define ncx_get_short_ulonglong vtk_netcdf_ncx_get_short_ulonglong
#define ncx_get_size_t vtk_netcdf_ncx_get_size_t
#define ncx_getn_double_double vtk_netcdf_ncx_getn_double_double
#define ncx_getn_double_float vtk_netcdf_ncx_getn_double_float
#define ncx_getn_double_int vtk_netcdf_ncx_getn_double_int
#define ncx_getn_double_longlong vtk_netcdf_ncx_getn_double_longlong
#define ncx_getn_double_schar vtk_netcdf_ncx_getn_double_schar
#define ncx_getn_double_short vtk_netcdf_ncx_getn_double_short
#define ncx_getn_double_uchar vtk_netcdf_ncx_getn_double_uchar
#define ncx_getn_double_uint vtk_netcdf_ncx_getn_double_uint
#define ncx_getn_double_ulonglong vtk_netcdf_ncx_getn_double_ulonglong
#define ncx_getn_float_double vtk_netcdf_ncx_getn_float_double
#define ncx_getn_float_float vtk_netcdf_ncx_getn_float_float
#define ncx_getn_float_int vtk_netcdf_ncx_getn_float_int
#define ncx_getn_float_longlong vtk_netcdf_ncx_getn_float_longlong
#define ncx_getn_float_schar vtk_netcdf_ncx_getn_float_schar
#define ncx_getn_float_short vtk_netcdf_ncx_getn_float_short
#define ncx_getn_float_uchar vtk_netcdf_ncx_getn_float_uchar
#define ncx_getn_float_uint vtk_netcdf_ncx_getn_float_uint
#define ncx_getn_float_ulonglong vtk_netcdf_ncx_getn_float_ulonglong
#define ncx_getn_int_double vtk_netcdf_ncx_getn_int_double
#define ncx_getn_int_float vtk_netcdf_ncx_getn_int_float
#define ncx_getn_int_int vtk_netcdf_ncx_getn_int_int
#define ncx_getn_int_longlong vtk_netcdf_ncx_getn_int_longlong
#define ncx_getn_int_schar vtk_netcdf_ncx_getn_int_schar
#define ncx_getn_int_short vtk_netcdf_ncx_getn_int_short
#define ncx_getn_int_uchar vtk_netcdf_ncx_getn_int_uchar
#define ncx_getn_int_uint vtk_netcdf_ncx_getn_int_uint
#define ncx_getn_int_ulonglong vtk_netcdf_ncx_getn_int_ulonglong
#define ncx_getn_schar_double vtk_netcdf_ncx_getn_schar_double
#define ncx_getn_schar_float vtk_netcdf_ncx_getn_schar_float
#define ncx_getn_schar_int vtk_netcdf_ncx_getn_schar_int
#define ncx_getn_schar_longlong vtk_netcdf_ncx_getn_schar_longlong
#define ncx_getn_schar_schar vtk_netcdf_ncx_getn_schar_schar
#define ncx_getn_schar_short vtk_netcdf_ncx_getn_schar_short
#define ncx_getn_schar_uchar vtk_netcdf_ncx_getn_schar_uchar
#define ncx_getn_schar_uint vtk_netcdf_ncx_getn_schar_uint
#define ncx_getn_schar_ulonglong vtk_netcdf_ncx_getn_schar_ulonglong
#define ncx_getn_short_double vtk_netcdf_ncx_getn_short_double
#define ncx_getn_short_float vtk_netcdf_ncx_getn_short_float
#define ncx_getn_short_int vtk_netcdf_ncx_getn_short_int
#define ncx_getn_short_longlong vtk_netcdf_ncx_getn_short_longlong
#define ncx_getn_short_schar vtk_netcdf_ncx_getn_short_schar
#define ncx_getn_short_short vtk_netcdf_ncx_getn_short_short
#define ncx_getn_short_uchar vtk_netcdf_ncx_getn_short_uchar
#define ncx_getn_short_uint vtk_netcdf_ncx_getn_short_uint
#define ncx_getn_short_ulonglong vtk_netcdf_ncx_getn_short_ulonglong
#define ncx_getn_text vtk_netcdf_ncx_getn_text
#define ncx_getn_void vtk_netcdf_ncx_getn_void
#define ncx_howmany vtk_netcdf_ncx_howmany
#define ncx_len_NC vtk_netcdf_ncx_len_NC
#define ncx_pad_getn_schar_double vtk_netcdf_ncx_pad_getn_schar_double
#define ncx_pad_getn_schar_float vtk_netcdf_ncx_pad_getn_schar_float
#define ncx_pad_getn_schar_int vtk_netcdf_ncx_pad_getn_schar_int
#define ncx_pad_getn_schar_longlong vtk_netcdf_ncx_pad_getn_schar_longlong
#define ncx_pad_getn_schar_schar vtk_netcdf_ncx_pad_getn_schar_schar
#define ncx_pad_getn_schar_short vtk_netcdf_ncx_pad_getn_schar_short
#define ncx_pad_getn_schar_uchar vtk_netcdf_ncx_pad_getn_schar_uchar
#define ncx_pad_getn_schar_uint vtk_netcdf_ncx_pad_getn_schar_uint
#define ncx_pad_getn_schar_ulonglong vtk_netcdf_ncx_pad_getn_schar_ulonglong
#define ncx_pad_getn_short_double vtk_netcdf_ncx_pad_getn_short_double
#define ncx_pad_getn_short_float vtk_netcdf_ncx_pad_getn_short_float
#define ncx_pad_getn_short_int vtk_netcdf_ncx_pad_getn_short_int
#define ncx_pad_getn_short_longlong vtk_netcdf_ncx_pad_getn_short_longlong
#define ncx_pad_getn_short_schar vtk_netcdf_ncx_pad_getn_short_schar
#define ncx_pad_getn_short_short vtk_netcdf_ncx_pad_getn_short_short
#define ncx_pad_getn_short_uchar vtk_netcdf_ncx_pad_getn_short_uchar
#define ncx_pad_getn_short_uint vtk_netcdf_ncx_pad_getn_short_uint
#define ncx_pad_getn_short_ulonglong vtk_netcdf_ncx_pad_getn_short_ulonglong
#define ncx_pad_getn_text vtk_netcdf_ncx_pad_getn_text
#define ncx_pad_getn_void vtk_netcdf_ncx_pad_getn_void
#define ncx_pad_putn_schar_double vtk_netcdf_ncx_pad_putn_schar_double
#define ncx_pad_putn_schar_float vtk_netcdf_ncx_pad_putn_schar_float
#define ncx_pad_putn_schar_int vtk_netcdf_ncx_pad_putn_schar_int
#define ncx_pad_putn_schar_longlong vtk_netcdf_ncx_pad_putn_schar_longlong
#define ncx_pad_putn_schar_schar vtk_netcdf_ncx_pad_putn_schar_schar
#define ncx_pad_putn_schar_short vtk_netcdf_ncx_pad_putn_schar_short
#define ncx_pad_putn_schar_uchar vtk_netcdf_ncx_pad_putn_schar_uchar
#define ncx_pad_putn_schar_uint vtk_netcdf_ncx_pad_putn_schar_uint
#define ncx_pad_putn_schar_ulonglong vtk_netcdf_ncx_pad_putn_schar_ulonglong
#define ncx_pad_putn_short_double vtk_netcdf_ncx_pad_putn_short_double
#define ncx_pad_putn_short_float vtk_netcdf_ncx_pad_putn_short_float
#define ncx_pad_putn_short_int vtk_netcdf_ncx_pad_putn_short_int
#define ncx_pad_putn_short_longlong vtk_netcdf_ncx_pad_putn_short_longlong
#define ncx_pad_putn_short_schar vtk_netcdf_ncx_pad_putn_short_schar
#define ncx_pad_putn_short_short vtk_netcdf_ncx_pad_putn_short_short
#define ncx_pad_putn_short_uchar vtk_netcdf_ncx_pad_putn_short_uchar
#define ncx_pad_putn_short_uint vtk_netcdf_ncx_pad_putn_short_uint
#define ncx_pad_putn_short_ulonglong vtk_netcdf_ncx_pad_putn_short_ulonglong
#define ncx_pad_putn_text vtk_netcdf_ncx_pad_putn_text
#define ncx_pad_putn_void vtk_netcdf_ncx_pad_putn_void
#define ncx_put_NC vtk_netcdf_ncx_put_NC
#define ncx_put_double_double vtk_netcdf_ncx_put_double_double
#define ncx_put_double_float vtk_netcdf_ncx_put_double_float
#define ncx_put_double_int vtk_netcdf_ncx_put_double_int
#define ncx_put_double_longlong vtk_netcdf_ncx_put_double_longlong
#define ncx_put_double_schar vtk_netcdf_ncx_put_double_schar
#define ncx_put_double_short vtk_netcdf_ncx_put_double_short
#define ncx_put_double_uchar vtk_netcdf_ncx_put_double_uchar
#define ncx_put_double_uint vtk_netcdf_ncx_put_double_uint
#define ncx_put_double_ulonglong vtk_netcdf_ncx_put_double_ulonglong
#define ncx_put_float_double vtk_netcdf_ncx_put_float_double
#define ncx_put_float_float vtk_netcdf_ncx_put_float_float
#define ncx_put_float_int vtk_netcdf_ncx_put_float_int
#define ncx_put_float_longlong vtk_netcdf_ncx_put_float_longlong
#define ncx_put_float_schar vtk_netcdf_ncx_put_float_schar
#define ncx_put_float_short vtk_netcdf_ncx_put_float_short
#define ncx_put_float_uchar vtk_netcdf_ncx_put_float_uchar
#define ncx_put_float_uint vtk_netcdf_ncx_put_float_uint
#define ncx_put_float_ulonglong vtk_netcdf_ncx_put_float_ulonglong
#define ncx_put_int_double vtk_netcdf_ncx_put_int_double
#define ncx_put_int_float vtk_netcdf_ncx_put_int_float
#define ncx_put_int_int vtk_netcdf_ncx_put_int_int
#define ncx_put_int_longlong vtk_netcdf_ncx_put_int_longlong
#define ncx_put_int_schar vtk_netcdf_ncx_put_int_schar
#define ncx_put_int_short vtk_netcdf_ncx_put_int_short
#define ncx_put_int_uchar vtk_netcdf_ncx_put_int_uchar
#define ncx_put_int_uint vtk_netcdf_ncx_put_int_uint
#define ncx_put_int_ulonglong vtk_netcdf_ncx_put_int_ulonglong
#define ncx_put_off_t vtk_netcdf_ncx_put_off_t
#define ncx_put_short_double vtk_netcdf_ncx_put_short_double
#define ncx_put_short_float vtk_netcdf_ncx_put_short_float
#define ncx_put_short_int vtk_netcdf_ncx_put_short_int
#define ncx_put_short_longlong vtk_netcdf_ncx_put_short_longlong
#define ncx_put_short_schar vtk_netcdf_ncx_put_short_schar
#define ncx_put_short_short vtk_netcdf_ncx_put_short_short
#define ncx_put_short_uchar vtk_netcdf_ncx_put_short_uchar
#define ncx_put_short_uint vtk_netcdf_ncx_put_short_uint
#define ncx_put_short_ulonglong vtk_netcdf_ncx_put_short_ulonglong
#define ncx_put_size_t vtk_netcdf_ncx_put_size_t
#define ncx_putn_double_double vtk_netcdf_ncx_putn_double_double
#define ncx_putn_double_float vtk_netcdf_ncx_putn_double_float
#define ncx_putn_double_int vtk_netcdf_ncx_putn_double_int
#define ncx_putn_double_longlong vtk_netcdf_ncx_putn_double_longlong
#define ncx_putn_double_schar vtk_netcdf_ncx_putn_double_schar
#define ncx_putn_double_short vtk_netcdf_ncx_putn_double_short
#define ncx_putn_double_uchar vtk_netcdf_ncx_putn_double_uchar
#define ncx_putn_double_uint vtk_netcdf_ncx_putn_double_uint
#define ncx_putn_double_ulonglong vtk_netcdf_ncx_putn_double_ulonglong
#define ncx_putn_float_double vtk_netcdf_ncx_putn_float_double
#define ncx_putn_float_float vtk_netcdf_ncx_putn_float_float
#define ncx_putn_float_int vtk_netcdf_ncx_putn_float_int
#define ncx_putn_float_longlong vtk_netcdf_ncx_putn_float_longlong
#define ncx_putn_float_schar vtk_netcdf_ncx_putn_float_schar
#define ncx_putn_float_short vtk_netcdf_ncx_putn_float_short
#define ncx_putn_float_uchar vtk_netcdf_ncx_putn_float_uchar
#define ncx_putn_float_uint vtk_netcdf_ncx_putn_float_uint
#define ncx_putn_float_ulonglong vtk_netcdf_ncx_putn_float_ulonglong
#define ncx_putn_int_double vtk_netcdf_ncx_putn_int_double
#define ncx_putn_int_float vtk_netcdf_ncx_putn_int_float
#define ncx_putn_int_int vtk_netcdf_ncx_putn_int_int
#define ncx_putn_int_longlong vtk_netcdf_ncx_putn_int_longlong
#define ncx_putn_int_schar vtk_netcdf_ncx_putn_int_schar
#define ncx_putn_int_short vtk_netcdf_ncx_putn_int_short
#define ncx_putn_int_uchar vtk_netcdf_ncx_putn_int_uchar
#define ncx_putn_int_uint vtk_netcdf_ncx_putn_int_uint
#define ncx_putn_int_ulonglong vtk_netcdf_ncx_putn_int_ulonglong
#define ncx_putn_schar_double vtk_netcdf_ncx_putn_schar_double
#define ncx_putn_schar_float vtk_netcdf_ncx_putn_schar_float
#define ncx_putn_schar_int vtk_netcdf_ncx_putn_schar_int
#define ncx_putn_schar_longlong vtk_netcdf_ncx_putn_schar_longlong
#define ncx_putn_schar_schar vtk_netcdf_ncx_putn_schar_schar
#define ncx_putn_schar_short vtk_netcdf_ncx_putn_schar_short
#define ncx_putn_schar_uchar vtk_netcdf_ncx_putn_schar_uchar
#define ncx_putn_schar_uint vtk_netcdf_ncx_putn_schar_uint
#define ncx_putn_schar_ulonglong vtk_netcdf_ncx_putn_schar_ulonglong
#define ncx_putn_short_double vtk_netcdf_ncx_putn_short_double
#define ncx_putn_short_float vtk_netcdf_ncx_putn_short_float
#define ncx_putn_short_int vtk_netcdf_ncx_putn_short_int
#define ncx_putn_short_longlong vtk_netcdf_ncx_putn_short_longlong
#define ncx_putn_short_schar vtk_netcdf_ncx_putn_short_schar
#define ncx_putn_short_short vtk_netcdf_ncx_putn_short_short
#define ncx_putn_short_uchar vtk_netcdf_ncx_putn_short_uchar
#define ncx_putn_short_uint vtk_netcdf_ncx_putn_short_uint
#define ncx_putn_short_ulonglong vtk_netcdf_ncx_putn_short_ulonglong
#define ncx_putn_text vtk_netcdf_ncx_putn_text
#define ncx_putn_void vtk_netcdf_ncx_putn_void
#define ncx_szof vtk_netcdf_ncx_szof
#define new_NC_string vtk_netcdf_new_NC_string
#define new_x_NC_attr vtk_netcdf_new_x_NC_attr
#define new_x_NC_dim vtk_netcdf_new_x_NC_dim
#define new_x_NC_var vtk_netcdf_new_x_NC_var
#define nextUTF8 vtk_netcdf_nextUTF8
#define nulldup vtk_netcdf_nulldup
#define pg_var vtk_netcdf_pg_var
#define read_numrecs vtk_netcdf_read_numrecs
#define set_NC_string vtk_netcdf_set_NC_string
#define type_list_del vtk_netcdf_type_list_del
#define utf8proc_NFC vtk_netcdf_utf8proc_NFC
#define utf8proc_NFD vtk_netcdf_utf8proc_NFD
#define utf8proc_NFKC vtk_netcdf_utf8proc_NFKC
#define utf8proc_NFKD vtk_netcdf_utf8proc_NFKD
#define utf8proc_check vtk_netcdf_utf8proc_check
#define utf8proc_codepoint_valid vtk_netcdf_utf8proc_codepoint_valid
#define utf8proc_combinations vtk_netcdf_utf8proc_combinations
#define utf8proc_decompose vtk_netcdf_utf8proc_decompose
#define utf8proc_decompose_char vtk_netcdf_utf8proc_decompose_char
#define utf8proc_encode_char vtk_netcdf_utf8proc_encode_char
#define utf8proc_errmsg vtk_netcdf_utf8proc_errmsg
#define utf8proc_get_property vtk_netcdf_utf8proc_get_property
#define utf8proc_iterate vtk_netcdf_utf8proc_iterate
#define utf8proc_map vtk_netcdf_utf8proc_map
#define utf8proc_properties vtk_netcdf_utf8proc_properties
#define utf8proc_reencode vtk_netcdf_utf8proc_reencode
#define utf8proc_sequences vtk_netcdf_utf8proc_sequences
#define utf8proc_stage1table vtk_netcdf_utf8proc_stage1table
#define utf8proc_stage2table vtk_netcdf_utf8proc_stage2table
#define utf8proc_utf8class vtk_netcdf_utf8proc_utf8class
#define write_numrecs vtk_netcdf_write_numrecs
#endif /* vtk_netcdf_mangle_h */
| [
"l”ibaojunqd@foxmail.com“"
] | l”ibaojunqd@foxmail.com“ |
9345a82407805c230cbeab1112b6cac9f252515b | a91151da47ddd7690c2a5317326f67effb7f665b | /lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h | 78476a8be095806fa7b50988469d2d93ccea0aca | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"FSFAP"
] | permissive | shivam00/thrift | 8ce84c032168760057a3282dfe2abd6c8810e420 | d81e9e3d22c130ef5ddba7b06fb9802267d9d1d7 | refs/heads/master | 2020-03-30T07:37:16.444343 | 2019-01-15T16:39:07 | 2019-01-15T16:39:07 | 150,953,345 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,780 | h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef THRIFT_TMULTIPLEXEDPROTOCOL_H_
#define THRIFT_TMULTIPLEXEDPROTOCOL_H_ 1
#include <thrift/protocol/TProtocolDecorator.h>
namespace apache {
namespace thrift {
namespace protocol {
using stdcxx::shared_ptr;
/**
* <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator
* that allows a Thrift client to communicate with a multiplexing Thrift server,
* by prepending the service name to the function name during function calls.
*
* \note THIS IS NOT USED BY SERVERS. On the server, use
* {@link apache::thrift::TMultiplexedProcessor TMultiplexedProcessor} to handle requests
* from a multiplexing client.
*
* This example uses a single socket transport to invoke two services:
*
* <blockquote><code>
* shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
* transport->open();
*
* shared_ptr<TBinaryProtocol> protocol(new TBinaryProtocol(transport));
*
* shared_ptr<TMultiplexedProtocol> mp1(new TMultiplexedProtocol(protocol, "Calculator"));
* shared_ptr<CalculatorClient> service1(new CalculatorClient(mp1));
*
* shared_ptr<TMultiplexedProtocol> mp2(new TMultiplexedProtocol(protocol, "WeatherReport"));
* shared_ptr<WeatherReportClient> service2(new WeatherReportClient(mp2));
*
* service1->add(2,2);
* int temp = service2->getTemperature();
* </code></blockquote>
*
* @see apache::thrift::protocol::TProtocolDecorator
*/
class TMultiplexedProtocol : public TProtocolDecorator {
public:
/**
* Wrap the specified protocol, allowing it to be used to communicate with a
* multiplexing server. The <code>serviceName</code> is required as it is
* prepended to the message header so that the multiplexing server can broker
* the function call to the proper service.
*
* \param _protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>.
* \param _serviceName The service name of the service communicating via this protocol.
*/
TMultiplexedProtocol(shared_ptr<TProtocol> _protocol, const std::string& _serviceName)
: TProtocolDecorator(_protocol), serviceName(_serviceName), separator(":") {}
virtual ~TMultiplexedProtocol() {}
/**
* Prepends the service name to the function name, separated by TMultiplexedProtocol::SEPARATOR.
*
* \param [in] _name The name of the method to be called in the service.
* \param [in] _type The type of message
* \param [in] _name The sequential id of the message
*
* \throws TException Passed through from wrapped <code>TProtocol</code> instance.
*/
uint32_t writeMessageBegin_virt(const std::string& _name,
const TMessageType _type,
const int32_t _seqid);
private:
const std::string serviceName;
const std::string separator;
};
}
}
}
#endif // THRIFT_TMULTIPLEXEDPROTOCOL_H_
| [
"shivam.gupta0002@gmail.com"
] | shivam.gupta0002@gmail.com |
ecb87ffbe9b356ec359fe41477226345d2a76688 | 7518a08a0b1280d86a8190b819ab4fb663df0b5e | /tests/all_tests.cpp | 56c715fc10dd81f77ffbbae883b576724d8a278a | [] | no_license | rootkit/h5cpp | a96703daa6d2a9188e6cb83f43114574399984fb | 47c42ab777c388669dafd6f66ac81902c924697c | refs/heads/master | 2021-06-22T20:51:43.658010 | 2016-07-06T18:35:47 | 2016-07-06T18:35:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | #include <iostream>
#include "boost/multi_array.hpp"
#include "hdf5.h"
#include <memory>
#include "h5file.h"
#include <vector>
using namespace std;
int main() {
//boost array properties
const int drank = 2;
using array_type = boost::multi_array<int, drank>;
//using index = array_type::index;
size_t n = 3;
//initialize the array
array_type A(boost::extents[n][n]);
for (size_t i = 0; i != n; i++) {
for (size_t j = 0; j != n; j++) {
A[i][j] = i + j;
}
}
vector<hsize_t> dims = {n,n};
vector<hsize_t> a_dims = {1};
int dx = 2;
double dt = 3.2;
int new_value = -1;
h5file f("test.h5", H5F_ACC_TRUNC);
{
auto g1 = f.create_group("/sub");
auto g2 = f.create_group("/sub/other");
}
auto g1 = f.open_group("/sub");
auto g2 = f.open_group("/sub/other");
{
auto d1 = f.create_dataset("data", H5T_NATIVE_INT, dims);
auto d2 = g1->create_dataset("data", H5T_NATIVE_INT, dims);
}
auto d3 = g2->create_dataset("data", H5T_NATIVE_INT, dims);
auto d1 = f.open_dataset("data");
auto d2 = f.open_dataset("sub/data");
d1->write(A.data());
d2->write(A.data());
d3->write(A.data());
{
auto a1 = f.create_attribute("dx", H5T_NATIVE_INT, a_dims);
auto a2 = g1->create_attribute("dx", H5T_NATIVE_INT, a_dims);
}
auto a3 = g2->create_attribute("dt", H5T_NATIVE_DOUBLE, a_dims);
auto a4 = d2->create_attribute("new", H5T_NATIVE_INT, a_dims);
auto a1 = f.open_attribute("dx");
auto a2 = f.open_attribute_by_name("dx", "/sub");
a1->write(&dx);
a2->write(&dx);
a3->write(&dt);
a4->write(&new_value);
}
| [
"japarker@uchicago.edu"
] | japarker@uchicago.edu |
aa509c293a791a7ce403fbe67b24398f3074aeac | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/cc/debug/benchmark_instrumentation.h | 909c7a34c570f338d5b35520f7f6fb36de96d5ca | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 1,331 | h | // Copyright 2013 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 CC_DEBUG_BENCHMARK_INSTRUMENTATION_H_
#define CC_DEBUG_BENCHMARK_INSTRUMENTATION_H_
#include "cc/debug/rendering_stats.h"
namespace cc {
namespace benchmark_instrumentation {
namespace internal {
const char kCategory[] = "cc,benchmark";
const char kBeginFrameId[] = "begin_frame_id";
}
const char kSendBeginFrame[] = "ThreadProxy::ScheduledActionSendBeginMainFrame";
const char kDoBeginFrame[] = "ThreadProxy::BeginMainFrame";
class ScopedBeginFrameTask {
public:
ScopedBeginFrameTask(const char* event_name, unsigned int begin_frame_id)
: event_name_(event_name) {
TRACE_EVENT_BEGIN1(internal::kCategory,
event_name_,
internal::kBeginFrameId,
begin_frame_id);
}
~ScopedBeginFrameTask() {
TRACE_EVENT_END0(internal::kCategory, event_name_);
}
private:
const char* event_name_;
DISALLOW_COPY_AND_ASSIGN(ScopedBeginFrameTask);
};
void IssueMainThreadRenderingStatsEvent(
const RenderingStats::MainThreadRenderingStats& stats);
void IssueImplThreadRenderingStatsEvent(
const RenderingStats::ImplThreadRenderingStats& stats);
}
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
90479948f0de0f47c8cf2ad124c1779b4c136820 | 01c286c750aa34f8bed760d3919e5a58539f4a8e | /Codeforces/877C.cpp | 79da333f8bc935f52a91c16db7481cce1116cb64 | [
"MIT"
] | permissive | Alipashaimani/Competitive-programming | 17686418664fb32a3f736bb4d57317dc6657b4a4 | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | refs/heads/master | 2023-04-19T03:21:22.172090 | 2021-05-06T15:30:25 | 2021-05-06T15:30:25 | 241,510,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int n; cin >> n;
cout << n + (n / 2) << '\n';
for (int i = 2; i <= n; i += 2)
cout << i << ' ';
for (int i = 1; i <= n; i += 2)
cout << i << ' ';
for (int i = 2; i <= n; i += 2)
cout << i << ' ';
return 0;
} | [
"apiv2009@icloud.com"
] | apiv2009@icloud.com |
3af878ef958ef89523c5a77214be4c4822b84654 | ebb70b0cbe7626366077cbb66a58334aaf880f49 | /slm_models/gecode.framework/Versions/48/include/gist/drawingcursor.hpp | d017500d142f44353b8c50aa4e766da8eaef044d | [
"MIT"
] | permissive | slemouton/gecodeMCP | fa06936f5159a56829a61825e90b3a297fef78dd | d038c52ffcf7351048fe5a018cee29c432d8184f | refs/heads/master | 2021-07-10T22:33:26.858361 | 2021-05-05T21:03:55 | 2021-05-05T21:03:55 | 60,289,358 | 1 | 1 | MIT | 2019-01-12T16:58:17 | 2016-06-02T18:52:11 | C++ | UTF-8 | C++ | false | false | 2,650 | hpp | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Guido Tack, 2006
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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.
*
*/
namespace Gecode { namespace Gist {
inline void
DrawingCursor::moveUpwards(void) {
x -= node()->getOffset();
y -= Layout::dist_y;
NodeCursor<VisualNode>::moveUpwards();
}
forceinline bool
DrawingCursor::isClipped(void) {
if (clippingRect.width() == 0 && clippingRect.x() == 0
&& clippingRect.height() == 0 && clippingRect.y() == 0)
return false;
BoundingBox b = node()->getBoundingBox();
return (x + b.left > clippingRect.x() + clippingRect.width() ||
x + b.right < clippingRect.x() ||
y > clippingRect.y() + clippingRect.height() ||
y + (node()->getShape()->depth()+1) * Layout::dist_y <
clippingRect.y());
}
inline bool
DrawingCursor::mayMoveDownwards(void) {
return NodeCursor<VisualNode>::mayMoveDownwards() &&
!node()->isHidden() &&
node()->childrenLayoutIsDone() &&
!isClipped();
}
inline void
DrawingCursor::moveDownwards(void) {
NodeCursor<VisualNode>::moveDownwards();
x += node()->getOffset();
y += Layout::dist_y;
}
inline void
DrawingCursor::moveSidewards(void) {
x -= node()->getOffset();
NodeCursor<VisualNode>::moveSidewards();
x += node()->getOffset();
}
}}
// STATISTICS: gist-any
| [
"lemouton@ircam.Fr"
] | lemouton@ircam.Fr |
dc7bb473f0af0c9dc3dc8e5a9544d870e4fc7e47 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/blink/renderer/core/animation/timing_calculations.h | 256a1e132b89a11b011b66a06ec992371fe119d8 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 18,347 | h | /*
* Copyright (C) 2013 Google Inc. 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 Google Inc. 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
* 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.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_TIMING_CALCULATIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_TIMING_CALCULATIONS_H_
#include "base/notreached.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/animation/timing.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
namespace {
inline bool EndsOnIterationBoundary(double iteration_count,
double iteration_start) {
DCHECK(std::isfinite(iteration_count));
return !fmod(iteration_count + iteration_start, 1);
}
} // namespace
static inline double TimingCalculationEpsilon() {
// Permit 2-bits of quantization error. Threshold based on experimentation
// with accuracy of fmod.
return 2.0 * std::numeric_limits<double>::epsilon();
}
static inline AnimationTimeDelta TimeTolerance() {
return ANIMATION_TIME_DELTA_FROM_SECONDS(0.000001 /*one microsecond*/);
}
static inline bool IsWithinAnimationTimeEpsilon(double a, double b) {
return std::abs(a - b) <= TimingCalculationEpsilon();
}
static inline bool IsWithinAnimationTimeTolerance(AnimationTimeDelta a,
AnimationTimeDelta b) {
if (a.is_inf() || b.is_inf()) {
return a == b;
}
AnimationTimeDelta difference = a >= b ? a - b : b - a;
return difference <= TimeTolerance();
}
static inline bool LessThanOrEqualToWithinEpsilon(double a, double b) {
return a <= b + TimingCalculationEpsilon();
}
static inline bool LessThanOrEqualToWithinTimeTolerance(AnimationTimeDelta a,
AnimationTimeDelta b) {
return a <= b + TimeTolerance();
}
static inline bool GreaterThanOrEqualToWithinEpsilon(double a, double b) {
return a >= b - TimingCalculationEpsilon();
}
static inline bool GreaterThanOrEqualToWithinTimeTolerance(
AnimationTimeDelta a,
AnimationTimeDelta b) {
return a >= b - TimeTolerance();
}
static inline bool GreaterThanWithinTimeTolerance(AnimationTimeDelta a,
AnimationTimeDelta b) {
return a > b - TimeTolerance();
}
static inline double MultiplyZeroAlwaysGivesZero(double x, double y) {
DCHECK(!std::isnan(x));
DCHECK(!std::isnan(y));
return x && y ? x * y : 0;
}
static inline AnimationTimeDelta MultiplyZeroAlwaysGivesZero(
AnimationTimeDelta x,
double y) {
DCHECK(!std::isnan(y));
return x.is_zero() || y == 0 ? AnimationTimeDelta() : (x * y);
}
// https://w3.org/TR/web-animations-1/#animation-effect-phases-and-states
static inline Timing::Phase CalculatePhase(
const Timing::NormalizedTiming& normalized,
absl::optional<AnimationTimeDelta>& local_time,
bool at_progress_timeline_boundary,
Timing::AnimationDirection direction) {
DCHECK(GreaterThanOrEqualToWithinTimeTolerance(normalized.active_duration,
AnimationTimeDelta()));
if (!local_time)
return Timing::kPhaseNone;
AnimationTimeDelta before_active_boundary_time =
std::max(std::min(normalized.start_delay, normalized.end_time),
AnimationTimeDelta());
if (IsWithinAnimationTimeTolerance(local_time.value(),
before_active_boundary_time)) {
local_time = before_active_boundary_time;
}
if (local_time.value() < before_active_boundary_time ||
(direction == Timing::AnimationDirection::kBackwards &&
local_time.value() == before_active_boundary_time &&
!at_progress_timeline_boundary)) {
return Timing::kPhaseBefore;
}
AnimationTimeDelta active_after_boundary_time =
std::max(std::min(normalized.start_delay + normalized.active_duration,
normalized.end_time),
AnimationTimeDelta());
if (IsWithinAnimationTimeTolerance(local_time.value(),
active_after_boundary_time)) {
local_time = active_after_boundary_time;
}
if (local_time.value() > active_after_boundary_time ||
(direction == Timing::AnimationDirection::kForwards &&
local_time.value() == active_after_boundary_time &&
!at_progress_timeline_boundary)) {
return Timing::kPhaseAfter;
}
return Timing::kPhaseActive;
}
// https://w3.org/TR/web-animations-1/#calculating-the-active-time
static inline absl::optional<AnimationTimeDelta> CalculateActiveTime(
const Timing::NormalizedTiming& normalized,
Timing::FillMode fill_mode,
absl::optional<AnimationTimeDelta> local_time,
Timing::Phase phase) {
DCHECK(GreaterThanOrEqualToWithinTimeTolerance(normalized.active_duration,
AnimationTimeDelta()));
switch (phase) {
case Timing::kPhaseBefore:
if (fill_mode == Timing::FillMode::BACKWARDS ||
fill_mode == Timing::FillMode::BOTH) {
DCHECK(local_time.has_value());
return std::max(local_time.value() - normalized.start_delay,
AnimationTimeDelta());
}
return absl::nullopt;
case Timing::kPhaseActive:
DCHECK(local_time.has_value());
return local_time.value() - normalized.start_delay;
case Timing::kPhaseAfter:
if (fill_mode == Timing::FillMode::FORWARDS ||
fill_mode == Timing::FillMode::BOTH) {
DCHECK(local_time.has_value());
return std::max(AnimationTimeDelta(),
std::min(normalized.active_duration,
local_time.value() - normalized.start_delay));
}
return absl::nullopt;
case Timing::kPhaseNone:
DCHECK(!local_time.has_value());
return absl::nullopt;
default:
NOTREACHED();
return absl::nullopt;
}
}
// Calculates the overall progress, which describes the number of iterations
// that have completed (including partial iterations).
// https://w3.org/TR/web-animations-1/#calculating-the-overall-progress
static inline absl::optional<double> CalculateOverallProgress(
Timing::Phase phase,
absl::optional<AnimationTimeDelta> active_time,
AnimationTimeDelta iteration_duration,
double iteration_count,
double iteration_start) {
// 1. If the active time is unresolved, return unresolved.
if (!active_time)
return absl::nullopt;
// 2. Calculate an initial value for overall progress.
double overall_progress = 0;
if (IsWithinAnimationTimeTolerance(iteration_duration,
AnimationTimeDelta())) {
if (phase != Timing::kPhaseBefore)
overall_progress = iteration_count;
} else {
overall_progress = (active_time.value() / iteration_duration);
}
return overall_progress + iteration_start;
}
// Calculates the simple iteration progress, which is a fraction of the progress
// through the current iteration that ignores transformations to the time
// introduced by the playback direction or timing functions applied to the
// effect.
// https://w3.org/TR/web-animations-1/#calculating-the-simple-iteration-progress
static inline absl::optional<double> CalculateSimpleIterationProgress(
Timing::Phase phase,
absl::optional<double> overall_progress,
double iteration_start,
absl::optional<AnimationTimeDelta> active_time,
AnimationTimeDelta active_duration,
double iteration_count) {
// 1. If the overall progress is unresolved, return unresolved.
if (!overall_progress)
return absl::nullopt;
// 2. If overall progress is infinity, let the simple iteration progress be
// iteration start % 1.0, otherwise, let the simple iteration progress be
// overall progress % 1.0.
double simple_iteration_progress = std::isinf(overall_progress.value())
? fmod(iteration_start, 1.0)
: fmod(overall_progress.value(), 1.0);
// active_time is not null is because overall_progress != null and
// CalculateOverallProgress() only returns null when active_time is null.
DCHECK(active_time);
// 3. If all of the following conditions are true,
// * the simple iteration progress calculated above is zero, and
// * the animation effect is in the active phase or the after phase, and
// * the active time is equal to the active duration, and
// * the iteration count is not equal to zero.
// let the simple iteration progress be 1.0.
if (IsWithinAnimationTimeEpsilon(simple_iteration_progress, 0.0) &&
(phase == Timing::kPhaseActive || phase == Timing::kPhaseAfter) &&
IsWithinAnimationTimeTolerance(active_time.value(), active_duration) &&
!IsWithinAnimationTimeEpsilon(iteration_count, 0.0)) {
simple_iteration_progress = 1.0;
}
// 4. Return simple iteration progress.
return simple_iteration_progress;
}
// https://w3.org/TR/web-animations-1/#calculating-the-current-iteration
static inline absl::optional<double> CalculateCurrentIteration(
Timing::Phase phase,
absl::optional<AnimationTimeDelta> active_time,
double iteration_count,
absl::optional<double> overall_progress,
absl::optional<double> simple_iteration_progress) {
// 1. If the active time is unresolved, return unresolved.
if (!active_time)
return absl::nullopt;
// 2. If the animation effect is in the after phase and the iteration count
// is infinity, return infinity.
if (phase == Timing::kPhaseAfter && std::isinf(iteration_count)) {
return std::numeric_limits<double>::infinity();
}
if (!overall_progress)
return absl::nullopt;
// simple iteration progress can only be null if overall progress is null.
DCHECK(simple_iteration_progress);
// 3. If the simple iteration progress is 1.0, return floor(overall progress)
// - 1.
if (simple_iteration_progress.value() == 1.0) {
// Safeguard for zero duration animation (crbug.com/954558).
return fmax(0, floor(overall_progress.value()) - 1);
}
// 4. Otherwise, return floor(overall progress).
return floor(overall_progress.value());
}
// https://w3.org/TR/web-animations-1/#calculating-the-directed-progress
static inline bool IsCurrentDirectionForwards(
absl::optional<double> current_iteration,
Timing::PlaybackDirection direction) {
const bool current_iteration_is_even =
!current_iteration ? false
: (std::isinf(current_iteration.value())
? true
: IsWithinAnimationTimeEpsilon(
fmod(current_iteration.value(), 2), 0));
switch (direction) {
case Timing::PlaybackDirection::NORMAL:
return true;
case Timing::PlaybackDirection::REVERSE:
return false;
case Timing::PlaybackDirection::ALTERNATE_NORMAL:
return current_iteration_is_even;
case Timing::PlaybackDirection::ALTERNATE_REVERSE:
return !current_iteration_is_even;
}
}
// https://w3.org/TR/web-animations-1/#calculating-the-directed-progress
static inline absl::optional<double> CalculateDirectedProgress(
absl::optional<double> simple_iteration_progress,
absl::optional<double> current_iteration,
Timing::PlaybackDirection direction) {
// 1. If the simple progress is unresolved, return unresolved.
if (!simple_iteration_progress)
return absl::nullopt;
// 2. Calculate the current direction.
bool current_direction_is_forwards =
IsCurrentDirectionForwards(current_iteration, direction);
// 3. If the current direction is forwards then return the simple iteration
// progress. Otherwise return 1 - simple iteration progress.
return current_direction_is_forwards ? simple_iteration_progress.value()
: 1 - simple_iteration_progress.value();
}
// https://w3.org/TR/web-animations-1/#calculating-the-transformed-progress
static inline absl::optional<double> CalculateTransformedProgress(
Timing::Phase phase,
absl::optional<double> directed_progress,
bool is_current_direction_forward,
scoped_refptr<TimingFunction> timing_function) {
if (!directed_progress)
return absl::nullopt;
// Set the before flag to indicate if at the leading edge of an iteration.
// This is used to determine if the left or right limit should be used if at a
// discontinuity in the timing function.
bool before = is_current_direction_forward ? phase == Timing::kPhaseBefore
: phase == Timing::kPhaseAfter;
TimingFunction::LimitDirection limit_direction =
before ? TimingFunction::LimitDirection::LEFT
: TimingFunction::LimitDirection::RIGHT;
// Snap boundaries to correctly render step timing functions at 0 and 1.
// (crbug.com/949373)
if (phase == Timing::kPhaseAfter) {
if (is_current_direction_forward &&
IsWithinAnimationTimeEpsilon(directed_progress.value(), 1)) {
directed_progress = 1;
} else if (!is_current_direction_forward &&
IsWithinAnimationTimeEpsilon(directed_progress.value(), 0)) {
directed_progress = 0;
}
}
// Return the result of evaluating the animation effect’s timing function
// passing directed progress as the input progress value.
return timing_function->Evaluate(directed_progress.value(), limit_direction);
}
// Offsets the active time by how far into the animation we start (i.e. the
// product of the iteration start and iteration duration). This is not part of
// the Web Animations spec; it is used for calculating the time until the next
// iteration to optimize scheduling.
static inline absl::optional<AnimationTimeDelta> CalculateOffsetActiveTime(
AnimationTimeDelta active_duration,
absl::optional<AnimationTimeDelta> active_time,
AnimationTimeDelta start_offset) {
DCHECK(GreaterThanOrEqualToWithinTimeTolerance(active_duration,
AnimationTimeDelta()));
DCHECK(GreaterThanOrEqualToWithinTimeTolerance(start_offset,
AnimationTimeDelta()));
if (!active_time)
return absl::nullopt;
DCHECK(GreaterThanOrEqualToWithinTimeTolerance(active_time.value(),
AnimationTimeDelta()) &&
LessThanOrEqualToWithinTimeTolerance(active_time.value(),
active_duration));
if (active_time->is_max())
return AnimationTimeDelta::Max();
return active_time.value() + start_offset;
}
// Maps the offset active time into 'iteration time space'[0], aka the offset
// into the current iteration. This is not part of the Web Animations spec (note
// that the section linked below is non-normative); it is used for calculating
// the time until the next iteration to optimize scheduling.
//
// [0] https://w3.org/TR/web-animations-1/#iteration-time-space
static inline absl::optional<AnimationTimeDelta> CalculateIterationTime(
AnimationTimeDelta iteration_duration,
AnimationTimeDelta active_duration,
absl::optional<AnimationTimeDelta> offset_active_time,
AnimationTimeDelta start_offset,
Timing::Phase phase,
const Timing& specified) {
DCHECK(
GreaterThanWithinTimeTolerance(iteration_duration, AnimationTimeDelta()));
DCHECK(IsWithinAnimationTimeTolerance(
active_duration, MultiplyZeroAlwaysGivesZero(iteration_duration,
specified.iteration_count)));
if (!offset_active_time)
return absl::nullopt;
DCHECK(GreaterThanWithinTimeTolerance(offset_active_time.value(),
AnimationTimeDelta()));
DCHECK(LessThanOrEqualToWithinTimeTolerance(
offset_active_time.value(), (active_duration + start_offset)));
if (offset_active_time->is_max() ||
(IsWithinAnimationTimeTolerance(offset_active_time.value() - start_offset,
active_duration) &&
specified.iteration_count &&
EndsOnIterationBoundary(specified.iteration_count,
specified.iteration_start)))
return absl::make_optional(iteration_duration);
DCHECK(!offset_active_time->is_max());
AnimationTimeDelta iteration_time = ANIMATION_TIME_DELTA_FROM_SECONDS(
fmod(offset_active_time->InSecondsF(), iteration_duration.InSecondsF()));
// This implements step 3 of
// https://w3.org/TR/web-animations-1/#calculating-the-simple-iteration-progress
if (iteration_time.is_zero() && phase == Timing::kPhaseAfter &&
!active_duration.is_zero() && !offset_active_time.value().is_zero())
return absl::make_optional(iteration_duration);
return iteration_time;
}
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_TIMING_CALCULATIONS_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
bf78904b65afd322bc19c5cfb76e8f6249212332 | a02a9701fca434612e1c78e20b884ab92be6b5ed | /include/datafile.h | 7664e168ba1dcb5852a7cebeadd76f4a00c8bc4b | [
"MIT"
] | permissive | alvarogonzalezferrer/warlord_premier_mr_bush | d74281b7fc904f75bb602b974a7d55c57c4fd64d | ebabaf8f5e57b9c8ba78e03af23b0788f681faa3 | refs/heads/master | 2022-11-15T08:19:59.690336 | 2020-07-04T08:37:53 | 2020-07-04T08:37:53 | 277,002,817 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,396 | h | // ---------------------------------------------------------------------------
// datafile.h
// ---------------------------------------------------------------------------
// This has data loading helpers, for loading Allegro datafiles and such.
// Has also a class for holding a datafile, with automatic error handling and all.
// ---------------------------------------------------------------------------
// By Kronoman. Highway Star.
// Copyright (c) 2005-2007, Kronoman
// In loving memory of my father.
// ---------------------------------------------------------------------------
#ifndef DATAFILE_H_FRAMEWORK
#define DATAFILE_H_FRAMEWORK
#include <allegro.h>
#include <string>
// ---------------------------------------------------------------------------
// data container class
// ---------------------------------------------------------------------------
class Datafile
{
public:
Datafile();
~Datafile();
void load(const char *filename); ///< load a datafile
void unload(); ///< unload current datafile
DATAFILE *getObject(const char *name); ///< get object by name
DATAFILE *getObject(const int index); ///< get object by index 0..size-1
std::string getFileName(); ///< loaded file name
DATAFILE *getDatafile(); ///< get internal datafile (dangerous to modify outside!)
int getSize(); ///< get number of loaded objects
private:
DATAFILE *data;
int size; // number of loaded objects
std::string fileName;
};
// ---------------------------------------------------------------------------
// data loading functions
// ---------------------------------------------------------------------------
DATAFILE *loadDatafile(const char *filename); ///< loads a datafile while showing a progress animation on screen.
DATAFILE *findDatafileObject(AL_CONST DATAFILE *dat, AL_CONST char *objectname); ///< searchs for a object inside a datafile, shows animation, ignores upper/lower case diferences in the object name
// ---------------------------------------------------------------------------
// misc, animations for loading progress...
// ---------------------------------------------------------------------------
void BaseAnimationForLoad(); ///< this draws the basic base graph for a progress animation
void UpdateAnimationForLoad(); ///< call this to update the animation on screen of loading (call once for each update)
#endif
| [
"alvarogonzalezferrer@users.noreply.github.com"
] | alvarogonzalezferrer@users.noreply.github.com |
f2e27eda9a4c05fdf87b14453808f56347e7e742 | 4b7ce5c214f4705eb994102f974be8e09609fe47 | /Leetcode/20. Valid Parentheses.cpp | 648a1d063b202fb642d3a45a25991579a6706c1a | [] | no_license | SEUNGHYUN-PARK/Algorithms | ab81cbdd8d43982a79131c75cb9ba402c24faa83 | 318624cc11a844c0082b25b9fd6bd099cb1befff | refs/heads/master | 2020-03-07T21:07:55.572464 | 2019-01-15T14:26:18 | 2019-01-15T14:26:18 | 127,706,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | class Solution {
public:
bool isValid(string s) {
stack<char> st;
if(s.size()==1) return false;
for(int i=0;i<s.size();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
st.push(s[i]);
}
else if(s[i]==')')
{
if(st.size()>0&&st.top()=='(')
st.pop();
else
st.push(s[i]);
}
else if(s[i]=='}')
{
if(st.size()>0&&st.top()=='{')
st.pop();
else
st.push(s[i]);
}
else if(s[i]==']')
{
if(st.size()>0&&st.top()=='[')
st.pop();
else
st.push(s[i]);
}
}
if(st.empty()) return true;
else return false;
}
}; | [
"shstyle812@gmail.com"
] | shstyle812@gmail.com |
ee023e4c93e73edb9bce03d5ad1a96a3150883a4 | ab51ea47b534dc565142f9b8e71540daf2080430 | /Old/Contests/C1/B.cpp | 9941a1e027f0ea274786c83e6aefd49324e5ad69 | [
"MIT"
] | permissive | Thulio-Carvalho/Advanced-Algorithms-Problems | 872e90d0508e36bf05cda66714f2252d1b670769 | 724bfb765d056ddab414df7dd640914aa0c665ae | refs/heads/master | 2020-03-11T21:19:53.347622 | 2019-06-13T22:19:29 | 2019-06-13T22:19:29 | 130,261,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,115 | cpp | #include <bits/stdc++.h>
using namespace std;
bitset<1010> matrix[1010];
int n, m, cnt;
bool canMove(int dir, int i, int j){
// 0 = up; 1 = right; 2 = down; 3 = left
// cout << "actual pos: i=" << i << " // j=" << j << endl;
// cout << "dir = " << dir << endl;
int adderI = 0;
int adderJ = 0;
switch (dir) {
case 0: adderI--;
break;
case 1: adderJ++;
break;
case 2: adderI++;
break;
case 3: adderJ--;
break;
}
// cout << "adderI = " << adderI << " // adderJ = " << adderJ << endl;
// if(i + adderI < 0 || i + adderI > n) return false;
// if(j + adderJ < 0 || j + adderJ > m) return false;
if(matrix[i + adderI][j + adderJ]){
// cout << "valores: i = " << i + adderI
// << " // j = " << j + adderJ << endl;
// cout << matrix[i+adderI][j+adderJ] << endl;
return false;
}
return true;
}
void move(int i, int j){
// moving up
int newI = i;
int newJ = j;
while(canMove(0, newI, newJ)){
newI--;
cnt++;
// cout << newI << " " << newJ << endl;
// cout << "movin up..." << endl;
}
// moving right
newI = i;
newJ = j;
while(canMove(1, newI, newJ)){
newJ++;
cnt++;
// cout << newI << " " << newJ << endl;
// cout << "movin right..." << endl;
}
// moving down
newI = i;
newJ = j;
while(canMove(2, newI, newJ)){
newI++;
cnt++;
// cout << newI << " " << newJ << endl;
// cout << "movin down..." << endl;
}
// moving left
newI = i;
newJ = j;
while(canMove(3, newI, newJ)){
newJ--;
cnt++;
// cout << newI << " " << newJ << endl;
// cout << "movin left..." << endl;
}
}
int main(){
for(int i = 0; i < 1010; i++){
matrix[i].set();
}
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
int aux;
scanf("%d", &aux);
matrix[i][j] = aux;
}
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
if (matrix[i][j]){
// cout << "debug123" << endl;
move(i, j);
}
}
}
cout << cnt << endl;
return 0;
}
| [
"thulioicc@gmail.com"
] | thulioicc@gmail.com |
4a3a813885f6799b6e94c7687a5fd68a0e921646 | a6590941fea4880593d5b1cd23eedfe696f4e446 | /ABC100_199/ABC140/d.cpp | 953d6e87b8e0c2741166022af4586cd2dc7be4df | [] | no_license | cod4i3/MyAtcoder | 9fb92f2dd06c5b6217e925a82d8db4f91355a70f | 53bdac3fa7eb4ac48ca6d5c70461639beb6aa81d | refs/heads/master | 2023-02-17T09:15:16.282873 | 2021-01-15T13:34:03 | 2021-01-15T13:34:03 | 232,006,424 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | cpp | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int N, K;
cin >> N >> K;
string str;
cin >> str;
vector<pair<char, int>> S;
for (int l = 0; l < N;) {
int r = l + 1;
for (; r < N && str[l] == str[r]; r++)
;
S.push_back({str[l], r - l});
l = r;
}
int sum = 0;
for (int i = 1; i < N; i++) {
if (str[i] == str[i - 1]) sum++;
}
int limit = S.size() / 2;
if (limit <= K) {
cout << N - 1 << endl;
return 0;
} else {
sum += 2 * K;
}
cout << sum << endl;
return 0;
} | [
"imasdaisukiproducermasu@gmail.com"
] | imasdaisukiproducermasu@gmail.com |
9174fb214507b6496cbf31231d44e9ff1db0bfb4 | 905f576ddcf27dd166b422dec595befb89633276 | /IO/Select/Server.cpp | 514c37dabba9599e8c9aa830ae08f073c744a9c8 | [] | no_license | LuckeX/AlgorithmStudy | 52b61bfda371741fb84172eb31deb35612779d79 | 8e4eedadb8918d914329bd4c72d7c73bf29da641 | refs/heads/master | 2023-04-15T11:07:55.004047 | 2021-04-26T02:42:41 | 2021-04-26T02:42:41 | 351,471,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,182 | cpp |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 1234 //连接时使用的端口
#define MAXCLINE 5 //连接队列中的个数
#define BUF_SIZE 200
int fd[MAXCLINE]; //连接的fd
int conn_amount; //当前的连接数
void showclient()
{
int i;
printf("client amount:%d\n", conn_amount);
for (i = 0; i < MAXCLINE; i++)
{
printf("[%d]:%d ", i, fd[i]);
}
printf("\n\n");
}
int main(void)
{
int sock_fd, new_fd; //监听套接字 连接套接字
struct sockaddr_in server_addr; // 服务器的地址信息
struct sockaddr_in client_addr; //客户端的地址信息
socklen_t sin_size;
int yes = 1;
char buf[BUF_SIZE];
int ret;
int i;
//建立sock_fd套接字
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("setsockopt");
exit(1);
}
//设置套接口的选项 SO_REUSEADDR 允许在同一个端口启动服务器的多个实例
// setsockopt的第二个参数SOL SOCKET 指定系统中,解释选项的级别 普通套接字
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
perror("setsockopt error \n");
exit(1);
}
server_addr.sin_family = AF_INET; //主机字节序
server_addr.sin_port = htons(MYPORT);
server_addr.sin_addr.s_addr = INADDR_ANY; //通配IP
memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));
if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
perror("bind error!\n");
exit(1);
}
if (listen(sock_fd, MAXCLINE) == -1)
{
perror("listen error!\n");
exit(1);
}
printf("listen port %d\n", MYPORT);
fd_set fdsr; //文件描述符集的定义
int maxsock;
struct timeval tv;
conn_amount = 0;
sin_size = sizeof(client_addr);
maxsock = sock_fd;
while (1)
{
//初始化文件描述符集合
FD_ZERO(&fdsr); //清除描述符集
FD_SET(sock_fd, &fdsr); //把sock_fd加入描述符集
//超时的设定
tv.tv_sec = 30;
tv.tv_usec = 0;
//添加活动的连接
for (i = 0; i < MAXCLINE; i++)
{
if (fd[i] != 0)
{
FD_SET(fd[i], &fdsr);
}
}
//如果文件描述符中有连接请求 会做相应的处理,实现I/O的复用 多用户的连接通讯
ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);
if (ret < 0) //没有找到有效的连接 失败
{
perror("select error!\n");
break;
}
else if (ret == 0) // 指定的时间到,
{
printf("timeout \n");
continue;
}
//循环判断有效的连接是否有数据到达
for (i = 0; i < conn_amount; i++)
{
if (FD_ISSET(fd[i], &fdsr))
{
ret = recv(fd[i], buf, sizeof(buf), 0);
if (ret <= 0) //客户端连接关闭,清除文件描述符集中的相应的位
{
printf("client[%d] close\n", i);
close(fd[i]);
FD_CLR(fd[i], &fdsr);
fd[i] = 0;
conn_amount--;
}
//否则有相应的数据发送过来 ,进行相应的处理
else
{
if (ret < BUF_SIZE)
memset(&buf[ret], '\0', 1);
printf("client[%d] send:%s\n", i, buf);
}
}
}
if (FD_ISSET(sock_fd, &fdsr))
{
new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
if (new_fd <= 0)
{
perror("accept error\n");
continue;
}
//添加新的fd 到数组中 判断有效的连接数是否小于最大的连接数,如果小于的话,就把新的连接套接字加入集合
if (conn_amount < MAXCLINE)
{
for (i = 0; i < MAXCLINE; i++)
{
if (fd[i] == 0)
{
fd[i] = new_fd;
break;
}
}
conn_amount++;
printf("new connection client[%d]%s:%d\n", conn_amount, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
if (new_fd > maxsock)
{
maxsock = new_fd;
}
}
else
{
printf("max connections arrive ,exit\n");
send(new_fd, "bye", 4, 0);
close(new_fd);
continue;
}
}
showclient();
}
for (i = 0; i < MAXCLINE; i++)
{
if (fd[i] != 0)
{
close(fd[i]);
}
}
exit(0);
} | [
"1196862599@qq.com"
] | 1196862599@qq.com |
e3dc0e4ee92d7401003dc6d28dd78ae2ee052b0c | 39b831ae89e0ba0627b2631482efcf4b3e5e67b4 | /tests/acap/HW_updated/grey_scale.cpp | 0c5fabfe43316d3ae0ef594f8aaaf2ab92f35fb5 | [
"NCSA"
] | permissive | triSYCL/triSYCL | 082a6284ade929925fab02cbf9ac25e40c1a0ea1 | 929ec95fae74e1123734417a95577842a9911a6f | refs/heads/master | 2023-08-17T10:40:46.579696 | 2023-08-15T20:59:10 | 2023-08-15T20:59:10 | 18,943,874 | 437 | 74 | NOASSERTION | 2023-09-08T17:14:25 | 2014-04-19T15:19:51 | C++ | UTF-8 | C++ | false | false | 3,092 | cpp | /* Grey scale example on 400 acap cores.
*/
#include <sycl/sycl.hpp>
#include <cstring>
#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
using namespace sycl::vendor::xilinx;
auto size_x = 800;
auto size_y = 600;
uint8_t *input_data;
uint8_t *output_data;
template <typename AIE, int X, int Y> struct prog : acap::aie::tile<AIE, X, Y> {
using t = acap::aie::tile<AIE, X, Y>;
auto get_tile_index() { return Y * 50 + X; }
auto get_tile_size() { return size_x * size_y / 400 * 3; }
auto get_tile_offset() { return get_tile_index() * get_tile_size(); }
bool prerun() {
/// acap::hw::args_begin_offset is the start of a region of memory
/// that is suitable for parmeter passing
/// acap::hw::self_tile_addr<X, Y> is the start of the tile from the
/// from the device perspective.
/// the start of the tile from the host's perspective is 0
/// The code below is assuming that sizeof(*this) on the host is >= to
/// sizeof(*this) on the device. this is should always true since
/// the only different I know is that pointer a 32bits in the device instead
/// of 64bits on the host
/// setup int8_t *dev_data to point just after the this object on device.
t::mem_write(acap::hw::args_begin_offset, acap::hw::self_tile_addr<X, Y> +
acap::hw::args_begin_offset +
sizeof(*this));
/// setup unsigned size;
t::mem_write(acap::hw::args_begin_offset + 4, get_tile_size());
/// copies input_data to where dev_data is pointing on device.
t::memcpy_h2d(acap::hw::args_begin_offset + sizeof(*this),
input_data + get_tile_offset(), get_tile_size());
return 1;
}
/// The run member function is defined as the tile program
int8_t *dev_data;
unsigned size;
void run() {
for (unsigned i = 0; i + 3 <= size; i += 3) {
unsigned mean = ((uint16_t)dev_data[i] + (uint16_t)dev_data[i + 1] +
(uint16_t)dev_data[i + 2]) /
3;
dev_data[i] = dev_data[i + 1] = dev_data[i + 2] = mean;
}
}
void postrun() {
/// copies the data pointed by dev_data on device to output_data on the host.
t::memcpy_d2h(output_data + get_tile_offset(),
acap::hw::args_begin_offset + sizeof(*this), get_tile_size());
}
};
int main(int argc, char **argv) {
cv::Mat input = cv::imread("vase2.bmp", cv::IMREAD_COLOR);
std::cout << "input size = " << input.cols << "x" << input.rows << "x3"
<< std::endl;
cv::Mat ouput = input.clone();
auto size_x = input.cols;
auto size_y = input.rows;
input_data = input.data;
output_data = ouput.data;
// Define AIE CGRA running a program "prog" on all the tiles of a VC1902
acap::aie::device<acap::aie::layout::vc1902> aie;
// Run up to completion of all the tile programs
aie.run<prog>();
cv::imwrite("output.bmp", ouput);
return 0;
}
| [
"gauthier@xilinx.com"
] | gauthier@xilinx.com |
14b453159a48b1f322d52ca3621315e208e18d7d | c0d429de0fb6afc8a03d6d4dc6b99b9b79fc72e9 | /Programme/lib/randomRoute/randomRoute.h | 91bc1b3f5d8eab70daf82d82ce8d7d4d1b2ffb66 | [] | no_license | Aegirs/ParticleScanRoom | cbb620e125da1968f2294de2f77145b307775ebe | 67e0c75138062d141c7987ee14de7b1a8720f1b8 | refs/heads/master | 2020-05-18T03:41:13.874009 | 2015-09-16T07:20:20 | 2015-09-16T07:20:20 | 42,571,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | h | #include "moteur.h"
#include "scan.h"
class RandomRoute{
protected:
Scan* scanner;
unsigned long timeout;
public:
RandomRoute(Scan* scan);
void randomRedirection(Moteur<RandomRoute>* moteur);
bool onStop();
bool onRunBack();
bool testForward();
};
| [
"="
] | = |
74ac4d62d1bc020036da0ccae05f26fe47287ace | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /vpc/include/tencentcloud/vpc/v20170312/model/DescribeAddressTemplatesRequest.h | bfb6c58d72fda821ad72565fba059f2234d65381 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 5,345 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_VPC_V20170312_MODEL_DESCRIBEADDRESSTEMPLATESREQUEST_H_
#define TENCENTCLOUD_VPC_V20170312_MODEL_DESCRIBEADDRESSTEMPLATESREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/vpc/v20170312/model/Filter.h>
namespace TencentCloud
{
namespace Vpc
{
namespace V20170312
{
namespace Model
{
/**
* DescribeAddressTemplates请求参数结构体
*/
class DescribeAddressTemplatesRequest : public AbstractModel
{
public:
DescribeAddressTemplatesRequest();
~DescribeAddressTemplatesRequest() = default;
std::string ToJsonString() const;
/**
* 获取过滤条件。
<li>address-template-name - IP地址模板名称。</li>
<li>address-template-id - IP地址模板实例ID,例如:ipm-mdunqeb6。</li>
<li>address-ip - IP地址。</li>
* @return Filters 过滤条件。
<li>address-template-name - IP地址模板名称。</li>
<li>address-template-id - IP地址模板实例ID,例如:ipm-mdunqeb6。</li>
<li>address-ip - IP地址。</li>
*
*/
std::vector<Filter> GetFilters() const;
/**
* 设置过滤条件。
<li>address-template-name - IP地址模板名称。</li>
<li>address-template-id - IP地址模板实例ID,例如:ipm-mdunqeb6。</li>
<li>address-ip - IP地址。</li>
* @param _filters 过滤条件。
<li>address-template-name - IP地址模板名称。</li>
<li>address-template-id - IP地址模板实例ID,例如:ipm-mdunqeb6。</li>
<li>address-ip - IP地址。</li>
*
*/
void SetFilters(const std::vector<Filter>& _filters);
/**
* 判断参数 Filters 是否已赋值
* @return Filters 是否已赋值
*
*/
bool FiltersHasBeenSet() const;
/**
* 获取偏移量,默认为0。
* @return Offset 偏移量,默认为0。
*
*/
std::string GetOffset() const;
/**
* 设置偏移量,默认为0。
* @param _offset 偏移量,默认为0。
*
*/
void SetOffset(const std::string& _offset);
/**
* 判断参数 Offset 是否已赋值
* @return Offset 是否已赋值
*
*/
bool OffsetHasBeenSet() const;
/**
* 获取返回数量,默认为20,最大值为100。
* @return Limit 返回数量,默认为20,最大值为100。
*
*/
std::string GetLimit() const;
/**
* 设置返回数量,默认为20,最大值为100。
* @param _limit 返回数量,默认为20,最大值为100。
*
*/
void SetLimit(const std::string& _limit);
/**
* 判断参数 Limit 是否已赋值
* @return Limit 是否已赋值
*
*/
bool LimitHasBeenSet() const;
private:
/**
* 过滤条件。
<li>address-template-name - IP地址模板名称。</li>
<li>address-template-id - IP地址模板实例ID,例如:ipm-mdunqeb6。</li>
<li>address-ip - IP地址。</li>
*/
std::vector<Filter> m_filters;
bool m_filtersHasBeenSet;
/**
* 偏移量,默认为0。
*/
std::string m_offset;
bool m_offsetHasBeenSet;
/**
* 返回数量,默认为20,最大值为100。
*/
std::string m_limit;
bool m_limitHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_VPC_V20170312_MODEL_DESCRIBEADDRESSTEMPLATESREQUEST_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
588cc1519a670913aed7027eaf5a0db277e94103 | 02a7a13981e8a10e393f86752715df2764389ca1 | /42_Trapping_Rain_Wter_RuntimeErroe.cpp | bca7d0f68d50f6011d4916581de665b07516c89e | [] | no_license | lylalala/leetcode | 7d05f85fa279ffd87632208eb422945ab1e980a5 | 9c647fa9866512195f5d3c4b1e37c9181e209e9a | refs/heads/master | 2021-01-21T04:46:40.958853 | 2016-06-21T06:17:56 | 2016-06-21T06:17:56 | 44,017,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,884 | cpp | //---------------------------------------------------------------------------------------------------------------
//42题 Trapping Rain Water
//利用while循环来得到各个"峰值",求取每两个峰值之间的数据。思路错误,例如[12,1,2,2,3,4,1,2,3,12]的情况下,此办法错误
//刘阳,2015.10.13
//liuyang070424@163.com/liuyang070424@gmail.com
//---------------------------------------------------------------------------------------------------------------
class Solution {
public:
int trap(vector<int>& height) {
if(height.size()<=1)
return 0;
vector<pair<int,int>> maxHeight;
int temp=0,res=0;
int i=0;
bool flag=false;
for(;i<=height.size()-2;){
while(i+1<height.size()&&height[i+1]<=height[i])//下降区间
i++;
if(i+1<height.size()&&height[i+1]>=height[i]){//如果是上升区间,则flag是真,后面需要记录顶点值
i++;
flag=true;
}
while(i+1<height.size()&&height[i+1]>=height[i])//遍历完上升区间,挑选最值
i++;
if(flag){//记录最值
maxHeight.push_back(make_pair(i,height[i]));
flag=false;
}
}
if(maxHeight.size()<=1)
return 0;
for(vector<pair<int,int>>::iterator it=maxHeight.begin();it!=maxHeight.end();it++){
temp=(it+1)->second<it->second?(it+1)->second:(it)->second;
for(int j=it->first;j<(it+1)->first;j++)
if(temp-height[j]>0)
res+=(temp-height[j]);
}
temp=height[0]>maxHeight[0].second?maxHeight[0].first:height[0];
for(int j=0;j<=maxHeight[0].first;j++)
if(temp-height[j]>0)
res+=(temp-height[j]);
return res;
}
};
| [
"liuyang070424@163.com"
] | liuyang070424@163.com |
0721440bb4c30896c3d46e736599de9918d72891 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_5389_git-2.13.1.cpp | 2424146954afc01feb801f87093b7a005800956c | [] | 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 | 1,201 | cpp | static int mark_object(struct object *obj, int type, void *data, struct fsck_options *options)
{
struct object *parent = data;
/*
* The only case data is NULL or type is OBJ_ANY is when
* mark_object_reachable() calls us. All the callers of
* that function has non-NULL obj hence ...
*/
if (!obj) {
/* ... these references to parent->fld are safe here */
printf("broken link from %7s %s\n",
printable_type(parent), describe_object(parent));
printf("broken link from %7s %s\n",
(type == OBJ_ANY ? "unknown" : typename(type)), "unknown");
errors_found |= ERROR_REACHABLE;
return 1;
}
if (type != OBJ_ANY && obj->type != type)
/* ... and the reference to parent is safe here */
objerror(parent, "wrong object type in link");
if (obj->flags & REACHABLE)
return 0;
obj->flags |= REACHABLE;
if (!(obj->flags & HAS_OBJ)) {
if (parent && !has_object_file(&obj->oid)) {
printf("broken link from %7s %s\n",
printable_type(parent), describe_object(parent));
printf(" to %7s %s\n",
printable_type(obj), describe_object(obj));
errors_found |= ERROR_REACHABLE;
}
return 1;
}
add_object_array(obj, NULL, &pending);
return 0;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
47d9b06dcbb59b76fb8d9b2b0538b948aeac2041 | f6c6f6ca06a12694b48f5422c4029070b3f7bc46 | /DynamicDLL/main.cpp | 0e5cf67c2a08c84fd4c561b622c23a4f1ba37e86 | [] | no_license | JulyaDon/DynamicDLLTritemius | c020e6d7b1c5713a05908cc1729139429237dbc5 | ce9dad6896f7a6eaee5c1a26c31ea10eb6a243d7 | refs/heads/master | 2021-01-09T20:32:43.513105 | 2016-08-08T11:25:06 | 2016-08-08T11:25:06 | 65,198,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 76 | cpp | extern "C" __declspec(dllexport) char* SayHello() {
return "Hello World";
} | [
"don.julya@yandex.ru"
] | don.julya@yandex.ru |
52d32d8f048b59f2e38f9123e7e06fef81f1450f | 92db2a637478ae4d2cc5857202626db4cef680f8 | /test/MidiGlobal/TestMidiGlobalFloor.cpp | 2be3a0c7fdf94b472884d68b3a856634d6968a56 | [] | no_license | adtavi/MidiMediaPlayer | 0f123731a9bf9b34a236625c61a217cd8607d495 | 4839ae2d25394c35ea0e95adba26a41b4cc08e1f | refs/heads/master | 2022-12-25T19:18:43.398925 | 2020-09-28T10:59:44 | 2020-09-28T10:59:44 | 281,145,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,727 | cpp | //
// TestMidiGlobalFloor.cpp
// TestMidiMediaPlayer
//
// Created by Adriel Taboada on 01/08/2020.
//
#include "catch.hpp"
#include "MidiGlobalFloor.hpp"
class TestMidiGlobalFloor
{
unique_ptr<MidiGlobalFloor> _floor;
public:
TestMidiGlobalFloor() {
MidiSettings::set_window(1024, 768);
_floor = make_unique<MidiGlobalFloor>();
};
void midi_note_on() {
_floor->midi_note_on();
}
void midi_note_off() {
_floor->midi_note_off();
}
void midi_control_change() {
_floor->midi_control_change();
}
bool to_delete() {
_floor->to_delete();
}
void window_resized() {
_floor->window_resized();
}
void update(uint64_t delta_pedal, uint64_t time_since_update) {
_floor->update( delta_pedal, time_since_update);
}
glm::vec3 get_position() {
return _floor->getPosition();
}
float get_width() {
return _floor->getWidth();
}
float get_height() {
return _floor->getHeight();
}
glm::vec3 get_orientation() {
return _floor->getOrientationEulerDeg();
}
};
TEST_CASE_METHOD(TestMidiGlobalFloor, "MidiGlobalFloor", "[MidiGlobalFloor]" ) {
REQUIRE(get_width() == MidiSettings::get_window_width()*2);
REQUIRE(get_height() == MidiSettings::get_window_depth()*2);
REQUIRE(get_position().x == MidiSettings::get_window_width()/2);
REQUIRE(get_position().y == MidiSettings::get_window_height());
REQUIRE(get_position().z == -MidiSettings::get_window_depth());
REQUIRE(get_orientation().x == 90);
REQUIRE(get_orientation().y == 0);
REQUIRE(get_orientation().z == 0);
}
| [
"adriel.taboada@gmail.com"
] | adriel.taboada@gmail.com |
09b0e591aa529a89f756be2e8b0f2d0df1e459ce | 03112612a44cc95b08b982bcc2937210929520f9 | /CommandLine/datatypes headers/Datatypes.h | 5b624e9cb7588397a614c5cfac747ccaf6c170bc | [] | no_license | HaikuArchives/ScannerBe | 703b5875d471380d432790f0d1c7117f608d1d5b | c4f889efda4839f48eca92bf669a0ff54e0cdc80 | refs/heads/master | 2021-01-23T05:45:21.581579 | 2007-04-01T19:21:38 | 2007-04-01T19:21:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,609 | h | // Datatypes.h
// Header file for the datatypes library.
// These functions allow for easy translation of
// unknown data into known types.
#pragma once
#ifndef _DATATYPES_H_
#define _DATATYPES_H_
#include <OS.h>
#include <StorageDefs.h>
#include <InterfaceDefs.h>
#include <Mime.h>
struct Format;
class BBitmap;
class BView;
class BPositionIO;
class BQuery;
class BMessage;
#include "DataFormats.h"
#pragma export on
typedef unsigned long DATAID;
struct DATAInfo { // Info about a specific translation
uint32 formatType; // B_ASCII_TYPE, ...
DATAID formatHandler; // Internal to datatypes library
uint32 formatGroup; // DATA_BITMAP, DATA_TEXT, ...
float formatQuality; // Quality of format in class 0.0-1.0
float formatCapability; // How much of the format do we do? 0.0-1.0
char formatName[B_MIME_TYPE_LENGTH+11];
char MIMEName[B_MIME_TYPE_LENGTH+11];
};
enum DATA_ERROR {
DATA_BASE_ERROR = (int)0xDADA0000,
DATA_NO_HANDLER = DATA_BASE_ERROR, // no handler exists for data
DATA_ILLEGAL_DATA, // data is not what it said it was
DATA_NOT_INITIALIZED
};
#define DATA_CURRENT_VERSION 163
#define DATA_MIN_VERSION 161
extern "C" {
// you need to initialize the library to use it
// you should also shutdown it before quitting
extern const char *DATAVersion( // returns version string
int32 & outCurVersion, // current version spoken
int32 & outMinVersion); // minimum version understood
extern status_t DATAInit( // establish connection
const char * app_signature,
const char * load_path = NULL);
extern status_t DATAShutdown(); // don't want to talk anymore
// these functions call through to the translators
// when wantType is not 0, will only take into consideration
// handlers that can read input data and produce output data
extern status_t DATAIdentify( // find out what something is
BPositionIO & inSource,
BMessage * ioExtension,
DATAInfo & outInfo,
uint32 inHintType = 0,
const char * inHintMIME = NULL,
uint32 inWantType = 0);
extern status_t DATAGetHandlers(// find all handlers for a type
BPositionIO & inSource,
BMessage * ioExtension,
DATAInfo * & outInfo, // call delete[] on outInfo when done
int32 & outNumInfo,
uint32 inHintType = 0,
const char * inHintMIME = NULL,
uint32 inWantType = 0);
extern status_t DATAGetAllHandlers(// find all handler IDs
DATAID * & outList,// call delete[] when done
int32 & outCount);
extern status_t DATAGetHandlerInfo(// given a handler, get user-visible info
DATAID forHandler,
const char * & outName,
const char * & outInfo,
int32 & outVersion);
// note that handlers may choose to be "invisible" to
// the public formats, and just kick in when they
// recognize a file format by its data.
extern status_t DATAGetInputFormats(// find all input formats for handler
DATAID forHandler,
const Format * & outFormats,// don't write contents!
int32 & outNumFormats);
extern status_t DATAGetOutputFormats(// find all output formats for handler
DATAID forHandler,
const Format * & outFormats,// don't write contents!
int32 & outNumFormats);
// actually do some work
extern status_t DATATranslate( // morph data into form we want
BPositionIO & inSource,
const DATAInfo * inInfo,// may be NULL
BMessage * ioExtension,
BPositionIO & outDestination,
uint32 inWantOutType,
uint32 inHintType = 0,
const char * inHintMIME = NULL);
// For configuring options of the handler, a handler can support
// creating a view to cofigure the handler. The handler can save
// its preferences in the database or settings file as it sees fit.
// As a convention, the handler should always save whatever
// settings are changed when the view is deleted or hidden.
extern status_t DATAMakeConfig(
DATAID forHandler,
BMessage * ioExtension,
BView * & outView,
BRect & outExtent);
// For saving settings and using them later, your app can get the
// current settings from a handler into a BMessage that you create
// and pass in empty. Pass this message (or a copy thereof) to the
// handler later in a call to DATATranslate to translate using
// those settings. This config message should also contain any
// DATACapture settings you may want to re-use.
extern status_t DATAGetConfigMessage(
DATAID forHandler,
BMessage * ioExtension);
// Some Datatypes get data from thin air (QuickCam, recorder, ...)
// These Datatypes utilize the Capture API, a simple API that lets
// applications run the Datatype and tell it to start generating
// data.
extern status_t DATAListCaptures( // experimental - may change
uint32 captureType,
DATAID * & outHandlers, // delete[] when done
int32 & outNumHandlers);
extern status_t DATAMakeCapturePanel( // experimental - may change
DATAID handler,
BMessage * ioExtension,
BView * & outView,
BRect & outExtent);
extern status_t DATACapture( // experimental - may change
DATAID handler,
BView * view, // can be NULL
BMessage * ioExtension, // can be NULL
BPositionIO & stream,
uint32 captureType);
}
#pragma export reset
#endif // _DATATYPES_H_
// _DATATYPES_H_
| [
"andrea@b1bb0d01-0d2d-0410-9e79-a451227b79de"
] | andrea@b1bb0d01-0d2d-0410-9e79-a451227b79de |
276e2842d22036497d79dac71b019564c33db881 | c304381776279bb96c7c73dff5147b826c1fee30 | /arg.cpp | 92b299474e40d88849ebea56422d7067a9c8c14f | [] | no_license | yuchun1214/JobShop | dfd339783f047eb24edb9e34a69318d454b1a33c | 20298374f0b1109ee09e263716d419a5a6800c6a | refs/heads/master | 2023-02-06T17:42:56.537159 | 2020-12-24T07:42:55 | 2020-12-24T07:42:55 | 291,057,637 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 249 | cpp | #include "./arg.h"
Arguments::Arguments(std::map<string, int> initArguments){
this->_arguments = initArguments
}
void Arguments::parseArgument(int argc, const char * argv[]){
for(int i = 0; i < argc; ++i){
std::cout<<argv[i]<<std::endl;
}
}
| [
"yuchunlin0075@gmail.com"
] | yuchunlin0075@gmail.com |
84b52e9cddea799d59e1932f134817c5022fa288 | 841d036dcd7ffd02137533b3c513eefb26a7a846 | /Game_test/Ship/Trash.cpp | e129d3957a808bd5e88e43d6ec2cb118d5750084 | [] | no_license | weimingtom/Project_KankoreSTG | 2e8f1b245e581888de5e4812142e01343152ac45 | 6275329e8f52b7890e08c7160bbadfee9f1dbaf3 | refs/heads/master | 2020-05-29T12:17:55.994567 | 2014-08-11T07:15:07 | 2014-08-11T07:15:07 | 33,701,128 | 1 | 0 | null | 2015-04-10T01:13:50 | 2015-04-10T01:13:50 | null | WINDOWS-1252 | C++ | false | false | 852 | cpp | //Âø³½¼ÄÄ¥Ãþ§O¹ê§@
#include "Trash.h"
Trash::Trash()
{
HP = 5;
ScaleNum = 1.0f;
ship = new hgeSprite(0,0,0,128,128);
countBulMax = 20;
ship->SetBlendMode(BLEND_ALPHABLEND | BLEND_ZWRITE);
ship->SetZ(0.5f);
ship->SetColor(0xFFFFFFFF);
newEne();
}
Trash::Trash(float newx, float newy, float newr, float newangle, float newrm, float newanglem, int Type) : Enemyship(Type)
{
ship = new hgeSprite(0,0,0,128,128);
ScaleNum = 1.0f;
ship->SetBlendMode(BLEND_ALPHABLEND | BLEND_ZWRITE);
ship->SetZ(0.5f);
ship->SetColor(0xFFFFFFFF);
newEne(newx,newy,newr,newangle,newrm,newanglem);
}
void Trash::move()
{
}
void Trash::setimgsnd()
{
}
void Trash::damage(int ATK)
{
}
void Trash::fire()
{
}
void Trash::Render()
{
ship->RenderEx(this->x,this->y,0,ScaleNum);
for (int i=0;i<bulNum;i++)
{
bull[i].Render();
}
}
| [
"layidismi@gmail.com"
] | layidismi@gmail.com |
8871a72f2bddf05b2b39ee74c41a99adf6c65cc0 | 6dcda687bc386b58c6391d150a3816adf43c7cea | /SDK/Sight_RedDot_parameters.h | e77f9a909739b4934ad98db4f27a659fcb0d1a3f | [] | no_license | firebiteLR/PavlovVR-SDK | 813f49c03140c46c318cae15fd5a03be77a80c05 | 0d31dec9aa671f0e9a2fbc37a9be34a9854e06a4 | refs/heads/master | 2023-07-23T11:28:43.963982 | 2021-02-18T15:06:38 | 2021-02-18T15:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 923 | h | #pragma once
#include "../SDK.h"
// Name: , Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function Sight_RedDot.Sight_RedDot_C.GetLenseMesh
struct ASight_RedDot_C_GetLenseMesh_Params
{
int MaterialIndex; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
class UMeshComponent* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData)
};
// Function Sight_RedDot.Sight_RedDot_C.UserConstructionScript
struct ASight_RedDot_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"albertarlington21@gmail.com"
] | albertarlington21@gmail.com |
a28fe6864ca2d8ddc452dfbf1047b5266b6c0841 | bfeb5fd0b933f214a99ae16e2ea9aae9fefefe1d | /Adafruit/Adafruit_ILI9341.cpp | 7154e1d4f300462bc8dd36a7af9e4a4d6b77ed4e | [] | no_license | svartbjorn/Thermostat_2 | 3be5d459856d1cb377a32768106fcc74a7a83669 | 881773fa2f7835d65770f201d93ff40a78aecbef | refs/heads/master | 2016-09-14T18:48:41.410283 | 2016-04-17T03:54:20 | 2016-04-17T03:54:20 | 56,406,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,932 | cpp | /***************************************************
This is an Arduino Library for the Adafruit 2.2" SPI display.
This library works with the Adafruit 2.2" TFT Breakout w/SD card
----> http://www.adafruit.com/products/1480
Check out the links above for our tutorials and wiring diagrams
These displays use SPI to communicate, 4 or 5 pins are required to
interface (RST is optional)
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_ILI9341.h"
#include <limits.h>
#include "application.h"
// Constructor when using hardware SPI. Faster, but must use specific SPI pins (http://docs.spark.io/#/hardware):
// A2 : SS(Slave Select)
// A3 : SCK(Serial Clock)
// A4 : MISO(Master In Slave Out)
// A5 : MOSI(Master Out Slave In)
// The other pins are: cs - Chip select (aka slave select), dc - D/C or A0 on the screen (Command/Data switch), rst - Reset
Adafruit_ILI9341::Adafruit_ILI9341(uint8_t cs, uint8_t dc, uint8_t rst) : Adafruit_GFX(ILI9341_TFTWIDTH, ILI9341_TFTHEIGHT) {
_cs = cs;
_dc = dc;
_rst = rst;
_mosi = _sclk = 0;
}
inline void Adafruit_ILI9341::spiwrite(uint8_t c) {
//Serial.print("0x"); Serial.print(c, HEX); Serial.print(", ");
SPI.transfer(c);
}
inline void Adafruit_ILI9341::writecommand(uint8_t c) {
pinResetFast(_dc); //digitalWrite(_dc, LOW);
//digitalWrite(_sclk, LOW);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
spiwrite(c);
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
inline void Adafruit_ILI9341::writedata(uint8_t c) {
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
//digitalWrite(_sclk, LOW);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
spiwrite(c);
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
// Rather than a bazillion writecommand() and writedata() calls, screen
// initialization commands and arguments are organized in these tables
// stored in PROGMEM. The table may look bulky, but that's mostly the
// formatting -- storage-wise this is hundreds of bytes more compact
// than the equivalent code. Companion function follows.
#define DELAY 0x80
// Companion code to the above tables. Reads and issues
// a series of LCD commands stored in PROGMEM byte array.
void Adafruit_ILI9341::commandList(uint8_t *addr) {
uint8_t numCommands, numArgs;
uint16_t ms;
numCommands = pgm_read_byte(addr++); // Number of commands to follow
while (numCommands--) { // For each command...
writecommand(pgm_read_byte(addr++)); // Read, issue command
numArgs = pgm_read_byte(addr++); // Number of args to follow
ms = numArgs & DELAY; // If hibit set, delay follows args
numArgs &= ~DELAY; // Mask out delay bit
while (numArgs--) { // For each argument...
writedata(pgm_read_byte(addr++)); // Read, issue argument
}
if (ms) {
ms = pgm_read_byte(addr++); // Read post-command delay time (ms)
if (ms == 255) {
ms = 500; // If 255, delay for 500 ms
}
delay(ms);
}
}
}
void Adafruit_ILI9341::begin(void) {
pinMode(_rst, OUTPUT);
pinMode(_dc, OUTPUT);
pinMode(_cs, OUTPUT);
digitalWrite(_rst, LOW);
mosiport = &_mosi;
clkport = &_sclk;
rsport = &_rst;
csport = &_cs;
dcport = &_dc;
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV2); //Full speed @18MHz
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
// toggle RST low to reset
pinSetFast(_rst); //digitalWrite(_rst, HIGH);
delay(5);
pinResetFast(_rst); //digitalWrite(_rst, LOW);
delay(20);
pinSetFast(_rst); //digitalWrite(_rst, HIGH);
delay(150);
writecommand(0xEF);
writedata(0x03);
writedata(0x80);
writedata(0x02);
writecommand(0xCF);
writedata(0x00);
writedata(0XC1);
writedata(0X30);
writecommand(0xED);
writedata(0x64);
writedata(0x03);
writedata(0X12);
writedata(0X81);
writecommand(0xE8);
writedata(0x85);
writedata(0x00);
writedata(0x78);
writecommand(0xCB);
writedata(0x39);
writedata(0x2C);
writedata(0x00);
writedata(0x34);
writedata(0x02);
writecommand(0xF7);
writedata(0x20);
writecommand(0xEA);
writedata(0x00);
writedata(0x00);
writecommand(ILI9341_PWCTR1); //Power control
writedata(0x23); //VRH[5:0]
writecommand(ILI9341_PWCTR2); //Power control
writedata(0x10); //SAP[2:0];BT[3:0]
writecommand(ILI9341_VMCTR1); //VCM control
writedata(0x3e);
writedata(0x28);
writecommand(ILI9341_VMCTR2); //VCM control2
writedata(0x86); //--
writecommand(ILI9341_MADCTL); // Memory Access Control
writedata(ILI9341_MADCTL_MX | ILI9341_MADCTL_BGR);
writecommand(ILI9341_PIXFMT);
writedata(0x55);
writecommand(ILI9341_FRMCTR1);
writedata(0x00);
writedata(0x18);
writecommand(ILI9341_DFUNCTR); // Display Function Control
writedata(0x08);
writedata(0x82);
writedata(0x27);
writecommand(0xF2); // 3Gamma Function Disable
writedata(0x00);
writecommand(ILI9341_GAMMASET); //Gamma curve selected
writedata(0x01);
writecommand(ILI9341_GMCTRP1); //Set Gamma
writedata(0x0F);
writedata(0x31);
writedata(0x2B);
writedata(0x0C);
writedata(0x0E);
writedata(0x08);
writedata(0x4E);
writedata(0xF1);
writedata(0x37);
writedata(0x07);
writedata(0x10);
writedata(0x03);
writedata(0x0E);
writedata(0x09);
writedata(0x00);
writecommand(ILI9341_GMCTRN1); //Set Gamma
writedata(0x00);
writedata(0x0E);
writedata(0x14);
writedata(0x03);
writedata(0x11);
writedata(0x07);
writedata(0x31);
writedata(0xC1);
writedata(0x48);
writedata(0x08);
writedata(0x0F);
writedata(0x0C);
writedata(0x31);
writedata(0x36);
writedata(0x0F);
writecommand(ILI9341_SLPOUT); //Exit Sleep
delay(120);
writecommand(ILI9341_DISPON); //Display on
}
void Adafruit_ILI9341::setAddrWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) {
writecommand(ILI9341_CASET); // Column addr set
writedata(x0 >> 8);
writedata(x0 & 0xFF); // XSTART
writedata(x1 >> 8);
writedata(x1 & 0xFF); // XEND
writecommand(ILI9341_PASET); // Row addr set
writedata(y0 >> 8);
writedata(y0); // YSTART
writedata(y1 >> 8);
writedata(y1); // YEND
writecommand(ILI9341_RAMWR); // write to RAM
}
void Adafruit_ILI9341::pushColor(uint16_t color) {
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
spiwrite(color >> 8);
spiwrite(color);
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9341::drawPixel(int16_t x, int16_t y, uint16_t color) {
if ((x < 0) || (x >= _width) || (y < 0) || (y >= _height)) {
return;
}
setAddrWindow(x, y, x + 1, y + 1);
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
spiwrite(color >> 8);
spiwrite(color);
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9341::drawFastVLine(int16_t x, int16_t y, int16_t h,
uint16_t color) {
// Rudimentary clipping
if ((x >= _width) || (y >= _height)) {
return;
}
if ((y + h - 1) >= _height) {
h = _height - y;
}
setAddrWindow(x, y, x, y + h - 1);
uint8_t hi = color >> 8, lo = color;
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
while (h--) {
spiwrite(hi);
spiwrite(lo);
}
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9341::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) {
// Rudimentary clipping
if ((x >= _width) || (y >= _height)) {
return;
}
if ((x + w - 1) >= _width) {
w = _width - x;
}
setAddrWindow(x, y, x + w - 1, y);
uint8_t hi = color >> 8, lo = color;
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
while (w--) {
spiwrite(hi);
spiwrite(lo);
}
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9341::fillScreen(uint16_t color) {
fillRect(0, 0, _width, _height, color);
}
// fill a rectangle
void Adafruit_ILI9341::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
uint16_t color) {
// rudimentary clipping (drawChar w/big text requires this)
if ((x >= _width) || (y >= _height)) {
return;
}
if ((x + w - 1) >= _width) {
w = _width - x;
}
if ((y + h - 1) >= _height) {
h = _height - y;
}
setAddrWindow(x, y, x + w - 1, y + h - 1);
uint8_t hi = color >> 8, lo = color;
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
for (y = h; y > 0; y--) {
for (x = w; x > 0; x--) {
spiwrite(hi);
spiwrite(lo);
}
}
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
}
// Pass 8-bit (each) R,G,B, get back 16-bit packed color
uint16_t Adafruit_ILI9341::Color565(uint8_t r, uint8_t g, uint8_t b) {
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
void Adafruit_ILI9341::setRotation(uint8_t m) {
writecommand(ILI9341_MADCTL);
rotation = m % 4; // can't be higher than 3
switch (rotation) {
case 0:
writedata(ILI9341_MADCTL_MX | ILI9341_MADCTL_BGR);
_width = ILI9341_TFTWIDTH;
_height = ILI9341_TFTHEIGHT;
break;
case 1:
writedata(ILI9341_MADCTL_MV | ILI9341_MADCTL_BGR);
_width = ILI9341_TFTHEIGHT;
_height = ILI9341_TFTWIDTH;
break;
case 2:
writedata(ILI9341_MADCTL_MY | ILI9341_MADCTL_BGR);
_width = ILI9341_TFTWIDTH;
_height = ILI9341_TFTHEIGHT;
break;
case 3:
writedata(
ILI9341_MADCTL_MV | ILI9341_MADCTL_MY | ILI9341_MADCTL_MX
| ILI9341_MADCTL_BGR);
_width = ILI9341_TFTHEIGHT;
_height = ILI9341_TFTWIDTH;
break;
}
}
void Adafruit_ILI9341::invertDisplay(boolean i) {
writecommand(i ? ILI9341_INVON : ILI9341_INVOFF);
}
////////// stuff not actively being used, but kept for posterity
inline uint8_t Adafruit_ILI9341::spiread(void) {
uint8_t r = 0;
r = SPI.transfer(0x00);
//Serial.print("read: 0x"); Serial.print(r, HEX);
return r;
}
inline uint8_t Adafruit_ILI9341::readdata(void) {
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
uint8_t r = spiread();
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
return r;
}
inline uint8_t Adafruit_ILI9341::readcommand8(uint8_t c) {
pinResetFast(_dc); //digitalWrite(_dc, LOW);
//digitalWrite(_sclk, LOW);
pinResetFast(_cs); //digitalWrite(_cs, LOW);
spiwrite(c);
pinSetFast(_dc); //digitalWrite(_dc, HIGH);
uint8_t r = spiread();
pinSetFast(_cs); //digitalWrite(_cs, HIGH);
return r;
}
| [
"svartbjorn@users.noreply.github.com"
] | svartbjorn@users.noreply.github.com |
d7f8dfb4d1539dcb2380d86c085e7e6e13057f21 | 9bc2462106be4df51f31e44e28ea6a78b42a3deb | /pastQuestionsOneYear/09/src.cpp | 2ca51f037e0e05ceeff5cdf3ffdd6979a058a81d | [] | no_license | ysuzuki19/atcoder | 4c8128c8a7c7ed10fc5684b1157ab5513ba9c32e | 0fbe0e41953144f24197b4dcd623ff04ef5bc4e4 | refs/heads/master | 2021-08-14T19:35:45.660024 | 2021-07-31T13:40:39 | 2021-07-31T13:40:39 | 178,597,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
reverse(s.begin(), s.end());
for(size_t i=0; i<s.length(); ++i){
if( s.substr(i,5) == "maerd" ){
i += 4;
continue;
}
if( s.substr(i,7) == "remaerd" ){
i += 6;
continue;
}
if( s.substr(i,5) == "esare" ){
i += 4;
continue;
}
if( s.substr(i,6) == "resare" ){
i += 5;
continue;
}
cout << "NO" << endl;
return 0;
}
cout << "YES" << endl;
return 0;
}
| [
"msethuuh7@i.softbank.jp"
] | msethuuh7@i.softbank.jp |
246e2066c26e9fe7bad75c99816eeea31a551c4c | 9a3b99b1eeb4f10400a799b51d789d0fde156be9 | /bitcoin_v0.12.1/src/main.cpp | edfab6b49153505456e32b81235165484ac5c336 | [
"MIT"
] | permissive | aijs/blockchain | 077e7e8bf515cac5afde04498e560f300041ceff | 89ee5dc0b243847688d7063820dc1ec58394c896 | refs/heads/master | 2020-03-28T02:55:05.362321 | 2018-08-20T09:58:32 | 2018-08-20T09:58:32 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 298,710 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "addrman.h"
#include "alert.h"
#include "arith_uint256.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "checkqueue.h"
#include "consensus/consensus.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "init.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "pow.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sigcache.h"
#include "script/standard.h"
#include "tinyformat.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "undo.h"
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "versionbits.h"
#include <sstream>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/math/distributions/poisson.hpp>
#include <boost/thread.hpp>
using namespace std;
#if defined(NDEBUG)
# error "Bitcoin cannot be compiled without assertions."
#endif
/**
* Global state
*/
CCriticalSection cs_main;
BlockMap mapBlockIndex; // 保存区块链上区块的索引
CChain chainActive; // 当前连接的区块链(激活的链)
CBlockIndex *pindexBestHeader = NULL;
int64_t nTimeBestReceived = 0;
CWaitableCriticalSection csBestBlock;
CConditionVariable cvBlockChange; // 区块改变的条件变量
int nScriptCheckThreads = 0;
bool fImporting = false;
bool fReindex = false;
bool fTxIndex = false;
bool fHavePruned = false;
bool fPruneMode = false;
bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
bool fRequireStandard = true;
unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;
bool fCheckBlockIndex = false;
bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED; // true 表示检查点标志,默认开启
size_t nCoinCacheUsage = 5000 * 300;
uint64_t nPruneTarget = 0;
bool fAlerts = DEFAULT_ALERTS;
bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT; // 内存池替换标志,默认开题
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying, mining and transaction creation) */ // 小于词费用(单位为 satoshi)被当作 0 费用(用于中继,挖矿和创建交易)
CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); // 最小中继交易费
CTxMemPool mempool(::minRelayTxFee); // 交易内存池全局对象,通过最小中继交易费创建
struct COrphanTx {
CTransaction tx;
NodeId fromPeer;
};
map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
static void CheckBlockIndex(const Consensus::Params& consensusParams);
/** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS;
const string strMessageMagic = "Bitcoin Signed Message:\n"; // 字符串类型的消息魔术头
// Internal stuff // 内部事务
namespace {
struct CBlockIndexWorkComparator // 区块索引工作量比较器(函数对象)
{
bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
// First sort by most total work, ... // 首先通过总工作量排序
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
// ... then by earliest time received, ... // 然后通过最早的接收时间排序
if (pa->nSequenceId < pb->nSequenceId) return false;
if (pa->nSequenceId > pb->nSequenceId) return true;
// Use pointer address as tie breaker (should only happen with blocks // 最后使用索引指针地址排序
// loaded from disk, as those all have id 0). // (应该只发生在从磁盘加载区块时,因为它们的 id 全为 0)
if (pa < pb) return false;
if (pa > pb) return true;
// Identical blocks. // 相同的区块。
return false; // 返回 false
}
};
CBlockIndex *pindexBestInvalid; // 最佳无效区块索引
/**
* The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
* as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
* missing the data for the block.
*/ // 全部带有 BLOCK_VALID_TRANSACTIONS 区块索引条目的集合(它自己和所有祖先)且和我们当前链尖一样或更好。条目可能失败,修剪节点可能会丢失该块的数据。
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates; // 区块索引候选集合
/** Number of nodes with fSyncStarted. */
int nSyncStarted = 0; // 节点的数量
/** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
* Pruned nodes may have entries where B is missing data.
*/ // 全部的对 A->B,其中 A(或其祖先块)丢失了交易,但 B 有交易。修剪的节点可能具有 B 区块丢失的数据的条目。
multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
CCriticalSection cs_LastBlockFile;
std::vector<CBlockFileInfo> vinfoBlockFile; // 区块文件信息列表
int nLastBlockFile = 0; // 最后一个文件号
/** Global flag to indicate we should check to see if there are
* block/undo files that should be deleted. Set on startup
* or if we allocate more file space when we're in prune mode
*/ // 全局标志,表示我们应检查是否存在应删除的区块/恢复文件。在启动时设置,或处于修剪模式时分配更多的文件空间。
bool fCheckForPruning = false;
/**
* Every received block is assigned a unique and increasing identifier, so we
* know which one to give priority in case of a fork.
*/
CCriticalSection cs_nBlockSequenceId;
/** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
uint32_t nBlockSequenceId = 1;
/**
* Sources of received blocks, saved to be able to send them reject
* messages or ban them when processing happens afterwards. Protected by
* cs_main.
*/
map<uint256, NodeId> mapBlockSource;
/**
* Filter for transactions that were recently rejected by
* AcceptToMemoryPool. These are not rerequested until the chain tip
* changes, at which point the entire filter is reset. Protected by
* cs_main.
*
* Without this filter we'd be re-requesting txs from each of our peers,
* increasing bandwidth consumption considerably. For instance, with 100
* peers, half of which relay a tx we don't accept, that might be a 50x
* bandwidth increase. A flooding attacker attempting to roll-over the
* filter using minimum-sized, 60byte, transactions might manage to send
* 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
* two minute window to send invs to us.
*
* Decreasing the false positive rate is fairly cheap, so we pick one in a
* million to make it highly unlikely for users to have issues with this
* filter.
*
* Memory used: 1.7MB
*/
boost::scoped_ptr<CRollingBloomFilter> recentRejects; // 最近拒绝的交易过滤器
uint256 hashRecentRejectsChainTip; // 最近拒绝的链尖哈希
/** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
struct QueuedBlock { // 飞行中的区块,和处于下载队列中的区块。
uint256 hash;
CBlockIndex* pindex; //!< Optional.
bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
};
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
/** Number of preferable block download peers. */
int nPreferredDownload = 0; // 优先去快下载的对端数
/** Dirty block index entries. */
set<CBlockIndex*> setDirtyBlockIndex; // 脏掉的区块索引条目集合
/** Dirty block file entries. */
set<int> setDirtyFileInfo; // 脏掉的区块文件条目
/** Number of peers from which we're downloading blocks. */
int nPeersWithValidatedDownloads = 0; // 我们正在下载区块的对端数
} // anon namespace
//////////////////////////////////////////////////////////////////////////////
//
// Registration of network node signals.
//
namespace {
struct CBlockReject {
unsigned char chRejectCode;
string strRejectReason;
uint256 hashBlock;
};
/**
* Maintain validation-specific state about nodes, protected by cs_main, instead
* by CNode's own locks. This simplifies asynchronous operation, where
* processing of incoming data is done after the ProcessMessage call returns,
* and we're no longer holding the node's locks.
*/ // 维护通过 cs_main 锁保护的节点特定的验证状态,而非 CNode 自己的锁。这简化了异步操作,在 ProcessMessage 调用返回后完成传入数据的处理,且我们不再持有节点的锁。
struct CNodeState { // 节点状态
//! The peer's address
CService address; // 对端地址
//! Whether we have a fully established connection.
bool fCurrentlyConnected; // 我们当前是否完全建立连接
//! Accumulated misbehaviour score for this peer.
int nMisbehavior;
//! Whether this peer should be disconnected and banned (unless whitelisted).
bool fShouldBan; // 是否断开或禁止对端连接(除非在白名单中)
//! String name of this peer (debugging/logging purposes).
std::string name; // 对端字符串类型的名字
//! List of asynchronously-determined block rejections to notify this peer about.
std::vector<CBlockReject> rejects; // 用于通知对端的异步确定的区块拒绝列表
//! The best known block we know this peer has announced.
CBlockIndex *pindexBestKnownBlock;
//! The hash of the last unknown block this peer has announced.
uint256 hashLastUnknownBlock;
//! The last full block we both have.
CBlockIndex *pindexLastCommonBlock;
//! The best header we have sent our peer.
CBlockIndex *pindexBestHeaderSent;
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted;
//! Since when we're stalling block download progress (in microseconds), or 0.
int64_t nStallingSince; // 当我们停止区块下载进度(以微秒为单位)的时间,或为 0。
list<QueuedBlock> vBlocksInFlight; // 飞行区块链表
//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. // 当飞行区块链表中首个条目开始下载。不关心该链表为空。
int64_t nDownloadingSince; // 下载开始时间
int nBlocksInFlight;
int nBlocksInFlightValidHeaders;
//! Whether we consider this a preferred download peer.
bool fPreferredDownload; // 我们是否认为这是首选的下载对端
//! Whether this peer wants invs or headers (when possible) for block announcements.
bool fPreferHeaders; // 该对端是否想要区块通知的 invs 和区块头
CNodeState() {
fCurrentlyConnected = false;
nMisbehavior = 0;
fShouldBan = false;
pindexBestKnownBlock = NULL;
hashLastUnknownBlock.SetNull();
pindexLastCommonBlock = NULL;
pindexBestHeaderSent = NULL;
fSyncStarted = false;
nStallingSince = 0;
nDownloadingSince = 0;
nBlocksInFlight = 0;
nBlocksInFlightValidHeaders = 0;
fPreferredDownload = false;
fPreferHeaders = false;
}
};
/** Map maintaining per-node state. Requires cs_main. */
map<NodeId, CNodeState> mapNodeState; // 维持每个节点状态映射列表
// Requires cs_main.
CNodeState *State(NodeId pnode) { // 通过节点 id 获取节点状态
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return NULL;
return &it->second;
}
int GetHeight() // 获取激活链的高度
{
LOCK(cs_main); // 上锁
return chainActive.Height(); // 返回激活链的高度
}
void UpdatePreferredDownload(CNode* node, CNodeState* state)
{
nPreferredDownload -= state->fPreferredDownload;
// Whether this node should be marked as a preferred download node.
state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
nPreferredDownload += state->fPreferredDownload;
}
void InitializeNode(NodeId nodeid, const CNode *pnode) {
LOCK(cs_main); // 上锁
CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; // 插入节点状态映射列表,并获取该节点状态的引用
state.name = pnode->addrName; // 修改状态名
state.address = pnode->addr; // 修改对端地址
}
void FinalizeNode(NodeId nodeid) {
LOCK(cs_main); // 上锁
CNodeState *state = State(nodeid); // 通过节点 id 创建节点状态对象
if (state->fSyncStarted) // 若节点数量非 0
nSyncStarted--; // 数量减 1
if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
AddressCurrentlyConnected(state->address);
}
BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
mapBlocksInFlight.erase(entry.hash);
}
EraseOrphansFor(nodeid);
nPreferredDownload -= state->fPreferredDownload;
nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
assert(nPeersWithValidatedDownloads >= 0);
mapNodeState.erase(nodeid); // 从节点状态映射列表中擦除该节点
if (mapNodeState.empty()) { // 若列表为空
// Do a consistency check after the last peer is removed. // 删除最后一个对等体后进行一致性检查
assert(mapBlocksInFlight.empty());
assert(nPreferredDownload == 0); // 优先区块下载对端数
assert(nPeersWithValidatedDownloads == 0); // 正在下载区块的对端数
}
}
// Requires cs_main.
// Returns a bool indicating whether we requested this block.
bool MarkBlockAsReceived(const uint256& hash) {
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) {
CNodeState *state = State(itInFlight->second.first);
state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
// Last validated block on the queue was received.
nPeersWithValidatedDownloads--;
}
if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
// First block on the queue was received, update the start download time for the next one
state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
}
state->vBlocksInFlight.erase(itInFlight->second.second);
state->nBlocksInFlight--;
state->nStallingSince = 0;
mapBlocksInFlight.erase(itInFlight);
return true;
}
return false;
}
// Requires cs_main.
void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
CNodeState *state = State(nodeid);
assert(state != NULL);
// Make sure it's not listed somewhere already.
MarkBlockAsReceived(hash);
QueuedBlock newentry = {hash, pindex, pindex != NULL};
list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
state->nBlocksInFlight++;
state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
if (state->nBlocksInFlight == 1) {
// We're starting a block download (batch) from this peer.
state->nDownloadingSince = GetTimeMicros();
}
if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
nPeersWithValidatedDownloads++;
}
mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
}
/** Check whether the last unknown block a peer advertized is not yet known. */
void ProcessBlockAvailability(NodeId nodeid) {
CNodeState *state = State(nodeid);
assert(state != NULL);
if (!state->hashLastUnknownBlock.IsNull()) {
BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = itOld->second;
state->hashLastUnknownBlock.SetNull();
}
}
}
/** Update tracking information about which blocks a peer is assumed to have. */ // 更新关于假定对端有那些区块的追踪信息
void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
CNodeState *state = State(nodeid);
assert(state != NULL);
ProcessBlockAvailability(nodeid);
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
// An actually better block was announced.
if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = it->second;
} else {
// An unknown block was announced; just assume that the latest one is the best one.
state->hashLastUnknownBlock = hash;
}
}
// Requires cs_main
bool CanDirectFetch(const Consensus::Params &consensusParams)
{
return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
}
// Requires cs_main
bool PeerHasHeader(CNodeState *state, CBlockIndex *pindex)
{
if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
return true;
if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
return true;
return false;
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */
CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
* at most count entries. */
void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
if (count == 0)
return;
vBlocks.reserve(vBlocks.size() + count);
CNodeState *state = State(nodeid);
assert(state != NULL);
// Make sure pindexBestKnownBlock is up to date, we'll need it.
ProcessBlockAvailability(nodeid);
if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
// This peer has nothing interesting.
return;
}
if (state->pindexLastCommonBlock == NULL) {
// Bootstrap quickly by guessing a parent of our best tip is the forking point.
// Guessing wrong in either direction is not a problem.
state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
}
// If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
// of its current tip anymore. Go back enough to fix that.
state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
return;
std::vector<CBlockIndex*> vToFetch;
CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
// Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
// linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
// download that next block if the window were 1 larger.
int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
NodeId waitingfor = -1;
while (pindexWalk->nHeight < nMaxHeight) {
// Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
// pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
// as iterating over ~100 CBlockIndex* entries anyway.
int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
vToFetch.resize(nToFetch);
pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
vToFetch[nToFetch - 1] = pindexWalk;
for (unsigned int i = nToFetch - 1; i > 0; i--) {
vToFetch[i - 1] = vToFetch[i]->pprev;
}
// Iterate over those blocks in vToFetch (in forward direction), adding the ones that
// are not yet downloaded and not in flight to vBlocks. In the mean time, update
// pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
// already part of our chain (and therefore don't need it even if pruned).
BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
if (!pindex->IsValid(BLOCK_VALID_TREE)) {
// We consider the chain that this peer is on invalid.
return;
}
if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
if (pindex->nChainTx)
state->pindexLastCommonBlock = pindex;
} else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
// The block is not already downloaded, and not yet in flight.
if (pindex->nHeight > nWindowEnd) {
// We reached the end of the window.
if (vBlocks.size() == 0 && waitingfor != nodeid) {
// We aren't able to fetch anything, but we would be if the download window was one larger.
nodeStaller = waitingfor;
}
return;
}
vBlocks.push_back(pindex);
if (vBlocks.size() == count) {
return;
}
} else if (waitingfor == -1) {
// This is the first already-in-flight block.
waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
}
}
}
}
} // anon namespace
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
LOCK(cs_main);
CNodeState *state = State(nodeid);
if (state == NULL)
return false;
stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
if (queue.pindex)
stats.vHeightInFlight.push_back(queue.pindex->nHeight);
}
return true;
}
void RegisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.connect(&GetHeight); // 获取激活的链高度
nodeSignals.ProcessMessages.connect(&ProcessMessages); // 处理消息,并进行响应
nodeSignals.SendMessages.connect(&SendMessages); // 发送消息
nodeSignals.InitializeNode.connect(&InitializeNode); // 初始化节点
nodeSignals.FinalizeNode.connect(&FinalizeNode); // 终止节点
}
void UnregisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.disconnect(&GetHeight);
nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
nodeSignals.SendMessages.disconnect(&SendMessages);
nodeSignals.InitializeNode.disconnect(&InitializeNode);
nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
}
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, locator.vHave) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (chain.Contains(pindex))
return pindex;
}
}
return chain.Genesis();
}
CCoinsViewCache *pcoinsTip = NULL;
CBlockTreeDB *pblocktree = NULL; // 区块树数据库指针
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
// // 孤儿交易映射列表
bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz > 5000)
{
LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
return false;
}
mapOrphanTransactions[hash].tx = tx;
mapOrphanTransactions[hash].fromPeer = peer;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
return true;
}
void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return;
BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
{
map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(hash);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
}
void EraseOrphansFor(NodeId peer)
{
int nErased = 0;
map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end())
{
map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
if (maybeErase->second.fromPeer == peer)
{
EraseOrphanTx(maybeErase->second.tx.GetHash());
++nErased;
}
}
if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
if (tx.nLockTime == 0) // 交易锁定时间为 0
return true;
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) // 锁定时间检测
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin) { // 遍历交易输入列表
if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL)) // 该交易的所有输入序列号有一笔不等于 CTxIn::SEQUENCE_FINAL
return false; // 非最终交易
}
return true;
}
bool CheckFinalTx(const CTransaction &tx, int flags)
{
AssertLockHeld(cs_main); // 检查主锁是否保持
// By convention a negative value for flags indicates that the
// current network-enforced consensus rules should be used. In
// a future soft-fork scenario that would mean checking which
// rules would be enforced for the next block and setting the
// appropriate flags. At the present time no soft-forks are
// scheduled, so no flags are set.
flags = std::max(flags, 0); // -1, 0
// CheckFinalTx() uses chainActive.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
// CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than chainActive.Height().
const int nBlockHeight = chainActive.Height() + 1; // 获取激活链高度并加 1
// BIP113 will require that time-locked transactions have nLockTime set to
// less than the median time of the previous block they're contained in.
// When the next block is created its previous block will be the current
// chain tip, so we use that to calculate the median time passed to
// IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) // 获取区块创建时间
? chainActive.Tip()->GetMedianTimePast()
: GetAdjustedTime();
return IsFinalTx(tx, nBlockHeight, nBlockTime); // 判断是否为最终交易
}
/**
* Calculates the block height and previous block's median time past at
* which the transaction will be considered final in the context of BIP 68.
* Also removes from the vector of input heights any entries which did not
* correspond to sequence locked inputs as they do not affect the calculation.
*/
static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
{
assert(prevHeights->size() == tx.vin.size());
// Will be set to the equivalent height- and time-based nLockTime
// values that would be necessary to satisfy all relative lock-
// time constraints given our view of block chain history.
// The semantics of nLockTime are the last invalid height/time, so
// use -1 to have the effect of any height or time being valid.
int nMinHeight = -1;
int64_t nMinTime = -1;
// tx.nVersion is signed integer so requires cast to unsigned otherwise
// we would be doing a signed comparison and half the range of nVersion
// wouldn't support BIP 68.
bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
&& flags & LOCKTIME_VERIFY_SEQUENCE;
// Do not enforce sequence numbers as a relative lock time
// unless we have been instructed to
if (!fEnforceBIP68) {
return std::make_pair(nMinHeight, nMinTime);
}
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
// Sequence numbers with the most significant bit set are not
// treated as relative lock-times, nor are they given any
// consensus-enforced meaning at this point.
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
// The height of this input is not relevant for sequence locks
(*prevHeights)[txinIndex] = 0;
continue;
}
int nCoinHeight = (*prevHeights)[txinIndex];
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
// NOTE: Subtract 1 to maintain nLockTime semantics
// BIP 68 relative lock times have the semantics of calculating
// the first block or time at which the transaction would be
// valid. When calculating the effective block time or height
// for the entire transaction, we switch to using the
// semantics of nLockTime which is the last invalid block
// time or height. Thus we subtract 1 from the calculated
// time or height.
// Time-based relative lock-times are measured from the
// smallest allowed timestamp of the block containing the
// txout being spent, which is the median time past of the
// block prior.
nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
} else {
nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
}
}
return std::make_pair(nMinHeight, nMinTime);
}
static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
{
assert(block.pprev);
int64_t nBlockTime = block.pprev->GetMedianTimePast();
if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
return false;
return true;
}
bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
{
return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
}
bool TestLockPointValidity(const LockPoints* lp)
{
AssertLockHeld(cs_main);
assert(lp);
// If there are relative lock times then the maxInputBlock will be set
// If there are no relative lock times, the LockPoints don't depend on the chain
if (lp->maxInputBlock) {
// Check whether chainActive is an extension of the block at which the LockPoints
// calculation was valid. If not LockPoints are no longer valid
if (!chainActive.Contains(lp->maxInputBlock)) {
return false;
}
}
// LockPoints still valid
return true;
}
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
{
AssertLockHeld(cs_main);
AssertLockHeld(mempool.cs);
CBlockIndex* tip = chainActive.Tip();
CBlockIndex index;
index.pprev = tip;
// CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
// height based locks because when SequenceLocks() is called within
// ConnectBlock(), the height of the block *being*
// evaluated is what is used.
// Thus if we want to know if a transaction can be part of the
// *next* block, we need to use one more than chainActive.Height()
index.nHeight = tip->nHeight + 1;
std::pair<int, int64_t> lockPair;
if (useExistingLockPoints) {
assert(lp);
lockPair.first = lp->height;
lockPair.second = lp->time;
}
else {
// pcoinsTip contains the UTXO set for chainActive.Tip()
CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
std::vector<int> prevheights;
prevheights.resize(tx.vin.size());
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
CCoins coins;
if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
return error("%s: Missing input", __func__);
}
if (coins.nHeight == MEMPOOL_HEIGHT) {
// Assume all mempool transaction confirm in the next block
prevheights[txinIndex] = tip->nHeight + 1;
} else {
prevheights[txinIndex] = coins.nHeight;
}
}
lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
if (lp) {
lp->height = lockPair.first;
lp->time = lockPair.second;
// Also store the hash of the block with the highest height of
// all the blocks which have sequence locked prevouts.
// This hash needs to still be on the chain
// for these LockPoint calculations to be valid
// Note: It is impossible to correctly calculate a maxInputBlock
// if any of the sequence locked inputs depend on unconfirmed txs,
// except in the special case where the relative lock time/height
// is 0, which is equivalent to no sequence lock. Since we assume
// input height of tip+1 for mempool txs and test the resulting
// lockPair from CalculateSequenceLocks against tip+1. We know
// EvaluateSequenceLocks will fail if there was a non-zero sequence
// lock on a mempool input, so we can use the return value of
// CheckSequenceLocks to indicate the LockPoints validity
int maxInputHeight = 0;
BOOST_FOREACH(int height, prevheights) {
// Can ignore mempool inputs since we'll fail if they had non-zero locks
if (height != tip->nHeight+1) {
maxInputHeight = std::max(maxInputHeight, height);
}
}
lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
}
}
return EvaluateSequenceLocks(index, lockPair);
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
{
if (tx.IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
bool CheckTransaction(const CTransaction& tx, CValidationState &state)
{
// Basic checks that don't depend on any context
if (tx.vin.empty()) // 输入不能为空
return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
if (tx.vout.empty()) // 输出不能为空
return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
// Size limits
if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) // 交易小于等于 MAX_BLOCK_SIZE
return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
// Check for negative or overflow output values // 检查小于或上溢的输出值
CAmount nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout) // 每个输出和其总量不能超过规定范围(0, 2,100万)
{
if (txout.nValue < 0)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
if (txout.nValue > MAX_MONEY)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
}
// Check for duplicate inputs // 检查重复输入
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (vInOutPoints.count(txin.prevout))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
vInOutPoints.insert(txin.prevout);
}
if (tx.IsCoinBase()) // 是否为创币交易
{
if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
}
else
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (txin.prevout.IsNull())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
}
return true;
}
void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
int expired = pool.Expire(GetTime() - age);
if (expired != 0)
LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
std::vector<uint256> vNoSpendsRemaining;
pool.TrimToSize(limit, &vNoSpendsRemaining);
BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
pcoinsTip->Uncache(removed);
}
/** Convert CValidationState to a human-readable message for logging */
std::string FormatStateMessage(const CValidationState &state)
{
return strprintf("%s%s (code %i)",
state.GetRejectReason(),
state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
state.GetRejectCode());
}
bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee,
std::vector<uint256>& vHashTxnToUncache)
{
AssertLockHeld(cs_main); // 验证持有主锁
if (pfMissingInputs)
*pfMissingInputs = false;
if (!CheckTransaction(tx, state)) // 检查交易状态
return false;
// Coinbase is only valid in a block, not as a loose transaction // 创币交易只在块中有效,而非一笔松散的交易
if (tx.IsCoinBase()) // 不能是创币交易
return state.DoS(100, false, REJECT_INVALID, "coinbase");
// Rather not work on nonstandard transactions (unless -testnet/-regtest) // 而不是非标准交易(除非 -testnet/-regtest)
string reason;
if (fRequireStandard && !IsStandardTx(tx, reason)) // 若要求标准交易,而非标准交易
return state.DoS(0, false, REJECT_NONSTANDARD, reason);
// Don't relay version 2 transactions until CSV is active, and we can be
// sure that such transactions will be mined (unless we're on
// -testnet/-regtest). // 在 CSV 激活前不要中继版本 2 交易,且我们可以确保这些交易将被挖(除非我们在 -testnet/-regtest)。
const CChainParams& chainparams = Params(); // 获取链参数
if (fRequireStandard && tx.nVersion >= 2 && VersionBitsTipState(chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV) != THRESHOLD_ACTIVE) {
return state.DoS(0, false, REJECT_NONSTANDARD, "premature-version2-tx");
}
// Only accept nLockTime-using transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet. // 只接受能被挖到下一个区块的使用 nLockTime 的交易;我们不想我们我们的矿池充满不能开采的交易。
if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS)) // 检查是否为最终交易(即能被挖到下一个区块的使用 nLockTime 的交易)
return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
// is it already in the memory pool? // 交易是否已经在内存池中?
uint256 hash = tx.GetHash(); // 获取交易哈希
if (pool.exists(hash)) // 检测该交易是否在内存池中已存在
return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
// Check for conflicts with in-memory transactions // 检测内存中的交易冲突
set<uint256> setConflicts; // 交易冲突集合
{
LOCK(pool.cs); // protect pool.mapNextTx
BOOST_FOREACH(const CTxIn &txin, tx.vin) // 便利该交易的输入列表
{
if (pool.mapNextTx.count(txin.prevout)) // 若该输入的上一笔输出存在于内存池下一笔交易映射列表
{ // 表示交易冲突
const CTransaction *ptxConflicting = pool.mapNextTx[txin.prevout].ptx; // 获取冲突的下一笔交易
if (!setConflicts.count(ptxConflicting->GetHash())) // 若该交易存在于交易冲突集合
{
// Allow opt-out of transaction replacement by setting
// nSequence >= maxint-1 on all inputs.
//
// maxint-1 is picked to still allow use of nLockTime by
// non-replacable transactions. All inputs rather than just one
// is for the sake of multi-party protocols, where we don't
// want a single party to be able to disable replacement.
//
// The opt-out ignores descendants as anyone relying on
// first-seen mempool behavior should be checking all
// unconfirmed ancestors anyway; doing otherwise is hopelessly
// insecure.
bool fReplacementOptOut = true; // 替换最优输出标志
if (fEnableReplacement) // 若开启了内存池替换
{
BOOST_FOREACH(const CTxIn &txin, ptxConflicting->vin) // 遍历冲突的交易输入列表
{
if (txin.nSequence < std::numeric_limits<unsigned int>::max()-1) // 若交易输入序列号小于 -1
{
fReplacementOptOut = false; // 替换最优输出标志置为 false
break;
}
}
}
if (fReplacementOptOut)
return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
setConflicts.insert(ptxConflicting->GetHash()); // 把该交易插入交易冲突集合
}
}
}
}
{
CCoinsView dummy; // 创建币视图对象
CCoinsViewCache view(&dummy); // 创建币视图缓存对象
CAmount nValueIn = 0;
LockPoints lp;
{
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do we already have it?
bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
if (view.HaveCoins(hash)) {
if (!fHadTxInCache)
vHashTxnToUncache.push_back(hash);
return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
}
// do all inputs exist? // 全部输入存在?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// and only helps with filling in pfMissingInputs (to determine missing vs spent).
BOOST_FOREACH(const CTxIn txin, tx.vin) {
if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
vHashTxnToUncache.push_back(txin.prevout.hash);
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
}
}
// are the actual inputs available? // 是可用的真正的输入?
if (!view.HaveInputs(tx)) // 查询是否有该交易的全部输入
return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
// Bring the best block into scope // 把最佳区块纳入范围
view.GetBestBlock(); // 获取最佳区块
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool // 现在我们缓存了全部的输入,切换回假,所以我们不需要锁定内存池
view.SetBackend(dummy);
// Only accept BIP68 sequence locked transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
// Must keep pool.cs for this unless we change CheckSequenceLocks to take a
// CoinsViewCache instead of create its own
if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
}
// Check for non-standard pay-to-script-hash in inputs
if (fRequireStandard && !AreInputsStandard(tx, view))
return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
unsigned int nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, view);
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn-nValueOut;
// nModifiedFees includes any fee deltas from PrioritiseTransaction
CAmount nModifiedFees = nFees;
double nPriorityDummy = 0;
pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
CAmount inChainInputValue;
double dPriority = view.GetPriority(tx, chainActive.Height(), inChainInputValue);
// Keep track of transactions that spend a coinbase, which we re-scan
// during reorgs to ensure COINBASE_MATURITY is still met.
bool fSpendsCoinbase = false;
BOOST_FOREACH(const CTxIn &txin, tx.vin) {
const CCoins *coins = view.AccessCoins(txin.prevout.hash);
if (coins->IsCoinBase()) {
fSpendsCoinbase = true;
break;
}
}
CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), pool.HasNoInputsOf(tx), inChainInputValue, fSpendsCoinbase, nSigOps, lp);
unsigned int nSize = entry.GetTxSize();
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
if ((nSigOps > MAX_STANDARD_TX_SIGOPS) || (nBytesPerSigOp && nSigOps > nSize / nBytesPerSigOp))
return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
strprintf("%d", nSigOps));
CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
} else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(chainActive.Height() + 1))) {
// Require that free transactions have sufficient priority to be mined in the next block.
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}
// Continuously rate-limit free (really, very-low-fee) transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize))
{
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
return state.Invalid(false,
REJECT_HIGHFEE, "absurdly-high-fee",
strprintf("%d > %d", nFees, ::minRelayTxFee.GetFee(nSize) * 10000));
// Calculate in-mempool ancestors, up to a limit.
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
}
// A transaction that spends outputs that would be replaced by it is invalid. Now
// that we have the set of all ancestors we can detect this
// pathological case by making sure setConflicts and setAncestors don't
// intersect.
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
{
const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
if (setConflicts.count(hashAncestor))
{
return state.DoS(10, error("AcceptToMemoryPool: %s spends conflicting transaction %s",
hash.ToString(),
hashAncestor.ToString()),
REJECT_INVALID, "bad-txns-spends-conflicting-tx");
}
}
// Check if it's economically rational to mine this transaction rather
// than the ones it replaces.
CAmount nConflictingFees = 0;
size_t nConflictingSize = 0;
uint64_t nConflictingCount = 0;
CTxMemPool::setEntries allConflicting;
// If we don't hold the lock allConflicting might be incomplete; the
// subsequent RemoveStaged() and addUnchecked() calls don't guarantee
// mempool consistency for us.
LOCK(pool.cs);
if (setConflicts.size())
{
CFeeRate newFeeRate(nModifiedFees, nSize);
set<uint256> setConflictsParents;
const int maxDescendantsToVisit = 100;
CTxMemPool::setEntries setIterConflicting;
BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
{
CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
if (mi == pool.mapTx.end())
continue;
// Save these to avoid repeated lookups
setIterConflicting.insert(mi);
// If this entry is "dirty", then we don't have descendant
// state for this transaction, which means we probably have
// lots of in-mempool descendants.
// Don't allow replacements of dirty transactions, to ensure
// that we don't spend too much time walking descendants.
// This should be rare.
if (mi->IsDirty()) {
return state.DoS(0,
error("AcceptToMemoryPool: rejecting replacement %s; cannot replace tx %s with untracked descendants",
hash.ToString(),
mi->GetTx().GetHash().ToString()),
REJECT_NONSTANDARD, "too many potential replacements");
}
// Don't allow the replacement to reduce the feerate of the
// mempool.
//
// We usually don't want to accept replacements with lower
// feerates than what they replaced as that would lower the
// feerate of the next block. Requiring that the feerate always
// be increased is also an easy-to-reason about way to prevent
// DoS attacks via replacements.
//
// The mining code doesn't (currently) take children into
// account (CPFP) so we only consider the feerates of
// transactions being directly replaced, not their indirect
// descendants. While that does mean high feerate children are
// ignored when deciding whether or not to replace, we do
// require the replacement to pay more overall fees too,
// mitigating most cases.
CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
if (newFeeRate <= oldFeeRate)
{
return state.DoS(0,
error("AcceptToMemoryPool: rejecting replacement %s; new feerate %s <= old feerate %s",
hash.ToString(),
newFeeRate.ToString(),
oldFeeRate.ToString()),
REJECT_INSUFFICIENTFEE, "insufficient fee");
}
BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
{
setConflictsParents.insert(txin.prevout.hash);
}
nConflictingCount += mi->GetCountWithDescendants();
}
// This potentially overestimates the number of actual descendants
// but we just want to be conservative to avoid doing too much
// work.
if (nConflictingCount <= maxDescendantsToVisit) {
// If not too many to replace, then calculate the set of
// transactions that would have to be evicted
BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
pool.CalculateDescendants(it, allConflicting);
}
BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
nConflictingFees += it->GetModifiedFee();
nConflictingSize += it->GetTxSize();
}
} else {
return state.DoS(0,
error("AcceptToMemoryPool: rejecting replacement %s; too many potential replacements (%d > %d)\n",
hash.ToString(),
nConflictingCount,
maxDescendantsToVisit),
REJECT_NONSTANDARD, "too many potential replacements");
}
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
// We don't want to accept replacements that require low
// feerate junk to be mined first. Ideally we'd keep track of
// the ancestor feerates and make the decision based on that,
// but for now requiring all new inputs to be confirmed works.
if (!setConflictsParents.count(tx.vin[j].prevout.hash))
{
// Rather than check the UTXO set - potentially expensive -
// it's cheaper to just check if the new input refers to a
// tx that's in the mempool.
if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
return state.DoS(0, error("AcceptToMemoryPool: replacement %s adds unconfirmed input, idx %d",
hash.ToString(), j),
REJECT_NONSTANDARD, "replacement-adds-unconfirmed");
}
}
// The replacement must pay greater fees than the transactions it
// replaces - if we did the bandwidth used by those conflicting
// transactions would not be paid for.
if (nModifiedFees < nConflictingFees)
{
return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s, less fees than conflicting txs; %s < %s",
hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)),
REJECT_INSUFFICIENTFEE, "insufficient fee");
}
// Finally in addition to paying more fees than the conflicts the
// new transaction must pay for its own bandwidth.
CAmount nDeltaFees = nModifiedFees - nConflictingFees;
if (nDeltaFees < ::minRelayTxFee.GetFee(nSize))
{
return state.DoS(0,
error("AcceptToMemoryPool: rejecting replacement %s, not enough additional fees to relay; %s < %s",
hash.ToString(),
FormatMoney(nDeltaFees),
FormatMoney(::minRelayTxFee.GetFee(nSize))),
REJECT_INSUFFICIENTFEE, "insufficient fee");
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
return false;
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
{
return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
__func__, hash.ToString(), FormatStateMessage(state));
}
// Remove conflicting transactions from the mempool
BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
{
LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
it->GetTx().GetHash().ToString(),
hash.ToString(),
FormatMoney(nModifiedFees - nConflictingFees),
(int)nSize - (int)nConflictingSize);
}
pool.RemoveStaged(allConflicting);
// Store transaction in memory
pool.addUnchecked(hash, entry, setAncestors, !IsInitialBlockDownload());
// trim mempool and check if tx was trimmed
if (!fOverrideMempoolLimit) {
LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
if (!pool.exists(hash))
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
}
}
SyncWithWallets(tx, NULL); // 同步交易到钱包
return true; // 成功返回 true
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee)
{
std::vector<uint256> vHashTxToUncache; // 未缓存交易哈希列表
bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, fOverrideMempoolLimit, fRejectAbsurdFee, vHashTxToUncache); // 接收到内存池工作者
if (!res) { // 若添加失败
BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache) // 遍历未缓存的交易哈希列表
pcoinsTip->Uncache(hashTx); // 从缓存中移除该交易索引
}
return res;
}
/** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
bool GetTransaction(const uint256 &hash, CTransaction &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
{
CBlockIndex *pindexSlow = NULL;
LOCK(cs_main);
if (mempool.lookup(hash, txOut))
{
return true;
}
if (fTxIndex) {
CDiskTxPos postx;
if (pblocktree->ReadTxIndex(hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
if (file.IsNull())
return error("%s: OpenBlockFile failed", __func__);
CBlockHeader header;
try {
file >> header;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> txOut;
} catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
hashBlock = header.GetHash();
if (txOut.GetHash() != hash)
return error("%s: txid mismatch", __func__);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
int nHeight = -1;
{
CCoinsViewCache &view = *pcoinsTip;
const CCoins* coins = view.AccessCoins(hash);
if (coins)
nHeight = coins->nHeight;
}
if (nHeight > 0)
pindexSlow = chainActive[nHeight];
}
if (pindexSlow) {
CBlock block;
if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
BOOST_FOREACH(const CTransaction &tx, block.vtx) {
if (tx.GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex // 区块和区块索引
//
bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("WriteBlockToDisk: OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(block);
fileout << FLATDATA(messageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("WriteBlockToDisk: ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
{
block.SetNull();
// Open history file to read // 打开并读历史文件
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) // 检查读取状态
return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
// Read block
try {
filein >> block; // 导入区块数据
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
}
// Check the header // 检查区块头
if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams)) // 通过区块哈希,区块难度和共识参数检查工作量证明
return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams)) // 调用重载函数读取区块信息到 block 对象
return false;
if (block.GetHash() != pindex->GetBlockHash()) // 验证读取的区块哈希
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
pindex->ToString(), pindex->GetBlockPos().ToString());
return true;
}
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams) // 获取当前的区块奖励
{
int halvings = nHeight / consensusParams.nSubsidyHalvingInterval; // 链高度(当前块数) / 奖励减半间隔(在 3 个网络中初始化)
// Force block reward to zero when right shift is undefined. // 当右移是未定义的大小时,强制块奖励为 0。
if (halvings >= 64) // 区块奖励 nSubsidy 最大右移 63 位
return 0;
CAmount nSubsidy = 50 * COIN; // CAmount 是 int64_t 类型
// Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years. // 区块奖励每 210,000 块进行减半,大概每 4 年发生一次。
nSubsidy >>= halvings; // 右移减半
return nSubsidy; // 返回当前区块奖励
}
bool IsInitialBlockDownload()
{
const CChainParams& chainParams = Params();
LOCK(cs_main);
if (fImporting || fReindex)
return true;
if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
return true;
static bool lockIBDState = false;
if (lockIBDState)
return false;
bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge()); // 最新的块据当前时间的间隔不能超过 nMaxTipAge,否则不能挖矿
if (!state)
lockIBDState = true;
return state; // 只有从这里返回,才满足挖矿条件
}
bool fLargeWorkForkFound = false;
bool fLargeWorkInvalidChainFound = false;
CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
void CheckForkWarningConditions()
{
AssertLockHeld(cs_main);
// Before we get past initial download, we cannot reliably alert about forks
// (we assume we don't get stuck on a fork before the last checkpoint)
if (IsInitialBlockDownload())
return;
// If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
// of our head, drop it
if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
pindexBestForkTip = NULL;
if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
{
if (!fLargeWorkForkFound && pindexBestForkBase)
{
std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
pindexBestForkBase->phashBlock->ToString() + std::string("'");
CAlert::Notify(warning, true);
}
if (pindexBestForkTip && pindexBestForkBase)
{
LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
fLargeWorkForkFound = true;
}
else
{
LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
fLargeWorkInvalidChainFound = true;
}
}
else
{
fLargeWorkForkFound = false;
fLargeWorkInvalidChainFound = false;
}
}
void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
{
AssertLockHeld(cs_main);
// If we are on a fork that is sufficiently large, set a warning flag
CBlockIndex* pfork = pindexNewForkTip;
CBlockIndex* plonger = chainActive.Tip();
while (pfork && pfork != plonger)
{
while (plonger && plonger->nHeight > pfork->nHeight)
plonger = plonger->pprev;
if (pfork == plonger)
break;
pfork = pfork->pprev;
}
// We define a condition where we should warn the user about as a fork of at least 7 blocks
// with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
// We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
// hash rate operating on the fork.
// or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
// We define it this way because it allows us to only store the highest fork tip (+ base) which meets
// the 7-block condition and from this always have the most-likely-to-cause-warning fork
if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
chainActive.Height() - pindexNewForkTip->nHeight < 72)
{
pindexBestForkTip = pindexNewForkTip;
pindexBestForkBase = pfork;
}
CheckForkWarningConditions();
}
// Requires cs_main.
void Misbehaving(NodeId pnode, int howmuch)
{
if (howmuch == 0)
return;
CNodeState *state = State(pnode);
if (state == NULL)
return;
state->nMisbehavior += howmuch;
int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
{
LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
state->fShouldBan = true;
} else
LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
pindexBestInvalid = pindexNew;
LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
pindexNew->GetBlockTime()));
CBlockIndex *tip = chainActive.Tip();
assert (tip);
LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
CheckForkWarningConditions();
}
void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
if (it != mapBlockSource.end() && State(it->second)) {
assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
State(it->second)->rejects.push_back(reject);
if (nDoS > 0)
Misbehaving(it->second, nDoS);
}
}
if (!state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
InvalidChainFound(pindex);
}
}
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase()) {
txundo.vprevout.reserve(tx.vin.size());
BOOST_FOREACH(const CTxIn &txin, tx.vin) {
CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
unsigned nPos = txin.prevout.n;
if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
assert(false);
// mark an outpoint spent, and construct undo information
txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
coins->Spend(nPos);
if (coins->vout.size() == 0) {
CTxInUndo& undo = txundo.vprevout.back();
undo.nHeight = coins->nHeight;
undo.fCoinBase = coins->fCoinBase;
undo.nVersion = coins->nVersion;
}
}
// add outputs
inputs.ModifyNewCoins(tx.GetHash())->FromTx(tx, nHeight);
}
else {
// add outputs for coinbase tx
// In this case call the full ModifyCoins which will do a database
// lookup to be sure the coins do not already exist otherwise we do not
// know whether to mark them fresh or not. We want the duplicate coinbases
// before BIP30 to still be properly overwritten.
inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
}
}
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
{
CTxUndo txundo;
UpdateCoins(tx, state, inputs, txundo, nHeight);
}
bool CScriptCheck::operator()() {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig; // 获取交易指定输入的脚本签名
if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) { // 验证脚本
return false;
}
return true;
}
int GetSpendHeight(const CCoinsViewCache& inputs)
{
LOCK(cs_main);
CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
return pindexPrev->nHeight + 1;
}
namespace Consensus {
bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
{
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!inputs.HaveInputs(tx))
return state.Invalid(false, 0, "", "Inputs unavailable");
CAmount nValueIn = 0;
CAmount nFees = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins *coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// If prev is coinbase, check that it's matured
if (coins->IsCoinBase()) {
if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
return state.Invalid(false,
REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
}
// Check for negative or overflow input values
nValueIn += coins->vout[prevout.n].nValue;
if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
}
if (nValueIn < tx.GetValueOut())
return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
// Tally transaction fees
CAmount nTxFee = nValueIn - tx.GetValueOut();
if (nTxFee < 0)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
nFees += nTxFee;
if (!MoneyRange(nFees))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
return true;
}
}// namespace Consensus
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
{
if (!tx.IsCoinBase())
{
if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
return false;
if (pvChecks)
pvChecks->reserve(tx.vin.size());
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip ECDSA signature verification when connecting blocks
// before the last block chain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (fScriptChecks) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins* coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// Verify signature
CScriptCheck check(*coins, tx, i, flags, cacheStore);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-standard DER encodings or non-null dummy
// arguments; if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
CScriptCheck check2(*coins, tx, i,
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
if (check2())
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. a invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after a soft-fork
// super-majority vote has passed.
return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
}
}
return true;
}
namespace {
bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: OpenUndoFile failed", __func__);
// Write index header
unsigned int nSize = fileout.GetSerializeSize(blockundo);
fileout << FLATDATA(messageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("%s: ftell failed", __func__);
pos.nPos = (unsigned int)fileOutPos;
fileout << blockundo;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << blockundo;
fileout << hasher.GetHash();
return true;
}
bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to read
CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s: OpenBlockFile failed", __func__);
// Read block
uint256 hashChecksum;
try {
filein >> blockundo;
filein >> hashChecksum;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << blockundo;
if (hashChecksum != hasher.GetHash())
return error("%s: Checksum mismatch", __func__);
return true;
}
/** Abort with a message */
bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
{
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
{
AbortNode(strMessage, userMessage);
return state.Error(strMessage);
}
} // anon namespace
/**
* Apply the undo operation of a CTxInUndo to the given chain state.
* @param undo The undo object.
* @param view The coins view to which to apply the changes.
* @param out The out point that corresponds to the tx input.
* @return True on success.
*/
static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
{
bool fClean = true;
CCoinsModifier coins = view.ModifyCoins(out.hash);
if (undo.nHeight != 0) {
// undo data contains height: this is the last output of the prevout tx being spent
if (!coins->IsPruned())
fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
coins->Clear();
coins->fCoinBase = undo.fCoinBase;
coins->nHeight = undo.nHeight;
coins->nVersion = undo.nVersion;
} else {
if (coins->IsPruned())
fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
}
if (coins->IsAvailable(out.n))
fClean = fClean && error("%s: undo data overwriting existing output", __func__);
if (coins->vout.size() < out.n+1)
coins->vout.resize(out.n+1);
coins->vout[out.n] = undo.txout;
return fClean;
}
bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
{
assert(pindex->GetBlockHash() == view.GetBestBlock());
if (pfClean)
*pfClean = false;
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
return error("DisconnectBlock(): no undo data available");
if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
return error("DisconnectBlock(): failure reading undo data");
if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
return error("DisconnectBlock(): block and undo data inconsistent");
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--) {
const CTransaction &tx = block.vtx[i];
uint256 hash = tx.GetHash();
// Check that all outputs are available and match the outputs in the block itself
// exactly.
{
CCoinsModifier outs = view.ModifyCoins(hash);
outs->ClearUnspendable();
CCoins outsBlock(tx, pindex->nHeight);
// The CCoins serialization does not serialize negative numbers.
// No network rules currently depend on the version here, so an inconsistency is harmless
// but it must be corrected before txout nversion ever influences a network rule.
if (outsBlock.nVersion < 0)
outs->nVersion = outsBlock.nVersion;
if (*outs != outsBlock)
fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
// remove outputs
outs->Clear();
}
// restore inputs
if (i > 0) { // not coinbases
const CTxUndo &txundo = blockUndo.vtxundo[i-1];
if (txundo.vprevout.size() != tx.vin.size())
return error("DisconnectBlock(): transaction and undo data inconsistent");
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint &out = tx.vin[j].prevout;
const CTxInUndo &undo = txundo.vprevout[j];
if (!ApplyTxInUndo(undo, view, out))
fClean = false;
}
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
if (pfClean) {
*pfClean = fClean;
return true;
}
return fClean;
}
void static FlushBlockFile(bool fFinalize = false)
{
LOCK(cs_LastBlockFile);
CDiskBlockPos posOld(nLastBlockFile, 0); // 构建磁盘区块位置对象
FILE *fileOld = OpenBlockFile(posOld); // 打开最后一个区块文件
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize); // 截短最后一个文件的大小
FileCommit(fileOld); // 文件提交
fclose(fileOld); // 关闭文件
}
fileOld = OpenUndoFile(posOld); // 打开恢复文件
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize); // 截短文件
FileCommit(fileOld); // 提价文件
fclose(fileOld); // 关闭文件
}
}
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
static CCheckQueue<CScriptCheck> scriptcheckqueue(128); // 脚本检查队列,队列容量为 128
void ThreadScriptCheck() {
RenameThread("bitcoin-scriptch"); // 1.重命名线程
scriptcheckqueue.Thread(); // 2.执行线程工作函数
}
//
// Called periodically asynchronously; alerts if it smells like
// we're being fed a bad chain (blocks being generated much
// too slowly or too quickly).
//
void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
int64_t nPowTargetSpacing)
{
if (bestHeader == NULL || initialDownloadCheck()) return;
static int64_t lastAlertTime = 0;
int64_t now = GetAdjustedTime();
if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
const int SPAN_HOURS=4;
const int SPAN_SECONDS=SPAN_HOURS*60*60;
int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
std::string strWarning;
int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
LOCK(cs);
const CBlockIndex* i = bestHeader;
int nBlocks = 0;
while (i->GetBlockTime() >= startTime) {
++nBlocks;
i = i->pprev;
if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
}
// How likely is it to find that many by chance?
double p = boost::math::pdf(poisson, nBlocks);
LogPrint("partitioncheck", "%s: Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
LogPrint("partitioncheck", "%s: likelihood: %g\n", __func__, p);
// Aim for one false-positive about every fifty years of normal running:
const int FIFTY_YEARS = 50*365*24*60*60;
double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
{
// Many fewer blocks than expected: alert!
strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
}
else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
{
// Many more blocks than expected: alert!
strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
}
if (!strWarning.empty())
{
strMiscWarning = strWarning;
CAlert::Notify(strWarning, true);
lastAlertTime = now;
}
}
// Protected by cs_main
static VersionBitsCache versionbitscache;
int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
{
LOCK(cs_main);
int32_t nVersion = VERSIONBITS_TOP_BITS;
for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
}
}
return nVersion;
}
/**
* Threshold condition checker that triggers when unknown versionbits are seen on the network.
*/
class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
{
private:
int bit;
public:
WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
int64_t BeginTime(const Consensus::Params& params) const { return 0; }
int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
{
return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
((pindex->nVersion >> bit) & 1) != 0 &&
((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
}
};
// Protected by cs_main
static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
static int64_t nTimeCheck = 0;
static int64_t nTimeForks = 0;
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
{
const CChainParams& chainparams = Params();
AssertLockHeld(cs_main);
int64_t nTimeStart = GetTimeMicros();
// Check it again in case a previous version let a bad block in
if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
return false;
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
assert(hashPrevBlock == view.GetBestBlock());
// Special case for the genesis block, skipping connection of its transactions
// (its coinbase is unspendable)
if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
if (!fJustCheck)
view.SetBestBlock(pindex->GetBlockHash());
return true;
}
bool fScriptChecks = true;
if (fCheckpointsEnabled) {
CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
// This block is an ancestor of a checkpoint: disable script checks
fScriptChecks = false;
}
}
int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes during their
// initial block download.
bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
!((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
(pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
// Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
// with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
// time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
// before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
// duplicate transactions descending from the known pairs either.
// If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
//Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
if (fEnforceBIP30) {
BOOST_FOREACH(const CTransaction& tx, block.vtx) {
const CCoins* coins = view.AccessCoins(tx.GetHash());
if (coins && !coins->IsPruned())
return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
REJECT_INVALID, "bad-txns-BIP30");
}
}
// BIP16 didn't become active until Apr 1 2012
int64_t nBIP16SwitchTime = 1333238400;
bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
// Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
// when 75% of the network has upgraded:
if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
flags |= SCRIPT_VERIFY_DERSIG;
}
// Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
// blocks, when 75% of the network has upgraded:
if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
}
// Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
int nLockTimeFlags = 0;
if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
}
int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
std::vector<int> prevheights;
CAmount nFees = 0;
int nInputs = 0;
unsigned int nSigOps = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
vPos.reserve(block.vtx.size());
blockundo.vtxundo.reserve(block.vtx.size() - 1);
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const CTransaction &tx = block.vtx[i];
nInputs += tx.vin.size();
nSigOps += GetLegacySigOpCount(tx);
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
if (!tx.IsCoinBase())
{
if (!view.HaveInputs(tx))
return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
// Check that transaction is BIP68 final
// BIP68 lock checks (as opposed to nLockTime checks) must
// be in ConnectBlock because they require the UTXO set
prevheights.resize(tx.vin.size());
for (size_t j = 0; j < tx.vin.size(); j++) {
prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
}
if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
REJECT_INVALID, "bad-txns-nonfinal");
}
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
}
nFees += view.GetValueIn(tx)-tx.GetValueOut();
std::vector<CScriptCheck> vChecks;
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL))
return error("ConnectBlock(): CheckInputs on %s failed with %s",
tx.GetHash().ToString(), FormatStateMessage(state));
control.Add(vChecks);
}
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
}
UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
vPos.push_back(std::make_pair(tx.GetHash(), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
if (block.vtx[0].GetValueOut() > blockReward)
return state.DoS(100,
error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
block.vtx[0].GetValueOut(), blockReward),
REJECT_INVALID, "bad-cb-amount");
if (!control.Wait())
return state.DoS(100, false);
int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
{
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos pos;
if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
return error("ConnectBlock(): FindUndoPos failed");
if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
return AbortNode(state, "Failed to write undo data");
// update nUndoPos in block index
pindex->nUndoPos = pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
setDirtyBlockIndex.insert(pindex);
}
if (fTxIndex)
if (!pblocktree->WriteTxIndex(vPos))
return AbortNode(state, "Failed to write transaction index");
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
// Watch for changes to the previous coinbase transaction.
static uint256 hashPrevBestCoinBase;
GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = block.vtx[0].GetHash();
int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
return true;
}
enum FlushStateMode {
FLUSH_STATE_NONE,
FLUSH_STATE_IF_NEEDED,
FLUSH_STATE_PERIODIC,
FLUSH_STATE_ALWAYS
};
/**
* Update the on-disk chain state.
* The caches and indexes are flushed depending on the mode we're called with
* if they're too large, if it's been a while since the last write,
* or always and in all cases if we're in prune mode and are deleting files.
*/ // 更新磁盘上的链状态。缓存和索引根据我们调用的模式刷新,如果它们太大,或经上次写入已有一段时间,或总在所有情况下,我们处于修剪模式并正在删除文件。
bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
const CChainParams& chainparams = Params();
LOCK2(cs_main, cs_LastBlockFile);
static int64_t nLastWrite = 0;
static int64_t nLastFlush = 0;
static int64_t nLastSetChain = 0;
std::set<int> setFilesToPrune; // 修剪的文件集合
bool fFlushForPrune = false;
try {
if (fPruneMode && fCheckForPruning && !fReindex) {
FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
fCheckForPruning = false;
if (!setFilesToPrune.empty()) {
fFlushForPrune = true;
if (!fHavePruned) {
pblocktree->WriteFlag("prunedblockfiles", true);
fHavePruned = true;
}
}
}
int64_t nNow = GetTimeMicros();
// Avoid writing/flushing immediately after startup. // 避免在启动后立刻写入/刷新。
if (nLastWrite == 0) {
nLastWrite = nNow;
}
if (nLastFlush == 0) {
nLastFlush = nNow;
}
if (nLastSetChain == 0) {
nLastSetChain = nNow;
}
size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); // 获取动态内存用量
// The cache is large and close to the limit, but we have time now (not in the middle of a block processing). // 缓存很大并接近极限,但我们现在有时间(不再块处理的中间)。
bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
// The cache is over the limit, we have to write now. // 缓存超过极限,我们现在写入。
bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. // 这需要一段时间,因为我们写区块索引到磁盘。经常这么做,所以我们不需要在崩溃后重新下载
bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. // 这会花很长时间,因为我们刷新了缓存。不常这样做,以优化缓存使用。
bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
// Combine all conditions that result in a full cache flush. // 合并所有导致完整缓存刷新的条件。
bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
// Write blocks and block index to disk. // 写入区块和区块索引到磁盘。
if (fDoFullFlush || fPeriodicWrite) {
// Depend on nMinDiskSpace to ensure we can write block index // 基于 nMinDiskSpace 以确保我们能写入区块索引
if (!CheckDiskSpace(0)) // 检查当前的磁盘空间
return state.Error("out of disk space");
// First make sure all block and undo data is flushed to disk. // 首次确保全部区块和恢复数据被刷新到磁盘
FlushBlockFile(); // 刷新区块文件
// Then update all block file information (which may refer to block and undo files). // 然后更新全部区块文件信息(可能参照区块和恢复文件)。
{
std::vector<std::pair<int, const CBlockFileInfo*> > vFiles; // <脏掉的文件号,区块文件信息指针>
vFiles.reserve(setDirtyFileInfo.size());
for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
setDirtyFileInfo.erase(it++);
}
std::vector<const CBlockIndex*> vBlocks; // 区块索引列表
vBlocks.reserve(setDirtyBlockIndex.size());
for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { // 遍历脏掉的区块索引集合
vBlocks.push_back(*it);
setDirtyBlockIndex.erase(it++);
}
if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { // 批量写入同步
return AbortNode(state, "Files to write to block index database");
}
}
// Finally remove any pruned files // 最终移除所有修剪的文件
if (fFlushForPrune)
UnlinkPrunedFiles(setFilesToPrune);
nLastWrite = nNow;
}
// Flush best chain related state. This can only be done if the blocks / block index write was also done. // 刷新最佳链相关的状态。该操作仅在区块/区块索引写入完成后执行。
if (fDoFullFlush) {
// Typical CCoins structures on disk are around 128 bytes in size. // 磁盘上的 CCoins 典型结构约 128 字节。
// Pushing a new one to the database can cause it to be written // 将推送一个新数据到数据库可能导致
// twice (once in the log, and once in the tables). This is already // 它被写入 2 次(一次在日志中,一次在表中)。
// an overestimation, as most will delete an existing entry or // 这已经是高估了,因为大多数人会删除现有条目或覆盖现有条目。
// overwrite one. Still, use a conservative safety factor of 2. // 仍使用保守的安全系数 2。
if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
return state.Error("out of disk space");
// Flush the chainstate (which may refer to block index entries). // 刷新链状态(可参考区块索引条目)。
if (!pcoinsTip->Flush())
return AbortNode(state, "Failed to write to coin database");
nLastFlush = nNow;
}
if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
// Update best block in wallet (so we can detect restored wallets). // 在钱包中更新最佳区块(以至于我们能检测到恢复的钱包)。
GetMainSignals().SetBestChain(chainActive.GetLocator());
nLastSetChain = nNow;
}
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error while flushing: ") + e.what());
}
return true; // 本地化状态成功返回 true
}
void FlushStateToDisk() {
CValidationState state;
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
}
void PruneAndFlush() {
CValidationState state;
fCheckForPruning = true; // 全局修剪标志置为 true
FlushStateToDisk(state, FLUSH_STATE_NONE); // 刷新磁盘上的链状态
}
/** Update chainActive and related internal data structures. */
void static UpdateTip(CBlockIndex *pindexNew) {
const CChainParams& chainParams = Params();
chainActive.SetTip(pindexNew);
// New best block
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
cvBlockChange.notify_all();
// Check the version of the last 100 blocks to see if we need to upgrade:
static bool fWarned = false;
if (!IsInitialBlockDownload())
{
int nUpgraded = 0;
const CBlockIndex* pindex = chainActive.Tip();
for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
WarningBitsConditionChecker checker(bit);
ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
if (state == THRESHOLD_ACTIVE) {
strMiscWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
if (!fWarned) {
CAlert::Notify(strMiscWarning, true);
fWarned = true;
}
} else {
LogPrintf("%s: unknown new rules are about to activate (versionbit %i)\n", __func__, bit);
}
}
}
for (int i = 0; i < 100 && pindex != NULL; i++)
{
int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
LogPrintf("%s: %d of last 100 blocks have unexpected version\n", __func__, nUpgraded);
if (nUpgraded > 100/2)
{
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
if (!fWarned) {
CAlert::Notify(strMiscWarning, true);
fWarned = true;
}
}
}
}
/** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */ // 断开激活的链尖。你可能想要调用 mempool.removeForReorg 并在该操作后手动再次限制内存池大小,同时持有主锁。
bool static DisconnectTip(CValidationState& state, const Consensus::Params& consensusParams)
{
CBlockIndex *pindexDelete = chainActive.Tip(); // 获取链尖区块索引
assert(pindexDelete);
// Read block from disk. // 从磁盘读区块
CBlock block;
if (!ReadBlockFromDisk(block, pindexDelete, consensusParams)) // 根据区块索引从磁盘读取区块到内存 block
return AbortNode(state, "Failed to read block");
// Apply the block atomically to the chain state. // 原子方式应用区块到链状态
int64_t nStart = GetTimeMicros(); // 获取当前时间
{
CCoinsViewCache view(pcoinsTip);
if (!DisconnectBlock(block, state, pindexDelete, view)) // 断开区块
return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
assert(view.Flush());
}
LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Write the chain state to disk, if necessary. // 如果需要,把链状态写到磁盘
if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED)) // 刷新链状态到磁盘
return false;
// Resurrect mempool transactions from the disconnected block. // 从断开链接的区块恢复交易到内存池
std::vector<uint256> vHashUpdate; // 待升级的交易哈希列表
BOOST_FOREACH(const CTransaction &tx, block.vtx) { // 遍历断开区块的交易列表
// ignore validation errors in resurrected transactions // 在恢复的交易中沪铝验证错误
list<CTransaction> removed;
CValidationState stateDummy;
if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL, true)) { // 若该交易为创币交易,则接受到内存池后
mempool.remove(tx, removed, true); // 从内存池中移除该交易
} else if (mempool.exists(tx.GetHash())) { // 否则若内存池中存在该交易
vHashUpdate.push_back(tx.GetHash()); // 加入到待升级的交易列表
}
}
// AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
// no in-mempool children, which is generally not true when adding
// previously-confirmed transactions back to the mempool.
// UpdateTransactionsFromBlock finds descendants of any transactions in this
// block that were added back and cleans up the mempool state.
mempool.UpdateTransactionsFromBlock(vHashUpdate); // 内存池更新来自区块的交易
// Update chainActive and related variables. // 更新激活链和相关变量
UpdateTip(pindexDelete->pprev); // 更新链尖为已删除链尖的前一个区块
// Let wallets know transactions went from 1-confirmed to
// 0-confirmed or conflicted:
BOOST_FOREACH(const CTransaction &tx, block.vtx) { // 遍历已删除区块的交易列表
SyncWithWallets(tx, NULL); // 同步到钱包
}
return true; // 返回 true
}
static int64_t nTimeReadFromDisk = 0;
static int64_t nTimeConnectTotal = 0;
static int64_t nTimeFlush = 0;
static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0;
/**
* Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*/
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const CBlock* pblock)
{
assert(pindexNew->pprev == chainActive.Tip());
// Read block from disk.
int64_t nTime1 = GetTimeMicros();
CBlock block;
if (!pblock) {
if (!ReadBlockFromDisk(block, pindexNew, chainparams.GetConsensus()))
return AbortNode(state, "Failed to read block");
pblock = █
}
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
{
CCoinsViewCache view(pcoinsTip);
bool rv = ConnectBlock(*pblock, state, pindexNew, view);
GetMainSignals().BlockChecked(*pblock, state);
if (!rv) {
if (state.IsInvalid())
InvalidBlockFound(pindexNew, state);
return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
}
mapBlockSource.erase(pindexNew->GetBlockHash());
nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
assert(view.Flush());
}
int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
return false;
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
// Remove conflicting transactions from the mempool.
list<CTransaction> txConflicted;
mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
// Update chainActive & related variables.
UpdateTip(pindexNew);
// Tell wallet about transactions that went from mempool
// to conflicted:
BOOST_FOREACH(const CTransaction &tx, txConflicted) {
SyncWithWallets(tx, NULL);
}
// ... and about transactions that got confirmed:
BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
SyncWithWallets(tx, pblock);
}
int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
return true;
}
/**
* Return the tip of the chain with the most work in it, that isn't
* known to be invalid (it's however far from certain to be valid).
*/ // 返回包含最多工作量的链尖区块索引,但不知道是否无效(不确定是否有效)。
static CBlockIndex* FindMostWorkChain() {
do {
CBlockIndex *pindexNew = NULL;
// Find the best candidate header. // 找到最佳候选区块头
{
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend())
return NULL;
pindexNew = *it;
}
// Check whether all blocks on the path between the currently active chain and the candidate are valid. // 检查在当前激活链和候选链之间路径上的所有区块是否有效。
// Just going until the active chain is an optimization, as we know all blocks in it are valid already. // 直到激活链是一个优化的链,因为我们直到全部区块已经是有效的。
CBlockIndex *pindexTest = pindexNew;
bool fInvalidAncestor = false;
while (pindexTest && !chainActive.Contains(pindexTest)) {
assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
// Pruned nodes may have entries in setBlockIndexCandidates for // 修剪过的节点可能在 setBlockIndexCandidates 集合中含有已删除的区块文件。
// which block files have been deleted. Remove those as candidates // 如果我们遇到这些文件
// for the most work chain if we come across them; we can't switch // 则删除作为大多数工作链的候选;
// to a chain unless we have all the non-active-chain parent blocks. // 除非我们拥有所有非活动链的父块,否则无法切换到链。
bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data) // 候选链不可用(无效或丢失数据)
if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew;
CBlockIndex *pindexFailed = pindexNew;
// Remove the entire chain from the set. // 从集合中移除整个链
while (pindexTest != pindexFailed) {
if (fFailedChain) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
} else if (fMissingData) {
// If we're missing data, then add back to mapBlocksUnlinked, // 如果我们丢失了数据,添加回未链接的区块映射列表,
// so that if the block arrives in the future we can try adding // 以至于如果之后区块到达,
// to setBlockIndexCandidates again. // 我们可以尝试再次添加到区块索引候选集中
mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
}
setBlockIndexCandidates.erase(pindexFailed);
pindexFailed = pindexFailed->pprev;
}
setBlockIndexCandidates.erase(pindexTest);
fInvalidAncestor = true;
break;
}
pindexTest = pindexTest->pprev;
}
if (!fInvalidAncestor)
return pindexNew;
} while(true);
}
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
static void PruneBlockIndexCandidates() { // 删除区块索引候选集合中币当前链尖差的全部条目。
// Note that we can't delete the current block itself, as we may need to return to it later in case a
// reorganization to a better block fails. // 注:我们不删除当前区块本身,因为我们可能需要稍后返回它以防重组更好的区块失败。
std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) { // 遍历区块候选集合
setBlockIndexCandidates.erase(it++); // 移除每个候选元素
}
// Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
assert(!setBlockIndexCandidates.empty()); // 我们正努力把当前链尖和其后继留在区块索引候选集合中。
}
/**
* Try to make some progress towards making pindexMostWork the active block.
* pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
*/ // 尝试激活 pindexMostWork 索引对应的区块。pblock 为空或是指向 pindexMostWork 对应区块的指针。
static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const CBlock* pblock)
{
AssertLockHeld(cs_main);
bool fInvalidFound = false;
const CBlockIndex *pindexOldTip = chainActive.Tip();
const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
// Disconnect active blocks which are no longer in the best chain. // 断开不再是最佳链上激活区块的连接。
bool fBlocksDisconnected = false;
while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
if (!DisconnectTip(state, chainparams.GetConsensus()))
return false;
fBlocksDisconnected = true;
}
// Build list of new blocks to connect. // 构建用于连接的新区块列表。
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way. // 不要将整个潜在改进列表迭代到最佳链尖,因为我们可能只需几个区块。
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks. // 连接到新区块。
BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
if (state.IsInvalid()) {
// The block violates a consensus rule. // 该区块违反共识规则。
if (!state.CorruptionPossible())
InvalidChainFound(vpindexToConnect.back());
state = CValidationState();
fInvalidFound = true;
fContinue = false;
break;
} else { // 发生了一个系统错误(磁盘空间,数据库错误,...)。
// A system error occurred (disk space, database error, ...).
return false;
}
} else {
PruneBlockIndexCandidates();
if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
// We're in a better position than we were. Return temporarily to release the lock. // 我们处于最佳位置。临时返回用来释放锁。
fContinue = false;
break;
}
}
}
}
if (fBlocksDisconnected) {
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
}
mempool.check(pcoinsTip);
// Callbacks/notifications for a new best chain. // 用于新最佳链的回调/通知。
if (fInvalidFound)
CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
else
CheckForkWarningConditions();
return true;
}
/**
* Make the best chain active, in multiple steps. The result is either failure
* or an activated best chain. pblock is either NULL or a pointer to a block
* that is already loaded (to avoid loading it again from disk).
*/ // 多步激活最佳链。结果使不是失败就是激活的最佳链。pblock 不是空就是是指向一个已经加载的区块的指针(避免再次从磁盘加载它)。
bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, const CBlock *pblock) {
CBlockIndex *pindexMostWork = NULL;
do {
boost::this_thread::interruption_point(); // 打个断点
if (ShutdownRequested()) // 若请求关闭
break; // 这里跳出
CBlockIndex *pindexNewTip = NULL;
const CBlockIndex *pindexFork;
bool fInitialDownload;
{
LOCK(cs_main); // 上锁
CBlockIndex *pindexOldTip = chainActive.Tip(); // 获取激活链尖区块索引
pindexMostWork = FindMostWorkChain(); // 查找最多工作量的链尖区块索引
// Whether we have anything to do at all. // 检查我们是否有事情要做
if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip()) // 若当前激活链尖区块已是最佳区块
return true; // 直接返回 true
if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL)) // 激活最佳链步骤
return false;
pindexNewTip = chainActive.Tip(); // 获取新链尖
pindexFork = chainActive.FindFork(pindexOldTip); // 查找分叉区块索引
fInitialDownload = IsInitialBlockDownload(); // 检查初始化块下载是否完成
} // 当我们到达这点时,我们切换到一个新的链尖(存储在 pindexNewTip)
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
// Notifications/callbacks that can run without cs_main // 不带 cs_main 可以运行的通知/回调
// Always notify the UI if a new block tip was connected // 如果链接了一个新区块尖总是通知 UI
if (pindexFork != pindexNewTip) { // 新链尖区块索引不是分叉块
uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
if (!fInitialDownload) { // 如果初始化块下载未完成
// Find the hashes of all blocks that weren't previously in the best chain. // 查找在最佳链上没有前辈的所有区块的哈希
std::vector<uint256> vHashes; // 区块哈希列表
CBlockIndex *pindexToAnnounce = pindexNewTip;
while (pindexToAnnounce != pindexFork) { // 不是分叉块
vHashes.push_back(pindexToAnnounce->GetBlockHash()); // 加入哈希列表
pindexToAnnounce = pindexToAnnounce->pprev; // 指向前一个区块
if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) { // 列表大小有 8 条时
// Limit announcements in case of a huge reorganization. // 如果大规模重组则限制通告。
// Rely on the peer's synchronization mechanism in that case. // 在此情况下依赖对端的同步机制。
break; // 跳出
}
}
// Relay inventory, but don't relay old inventory during initial block download. // 在初始化块下载过程中,中继库存但不中继旧的库存
int nBlockEstimate = 0;
if (fCheckpointsEnabled) // 检查点可用
nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()); // 获取区块总估计
{
LOCK(cs_vNodes); // 已连接的节点列表上锁
BOOST_FOREACH(CNode* pnode, vNodes) { // 遍历该节点列表
if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) { // 若激活的链高度大于当前节点
BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) { // 遍历区块哈希列表
pnode->PushBlockHash(hash); // 加入待通告的区块哈希列表
}
}
}
}
// Notify external listeners about the new tip. // 通知外部监听者关于新链尖的信息
if (!vHashes.empty()) { // 若区块哈希列表非空
GetMainSignals().UpdatedBlockTip(pindexNewTip); // 发送信号更新区块链尖
}
}
}
} while(pindexMostWork != chainActive.Tip());
CheckBlockIndex(chainparams.GetConsensus()); // 检查区块索引
// Write changes periodically to disk, after relay. // 在中继后,周期性的写入状态到磁盘
if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) { // 刷新状态到磁盘
return false;
}
return true; // 成功返回 true
}
bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex)
{
AssertLockHeld(cs_main); // 保持上锁状态
// Mark the block itself as invalid. // 标记区块自身状态为无效
pindex->nStatus |= BLOCK_FAILED_VALID; // 设置无效状态
setDirtyBlockIndex.insert(pindex); // 加入无效区块索引集合
setBlockIndexCandidates.erase(pindex); // 从区块索引候选集中擦除该索引
while (chainActive.Contains(pindex)) { // 当激活的链中包含该区块索引
CBlockIndex *pindexWalk = chainActive.Tip(); // 获取激活的链尖区块索引
pindexWalk->nStatus |= BLOCK_FAILED_CHILD; // 设置该区块状态为无效区块后代
setDirtyBlockIndex.insert(pindexWalk); // 加入无效区块索引集合
setBlockIndexCandidates.erase(pindexWalk); // 从区块索引候选集中擦除该索引
// ActivateBestChain considers blocks already in chainActive // ActivateBestChain 认为已经在激活链上的区块
// unconditionally valid already, so force disconnect away from it. // 已经无条件有效,强制断开它于链的链接
if (!DisconnectTip(state, consensusParams)) { // 断开链尖链接
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
return false;
}
}
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); // 限制内存池大小
// The resulting new best tip may not be in setBlockIndexCandidates anymore, so
// add it again. // 结果新的最佳链尖可能不在区块索引候选集中,所以再次添加它。
BlockMap::iterator it = mapBlockIndex.begin(); // 获取区块索引映射列表首迭代器
while (it != mapBlockIndex.end()) { // 遍历区块索引映射列表
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) { // 若区块索引有效 且 该区块所有交易依赖的交易可用 且 该区块索引是最佳链尖
setBlockIndexCandidates.insert(it->second); // 插入区块索引候选集
}
it++;
}
InvalidChainFound(pindex); // 查找无效的链
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
return true;
}
bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
AssertLockHeld(cs_main); // 上锁
int nHeight = pindex->nHeight; // 获取指定区块高度
// Remove the invalidity flag from this block and all its descendants. // 移除该区块及其后辈的无效化标志
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) { // 遍历区块索引映射列表
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) { // 若该索引无效
it->second->nStatus &= ~BLOCK_FAILED_MASK; // 改变区块状态
setDirtyBlockIndex.insert(it->second); // 插入无效区块索引集合
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) { // 若该区块交易有效
setBlockIndexCandidates.insert(it->second); // 插入区块索引候选集
}
if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those. // 如果它指向其中一个,重置无效区块标记
pindexBestInvalid = NULL;
}
}
it++;
}
// Remove the invalidity flag from all ancestors too. // 也移除全部祖先的无效化标志
while (pindex != NULL) { // 区块索引指针非空
if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK; // 0
setDirtyBlockIndex.insert(pindex); // 插入无效区块索引集合
}
pindex = pindex->pprev; // 指向前一个区块
}
return true; // 成功返回 true
}
CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
{
// Check for duplicate // 查重
uint256 hash = block.GetHash(); // 获取区块哈希
BlockMap::iterator it = mapBlockIndex.find(hash); // 从区块索引映射列表中查找
if (it != mapBlockIndex.end()) // 若找到(已存在)
return it->second; // 直接返回该区块索引
// Construct new block index object // 构造新的区块索引对象
CBlockIndex* pindexNew = new CBlockIndex(block);
assert(pindexNew);
// We assign the sequence id to blocks only when the full data is available, // 我们只在完整数据可用时给区块分配序列号
// to avoid miners withholding blocks but broadcasting headers, to get a // 避免矿工扣留块只广播区块头,
// competitive advantage. // 以获取竞争优势。
pindexNew->nSequenceId = 0;
BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; // 插入区块索引映射列表并获取并获取其迭代器
pindexNew->phashBlock = &((*mi).first); // 获取区块哈希
BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock); // 在区块索引映射列表中查找前一个区块
if (miPrev != mapBlockIndex.end()) // 若找到
{
pindexNew->pprev = (*miPrev).second; // 获取其索引作为当前区块的前一个区块
pindexNew->nHeight = pindexNew->pprev->nHeight + 1; // 计算当前区块的高度(前一区块高度加 1)
pindexNew->BuildSkip(); // 构建跳表
}
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew); // 计算当前区块的链工作量
pindexNew->RaiseValidity(BLOCK_VALID_TREE); // 提升该区块索引的有效等级
if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) // 最佳区块头索引为空,或最佳区块链工作量小于当前区块
pindexBestHeader = pindexNew; // 当前区块成为新的最佳区块头
setDirtyBlockIndex.insert(pindexNew); // 插入脏掉的区块索引集合
return pindexNew; // 返回新区块的索引
}
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */ // 标记一个区块其数据为已接收和检查(直到 BLOCK_VALID_TRANSACTIONS)
bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
{
pindexNew->nTx = block.vtx.size(); // 获取交易数
pindexNew->nChainTx = 0;
pindexNew->nFile = pos.nFile; // 所在区块文件号
pindexNew->nDataPos = pos.nPos; // 所在文件中的位移
pindexNew->nUndoPos = 0;
pindexNew->nStatus |= BLOCK_HAVE_DATA; // 区块状态
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS); // 提升区块索引的有效性
setDirtyBlockIndex.insert(pindexNew); // 插入脏的区块索引集合
if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { // 若区块前一个区块为空,或前一个区块的链交易非 0
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. // pindexNew 是创世区块,或其全部双亲为 BLOCK_VALID_TRANSACTIONS
deque<CBlockIndex*> queue; // 区块索引双端队列
queue.push_back(pindexNew); // 加入索引队列
// Recursively process any descendant blocks that now may be eligible to be connected. // 递归处理现在有资格连接的任何后代区块。
while (!queue.empty()) { // 当队列非空时
CBlockIndex *pindex = queue.front(); // 获取队头区块索引
queue.pop_front(); // 队头索引出队
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx; // 计算该区块的链交易
{
LOCK(cs_nBlockSequenceId);
pindex->nSequenceId = nBlockSequenceId++; // 区块序列号
}
if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) { // 若激活的链尖为空,或当前区块非激活链尖
setBlockIndexCandidates.insert(pindex); // 插入区块索引候选集
}
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex); // 获取一对范围迭代器 <键不小于 pindex,键大于 pindex>
while (range.first != range.second) { // 把等于但不大于 pindex 的区块索引
std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
queue.push_back(it->second); // 加入索引队列
range.first++;
mapBlocksUnlinked.erase(it); // 并从未链接的区块映射列表中擦除
}
}
} else { // 否则
if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) { // 如果前一个区块存在,且前一个区块状态为 BLOCK_VALID_TREE
mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew)); // 则与前一个区块索引配对插入区块未连接映射列表中
}
}
return true; // 成功返回 true
}
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
{
LOCK(cs_LastBlockFile);
unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
if (!fKnown) {
while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
nFile++;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
}
pos.nFile = nFile;
pos.nPos = vinfoBlockFile[nFile].nSize;
}
if ((int)nFile != nLastBlockFile) {
if (!fKnown) {
LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
}
FlushBlockFile(!fKnown);
nLastBlockFile = nFile;
}
vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
if (fKnown)
vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
else
vinfoBlockFile[nFile].nSize += nAddSize;
if (!fKnown) {
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenBlockFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error("out of disk space");
}
}
setDirtyFileInfo.insert(nFile);
return true;
}
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
pos.nPos = vinfoBlockFile[nFile].nUndoSize;
nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
setDirtyFileInfo.insert(nFile);
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenUndoFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error("out of disk space");
}
return true;
}
bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
{
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
REJECT_INVALID, "high-hash");
// Check timestamp
if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
REJECT_INVALID, "time-too-new");
return true;
}
bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
{
// These are checks that are independent of context.
if (block.fChecked)
return true;
// Check that the header is valid (particularly PoW). This is mostly
// redundant with the call in AcceptBlockHeader.
if (!CheckBlockHeader(block, state, fCheckPOW))
return false;
// Check the merkle root.
if (fCheckMerkleRoot) {
bool mutated;
uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
REJECT_INVALID, "bad-txnmrklroot", true);
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.DoS(100, error("CheckBlock(): duplicate transaction"),
REJECT_INVALID, "bad-txns-duplicate", true);
}
// All potential-corruption validation must be done before we do any
// transaction validation, as otherwise we may mark the header as invalid
// because we receive the wrong transactions for it.
// Size limits
if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return state.DoS(100, error("CheckBlock(): size limits failed"),
REJECT_INVALID, "bad-blk-length");
// First transaction must be coinbase, the rest must not be
if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
REJECT_INVALID, "bad-cb-missing");
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i].IsCoinBase())
return state.DoS(100, error("CheckBlock(): more than one coinbase"),
REJECT_INVALID, "bad-cb-multiple");
// Check transactions
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!CheckTransaction(tx, state))
return error("CheckBlock(): CheckTransaction of %s failed with %s",
tx.GetHash().ToString(),
FormatStateMessage(state));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, block.vtx)
{
nSigOps += GetLegacySigOpCount(tx);
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
REJECT_INVALID, "bad-blk-sigops");
if (fCheckPOW && fCheckMerkleRoot)
block.fChecked = true;
return true;
}
static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
{
if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
return true;
int nHeight = pindexPrev->nHeight+1;
// Don't accept any forks from the main chain prior to last checkpoint
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
if (pcheckpoint && nHeight < pcheckpoint->nHeight)
return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
return true;
}
bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
{
const Consensus::Params& consensusParams = Params().GetConsensus();
// Check proof of work
if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
return state.DoS(100, error("%s: incorrect proof of work", __func__),
REJECT_INVALID, "bad-diffbits");
// Check timestamp against prev
if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
return state.Invalid(error("%s: block's timestamp is too early", __func__),
REJECT_INVALID, "time-too-old");
// Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
REJECT_OBSOLETE, "bad-version");
// Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
return state.Invalid(error("%s: rejected nVersion=2 block", __func__),
REJECT_OBSOLETE, "bad-version");
// Reject block.nVersion=3 blocks when 95% (75% on testnet) of the network has upgraded:
if (block.nVersion < 4 && IsSuperMajority(4, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
return state.Invalid(error("%s : rejected nVersion=3 block", __func__),
REJECT_OBSOLETE, "bad-version");
return true;
}
bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
{
const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
const Consensus::Params& consensusParams = Params().GetConsensus();
// Start enforcing BIP113 (Median Time Past) using versionbits logic.
int nLockTimeFlags = 0;
if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
}
int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
? pindexPrev->GetMedianTimePast()
: block.GetBlockTime();
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, block.vtx) {
if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
}
}
// Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
// if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
{
CScript expect = CScript() << nHeight;
if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
}
}
return true;
}
static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex=NULL)
{
AssertLockHeld(cs_main);
// Check for duplicate // 查重
uint256 hash = block.GetHash(); // 获取区块哈希
BlockMap::iterator miSelf = mapBlockIndex.find(hash); // 在区块索引映射列表中查询
CBlockIndex *pindex = NULL;
if (hash != chainparams.GetConsensus().hashGenesisBlock) {
if (miSelf != mapBlockIndex.end()) { // 若该区块已存在
// Block header is already known.
pindex = miSelf->second;
if (ppindex)
*ppindex = pindex;
if (pindex->nStatus & BLOCK_FAILED_MASK)
return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
return true;
}
if (!CheckBlockHeader(block, state))
return false;
// Get prev block index // 获取前一个区块索引
CBlockIndex* pindexPrev = NULL;
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); // 查找前一个区块索引迭代器
if (mi == mapBlockIndex.end()) // 若未找到
return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); // 报错
pindexPrev = (*mi).second; // 拿到前一个区块索引
if (pindexPrev->nStatus & BLOCK_FAILED_MASK) // 检查区块验证状态
return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
assert(pindexPrev); // 不能为空
if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash)) // 若检测点功能开启,检查是否符合检测点
return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
if (!ContextualCheckBlockHeader(block, state, pindexPrev)) // 检查区块头上下文
return false;
}
if (pindex == NULL) // 若区块索引为空,表示区块索引映射列表中不存在该新区块
pindex = AddToBlockIndex(block); // 添加该区块到区块索引映射列表
if (ppindex) // 添加新区块完成后
*ppindex = pindex; // 把前一个区块索引指针指向添加的新区块
return true;
}
/** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */ // 存储区块到硬盘。如果 dbp 非空,已知文件已经存在在硬盘上
static bool AcceptBlock(const CBlock& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
{
AssertLockHeld(cs_main); // 持有主锁
CBlockIndex *&pindex = *ppindex; // 获取前一个(当前最佳)区块索引指针
if (!AcceptBlockHeader(block, state, chainparams, &pindex)) // 接受区块头(添加新区块到区块索引映射列表)
return false;
// Try to process all requested blocks that we don't have, but only // 尝试处理我们没有的请求的块,
// process an unrequested block if it's new and has enough work to // 但只处理一个未请求的块,如果它是新的且
// advance our tip, and isn't too many blocks ahead. // 有足够的工作量来推进我们的链尖,且前面没有太多区块。
bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA; // 已经存在标志
bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true); // 工作量是否充足
// Blocks that are too out-of-order needlessly limit the effectiveness of // 过于无序的区块不必要地限制了修剪效率,
// pruning, because pruning will not delete block files that contain any // 因为修剪不会删除包含任何与链尖太接近的区块的文件。
// blocks which are too close in height to the tip. Apply this test // 无论是否开启修剪都应用此项;
// regardless of whether pruning is enabled; it should generally be safe to
// not process unrequested blocks. // 不处理未请求块通常是安全的。
bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP)); // 区块过高,超过当前链高度 + 288
// TODO: deal better with return value and error conditions for duplicate
// and unrequested blocks. // TODO:更好地处理重复和未请求区块的返回值和错误条件。
if (fAlreadyHave) return true; // 若已经存在该区块,直接返回 true
if (!fRequested) { // If we didn't ask for it: // 若我么们没有要求它:
if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned // 这是一个已修剪的预处理过的区块
if (!fHasMoreWork) return true; // Don't process less-work chains // 不处理低工作量链
if (fTooFarAhead) return true; // Block height is too high // 区块高度过高
}
if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) { // 检查区块状态和上下文
if (state.IsInvalid() && !state.CorruptionPossible()) { // 若状态无效 且
pindex->nStatus |= BLOCK_FAILED_VALID; // 设置该区块状态为无效
setDirtyBlockIndex.insert(pindex); // 插入无效区块索引集合
}
return false;
}
int nHeight = pindex->nHeight; // 获取区块高度
// Write block to history file // 写区块数据到历史文件
try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); // 获取序列化的区块大小
CDiskBlockPos blockPos;
if (dbp != NULL)
blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) // 查找区块位置
return error("AcceptBlock(): FindBlockPos failed");
if (dbp == NULL) // 若未找到
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) // 把该区块写入磁盘
AbortNode(state, "Failed to write block");
if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) // 标记区块交易为已接收
return error("AcceptBlock(): ReceivedBlockTransactions failed");
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error: ") + e.what());
}
if (fCheckForPruning) // 若检查修剪,则刷新状态到磁盘
FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
return true;
}
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
{
unsigned int nFound = 0;
for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp)
{
// Preliminary checks // 初步检查
bool checked = CheckBlock(*pblock, state);
{
LOCK(cs_main);
bool fRequested = MarkBlockAsReceived(pblock->GetHash()); // 标记区块为已收到
fRequested |= fForceProcessing; // true
if (!checked) {
return error("%s: CheckBlock FAILED", __func__);
}
// Store to disk
CBlockIndex *pindex = NULL; // 区块索引
bool ret = AcceptBlock(*pblock, state, chainparams, &pindex, fRequested, dbp); // 接受该区块,存储区块数据到硬盘
if (pindex && pfrom) { // NULL
mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
}
CheckBlockIndex(chainparams.GetConsensus()); // 检查区块索引
if (!ret)
return error("%s: AcceptBlock FAILED", __func__);
}
if (!ActivateBestChain(state, chainparams, pblock)) // 激活最佳链
return error("%s: ActivateBestChain failed", __func__);
return true;
}
bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
{
AssertLockHeld(cs_main);
assert(pindexPrev && pindexPrev == chainActive.Tip());
if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
CCoinsViewCache viewNew(pcoinsTip);
CBlockIndex indexDummy(block);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, pindexPrev))
return false;
if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
return false;
if (!ContextualCheckBlock(block, state, pindexPrev))
return false;
if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
return false;
assert(state.IsValid());
return true;
}
/**
* BLOCK PRUNING CODE
*/ // 区块修剪代码
/* Calculate the amount of disk space the block & undo files currently use */
uint64_t CalculateCurrentUsage() // 计算区块和恢复文件当前使用的磁盘空间
{
uint64_t retval = 0;
BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
retval += file.nSize + file.nUndoSize;
}
return retval;
}
/* Prune a block file (modify associated database entries)*/
void PruneOneBlockFile(const int fileNumber) // 修剪一个区块文件(修改关联的数据库条目)
{
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
CBlockIndex* pindex = it->second;
if (pindex->nFile == fileNumber) {
pindex->nStatus &= ~BLOCK_HAVE_DATA;
pindex->nStatus &= ~BLOCK_HAVE_UNDO;
pindex->nFile = 0;
pindex->nDataPos = 0;
pindex->nUndoPos = 0;
setDirtyBlockIndex.insert(pindex);
// Prune from mapBlocksUnlinked -- any block we prune would have
// to be downloaded again in order to consider its chain, at which
// point it would be considered as a candidate for
// mapBlocksUnlinked or setBlockIndexCandidates.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
while (range.first != range.second) {
std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
range.first++;
if (it->second == pindex) {
mapBlocksUnlinked.erase(it);
}
}
}
}
vinfoBlockFile[fileNumber].SetNull();
setDirtyFileInfo.insert(fileNumber);
}
void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
{
for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) { // 遍历待修剪的文件集
CDiskBlockPos pos(*it, 0);
boost::filesystem::remove(GetBlockPosFilename(pos, "blk")); // 移除区块文件
boost::filesystem::remove(GetBlockPosFilename(pos, "rev")); // 移除恢复文件
LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
}
}
/* Calculate the block/rev files that should be deleted to remain under target*/
void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
{
LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == NULL || nPruneTarget == 0) {
return;
}
if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
return;
}
unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
uint64_t nCurrentUsage = CalculateCurrentUsage();
// We don't check to prune until after we've allocated new space for files
// So we should leave a buffer under our target to account for another allocation
// before the next pruning.
uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
uint64_t nBytesToPrune;
int count=0;
if (nCurrentUsage + nBuffer >= nPruneTarget) {
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
if (vinfoBlockFile[fileNumber].nSize == 0)
continue;
if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
break;
// don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
continue;
PruneOneBlockFile(fileNumber);
// Queue up the files for removal
setFilesToPrune.insert(fileNumber);
nCurrentUsage -= nBytesToPrune;
count++;
}
}
LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
nLastBlockWeCanPrune, count);
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available; // 获取数据目录所在磁盘的剩余(可用)空间的大小,单位 Byte
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) // 磁盘剩余空间最小为 50MB
return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
return true; // 若剩余空间大于等于 50MB,则返回 true
}
FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
{
if (pos.IsNull())
return NULL;
boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+");
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
LogPrintf("Unable to open file %s\n", path.string());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file);
return NULL;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "blk", fReadOnly);
}
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "rev", fReadOnly);
}
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
{
return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile); // 拼接 2 种前缀的区块数据文件路径名
}
CBlockIndex * InsertBlockIndex(uint256 hash)
{
if (hash.IsNull()) // 哈希非空
return NULL;
// Return existing // 返回已存在的
BlockMap::iterator mi = mapBlockIndex.find(hash); // 在区块索引映射列表中查找
if (mi != mapBlockIndex.end()) // 若存在该哈希的索引
return (*mi).second; // 直接返回对应的区块索引
// Create new // 创建新的
CBlockIndex* pindexNew = new CBlockIndex(); // 新建区块索引对象
if (!pindexNew)
throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; // 与区块哈希配对后插入区块索引映射列表,并获取对应位置的迭代器
pindexNew->phashBlock = &((*mi).first); // 获取其哈希值
return pindexNew; // 返回新的区块索引
}
bool static LoadBlockIndexDB()
{
const CChainParams& chainparams = Params(); // 获取网络链参数
if (!pblocktree->LoadBlockIndexGuts()) // 区块树加载区块索引框架
return false;
boost::this_thread::interruption_point(); // 打个断点
// Calculate nChainWork // 计算链工作量
vector<pair<int, CBlockIndex*> > vSortedByHeight; // 通过高度排序的有序区块高度索引映射列表
vSortedByHeight.reserve(mapBlockIndex.size()); // 预开辟与区块索引映射列表等大的空间
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) // 遍历区块索引映射列表
{
CBlockIndex* pindex = item.second; // 获取区块索引
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); // 与区块高度配对加入待排序列表
}
sort(vSortedByHeight.begin(), vSortedByHeight.end()); // 按高度排序
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) // 遍历有序的区块索引映射列表
{
CBlockIndex* pindex = item.second; // 获取区块索引
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex); // 若该区块的前一个区块存在,则获取前一个区块的链工作量,再加上该区块的工作量证明
// We can link the chain of blocks for which we've received transactions at some point. // 我们可以连接到区块链用于接收某些节点的交易。
// Pruned nodes may have deleted the block. // 修剪节点可能会删除区块。
if (pindex->nTx > 0) { // 若该区块的交易数大于 0
if (pindex->pprev) {
if (pindex->pprev->nChainTx) { // 如果前一个区块存在链交易
pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx; // 用前一个区块的链交易 + 该区块的交易 得到该区块的链交易
} else { // 否则
pindex->nChainTx = 0; // 该区块的链交易为 0
mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex)); // 与前一个区块的索引配对插入未连接的区块映射列表
}
} else { // 否则
pindex->nChainTx = pindex->nTx; // 区块的链交易数等于区块的交易数
}
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) // 若该区块交易有效,且有链交易,或前一个区块不存在
setBlockIndexCandidates.insert(pindex); // 插入区块索引候选集
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork)) // 若区块状态为 BLOCK_FAILED_MASK,且最佳无效区块为空,或链工作大于最佳无效区块
pindexBestInvalid = pindex; // 该区块为最佳无效区块
if (pindex->pprev) // 若前一个区块存在
pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex; // 该区块索引为最佳区块头索引
}
// Load block file info // 加载区块文件信息
pblocktree->ReadLastBlockFile(nLastBlockFile); // 读取最后一个区块文件
vinfoBlockFile.resize(nLastBlockFile + 1); // 预开辟相同的空间
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) { // 遍历区块文件
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]); // 读区块文件信息
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) { // 从最后一个文件号加 1 开始
CBlockFileInfo info;
if (pblocktree->ReadBlockFileInfo(nFile, info)) { // 读取
vinfoBlockFile.push_back(info); // 并加入区块文件信息列表
} else { // 若读取失败(文件不存在)
break; // 跳出
}
}
// Check presence of blk files // 检查区块文件是否存在
LogPrintf("Checking all blk files are present...\n");
set<int> setBlkDataFiles; // 用于保存所有区块数据文件的序号
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) // 遍历区块索引映射列表
{
CBlockIndex* pindex = item.second; // 获取区块索引
if (pindex->nStatus & BLOCK_HAVE_DATA) { // 若区块状态为 BLOCK_HAVE_DATA
setBlkDataFiles.insert(pindex->nFile); // 把该区块所在文件号插入区块数据文件集合中
}
}
for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) // 遍历区块数据文件集合
{
CDiskBlockPos pos(*it, 0); // 创建磁盘区块位置对象
if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) { // 创建文件指针托管临时对象
return false;
}
}
// Check whether we have ever pruned block & undo files // 检查我们是否曾修剪过区块和恢复文件
pblocktree->ReadFlag("prunedblockfiles", fHavePruned); // 读取修剪区块文件标志
if (fHavePruned)
LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
// Check whether we need to continue reindexing // 检查我们是否需要继续再索引
bool fReindexing = false;
pblocktree->ReadReindexing(fReindexing); // 读取再索引标志
fReindex |= fReindexing;
// Check whether we have a transaction index // 检查我们是否有交易索引
pblocktree->ReadFlag("txindex", fTxIndex); // 读取交易索引标志
LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
// Load pointer to end of best chain // 加载指向最佳链尾部的指针
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); // 获取最佳区块的索引
if (it == mapBlockIndex.end()) // 若未找到
return true; // 直接返回 true
chainActive.SetTip(it->second); // 若存在,则设置该区块索引为激活链的链尖(放入区块索引列表中)
PruneBlockIndexCandidates(); // 修剪区块索引候选
LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
return true; // 加载成功返回 true
}
CVerifyDB::CVerifyDB()
{
uiInterface.ShowProgress(_("Verifying blocks..."), 0);
}
CVerifyDB::~CVerifyDB()
{
uiInterface.ShowProgress("", 100);
}
bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
{
LOCK(cs_main); // 上锁
if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL) // 激活的链尖非空 且 链尖的前一个区块哈希非空(即区块链高度至少为 1)
return true;
// Verify blocks in the best chain // 验证最佳链上的区块
if (nCheckDepth <= 0) // 检查深度若为负数
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > chainActive.Height()) // 检查深度若大于当前激活链高度
nCheckDepth = chainActive.Height(); // 检查深度等于链高度
nCheckLevel = std::max(0, std::min(4, nCheckLevel)); // 检查等级,最高 4 级
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); // 记录检查信息
CCoinsViewCache coins(coinsview);
CBlockIndex* pindexState = chainActive.Tip(); // 获取链尖区块索引
CBlockIndex* pindexFailure = NULL;
int nGoodTransactions = 0; // 好的交易数
CValidationState state; // 用于保存区块的验证状态
for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
{ // 遍历区块链,从新到旧
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
if (pindex->nHeight < chainActive.Height()-nCheckDepth) // 若当前验证的区块数大于检查深度
break; // 跳出
CBlock block;
// check level 0: read from disk // 检查等级 0:从磁盘读
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) // 根据区块索引从磁盘读区块数据到内存 block
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 1: verify block validity // 检查等级 1:验证区块有效性
if (nCheckLevel >= 1 && !CheckBlock(block, state)) // 检查区块状态
return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 2: verify undo validity // 检查等级 2:验证撤销有效性
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos(); // 获取区块在磁盘上撤销的位置
if (!pos.IsNull()) {
if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash())) // 撤销从磁盘读,从历史文件读
return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks // 检查等级 3:检查在内存中断开链尖区块连接的不一致性
if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) { // 币的动态内存用量不能大于 5000 * 300 (1M 多)
bool fClean = true;
if (!DisconnectBlock(block, state, pindex, coins, &fClean)) // 断开链尖区块
return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
pindexState = pindex->pprev; // 指向前一个区块(新的链尖区块)
if (!fClean) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else
nGoodTransactions += block.vtx.size(); // 记录好的交易数
}
if (ShutdownRequested()) // 这里如果比特币核心被请求断开连接
return true; // 直接返回 true
}
if (pindexFailure) // 记录失败信息
return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
// check level 4: try reconnecting blocks // 检查等级 4:尝试重连区块
if (nCheckLevel >= 4) { // 最高等级 4
CBlockIndex *pindex = pindexState; // 获取当前区块索引
while (pindex != chainActive.Tip()) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
pindex = chainActive.Next(pindex); // 指向下一个区块索引
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) // 从磁盘中读区块数据
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!ConnectBlock(block, state, pindex, coins)) // 连接该区块
return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions); // 检验完成,没有不一致
return true; // 返回 true
}
void UnloadBlockIndex()
{
LOCK(cs_main); // 保证线程安全
setBlockIndexCandidates.clear();
chainActive.SetTip(NULL);
pindexBestInvalid = NULL;
pindexBestHeader = NULL;
mempool.clear();
mapOrphanTransactions.clear();
mapOrphanTransactionsByPrev.clear();
nSyncStarted = 0;
mapBlocksUnlinked.clear();
vinfoBlockFile.clear();
nLastBlockFile = 0;
nBlockSequenceId = 1;
mapBlockSource.clear();
mapBlocksInFlight.clear();
nPreferredDownload = 0;
setDirtyBlockIndex.clear();
setDirtyFileInfo.clear();
mapNodeState.clear();
recentRejects.reset(NULL);
versionbitscache.Clear();
for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
warningcache[b].clear();
}
BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
delete entry.second;
}
mapBlockIndex.clear(); // 清空区块索引映射
fHavePruned = false;
}
bool LoadBlockIndex()
{
// Load block index from databases // 从数据库加载区块索引
if (!fReindex && !LoadBlockIndexDB()) // 若未开启再索引,则加载区块索引数据库,否则不加载,在后面会重新索引
return false;
return true; // 加载成功返回 true
}
bool InitBlockIndex(const CChainParams& chainparams)
{
LOCK(cs_main); // 线程安全锁
// Initialize global variables that cannot be constructed at startup.
recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); // 初始化不能再启动时创建的全局对象
// Check whether we're already initialized
if (chainActive.Genesis() != NULL) // 检查是否初始化了创世区块索引
return true;
// Use the provided setting for -txindex in the new database // 在新数据库中对 -txindex 使用提供的设置
fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX); // 先获取默认设置
pblocktree->WriteFlag("txindex", fTxIndex); // 写入数据库
LogPrintf("Initializing databases...\n");
// Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
if (!fReindex) { // 如果不再索引只添加创世区块(此时我们重用磁盘上已存在的创世区块所在的区块文件)
try {
CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock()); // 获取创世区块的引用
// Start new block file // 开始新的区块文件
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); // 获取序列化大小
CDiskBlockPos blockPos;
CValidationState state;
if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime())) // 获取区块状态和位置
return error("LoadBlockIndex(): FindBlockPos failed");
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) // 把区块信息(状态和位置)写到磁盘
return error("LoadBlockIndex(): writing genesis block to disk failed");
CBlockIndex *pindex = AddToBlockIndex(block); // 添加到区块索引
if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) // 接收区块交易
return error("LoadBlockIndex(): genesis block not accepted");
if (!ActivateBestChain(state, chainparams, &block)) // 激活最佳链
return error("LoadBlockIndex(): genesis block cannot be activated");
// Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data // 强制把链状态写入磁盘,以至于当我们一段时间内验证数据库时,不会检查旧数据
return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
} catch (const std::runtime_error& e) {
return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
}
}
return true; // 成功返回 true
}
bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
{
// Map of disk positions for blocks with unknown parent (only used for reindex) // 具有位置双亲的区块的磁盘位置映射(只用于再索引)
static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
int64_t nStart = GetTimeMillis();
int nLoaded = 0; // 加载的区块数
try {
// This takes over fileIn and calls fclose() on it in the CBufferedFile destructor // 这将接管 fileIn 并在 CBufferedFile 的析构函数中调用 fclose() 关闭它
CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); // 创建缓冲文件对象
uint64_t nRewind = blkdat.GetPos(); // 把当前读取的位置作为回退点
while (!blkdat.eof()) { // 若该文件没到文件结尾
boost::this_thread::interruption_point(); // 打个断点
blkdat.SetPos(nRewind); // 设置回退点
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit // 移除以前的限制
unsigned int nSize = 0;
try {
// locate a header // 定位区块头
unsigned char buf[MESSAGE_START_SIZE]; // 4bytes
blkdat.FindByte(chainparams.MessageStart()[0]); // 搜索消息头的首个字符
nRewind = blkdat.GetPos()+1; // 回退位置为读取位置加 1
blkdat >> FLATDATA(buf);
if (memcmp(buf, chainparams.MessageStart(), MESSAGE_START_SIZE)) // 把消息头拷贝到 buf 中
continue;
// read size // 读大小
blkdat >> nSize; // 导入区块大小
if (nSize < 80 || nSize > MAX_BLOCK_SIZE) // 区块头数据大小检验
continue;
} catch (const std::exception&) {
// no valid block header found; don't complain // 无效区块头被找到,不抱怨(啥也不做)
break; // 直接跳出
}
try {
// read block // 读区块
uint64_t nBlockPos = blkdat.GetPos(); // 获取区块位置
if (dbp) // 区块数据库文件指针
dbp->nPos = nBlockPos; // 设置位置
blkdat.SetLimit(nBlockPos + nSize); // 设置限制
blkdat.SetPos(nBlockPos); // 设置区块位置
CBlock block; // 创建空的区块对象
blkdat >> block; // 导入区块数据
nRewind = blkdat.GetPos(); // 获取当前读取的位置
// detect out of order blocks, and store them for later // 侦测无序块,并存储下来供以后使用
uint256 hash = block.GetHash(); // 获取区块哈希
if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) { // 该哈希不能等于共识上创世区块的哈希,且在区块索引映射列表中找到该区块的前一个区块
LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
block.hashPrevBlock.ToString()); // 把前一个区块哈希转换为字符串形式
if (dbp) // 如果区块磁盘位置对象非空
mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); // 插入区块的未知双亲映射列表
continue; // 跳过
}
// process in case the block isn't known yet // 如果区块未知,则进行处理
if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { // 若该区块哈希不存在于区块索引映射列表,或存在,且其状态为 BLOCK_HAVE_DATA
CValidationState state;
if (ProcessNewBlock(state, chainparams, NULL, &block, true, dbp)) // 处理新区块
nLoaded++; // 加载的区块数加 1
if (state.IsError())
break;
} else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) { // 若区块哈希不等于创世区块哈希,且高度低于 1000
LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
}
// Recursively process earlier encountered successors of this block // 递归处理该块早期遇到的后继
deque<uint256> queue; // 双端队列
queue.push_back(hash); // 放入队列
while (!queue.empty()) { // 当队列非空时
uint256 head = queue.front(); // 取队头
queue.pop_front(); // 队头出队
std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
while (range.first != range.second) {
std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
if (ReadBlockFromDisk(block, it->second, chainparams.GetConsensus()))
{
LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
head.ToString());
CValidationState dummy;
if (ProcessNewBlock(dummy, chainparams, NULL, &block, true, &it->second))
{
nLoaded++;
queue.push_back(block.GetHash());
}
}
range.first++;
mapBlocksUnknownParent.erase(it);
}
}
} catch (const std::exception& e) {
LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
}
}
} catch (const std::runtime_error& e) {
AbortNode(std::string("System error: ") + e.what());
}
if (nLoaded > 0) // 若成功加载了区块
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0; // 返回 true
}
void static CheckBlockIndex(const Consensus::Params& consensusParams)
{
if (!fCheckBlockIndex) {
return;
}
LOCK(cs_main);
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
// so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
// iterating the block tree require that chainActive has been initialized.)
if (chainActive.Height() < 0) {
assert(mapBlockIndex.size() <= 1);
return;
}
// Build forward-pointing map of the entire block tree.
std::multimap<CBlockIndex*,CBlockIndex*> forward;
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
forward.insert(std::make_pair(it->second->pprev, it->second));
}
assert(forward.size() == mapBlockIndex.size());
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
CBlockIndex *pindex = rangeGenesis.first->second;
rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
// Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties.
size_t nNodes = 0;
int nHeight = 0;
CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != NULL) {
nNodes++;
if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
// Begin: actual consistency checks.
if (pindex->pprev == NULL) {
// Genesis block checks.
assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
}
if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
// VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
// HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
if (!fHavePruned) {
// If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(pindexFirstMissing == pindexFirstNeverProcessed);
} else {
// If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
}
if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
// All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == NULL) {
// Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
}
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
if (pindexFirstInvalid == NULL) {
// If this block sorts at least as good as the current tip and
// is valid and we have all data for its parents, it must be in
// setBlockIndexCandidates. chainActive.Tip() must also be there
// even if some data has been pruned.
if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
assert(setBlockIndexCandidates.count(pindex));
}
// If some parent is missing, then it could be that this block was in
// setBlockIndexCandidates but had to be removed because of the missing data.
// In this case it must be in mapBlocksUnlinked -- see test below.
}
} else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex) == 0);
}
// Check whether this block is in mapBlocksUnlinked.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
bool foundInUnlinked = false;
while (rangeUnlinked.first != rangeUnlinked.second) {
assert(rangeUnlinked.first->first == pindex->pprev);
if (rangeUnlinked.first->second == pindex) {
foundInUnlinked = true;
break;
}
rangeUnlinked.first++;
}
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
// If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
assert(foundInUnlinked);
}
if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
// We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
assert(fHavePruned); // We must have pruned.
// This block may have entered mapBlocksUnlinked if:
// - it has a descendant that at some point had more work than the
// tip, and
// - we tried switching to that descendant but were missing
// data for some intermediate block between chainActive and the
// tip.
// So if this block is itself better than chainActive.Tip() and it wasn't in
// setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
if (pindexFirstInvalid == NULL) {
assert(foundInUnlinked);
}
}
}
// assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
// End: actual consistency checks.
// Try descending into the first subnode.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
if (range.first != range.second) {
// A subnode was found.
pindex = range.first->second;
nHeight++;
continue;
}
// This is a leaf node.
// Move upwards until we reach a node of which we have not yet visited the last child.
while (pindex) {
// We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
// Find our parent.
CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
while (rangePar.first->second != pindex) {
assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
rangePar.first++;
}
// Proceed to the next one.
rangePar.first++;
if (rangePar.first != rangePar.second) {
// Move to the sibling.
pindex = rangePar.first->second;
break;
} else {
// Move up further.
pindex = pindexPar;
nHeight--;
continue;
}
}
}
// Check that we actually traversed the entire map.
assert(nNodes == forward.size());
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert // 警报
//
std::string GetWarnings(const std::string& strFor) // rpc
{
int nPriority = 0; // 优先级
string strStatusBar; // 状态条
string strRPC;
string strGUI;
if (!CLIENT_VERSION_IS_RELEASE) { // 客户端版本非发行版
strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
}
if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE)) // 测试安全模式,默认关闭,若开启
strStatusBar = strRPC = strGUI = "testsafemode enabled"; // 初始化信息
// Misc warnings like out of disk space and clock is wrong // 磁盘空间和时钟错误的杂项警告
if (strMiscWarning != "") // 若有杂项警告信息
{
nPriority = 1000; // 设置优先级
strStatusBar = strGUI = strMiscWarning; // 设置信息
}
if (fLargeWorkForkFound) // 若找到大工作量分叉
{
nPriority = 2000;
strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
strGUI = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
}
else if (fLargeWorkInvalidChainFound) // 若找到大工作量无效链
{
nPriority = 2000;
strStatusBar = strRPC = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
strGUI = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
// Alerts // 警报
{
LOCK(cs_mapAlerts); // 警报列表上锁
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) // 遍历警报映射列表
{
const CAlert& alert = item.second; // 获取警报
if (alert.AppliesToMe() && alert.nPriority > nPriority) // 应用到自己 且 该警告优先级高于当前
{
nPriority = alert.nPriority; // 设置高优先级
strStatusBar = strGUI = alert.strStatusBar; // 设置信息
}
}
}
if (strFor == "gui") // 选择 3 种情况
return strGUI;
else if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC; // 返回
assert(!"GetWarnings(): invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) // 检测是否有指定条目
{
switch (inv.type) // 根据库存条目类型进行选择
{
case MSG_TX: // 交易消息
{
assert(recentRejects);
if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) // 若激活的链尖哈希不是最近拒绝的链尖
{
// If the chain tip has changed previously rejected transactions
// might be now valid, e.g. due to a nLockTime'd tx becoming valid,
// or a double-spend. Reset the rejects filter and give those
// txs a second chance.
hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); // 拒绝当前最佳区块
recentRejects->reset();
}
return recentRejects->contains(inv.hash) || // 最近拒绝列表中包含该库存条目
mempool.exists(inv.hash) || // 或交易内存池中包含该交易
mapOrphanTransactions.count(inv.hash) || // 或孤儿交易映射列表中包含该交易
pcoinsTip->HaveCoins(inv.hash); // 或币视图缓存中包含该交易
}
case MSG_BLOCK: // 区块消息
return mapBlockIndex.count(inv.hash); // 根据条目哈希在区块索引映射列表中查询
}
// Don't know what it is, just say we already got one
return true;
}
void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams) // 处理(推送)要获取的数据
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin(); // 获取接收获取数据队列首个元素的迭代器
vector<CInv> vNotFound; // 未找到库存列表
LOCK(cs_main); // 上锁
while (it != pfrom->vRecvGetData.end()) { // 遍历接收获取数据列表
// Don't bother if send buffer is too full to respond anyway // 若发送缓冲区过满无法响应,不要打扰它。
if (pfrom->nSendSize >= SendBufferSize()) // 若发送缓冲区当前大小达到其阈值
break; // 直接跳出
const CInv &inv = *it; // 获取库存条目的引用
{
boost::this_thread::interruption_point(); // 打个断点
it++; // 迭代器后移
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) // 库存消息类型为区块或过滤的区块
{
bool send = false; // 发送标志初始化 false
BlockMap::iterator mi = mapBlockIndex.find(inv.hash); // 从区块索引映射列表中获取该区块索引
if (mi != mapBlockIndex.end()) // 若找到指定的区块索引
{
if (chainActive.Contains(mi->second)) { // 若激活的链上包含该区块
send = true; // 发送标志置为 true
} else { // 否则
static const int nOneMonth = 30 * 24 * 60 * 60; // 一个月的时间 30d
// To prevent fingerprinting attacks, only send blocks outside of the active
// chain if they are valid, and no more than a month older (both in time, and in
// best equivalent proof of work) than the best header chain we know about.
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
(pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
(GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
if (!send) { // 若发送标志为 false
LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId()); // 记录日志
}
}
}
// disconnect node in case we have reached the outbound limit for serving historical blocks
// never disconnect whitelisted nodes // 一旦我们达到服务历史区块的出战限制,断开节点的连接,但永远不会断开白名单中的节点
static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical // 一周时间 7d
if (send && CNode::OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted) // 最佳区块时间和当前区块时间差超过一周 或 库存条目类型为过滤的区块 且 该节点不在白名单中
{
LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
//disconnect node // 断开节点连接
pfrom->fDisconnect = true; // 该节点的断开连接标志置为 true
send = false; // 发送标志置为 false
}
// Pruned nodes may have deleted the block, so check whether
// it's available before trying to send. // 修剪得节点可能删除了该区块,所以在尝试发送前检查它是否可用
if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) // 发送标志为 true 且该区块状态有数据
{
// Send block from disk // 从磁盘上发送区块
CBlock block; // 区块对象
if (!ReadBlockFromDisk(block, (*mi).second, consensusParams)) // 从磁盘上读取区块索引对应区块
assert(!"cannot load block from disk");
if (inv.type == MSG_BLOCK) // 若库存条目类型为区块
pfrom->PushMessage(NetMsgType::BLOCK, block); // 发送该区块到对端
else // MSG_FILTERED_BLOCK) // 否则为过滤得区块
{
LOCK(pfrom->cs_filter); // 过滤器上锁
if (pfrom->pfilter) // 若布鲁姆过滤器存在
{
CMerkleBlock merkleBlock(block, *pfrom->pfilter);
pfrom->PushMessage(NetMsgType::MERKLEBLOCK, merkleBlock);
// CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
// This avoids hurting performance by pointlessly requiring a round-trip
// Note that there is currently no way for a node to request any single transactions we didn't send here -
// they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
pfrom->PushMessage(NetMsgType::TX, block.vtx[pair.first]);
}
// else // 否则
// no response // 无响应
}
// Trigger the peer node to send a getblocks request for the next batch of inventory // 触发对端节点发送一个用于下一批库存的 getblocks 请求
if (inv.hash == pfrom->hashContinue) // 若该库存条目为下一批的首个区块哈希
{
// Bypass PushInventory, this must send even if redundant, // 绕过 PushInventory,尽管冗余但必须发送,
// and we want it right after the last block so they don't // 我们希望它在最后一个块之后,所以它们不会先等待其它东西。
// wait for other stuff first.
vector<CInv> vInv; // 库存列表
vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); // 加入最佳区块到库存列表中
pfrom->PushMessage(NetMsgType::INV, vInv); // 推送库存列表到对端
pfrom->hashContinue.SetNull(); // 置空下一批首个区块哈希
}
}
}
else if (inv.IsKnownType()) // 若该库存条目为已知类型
{
// Send stream from relay memory // 从中继内存中发送数据流
bool pushed = false; // 推送标志初始化为 false
{
LOCK(cs_mapRelay); // 中继映射列表上锁
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); // 在中继映射列表中查找该库存条目
if (mi != mapRelay.end()) { // 若找到
pfrom->PushMessage(inv.GetCommand(), (*mi).second); // 推送对应数据到对端
pushed = true; // 推送标志置 true
}
}
if (!pushed && inv.type == MSG_TX) { // 若未找到该库存 且 该条目类型为交易消息
CTransaction tx; // 创建一个交易对象
if (mempool.lookup(inv.hash, tx)) { // 在内存之中查找并获取该交易
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); // 创建数据流对象
ss.reserve(1000); // 预开辟 1000 个字节
ss << tx; // 把交易导入数据流
pfrom->PushMessage(NetMsgType::TX, ss); // 把该交易的数据流推送给对端
pushed = true; // 推送标志置为 true
}
}
if (!pushed) { // 若推送标志为 false
vNotFound.push_back(inv); // 把该条目加入未找到的库存列表
}
}
// Track requests for our stuff. // 跟踪我们东西的请求
GetMainSignals().Inventory(inv.hash); // 增加库存请求的次数
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) // 若条目类型为区块或过滤的区块
break; // 跳出
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); // 从接收的获取数据队列中擦除已处理(推送)的数据
if (!vNotFound.empty()) { // 若未找到库存列表非空
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage(NetMsgType::NOTFOUND, vNotFound); // 推送未找到列表到对端
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived) // 入参:节点,命令,数据,接收时间
{
const CChainParams& chainparams = Params(); // 获取链参数
RandAddSeedPerfmon(); // 设置随机数种子
LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); // 日志记录命令(序列化字符串,防止字符串格式攻击)、接收数据大小、对方 id
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) // 若开启了丢弃消息测试选项,则获取一个随机数若为 0,则丢弃该命令
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); // 记录日志,不处理该命令
return true; // 直接返回 true
}
if (!(nLocalServices & NODE_BLOOM) &&
(strCommand == NetMsgType::FILTERLOAD || // 若为加载过滤器
strCommand == NetMsgType::FILTERADD || // 添加过滤器
strCommand == NetMsgType::FILTERCLEAR)) // 清除过滤器
{
if (pfrom->nVersion >= NO_BLOOM_VERSION) { // 版本号满足 70011
Misbehaving(pfrom->GetId(), 100); // 处理行为不端的节点
return false;
} else if (GetBoolArg("-enforcenodebloom", false)) { // 若强制节点布鲁姆选项开启
pfrom->fDisconnect = true; // 断开连接标志置为 true
return false; // 退出返回 false
}
}
if (strCommand == NetMsgType::VERSION) // 版本消息
{
// Each connection can only send one version message // 每建立一条连接便会先(只)发送一条该消息
if (pfrom->nVersion != 0) // 若版本号不为 0,则说明第二次收到该版本信息
{
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, string("Duplicate version message")); // 回复 REJECT 消息,表明重复发送版本消息
Misbehaving(pfrom->GetId(), 1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; // 按序接收至接收者地址信息
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION) // 若协议版本比 MIN_PEER_PROTO_VERSION 低,则发送相应提示信息并断开连接
{
// disconnect from peers older than this proto version // 与低于该版本的对端断开连接
LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)); // 协议版本号过低,回复 REJECT 消息
pfrom->fDisconnect = true; // 断开连接标志置为 true
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce; // 接收发送者地址信息和节点唯一随机 id
if (!vRecv.empty()) {
vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH); // 接收自版本信息
pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
}
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight; // 接收发送节点拥有的最新块高度
if (!vRecv.empty())
vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message // 设置是否转发交易条目
else
pfrom->fRelayTxes = true;
// Disconnect if we connected to ourself // 如果我们连接到自己则断开连接
if (nNonce == nLocalHostNonce && nNonce > 1) // 若连接到自身就断开
{
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true; // 断开连接标志置为 true
return true;
}
pfrom->addrLocal = addrMe;
if (pfrom->fInbound && addrMe.IsRoutable())
{
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear // 害羞,我们不发送版本直到我们接收到
if (pfrom->fInbound) // 若连入标志为 true
pfrom->PushVersion(); // 发送版本信息
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
// Potentially mark this peer as a preferred download peer. // 可能编辑该对端为最佳下载对端
UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
// Change version // 改变版本
pfrom->PushMessage(NetMsgType::VERACK); // 发送版本确认信息
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); // 保证协议版本至少为 70012
if (!pfrom->fInbound) // 若连入标志为 false
{
// Advertise our address // 广告我们的地址
if (fListen && !IsInitialBlockDownload()) // 若为监听节点 且 为完成 IBD
{
CAddress addr = GetLocalAddress(&pfrom->addr); // 获取本地地址
if (addr.IsRoutable()) // 查路由表
{
LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
pfrom->PushAddress(addr); // 推送该地址到对端
} else if (IsPeerAddrLocalGood(pfrom)) { // 若是对端地址
addr.SetIP(pfrom->addrLocal); // 设置本地 IP
LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
pfrom->PushAddress(addr); // 推送该地址到对端
}
}
// Get recent addresses // 获取最近的地址集
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) // 若对方为 fOneShot,或协议版本大于 31402,或本地地址库存小于 1000
{
pfrom->PushMessage(NetMsgType::GETADDR); // 回复 GETADDR 消息
pfrom->fGetAddr = true; // 获取地址标志置为 true
}
addrman.Good(pfrom->addr); // 标记该地址为可访问
} else { // 若连入标志为 true
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) // 且 form 地址和本地地址相同
{
addrman.Add(addrFrom, addrFrom); // 添加单个地址到地址管理器
addrman.Good(addrFrom); // 标记该地址为可访问
}
}
// Relay alerts // 中继报警
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) // 若本地接收过告警消息,则转发 ALERT 消息
item.second.RelayTo(pfrom); // 中继到对端
}
pfrom->fSuccessfullyConnected = true; // 成功连接标志置为 true
string remoteAddr;
if (fLogIPs) // 若记录 IPs 到日志选项开启
remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
pfrom->cleanSubVer, pfrom->nVersion,
pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
remoteAddr);
int64_t nTimeOffset = nTime - GetTime();
pfrom->nTimeOffset = nTimeOffset; // 时间偏移量,即消息发送时到接收后的时间差
AddTimeData(pfrom->addr, nTimeOffset); // 这里标志这一条连接的真正建立
}
else if (pfrom->nVersion == 0) // 在其他任何命令执行之前必须有版本信息
{
// Must have a version message before anything else
Misbehaving(pfrom->GetId(), 1);
return false;
}
else if (strCommand == NetMsgType::VERACK) // 版本确认消息,用于确认版本消息
{
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
// Mark this node as currently connected, so we update its timestamp later.
if (pfrom->fNetworkNode) {
LOCK(cs_main);
State(pfrom->GetId())->fCurrentlyConnected = true; // 标记此节点已连接
}
if (pfrom->nVersion >= SENDHEADERS_VERSION) { // 若协议版本大于等于 70012
// Tell our peer we prefer to receive headers rather than inv's
// We send this to non-NODE NETWORK peers as well, because even
// non-NODE NETWORK peers can announce blocks (such as pruning
// nodes)
pfrom->PushMessage(NetMsgType::SENDHEADERS); // 回复 SENDHEADERS 消息,标识节点使用头优先模式来同步区块
}
}
else if (strCommand == NetMsgType::ADDR) // 地址消息,转发节点地址列表
{
vector<CAddress> vAddr; // 地址列表
vRecv >> vAddr; // 导入接收的数据
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) // 协议版本过早且本地连接库存大于 1000 条
return true;
if (vAddr.size() > 1000) // 地址列表条目最大限制为 1000 条
{
Misbehaving(pfrom->GetId(), 20);
return error("message addr size() = %u", vAddr.size());
}
// Store the new addresses // 存储新地址
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr) // 遍历地址列表
{
boost::this_thread::interruption_point(); // 打个断点
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the addrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt.IsNull())
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable) // 不存储我们连不上的地址
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == NetMsgType::SENDHEADERS) // 头优先消息,用于区块同步
{
LOCK(cs_main);
State(pfrom->GetId())->fPreferHeaders = true; // 设置头优先模式
}
else if (strCommand == NetMsgType::INV) // 库存消息,用于发送本节点的交易和区块列表
{
vector<CInv> vInv; // 库存列表
vRecv >> vInv; // 接收数据导入库存(包含交易、区块列表)
if (vInv.size() > MAX_INV_SZ) // 库存条目最大 50000 条
{
Misbehaving(pfrom->GetId(), 20);
return error("message inv size() = %u", vInv.size());
}
bool fBlocksOnly = GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
// Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true // 如果 whitelistrelay 为 true,则允许白名单的对端在仅区块模式中发送块之外的数据
if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) // 默认允许
fBlocksOnly = false;
LOCK(cs_main);
std::vector<CInv> vToFetch;
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) // 遍历 'inv' 列表
{
const CInv &inv = vInv[nInv]; // 获取一条 'inv'
boost::this_thread::interruption_point(); // 打个断点
pfrom->AddInventoryKnown(inv); // 添加到已知的库存
bool fAlreadyHave = AlreadyHave(inv); // 是否已经有此库存条目
LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
if (inv.type == MSG_BLOCK) { // 库存条目类型为 block
UpdateBlockAvailability(pfrom->GetId(), inv.hash);
if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) { // 满足这 4 个条件
// First request the headers preceding the announced block. In the normal fully-synced
// case where a new block is announced that succeeds the current tip (no reorganization),
// there are no such headers.
// Secondly, and only when we are close to being synced, we request the announced block directly,
// to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
// time the block arrives, the header chain leading up to it is already validated. Not
// doing this will result in the received block being rejected as an orphan in case it is
// not a direct successor.
pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash); // 获取区块头
CNodeState *nodestate = State(pfrom->GetId()); // 获取节点当前的状态
if (CanDirectFetch(chainparams.GetConsensus()) &&
nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { // 冲突区块数小于 16
vToFetch.push_back(inv); // 把 'inv' 条目加入用于获取的列表
// Mark block as in flight already, even though the actual "getdata" message only goes out
// later (within the same cs_main lock, though). // 尽管真正的 "getdata" 数据在后面发送,在这里标记该区块为已经飞行。
MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
}
LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
}
}
else
{
if (fBlocksOnly)
LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id);
else if (!fAlreadyHave && !fImporting && !fReindex)
pfrom->AskFor(inv);
}
// Track requests for our stuff // 追踪我们请求的东西
GetMainSignals().Inventory(inv.hash); // 增加指定区块的 getdata 请求次数
if (pfrom->nSendSize > (SendBufferSize() * 2)) {
Misbehaving(pfrom->GetId(), 50);
return error("send buffer size() = %u", pfrom->nSendSize);
}
}
if (!vToFetch.empty())
pfrom->PushMessage(NetMsgType::GETDATA, vToFetch);
}
else if (strCommand == NetMsgType::GETDATA) // 获取数据消息,用于收到 INV 消息后请求自己不存在的 tx 或 block
{
vector<CInv> vInv; // 'inv' 列表
vRecv >> vInv; // 到入接收数据
if (vInv.size() > MAX_INV_SZ) // 数据尺寸检查
{
Misbehaving(pfrom->GetId(), 20);
return error("message getdata size() = %u", vInv.size());
}
if (fDebug || (vInv.size() != 1)) // 调试打印
LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); // 插入 'inv' 双端队列
ProcessGetData(pfrom, chainparams.GetConsensus());
}
else if (strCommand == NetMsgType::GETBLOCKS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
// Send the rest of the chain
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex))
{
if (pindex->GetBlockHash() == hashStop)
{
LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
// If pruning, don't inv blocks unless we have on disk and are likely to still have
// for some reasonable time window (1 hour) that block relay might require.
const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
{
LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll
// trigger the peer to getblocks the next batch of inventory.
LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == NetMsgType::GETHEADERS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
return true;
}
CNodeState *nodestate = State(pfrom->GetId());
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
BlockMap::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = FindForkInGlobalIndex(chainActive, locator);
if (pindex)
pindex = chainActive.Next(pindex);
}
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
vector<CBlock> vHeaders;
int nLimit = MAX_HEADERS_RESULTS;
LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex))
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
// pindex can be NULL either if we sent chainActive.Tip() OR
// if our peer has chainActive.Tip() (and thus we are sending an empty
// headers message). In both cases it's safe to update
// pindexBestHeaderSent to be our tip.
nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
pfrom->PushMessage(NetMsgType::HEADERS, vHeaders);
}
else if (strCommand == NetMsgType::TX)
{
// Stop processing the transaction early if
// We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
{
LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom->id);
return true;
}
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
bool fMissingInputs = false;
CValidationState state;
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv);
if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
{
mempool.check(pcoinsTip);
RelayTransaction(tx);
vWorkQueue.push_back(inv.hash);
LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
pfrom->id,
tx.GetHash().ToString(),
mempool.size(), mempool.DynamicMemoryUsage() / 1000);
// Recursively process any orphan transactions that depended on this one
set<NodeId> setMisbehaving;
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
if (itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for (set<uint256>::iterator mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi)
{
const uint256& orphanHash = *mi;
const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
bool fMissingInputs2 = false;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
// resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
// anyone relaying LegitTxX banned)
CValidationState stateDummy;
if (setMisbehaving.count(fromPeer))
continue;
if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
{
LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
RelayTransaction(orphanTx);
vWorkQueue.push_back(orphanHash);
vEraseQueue.push_back(orphanHash);
}
else if (!fMissingInputs2)
{
int nDos = 0;
if (stateDummy.IsInvalid(nDos) && nDos > 0)
{
// Punish peer that gave us an invalid orphan tx
Misbehaving(fromPeer, nDos);
setMisbehaving.insert(fromPeer);
LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
}
// Has inputs but not accepted to mempool
// Probably non-standard or insufficient fee/priority
LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
vEraseQueue.push_back(orphanHash);
assert(recentRejects);
recentRejects->insert(orphanHash);
}
mempool.check(pcoinsTip);
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(tx, pfrom->GetId());
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
if (nEvicted > 0)
LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
} else {
assert(recentRejects);
recentRejects->insert(tx.GetHash());
if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
// Always relay transactions received from whitelisted peers, even
// if they were already in the mempool or rejected from it due
// to policy, allowing the node to function as a gateway for
// nodes hidden behind it.
//
// Never relay transactions that we would assign a non-zero DoS
// score for, as we expect peers to do the same with us in that
// case.
int nDoS = 0;
if (!state.IsInvalid(nDoS) || nDoS == 0) {
LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
RelayTransaction(tx);
} else {
LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state));
}
}
}
int nDoS = 0;
if (state.IsInvalid(nDoS))
{
LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
pfrom->id,
FormatStateMessage(state));
if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
}
FlushStateToDisk(state, FLUSH_STATE_PERIODIC);
}
else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
{
std::vector<CBlockHeader> headers;
// Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
unsigned int nCount = ReadCompactSize(vRecv);
if (nCount > MAX_HEADERS_RESULTS) {
Misbehaving(pfrom->GetId(), 20);
return error("headers message size = %u", nCount);
}
headers.resize(nCount);
for (unsigned int n = 0; n < nCount; n++) {
vRecv >> headers[n];
ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
}
LOCK(cs_main);
if (nCount == 0) {
// Nothing interesting. Stop asking this peers for more headers.
return true;
}
CBlockIndex *pindexLast = NULL;
BOOST_FOREACH(const CBlockHeader& header, headers) {
CValidationState state;
if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
Misbehaving(pfrom->GetId(), 20);
return error("non-continuous headers sequence");
}
if (!AcceptBlockHeader(header, state, chainparams, &pindexLast)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
return error("invalid header received");
}
}
}
if (pindexLast)
UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
// Headers message had its maximum size; the peer may have more headers.
// TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
// from there instead.
LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256());
}
bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
CNodeState *nodestate = State(pfrom->GetId());
// If this set of headers is valid and ends in a block with at least as
// much work as our tip, download as much as possible.
if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
vector<CBlockIndex *> vToFetch;
CBlockIndex *pindexWalk = pindexLast;
// Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
!mapBlocksInFlight.count(pindexWalk->GetBlockHash())) {
// We don't have this block, and it's not yet in flight.
vToFetch.push_back(pindexWalk);
}
pindexWalk = pindexWalk->pprev;
}
// If pindexWalk still isn't on our main chain, we're looking at a
// very large reorg at a time we think we're close to caught up to
// the main chain -- this shouldn't really happen. Bail out on the
// direct fetch and rely on parallel download instead.
if (!chainActive.Contains(pindexWalk)) {
LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n",
pindexLast->GetBlockHash().ToString(),
pindexLast->nHeight);
} else {
vector<CInv> vGetData;
// Download as much as possible, from earliest to latest.
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vToFetch) {
if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
// Can't download any more from this peer
break;
}
vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex);
LogPrint("net", "Requesting block %s from peer=%d\n",
pindex->GetBlockHash().ToString(), pfrom->id);
}
if (vGetData.size() > 1) {
LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n",
pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
}
if (vGetData.size() > 0) {
pfrom->PushMessage(NetMsgType::GETDATA, vGetData);
}
}
}
CheckBlockIndex(chainparams.GetConsensus());
}
else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
CInv inv(MSG_BLOCK, block.GetHash());
LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
pfrom->AddInventoryKnown(inv);
CValidationState state;
// Process all blocks from whitelisted peers, even if not requested,
// unless we're still syncing with the network.
// Such an unrequested block may still be processed, subject to the
// conditions in AcceptBlock().
bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
ProcessNewBlock(state, chainparams, pfrom, &block, forceProcessing, NULL);
int nDoS;
if (state.IsInvalid(nDoS)) {
assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if (nDoS > 0) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), nDoS);
}
}
}
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making nodes which are behind NAT and can only make outgoing connections ignore
// the getaddr message mitigates the attack.
else if ((strCommand == NetMsgType::GETADDR) && (pfrom->fInbound)) // 获取地址消息
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr); // 回复本地节点的地址列表信息
}
else if (strCommand == NetMsgType::MEMPOOL)
{
if (CNode::OutboundTargetReached(false) && !pfrom->fWhitelisted)
{
LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
pfrom->fDisconnect = true;
return true;
}
LOCK2(cs_main, pfrom->cs_filter);
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
BOOST_FOREACH(uint256& hash, vtxid) {
CInv inv(MSG_TX, hash);
if (pfrom->pfilter) {
CTransaction tx;
bool fInMemPool = mempool.lookup(hash, tx);
if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
if (!pfrom->pfilter->IsRelevantAndUpdate(tx)) continue;
}
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pfrom->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
if (vInv.size() > 0)
pfrom->PushMessage(NetMsgType::INV, vInv);
}
else if (strCommand == NetMsgType::PING) // 类似于心跳机制,收到 ping 后,回复 pong
{
if (pfrom->nVersion > BIP0031_VERSION) // BIP0031 之后的版本可用
{
uint64_t nonce = 0;
vRecv >> nonce; // 接收 ping 方发送的随机数
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage(NetMsgType::PONG, nonce); // 发送包含该随机数的 pong 消息,用于验证,类似于回显
}
}
else if (strCommand == NetMsgType::PONG) // pong 消息,用于回复 ping 消息
{
int64_t pingUsecEnd = nTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail(); // 获取接收消息体数据的大小
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce; // 获取回复的随机数
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) { // 比较发送过去的随机数和接收到回复的随机数
// Matching pong received, this ping is no longer outstanding
bPingFinished = true; // ping 成功
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else { // 随机数不匹配
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
pfrom->id,
sProblem,
pfrom->nPingNonceSent,
nonce,
nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0; // ping 成功后,发送随机数置 0
}
}
else if (fAlerts && strCommand == NetMsgType::ALERT) // 改变消息,用于节点间发送通知
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert(chainparams.AlertKey()))
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode); // 传播消息到每个与之相连的节点
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
Misbehaving(pfrom->GetId(), 10);
}
}
}
else if (strCommand == NetMsgType::FILTERLOAD) // Bloom Filter
{
CBloomFilter filter;
vRecv >> filter;
if (!filter.IsWithinSizeConstraints())
// There is no excuse for sending a too-large filter
Misbehaving(pfrom->GetId(), 100);
else
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
pfrom->pfilter->UpdateEmptyFull();
}
pfrom->fRelayTxes = true;
}
else if (strCommand == NetMsgType::FILTERADD) // Bloom Filter
{
vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
Misbehaving(pfrom->GetId(), 100);
} else {
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
pfrom->pfilter->insert(vData);
else
Misbehaving(pfrom->GetId(), 100);
}
}
else if (strCommand == NetMsgType::FILTERCLEAR) // Bloom Filter
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter();
pfrom->fRelayTxes = true;
}
else if (strCommand == NetMsgType::REJECT) // 拒绝消息,用于告知对方发送的消息被拒
{
if (fDebug) { // debug 模式下可用
try {
string strMsg; unsigned char ccode; string strReason;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
{
uint256 hash;
vRecv >> hash;
ss << ": hash " << hash.ToString();
}
LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
} catch (const std::ios_base::failure&) {
// Avoid feedback loops by preventing reject messages from triggering a new reject message.
LogPrint("net", "Unparseable reject message received\n");
}
}
}
else
{
// Ignore unknown commands for extensibility // 忽略未知命令,为了可扩展性
LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
}
return true;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom) // 处理网络消息
{
const CChainParams& chainparams = Params(); // 获取链参数
//if (fDebug)
// LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
//
// Message format // 消息格式:消息头(24bytes) + 消息体(数据)
// (4) message start // 魔数,用于区分网络消息类型
// (12) command // 消息类型(命令)不足后补'\0'
// (4) size // 数据长度,限制 MAX_PROTOCOL_MESSAGE_LENGTH = 2MB
// (4) checksum // 校验和,SHA256(SHA256(data))结果的前 4 个字节,对于 VERACK、GETADDR 和 SEND-HEADERS 这种无 data 的消息,则固定为 0x5df6e0e2 (SHA256(SHA256(<empty string>)))
// (x) data // 数据,注:比特币消息报文中,大多数整数都是使用的小端编码,只有 IP 地址和端口号使用大端编码
//
bool fOk = true; // ok 标志,初始化为 true
if (!pfrom->vRecvGetData.empty()) // 若接收获取数据 inv 队列非空
ProcessGetData(pfrom, chainparams.GetConsensus()); // 处理获取数据
// this maintains the order of responses // 该操作维持响应顺序
if (!pfrom->vRecvGetData.empty()) return fOk; // 若接收获取数据队列还非空,直接返回 true
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // 若未断开连接,则遍历接收消息队列
// Don't bother if send buffer is too full to respond anyway // 若发送缓冲区太满而无法响应,不要打扰
if (pfrom->nSendSize >= SendBufferSize()) // 若发送缓冲区大小超过其阈值
break; // 跳出
// get next message // 获取下一条消息
CNetMessage& msg = *it; // 获取当前的网络消息
//if (fDebug)
// LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete()) // 若消息不完整
break; // 跳出
// at this point, any failure means we can delete the current message // 此时,任何失败意味着我们可以删除当前消息
it++; // 消息队列迭代器向后移动一位
// Scan for message start // 扫描消息魔数
if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), MESSAGE_START_SIZE) != 0) { // 验证消息魔数
LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
fOk = false; // 若消息魔数不匹配,状态置为 false
break; // 跳出
}
// Read header // 读消息头
CMessageHeader& hdr = msg.hdr; // 获取消息头
if (!hdr.IsValid(chainparams.MessageStart())) // 再次检查消息头魔数是否一致
{
LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
continue;
}
string strCommand = hdr.GetCommand(); // 获取命令
// Message size // 消息大小
unsigned int nMessageSize = hdr.nMessageSize; // 获取数据大小
// Checksum // 校验和
CDataStream& vRecv = msg.vRecv; // 获取消息体数据
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); // 计算消息体哈希
unsigned int nChecksum = ReadLE32((unsigned char*)&hash); // 计算校验和
if (nChecksum != hdr.nChecksum) // 通过校验和进行数据的一致性检查
{
LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message // 处理消息
bool fRet = false;
try
{
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime); // 根据命令进行响应
boost::this_thread::interruption_point(); // 打个断点
}
catch (const std::ios_base::failure& e)
{ // 失败根据错误类型进行响应
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, string("error parsing message"));
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
break; // 跳出,调用该接口一次只处理一条网络消息
}
// In case the connection got shut down, its receive buffer was wiped // 一旦连接关闭,其接收缓冲区会被擦除
if (!pfrom->fDisconnect) // 若未断开连接
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); // 从接收消息队列中擦除读取过的网络消息
return fOk; // 返回 ok 状态
}
bool SendMessages(CNode* pto) // 发送消息
{
const Consensus::Params& consensusParams = Params().GetConsensus(); // 获取共识
{
// Don't send anything until we get its version message // 在我们获取其版本信息前不发送任何内容
if (pto->nVersion == 0) // 确保连接建立完毕,且版本号非 0
return true;
//
// Message: ping // 消息:ping
//
bool pingSend = false; // ping 发送标志初始化为 false
if (pto->fPingQueued) { // 若该节点请求一个 ping
// RPC ping request by user // 通过用户调用 RPC ping 请求
pingSend = true; // 发送 ping 标志置为 true
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) { // 若预计无 pong 响应且
// Ping automatically sent as a latency probe & keepalive. // ping 自动发送,用于延迟(2 分钟)刺探和保活
pingSend = true; // 发送 ping 标志置为 true
}
if (pingSend) { // 若发送 ping 的标志为 true
uint64_t nonce = 0;
while (nonce == 0) {
GetRandBytes((unsigned char*)&nonce, sizeof(nonce)); // 生成一个随机数
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros(); // 设置当前时间(微秒)为最后一个 ping 的发送时间
if (pto->nVersion > BIP0031_VERSION) { // 若节点版本超过 60000(新版)
pto->nPingNonceSent = nonce; // 把随机数作为预计 pong 的响应时间
pto->PushMessage(NetMsgType::PING, nonce); // 发送 ping 命令
} else { // 否则对端太旧了,不支持带 nonce 的 ping 命令,pong 从不会到达。
// Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0;
pto->PushMessage(NetMsgType::PING); // 发送 ping 命令
}
}
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
// Address refresh broadcast // 地址刷新广播
int64_t nNow = GetTimeMicros(); // 获取当前时间,微秒
if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) { // 若未初始化块下载完成 且 下一个本地地址发送时间小于当前时间
AdvertizeLocal(pto); // 推送我们自己的地址到对端
pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); // 泊松分布获取下一个发送的时间
}
//
// Message: addr // 消息:地址
//
if (pto->nNextAddrSend < nNow) {
pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
vector<CAddress> vAddr; // 地址列表
vAddr.reserve(pto->vAddrToSend.size()); // 预开辟与待发送地址列表一样大小的空间
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) // 遍历待发送的地址列表
{
if (!pto->addrKnown.contains(addr.GetKey())) // 若该地址不在已知的地址过滤器中
{
pto->addrKnown.insert(addr.GetKey()); // 插入已知的地址过滤器
vAddr.push_back(addr); // 并加入地址列表
// receiver rejects addr messages larger than 1000 // 接收者拒绝条目超过 1000 的消息
if (vAddr.size() >= 1000) // 若地址条目等于 1000
{
pto->PushMessage(NetMsgType::ADDR, vAddr); // 发送该地址列表到对端
vAddr.clear(); // 清空地址列表
}
}
}
pto->vAddrToSend.clear(); // 清空待发送的地址列表
if (!vAddr.empty()) // 若地址列表非空
pto->PushMessage(NetMsgType::ADDR, vAddr); // 再次发送地址列表到对端
}
CNodeState &state = *State(pto->GetId()); // 根据节点 id 获取节点状态
if (state.fShouldBan) { // 若该节点应该被断开或屏蔽
if (pto->fWhitelisted) // 且该节点在白名单中
LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
else { // 否则
pto->fDisconnect = true; // 断开连接标志置为 true
if (pto->addr.IsLocal()) // 若对端是本地节点
LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
else // 否则
{
CNode::Ban(pto->addr, BanReasonNodeMisbehaving); // 添加该节点地址到禁止列表(黑名单)中
}
}
state.fShouldBan = false; // 应该屏蔽的状态置为 false
}
BOOST_FOREACH(const CBlockReject& reject, state.rejects) // 遍历节点状态区块拒绝列表
pto->PushMessage(NetMsgType::REJECT, (string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock); // 推送到拒消息到对端
state.rejects.clear(); // 清空拒绝列表
// Start block sync // 开始区块同步
if (pindexBestHeader == NULL)
pindexBestHeader = chainActive.Tip(); // 获取当前最佳链尖区块索引指针
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
// Only actively request headers from a single peer, unless we're close to today.
if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
state.fSyncStarted = true; // 开始同步标志置为 true
nSyncStarted++; // 开启同步标志的节点数量加 1
const CBlockIndex *pindexStart = pindexBestHeader; // 获取最佳区块索引
/* If possible, start at the block preceding the currently
best known header. This ensures that we always get a
non-empty list of headers back as long as the peer
is up-to-date. With a non-empty response, we can initialise
the peer's known best block. This wouldn't be possible
if we requested starting at pindexBestHeader and
got back an empty response. */
if (pindexStart->pprev) // 若前一个块存在
pindexStart = pindexStart->pprev; // 指向前一个块
LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
pto->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()); // 发送获取区块头的消息
}
}
// Resend wallet transactions that haven't gotten in a block yet // 重新还没进入块发送钱包交易,
// Except during reindex, importing and IBD, when old wallet // 除了再索引,导入和 IBD 期间,
// transactions become unconfirmed and spams other nodes. // 当旧钱包交易变成未确认的且阻止其它节点
if (!fReindex && !fImporting && !IsInitialBlockDownload()) // 非再索引 且 非导入 且 非 IBD 完成
{
GetMainSignals().Broadcast(nTimeBestReceived); // 重新进行交易广播
}
//
// Try sending block announcements via headers // 尝试通过区块头发送区块广播
//
{
// If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
// list of block hashes we're relaying, and our peer wants
// headers announcements, then find the first header
// not yet known to our peer but would connect, and send.
// If no header would connect, or if we have too many
// blocks, or if the peer doesn't want headers, just
// add all to the inv queue.
LOCK(pto->cs_inventory); // 库存上锁
vector<CBlock> vHeaders; // 区块头列表
bool fRevertToInv = (!state.fPreferHeaders || pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
CBlockIndex *pBestIndex = NULL; // last header queued for delivery
ProcessBlockAvailability(pto->id); // ensure pindexBestKnownBlock is up-to-date
if (!fRevertToInv) { // false
bool fFoundStartingHeader = false;
// Try to find first header that our peer doesn't have, and // 尝试找到我们对端没有的第一个头,
// then send all headers past that one. If we come across any // 然后发送之后的所有区块头。
// headers that aren't on chainActive, give up. // 如果我们遇到任何不在激活链上的区块头,放弃。
BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) { // 遍历待通知的区块哈希列表
BlockMap::iterator mi = mapBlockIndex.find(hash); // 从区块索引映射列表中查找该区块
assert(mi != mapBlockIndex.end()); // 若找到
CBlockIndex *pindex = mi->second; // 获取该区块索引
if (chainActive[pindex->nHeight] != pindex) { // 验证该区块是否在激活的链上
// Bail out if we reorged away from this block
fRevertToInv = true;
break;
}
assert(pBestIndex == NULL || pindex->pprev == pBestIndex); // 最佳区块索引为空 或 该区块前一个为最佳区块
pBestIndex = pindex; // 最佳区块索引指向当前区块
if (fFoundStartingHeader) { // false
// add this to the headers message // 添加该区块到区块头消息
vHeaders.push_back(pindex->GetBlockHeader());
} else if (PeerHasHeader(&state, pindex)) { // 若对端有该区块头
continue; // keep looking for the first new block // 跳过
} else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) { // 若该区块前没有区块 或 对端有前一个区块
// Peer doesn't have this header but they do have the prior one.
// Start sending headers. // 对端没有该区块头,但它们有前一个区块头。开始发送区块头。
fFoundStartingHeader = true; // 找到并开始发送区块头标志置为 true
vHeaders.push_back(pindex->GetBlockHeader()); // 获取该区块头并发送到对端
} else { // 对端没有该区块头或前一个区块的头 -- 什么都不做,如此纾困
// Peer doesn't have this header or the prior one -- nothing will
// connect, so bail out.
fRevertToInv = true;
break; // 跳出
}
}
}
if (fRevertToInv) { // 若退回到使用 inv,只尝试 inv 链尖。
// If falling back to using an inv, just try to inv the tip.
// The last entry in vBlockHashesToAnnounce was our tip at some point
// in the past. // 待发送的区块列表中最新的条目是我们过去某时刻的链尖。
if (!pto->vBlockHashesToAnnounce.empty()) { // 若该列表非空
const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back(); // 获取尾部(最新)的区块哈希
BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce); // 在区块索引映射列表中查找
assert(mi != mapBlockIndex.end()); // 若找到
CBlockIndex *pindex = mi->second; // 获取对应的区块索引
// Warn if we're announcing a block that is not on the main chain.
// This should be very rare and could be optimized out.
// Just log for now. // 如果我们通知一个不在主链上的区块则发出警告。这应该是罕见的且可以优化。现在只做记录。
if (chainActive[pindex->nHeight] != pindex) { // 若该区块不再激活的链上
LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n",
hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString()); // 记录日志
}
// If the peer announced this block to us, don't inv it back. // 如果对端向我们通知了该块,不要 inv 回它。
// (Since block announcements may not be via inv's, we can't solely rely on
// setInventoryKnown to track this.) // (因为区块通知可能不是通过 inv,所以我们不能单独依赖 setInventoryKnown 来跟踪它。)
if (!PeerHasHeader(&state, pindex)) { // 若对端没有该区块头
pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce)); // 发送 inv 消息到对端
LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__,
pto->id, hashToAnnounce.ToString());
}
}
} else if (!vHeaders.empty()) { // 若区块头列表非空
if (vHeaders.size() > 1) { // 且区块头列表元素个数大于 1
LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
vHeaders.size(),
vHeaders.front().GetHash().ToString(),
vHeaders.back().GetHash().ToString(), pto->id);
} else { // 只有一个或没有的情况
LogPrint("net", "%s: sending header %s to peer=%d\n", __func__,
vHeaders.front().GetHash().ToString(), pto->id);
}
pto->PushMessage(NetMsgType::HEADERS, vHeaders); // 发送区块头列表到对端
state.pindexBestHeaderSent = pBestIndex; // 覆盖节点状态:发送的最佳区块头索引指针
}
pto->vBlockHashesToAnnounce.clear(); // 清空待通知的区块哈希列表
}
//
// Message: inventory // 消息:库存(交易)
//
vector<CInv> vInv; // 库存列表
vector<CInv> vInvWait; // 库存等待列表
{
bool fSendTrickle = pto->fWhitelisted; // 获取该节点加入白名单的标志作为涓流发送标志
if (pto->nNextInvSend < nNow) { // 若下一条库存发送时间小于当前时间
fSendTrickle = true; // 涓流发送标志置为 true
pto->nNextInvSend = PoissonNextSend(nNow, AVG_INVENTORY_BROADCAST_INTERVAL);
}
LOCK(pto->cs_inventory); // 库存上锁
vInv.reserve(std::min<size_t>(1000, pto->vInventoryToSend.size())); // 预开辟至多 1000 条目的空间
vInvWait.reserve(pto->vInventoryToSend.size()); // 库存等待列表预开辟和待发送库存列表一样大的空间
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) // 遍历待发送库存列表
{
if (inv.type == MSG_TX && pto->filterInventoryKnown.contains(inv.hash)) // 若条目类型为交易 且 已知的条目过滤器中含有此交易
continue; // 跳过
// trickle out tx inv to protect privacy // 涓流交易条目来保护隐私
if (inv.type == MSG_TX && !fSendTrickle) // 类型为交易 且 涓流发送标志为 false
{
// 1/4 of tx invs blast to all immediately // 1/4 的交易立刻对所有节点进行轰炸
static uint256 hashSalt;
if (hashSalt.IsNull())
hashSalt = GetRandHash(); // 获取一个随机哈希作为盐值
uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt)); // 该条目哈希 异或 盐值哈希
hashRand = Hash(BEGIN(hashRand), END(hashRand)); // 把上步结果进行 hash256
bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0); // 涓流等待标志
if (fTrickleWait) // 若满足条件
{
vInvWait.push_back(inv); // 加入涓流等待条目列表
continue;
}
}
pto->filterInventoryKnown.insert(inv.hash); // 把该条目哈希插入已知条目的过滤器中
vInv.push_back(inv); // 加入库存列表
if (vInv.size() >= 1000) // 若库存列表元素等于 1000 个
{
pto->PushMessage(NetMsgType::INV, vInv); // 发送该库存列表
vInv.clear(); // 库存列表清空
}
}
pto->vInventoryToSend = vInvWait; // 把库存等待列表中的条目重新放入待发送的库存列表
}
if (!vInv.empty()) // 若库存列表非空
pto->PushMessage(NetMsgType::INV, vInv); // 再次发送库存列表
// Detect whether we're stalling // 检测我们是否停止不前
nNow = GetTimeMicros(); // 获取当前时间,微秒
if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) { // 若节点未断开 且 停止区块下载时间非 0 且 停止时间据当前时间不能超过 2s
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
pto->fDisconnect = true; // 节点断开连接标志置为 true
}
// In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
// (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
// We compensate for other peers to prevent killing off peers due to our own downstream link
// being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
// to unreasonably increase our timeout.
if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) { // 若节点未断开连接 且 飞行中区块链表有元素
QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); // 获取链表中的首个元素
int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0); // 获取已验证下载的同伴个数
if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { // 满足条件
LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id); // 超时下载区块记录
pto->fDisconnect = true; // 节点断开连接标志置为 true
}
}
//
// Message: getdata (blocks) // 消息:getdata(区块)
//
vector<CInv> vGetData; // 获取数据条目列表
if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { // 若节点未断开连接 且 非客户端标志 且
vector<CBlockIndex*> vToDownload;
NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
pindex->nHeight, pto->id);
}
if (state.nBlocksInFlight == 0 && staller != -1) {
if (State(staller)->nStallingSince == 0) {
State(staller)->nStallingSince = nNow;
LogPrint("net", "Stall started peer=%d\n", staller);
}
}
}
//
// Message: getdata (non-blocks) // 消息:getdata(非区块)
//
while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{ // 该节点未断开连接 且 请求映射列表非空 且 该列表中首个元素的时间小于等于当前时间
const CInv& inv = (*pto->mapAskFor.begin()).second; // 获取首个元素的库存条目
if (!AlreadyHave(inv)) // 若该条目不存在
{
if (fDebug) // 若 debug 标志开启,记录相关信息
LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
vGetData.push_back(inv); // 把该条目放入获取数据条目列表
if (vGetData.size() >= 1000) // 当该列表中的条目等于 1000 条时
{
pto->PushMessage(NetMsgType::GETDATA, vGetData); // 推送待获取数据条目列表到对端
vGetData.clear(); // 清空该列表
}
} else { // 若该条目已经存在
//If we're not going to ask, don't expect a response. // 如果我们不去请求,不要期望回复。
pto->setAskFor.erase(inv.hash); // 从待获取数据条目列表中擦除该条目
}
pto->mapAskFor.erase(pto->mapAskFor.begin()); // 从待请求列表中擦除第一项
}
if (!vGetData.empty()) // 若带获取数据条目列表非空
pto->PushMessage(NetMsgType::GETDATA, vGetData); // 再次发送该列表到对端
}
return true;
}
std::string CBlockFileInfo::ToString() const { // 获取区块文件信息
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
}
ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
{
LOCK(cs_main);
return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
}
class CMainCleanup // 主清理类
{
public:
CMainCleanup() {}
~CMainCleanup() {
// block headers // 清理区块头
BlockMap::iterator it1 = mapBlockIndex.begin();
for (; it1 != mapBlockIndex.end(); it1++) // 遍历区块索引映射列表
delete (*it1).second; // 删除区块索引
mapBlockIndex.clear(); // 清空区块索引映射列表
// orphan transactions // 清理孤儿交易
mapOrphanTransactions.clear(); // 清空孤儿交易映射列表
mapOrphanTransactionsByPrev.clear();
}
} instance_of_cmaincleanup; // 全局主清理对象
| [
"mistydew@qq.com"
] | mistydew@qq.com |
fae9affc22bb73220a17c9891d5e952e737cdfec | ff727506bd7b160507ead6d83659b1709b87666c | /simple_edge_detection/ios/Classes/edge_detector.cpp | f6c52533a435cd2e6acac73ce030213acfcdb1e4 | [] | no_license | kevinGmezIoT/OCR_LicenseApp | b8b2624421a691e8fb736434c5f5897bf48dff0d | e980660fac2eb34f32a96b3fc0a8457a601fd32c | refs/heads/main | 2023-03-08T02:16:22.605010 | 2021-02-16T00:22:59 | 2021-02-16T00:22:59 | 335,440,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,390 | cpp | #include "edge_detector.hpp"
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
using namespace cv;
using namespace std;
// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
double EdgeDetector::get_cosine_angle_between_vectors(cv::Point pt1, cv::Point pt2, cv::Point pt0)
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
vector<cv::Point> image_to_vector(Mat& image)
{
int imageWidth = image.size().width;
int imageHeight = image.size().height;
return {
cv::Point(0, 0),
cv::Point(imageWidth, 0),
cv::Point(0, imageHeight),
cv::Point(imageWidth, imageHeight)
};
}
vector<cv::Point> EdgeDetector::detect_edges(Mat& image)
{
vector<vector<cv::Point>> squares = find_squares(image);
vector<cv::Point>* biggestSquare = NULL;
// Sort so that the points are ordered clockwise
struct sortY {
bool operator() (cv::Point pt1, cv::Point pt2) { return (pt1.y < pt2.y);}
} orderRectangleY;
struct sortX {
bool operator() (cv::Point pt1, cv::Point pt2) { return (pt1.x < pt2.x);}
} orderRectangleX;
for (int i = 0; i < squares.size(); i++) {
vector<cv::Point>* currentSquare = &squares[i];
std::sort(currentSquare->begin(),currentSquare->end(), orderRectangleY);
std::sort(currentSquare->begin(),currentSquare->begin()+2, orderRectangleX);
std::sort(currentSquare->begin()+2,currentSquare->end(), orderRectangleX);
float currentSquareWidth = get_width(*currentSquare);
float currentSquareHeight = get_height(*currentSquare);
if (currentSquareWidth < image.size().width / 5 || currentSquareHeight < image.size().height / 5) {
continue;
}
if (currentSquareWidth > image.size().width * 0.99 || currentSquareHeight > image.size().height * 0.99) {
continue;
}
if (biggestSquare == NULL) {
biggestSquare = currentSquare;
continue;
}
float biggestSquareWidth = get_width(*biggestSquare);
float biggestSquareHeight = get_height(*biggestSquare);
if (currentSquareWidth * currentSquareHeight >= biggestSquareWidth * biggestSquareHeight) {
biggestSquare = currentSquare;
}
}
if (biggestSquare == NULL) {
return image_to_vector(image);
}
std::sort(biggestSquare->begin(),biggestSquare->end(), orderRectangleY);
std::sort(biggestSquare->begin(),biggestSquare->begin()+2, orderRectangleX);
std::sort(biggestSquare->begin()+2,biggestSquare->end(), orderRectangleX);
return *biggestSquare;
}
float EdgeDetector::get_height(vector<cv::Point>& square) {
float upperLeftToLowerRight = square[3].y - square[0].y;
float upperRightToLowerLeft = square[1].y - square[2].y;
return max(upperLeftToLowerRight, upperRightToLowerLeft);
}
float EdgeDetector::get_width(vector<cv::Point>& square) {
float upperLeftToLowerRight = square[3].x - square[0].x;
float upperRightToLowerLeft = square[1].x - square[2].x;
return max(upperLeftToLowerRight, upperRightToLowerLeft);
}
cv::Mat EdgeDetector::debug_squares( cv::Mat image )
{
vector<vector<cv::Point> > squares = find_squares(image);
for (const auto & square : squares) {
// draw rotated rect
cv::RotatedRect minRect = minAreaRect(cv::Mat(square));
cv::Point2f rect_points[4];
minRect.points( rect_points );
for ( int j = 0; j < 4; j++ ) {
cv::line( image, rect_points[j], rect_points[(j+1)%4], cv::Scalar(0,0,255), 1, 8 ); // blue
}
}
return image;
}
vector<cv::Point> orderPoint(std::vector<Point> const& input)
{
vector<cv::Point> rect;
rect.push_back(Point(0, 0));
rect.push_back(Point(0, 0));
rect.push_back(Point(0, 0));
rect.push_back(Point(0, 0));
vector<float> suma, resta;
for (int i = 0; i < input.size(); i++) {
suma.push_back(input.at(i).x + input.at(i).y);
}
for (int i = 0; i < suma.size(); i++) {
cout << suma.at(i);
cout << endl;
}
for (int i = 0; i < input.size(); i++) {
resta.push_back(input.at(i).x - input.at(i).y);
}
cout << min_element(suma.begin(), suma.end())-suma.begin();
cout << endl;
cout << max_element(suma.begin(), suma.end())-suma.begin();
cout << endl;
rect.at(0) = input.at(min_element(suma.begin(), suma.end()) - suma.begin());
rect.at(2) = input.at(max_element(suma.begin(), suma.end()) - suma.begin());
rect.at(1) = input.at(min_element(resta.begin(), resta.end()) - resta.begin());
rect.at(3) = input.at(max_element(resta.begin(), resta.end()) - resta.begin());
return rect;
}
vector<vector<cv::Point> > EdgeDetector::find_squares(Mat& image)
{
/*
int erosion_size = 5;
cv::Mat bilateral;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1),
cv::Point(erosion_size, erosion_size));
vector<vector<cv::Point> > contours;
vector<cv::Point> found,approx;
cvtColor(image, image, COLOR_BGR2GRAY);
GaussianBlur(image, image, Size(7, 7),0,0,0);
Canny(image, image, 30, 50, 3);
dilate(image, image, element);
findContours(image, contours, RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
int conteo = 0;
int iWidth = image.size().width;
int iHeight = image.size().height;
int area = iWidth * iHeight;
for (const auto& contour : contours) {
if (cv::contourArea(contour)>=area*0.4 && cv::contourArea(contour) <= area*0.8) {
found = contour;
}
}
float epsilon = 0.1 * arcLength(found, true);
approxPolyDP(found, approx, epsilon, true);
vector<cv::Point> points = orderPoint(approx);
RotatedRect minRect = minAreaRect(found);
Mat boxPts;
boxPoints(minRect, boxPts);
vector<Point> vBoxPts, cornerPts;
for (int y = 0; y < boxPts.rows; y++) {
vBoxPts.push_back(cv::Point(boxPts.at<float>(y, 0), boxPts.at<float>(y, 1)));
}
vector<cv::Point> sqrPoints = orderPoint(vBoxPts);
vector<vector<Point> > squares;
for (int y = 0; y < boxPts.rows; y++) {
cornerPts.push_back((sqrPoints[y] + points[y]) / 2);
}
squares.push_back(cornerPts);
return squares;
*/
int erosion_size = 5;
cv::Mat blur, mask;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1),
cv::Point(erosion_size, erosion_size));
vector<vector<cv::Point> > contours;
vector<cv::Point> found, approx;
GaussianBlur(image, blur, Size(5, 5), 0, 0, 0);
cvtColor(blur, blur, COLOR_BGR2HSV);
inRange(blur, Scalar(21, 39, 64), Scalar(40, 255, 255), mask);
Canny(mask, mask, 30, 40, 3);
dilate(mask, mask, element);
findContours(mask, contours, RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
int conteo = 0;
int iWidth = image.size().width;
int iHeight = image.size().height;
int area = iWidth * iHeight;
for (const auto& contour : contours) {
if (cv::contourArea(contour) >= area * 0.2 && cv::contourArea(contour) <= area * 0.8) {
found = contour;
break;
}
conteo++;
}
//cout << found;
float epsilon = 0.1 * arcLength(found, true);
approxPolyDP(found, approx, epsilon, true);
cout << approx;
vector<cv::Point> points = orderPoint(approx);
cout << points;
cv::cvtColor(mask, mask, CV_GRAY2BGR);
RotatedRect minRect = minAreaRect(found);
Mat boxPts;
boxPoints(minRect, boxPts);
cout << endl << "boxPts " << endl << " " << boxPts << endl;
vector<Point> vBoxPts, cornerPts;
for (int y = 0; y < boxPts.rows; y++) {
vBoxPts.push_back(cv::Point(boxPts.at<float>(y, 0), boxPts.at<float>(y, 1)));
}
vector<cv::Point> sqrPoints = orderPoint(vBoxPts);
vector<vector<Point> > squares;
for (int y = 0; y < boxPts.rows; y++) {
cornerPts.push_back((sqrPoints[y] + points[y]) / 2);
}
squares.push_back(cornerPts);
return squares;
} | [
"kevin.gomez.villanueva.uni@outlook.com"
] | kevin.gomez.villanueva.uni@outlook.com |
47508adeaff7c15fab77a5f0a65788fbed88973a | 04251e142abab46720229970dab4f7060456d361 | /lib/rosetta/source/src/core/energy_methods/SmoothCenPairEnergyCreator.hh | 3ee6f86b141a086f64ed56dea1ad611047eb9682 | [] | no_license | sailfish009/binding_affinity_calculator | 216257449a627d196709f9743ca58d8764043f12 | 7af9ce221519e373aa823dadc2005de7a377670d | refs/heads/master | 2022-12-29T11:15:45.164881 | 2020-10-22T09:35:32 | 2020-10-22T09:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file core/energy_methods/SmoothCenPairEnergy.cc
/// @brief Smooth, differentiable, version of cenpair
/// @author Frank DiMaio
#ifndef INCLUDED_core_scoring_methods_SmoothCenPairEnergyCreator_hh
#define INCLUDED_core_scoring_methods_SmoothCenPairEnergyCreator_hh
#include <core/scoring/methods/EnergyMethodCreator.hh>
#include <core/scoring/methods/EnergyMethodOptions.fwd.hh>
#include <core/scoring/methods/EnergyMethod.fwd.hh>
#include <utility/vector1.hh>
namespace core {
namespace scoring {
namespace methods {
class SmoothCenPairEnergyCreator : public EnergyMethodCreator
{
public:
/// @brief Instantiate a new SmoothCenPairEnergy
methods::EnergyMethodOP
create_energy_method(
methods::EnergyMethodOptions const &
) const override;
/// @brief Return the set of score types claimed by the EnergyMethod
/// this EnergyMethodCreator creates in its create_energy_method() function
ScoreTypes
score_types_for_method() const override;
};
}
}
}
#endif
| [
"lzhangbk@connect.ust.hk"
] | lzhangbk@connect.ust.hk |
32e499c0b6ed9141e563cfa6b8926506b4833d47 | 38e015252bd4151ba7bd79f9384c275d19cef5b5 | /EE205/sudoku/v4/puzzle.cc | 612ff96248720c5c06882cce8b106731c6a283fe | [] | no_license | kensw/EE205 | ca4573af1e14f2566e569136f68df120fd78c9f7 | c52d3fc7a607be5a180c9b61ffb9d8624dc34b47 | refs/heads/master | 2016-09-02T02:35:06.750460 | 2013-05-06T22:18:33 | 2013-05-06T22:18:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,802 | cc | /* file: puzzle_v2.cc */
#include <curses.h>
#include "puzzle.h"
#include "cell.h"
#include <ncurses.h>
#include <iostream>
using namespace std;
/************************************************/
/* */
/* Constructors */
/* */
/************************************************/
Puzzle :: Puzzle() : row(0), col(0), changed(true), protlevel(1)
{
wnd = initscr();
/* title screen */
move(3,20);
deleteln();
insstr("/*************************************/");
move(4,20);
deleteln();
insstr("/* */");
move(5,20);
deleteln();
insstr("/* XTREME SUDOKU */");
move(6,20);
deleteln();
insstr("/* */");
move(7,20);
deleteln();
insstr("/*************************************/");
move(9,12);
insstr("by Matthew Fall, Ken Wallace, Sammy Khamis, Ed Nerad");
move(15,12);
insstr("please expand window size for the Extreme experience");
move(20,28);
insstr("press any key to continue");
move(20,53);
refresh();
getchar();
/* initialize board */
drawbold(0);
drawrow(1);
drawrow(2);
drawhor(3);
drawrow(4);
drawrow(5);
drawhor(6);
drawrow(7);
drawrow(8);
drawbold(9);
drawrow(10);
drawrow(11);
drawhor(12);
drawrow(13);
drawrow(14);
drawhor(15);
drawrow(16);
drawrow(17);
drawbold(18);
drawrow(19);
drawrow(20);
drawhor(21);
drawrow(22);
drawrow(23);
drawhor(24);
drawrow(25);
drawrow(26);
drawbold(27);
/* display controls */
move(1, 65);
insstr("Controls");
move(2, 65);
insstr("wasd or hjkl = navigation");
move(3, 65);
insstr("n = enter note mode");
move(4, 68);
insstr("-- number = add note (max 3)");
move(5, 68);
insstr("-- BACKSPACE = clear all notes");
move(6, 65);
insstr("H = display hint");
move(7, 65);
insstr("G = give up");
move(8, 65);
insstr("S = submit solution");
move(9, 65);
insstr("Q = quit");
/* initialize cursor starting position */
row = 14;
col = 32;
move(row,col);
refresh();
}
Puzzle :: ~Puzzle()
{ endwin(); }
/************************************************/
/* */
/* Mutators */
/* */
/************************************************/
void Puzzle :: insert(chtype c)
{
/* don't insert anything if the number is already given */
if(cells[realrow(row)][realcol(col)].isgiven())
message("I wouldn't recommend changing that");
else
{ delch();
insch(c);
refresh();
/* update data */
if((c & A_CHARTEXT) == ' ' || (c & A_CHARTEXT) == 8)
cells[realrow(row)][realcol(col)].setnumber(0);
else
cells[realrow(row)][realcol(col)].setnumber(chtypetoint(c));
}
}
void Puzzle :: insert(chtype c, int x, int y)
{ move(x,y);
delch();
insch(c);
move(row,col);
refresh();
}
void Puzzle :: insertnote(char c)
{
chtype ch;
ch = c | A_BOLD;
/* clears all notes */
if(c == 8)
{
for(int i = col-3 ; i != col+3 ; i+=2)
{ move(row-1 , i);
delch();
insch(' ');
}
cells[realrow(row)][realcol(col)].nclear();
}
/* if you try to add more than 3 notes */
else if(cells[realrow(row)][realcol(col)].getncount() == 3)
message("3 notes yo");
/* add the note */
else
{
move(row-1, col-3+2*cells[realrow(row)][realcol(col)].getncount());
delch();
insch(ch);
cells[realrow(row)][realcol(col)].nincrement();
}
move(row, col);
refresh();
}
void Puzzle :: hint()
{ chtype ans;
/* get the answer */
ans = inttochar(cells[realrow(row)][realcol(col)].getanswer()) | A_STANDOUT;
/* show it */
insert(ans);
/* update the data */
cells[realrow(row)][realcol(col)].reveal();
}
void Puzzle :: giveup()
{ for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
if(!cells[i][j].isgiven())
insert(inttochar(cells[i][j].getanswer()), fakerow(i), fakecol(j));
}
bool Puzzle :: submit()
{ bool correct = true;
chtype num;
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
if(!cells[i][j].iscorrect())
{ num = inttochar(cells[i][j].getnumber()) | A_REVERSE;
insert(num, fakerow(i), fakecol(j));
correct = false;
}
return correct;
}
/************************************************/
/* */
/* Helpful public functions */
/* */
/************************************************/
void Puzzle :: message(const char * str)
{
move(30, 1);
deleteln();
insstr(str);
move(row,col);
refresh();
}
void Puzzle :: clearmessage()
{
move(30, 1);
deleteln();
move(row,col);
refresh();
}
void Puzzle :: moveup(void)
{ /* move cursor to opposite side if end of board is reached */
if(row == 2) row = 26;
else row -=3;
move(row,col);
refresh();
}
void Puzzle :: movedown(void)
{ /* move cursor to opposite side if end of board is reached */
if(row == 26) row = 2;
else row +=3;
move(row,col);
refresh();
}
void Puzzle :: moveleft(void)
{ /* move cursor to opposite side if end of board is reached */
if(col == 4) col = 60;
else col -=7;
move(row,col);
refresh();
}
void Puzzle :: moveright(void)
{ /* move cursor to opposite side if end of board is reached */
if(col == 60) col = 4;
else col +=7;
move(row,col);
refresh();
}
/************************************************/
/* */
/* Puzzle Initialization functions */
/* */
/************************************************/
void Puzzle :: clear()
{
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{ cells[i][j].clear();
insert(' ', fakerow(i), fakecol(j));
}
changed = true;
protlevel = 1;
}
void Puzzle :: make()
{ chtype number;
int x, y;
int guessrow, guesscol;
/* this is an easy puzzle that can be solved without guess mode */
/* puzzle 1 easy book */
/*
int solution[9][9] = {
{3,0,1,0,7,9,0,2,5},
{0,0,0,6,0,0,4,1,7},
{0,0,0,0,1,5,3,0,0},
{0,9,0,0,4,7,0,0,2},
{0,0,4,3,0,8,0,7,0},
{0,8,0,9,6,0,5,3,0},
{7,0,5,0,9,6,0,4,8},
{2,1,0,5,0,0,7,0,6},
{0,4,0,7,0,1,2,5,0} };
*/
/* another easy puzzle */
/* puzzle 80 easy book */
/*
int solution[9][9] = {
{5,4,0,0,0,0,0,0,0},
{0,0,0,7,0,0,0,0,0},
{0,0,0,0,0,1,0,5,6},
{0,7,0,0,0,0,0,3,0},
{0,0,1,0,0,9,0,0,2},
{8,0,5,0,0,0,0,0,0},
{4,9,0,0,0,5,0,8,0},
{0,3,2,9,0,0,4,7,0},
{0,0,0,6,0,0,0,0,9} };
*/
/* this is a medium puzzle that we must use the guess mode to solve */
/* puzzle 40 medium book */
int solution[9][9] = {
{1,0,0,0,8,5,0,0,7},
{0,0,0,0,3,0,0,0,0},
{0,4,0,0,0,0,6,5,0},
{5,0,0,0,7,6,0,0,0},
{2,9,0,0,0,0,0,0,0},
{0,0,4,5,0,3,0,8,0},
{0,6,0,0,0,0,9,1,0},
{0,0,0,9,0,0,0,0,0},
{3,7,0,0,2,4,0,0,0} };
/* solution with correct rows and cols , incorrect boxes */
/*
int solution[9][9] = {
{1,2,3,4,5,6,7,8,9},
{9,1,2,3,4,5,6,7,8},
{8,9,1,2,3,4,5,6,7},
{7,8,9,1,2,3,4,5,6},
{6,7,8,9,1,2,3,4,5},
{5,6,7,8,9,1,2,3,4},
{4,5,6,7,8,9,1,2,3},
{3,4,5,6,7,8,9,1,2},
{2,3,4,5,6,7,8,9,1} };
*/
/* insert answer matrix into cells */
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
cells[i][j].setanswer(solution[i][j]);
cells[i][j].setlevel(protlevel);
}
/* solve */
while(!CorrectSolution())
while(!CompleteSolution())
{
/*Solving with Smart Logic */
changed = true;
while(changed)
{ changed = false;
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
elimrow(i,j);
elimcol(i,j);
elimbox(i,j);
}
}
/* apply current protection level to filled in cells */
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
if(cells[i][j].getanswer() && !cells[i][j].getlevel())
cells[i][j].setlevel(protlevel);
}
/* Guessing algorithm */
if(!CompleteSolution())
{
protlevel++;
guess();
}
}
/* check if puzzle is correct */
if(CorrectSolution())
message("Yea boi");
if(!CorrectSolution())
{
message("Shit");
/* pick the next guess */
do {
/* go to the latest guess and eliminate that guess from possibilites */
for(x = 0; x < 9; x++)
for(y = 0; y < 9; y++)
{
if(cells[x][y].getnumber() && cells[x][y].getlevel() == protlevel)
{
cells[x][y].eliminate(cells[x][y].getnumber());
cells[x][y].setlevel(0);
guessrow = x;
guesscol = y;
break;
}
}
/* clear all cells that resulted from incorrect guess */
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
if(cells[i][j].getlevel() == protlevel)
cells[i][j].clear();
}
} while(!guess(guessrow, guesscol, cells[guessrow][guesscol].getnumber()));
}
}
/************************************************/
/* */
/* Helper Functions */
/* */
/************************************************/
void Puzzle :: drawrow(int i)
{
chtype bold = ' ' | A_REVERSE;
chtype line = '|';
chtype space = ' ';
for(int n = 0 ; n < 64 ; n++)
{
move(i,col);
delch();
if(n%21 == 0) insch(bold);
else if(n%7 == 0) insch(line);
else insch(space);
refresh();
col++;
}
col = 0;
}
void Puzzle :: drawhor(int i)
{
chtype bold = ' ' | A_REVERSE;
chtype line = '|';
chtype hor = '_';
for(int n = 0 ; n < 64 ; n++)
{
move(i,col);
delch();
if(n%21 == 0) insch(bold);
else if(n%7 == 0) insch(line);
else insch(hor);
refresh();
col++;
}
col = 0;
}
void Puzzle:: drawbold(int i)
{
chtype dc = ' ' | A_REVERSE;
for(int n = 0 ; n < 64 ; n++)
{
move(i,col);
delch();
insch(dc);
refresh();
col++;
}
col = 0;
}
char Puzzle :: inttochar(int x)
{ return (char)(((int)'0') + x); }
int Puzzle :: chtypetoint(chtype x)
{ char ch;
ch = x & A_CHARTEXT;
return (int)ch-(int)'0';
}
int Puzzle :: findbox(const int x, const int y)const
{
if(x < 3) // row 1
{
if(y < 3) // box 1
return 1;
else if(y > 5) // box 3
return 3;
else // box 2
return 2;
}
else if(x > 5) // row 3
{
if(y < 3) // box 7
return 7;
else if(y > 5) // box 9
return 9;
else // box 8
return 8;
}
else // row 2
{
if(y < 3) // box 4
return 4;
else if(y > 5) // box 6
return 6;
else // box 5
return 5;
}
}
/************************************************/
/* */
/* Puzzle Solving Functions */
/* */
/************************************************/
void Puzzle :: elimrow(int x, int y)
{
/* only eliminate if there isn't an answer in the cell */
if(!cells[x][y].getanswer())
/* eliminate all the possibilities by row */
for(int i = 0; i < 9; i++)
if(cells[x][y].eliminate(cells[x][i].getanswer()))
changed = true;
}
void Puzzle :: elimcol(int x, int y)
{
/* only eliminate if there isn't an answer in the cell */
if(!cells[x][y].getanswer())
/* eliminate all the possibilities by column */
for(int i = 0; i < 9; i++)
if(cells[x][y].eliminate(cells[i][y].getanswer()))
changed = true;
}
void Puzzle :: elimbox(int x, int y)
{
/* only eliminate if there isn't an answer in the cell */
if(!cells[x][y].getanswer())
/* eliminate all the possibilities by box */
switch(findbox(x, y))
{
case 1:
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 2:
for(int i=0;i<3;i++)
for(int j=3;j<6;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 3:
for(int i=0;i<3;i++)
for(int j=6;j<9;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 4:
for(int i=3;i<6;i++)
for(int j=0;j<3;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 5:
for(int i=3;i<6;i++)
for(int j=3;j<6;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 6:
for(int i=3;i<6;i++)
for(int j=6;j<9;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 7:
for(int i=6;i<9;i++)
for(int j=0;j<3;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 8:
for(int i=6;i<9;i++)
for(int j=3;j<6;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer()))changed = true;
break;
case 9:
for(int i=6;i<9;i++)
for(int j=6;j<9;j++)
if(cells[x][y].eliminate(cells[i][j].getanswer())) changed = true;
}
}
bool Puzzle :: CompleteSolution()const
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(cells[i][j].getanswer() == 0)
return false;
return true;
}
bool Puzzle :: CorrectSolution() const
{ if(!CompleteSolution()) return false;
int count = 0;
/* check rows */
for(int i = 0; i < 9; i++)
for(int n = 1; n < 10; n++)
{ for(int j = 0; j < 9; j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check columns */
for(int j = 0; j < 9; j++)
for(int n = 1; n < 10; n++)
{ for(int i = 0; i < 9; i++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check boxes */
/* check box 1 */
for(int n = 1; n < 10; n++)
{ for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 2 */
for(int n = 1; n < 10; n++)
{ for(int i=0;i<3;i++)
for(int j=3;j<6;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 3 */
for(int n = 1; n < 10; n++)
{ for(int i=0;i<3;i++)
for(int j=6;j<9;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 4 */
for(int n = 1; n < 10; n++)
{ for(int i=3;i<6;i++)
for(int j=0;j<3;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 5 */
for(int n = 1; n < 10; n++)
{ for(int i=3;i<6;i++)
for(int j=3;j<6;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 6 */
for(int n = 1; n < 10; n++)
{ for(int i=3;i<6;i++)
for(int j=6;j<9;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 7 */
for(int n = 1; n < 10; n++)
{ for(int i=6;i<9;i++)
for(int j=0;j<3;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 8 */
for(int n = 1; n < 10; n++)
{ for(int i=6;i<9;i++)
for(int j=3;j<6;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
/* check box 9 */
for(int n = 1; n < 10; n++)
{ for(int i=6;i<9;i++)
for(int j=6;j<9;j++)
{ if(cells[i][j].getanswer() == n)
count++;
}
/* there can be only one */
if(count != 1) return false;
else count = 0;
}
return true;
}
void Puzzle :: guess()
{
int x;
for(float n=1.0;n<10;n++)
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
if(!cells[i][j].getanswer())
{
for(x=1;x<10;x++)
if(cells[i][j].probability(x) == 1.0/n)
{
cells[i][j].setanswer(x); /* assume guess is the answer */
cells[i][j].setnumber(x); /* save the guess in the number data field */
cells[i][j].setlevel(protlevel);
return;
}
}
}
bool Puzzle :: guess(const int x, const int y, const int prevguess)
{
for(int n=prevguess;n<10;n++)
if(cells[x][y].probability(n))
{
cells[x][y].setanswer(n); /* assume guess is the answer */
cells[x][y].setnumber(n); /* save the guess in the number data field */
cells[x][y].setlevel(protlevel);
return true;
}
protlevel--;
return false;
}
| [
"kensw@wiliki.eng.hawaii.edu"
] | kensw@wiliki.eng.hawaii.edu |
1c11ca54686e3e17752615784b33fe5d80f0801b | 183bc2383944499c7f1dda1baa77cfcfbfab5ba7 | /PineEngine/Source/Pine/Rendering/OrthographicCamera.h | 19ebdc007dff2e6f58bd3831cfde14f79c46e200 | [
"Apache-2.0"
] | permissive | BradleyMarden/PineEngine | e476b92beb2d917df2dab17d441ead8106c19602 | 089cb6853a59ab37b484bb7442932da3f1ab079b | refs/heads/main | 2023-06-20T23:19:00.793561 | 2021-07-29T18:11:54 | 2021-07-29T18:11:54 | 302,451,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,440 | h | #pragma once
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
namespace Pine {
class OrthographicCamera
{
public:
OrthographicCamera(float p_Left, float p_Right, float p_bottom, float p_Top);
glm::vec3 GetPosition() const { return m_Pos; }
void SetPosition(const glm::vec3& p_Pos) { m_Pos = p_Pos; UpdateViewMatrix(); }
float GetRotation() const { return m_Rotation; }
void SetRotation(float p_Rot) { m_Rotation = p_Rot; UpdateViewMatrix(); }
void SetProjection(float left, float right, float bottom, float top);
const glm::mat4& GetProjectionMatrix() const { return m_ProjectionMat; }
const glm::mat4& GetViewMatrix() const { return m_ViewMat; }
const glm::mat4& GetViewProjectionMatrix() { return m_ViewProjectionMat; }
private:
void UpdateViewMatrix();
glm::mat4 m_ProjectionMat;
glm::mat4 m_ViewMat;
glm::mat4 m_ViewProjectionMat;
glm::vec3 m_Pos;
float m_Rotation = 0;
};
//glm::mat4 projection = glm::ortho(0.0f, Window::GetMainWindow()->s_WindowSize.x, 0.0f, Window::GetMainWindow()->s_WindowSize.y, -1.0f, 1.0f);//converts screen space to values between -1:1
//glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, 0));//can be used to imitate move camera(works by shifting all onjects in scene)
//glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, 0));//controls positon of object on screen
//glm::mat4 mvp = projection * view * model;
} | [
"bradleymarden@ez-gamelogic.com"
] | bradleymarden@ez-gamelogic.com |
e615d0df1056708a7521caac4b615c8ebc37c26a | b111f61b47581aa6236ff720c999d5fb0503b83c | /Course 1: Algorithmic Toolbox/week4_divide_and_conquer/2_majority_element/majority_element.cpp | 305b93fa5d58c24567d90f22bc8270fe8755747e | [] | no_license | biqar/data-structures-and-algorithms-specialization | 2e8d41b1538e66a5fd91a6a0058d123378f6d066 | 7c149a3330b79366c3710b4409d3e77e097f4040 | refs/heads/master | 2021-07-25T02:41:23.546913 | 2020-12-24T06:04:03 | 2020-12-24T06:04:03 | 231,165,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | cpp | #include <algorithm>
#include <iostream>
#include <vector>
#include <map>
using std::vector;
using std::map;
int get_majority_element(vector<int> &a, int left, int right) {
if (left == right) return -1;
if (left + 1 == right) return a[left];
//write your code here
return -1;
}
int main() {
int n, x;
map<int, int> m;
std::cin >> n;
map<int, int>::iterator it;
//vector<int> a(n);
for (int i = 0; i < n; i++) {
//std::cin >> a[i];
std::cin >> x;
it = m.find(x);
if (it != m.end()) m[x] += 1;
else m[x] = 1;
}
int mx = -1;
for ( it = m.begin(); it != m.end(); it++) {
if(mx < it->second) mx = it->second;
}
std::cout << (mx > n/2) << '\n';
}
| [
"raqib@tigerit.com"
] | raqib@tigerit.com |
2bcffb9fb8f69cb290b994cbfb6fab57bc603148 | c3782a52da4479a5ca3d0131cbacd3ff23cea572 | /NCKUOnlineJudge/contest3/pC.cpp | 7a49681a27cc578c116a5e91ace10f92cf6bfd24 | [] | no_license | misclicked/Codes | 5def6d488bfd028d415f3dc6f18ff6d904226e6f | 1aa53cf585abf0eed1a47e0a95d894d34942e3b1 | refs/heads/master | 2021-07-16T00:28:05.717259 | 2020-05-25T06:20:37 | 2020-05-25T06:20:37 | 142,436,632 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | cpp | //
// Created by ISMP on 2020/4/8.
//
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define MAX_N 100000
pii fa[2 * MAX_N + 5];
pii find(int x) {
while (fa[x].first != x) {
fa[x] = fa[fa[x].first];
x = fa[x].first;
}
return fa[x];
}
void unite(int x, int y) {
pii X = find(x);
pii Y = find(y);
fa[Y.first] = X;
fa[Y.second] = {X.second, X.first};
}
void en(int x, int y) {
pii X = find(x);
pii Y = find(y);
fa[Y.first] = {X.second, X.first};;
fa[Y.second] = X;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
int a, b, c;
for (int i = 0; i < n; i++) {
fa[i] = {i, MAX_N + 1 + i};
fa[MAX_N + 1 + i] = {MAX_N + 1 + i, i};
}
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &a, &b, &c);
if (a == 1) {
if (find(b) != find(c) && find(b).first != b && find(c).first != c) {
puts("nani");
} else {
unite(b, c);
}
} else if (a == 2) {
if (find(b) == find(c) && find(b).first != b && find(c).first != c) {
puts("nani");
} else {
en(b, c);
}
} else {
if (find(b).first != find(c).first
&& find(b).first != find(c).second
&& find(c).first != find(b).second) {
puts("none");
} else if (find(b) == find(c)) {
puts("friend");
} else {
puts("enemy");
}
}
}
} | [
"lspss92189@gmail.com"
] | lspss92189@gmail.com |
3dab1fcdc826f3cb0a8b80f1f75c04af51cd54d1 | 8b5ab02d82af519962062b2449ff9b93701bdb21 | /CPU/src/Thyristor.cpp | 23d5bc22776710aa1d980f29abaf03358373f929 | [] | no_license | LuizFelipeR/realtimeEMTP | 51df73184dc7084cc3a4b44bb1ca87dd9a235340 | 54c89992c839f5d7bd56fc987259240745a8a52f | refs/heads/master | 2021-11-22T16:40:18.979261 | 2021-11-08T16:46:33 | 2021-11-08T16:46:33 | 171,333,098 | 1 | 0 | null | 2019-03-26T12:35:50 | 2019-02-18T18:16:01 | Makefile | UTF-8 | C++ | false | false | 12,196 | cpp | #include "Thyristor.h"
#include <iostream>
#include <fstream>
#ifdef EXPANDED_SWITCH
Thyristor::Thyristor(double Value, int Node1, int Node2,Circuit& circuit) {
/*
Sets the internal values of the variables as passed by the function
*/
this->value = Value;
this->nodes[0] = Node1;
this->nodes[1] = Node2;
this->Ih = 0;
/*
Sets the pointers V1 and V2 to the corresponding node in the SolvedVector, for the ground node
exception sets the pointer to a member 0 in the Circuit.
*/
if (nodes[0] == 0) {
V1 = &(circuit.V0);
}
else {
V1 = &(circuit.SolvedVector[nodes[0] - 1]);
}
if (nodes[1] == 0) {
V2 = &(circuit.V0);
}
else {
V2 = &(circuit.SolvedVector[nodes[1] - 1]);
}
circuit.SourceId++;
ID = circuit.SourceId;
std::ofstream myfile;
myfile.open("example.txt", std::ios::out | std::ios::app);
myfile << 'I' << 'd' << ID << '\t';
}
//Overrides the stamp fucntion to the Resistor stamp for MNA
void Thyristor::stamp(Circuit& circuit) {
//Creates temporary variables for improved readability
double StampValue;
double Stmp;
int n = 0, nn = 0;
StampValue = (this->value);
//for each node adds to the diagonal a G value
//and substract G from the (i,j) and (j,i) of the AdmittanceMatrix
//The ground node does not appear in the matrix as it is the reference
for (int i = 0; i < 2; i++) {
//Assign the value of the node with a decrement so node 1 is considered the 0th index
n = nodes[i] - 1;
//if node[i] is not ground
if (n != -1) {
for (int ii = 0; ii < 2; ii++) {
//Assign the value of the node with a decrement so node 1 is considered the 0th index
nn = nodes[ii] - 1;
//if node[ii] is not ground
if (nn != -1) {
//Establish the Stmp as the Value G
Stmp = StampValue;
//If not in the diagonal Stmp is assigned as -G
if (n != nn) {
Stmp = -StampValue;
};
//Stamps the term A[i][ii] in the AdmittanceMatrix
circuit.AdmittanceMatrix[n*circuit.totalSize + nn] += Stmp;
};
};
};
};
circuit.AdmittanceMatrix[circuit.totalSize*(circuit.numNodes + ID - 1) + circuit.numNodes + ID - 1] += 1;
if (nodes[0] != 0) {
circuit.AdmittanceMatrix[
circuit.totalSize*(this->nodes[0] - 1) + (circuit.numNodes + ID - 1)
] += 1;
};
if (nodes[1] != 0) {
circuit.AdmittanceMatrix[
circuit.totalSize*(this->nodes[1] - 1) + (circuit.numNodes + ID - 1)
] -= 1;
}
};
void Thyristor::stampRightHand(Circuit& circuit) {
double G;
G = this->value;
S = S * (Ih - G * (*V1 - *V2) < 0) + (1 - S)*(*V1 > *V2);
Ih = S * Ih - (2 * S - 1) * G*(*V1 - *V2);
circuit.RightHandVector[circuit.numNodes + ID - 1] = -Ih;
};
void Thyristor::idealStamp(Circuit& circuit) {
circuit.AdmittanceMatrix[circuit.totalSize*(circuit.numNodes + ID - 1) + circuit.numNodes + ID - 1] += S;
if (nodes[0] != 0) {
circuit.AdmittanceMatrix[
circuit.totalSize*(this->nodes[0] - 1) + (circuit.numNodes + ID - 1)
] += 1;
circuit.AdmittanceMatrix[
circuit.totalSize*(circuit.numNodes + ID - 1) + (this->nodes[0] - 1)
] += 1 - S;
};
if (nodes[1] != 0) {
circuit.AdmittanceMatrix[
circuit.totalSize*(this->nodes[1] - 1) + (circuit.numNodes + ID - 1)
] -= 1;
circuit.AdmittanceMatrix[
circuit.totalSize*(circuit.numNodes + ID - 1) + (this->nodes[1] - 1)
] -= 1 - S;
};
}
#else
/*
Constructor of the Thyristor object
*/
Thyristor::Thyristor(double Value, int Node1, int Node2, Circuit &circuit) {
/*
Sets the internal values of the variables as passed by the function
*/
this->value = Value;
this->nodes.push_back(Node1);
this->nodes.push_back(Node2);
this->Ih = 0;
this->S = 1;
circuit.controlSignals.push_back(new bool(true));
this->gate = circuit.controlSignals[circuit.controlSignals.size()-1];
this->flag = circuit.switchFlag;
if(this->flag==2){
circuit.SourceId++;
ID = circuit.SourceId;
}
}
//Overrides the stamp fucntion to the Thyristor stamp for FAMNM
void Thyristor::stamp(Circuit& circuit) {
switch(circuit.switchFlag){
case 0:
stampConductance(circuit);
break;
case 1:
stampPejovic(circuit);
break;
case 2:
stampMANA(circuit);
break;
default:
stampConductance(circuit);
}
}
void Thyristor::stampConductance(Circuit& circuit){
//Creates temporary variables for improved readability
double StampValue;
double Stmp;
int n = 0, nn = 0;
StampValue = pow((this->value),(2*S-1));
//for each node adds to the diagonal a G value
//and substract G from the (i,j) and (j,i) of the AdmittanceMatrix
//The ground node does not appear in the matrix as it is the reference
for (int i = 0; i < 2; i++) {
//Assign the value of the node with a decrement so node 1 is considered the 0th index
n = nodes[i] - 1;
//if node[i] is not ground
if (n != -1) {
for (int ii = 0; ii < 2; ii++) {
//Assign the value of the node with a decrement so node 1 is considered the 0th index
nn = nodes[ii] - 1;
//if node[ii] is not ground
if (nn != -1) {
//Establish the Stmp as the Value G
Stmp = StampValue;
//If not in the diagonal Stmp is assigned as -G
if (n != nn) {
Stmp = -StampValue;
};
//Stamps the term A[i][ii] in the AdmittanceMatrix
circuit.AdmittanceMatrix[n*circuit.totalSize + nn] += Stmp;
};
};
};
};
};
void Thyristor::stampPejovic(Circuit& circuit){
//Creates temporary variables for improved readability
double StampValue;
double Stmp;
int n = 0, nn = 0;
StampValue = this->value;
//for each node adds to the diagonal a G value
//and substract G from the (i,j) and (j,i) of the AdmittanceMatrix
//The ground node does not appear in the matrix as it is the reference
for (int i = 0; i < 2; i++) {
//Assign the value of the node with a decrement so node 1 is considered the 0th index
n = nodes[i] - 1;
//if node[i] is not ground
if (n != -1) {
for (int ii = 0; ii < 2; ii++) {
//Assign the value of the node with a decrement so node 1 is considered the 0th index
nn = nodes[ii] - 1;
//if node[ii] is not ground
if (nn != -1) {
//Establish the Stmp as the Value G
Stmp = StampValue;
//If not in the diagonal Stmp is assigned as -G
if (n != nn) {
Stmp = -StampValue;
};
//Stamps the term A[i][ii] in the AdmittanceMatrix
circuit.AdmittanceMatrix[n*circuit.totalSize + nn] += Stmp;
};
};
};
};
};
void Thyristor::stampMANA(Circuit &circuit){
if(S){
/*
Check if the node is not ground
*/
if (nodes[0] != 0) {
/*
Stamps +1 for the positive node
*/
circuit.AdmittanceMatrix[
circuit.numNodes + this->ID - 1 + circuit.totalSize*(this->nodes[0] - 1)
] -= 1;
circuit.AdmittanceMatrix[
circuit.totalSize*(circuit.numNodes + this->ID - 1) + (this->nodes[0] - 1)
] += 1;
};
/*
Repeat the ground check
*/
if (nodes[1] != 0) {
/*
Stamps -1 for the negative node
*/
circuit.AdmittanceMatrix[
circuit.numNodes + ID - 1 + circuit.totalSize*(this->nodes[1] - 1)
] += 1;
circuit.AdmittanceMatrix[
circuit.totalSize*(circuit.numNodes + ID - 1) + (this->nodes[1] - 1)
] -= 1;
};
}
else{
if (nodes[0] != 0) {
/*
Stamps +1 for the positive node
*/
circuit.AdmittanceMatrix[
circuit.numNodes + this->ID - 1 + circuit.totalSize*(this->nodes[0] - 1)
] -= 1;
};
/*
Repeat the ground check
*/
if (nodes[1] != 0) {
/*
Stamps -1 for the negative node
*/
circuit.AdmittanceMatrix[
circuit.numNodes + ID - 1 + circuit.totalSize*(this->nodes[1] - 1)
] += 1;
};
circuit.AdmittanceMatrix[
circuit.numNodes + ID - 1 + circuit.totalSize*(circuit.numNodes + ID - 1)
] += 1;
}
}
void Thyristor::trapStamp(Circuit& circuit) {
//Creates temporary variables for improved readability
double G;
G = this->value;
double n1 = nodes[0] - 1;
double n2 = nodes[1] - 1;
/*
Calculates the polarization of the diode
*/
/*
Ih must be:
Ik,m(t-dt) = -ik,m(t-dt), when S=1;
Ik,m(t-dt) = G * Vk,m(t-dt), when S=0.
It's valid to note that for programming purpose the Ih source is pointed towards the node 1,
instead of node 2 as it is in the Capacitor and inductor.
*/
Ihh = Ih;
if(S){
Ih = Ih - G*(*(this->Voltage[0]) - *(this->Voltage[1]));
}
else{
Ih = -Ih + 2*G*(*(Voltage[0])-*(Voltage[1]));
}
//Stamps Ih in the correct position in RightHandVector
if (n1 != -1) {
*circuit.RightHandVector[n1] += Ih;
}
if (n2 != -1) {
*circuit.RightHandVector[n2] -= Ih;
}
}
/*
Stamps the Thyristor in the RightHandVector
*/
void Thyristor::stampRightHand(Circuit& circuit) {
//Creates temporary variables for improved readability
double G;
G = this->value;
double n1 = nodes[0] - 1;
double n2 = nodes[1] - 1;
/*
Calculates the polarization of the Thyristor
*/
/*
Ih must be:
Ik,m(t-dt) = -ik,m(t-dt), when S=1;
Ik,m(t-dt) = G * Vk,m(t-dt), when S=0.
It's valid to note that for programming purpose the Ih source is pointed towards the node 1,
instead of node 2 as it is in the Capacitor and inductor.
*/
// S = S * (Ih - G * (*Voltage[0] - *Voltage[1]) < 0) + (1 - S)*(*Voltage[0] > *Voltage[1]);
Ih = S * Ih - (2 * S - 1) * G*(*Voltage[0] - *Voltage[1]);
//Stamps Ih in the correct position in RightHandVector
if (n1 != -1) {
*circuit.RightHandVector[n1] += Ih;;
}
if (n2 != -1) {
*circuit.RightHandVector[n2] -= Ih;;
}
};
void Thyristor::idealStamp(Circuit& circuit) {}
std::string Thyristor::nodesQuery() {
std::string nodesStr;
for(int i: nodes){
nodesStr+= std::to_string(i) + "\n";
}
return nodesStr;
}
void Thyristor::calculateState(){
switch(this->flag){
case 0:
bool Vpos;
Vpos = *(this->Voltage[0]) > *(this->Voltage[1]);
this->S = this->S*(Vpos)+(1-this->S)*((*this->gate)*Vpos);
break;
case 1:
if(S){
S = (this->Ih - this->value*(*(Voltage[0]) - *(Voltage[1])) < 0);
}
else{
S= (*this->gate)*(*(this->Voltage[0])>*(this->Voltage[1]));
}
break;
case 2:
S = this->S*((this->parentCircuit->SolvedVector[parentCircuit->numNodes+this->ID-1]<0))+
(1-this->S)*(*this->gate)*(*(this->Voltage[0]) > *(this->Voltage[1]));
}
}
double Thyristor::getCurrent(Circuit &circuit){
return (*(this->Voltage[0]) - *(this->Voltage[1]))/pow((this->value),(2*S-1));
}
#endif
| [
"Luizfelipecss@poli.ufrj.br"
] | Luizfelipecss@poli.ufrj.br |
1984502bb48e2e7dbc37cceb80cab82a63a7cb14 | d808d3b7576383329b21847b92a22c7552ac9ae7 | /chrome/browser/ui/webui/chromeos/login/os_install_screen_handler.cc | c8a73818e962f1a96cb41a5f1712692d53213969 | [
"BSD-3-Clause"
] | permissive | tianyu-devc/chromium | a9985e6aaab42360a16624cf62678fba4cd42376 | 8918131525c4c8b438cf593535172ef327b463f9 | refs/heads/master | 2023-06-05T02:29:40.468056 | 2021-06-28T17:50:36 | 2021-06-28T17:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,117 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/login/os_install_screen_handler.h"
#include "base/notreached.h"
#include "chrome/browser/ash/login/screens/os_install_screen.h"
#include "chrome/browser/ui/webui/chromeos/login/js_calls_container.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/login/localized_values_builder.h"
#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
namespace {
constexpr const char kShowConfirmStep[] =
"login.OsInstallScreen.showConfirmStep";
constexpr const char kShowInProgressStep[] =
"login.OsInstallScreen.showInProgressStep";
constexpr const char kShowErrorStep[] = "login.OsInstallScreen.showErrorStep";
constexpr const char kShowSuccessStep[] =
"login.OsInstallScreen.showSuccessStep";
} // namespace
// static
constexpr StaticOobeScreenId OsInstallScreenView::kScreenId;
OsInstallScreenHandler::OsInstallScreenHandler(
JSCallsContainer* js_calls_container)
: BaseScreenHandler(kScreenId, js_calls_container) {
set_user_acted_method_path("login.OsInstallScreen.userActed");
}
OsInstallScreenHandler::~OsInstallScreenHandler() {
OsInstallClient::Get()->RemoveObserver(this);
if (screen_)
screen_->OnViewDestroyed(this);
}
void OsInstallScreenHandler::DeclareLocalizedValues(
::login::LocalizedValuesBuilder* builder) {
builder->Add("osInstallDialogIntroTitle", IDS_OS_INSTALL_SCREEN_INTRO_TITLE);
builder->Add("osInstallDialogIntroSubtitle",
IDS_OS_INSTALL_SCREEN_INTRO_SUBTITLE);
builder->Add("osInstallDialogIntroBody", IDS_OS_INSTALL_SCREEN_INTRO_BODY);
builder->Add("osInstallDialogIntroNextButton",
IDS_OS_INSTALL_SCREEN_INTRO_NEXT_BUTTON);
builder->Add("osInstallDialogConfirmTitle",
IDS_OS_INSTALL_SCREEN_CONFIRM_TITLE);
builder->Add("osInstallDialogConfirmBody",
IDS_OS_INSTALL_SCREEN_CONFIRM_BODY);
builder->Add("osInstallDialogConfirmNextButton",
IDS_OS_INSTALL_SCREEN_CONFIRM_NEXT_BUTTON);
builder->Add("osInstallDialogInProgressTitle",
IDS_OS_INSTALL_SCREEN_IN_PROGRESS_TITLE);
builder->Add("osInstallDialogInProgressSubtitle",
IDS_OS_INSTALL_SCREEN_IN_PROGRESS_SUBTITLE);
builder->Add("osInstallDialogErrorTitle", IDS_OS_INSTALL_SCREEN_ERROR_TITLE);
builder->Add("osInstallDialogSuccessTitle",
IDS_OS_INSTALL_SCREEN_SUCCESS_TITLE);
builder->Add("osInstallDialogShutdownButton",
IDS_OS_INSTALL_SCREEN_SHUTDOWN_BUTTON);
}
void OsInstallScreenHandler::Initialize() {}
void OsInstallScreenHandler::Show() {
ShowScreen(kScreenId);
}
void OsInstallScreenHandler::Bind(OsInstallScreen* screen) {
screen_ = screen;
BaseScreenHandler::SetBaseScreen(screen_);
}
void OsInstallScreenHandler::Unbind() {
screen_ = nullptr;
BaseScreenHandler::SetBaseScreen(nullptr);
}
void OsInstallScreenHandler::ShowConfirmStep() {
CallJS(kShowConfirmStep);
}
void OsInstallScreenHandler::StartInstall() {
CallJS(kShowInProgressStep);
OsInstallClient* const os_install_client = OsInstallClient::Get();
os_install_client->AddObserver(this);
os_install_client->StartOsInstall();
}
void OsInstallScreenHandler::StatusChanged(OsInstallClient::Status status,
const std::string& service_log) {
switch (status) {
case OsInstallClient::Status::InProgress:
CallJS(kShowInProgressStep);
break;
case OsInstallClient::Status::Succeeded:
CallJS(kShowSuccessStep);
break;
case OsInstallClient::Status::Failed:
case OsInstallClient::Status::NoDestinationDeviceFound:
CallJS(kShowErrorStep);
break;
}
}
void OsInstallScreenHandler::OsInstallStarted(
absl::optional<OsInstallClient::Status> status) {
if (!status) {
status = OsInstallClient::Status::Failed;
}
StatusChanged(*status, /*service_log=*/"");
}
} // namespace chromeos
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
8f5effeac8a2b07dd6a648cc0849a7130c957643 | 3e0ef6433721c5889a0af8e2740fb26c6cb31148 | /Fusion/src/Fusion/Core/Timestep.h | 7102a5a6f83b211228aa53cf0a5ddd5f5e26b60b | [
"Apache-2.0"
] | permissive | WhoseTheNerd/Fusion | a50dc957c7a26b59cd777ee30f5f6e32319b80aa | 35ab536388392b3ba2e14f288eecbc292abd7dea | refs/heads/master | 2023-04-22T09:00:07.325716 | 2021-05-17T10:14:46 | 2021-05-17T10:14:46 | 188,681,308 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | #pragma once
#include "Fusion/Core/Base.h"
namespace Fusion {
class F_API Timestep
{
public:
Timestep(const float time = 0.0f)
: m_Time(time)
{}
operator float() const { return m_Time; }
float GetSeconds() const { return m_Time; }
float GetMilliseconds() const { return m_Time * 1000.0f; }
private:
float m_Time;
};
}
| [
"tutorialvideohd@gmail.com"
] | tutorialvideohd@gmail.com |
fda61e34d63115d73f05a6f5c80e1f96364aab75 | 420727803d75cfd165fe755e3124070284f71bcb | /PanoHDR/jni/PanoHDR.cpp | 28ee12476a96e6501cd232da16a0f27c5cd016fe | [] | no_license | lidai89/ELEC-549 | 92329c0ef0746103916b62a059c55e87f099f567 | 8f9bbd3ff9d1fab723df445aac8afde30ff07bd8 | refs/heads/master | 2021-01-02T09:44:08.188207 | 2017-01-12T05:47:39 | 2017-01-12T05:47:39 | 78,714,090 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp | #include "PanoHDR.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
//In Panorama.cpp:
void CreatePanorama(vector<string> inputImagePaths, string outputImagePath);
bool CreateHDR(vector<string> inputImagePaths, string outputImagePath);
enum ImageOperation
{
IMAGE_OP_PANORAMA = 0,
IMAGE_OP_HDR = 1
};
static string convertToString(JNIEnv* env, jstring js)
{
const char* stringChars = env->GetStringUTFChars(js, 0);
string s = string(stringChars);
env->ReleaseStringUTFChars(js, stringChars);
return s;
}
JNIEXPORT void JNICALL Java_edu_stanford_cvgl_panohdr_ImageProcessingTask_processImages(JNIEnv* env,
jobject, jobjectArray inputImages, jstring outputPath, jint opCode)
{
string outputImagePath = convertToString(env, outputPath);
vector<string> inputImagePaths;
int imageCount = env->GetArrayLength(inputImages);
for(int i = 0; i < imageCount; ++i)
{
jstring js = (jstring) (env->GetObjectArrayElement(inputImages, i));
inputImagePaths.push_back(convertToString(env, js));
}
switch(opCode)
{
case IMAGE_OP_PANORAMA:
CreatePanorama(inputImagePaths, outputImagePath);
break;
case IMAGE_OP_HDR:
CreateHDR(inputImagePaths, outputImagePath);
break;
default:
cerr << "Invalid operation code provided: " << opCode << endl;
break;
}
}
| [
"lidai89@gmail.com"
] | lidai89@gmail.com |
031146290f650401c267467258752786e5f4a0e8 | ba8c2a94e4e5cc9760534a1d2dc6e8db20d7343e | /DirectX9/DXD9 Practice/121014 Transformation/121014 Transformation/cMatrix.h | 69b5b3af889bdafd1a5c0335030a022da1383ff8 | [
"MIT"
] | permissive | arkiny/Direct3D | a0b8730b8c812eedf5b0c01cc3aa1fe256459a1f | 4ac085976b88a0861453136f0e99d3dc7ab051c7 | refs/heads/master | 2020-12-30T10:23:13.790036 | 2017-04-02T14:02:41 | 2017-04-02T14:02:41 | 27,359,575 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #pragma once
#include <vector>
class vector4;
class cMatrix
{
public:
cMatrix();
~cMatrix();
void setElement(int x, int y, float value);
float getElement(int x, int y);
vector4 operator*(vector4& in);
cMatrix operator*(cMatrix& in);
cMatrix translate(float ix, float iy, float iz);
cMatrix rotateX(float degree);
cMatrix rotateY(float degree);
cMatrix rotateZ(float degree);
cMatrix scale(float ix, float iy, float iz);
private:
std::vector<float> m_vecData;
};
| [
"arkinylee@gmail.com"
] | arkinylee@gmail.com |
2d318015303f3543323c79fb02a167a99dcddd90 | e0f08f8cc9f0547a55b2263bd8b9ee17dcb6ed8c | /SPOJ/SPOJ/XMEN.cpp | 3934614da81f30fe006b6540a8b1c19ed33f7aad | [
"MIT"
] | permissive | aqfaridi/Competitve-Programming-Codes | 437756101f45d431e4b4a14f4d461e407a7df1e9 | d055de2f42d3d6bc36e03e67804a1dd6b212241f | refs/heads/master | 2021-01-10T13:56:04.424041 | 2016-02-15T08:03:51 | 2016-02-15T08:03:51 | 51,711,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,500 | cpp | /*******************************
// Name : Abdul Qadir Faridi
// IPG-3rd yr
// Institute : ABV-IIITM,Gwalior
*********************************/
//header files
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
#include <cassert>
#include <iomanip>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <complex>
#include <numeric>
#include <functional>
#include <sstream>
#include <algorithm>
//Preprocessor directives
#define MAX 1000010
#define MOD 1000000007
#define gc getchar_unlocked
//macros input-output
#define si(n) scanf("%d",&n)
#define sll(n) scanf("%lld",&n)
#define sf(n) scanf("%f",&n)
#define ss(str) scanf("%s",str)
#define sd(n) scanf("%lf",&n)
#define INF INT_MAX
#define LINF (LL)1e18
#define maX(a,b) ((a)>(b)?(a):(b))
#define miN(a,b) ((a)<(b)?(a):(b))
#define abS(x) ((x)<0?-(x):(x))
#define forr(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) forr(i,0,n)
#define pn() printf("\n")
#define pi(n) printf("%d",n)
#define pll(n) printf("%lld",n)
#define pd(n) printf("%lf",n)
#define ps(str) printf("%s",str)
//macros stl
#define mp make_pair
#define tri(a,b,c) mp(a,mp(b,c))
#define pb push_back
#define fill(a,v) memset(a,v,sizeof a)
#define all(x) x.begin(),x.end()
#define uniq(v) sort(all(v));v.erase(unique(all(v)),v.end())
#define findval(arr,val) (lower_bound(all(arr)),val)-arr.begin()
#define clr(a) memset(a,0,sizeof a)
//debug
#define debug if(1)
#define debugoff if(0)
//constants
#define PI M_PI
#define E M_E
using namespace std;
//typedef
typedef long long LL;
typedef unsigned long long uLL;
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;
typedef pair<int,pii> tri;
//FAST io
#define input(n) read(&n)
/**
void read(int *x)
{
register int c = gc();
*x = 0;
for(;(c<48 || c>57);c = gc());
for(;c>47 && c<58;c = gc()) {*x = (*x<<1) + (*x<<3) + c - 48;}
}
**/
int a[100010],pos[100010];
int LIS(int a[],int size)
{
int table[size+1];
int len;//points to empty slot
memset(table,0,sizeof table);
table[1] = a[1];
len = 2;
for(int i=2 ; i<=size ; i++)
{
if(a[i] < table[1])//starting of new list
table[1] = a[i];
else if(a[i] > table[len-1])//clone and extend
table[len++] = a[i];
else //replace
table[upper_bound(table+1,table+len,a[i]) - table] = a[i];
}
return len - 1;
}
int main()
{
int t;
int n,num;
si(t);
while(t--)
{
si(n);
for(int i=1;i<=n;i++)
{
si(a[i]);
pos[a[i]] = i;
}
for(int i=1;i<=n;i++)
{
si(num);
a[i] = pos[num];
}
//find lis of a[]
printf("%d\n",LIS(a,n));
}
return 0;
}
| [
"aqfaridi@gmail.com"
] | aqfaridi@gmail.com |
876fa272fefdb7e04db19bba3d41c9bb8e4ae4f2 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5751500831719424_0/C++/Balajiganapathi/a.cpp | 1aec27f9786e8c9a7ffc57caa682d2072b700501 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,539 | cpp | //Coder: Balajiganapathi
#define TRACE
#define DEBUG
#include <algorithm>
#include <bitset>
#include <deque>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
typedef vector<string> vs;
// Basic macros
#define st first
#define se second
#define all(x) (x).begin(), (x).end()
#define ini(a, v) memset(a, v, sizeof(a))
#define re(i,s,n) for(int i=s;i<(n);++i)
#define rep(i,s,n) for(int i=s;i<=(n);++i)
#define fr(i,n) re(i,0,n)
#define repv(i,f,t) for(int i = f; i >= t; --i)
#define rev(i,f,t) repv(i,f - 1,t)
#define frv(i,n) rev(i,n,0)
#define pu push_back
#define mp make_pair
#define sz(x) (int)(x.size())
const int oo = 2000000009;
const double eps = 1e-9;
#ifdef TRACE
#define trace1(x) cerr << #x << ": " << x << endl;
#define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;
#define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl;
#else
#define trace1(x)
#define trace2(x, y)
#define trace3(x, y, z)
#define trace4(a, b, c, d)
#define trace5(a, b, c, d, e)
#define trace6(a, b, c, d, e, f)
#endif
const int mx = 155;
char str[mx][mx];
int idx[mx];
int n;
bool left() {
fr(i, n) if(str[i][idx[i]]) return true;
return false;
}
int solve() {
int ret = 0;
ini(idx, 0);
//trace1(left());
while(left()) {
char c = str[0][idx[0]];
//trace1(c);
vi v;
fr(i, n) {
if(str[i][idx[i]] != c) return -1;
int cnt = 0;
while(str[i][idx[i]] == c) {
++cnt;
++idx[i];
}
v.pu(cnt);
}
sort(all(v));
int target = v[n / 2];
//trace2(c, target);
//fr(i,sz(v)) trace2(i, v[i]);
fr(i, n) ret += abs(target - v[i]);
}
fr(i, n) if(str[i][idx[i]]) return -1;
return ret;
}
int main() {
//freopen("sample.txt", "r", stdin);
freopen("A-small-attempt0.in", "r", stdin);
//freopen("A-large.in", "r", stdin);
//freopen("output.txt", "w", stdout);
freopen("small0.txt", "w", stdout);
//freopen("large.txt", "w", stdout);
int kases, kase;
scanf("%d", &kases);
for(kase = 1; kase <= kases; ++kase) {
//trace2(n, kase);
scanf("%d", &n);
fr(i, n) scanf("%s",str[i]);
printf("Case #%d: ", kase);
int ans = solve();
if(ans == -1) printf("Fegla Won\n");
else printf("%d\n", ans);
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
89ac8f1712118d6f9e88abb4ab962383600486b3 | 3bc1d1c05c41ba7099edc4bf2ff90ab872892da5 | /rug_simulated_user/src/draft/race_simulated_user_JIRS_RAS.cpp | 16d91f86331c7b24b0047ed6bb7c67337fed2860 | [] | no_license | AndreiMiculita/CoR-lab | 13e506627511f13445c32ed0d4681bb131fa8f41 | d3023cf33bead2da096d53a48faff906a162066d | refs/heads/master | 2022-03-19T07:55:19.874256 | 2019-10-10T22:02:18 | 2019-10-10T22:02:18 | 208,286,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,410 | cpp | // ############################################################################
//
// Created: 1/05/2014
// Author : Hamidreza Kasaei
// Email : seyed.hamidreza@ua.pt
// Purpose: (Purely instance based learning approach)This program follows
// the teaching protocol and autonomously interact with the system
// using teach, ask and correct actions. For each newly taught category,
// the average sucess of the system should be computed. To do that,
// the simulated teacher repeatedly picks object views of the currently
// known categories from a database and presents them to the system for
// checking whether the system can recognize them. If not, the simulated
// teacher provides corrective feedback.
//
// This program is part of the RACE project, partially funded by the
// European Commission under the 7th Framework Program.
//
// See http://www.project-race.eu
//
// (Copyright) University of Aveiro - RACE Consortium
//
// ############################################################################
/* _________________________________
| |
| RUN SYSTEM BY |
|_________________________________| */
//rm -rf /tmp/pdb
//roslaunch race_simulated_user simulated_user.launch
/* _________________________________
| |
| INCLUDES |
|_________________________________| */
//system includes
#include <std_msgs/String.h>
#include <sstream>
#include <fstream>
//ros includes
#include <ros/ros.h>
#include <ros/package.h>
#include <sensor_msgs/PointCloud2.h>
#include <pluginlib/class_list_macros.h>
#include <stdio.h>
#include <race_perception_db/perception_db.h>
#include <race_perception_db/perception_db_serializer.h>
//pcl includes
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl_conversions/pcl_conversions.h>
//package includes
#include <feature_extraction/spin_image.h>
#include <race_perception_msgs/perception_msgs.h>
#include <object_conceptualizer/object_conceptualization.h>
#include <race_simulated_user/race_simulated_user_functionality.h>
#include <race_perception_utils/print.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <CGAL/Plane_3.h>
#include "std_msgs/Float64.h"
/* _________________________________
| |
| NameSpace |
|_________________________________| */
using namespace pcl;
using namespace std;
using namespace ros;
using namespace race_perception_utils;
using namespace race_perception_msgs;
typedef pcl::PointXYZRGBA PointT;
/* _________________________________
| |
| Global Parameters |
|_________________________________| */
//dataset
std::string home_address; // IEETA: "/home/hamidreza/";
// Washington: "/media/E2480872480847AD/washington/";
//spin images parameters
int spin_image_width = 8 ;
double spin_image_support_lenght = 0.2;
int subsample_spinimages = 10;
//simulated user parameters
double P_Threshold = 0.67;
int user_sees_no_improvment_const = 100;
int window_size = 3;
int number_of_categories =49 ;
double uniform_sampling_size = 0.03;
double recognition_threshold = 2;
std::string name_of_approach;
/* _________________________________
| |
| Global Variable |
|_________________________________| */
PerceptionDB* _pdb;
typedef pcl::PointXYZRGBA PointT;
unsigned int cat_id = 1;
unsigned int track_id =1;
unsigned int view_id = 1;
string InstancePathTmp= "";
std::string PCDFileAddressTmp;
std::string True_Category_Global;
std::string Object_name_orginal;
std::string evaluationFile, evaluationTable, precision_file, local_F1_vs_learned_category, F1_vs_learned_category;
std::ofstream Result , Result_table , PrecisionMonitor, local_F1_vs_category, F1_vs_category, NumberofFeedback , category_random, instances_random, category_introduced;
int TP =0, FP=0, FN=0, TPtmp =0, FPtmp=0, FNtmp=0, Obj_Num=0, number_of_instances=0;//track_id_gloabal = 1 ;//, track_id_gloabal2=1;
float PrecisionSystem =0;
float F1System =0;
vector <int> recognition_results; // we coded 0: continue(correctly detect unkown object)
// 1: TP , 2: FP
//3: FN , 4: FP and FN
void evaluationfunction(const race_perception_msgs::RRTOV &result)
{
PrettyPrint pp;
string tmp = result.ground_truth_name.substr(home_address.size(),result.ground_truth_name.size());
string True_cat = extractCategoryName(tmp);
InstancePathTmp=tmp;
std:: string Object_name;
Object_name = extractObjectName (result.ground_truth_name);
// Object_name = extractObjectName (Object_name_orginal);
pp.info(std::ostringstream().flush() << "extractObjectName: "<< Object_name.c_str());
Obj_Num++;
pp.info(std::ostringstream().flush() << "track_id="<<result.track_id << "\tview_id=" << result.view_id);
pp.info(std::ostringstream().flush() << "normalizedObjectCategoriesDistance{");
for (size_t i = 0; i < result.result.size(); i++)
{
pp.info(std::ostringstream().flush() << "-"<< result.result.at(i).normalized_distance);
}
pp.info(std::ostringstream().flush() << "}\n");
if ( result.result.size() <= 0)
{
pp.warn(std::ostringstream().flush() << "Warning: Size of NormalObjectToCategoriesDistances is 0");
}
float minimumDistance = result.minimum_distance;
string Predict_cat;
Predict_cat= result.recognition_result.c_str();
pp.info(std::ostringstream().flush() << "[-]Object_name: "<< Object_name.c_str());
pp.info(std::ostringstream().flush() << "[-]True_cat: "<<True_cat.c_str());
pp.info(std::ostringstream().flush() << "[-]Predict_cat: " << Predict_cat.c_str());
char Unknown[] = "Unknown";
Result.open( evaluationFile.c_str(), std::ofstream::app);
Result.precision(4);
if ((strcmp(True_cat.c_str(),Unknown)==0) && (strcmp(Predict_cat.c_str(),Unknown)==0))
{
recognition_results.push_back(0);// continue
Result << "\n"<<Obj_Num<<"\t"<<Object_name <<"\t\t"<< True_cat <<"\t\t"<< Predict_cat <<"\t\t"<< "0\t0\t0"<< "\t\t"<< minimumDistance;
Result << "\n-----------------------------------------------------------------------------------------------------------------------------------";
}
else if ((strcmp(True_cat.c_str(),Predict_cat.c_str())==0))
{
TP++;
TPtmp++;
recognition_results.push_back(1);
Result << "\n"<<Obj_Num<<"\t"<<Object_name <<"\t\t"<< True_cat <<"\t\t"<< Predict_cat <<"\t\t"<< "1\t0\t0" << "\t\t"<< minimumDistance;
Result << "\n-----------------------------------------------------------------------------------------------------------------------------------";
}
else if ((strcmp(True_cat.c_str(),Unknown)==0) && (strcmp(Predict_cat.c_str(),Unknown)!=0))
{
FP++;
FPtmp++;
recognition_results.push_back(2);
Result << "\n"<<Obj_Num<<"\t"<<Object_name <<"\t\t"<< True_cat <<"\t\t"<< Predict_cat <<"\t\t"<< "0\t1\t0"<< "\t\t"<< minimumDistance;
Result << "\n-----------------------------------------------------------------------------------------------------------------------------------";
}
else if ((strcmp(True_cat.c_str(),Unknown)!=0) && (strcmp(Predict_cat.c_str(),Unknown)==0))
{
FN++;
FNtmp++;
recognition_results.push_back(3);
Result << "\n"<<Obj_Num<<"\t"<<Object_name <<"\t\t"<< True_cat <<"\t\t"<< Predict_cat <<"\t\t"<< "0\t0\t1"<< "\t\t"<< minimumDistance;
Result << "\n-----------------------------------------------------------------------------------------------------------------------------------";
Result << "\n\n\t.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.";
Result << "\n\t - Correct classifier - Category Updated";
Result << "\n\t .<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.\n\n";
number_of_instances ++;
// IntroduceNewInstance (InstancePathTmp,
// cat_id, track_id,
// view_id,
// spin_image_width,
// spin_image_support_lenght,
// subsample_spinimages
// );
IntroduceNewInstance2 (home_address,
InstancePathTmp,
cat_id, track_id, view_id,
spin_image_width,
spin_image_support_lenght,
uniform_sampling_size);
track_id++;
pp.info(std::ostringstream().flush() << "[-]Category Updated");
}
else if ((strcmp(True_cat.c_str(),Predict_cat.c_str())!=0))
{
FP++; FN++;
FPtmp++; FNtmp++;
recognition_results.push_back(4);
Result << "\n"<<Obj_Num<<"\t"<<Object_name <<"\t\t"<< True_cat <<"\t\t"<< Predict_cat <<"\t\t"<< "0\t1\t1"<< "\t\t"<< minimumDistance;
Result << "\n-----------------------------------------------------------------------------------------------------------------------------------";
Result << "\n\n\t.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.";
Result << "\n\t - Correct classifier - Category Updated";
Result << "\n\t .<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.<>.\n\n";
number_of_instances++;
// IntroduceNewInstance (InstancePathTmp,
// cat_id, track_id,
// view_id,
// spin_image_width,
// spin_image_support_lenght,
// subsample_spinimages
// );
IntroduceNewInstance2 (home_address,
InstancePathTmp,
cat_id, track_id, view_id,
spin_image_width,
spin_image_support_lenght,
uniform_sampling_size);
track_id++;
pp.info(std::ostringstream().flush() << "[-]Category Updated");
}
Result.close();
Result.clear();
pp.printCallback();
}
int monitorComputationTimeForSpecificPackage (string pakage_name, unsigned int TID, bool init, float duration)
{
char TIDC [10];
sprintf( TIDC, "%d",TID );
std::string processing_time_path = ros::package::getPath(pakage_name)+ "/result/TID"+ TIDC +"processing_time_evaluation.txt";
std::ofstream processing_time;
if (init)
{
processing_time.open (processing_time_path.c_str(), std::ofstream::out);
processing_time.precision(8);
processing_time << "TID" << TID <<" has been initialized at "<< ros::Time::now() <<"\n";
processing_time.close();
}
else
{
processing_time.open (processing_time_path.c_str(), std::ofstream::app);
processing_time.precision(8);
processing_time << duration <<"\n";
processing_time.close();
}
return 0;
}
int main(int argc, char** argv)
{
int RunCount=1;
// while(RunCount <= number_of_categories)
// {
/* __________________________________
| |
| Creating a folder for each RUN |
|_________________________________| */
//int to string converting
char run_count [10];
sprintf( run_count, "%d",RunCount );
//Creating a folder for each RUN.
string systemStringCommand= "mkdir "+ ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count ;
system( systemStringCommand.c_str());
/* _________________________________
| |
| Randomly sort categories |
|_________________________________| */
generateRrandomSequencesCategories(RunCount);
ros::init (argc, argv, "EVALUATION");
ros::NodeHandle nh;
// initialize perception database
_pdb = race_perception_db::PerceptionDB::getPerceptionDB(&nh); //initialize the database class_list_macros
string name = nh.getNamespace();
/* ________________________________________
| |
| read prameters from launch file |
|_______________________________________| */
// read database parameter
nh.param<std::string>("/perception/home_address", home_address, "default_param");
nh.param<int>("/perception/number_of_categories", number_of_categories, number_of_categories);
nh.param<std::string>("/perception/name_of_approach", name_of_approach, "default_param");
//read spin images parameters
nh.param<int>("/perception/spin_image_width", spin_image_width, spin_image_width);
nh.param<double>("/perception/spin_image_support_lenght", spin_image_support_lenght, spin_image_support_lenght);
nh.param<int>("/perception/subsample_spinimages", subsample_spinimages, subsample_spinimages);
nh.param<double>("/perception/uniform_sampling_size", uniform_sampling_size, uniform_sampling_size);
//read simulated teacher parameters
nh.param<double>("/perception/P_Threshold", P_Threshold, P_Threshold);
nh.param<int>("/perception/user_sees_no_improvment_const", user_sees_no_improvment_const, user_sees_no_improvment_const);
nh.param<int>("/perception/window_size", window_size, window_size);
//recognition threshold
nh.param<double>("/perception/recognition_threshold", recognition_threshold, recognition_threshold);
string category_introduced_txt = ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count + "/Category_Introduced.txt";
category_introduced.open (category_introduced_txt.c_str(), std::ofstream::out);
//TODO : create a function
string dataset= (home_address == "/home/hamidreza/") ? "IEETA" : "RGB-D Washington";
evaluationFile = ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count + "/Detail_Evaluation.txt";
Result.open (evaluationFile.c_str(), std::ofstream::out);
Result << "system configuration:"
<< "\n\t-experiment_name = " << name_of_approach.c_str()
<< "\n\t-name_of_dataset = " << dataset
<< "\n\t-spin_image_width = "<< spin_image_width
<< "\n\t-spin_image_support_lenght = "<< spin_image_support_lenght
<< "\n\t-uniform_sampling_size = "<< uniform_sampling_size
<< "\n\t-recognition_threshold = "<< recognition_threshold
<< "\n------------------------------------------------------------------------------------------------------------------------------------\n\n";
Result << "\nNum"<<"\tObject_name" <<"\t\t\t"<< "True_Category" <<"\t\t"<< "Predict_Category"<< "\t"<< "TP" << "\t"<< "FP"<< "\t"<< "FN \t\tDistance";
Result << "\n------------------------------------------------------------------------------------------------------------------------------------";
Result.close();
Result.clear();
precision_file = ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count +"/PrecisionMonitor.txt";
PrecisionMonitor.open (precision_file.c_str(), std::ofstream::trunc);
PrecisionMonitor.precision(4);
PrecisionMonitor.close();
local_F1_vs_learned_category = ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count +"/local_F1_vs_learned_category.txt";
local_F1_vs_category.open (local_F1_vs_learned_category.c_str(), std::ofstream::trunc);
local_F1_vs_category.precision(4);
local_F1_vs_category.close();
F1_vs_learned_category = ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count +"/F1_vs_learned_category.txt";
F1_vs_category.open (F1_vs_learned_category.c_str(), std::ofstream::trunc);
F1_vs_category.precision(4);
F1_vs_category.close();
/* ____________________________________________________
| |
| create a subscriber to get recognition feedback |
|___________________________________________________| */
unsigned found = name.find_last_of("/\\");
std::string topic_name = name.substr(0,found) + "/tracking/recognition_result";
ros::Subscriber sub = nh.subscribe(topic_name, 10, evaluationfunction);
/* ______________________________
| |
| create a publisher |
|________________________________| */
//
// std::string pcin_topic = name.substr(0,found) + "/pipeline_default/tracker/tracked_object_point_cloud";
// ros::Publisher pub = nh.advertise< race_perception_msgs::PCTOV> (pcin_topic, 1000);
std::string topic = name.substr(0,found) + "/pipeline_default/feature_extraction/spin_images_tracked_object_view";
ros::Publisher pub_spin_image = nh.advertise<race_perception_msgs::CompleteRTOV> (topic, 100);
/* ______________________________
| |
| wait for 0.5 second |
|________________________________| */
ros::Time start_time = ros::Time::now();
while (ros::ok() && (ros::Time::now() - start_time).toSec() <1)
{ //wait
}
/* _________________________________
| |
| Initialization |
|________________________________| */
string categoryName="";
string InstancePath= "";
int class_index = 1; // class index
unsigned int instance_number = 1;
cat_id = 1;// it is a constant to create key for categories <Cat_Name><Cat_ID>
track_id = 1;
view_id = 1; // it is a constant to create key for categories <TID><VID> (since the database samples were
// collected manually, each track_id has exactly one view)
vector <unsigned int> instance_number2;
for (int i = 0; i < number_of_categories ; i++)
{
instance_number2.push_back(1);
}
int number_of_taught_categories = 0;
//start tic
ros::Time beginProc = ros::Time::now();
/* ______________________________
| |
| Introduce category |
|________________________________| */
// /*
// introduceNewCategory( class_index,track_id,instance_number2.at(class_index-1),evaluationFile,
// spin_image_width,
// spin_image_support_lenght,
// subsample_spinimages);
// */
introduceNewCategory2( home_address,
class_index,track_id,instance_number2.at(class_index-1),evaluationFile,
spin_image_width,
spin_image_support_lenght,
uniform_sampling_size);
number_of_instances+=3;
number_of_taught_categories ++;
category_introduced<< "1\n";
/* ______________________________
| |
| Simulated Teacher |
|________________________________| */
categoryName = "";
float Precision = 0;
float Recall = 0;
float F1 =0;
vector <float> average_class_precision;
while ( class_index < number_of_categories) // one category already taught above
{
class_index ++; // class index
InstancePath= "";
// if (introduceNewCategory( class_index,track_id,instance_number2.at(class_index-1),evaluationFile,
// spin_image_width,
// spin_image_support_lenght,
// subsample_spinimages) == -1)
if (introduceNewCategory2( home_address,
class_index,track_id,instance_number2.at(class_index-1),evaluationFile,
spin_image_width,
spin_image_support_lenght,
uniform_sampling_size) == -1)
{
ROS_INFO ("Note: the experiment is terminated because there is not enough test data to continue the evaluation");
ros::Duration duration = ros::Time::now() - beginProc;
report_current_results(TP,FP,FN,evaluationFile,true);
report_experiment_result ( average_class_precision,
number_of_instances,
number_of_taught_categories,
evaluationFile, duration);
report_all_experiments_results (TP, FP, FN, Obj_Num,
average_class_precision,
number_of_instances,
number_of_taught_categories,
name_of_approach );
category_introduced.close();
monitor_F1_vs_learned_category (F1_vs_learned_category, TP, FP, FN );
Visualize_simulated_teacher_in_MATLAB(RunCount, P_Threshold, precision_file);
Visualize_Local_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, P_Threshold, local_F1_vs_learned_category.c_str());
Visualize_Global_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, F1_vs_learned_category.c_str());
Visualize_Number_of_learned_categories_vs_Iterations (RunCount, category_introduced_txt.c_str());
systemStringCommand= "cp "+home_address+"/Category/Category.txt " + ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count ;
system( systemStringCommand.c_str());
return (0) ;
}
number_of_instances+=3;
number_of_taught_categories ++;
category_introduced<< "1\n";
categoryName = "";
TPtmp = 0; FPtmp = 0; FNtmp = 0;
int k = 0; // number of classification results
float Precision_tmp = 0;
Precision = 0;
F1=0;
Recall=0;
unsigned int c =1;// class index
int iterations =1;
int iterations_user_sees_no_improvment =0;
bool User_sees_no_improvement_in_precision = false; // In the current implementation, If the simulated teacher
// sees the precision doesn't improve in 100 iteration, then,
// it terminares evaluation of the system, originally,
// it was an empirical decision of the human instructor
// while ( ((Precision < P_Threshold ) or (k < number_of_taught_categories)) and (!User_sees_no_improvement_in_precision) )
while ( ((F1 < P_Threshold ) or (k < number_of_taught_categories)) and (!User_sees_no_improvement_in_precision) )
{
category_introduced<< "0\n";
ROS_INFO("\t\t[-] Iteration:%i",iterations);
ROS_INFO("\t\t[-] c:%i",c);
ROS_INFO("\t\t[-] Instance number:%i",instance_number2.at(c-1));
//info for debug
ROS_INFO("\t\t[-] Home address parameter : %s", home_address.c_str());
ROS_INFO("\t\t[-] number_of_categories : %i", number_of_categories);
ROS_INFO("\t\t[-] spin_image_width : %i", spin_image_width);
ROS_INFO("\t\t[-] spin_image_support_lenght : %lf", spin_image_support_lenght);
ROS_INFO("\t\t[-] subsample_spinimages : %i", subsample_spinimages);
ROS_INFO("\t\t[-] P_Threshold : %lf", P_Threshold);
ROS_INFO("\t\t[-] user_sees_no_improvment_const : %i", user_sees_no_improvment_const);
ROS_INFO("\t\t[-] window_size : %i", window_size);
//test keypoint selection
// char ch='1';
// while (ch !='0')
// {
// select an instance from an specific category
InstancePath= "";
selectAnInstancefromSpecificCategory(c, instance_number2.at(c-1), InstancePath);
ROS_INFO("\t\t[-]-Test Instance: %s", InstancePath.c_str());
// check the selected instance exist or not? if yes, send it to the race_feature_extractor
if (InstancePath.size() < 2)
{
ROS_INFO("\t\t[-]-The %s file does not exist", InstancePath.c_str());
category_introduced.close();
ROS_INFO("\t\t[-]- number of taught categories= %i", number_of_taught_categories);
ROS_INFO ("Note: the experiment is terminated because there is not enough test data to continue the evaluation");
ros::Duration duration = ros::Time::now() - beginProc;
report_experiment_result (average_class_precision,
number_of_instances,
number_of_taught_categories,
evaluationFile, duration);
report_current_results(TP,FP,FN,evaluationFile,true);
report_all_experiments_results (TP, FP, FN, Obj_Num,
average_class_precision,
number_of_instances,
number_of_taught_categories,
name_of_approach );
monitor_F1_vs_learned_category (F1_vs_learned_category, TP, FP, FN );
Visualize_simulated_teacher_in_MATLAB(RunCount, P_Threshold, precision_file);
Visualize_Local_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, P_Threshold, local_F1_vs_learned_category.c_str());
Visualize_Global_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, F1_vs_learned_category.c_str());
Visualize_Number_of_learned_categories_vs_Iterations (RunCount, category_introduced_txt.c_str());
systemStringCommand= "cp "+home_address+"/Category/Category.txt " + ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count ;
system( systemStringCommand.c_str());
return (0) ;
}
else
{
std::string ground_truth_category_name =extractCategoryName(InstancePath);
InstancePath = home_address +"/"+ InstancePath.c_str();
//load an instance from file
boost::shared_ptr<PointCloud<PointT> > PCDFile (new PointCloud<PointT>);
if (io::loadPCDFile <PointXYZRGBA> (InstancePath.c_str(), *PCDFile) == -1)
{
ROS_ERROR("\t\t[-]-Could not read given object %s :",InstancePath.c_str());
return(0);
}
ROS_INFO("\t\t[-]- track_id: %i , \tview_id: %i ",track_id, view_id );
// boost::shared_ptr<PointCloud<PointT> > cloud_filtered (new PointCloud<PointT>);
// pcl::VoxelGrid<PointT > voxelized_point_cloud;
// voxelized_point_cloud.setInputCloud (PCDFile);
// voxelized_point_cloud.setLeafSize (0.005, 0.005, 0.005);
// voxelized_point_cloud.filter (*cloud_filtered);
//
//Declare PCTOV msg
// boost::shared_ptr<race_perception_msgs::PCTOV> msg (new race_perception_msgs::PCTOV );
// pcl::toROSMsg(*PCDFile, msg->point_cloud);
// msg->track_id = track_id;//it is
// msg->view_id = view_id;
// msg->ground_truth_name = InstancePath;//extractCategoryName(InstancePath);
// pub.publish (msg);
// ROS_INFO("\t\t[-]- Emulating race_object_tracking pakage by publish a point cloud: %s", InstancePath.c_str());
//
//Declare a boost share ptr to the spin image msg
boost::shared_ptr< vector <SITOV> > msg_out;
msg_out = (boost::shared_ptr< vector <SITOV> >) new (vector <SITOV>);
boost::shared_ptr<PointCloud<PointT> > uniform_keypoints (new PointCloud<PointT>);
boost::shared_ptr<pcl::PointCloud<int> >uniform_sampling_indices (new PointCloud<int>);
keypoint_selection( PCDFile,
uniform_sampling_size,
uniform_keypoints,
uniform_sampling_indices);
if (!estimateSpinImages2(PCDFile,
0.01 /*downsampling_voxel_size*/,
0.05 /*normal_estimation_radius*/,
spin_image_width /*spin_image_width*/,
0.0 /*spin_image_cos_angle*/,
1 /*spin_image_minimum_neighbor_density*/,
spin_image_support_lenght/*spin_image_support_lenght*/,
msg_out,
uniform_sampling_indices
))
{
ROS_INFO( "Could not compute spin images");
return 1;
}
//Declare SITOV (Spin Images of Tracked Object View)
SITOV _sitov;
//declare the RTOV complete variable
race_perception_msgs::CompleteRTOV _crtov;
_crtov.track_id = track_id;
_crtov.view_id = view_id;
_crtov.ground_truth_name = InstancePath.c_str();
//Add the Spin Images in msg_out to sitovs to put in the DB
for (size_t i = 0; i < msg_out->size(); i++)
{
_sitov = msg_out->at(i); //copy spin images
_sitov.track_id = track_id; //copy track_id
_sitov.view_id = view_id; //copy view_id
_sitov.spin_img_id = i; //copy spin image id
//Addd sitov to completertov sitov list
_crtov.sitov.push_back(_sitov);
}
//Publish the CompleteRTOV to recognition
pub_spin_image.publish (_crtov);
/* _______________________________
| |
| wait for 0.5 second |
|________________________________| */
start_time = ros::Time::now();
while (ros::ok() && (ros::Time::now() - start_time).toSec() < 0.5)
{ //wait
}
ros::spinOnce();
//
if (c >= number_of_taught_categories)
{
c = 1;
}
else
{
c++;
}
// boost::shared_ptr<race_perception_msgs::PCTOV> msg (new race_perception_msgs::PCTOV );
// pcl::toROSMsg(*PCDFile, msg->point_cloud);
// msg->track_id = track_id;//it is
// msg->view_id = view_id;
// msg->ground_truth_name = InstancePath;//extractCategoryName(InstancePath);
// pub.publish (msg);
// ROS_INFO("\t\t[-]- Emulating race_object_tracking pakage by publish a point cloud: %s", InstancePath.c_str());
// cin >>ch;
// }/////////////////while test
// if (iterations != TPtmp+FNtmp)
// {
// pub.publish (msg);
// start_time = ros::Time::now();
// while (ros::ok() && (ros::Time::now() - start_time).toSec() < 1)
// { //wait
// }
// ros::spinOnce();
// ROS_INFO("\t\t[-]- *iterationst= %i", iterations);
// ROS_INFO("\t\t[-]- *TPtmp+FPtmp= %i", TPtmp+FPtmp);
// }
if ( (iterations >= number_of_taught_categories) and (iterations <= window_size * number_of_taught_categories))
{
if ((TPtmp+FPtmp)!=0)
{
Precision = TPtmp/double (TPtmp+FPtmp);
}
else
{
Precision = 0;
}
if ((TPtmp+FNtmp)!=0)
{
Recall = TPtmp/double (TPtmp+FNtmp);
}
else
{
Recall = 0;
}
if ((Precision + Recall)!=0)
{
F1 = 2 * (Precision * Recall )/(Precision + Recall );
}
else
{
F1 = 0;
}
// monitor_precision (precision_file, Precision);
monitor_precision (precision_file, F1);
// if (Precision > P_Threshold)
if (F1 > P_Threshold)
{
// average_class_precision.push_back(Precision);
average_class_precision.push_back(F1);
User_sees_no_improvement_in_precision = false;
ROS_INFO("\t\t[-]- Precision= %f", Precision);
ROS_INFO("\t\t[-]- F1 = %f", F1);
// double Recall = TPtmp/double (TPtmp+FNtmp);
report_current_results(TPtmp,FPtmp,FNtmp,evaluationFile,false);
iterations = 1;
monitor_precision (local_F1_vs_learned_category, F1);
ros::spinOnce();
}
}//if
else if ( (iterations > window_size * number_of_taught_categories)) // In this condition, if we are at iteration I>3n, we only
// compute precision as the average of last 3n, and discart the first
// I-3n iterations.
{
//compute precision of last 3n, and discart the first I-3n iterations
// Precision = compute_precision_of_last_3n (recognition_results, number_of_taught_categories);
F1 = compute_Fmeasure_of_last_3n (recognition_results, number_of_taught_categories);
// ROS_INFO("\t\t[-]- Precision= %f", Precision);
// monitor_precision (precision_file, Precision);
monitor_precision (precision_file, F1);
// report_precision_of_last_3n (evaluationFile, Precision);
report_F1_of_last_3n (evaluationFile, F1);
// Result << "\n\t\t - precision = "<< Precision;
Result << "\n\t\t - F1 = "<< F1;
// if (Precision > P_Threshold)
if (F1 > P_Threshold)
{
// average_class_precision.push_back(Precision);
average_class_precision.push_back(F1);
User_sees_no_improvement_in_precision = false;
report_current_results(TPtmp,FPtmp,FNtmp,evaluationFile,false);
monitor_precision (local_F1_vs_learned_category, F1);
iterations = 1;
iterations_user_sees_no_improvment=0;
ros::spinOnce();
}
else
{
iterations_user_sees_no_improvment++;
ROS_INFO("\t\t[-]- %i user_sees_no_improvement_in_F1", iterations_user_sees_no_improvment);
if (iterations_user_sees_no_improvment > user_sees_no_improvment_const)
{
// average_class_precision.push_back(Precision);
average_class_precision.push_back(F1);
User_sees_no_improvement_in_precision = true;
ROS_INFO("\t\t[-]- User_sees_no_improvement_in_precision");
ROS_INFO("\t\t[-]- Finish");
ROS_INFO("\t\t[-]- Number of taught categories= %i", number_of_taught_categories);
Result.open (evaluationFile.c_str(), std::ofstream::app);
Result << "\n After " << user_sees_no_improvment_const <<" iterations, user sees no improvement in precision";
Result.close();
monitor_precision (local_F1_vs_learned_category, F1);
monitor_F1_vs_learned_category (F1_vs_learned_category, TP, FP, FN );
ros::Duration duration = ros::Time::now() - beginProc;
report_experiment_result (average_class_precision,
number_of_instances,
number_of_taught_categories,
evaluationFile, duration);
category_introduced.close();
report_current_results(TP,FP,FN,evaluationFile,true);
report_all_experiments_results (TP, FP, FN, Obj_Num,
average_class_precision,
number_of_instances,
number_of_taught_categories,
name_of_approach);
Visualize_simulated_teacher_in_MATLAB(RunCount, P_Threshold, precision_file);
Visualize_Local_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, P_Threshold, local_F1_vs_learned_category.c_str());
Visualize_Global_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, F1_vs_learned_category.c_str());
Visualize_Number_of_learned_categories_vs_Iterations (RunCount, category_introduced_txt.c_str());
systemStringCommand= "cp "+home_address+"/Category/Category.txt " + ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count ;
ROS_INFO("\t\t[-]- %s", systemStringCommand.c_str());
system( systemStringCommand.c_str());
return 0 ;
}
}
}
else
{
// if ((TPtmp+FPtmp)!= 0)
// PrecisionSystem = TPtmp/double (TPtmp+FPtmp);
// else
// PrecisionSystem=0;
if ((TPtmp+FPtmp)!=0)
{
Precision = TPtmp/double (TPtmp+FPtmp);
}
else
{
Precision = 0;
}
if ((TPtmp+FNtmp)!=0)
{
Recall = TPtmp/double (TPtmp+FNtmp);
}
else
{
Recall = 0;
}
if ((Precision + Recall)!=0)
{
F1System = 2 * (Precision * Recall )/(Precision + Recall );
}
else
{
F1System = 0;
}
monitor_precision (precision_file, F1System);
}
k++; // k<-k+1 : number of classification result
iterations ++;
}//else
}
// ROS_INFO("\t\t[-]- number of Iterations = %ld", iterations);
monitor_F1_vs_learned_category (F1_vs_learned_category, TP, FP, FN );
}
ROS_INFO("\t\t[-]- Finish");
ROS_INFO("\t\t[-]- Number of taught categories= %i", number_of_taught_categories);
//get toc
ros::Duration duration = ros::Time::now() - beginProc;
monitor_precision (local_F1_vs_learned_category, F1);
monitor_F1_vs_learned_category (F1_vs_learned_category, TP, FP, FN );
report_current_results(TP,FP,FN,evaluationFile,true);
report_experiment_result (average_class_precision,
number_of_instances,
number_of_taught_categories,
evaluationFile, duration);
category_introduced.close();
report_all_experiments_results (TP, FP, FN, Obj_Num,
average_class_precision,
number_of_instances,
number_of_taught_categories,
name_of_approach);
Visualize_simulated_teacher_in_MATLAB(RunCount, P_Threshold, precision_file);
Visualize_Local_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, P_Threshold, local_F1_vs_learned_category.c_str());
Visualize_Global_F1_vs_Number_of_learned_categories_in_MATLAB (RunCount, F1_vs_learned_category.c_str());
Visualize_Number_of_learned_categories_vs_Iterations (RunCount, category_introduced_txt.c_str());
systemStringCommand= "cp "+home_address+"/Category/Category.txt " + ros::package::getPath("race_simulated_user")+ "/result/RUN"+ run_count ;
ROS_INFO("\t\t[-]- %s", systemStringCommand.c_str());
system( systemStringCommand.c_str());
RunCount++;
// }//while(RunCount)
return 0 ;
}
| [
"andreimiculita@gmail.com"
] | andreimiculita@gmail.com |
6bf1691634695c14dd6f9de8cdaa41deeef3317f | 7f0bebd8bcdbce110f4cc6d477299366e6efe2ee | /ALGOCODING/Graph/BOJ11724_dfs.cpp | 8e039aa506d911e6f83fc3c43419e79d7a8a957d | [] | no_license | algocoding/cppsrc | 8ce1dc98a83e772524a57e800eaa2ea3c3104793 | 60e197dd295498a52d5ec214394c73117ec3b0e4 | refs/heads/master | 2021-01-21T14:53:14.575419 | 2017-08-17T04:44:25 | 2017-08-17T04:44:25 | 95,349,501 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 727 | cpp | /*
* BOJ11724_dfs.cpp
*
* 연결 요소의 개수 https://www.acmicpc.net/problem/11724
* Created on: 2017. 8. 16.
* Author: JongYun
*/
#include <cstdio>
using namespace std;
const int MAXN = 1000;
int G[MAXN + 1][MAXN + 1];
int top[MAXN + 1];
int cid[MAXN + 1];
int N, M, id;
void DFS(int v)
{
cid[v] = id;
for(int i = 0; i < top[v]; i++)
{
if(cid[G[v][i]] == 0)
DFS(G[v][i]);
}
}
int main()
{
scanf("%d%d", &N, &M);
for(int i = 0; i < M; i++)
{
int u, v;
scanf("%d%d", &u, &v);
G[u][top[u]++] = v;
G[v][top[v]++] = u;
}
id = 0;
for(int i = 1; i <= N; i++)
{
if(cid[i] == 0)
{
++id; DFS(i);
}
}
printf("%d\n", id);
return 0;
}
| [
"jongyun.jung@gmail.com"
] | jongyun.jung@gmail.com |
1dafcae36497bc355d87aa73d824828cd73a43c2 | 136f973c53f4222addbe96e1b991b5eb538ad4ff | /cs12_labs/lab02/main.cpp | 1b0c2469128b0209074373358f134e1767101595 | [] | no_license | ksand012/UCR-Files | 0fb08348524cca4a0f700d4f6ded16d282f3b320 | 9e30b4d51b0bfcfc678ea74001b18698281f931f | refs/heads/master | 2022-06-19T08:07:13.687772 | 2020-05-06T02:45:14 | 2020-05-06T02:45:14 | 119,735,175 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,699 | cpp | #include <iostream>
using namespace std;
class Rational
{
private:
int numerator;
int denominator;
public:
Rational();
explicit Rational(int);
Rational(int, int);
const Rational add(const Rational &) const;
const Rational subtract(const Rational &) const;
const Rational multiply(const Rational &) const;
const Rational divide(const Rational &) const;
void display() const;
};
Rational::Rational(int num, int denom)
{
numerator = num;
denominator = denom;
}
Rational::Rational(int num)
{
numerator = num;
denominator = 1;
}
Rational::Rational()
{
numerator = 0;
denominator = 1;
}
const Rational Rational::add(const Rational& r2) const
{
Rational temp;
temp.numerator = ((this->numerator*r2.denominator) + (this->denominator*r2.numerator));
temp.denominator = (this->denominator*r2.denominator);
return temp;
}
const Rational Rational::subtract(const Rational& r2) const
{
Rational temp;
temp.numerator = ((this->numerator*r2.denominator) - (this->denominator*r2.numerator));
temp.denominator = (this->denominator*r2.denominator);
return temp;
}
const Rational Rational::multiply(const Rational& r2) const
{
Rational temp;
temp.numerator = (this->numerator*r2.numerator);
temp.denominator = (this->denominator*r2.denominator);
return temp;
}
const Rational Rational::divide(const Rational& r2) const
{
Rational temp;
temp.numerator = (this->numerator*r2.denominator);
temp.denominator = (this->denominator*r2.numerator);
return temp;
}
void Rational::display() const
{
cout << numerator << " / " << denominator;
}
Rational getRational();
void displayResult(const string &, const Rational &, const Rational&, const Rational&);
int main() {
Rational A, B, result;
int choice;
cout << "Enter Rational A:" << endl;
A = getRational();
cout << endl;
cout << "Enter Rational B:" << endl;
B = getRational();
cout << endl;
cout << "Enter Operation (1 - 4):" << endl
<< "1 - Addition (A + B)" << endl
<< "2 - Subtraction (A - B)" << endl
<< "3 - Multiplication (A * B)" << endl
<< "4 - Division (A / B)" << endl;
cin >> choice;
cout << endl;
if (choice == 1) {
result = A.add(B);
displayResult("+", A, B, result);
} else if (choice == 2) {
result = A.subtract(B);
displayResult("-", A, B, result);
} else if (choice == 3) {
result = A.multiply(B);
displayResult("*", A, B, result);
} else if (choice == 4) {
result = A.divide(B);
displayResult("/", A, B, result);
} else {
cout << "Unknown Operation";
}
cout << endl;
return 0;
}
Rational getRational() {
int choice;
int numer, denom;
cout << "Which Rational constructor? (Enter 1, 2, or 3)" << endl
<< "1 - 2 parameters (numerator & denominator)" << endl
<< "2 - 1 parameter (numerator)" << endl
<< "3 - 0 parameters (default)" << endl;
cin >> choice;
cout << endl;
if (choice == 1) {
cout << "numerator? ";
cin >> numer;
cout << endl;
cout << "denominator? ";
cin >> denom;
cout << endl;
return Rational(numer, denom);
} else if (choice == 2) {
cout << "numerator? ";
cin >> numer;
cout << endl;
return Rational(numer);
} else {
return Rational();
}
}
void displayResult(const string &op, const Rational &lhs, const Rational&rhs, const Rational &result) {
cout << "(";
lhs.display();
cout << ") " << op << " (";
rhs.display();
cout << ") = (";
result.display();
cout << ")";
} | [
"ksand012@ucr.edu"
] | ksand012@ucr.edu |
0e16535fa98ed03504160d750cf9fc69237c7df5 | 67c174947d2bb6c8e01cf2093a16cf03a9925744 | /NetMePiet/src/message_selected.cpp | 223a2f6d110987c6282ed578f93861455bfbaea0 | [
"MIT"
] | permissive | Assertores/NetMePiet | 44389596556b4395db26f6b4ebc0e46d5bb2abe2 | b2054d9c41f214f6c4a285c4798fd281d5c2d12d | refs/heads/master | 2021-02-07T06:55:26.889453 | 2020-06-09T16:57:03 | 2020-06-09T16:57:03 | 243,994,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cpp | #include "network/messages/message_selected.hpp"
//===== ===== EXTERN ===== =====
#include <iostream>
//===== ===== INTERN ===== =====
namespace NMP::Network::Messages {
size_t Selected::DataSerialize(uint8_t buffer[], const size_t maxSize) const {
if(buffer == nullptr) {
return 0;
}
size_t payloadSize = sizeof(uint32_t) * 3;
if(maxSize < payloadSize) {
return 0;
}
*((uint32_t*)buffer) = _clientID;
buffer += sizeof(uint32_t);
*((uint32_t*)buffer) = _x;
buffer += sizeof(uint32_t);
*((uint32_t*)buffer) = _y;
buffer += sizeof(uint32_t);
return payloadSize;
}
void Selected::DataDeserialize(const uint8_t msg[], const size_t length) {
if(msg == nullptr) {
return;
}
_clientID = *((uint32_t*)msg);
msg += sizeof(uint32_t);
_x = *((uint32_t*)msg);
msg += sizeof(uint32_t);
_y = *((uint32_t*)msg);
msg += sizeof(uint32_t);
}
std::string Selected::ToString(void) {
std::stringstream ss;
ss << "Selected | " << _clientID << ": (" << _x << " | " << _y << ")";
return ss.str();
}
}
| [
"andreas.edmeier@web.de"
] | andreas.edmeier@web.de |
cb4281c5d3f7efa40d9798983cfe4e59d93d18cc | ddb8a1e348f3fac2c1887f20e1ca515c7380f043 | /projects/testdata/src/Graphics/TextureCubeMapData.cpp | 1702b99ad6b9e8ce3f9e5d88b121c8b4b580c88f | [] | no_license | FardeenF/OTTER | d232f3c536e5cf0b36d80d140de61cb0109e82ea | 8c5f3b7a7e5e625e23b326861ec0a38d646f2a0b | refs/heads/master | 2023-04-09T18:14:07.833139 | 2021-04-13T03:11:50 | 2021-04-13T03:11:50 | 296,718,341 | 0 | 0 | null | 2020-09-18T20:01:36 | 2020-09-18T20:01:36 | null | UTF-8 | C++ | false | false | 2,984 | cpp | ilename="../../Dialogs/ResumeRecoverySettings.ui" line="197"/>
<source>Resume Recovery</source>
<translation>Reanudar recuperación</translation>
</message>
<message>
<location filename="../../Dialogs/ResumeRecoverySettings.ui" line="216"/>
<source>Add</source>
<translation>Añadir</translation>
</message>
<message>
<location filename="../../Dialogs/ResumeRecoverySettings.ui" line="235"/>
<source>Remove</source>
<translation>Eliminar</translation>
</message>
<message>
<location filename="../../Dialogs/ResumeRecoverySettings.ui" line="254"/>
<source>Reset</source>
<translation>Restablecer</translation>
</message>
<message>
<location filename="../../Dialogs/ResumeRecoverySettings.ui" line="314"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Segoe UI'; font-size:10pt; font-weight:400; font-style:normal;">
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html></source>
<translation></translation>
</message>
<message>
<location filename="../../Dialogs/ResumeRecoverySettings.ui" line="339"/>
<source>Resume Recovery:</source>
<translation>Reanudar recuperación:</translation>
</message>
</context>
<context>
<name>SavingDlg</name>
<message>
<source>Stellar Phoenix Windows Data Recovery</source>
<translation type="obsolete">Stellar Data Recovery</translation>
</message>
<message>
<location filename="../../Dialogs/SavingDialog.ui" line="363"/>
<source>Select Destination and click 'Start Saving' To Save Data.</source>
<translation>Seleccionar el destino y hacer clic en Empezar a guardar para guardar datos.</translation>
</message>
<message>
<location filename="../../Dialogs/SavingDialog.ui" line="538"/>
<source>Browse...</source>
<translation>Examinar…</translation>
</message>
<message>
<location filename="../../Dialogs/SavingDialog.ui" line="706"/>
<source>Advanced Settings</source>
<translation>Configuración avanzada</translation>
</message>
<message>
<location filename="../../Dialogs/SavingDialog.ui" line="771"/>
<source>Start Saving</source>
<translation>Empezar a guardar</translation>
</message>
<message>
<location filename="../../Dialogs/SavingDialog.ui" line="830"/>
<source>Close</source>
<transl | [
"fardeen.faisal@ontariotechu.net"
] | fardeen.faisal@ontariotechu.net |
fc11ea693ed394c341c2c080c416ee8facc6051c | d2f59681845e912e4a8871c9b82c7360568a0cb3 | /Lab2/src/algorithm.h | af6e696d5150bc3639f716c3bd85698e73688223 | [] | no_license | reidaruss/Reid_Russell_CS3353 | be79da6437f31741015985e50995454935e33f43 | 0a3a3b5259962645a3c69f467033b3f117b39985 | refs/heads/master | 2022-03-20T20:38:18.325946 | 2019-12-05T17:49:39 | 2019-12-05T17:49:39 | 205,235,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | h | #ifndef ALGORITHM_H
#define ALGORITHM_H
#include <string>
using namespace std;
class Algorithm{
public:
virtual void load(string filePath) = 0;
virtual void execute(int start, int end) = 0;
virtual void display() = 0;
virtual void select(int n) = 0;
virtual void save() = 0;
virtual void stats() = 0;
virtual void configure() = 0;
virtual void reportTests() =0;
enum algos{BFSSEARCH=0,DFSSEARCH,DIJKSTRA,ASTAR,LAST};
};
#endif // ALGORITHM_H
| [
"reidarussell@gmail.com"
] | reidarussell@gmail.com |
3ba5952acba51012627ab703f426474c1ba217d6 | 8d08e6f3e0e1ecaf53c3f996cf53df3a27ec49a3 | /src/SensitiveDetector.cc | d79ee60d3492adf36bc11b4ed2d4211e2177f24f | [] | no_license | DrWLucky/interactionDensity | 0ba723358d17042f97cb93e4670fdc08efd3004e | ba1808f29d18d151fc81fc9a89ac4fc7d14bd2b3 | refs/heads/master | 2022-04-01T22:21:19.126321 | 2020-02-11T13:43:49 | 2020-02-11T13:43:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,719 | cc | #include "DetectorHit.hh"
#include "RootAnalysis.hh"
#include "SensitiveDetector.hh"
#include "G4HCofThisEvent.hh"
#include "G4THitsCollection.hh"
#include "G4Step.hh"
#include "G4ThreeVector.hh"
#include "G4SDManager.hh"
#include "G4ios.hh"
#include "G4TouchableHistory.hh"
#include <G4VProcess.hh>
#include "G4RunManager.hh"
#include "RunAction.hh"
#include "Analysis.hh"
#include "G4UnitsTable.hh"
#include "G4PhysicalConstants.hh"
#include "G4SystemOfUnits.hh"
SensitiveDetector::SensitiveDetector(const G4String& name,
const G4String& hitsCollectionName) :
G4VSensitiveDetector(name)
,fHitsCollection(NULL)
{
collectionName.insert(hitsCollectionName);
}
SensitiveDetector::~SensitiveDetector()
{}
void SensitiveDetector::Initialize(G4HCofThisEvent* hce)
{
fHitsCollection
= new DetectorHitsCollection(SensitiveDetectorName, collectionName[0]);
static G4int hcID = -1;
if(hcID<0){
hcID= G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
}
hce->AddHitsCollection( hcID, fHitsCollection );
}
G4bool SensitiveDetector::ProcessHits(G4Step* aStep,G4TouchableHistory*)
{
//Printing particle name in current step
G4Track* track = aStep->GetTrack();
const G4ParticleDefinition* particle = (track->GetParticleDefinition());
const G4String particleName = particle->GetParticleName();
const G4int pdgID = particle->GetPDGEncoding();
G4cout << "Particle: " << std::setw(10) << particleName << G4endl;
//Geting process name that the particle underwent
G4String processName = ((aStep->GetPostStepPoint())->GetProcessDefinedStep())->GetProcessName();
//Getting particle ID
//G4int particleID = track->GetTrackID();
//Energy deposit
G4double energy = aStep->GetTotalEnergyDeposit();
if (energy == 0.) return false; //Particle inside sensitive detector, but no interaction with the medium
//
//Getting the secondary electron information
//
const std::vector<const G4Track*>* secondary = aStep->GetSecondaryInCurrentStep();
int number_secondaries = (*secondary).size();
if (particleName=="gamma" && number_secondaries!=0) {
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
G4double kinEnergy = 0;
G4ThreeVector secondaryPosition;
G4ThreeVector momentumDirection;
for (int i=0; i<number_secondaries; i++) {
const G4ParticleDefinition* secondaryDefinition = (*secondary)[i]->GetParticleDefinition();
G4String secondaryName = secondaryDefinition->GetParticleName();
if (secondaryName == "e-") {
//Kinectic energy of the secondary
kinEnergy = (*secondary)[i]->GetKineticEnergy();
secondaryPosition = (*secondary)[i]->GetPosition();
momentumDirection = (*secondary)[i]->GetMomentumDirection();
G4cout << std::setw(10) << G4BestUnit(kinEnergy,"Energy") << G4endl;
RootAnalysis* rootAnalysis = RootAnalysis::Instance();
rootAnalysis->Write(kinEnergy, secondaryPosition, momentumDirection);
}
}
}
//Storing the hit (interation) information of the current step
DetectorHit* newHit = new DetectorHit();
newHit->SetEnergyDeposit(energy);
newHit->SetPosition (aStep->GetPostStepPoint()->GetPosition());
newHit->SetParticleName(particleName);
newHit->SetProcessName(processName);
newHit->SetPDGid(pdgID);
fHitsCollection->insert(newHit);
newHit->Print();
return true;
}
void SensitiveDetector::EndOfEvent(G4HCofThisEvent*)
{
}
| [
"lucasmaiarios@gmail.com"
] | lucasmaiarios@gmail.com |
72b208888559a8260cf6367b8ff3348eb5181c9f | d49d382c42bf9451bb03d15be0789fd380128117 | /wx/include/wx/osx/menuitem.h | 2e064081dca4d888c91a9187878bb7d9e0418908 | [] | no_license | sukingw/MCDUSim | 30bababcc8f988befafcc7f30dcd2ed44ac027b6 | 5aea62f9e55bb8c7e6b259bc5ff4024610cf33f4 | refs/heads/master | 2023-05-28T04:18:02.996292 | 2017-03-17T02:51:58 | 2017-03-17T02:51:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,816 | h | ///////////////////////////////////////////////////////////////////////////////
// Name: wx/osx/menuitem.h
// Purpose: wxMenuItem class
// Author: Vadim Zeitlin
// Modified by:
// Created: 11.11.97
// RCS-ID: $Id: menuitem.h 64943 2010-07-13 13:29:58Z VZ $
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _MENUITEM_H
#define _MENUITEM_H
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/defs.h"
#include "wx/bitmap.h"
// ----------------------------------------------------------------------------
// wxMenuItem: an item in the menu, optionally implements owner-drawn behaviour
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_FWD_CORE wxMenuItemImpl ;
class WXDLLIMPEXP_CORE wxMenuItem: public wxMenuItemBase
{
public:
// ctor & dtor
wxMenuItem(wxMenu *parentMenu = NULL,
int id = wxID_SEPARATOR,
const wxString& name = wxEmptyString,
const wxString& help = wxEmptyString,
wxItemKind kind = wxITEM_NORMAL,
wxMenu *subMenu = NULL);
virtual ~wxMenuItem();
// override base class virtuals
virtual void SetItemLabel(const wxString& strName);
virtual void Enable(bool bDoEnable = true);
virtual void Check(bool bDoCheck = true);
virtual void SetBitmap(const wxBitmap& bitmap) ;
virtual const wxBitmap& GetBitmap() const { return m_bitmap; }
// update the os specific representation
void UpdateItemBitmap() ;
void UpdateItemText() ;
void UpdateItemStatus() ;
// mark item as belonging to the given radio group
void SetAsRadioGroupStart();
void SetRadioGroupStart(int start);
void SetRadioGroupEnd(int end);
wxMenuItemImpl* GetPeer() { return m_peer; }
private:
void UncheckRadio() ;
// the positions of the first and last items of the radio group this item
// belongs to or -1: start is the radio group start and is valid for all
// but first radio group items (m_isRadioGroupStart == FALSE), end is valid
// only for the first one
union
{
int start;
int end;
} m_radioGroup;
// does this item start a radio group?
bool m_isRadioGroupStart;
wxBitmap m_bitmap; // Bitmap for menuitem, if any
void* m_menu ; // the appropriate menu , may also be a system menu
wxMenuItemImpl* m_peer;
DECLARE_DYNAMIC_CLASS(wxMenuItem)
};
#endif //_MENUITEM_H
| [
"zhijian.xu@honeywell.com"
] | zhijian.xu@honeywell.com |
22e666e93d60a282e9df1c03ca623224c725f54a | 50040215471e72eec1fb7e8ed5cad87a5539e0e5 | /SR_FrameWork_20200330_RealRealFinal/Engine/Resources/Codes/TerrainCol.cpp | 5871b464840d5be73889b158fc62f2019bc89aab | [] | no_license | DeokgyuKim/Tycoon | 0ed71f9475d7243df7dec1eea5303a6d14aa7613 | b3b026c05c85b9482aa3d7f3c53d24470c526807 | refs/heads/main | 2023-08-15T22:25:01.668637 | 2021-10-11T00:04:06 | 2021-10-11T00:04:06 | 415,726,064 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,038 | cpp | #include "TerrainCol.h"
USING(ENGINE)
CTerrainCol::CTerrainCol(LPDIRECT3DDEVICE9 pGraphicDev)
: CVIBuffer(pGraphicDev)
{
}
CTerrainCol::~CTerrainCol()
{
Release();
}
void CTerrainCol::Render(WORD wIndex/* = 0*/)
{
CVIBuffer::Render();
}
HRESULT CTerrainCol::CreateBuffer(const WORD& wCntX, const WORD& wCntZ, const WORD& wItv/* = 1*/)
{
m_dwVtxSize = sizeof(VTX_COL);
m_dwVtxFVF = VTXFVF_COL;
m_dwIdxSize = sizeof(INDEX16);
m_IdxFmt = D3DFMT_INDEX16;
m_dwVtxCount = wCntX * wCntZ;
m_dwTriCount = (wCntX - 1) * (wCntZ - 1) * 2;
FAILED_CHECK_RETURN(CVIBuffer::CreateBuffer(), E_FAIL);
VTX_COL* pVtxCol = nullptr;
m_pVB->Lock(0, 0, (void**)&pVtxCol, 0);
// 로컬 스페이스
WORD wIndex = 0;
for (WORD i = 0; i < wCntZ; ++i)
{
for (WORD j = 0; j < wCntX; ++j)
{
wIndex = i * wCntX + j;
pVtxCol[wIndex].vPos = { float(j * wItv), 0.f, float(i * wItv) };
pVtxCol[wIndex].dwColor = D3DCOLOR_ARGB(255, 255, 255, 255);
}
}
// Origin Vtx
m_pOriginVtx = new VTX_COL[m_dwVtxCount];
memcpy(m_pOriginVtx, pVtxCol, m_dwVtxSize * m_dwVtxCount);
m_pVB->Unlock();
INDEX16* pIndex = nullptr;
m_pIB->Lock(0, 0, (void**)&pIndex, 0);
WORD wTriIndex = 0;
for (WORD i = 0; i < wCntZ - 1; ++i)
{
for (WORD j = 0; j < wCntX - 1; ++j)
{
wIndex = i * wCntX + j;
/*
0 1
2
*/
pIndex[wTriIndex]._1 = wIndex + wCntX;
pIndex[wTriIndex]._2 = wIndex + wCntX + 1;
pIndex[wTriIndex++]._3 = wIndex + 1;
/*
0
3 2
*/
pIndex[wTriIndex]._1 = wIndex + wCntX;
pIndex[wTriIndex]._2 = wIndex + 1;
pIndex[wTriIndex++]._3 = wIndex;
}
}
m_pIB->Unlock();
return S_OK;
}
void CTerrainCol::Release()
{
}
CTerrainCol* CTerrainCol::Create(LPDIRECT3DDEVICE9 pGraphicDev, const WORD& wCntX, const WORD& wCntZ, const WORD& wItv/* = 1*/)
{
NULL_CHECK_RETURN(pGraphicDev, nullptr);
CTerrainCol* pInstance = new CTerrainCol(pGraphicDev);
if (FAILED(pInstance->CreateBuffer(wCntX, wCntZ, wItv)))
{
SafeDelete(pInstance);
return nullptr;
}
return pInstance;
}
| [
"kduck119@gmail.com"
] | kduck119@gmail.com |
716d1dbf06288e4104636fa07db97ed81275c881 | e083c99675bdd20c45bd97e77573344a6ea4f564 | /Project1_GL/Node.h | ba2018d383619332750c8052aefeeeafd0a5c7c6 | [] | no_license | BrettSchumacher/5611-Project-1 | 5fb82923ac8059c4a328ffb17c1678f16ac3f8fc | 7b9559379c4b4ab1cdcbefdd61bf0293d4a74ec6 | refs/heads/master | 2023-08-07T00:19:39.285693 | 2021-10-08T14:49:10 | 2021-10-08T14:49:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 558 | h | #ifndef NODE_CLASS_H
#define NODE_CLASS_H
#include"SquareCollider.h"
enum class NodeType
{
START,
END,
REGULAR
};
class Node
{
public:
SquareCollider collider;
Node* parent;
float cost;
float heuristic;
float weight;
bool seen = false;
bool visited = false;
SquareCollider* parentObst = NULL;
NodeType type = NodeType::REGULAR;
std::vector<Node*> neighbors;
int ID;
Node(SquareCollider collider = SquareCollider(), Node* parent = NULL, float cost = -1.0f, float heuristic = -1.0f);
void SetWeight(float cost, float heuristic);
};
#endif
| [
"schum830@umn.edu"
] | schum830@umn.edu |
097bb3ff3cfccf4cad71c6fe1641dec9290f8679 | 68916c0ae2c7804847622ca39312638e8caf3589 | /src/game/scenes/debug/playmat_slots.hpp | 2630002ae4ff8f31e558ee17362314ee41bbb610 | [] | no_license | NeonSky/open-pokemon-tcg | cf85161807f2b91088aefe7118694d914f4824db | 353ec2dd21e9d981b32da209fa902dabb0bd26e9 | refs/heads/master | 2022-11-24T07:45:26.194184 | 2020-07-07T15:37:56 | 2020-07-07T15:37:56 | 268,048,088 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,161 | hpp | #pragma once
#include "../../view/card.hpp"
#include "../debug_camera.hpp"
#include "../../playmats/black_playmat.hpp"
#include "../../playmats/green_playmat.hpp"
#include "../../../engine/debug/logger.hpp"
#include "../../../engine/debug/debug_drawer.hpp"
#include "../../../engine/graphics/texture.hpp"
#include "../../../engine/gui/window.hpp"
#include "../../../engine/scene/scene.hpp"
#include "../../../engine/graphics/rectangle.hpp"
#include "playmat.hpp"
#include <glm/ext/scalar_constants.hpp>
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
#include <imgui.h>
namespace open_pokemon_tcg::game::scenes {
class PlaymatSlots : public engine::scene::IScene {
public:
PlaymatSlots(engine::gui::Window* window);
~PlaymatSlots();
void update() override;
void render() override;
void gui() override;
private:
DebugCamera camera;
engine::graphics::Shader *shader;
open_pokemon_tcg::game::view::IPlaymat *playmat;
std::vector<Card> cards;
Card debug_card;
// GUI options
bool show_cards = true;
bool show_debug_card = false;
glm::vec3 debug_card_pos = glm::vec3(0.0f, 0.02f, 0.0f);
glm::vec3 debug_card_rot = glm::vec3(-glm::half_pi<float>(), 0.0f, 0.0f);
};
PlaymatSlots::PlaymatSlots(engine::gui::Window* window) :
camera(DebugCamera(window,
engine::geometry::Transform(glm::vec3(0.0f, 10.0f, 0.0f),
glm::vec3(-glm::half_pi<float>(), 0.0f, 0.0f)))),
debug_card(Card(engine::geometry::Transform(), engine::graphics::Texture("img/cardback.png").id())) {
this->shader = new engine::graphics::Shader("simple.vert", "simple.frag");
// this->playmat = new playmats::BlackPlaymat();
this->playmat = new playmats::GreenPlaymat();
// Player 1
engine::graphics::Texture texture1("cache/cards/img/base1-8.png");
this->cards.push_back(Card(playmat->active_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1).transform(), texture1.id()));
this->cards.push_back(Card(playmat->supporter_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1).transform(), texture1.id()));
this->cards.push_back(Card(playmat->stadium_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1).transform(), texture1.id()));
for (int i = 0; i < 5; i++)
this->cards.push_back(Card(playmat->bench_slots(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1)[i].transform(), texture1.id()));
for (int i = 0; i < 6; i++)
this->cards.push_back(Card(playmat->prize_slots(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1)[i].transform(), texture1.id()));
this->cards.push_back(Card(playmat->deck_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1).transform(), texture1.id()));
this->cards.push_back(Card(playmat->discard_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER1).transform(), texture1.id()));
// Player 2
engine::graphics::Texture texture2("cache/cards/img/base1-24.png");
this->cards.push_back(Card(playmat->active_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2).transform(), texture2.id()));
this->cards.push_back(Card(playmat->supporter_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2).transform(), texture2.id()));
this->cards.push_back(Card(playmat->stadium_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2).transform(), texture2.id()));
for (int i = 0; i < 5; i++)
this->cards.push_back(Card(playmat->bench_slots(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2)[i].transform(), texture2.id()));
for (int i = 0; i < 6; i++)
this->cards.push_back(Card(playmat->prize_slots(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2)[i].transform(), texture2.id()));
this->cards.push_back(Card(playmat->deck_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2).transform(), texture2.id()));
this->cards.push_back(Card(playmat->discard_slot(open_pokemon_tcg::game::view::IPlaymat::Side::PLAYER2).transform(), texture2.id()));
}
PlaymatSlots::~PlaymatSlots() {}
void PlaymatSlots::update() {
this->debug_card.transform.position = debug_card_pos;
this->debug_card.transform.rotation = debug_card_rot;
}
void PlaymatSlots::render() {
glm::mat4 viewMatrix = this->camera.view_matrix();
glm::mat4 projectionMatrix = this->camera.projection_matrix();
glm::mat4 view_projection_matrix = projectionMatrix * viewMatrix;
this->shader->use();
if (show_debug_card)
this->debug_card.render(view_projection_matrix, this->shader);
if (show_cards)
for (Card &c : cards)
c.render(view_projection_matrix, this->shader);
this->playmat->render(view_projection_matrix, this->shader);
}
void PlaymatSlots::gui() {
ImGui::Begin("Playmat");
ImGui::Checkbox("Show cards", &show_cards);
ImGui::End();
ImGui::Begin("Debug Card");
ImGui::Checkbox("Show", &show_debug_card);
ImGui::DragFloat3("position", (float*)&debug_card_pos, -10.0f , 10.0f);
ImGui::DragFloat3("rotation", (float*)&debug_card_rot, -2*glm::pi<float>(), 2*glm::pi<float>());
ImGui::End();
}
}
| [
"jacob.a.eriksson@gmail.com"
] | jacob.a.eriksson@gmail.com |
ec6a3f0859076c59d5355435b316f07fc05102f3 | 431859ff9a4904b9c4890d55567bfc9dcd013a1d | /OperatorOverloading_Exercise/OperatorOverloading_Exercise/MainBody.cpp | 1cf066bc2709956cf582a1a469c0126a239a5806 | [] | no_license | LoganPletcher/Homework | 880ce2ec67c4d298be0ee08238832babe5422ca2 | 56bc0bad69d53264a5927604f390a836cb238526 | refs/heads/master | 2021-01-21T12:46:19.357591 | 2016-09-19T15:45:39 | 2016-09-19T15:45:39 | 41,038,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,824 | cpp | //////////////////////////////////////////////////
// File: OperatorOverloading_Exercise //
// Author: Logan Pletcher //
// Date Created: 10/6/2015 //
// Brief: Creates a vector that overloads. //
//////////////////////////////////////////////////
#include <iostream>
#include <string>
#include "Vector2.h"
using namespace std;
int main()
{
Vector2 first;
Vector2 second;
string input;
cout << "Do you want to give values to the x or y of the first vector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
first.Initialise(first);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
system("cls");
cout << "Do you want to give values to the x or y of the second vector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
second.Initialise(second);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
system("cls");
cout << "Do you want to see the data for the first vector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
first.Data(first);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
system("cls");
cout << "Do you want to see the data for the second vector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
second.Data(second);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
system("cls");
cout << "Do you want to add or subtract the values of the second vector to the first \nvector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
first.Addition(second);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
cout << "Do you want to see the data for the first vector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
first.Data(first);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
system("cls");
cout << "Do you want to add or subtract the values of the first vector to the second \nvector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
second.Addition(first);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
system("cls");
cout << "Do you want to see the data for the second vector?\nType in yes or no.\n";
for (int i = 0; i < 2; i++)
{
getline(cin, input);
if (input == "yes")
{
second.Data(second);
i = 2;
}
else if (input == "no")
{
i = 2;
}
else
{
i = 0;
}
}
return 0;
} | [
"lpletch95@hotmail.com"
] | lpletch95@hotmail.com |
067390f94b608d858d1d202a65236b0a5d49a35f | e7e2acd86a83d7f32260b653363b11096a5c28c4 | /src/common/requests/MetadataResponse.cpp | 874c53e87c2f6150b83ca516cf79ecf065e64eee | [
"Apache-2.0"
] | permissive | sxzh12138/kafkaclient-cpp | d280cce80bd66a5b5b2946ec35e232baac08786b | cc13668ca4b3bf17cb94001343d3c11e8a013625 | refs/heads/master | 2020-05-21T07:39:36.999632 | 2019-05-10T08:45:35 | 2019-05-10T08:45:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,805 | cpp | #include "MetadataResponse.h"
#include "Errors.h"
#include "Integer.h"
#include "Utils.h"
#include "CommonFields.h"
#include "Struct.h"
#include "Schema.h"
#include "Field.h"
#include "ObjectArray.h"
#include "PartitionInfo.h"
#include "Cluster.h"
#include "ApiKeys.h"
#include "InvalidMetadataException.h"
#include "Node.h"
#include "Short.h"
#include "RequestUtils.h"
#include "String0.h"
#include "Boolean.h"
#include <set>
ComplexArray* MetadataResponse::BROKERS = new ComplexArray("brokers",
"Host and port information for all brokers.");
ComplexArray* MetadataResponse::TOPIC_METADATA = new ComplexArray("topic_metadata",
"Metadata for requested topics");
NullableStr* MetadataResponse::CLUSTER_ID = new NullableStr("cluster_id",
"The cluster id that this broker belongs to.");
Int32* MetadataResponse::CONTROLLER_ID = new Int32("controller_id",
"The broker id of the controller broker.");
Int32* MetadataResponse::NODE_ID = new Int32("node_id", "The broker id.");
Str* MetadataResponse::HOST = new Str("host", "The hostname of the broker.");
Int32* MetadataResponse::PORT = new Int32("port", "The port on which the broker accepts requests.");
NullableStr* MetadataResponse::RACK = new NullableStr("rack", "The rack of the broker.");
ComplexArray* MetadataResponse::PARTITION_METADATA = new ComplexArray("partition_metadata",
"Metadata for each partition of the topic.");
Bool* MetadataResponse::IS_INTERNAL = new Bool("is_internal",
"Indicates if the topic is considered a Kafka internal topic");
Int32* MetadataResponse::LEADER = new Int32("leader",
"The id of the broker acting as leader for this partition.");
Array* MetadataResponse::REPLICAS = new Array("replicas", Type::INT32(),
"The set of all nodes that host this partition.");
Array* MetadataResponse::ISR = new Array("isr", Type::INT32(),
"The set of nodes that are in sync with the leader for this partition.");
Array* MetadataResponse::OFFLINE_REPLICAS = new Array("offline_replicas", Type::INT32(),
"The set of offline replicas of this partition.");
Field* MetadataResponse::METADATA_BROKER_V0 = BROKERS->withFields(3,
NODE_ID,
HOST,
PORT);
Field* MetadataResponse::PARTITION_METADATA_V0 = PARTITION_METADATA->withFields(5,
CommonFields::ERROR_CODE,
CommonFields::PARTITION_ID,
LEADER,
REPLICAS,
ISR);
Field* MetadataResponse::TOPIC_METADATA_V0 = TOPIC_METADATA->withFields(3,
CommonFields::ERROR_CODE,
CommonFields::TOPIC_NAME,
PARTITION_METADATA_V0);
Schema* MetadataResponse::METADATA_RESPONSE_V0 = new Schema(2,
METADATA_BROKER_V0,
TOPIC_METADATA_V0);
Field* MetadataResponse::METADATA_BROKER_V1 = BROKERS->withFields(4,
NODE_ID,
HOST,
PORT,
RACK);
Field* MetadataResponse::TOPIC_METADATA_V1 = TOPIC_METADATA->withFields(4,
CommonFields::ERROR_CODE,
CommonFields::TOPIC_NAME,
IS_INTERNAL,
PARTITION_METADATA_V0);
Schema* MetadataResponse::METADATA_RESPONSE_V1 = new Schema(3,
METADATA_BROKER_V1,
CONTROLLER_ID,
TOPIC_METADATA_V1);
Schema* MetadataResponse::METADATA_RESPONSE_V2 = new Schema(4,
METADATA_BROKER_V1,
CLUSTER_ID,
CONTROLLER_ID,
TOPIC_METADATA_V1);
Schema* MetadataResponse::METADATA_RESPONSE_V3 = new Schema(5,
CommonFields::THROTTLE_TIME_MS,
METADATA_BROKER_V1,
CLUSTER_ID,
CONTROLLER_ID,
TOPIC_METADATA_V1);
Schema* MetadataResponse::METADATA_RESPONSE_V4 = METADATA_RESPONSE_V3;
Field* MetadataResponse::PARTITION_METADATA_V5 = PARTITION_METADATA->withFields(6,
CommonFields::ERROR_CODE,
CommonFields::PARTITION_ID,
LEADER,
REPLICAS,
ISR,
OFFLINE_REPLICAS);
Field* MetadataResponse::TOPIC_METADATA_V5 = TOPIC_METADATA->withFields(4,
CommonFields::ERROR_CODE,
CommonFields::TOPIC_NAME,
IS_INTERNAL,
PARTITION_METADATA_V5);
Schema* MetadataResponse::METADATA_RESPONSE_V5 = new Schema(5,
CommonFields::THROTTLE_TIME_MS,
METADATA_BROKER_V1,
CLUSTER_ID,
CONTROLLER_ID,
TOPIC_METADATA_V5);
Schema* MetadataResponse::METADATA_RESPONSE_V6 = METADATA_RESPONSE_V5;
Field* MetadataResponse::PARTITION_METADATA_V7 = PARTITION_METADATA->withFields(7,
CommonFields::ERROR_CODE,
CommonFields::PARTITION_ID,
LEADER,
CommonFields::LEADER_EPOCH,
REPLICAS,
ISR,
OFFLINE_REPLICAS);
Field* MetadataResponse::TOPIC_METADATA_V7 = TOPIC_METADATA->withFields(4,
CommonFields::ERROR_CODE,
CommonFields::TOPIC_NAME,
IS_INTERNAL,
PARTITION_METADATA_V7);
Schema* MetadataResponse::METADATA_RESPONSE_V7 = new Schema(5,
CommonFields::THROTTLE_TIME_MS,
METADATA_BROKER_V1,
CLUSTER_ID,
CONTROLLER_ID,
TOPIC_METADATA_V7);
PartitionMetadata::PartitionMetadata(Errors *error, int partition, Node *leader, Integer *leaderEpoch, std::list<Node*> replicas, std::list<Node*> isr, std::list<Node*> offlineReplicas)
{
this->error_ = error;
this->partition_ = partition;
this->leader_ = leader;
this->leaderEpoch_ = leaderEpoch;
this->replicas_ = replicas;
this->isr_ = isr;
this->offlineReplicas_ = offlineReplicas;
}
std::string PartitionMetadata::toString()
{
return "(type=PartitionMetadata"
", error=" + error_->toString() +
", partition=" + std::to_string(partition_) +
", leader=" + leader_->toString() +
", leaderEpoch=" + std::to_string(*leaderEpoch_) +
", replicas=" + Utils::join(replicas_, ",") +
", isr=" + Utils::join(isr_, ",") +
", offlineReplicas=" + Utils::join(offlineReplicas_, ",") + ')';
}
TopicMetadata::TopicMetadata(Errors *error, const char *topic, bool isInternal, std::list<PartitionMetadata*> partitionMetadata)
{
this->error_ = error;
this->topic_ = topic;
this->isInternal_ = isInternal;
this->partitionMetadata_ = partitionMetadata;
}
std::string TopicMetadata::toString()
{
return "(type=TopicMetadata"
", error=" + error_->toString() +
", topic=" + topic_ +
", isInternal=" + std::to_string(isInternal_) +
", partitionMetadata=" + Utils::join(partitionMetadata_, ",") + ')';
}
Schema** MetadataResponse::schemaVersions()
{
static Schema* schemas[] = { METADATA_RESPONSE_V0, METADATA_RESPONSE_V1, METADATA_RESPONSE_V2, METADATA_RESPONSE_V3,
METADATA_RESPONSE_V4, METADATA_RESPONSE_V5, METADATA_RESPONSE_V6, METADATA_RESPONSE_V7, NULL };
return schemas;
}
MetadataResponse::MetadataResponse(std::list<Node*> brokers, const char *clusterId, int controllerId, std::list<TopicMetadata*> topicMetadata)
{
new (this)MetadataResponse(DEFAULT_THROTTLE_TIME, brokers, clusterId, controllerId, topicMetadata);
}
MetadataResponse::MetadataResponse(int throttleTimeMs, std::list<Node*> brokers, const char *clusterId, int controllerId, std::list<TopicMetadata*> topicMetadata)
{
this->throttleTimeMs_ = throttleTimeMs;
this->brokers_ = brokers;
this->controller_ = getControllerNode(controllerId, brokers);
this->topicMetadata_ = topicMetadata;
this->clusterId_ = new String(clusterId);
}
MetadataResponse::MetadataResponse(Struct *s)
{
this->throttleTimeMs_ = *s->getOrElse(CommonFields::THROTTLE_TIME_MS, DEFAULT_THROTTLE_TIME);
std::map<int, Node*> brokers;
ObjectArray *brokerStructs = s->get(BROKERS);
for (int i = 0; i < *brokerStructs; i ++)
{
Struct *broker = (Struct*)(*brokerStructs)[i];
int nodeId = *broker->get(NODE_ID);
std::string host = *broker->get(HOST);
int port = *broker->get(PORT);
String *rack = broker->getOrElse(RACK, NULL);
brokers[nodeId] = new Node(nodeId, host.c_str(), port, rack == NULL ? NULL : (const char*)*rack);
}
int controllerId = *s->getOrElse(CONTROLLER_ID, NO_CONTROLLER_ID);
this->clusterId_ = s->getOrElse(CLUSTER_ID, NULL);
std::list<TopicMetadata*> topicMetadata;
ObjectArray *topicInfos = s->get(TOPIC_METADATA);
for (int i = 0; i < *topicInfos; i++)
{
Struct *topicInfo = (Struct*)(*topicInfos)[i];
Errors *topicError = Errors::forCode(*topicInfo->get(CommonFields::ERROR_CODE));
String *topic = topicInfo->get(CommonFields::TOPIC_NAME);
bool isInternal = topicInfo->getOrElse(IS_INTERNAL, false);
std::list<PartitionMetadata*> partitionMetadata;
ObjectArray *partitionInfos = topicInfo->get(PARTITION_METADATA);
for (int i = 0; i < *partitionInfos; i ++)
{
Struct *partitionInfo = (Struct*)(*partitionInfos)[i];
Errors *partitionError = Errors::forCode(*partitionInfo->get(CommonFields::ERROR_CODE));
int partition = *partitionInfo->get(CommonFields::PARTITION_ID);
int leader = *partitionInfo->get(LEADER);
Integer *leaderEpoch = RequestUtils::getLeaderEpoch(partitionInfo, CommonFields::LEADER_EPOCH);
Node *leaderNode = leader == -1 ? NULL : brokers[leader];
ObjectArray *replicas = partitionInfo->get(REPLICAS);
std::list<Node*> replicaNodes = convertToNodes(brokers, replicas);
ObjectArray *isr = partitionInfo->get(ISR);
std::list<Node*> isrNodes = convertToNodes(brokers, isr);
ObjectArray *offlineReplicas = partitionInfo->getOrEmpty(OFFLINE_REPLICAS);
std::list<Node*> offlineNodes = convertToNodes(brokers, offlineReplicas);
partitionMetadata.push_back(new PartitionMetadata(partitionError, partition, leaderNode, leaderEpoch,
replicaNodes, isrNodes, offlineNodes));
}
topicMetadata.push_back(new TopicMetadata(topicError, *topic, isInternal, partitionMetadata));
}
this->brokers_ = Utils::values(brokers);
this->controller_ = getControllerNode(controllerId, Utils::values(brokers));
this->topicMetadata_ = topicMetadata;
}
std::map<std::string, Errors*> MetadataResponse::errors()
{
std::map<std::string, Errors*> errors;
for (TopicMetadata *metadata : topicMetadata_)
{
if (metadata->error() != Errors::NONE)
errors[metadata->topic()] = metadata->error();
}
return errors;
}
std::map<Errors*, int> MetadataResponse::errorCounts()
{
std::map<Errors*, int> errorCounts;
for (TopicMetadata *metadata : topicMetadata_)
updateErrorCounts(errorCounts, metadata->error());
return errorCounts;
}
std::set<std::string> MetadataResponse::topicsByError(Errors *error)
{
std::set<std::string> errorTopics;
for (TopicMetadata *metadata : topicMetadata_)
{
if (metadata->error() == error)
errorTopics.insert(metadata->topic());
}
return errorTopics;
}
std::set<std::string> MetadataResponse::unavailableTopics()
{
std::set<std::string> invalidMetadataTopics;
for (TopicMetadata *topicMetadata : this->topicMetadata_)
{
if (dynamic_cast<InvalidMetadataException*>(topicMetadata->error()->exception()))
invalidMetadataTopics.insert(topicMetadata->topic());
else
{
for (PartitionMetadata *partitionMetadata : topicMetadata->partitionMetadata())
{
if (dynamic_cast<InvalidMetadataException*>(partitionMetadata->error()->exception()))
{
invalidMetadataTopics.insert(topicMetadata->topic());
break;
}
}
}
}
return invalidMetadataTopics;
}
Cluster* MetadataResponse::cluster()
{
std::set<std::string> internalTopics;
std::list<PartitionInfo*> partitions;
for (auto iter : topicMetadata_)
{
TopicMetadata metadata = *iter;
if (metadata.error() == Errors::NONE)
{
if (metadata.isInternal())
internalTopics.insert(metadata.topic());
for (PartitionMetadata *partitionMetadata : metadata.partitionMetadata())
{
partitions.push_back(partitionMetaToInfo(metadata.topic().c_str(), partitionMetadata));
}
}
}
return new Cluster(*this->clusterId_, this->brokers_, partitions, topicsByError(Errors::TOPIC_AUTHORIZATION_FAILED),
topicsByError(Errors::INVALID_TOPIC_EXCEPTION), internalTopics, this->controller_);
}
PartitionInfo* MetadataResponse::partitionMetaToInfo(const char *topic, PartitionMetadata *partitionMetadata)
{
return new PartitionInfo(
topic,
partitionMetadata->partition(),
partitionMetadata->leader(),
partitionMetadata->replicas(),
partitionMetadata->isr(),
partitionMetadata->offlineReplicas());
}
MetadataResponse* MetadataResponse::parse(ByteBuffer *buffer, short version)
{
return new MetadataResponse(ApiKeys::METADATA()->parseResponse(version, buffer));
}
Struct* MetadataResponse::toStruct(short version)
{
Struct *s = new Struct(ApiKeys::METADATA()->responseSchema(version));
s->setIfExists(CommonFields::THROTTLE_TIME_MS, new Integer(throttleTimeMs_));
std::list<Struct*> brokerArray;
for (Node *node : brokers_)
{
Struct *broker = s->instance(BROKERS);
broker->set(NODE_ID, node->id());
broker->set(HOST, node->host());
broker->set(PORT, node->port());
broker->setIfExists(RACK, new String(node->rack()));
brokerArray.push_back(broker);
}
s->set(BROKERS, Utils::toArray(brokerArray));
s->setIfExists(CONTROLLER_ID, controller_ == NULL ? new Integer(NO_CONTROLLER_ID) : new Integer(controller_->id()));
s->setIfExists(CLUSTER_ID, clusterId_);
std::list<Struct*> topicMetadataArray;
for (TopicMetadata *metadata : topicMetadata_)
{
Struct *topicData = s->instance(TOPIC_METADATA);
topicData->set(CommonFields::TOPIC_NAME, metadata->topic().c_str());
topicData->set(CommonFields::ERROR_CODE, metadata->error()->code());
topicData->setIfExists(IS_INTERNAL, new Boolean(metadata->isInternal()));
std::list<Struct*> partitionMetadataArray;
for (PartitionMetadata *partitionMetadata : metadata->partitionMetadata())
{
Struct *partitionData = topicData->instance(PARTITION_METADATA);
partitionData->set(CommonFields::ERROR_CODE, partitionMetadata->error()->code());
partitionData->set(CommonFields::PARTITION_ID, partitionMetadata->partition());
partitionData->set(LEADER, partitionMetadata->leaderId());
RequestUtils::setLeaderEpochIfExists(partitionData, CommonFields::LEADER_EPOCH, partitionMetadata->leaderEpoch());
std::list<int> replicas;
for (Node *node : partitionMetadata->replicas())
replicas.push_back(node->id());
partitionData->set(REPLICAS, Utils::toArray(replicas));
std::list<int> isr;
for (Node *node : partitionMetadata->isr())
isr.push_back(node->id());
partitionData->set(ISR, Utils::toArray(isr));
if (partitionData->hasField(OFFLINE_REPLICAS))
{
std::list<int> offlineReplicas;
for (Node *node : partitionMetadata->offlineReplicas())
offlineReplicas.push_back(node->id());
partitionData->set(OFFLINE_REPLICAS, Utils::toArray(offlineReplicas));
}
partitionMetadataArray.push_back(partitionData);
}
topicData->set(PARTITION_METADATA, Utils::toArray(partitionMetadataArray));
topicMetadataArray.push_back(topicData);
}
s->set(TOPIC_METADATA, Utils::toArray(topicMetadataArray));
return s;
}
std::list<Node*> MetadataResponse::convertToNodes(std::map<int, Node*> brokers, ObjectArray *brokerIds)
{
std::list<Node*> nodes;
for (int i = 0; i < *brokerIds; i++)
{
Object *brokerId = (*brokerIds)[i];
int id = *(Integer*)brokerId;
if (brokers.find(id) != brokers.end())
nodes.push_back(brokers[id]);
else
nodes.push_back(new Node(id, "", -1));
}
return nodes;
}
Node* MetadataResponse::getControllerNode(int controllerId, std::list<Node*> brokers)
{
for (auto iter : brokers)
{
if (iter->id() == controllerId)
return iter;
}
return NULL;
}
| [
"smartdu@qq.com"
] | smartdu@qq.com |
57c78390b1c0be6a85ddd7258eeb5226dff6f96a | 14012471f78447bc651bae58e78ca42f85f1f7dd | /jlx_third_party/third_party/OpenCV-android-sdk/sdk/native/jni/include/opencv2/core/mat.hpp | c93a3bbfce3448db2526891c02e35a21803214d3 | [
"BSD-3-Clause"
] | permissive | IsaiahKing/useCamera2Demo | 04d416df15f327d6013eab07ae9bbeed3cf2c216 | 83910d034c9985895696aaa7da7602af7e3fc5d0 | refs/heads/master | 2022-12-20T12:07:46.591241 | 2019-09-11T03:50:18 | 2019-09-11T03:50:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153,911 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_CORE_MAT_HPP
#define OPENCV_CORE_MAT_HPP
#ifndef __cplusplus
# error mat.hpp header must be compiled as C++
#endif
#include "opencv2/core/matx.hpp"
#include "opencv2/core/types.hpp"
#include "opencv2/core/bufferpool.hpp"
#ifdef CV_CXX11
#include <type_traits>
#endif
namespace cv
{
//! @addtogroup core_basic
//! @{
enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
CV__DEBUG_NS_BEGIN
class CV_EXPORTS _OutputArray;
//////////////////////// Input/Output Array Arguments /////////////////////////////////
/** @brief This is the proxy class for passing read-only input arrays into OpenCV functions.
It is defined as:
@code
typedef const _InputArray& InputArray;
@endcode
where _InputArray is a class that can be constructed from `Mat`, `Mat_<T>`, `Matx<T, m, n>`,
`std::vector<T>`, `std::vector<std::vector<T> >`, `std::vector<Mat>`, `std::vector<Mat_<T> >`,
`UMat`, `std::vector<UMat>` or `double`. It can also be constructed from a matrix expression.
Since this is mostly implementation-level class, and its interface may change in future versions, we
do not describe it in details. There are a few key things, though, that should be kept in mind:
- When you see in the reference manual or in OpenCV source code a function that takes
InputArray, it means that you can actually pass `Mat`, `Matx`, `vector<T>` etc. (see above the
complete list).
- Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or
simply cv::Mat() as you probably did before).
- The class is designed solely for passing parameters. That is, normally you *should not*
declare class members, local and global variables of this type.
- If you want to design your own function or a class method that can operate of arrays of
multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside
a function you should use _InputArray::getMat() method to construct a matrix header for the
array (without copying data). _InputArray::kind() can be used to distinguish Mat from
`vector<>` etc., but normally it is not needed.
Here is how you can use a function that takes InputArray :
@code
std::vector<Point2f> vec;
// points or a circle
for( int i = 0; i < 30; i++ )
vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)),
(float)(100 - 30*sin(i*CV_PI*2/5))));
cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20));
@endcode
That is, we form an STL vector containing points, and apply in-place affine transformation to the
vector using the 2x3 matrix created inline as `Matx<float, 2, 3>` instance.
Here is how such a function can be implemented (for simplicity, we implement a very specific case of
it, according to the assertion statement inside) :
@code
void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m)
{
// get Mat headers for input arrays. This is O(1) operation,
// unless _src and/or _m are matrix expressions.
Mat src = _src.getMat(), m = _m.getMat();
CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) );
// [re]create the output array so that it has the proper size and type.
// In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize.
_dst.create(src.size(), src.type());
Mat dst = _dst.getMat();
for( int i = 0; i < src.rows; i++ )
for( int j = 0; j < src.cols; j++ )
{
Point2f pt = src.at<Point2f>(i, j);
dst.at<Point2f>(i, j) = Point2f(m.at<float>(0, 0)*pt.x +
m.at<float>(0, 1)*pt.y +
m.at<float>(0, 2),
m.at<float>(1, 0)*pt.x +
m.at<float>(1, 1)*pt.y +
m.at<float>(1, 2));
}
}
@endcode
There is another related type, InputArrayOfArrays, which is currently defined as a synonym for
InputArray:
@code
typedef InputArray InputArrayOfArrays;
@endcode
It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate
synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation
level their use is similar, but _InputArray::getMat(idx) should be used to get header for the
idx-th component of the outer vector and _InputArray::size().area() should be used to find the
number of components (vectors/matrices) of the outer vector.
*/
class CV_EXPORTS _InputArray
{
public:
enum {
KIND_SHIFT = 16,
FIXED_TYPE = 0x8000 << KIND_SHIFT,
FIXED_SIZE = 0x4000 << KIND_SHIFT,
KIND_MASK = 31 << KIND_SHIFT,
NONE = 0 << KIND_SHIFT,
MAT = 1 << KIND_SHIFT,
MATX = 2 << KIND_SHIFT,
STD_VECTOR = 3 << KIND_SHIFT,
STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
STD_VECTOR_MAT = 5 << KIND_SHIFT,
EXPR = 6 << KIND_SHIFT,
OPENGL_BUFFER = 7 << KIND_SHIFT,
CUDA_HOST_MEM = 8 << KIND_SHIFT,
CUDA_GPU_MAT = 9 << KIND_SHIFT,
UMAT =10 << KIND_SHIFT,
STD_VECTOR_UMAT =11 << KIND_SHIFT,
STD_BOOL_VECTOR =12 << KIND_SHIFT,
STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT,
STD_ARRAY =14 << KIND_SHIFT,
STD_ARRAY_MAT =15 << KIND_SHIFT
};
_InputArray();
_InputArray(int _flags, void* _obj);
_InputArray(const Mat& m);
_InputArray(const MatExpr& expr);
_InputArray(const std::vector<Mat>& vec);
template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
_InputArray(const std::vector<bool>& vec);
template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
_InputArray(const std::vector<std::vector<bool> >&);
template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _InputArray(const _Tp* vec, int n);
template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
_InputArray(const double& val);
_InputArray(const cuda::GpuMat& d_mat);
_InputArray(const std::vector<cuda::GpuMat>& d_mat_array);
_InputArray(const ogl::Buffer& buf);
_InputArray(const cuda::HostMem& cuda_mem);
template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
_InputArray(const UMat& um);
_InputArray(const std::vector<UMat>& umv);
#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _InputArray(const std::array<_Tp, _Nm>& arr);
template<std::size_t _Nm> _InputArray(const std::array<Mat, _Nm>& arr);
#endif
Mat getMat(int idx=-1) const;
Mat getMat_(int idx=-1) const;
UMat getUMat(int idx=-1) const;
void getMatVector(std::vector<Mat>& mv) const;
void getUMatVector(std::vector<UMat>& umv) const;
void getGpuMatVector(std::vector<cuda::GpuMat>& gpumv) const;
cuda::GpuMat getGpuMat() const;
ogl::Buffer getOGlBuffer() const;
int getFlags() const;
void* getObj() const;
Size getSz() const;
int kind() const;
int dims(int i=-1) const;
int cols(int i=-1) const;
int rows(int i=-1) const;
Size size(int i=-1) const;
int sizend(int* sz, int i=-1) const;
bool sameSize(const _InputArray& arr) const;
size_t total(int i=-1) const;
int type(int i=-1) const;
int depth(int i=-1) const;
int channels(int i=-1) const;
bool isContinuous(int i=-1) const;
bool isSubmatrix(int i=-1) const;
bool empty() const;
void copyTo(const _OutputArray& arr) const;
void copyTo(const _OutputArray& arr, const _InputArray & mask) const;
size_t offset(int i=-1) const;
size_t step(int i=-1) const;
bool isMat() const;
bool isUMat() const;
bool isMatVector() const;
bool isUMatVector() const;
bool isMatx() const;
bool isVector() const;
bool isGpuMatVector() const;
~_InputArray();
protected:
int flags;
void* obj;
Size sz;
void init(int _flags, const void* _obj);
void init(int _flags, const void* _obj, Size _sz);
};
/** @brief This type is very similar to InputArray except that it is used for input/output and output function
parameters.
Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`,
`vector<T>` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly
create OutputArray instances* applies here too.
If you want to make your function polymorphic (i.e. accept different arrays as output parameters),
it is also not very difficult. Take the sample above as the reference. Note that
_OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee
that the output array is properly allocated.
Optional output parameters. If you do not need certain output array to be computed and returned to
you, pass cv::noArray(), just like you would in the case of optional input array. At the
implementation level, use _OutputArray::needed() to check if certain output array needs to be
computed or not.
There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper
generators:
@code
typedef OutputArray OutputArrayOfArrays;
typedef OutputArray InputOutputArray;
typedef OutputArray InputOutputArrayOfArrays;
@endcode
*/
class CV_EXPORTS _OutputArray : public _InputArray
{
public:
enum
{
DEPTH_MASK_8U = 1 << CV_8U,
DEPTH_MASK_8S = 1 << CV_8S,
DEPTH_MASK_16U = 1 << CV_16U,
DEPTH_MASK_16S = 1 << CV_16S,
DEPTH_MASK_32S = 1 << CV_32S,
DEPTH_MASK_32F = 1 << CV_32F,
DEPTH_MASK_64F = 1 << CV_64F,
DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
};
_OutputArray();
_OutputArray(int _flags, void* _obj);
_OutputArray(Mat& m);
_OutputArray(std::vector<Mat>& vec);
_OutputArray(cuda::GpuMat& d_mat);
_OutputArray(std::vector<cuda::GpuMat>& d_mat);
_OutputArray(ogl::Buffer& buf);
_OutputArray(cuda::HostMem& cuda_mem);
template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
_OutputArray(std::vector<bool>& vec);
template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
_OutputArray(std::vector<std::vector<bool> >&);
template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
template<typename _Tp> _OutputArray(_Tp* vec, int n);
template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
_OutputArray(UMat& m);
_OutputArray(std::vector<UMat>& vec);
_OutputArray(const Mat& m);
_OutputArray(const std::vector<Mat>& vec);
_OutputArray(const cuda::GpuMat& d_mat);
_OutputArray(const std::vector<cuda::GpuMat>& d_mat);
_OutputArray(const ogl::Buffer& buf);
_OutputArray(const cuda::HostMem& cuda_mem);
template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
template<typename _Tp> _OutputArray(const _Tp* vec, int n);
template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
_OutputArray(const UMat& m);
_OutputArray(const std::vector<UMat>& vec);
#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _OutputArray(std::array<_Tp, _Nm>& arr);
template<typename _Tp, std::size_t _Nm> _OutputArray(const std::array<_Tp, _Nm>& arr);
template<std::size_t _Nm> _OutputArray(std::array<Mat, _Nm>& arr);
template<std::size_t _Nm> _OutputArray(const std::array<Mat, _Nm>& arr);
#endif
bool fixedSize() const;
bool fixedType() const;
bool needed() const;
Mat& getMatRef(int i=-1) const;
UMat& getUMatRef(int i=-1) const;
cuda::GpuMat& getGpuMatRef() const;
std::vector<cuda::GpuMat>& getGpuMatVecRef() const;
ogl::Buffer& getOGlBufferRef() const;
cuda::HostMem& getHostMemRef() const;
void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
void createSameSize(const _InputArray& arr, int mtype) const;
void release() const;
void clear() const;
void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
void assign(const UMat& u) const;
void assign(const Mat& m) const;
void assign(const std::vector<UMat>& v) const;
void assign(const std::vector<Mat>& v) const;
};
class CV_EXPORTS _InputOutputArray : public _OutputArray
{
public:
_InputOutputArray();
_InputOutputArray(int _flags, void* _obj);
_InputOutputArray(Mat& m);
_InputOutputArray(std::vector<Mat>& vec);
_InputOutputArray(cuda::GpuMat& d_mat);
_InputOutputArray(ogl::Buffer& buf);
_InputOutputArray(cuda::HostMem& cuda_mem);
template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
_InputOutputArray(std::vector<bool>& vec);
template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
_InputOutputArray(UMat& m);
_InputOutputArray(std::vector<UMat>& vec);
_InputOutputArray(const Mat& m);
_InputOutputArray(const std::vector<Mat>& vec);
_InputOutputArray(const cuda::GpuMat& d_mat);
_InputOutputArray(const std::vector<cuda::GpuMat>& d_mat);
_InputOutputArray(const ogl::Buffer& buf);
_InputOutputArray(const cuda::HostMem& cuda_mem);
template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
_InputOutputArray(const UMat& m);
_InputOutputArray(const std::vector<UMat>& vec);
#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _InputOutputArray(std::array<_Tp, _Nm>& arr);
template<typename _Tp, std::size_t _Nm> _InputOutputArray(const std::array<_Tp, _Nm>& arr);
template<std::size_t _Nm> _InputOutputArray(std::array<Mat, _Nm>& arr);
template<std::size_t _Nm> _InputOutputArray(const std::array<Mat, _Nm>& arr);
#endif
};
CV__DEBUG_NS_END
typedef const _InputArray& InputArray;
typedef InputArray InputArrayOfArrays;
typedef const _OutputArray& OutputArray;
typedef OutputArray OutputArrayOfArrays;
typedef const _InputOutputArray& InputOutputArray;
typedef InputOutputArray InputOutputArrayOfArrays;
CV_EXPORTS InputOutputArray noArray();
/////////////////////////////////// MatAllocator //////////////////////////////////////
//! Usage flags for allocator
enum UMatUsageFlags
{
USAGE_DEFAULT = 0,
// buffer allocation policy is platform and usage specific
USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY
__UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
};
struct CV_EXPORTS UMatData;
/** @brief Custom array allocator
*/
class CV_EXPORTS MatAllocator
{
public:
MatAllocator() {}
virtual ~MatAllocator() {}
// let's comment it off for now to detect and fix all the uses of allocator
//virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
// uchar*& datastart, uchar*& data, size_t* step) = 0;
//virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
virtual UMatData* allocate(int dims, const int* sizes, int type,
void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
virtual void deallocate(UMatData* data) const = 0;
virtual void map(UMatData* data, int accessflags) const;
virtual void unmap(UMatData* data) const;
virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
const size_t srcofs[], const size_t srcstep[],
const size_t dststep[]) const;
virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
const size_t dstofs[], const size_t dststep[],
const size_t srcstep[]) const;
virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
const size_t srcofs[], const size_t srcstep[],
const size_t dstofs[], const size_t dststep[], bool sync) const;
// default implementation returns DummyBufferPoolController
virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const;
};
//////////////////////////////// MatCommaInitializer //////////////////////////////////
/** @brief Comma-separated Matrix Initializer
The class instances are usually not created explicitly.
Instead, they are created on "matrix << firstValue" operator.
The sample below initializes 2x2 rotation matrix:
\code
double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
Mat R = (Mat_<double>(2,2) << a, -b, b, a);
\endcode
*/
template<typename _Tp> class MatCommaInitializer_
{
public:
//! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
MatCommaInitializer_(Mat_<_Tp>* _m);
//! the operator that takes the next value and put it to the matrix
template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
//! another form of conversion operator
operator Mat_<_Tp>() const;
protected:
MatIterator_<_Tp> it;
};
/////////////////////////////////////// Mat ///////////////////////////////////////////
// note that umatdata might be allocated together
// with the matrix data, not as a separate object.
// therefore, it does not have constructor or destructor;
// it should be explicitly initialized using init().
struct CV_EXPORTS UMatData
{
enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64,
ASYNC_CLEANUP=128
};
UMatData(const MatAllocator* allocator);
~UMatData();
// provide atomic access to the structure
void lock();
void unlock();
bool hostCopyObsolete() const;
bool deviceCopyObsolete() const;
bool deviceMemMapped() const;
bool copyOnMap() const;
bool tempUMat() const;
bool tempCopiedUMat() const;
void markHostCopyObsolete(bool flag);
void markDeviceCopyObsolete(bool flag);
void markDeviceMemMapped(bool flag);
const MatAllocator* prevAllocator;
const MatAllocator* currAllocator;
int urefcount;
int refcount;
uchar* data;
uchar* origdata;
size_t size;
int flags;
void* handle;
void* userdata;
int allocatorFlags_;
int mapcount;
UMatData* originalUMatData;
};
struct CV_EXPORTS UMatDataAutoLock
{
explicit UMatDataAutoLock(UMatData* u);
~UMatDataAutoLock();
UMatData* u;
};
struct CV_EXPORTS MatSize
{
explicit MatSize(int* _p);
Size operator()() const;
const int& operator[](int i) const;
int& operator[](int i);
operator const int*() const;
bool operator == (const MatSize& sz) const;
bool operator != (const MatSize& sz) const;
int* p;
};
struct CV_EXPORTS MatStep
{
MatStep();
explicit MatStep(size_t s);
const size_t& operator[](int i) const;
size_t& operator[](int i);
operator size_t() const;
MatStep& operator = (size_t s);
size_t* p;
size_t buf[2];
protected:
MatStep& operator = (const MatStep&);
};
/** @example cout_mat.cpp
An example demonstrating the serial out capabilities of cv::Mat
*/
/** @brief n-dimensional dense array class \anchor CVMat_Details
The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It
can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel
volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms
may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array
`M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k<M.size[k]\f$, is
computed as:
\f[addr(M_{i_0,...,i_{M.dims-1}}) = M.data + M.step[0]*i_0 + M.step[1]*i_1 + ... + M.step[M.dims-1]*i_{M.dims-1}\f]
In case of a 2-dimensional array, the above formula is reduced to:
\f[addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j\f]
Note that `M.step[i] >= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means
that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane,
and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() .
So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV
1.x. It is also compatible with the majority of dense array types from the standard toolkits and
SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any
array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this
compatibility, it is possible to make a Mat header for user-allocated data and process it in-place
using OpenCV functions.
There are many different ways to create a Mat object. The most popular options are listed below:
- Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue])
constructor. A new array of the specified size and type is allocated. type has the same meaning as
in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2
means a 2-channel (complex) floating-point array, and so on.
@code
// make a 7x7 complex matrix filled with 1+3j.
Mat M(7,7,CV_32FC2,Scalar(1,3));
// and now turn M to a 100x60 15-channel 8-bit matrix.
// The old content will be deallocated
M.create(100,60,CV_8UC(15));
@endcode
As noted in the introduction to this chapter, create() allocates only a new array when the shape
or type of the current array are different from the specified ones.
- Create a multi-dimensional array:
@code
// create a 100x100x100 8-bit array
int sz[] = {100, 100, 100};
Mat bigCube(3, sz, CV_8U, Scalar::all(0));
@endcode
It passes the number of dimensions =1 to the Mat constructor but the created array will be
2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0
when the array is empty).
- Use a copy constructor or assignment operator where there can be an array or expression on the
right side (see below). As noted in the introduction, the array assignment is an O(1) operation
because it only copies the header and increases the reference counter. The Mat::clone() method can
be used to get a full (deep) copy of the array when you need it.
- Construct a header for a part of another array. It can be a single row, single column, several
rows, several columns, rectangular region in the array (called a *minor* in algebra) or a
diagonal. Such operations are also O(1) because the new header references the same data. You can
actually modify a part of the array using this feature, for example:
@code
// add the 5-th row, multiplied by 3 to the 3rd row
M.row(3) = M.row(3) + M.row(5)*3;
// now copy the 7-th column to the 1-st column
// M.col(1) = M.col(7); // this will not work
Mat M1 = M.col(1);
M.col(7).copyTo(M1);
// create a new 320x240 image
Mat img(Size(320,240),CV_8UC3);
// select a ROI
Mat roi(img, Rect(10,10,100,100));
// fill the ROI with (0,255,0) (which is green in RGB space);
// the original 320x240 image will be modified
roi = Scalar(0,255,0);
@endcode
Due to the additional datastart and dataend members, it is possible to compute a relative
sub-array position in the main *container* array using locateROI():
@code
Mat A = Mat::eye(10, 10, CV_32S);
// extracts A columns, 1 (inclusive) to 3 (exclusive).
Mat B = A(Range::all(), Range(1, 3));
// extracts B rows, 5 (inclusive) to 9 (exclusive).
// that is, C \~ A(Range(5, 9), Range(1, 3))
Mat C = B(Range(5, 9), Range::all());
Size size; Point ofs;
C.locateROI(size, ofs);
// size will be (width=10,height=10) and the ofs will be (x=1, y=5)
@endcode
As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted
sub-matrices.
- Make a header for user-allocated data. It can be useful to do the following:
-# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or
a processing module for gstreamer, and so on). For example:
@code
void process_video_frame(const unsigned char* pixels,
int width, int height, int step)
{
Mat img(height, width, CV_8UC3, pixels, step);
GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
}
@endcode
-# Quickly initialize small matrices and/or get a super-fast element access.
@code
double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
Mat M = Mat(3, 3, CV_64F, m).inv();
@endcode
.
Partial yet very common cases of this *user-allocated data* case are conversions from CvMat and
IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or
IplImage and the optional position indicating whether to copy the data or not.
@snippet samples/cpp/image.cpp iplimage
- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example:
@code
// create a double-precision identity matrix and add it to M.
M += Mat::eye(M.rows, M.cols, CV_64F);
@endcode
- Use a comma-separated initializer:
@code
// create a 3x3 double-precision identity matrix
Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
@endcode
With this approach, you first call a constructor of the Mat class with the proper parameters, and
then you just put `<< operator` followed by comma-separated values that can be constants,
variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation
errors.
Once the array is created, it is automatically managed via a reference-counting mechanism. If the
array header is built on top of user-allocated data, you should handle the data by yourself. The
array data is deallocated when no one points to it. If you want to release the data pointed by a
array header before the array destructor is called, use Mat::release().
The next important thing to learn about the array class is element access. This manual already
described how to compute an address of each array element. Normally, you are not required to use the
formula directly in the code. If you know the array element type (which can be retrieved using the
method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as:
@code
M.at<double>(i,j) += 1.f;
@endcode
assuming that `M` is a double-precision floating-point array. There are several variants of the method
at for a different number of dimensions.
If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to
the row first, and then just use the plain C operator [] :
@code
// compute sum of positive matrix elements
// (assuming that M is a double-precision matrix)
double sum=0;
for(int i = 0; i < M.rows; i++)
{
const double* Mi = M.ptr<double>(i);
for(int j = 0; j < M.cols; j++)
sum += std::max(Mi[j], 0.);
}
@endcode
Some operations, like the one above, do not actually depend on the array shape. They just process
elements of an array one by one (or elements from multiple arrays that have the same coordinates,
for example, array addition). Such operations are called *element-wise*. It makes sense to check
whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If
yes, process them as a long single row:
@code
// compute the sum of positive matrix elements, optimized variant
double sum=0;
int cols = M.cols, rows = M.rows;
if(M.isContinuous())
{
cols *= rows;
rows = 1;
}
for(int i = 0; i < rows; i++)
{
const double* Mi = M.ptr<double>(i);
for(int j = 0; j < cols; j++)
sum += std::max(Mi[j], 0.);
}
@endcode
In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is
smaller, which is especially noticeable in case of small matrices.
Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
@code
// compute sum of positive matrix elements, iterator-based variant
double sum=0;
MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
for(; it != it_end; ++it)
sum += std::max(*it, 0.);
@endcode
The matrix iterators are random-access iterators, so they can be passed to any STL algorithm,
including std::sort().
@note Matrix Expressions and arithmetic see MatExpr
*/
class CV_EXPORTS Mat
{
public:
/**
These are various constructors that form a matrix. As noted in the AutomaticAllocation, often
the default constructor is enough, and the proper matrix will be allocated by an OpenCV function.
The constructed matrix can further be assigned to another matrix or matrix expression or can be
allocated with Mat::create . In the former case, the old content is de-referenced.
*/
Mat();
/** @overload
@param rows Number of rows in a 2D array.
@param cols Number of columns in a 2D array.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
*/
Mat(int rows, int cols, int type);
/** @overload
@param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
number of columns go in the reverse order.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
*/
Mat(Size size, int type);
/** @overload
@param rows Number of rows in a 2D array.
@param cols Number of columns in a 2D array.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param s An optional value to initialize each matrix element with. To set all the matrix elements to
the particular value after the construction, use the assignment operator
Mat::operator=(const Scalar& value) .
*/
Mat(int rows, int cols, int type, const Scalar& s);
/** @overload
@param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
number of columns go in the reverse order.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param s An optional value to initialize each matrix element with. To set all the matrix elements to
the particular value after the construction, use the assignment operator
Mat::operator=(const Scalar& value) .
*/
Mat(Size size, int type, const Scalar& s);
/** @overload
@param ndims Array dimensionality.
@param sizes Array of integers specifying an n-dimensional array shape.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
*/
Mat(int ndims, const int* sizes, int type);
/** @overload
@param sizes Array of integers specifying an n-dimensional array shape.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
*/
Mat(const std::vector<int>& sizes, int type);
/** @overload
@param ndims Array dimensionality.
@param sizes Array of integers specifying an n-dimensional array shape.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param s An optional value to initialize each matrix element with. To set all the matrix elements to
the particular value after the construction, use the assignment operator
Mat::operator=(const Scalar& value) .
*/
Mat(int ndims, const int* sizes, int type, const Scalar& s);
/** @overload
@param sizes Array of integers specifying an n-dimensional array shape.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param s An optional value to initialize each matrix element with. To set all the matrix elements to
the particular value after the construction, use the assignment operator
Mat::operator=(const Scalar& value) .
*/
Mat(const std::vector<int>& sizes, int type, const Scalar& s);
/** @overload
@param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
formed using such a constructor, you also modify the corresponding elements of m . If you want to
have an independent copy of the sub-array, use Mat::clone() .
*/
Mat(const Mat& m);
/** @overload
@param rows Number of rows in a 2D array.
@param cols Number of columns in a 2D array.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param data Pointer to the user data. Matrix constructors that take data and step parameters do not
allocate matrix data. Instead, they just initialize the matrix header that points to the specified
data, which means that no data is copied. This operation is very efficient and can be used to
process external data using OpenCV functions. The external data is not automatically deallocated, so
you should take care of it.
@param step Number of bytes each matrix row occupies. The value should include the padding bytes at
the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
*/
Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
/** @overload
@param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
number of columns go in the reverse order.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param data Pointer to the user data. Matrix constructors that take data and step parameters do not
allocate matrix data. Instead, they just initialize the matrix header that points to the specified
data, which means that no data is copied. This operation is very efficient and can be used to
process external data using OpenCV functions. The external data is not automatically deallocated, so
you should take care of it.
@param step Number of bytes each matrix row occupies. The value should include the padding bytes at
the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
*/
Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
/** @overload
@param ndims Array dimensionality.
@param sizes Array of integers specifying an n-dimensional array shape.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param data Pointer to the user data. Matrix constructors that take data and step parameters do not
allocate matrix data. Instead, they just initialize the matrix header that points to the specified
data, which means that no data is copied. This operation is very efficient and can be used to
process external data using OpenCV functions. The external data is not automatically deallocated, so
you should take care of it.
@param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
set to the element size). If not specified, the matrix is assumed to be continuous.
*/
Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
/** @overload
@param sizes Array of integers specifying an n-dimensional array shape.
@param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
@param data Pointer to the user data. Matrix constructors that take data and step parameters do not
allocate matrix data. Instead, they just initialize the matrix header that points to the specified
data, which means that no data is copied. This operation is very efficient and can be used to
process external data using OpenCV functions. The external data is not automatically deallocated, so
you should take care of it.
@param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
set to the element size). If not specified, the matrix is assumed to be continuous.
*/
Mat(const std::vector<int>& sizes, int type, void* data, const size_t* steps=0);
/** @overload
@param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
formed using such a constructor, you also modify the corresponding elements of m . If you want to
have an independent copy of the sub-array, use Mat::clone() .
@param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range
end is exclusive. Use Range::all() to take all the rows.
@param colRange Range of the m columns to take. Use Range::all() to take all the columns.
*/
Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
/** @overload
@param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
formed using such a constructor, you also modify the corresponding elements of m . If you want to
have an independent copy of the sub-array, use Mat::clone() .
@param roi Region of interest.
*/
Mat(const Mat& m, const Rect& roi);
/** @overload
@param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
formed using such a constructor, you also modify the corresponding elements of m . If you want to
have an independent copy of the sub-array, use Mat::clone() .
@param ranges Array of selected ranges of m along each dimensionality.
*/
Mat(const Mat& m, const Range* ranges);
/** @overload
@param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
formed using such a constructor, you also modify the corresponding elements of m . If you want to
have an independent copy of the sub-array, use Mat::clone() .
@param ranges Array of selected ranges of m along each dimensionality.
*/
Mat(const Mat& m, const std::vector<Range>& ranges);
/** @overload
@param vec STL vector whose elements form the matrix. The matrix has a single column and the number
of rows equal to the number of vector elements. Type of the matrix matches the type of vector
elements. The constructor can handle arbitrary types, for which there is a properly declared
DataType . This means that the vector elements must be primitive numbers or uni-type numerical
tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is
explicit. Since STL vectors are not automatically converted to Mat instances, you should write
Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements
will be added to the vector because it can potentially yield vector data reallocation, and, thus,
the matrix data pointer will be invalid.
@param copyData Flag to specify whether the underlying data of the STL vector should be copied
to (true) or shared with (false) the newly constructed matrix. When the data is copied, the
allocated buffer is managed using Mat reference counting mechanism. While the data is shared,
the reference counter is NULL, and you should not deallocate the data until the matrix is not
destructed.
*/
template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
#ifdef CV_CXX11
/** @overload
*/
template<typename _Tp, typename = typename std::enable_if<std::is_arithmetic<_Tp>::value>::type>
explicit Mat(const std::initializer_list<_Tp> list);
#endif
#ifdef CV_CXX_STD_ARRAY
/** @overload
*/
template<typename _Tp, size_t _Nm> explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false);
#endif
/** @overload
*/
template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
/** @overload
*/
template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
/** @overload
*/
template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
/** @overload
*/
template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
/** @overload
*/
template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
//! download data from GpuMat
explicit Mat(const cuda::GpuMat& m);
//! destructor - calls release()
~Mat();
/** @brief assignment operators
These are available assignment operators. Since they all are very different, make sure to read the
operator parameters description.
@param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that
no data is copied but the data is shared and the reference counter, if any, is incremented. Before
assigning new data, the old data is de-referenced via Mat::release .
*/
Mat& operator = (const Mat& m);
/** @overload
@param expr Assigned matrix expression object. As opposite to the first form of the assignment
operation, the second form can reuse already allocated matrix if it has the right size and type to
fit the matrix expression result. It is automatically handled by the real function that the matrix
expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of
automatic C reallocation.
*/
Mat& operator = (const MatExpr& expr);
//! retrieve UMat from Mat
UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
/** @brief Creates a matrix header for the specified matrix row.
The method makes a new header for the specified matrix row and returns it. This is an O(1)
operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
original matrix. Here is the example of one of the classical basic matrix processing operations,
axpy, used by LU and many other algorithms:
@code
inline void matrix_axpy(Mat& A, int i, int j, double alpha)
{
A.row(i) += A.row(j)*alpha;
}
@endcode
@note In the current implementation, the following code does not work as expected:
@code
Mat A;
...
A.row(i) = A.row(j); // will not work
@endcode
This happens because A.row(i) forms a temporary header that is further assigned to another header.
Remember that each of these operations is O(1), that is, no data is copied. Thus, the above
assignment is not true if you may have expected the j-th row to be copied to the i-th row. To
achieve that, you should either turn this simple assignment into an expression or use the
Mat::copyTo method:
@code
Mat A;
...
// works, but looks a bit obscure.
A.row(i) = A.row(j) + 0;
// this is a bit longer, but the recommended method.
A.row(j).copyTo(A.row(i));
@endcode
@param y A 0-based row index.
*/
Mat row(int y) const;
/** @brief Creates a matrix header for the specified matrix column.
The method makes a new header for the specified matrix column and returns it. This is an O(1)
operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
original matrix. See also the Mat::row description.
@param x A 0-based column index.
*/
Mat col(int x) const;
/** @brief Creates a matrix header for the specified row span.
The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and
Mat::col , this is an O(1) operation.
@param startrow An inclusive 0-based start index of the row span.
@param endrow An exclusive 0-based ending index of the row span.
*/
Mat rowRange(int startrow, int endrow) const;
/** @overload
@param r Range structure containing both the start and the end indices.
*/
Mat rowRange(const Range& r) const;
/** @brief Creates a matrix header for the specified column span.
The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and
Mat::col , this is an O(1) operation.
@param startcol An inclusive 0-based start index of the column span.
@param endcol An exclusive 0-based ending index of the column span.
*/
Mat colRange(int startcol, int endcol) const;
/** @overload
@param r Range structure containing both the start and the end indices.
*/
Mat colRange(const Range& r) const;
/** @brief Extracts a diagonal from a matrix
The method makes a new header for the specified matrix diagonal. The new matrix is represented as a
single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation.
@param d index of the diagonal, with the following values:
- `d=0` is the main diagonal.
- `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set
immediately below the main one.
- `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set
immediately above the main one.
For example:
@code
Mat m = (Mat_<int>(3,3) <<
1,2,3,
4,5,6,
7,8,9);
Mat d0 = m.diag(0);
Mat d1 = m.diag(1);
Mat d_1 = m.diag(-1);
@endcode
The resulting matrices are
@code
d0 =
[1;
5;
9]
d1 =
[2;
6]
d_1 =
[4;
8]
@endcode
*/
Mat diag(int d=0) const;
/** @brief creates a diagonal matrix
The method creates a square diagonal matrix from specified main diagonal.
@param d One-dimensional matrix that represents the main diagonal.
*/
static Mat diag(const Mat& d);
/** @brief Creates a full copy of the array and the underlying data.
The method creates a full copy of the array. The original step[] is not taken into account. So, the
array copy is a continuous array occupying total()*elemSize() bytes.
*/
Mat clone() const;
/** @brief Copies the matrix to another one.
The method copies the matrix data to another matrix. Before copying the data, the method invokes :
@code
m.create(this->size(), this->type());
@endcode
so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the
function does not handle the case of a partial overlap between the source and the destination
matrices.
When the operation mask is specified, if the Mat::create call shown above reallocates the matrix,
the newly allocated matrix is initialized with all zeros before copying the data.
@param m Destination matrix. If it does not have a proper size or type before the operation, it is
reallocated.
*/
void copyTo( OutputArray m ) const;
/** @overload
@param m Destination matrix. If it does not have a proper size or type before the operation, it is
reallocated.
@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
*/
void copyTo( OutputArray m, InputArray mask ) const;
/** @brief Converts an array to another data type with optional scaling.
The method converts source pixel values to the target data type. saturate_cast\<\> is applied at
the end to avoid possible overflows:
\f[m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) + \beta )\f]
@param m output matrix; if it does not have a proper size or type before the operation, it is
reallocated.
@param rtype desired output matrix type or, rather, the depth since the number of channels are the
same as the input has; if rtype is negative, the output matrix will have the same type as the input.
@param alpha optional scale factor.
@param beta optional delta added to the scaled values.
*/
void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
/** @brief Provides a functional form of convertTo.
This is an internally used method called by the @ref MatrixExpressions engine.
@param m Destination array.
@param type Desired destination array depth (or -1 if it should be the same as the source type).
*/
void assignTo( Mat& m, int type=-1 ) const;
/** @brief Sets all or some of the array elements to the specified value.
@param s Assigned scalar converted to the actual array type.
*/
Mat& operator = (const Scalar& s);
/** @brief Sets all or some of the array elements to the specified value.
This is an advanced variant of the Mat::operator=(const Scalar& s) operator.
@param value Assigned scalar converted to the actual array type.
@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels
*/
Mat& setTo(InputArray value, InputArray mask=noArray());
/** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data.
The method makes a new matrix header for \*this elements. The new matrix may have a different size
and/or different number of channels. Any combination is possible if:
- No extra elements are included into the new matrix and no elements are excluded. Consequently,
the product rows\*cols\*channels() must stay the same after the transformation.
- No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of
rows, or the operation changes the indices of elements row in some other way, the matrix must be
continuous. See Mat::isContinuous .
For example, if there is a set of 3D points stored as an STL vector, and you want to represent the
points as a 3xN matrix, do the following:
@code
std::vector<Point3f> vec;
...
Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
// Also, an O(1) operation
t(); // finally, transpose the Nx3 matrix.
// This involves copying all the elements
@endcode
@param cn New number of channels. If the parameter is 0, the number of channels remains the same.
@param rows New number of rows. If the parameter is 0, the number of rows remains the same.
*/
Mat reshape(int cn, int rows=0) const;
/** @overload */
Mat reshape(int cn, int newndims, const int* newsz) const;
/** @overload */
Mat reshape(int cn, const std::vector<int>& newshape) const;
/** @brief Transposes a matrix.
The method performs matrix transposition by means of matrix expressions. It does not perform the
actual transposition but returns a temporary matrix transposition object that can be further used as
a part of more complex matrix expressions or can be assigned to a matrix:
@code
Mat A1 = A + Mat::eye(A.size(), A.type())*lambda;
Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)
@endcode
*/
MatExpr t() const;
/** @brief Inverses a matrix.
The method performs a matrix inversion by means of matrix expressions. This means that a temporary
matrix inversion object is returned by the method and can be used further as a part of more complex
matrix expressions or can be assigned to a matrix.
@param method Matrix inversion method. One of cv::DecompTypes
*/
MatExpr inv(int method=DECOMP_LU) const;
/** @brief Performs an element-wise multiplication or division of the two matrices.
The method returns a temporary object encoding per-element array multiplication, with optional
scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator.
Example:
@code
Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
@endcode
@param m Another array of the same type and the same size as \*this, or a matrix expression.
@param scale Optional scale factor.
*/
MatExpr mul(InputArray m, double scale=1) const;
/** @brief Computes a cross-product of two 3-element vectors.
The method computes a cross-product of two 3-element vectors. The vectors must be 3-element
floating-point vectors of the same shape and size. The result is another 3-element vector of the
same shape and type as operands.
@param m Another cross-product operand.
*/
Mat cross(InputArray m) const;
/** @brief Computes a dot-product of two vectors.
The method computes a dot-product of two matrices. If the matrices are not single-column or
single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D
vectors. The vectors must have the same size and type. If the matrices have more than one channel,
the dot products from all the channels are summed together.
@param m another dot-product operand.
*/
double dot(InputArray m) const;
/** @brief Returns a zero array of the specified size and type.
The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant
array as a function parameter, part of a matrix expression, or as a matrix initializer. :
@code
Mat A;
A = Mat::zeros(3, 3, CV_32F);
@endcode
In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix.
Otherwise, the existing matrix A is filled with zeros.
@param rows Number of rows.
@param cols Number of columns.
@param type Created matrix type.
*/
static MatExpr zeros(int rows, int cols, int type);
/** @overload
@param size Alternative to the matrix size specification Size(cols, rows) .
@param type Created matrix type.
*/
static MatExpr zeros(Size size, int type);
/** @overload
@param ndims Array dimensionality.
@param sz Array of integers specifying the array shape.
@param type Created matrix type.
*/
static MatExpr zeros(int ndims, const int* sz, int type);
/** @brief Returns an array of all 1's of the specified size and type.
The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using
this method you can initialize an array with an arbitrary value, using the following Matlab idiom:
@code
Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.
@endcode
The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it
just remembers the scale factor (3 in this case) and use it when actually invoking the matrix
initializer.
@param rows Number of rows.
@param cols Number of columns.
@param type Created matrix type.
*/
static MatExpr ones(int rows, int cols, int type);
/** @overload
@param size Alternative to the matrix size specification Size(cols, rows) .
@param type Created matrix type.
*/
static MatExpr ones(Size size, int type);
/** @overload
@param ndims Array dimensionality.
@param sz Array of integers specifying the array shape.
@param type Created matrix type.
*/
static MatExpr ones(int ndims, const int* sz, int type);
/** @brief Returns an identity matrix of the specified size and type.
The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to
Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently:
@code
// make a 4x4 diagonal matrix with 0.1's on the diagonal.
Mat A = Mat::eye(4, 4, CV_32F)*0.1;
@endcode
@param rows Number of rows.
@param cols Number of columns.
@param type Created matrix type.
*/
static MatExpr eye(int rows, int cols, int type);
/** @overload
@param size Alternative matrix size specification as Size(cols, rows) .
@param type Created matrix type.
*/
static MatExpr eye(Size size, int type);
/** @brief Allocates new array data if needed.
This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays
call this method for each output array. The method uses the following algorithm:
-# If the current array shape and the type match the new ones, return immediately. Otherwise,
de-reference the previous data by calling Mat::release.
-# Initialize the new header.
-# Allocate the new data of total()\*elemSize() bytes.
-# Allocate the new, associated with the data, reference counter and set it to 1.
Such a scheme makes the memory management robust and efficient at the same time and helps avoid
extra typing for you. This means that usually there is no need to explicitly allocate output arrays.
That is, instead of writing:
@code
Mat color;
...
Mat gray(color.rows, color.cols, color.depth());
cvtColor(color, gray, COLOR_BGR2GRAY);
@endcode
you can simply write:
@code
Mat color;
...
Mat gray;
cvtColor(color, gray, COLOR_BGR2GRAY);
@endcode
because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array
internally.
@param rows New number of rows.
@param cols New number of columns.
@param type New matrix type.
*/
void create(int rows, int cols, int type);
/** @overload
@param size Alternative new matrix size specification: Size(cols, rows)
@param type New matrix type.
*/
void create(Size size, int type);
/** @overload
@param ndims New array dimensionality.
@param sizes Array of integers specifying a new array shape.
@param type New matrix type.
*/
void create(int ndims, const int* sizes, int type);
/** @overload
@param sizes Array of integers specifying a new array shape.
@param type New matrix type.
*/
void create(const std::vector<int>& sizes, int type);
/** @brief Increments the reference counter.
The method increments the reference counter associated with the matrix data. If the matrix header
points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no
effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It
is called implicitly by the matrix assignment operator. The reference counter increment is an atomic
operation on the platforms that support it. Thus, it is safe to operate on the same matrices
asynchronously in different threads.
*/
void addref();
/** @brief Decrements the reference counter and deallocates the matrix if needed.
The method decrements the reference counter associated with the matrix data. When the reference
counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers
are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the
reference counter is NULL, and the method has no effect in this case.
This method can be called manually to force the matrix data deallocation. But since this method is
automatically called in the destructor, or by any other method that changes the data pointer, it is
usually not needed. The reference counter decrement and check for 0 is an atomic operation on the
platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in
different threads.
*/
void release();
//! internal use function, consider to use 'release' method instead; deallocates the matrix data
void deallocate();
//! internal use function; properly re-allocates _size, _step arrays
void copySize(const Mat& m);
/** @brief Reserves space for the certain number of rows.
The method reserves space for sz rows. If the matrix already has enough space to store sz rows,
nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method
emulates the corresponding method of the STL vector class.
@param sz Number of rows.
*/
void reserve(size_t sz);
/** @brief Reserves space for the certain number of bytes.
The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes,
nothing happens. If matrix has to be reallocated its previous content could be lost.
@param sz Number of bytes.
*/
void reserveBuffer(size_t sz);
/** @brief Changes the number of matrix rows.
The methods change the number of matrix rows. If the matrix is reallocated, the first
min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL
vector class.
@param sz New number of rows.
*/
void resize(size_t sz);
/** @overload
@param sz New number of rows.
@param s Value assigned to the newly added elements.
*/
void resize(size_t sz, const Scalar& s);
//! internal function
void push_back_(const void* elem);
/** @brief Adds elements to the bottom of the matrix.
The methods add one or more elements to the bottom of the matrix. They emulate the corresponding
method of the STL vector class. When elem is Mat , its type and the number of columns must be the
same as in the container matrix.
@param elem Added element(s).
*/
template<typename _Tp> void push_back(const _Tp& elem);
/** @overload
@param elem Added element(s).
*/
template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
/** @overload
@param elem Added element(s).
*/
template<typename _Tp> void push_back(const std::vector<_Tp>& elem);
/** @overload
@param m Added line(s).
*/
void push_back(const Mat& m);
/** @brief Removes elements from the bottom of the matrix.
The method removes one or more rows from the bottom of the matrix.
@param nelems Number of removed rows. If it is greater than the total number of rows, an exception
is thrown.
*/
void pop_back(size_t nelems=1);
/** @brief Locates the matrix header within a parent matrix.
After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange,
Mat::colRange, and others, the resultant submatrix points just to the part of the original big
matrix. However, each submatrix contains information (represented by datastart and dataend
fields) that helps reconstruct the original matrix size and the position of the extracted
submatrix within the original matrix. The method locateROI does exactly that.
@param wholeSize Output parameter that contains the size of the whole matrix containing *this*
as a part.
@param ofs Output parameter that contains an offset of *this* inside the whole matrix.
*/
void locateROI( Size& wholeSize, Point& ofs ) const;
/** @brief Adjusts a submatrix size and position within the parent matrix.
The method is complimentary to Mat::locateROI . The typical use of these functions is to determine
the submatrix position within the parent matrix and then shift the position somehow. Typically, it
can be required for filtering operations when pixels outside of the ROI should be taken into
account. When all the method parameters are positive, the ROI needs to grow in all directions by the
specified amount, for example:
@code
A.adjustROI(2, 2, 2, 2);
@endcode
In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted
by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the
filtering with the 5x5 kernel.
adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the
adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is
located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not
be increased in the upward direction.
The function is used internally by the OpenCV filtering functions, like filter2D , morphological
operations, and so on.
@param dtop Shift of the top submatrix boundary upwards.
@param dbottom Shift of the bottom submatrix boundary downwards.
@param dleft Shift of the left submatrix boundary to the left.
@param dright Shift of the right submatrix boundary to the right.
@sa copyMakeBorder
*/
Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
/** @brief Extracts a rectangular submatrix.
The operators make a new header for the specified sub-array of \*this . They are the most
generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example,
`A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above,
the operators are O(1) operations, that is, no matrix data is copied.
@param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To
select all the rows, use Range::all().
@param colRange Start and end column of the extracted submatrix. The upper boundary is not included.
To select all the columns, use Range::all().
*/
Mat operator()( Range rowRange, Range colRange ) const;
/** @overload
@param roi Extracted submatrix specified as a rectangle.
*/
Mat operator()( const Rect& roi ) const;
/** @overload
@param ranges Array of selected ranges along each array dimension.
*/
Mat operator()( const Range* ranges ) const;
/** @overload
@param ranges Array of selected ranges along each array dimension.
*/
Mat operator()(const std::vector<Range>& ranges) const;
// //! converts header to CvMat; no data is copied
// operator CvMat() const;
// //! converts header to CvMatND; no data is copied
// operator CvMatND() const;
// //! converts header to IplImage; no data is copied
// operator IplImage() const;
template<typename _Tp> operator std::vector<_Tp>() const;
template<typename _Tp, int n> operator Vec<_Tp, n>() const;
template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
#endif
/** @brief Reports whether the matrix is continuous or not.
The method returns true if the matrix elements are stored continuously without gaps at the end of
each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous.
Matrices created with Mat::create are always continuous. But if you extract a part of the matrix
using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data,
such matrices may no longer have this property.
The continuity position is stored as a bit in the Mat::flags field and is computed automatically when
you construct a matrix header. Thus, the continuity check is a very fast operation, though
theoretically it could be done as follows:
@code
// alternative implementation of Mat::isContinuous()
bool myCheckMatContinuity(const Mat& m)
{
//return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
return m.rows == 1 || m.step == m.cols*m.elemSize();
}
@endcode
The method is used in quite a few of OpenCV functions. The point is that element-wise operations
(such as arithmetic and logical operations, math functions, alpha blending, color space
transformations, and others) do not depend on the image geometry. Thus, if all the input and output
arrays are continuous, the functions can process them as very long single-row vectors. The example
below illustrates how an alpha-blending function can be implemented:
@code
template<typename T>
void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
{
const float alpha_scale = (float)std::numeric_limits<T>::max(),
inv_scale = 1.f/alpha_scale;
CV_Assert( src1.type() == src2.type() &&
src1.type() == CV_MAKETYPE(traits::Depth<T>::value, 4) &&
src1.size() == src2.size());
Size size = src1.size();
dst.create(size, src1.type());
// here is the idiom: check the arrays for continuity and,
// if this is the case,
// treat the arrays as 1D vectors
if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
{
size.width *= size.height;
size.height = 1;
}
size.width *= 4;
for( int i = 0; i < size.height; i++ )
{
// when the arrays are continuous,
// the outer loop is executed only once
const T* ptr1 = src1.ptr<T>(i);
const T* ptr2 = src2.ptr<T>(i);
T* dptr = dst.ptr<T>(i);
for( int j = 0; j < size.width; j += 4 )
{
float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
}
}
}
@endcode
This approach, while being very simple, can boost the performance of a simple element-operation by
10-20 percents, especially if the image is rather small and the operation is quite simple.
Another OpenCV idiom in this function, a call of Mat::create for the destination array, that
allocates the destination array unless it already has the proper size and type. And while the newly
allocated arrays are always continuous, you still need to check the destination array because
Mat::create does not always allocate a new matrix.
*/
bool isContinuous() const;
//! returns true if the matrix is a submatrix of another matrix
bool isSubmatrix() const;
/** @brief Returns the matrix element size in bytes.
The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 ,
the method returns 3\*sizeof(short) or 6.
*/
size_t elemSize() const;
/** @brief Returns the size of each matrix element channel in bytes.
The method returns the matrix element channel size in bytes, that is, it ignores the number of
channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2.
*/
size_t elemSize1() const;
/** @brief Returns the type of a matrix element.
The method returns a matrix element type. This is an identifier compatible with the CvMat type
system, like CV_16SC3 or 16-bit signed 3-channel array, and so on.
*/
int type() const;
/** @brief Returns the depth of a matrix element.
The method returns the identifier of the matrix element depth (the type of each individual channel).
For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of
matrix types contains the following values:
- CV_8U - 8-bit unsigned integers ( 0..255 )
- CV_8S - 8-bit signed integers ( -128..127 )
- CV_16U - 16-bit unsigned integers ( 0..65535 )
- CV_16S - 16-bit signed integers ( -32768..32767 )
- CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
- CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
- CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
*/
int depth() const;
/** @brief Returns the number of matrix channels.
The method returns the number of matrix channels.
*/
int channels() const;
/** @brief Returns a normalized step.
The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an
arbitrary matrix element.
*/
size_t step1(int i=0) const;
/** @brief Returns true if the array has no elements.
The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and
resize() methods `M.total() == 0` does not imply that `M.data == NULL`.
*/
bool empty() const;
/** @brief Returns the total number of array elements.
The method returns the number of array elements (a number of pixels if the array represents an
image).
*/
size_t total() const;
/** @brief Returns the total number of array elements.
The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim
*/
size_t total(int startDim, int endDim=INT_MAX) const;
//! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
/** @brief Returns a pointer to the specified matrix row.
The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in
Mat::isContinuous to know how to use these methods.
@param i0 A 0-based row index.
*/
uchar* ptr(int i0=0);
/** @overload */
const uchar* ptr(int i0=0) const;
/** @overload
@param row Index along the dimension 0
@param col Index along the dimension 1
*/
uchar* ptr(int row, int col);
/** @overload
@param row Index along the dimension 0
@param col Index along the dimension 1
*/
const uchar* ptr(int row, int col) const;
/** @overload */
uchar* ptr(int i0, int i1, int i2);
/** @overload */
const uchar* ptr(int i0, int i1, int i2) const;
/** @overload */
uchar* ptr(const int* idx);
/** @overload */
const uchar* ptr(const int* idx) const;
/** @overload */
template<int n> uchar* ptr(const Vec<int, n>& idx);
/** @overload */
template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
/** @overload */
template<typename _Tp> _Tp* ptr(int i0=0);
/** @overload */
template<typename _Tp> const _Tp* ptr(int i0=0) const;
/** @overload
@param row Index along the dimension 0
@param col Index along the dimension 1
*/
template<typename _Tp> _Tp* ptr(int row, int col);
/** @overload
@param row Index along the dimension 0
@param col Index along the dimension 1
*/
template<typename _Tp> const _Tp* ptr(int row, int col) const;
/** @overload */
template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
/** @overload */
template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
/** @overload */
template<typename _Tp> _Tp* ptr(const int* idx);
/** @overload */
template<typename _Tp> const _Tp* ptr(const int* idx) const;
/** @overload */
template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
/** @overload */
template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
/** @brief Returns a reference to the specified array element.
The template methods return a reference to the specified array element. For the sake of higher
performance, the index range checks are only performed in the Debug configuration.
Note that the variants with a single index (i) can be used to access elements of single-row or
single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and
B is an M x 1 integer matrix, you can simply write `A.at<float>(k+4)` and `B.at<int>(2*i+1)`
instead of `A.at<float>(0,k+4)` and `B.at<int>(2*i+1,0)`, respectively.
The example below initializes a Hilbert matrix:
@code
Mat H(100, 100, CV_64F);
for(int i = 0; i < H.rows; i++)
for(int j = 0; j < H.cols; j++)
H.at<double>(i,j)=1./(i+j+1);
@endcode
Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends
on the image from which you are trying to retrieve the data. The table below gives a better insight in this:
- If matrix is of type `CV_8U` then use `Mat.at<uchar>(y,x)`.
- If matrix is of type `CV_8S` then use `Mat.at<schar>(y,x)`.
- If matrix is of type `CV_16U` then use `Mat.at<ushort>(y,x)`.
- If matrix is of type `CV_16S` then use `Mat.at<short>(y,x)`.
- If matrix is of type `CV_32S` then use `Mat.at<int>(y,x)`.
- If matrix is of type `CV_32F` then use `Mat.at<float>(y,x)`.
- If matrix is of type `CV_64F` then use `Mat.at<double>(y,x)`.
@param i0 Index along the dimension 0
*/
template<typename _Tp> _Tp& at(int i0=0);
/** @overload
@param i0 Index along the dimension 0
*/
template<typename _Tp> const _Tp& at(int i0=0) const;
/** @overload
@param row Index along the dimension 0
@param col Index along the dimension 1
*/
template<typename _Tp> _Tp& at(int row, int col);
/** @overload
@param row Index along the dimension 0
@param col Index along the dimension 1
*/
template<typename _Tp> const _Tp& at(int row, int col) const;
/** @overload
@param i0 Index along the dimension 0
@param i1 Index along the dimension 1
@param i2 Index along the dimension 2
*/
template<typename _Tp> _Tp& at(int i0, int i1, int i2);
/** @overload
@param i0 Index along the dimension 0
@param i1 Index along the dimension 1
@param i2 Index along the dimension 2
*/
template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
/** @overload
@param idx Array of Mat::dims indices.
*/
template<typename _Tp> _Tp& at(const int* idx);
/** @overload
@param idx Array of Mat::dims indices.
*/
template<typename _Tp> const _Tp& at(const int* idx) const;
/** @overload */
template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
/** @overload */
template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
/** @overload
special versions for 2D arrays (especially convenient for referencing image pixels)
@param pt Element position specified as Point(j,i) .
*/
template<typename _Tp> _Tp& at(Point pt);
/** @overload
special versions for 2D arrays (especially convenient for referencing image pixels)
@param pt Element position specified as Point(j,i) .
*/
template<typename _Tp> const _Tp& at(Point pt) const;
/** @brief Returns the matrix iterator and sets it to the first matrix element.
The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very
similar to the use of bi-directional STL iterators. In the example below, the alpha blending
function is rewritten using the matrix iterators:
@code
template<typename T>
void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
{
typedef Vec<T, 4> VT;
const float alpha_scale = (float)std::numeric_limits<T>::max(),
inv_scale = 1.f/alpha_scale;
CV_Assert( src1.type() == src2.type() &&
src1.type() == traits::Type<VT>::value &&
src1.size() == src2.size());
Size size = src1.size();
dst.create(size, src1.type());
MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
MatConstIterator_<VT> it2 = src2.begin<VT>();
MatIterator_<VT> dst_it = dst.begin<VT>();
for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
{
VT pix1 = *it1, pix2 = *it2;
float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
*dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
}
}
@endcode
*/
template<typename _Tp> MatIterator_<_Tp> begin();
template<typename _Tp> MatConstIterator_<_Tp> begin() const;
/** @brief Returns the matrix iterator and sets it to the after-last matrix element.
The methods return the matrix read-only or read-write iterators, set to the point following the last
matrix element.
*/
template<typename _Tp> MatIterator_<_Tp> end();
template<typename _Tp> MatConstIterator_<_Tp> end() const;
/** @brief Runs the given functor over all matrix elements in parallel.
The operation passed as argument has to be a function pointer, a function object or a lambda(C++11).
Example 1. All of the operations below put 0xFF the first channel of all matrix elements:
@code
Mat image(1920, 1080, CV_8UC3);
typedef cv::Point3_<uint8_t> Pixel;
// first. raw pointer access.
for (int r = 0; r < image.rows; ++r) {
Pixel* ptr = image.ptr<Pixel>(r, 0);
const Pixel* ptr_end = ptr + image.cols;
for (; ptr != ptr_end; ++ptr) {
ptr->x = 255;
}
}
// Using MatIterator. (Simple but there are a Iterator's overhead)
for (Pixel &p : cv::Mat_<Pixel>(image)) {
p.x = 255;
}
// Parallel execution with function object.
struct Operator {
void operator ()(Pixel &pixel, const int * position) {
pixel.x = 255;
}
};
image.forEach<Pixel>(Operator());
// Parallel execution using C++11 lambda.
image.forEach<Pixel>([](Pixel &p, const int * position) -> void {
p.x = 255;
});
@endcode
Example 2. Using the pixel's position:
@code
// Creating 3D matrix (255 x 255 x 255) typed uint8_t
// and initialize all elements by the value which equals elements position.
// i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
int sizes[] = { 255, 255, 255 };
typedef cv::Point3_<uint8_t> Pixel;
Mat_<Pixel> image = Mat::zeros(3, sizes, CV_8UC3);
image.forEach<Pixel>([&](Pixel& pixel, const int position[]) -> void {
pixel.x = position[0];
pixel.y = position[1];
pixel.z = position[2];
});
@endcode
*/
template<typename _Tp, typename Functor> void forEach(const Functor& operation);
/** @overload */
template<typename _Tp, typename Functor> void forEach(const Functor& operation) const;
#ifdef CV_CXX_MOVE_SEMANTICS
Mat(Mat&& m);
Mat& operator = (Mat&& m);
#endif
enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
/*! includes several bit-fields:
- the magic signature
- continuity position
- depth
- number of channels
*/
int flags;
//! the matrix dimensionality, >= 2
int dims;
//! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
int rows, cols;
//! pointer to the data
uchar* data;
//! helper fields used in locateROI and adjustROI
const uchar* datastart;
const uchar* dataend;
const uchar* datalimit;
//! custom allocator
MatAllocator* allocator;
//! and the standard allocator
static MatAllocator* getStdAllocator();
static MatAllocator* getDefaultAllocator();
static void setDefaultAllocator(MatAllocator* allocator);
//! interaction with UMat
UMatData* u;
MatSize size;
MatStep step;
protected:
template<typename _Tp, typename Functor> void forEach_impl(const Functor& operation);
};
///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
/** @brief Template matrix class derived from Mat
@code{.cpp}
template<typename _Tp> class Mat_ : public Mat
{
public:
// ... some specific methods
// and
// no new extra fields
};
@endcode
The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any
extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to
these two classes can be freely but carefully converted one to another. For example:
@code{.cpp}
// create a 100x100 8-bit matrix
Mat M(100,100,CV_8U);
// this will be compiled fine. no any data conversion will be done.
Mat_<float>& M1 = (Mat_<float>&)M;
// the program is likely to crash at the statement below
M1(99,99) = 1.f;
@endcode
While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element
access operations and if you know matrix type at the compilation time. Note that
`Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same
and run at the same speed, but the latter is certainly shorter:
@code{.cpp}
Mat_<double> M(20,20);
for(int i = 0; i < M.rows; i++)
for(int j = 0; j < M.cols; j++)
M(i,j) = 1./(i+j+1);
Mat E, V;
eigen(M,E,V);
cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
@endcode
To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter:
@code{.cpp}
// allocate a 320x240 color image and fill it with green (in RGB space)
Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
// now draw a diagonal white line
for(int i = 0; i < 100; i++)
img(i,i)=Vec3b(255,255,255);
// and now scramble the 2nd (red) channel of each pixel
for(int i = 0; i < img.rows; i++)
for(int j = 0; j < img.cols; j++)
img(i,j)[2] ^= (uchar)(i ^ j);
@endcode
Mat_ is fully compatible with C++11 range-based for loop. For example such loop
can be used to safely apply look-up table:
@code{.cpp}
void applyTable(Mat_<uchar>& I, const uchar* const table)
{
for(auto& pixel : I)
{
pixel = table[pixel];
}
}
@endcode
*/
template<typename _Tp> class Mat_ : public Mat
{
public:
typedef _Tp value_type;
typedef typename DataType<_Tp>::channel_type channel_type;
typedef MatIterator_<_Tp> iterator;
typedef MatConstIterator_<_Tp> const_iterator;
//! default constructor
Mat_();
//! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
Mat_(int _rows, int _cols);
//! constructor that sets each matrix element to specified value
Mat_(int _rows, int _cols, const _Tp& value);
//! equivalent to Mat(_size, DataType<_Tp>::type)
explicit Mat_(Size _size);
//! constructor that sets each matrix element to specified value
Mat_(Size _size, const _Tp& value);
//! n-dim array constructor
Mat_(int _ndims, const int* _sizes);
//! n-dim array constructor that sets each matrix element to specified value
Mat_(int _ndims, const int* _sizes, const _Tp& value);
//! copy/conversion contructor. If m is of different type, it's converted
Mat_(const Mat& m);
//! copy constructor
Mat_(const Mat_& m);
//! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
//! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
//! selects a submatrix
Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
//! selects a submatrix
Mat_(const Mat_& m, const Rect& roi);
//! selects a submatrix, n-dim version
Mat_(const Mat_& m, const Range* ranges);
//! selects a submatrix, n-dim version
Mat_(const Mat_& m, const std::vector<Range>& ranges);
//! from a matrix expression
explicit Mat_(const MatExpr& e);
//! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
#ifdef CV_CXX11
Mat_(std::initializer_list<_Tp> values);
#endif
#ifdef CV_CXX_STD_ARRAY
template <std::size_t _Nm> explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false);
#endif
Mat_& operator = (const Mat& m);
Mat_& operator = (const Mat_& m);
//! set all the elements to s.
Mat_& operator = (const _Tp& s);
//! assign a matrix expression
Mat_& operator = (const MatExpr& e);
//! iterators; they are smart enough to skip gaps in the end of rows
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
//! template methods for for operation over all matrix elements.
// the operations take care of skipping gaps in the end of rows (if any)
template<typename Functor> void forEach(const Functor& operation);
template<typename Functor> void forEach(const Functor& operation) const;
//! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
void create(int _rows, int _cols);
//! equivalent to Mat::create(_size, DataType<_Tp>::type)
void create(Size _size);
//! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
void create(int _ndims, const int* _sizes);
//! equivalent to Mat::release()
void release();
//! cross-product
Mat_ cross(const Mat_& m) const;
//! data type conversion
template<typename T2> operator Mat_<T2>() const;
//! overridden forms of Mat::row() etc.
Mat_ row(int y) const;
Mat_ col(int x) const;
Mat_ diag(int d=0) const;
Mat_ clone() const;
//! overridden forms of Mat::elemSize() etc.
size_t elemSize() const;
size_t elemSize1() const;
int type() const;
int depth() const;
int channels() const;
size_t step1(int i=0) const;
//! returns step()/sizeof(_Tp)
size_t stepT(int i=0) const;
//! overridden forms of Mat::zeros() etc. Data type is omitted, of course
static MatExpr zeros(int rows, int cols);
static MatExpr zeros(Size size);
static MatExpr zeros(int _ndims, const int* _sizes);
static MatExpr ones(int rows, int cols);
static MatExpr ones(Size size);
static MatExpr ones(int _ndims, const int* _sizes);
static MatExpr eye(int rows, int cols);
static MatExpr eye(Size size);
//! some more overriden methods
Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
Mat_ operator()( const Rect& roi ) const;
Mat_ operator()( const Range* ranges ) const;
Mat_ operator()(const std::vector<Range>& ranges) const;
//! more convenient forms of row and element access operators
_Tp* operator [](int y);
const _Tp* operator [](int y) const;
//! returns reference to the specified element
_Tp& operator ()(const int* idx);
//! returns read-only reference to the specified element
const _Tp& operator ()(const int* idx) const;
//! returns reference to the specified element
template<int n> _Tp& operator ()(const Vec<int, n>& idx);
//! returns read-only reference to the specified element
template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
//! returns reference to the specified element (1D case)
_Tp& operator ()(int idx0);
//! returns read-only reference to the specified element (1D case)
const _Tp& operator ()(int idx0) const;
//! returns reference to the specified element (2D case)
_Tp& operator ()(int row, int col);
//! returns read-only reference to the specified element (2D case)
const _Tp& operator ()(int row, int col) const;
//! returns reference to the specified element (3D case)
_Tp& operator ()(int idx0, int idx1, int idx2);
//! returns read-only reference to the specified element (3D case)
const _Tp& operator ()(int idx0, int idx1, int idx2) const;
_Tp& operator ()(Point pt);
const _Tp& operator ()(Point pt) const;
//! conversion to vector.
operator std::vector<_Tp>() const;
#ifdef CV_CXX_STD_ARRAY
//! conversion to array.
template<std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
#endif
//! conversion to Vec
template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
//! conversion to Matx
template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
#ifdef CV_CXX_MOVE_SEMANTICS
Mat_(Mat_&& m);
Mat_& operator = (Mat_&& m);
Mat_(Mat&& m);
Mat_& operator = (Mat&& m);
Mat_(MatExpr&& e);
#endif
};
typedef Mat_<uchar> Mat1b;
typedef Mat_<Vec2b> Mat2b;
typedef Mat_<Vec3b> Mat3b;
typedef Mat_<Vec4b> Mat4b;
typedef Mat_<short> Mat1s;
typedef Mat_<Vec2s> Mat2s;
typedef Mat_<Vec3s> Mat3s;
typedef Mat_<Vec4s> Mat4s;
typedef Mat_<ushort> Mat1w;
typedef Mat_<Vec2w> Mat2w;
typedef Mat_<Vec3w> Mat3w;
typedef Mat_<Vec4w> Mat4w;
typedef Mat_<int> Mat1i;
typedef Mat_<Vec2i> Mat2i;
typedef Mat_<Vec3i> Mat3i;
typedef Mat_<Vec4i> Mat4i;
typedef Mat_<float> Mat1f;
typedef Mat_<Vec2f> Mat2f;
typedef Mat_<Vec3f> Mat3f;
typedef Mat_<Vec4f> Mat4f;
typedef Mat_<double> Mat1d;
typedef Mat_<Vec2d> Mat2d;
typedef Mat_<Vec3d> Mat3d;
typedef Mat_<Vec4d> Mat4d;
/** @todo document */
class CV_EXPORTS UMat
{
public:
//! default constructor
UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT);
//! constructs 2D matrix of the specified size and type
// (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
//! constucts 2D matrix and fills it with the specified value _s.
UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
//! constructs n-dimensional matrix
UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
//! copy constructor
UMat(const UMat& m);
//! creates a matrix header for a part of the bigger matrix
UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
UMat(const UMat& m, const Rect& roi);
UMat(const UMat& m, const Range* ranges);
UMat(const UMat& m, const std::vector<Range>& ranges);
//! builds matrix from std::vector with or without copying the data
template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
//! builds matrix from cv::Vec; the data is copied by default
template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true);
//! builds matrix from cv::Matx; the data is copied by default
template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
//! builds matrix from a 2D point
template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
//! builds matrix from a 3D point
template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
//! builds matrix from comma initializer
template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
//! destructor - calls release()
~UMat();
//! assignment operators
UMat& operator = (const UMat& m);
Mat getMat(int flags) const;
//! returns a new matrix header for the specified row
UMat row(int y) const;
//! returns a new matrix header for the specified column
UMat col(int x) const;
//! ... for the specified row span
UMat rowRange(int startrow, int endrow) const;
UMat rowRange(const Range& r) const;
//! ... for the specified column span
UMat colRange(int startcol, int endcol) const;
UMat colRange(const Range& r) const;
//! ... for the specified diagonal
//! (d=0 - the main diagonal,
//! >0 - a diagonal from the upper half,
//! <0 - a diagonal from the lower half)
UMat diag(int d=0) const;
//! constructs a square diagonal matrix which main diagonal is vector "d"
static UMat diag(const UMat& d);
//! returns deep copy of the matrix, i.e. the data is copied
UMat clone() const;
//! copies the matrix content to "m".
// It calls m.create(this->size(), this->type()).
void copyTo( OutputArray m ) const;
//! copies those matrix elements to "m" that are marked with non-zero mask elements.
void copyTo( OutputArray m, InputArray mask ) const;
//! converts matrix to another datatype with optional scaling. See cvConvertScale.
void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
void assignTo( UMat& m, int type=-1 ) const;
//! sets every matrix element to s
UMat& operator = (const Scalar& s);
//! sets some of the matrix elements to s, according to the mask
UMat& setTo(InputArray value, InputArray mask=noArray());
//! creates alternative matrix header for the same data, with different
// number of channels and/or different number of rows. see cvReshape.
UMat reshape(int cn, int rows=0) const;
UMat reshape(int cn, int newndims, const int* newsz) const;
//! matrix transposition by means of matrix expressions
UMat t() const;
//! matrix inversion by means of matrix expressions
UMat inv(int method=DECOMP_LU) const;
//! per-element matrix multiplication by means of matrix expressions
UMat mul(InputArray m, double scale=1) const;
//! computes dot-product
double dot(InputArray m) const;
//! Matlab-style matrix initialization
static UMat zeros(int rows, int cols, int type);
static UMat zeros(Size size, int type);
static UMat zeros(int ndims, const int* sz, int type);
static UMat ones(int rows, int cols, int type);
static UMat ones(Size size, int type);
static UMat ones(int ndims, const int* sz, int type);
static UMat eye(int rows, int cols, int type);
static UMat eye(Size size, int type);
//! allocates new matrix data unless the matrix already has specified size and type.
// previous data is unreferenced if needed.
void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
void create(const std::vector<int>& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
//! increases the reference counter; use with care to avoid memleaks
void addref();
//! decreases reference counter;
// deallocates the data when reference counter reaches 0.
void release();
//! deallocates the matrix data
void deallocate();
//! internal use function; properly re-allocates _size, _step arrays
void copySize(const UMat& m);
//! locates matrix header within a parent matrix. See below
void locateROI( Size& wholeSize, Point& ofs ) const;
//! moves/resizes the current matrix ROI inside the parent matrix.
UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
//! extracts a rectangular sub-matrix
// (this is a generalized form of row, rowRange etc.)
UMat operator()( Range rowRange, Range colRange ) const;
UMat operator()( const Rect& roi ) const;
UMat operator()( const Range* ranges ) const;
UMat operator()(const std::vector<Range>& ranges) const;
//! returns true iff the matrix data is continuous
// (i.e. when there are no gaps between successive rows).
// similar to CV_IS_MAT_CONT(cvmat->type)
bool isContinuous() const;
//! returns true if the matrix is a submatrix of another matrix
bool isSubmatrix() const;
//! returns element size in bytes,
// similar to CV_ELEM_SIZE(cvmat->type)
size_t elemSize() const;
//! returns the size of element channel in bytes.
size_t elemSize1() const;
//! returns element type, similar to CV_MAT_TYPE(cvmat->type)
int type() const;
//! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
int depth() const;
//! returns element type, similar to CV_MAT_CN(cvmat->type)
int channels() const;
//! returns step/elemSize1()
size_t step1(int i=0) const;
//! returns true if matrix data is NULL
bool empty() const;
//! returns the total number of matrix elements
size_t total() const;
//! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
#ifdef CV_CXX_MOVE_SEMANTICS
UMat(UMat&& m);
UMat& operator = (UMat&& m);
#endif
/*! Returns the OpenCL buffer handle on which UMat operates on.
The UMat instance should be kept alive during the use of the handle to prevent the buffer to be
returned to the OpenCV buffer pool.
*/
void* handle(int accessFlags) const;
void ndoffset(size_t* ofs) const;
enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
/*! includes several bit-fields:
- the magic signature
- continuity position
- depth
- number of channels
*/
int flags;
//! the matrix dimensionality, >= 2
int dims;
//! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
int rows, cols;
//! custom allocator
MatAllocator* allocator;
UMatUsageFlags usageFlags; // usage flags for allocator
//! and the standard allocator
static MatAllocator* getStdAllocator();
// black-box container of UMat data
UMatData* u;
// offset of the submatrix (or 0)
size_t offset;
MatSize size;
MatStep step;
protected:
};
/////////////////////////// multi-dimensional sparse matrix //////////////////////////
/** @brief The class SparseMat represents multi-dimensional sparse numerical arrays.
Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only
non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its
stored elements can actually become 0. It is up to you to detect such elements and delete them
using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is
filled so that the search time is O(1) in average (regardless of whether element is there or not).
Elements can be accessed using the following methods:
- Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and
SparseMat::find), for example:
@code
const int dims = 5;
int size[5] = {10, 10, 10, 10, 10};
SparseMat sparse_mat(dims, size, CV_32F);
for(int i = 0; i < 1000; i++)
{
int idx[dims];
for(int k = 0; k < dims; k++)
idx[k] = rand() % size[k];
sparse_mat.ref<float>(idx) += 1.f;
}
cout << "nnz = " << sparse_mat.nzcount() << endl;
@endcode
- Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator.
That is, the iteration loop is familiar to STL users:
@code
// prints elements of a sparse floating-point matrix
// and the sum of elements.
SparseMatConstIterator_<float>
it = sparse_mat.begin<float>(),
it_end = sparse_mat.end<float>();
double s = 0;
int dims = sparse_mat.dims();
for(; it != it_end; ++it)
{
// print element indices and the element value
const SparseMat::Node* n = it.node();
printf("(");
for(int i = 0; i < dims; i++)
printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")");
printf(": %g\n", it.value<float>());
s += *it;
}
printf("Element sum is %g\n", s);
@endcode
If you run this loop, you will notice that elements are not enumerated in a logical order
(lexicographical, and so on). They come in the same order as they are stored in the hash table
(semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering.
Note, however, that pointers to the nodes may become invalid when you add more elements to the
matrix. This may happen due to possible buffer reallocation.
- Combination of the above 2 methods when you need to process 2 or more sparse matrices
simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2
floating-point sparse matrices:
@code
double cross_corr(const SparseMat& a, const SparseMat& b)
{
const SparseMat *_a = &a, *_b = &b;
// if b contains less elements than a,
// it is faster to iterate through b
if(_a->nzcount() > _b->nzcount())
std::swap(_a, _b);
SparseMatConstIterator_<float> it = _a->begin<float>(),
it_end = _a->end<float>();
double ccorr = 0;
for(; it != it_end; ++it)
{
// take the next element from the first matrix
float avalue = *it;
const Node* anode = it.node();
// and try to find an element with the same index in the second matrix.
// since the hash value depends only on the element index,
// reuse the hash value stored in the node
float bvalue = _b->value<float>(anode->idx,&anode->hashval);
ccorr += avalue*bvalue;
}
return ccorr;
}
@endcode
*/
class CV_EXPORTS SparseMat
{
public:
typedef SparseMatIterator iterator;
typedef SparseMatConstIterator const_iterator;
enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
//! the sparse matrix header
struct CV_EXPORTS Hdr
{
Hdr(int _dims, const int* _sizes, int _type);
void clear();
int refcount;
int dims;
int valueOffset;
size_t nodeSize;
size_t nodeCount;
size_t freeList;
std::vector<uchar> pool;
std::vector<size_t> hashtab;
int size[MAX_DIM];
};
//! sparse matrix node - element of a hash table
struct CV_EXPORTS Node
{
//! hash value
size_t hashval;
//! index of the next node in the same hash table entry
size_t next;
//! index of the matrix element
int idx[MAX_DIM];
};
/** @brief Various SparseMat constructors.
*/
SparseMat();
/** @overload
@param dims Array dimensionality.
@param _sizes Sparce matrix size on all dementions.
@param _type Sparse matrix data type.
*/
SparseMat(int dims, const int* _sizes, int _type);
/** @overload
@param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
to sparse representation.
*/
SparseMat(const SparseMat& m);
/** @overload
@param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
to sparse representation.
*/
explicit SparseMat(const Mat& m);
//! the destructor
~SparseMat();
//! assignment operator. This is O(1) operation, i.e. no data is copied
SparseMat& operator = (const SparseMat& m);
//! equivalent to the corresponding constructor
SparseMat& operator = (const Mat& m);
//! creates full copy of the matrix
SparseMat clone() const;
//! copies all the data to the destination matrix. All the previous content of m is erased
void copyTo( SparseMat& m ) const;
//! converts sparse matrix to dense matrix.
void copyTo( Mat& m ) const;
//! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
//! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
/*!
@param [out] m - output matrix; if it does not have a proper size or type before the operation,
it is reallocated
@param [in] rtype - desired output matrix type or, rather, the depth since the number of channels
are the same as the input has; if rtype is negative, the output matrix will have the
same type as the input.
@param [in] alpha - optional scale factor
@param [in] beta - optional delta added to the scaled values
*/
void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
// not used now
void assignTo( SparseMat& m, int type=-1 ) const;
//! reallocates sparse matrix.
/*!
If the matrix already had the proper size and type,
it is simply cleared with clear(), otherwise,
the old matrix is released (using release()) and the new one is allocated.
*/
void create(int dims, const int* _sizes, int _type);
//! sets all the sparse matrix elements to 0, which means clearing the hash table.
void clear();
//! manually increments the reference counter to the header.
void addref();
// decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
void release();
//! converts sparse matrix to the old-style representation; all the elements are copied.
//operator CvSparseMat*() const;
//! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
size_t elemSize() const;
//! returns elemSize()/channels()
size_t elemSize1() const;
//! returns type of sparse matrix elements
int type() const;
//! returns the depth of sparse matrix elements
int depth() const;
//! returns the number of channels
int channels() const;
//! returns the array of sizes, or NULL if the matrix is not allocated
const int* size() const;
//! returns the size of i-th matrix dimension (or 0)
int size(int i) const;
//! returns the matrix dimensionality
int dims() const;
//! returns the number of non-zero elements (=the number of hash table nodes)
size_t nzcount() const;
//! computes the element hash value (1D case)
size_t hash(int i0) const;
//! computes the element hash value (2D case)
size_t hash(int i0, int i1) const;
//! computes the element hash value (3D case)
size_t hash(int i0, int i1, int i2) const;
//! computes the element hash value (nD case)
size_t hash(const int* idx) const;
//!@{
/*!
specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
return pointer to the matrix element.
- if the element is there (it's non-zero), the pointer to it is returned
- if it's not there and createMissing=false, NULL pointer is returned
- if it's not there and createMissing=true, then the new element
is created and initialized with 0. Pointer to it is returned
- if the optional hashval pointer is not NULL, the element hash value is
not computed, but *hashval is taken instead.
*/
//! returns pointer to the specified element (1D case)
uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
//! returns pointer to the specified element (2D case)
uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
//! returns pointer to the specified element (3D case)
uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
//! returns pointer to the specified element (nD case)
uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
//!@}
//!@{
/*!
return read-write reference to the specified sparse matrix element.
`ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`.
The methods always return a valid reference.
If the element did not exist, it is created and initialiazed with 0.
*/
//! returns reference to the specified element (1D case)
template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
//! returns reference to the specified element (2D case)
template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
//! returns reference to the specified element (3D case)
template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
//! returns reference to the specified element (nD case)
template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
//!@}
//!@{
/*!
return value of the specified sparse matrix element.
`value<_Tp>(i0,...[,hashval])` is equivalent to
@code
{ const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
@endcode
That is, if the element did not exist, the methods return 0.
*/
//! returns value of the specified element (1D case)
template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
//! returns value of the specified element (2D case)
template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
//! returns value of the specified element (3D case)
template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
//! returns value of the specified element (nD case)
template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
//!@}
//!@{
/*!
Return pointer to the specified sparse matrix element if it exists
`find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`.
If the specified element does not exist, the methods return NULL.
*/
//! returns pointer to the specified element (1D case)
template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
//! returns pointer to the specified element (2D case)
template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
//! returns pointer to the specified element (3D case)
template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
//! returns pointer to the specified element (nD case)
template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
//!@}
//! erases the specified element (2D case)
void erase(int i0, int i1, size_t* hashval=0);
//! erases the specified element (3D case)
void erase(int i0, int i1, int i2, size_t* hashval=0);
//! erases the specified element (nD case)
void erase(const int* idx, size_t* hashval=0);
//!@{
/*!
return the sparse matrix iterator pointing to the first sparse matrix element
*/
//! returns the sparse matrix iterator at the matrix beginning
SparseMatIterator begin();
//! returns the sparse matrix iterator at the matrix beginning
template<typename _Tp> SparseMatIterator_<_Tp> begin();
//! returns the read-only sparse matrix iterator at the matrix beginning
SparseMatConstIterator begin() const;
//! returns the read-only sparse matrix iterator at the matrix beginning
template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
//!@}
/*!
return the sparse matrix iterator pointing to the element following the last sparse matrix element
*/
//! returns the sparse matrix iterator at the matrix end
SparseMatIterator end();
//! returns the read-only sparse matrix iterator at the matrix end
SparseMatConstIterator end() const;
//! returns the typed sparse matrix iterator at the matrix end
template<typename _Tp> SparseMatIterator_<_Tp> end();
//! returns the typed read-only sparse matrix iterator at the matrix end
template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
//! returns the value stored in the sparse martix node
template<typename _Tp> _Tp& value(Node* n);
//! returns the value stored in the sparse martix node
template<typename _Tp> const _Tp& value(const Node* n) const;
////////////// some internal-use methods ///////////////
Node* node(size_t nidx);
const Node* node(size_t nidx) const;
uchar* newNode(const int* idx, size_t hashval);
void removeNode(size_t hidx, size_t nidx, size_t previdx);
void resizeHashTab(size_t newsize);
int flags;
Hdr* hdr;
};
///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
/** @brief Template sparse n-dimensional array class derived from SparseMat
SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies
notation of some operations:
@code
int sz[] = {10, 20, 30};
SparseMat_<double> M(3, sz);
...
M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);
@endcode
*/
template<typename _Tp> class SparseMat_ : public SparseMat
{
public:
typedef SparseMatIterator_<_Tp> iterator;
typedef SparseMatConstIterator_<_Tp> const_iterator;
//! the default constructor
SparseMat_();
//! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type)
SparseMat_(int dims, const int* _sizes);
//! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
SparseMat_(const SparseMat& m);
//! the copy constructor. This is O(1) operation - no data is copied
SparseMat_(const SparseMat_& m);
//! converts dense matrix to the sparse form
SparseMat_(const Mat& m);
//! converts the old-style sparse matrix to the C++ class. All the elements are copied
//SparseMat_(const CvSparseMat* m);
//! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
SparseMat_& operator = (const SparseMat& m);
//! the assignment operator. This is O(1) operation - no data is copied
SparseMat_& operator = (const SparseMat_& m);
//! converts dense matrix to the sparse form
SparseMat_& operator = (const Mat& m);
//! makes full copy of the matrix. All the elements are duplicated
SparseMat_ clone() const;
//! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
void create(int dims, const int* _sizes);
//! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
//operator CvSparseMat*() const;
//! returns type of the matrix elements
int type() const;
//! returns depth of the matrix elements
int depth() const;
//! returns the number of channels in each matrix element
int channels() const;
//! equivalent to SparseMat::ref<_Tp>(i0, hashval)
_Tp& ref(int i0, size_t* hashval=0);
//! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
_Tp& ref(int i0, int i1, size_t* hashval=0);
//! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
_Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
//! equivalent to SparseMat::ref<_Tp>(idx, hashval)
_Tp& ref(const int* idx, size_t* hashval=0);
//! equivalent to SparseMat::value<_Tp>(i0, hashval)
_Tp operator()(int i0, size_t* hashval=0) const;
//! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
_Tp operator()(int i0, int i1, size_t* hashval=0) const;
//! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
_Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
//! equivalent to SparseMat::value<_Tp>(idx, hashval)
_Tp operator()(const int* idx, size_t* hashval=0) const;
//! returns sparse matrix iterator pointing to the first sparse matrix element
SparseMatIterator_<_Tp> begin();
//! returns read-only sparse matrix iterator pointing to the first sparse matrix element
SparseMatConstIterator_<_Tp> begin() const;
//! returns sparse matrix iterator pointing to the element following the last sparse matrix element
SparseMatIterator_<_Tp> end();
//! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
SparseMatConstIterator_<_Tp> end() const;
};
////////////////////////////////// MatConstIterator //////////////////////////////////
class CV_EXPORTS MatConstIterator
{
public:
typedef uchar* value_type;
typedef ptrdiff_t difference_type;
typedef const uchar** pointer;
typedef uchar* reference;
typedef std::random_access_iterator_tag iterator_category;
//! default constructor
MatConstIterator();
//! constructor that sets the iterator to the beginning of the matrix
MatConstIterator(const Mat* _m);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator(const Mat* _m, int _row, int _col=0);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator(const Mat* _m, Point _pt);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator(const Mat* _m, const int* _idx);
//! copy constructor
MatConstIterator(const MatConstIterator& it);
//! copy operator
MatConstIterator& operator = (const MatConstIterator& it);
//! returns the current matrix element
const uchar* operator *() const;
//! returns the i-th matrix element, relative to the current
const uchar* operator [](ptrdiff_t i) const;
//! shifts the iterator forward by the specified number of elements
MatConstIterator& operator += (ptrdiff_t ofs);
//! shifts the iterator backward by the specified number of elements
MatConstIterator& operator -= (ptrdiff_t ofs);
//! decrements the iterator
MatConstIterator& operator --();
//! decrements the iterator
MatConstIterator operator --(int);
//! increments the iterator
MatConstIterator& operator ++();
//! increments the iterator
MatConstIterator operator ++(int);
//! returns the current iterator position
Point pos() const;
//! returns the current iterator position
void pos(int* _idx) const;
ptrdiff_t lpos() const;
void seek(ptrdiff_t ofs, bool relative = false);
void seek(const int* _idx, bool relative = false);
const Mat* m;
size_t elemSize;
const uchar* ptr;
const uchar* sliceStart;
const uchar* sliceEnd;
};
////////////////////////////////// MatConstIterator_ /////////////////////////////////
/** @brief Matrix read-only iterator
*/
template<typename _Tp>
class MatConstIterator_ : public MatConstIterator
{
public:
typedef _Tp value_type;
typedef ptrdiff_t difference_type;
typedef const _Tp* pointer;
typedef const _Tp& reference;
typedef std::random_access_iterator_tag iterator_category;
//! default constructor
MatConstIterator_();
//! constructor that sets the iterator to the beginning of the matrix
MatConstIterator_(const Mat_<_Tp>* _m);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
//! copy constructor
MatConstIterator_(const MatConstIterator_& it);
//! copy operator
MatConstIterator_& operator = (const MatConstIterator_& it);
//! returns the current matrix element
const _Tp& operator *() const;
//! returns the i-th matrix element, relative to the current
const _Tp& operator [](ptrdiff_t i) const;
//! shifts the iterator forward by the specified number of elements
MatConstIterator_& operator += (ptrdiff_t ofs);
//! shifts the iterator backward by the specified number of elements
MatConstIterator_& operator -= (ptrdiff_t ofs);
//! decrements the iterator
MatConstIterator_& operator --();
//! decrements the iterator
MatConstIterator_ operator --(int);
//! increments the iterator
MatConstIterator_& operator ++();
//! increments the iterator
MatConstIterator_ operator ++(int);
//! returns the current iterator position
Point pos() const;
};
//////////////////////////////////// MatIterator_ ////////////////////////////////////
/** @brief Matrix read-write iterator
*/
template<typename _Tp>
class MatIterator_ : public MatConstIterator_<_Tp>
{
public:
typedef _Tp* pointer;
typedef _Tp& reference;
typedef std::random_access_iterator_tag iterator_category;
//! the default constructor
MatIterator_();
//! constructor that sets the iterator to the beginning of the matrix
MatIterator_(Mat_<_Tp>* _m);
//! constructor that sets the iterator to the specified element of the matrix
MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
//! constructor that sets the iterator to the specified element of the matrix
MatIterator_(Mat_<_Tp>* _m, Point _pt);
//! constructor that sets the iterator to the specified element of the matrix
MatIterator_(Mat_<_Tp>* _m, const int* _idx);
//! copy constructor
MatIterator_(const MatIterator_& it);
//! copy operator
MatIterator_& operator = (const MatIterator_<_Tp>& it );
//! returns the current matrix element
_Tp& operator *() const;
//! returns the i-th matrix element, relative to the current
_Tp& operator [](ptrdiff_t i) const;
//! shifts the iterator forward by the specified number of elements
MatIterator_& operator += (ptrdiff_t ofs);
//! shifts the iterator backward by the specified number of elements
MatIterator_& operator -= (ptrdiff_t ofs);
//! decrements the iterator
MatIterator_& operator --();
//! decrements the iterator
MatIterator_ operator --(int);
//! increments the iterator
MatIterator_& operator ++();
//! increments the iterator
MatIterator_ operator ++(int);
};
/////////////////////////////// SparseMatConstIterator ///////////////////////////////
/** @brief Read-Only Sparse Matrix Iterator.
Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
\code
SparseMatConstIterator it = m.begin(), it_end = m.end();
double s = 0;
CV_Assert( m.type() == CV_32F );
for( ; it != it_end; ++it )
s += it.value<float>();
\endcode
*/
class CV_EXPORTS SparseMatConstIterator
{
public:
//! the default constructor
SparseMatConstIterator();
//! the full constructor setting the iterator to the first sparse matrix element
SparseMatConstIterator(const SparseMat* _m);
//! the copy constructor
SparseMatConstIterator(const SparseMatConstIterator& it);
//! the assignment operator
SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
//! template method returning the current matrix element
template<typename _Tp> const _Tp& value() const;
//! returns the current node of the sparse matrix. it.node->idx is the current element index
const SparseMat::Node* node() const;
//! moves iterator to the previous element
SparseMatConstIterator& operator --();
//! moves iterator to the previous element
SparseMatConstIterator operator --(int);
//! moves iterator to the next element
SparseMatConstIterator& operator ++();
//! moves iterator to the next element
SparseMatConstIterator operator ++(int);
//! moves iterator to the element after the last element
void seekEnd();
const SparseMat* m;
size_t hashidx;
uchar* ptr;
};
////////////////////////////////// SparseMatIterator /////////////////////////////////
/** @brief Read-write Sparse Matrix Iterator
The class is similar to cv::SparseMatConstIterator,
but can be used for in-place modification of the matrix elements.
*/
class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
{
public:
//! the default constructor
SparseMatIterator();
//! the full constructor setting the iterator to the first sparse matrix element
SparseMatIterator(SparseMat* _m);
//! the full constructor setting the iterator to the specified sparse matrix element
SparseMatIterator(SparseMat* _m, const int* idx);
//! the copy constructor
SparseMatIterator(const SparseMatIterator& it);
//! the assignment operator
SparseMatIterator& operator = (const SparseMatIterator& it);
//! returns read-write reference to the current sparse matrix element
template<typename _Tp> _Tp& value() const;
//! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
SparseMat::Node* node() const;
//! moves iterator to the next element
SparseMatIterator& operator ++();
//! moves iterator to the next element
SparseMatIterator operator ++(int);
};
/////////////////////////////// SparseMatConstIterator_ //////////////////////////////
/** @brief Template Read-Only Sparse Matrix Iterator Class.
This is the derived from SparseMatConstIterator class that
introduces more convenient operator *() for accessing the current element.
*/
template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
{
public:
typedef std::forward_iterator_tag iterator_category;
//! the default constructor
SparseMatConstIterator_();
//! the full constructor setting the iterator to the first sparse matrix element
SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
SparseMatConstIterator_(const SparseMat* _m);
//! the copy constructor
SparseMatConstIterator_(const SparseMatConstIterator_& it);
//! the assignment operator
SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
//! the element access operator
const _Tp& operator *() const;
//! moves iterator to the next element
SparseMatConstIterator_& operator ++();
//! moves iterator to the next element
SparseMatConstIterator_ operator ++(int);
};
///////////////////////////////// SparseMatIterator_ /////////////////////////////////
/** @brief Template Read-Write Sparse Matrix Iterator Class.
This is the derived from cv::SparseMatConstIterator_ class that
introduces more convenient operator *() for accessing the current element.
*/
template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
{
public:
typedef std::forward_iterator_tag iterator_category;
//! the default constructor
SparseMatIterator_();
//! the full constructor setting the iterator to the first sparse matrix element
SparseMatIterator_(SparseMat_<_Tp>* _m);
SparseMatIterator_(SparseMat* _m);
//! the copy constructor
SparseMatIterator_(const SparseMatIterator_& it);
//! the assignment operator
SparseMatIterator_& operator = (const SparseMatIterator_& it);
//! returns the reference to the current element
_Tp& operator *() const;
//! moves the iterator to the next element
SparseMatIterator_& operator ++();
//! moves the iterator to the next element
SparseMatIterator_ operator ++(int);
};
/////////////////////////////////// NAryMatIterator //////////////////////////////////
/** @brief n-ary multi-dimensional array iterator.
Use the class to implement unary, binary, and, generally, n-ary element-wise operations on
multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some
may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of
the iterators after each small operations may be a big overhead. In this case consider using
NAryMatIterator to iterate through several matrices simultaneously as long as they have the same
geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`,
`it.planes[1]`,... will be the slices of the corresponding matrices.
The example below illustrates how you can compute a normalized and threshold 3D color histogram:
@code
void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb)
{
const int histSize[] = {N, N, N};
// make sure that the histogram has a proper size and type
hist.create(3, histSize, CV_32F);
// and clear it
hist = Scalar(0);
// the loop below assumes that the image
// is a 8-bit 3-channel. check it.
CV_Assert(image.type() == CV_8UC3);
MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
it_end = image.end<Vec3b>();
for( ; it != it_end; ++it )
{
const Vec3b& pix = *it;
hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
}
minProb *= image.rows*image.cols;
// initialize iterator (the style is different from STL).
// after initialization the iterator will contain
// the number of slices or planes the iterator will go through.
// it simultaneously increments iterators for several matrices
// supplied as a null terminated list of pointers
const Mat* arrays[] = {&hist, 0};
Mat planes[1];
NAryMatIterator itNAry(arrays, planes, 1);
double s = 0;
// iterate through the matrix. on each iteration
// itNAry.planes[i] (of type Mat) will be set to the current plane
// of the i-th n-dim matrix passed to the iterator constructor.
for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
{
threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO);
s += sum(itNAry.planes[0])[0];
}
s = 1./s;
itNAry = NAryMatIterator(arrays, planes, 1);
for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
itNAry.planes[0] *= s;
}
@endcode
*/
class CV_EXPORTS NAryMatIterator
{
public:
//! the default constructor
NAryMatIterator();
//! the full constructor taking arbitrary number of n-dim matrices
NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
//! the full constructor taking arbitrary number of n-dim matrices
NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
//! the separate iterator initialization method
void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
//! proceeds to the next plane of every iterated matrix
NAryMatIterator& operator ++();
//! proceeds to the next plane of every iterated matrix (postfix increment operator)
NAryMatIterator operator ++(int);
//! the iterated arrays
const Mat** arrays;
//! the current planes
Mat* planes;
//! data pointers
uchar** ptrs;
//! the number of arrays
int narrays;
//! the number of hyper-planes that the iterator steps through
size_t nplanes;
//! the size of each segment (in elements)
size_t size;
protected:
int iterdepth;
size_t idx;
};
///////////////////////////////// Matrix Expressions /////////////////////////////////
class CV_EXPORTS MatOp
{
public:
MatOp();
virtual ~MatOp();
virtual bool elementWise(const MatExpr& expr) const;
virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
virtual void roi(const MatExpr& expr, const Range& rowRange,
const Range& colRange, MatExpr& res) const;
virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
virtual void abs(const MatExpr& expr, MatExpr& res) const;
virtual void transpose(const MatExpr& expr, MatExpr& res) const;
virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
virtual Size size(const MatExpr& expr) const;
virtual int type(const MatExpr& expr) const;
};
/** @brief Matrix expression representation
@anchor MatrixExpressions
This is a list of implemented matrix operations that can be combined in arbitrary complex
expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a
real-valued scalar ( double )):
- Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A`
- Scaling: `A*alpha`
- Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A`
- Matrix multiplication: `A*B`
- Transposition: `A.t()` (means A<sup>T</sup>)
- Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
`A.inv([method]) (~ A<sup>-1</sup>)`, `A.inv([method])*B (~ X: AX=B)`
- Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of
`>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose
elements are set to 255 (if the particular element or pair of elements satisfy the condition) or
0.
- Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of
`&`, `|`, `^`.
- Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)`
- Element-wise absolute value: `abs(A)`
- Cross-product, dot-product: `A.cross(B)`, `A.dot(B)`
- Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm,
mean, sum, countNonZero, trace, determinant, repeat, and others.
- Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated
initializers, matrix constructors and operators that extract sub-matrices (see Mat description).
- Mat_<destination_type>() constructors to cast the result to the proper type.
@note Comma-separated initializers and probably some other operations may require additional
explicit Mat() or Mat_<T>() constructor calls to resolve a possible ambiguity.
Here are examples of matrix expressions:
@code
// compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD)
SVD svd(A);
Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t();
// compute the new vector of parameters in the Levenberg-Marquardt algorithm
x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err);
// sharpen image using "unsharp mask" algorithm
Mat blurred; double sigma = 1, threshold = 5, amount = 1;
GaussianBlur(img, blurred, Size(), sigma, sigma);
Mat lowContrastMask = abs(img - blurred) < threshold;
Mat sharpened = img*(1+amount) + blurred*(-amount);
img.copyTo(sharpened, lowContrastMask);
@endcode
*/
class CV_EXPORTS MatExpr
{
public:
MatExpr();
explicit MatExpr(const Mat& m);
MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
operator Mat() const;
template<typename _Tp> operator Mat_<_Tp>() const;
Size size() const;
int type() const;
MatExpr row(int y) const;
MatExpr col(int x) const;
MatExpr diag(int d = 0) const;
MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
MatExpr operator()( const Rect& roi ) const;
MatExpr t() const;
MatExpr inv(int method = DECOMP_LU) const;
MatExpr mul(const MatExpr& e, double scale=1) const;
MatExpr mul(const Mat& m, double scale=1) const;
Mat cross(const Mat& m) const;
double dot(const Mat& m) const;
const MatOp* op;
int flags;
Mat a, b, c;
double alpha, beta;
Scalar s;
};
//! @} core_basic
//! @relates cv::MatExpr
//! @{
CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
CV_EXPORTS MatExpr operator - (const Mat& m);
CV_EXPORTS MatExpr operator - (const MatExpr& e);
CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator * (const Mat& a, double s);
CV_EXPORTS MatExpr operator * (double s, const Mat& a);
CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator / (const Mat& a, double s);
CV_EXPORTS MatExpr operator / (double s, const Mat& a);
CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator < (const Mat& a, double s);
CV_EXPORTS MatExpr operator < (double s, const Mat& a);
CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator == (const Mat& a, double s);
CV_EXPORTS MatExpr operator == (double s, const Mat& a);
CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator != (const Mat& a, double s);
CV_EXPORTS MatExpr operator != (double s, const Mat& a);
CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator > (const Mat& a, double s);
CV_EXPORTS MatExpr operator > (double s, const Mat& a);
CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
CV_EXPORTS MatExpr operator ~(const Mat& m);
CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
CV_EXPORTS MatExpr min(const Mat& a, double s);
CV_EXPORTS MatExpr min(double s, const Mat& a);
CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
CV_EXPORTS MatExpr max(const Mat& a, double s);
CV_EXPORTS MatExpr max(double s, const Mat& a);
/** @brief Calculates an absolute value of each matrix element.
abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms:
- C = abs(A-B) is equivalent to `absdiff(A, B, C)`
- C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)`
- C = `Mat_<Vec<uchar,n> >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha,
beta)`
The output matrix has the same size and the same type as the input one except for the last case,
where C is depth=CV_8U .
@param m matrix.
@sa @ref MatrixExpressions, absdiff, convertScaleAbs
*/
CV_EXPORTS MatExpr abs(const Mat& m);
/** @overload
@param e matrix expression.
*/
CV_EXPORTS MatExpr abs(const MatExpr& e);
//! @} relates cv::MatExpr
} // cv
#include "opencv2/core/mat.inl.hpp"
#endif // OPENCV_CORE_MAT_HPP
| [
"459103831@qq.com"
] | 459103831@qq.com |
cc877cfe33de32e0ae7938e5b1f0026d1d3c8c3e | 8df198126a11543066c64a98a9d5ee24c7fa7618 | /(((... All online judge practice and contest ...)))/@@Virtual Judge/contest-3/CodeForces 158B_B - Taxi.cpp | e6be1e18777e8e0b1af17e097f52c4736dbdb08b | [] | no_license | mehadi-trackrep/ACM_Programming_related | eef0933febf44e3b024bc45afb3195b854eba719 | 7303931aa9f2ab68d76bbe04b06157b00ac9f6a6 | refs/heads/master | 2021-10-09T03:15:09.188172 | 2018-12-20T09:35:22 | 2018-12-20T09:35:22 | 117,265,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
int x,total;
scanf("%d",&n);
map <int,int> mp;
for(int i=1; i<=n; i++){ ///AC
scanf("%d",&x);
mp[x]++;
}
int one,two,three,four;
one = mp[1];
two = mp[2];
three = mp[3];
four = mp[4];
total = four + two/2;
two %= 2;
if(one > 0 && three > 0){
if(one >= three){
one -= three;
total += three;
}
else{
total += three;
one = 0;
}
}
else
total += three;
if(one > 0 && two > 0){
if(one <= 2){
total++;
one = 0;
two = 0;
}
else{
two = 0;
one -= 2;
total++;
}
}
if(two > 0)
total++;
if(one > 0){
total += one/4;
one %= 4;
if(one > 0)
total++;
}
printf("%d\n",total);
return 0;
}
| [
"mehadi541@gmail.com"
] | mehadi541@gmail.com |
466efe62440ddb9304985fcf922a003bbdd6d477 | f7b567677e8c788210cb00aec02742f4442f59ab | /leetcode/leetcode/src.cpp | cc0ef8c99ea8dcee8a98a05acbbd2782a4b863a5 | [] | no_license | Expost/algorithmic_practice | 77d3994de37cba65e7c866117c0d6901009e2359 | 9b288558e5b6cbb819d8043a8d3689698cc1655f | refs/heads/master | 2020-07-30T06:50:58.794518 | 2020-07-12T17:13:20 | 2020-07-12T17:13:20 | 210,123,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | cpp | #include <stdio.h>
#include <string.h>
// 这道题跟青蛙跳楼梯一样
// 下面这种方法重复运算太多,因此需要优化
//int climbStairs(int n) {
// if (n == 0) {
// return 0;
// }
//
// if (n == 1) {
// return 1;
// }
//
// if (n == 2) {
// return 2;
// }
//
// return climbStairs(n - 1) + climbStairs(n - 2);
//}
// 优化的第一种方法是将重叠问题进行备份
// 这种方式占的内存比较多
//int interClimbStairs(int *data, int n) {
// if (data[n] != 0) {
// return data[n];
// }
//
// data[n] = interClimbStairs(data, n - 1) + interClimbStairs(data, n - 2);
// return data[n];
//}
//
//int climbStairs(int n) {
// if (n == 0) return 0;
// if (n == 1) return 1;
// if (n == 2) return 2;
//
// int *data = new int[n + 1];
// memset(data, 0, sizeof(int) * (n + 1));
// data[1] = 1;
// data[2] = 2;
//
// auto value = interClimbStairs(data, n);
// delete[] data;
// return value;
//}
// 仔细分析会发现,实际上只有当前状态的前两个状态的值,如果使用迭代由底向上将会容易很多
int climbStairs(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
int a = 1;
int b = 2;
int v = 0;
for (int i = 3; i <= n; i++) {
v = a + b;
a = b;
b = v;
}
return v;
}
int main() {
int ret = 0;
ret = climbStairs(1);
printf("ret %d\n", ret);
ret = climbStairs(3);
printf("ret %d\n", ret);
ret = climbStairs(5);
printf("ret %d\n", ret);
ret = climbStairs(44);
printf("ret %d\n", ret);
return 0;
} | [
"renyili@tencent.com"
] | renyili@tencent.com |
1dbbd79c14eed4d6c55899d4a726d58ec718af7d | 4bea57e631734f8cb1c230f521fd523a63c1ff23 | /projects/openfoam/rarefied-flows/impingment/sims/test/nozzle1/7.96/uniform/time | 02aea29b4cfbdc7be2882e21e31645f2c80a4ebd | [] | no_license | andytorrestb/cfal | 76217f77dd43474f6b0a7eb430887e8775b78d7f | 730fb66a3070ccb3e0c52c03417e3b09140f3605 | refs/heads/master | 2023-07-04T01:22:01.990628 | 2021-08-01T15:36:17 | 2021-08-01T15:36:17 | 294,183,829 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "7.96/uniform";
object time;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
value 7.95999999999776264;
name "7.96";
index 79600;
deltaT 0.0001;
deltaT0 0.0001;
// ************************************************************************* //
| [
"andytorrestb@gmail.com"
] | andytorrestb@gmail.com | |
79c9c3203866f4db2016f42ac82dced4069f905e | 9ff35738af78a2a93741f33eeb639d22db461c5f | /.build/Android-Debug/jni/app/Experimental.Physics.Friction__float2.cpp | 1c45c8fc5f1b567c3ce66fb3d7fb98b4d566b3f6 | [] | no_license | shingyho4/FuseProject-Minerals | aca37fbeb733974c1f97b1b0c954f4f660399154 | 643b15996e0fa540efca271b1d56cfd8736e7456 | refs/heads/master | 2016-09-06T11:19:06.904784 | 2015-06-15T09:28:09 | 2015-06-15T09:28:09 | 37,452,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,551 | cpp | // This file was generated based on 'C:\ProgramData\Uno\Packages\Experimental.Physics\0.1.0\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#include <app/Experimental.Physics.Friction__float2.h>
#include <app/Fuse.Internal.Blender__float2.h>
#include <app/Fuse.Internal.BlenderMap.h>
namespace app {
namespace Experimental {
namespace Physics {
Friction__float2__uType* Friction__float2__typeof()
{
static Friction__float2__uType* type;
if (::uEnterCriticalIfNull(&type))
{
type = (Friction__float2__uType*)::uAllocClassType(sizeof(Friction__float2__uType), "Experimental.Physics.Friction<float2>", ::uObject__typeof(), 2, 1);
type->__interface_0.__fp_get_Position = (::app::Uno::Float2(*)(void*))Friction__float2__get_Position;
type->__interface_0.__fp_set_Position = (void(*)(void*, ::app::Uno::Float2))Friction__float2__set_Position;
type->__interface_0.__fp_get_Velocity = (::app::Uno::Float2(*)(void*))Friction__float2__get_Velocity;
type->__interface_0.__fp_set_Velocity = (void(*)(void*, ::app::Uno::Float2))Friction__float2__set_Velocity;
type->__interface_1.__fp_Update = (void(*)(void*, double))Friction__float2__Update;
type->__interface_1.__fp_get_IsStatic = (bool(*)(void*))Friction__float2__get_IsStatic;
type->Implements[0] = ::app::Experimental::Physics::MotionSimulation__float2__typeof();
type->Implements[1] = ::app::Experimental::Physics::Simulation__typeof();
type->InterfaceOffsets[0] = offsetof(Friction__float2__uType, __interface_0);
type->InterfaceOffsets[1] = offsetof(Friction__float2__uType, __interface_1);
type->StrongRefOffsets[0] = offsetof(Friction__float2, _blender);
#ifdef U_DEBUG_MEM
type->StrongRefNames[0] = "_blender";
#endif
::uRetainObject(type);
::uExitCritical();
}
return type;
}
float Friction__float2__get_SpeedDropout(Friction__float2* __this)
{
return __this->_speedDropout;
}
void Friction__float2__set_SpeedDropout(Friction__float2* __this, float value)
{
__this->_speedDropout = value;
}
float Friction__float2__get_KineticDeceleration(Friction__float2* __this)
{
return __this->_kineticDeceleration;
}
void Friction__float2__set_KineticDeceleration(Friction__float2* __this, float value)
{
__this->_kineticDeceleration = value;
}
float Friction__float2__get_LowFluidDeceleration(Friction__float2* __this)
{
return __this->_lowFluidDeceleration;
}
void Friction__float2__set_LowFluidDeceleration(Friction__float2* __this, float value)
{
__this->_lowFluidDeceleration = value;
}
float Friction__float2__get_HighFluidDeceleration(Friction__float2* __this)
{
return __this->_highFluidDeceleration;
}
void Friction__float2__set_HighFluidDeceleration(Friction__float2* __this, float value)
{
__this->_highFluidDeceleration = value;
}
::app::Uno::Float2 Friction__float2__get_Velocity(Friction__float2* __this)
{
return __this->_velocity;
}
void Friction__float2__set_Velocity(Friction__float2* __this, ::app::Uno::Float2 value)
{
__this->_velocity = value;
__this->_isStatic = false;
}
::app::Uno::Float2 Friction__float2__get_Position(Friction__float2* __this)
{
return __this->_position;
}
void Friction__float2__set_Position(Friction__float2* __this, ::app::Uno::Float2 value)
{
__this->_position = value;
}
bool Friction__float2__get_IsStatic(Friction__float2* __this)
{
return __this->_isStatic;
}
Friction__float2* Friction__float2__CreatePixelFlat(::uStatic* __this)
{
Friction__float2* n = Friction__float2__New_1(NULL);
::uPtr< ::app::Experimental::Physics::Friction__float2*>(n)->SpeedDropout(25.0f);
n->KineticDeceleration(60.0f);
n->LowFluidDeceleration(1.5f);
n->HighFluidDeceleration(0.0f);
return n;
}
void Friction__float2__Update(Friction__float2* __this, double elapsed)
{
::app::Uno::Float2 step = ::uPtr< ::app::Fuse::Internal::Blender__float2*>(__this->_blender)->Weight(__this->_velocity, (float)elapsed);
__this->_position = ::uPtr< ::app::Fuse::Internal::Blender__float2*>(__this->_blender)->Add(__this->_position, step);
float linear = ::uPtr< ::app::Fuse::Internal::Blender__float2*>(__this->_blender)->Length(__this->_velocity);
if (linear < __this->_speedDropout)
{
__this->_velocity = ::uPtr< ::app::Fuse::Internal::Blender__float2*>(__this->_blender)->Zero();
__this->_isStatic = true;
return;
}
float fluid = __this->_kineticDeceleration + (linear * __this->_lowFluidDeceleration);
linear = linear + (-fluid * (float)elapsed);
if (linear < __this->_speedDropout)
{
__this->_velocity = ::uPtr< ::app::Fuse::Internal::Blender__float2*>(__this->_blender)->Zero();
__this->_isStatic = true;
return;
}
__this->_velocity = ::uPtr< ::app::Fuse::Internal::Blender__float2*>(__this->_blender)->UnitWeight(__this->_velocity, linear);
}
void Friction__float2___ObjInit(Friction__float2* __this)
{
__this->_blender = ::app::Fuse::Internal::BlenderMap__Get__float2(NULL);
__this->_speedDropout = 25.0f;
__this->_kineticDeceleration = 60.0f;
__this->_lowFluidDeceleration = 1.5f;
}
Friction__float2* Friction__float2__New_1(::uStatic* __this)
{
Friction__float2* inst = (::app::Experimental::Physics::Friction__float2*)::uAllocObject(sizeof(::app::Experimental::Physics::Friction__float2), ::app::Experimental::Physics::Friction__float2__typeof());
inst->_ObjInit();
return inst;
}
}}}
| [
"hyl.hsy@gmail.com"
] | hyl.hsy@gmail.com |
262aca675ec28f970f5fc7fe992f405d418dd8ce | afedeaa7b355e65109d4fc0e3e91be67e55a0558 | /shell/shell_main.cc | 5dace4695296e32cb4a8083d06877dc90b799f2d | [] | no_license | StuartHa/shell | 26cd1e89b21bb805a9d5ee2999b687a0fb0d33ea | 89579d55d765b0137e68426f9fb10bbb82131567 | refs/heads/master | 2020-07-06T10:24:42.690794 | 2016-09-10T23:59:27 | 2016-09-10T23:59:27 | 67,896,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,101 | cc | #include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <signal.h>
#include <unistd.h>
#include "job.h"
#include "shell.h"
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
static void handler(int sig) {
fprintf(stderr, "Process %ld received signal %d (%s)\n", (long) getpid(), sig, strsignal(sig));
}
int main(int argc, char* argv[], char* envp[]) {
// Setup signals, this probably doesn't belong here...
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = handler;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTSTP, &sa, NULL);
sigaction(SIGCONT, &sa, NULL);
sigaction(SIGTTIN, &sa, NULL);
Shell shell;
while (true) {
cout << "$ ";
string line;
std::getline(cin, line);
if (cin.eof()) {
break;
}
if (line == "") {
continue;
}
Job piped_cmds;
bool status = Job::Parse(line, &piped_cmds);
if (!status) {
cerr << "Error parsing command." << endl;
continue;
}
if (line == "exit")
break;
shell.Execute(piped_cmds);
}
return EXIT_SUCCESS;
}
| [
"me@stuart.pw"
] | me@stuart.pw |
72eb9bd5332d4492e2996d8939d7d8e8556e2e7c | aa0be8e15198d3302580470c73cb49513203c13b | /WindSim/src/3D/objectManager.cpp | 766bf032db7f0c16dca193378e2188751784de82 | [] | no_license | gudajan/Windsim | 0bf6c57d975c110ccdd7c822274923009dc7df9c | 5cc75deb9ea0b00739682dc48c0f4bb322e03276 | refs/heads/master | 2021-01-21T04:47:59.560952 | 2016-06-15T20:51:08 | 2016-06-15T20:51:08 | 45,236,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,252 | cpp | #include "objectManager.h"
#include "mesh3D.h"
#include "MeshActor.h"
#include "sky.h"
#include "skyActor.h"
#include "axes.h"
#include "axesActor.h"
#include "voxelGrid.h"
#include "voxelGridActor.h"
#include "dx11Renderer.h"
#include <d3d11.h>
#include <DirectXMath.h>
#include <DirectXPackedVector.h>
#include <limits>
using namespace DirectX;
ObjectManager::ObjectManager(DX11Renderer* renderer)
: m_hoveredId(0),
m_selectedIds(),
m_objects(),
m_actors(),
m_accessoryObjects(),
m_accessoryActors(),
m_renderer(renderer)
{
}
void ObjectManager::add(ID3D11Device* device, const QJsonObject& data)
{
int id = data["id"].toInt();
ObjectType type = stringToObjectType(data["type"].toString().toStdString());
const std::string& name = data["name"].toString().toStdString();
if (m_objects.find(id) == m_objects.end() && m_actors.find(id) == m_actors.end())
{
if (type == ObjectType::Mesh)
{
auto objIt = data.find("obj-file");
if (objIt == data.end())
{
throw std::invalid_argument("Failed to create Mesh object '" + name + "' because no OBJ-Path was given in 'data' variable!");
}
Mesh3D* obj = new Mesh3D(objIt->toString().toStdString(), m_renderer);
m_objects.emplace(id, std::shared_ptr<Object3D>(obj));
MeshActor* act = new MeshActor(*obj, id, name);
m_actors.emplace(id, std::shared_ptr<Actor>(act));
obj->create(device, false);
act->create(device);
}
else if (type == ObjectType::Sky)
{
Sky* obj = new Sky(m_renderer);
m_objects.emplace(id, std::shared_ptr<Object3D>(obj));
SkyActor* act = new SkyActor(*obj, id, name);
m_actors.emplace(id, std::shared_ptr<Actor>(act));
obj->create(device, true);
}
else if (type == ObjectType::CoordinateAxes)
{
Axes* obj = new Axes(m_renderer);
m_objects.emplace(id, std::shared_ptr<Object3D>(obj));
AxesActor* act = new AxesActor(*obj, id, name);
m_actors.emplace(id, std::shared_ptr<Actor>(act));
obj->create(device, true);
}
else if (type == ObjectType::VoxelGrid)
{
if (!data.contains("resolution") || !data.contains("gridSize"))
throw std::invalid_argument("Failed to create VoxelGrid object '" + name + "' because no resolution or gridSize was given in 'data' variable!");
QJsonObject resolution = data["resolution"].toObject();
XMUINT3 res(resolution["x"].toInt(), resolution["y"].toInt(), resolution["z"].toInt());
QJsonObject gridSize = data["gridSize"].toObject();
XMFLOAT3 vs(gridSize["x"].toDouble() / res.x, gridSize["y"].toDouble() / res.y, gridSize["z"].toDouble() / res.z);
VoxelGrid* obj = new VoxelGrid(this, data["windTunnelSettings"].toString(), res, vs, m_renderer);
m_objects.emplace(id, std::shared_ptr<Object3D>(obj));
VoxelGridActor* act = new VoxelGridActor(*obj, id, name);
m_actors.emplace(id, std::shared_ptr<Actor>(act));
obj->create(device, false);
}
else
{
throw std::runtime_error("Object '" + name + "' has type Invalid!");
}
modify(data); // Set initial values from the data
}
else
{
throw std::runtime_error("Failed to add object '" + name + "' with id " + std::to_string(id) + " as object with identical id already exists!");
}
}
void ObjectManager::remove(int id)
{
const auto object = m_objects.find(id);
if (object == m_objects.end())
throw std::runtime_error("Failed to remove object with id '" + std::to_string(id) + "' as the id was not found!");
object->second->release();
m_objects.erase(id);
m_actors.erase(id);
}
void ObjectManager::removeAll()
{
release(false);
m_objects.clear();
m_actors.clear();
}
void ObjectManager::triggerObjectFunction(const QJsonObject& data)
{
int id = data["id"].toInt();
auto it = m_actors.find(id);
if (it == m_actors.end())
{
throw std::runtime_error("Failed to trigger function of object with id '" + std::to_string(id) + "' as the id was not found!");
}
auto fIt = data.find("function");
if (fIt == data.end())
{
throw std::runtime_error("Failed to trigger function of object with id '" + std::to_string(id) + "' as the data did not contain 'function' key!");
}
if (fIt->toString() == "restartSimulation")
std::dynamic_pointer_cast<VoxelGridActor>(it->second)->getObject()->restartSimulation();
}
void ObjectManager::modify(const QJsonObject& data)
{
int id = data["id"].toInt();
ObjectType type = stringToObjectType(data["type"].toString().toStdString());
std::string name = data["name"].toString().toStdString();
auto it = m_actors.find(id);
if (it == m_actors.end())
{
throw std::runtime_error("Failed to modify object with id '" + std::to_string(id) + "' as the id was not found!");
}
Modifications mod = All;
if (data.contains("modifications"))
mod = Modifications(data["modifications"].toInt());
// Modify general data
bool render = data["enabled"].toBool();
bool oldRender = it->second->getRender();
it->second->setRender(render);
// Modify object specific data
if (type == ObjectType::Mesh)
{
QJsonObject jPos = data["position"].toObject();
XMFLOAT3 pos(jPos["x"].toDouble(), jPos["y"].toDouble(), jPos["z"].toDouble());
QJsonObject jScale = data["scaling"].toObject();
XMFLOAT3 scale(jScale["x"].toDouble(), jScale["y"].toDouble(), jScale["z"].toDouble());
QJsonObject jRot = data["rotation"].toObject();
XMFLOAT4 rot;
XMVECTOR axis = XMVectorSet(jRot["ax"].toDouble(), jRot["ay"].toDouble(), jRot["az"].toDouble(), 0.0);
if (XMVector3Equal(axis, XMVectorZero()))
XMStoreFloat4(&rot, XMQuaternionIdentity());
else
XMStoreFloat4(&rot, XMQuaternionRotationAxis(axis, degToRad(jRot["angle"].toDouble())));
bool flatShading = data["shading"].toString() == "Smooth" ? false : true;
QJsonObject jCol = data["color"].toObject();
PackedVector::XMCOLOR col(jCol["r"].toInt() / 255.0f, jCol["g"].toInt() / 255.0f, jCol["b"].toInt() / 255.0f, 1.0f);
QJsonObject jAxis = data["localRotAxis"].toObject();
XMFLOAT3 localRotationAxis;
if (jAxis["enabled"].toBool())
localRotationAxis = XMFLOAT3(jAxis["x"].toDouble(), jAxis["y"].toDouble(), jAxis["z"].toDouble());
else
localRotationAxis = XMFLOAT3(0.0f, 0.0f, 0.0f);
std::shared_ptr<MeshActor> act = std::dynamic_pointer_cast<MeshActor>(it->second);
act->setPos(pos);
act->setScale(scale);
act->setRot(rot);
act->computeWorld();
act->setFlatShading(flatShading);
act->setColor(col);
act->setVoxelize(data["voxelize"].toBool());
if (mod.testFlag(DynamicsSettings))
{
act->setDynamics(data["dynamics"].toBool());
act->setDensity(data["density"].toDouble());
act->setLocalRotationAxis(localRotationAxis);
}
if (mod.testFlag(Scaling) || mod.testFlag(DynamicsSettings))
act->updateInertiaTensor();
if (mod.testFlag(ShowAccelArrow))
act->setShowAccelArrow(data["showAccelArrow"].toBool());
if (render != oldRender && !render)
{
m_selectedIds.erase(act->getId());
act->setSelected(false);
}
}
else if (type == ObjectType::VoxelGrid)
{
std::shared_ptr<VoxelGridActor> act = std::dynamic_pointer_cast<VoxelGridActor>(it->second);
QJsonObject jPos = data["position"].toObject();
XMFLOAT3 pos(jPos["x"].toDouble(), jPos["y"].toDouble(), jPos["z"].toDouble());
QJsonObject jRes = data["resolution"].toObject();
XMUINT3 res(jRes["x"].toInt(), jRes["y"].toInt(), jRes["z"].toInt());
QJsonObject jS = data["gridSize"].toObject();
XMFLOAT3 vs(jS["x"].toDouble() / res.x, jS["y"].toDouble() / res.y, jS["z"].toDouble() / res.z); // Calc voxel size from resolution and grid size
act->setPos(pos);
act->computeWorld();
act->getObject()->resize(res, vs);
if (mod.testFlag(VoxelSettings))
act->getObject()->setVoxelSettings(data["voxel"].toObject());
if (mod.testFlag(GlyphSettings))
act->getObject()->setGlyphSettings(data["glyphs"].toObject());
if (mod.testFlag(VolumeSettings))
act->getObject()->changeVolumeSettings(data["volume"].toObject());
if (mod.testFlag(WindTunnelSettings))
act->getObject()->changeSimSettings(data["windTunnelSettings"].toString());
if (mod.testFlag(SmokeSettings))
act->getObject()->changeSmokeSettings(data["smoke"].toObject());
if (mod.testFlag(LineSettings))
act->getObject()->changeLineSettings(data["lines"].toObject());
if (mod.testFlag(RunSimulation))
act->getObject()->runSimulation(data["runSimulation"].toBool());
}
}
void ObjectManager::render(ID3D11Device* device, ID3D11DeviceContext* context, const DirectX::XMFLOAT4X4& view, const DirectX::XMFLOAT4X4& projection, double elapsedTime)
{
for (const auto& actor : m_actors)
{
actor.second->render(device, context, view, projection, elapsedTime);
}
for (const auto& actor : m_accessoryActors)
{
actor.second->render(device, context, view, projection, elapsedTime);
}
for (const auto& actor : m_actors)
{
if (actor.second->getType() == ObjectType::VoxelGrid)
std::dynamic_pointer_cast<VoxelGridActor>(actor.second)->renderVolume(device, context, view, projection, elapsedTime);
}
}
void ObjectManager::initOpenCL()
{
for (const auto& actor : m_actors)
{
if (actor.second->getType() == ObjectType::VoxelGrid)
std::dynamic_pointer_cast<VoxelGridActor>(actor.second)->getObject()->reinitWindTunnel();
if (actor.second->getType() == ObjectType::Mesh)
std::dynamic_pointer_cast<MeshActor>(actor.second)->resetDynamics();
}
}
void ObjectManager::runSimulation(bool enabled)
{
for (const auto& actor : m_actors)
{
if (actor.second->getType() == ObjectType::VoxelGrid)
std::dynamic_pointer_cast<VoxelGridActor>(actor.second)->getObject()->runSimulationSync(enabled);
}
}
void ObjectManager::release(bool withAccessories)
{
for (const auto& object : m_objects)
{
object.second->release();
}
for (const auto& actor : m_actors)
{
if (actor.second->getType() == ObjectType::Mesh)
{
std::dynamic_pointer_cast<MeshActor>(actor.second)->release();
}
}
if (withAccessories)
{
for (const auto& object : m_accessoryObjects)
{
object.second->release();
}
}
}
void ObjectManager::voxelizeNextFrame()
{
for (const auto& act : m_actors)
{
if (act.second->getType() == ObjectType::VoxelGrid)
std::dynamic_pointer_cast<VoxelGridActor>(act.second)->getObject()->setVoxelize(true);
}
}
void ObjectManager::updateCursor(const XMFLOAT3& origin, const XMFLOAT3& direction, bool containsCursor)
{
float distance = std::numeric_limits<float>::infinity();
if (containsCursor) // Only check for intersection if cursor within 3D view
m_hoveredId = computeIntersection(origin, direction, distance);
else
m_hoveredId = 0;
}
bool ObjectManager::updateSelection(Selection op)
{
if (m_hoveredId) // Only change selection if clicked onto an object
{
std::unordered_set<int> ids = m_selectedIds;
if (op == Selection::Replace) // No modifier
{
m_selectedIds.clear();
m_selectedIds.insert(m_hoveredId);
}
else if (op == Selection::Switch) // Ctrl key is pressed
{
// If hovered id not removed from selection: insert it; otherwise: id removed as necessary
if (!m_selectedIds.erase(m_hoveredId))
m_selectedIds.insert(m_hoveredId);
}
else if (op == Selection::Clear)
{
m_selectedIds.clear();
}
bool changed = ids != m_selectedIds;
if (changed)
setSelected();
return changed;
}
return false;
}
void ObjectManager::setHovered()
{
// Set all Meshes to not hovered
for (auto& act : m_actors)
{
if (act.second->getType() == ObjectType::Mesh)
{
std::dynamic_pointer_cast<MeshActor>(act.second)->setHovered(false);
}
}
// If intersection found and its at a mesh -> set to be hovered
auto& act = m_actors.find(m_hoveredId);
if (act != m_actors.end() && act->second->getType() == ObjectType::Mesh)
std::dynamic_pointer_cast<MeshActor>(act->second)->setHovered(true);
}
void ObjectManager::addAccessoryObject(const std::string& name, std::shared_ptr<Object3D> obj, std::shared_ptr<Actor> act)
{
bool inserted = m_accessoryObjects.emplace(name, obj).second;
if (!inserted)
throw std::runtime_error("Failed to add accessory object '" + name + "' as identically named object already exists!");
m_accessoryActors.emplace(name, act);
}
int ObjectManager::computeIntersection(const DirectX::XMFLOAT3& origin, const DirectX::XMFLOAT3& direction, float& distance) const
{
float closestDist = std::numeric_limits<float>::infinity(); // The distance to the intersection, closest to the camera
int closestID = 0;
// Search for intersection, closes to the camera
for (auto& act : m_actors)
{
// Only enabled meshes are searched for intersections
if (act.second->getType() == ObjectType::Mesh && act.second->getRender())
{
float dist = std::numeric_limits<float>::infinity();
if (std::dynamic_pointer_cast<MeshActor>(act.second)->intersect(origin, direction, dist)) // If intersected -> maybe hovered
{
if (dist < closestDist) // If new intersection is closer than closest intersection up to now
{
closestDist = dist;
closestID = act.first;
}
}
}
}
distance = closestDist;
return closestID;
}
void ObjectManager::setSelected()
{
// Set made selection
for (auto& act : m_actors)
{
if (act.second->getType() == ObjectType::Mesh)
{
std::dynamic_pointer_cast<MeshActor>(act.second)->setSelected(false);
}
}
for (int id : m_selectedIds)
{
std::dynamic_pointer_cast<MeshActor>(m_actors.find(id)->second)->setSelected(true); // All ids belong to meshes
}
}
const void ObjectManager::setSelection(const std::unordered_set<int>& selection)
{
m_selectedIds.clear();
// Check which ids belong to meshes and add them if so
for (int id : selection)
{
std::shared_ptr<Actor> a = m_actors.find(id)->second;
if (a->getType() == ObjectType::Mesh && a->getRender())
m_selectedIds.insert(id);
}
}
void ObjectManager::log(const std::string& msg)
{
m_renderer->getLogger()->logit(QString::fromStdString(msg));
} | [
"krohn@in.tum.de"
] | krohn@in.tum.de |
b86b3c63603ffbacf7e56f964143a261b1ab8ece | ef4d8a0d5aa7cfa3e9d16c358a7c2c41424a1b07 | /src/alert.cpp | f584e3d9f8710b09cb92475041419e9803a43f53 | [
"MIT"
] | permissive | dutcoin/dutcoin | c9810befeb7cd8cbde9a6013f589cd845b7314fb | 7c68a7e7561ca1185603be614aeefc2a96d5d3c1 | refs/heads/main | 2023-03-19T22:59:41.281470 | 2021-03-21T00:51:01 | 2021-03-21T00:51:01 | 348,498,448 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,320 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018 The dutcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "alert.h"
#include "chainparams.h"
#include "clientversion.h"
#include "net.h"
#include "pubkey.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include <algorithm>
#include <map>
#include <stdint.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
using namespace std;
map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
void CUnsignedAlert::SetNull()
{
nVersion = 1;
nRelayUntil = 0;
nExpiration = 0;
nID = 0;
nCancel = 0;
setCancel.clear();
nMinVer = 0;
nMaxVer = 0;
setSubVer.clear();
nPriority = 0;
strComment.clear();
strStatusBar.clear();
strReserved.clear();
}
std::string CUnsignedAlert::ToString() const
{
std::string strSetCancel;
for (auto& n: setCancel)
strSetCancel += strprintf("%d ", n);
std::string strSetSubVer;
BOOST_FOREACH (std::string str, setSubVer)
strSetSubVer += "\"" + str + "\" ";
return strprintf(
"CAlert(\n"
" nVersion = %d\n"
" nRelayUntil = %d\n"
" nExpiration = %d\n"
" nID = %d\n"
" nCancel = %d\n"
" setCancel = %s\n"
" nMinVer = %d\n"
" nMaxVer = %d\n"
" setSubVer = %s\n"
" nPriority = %d\n"
" strComment = \"%s\"\n"
" strStatusBar = \"%s\"\n"
")\n",
nVersion,
nRelayUntil,
nExpiration,
nID,
nCancel,
strSetCancel,
nMinVer,
nMaxVer,
strSetSubVer,
nPriority,
strComment,
strStatusBar);
}
void CAlert::SetNull()
{
CUnsignedAlert::SetNull();
vchMsg.clear();
vchSig.clear();
}
bool CAlert::IsNull() const
{
return (nExpiration == 0);
}
uint256 CAlert::GetHash() const
{
return Hash(this->vchMsg.begin(), this->vchMsg.end());
}
bool CAlert::IsInEffect() const
{
return (GetAdjustedTime() < nExpiration);
}
bool CAlert::Cancels(const CAlert& alert) const
{
if (!IsInEffect())
return false; // this was a no-op before 31403
return (alert.nID <= nCancel || setCancel.count(alert.nID));
}
bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const
{
// TODO: rework for client-version-embedded-in-strSubVer ?
return (IsInEffect() &&
nMinVer <= nVersion && nVersion <= nMaxVer &&
(setSubVer.empty() || setSubVer.count(strSubVerIn)));
}
bool CAlert::AppliesToMe() const
{
return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
}
bool CAlert::RelayTo(CNode* pnode) const
{
if (!IsInEffect())
return false;
// don't relay to nodes which haven't sent their version message
if (pnode->nVersion == 0)
return false;
// returns true if wasn't already contained in the set
if (pnode->setKnown.insert(GetHash()).second) {
if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
AppliesToMe() ||
GetAdjustedTime() < nRelayUntil) {
pnode->PushMessage("alert", *this);
return true;
}
}
return false;
}
bool CAlert::CheckSignature() const
{
CPubKey key(Params().AlertKey());
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
return error("CAlert::CheckSignature() : verify signature failed");
// Now unserialize the data
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
sMsg >> *(CUnsignedAlert*)this;
return true;
}
CAlert CAlert::getAlertByHash(const uint256& hash)
{
CAlert retval;
{
LOCK(cs_mapAlerts);
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
if (mi != mapAlerts.end())
retval = mi->second;
}
return retval;
}
bool CAlert::ProcessAlert(bool fThread)
{
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
// alert.nID=max is reserved for if the alert key is
// compromised. It must have a pre-defined message,
// must never expire, must apply to all versions,
// and must cancel all previous
// alerts or it will be ignored (so an attacker can't
// send an "everything is OK, don't panic" version that
// cannot be overridden):
int maxInt = std::numeric_limits<int>::max();
if (nID == maxInt) {
if (!(
nExpiration == maxInt &&
nCancel == (maxInt - 1) &&
nMinVer == 0 &&
nMaxVer == maxInt &&
setSubVer.empty() &&
nPriority == maxInt &&
strStatusBar == "URGENT: Alert key compromised, upgrade required"))
return false;
}
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) {
const CAlert& alert = (*mi).second;
if (Cancels(alert)) {
LogPrint("alert", "cancelling alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
} else if (!alert.IsInEffect()) {
LogPrint("alert", "expiring alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
} else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts) {
const CAlert& alert = item.second;
if (alert.Cancels(*this)) {
LogPrint("alert", "alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
// Notify UI and -alertnotify if it applies to me
if (AppliesToMe()) {
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
Notify(strStatusBar, fThread);
}
}
LogPrint("alert", "accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
return true;
}
void CAlert::Notify(const std::string& strMessage, bool fThread)
{
std::string strCmd = GetArg("-alertnotify", "");
if (strCmd.empty()) return;
// Alert text should be plain ascii coming from a trusted source, but to
// be safe we first strip anything not in safeChars, then add single quotes around
// the whole string before passing it to the shell:
std::string singleQuote("'");
std::string safeStatus = SanitizeString(strMessage);
safeStatus = singleQuote + safeStatus + singleQuote;
boost::replace_all(strCmd, "%s", safeStatus);
if (fThread)
boost::thread t(runCommand, strCmd); // thread runs free
else
runCommand(strCmd);
}
| [
"dutcoin@hotmail.com"
] | dutcoin@hotmail.com |
17f86afd008590ecbad70e5c58453462ed4d581b | 4f4ced810f7fdcbf99593c157a87ce301d122bdf | /CFS_Knitro_2D/src/ProblemCFS.h | 2e0cdd17cb0d4d91b1aca3a40185f28a882f1bde | [
"MIT"
] | permissive | carlchan0514/CFS | 784a8c7d9c7f649a5c7314156d5851fbed993c3c | f8b4e31ae31808c45dc7a464644972f7dae5d13c | refs/heads/master | 2023-03-18T05:13:41.853710 | 2019-01-12T02:26:44 | 2019-01-12T02:26:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,256 | h | //#ifndef _PROBLEMCFS_H_
//#define _PROBLEMCFS_H_
#pragma once
#include "KTRSolver.h"
#include "KTRProblem.h"
#include "ProblemQP.h"
#include "d2problem.h"
#include "customizedPrint.h"
#include "PlanningProblem.h"
#include <math.h>
#include <cmath>
#include <vector>
#include <iomanip>
class ProblemCFS {
public:
//ProblemCFS(int nstep, int dim, int nobs)
// : nstep_(nstep), dim_(dim), nobs_(nobs) { }
ProblemCFS(PlanningProblem* pp) {
pp_ = pp;
}
PlanningProblem* pp_;
double iteration_time_;
int iteration_;
std::vector<double> qp_time_;
std::vector<double> process_time_;
std::vector<double> cost_;
std::vector<double> soln_;
bool checkConvergence(const std::vector<double>& x, std::vector<double>& xold, const double& tolX){
double diff=0;
int N = pp_->nstep_ * pp_->dim_;
for (int i=0; i<N; i++){
diff += pow(x[i] - xold[i],2);
xold[i] = x[i];
}
std::cout << "diff = " << sqrt(diff) << "; tolX = " << tolX << std::endl;
if (sqrt(diff)/N<tolX){
return true;
}
else{
return false;
}
}
/*
bool autotest(){
// Construct Quadratic Objective x'*Hfull_*x + f_*x;
std::vector<double> H_;
std::vector< std::vector<double> > Hfull_(nstep_*dim_,std::vector<double>(nstep_*dim_));
std::vector<int> hessrows, hesscols;
std::vector<double> f_(nstep_*dim_);
H_.clear(); hessrows.clear(); hesscols.clear();
double hij;
for (int i=0; i<nstep_*dim_; i++){
f_[i] = 0;
for (int j=0; j<nstep_*dim_; j++)
{
f_[i] += -2*Qref_[i][j]*xref_[j];
if (i<=j){
hij = Qref_[i][j] + Qself_[i][j];
Hfull_[i][j] = hij;
Hfull_[j][i] = hij;
if (hij) {
H_.push_back(hij);
hessrows.push_back(i);
hesscols.push_back(j);
}
}
}
}
//printVector(hessrows.data(),hessrows.size());
//printVector(hesscols.data(),hesscols.size());
std::vector<int> jacrows, jaccols;
setConstraintSparcity(jacrows,jaccols);
// Instanciate a QP subproblem
ProblemQP subproblem(nstep_*dim_,nstep_*nobs_,hessrows,hesscols,jacrows,jaccols);
std::vector<double> x_(xref_);
std::vector<double> obspoly_;
std::vector< std::vector<double> > Lfull_(nstep_*nobs_, std::vector<double>(nstep_*dim_));
std::vector<double> S_(nstep_*nobs_);
std::vector<double> L_;
// Get L_ and S_;
L_.clear();
for (int i=0; i<nstep_; i++){
for (int j=0; j<nobs_; j++){
std::vector<double> l(dim_);
double s;
//std::cout << "Step " << i << ", Obstacle " << j << std::endl;
obspoly_ = Obs_[i][j];
d2poly(obspoly_, x_.data()+i*dim_, l, s);
//std::cout << "l = (" << l[0] << "," << l[1] << "); s = " << s << std::endl;
Lfull_[i*nobs_+j][i*dim_] = l[0];
Lfull_[i*nobs_+j][i*dim_ + 1] = l[1];
S_[i*nobs_+j] = s;
L_.push_back(l[0]);
L_.push_back(l[1]);
}
}
//test sparce
subproblem.setObjective(H_,f_);
subproblem.setConstraints(L_,S_);
std::vector<double> c1, objGrad1, jac1;
double obj1 = subproblem.evaluateFC(xref_, c1, objGrad1, jac1);
subproblem.evaluateGA(xref_, objGrad1, jac1);
subproblem.setObjective(Hfull_,f_);
subproblem.setConstraints(Lfull_,S_);
std::vector<double> c2, objGrad2, jac2;
double obj2 = subproblem.evaluateFC(xref_, c2, objGrad2, jac2);
subproblem.evaluateGA(xref_, objGrad2, jac2);
printMessage("The difference between obj is:");
std::cout << obj1-obj2 << std::endl;
printVector(c1.data(),c1.size());
printVector(c2.data(),c2.size());
printVector(objGrad1.data(),objGrad1.size());
printVector(objGrad2.data(),objGrad2.size());
printVector(jac1.data(),jac1.size());
printVector(jac2.data(),jac2.size());
}*/
int iteration(int iterMax, double tolX)
{
std::vector<double> xref(pp_->nstep_ * (pp_->dim_ + pp_->neq_));
pp_->setReferenceTrajectory(xref);
//pp_->printTrajectory(xref);
bool sparce_obj = true;
bool sparce_con = true;
int two_side = 2;
std::vector<double> H_;
std::vector< std::vector<double> > Hfull_(pp_->nstep_ * pp_->dim_, std::vector<double>(pp_->nstep_ * pp_->dim_));
std::vector<double> f_(pp_->nstep_*(pp_->dim_ + pp_->neq_));
std::vector<int> hessrows, hesscols;
pp_->setSparceObjective(xref, H_, f_, hessrows, hesscols);
printMessage("Sparce objective set.");
std::vector<int> jacrows, jaccols;
pp_->setConstraintSparcity(jacrows,jaccols,two_side);
printMessage("Sparce constraint set.");
// Instanciate a QP subproblem
int n_variable = pp_->nstep_ * (pp_->dim_ + pp_->neq_);
int n_constraint = pp_->nstep_ * pp_->nobs_ + (pp_->nstep_ - 2) * pp_->neq_ * two_side;
ProblemQP subproblem(n_variable, n_constraint , hessrows,hesscols,jacrows,jaccols);
if (sparce_obj){
subproblem.setObjective(H_,f_);
}
else{
subproblem.setObjective(Hfull_,f_);
}
subproblem.setInitial(xref,pp_->dim_,pp_->nstep_,2);
// Create a solver
knitro::KTRSolver solver(&subproblem);
solver.setParam(KTR_PARAM_OPTTOL, 1.0e-3);
solver.setParam(KTR_PARAM_ALG, 1);
solver.setParam(KTR_PARAM_PRESOLVE, 1);
//solver.setParam(KTR_PARAM_XTOL, 1.0e-3);
int solveStatus;
printMessage("Solver Created in CFS");
std::vector<double> x_(xref);
std::vector<double> xold_(xref);
std::vector<double> S_(pp_->nstep_ * (pp_->nobs_ + pp_->neq_));
double iter_start_time = 0;
double iter_end_time = 0;
double qp_start_time = 0;
double qp_end_time = 0;
double process_start_time = 0;
double process_end_time = 0;
// The iteration
qp_time_.clear();
cost_.clear();
cost_.push_back(subproblem.evaluateObj(xref));
std::vector<double> lambda(pp_->nstep_ * (pp_->nobs_ + pp_->neq_));
iter_start_time = std::clock();
for (int k=0; k<iterMax; k++){
//std::cout << "----------------------" << std::endl;
//std::cout << "Iteration " << k << std::endl;
// Processing
process_start_time = std::clock();
if (sparce_con){
std::vector<double> L_(jaccols.size());
if (k<0) {pp_->linConstraint(x_, L_, S_, 0);}
else{
pp_->linConstraint(x_, L_, S_, two_side);
}
subproblem.setConstraints(L_,S_);
}
else{
std::vector< std::vector<double> > Lfull_(pp_->nstep_*pp_->nobs_, std::vector<double>(pp_->nstep_ * pp_->dim_));
pp_->linConstraint(x_, Lfull_, S_);
subproblem.setConstraints(Lfull_,S_);
}
process_end_time = std::clock();
//printTimeEllapse(process_start_time, process_end_time, "Process Time");
process_time_.push_back((process_end_time - process_start_time)/CLOCKS_PER_SEC*1000);
printMessage("Specify initial");
subproblem.setInitial(x_,pp_->dim_,pp_->nstep_);
// Solve the subproblem
qp_start_time = std::clock();
solveStatus = solver.solve();
qp_end_time = std::clock();
//printTimeEllapse(qp_start_time, qp_end_time, "QP Time");
qp_time_.push_back((qp_end_time - qp_start_time)/CLOCKS_PER_SEC*1000);
x_ = solver.getXValues();
//pp_->printTrajectory(x_);
lambda = solver.getLambdaValues();
if (pp_->neq_) {pp_->normTrajectory(x_);}
//pp_->printTrajectory(x_);
cost_.push_back(subproblem.evaluateObj(x_));
// Convergence check
if (checkConvergence(x_,xold_,tolX)){
std::cout << "Converged at step " << k << std::endl;
iteration_ = k;
break;
}
solver.restart(x_, lambda);
}
soln_ = x_;
iter_end_time = std::clock();
//printTimeEllapse(iter_start_time, iter_end_time, "Iteration Time");
iteration_time_ = (iter_end_time - iter_start_time)/CLOCKS_PER_SEC*1000;
return iteration_;
}
int printResult(){
printVector(process_time_.data(),process_time_.size());
printVector(qp_time_.data(),qp_time_.size());
printVector(cost_.data(),cost_.size());
//pp_->printTrajectory(soln_);
std::cout << "total iteration time = " << iteration_time_ << "ms" << std::endl;
}
};
//#endif
| [
"changliu.liu@le.com"
] | changliu.liu@le.com |
87b0ff138c6a54596efe7096dbb970619a3c8763 | f504fe5f650a2f64c71a69ab450a5857dc8986f9 | /radiusImageMatch.h | 4016d653d2bb071ac66ab43af27cbf9425142ac7 | [] | no_license | Ienu/KDTREEucv | a10a5f6fa60b9444cf72bdb0b53ffdaf8e77b3c0 | dea9341369ed2a104cde93185ae06d61644fae89 | refs/heads/master | 2021-01-24T11:21:54.014472 | 2018-02-27T08:39:28 | 2018-02-27T08:39:28 | 123,078,218 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,223 | h | //1,radius匹配
#ifndef RADIUS_IMAGE_MATCH_H
#define RADIUS_IMAGE_MATCH_H
#include <vector>
#include<opencv2/legacy/legacy.hpp>
#include<opencv2/highgui/highgui.hpp>
#include "UcvImageMatch.h"
#include "UcvImageFeature.h"
#include "SurfFeature.h"
using namespace cv;
using namespace std;
class RadiusImageMatch: public UcvImageMatch
{
public:
void init( UcvImageFeature &uifSrc, UcvImageFeature &uifMatch)
{
uifSrc.getImage().copyTo(uif_src.image);
uif_src.descriptors = uifSrc.getDescriptors();
uif_src.keyPoints = uifSrc.getKeyPoint();
uifMatch.getImage().copyTo(uif_match.image);
uif_match.descriptors = uifMatch.getDescriptors();
uif_match.keyPoints = uifMatch.getKeyPoint();
}
void radiusMatch()
{
cv::BFMatcher matcher(NORM_L2,true);//针对surf,sift特征,float型数据,试验orb也行
//cv::BFMatcher matcher(NORM_HAMMING,true);//针对orb和brief特征,uchar型数据
matcher.radiusMatch(uif_src.descriptors,uif_match.descriptors, matches1, 150);//0.2是半径,距离小于该长度则认为是匹配点
matcher.radiusMatch(uif_match.descriptors,uif_src.descriptors, matches2, 150);
}
vector<vector<DMatch>> getMatches1(){return matches1;}
vector<vector<DMatch>> getMatches2(){return matches2;}
Mat getRadiusMatchImage1()
{
Mat imageMatches1;
drawMatches(uif_src.image,uif_src.keyPoints, // 1st image and its keypoints
uif_match.image,uif_match.keyPoints, // 2nd image and its keypoints
matches1, // the matches
imageMatches1, // the image produced
Scalar(255,255,255)); // color of the lines
// namedWindow("Matches1");
//imshow("Matches1",imageMatches1);
//waitKey(0);
return (imageMatches1);
}
Mat getRadiusMatchImage2()
{
cv::Mat imageMatches2;
cv::drawMatches(uif_match.image,uif_match.keyPoints, // 1st image and its keypoints
uif_src.image,uif_src.keyPoints, // 2nd image and its keypoints
matches2, // the matches
imageMatches2, // the image produced
Scalar(255,255,255)); // color of the lines
// namedWindow("Matches2");
// imshow("Matches2",imageMatches2);
//waitKey(0);
return (imageMatches2);
}
};
#endif; | [
"0910692@mail.nankai.edu.cn"
] | 0910692@mail.nankai.edu.cn |
5b713af3c805143c1e1c9ebb8b69c86fe044709b | 53c8a1890ff5f2bc7e4943a0c5184cd7ae740960 | /viewres.h | 47f9205b6e24ba01ddff18ca2b072883b3e5117b | [] | no_license | LinuxZhaoLi/MultiInterface | 7a8c387878a42e06e37b384313645a559ba0fab4 | 5213a4cb55e2678aad6ae1a23e8278e5e6fdd2bb | refs/heads/main | 2022-12-28T13:45:50.035491 | 2020-10-13T09:39:48 | 2020-10-13T09:39:48 | 303,099,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | h | #ifndef VIEWRES_H
#define VIEWRES_H
#include <QVariantMap>
#include <QObject>
class ViewRes : public QObject
{
Q_OBJECT
public:
explicit ViewRes(QObject *parent = 0);
QVariantMap Images();
~ViewRes();
};
#endif // VIEWRES_H
| [
"48636586+LinuxZhaoLi@users.noreply.github.com"
] | 48636586+LinuxZhaoLi@users.noreply.github.com |
f099cdaa8715a0082a4b6b24d70e8521d2ca2a5a | becdad9e2d4103971ae3f55b0fd469031ae1472c | /game/1/Psycho.h | dc7e58b2688d958cd64eb2ef77797ec83bb46e2d | [] | no_license | Bylinka/Game | 16c89cc172783010fabc8a54251ad4019875b266 | 5e38b403a4e29166a665aeaa62dc6a91abae6ddb | refs/heads/master | 2020-03-26T01:29:12.946174 | 2018-08-11T08:49:17 | 2018-08-11T08:49:17 | 144,369,412 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 364 | h | #pragma once
class Psycho
: public IUnit
{
public:
Type getType() { return Type::psycho; }
SafeCeil& nextCeil() {
switch (rand()%4) {
case 0: return self().left();
case 1: return self().right();
case 2: return self().up();
case 3: return self().down();
}
}
void move() {
while (isAlive()) {
go(&nextCeil());
Sleep(Speed());
}
}
};
| [
"w-x-t@ukr.net"
] | w-x-t@ukr.net |
71f84ac653d9cea5c49547c5e0bec37556c1a9be | 0c717271d43dd86ed4aa7f047a856a34bf2e033d | /Codeforces/Round 709(Div 2)/Matrix_XOR.cpp | c516a8cee885f1da8e072e5f1ecc100f80601877 | [] | no_license | sudo1729/CODING-SOLUTIONS | 378ff550f38f03999be665dc9020eb4eea7d364e | 0cf8657c6832f2587bfd1aa5cf5bbcd0de2ecc7d | refs/heads/master | 2023-04-19T02:01:42.824523 | 2021-04-18T05:47:07 | 2021-04-18T05:47:07 | 305,708,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | cpp | /*
``````````````````$$$$$
`````````````$$$$$$´´´´$$$$$$
``````````$$$´´´´´´´´´´´´´´´´$$$
````````$`$$´´´´´´´´´´´´´´´´´´´´$$
```````$´$$$´´´´´´´´´´´´´´´´´´´´´$$$$
`````$´´$$$$´´´´´´´´´´´´´´´´´´´´´´´´´´$
````$´´$$$$$´´´´´´´´´´$$$$$$$´´´´´´´´´$$
```$´´´$$$$$$$´´´$$$$$$$$$$$$$$$$$´´´´´$$
``$´´´´$$$$$$$$$$$$$$$$$$$$$$$$$$$$$´´´´$$
`$´´´´´´$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$´´$
`$´´´´´´$$$$$$$$$$$´´´´$$$$$$$$$$$$$$$$$$$
$´´´´´´´´$$$$$$$$´´´´´´´´$$$$$$$´´´´´´´´$$
$´´´´´´´´´$$$$$$´´´´´´´´´´$$$$´´´´´´´´´´´$
`$´´´´´´´´´$$$$$´´´´´´´´´´$$$´´´´´´´´´´´$
`$´´´´´´´´´´$$$$$´´´´´´´´$$$$´´´´´´´´´´´$
`$´´´´´´´´´´´$$$$$$´´´´$$$$$´´´´´´´´´´´$$
``$´´´´´´´´´´´$$$$$$$$$$$$$$´´´´´´´´´´´$
``$$´´´´´´´´´´´´$$$$$$$$$$$$´´´´´´´´´´$$
```$$´´´´´´´´´´´´$$$$$$$$$$´´´´´´´´´´$$
````$´´´´´´´´´´´´$$$$$$$$$´´´´´´´´´´´$
`````$´´´´´´´´´´´$$$$$$$$´´´´´´´´´´´$
``````$$´´´´´´´´´$$$$$$´´´´´´´´´´´$$
````````$$´´´´´´$$$$$´´´´´´´´´´´$$
``````````$$$´$$$$´´´´´´´´´´´$$$
`````````````$$$$$´´´´´´$$$$$
``````````````````$$$$$$
*/
#include<bits/stdc++.h>
#define ll long long int
#define pb push_back
#define F first
#define S second
#define vi vector<ll>
#define vs vector<string>
#define input(v,n) for(ll VAL=0;VAL<n;VAL++){ll VALUE;cin>>VALUE;v.pb(VALUE);}
#define mi map<ll,ll>
#define FOR(i,a,b) for(ll i=a;i<b;i++)
#define mi map<ll,ll>
#define print(v) for(ll printing=0;printing<v.size();printing++){cout<<v[printing]<<' ';}
#define TestCase ll testcase;cin>>testcase;while(testcase--)
#define bin(n) bitset<32>(n).to_string();
#define maxv(v) *max_element(v.begin(),v.end())
#define minv(v) *min_element(v.begin(),v.end())
#define decimal(s) stoll(s,nullptr,2)
#define rmLead(str) str.erase(0, min(str.find_first_not_of('0'), str.size()-1));
using namespace std;
void solve(){
ll n,m,k;cin>>n>>m>>k;
ll ans=0;
for(ll i=1;i<=min(n,m);i++){
ans=ans^(k+2*i);
}
cout<<ans<<"\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
TestCase{
solve();
}
} | [
"tripathiakhilesh98163@gmail.com"
] | tripathiakhilesh98163@gmail.com |
04c0baa870d94406d0d9ecf51b4278a870b6df43 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/collectd/new_hunk_1.cpp | 609aa7d9688914d2b704c9e2409527114cf412ad | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 173 | cpp | }
| block_begin block_end
{
if (strcmp($1.key, $2) != 0)
{
printf("block_begin = %s; block_end = %s;\n", $1.key, $2);
yyerror("block not closed");
YYERROR;
}
| [
"993273596@qq.com"
] | 993273596@qq.com |
90d838260b382e66afc252ca4e3f8b6e512a00c2 | a52eb0652ab3f18c76019c0ebc090a07cb5e9dd4 | /src/server/game/Pools/PoolMgr.h | a2fa9be09b838b6df5df82f5f109f61b4ed5059b | [] | no_license | szhxjt1334/WoWCircle434 | b0531ec16b76e4430d718620477d3532566188aa | de3fa2b4be52a7a683b0427269c51801fc0df062 | refs/heads/master | 2021-01-12T11:03:08.102883 | 2016-10-11T22:05:13 | 2016-10-11T22:05:13 | 72,802,348 | 0 | 1 | null | 2016-11-04T01:24:11 | 2016-11-04T01:24:10 | null | UTF-8 | C++ | false | false | 6,849 | h | /*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://www.mangosproject.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_POOLHANDLER_H
#define TRINITY_POOLHANDLER_H
#include "Define.h"
#include <ace/Singleton.h>
#include "Creature.h"
#include "GameObject.h"
#include "QuestDef.h"
struct PoolTemplateData
{
uint32 MaxLimit;
};
struct PoolObject
{
uint32 guid;
float chance;
PoolObject(uint32 _guid, float _chance): guid(_guid), chance(fabs(_chance)) {}
};
class Pool // for Pool of Pool case
{
};
typedef std::set<uint32> ActivePoolObjects;
typedef std::map<uint32, uint32> ActivePoolPools;
class ActivePoolData
{
public:
template<typename T>
bool IsActiveObject(uint32 db_guid_or_pool_id) const;
uint32 GetActiveObjectCount(uint32 pool_id) const;
template<typename T>
void ActivateObject(uint32 db_guid_or_pool_id, uint32 pool_id);
template<typename T>
void RemoveObject(uint32 db_guid_or_pool_id, uint32 pool_id);
ActivePoolObjects GetActiveQuests() const { return mActiveQuests; } // a copy of the set
private:
ActivePoolObjects mSpawnedCreatures;
ActivePoolObjects mSpawnedGameobjects;
ActivePoolObjects mActiveQuests;
ActivePoolPools mSpawnedPools;
};
template <class T>
class PoolGroup
{
typedef std::vector<PoolObject> PoolObjectList;
public:
explicit PoolGroup() : poolId(0) { }
void SetPoolId(uint32 pool_id) { poolId = pool_id; }
~PoolGroup() {};
bool isEmpty() const { return ExplicitlyChanced.empty() && EqualChanced.empty(); }
void AddEntry(PoolObject& poolitem, uint32 maxentries);
bool CheckPool() const;
PoolObject* RollOne(ActivePoolData& spawns, uint32 triggerFrom);
void DespawnObject(ActivePoolData& spawns, uint32 guid=0);
void Despawn1Object(uint32 guid);
void SpawnObject(ActivePoolData& spawns, uint32 limit, uint32 triggerFrom);
void Spawn1Object(PoolObject* obj);
void ReSpawn1Object(PoolObject* obj);
void RemoveOneRelation(uint32 child_pool_id);
uint32 GetFirstEqualChancedObjectId()
{
if (EqualChanced.empty())
return 0;
return EqualChanced.front().guid;
}
uint32 GetPoolId() const { return poolId; }
private:
uint32 poolId;
PoolObjectList ExplicitlyChanced;
PoolObjectList EqualChanced;
};
typedef std::multimap<uint32, uint32> PooledQuestRelation;
typedef std::pair<PooledQuestRelation::const_iterator, PooledQuestRelation::const_iterator> PooledQuestRelationBounds;
typedef std::pair<PooledQuestRelation::iterator, PooledQuestRelation::iterator> PooledQuestRelationBoundsNC;
class PoolMgr
{
friend class ACE_Singleton<PoolMgr, ACE_Null_Mutex>;
private:
PoolMgr();
~PoolMgr() {};
public:
void LoadFromDB();
void LoadQuestPools();
void SaveQuestsToDB();
void Initialize();
template<typename T>
uint32 IsPartOfAPool(uint32 db_guid_or_pool_id) const;
template<typename T>
bool IsSpawnedObject(uint32 db_guid_or_pool_id) const { return mSpawnedData.IsActiveObject<T>(db_guid_or_pool_id); }
bool CheckPool(uint32 pool_id) const;
void SpawnPool(uint32 pool_id);
void DespawnPool(uint32 pool_id);
template<typename T>
void UpdatePool(uint32 pool_id, uint32 db_guid_or_pool_id);
void ChangeDailyQuests();
void ChangeWeeklyQuests();
PooledQuestRelation mQuestCreatureRelation;
PooledQuestRelation mQuestGORelation;
private:
template<typename T>
void SpawnPool(uint32 pool_id, uint32 db_guid_or_pool_id);
uint32 max_pool_id;
typedef std::vector<PoolTemplateData> PoolTemplateDataMap;
typedef std::vector<PoolGroup<Creature> > PoolGroupCreatureMap;
typedef std::vector<PoolGroup<GameObject> > PoolGroupGameObjectMap;
typedef std::vector<PoolGroup<Pool> > PoolGroupPoolMap;
typedef std::vector<PoolGroup<Quest> > PoolGroupQuestMap;
typedef std::pair<uint32, uint32> SearchPair;
typedef std::map<uint32, uint32> SearchMap;
PoolTemplateDataMap mPoolTemplate;
PoolGroupCreatureMap mPoolCreatureGroups;
PoolGroupGameObjectMap mPoolGameobjectGroups;
PoolGroupPoolMap mPoolPoolGroups;
PoolGroupQuestMap mPoolQuestGroups;
SearchMap mCreatureSearchMap;
SearchMap mGameobjectSearchMap;
SearchMap mPoolSearchMap;
SearchMap mQuestSearchMap;
// dynamic data
ActivePoolData mSpawnedData;
};
#define sPoolMgr ACE_Singleton<PoolMgr, ACE_Null_Mutex>::instance()
// Method that tell if the creature is part of a pool and return the pool id if yes
template<>
inline uint32 PoolMgr::IsPartOfAPool<Creature>(uint32 db_guid) const
{
SearchMap::const_iterator itr = mCreatureSearchMap.find(db_guid);
if (itr != mCreatureSearchMap.end())
return itr->second;
return 0;
}
// Method that tell if the gameobject is part of a pool and return the pool id if yes
template<>
inline uint32 PoolMgr::IsPartOfAPool<GameObject>(uint32 db_guid) const
{
SearchMap::const_iterator itr = mGameobjectSearchMap.find(db_guid);
if (itr != mGameobjectSearchMap.end())
return itr->second;
return 0;
}
// Method that tell if the quest is part of another pool and return the pool id if yes
template<>
inline uint32 PoolMgr::IsPartOfAPool<Quest>(uint32 pool_id) const
{
SearchMap::const_iterator itr = mQuestSearchMap.find(pool_id);
if (itr != mQuestSearchMap.end())
return itr->second;
return 0;
}
// Method that tell if the pool is part of another pool and return the pool id if yes
template<>
inline uint32 PoolMgr::IsPartOfAPool<Pool>(uint32 pool_id) const
{
SearchMap::const_iterator itr = mPoolSearchMap.find(pool_id);
if (itr != mPoolSearchMap.end())
return itr->second;
return 0;
}
#endif
| [
"Tobias Pohlmann"
] | Tobias Pohlmann |
22d09f7ff2f12855b205ed12b4777cace6c20a1e | aaadfc7a2715df2047d76be8dc0732bc0921e0cd | /Tut03OpenGLsMovingTriangle/vertPositionOffset.cpp | c89fd4784c151b7cbc93d1c1cb706bfd0e4818c7 | [
"MIT",
"LicenseRef-scancode-public-domain",
"CC-BY-3.0"
] | permissive | Zaela24/gltut | 51d72c9ed3b632dd448f371827dbfab600b8d708 | 10d6f571db9c13d7ff173f52be8e25720dbfe71b | refs/heads/master | 2022-09-07T17:57:23.080661 | 2020-05-27T04:57:14 | 2020-05-27T04:57:14 | 266,958,080 | 0 | 0 | NOASSERTION | 2020-05-26T06:03:31 | 2020-05-26T06:03:30 | null | UTF-8 | C++ | false | false | 3,181 | cpp |
#include <string>
#include <vector>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <glload/gl_3_3.h>
#include <GL/freeglut.h>
#include "../framework/framework.h"
GLuint theProgram;
GLuint offsetLocation;
void InitializeProgram()
{
std::vector<GLuint> shaderList;
shaderList.push_back(Framework::LoadShader(GL_VERTEX_SHADER, "positionOffset.vert"));
shaderList.push_back(Framework::LoadShader(GL_FRAGMENT_SHADER, "standard.frag"));
theProgram = Framework::CreateProgram(shaderList);
offsetLocation = glGetUniformLocation(theProgram, "offset");
}
const float vertexPositions[] = {
0.25f, 0.25f, 0.0f, 1.0f,
0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f,
};
GLuint positionBufferObject;
GLuint vao;
void InitializeVertexBuffer()
{
glGenBuffers(1, &positionBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//Called after the window and OpenGL are initialized. Called exactly once, before the main loop.
void init()
{
InitializeProgram();
InitializeVertexBuffer();
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
}
void ComputePositionOffsets(float &fXOffset, float &fYOffset)
{
const float fLoopDuration = 5.0f;
const float fScale = 3.14159f * 2.0f / fLoopDuration;
float fElapsedTime = glutGet(GLUT_ELAPSED_TIME) / 1000.0f;
float fCurrTimeThroughLoop = fmodf(fElapsedTime, fLoopDuration);
fXOffset = cosf(fCurrTimeThroughLoop * fScale) * 0.5f;
fYOffset = sinf(fCurrTimeThroughLoop * fScale) * 0.5f;
}
//Called to update the display.
//You should call glutSwapBuffers after all of your rendering to display what you rendered.
//If you need continuous updates of the screen, call glutPostRedisplay() at the end of the function.
void display()
{
float fXOffset = 0.0f, fYOffset = 0.0f;
ComputePositionOffsets(fXOffset, fYOffset);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(theProgram);
glUniform2f(offsetLocation, fXOffset, fYOffset);
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glUseProgram(0);
glutSwapBuffers();
glutPostRedisplay();
}
//Called whenever the window is resized. The new window size is given, in pixels.
//This is an opportunity to call glViewport or glScissor to keep up with the change in size.
void reshape (int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
}
//Called whenever a key on the keyboard was pressed.
//The key is given by the ''key'' parameter, which is in ASCII.
//It's often a good idea to have the escape key (ASCII value 27) call glutLeaveMainLoop() to
//exit the program.
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 27:
glutLeaveMainLoop();
return;
}
}
unsigned int defaults(unsigned int displayMode, int &width, int &height) {return displayMode;}
| [
"unknown"
] | unknown |
70277436582ef5c50415af3ddb4899380f00fcb9 | af976711c178037f4e72fc9aa5577a007da77b0d | /src/snapplot/dlg_error_options.hpp | 41cdfad192782546e772d6a295e622767cd96a9a | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | linz/snap | 865ebb67306de3a4703eb7972397c6ffbea2f1f6 | 62e0708da11e5c918de760d06c75a27b59463461 | refs/heads/master | 2023-06-02T11:36:28.508813 | 2023-05-16T18:52:38 | 2023-05-16T18:52:38 | 43,912,064 | 8 | 5 | NOASSERTION | 2022-04-02T18:10:27 | 2015-10-08T19:35:16 | C | UTF-8 | C++ | false | false | 122 | hpp | #ifndef DLG_ERROR_OPTIONS_HPP
#define DLG_ERROR_OPTIONS_HPP
bool SetupErrorOptions( wxHelpController *help = 0 );
#endif | [
"ccrook@linz.govt.nz"
] | ccrook@linz.govt.nz |
9ca4fe6d7af207f4e7c9aa3d5266faf650e865a1 | ba9322f7db02d797f6984298d892f74768193dcf | /imm/src/model/IndexVideoRequest.cc | 65959f53ee8bd0e004e910a0707873207e7441e7 | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 4,372 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/imm/model/IndexVideoRequest.h>
using AlibabaCloud::Imm::Model::IndexVideoRequest;
IndexVideoRequest::IndexVideoRequest() :
RpcServiceRequest("imm", "2017-09-06", "IndexVideo")
{}
IndexVideoRequest::~IndexVideoRequest()
{}
std::string IndexVideoRequest::getGrabType()const
{
return grabType_;
}
void IndexVideoRequest::setGrabType(const std::string& grabType)
{
grabType_ = grabType;
setCoreParameter("GrabType", grabType);
}
std::string IndexVideoRequest::getRemarksB()const
{
return remarksB_;
}
void IndexVideoRequest::setRemarksB(const std::string& remarksB)
{
remarksB_ = remarksB;
setCoreParameter("RemarksB", remarksB);
}
std::string IndexVideoRequest::getProject()const
{
return project_;
}
void IndexVideoRequest::setProject(const std::string& project)
{
project_ = project;
setCoreParameter("Project", project);
}
std::string IndexVideoRequest::getRemarksA()const
{
return remarksA_;
}
void IndexVideoRequest::setRemarksA(const std::string& remarksA)
{
remarksA_ = remarksA;
setCoreParameter("RemarksA", remarksA);
}
std::string IndexVideoRequest::getEndTime()const
{
return endTime_;
}
void IndexVideoRequest::setEndTime(const std::string& endTime)
{
endTime_ = endTime;
setCoreParameter("EndTime", endTime);
}
std::string IndexVideoRequest::getExternalId()const
{
return externalId_;
}
void IndexVideoRequest::setExternalId(const std::string& externalId)
{
externalId_ = externalId;
setCoreParameter("ExternalId", externalId);
}
std::string IndexVideoRequest::getStartTime()const
{
return startTime_;
}
void IndexVideoRequest::setStartTime(const std::string& startTime)
{
startTime_ = startTime;
setCoreParameter("StartTime", startTime);
}
std::string IndexVideoRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void IndexVideoRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setCoreParameter("AccessKeyId", accessKeyId);
}
std::string IndexVideoRequest::getVideoUri()const
{
return videoUri_;
}
void IndexVideoRequest::setVideoUri(const std::string& videoUri)
{
videoUri_ = videoUri;
setCoreParameter("VideoUri", videoUri);
}
bool IndexVideoRequest::getSaveType()const
{
return saveType_;
}
void IndexVideoRequest::setSaveType(bool saveType)
{
saveType_ = saveType;
setCoreParameter("SaveType", saveType ? "true" : "false");
}
std::string IndexVideoRequest::getRegionId()const
{
return regionId_;
}
void IndexVideoRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setCoreParameter("RegionId", regionId);
}
std::string IndexVideoRequest::getRemarksD()const
{
return remarksD_;
}
void IndexVideoRequest::setRemarksD(const std::string& remarksD)
{
remarksD_ = remarksD;
setCoreParameter("RemarksD", remarksD);
}
std::string IndexVideoRequest::getRemarksC()const
{
return remarksC_;
}
void IndexVideoRequest::setRemarksC(const std::string& remarksC)
{
remarksC_ = remarksC;
setCoreParameter("RemarksC", remarksC);
}
std::string IndexVideoRequest::getSetId()const
{
return setId_;
}
void IndexVideoRequest::setSetId(const std::string& setId)
{
setId_ = setId;
setCoreParameter("SetId", setId);
}
std::string IndexVideoRequest::getInterval()const
{
return interval_;
}
void IndexVideoRequest::setInterval(const std::string& interval)
{
interval_ = interval;
setCoreParameter("Interval", interval);
}
std::string IndexVideoRequest::getTgtUri()const
{
return tgtUri_;
}
void IndexVideoRequest::setTgtUri(const std::string& tgtUri)
{
tgtUri_ = tgtUri;
setCoreParameter("TgtUri", tgtUri);
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
0d3f04a927512a3c2341611e356525e6b0291157 | 34983bc6829614602be7c366864926568762c5f5 | /zubax_chibios/util/helpers.hpp | 34683bcac2a989fca23297555f7351dac770cde8 | [
"MIT"
] | permissive | zwx230741/zubax_chibios | 72e3810280cbf2ee8c2f8f0eb4fefb53be12ee46 | 2d96b0cb3d30e4108c0dce721e272e6ae5de5095 | refs/heads/master | 2020-03-19T11:37:01.585973 | 2018-06-02T17:59:13 | 2018-06-02T17:59:13 | 110,653,512 | 0 | 0 | null | 2017-11-14T07:05:57 | 2017-11-14T07:05:57 | null | UTF-8 | C++ | false | false | 1,186 | hpp | /*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* Various small helpers.
*/
#pragma once
#include <cassert>
#include <cstdint>
#include <utility>
#include <algorithm>
#include <iterator>
#define EXECUTE_ONCE_CAT1_(a, b) EXECUTE_ONCE_CAT2_(a, b)
#define EXECUTE_ONCE_CAT2_(a, b) a##b
/**
* This macro can be used in function and method bodies to execute a certain block of code only once.
* Every instantiation creates one static variable.
* This macro is not thread safe.
*
* Usage:
* puts("Regular code");
* EXECUTE_ONCE_NON_THREAD_SAFE
* {
* puts("This block will be executed only once");
* }
* puts("Regular code again");
*/
#define EXECUTE_ONCE_NON_THREAD_SAFE \
static bool EXECUTE_ONCE_CAT1_(_executed_once_, __LINE__) = false; \
for (; EXECUTE_ONCE_CAT1_(_executed_once_, __LINE__) == false; EXECUTE_ONCE_CAT1_(_executed_once_, __LINE__) = true)
/**
* Branching hints; these are compiler-dependent.
*/
#define LIKELY(x) (__builtin_expect((x), true))
#define UNLIKELY(x) (__builtin_expect((x), false))
| [
"pavel.kirienko@gmail.com"
] | pavel.kirienko@gmail.com |
d99f517575a4b66be85411e4d61a1a0d7a726017 | cb052ee1c43f00849811db2509d07826afb9a9bf | /xenum/test/src/xenums/FruitsNoNsNoCls.cpp | 10be555565cb5381ddc21dbfd1445ea6e01bea1c | [] | no_license | rodrigobmg/xenum | 7407731bae3eba9e7a2f1edc30fe86283425f830 | 0436738af5165e41f560b92f88bb11a92a6ed2f5 | refs/heads/master | 2020-06-08T16:39:41.674891 | 2018-07-17T00:07:04 | 2018-07-17T00:07:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | /**
* @file
* @author Simon Lodal
* @copyright 2017-2018 Simon Lodal <simonl@parknet.dk>
* @license GNU GPL version 3
*/
#include <test/xenum/xenums/FruitsNoNsNoCls.hpp>
XENUM5_DEFINE(Fruits_NoNsNoCls)
| [
"simon.lodal@gmail.com"
] | simon.lodal@gmail.com |
d235873c2b8c0e7c341e8e7736622b14f44b269f | 065fe62aa6f9004fc91b07e6c676e8d500a47048 | /ANPR-Demo-master/ANPR/Recognise.cpp | 84e3b356a47b18f16288cea45a91935787c60f11 | [] | no_license | huyleonis/Capstone | ee8f185348e6637f0711bf01921e1f1df1f8dab4 | bebe728619453fd1097e373b87828f8c843d9677 | refs/heads/master | 2021-05-16T17:49:32.261190 | 2017-12-12T09:56:59 | 2017-12-12T09:56:59 | 103,046,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,639 | cpp | #include "Recognise.h"
const CvScalar RED = CV_RGB(255,0,0);
const CvScalar GREEN = CV_RGB(0,255,0);
const CvScalar BLUE = CV_RGB(0,0,255);
Recognise::Recognise() {
}
vector<IplImage *> Recognise::FindCharacter (IplImage *plate) {
vector<IplImage *> charImgVector;
vector<CvRect> rect;
IplImage *resizeImg, *binaryImg, *cloneImg;
resizeImg = cvCreateImage (cvSize(408, 70), IPL_DEPTH_8U, 3);
binaryImg = cvCreateImage (cvSize(408, 70), IPL_DEPTH_8U, 1);
cvResize(plate, resizeImg);
cvCvtColor(resizeImg, binaryImg, CV_RGB2GRAY);
cvAdaptiveThreshold(binaryImg, binaryImg, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 13, 2);
cloneImg = cvCloneImage(resizeImg);
CvMemStorage *storage = cvCreateMemStorage(0);
CvSeq *contours = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint), storage);
cvFindContours(binaryImg, storage, &contours);
double ratio, ratioWhite;
int s, white;
while (contours) {
CvRect r = cvBoundingRect(contours, 0);
ratio = (double)r.width/r.height;
s = r.width * r.height;
cvSetImageROI(binaryImg, r);
white = cvCountNonZero(binaryImg);
cvResetImageROI(binaryImg);
ratioWhite = (double) white / s;
if (ratio > 0.3 && ratio < 1.1 &&
s > 375 && r.width > 15 && r.width < 50 &&
r.height > 30 && r.height < 65 &&
ratioWhite > 0.3 && ratioWhite < 0.75 && r.x > 2)
{
cvRectangle(cloneImg, cvPoint(r.x, r.y), cvPoint(r.x + r.width, r.y + r.height), BLUE, 2);
rect.push_back(r);
}
contours = contours->h_next;
}
// sap xep
for (int i = 0; i < rect.size() - 1; i++)
{
for (int j = i + 1; j < rect.size(); j++)
{
if (rect[i].x > rect[j].x)
{
CvRect sw;
sw = rect[i];
rect[i] = rect[j];
rect[j] = sw;
}
}
}
// cat ky tu
IplImage *charImg;
IplImage *saveImg;
for (int i = 0; i < rect.size(); i++)
{
charImg = cvCreateImage(cvSize(rect[i].width, rect[i].height), IPL_DEPTH_8U, 3);
cvSetImageROI(resizeImg, rect[i]);
cvCopy(resizeImg, charImg, NULL);
cvResetImageROI(resizeImg);
// add anh vao vector ki tu
charImgVector.push_back(charImg);
// show
char name[8];
sprintf(name, "Anh %d", i + 1);
cvShowImage(name, charImg);
// Luu anh lam mau de training
saveImg = cvCreateImage(cvSize(rect[i].width, rect[i].height), IPL_DEPTH_8U, 1);
cvCvtColor(charImgVector[i], saveImg, CV_RGB2GRAY);
cvAdaptiveThreshold(saveImg, saveImg, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 13, 2);
char sname[8];
sprintf(sname, "Data/%d.jpg", i + 1);
//cvShowImage(sname, saveImg);
cvSaveImage(sname, saveImg);
}
cvShowImage("character", cloneImg);
return charImgVector;
} | [
"tin.bambo1112@gmail.com"
] | tin.bambo1112@gmail.com |
c6c7cd0b580a2d068f44f756fbf445080885306c | d7a6eebfcfbe25734889fe7b0ec597386800160b | /NovodeXWrapper/NwRagdoll.cpp | abe340756861d6f1aab3ac2b3631fd6d0b55ca17 | [] | no_license | naturalleo/coh-score | 09f3a9137ab845739f3cc4be026c014af99ed81e | ccb216f07c25457991b86d3b41ec98ff858ed187 | refs/heads/master | 2020-11-24T19:45:13.700022 | 2019-07-28T14:36:02 | 2019-07-28T14:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,280 | cpp | #include "NwWrapper.h"
#if NOVODEX
//#include "NxMath.h" // needs to be included before mathutil.h or there's a define conflict
#define NO_TEXT_PARSER 1
#include "NwRagdoll.h"
#include "NxActor.h"
#include "NxPhysicsSDK.h"
#include "NxMaterial.h"
#include "NxScene.h"
#include "NxJoint.h"
#include "NxFixedJoint.h"
#include "NxFixedJointDesc.h"
#include "NxSphericalJointDesc.h"
#include "NxRevoluteJointDesc.h"
extern "C"
{
#include "anim.h"
#include "ragdoll.h"
#include "gfxtree.h"
#include "seq.h"
#include "mathutil.h"
#include "queue.h"
#include "entity.h"
#include "renderprim.h"
#include "motion.h"
#include "groupnovodex.h"
#include "costume.h"
#include "error.h"
#include "timing.h"
#include "earray.h"
#include "Quat.h"
}
typedef enum ragGeom
{
RAG_GEOM_CAPSULE,
RAG_GEOM_BOX,
RAG_GEOM_SPHERE
} ragGeom;
typedef struct RagdollGeometry
{
Mat4 mOffsetMat;
F32 fHeight;
F32 fRadius;
Vec3 vSize;
bool bCCD;
ragGeom geom;
bool bOffset;
} RagdollGeometry;
extern NxState nx_state;
// NovodeX-specific parameters.
extern NxPhysicsSDK* nxSDK;
extern NxScene* nxScene[];
static struct
{
float swing_spring;// = 0.2f;
float swing_damper;// = 0.1f;
float twist_spring;// = 0.2f;
float twist_damper;// = 0.1f;
float swing_hardness;// = 0.9f;
float twist_hardness;// = 0.9f;
float hinge_hardness;// = 0.9f;
float projection_distance;// = 0.15f;
float linearDamping; // novodex default - 0.0f
float angularDamping; // novodex default 0.05f
float linearSleepVelocity; // novodex default - 0.15f
float angularSleepVelocity; // novodex default - 0.14f
bool doCCD; // true
bool bInited;
} ragdollConstants;
static Queue ragdollCreationQueue;
static Queue ragdollDeletionWithFreeQueue;
#define DEFAULT_SWING_SPRING ragdollConstants.swing_spring
#define DEFAULT_SWING_DAMPER ragdollConstants.swing_damper
#define DEFAULT_TWIST_SPRING ragdollConstants.twist_spring
#define DEFAULT_TWIST_DAMPER ragdollConstants.twist_damper
#define DEFAULT_SWING_HARDNESS ragdollConstants.swing_hardness
#define DEFAULT_TWIST_HARDNESS ragdollConstants.twist_hardness
#define DEFAULT_HINGE_HARDNESS ragdollConstants.hinge_hardness
#define DEFAULT_PROJECTON_DIST ragdollConstants.projection_distance
#define DEFAULT_PROJECTION_METHOD NX_JPM_POINT_MINDIST
//#define DEFAULT_PROJECTION_METHOD NX_JPM_NONE
NxJoint* jointRagdoll( NxActor* parentActor, NxActor* childActor, U8 boneId, Vec3 vGlobalAnchor, int iScene )
{
NxJoint* jointToReturn = NULL;
NxVec3 nxvGlobalAnchor;
U8 uiBoneId = boneId;
copyVec3(vGlobalAnchor, nxvGlobalAnchor);
switch (uiBoneId)
{
xcase BONEID_CHEST:
{
NxSphericalJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
NxMat33 mChildOrientation = childActor->getGlobalOrientation();
NxMat33 mParentOrientation = parentActor->getGlobalOrientation();
NxMat33 mUnitMat;
mUnitMat.id();
parentActor->setGlobalOrientation(mUnitMat);
childActor->setGlobalOrientation(mUnitMat);
NxVec3 vGlobalAxis = mUnitMat.getColumn(1);
//vGlobalAxis = mParentOrientation * vGlobalAxis;
jointDesc.setGlobalAxis(vGlobalAxis);
childActor->setGlobalOrientation(mChildOrientation);
parentActor->setGlobalOrientation(mParentOrientation);
jointDesc.flags |= NX_SJF_SWING_LIMIT_ENABLED;
jointDesc.swingLimit.value = RAD(25.0f);
jointDesc.swingLimit.hardness = DEFAULT_SWING_HARDNESS;
jointDesc.swingLimit.restitution = 0.5;
jointDesc.flags |= NX_SJF_SWING_SPRING_ENABLED;
jointDesc.swingSpring.spring = 0.5;
jointDesc.swingSpring.damper = 0.2;
jointDesc.flags |= NX_SJF_TWIST_LIMIT_ENABLED;
jointDesc.twistLimit.low.value = -RAD(60.0f);
jointDesc.twistLimit.low.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.low.restitution = 0.5;
jointDesc.twistLimit.high.value = RAD(60.0f);
jointDesc.twistLimit.high.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.high.restitution = 0.5;
jointDesc.flags |= NX_SJF_TWIST_SPRING_ENABLED;
jointDesc.twistSpring.spring = 0.5;
jointDesc.twistSpring.damper = 0.2;
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointDesc.projectionDistance = DEFAULT_PROJECTON_DIST;
jointDesc.projectionMode = DEFAULT_PROJECTION_METHOD;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
}
xcase BONEID_HEAD:
{
NxSphericalJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
NxMat33 mChildOrientation = childActor->getGlobalOrientation();
NxMat33 mParentOrientation = parentActor->getGlobalOrientation();
NxMat33 mUnitMat;
mUnitMat.id();
parentActor->setGlobalOrientation(mUnitMat);
childActor->setGlobalOrientation(mUnitMat);
NxVec3 vGlobalAxis = mUnitMat.getColumn(1);
//vGlobalAxis = mParentOrientation * vGlobalAxis;
jointDesc.setGlobalAxis(vGlobalAxis);
childActor->setGlobalOrientation(mChildOrientation);
parentActor->setGlobalOrientation(mParentOrientation);
jointDesc.flags |= NX_SJF_SWING_LIMIT_ENABLED;
jointDesc.swingLimit.value = RAD(35.0f);
jointDesc.swingLimit.hardness = DEFAULT_SWING_HARDNESS;
jointDesc.swingLimit.restitution = 0.5;
jointDesc.flags |= NX_SJF_SWING_SPRING_ENABLED;
jointDesc.swingSpring.spring = 0.5;
jointDesc.swingSpring.damper = 0.2;
jointDesc.flags |= NX_SJF_TWIST_LIMIT_ENABLED;
jointDesc.twistLimit.low.value = -RAD(80.0f);
jointDesc.twistLimit.low.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.low.restitution = 0.5;
jointDesc.twistLimit.high.value = RAD(80.0f);
jointDesc.twistLimit.high.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.high.restitution = 0.5;
#ifdef DEFAULT_TWIST_SPRING
jointDesc.flags |= NX_SJF_TWIST_SPRING_ENABLED;
jointDesc.twistSpring.spring = DEFAULT_TWIST_SPRING;
jointDesc.twistSpring.damper = DEFAULT_TWIST_DAMPER;
#endif
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointDesc.projectionDistance = DEFAULT_PROJECTON_DIST;
jointDesc.projectionMode = DEFAULT_PROJECTION_METHOD;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
}
xcase BONEID_UARMR:
case BONEID_UARML:
{
NxSphericalJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
// Ok, first we need to rotate the child actor so that it is in the identity matrix wrt the parent
NxMat33 mChildOrientation = childActor->getGlobalOrientation();
NxMat33 mParentOrientation = parentActor->getGlobalOrientation();
NxMat33 mUnitMat;
mUnitMat.id();
parentActor->setGlobalOrientation(mUnitMat);
// Orient the child into the right position.
bool bApplyOffset = false;
NxMat33 mFixOrientation;
F32 fFlipSign = 1.0f;
if ( boneId == 8)
{
fFlipSign = -1.0f;
bApplyOffset = true;
mFixOrientation.rotX(RAD(180.0f));
mUnitMat *= mFixOrientation;
// mFixOrientation.rotY(RAD(180.0f));
// mUnitMat *= mFixOrientation;
}
mFixOrientation.rotY(-RAD(60.0f));
mUnitMat *= mFixOrientation;
mFixOrientation.rotZ(RAD(90.0f) * fFlipSign);
mUnitMat *= mFixOrientation;
childActor->setGlobalOrientation(mUnitMat);
NxVec3 vGlobalAxis = -mUnitMat.getColumn(1);
//vGlobalAxis = mParentOrientation * vGlobalAxis;
jointDesc.setGlobalAxis(vGlobalAxis);
childActor->setGlobalOrientation(mChildOrientation);
parentActor->setGlobalOrientation(mParentOrientation);
jointDesc.flags |= NX_SJF_SWING_LIMIT_ENABLED;
jointDesc.swingLimit.value = RAD(70.0f);
jointDesc.swingLimit.hardness = DEFAULT_SWING_HARDNESS;
jointDesc.swingLimit.restitution = 0.5;
#ifdef DEFAULT_SWING_SPRING
jointDesc.flags |= NX_SJF_SWING_SPRING_ENABLED;
jointDesc.swingSpring.spring = DEFAULT_SWING_SPRING;
jointDesc.swingSpring.damper = DEFAULT_SWING_DAMPER;
#endif
F32 fOffsetAngle = 0.0f;
if ( bApplyOffset )
fOffsetAngle = RAD(180.0f);
jointDesc.flags |= NX_SJF_TWIST_LIMIT_ENABLED;
jointDesc.twistLimit.low.value = -RAD(70.0f) + fOffsetAngle;
jointDesc.twistLimit.low.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.low.restitution = 0.5;
jointDesc.twistLimit.high.value = RAD(70.0f) + fOffsetAngle;
jointDesc.twistLimit.high.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.high.restitution = 0.5;
#ifdef DEFAULT_TWIST_SPRING
jointDesc.flags |= NX_SJF_TWIST_SPRING_ENABLED;
jointDesc.twistSpring.spring = DEFAULT_TWIST_SPRING;
jointDesc.twistSpring.damper = DEFAULT_TWIST_DAMPER;
//jointDesc.twistSpring.targetValue = -RAD(70.0f) + fOffsetAngle;
#endif
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointDesc.projectionDistance = DEFAULT_PROJECTON_DIST;
jointDesc.projectionMode = DEFAULT_PROJECTION_METHOD;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
}
xcase BONEID_LARMR:
case BONEID_LARML:
{
NxRevoluteJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
// Ok, first we need to rotate the child actor so that it is in the identity matrix wrt the parent
NxMat33 mChildOrientation = childActor->getGlobalOrientation();
NxMat33 mParentOrientation = parentActor->getGlobalOrientation();
NxMat33 mUnitMat;
mUnitMat.id();
parentActor->setGlobalOrientation(mUnitMat);
NxMat33 mFixOrientation;
F32 fOffsetAngle = 0.0f;
F32 fFlipSign = 1.0f;
if ( boneId == 10)
{
fFlipSign = -1.0f;
}
/*
fOffsetAngle = 0.0f;
mFixOrientation.rotY(RAD(260.0f));
mUnitMat *= mFixOrientation;
}
else
{
mFixOrientation.rotX(RAD(180.0f));
mUnitMat *= mFixOrientation;
}
*/
//mFixOrientation.rotZ(RAD(90.0f) * fFlipSign);
//mUnitMat *= mFixOrientation;
//fOffsetAngle = RAD(90.0f);
childActor->setGlobalOrientation(mUnitMat);
NxVec3 vGlobalAxis = mUnitMat.getColumn(0);
//vGlobalAxis = mParentOrientation * vGlobalAxis;
jointDesc.setGlobalAxis(vGlobalAxis);
childActor->setGlobalOrientation(mChildOrientation);
parentActor->setGlobalOrientation(mParentOrientation);
jointDesc.flags |= NX_RJF_LIMIT_ENABLED;
jointDesc.limit.high.value = RAD(135.0f) + fOffsetAngle;
jointDesc.limit.high.hardness = DEFAULT_HINGE_HARDNESS;
jointDesc.limit.high.restitution = 0.5;
jointDesc.limit.low.value = RAD(5.0f) + fOffsetAngle;
jointDesc.limit.low.hardness = DEFAULT_HINGE_HARDNESS;
jointDesc.limit.low.restitution = 0.5;
#ifdef DEFAULT_SWING_SPRING
jointDesc.flags |= NX_RJF_SPRING_ENABLED;
jointDesc.spring.spring = 0.1f;
jointDesc.spring.damper = DEFAULT_SWING_DAMPER;
jointDesc.spring.targetValue = RAD(10.0f);
#endif
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointDesc.projectionDistance = DEFAULT_PROJECTON_DIST;
jointDesc.projectionMode = DEFAULT_PROJECTION_METHOD;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
}
xcase BONEID_ULEGR:
case BONEID_ULEGL:
{
NxSphericalJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
// Ok, first we need to rotate the child actor so that it is in the identity matrix wrt the parent
NxMat33 mChildOrientation = childActor->getGlobalOrientation();
NxMat33 mParentOrientation = parentActor->getGlobalOrientation();
NxMat33 mFixOrientation;
mFixOrientation.rotX(RAD(-15.0f));
mParentOrientation *= mFixOrientation;
if ( boneId == 23)
mFixOrientation.rotZ(RAD(15.0f));
else
mFixOrientation.rotZ(RAD(-15.0f));
mParentOrientation *= mFixOrientation;
childActor->setGlobalOrientation(mParentOrientation);
NxVec3 vGlobalAxis(0.0f,-1.0f,0.0f);
vGlobalAxis = mParentOrientation * vGlobalAxis;
jointDesc.setGlobalAxis(vGlobalAxis);
childActor->setGlobalOrientation(mChildOrientation);
jointDesc.flags |= NX_SJF_SWING_LIMIT_ENABLED;
jointDesc.swingLimit.value = RAD(35.0f);
jointDesc.swingLimit.hardness = DEFAULT_SWING_HARDNESS;
jointDesc.swingLimit.restitution = 0.5;
#ifdef DEFAULT_SWING_SPRING
jointDesc.flags |= NX_SJF_SWING_SPRING_ENABLED;
jointDesc.swingSpring.spring = DEFAULT_SWING_SPRING;
jointDesc.swingSpring.damper = DEFAULT_SWING_DAMPER;
#endif
jointDesc.flags |= NX_SJF_TWIST_LIMIT_ENABLED;
jointDesc.twistLimit.low.value = -RAD(45.0f);
jointDesc.twistLimit.low.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.low.restitution = 0.5;
jointDesc.twistLimit.high.value = RAD(45.0f);
jointDesc.twistLimit.high.hardness = DEFAULT_TWIST_HARDNESS;
jointDesc.twistLimit.high.restitution = 0.5;
#ifdef DEFAULT_TWIST_SPRING
jointDesc.flags |= NX_SJF_TWIST_SPRING_ENABLED;
jointDesc.twistSpring.spring = DEFAULT_TWIST_SPRING;
jointDesc.twistSpring.damper = DEFAULT_TWIST_DAMPER;
#endif
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointDesc.projectionDistance = DEFAULT_PROJECTON_DIST;
jointDesc.projectionMode = DEFAULT_PROJECTION_METHOD;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
}
xcase BONEID_LLEGR:
case BONEID_LLEGL:
{
NxRevoluteJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
// Ok, first we need to rotate the child actor so that it is in the identity matrix wrt the parent
NxMat33 mChildOrientation = childActor->getGlobalOrientation();
NxMat33 mParentOrientation = parentActor->getGlobalOrientation();
// NxMat33 mFixOrientation;
// mFixOrientation.rotX(RAD(80.0f));
// mParentOrientation *= mFixOrientation;
childActor->setGlobalOrientation(mParentOrientation);
NxVec3 vGlobalAxis(1.0f,0.0f,0.0f);
vGlobalAxis = mParentOrientation * vGlobalAxis;
jointDesc.setGlobalAxis(vGlobalAxis);
childActor->setGlobalOrientation(mChildOrientation);
jointDesc.flags |= NX_RJF_LIMIT_ENABLED;
jointDesc.limit.high.value = RAD(0.0f);
jointDesc.limit.high.hardness = DEFAULT_HINGE_HARDNESS;
jointDesc.limit.high.restitution = 0.5;
jointDesc.limit.low.value = -RAD(120.0f);
jointDesc.limit.low.hardness = DEFAULT_HINGE_HARDNESS;
jointDesc.limit.low.restitution = 0.5;
#ifdef DEFAULT_SWING_SPRING
jointDesc.flags |= NX_RJF_SPRING_ENABLED;
jointDesc.spring.spring = DEFAULT_SWING_SPRING;
jointDesc.spring.damper = DEFAULT_SWING_DAMPER;
#endif
jointDesc.projectionDistance = DEFAULT_PROJECTON_DIST;
jointDesc.projectionMode = DEFAULT_PROJECTION_METHOD;
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
}
xdefault:
{
NxFixedJointDesc jointDesc;
jointDesc.actor[0] = parentActor;
jointDesc.actor[1] = childActor;
jointDesc.setGlobalAnchor(nxvGlobalAnchor);
/*
NxVec3 vGlobalAxis = childActor->getGlobalPosition() - parentActor->getGlobalPosition();
vGlobalAxis.normalize();
jointDesc.setGlobalAxis(vGlobalAxis);
*/
jointDesc.jointFlags &= ~NX_JF_COLLISION_ENABLED;
jointToReturn = nxScene[iScene]->createJoint(jointDesc);
// assert( jointToReturn );
}
}
// assert( jointToReturn );
return jointToReturn;
}
static void* createNovodexGeometry(RagdollGeometry* rg, NxGroupType group, F32 fDensity, int iSceneNum)
{
if ( rg->geom == RAG_GEOM_CAPSULE)
return nwCreateCapsuleActor(rg->mOffsetMat, rg->fRadius, rg->fHeight, group, fDensity, iSceneNum);
else if ( rg->geom == RAG_GEOM_SPHERE )
return nwCreateSphereActor(rg->mOffsetMat, rg->fRadius, group, fDensity, iSceneNum );
else // iGeom == RAG_GEOM_BOX
return nwCreateBoxActor(rg->mOffsetMat, rg->vSize, group, fDensity, iSceneNum);
}
static bool findChildRelativePositionFromBoneId(GfxNode* parentNode, BoneId boneId, const Mat4 mParentMat, Vec3 vResult)
{
// Recurse through tree
GfxNode* childNode = parentNode->child;
if(boneId == parentNode->anim_id)
{
copyVec3(mParentMat[3], vResult);
return true;
}
while (childNode)
{
Mat4 mXform;
mulMat4(mParentMat, childNode->mat, mXform);
if(findChildRelativePositionFromBoneId(childNode, boneId, mXform, vResult))
return true;
childNode = childNode->next;
}
return false;
}
static GfxNode* findChildNodeFromBoneID(GfxNode* parentNode, BoneId boneId )
{
// Recurse through tree
GfxNode* childNode = parentNode->child;
if(boneId == parentNode->anim_id)
return parentNode;
while (childNode)
{
GfxNode* childSearch = findChildNodeFromBoneID(childNode, boneId);
if (childSearch)
return childSearch;
childNode = childNode->next;
}
return NULL;
}
static void calcGeomParamsFromBoneID(BoneId boneId, RagdollGeometry* rg, const Vec3 geomScale, GfxNode* node, SeqInst* seq, int iSceneNum)
{
rg->fHeight = 1.0f * geomScale[1];
rg->fRadius = 0.3f * geomScale[0];
copyVec3(onevec3, rg->vSize);
Vec3 vResult;
rg->bCCD = false;
switch(boneId)
{
xcase BONEID_HIPS:
rg->bOffset = false;
rg->geom = RAG_GEOM_BOX;
rg->bCCD = true;
{
Vec3 vResultA, vResultB;
bool bFoundA, bFoundB;
// Width
bFoundA = findChildRelativePositionFromBoneId(node, BONEID_ULEGR, unitmat, vResultA);
bFoundB = findChildRelativePositionFromBoneId(node, BONEID_ULEGL, unitmat, vResultB);
if ( bFoundA && bFoundB )
{
Vec3 vDiff;
subVec3(vResultA, vResultB, vDiff);
rg->vSize[0] = fabsf(vDiff[0] * geomScale[0]);
}
else
{
rg->vSize[0] = 0.5f * geomScale[0];
}
// Height
bFoundA = findChildRelativePositionFromBoneId(node, BONEID_WAIST, unitmat, vResultA);
if ( bFoundA )
{
rg->vSize[1] = fabsf(vResultA[1] * 0.5f * geomScale[1]);
}
else
{
rg->vSize[1] = 0.7f * geomScale[1];
}
}
if ( geomScale[0] > 0)
rg->vSize[2] = (0.4f * rg->vSize[0] / geomScale[0]) * geomScale[2];
xcase BONEID_ULEGR:
case BONEID_ULEGL:
if(findChildRelativePositionFromBoneId(node, BoneId(boneId+2), unitmat, vResult)) // lower legs
rg->fHeight = lengthVec3(vResult) * geomScale[1];
else
rg->fHeight = 1.2f * geomScale[1]; // default
xcase BONEID_LLEGR:
case BONEID_LLEGL:
rg->bCCD = true;
if(findChildRelativePositionFromBoneId(node, BoneId(boneId+4), unitmat, vResult)) // toes
rg->fHeight = lengthVec3(vResult) * geomScale[1];
else
rg->fHeight = 1.6f * geomScale[1]; // default
xcase BONEID_CHEST:
rg->bOffset = false;
rg->geom = RAG_GEOM_BOX;
rg->bCCD = true;
{
Vec3 vResultA, vResultB;
bool bFoundA, bFoundB;
// Width
bFoundA = findChildRelativePositionFromBoneId(node, BONEID_UARMR, unitmat, vResultA);
bFoundB = findChildRelativePositionFromBoneId(node, BONEID_UARML, unitmat, vResultB);
if ( bFoundA && bFoundB )
{
Vec3 vDiff;
subVec3(vResultA, vResultB, vDiff);
rg->vSize[0] = fabsf(vDiff[0] * 0.5f * geomScale[0]);
}
else
{
rg->vSize[0] = 0.5f * geomScale[0];
}
// Height
bFoundA = findChildRelativePositionFromBoneId(seq->gfx_root->child, BONEID_NECK, unitmat, vResultA);
if ( bFoundA )
{
rg->vSize[1] = fabsf(vResultA[1] * 0.5f * geomScale[1]);
}
else
{
rg->vSize[1] = 0.7f * geomScale[1];
}
}
if ( geomScale[0] > 0)
rg->vSize[2] = (0.4f * rg->vSize[0] / geomScale[0]) * geomScale[2];
xcase BONEID_UARMR:
case BONEID_UARML:
if(boneId == BONEID_UARMR)
rollMat3(RAD(-90.0f), rg->mOffsetMat);
else
rollMat3(RAD(90.0f), rg->mOffsetMat);
rg->fRadius = 0.3f * geomScale[2];
if(findChildRelativePositionFromBoneId(node, BoneId(boneId+2), unitmat, vResult)) // lower arm
rg->fHeight = lengthVec3(vResult) * geomScale[1];
else
rg->fHeight = 0.9f * geomScale[0];
xcase BONEID_LARMR:
case BONEID_LARML:
rg->bCCD = true;
if(boneId == BONEID_LARMR)
rollMat3(RAD(-90.0f), rg->mOffsetMat);
else
rollMat3(RAD(90.0f), rg->mOffsetMat);
rg->fRadius = 0.3f * geomScale[2];
if(findChildRelativePositionFromBoneId(node, BoneId(boneId+4), unitmat, vResult)) // fingers
rg->fHeight = lengthVec3(vResult) * geomScale[1];
else
rg->fHeight = 0.6f * geomScale[0];
xcase BONEID_HEAD:
rg->fHeight = 0.5f * geomScale[1];
rg->bOffset = false;
xcase BONEID_WAIST:
/* Snakeman
case 89: //Fore_FootL
uiSubBoneId = 92;
bSnakeTail = true;
break;
case 92: //Fore_LlegL
uiSubBoneId = 87;
bSnakeTail = true;
break;
case 87: //Fore_ULegL
uiSubBoneId = 79;
bSnakeTail = true;
break;
case 79: //Hind_ULegL
uiSubBoneId = 80;
bSnakeTail = true;
break;
case 80: //Hind_LlegL
uiSubBoneId = 81;
bSnakeTail = true;
break;
case 81: //Hind_FootL
uiSubBoneId = 82;
bSnakeTail = true;
break;
case 82: //Hind_ToeL
uiSubBoneId = 91;
bSnakeTail = true;
break;
case 91: //Hind_ULegR
uiSubBoneId = 85;
bSnakeTail = true;
break;
*/
xdefault:
;
}
}
void* createRagdollGeometry(Mat4 mWorldSpaceMat, BoneId boneId, Vec3 geomScale, GfxNode * node, SeqInst* seq, int iSceneNum)
{
RagdollGeometry rg;
rg.geom = RAG_GEOM_CAPSULE;
rg.bOffset = true;
Vec3 vOffset;
copyMat4(mWorldSpaceMat, rg.mOffsetMat);
/*
if ( bSnakeTail )
{
GfxNode* pChildNode = findChildNodeFromBoneID(node, uiSubBoneId);
if ( pChildNode )
{
Vec3 vDiff;
subVec3(pChildNode->mat[3], node->mat[3], vDiff);
fHeight = lengthVec3(vDiff) * geomScale[1] * 2.0f;
}
else
{
fHeight = 0.3f * geomScale[1]; // default
}
}
*/
calcGeomParamsFromBoneID(boneId, &rg, geomScale, node, seq, iSceneNum );
if ( rg.bOffset )
{
scaleVec3(rg.mOffsetMat[1],rg.fHeight * 0.5f, vOffset);
subVec3(rg.mOffsetMat[3], vOffset, rg.mOffsetMat[3]);
}
F32 fDensity = 1.f;
void* actor = createNovodexGeometry(&rg, nxGroupRagdoll, fDensity, iSceneNum);
if ( actor )
{
nwSetActorSleepVelocities(actor, ragdollConstants.angularSleepVelocity, ragdollConstants.linearSleepVelocity);
nwSetActorDamping(actor, ragdollConstants.angularDamping, ragdollConstants.linearDamping);
nwSetActorMass(actor, fDensity*geomScale[0]*geomScale[1]*geomScale[2]);
if ( rg.bCCD && ragdollConstants.doCCD )
{
nwAddCCDSkeletonForActor(actor);
}
}
return actor;
}
#ifdef CLIENT
static void drawRagdollBone( Mat4 mWorldSpaceMat, BoneId boneId, const Vec3 geomScale, GfxNode * node, SeqInst* seq )
{
RagdollGeometry rg;
Vec3 vOffset;
rg.geom = RAG_GEOM_CAPSULE;
rg.bOffset = true;
copyMat4(mWorldSpaceMat, rg.mOffsetMat);
calcGeomParamsFromBoneID(boneId, &rg, geomScale, node, seq, NX_CLIENT_SCENE);
if(boneId == BONEID_UARMR)
{
int asijck = 0;
}
if ( rg.bOffset )
{
scaleVec3(rg.mOffsetMat[1],rg.fHeight * 1.0f, vOffset);
subVec3(rg.mOffsetMat[3], vOffset, rg.mOffsetMat[3]);
}
Vec3 vStart, vEnd, vEndXformed;
copyVec3( rg.mOffsetMat[3], vStart);
zeroVec3(vEnd);
vEnd[1] = rg.fHeight;
mulVecMat3(vEnd, rg.mOffsetMat, vEndXformed);
addVec3(vStart, vEndXformed, vEnd);
//if(uiBoneId == BONEID_ULEGR)
drawLine3D(vStart, vEnd, 0xffffffff);
}
void drawRagdollSkeleton( GfxNode* rootNode, Mat4 parentMat, SeqInst* seq )
{
GfxNode * node;
for(node = rootNode ; node ; node = node->next)
{
Mat4 mChildMat;
Vec3 vDiff;
if ( seq->handle != node->seqHandle )
continue;
mulMat4(parentMat, node->mat, mChildMat);
//if(node->anim_id == BONEID_LLEGR)
drawLine3D(parentMat[3], mChildMat[3], 0x790000ff);
subVec3(parentMat[3], mChildMat[3], vDiff);
if (!isRagdollBone(node->anim_id))
{
if ( node->child )
drawRagdollSkeleton(node->child, mChildMat, seq );
continue;
}
drawRagdollBone(mChildMat, node->anim_id, onevec3, node, seq);
drawRagdollSkeleton(node->child, mChildMat, seq );
}
}
#endif
static Ragdoll* pLastHips = NULL;
int walkSkeletonAndCreateRagdoll( GfxNode* rootNode, const Mat4 parentMat, Ragdoll* parentRagdoll, SeqInst* seq, Ragdoll** rootRagdoll, Vec3 vInitialVel, bool bCreateNovodexPresence, Vec3 vScale, int iSceneNum )
{
GfxNode * node;
int iBoneCount = 0; // we are a bone, necessarily
for(node = rootNode ; node ; node = node->next)
{
// Only deal with nodes attached to this seqinst
if ( seq->handle != node->seqHandle )
continue;
if (!isRagdollBone(node->anim_id))
{
// This bone is excluded, but it might have included children
if ( node->child )
{
Mat4 mWorldSpaceMat;
Mat4 mNodeMat;
copyMat4(node->mat, mNodeMat);
mulVecVec3(mNodeMat[3], vScale, mNodeMat[3]);
mulMat4(parentMat, mNodeMat, mWorldSpaceMat);
iBoneCount += walkSkeletonAndCreateRagdoll(node->child, mWorldSpaceMat, parentRagdoll, seq, NULL, vInitialVel, bCreateNovodexPresence, vScale, iSceneNum);
}
continue;
}
// One last test, we must know that there is geometry for this before it can be a ragdoll bone
/*
char buf[100];
sprintf( buf, "GEO_%s", getBoneNameFromNumber( node->anim_id ) );
char* cFileName = "player_library/G_steve_blockman.anm";
Model* pModel = modelFind( buf, cFileName, LOAD_NOW, GEO_INIT_FOR_DRAWING | GEO_USED_BY_GFXTREE);
if (!pModel)
continue;
*/
// Ok, this node counts as a ragdoll bone
++iBoneCount;
// Allocate it
Ragdoll* newRagdoll = (Ragdoll*)malloc(sizeof(Ragdoll));
// Set defaults
newRagdoll->boneId = node->anim_id;
newRagdoll->iSceneNum = iSceneNum;
newRagdoll->child = NULL;
newRagdoll->next = NULL;
// Snakeman hack!
/*
if ( node->anim_id == 89 )
{
parentRagdoll = pLastHips;
}
*/
newRagdoll->parent = parentRagdoll;
newRagdoll->hist_latest = 0;
memset(newRagdoll->absTimeHist, 0, sizeof(newRagdoll->absTimeHist));
if ( node->anim_id == 0)
pLastHips = newRagdoll;
// Calculate quaternion from initial node orientation
mat3ToQuat(node->mat, newRagdoll->qCurrentRot);
quatNormalize(newRagdoll->qCurrentRot);
// copyVec3(node->mat[3], newRagdoll->vCurrentPos);
// Calculate world space position, and create actor there
Mat4 mWorldSpaceMat;
Mat4 mNodeMat;
copyMat4(node->mat, mNodeMat);
mulVecVec3(mNodeMat[3], vScale, mNodeMat[3]);
mulMat4(parentMat, mNodeMat, mWorldSpaceMat);
//copyMat3(unitmat, node->mat);
if (bCreateNovodexPresence)
{
// Vec3 vNewInitialVel;
newRagdoll->pActor = createRagdollGeometry(mWorldSpaceMat, newRagdoll->boneId, vScale, node, seq, iSceneNum);
assert( newRagdoll->pActor );
if ( newRagdoll->pActor )
{
F32 omega, rho;
Vec3 vRandAxis;
Vec3 vResult;
getRandomPointOnSphereSurface(&omega, &rho );
sphericalCoordsToVec3(vRandAxis, omega, rho, 1.0f);
if ( lengthVec3Squared(vInitialVel) > 0.1f )
{
scaleVec3(vRandAxis, lengthVec3(vInitialVel) * 0.6f, vRandAxis );
}
else
{
scaleVec3(vRandAxis, 0.5f, vRandAxis);
}
addVec3(vRandAxis, vInitialVel, vResult);
nwSetActorLinearVelocity(newRagdoll->pActor, vResult );
}
// Create novodex actor and joint for this ragdoll bone
/*
int iVert=0;
Vec3* verts = (Vec3*)_alloca(pModel->vert_count * sizeof(*verts));
geoUnpackDeltas(&pModel->pack.verts, verts, 3, pModel->vert_count, PACK_F32);
newRagdoll->pActor = nwCreateConvexActor(pModel->name, mWorldSpaceMat, (float*)verts, pModel->vert_count, nxGroupDebris, NULL, 1.0f );
*/
if ( parentRagdoll && parentRagdoll->pActor )
newRagdoll->pJointToParent = jointRagdoll( (NxActor*)parentRagdoll->pActor, (NxActor*)newRagdoll->pActor, newRagdoll->boneId, mWorldSpaceMat[3], iSceneNum );
else
newRagdoll->pJointToParent = NULL;
}
else
{
newRagdoll->pActor = newRagdoll->pJointToParent = NULL;
}
// Ok, now we have our new ragdoll, insert it into our ragdoll tree
// assuming we're not the root
if ( parentRagdoll )
{
if ( !parentRagdoll->child )
parentRagdoll->child = newRagdoll;
else
{
Ragdoll* spotForNewRagdoll = parentRagdoll->child;
while (spotForNewRagdoll->next)
spotForNewRagdoll = spotForNewRagdoll->next;
spotForNewRagdoll->next = newRagdoll;
}
}
else
{
assert(rootRagdoll);
*rootRagdoll = newRagdoll;
}
// Now, continue with our child, if it exists
if ( node->child )
iBoneCount += walkSkeletonAndCreateRagdoll(node->child, mWorldSpaceMat, newRagdoll, seq, NULL, vInitialVel, bCreateNovodexPresence, vScale, iSceneNum);
}
if ( parentRagdoll )
parentRagdoll->numBones = iBoneCount+1;
return iBoneCount;
}
// -------------------------------------------------------------------------------------------------------------------
static void nwFreeRagdoll(Ragdoll* parentRagdoll, int iScene)
{
if (!parentRagdoll)
return;
Ragdoll* pChildRagdoll = parentRagdoll->child;
while (pChildRagdoll != NULL )
{
nwFreeRagdoll( pChildRagdoll, iScene);
Ragdoll* pNextRagdoll = pChildRagdoll->next;
free( pChildRagdoll );
pChildRagdoll = pNextRagdoll;
}
if ( nwEnabled() )
{
if (parentRagdoll->pJointToParent)
{
assert( iScene >= 0 && iScene < MAX_NX_SCENES);
if ( nxScene[iScene] )
nxScene[iScene]->releaseJoint( *((NxJoint*)parentRagdoll->pJointToParent) );
parentRagdoll->pJointToParent = NULL;
}
if (parentRagdoll->pActor)
{
assert( iScene >= 0 && iScene < MAX_NX_SCENES);
//nwDeleteActor(parentRagdoll->pActor);
if ( nxScene[iScene] )
{
NxActor* actor = (NxActor*)parentRagdoll->pActor;
nwRemoveCCDSkeletonForActor(actor);
nxScene[iScene]->releaseActor( *actor );
}
nx_state.dynamicActorCount--;
parentRagdoll->pActor = NULL;
}
}
else
{
parentRagdoll->pJointToParent = NULL;
parentRagdoll->pActor = NULL;
}
parentRagdoll->iSceneNum = -1; // we've removed it from the scene
}
static void nwDeleteRagdollImmediately(Ragdoll* parentRagdoll);
// QUEUED STUFF
#ifdef SERVER
#if !BEACONIZER
void nwCreateRagdollQueues()
{
if ( ragdollCreationQueue )
{
assert( ragdollDeletionWithFreeQueue );
return;
}
const int iMaxQueueSize = 128;
ragdollCreationQueue = createQueue();
ragdollDeletionWithFreeQueue = createQueue();
qSetMaxSizeLimit( ragdollCreationQueue, iMaxQueueSize );
qSetMaxSizeLimit( ragdollDeletionWithFreeQueue, iMaxQueueSize );
initQueue( ragdollCreationQueue, 16 );
initQueue( ragdollDeletionWithFreeQueue, 16 );
}
// -------------------------------------------------------------------------------------------------------------------
void nwDeleteRagdollQueues()
{
// flush deletion queues
processRagdollDeletionQueues();
assert( qGetSize(ragdollDeletionWithFreeQueue) == 0);
// ignore creation queues, just destroy the queue
//nwProcessRagdollQueue();
destroyQueue(ragdollCreationQueue);
destroyQueue(ragdollDeletionWithFreeQueue);
ragdollCreationQueue = NULL;
ragdollDeletionWithFreeQueue = NULL;
}
// -------------------------------------------------------------------------------------------------------------------
void processRagdollDeletionQueues()
{
assert( ragdollDeletionWithFreeQueue );
Ragdoll* pRagdoll;
pRagdoll = (Ragdoll*)qDequeue(ragdollDeletionWithFreeQueue);
while ( pRagdoll )
{
nwDeleteRagdollImmediately(pRagdoll);
pRagdoll = (Ragdoll*)qDequeue(ragdollDeletionWithFreeQueue);
}
}
#endif
#endif
// -------------------------------------------------------------------------------------------------------------------
static void nwDeleteRagdollImmediately(Ragdoll* parentRagdoll)
{
if (!parentRagdoll)
return;
int iScene = parentRagdoll->iSceneNum;
if ( iScene >= 0 )
{
nwEndThread(iScene);
}
nwFreeRagdoll(parentRagdoll, iScene );
if ( nwEnabled() && iScene >= 0 )
{
removeInfluenceSphere(iScene);
nwDeleteScene(iScene);
}
free(parentRagdoll);
}
// -------------------------------------------------------------------------------------------------------------------
void nwDeleteRagdoll(Ragdoll* parentRagdoll)
{
if (!parentRagdoll)
return;
#ifdef CLIENT
nwDeleteRagdollImmediately(parentRagdoll);
return;
#elif SERVER
if ( nwEnabled() )
{
assert( ragdollDeletionWithFreeQueue );
int iSuccess;
if(qIsFull(ragdollDeletionWithFreeQueue))
qSetMaxSizeLimit(ragdollDeletionWithFreeQueue, 2*qGetMaxSize(ragdollDeletionWithFreeQueue));
iSuccess = qEnqueue( ragdollDeletionWithFreeQueue, (void*) parentRagdoll );
assert( iSuccess );
}
else
{
nwDeleteRagdollImmediately(parentRagdoll);
}
#endif
}
// -------------------------------------------------------------------------------------------------------------------
#ifdef CLIENT
Ragdoll* nwCreateRagdollNoPhysics( Entity* e )
{
assert(e);
if ( !e || !e->seq || !e->seq->gfx_root || !e->seq->gfx_root->child)
return NULL;
PERFINFO_AUTO_START("nwCreateRagdollNoPhysics", 1);
int iRagdollScene = -1;
GfxNode* rootNode = e->seq->gfx_root->child;
//printf("Animation = %s\n", e->seq->animation.move->name);
//printf("RootNode up = %.2f\n", rootNode->mat[2][1]);
Ragdoll* rootRagdoll = NULL;
Vec3 vInitialVel;
copyVec3(e->motion->vel, vInitialVel);
#ifdef RAGDOLL
// Calculate first frame ragdoll offset, since we switch from mat corresponding
// from root to hips
{
Vec3 vOffsetPos;
Vec3 vCombatBias;
zeroVec3(vCombatBias);
vCombatBias[2] = -0.8f;
addVec3(vCombatBias, e->seq->gfx_root->child->mat[3], vOffsetPos);
mulVecMat3(vOffsetPos, ENTMAT(e), e->ragdoll_offset_pos);
//mat3ToQuat(e->seq->gfx_root->child->mat, e->ragdoll_offset_qrot);
}
#endif
Vec3 vScale;
F32 fCostumeScale = e->costume ? (100.0f + e->costume->appearance.fScale) * 0.01f : 1.0f;
scaleVec3(e->seq->currgeomscale, fCostumeScale, vScale);
walkSkeletonAndCreateRagdoll( rootNode, ENTMAT(e), NULL, e->seq, &rootRagdoll, vInitialVel, false, vScale, iRagdollScene);
//rootRagdoll->numBones++;
//assert (rootRagdoll->next == NULL);
PERFINFO_AUTO_STOP();
return rootRagdoll;
}
#endif
// -------------------------------------------------------------------------------------------------------------------
static void initRagdollConstants()
{
ragdollConstants.swing_spring = 0.2f;
ragdollConstants.swing_damper = 0.1;
ragdollConstants.twist_spring = 0.2f;
ragdollConstants.twist_damper = 0.1f;
ragdollConstants.swing_hardness = 0.9f;
ragdollConstants.twist_hardness = 0.9f;
ragdollConstants.hinge_hardness = 0.9f;
ragdollConstants.projection_distance = 0.15f;
ragdollConstants.linearDamping = 0.15f;
ragdollConstants.angularDamping = 0.20f;
ragdollConstants.linearSleepVelocity = 0.35f;
ragdollConstants.angularSleepVelocity = 0.34f;
ragdollConstants.doCCD = true;
ragdollConstants.bInited = true;
}
#ifdef SERVER
void nwPushRagdoll( Entity* e )
{
assert(e && ragdollCreationQueue );
if ( !ragdollConstants.bInited )
{
initRagdollConstants();
}
if (qFind(ragdollCreationQueue, (void*)e ))
return; // already enqueued
int iSuccess = qEnqueue( ragdollCreationQueue, (void*) e );
// ARM NOTE: This devassert seems to be causing false positive crashes internally.
// I used I Win Button to kill 720 dudes at the same instant, and the server stood through it.
// Feel free to re-add it if you know that I did something wrong here.
//devassert( iSuccess );
}
// -------------------------------------------------------------------------------------------------------------------
static void nwCreateDelayedRagdoll( Entity* e )
{
assert(e);
if ( !nwEnabled())
return;
e->firstRagdollFrame = 1;
if ( !e || !e->seq || !e->seq->gfx_root || !e->seq->gfx_root->child)
return;
PERFINFO_AUTO_START("nwCreateRagdoll", 1);
int iRagdollScene = nwCreateScene();
if ( iRagdollScene < 0 )
{
PERFINFO_AUTO_STOP();
return;
}
addInfluenceSphere(iRagdollScene, e);
if ( !ragdollConstants.bInited )
{
initRagdollConstants();
}
GfxNode* rootNode = e->seq->gfx_root->child;
Ragdoll* rootRagdoll = NULL;
Vec3 vInitialVel;
copyVec3(e->motion->vel, vInitialVel);
Vec3 vScale;
F32 fCostumeScale = (100.0f + e->costume->appearance.fScale) * 0.01f;
scaleVec3(e->seq->currgeomscale, fCostumeScale, vScale);
walkSkeletonAndCreateRagdoll( rootNode, ENTMAT(e), NULL, e->seq, &rootRagdoll, vInitialVel, true, vScale, iRagdollScene);
//rootRagdoll->numBones++;
//assert (rootRagdoll->next == NULL);
PERFINFO_AUTO_STOP();
e->ragdoll = rootRagdoll;
}
// -------------------------------------------------------------------------------------------------------------------
void nwProcessRagdollQueue( )
{
Entity* e;
assert( ragdollCreationQueue );
e = (Entity*)qDequeue(ragdollCreationQueue);
while ( e )
{
nwCreateDelayedRagdoll(e);
e = (Entity*)qDequeue(ragdollCreationQueue);
}
}
#endif SERVER
// -------------------------------------------------------------------------------------------------------------------
void nwSetRagdollFromQuaternions( Ragdoll* ragdoll, Quat qRoot )
{
Ragdoll* pRagdoll;
for( pRagdoll = ragdoll; pRagdoll; pRagdoll = pRagdoll->next )
{
// Set quat from actor
NxActor* pActor = (NxActor*)pRagdoll->pActor;
if ( pActor )
{
NxQuat nxqWorldQuat = pActor->getGlobalOrientationQuat();
Quat qWorldQuat;
copyQuat((float*)&nxqWorldQuat, qWorldQuat);
Quat qLocal;
Quat qInverseRoot;
float fFixAngle = 0.0f;
//Quat qActorSpaceQuat;
quatInverse(qRoot, qInverseRoot);
switch (pRagdoll->boneId)
{
case 7:
case 9:
fFixAngle = RAD(90.0f);
break;
case 8:
case 10:
fFixAngle = RAD(-90.0f);
break;
default:
break;
};
if ( fFixAngle != 0.0f)
{
Mat3 mFix;
quatToMat(qWorldQuat, mFix);
rollMat3World(fFixAngle, mFix);
mat3ToQuat(mFix, qWorldQuat);
//assert(validateMat3(mFix));
}
// Snakeman hack!
/*
if ( pRagdoll->boneId == 89)
{
unitquat(qInverseRoot);
}
*/
quatMultiply(qInverseRoot, qWorldQuat, qLocal);
quatInverse(qLocal,qLocal);
copyQuat(qLocal, pRagdoll->qCurrentRot);
//assert(quatIsValid(qWorldQuat));
nwSetRagdollFromQuaternions(pRagdoll->child, qWorldQuat);
}
else
{
// we're not updating this quat, so multiply it through
Quat qNewRoot;
if (0 && quatIsValid(pRagdoll->qCurrentRot))
quatMultiply(qRoot, pRagdoll->qCurrentRot, qNewRoot);
else
copyQuat(qRoot, qNewRoot);
//assert(quatIsValid(qNewRoot));
nwSetRagdollFromQuaternions(pRagdoll->child, qNewRoot);
}
}
}
#endif
| [
"omegablast2002@yahoo.com"
] | omegablast2002@yahoo.com |
c771d6605314457613e9b4b050b716f8a19cd9c1 | bb6ebff7a7f6140903d37905c350954ff6599091 | /remoting/host/win/host_service.cc | 7c1197a87ccfe14478e99b8a8ac10ba5f5acba0a | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 13,925 | cc | // Copyright (c) 2012 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.
//
// This file implements the Windows service controlling Me2Me host processes
// running within user sessions.
#include "remoting/host/win/host_service.h"
#include <sddl.h>
#include <windows.h>
#include <wtsapi32.h>
#include "base/base_paths.h"
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "base/win/message_window.h"
#include "base/win/scoped_com_initializer.h"
#include "remoting/base/auto_thread.h"
#include "remoting/base/scoped_sc_handle_win.h"
#include "remoting/host/branding.h"
#include "remoting/host/daemon_process.h"
#include "remoting/host/host_exit_codes.h"
#include "remoting/host/logging.h"
#include "remoting/host/win/com_security.h"
#include "remoting/host/win/core_resource.h"
#include "remoting/host/win/wts_terminal_observer.h"
namespace remoting {
namespace {
const char kIoThreadName[] = "I/O thread";
// Command line switches:
// "--console" runs the service interactively for debugging purposes.
const char kConsoleSwitchName[] = "console";
// Security descriptor allowing local processes running under SYSTEM or
// LocalService accounts to call COM methods exposed by the daemon.
const wchar_t kComProcessSd[] =
SDDL_OWNER L":" SDDL_LOCAL_SYSTEM
SDDL_GROUP L":" SDDL_LOCAL_SYSTEM
SDDL_DACL L":"
SDDL_ACE(SDDL_ACCESS_ALLOWED, SDDL_COM_EXECUTE_LOCAL, SDDL_LOCAL_SYSTEM)
SDDL_ACE(SDDL_ACCESS_ALLOWED, SDDL_COM_EXECUTE_LOCAL, SDDL_LOCAL_SERVICE);
// Appended to |kComProcessSd| to specify that only callers running at medium or
// higher integrity level are allowed to call COM methods exposed by the daemon.
const wchar_t kComProcessMandatoryLabel[] =
SDDL_SACL L":"
SDDL_ACE(SDDL_MANDATORY_LABEL, SDDL_NO_EXECUTE_UP, SDDL_ML_MEDIUM);
} // namespace
HostService* HostService::GetInstance() {
return Singleton<HostService>::get();
}
bool HostService::InitWithCommandLine(const base::CommandLine* command_line) {
base::CommandLine::StringVector args = command_line->GetArgs();
if (!args.empty()) {
LOG(ERROR) << "No positional parameters expected.";
return false;
}
// Run interactively if needed.
if (run_routine_ == &HostService::RunAsService &&
command_line->HasSwitch(kConsoleSwitchName)) {
run_routine_ = &HostService::RunInConsole;
}
return true;
}
int HostService::Run() {
return (this->*run_routine_)();
}
bool HostService::AddWtsTerminalObserver(const std::string& terminal_id,
WtsTerminalObserver* observer) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
RegisteredObserver registered_observer;
registered_observer.terminal_id = terminal_id;
registered_observer.session_id = kInvalidSessionId;
registered_observer.observer = observer;
bool session_id_found = false;
std::list<RegisteredObserver>::const_iterator i;
for (i = observers_.begin(); i != observers_.end(); ++i) {
// Get the attached session ID from another observer watching the same WTS
// console if any.
if (i->terminal_id == terminal_id) {
registered_observer.session_id = i->session_id;
session_id_found = true;
}
// Check that |observer| hasn't been registered already.
if (i->observer == observer)
return false;
}
// If |terminal_id| is new, enumerate all sessions to see if there is one
// attached to |terminal_id|.
if (!session_id_found)
registered_observer.session_id = LookupSessionId(terminal_id);
observers_.push_back(registered_observer);
if (registered_observer.session_id != kInvalidSessionId) {
observer->OnSessionAttached(registered_observer.session_id);
}
return true;
}
void HostService::RemoveWtsTerminalObserver(WtsTerminalObserver* observer) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
std::list<RegisteredObserver>::const_iterator i;
for (i = observers_.begin(); i != observers_.end(); ++i) {
if (i->observer == observer) {
observers_.erase(i);
return;
}
}
}
HostService::HostService() :
run_routine_(&HostService::RunAsService),
service_status_handle_(0),
stopped_event_(true, false),
weak_factory_(this) {
}
HostService::~HostService() {
}
void HostService::OnSessionChange(uint32 event, uint32 session_id) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
DCHECK_NE(session_id, kInvalidSessionId);
// Process only attach/detach notifications.
if (event != WTS_CONSOLE_CONNECT && event != WTS_CONSOLE_DISCONNECT &&
event != WTS_REMOTE_CONNECT && event != WTS_REMOTE_DISCONNECT) {
return;
}
// Assuming that notification can arrive later query the current state of
// |session_id|.
std::string terminal_id;
bool attached = LookupTerminalId(session_id, &terminal_id);
std::list<RegisteredObserver>::iterator i = observers_.begin();
while (i != observers_.end()) {
std::list<RegisteredObserver>::iterator next = i;
++next;
// Issue a detach notification if the session was detached from a client or
// if it is now attached to a different client.
if (i->session_id == session_id &&
(!attached || !(i->terminal_id == terminal_id))) {
i->session_id = kInvalidSessionId;
i->observer->OnSessionDetached();
i = next;
continue;
}
// The client currently attached to |session_id| was attached to a different
// session before. Reconnect it to |session_id|.
if (attached && i->terminal_id == terminal_id &&
i->session_id != session_id) {
WtsTerminalObserver* observer = i->observer;
if (i->session_id != kInvalidSessionId) {
i->session_id = kInvalidSessionId;
i->observer->OnSessionDetached();
}
// Verify that OnSessionDetached() above didn't remove |observer|
// from the list.
std::list<RegisteredObserver>::iterator j = next;
--j;
if (j->observer == observer) {
j->session_id = session_id;
observer->OnSessionAttached(session_id);
}
}
i = next;
}
}
void HostService::CreateLauncher(
scoped_refptr<AutoThreadTaskRunner> task_runner) {
// Launch the I/O thread.
scoped_refptr<AutoThreadTaskRunner> io_task_runner =
AutoThread::CreateWithType(
kIoThreadName, task_runner, base::MessageLoop::TYPE_IO);
if (!io_task_runner) {
LOG(FATAL) << "Failed to start the I/O thread";
return;
}
daemon_process_ = DaemonProcess::Create(
task_runner,
io_task_runner,
base::Bind(&HostService::StopDaemonProcess, weak_ptr_));
}
int HostService::RunAsService() {
SERVICE_TABLE_ENTRYW dispatch_table[] = {
{ const_cast<LPWSTR>(kWindowsServiceName), &HostService::ServiceMain },
{ NULL, NULL }
};
if (!StartServiceCtrlDispatcherW(dispatch_table)) {
PLOG(ERROR) << "Failed to connect to the service control manager";
return kInitializationFailed;
}
// Wait until the service thread completely exited to avoid concurrent
// teardown of objects registered with base::AtExitManager and object
// destoyed by the service thread.
stopped_event_.Wait();
return kSuccessExitCode;
}
void HostService::RunAsServiceImpl() {
base::MessageLoopForUI message_loop;
base::RunLoop run_loop;
main_task_runner_ = message_loop.message_loop_proxy();
weak_ptr_ = weak_factory_.GetWeakPtr();
// Register the service control handler.
service_status_handle_ = RegisterServiceCtrlHandlerExW(
kWindowsServiceName, &HostService::ServiceControlHandler, this);
if (service_status_handle_ == 0) {
PLOG(ERROR) << "Failed to register the service control handler";
return;
}
// Report running status of the service.
SERVICE_STATUS service_status;
ZeroMemory(&service_status, sizeof(service_status));
service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
service_status.dwCurrentState = SERVICE_RUNNING;
service_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN |
SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_SESSIONCHANGE;
service_status.dwWin32ExitCode = kSuccessExitCode;
if (!SetServiceStatus(service_status_handle_, &service_status)) {
PLOG(ERROR)
<< "Failed to report service status to the service control manager";
return;
}
// Initialize COM.
base::win::ScopedCOMInitializer com_initializer;
if (!com_initializer.succeeded())
return;
if (!InitializeComSecurity(base::WideToUTF8(kComProcessSd),
base::WideToUTF8(kComProcessMandatoryLabel),
false)) {
return;
}
CreateLauncher(scoped_refptr<AutoThreadTaskRunner>(
new AutoThreadTaskRunner(main_task_runner_,
run_loop.QuitClosure())));
// Run the service.
run_loop.Run();
weak_factory_.InvalidateWeakPtrs();
// Tell SCM that the service is stopped.
service_status.dwCurrentState = SERVICE_STOPPED;
service_status.dwControlsAccepted = 0;
if (!SetServiceStatus(service_status_handle_, &service_status)) {
PLOG(ERROR)
<< "Failed to report service status to the service control manager";
return;
}
}
int HostService::RunInConsole() {
base::MessageLoopForUI message_loop;
base::RunLoop run_loop;
main_task_runner_ = message_loop.message_loop_proxy();
weak_ptr_ = weak_factory_.GetWeakPtr();
int result = kInitializationFailed;
// Initialize COM.
base::win::ScopedCOMInitializer com_initializer;
if (!com_initializer.succeeded())
return result;
if (!InitializeComSecurity(base::WideToUTF8(kComProcessSd),
base::WideToUTF8(kComProcessMandatoryLabel),
false)) {
return result;
}
// Subscribe to Ctrl-C and other console events.
if (!SetConsoleCtrlHandler(&HostService::ConsoleControlHandler, TRUE)) {
PLOG(ERROR) << "Failed to set console control handler";
return result;
}
// Create a window for receiving session change notifications.
base::win::MessageWindow window;
if (!window.Create(base::Bind(&HostService::HandleMessage,
base::Unretained(this)))) {
PLOG(ERROR) << "Failed to create the session notification window";
goto cleanup;
}
// Subscribe to session change notifications.
if (WTSRegisterSessionNotification(window.hwnd(),
NOTIFY_FOR_ALL_SESSIONS) != FALSE) {
CreateLauncher(scoped_refptr<AutoThreadTaskRunner>(
new AutoThreadTaskRunner(main_task_runner_,
run_loop.QuitClosure())));
// Run the service.
run_loop.Run();
// Release the control handler.
stopped_event_.Signal();
WTSUnRegisterSessionNotification(window.hwnd());
result = kSuccessExitCode;
}
cleanup:
weak_factory_.InvalidateWeakPtrs();
// Unsubscribe from console events. Ignore the exit code. There is nothing
// we can do about it now and the program is about to exit anyway. Even if
// it crashes nothing is going to be broken because of it.
SetConsoleCtrlHandler(&HostService::ConsoleControlHandler, FALSE);
return result;
}
void HostService::StopDaemonProcess() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
daemon_process_.reset();
}
bool HostService::HandleMessage(
UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) {
if (message == WM_WTSSESSION_CHANGE) {
OnSessionChange(wparam, lparam);
*result = 0;
return true;
}
return false;
}
// static
BOOL WINAPI HostService::ConsoleControlHandler(DWORD event) {
HostService* self = HostService::GetInstance();
switch (event) {
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
self->main_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostService::StopDaemonProcess,
self->weak_ptr_));
return TRUE;
default:
return FALSE;
}
}
// static
DWORD WINAPI HostService::ServiceControlHandler(DWORD control,
DWORD event_type,
LPVOID event_data,
LPVOID context) {
HostService* self = reinterpret_cast<HostService*>(context);
switch (control) {
case SERVICE_CONTROL_INTERROGATE:
return NO_ERROR;
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
self->main_task_runner_->PostTask(
FROM_HERE, base::Bind(&HostService::StopDaemonProcess,
self->weak_ptr_));
return NO_ERROR;
case SERVICE_CONTROL_SESSIONCHANGE:
self->main_task_runner_->PostTask(FROM_HERE, base::Bind(
&HostService::OnSessionChange, self->weak_ptr_, event_type,
reinterpret_cast<WTSSESSION_NOTIFICATION*>(event_data)->dwSessionId));
return NO_ERROR;
default:
return ERROR_CALL_NOT_IMPLEMENTED;
}
}
// static
VOID WINAPI HostService::ServiceMain(DWORD argc, WCHAR* argv[]) {
HostService* self = HostService::GetInstance();
// Run the service.
self->RunAsServiceImpl();
// Release the control handler and notify the main thread that it can exit
// now.
self->stopped_event_.Signal();
}
int DaemonProcessMain() {
HostService* service = HostService::GetInstance();
if (!service->InitWithCommandLine(base::CommandLine::ForCurrentProcess())) {
return kUsageExitCode;
}
return service->Run();
}
} // namespace remoting
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
ca80201319fc676ff5a464c2dc55bc37b67de3ea | 7045bb4f95ada6e1669a3cd9520681b7e548c319 | /Meijer/Popup/Popup.h | a9b3d3a749c3282739dada71b92b2981b137f78f | [] | no_license | co185057/MeijerTESTSVN | 0ffe207db43c8e881fdbad66c1c058e25fe451f5 | 3a3df97b2decc1a04e6efe7c8ab74eff5409f39f | refs/heads/master | 2023-05-30T00:19:36.524059 | 2021-06-10T08:41:31 | 2021-06-10T08:41:31 | 375,576,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | h | // Popup.h : main header file for the POPUP application
//
#if !defined(AFX_POPUP_H__0B33DE7A_F2E9_11D4_8943_00A0C9EDD46B__INCLUDED_)
#define AFX_POPUP_H__0B33DE7A_F2E9_11D4_8943_00A0C9EDD46B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CPopupApp:
// See Popup.cpp for the implementation of this class
//
class CPopupApp : public CWinApp
{
public:
CPopupApp();
long m_lTimerID;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPopupApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CPopupApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_POPUP_H__0B33DE7A_F2E9_11D4_8943_00A0C9EDD46B__INCLUDED_)
| [
"co185057@ncr.com"
] | co185057@ncr.com |
2547cbb4abcba3a2a8d52efe4e798c355d372e6d | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/query/web/dll/errormsg.cxx | 20e51a42cfe65747ca31513267324a632e94065a | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,942 | cxx | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 2000.
//
// File: errormsg.cxx
//
// Contents: Error messages for output/running queries
//
// History: 96/Mar/3 DwightKr Created
//
//----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#define ERROR_MESSAGE_SIZE 512
//+---------------------------------------------------------------------------
//
// Function: GetErrorPageNoThrow - public
//
// Synposis: Generates an error page based on the error parameters passed.
//
// Arguments: [eErrorClass] - class of error (IDQ, HTX, restirction, etc)
// [status] - error code generated
// [ulErrorLine] - line on which the error occured
// [wcsErrorFileName] - name of file which generated the error
// [pVariableSet] - replaceable parameters which generated the error
// [pOutputFormat] - format of dates & numbers
// [locale] - locale of the browser
// [webServer] - the web server
// [vString] - virtual string to contain error code
//
// History: 96/Feb/29 DwightKr Created
//
//----------------------------------------------------------------------------
void GetErrorPageNoThrow(
int eErrorClass,
NTSTATUS status,
ULONG ulErrorLine,
WCHAR const * wcsErrorFileName,
CVariableSet * pVariableSet,
COutputFormat * pOutputFormat,
LCID locale,
CWebServer & webServer,
CVirtualString & vString )
{
//
// If the error was caused by a failure to WRITE to the web server,
// then don't bother trying to report an error, there is no one to
// receive it.
//
if ( eWebServerWriteError == eErrorClass )
{
ciGibDebugOut(( DEB_IWARN, "Failed to write to the web server" ));
return;
}
//
// If the error was the result of an access denied problem, then simply
// return a 401 error to the browser
//
WCHAR awcsErrorMessage[ERROR_MESSAGE_SIZE];
WCHAR * pwszErrorMessage = awcsErrorMessage;
ULONG cchAvailMessage = ERROR_MESSAGE_SIZE;
//
// Generate the Win32 error code by removing the facility code (7) and
// the error bit.
//
ULONG Win32status = status;
if ( (Win32status & (FACILITY_WIN32 << 16)) == (FACILITY_WIN32 << 16) )
{
Win32status &= ~( 0x80000000 | (FACILITY_WIN32 << 16) );
}
if ( (STATUS_ACCESS_DENIED == status) ||
(STATUS_NETWORK_ACCESS_DENIED == status) ||
(ERROR_ACCESS_DENIED == Win32status) ||
(ERROR_INVALID_ACCESS == Win32status) ||
(ERROR_NETWORK_ACCESS_DENIED == Win32status)
)
{
ciGibDebugOut(( DEB_WARN, "mapping 0x%x to 401 access denied\n", status ));
ReturnServerError( HTTP_STATUS_DENIED, webServer );
return;
}
//
// Map special error codes to their message equivalents.
//
if ( QUERY_E_DUPLICATE_OUTPUT_COLUMN == status )
{
status = MSG_CI_IDQ_DUPLICATE_COLUMN;
}
else if ( QUERY_E_INVALID_OUTPUT_COLUMN == status )
{
status = MSG_CI_IDQ_NO_SUCH_COLUMN_PROPERTY;
}
if ( 0 != wcsErrorFileName )
{
WCHAR *p = wcsrchr( wcsErrorFileName, L'\\' );
if ( 0 == p )
p = wcsrchr( wcsErrorFileName, L'/' );
if ( 0 == p )
p = wcsrchr( wcsErrorFileName, L':' );
if ( 0 != p )
wcsErrorFileName = p + 1;
}
//
// Don't pass a specific lang id to FormatMessage since it will
// fail if there's no message in that language. Instead set
// the thread locale, which will get FormatMessage to use a search
// algorithm to find a message of the appropriate language or
// use a reasonable fallback msg if there's none.
//
LCID SaveLCID = GetThreadLocale();
SetThreadLocale(locale);
switch (eErrorClass)
{
case eIDQParseError:
{
//
// These are errors encountered while parsing the IDQ file
//
DWORD_PTR args [] = {
(DWORD_PTR) ulErrorLine,
(DWORD_PTR) wcsErrorFileName
};
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
GetModuleHandle(L"idq.dll"),
status,
0,
pwszErrorMessage,
cchAvailMessage,
(va_list *) args ) )
{
ciGibDebugOut(( DEB_ERROR, "Format message failed with error 0x%x\n", GetLastError() ));
swprintf( pwszErrorMessage,
L"Processing of IDQ file %ls failed with error 0x%x\n",
wcsErrorFileName,
status );
}
}
break;
case eIDQPlistError:
{
//
// These are errors encountered while parsing the [names] section
//
if (wcsErrorFileName != 0)
{
DWORD_PTR args [] = {
(DWORD_PTR) wcsErrorFileName,
(DWORD_PTR) ulErrorLine,
};
NTSTATUS MsgNum = MSG_IDQ_FILE_MESSAGE;
if (ulErrorLine != 0)
{
MsgNum = MSG_IDQ_FILE_LINE_MESSAGE;
}
ULONG cchMsg = FormatMessage( FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
GetModuleHandle(L"idq.dll"),
MsgNum,
0,
pwszErrorMessage,
cchAvailMessage,
(va_list *) args );
pwszErrorMessage += cchMsg;
cchAvailMessage -= cchMsg;
}
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(L"query.dll"),
status,
0,
pwszErrorMessage,
cchAvailMessage,
0 ) )
{
ciGibDebugOut(( DEB_ERROR, "Format message failed with error 0x%x\n", GetLastError() ));
swprintf( pwszErrorMessage,
L"Processing of IDQ file [names] failed with error 0x%x\n",
status );
}
}
break;
case eHTXParseError:
{
//
// These are errors encountered while parsing the IDQ file
//
DWORD_PTR args [] = {
(DWORD_PTR) ulErrorLine,
(DWORD_PTR) wcsErrorFileName
};
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
GetModuleHandle(L"idq.dll"),
status,
0,
pwszErrorMessage,
cchAvailMessage,
(va_list *) args ) )
{
ciGibDebugOut(( DEB_ERROR, "Format message failed with error 0x%x\n", GetLastError() ));
swprintf( pwszErrorMessage,
L"Error 0x%x occured while parsing in HTX file %ls\n",
status,
wcsErrorFileName );
}
}
break;
case eRestrictionParseError:
{
//
// These are errors encountered while parsing the restriction
//
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(L"query.dll"),
status,
0,
pwszErrorMessage,
cchAvailMessage,
0 ) )
{
ciGibDebugOut(( DEB_ERROR, "Format message failed with error 0x%x\n", GetLastError() ));
swprintf( pwszErrorMessage,
L"Restriction parsing failed with error 0x%x\n",
status );
}
}
break;
default:
{
//
// All other errors; other major classes of errors are caught above.
//
DWORD_PTR args [] = {
(DWORD_PTR) ulErrorLine,
(DWORD_PTR) wcsErrorFileName
};
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
GetModuleHandle(L"idq.dll"),
status,
0,
pwszErrorMessage,
cchAvailMessage,
(va_list *) args ) )
{
if (wcsErrorFileName != 0)
{
NTSTATUS MsgNum = MSG_IDQ_FILE_MESSAGE;
args[0] = (DWORD_PTR)wcsErrorFileName;
if (ulErrorLine != 0)
{
args[1] = ulErrorLine;
MsgNum = MSG_IDQ_FILE_LINE_MESSAGE;
}
ULONG cchMsg = FormatMessage( FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
GetModuleHandle(L"idq.dll"),
MsgNum,
0,
pwszErrorMessage,
cchAvailMessage,
(va_list *) args );
pwszErrorMessage += cchMsg;
cchAvailMessage -= cchMsg;
}
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(L"query.dll"),
status,
0,
pwszErrorMessage,
cchAvailMessage,
0 ) )
{
//
// Try looking up the error in the Win32 list of error codes
//
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(L"kernel32.dll"),
Win32status,
0,
pwszErrorMessage,
cchAvailMessage,
0 ) )
{
ciGibDebugOut(( DEB_ERROR,
"Format message failed with error 0x%x\n",
GetLastError() ));
swprintf( pwszErrorMessage,
L"Error 0x%x caught while processing query\n",
status );
}
}
}
}
break;
}
SetThreadLocale(SaveLCID);
BOOL fCaughtException = FALSE;
//
// Try to bind to language object by looking up registry and get
// the error message HTX file associated with this class of error.
//
TRY
{
CWebLangLocator langreg( locale );
WCHAR * wcsErrorFile = 0;
if ( langreg.LocaleFound() )
{
//
// If the locale was found in the registry, get the error message
// file associated with this language.
//
switch (eErrorClass)
{
case eIDQParseError:
case eIDQPlistError:
wcsErrorFile = langreg.GetIDQErrorFile();
break;
case eHTXParseError:
wcsErrorFile = langreg.GetHTXErrorFile();
break;
case eRestrictionParseError:
wcsErrorFile = langreg.GetRestrictionErrorFile();
break;
default:
wcsErrorFile = langreg.GetDefaultErrorFile();
break;
}
}
if ( ( 0 != pVariableSet ) &&
( 0 != pOutputFormat ) &&
( 0 != wcsErrorFile ) &&
( wcslen(wcsErrorFile) > 0 ) )
{
//
// Set CiErrorMessage and CiErrorNumber.
//
// The variables won't own the memory for the strings;
// the pointers will be reset later.
//
PROPVARIANT propVariant;
propVariant.vt = VT_LPWSTR;
propVariant.pwszVal = awcsErrorMessage;
pVariableSet->SetVariable( ISAPI_CI_ERROR_MESSAGE,
&propVariant,
0 );
WCHAR achErrorNumber[11];
swprintf( achErrorNumber, L"0x%8x", status );
propVariant.pwszVal = achErrorNumber;
pVariableSet->SetVariable( ISAPI_CI_ERROR_NUMBER,
&propVariant,
0 );
WCHAR wcsPhysicalPath[_MAX_PATH];
ULONG cwcVirtualPath = wcslen(wcsErrorFile) + 1;
XPtrST<WCHAR> wcsVirtualPath( new WCHAR[cwcVirtualPath] );
//
// We could have a virtual root or a physical root
// All virtual roots begin with a "/".
//
if (wcsErrorFile[0] == L'/')
{
//
// Ask the web server to convert the virtual path to our error
// message file to a physical path.
//
webServer.GetPhysicalPath( wcsErrorFile, wcsPhysicalPath, _MAX_PATH );
RtlCopyMemory( wcsVirtualPath.GetPointer(),
wcsErrorFile,
cwcVirtualPath*sizeof(WCHAR) );
}
else
{
// simply copy the path to physical path. It has to be a physical
// path. If not, it will result in an error later.
wcscpy(wcsPhysicalPath, wcsErrorFile);
}
CSecurityIdentity securityStub;
CHTXFile htxFile( wcsVirtualPath,
pOutputFormat->CodePage(),
securityStub,
pOutputFormat->GetServerInstance() );
ciGibDebugOut((DEB_ITRACE, "File is: %ws\n", wcsPhysicalPath));
htxFile.ParseFile( wcsPhysicalPath, *pVariableSet, webServer );
htxFile.GetHeader( vString, *pVariableSet, *pOutputFormat );
}
else
{
vString.StrCat( L"<HTML>" );
HTMLEscapeW( awcsErrorMessage,
vString,
pOutputFormat->CodePage() );
}
}
CATCH ( CException, e )
{
fCaughtException = TRUE;
}
END_CATCH
TRY
{
// Extending the vstring can fail
if ( fCaughtException )
{
vString.StrCat( L"<HTML>" );
HTMLEscapeW( awcsErrorMessage,
vString,
pOutputFormat->CodePage() );
}
// These can fail if the variable wasn't set above
if ( pVariableSet )
{
PROPVARIANT propVariant;
propVariant.vt = VT_EMPTY;
pVariableSet->SetVariable( ISAPI_CI_ERROR_MESSAGE,
&propVariant,
0 );
pVariableSet->SetVariable( ISAPI_CI_ERROR_NUMBER,
&propVariant,
0 );
}
}
CATCH ( CException, e )
{
// give up
}
END_CATCH
} //GetErrorPageNoThrow
//+---------------------------------------------------------------------------
//
// Function: GetErrorPageNoThrow - public
//
// Synposis: Generates an error page based on the error parameters passed.
// The error description is already available.
//
// Arguments: [scError] - error SCODE generated
// [pwszErrorMessage] - description provided by ole-db error mechanism
// [pVariableSet] - replaceable parameters which generated the error
// [pOutputFormat] - format of dates & numbers
// [locale] - locale of the browser
// [webServer] - the web server
// [vString] - virtual string to contain error code
//
// History: 08-May-97 KrishnaN Created
//
//----------------------------------------------------------------------------
void GetErrorPageNoThrow( int eErrorClass,
SCODE scError,
WCHAR const * pwszErrorMessage,
CVariableSet * pVariableSet,
COutputFormat * pOutputFormat,
LCID locale,
CWebServer & webServer,
CVirtualString & vString
)
{
BOOL fCaughtException = FALSE;
//
// Try to bind to language object by looking up registry and get
// the error message HTX file associated with this class of error.
//
TRY
{
//
// If the error was the result of an access denied problem, then simply
// return a 401 error to the browser
//
//
// Generate the Win32 error code by removing the facility code (7) and
// the error bit.
//
ULONG Win32status = scError;
if ( (Win32status & (FACILITY_WIN32 << 16)) == (FACILITY_WIN32 << 16) )
{
Win32status &= ~( 0x80000000 | (FACILITY_WIN32 << 16) );
}
if ( (STATUS_ACCESS_DENIED == scError) ||
(STATUS_NETWORK_ACCESS_DENIED == scError) ||
(ERROR_ACCESS_DENIED == Win32status) ||
(ERROR_INVALID_ACCESS == Win32status) ||
(ERROR_NETWORK_ACCESS_DENIED == Win32status)
)
{
ciGibDebugOut(( DEB_WARN, "mapping 0x%x to 401 access denied\n", scError ));
ReturnServerError( HTTP_STATUS_DENIED, webServer );
return;
}
CWebLangLocator langreg( locale );
WCHAR * wcsErrorFile = 0;
if ( langreg.LocaleFound() )
{
//
// If the locale was found in the registry, get the error message
// file associated with this language.
//
switch (eErrorClass)
{
case eIDQParseError:
case eIDQPlistError:
wcsErrorFile = langreg.GetIDQErrorFile();
break;
case eHTXParseError:
wcsErrorFile = langreg.GetHTXErrorFile();
break;
case eRestrictionParseError:
wcsErrorFile = langreg.GetRestrictionErrorFile();
break;
default:
wcsErrorFile = langreg.GetDefaultErrorFile();
break;
}
}
if ( ( 0 != pVariableSet ) &&
( 0 != pOutputFormat ) &&
( 0 != wcsErrorFile ) &&
( wcslen(wcsErrorFile) > 0 ) )
{
//
// Set CiErrorMessage and CiErrorNumber.
//
// The variables won't own the memory for the strings;
// the pointers will be reset later.
//
PROPVARIANT propVariant;
propVariant.vt = VT_LPWSTR;
propVariant.pwszVal = (LPWSTR)pwszErrorMessage;
pVariableSet->SetVariable( ISAPI_CI_ERROR_MESSAGE,
&propVariant,
0 );
WCHAR achErrorNumber[11];
swprintf( achErrorNumber, L"0x%8x", scError );
propVariant.pwszVal = achErrorNumber;
pVariableSet->SetVariable( ISAPI_CI_ERROR_NUMBER,
&propVariant,
0 );
WCHAR wcsPhysicalPath[_MAX_PATH];
ULONG cwcVirtualPath = wcslen(wcsErrorFile) + 1;
XPtrST<WCHAR> wcsVirtualPath( new WCHAR[cwcVirtualPath] );
//
// We could have a virtual root or a physical root
// All virtual roots begin with a "/".
//
if (wcsErrorFile[0] == L'/')
{
//
// Ask the web server to convert the virtual path to our error
// message file to a physical path.
//
webServer.GetPhysicalPath( wcsErrorFile, wcsPhysicalPath, _MAX_PATH );
RtlCopyMemory( wcsVirtualPath.GetPointer(),
wcsErrorFile,
cwcVirtualPath*sizeof(WCHAR) );
}
else
{
// simply copy the path to physical path. It has to be a physical
// path. If not, it will result in an error later.
wcscpy(wcsPhysicalPath, wcsErrorFile);
}
CSecurityIdentity securityStub;
CHTXFile htxFile( wcsVirtualPath,
pOutputFormat->CodePage(),
securityStub,
pOutputFormat->GetServerInstance() );
ciGibDebugOut((DEB_ITRACE, "File is: %ws\n", wcsPhysicalPath));
htxFile.ParseFile( wcsPhysicalPath, *pVariableSet, webServer );
htxFile.GetHeader( vString, *pVariableSet, *pOutputFormat );
}
else
{
vString.StrCat( L"<HTML>" );
vString.StrCat( pwszErrorMessage );
}
}
CATCH ( CException, e )
{
fCaughtException = TRUE;
}
END_CATCH
TRY
{
// Extending the vstring can fail
if ( fCaughtException )
{
vString.StrCat( L"<HTML>" );
vString.StrCat( pwszErrorMessage );
}
// These can fail if the variable wasn't set above
if ( pVariableSet )
{
PROPVARIANT propVariant;
propVariant.vt = VT_EMPTY;
pVariableSet->SetVariable( ISAPI_CI_ERROR_MESSAGE,
&propVariant,
0 );
pVariableSet->SetVariable( ISAPI_CI_ERROR_NUMBER,
&propVariant,
0 );
}
}
CATCH ( CException, e )
{
// give up
}
END_CATCH
} //GetErrorPageNoThrow
enum
{
eAccessDeniedMsg = 0,
eServerBusyMsg,
eServerErrorMsg,
};
#define MAX_SERVER_ERROR_MSGSIZE 100
WCHAR g_awszServerErrorMsgs [3] [MAX_SERVER_ERROR_MSGSIZE] =
{
L"Access denied.\r\n",
L"Server too busy.\r\n",
L"Unexpected server error.\r\n",
};
//+---------------------------------------------------------------------------
//
// Function: ReturnServerError - public
//
// Synposis: Generates an error page for an HTTP error code.
//
// Arguments: [httpError] - the HTTP status code
// [webServer] - the web server
//
// Notes: This is used when the server is too busy; it should be a
// very low-overhead path.
//
// History: 12 Aug 1997 AlanW Created
//
//----------------------------------------------------------------------------
void ReturnServerError( ULONG httpError,
CWebServer & webServer )
{
char const * pszHeader = "";
int iMessage = 0;
switch (httpError)
{
case HTTP_STATUS_DENIED:
pszHeader = "401 Access denied";
iMessage = eAccessDeniedMsg;
break;
case HTTP_STATUS_SERVICE_UNAVAIL:
pszHeader = "503 Server busy";
iMessage = eServerBusyMsg;
break;
default:
ciGibDebugOut(( DEB_ERROR, "unexpected server error status %d\n", httpError ));
httpError = HTTP_STATUS_SERVER_ERROR;
iMessage = eServerErrorMsg;
break;
}
webServer.WriteHeader( 0, pszHeader );
WCHAR * pwszMessage = g_awszServerErrorMsgs[iMessage];
webServer.WriteClient( pwszMessage );
webServer.SetHttpStatus( httpError );
}
//+---------------------------------------------------------------------------
//
// Function: LoadServerErrors - public
//
// Synposis: Load messages for server errors.
//
// Arguments: -NONE-
//
// Notes:
//
// History: 29 Sep 1997 AlanW Created
//
//----------------------------------------------------------------------------
void LoadServerErrors( )
{
unsigned iMessage = eAccessDeniedMsg;
SCODE scMessage = MSG_CI_ACCESS_DENIED;
const unsigned cMessages = sizeof g_awszServerErrorMsgs /
sizeof g_awszServerErrorMsgs[0];
while (iMessage < cMessages)
{
FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(L"idq.dll"),
scMessage,
GetSystemDefaultLangID(),
&g_awszServerErrorMsgs [iMessage][0],
MAX_SERVER_ERROR_MSGSIZE,
0 );
scMessage++;
iMessage++;
}
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
c7d983fcd69a2a217ab8fb14d7f4fd1026ed5d8e | 48e9625fcc35e6bf790aa5d881151906280a3554 | /Sources/Elastos/LibCore/inc/org/apache/http/client/utils/CloneUtils.h | 585f640316dad172c3d9acfb0e4b3f10857f659d | [
"Apache-2.0"
] | permissive | suchto/ElastosRT | f3d7e163d61fe25517846add777690891aa5da2f | 8a542a1d70aebee3dbc31341b7e36d8526258849 | refs/heads/master | 2021-01-22T20:07:56.627811 | 2017-03-17T02:37:51 | 2017-03-17T02:37:51 | 85,281,630 | 4 | 2 | null | 2017-03-17T07:08:49 | 2017-03-17T07:08:49 | null | UTF-8 | C++ | false | false | 1,499 | h | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __ORG_APACHE_HTTP_CLIENT_UTILS_CLONEUTILS_H__
#define __ORG_APACHE_HTTP_CLIENT_UTILS_CLONEUTILS_H__
#include "Elastos.CoreLibrary.h"
#include <elastos/coredef.h>
namespace Org {
namespace Apache {
namespace Http {
namespace Client {
namespace Utils {
/**
* A collection of utilities to workaround limitations of Java clone framework.
*/
class CloneUtils
{
private:
/**
* This class should not be instantiated.
*/
CloneUtils() {}
public:
static CARAPI Clone(
/* [in] */ IObject* obj,
/* [out] */ IObject** cloneObj);
};
} // namespace Utils
} // namespace Client
} // namespace Http
} // namespace Apache
} // namespace Org
#endif // __ORG_APACHE_HTTP_CLIENT_UTILS_CLONEUTILS_H__
| [
"cao.jing@kortide.com"
] | cao.jing@kortide.com |
729d513cefa270e2b1852ab097253a4179a9220f | 0c361c1dd7eb844cc26bfb683232bbde750388dc | /2tha/C.cpp | e786ce919572e3b9f3447f1ff4a1cbdf3afa91bd | [] | no_license | rizaust/sdust-cs-assignment | 831f3279ef7187b6d1e685f3790fbfc3a0228b6d | afd7ebbf8b3965eb1e704b4a2088197057477085 | refs/heads/master | 2022-05-11T09:46:23.311682 | 2022-03-29T03:02:35 | 2022-03-29T03:02:35 | 253,204,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,030 | cpp | #include <bits/stdc++.h>
using namespace std;
class Date {
public:
Date(int a, int b, int c) {
year = a;
month = b;
day = c;
}
void showDate() {
cout << setfill('0') << setw(4) << year << "-" << setw(2) << month
<< "-" << setw(2) << day;
}
int year, month, day;
};
class Time {
public:
Time(int a, int b, int c) {
hour = a;
minute = b;
sec = c;
}
void showTime() {
cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute
<< ":" << setw(2) << sec;
}
int hour, minute, sec;
};
int main() {
int cases;
cin >> cases;
for (int ca = 0; ca < cases; ca++) {
int year, month, day;
cin >> year >> month >> day;
Date date(year, month, day);
date.showDate();
cout << " ";
int hour, minute, second;
cin >> hour >> minute >> second;
Time time(hour, minute, second);
time.showTime();
cout << endl;
}
} | [
"540040135@qq.com"
] | 540040135@qq.com |
a25ad70b277cd84239db7472a656883c3d04c505 | 20b2af5e275469261d95d4441303d567b5c03bba | /src/brain/Behavior/DucksBehaviour/States/Initial.hpp | f72a110a4246b14091894721cd18f8bc4d8f5e20 | [
"BSD-2-Clause"
] | permissive | humanoid-robotics-htl-leonding/robo-ducks-core | efd513dedf58377dadc6a3094dd5c01f13c32eb1 | 1644b8180214b95ad9ce8fa97318a51748b5fe3f | refs/heads/master | 2022-04-26T17:19:00.073468 | 2020-04-23T07:05:25 | 2020-04-23T07:05:25 | 181,146,731 | 7 | 0 | NOASSERTION | 2022-04-08T13:25:14 | 2019-04-13T09:07:29 | C++ | UTF-8 | C++ | false | false | 243 | hpp | #pragma once
DucksActionCommand initial(const DucksDataSet &d)
{
auto command = DucksActionCommand::stand();
if (d.thoughts.handleNewState()) {
command.combineThoughtCommand(ThoughtCommand::RESET_COMPASS_DIRECTION);
}
return command;
} | [
"erik.mayrhofer@liwest.at"
] | erik.mayrhofer@liwest.at |
f944acf6e9c632fad77b358cc87851021a33b0f6 | bc39ecd1bcd53522dae37385843d8bbe949a4c9d | /practising_for_contest.cpp | f7cf41fb1eb7e5382223e472c3d7c52c246ff0f3 | [] | no_license | joydip10/Code-Practise-with-C- | e34f513e82cf1fdecf3ad4f3c40ed94430b25e71 | fdbc0c81a1db4d9a5ae47209704f0c7e0de1e926 | refs/heads/main | 2023-06-21T14:25:34.053465 | 2021-07-12T03:44:54 | 2021-07-12T03:44:54 | 385,116,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 113 | cpp | #include<bits//stdc++.h>
using namespace std;
int main()
{
char c[10];
scanf("%[^\n]",c);
cout<<c;
}
| [
"joydipdasNSTU@gmail.com"
] | joydipdasNSTU@gmail.com |
06f484f37048eb2b0071631e4c5861990c532849 | fbd1f6f25f42a807f2032a74782434cf082df621 | /cpp/SAIDA/DeepLearning/SharedMemoryMessageHandler.cpp | c3806b2cbf82bd090aa2be32494c6cbb8abb30d0 | [
"MIT",
"LicenseRef-scancode-protobuf"
] | permissive | rickyHong/StarCraft-RL-repl | 0fb1423ec83663767a21b487253a228e4a9675e3 | 6039dbeab185f39a19901b70916192f4915efea8 | refs/heads/master | 2022-12-12T08:57:11.700222 | 2019-05-29T03:07:15 | 2019-05-29T03:07:15 | 189,161,056 | 1 | 1 | MIT | 2022-12-08T05:10:54 | 2019-05-29T06:09:05 | C++ | UTF-8 | C++ | false | false | 381 | cpp | /*
* Copyright (C) 2019 SAMSUNG SDS <Team.SAIDA@gmail.com>
*
* This code is distribued under the terms and conditions from the MIT License (MIT).
*
* Authors : Iljoo Yoon, Daehun Jun, Hyunjae Lee, Uk Jo
*/
#include "SharedMemoryMessageHandler.h"
SharedMemoryMessageHandler::SharedMemoryMessageHandler()
{
}
SharedMemoryMessageHandler::~SharedMemoryMessageHandler()
{
}
| [
"vpds@naver.com"
] | vpds@naver.com |
66f8f07aeed297550702a3825f0144715706f1e6 | e5e657b26c2e61d2401ba3c027b2787e3ba60493 | /lib/websocket/WebSocketStatelessHandler.hpp | bbaf1ad5e307c2117ad1f4b115cb3811c9a491b0 | [
"Apache-2.0"
] | permissive | severnt/pravala-toolkit | db18cb1e6d4bb8a88b72b8ce9f4733b5f1ac4a68 | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | refs/heads/master | 2021-01-02T20:39:43.640078 | 2020-02-01T16:03:28 | 2020-02-01T16:03:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,574 | hpp | /*
* Copyright 2019 Carnegie Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "basic/MemHandle.hpp"
#include "basic/HashSet.hpp"
#include "basic/String.hpp"
#include "object/SimpleObject.hpp"
#include "WebSocketHandler.hpp"
#include "WebSocketConnection.hpp"
namespace Pravala
{
/// @brief Base for a simple server handler that requires no state.
/// The inheriting class must implement functions that this class inherits that aren't implemented.
/// For example: wsRead
class WebSocketStatelessHandler:
public WebSocketHandler,
public WebSocketConnectionOwner
{
protected:
/// @brief All sockets managed by this WebSocketHandler
/// Objects must be ref/unref'ed when they are added/removed from this set!
HashSet<WebSocketConnection *> _allSocks;
virtual ~WebSocketStatelessHandler();
virtual void addConnection ( WebSocketListener * listener, WebSocketConnection * conn );
virtual void wsClosed ( WebSocketConnection * sock );
/// @brief Broadcast some data to all sockets
/// @param [in] data Data to broadcast
/// @param [in] isText True if the data being broadcast is text, false if it is binary
void broadcast ( const MemHandle & data, bool isText );
/// @brief Broadcast some data to all sockets
/// @param [in] data Data to broadcast
/// @param [in] len Length of data to broadcast
/// @param [in] isText True if the data being broadcast is text, false if it is binary
void broadcast ( const char * data, size_t len, bool isText );
/// @brief Broadcast a null terminated text string to all sockets
/// @param [in] data Null terminated text string to broadcast
void broadcast ( const char * data );
/// @brief Broadcast a string to all sockets
/// @param [in] data String to broadcast
inline void broadcast ( const String & data )
{
broadcast ( data.c_str(), data.length(), true );
}
};
}
| [
"narmstrong@carnegietechnologies.com"
] | narmstrong@carnegietechnologies.com |
d9856f577a1547d1d8a21178392ad5939752b856 | 408718e6d8645fdbf4706104abbcd45739902a59 | /Engine/SystemManagers/Events/EventManager.h | c18a78fba46dc1d701dfc8c8342354240467ff10 | [] | no_license | worldwebbull/ZCEngine | 5776f1272bff479a639f741a77fc9107bb78e9e3 | 68f7c93c2bf933f8742d79a47154632d6a463f52 | refs/heads/master | 2021-12-04T09:49:03.724993 | 2015-03-06T09:56:24 | 2015-03-06T09:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | h | //
// EventManager.h
// ZenCoderEngine
//
// Created by Srinavin Nair on 10/18/13.
// Copyright (c) 2013 Srinavin Nair. All rights reserved.
//
#ifndef ZenCoderEngine_EventManager_h
#define ZenCoderEngine_EventManager_h
#include <SDL2/SDL.h>
#include <functional>
#include "SystemManager.h"
typedef std::function<void()> EventCallbackDelegate;
typedef std::function<void(SDL_Keycode keyCode)> KeyboardEventCallbackDelegate;
class EventManager:public SystemManager
{
private:
static int ID;
SDL_Event *evt;
EventCallbackDelegate onSDLQuit;
KeyboardEventCallbackDelegate onSDLKeyboardPress, onSDLKeyboardRelease;
void OnEvent(SDL_Event *event);
public:
EventManager();
~EventManager();
void RegisterSDLQuit(EventCallbackDelegate func);
void RegisterSDLKeyboardInputs(KeyboardEventCallbackDelegate keyPressFunc, KeyboardEventCallbackDelegate keyReleaseFunc);
void Update();
};
#endif
| [
"zencoder1985@gmail.com"
] | zencoder1985@gmail.com |
c9d3c171824011d9f6f9a2a7bdc759201ae730af | 16c25858ef1e5f29f653580d4aacda69a50c3244 | /hikr/build/Android/Preview/app/src/main/include/Fuse.Triggers.WhileValue-1.h | 5b4f33c6861fac00640875e69d8190b68570f4e4 | [] | no_license | PoliGomes/tutorialfuse | 69c32ff34ba9236bc3e84e99e00eb116d6f16422 | 0b7fadfe857fed568a5c2899d176acf45249d2b8 | refs/heads/master | 2021-08-16T02:50:08.993542 | 2017-11-18T22:04:56 | 2017-11-18T22:04:56 | 111,242,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,954 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Triggers/1.2.1/$.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IBase-d3bd6f2e.h>
#include <Fuse.Animations.IUnwr-594abe9.h>
#include <Fuse.Binding.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.IPulseTrigger.h>
#include <Fuse.Triggers.WhileTrigger.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
namespace g{namespace Fuse{namespace Triggers{struct WhileValue;}}}
namespace g{namespace Fuse{struct Node;}}
namespace g{namespace Uno{namespace UX{struct ValueChangedArgs;}}}
namespace g{
namespace Fuse{
namespace Triggers{
// public abstract class WhileValue<T> :4213
// {
struct WhileValue_type : ::g::Fuse::Triggers::Trigger_type
{
::g::Fuse::Triggers::IPulseTrigger interface8;
void(*fp_get_IsOn)(::g::Fuse::Triggers::WhileValue*, bool*);
};
WhileValue_type* WhileValue_typeof();
void WhileValue__ctor_6_fn(WhileValue* __this);
void WhileValue__FindValueNode_fn(uType* __type, ::g::Fuse::Node* n, uObject** __retval);
void WhileValue__OnRooted_fn(WhileValue* __this);
void WhileValue__OnUnrooted_fn(WhileValue* __this);
void WhileValue__OnValueChanged_fn(WhileValue* __this, uObject* s, ::g::Uno::UX::ValueChangedArgs* a);
void WhileValue__Pulse1_fn(WhileValue* __this);
void WhileValue__get_Source_fn(WhileValue* __this, uObject** __retval);
void WhileValue__set_Source_fn(WhileValue* __this, uObject* value);
void WhileValue__UpdateState_fn(WhileValue* __this);
void WhileValue__get_Value_fn(WhileValue* __this, uTRef __retval);
void WhileValue__set_Value_fn(WhileValue* __this, void* value);
void WhileValue__add_ValueChanged_fn(WhileValue* __this, uDelegate* value);
void WhileValue__remove_ValueChanged_fn(WhileValue* __this, uDelegate* value);
struct WhileValue : ::g::Fuse::Triggers::WhileTrigger
{
bool _hasValue;
uStrong<uObject*> _obj;
uStrong<uObject*> _source;
uTField _value() { return __type->Field(this, 37); }
uStrong<uDelegate*> ValueChanged1;
void ctor_6();
bool IsOn() { bool __retval; return (((WhileValue_type*)__type)->fp_get_IsOn)(this, &__retval), __retval; }
void OnValueChanged(uObject* s, ::g::Uno::UX::ValueChangedArgs* a);
void Pulse1();
uObject* Source();
void Source(uObject* value);
void UpdateState();
template<class T>
T Value() { T __retval; return WhileValue__get_Value_fn(this, &__retval), __retval; }
template<class T>
void Value(T value) { WhileValue__set_Value_fn(this, uConstrain(__type->GetBase(WhileValue_typeof())->T(0), value)); }
void add_ValueChanged(uDelegate* value);
void remove_ValueChanged(uDelegate* value);
static uObject* FindValueNode(uType* __type, ::g::Fuse::Node* n);
};
// }
}}} // ::g::Fuse::Triggers
| [
"poliana.ph@gmail.com"
] | poliana.ph@gmail.com |
8b4fdce889fa4c595bea5e68b399515644ac16f3 | 784b33a310d3a797a692758d44eca4f547a1d0b7 | /CompetitiveProgramming/greaterTwoNoIfElse.cpp | a5ba7a999a98bfec5f11531a6e7b93d41a749bf4 | [] | no_license | bikash-das/cppPrograms | cf55ee4db713fa14ec3f5ae188cbf297795c7cc9 | 8b70bce4b8a6de6c2b9076f3eec897ec625888ff | refs/heads/master | 2020-05-02T19:46:52.943982 | 2019-12-26T15:04:18 | 2019-12-26T15:04:18 | 178,168,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include <iostream>
using namespace std;
int larger(int a, int b){
int c = a-b;
//find msb = k
int mask = 100000000;
int k = c & mask;
if(k == mask){
k = 1;
}
// cout << "k: " << k <<"\n";
return (1-k)*a + k * b;
}
int main(){
int a = 200, b = 100;
cout << larger(a,b) << "\n";
}
| [
"dasbikash989@gmail.com"
] | dasbikash989@gmail.com |
c026ce127430cd7d9dda1030b81360b8af164855 | 16644e730cddde1df0d0ba9cfcc1c5e586e08ac9 | /DOD Ray Tracer/main.cpp | 391446ab9f76313f0b966c49de3a498b7dd22d68 | [] | no_license | rstratton/dod-ray-tracer | 969a446d853765444391f53a4425cc81322c69c4 | 52565f00c27745e422e089aa9b1ee8f45dfba611 | refs/heads/master | 2020-05-17T03:41:34.424344 | 2019-05-07T01:38:48 | 2019-05-07T01:38:48 | 183,487,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,140 | cpp | #include "pch.h"
#define _USE_MATH_DEFINES
#include "math.h"
#include <iostream>
#include <vector>
#include <limits>
#pragma warning(disable:4996)
inline float max(float a, float b) {
return a > b ? a : b;
}
inline float min(float a, float b) {
return a < b ? a : b;
}
struct Vector {
float x;
float y;
float z;
Vector() {};
Vector(float x, float y, float z) : x(x), y(y), z(z) {};
Vector(const Vector& v) : x(v.x), y(v.y), z(v.z) {};
Vector operator+(const Vector& o) const {
return Vector(
x + o.x,
y + o.y,
z + o.z
);
}
Vector& operator+=(const Vector& o) {
x += o.x;
y += o.y;
z += o.z;
return *this;
}
Vector operator-(const Vector& o) const {
return Vector(
x - o.x,
y - o.y,
z - o.z
);
}
Vector operator-() const {
return Vector(-x, -y, -z);
}
Vector operator*(float f) const {
return Vector(
f * x,
f * y,
f * z
);
}
Vector operator/(float f) const {
return Vector(
x / f,
y / f,
z / f
);
}
Vector normalized() const {
return (*this) / mag();
}
float mag() const {
return sqrt(sqmag());
}
float sqmag() const {
return x * x + y * y + z * z;
}
float dot(const Vector& o) const {
return x * o.x + y * o.y + z * o.z;
}
};
Vector operator*(float f, const Vector& v) {
return Vector(
f * v.x,
f * v.y,
f * v.z
);
}
struct Ray {
Vector pos;
Vector dir;
Ray() {};
Ray(const Vector& pos, const Vector& dir) : pos(pos), dir(dir) {};
};
struct RayHit {
Vector pos;
Vector norm;
Vector dir;
uint8_t hasHit : 1;
};
struct Camera {
float verticalFov;
int width;
int height;
Vector pos;
};
struct Plane {
Vector pos;
Vector norm;
};
struct Sphere {
Vector pos;
float rad;
};
struct Color {
uint8_t r;
uint8_t g;
uint8_t b;
};
struct PointLight {
Vector pos;
Vector color;
};
float degToRad(float deg) {
return deg * M_PI / 180.f;
}
void createPrimaryRays(Camera camera, Ray** pRays, int& numRays) {
int pixelCount = camera.width * camera.height;
Ray* rays = new Ray[pixelCount];
*pRays = rays;
numRays = pixelCount;
float verticalImagePlaneSize = 2 * tanf(degToRad(camera.verticalFov / 2));
float horizontalImagePlaneSize = (verticalImagePlaneSize / camera.height) * camera.width;
float x_0 = -horizontalImagePlaneSize / 2;
float y_0 = verticalImagePlaneSize / 2;
float dx = horizontalImagePlaneSize / camera.width;
float dy = -verticalImagePlaneSize / camera.height;
for (int i = 0; i < camera.height; ++i) {
int rowOffset = i * camera.width;
for (int j = 0; j < camera.width; ++j) {
int rayIdx = rowOffset + j;
// NOTE: Primary rays all share the initial camera position. Maybe primary rays should be
// a different struct since they'll all share the same position.
rays[rayIdx].pos = camera.pos;
rays[rayIdx].dir = Vector(x_0 + j * dx, y_0 + i * dy, -1.f).normalized();
}
}
}
bool rayIntersectsSphere(const Ray& r, const Sphere& s, RayHit& h) {
float a = r.dir.sqmag();
Vector v = r.pos - s.pos;
float b = 2 * r.dir.dot(v);
float c = v.sqmag() - s.rad * s.rad;
float disc = b * b - 4 * a*c;
if (disc < 0) return false;
//we only care about the minus in the plus or minus
float t = (-b - sqrt(disc)) / (2 * a);
h.hasHit = false;
if (t < 0) return false;
h.pos = r.pos + r.dir * t;
h.norm = (h.pos - s.pos).normalized();
h.dir = r.dir;
h.hasHit = true;
return true;
}
bool rayIntersectsPlane(Ray r, Plane p, RayHit& h) {
// Taken from graphicscodex.com
// t = ((P - C).dot(n)) / (w.dot(n))
// Ray equation: X(t) = P + t*w
h.hasHit = false;
float numerator = (r.pos - p.pos).dot(p.norm);
float denominator = r.dir.dot(p.norm);
if (denominator >= 0) return false;
float t = -numerator / denominator;
if (t < 0) return false;
h.norm = p.norm;
h.pos = r.pos + t * r.dir;
h.dir = r.dir;
h.hasHit = true;
return true;
}
void computeRayHits(Ray* rays, int numRays, Sphere* spheres, int numSpheres, Plane* planes, int numPlanes, RayHit** pRayHits) {
// We will have at most `numRays` hits
RayHit* rayHits = new RayHit[numRays];
*pRayHits = rayHits;
for (int rayIdx = 0; rayIdx < numRays; ++rayIdx) {
Ray ray = rays[rayIdx];
RayHit newHit, closestHit;
float closestHitDistanceSquared = std::numeric_limits<float>::infinity();
// Spheres
for (int sphereIdx = 0; sphereIdx < numSpheres; ++sphereIdx) {
if (rayIntersectsSphere(ray, spheres[sphereIdx], newHit)) {
float newHitDistanceSquared = (newHit.pos - ray.pos).sqmag();
if (closestHitDistanceSquared > newHitDistanceSquared) {
closestHit = newHit;
closestHitDistanceSquared = newHitDistanceSquared;
}
}
}
// Planes
for (int planeIdx = 0; planeIdx < numPlanes; ++planeIdx) {
if (rayIntersectsPlane(ray, planes[planeIdx], newHit)) {
float newHitDistanceSquared = (newHit.pos - ray.pos).sqmag();
if (closestHitDistanceSquared > newHitDistanceSquared) {
closestHit = newHit;
closestHitDistanceSquared = newHitDistanceSquared;
}
}
}
rayHits[rayIdx] = closestHit;
}
}
void selectReflectableIntersections(RayHit* rayHits, int numRayHits, std::vector<int>** pReflectableRayHits, std::vector<int>* primaryRayIndices, std::vector<int>** pNewPrimaryRayIndices, int& numReflectableRayHits) {
std::vector<int>* reflectableRayHits = new std::vector<int>();
*pReflectableRayHits = reflectableRayHits;
std::vector<int>* newPrimaryRayIndices = new std::vector<int>();
*pNewPrimaryRayIndices = newPrimaryRayIndices;
reflectableRayHits->reserve(numRayHits);
newPrimaryRayIndices->reserve(numRayHits);
int numReflectable = 0;
for (int i = 0; i < numRayHits; ++i) {
if (rayHits[i].hasHit) {
reflectableRayHits->push_back(i);
newPrimaryRayIndices->push_back((*primaryRayIndices)[i]);
++numReflectable;
}
}
numReflectableRayHits = numReflectable;
reflectableRayHits->shrink_to_fit();
newPrimaryRayIndices->shrink_to_fit();
}
void computeReflectionRays(RayHit* rayHits, int numRayHits, Ray** pReflectionRays) {
Ray* reflectionRays = new Ray[numRayHits];
*pReflectionRays = reflectionRays;
for (int i = 0; i < numRayHits; ++i) {
RayHit hit = rayHits[i];
Vector v = -hit.dir.normalized();
Vector n = hit.norm.normalized();
Vector direction = ((n * (2 * v.dot(n))) - v).normalized();
reflectionRays[i] = Ray(hit.pos + 0.001f * direction, direction);
}
}
void computePointLightDiffuse(RayHit* rayHits, int numRayHits, PointLight* lights, int numLights, Vector* diffuseColor, Sphere* spheres, int numSpheres, Plane* planes, int numPlanes) {
for (int rayHitIdx = 0; rayHitIdx < numRayHits; ++rayHitIdx) {
RayHit hit = rayHits[rayHitIdx];
if (!hit.hasHit) {
continue;
}
for (int lightIdx = 0; lightIdx < numLights; ++lightIdx) {
PointLight light = lights[lightIdx];
Vector lightDiff = light.pos - hit.pos;
float lightDistanceSquared = lightDiff.sqmag();
Vector lightDir = lightDiff.normalized();
Ray shadowRay(hit.pos + hit.norm * 0.001f, lightDir);
RayHit shadowHit;
bool hasHit = false;
// Spheres
for (int sphereIdx = 0; sphereIdx < numSpheres && !hasHit; ++sphereIdx) {
if (rayIntersectsSphere(shadowRay, spheres[sphereIdx], shadowHit)) {
if ((shadowHit.pos - hit.pos).sqmag() < lightDistanceSquared) {
hasHit = true;
}
}
}
// Planes
for (int planeIdx = 0; planeIdx < numPlanes && !hasHit; ++planeIdx) {
if (rayIntersectsPlane(shadowRay, planes[planeIdx], shadowHit)) {
if ((shadowHit.pos - hit.pos).sqmag() < lightDistanceSquared) {
hasHit = true;
}
}
}
if (!hasHit) {
diffuseColor[rayHitIdx] = diffuseColor[rayHitIdx] + light.color * max(hit.norm.dot(lightDir), 0.f);
}
}
}
}
void convertDiffuseToPixels(Vector* diffuse, unsigned char **pPixels, int numPixels) {
unsigned char *pixels = new unsigned char[3 * numPixels];
*pPixels = pixels;
for (int i = 0; i < numPixels; ++i) {
Vector value = diffuse[i];
pixels[3 * i] = (int) min(value.x * 255, 255);
pixels[3 * i + 1] = (int) min(value.y * 255, 255);
pixels[3 * i + 2] = (int) min(value.z * 255, 255);
}
}
void integrateReflection(Vector* diffuse, Vector* refDiffuse, int numReflectionRays, std::vector<int>& primaryRayIndices) {
for (int i = 0; i < numReflectionRays; ++i) {
int diffIdx = primaryRayIndices[i];
diffuse[diffIdx] = diffuse[diffIdx] + refDiffuse[i];
}
}
void writePPM(unsigned char *buf, int width, int height, const char *fn) {
FILE *fp = fopen(fn, "wb");
fprintf(fp, "P6\n");
fprintf(fp, "%d %d\n", width, height);
fprintf(fp, "255\n");
for (int i = 0; i < width*height * 3; ++i) {
fputc(buf[i], fp);
}
fclose(fp);
printf("Wrote image file %s\n", fn);
}
int main()
{
Camera camera;
camera.verticalFov = 50.f;
camera.width = 1000;
camera.height = 1000;
camera.pos = { 0.f, 6.f, 20.f };
int numSpheresHorizontal = 5;
int numSpheresVertical = 5;
int numSpheres = numSpheresHorizontal * numSpheresVertical;
Sphere* spheres = new Sphere[numSpheres];
for (int i = 0; i < numSpheresHorizontal; ++i) {
for (int j = 0; j < numSpheresVertical; ++j) {
Sphere s;
s.pos = Vector((i * 3) - 6, 0, -j * 3);
s.rad = 1.f;
spheres[i * numSpheresHorizontal + j] = s;
}
}
int numPlanes = 6;
Plane* planes = new Plane[numPlanes];
planes[0] = { { 0.f, -1.f, 0.f }, { 0.f, 1.f, 0.f } };
planes[1] = { { 0.f, 0.f, -30.f }, { 0.f, 0.f, 1.f } };
planes[2] = { { -20.f, 0.f, 0.f }, { 1.f, 0.f, 0.f } };
planes[3] = { { 20.f, 0.f, 0.f }, { -1.f, 0.f, 0.f } };
planes[4] = { { 0.f, 40.f, 0.f }, { 0.f, -1.f, 0.f } };
planes[5] = { { 0.f, 0.f, 39.f }, { 0.f, 0.f, -1.f } };
int numLights = 2;
PointLight* pointLights = new PointLight[numLights];
pointLights[0] = { { 19.f, 19.f, 1.f }, { 0.07f, 0.07f, 0.05f } };
pointLights[1] = { { -19.f, 4.f, 4.f }, { 0.05f, 0.05f, 0.07f } };
// Create primary rays
int numRays;
Ray* rays;
createPrimaryRays(camera, &rays, numRays);
// Compute primary ray hits
RayHit* rayHits;
computeRayHits(rays, numRays, spheres, numSpheres, planes, numPlanes, &rayHits);
delete[] rays;
// Compute direct illumination for primary ray hits
Vector* diffuse = new Vector[numRays];
for (int i = 0; i < numRays; ++i) {
diffuse[i] = { 0.f, 0.f, 0.f };
}
computePointLightDiffuse(rayHits, numRays, pointLights, numLights, diffuse, spheres, numSpheres, planes, numPlanes);
// Initialize map from rayHit index to primaryRay/pixel index (initialized to identity map)
std::vector<int>* primaryRayIndices = new std::vector<int>();
primaryRayIndices->resize(numRays);
for (int i = 0; i < numRays; ++i) {
(*primaryRayIndices)[i] = i;
}
int curNumRays = numRays;
// Compute contribution from reflections
for (int i = 0; i < 10; ++i) {
// Select rays which intersected with scene objects
std::vector<int>* reflectableRayHitIndices;
std::vector<int>* newPrimaryRayIndices;
int numReflectableRayHits;
selectReflectableIntersections(rayHits, curNumRays, &reflectableRayHitIndices, primaryRayIndices, &newPrimaryRayIndices, numReflectableRayHits);
delete primaryRayIndices;
primaryRayIndices = newPrimaryRayIndices;
RayHit* reflectableRayHits = new RayHit[numReflectableRayHits];
for (int j = 0; j < numReflectableRayHits; ++j) {
reflectableRayHits[j] = rayHits[(*reflectableRayHitIndices)[j]];
}
delete[] rayHits;
Ray* reflectionRays;
computeReflectionRays(reflectableRayHits, numReflectableRayHits, &reflectionRays);
delete[] reflectableRayHits;
// Compute reflection ray hits
RayHit* reflectionRayHits;
computeRayHits(reflectionRays, numReflectableRayHits, spheres, numSpheres, planes, numPlanes, &reflectionRayHits);
delete[] reflectionRays;
// Compute diffuse color for reflection ray hits
Vector* refDiffuse = new Vector[numReflectableRayHits];
for (int i = 0; i < numReflectableRayHits; ++i) {
refDiffuse[i] = { 0.f, 0.f, 0.f };
}
computePointLightDiffuse(reflectionRayHits, numReflectableRayHits, pointLights, numLights, refDiffuse, spheres, numSpheres, planes, numPlanes);
rayHits = reflectionRayHits;
curNumRays = numReflectableRayHits;
// Integrate diffuse from reflection rays with primary rays
integrateReflection(diffuse, refDiffuse, numReflectableRayHits, *primaryRayIndices);
delete[] refDiffuse;
}
unsigned char* pixels;
convertDiffuseToPixels(diffuse, &pixels, numRays);
writePPM(pixels, camera.width, camera.height, "..\\renders\\image.ppm");
return 0;
} | [
"r.a.stratton88@gmail.com"
] | r.a.stratton88@gmail.com |
5e260fb72c851f131a5f259c14e16f29151b64f4 | 9424f16b1f70e2b009872d70c32fe6ac7df563b0 | /2_Data_Structures/Fundamentals/Sparse_Table/Codeforces-Maximum_of_Maximums_of_Minimums.cpp | dbb3be0d26a2352152fb8c528c9f38cafc7d02e5 | [] | no_license | prajapati-sumit/CP-Algorithms | 196d46b8c9bad911b7120bfc33e4e1f8ad46ef9c | b4c99fa832d3ea9d9ae43a8ea1a6e33dfa678677 | refs/heads/master | 2023-08-18T04:46:11.620709 | 2021-10-11T05:57:49 | 2021-10-11T05:57:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,812 | cpp | // AUTHOR: SUMIT PRAJAPATI
#include "bits/stdc++.h"
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pl;
#define PI 3.1415926535897932384626
#define pb push_back
#define mk make_pair
#define ff first
#define ss second
#define trav(v) for(auto &el:v)
#define watch(x) cerr<<#x<<" = "<<x<<'\n'
#define rep(i,n) for(ll i=0;i<n;i++)
#define repe(i,n) for(ll i=1;i<=n;i++)
#define FOR(i,a,b) for(ll i=a;i<=b;i++)
#define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n'
#define curtime chrono::high_resolution_clock::now()
#define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count()
#define TESTCASES 0
const int INF=1e9;
const int MX=1e5+5;
const int MD=1e9+7;
const int MDL=998244353;
auto time0 = curtime;
void solve(){
int n,k;
cin>>n>>k;
vector<int>v(n,0);
rep(i,n)
cin>>v[i];
if(k==1){
int ans=*min_element(v.begin(),v.end());
cout<<ans;
}
else if(k==2){
int best=v[0];
int pref[n],suf[n];
rep(i,n)
pref[i]=(i==0)?v[0]:min(v[i],pref[i-1]);
for(int i=n-1;i>=0;i--)
suf[i]=(i==n-1)?v[n-1]:min(v[i],suf[i+1]);
rep(i,n-1){
int t=max(pref[i],suf[i+1]);
if(t>best)
best=t;
}
cout<<best;
}
else{
int ans=*max_element(v.begin(),v.end());
cout<<ans;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
srand(time(0));
time0 = curtime;
ll t=1;
if(TESTCASES)cin>>t;
repe(tt,t){
//cout<<"Case #"<<tt<<": ";
solve();
}
//cerr<<"Execution Time: "<<timedif(time0,curtime)*1e-9<<" sec\n";
return 0;
} | [
"sumitprajapati821@gmail.com"
] | sumitprajapati821@gmail.com |
52ac791956fd0e7b2b8b6f76cd16f045c9c17ec6 | f700ef57902e8b92891a78d599f55328e3e02770 | /sort/sort/quick.h | cff6d71d41b387c2229e5bbc7a74fa670e2fde7e | [] | no_license | Gautumn/Algorithm | 77833ea36b64484ad0334e9b48bb5ba3bd965cc7 | e4ab697b596bd456b8b041dc6304c902fc8d05a0 | refs/heads/master | 2020-12-07T19:45:34.468096 | 2020-01-17T10:51:47 | 2020-01-17T10:51:47 | 232,784,864 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,340 | h | #pragma once
template <typename T, typename Comp>
size_t quickSort(std::vector<T> &v, size_t lo, size_t hi, const Comp &comp) {
size_t i = lo, j = hi + 1;
while (true) {
while (comp(a[++i], a[lo])) if (i == hi) break;
while (comp[a[lo], a[--j]]) if (j == lo) break;
if (i >= j) break;
std::swap(v[i], v[j]);
}
std::swap(a[lo], a[j]);
return j;
}
template <typename T, typename Comp>
void quickSort(std::vector<T> &v, size_t lo, size_t hi, const Comp &comp) {
if (hi <= lo) return;
size_t j = partition(v, lo, hi);
quickSort(v, lo, j - 1);
quickSort(v, j + 1, hi);
}
/// ÈýÏòÇзÖ
template <typename T, typename Comp>
void quickSort(std::vector<T> &v, size_t lo, size_t hi, const Comp &comp) {
if (hi <= lo) return;
size_t lt = lo, i = lo + 1, gt = hi;
while (i <= gt) {
int cmp = comp(a[i], a[lo]);
if (cmp < 0) std::swap(v[lt++], v[i++]);
else if (cmp > 0) std::swap(v[gt--], v[i]);
else i++;
}
sort(v, lo, lt - 1, comp);
sort(v, gt + 1, hi, comp);
}
template <typename T, typename Comp>
void quickSort(std::vector<T> &v, const Comp &comp) {
quickSort(v, 0, v.size() - 1, comp);
}
template <typename T>
void quickSort(std::vector<T> &v) {
quickSort(v, std::less<T>());
} | [
"g_autumn@126.com"
] | g_autumn@126.com |
417f0f8305423bf823872b1af6d0c647213e031e | 2cae3c65a40a43aa1376fe8f6302ae84b2185b68 | /StJetAnalysis.cxx | 7183e05bef3a21f3b7c348ad283cfad7d43c2546 | [] | no_license | mckinziebrandon/STAR | a7039b28e4ea6367a8e4752abb8036a26722593a | e1626b9f0795cb2e8d339e42fc86b7e4cd9b2d47 | refs/heads/master | 2020-04-25T18:43:53.617355 | 2015-09-30T18:53:20 | 2015-09-30T18:53:20 | 33,167,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224,377 | cxx | #include "StJetAnalysis.h"
//----------------------------------------------------------------------------------------
static TRandom ran;
static TRandom3 r3;
static TString HistName;
static char NoP[50];
static TRandom ran_gen;
//----------------------------------------------------------------------------------------
static StRefMultCorr* refmultCorrUtil;
static Int_t erefMult_bin;
static Int_t erefMult_bin16;
static char* ALEX_EVENT_TREE = "JetTrackEvent";
static char* ALEX_EVENT_BRANCH = "Events";
static Double_t jet_R;
static Double_t jet_R_background;
static const Int_t N_Beamtime = 8; // 0 == 7.7, 1 == 11.5, 2 == 39, 3 == 62.4, 4 == 19.6, 5 == 27, 6 == 200, 7 == 14.5
static const Int_t N_jet_areas = 16; //
static const Int_t N_z_vertex_bins = 20; // 8
static const Int_t N_mult_bins = 8; // 4
static const Int_t N_Psi_bins = 4; // 5
static const Int_t N_global_bin = N_Psi_bins*N_mult_bins*N_z_vertex_bins;
static const Double_t max_pt_val_embed = 50.0; // maximum pt value embeded for Delta pt calculation
static const Double_t track_eff_scaling_factor = 81499.0/73525.0; // ratio of reconstructed tracks (1000 events) for Nhitsfit > 14 and Nhitsfit > 19
static Int_t Remove_N_hardest; // 2 for same event, 0 for mixed event (if high pT tracks were removed or scaled down)
static const Int_t N_Et_bins = 5;
static const Int_t N_leading_pt_bins = 20; // 15
static const Double_t leading_pt_split_cut = 4.0; // cut at which the tracks are split into tracks with smaller pT // 2.5 // 1.5
static const Double_t leading_pt_split_val = 0.5;
static const Double_t max_pt_threshold = 30.0; // 30
static Double_t max_pt_downscale_threshold; // Used only for eMode == 32, all particles with this momentum will be downscaled by downscale_factor
static const Double_t downscale_factor = 0.1;
static const Int_t N_track_pt_bins_eta_phi = 3;
static const Double_t array_pt_bins_eta_phi[N_track_pt_bins_eta_phi] = {0.5,2.0,max_pt_threshold}; // binning in pT (upper values) for eta vs. phi 2D histograms
static const Double_t jet_delta_eta_cut = 100.0;
static const Double_t jet_delta_phi_cut = 45.0*(2.0*Pi/360.0);
static const Double_t track_pT_assoc_threshold = 2.0;
static const Double_t array_areas[N_jet_areas] = {0.0,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75};
static const Int_t N_Delta_pt_bins = 5;
static const Double_t array_pt_bins_Delta_pt[N_Delta_pt_bins] = {1,3,5,10,15};
// R = 0.2 --> area = 0.13
// R = 0.3 --> area = 0.28
// R = 0.4 --> area = 0.5
// R = 0.5 --> area = 0.79
static Double_t PYTHIA_hard_bin_weigh_factors[11] = {1.6137644,0.136423,0.022972,0.005513,0.001650,0.000574,0.000390,0.000010200809,0.000000501270,0.000000028611,0.000000001446};
static Double_t PYTHIA_hard_bin_high_pT_N_events[11] = {5,61,1275,9844,39541,103797,338451,1655573,3084417,3997019,4471887}; // Number of PYTHIA events with at least one 9 GeV/c track
static TH1D* h_PYTHIA_hard_bin_weigh_factors;
static TH1D* h_PYTHIA_hard_bin_high_pT_N_events;
static Long64_t N_PYTHIA_events[11];
static Long64_t counter_PYTHIA[11];
static TH2D* h_Delta_pt_vs_embed_pt[N_jet_areas][2][N_Psi_bins];
static TH2D* h_Delta_pt_vs_embed_pt_weight[N_jet_areas][2][N_Psi_bins];
static TH1D* h_jet_pt[N_jet_areas][N_leading_pt_bins+1][4];
static TH1D* h_jet_pt_sub[N_jet_areas][N_leading_pt_bins+1][4];
static TH2D* h2D_dijet_pt[N_jet_areas][N_leading_pt_bins+1][4];
static TH2D* h2D_dijet_pt_sub[N_jet_areas][N_leading_pt_bins+1][4];
static TH1D* h_N_tracks_dijet[N_leading_pt_bins+1][2];
static TH2D* h2D_mult_vs_global_bin[N_leading_pt_bins+1][2];
static TH1D* h_trigger_track[4];
static TH2D* h_trigger_track_vs_global_bin[4];
static TH1D* h_jet_area[N_jet_areas][2];
static TH1D* h_jet_rho[N_jet_areas][2];
static TH1D* h_jet_per_event[N_jet_areas][2];
static TH1D* h_dijet_per_event[N_jet_areas][2];
static TProfile* p_jet_area_values;
static TH1D* h_jet_area_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_jet_rho_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_jet_rhoarea_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH2D* h2D_jet_rho_vs_mult_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH2D* h2D_track_eta_vs_phi[N_z_vertex_bins][N_mult_bins][N_Psi_bins][N_track_pt_bins_eta_phi];
static TH2D* h2D_jet_rho_vs_mult_array_In[N_z_vertex_bins][N_mult_bins][N_Psi_bins][2];
static TH1D* h_jet_Et_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_jet_Et_array_weight[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_jet_Et_array_In[N_z_vertex_bins][N_mult_bins][N_Psi_bins][2];
static TH1D* h_jet_per_event_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_tracks_per_event_array[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_tracks_per_event_array_In[N_z_vertex_bins][N_mult_bins][N_Psi_bins][2];
static TH2D* h_tracks_vs_z_vertex_array[N_z_vertex_bins][N_mult_bins];
static TH2D* h_Psi_vs_z_vertex_array[N_z_vertex_bins][N_Psi_bins];
static TH2D* h_tracks_vs_z_vertex_sample;
static TH1D* h_Psi2_sample;
static TH2D* h_jet_rho_vs_Et;
static TH2D* h_Phi_vs_eta[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH2D* h_Phi_vs_eta_random_phi[N_z_vertex_bins];
static TH1D* h_Momentum[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH2D* h_tracks_vs_z_vertex[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_Psi2[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH1D* h_Et[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static TH2D* h_ratio_sub_lead_to_lead_pt_vs_lead_pt;
static TH2D* h_sub_lead_vs_lead_pt;
static TH2D* h_PsiA_vs_PsiB;
static TH1D* h_PsiA;
static TH1D* h_PsiB;
static TH1D* h_Psi_Full;
static TH1D* h_Psi_etapos;
static TH1D* h_Psi_etaneg;
static TH1D* h_phi;
static TH2D* h_area_vs_jet_pt;
static TH2D* h_area_vs_recoil_jet_pt[N_leading_pt_bins+1];
static TH1D* h_rho[N_leading_pt_bins+1];
static TH1D* h_area;
static TH1D* h_track_pT;
static TH1D* h_track_pT_cut;
static TH1D* h_tracks_above_threshold_per_event;
static TProfile* p_pt_Ach[2];
static TH1F* h_Ach;
static const Int_t N2D_tracks_above_threshold = 10;
static TH2D* h2D_tracks_above_threshold[N2D_tracks_above_threshold];
static TH2D* h2D_Sim_matched_pT_vs_original_pT[N_jet_areas];
static TH2D* h2D_Sim_original_pT_vs_matched_pT[N_jet_areas];
static TH1D* h_matched_tracks_fraction[N_jet_areas];
static TH2D* h2D_matched_tracks_fraction_vs_original_pT[N_jet_areas];
static TH1D* h_N_accepted_recoil_jets[N_jet_areas][N_leading_pt_bins+1];
static const Int_t Array_runID_eff_track_rec[7] = {12126100,12138025,12145021,12152017,12154022,12165032,12171017};
static const TString Array_PID_eff_track_rec[6] = {"pplus","pminus","piplus","piminus","kplus","kminus"};
static TF1* f_EfficiencyVsPt[9][7][6]; //centrality(9),runID(7),PID(6)
static TProfile* p_v2_vs_pt;
static TProfile* p_v2_vs_pt_jet;
static TProfile* p_parameters;
static TProfile* p_Array_leading_pt_bins[2];
Float_t vertex_z_start_stop_delta[N_Beamtime][3] =
{
{-40.0,40.0,1.0},
{-40.0,40.0,1.0},
{-40.0,40.0,1.0},
{-40.0,40.0,1.0},
{-40.0,40.0,1.0},
{-40.0,40.0,1.0},
{-40.0,40.0,1.0},
{-40.0,40.0,1.0}
};
static const Double_t z_acceptance[N_Beamtime] = {70.0,50.0,40.0,40.0,70.0,70.0,30.0,50.0};
Double_t Psi_start_stop_delta[N_Beamtime][3] =
{
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0},
{-TMath::Pi()/2.0,TMath::Pi()/2.0,1.0}
};
//static const Float_t Array_leading_pt_bins[2][N_leading_pt_bins+1] =
//{
// {0.0,0.5,1.0,2.0,3.0,4.0,5.0,6.0,7.0,10.0,15.0,0.0,5.0,10.0,7.0,0.0},
// {0.5,1.0,2.0,3.0,4.0,5.0,6.0,7.0,10.0,15.0,20.0,5.0,10.0,20.0,20.0,500.0}
//};
static const Float_t Array_leading_pt_bins[2][N_leading_pt_bins+1] =
{
{0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,0.0},
{1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,500.0}
};
static Double_t Integrated_events_SE_ME[2];
static Double_t SE_ME_integral_scale_factor;
static const Int_t n_z_vertex_bins = 10;
static const Int_t n_params = 3;
static TH1D* h_rc_QxQy_etapm_z_vs_index_[6][n_z_vertex_bins][n_params]; // stores the fit parameters as a function of the index
static TH1D* h_runId_index_rc;
static TH1D* h_runId_index_rc_inv;
static TH1D* h_runId_index_rc_clone;
static TFile* re_centering;
static Float_t start_z;
static Float_t delta_z;
static Int_t gBeamTimeNum;
static TF1* LevyFit_pT;
//------------------------------------------------------------------------------------------------------------------
// For mixed event
Float_t mult_start_stop_delta[N_Beamtime][3] =
{
{700.0,1000.0,1.0},
{700.0,1000.0,1.0},
{700.0,1000.0,1.0},
{700.0,1000.0,1.0},
{700.0,1000.0,1.0},
{700.0,1000.0,1.0},
{700.0,1000.0,1.0},
{700.0,1000.0,1.0}
};
TFile* F_mixed_event[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static StJetTrackEvent JetTrackEvent_Fill[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static StJetTrackEvent *JetTrackEvent_ptr_Fill[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static StJetTrackParticle *JetTrackParticle_Fill;
static StJetTrackParticle *JetTrackParticle_ME;
static TTree *Tree_JetTrackEvent_Fill[N_z_vertex_bins][N_mult_bins][N_Psi_bins];
static const char JETTRACK_EVENT_TREE[] = "JetTrackEvent";
static const char JETTRACK_EVENT_BRANCH[] = "Events";
static std::vector<StJetTrackEvent*> JetTrackEvent_ME;
static Int_t N_max_events;
//------------------------------------------------------------------------------------------------------------------
static TFile* f_track_efficiencies;
static TF1* func_effLow;
static TF1* func_effHigh;
//TCanvas* c_3D;
//TH3D* h_3D_dummy;
static TNtuple *NT_ReCoil_Jet;
static Float_t ReCoil_Jet_NTDataArray[14];
static Int_t N_orig_smear = 1; // used only for PYTHIA
//------------------------------------------------------------------------------------------------------------------------------------
// bad run lists
static const Int_t n_bad_run_numbers[N_Beamtime] = {328,27,38,105,35,34,179,1};
static const Int_t bad_run_list_7GeV[328] = {11114084,11114085,11114086,11114088,11114089,11114094,11114095,11114100,11114109,11115005,11115007,11115013,11115019,11115025,11115027,11115028,11115030,11115032,11115051,11115062,11115064,11115069,11115072,11115078,11115079,11115080,11115086,11115088,11115094,11116001,11116002,11116005,11116006,11116010,11116014,11116020,11116023,11116028,11116060,11116061,11116062,11116064,11116068,11116070,11116072,11116073,11116075,11117002,11117006,11117031,11117033,11117034,11117036,11117039,11117044,11117045,11117046,11117052,11117055,11117063,11117064,11117071,11117075,11117085,11117088,11117089,11117090,11117093,11117094,11117095,11117098,11117100,11117103,11117104,11117107,11118007,11118008,11118016,11118024,11118025,11118026,11118039,11118044,11119001,11119003,11119006,11119007,11119009,11119012,11119013,11119015,11119016,11119017,11119022,11119024,11119026,11119029,11119030,11119056,11119057,11119060,11119062,11119067,11119069,11119070,11119071,11119074,11119075,11119077,11119079,11119081,11119090,11119091,11119100,11119101,11120003,11120006,11120008,11120011,11120014,11120019,11120023,11120030,11120034,11120037,11120039,11120040,11120045,11120052,11120057,11120062,11120063,11120069,11120070,11120071,11120074,11120077,11120078,11120084,11120092,11121006,11121014,11121015,11121019,11121029,11121030,11121034,11121035,11121043,11121044,11121054,11121058,11121066,11121067,11121070,11121075,11121082,11122001,11122007,11122008,11122010,11122017,11122024,11122037,11122038,11122047,11122048,11122049,11122050,11122053,11122058,11122062,11122069,11122073,11122078,11122085,11122097,11123003,11123004,11123015,11123026,11123028,11123040,11123044,11123055,11123057,11123058,11123059,11123067,11123075,11123076,11123077,11123079,11123081,11123084,11123086,11123088,11123089,11123093,11123094,11123095,11123100,11123101,11123102,11123104,11124001,11124005,11124007,11124008,11124015,11124016,11124018,11124041,11124046,11124050,11124051,11124052,11124053,11124058,11124060,11124061,11124062,11124063,11124064,11124065,11124066,11124069,11125002,11125003,11125004,11125005,11125006,11125008,11125012,11125013,11125014,11125015,11125016,11125017,11125020,11125021,11125022,11125023,11125073,11125081,11125089,11125090,11125096,11125097,11126005,11126006,11126007,11126016,11126018,11126022,11126023,11127001,11127002,11127043,11128005,11128012,11128018,11128050,11128056,11128072,11129018,11129022,11129028,11129051,11130027,11130034,11130057,11131038,11131062,11132013,11132070,11133006,11133019,11134053,11134060,11134067,11134076,11135068,11136003,11136005,11136006,11136007,11136008,11136012,11136013,11136014,11136061,11136076,11136101,11136130,11136160,11136163,11137019,11138027,11138049,11138086,11138124,11139014,11140076,11140086,11141063,11142117,11143026,11143028,11144001,11144009,11144031,11144033,11144040,11144043,11144052,11145008,11145028,11145035,11146061,11146076,11146079,11147004,11147006,11147014,11147017,11147021,11147023};
static const Int_t bad_run_list_11GeV[27] = {11148039,11148045,11149001,11149008,11149010,11149011,11149015,11149047,11150016,11150025,11150028,11151036,11151040,11151050,11152016,11152036,11152078,11153032,11153042,11155001,11155009,11156003,11156009,11157012,11158006,11158022,11158024};
static const Int_t bad_run_list_19GeV[35] = {12113091,12114007,12114035,12114078,12114092,12114116,12115009,12115014,12115015,12115016,12115018,12115019,12115020,12115022,12115023,12115062,12115073,12115093,12115094,12116012,12116054,12117010,12117016,12117020,12117065,12119040,12119042,12120017,12120026,12121017,12121022,12121034,12121050,12121067,12122019};
static const Int_t bad_run_list_27GeV[34] = {12172050,12172051,12172055,12173030,12173031,12173032,12173033,12173034,12174067,12174085,12175062,12175087,12175113,12175114,12175115,12176001,12176044,12176054,12176071,12177015,12177061,12177092,12177099,12177101,12177106,12177107,12177108,12178003,12178004,12178005,12178006,12178013,12178099,12178120};
static const Int_t bad_run_list_39GeV[38] = {11199124,11100002,11100045,11101046,11102012,11102051,11102052,11102053,11102054,11102055,11102058,11103035,11103056,11103058,11103092,11103093,11105052,11105053,11105054,11105055,11107007,11107042,11107057,11107061,11107065,11107074,11108101,11109013,11109077,11109088,11109090,11109127,11110013,11110034,11110073,11110076,11111084,11111085};
static const Int_t bad_run_list_62GeV[105] = {11080072,11081023,11081025,11082012,11082013,11082046,11082056,11082057,11084009,11084011,11084012,11084013,11084020,11084021,11084035,11084044,11084064,11085015,11085025,11085030,11085046,11085055,11085056,11085057,11086005,11086007,11087001,11087002,11087003,11087004,11088013,11089026,11089028,11089029,11089055,11089068,11089072,11091007,11091015,11091021,11091078,11092010,11092011,11092012,11092032,11092033,11092034,11092067,11092096,11093001,11094016,11094017,11094018,11094019,11094020,11094021,11094022,11094023,11094024,11094027,11094028,11094042,11094044,11094045,11094046,11094047,11094048,11094050,11094051,11094052,11094053,11094054,11094055,11094074,11094075,11094077,11095001,11095002,11095003,11095004,11095005,11095006,11095009,11095010,11095011,11095012,11095013,11095014,11095015,11095022,11095040,11095048,11095050,11095051,11095061,11095062,11095063,11095064,11095082,11095087,11096024,11096039,11096043,11096044,11097093};
static const Int_t bad_run_list_200GeV[179] = {12126101,12127003,12127017,12127018,12127032,12128025,12132043,12133018,12134023,12136005,12136006,12136014,12136017,12136022,12136023,12136024,12136025,12136027,12136028,12136029,12136030,12136031,12136034,12136054,12138017,12138021,12138081,12138082,12139006,12139007,12139015,12139016,12139028,12139059,12139075,12139076,12139077,12139078,12139079,12139080,12140010,12140011,12140012,12140013,12140014,12140015,12140016,12140018,12140019,12140020,12140021,12140025,12140026,12140027,12140028,12140029,12140042,12140051,12140052,12140053,12140054,12140055,12140056,12140064,12140066,12140067,12141001,12141002,12141003,12141004,12141005,12141006,12141009,12141014,12141015,12141016,12141017,12141018,12141019,12141026,12141027,12141028,12141029,12141030,12141032,12141033,12141034,12141035,12141036,12141041,12141042,12141043,12141044,12141045,12141046,12141048,12141050,12141051,12141052,12141056,12141059,12141060,12141061,12141062,12141063,12141064,12141065,12141066,12141067,12141071,12141072,12142001,12142002,12142003,12142006,12142013,12142014,12142015,12142016,12142017,12142018,12142019,12142020,12142021,12142022,12142023,12142026,12142027,12142032,12142033,12142034,12142046,12142047,12142048,12142049,12142050,12142051,12142061,12142062,12142063,12142076,12142077,12143016,12143018,12143054,12143075,12144001,12144002,12144013,12144014,12144027,12144028,12157038,12157051,12158040,12158041,12158054,12158056,12158057,12162055,12162056,12162057,12162058,12164037,12164078,12164079,12166002,12166003,12167015,12167024,12167052,12168002,12168009,12168022,12168077,12170044,12170045,12170054,12170056};
static const Int_t bad_run_list_15GeV[1] = {1};
//------------------------------------------------------------------------------------------------------------------------------------
#include "StJetAnalysis_Func.h"
//------------------------------------------------------------------------------------------------------------------
ClassImp(StJetAnalysis)
StJetAnalysis::StJetAnalysis()
{
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
StJetAnalysis::~StJetAnalysis()
{
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
Int_t StJetAnalysis::Get_runID_range_Index(Int_t runID)
{
for(Int_t i_range = 0; i_range < 6; i_range++)
{
if(runID > Array_runID_eff_track_rec[i_range] && runID <= Array_runID_eff_track_rec[i_range+1])
{
return i_range;
}
}
return -1;
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
Double_t* StJetAnalysis::Parameter_eff_track_rec_function(Int_t Centrality, Int_t runID, Int_t PID, Int_t All)
{
Int_t runID_range = -1;
Double_t *Parameter = new Double_t[4];
for(int i = 0; i < 4; i++)
{
Parameter[i] = 0;
}
runID_range = Get_runID_range_Index(runID);
if(runID_range < 0)
{
cout << "WARNING: runID is out of range" << endl;
return 0;
}
if( PID < 0 || PID > 5)
{
cout << "PID is out of range" << endl;
return 0;
}
runID_range += 1; // index 0 is for all runIDs together
if(All == 1){runID_range = 0;}
Parameter[0] = Global_ABC_Parameters_A[Centrality][runID_range][PID];
Parameter[1] = Global_ABC_Parameters_B[Centrality][runID_range][PID];
Parameter[2] = Global_ABC_Parameters_C[Centrality][runID_range][PID];
Parameter[3] = runID_range;
return Parameter;
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
void StJetAnalysis::Read_ABC_params_eff_track_rec_function() //read ABC Parameter from a root file
{
Int_t Switch_Array[6]={2,3,4,5,0,1}; //change PID in turn
cout << "Read track reconstruction efficiency parameter file: " << eEff_file.Data() << endl;
TFile *Eff_file=new TFile(eEff_file.Data());
TH3D* hA =(TH3D*)Eff_file->Get("hA");
TH3D* hB =(TH3D*)Eff_file->Get("hB");
TH3D* hC =(TH3D*)Eff_file->Get("hC");
TH2D* hsA =(TH2D*)Eff_file->Get("hsA");
TH2D* hsB =(TH2D*)Eff_file->Get("hsB");
TH2D* hsC =(TH2D*)Eff_file->Get("hsC");
for(Int_t i = 0; i < 6; i++) // PID
{
for(Int_t j = 0; j < 9; j++) // Centrality
{
for(Int_t k = 0; k < 7; k++) // runID
{
Global_ABC_Parameters_A[j][k][Switch_Array[i]] = hA->GetBinContent(hA->FindBin(i,j,k));
Global_ABC_Parameters_B[j][k][Switch_Array[i]] = hB->GetBinContent(hB->FindBin(i,j,k));
Global_ABC_Parameters_C[j][k][Switch_Array[i]] = hC->GetBinContent(hC->FindBin(i,j,k));
}
}
}
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
Int_t StJetAnalysis::Init()
{
cout << "Init started" << endl;
r3.SetSeed(0);
refmultCorrUtil = CentralityMaker::instance()->getRefMultCorr();
jet_R = eJet_R;
jet_R_background = eBkg_R;
Remove_N_hardest = eRem_n_hardest;
max_pt_downscale_threshold = emax_pt_down_scale;
for(Int_t i = 0; i < 11; i++)
{
counter_PYTHIA[i] = 0;
}
for(Int_t i_charge = 0; i_charge < 2; i_charge++)
{
HistName = "p_pt_Ach_";
HistName += i_charge;
p_pt_Ach[i_charge] = new TProfile(HistName.Data(),HistName.Data(),15,-0.25,0.25);
}
h_Ach = new TH1F("h_Ach","h_Ach",60,-0.3,0.3);
//------------------------------------------------------------
cout << "Initialize track reconstruction efficiency functions" << endl;
TString FuncName;
for(Int_t loop_Centr = 0; loop_Centr < 9; loop_Centr++) // Centrality
{
for(Int_t loop_runID = 0; loop_runID < 7; loop_runID++) // runID
{
for(Int_t loop_PID = 0; loop_PID < 6; loop_PID++) // PID
{
Int_t loop_runID_use = loop_runID - 1; // runIDs start from loop_runID = 1, for loop_runID = 0 all runIDs are used
Int_t use_all_runIDs = 0;
if(loop_runID == 0) // for first index use all runIDs
{
loop_runID_use = 0;
use_all_runIDs = 1;
}
Double_t* Parameter = Parameter_eff_track_rec_function(loop_Centr,Array_runID_eff_track_rec[loop_runID_use+1],loop_PID,use_all_runIDs);
FuncName = "f_EfficiencyVsPt_runID_Centr_";
FuncName += loop_Centr;
FuncName += "_runID_";
FuncName += loop_runID;
FuncName += "_PID_";
FuncName += Array_PID_eff_track_rec[loop_PID];
f_EfficiencyVsPt[loop_Centr][loop_runID][loop_PID] = new TF1(FuncName.Data(),Eff_track_rec_function,0,50.0,3);
f_EfficiencyVsPt[loop_Centr][loop_runID][loop_PID]->SetParameter(0,Parameter[0]);
f_EfficiencyVsPt[loop_Centr][loop_runID][loop_PID]->SetParameter(1,Parameter[1]);
f_EfficiencyVsPt[loop_Centr][loop_runID][loop_PID]->SetParameter(2,Parameter[2]);
delete[] Parameter;
}
}
}
//------------------------------------------------------------
//------------------------------------------------------------
cout << "Open re-centering correction histograms" << endl;
// Open the mean Qx, Qy histograms for re-centering correction
start_z = -z_acceptance[eBeamTimeNum];
delta_z = 2.0*z_acceptance[eBeamTimeNum]/((Float_t)n_z_vertex_bins);
gBeamTimeNum = eBeamTimeNum;
re_centering = TFile::Open(re_centering_name.Data()); // open the file
cout << "Opened re centering file = " << re_centering_name.Data() << endl;
for(Int_t n_qxy = 0; n_qxy < 6; n_qxy++)
{
for(Int_t n_z = 0; n_z < n_z_vertex_bins; n_z++)
{
for(Int_t n_par = 0; n_par < n_params; n_par++)
{
HistName = "h_rc_QxQy_etapm_z_vs_index_";
HistName += n_qxy;
HistName += "_";
HistName += n_z;
HistName += "_";
HistName += n_par;
h_rc_QxQy_etapm_z_vs_index_[n_qxy][n_z][n_par] = (TH1D*)re_centering->FindObjectAny(HistName.Data());
}
}
}
h_runId_index_rc = (TH1D*)re_centering->FindObjectAny("h_runId_index");
h_runId_index_rc->SetName("h_runId_index_rc");
Double_t h_min_rc = h_runId_index_rc->GetMinimum();
Double_t h_max_rc = h_runId_index_rc->GetMaximum();
Int_t h_Nbins_rc = h_runId_index_rc->GetNbinsX();
Int_t h_Nbins_rc_inv = (Int_t)(h_max_rc-h_min_rc)+1;
cout << "h_Nbins_rc = " << h_Nbins_rc << ", h_min_rc = " << h_min_rc << ", h_max_rc = " << h_max_rc << endl;
h_runId_index_rc_inv = new TH1D("h_runId_index_rc_inv","h_runId_index_rc_inv",h_Nbins_rc_inv,h_min_rc,h_max_rc+1.0);
cout << "h_Nbins_rc_inv = " << h_runId_index_rc_inv->GetNbinsX() << endl;
for(Int_t i_rc = 1; i_rc < h_Nbins_rc+1; i_rc++)
{
h_runId_index_rc_inv->SetBinContent(h_runId_index_rc_inv->FindBin(h_runId_index_rc->GetBinContent(i_rc)),(Float_t)i_rc);
}
h_runId_index_rc_clone = (TH1D*)h_runId_index_rc->Clone("h_runId_index_rc_clone");
h_runId_index_rc_clone->Reset();
for(Int_t i_rc = 1; i_rc < h_runId_index_rc_inv->GetNbinsX()+1; i_rc++)
{
h_runId_index_rc_clone->SetBinContent(h_runId_index_rc_clone->FindBin(h_runId_index_rc_inv->GetBinContent(i_rc)),h_runId_index_rc_inv->GetBinCenter(i_rc));
}
h_runId_index_rc_clone->Add(h_runId_index_rc,-1);
// End recentering files
//------------------------------------------------------------
if(eMode == 311 || eMode == 312) N_orig_smear = 2; // PYTHIA
if(eCentrality == 1) // 60-80%
{
mult_start_stop_delta[0][0] = 5.0; // 5.0
mult_start_stop_delta[0][1] = 120.0; // 135.0
mult_start_stop_delta[0][2] = 1.0;
mult_start_stop_delta[1][0] = 5.0;
mult_start_stop_delta[1][1] = 120.0;
mult_start_stop_delta[1][2] = 1.0;
mult_start_stop_delta[2][0] = 5.0;
mult_start_stop_delta[2][1] = 120.0;
mult_start_stop_delta[2][2] = 1.0;
mult_start_stop_delta[3][0] = 5.0;
mult_start_stop_delta[3][1] = 120.0;
mult_start_stop_delta[3][2] = 1.0;
mult_start_stop_delta[4][0] = 5.0; // 5.0
mult_start_stop_delta[4][1] = 120.0; // 135.0
mult_start_stop_delta[4][2] = 1.0;
mult_start_stop_delta[5][0] = 5.0;
mult_start_stop_delta[5][1] = 120.0;
mult_start_stop_delta[5][2] = 1.0;
mult_start_stop_delta[6][0] = 5.0;
mult_start_stop_delta[6][1] = 120.0;
mult_start_stop_delta[6][2] = 1.0;
mult_start_stop_delta[7][0] = 5.0;
mult_start_stop_delta[7][1] = 120.0;
mult_start_stop_delta[7][2] = 1.0;
}
cout << "Open track efficiency file" << endl;
f_track_efficiencies = TFile::Open("/project/projectdirs/star/aschmah/Jet/Data/Efficiencies/eff_pp.root"); // open the file
func_effLow = (TF1*)f_track_efficiencies->Get("effhL");
func_effHigh = (TF1*)f_track_efficiencies->Get("effhH");
//----------------------------------------------------------------------------------------
cout << "Define functions" << endl;
LevyFit_pT = new TF1("LevyFit_pT",LevyFitFunc_pT,0.0,6.0,4);
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
if(eMode == 0 || eMode == 1 || eMode == 311 || eMode == 312)
{
// Same event input
for(Int_t i_SE_ME = 0; i_SE_ME < 1; i_SE_ME++)
{
TString SE_ME_List = SEList;
//if(i_SE_ME == 1) SE_ME_List = MEList;
if (!SE_ME_List.IsNull()) // if input file is ok
{
cout << "Open file list " << SE_ME_List << endl;
ifstream in(SE_ME_List); // input stream
if(in)
{
cout << "file list is ok" << endl;
if(eMode == 0 || eMode == 1 || eMode == 311)
{
input_SE_ME[i_SE_ME] = new TChain( ALEX_EVENT_TREE, ALEX_EVENT_TREE );
char str[255]; // char array for each file name
Long64_t entries_save = 0;
while(in)
{
in.getline(str,255); // take the lines of the file list
if(str[0] != 0)
{
TString addfile;
if(eMode == 0 || eMode == 1) addfile = "jet_trees_V2/";
addfile += str;
if(eMode == 311) addfile = pinputdirPYTHIA+addfile;
if(eMode == 312) addfile = pinputdir+addfile;
Long64_t file_entries;
input_SE_ME[i_SE_ME] ->AddFile(addfile.Data(),-1, ALEX_EVENT_TREE );
file_entries = input_SE_ME[i_SE_ME]->GetEntries();
cout << "File added to data chain: " << addfile.Data() << " with " << (file_entries-entries_save) << " entries" << endl;
entries_save = file_entries;
}
}
}
if(eMode == 312)
{
char str[255]; // char array for each file name
Int_t PYTHIA_file = 0;
while(in)
{
input_PYTHIA[PYTHIA_file] = new TChain( ALEX_EVENT_TREE, ALEX_EVENT_TREE );
in.getline(str,255); // take the lines of the file list
if(str[0] != 0)
{
TString addfile;
TString inputdir_full = pinputdirPYTHIA;
inputdir_full += "Pythia/Trees_9GeV/";
addfile += str;
addfile = inputdir_full+addfile;
Long64_t file_entries;
input_PYTHIA[PYTHIA_file] ->AddFile(addfile.Data(),-1, ALEX_EVENT_TREE );
file_entries = input_PYTHIA[PYTHIA_file]->GetEntries();
N_PYTHIA_events[PYTHIA_file] = file_entries;
cout << "File added to data chain: " << addfile.Data() << " with " << file_entries << " entries" << endl;
}
PYTHIA_file++;
}
}
}
else
{
cout << "WARNING: file input is problemtic" << endl;
}
if(eMode == 0 || eMode == 1 || eMode == 311)
{
JetTrackEvent = new StJetTrackEvent();
input_SE_ME[i_SE_ME] ->SetBranchAddress( ALEX_EVENT_BRANCH, &JetTrackEvent );
}
if(eMode == 312)
{
for(Int_t PYTHIA_file = 0; PYTHIA_file < 11; PYTHIA_file++)
{
cout << "Set branch address for PYTHIA hard bin file: " << PYTHIA_file << endl;
JetTrackEvent_PYTHIA[PYTHIA_file] = new StJetTrackEvent();
input_PYTHIA[PYTHIA_file] ->SetBranchAddress( ALEX_EVENT_BRANCH, &JetTrackEvent_PYTHIA[PYTHIA_file] );
}
}
}
if(eMode == 0 || eMode == 1 || eMode == 311)
{
file_entries_SE_ME[i_SE_ME] = input_SE_ME[i_SE_ME]->GetEntries();
cout << "Number of entries in chain: " << file_entries_SE_ME[i_SE_ME] << endl;
}
}
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
if(eMode == 2 || eMode == 3 || eMode == 4
|| eMode == 11 || eMode == 31 || eMode == 32 || eMode == 42 || eMode == 312
)
{
N_max_events = mult_start_stop_delta[eBeamTimeNum][1]*1.1;
JetTrackEvent_ME.resize(N_max_events);
for(Int_t mix_loop = 0; mix_loop < N_max_events; mix_loop++)
{
JetTrackEvent_ME[mix_loop] = new StJetTrackEvent();
}
//Int_t size = JetTrackEvent_ME.size();
//cout << "size = " << size << endl;
//JetTrackEvent_ME.clear();
//cout << "cleared" << endl;
input_SE_ME[0] = new TChain( ALEX_EVENT_TREE, ALEX_EVENT_TREE );
Long64_t entries_save = 0;
TString addfile;
//addfile = "histo_out/mode_";
addfile = "/histo_out_V2/mode_";
if(eIn_Mode != 24)
{
addfile += eIn_Mode;
}
else
{
addfile += 2;
}
addfile += "/F_mixed_event_z_";
addfile += ez_bin;
addfile += "_mult_";
addfile += emult_bin;
addfile += "_Psi_";
addfile += ePsi_bin;
addfile += "_mode_";
if(eIn_Mode != 24)
{
addfile += eIn_Mode;
}
if(eIn_Mode == 2)
{
addfile += "_In_mode_1";
}
if(eIn_Mode == 24)
{
addfile += "2_In_mode_4";
}
if(eCentrality == 0) addfile += "_0_10";
if(eCentrality == 1) addfile += "_60_80";
addfile += "_V2.root";
addfile = pinputdir+addfile;
Long64_t file_entries;
input_SE_ME[0] ->AddFile(addfile.Data(),-1, ALEX_EVENT_TREE );
file_entries = input_SE_ME[0]->GetEntries();
cout << "File added to data chain: " << addfile.Data() << " with " << (file_entries-entries_save) << " entries" << endl;
entries_save = file_entries;
JetTrackEvent = new StJetTrackEvent();
input_SE_ME[0] ->SetBranchAddress( ALEX_EVENT_BRANCH, &JetTrackEvent );
file_entries_SE_ME[0] = input_SE_ME[0]->GetEntries();
cout << "Number of entries in chain: " << file_entries_SE_ME[0] << endl;
if(eMode != 11)
{
cout << "Load sample histogram file: " << eSampleHist.Data() << endl;
Inputfile = TFile::Open(eSampleHist.Data()); // open the file
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_mult = 0; i_mult < N_mult_bins; i_mult++)
{
HistName = "h_tracks_vs_z_vertex_array_z_";
HistName += i_z;
HistName += "_m_";
HistName += i_mult;
h_tracks_vs_z_vertex_array[i_z][i_mult] = (TH2D*)Inputfile->Get(HistName.Data());
}
}
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
HistName = "h_Psi_vs_z_vertex_array_z_";
HistName += i_z;
HistName += "_m_";
HistName += i_Psi;
h_Psi_vs_z_vertex_array[i_z][i_Psi] = (TH2D*)Inputfile->Get(HistName.Data());
}
}
for(Int_t i_pT = 0; i_pT < N_track_pt_bins_eta_phi; i_pT++)
{
HistName = "h2D_track_eta_vs_phi_";
HistName += ez_bin;
HistName += "_m_";
HistName += emult_bin;
HistName += "_P_";
HistName += ePsi_bin;
HistName += "_pT_";
HistName += i_pT;
h2D_track_eta_vs_phi[ez_bin][emult_bin][ePsi_bin][i_pT] = (TH2D*)Inputfile->Get(HistName.Data());
}
}
cout << "Load SE Et histogram file: " << eSE_Et_Hist.Data() << endl;
Inputfile_Et[0] = TFile::Open(eSE_Et_Hist.Data()); // open the file
cout << "Load ME Et histogram file: " << eME_Et_Hist.Data() << endl;
Inputfile_Et[1] = TFile::Open(eME_Et_Hist.Data()); // open the file
//h_tracks_vs_z_vertex_sample = (TH2D*)Inputfile->Get("h_tracks_vs_z_vertex");
//h_tracks_vs_z_vertex_sample ->SetName("h_tracks_vs_z_vertex_sample");
//h_Psi2_sample = (TH1D*)Inputfile->Get("h_Psi2");
//h_Psi2_sample ->SetName("h_Psi2_sample");
cout << "Histograms loaded" << endl;
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
p_jet_area_values = new TProfile("p_jet_area_values","p_jet_area_values",100,0,100);
for(Int_t i_val = 0; i_val < N_jet_areas; i_val++)
{
p_jet_area_values->Fill(i_val,(Double_t)array_areas[i_val]);
}
p_parameters = new TProfile("p_parameters","p_parameters",100,0,100);
p_parameters ->Fill(0.0,(Double_t)N_Beamtime);
p_parameters ->Fill(1.0,(Double_t)N_jet_areas);
p_parameters ->Fill(2.0,(Double_t)N_z_vertex_bins);
p_parameters ->Fill(3.0,(Double_t)N_mult_bins);
p_parameters ->Fill(4.0,(Double_t)N_Psi_bins);
p_parameters ->Fill(5.0,(Double_t)N_Et_bins);
p_parameters ->Fill(6.0,(Double_t)N_leading_pt_bins);
p_parameters ->Fill(7.0,(Double_t)leading_pt_split_cut);
p_parameters ->Fill(8.0,(Double_t)leading_pt_split_val);
p_parameters ->Fill(9.0,(Double_t)max_pt_threshold);
p_parameters ->Fill(10.0,(Double_t)jet_delta_eta_cut);
p_parameters ->Fill(11.0,(Double_t)jet_delta_phi_cut);
p_parameters ->Fill(12.0,(Double_t)track_pT_assoc_threshold);
p_parameters ->Fill(13.0,(Double_t)jet_R);
p_parameters ->Fill(14.0,(Double_t)array_areas[0]);
p_parameters ->Fill(15.0,(Double_t)array_areas[1]);
p_parameters ->Fill(16.0,(Double_t)array_areas[2]);
p_parameters ->Fill(17.0,(Double_t)array_areas[3]);
p_parameters ->Fill(18.0,(Double_t)array_areas[4]);
p_parameters ->Fill(19.0,(Double_t)Remove_N_hardest);
p_parameters ->Fill(20.0,(Double_t)ePYTHIA_eff_factor);
p_parameters ->Fill(21.0,(Double_t)downscale_factor);
p_parameters ->Fill(22.0,(Double_t)N_Delta_pt_bins);
p_parameters ->Fill(23.0,(Double_t)array_pt_bins_Delta_pt[0]);
p_parameters ->Fill(24.0,(Double_t)array_pt_bins_Delta_pt[1]);
p_parameters ->Fill(25.0,(Double_t)array_pt_bins_Delta_pt[2]);
p_parameters ->Fill(26.0,(Double_t)array_pt_bins_Delta_pt[3]);
p_parameters ->Fill(27.0,(Double_t)array_pt_bins_Delta_pt[4]);
p_parameters ->Fill(28.0,(Double_t)jet_R_background);
p_parameters ->Fill(29.0,(Double_t)track_eff_scaling_factor);
p_parameters ->Fill(30.0,(Double_t)max_pt_downscale_threshold);
p_parameters ->Fill(31.0,(Double_t)max_pt_val_embed);
cout << "Parameters set" << endl;
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
HistName = "h_area_vs_recoil_jet_pt_";
HistName += ipt_lead;
h_area_vs_recoil_jet_pt[ipt_lead] = new TH2D(HistName.Data(),HistName.Data(),400,-20,80,400,0,2);
h_area_vs_recoil_jet_pt[ipt_lead]->Sumw2();
HistName = "h_rho_";
HistName += ipt_lead;
h_rho[ipt_lead] = new TH1D(HistName.Data(),HistName.Data(),400,0.0,60);
h_rho[ipt_lead]->Sumw2();
}
h_area_vs_jet_pt = new TH2D("h_area_vs_jet_pt","h_area_vs_jet_pt",400,-20,80,400,0,2);
h_area_vs_jet_pt->Sumw2();
h_area = new TH1D("h_area","h_area",400,0,2);
h_area->Sumw2();
h_track_pT = new TH1D("h_track_pT","h_track_pT",500,0,200);
h_track_pT->Sumw2();
h_track_pT_cut = new TH1D("h_track_pT_cut","h_track_pT_cut",500,0,200);
h_track_pT_cut->Sumw2();
h_tracks_above_threshold_per_event = new TH1D("h_tracks_above_threshold_per_event","h_tracks_above_threshold_per_event",20,0,20);
h_tracks_above_threshold_per_event->Sumw2();
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
HistName = "h2D_tracks_above_threshold_";
HistName += i_hist;
h2D_tracks_above_threshold[i_hist] = new TH2D(HistName.Data(),HistName.Data(),20,0,20,20,0,20);
h2D_tracks_above_threshold[i_hist]->Sumw2();
}
if(eMode == 0 || eMode == 3 || eMode == 31 || eMode == 32 || eMode == 311 || eMode == 312 || eMode == 42)
{
if(eMode == 3 || eMode == 31 || eMode == 32 || eMode == 312 || eMode == 42)
{
outputfile_name = eOutdir;
outputfile_name += "F_mixed_event_z_";
outputfile_name += ez_bin;
outputfile_name += "_mult_";
outputfile_name += emult_bin;
outputfile_name += "_Psi_";
outputfile_name += ePsi_bin;
outputfile_name += "_mode_";
outputfile_name += eMode;
outputfile_name += "_In_mode_";
outputfile_name += eIn_Mode;
if(eCentrality == 0) outputfile_name += "_0_10";
if(eCentrality == 1) outputfile_name += "_60_80";
outputfile_name += ".root";
}
cout << "Output file: " << outputfile_name.Data() << endl;
Outputfile = new TFile(outputfile_name.Data(),"RECREATE");
NT_ReCoil_Jet = new TNtuple("NT_ReCoil_Jet","NT_ReCoil_Jet Ntuple","EventId:JetId:rho:area:Jetphi:Jeteta:Jetpt:TrackId:eta:phi:pt:x:y:z");
NT_ReCoil_Jet ->SetAutoSave( 5000000 );
//c_3D = new TCanvas("c_3D","c_3D",10,10,800,800);
//h_3D_dummy = new TH3D("h_3D_dummy","h_3D_dummy",200,-300,300,200,-300,300,200,-1000,1000);
//Draw_STAR_3D();
}
if(eMode == 11)
{
outputfile_name = eOutdir;
outputfile_name += "Jet_sample_histos_out_z_";
//outputfile_name += eSuffix.Data();
outputfile_name += ez_bin;
outputfile_name += "_mult_";
outputfile_name += emult_bin;
outputfile_name += "_Psi_";
outputfile_name += ePsi_bin;
outputfile_name += "_mode_";
outputfile_name += eMode;
outputfile_name += "_In_mode_";
outputfile_name += eIn_Mode;
if(eCentrality == 0) outputfile_name += "_0_10";
if(eCentrality == 1) outputfile_name += "_60_80";
outputfile_name += ".root";
Outputfile = new TFile(outputfile_name.Data(),"RECREATE");
}
if(eMode == 1 || eMode == 2 || eMode == 4) // create sub category trees
{
cout << "Create sub category output files" << endl;
Int_t start_z = 0;
Int_t start_mult = 0;
Int_t start_Psi = 0;
//Int_t start_Psi = ePsi_bin;
Int_t stop_z = N_z_vertex_bins;
Int_t stop_mult = N_mult_bins;
Int_t stop_Psi = N_Psi_bins;
//Int_t stop_Psi = ePsi_bin+1;
if(eMode == 2
|| eMode == 1
|| eMode == 4
)
{
start_z = ez_bin;
start_mult = emult_bin;
start_Psi = ePsi_bin;
stop_z = ez_bin+1;
stop_mult = emult_bin+1;
stop_Psi = ePsi_bin+1;
}
for(Int_t i_z = start_z; i_z < stop_z; i_z++)
{
for(Int_t i_mult = start_mult; i_mult < stop_mult; i_mult++)
{
for(Int_t i_Psi = start_Psi; i_Psi < stop_Psi; i_Psi++)
{
TString mixed_event_outfile_name = eOutdir;
mixed_event_outfile_name += "F_mixed_event_z_";
mixed_event_outfile_name += i_z;
mixed_event_outfile_name += "_mult_";
mixed_event_outfile_name += i_mult;
mixed_event_outfile_name += "_Psi_";
mixed_event_outfile_name += i_Psi;
mixed_event_outfile_name += "_mode_";
mixed_event_outfile_name += eMode;
if(eMode == 2)
{
mixed_event_outfile_name += "_In_mode_";
mixed_event_outfile_name += eIn_Mode;
}
mixed_event_outfile_name += eSuffix.Data();
if(eCentrality == 0) mixed_event_outfile_name += "_0_10";
if(eCentrality == 1) mixed_event_outfile_name += "_60_80";
mixed_event_outfile_name += ".root";
F_mixed_event[i_z][i_mult][i_Psi] = new TFile(mixed_event_outfile_name.Data(),"RECREATE");
cout << "Sub category output file" << mixed_event_outfile_name.Data() << " created" << endl;
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi] = NULL;
JetTrackEvent_ptr_Fill[i_z][i_mult][i_Psi] = &JetTrackEvent_Fill[i_z][i_mult][i_Psi];
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi] = new TTree(JETTRACK_EVENT_TREE , JETTRACK_EVENT_TREE);
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi]->Branch(JETTRACK_EVENT_BRANCH , "StJetTrackEvent", &JetTrackEvent_ptr_Fill[i_z][i_mult][i_Psi]);
Long64_t maxtreesize = 2000000000;
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi]->SetMaxTreeSize(5*Long64_t(maxtreesize));
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi]->SetAutoSave( 10000000 );
//Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi]->SetBasketSize("*",128000);
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi]->SetBasketSize("*",128000*10);
HistName = "h_Momentum_z_";
HistName += i_z;
HistName += "_mult_";
HistName += i_mult;
HistName += "_Psi_";
HistName += i_Psi;
h_Momentum[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),500,-50,50);
HistName = "h_tracks_vs_z_vertex_z_";
HistName += i_z;
HistName += "_mult_";
HistName += i_mult;
HistName += "_Psi_";
HistName += i_Psi;
h_tracks_vs_z_vertex[i_z][i_mult][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),100,-50,50,1300,0,1300);
HistName = "h_Psi2_z_";
HistName += i_z;
HistName += "_mult_";
HistName += i_mult;
HistName += "_Psi_";
HistName += i_Psi;
h_Psi2[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),100,-TMath::Pi(),TMath::Pi());
HistName = "h_Et_z_";
HistName += i_z;
HistName += "_mult_";
HistName += i_mult;
HistName += "_Psi_";
HistName += i_Psi;
h_Et[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),1000,0,1000);
HistName = "h_Phi_vs_eta_z_";
HistName += i_z;
HistName += "_mult_";
HistName += i_mult;
HistName += "_Psi_";
HistName += i_Psi;
h_Phi_vs_eta[i_z][i_mult][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),200,-1.5,1.5,200,-1.0*TMath::Pi(),1.0*TMath::Pi());
}
}
}
h_PsiA_vs_PsiB = new TH2D("h_PsiA_vs_PsiB","h_PsiA_vs_PsiB",100,-TMath::Pi(),TMath::Pi(),100,-TMath::Pi(),TMath::Pi());
h_PsiA = new TH1D("h_PsiA","h_PsiA",100,-TMath::Pi(),TMath::Pi());
h_PsiB = new TH1D("h_PsiB","h_PsiB",100,-TMath::Pi(),TMath::Pi());
h_Psi_Full = new TH1D("h_Psi_Full","h_Psi_Full",100,-TMath::Pi(),TMath::Pi());
}
cout << "QA histograms created" << endl;
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
if(eMode == 11)
{
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_mult = 0; i_mult < N_mult_bins; i_mult++)
{
HistName = "h_tracks_vs_z_vertex_array_z_";
HistName += i_z;
HistName += "_m_";
HistName += i_mult;
h_tracks_vs_z_vertex_array[i_z][i_mult] = new TH2D(HistName.Data(),HistName.Data(),100,-50,50,1300,0,1300);
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
for(Int_t i_pT = 0; i_pT < N_track_pt_bins_eta_phi; i_pT++)
{
HistName = "h2D_track_eta_vs_phi_";
HistName += i_z;
HistName += "_m_";
HistName += i_mult;
HistName += "_P_";
HistName += i_Psi;
HistName += "_pT_";
HistName += i_pT;
h2D_track_eta_vs_phi[i_z][i_mult][i_Psi][i_pT] = new TH2D(HistName.Data(),HistName.Data(),80,-TMath::Pi(),TMath::Pi(),80,-1,1);
}
}
}
}
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
HistName = "h_Psi_vs_z_vertex_array_z_";
HistName += i_z;
HistName += "_m_";
HistName += i_Psi;
h_Psi_vs_z_vertex_array[i_z][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),100,-50,50,100,-TMath::Pi()/2.0,TMath::Pi()/2.0);
}
}
}
cout << "Additional histograms created" << endl;
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
if( (eMode == 3 || eMode == 31 || eMode == 32 || eMode == 312 || eMode == 42) && eRandom != -1)
{
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_mult = 0; i_mult < N_mult_bins; i_mult++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
Float_t Int_SE_ME[2];
for(Int_t iSE_ME = 0; iSE_ME < 2; iSE_ME++)
{
/*
HistName = "QA_hist_arrays/h_jet_Et_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME] = (TH1D*)Inputfile_Et[iSE_ME]->Get(HistName.Data());
HistName += "_iSE_ME";
HistName += iSE_ME;
h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME]->SetName(HistName.Data());
h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME]->Rebin(4);
//h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME]->Sumw2();
Float_t start_int_area = 0.0;
Float_t stop_int_area = 1000.0;
Int_SE_ME[iSE_ME] = h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME]->Integral(h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME]->FindBin(start_int_area),h_jet_Et_array_In[i_z][i_mult][i_Psi][iSE_ME]->FindBin(stop_int_area));
HistName = "QA_hist_arrays/h_tracks_per_event_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_tracks_per_event_array_In[i_z][i_mult][i_Psi][iSE_ME] = (TH1D*)Inputfile_Et[iSE_ME]->Get(HistName.Data());
HistName += "_iSE_ME";
HistName += iSE_ME;
h_tracks_per_event_array_In[i_z][i_mult][i_Psi][iSE_ME]->SetName(HistName.Data());
Integrated_events_SE_ME[iSE_ME] += h_tracks_per_event_array_In[i_z][i_mult][i_Psi][iSE_ME]->Integral(1,h_tracks_per_event_array_In[i_z][i_mult][i_Psi][iSE_ME]->GetNbinsX());
*/
HistName = "QA_hist_arrays/h2D_jet_rho_vs_mult_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
//cout << "Old name" << HistName.Data() << endl;
h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME] = (TH2D*)Inputfile_Et[iSE_ME]->Get(HistName.Data());
if(!h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME])
{
cout << "WARNING: " << HistName.Data() << " does not exist!" << endl;
if(eCentrality != 1)
{
h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME] = new TH2D(HistName.Data(),HistName.Data(),100,720,1020,150,15,45);
}
else
{
h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME] = new TH2D(HistName.Data(),HistName.Data(),60,0,180,150,0,30);
}
}
HistName += "_iSE_ME";
HistName += iSE_ME;
//cout << "New name" << HistName.Data() << endl;
h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME]->SetName(HistName.Data());
Integrated_events_SE_ME[iSE_ME] += h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME]->Integral(1,h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME]->GetNbinsX(),1,h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][iSE_ME]->GetNbinsY());
}
if(Int_SE_ME[0] > 0.0 && Int_SE_ME[1] > 0.0)
{
// Normalization? I removed it to take into account the different number of entries in SE and ME for different bins
//h_jet_Et_array_In[i_z][i_mult][i_Psi][1]->Scale(Int_SE_ME[0]/Int_SE_ME[1]);
}
}
}
}
cout << "All normalization histograms loaded" << endl;
SE_ME_integral_scale_factor = 1.0;
if(Integrated_events_SE_ME[0] > 0 && Integrated_events_SE_ME[1] > 0)
{
SE_ME_integral_scale_factor = Integrated_events_SE_ME[0]/Integrated_events_SE_ME[1];
}
cout << "Integrated_events_SE_ME[0] = " << Integrated_events_SE_ME[0] << ", Integrated_events_SE_ME[1] = " << Integrated_events_SE_ME[1] << ", SE_ME_integral_scale_factor = " << SE_ME_integral_scale_factor << endl;
// Apply global normalization factor to ME histograms -> same integrated number of counts
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_mult = 0; i_mult < N_mult_bins; i_mult++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
//h_tracks_per_event_array_In[i_z][i_mult][i_Psi][1]->Scale(SE_ME_integral_scale_factor);
h2D_jet_rho_vs_mult_array_In[i_z][i_mult][i_Psi][1]->Scale(SE_ME_integral_scale_factor);
}
}
}
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
h_ratio_sub_lead_to_lead_pt_vs_lead_pt = new TH2D("h_ratio_sub_lead_to_lead_pt_vs_lead_pt","h_ratio_sub_lead_to_lead_pt_vs_lead_pt",300,0,50,300,0,2);
h_sub_lead_vs_lead_pt = new TH2D("h_sub_lead_vs_lead_pt","h_sub_lead_vs_lead_pt",300,0,50,300,0,50);
for(Int_t i_area_acc = 0; i_area_acc < N_jet_areas; i_area_acc++)
{
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
HistName = "h_N_accepted_recoil_jets_area_";
HistName += i_area_acc;
HistName += "_pt_";
HistName += ipt_lead;
h_N_accepted_recoil_jets[i_area_acc][ipt_lead] = new TH1D(HistName.Data(),HistName.Data(),20,0,20);
h_N_accepted_recoil_jets[i_area_acc][ipt_lead]->Sumw2();
}
}
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_mult = 0; i_mult < N_mult_bins; i_mult++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
HistName = "h_jet_area_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_area_array[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),1000,0.0,2.0);
HistName = "h_jet_rho_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_rho_array[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),1000,0.0,100);
HistName = "h_jet_rhoarea_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_rhoarea_array[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),1000,0.0,200);
HistName = "h2D_jet_rho_vs_mult_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
if(eCentrality != 1)
{
h2D_jet_rho_vs_mult_array[i_z][i_mult][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),100,720,1020,150,15,45);
}
else
{
h2D_jet_rho_vs_mult_array[i_z][i_mult][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),60,0,180,150,0,30);
}
HistName = "h_jet_Et_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_Et_array[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),2000,0.0,1000);
HistName = "h_jet_Et_array_weight_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_Et_array_weight[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),2000,0.0,1000);
HistName = "h_jet_per_event_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_jet_per_event_array[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),100,0.0,100);
HistName = "h_tracks_per_event_array_z";
HistName += i_z;
HistName += "_m";
HistName += i_mult;
HistName += "_P";
HistName += i_Psi;
h_tracks_per_event_array[i_z][i_mult][i_Psi] = new TH1D(HistName.Data(),HistName.Data(),1300,0.0,1300);
}
}
}
h_jet_rho_vs_Et = new TH2D("h_jet_rho_vs_Et","h_jet_rho_vs_ET",2000,0.0,1000,1000,0.0,100);
h_trigger_track[0] = new TH1D("h_trigger_track","h_trigger_track",N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track[1] = new TH1D("h_trigger_track_smear","h_trigger_track_smear",N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track[2] = new TH1D("h_trigger_track_all","h_trigger_track_all",N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track[3] = new TH1D("h_trigger_track_smear_all","h_trigger_track_smear_all",N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track_vs_global_bin[0] = new TH2D("h_trigger_track_vs_global_bin","h_trigger_track_vs_global_bin",N_global_bin,0,N_global_bin,N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track_vs_global_bin[1] = new TH2D("h_trigger_track_vs_global_bin_smear","h_trigger_track_vs_global_bin_smear",N_global_bin,0,N_global_bin,N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track_vs_global_bin[2] = new TH2D("h_trigger_track_vs_global_bin_all","h_trigger_track_vs_global_bin_all",N_global_bin,0,N_global_bin,N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_trigger_track_vs_global_bin[3] = new TH2D("h_trigger_track_vs_global_bin_smear_all","h_trigger_track_vs_global_bin_smear_all",N_global_bin,0,N_global_bin,N_leading_pt_bins+1,0,N_leading_pt_bins+1);
h_jet_rho_vs_Et ->Sumw2();
h_trigger_track[0] ->Sumw2();
h_trigger_track[1] ->Sumw2();
h_trigger_track[2] ->Sumw2();
h_trigger_track[3] ->Sumw2();
h_trigger_track_vs_global_bin[0] ->Sumw2();
h_trigger_track_vs_global_bin[1] ->Sumw2();
h_trigger_track_vs_global_bin[2] ->Sumw2();
h_trigger_track_vs_global_bin[3] ->Sumw2();
for(Int_t i = 0; i < 2; i++)
{
HistName = "p_Array_leading_pt_bins_";
HistName += i;
p_Array_leading_pt_bins[i] = new TProfile(HistName.Data(),HistName.Data(),N_leading_pt_bins+1,0,N_leading_pt_bins+1);
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
p_Array_leading_pt_bins[i] ->Fill(ipt_lead,Array_leading_pt_bins[i][ipt_lead]);
}
}
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
HistName = "h_N_tracks_dijet_pt_";
HistName += ipt_lead;
if(i_orig_smear == 1) HistName += "_smear";
h_N_tracks_dijet[ipt_lead][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),100,mult_start_stop_delta[eBeamTimeNum][0],mult_start_stop_delta[eBeamTimeNum][1]);
h_N_tracks_dijet[ipt_lead][i_orig_smear] ->Sumw2();
HistName = "h2D_mult_vs_global_bin_pt_";
HistName += ipt_lead;
if(i_orig_smear == 1) HistName += "_smear";
h2D_mult_vs_global_bin[ipt_lead][i_orig_smear] = new TH2D(HistName.Data(),HistName.Data(),N_global_bin,0,N_global_bin,100,mult_start_stop_delta[eBeamTimeNum][0],mult_start_stop_delta[eBeamTimeNum][1]);
h2D_mult_vs_global_bin[ipt_lead][i_orig_smear] ->Sumw2();
}
}
if(eMode == 311 || eMode == 312)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
HistName = "h2D_Sim_matched_pT_vs_original_pT_area";
HistName += i;
h2D_Sim_matched_pT_vs_original_pT[i] = new TH2D(HistName.Data(),HistName.Data(),280,0,70,280,0,70);
HistName = "h2D_Sim_original_pT_vs_matched_pT_area";
HistName += i;
h2D_Sim_original_pT_vs_matched_pT[i] = new TH2D(HistName.Data(),HistName.Data(),280,0,70,280,0,70);
HistName = "h_matched_tracks_fraction_area";
HistName += i;
h_matched_tracks_fraction[i] = new TH1D(HistName.Data(),HistName.Data(),150,0,1.5);
HistName = "h2D_matched_tracks_fraction_vs_original_pT_area";
HistName += i;
h2D_matched_tracks_fraction_vs_original_pT[i] = new TH2D(HistName.Data(),HistName.Data(),280,0,70,150,0,1.5);
h2D_Sim_matched_pT_vs_original_pT[i] ->Sumw2();
h2D_Sim_original_pT_vs_matched_pT[i] ->Sumw2();
h_matched_tracks_fraction[i] ->Sumw2();
h2D_matched_tracks_fraction_vs_original_pT[i] ->Sumw2();
}
}
if(eMode == 312)
{
h_PYTHIA_hard_bin_weigh_factors = new TH1D("h_PYTHIA_hard_bin_weigh_factors","h_PYTHIA_hard_bin_weigh_factors",11,0,11);
h_PYTHIA_hard_bin_high_pT_N_events = new TH1D("h_PYTHIA_hard_bin_high_pT_N_events","h_PYTHIA_hard_bin_high_pT_N_events",11,0,11);
for(Int_t PYTHIA_file = 0; PYTHIA_file < 11; PYTHIA_file++)
{
h_PYTHIA_hard_bin_weigh_factors ->SetBinContent(PYTHIA_file+1,PYTHIA_hard_bin_weigh_factors[PYTHIA_file]);
h_PYTHIA_hard_bin_high_pT_N_events->SetBinContent(PYTHIA_file+1,PYTHIA_hard_bin_high_pT_N_events[PYTHIA_file]);
//cout << "PYTHIA_file: " << PYTHIA_file << ", weight: " << PYTHIA_hard_bin_weigh_factors[PYTHIA_file]
// << ", weight2: " << h_PYTHIA_hard_bin_weigh_factors->GetBinContent(PYTHIA_file + 1) << endl;
}
}
if(eMode == 42 || eMode == 312)
{
p_v2_vs_pt = new TProfile("p_v2_vs_pt","p_v2_ps_pt",200,0,20);
p_v2_vs_pt_jet = new TProfile("p_v2_vs_pt_jet","p_v2_ps_pt_jet",200,0,20);
h_Psi_Full = new TH1D("h_Psi_Full","h_Psi_Full",100,-TMath::Pi(),TMath::Pi());
h_phi = new TH1D("h_phi","h_phi",200,-2.0*TMath::Pi(),2.0*TMath::Pi());
h_Psi_etapos = new TH1D("h_Psi_etapos","h_Psi_etapos",100,-TMath::Pi(),TMath::Pi());
h_Psi_etaneg = new TH1D("h_Psi_etaneg","h_Psi_etaneg",100,-TMath::Pi(),TMath::Pi());
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
HistName = "h_Delta_pt_vs_embed_pt_";
HistName += i;
HistName += "_P_";
HistName += i_Psi;
if(i_orig_smear == 1) HistName += "_smear";
const Int_t N_bins_pt_embed = (Int_t)(max_pt_val_embed*4.0);
const Double_t Pt_range_embed = (Double_t)(N_bins_pt_embed/4.0);
h_Delta_pt_vs_embed_pt[i][i_orig_smear][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),N_bins_pt_embed,0,Pt_range_embed,160,-30,50.0);
h_Delta_pt_vs_embed_pt[i][i_orig_smear][i_Psi] ->Sumw2();
if(eMode == 42)
{
HistName = "h_Delta_pt_vs_embed_pt_weight_";
HistName += i;
HistName += "_P_";
HistName += i_Psi;
if(i_orig_smear == 1) HistName += "_smear";
const Int_t N_bins_pt_embed = (Int_t)(max_pt_val_embed*4.0);
const Double_t Pt_range_embed = (Double_t)(N_bins_pt_embed/4.0);
h_Delta_pt_vs_embed_pt_weight[i][i_orig_smear][i_Psi] = new TH2D(HistName.Data(),HistName.Data(),N_bins_pt_embed,0,Pt_range_embed,160,-30,50.0);
h_Delta_pt_vs_embed_pt_weight[i][i_orig_smear][i_Psi] ->Sumw2();
}
}
}
}
}
for(Int_t i_orig_smear = 0; i_orig_smear < 4; i_orig_smear++)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
HistName = "h_jet_pt_";
HistName += i;
HistName += "_lead_pt_";
HistName += ipt_lead;
if(i_orig_smear == 1) HistName += "_smear";
if(i_orig_smear > 1)
{
HistName += "_";
HistName += i_orig_smear;
}
h_jet_pt[i][ipt_lead][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),1400,-40,100.0);
h_jet_pt[i][ipt_lead][i_orig_smear] ->Sumw2();
HistName = "h_jet_pt_sub_";
HistName += i;
HistName += "_lead_pt_";
HistName += ipt_lead;
if(i_orig_smear == 1) HistName += "_smear";
if(i_orig_smear > 1)
{
HistName += "_";
HistName += i_orig_smear;
}
h_jet_pt_sub[i][ipt_lead][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),1400,-40,100.0);
h_jet_pt_sub[i][ipt_lead][i_orig_smear] ->Sumw2();
HistName = "h2D_dijet_pt_";
HistName += i;
HistName += "_lead_pt_";
HistName += ipt_lead;
if(i_orig_smear == 1) HistName += "_smear";
if(i_orig_smear > 1)
{
HistName += "_";
HistName += i_orig_smear;
}
h2D_dijet_pt[i][ipt_lead][i_orig_smear] = new TH2D(HistName.Data(),HistName.Data(),100,-0.5*Pi,1.5*Pi,350,-40,100.0);
h2D_dijet_pt[i][ipt_lead][i_orig_smear] ->Sumw2();
HistName = "h2D_dijet_pt_sub_";
HistName += i;
HistName += "_lead_pt_";
HistName += ipt_lead;
if(i_orig_smear == 1) HistName += "_smear";
if(i_orig_smear > 1)
{
HistName += "_";
HistName += i_orig_smear;
}
h2D_dijet_pt_sub[i][ipt_lead][i_orig_smear] = new TH2D(HistName.Data(),HistName.Data(),100,-0.5*Pi,1.5*Pi,350,-40,100.0);
h2D_dijet_pt_sub[i][ipt_lead][i_orig_smear] ->Sumw2();
}
if(i_orig_smear < N_orig_smear)
{
HistName = "h_jet_area_";
HistName += i;
if(i_orig_smear == 1) HistName += "_smear";
h_jet_area[i][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),1000,0.0,2.0);
h_jet_area[i][i_orig_smear] ->Sumw2();
HistName = "h_jet_rho_";
HistName += i;
if(i_orig_smear == 1) HistName += "_smear";
h_jet_rho[i][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),1000,0.0,100);
h_jet_rho[i][i_orig_smear] ->Sumw2();
HistName = "h_jet_per_event_";
HistName += i;
if(i_orig_smear == 1) HistName += "_smear";
h_jet_per_event[i][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),100,0.0,100.0);
h_jet_per_event[i][i_orig_smear] ->Sumw2();
HistName = "h_dijet_per_event_";
HistName += i;
if(i_orig_smear == 1) HistName += "_smear";
h_dijet_per_event[i][i_orig_smear] = new TH1D(HistName.Data(),HistName.Data(),100,0.0,100.0);
h_dijet_per_event[i][i_orig_smear] ->Sumw2();
}
}
}
if(eMode == 0 || eMode == 1 || eMode == 2 || eMode == 4)
{
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
HistName = "h_Phi_vs_eta_random_phi_";
HistName += i_z;
h_Phi_vs_eta_random_phi[i_z] = new TH2D(HistName.Data(),HistName.Data(),200,-1.5,1.5,200,-1.0*TMath::Pi(),1.0*TMath::Pi());
}
}
Float_t delta_z = (vertex_z_start_stop_delta[eBeamTimeNum][1] - vertex_z_start_stop_delta[eBeamTimeNum][0])/((Float_t)N_z_vertex_bins);
vertex_z_start_stop_delta[eBeamTimeNum][2] = delta_z;
Float_t delta_mult = (mult_start_stop_delta[eBeamTimeNum][1] - mult_start_stop_delta[eBeamTimeNum][0])/((Float_t)N_mult_bins);
mult_start_stop_delta[eBeamTimeNum][2] = delta_mult;
Float_t delta_Psi = (Psi_start_stop_delta[eBeamTimeNum][1] - Psi_start_stop_delta[eBeamTimeNum][0])/((Float_t)N_Psi_bins);
Psi_start_stop_delta[eBeamTimeNum][2] = delta_Psi;
//----------------------------------------------------------------------------------------------------
return 1;
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
Int_t StJetAnalysis::Make()
{
cout << "Make started" << endl;
r3.SetSeed(0);
gRandom->SetSeed(0);
cout << "Seed = " << r3.GetSeed() << endl;
ran_gen.SetSeed(0);
ran.SetSeed(0);
//----------------------------------------------------------------------------------------------------
cout << "Define bad run list" << endl;
Int_t bad_run_numbers[n_bad_run_numbers[eBeamTimeNum]];
for(Int_t j = 0; j < n_bad_run_numbers[eBeamTimeNum]; j++)
{
if(eBeamTimeNum == 0) bad_run_numbers[j] = bad_run_list_7GeV[j];
if(eBeamTimeNum == 1) bad_run_numbers[j] = bad_run_list_11GeV[j];
if(eBeamTimeNum == 2) bad_run_numbers[j] = bad_run_list_39GeV[j];
if(eBeamTimeNum == 3) bad_run_numbers[j] = bad_run_list_62GeV[j];
if(eBeamTimeNum == 4) bad_run_numbers[j] = bad_run_list_19GeV[j];
if(eBeamTimeNum == 5) bad_run_numbers[j] = bad_run_list_27GeV[j];
if(eBeamTimeNum == 6) bad_run_numbers[j] = bad_run_list_200GeV[j];
if(eBeamTimeNum == 7) bad_run_numbers[j] = bad_run_list_15GeV[j];
}
//----------------------------------------------------------------------------------------------------
if(eMode == 0 || eMode == 1 || eMode == 11 || eMode == 3 || eMode == 31 || eMode == 32 || eMode == 312 || eMode == 42 || eMode == 4 || eMode == 311) // eMode 2 is mixed event
{
if(eMode == 1 || eMode == 2 || eMode == 4)
{
F_mixed_event[ez_bin][emult_bin][ePsi_bin] ->cd();
}
for(Int_t i_SE_ME = 0; i_SE_ME < 1; i_SE_ME++)
{
if(i_SE_ME == 0) cout << "Same event loop started" << endl;
if(i_SE_ME == 1) cout << "Mixed event loop started" << endl;
Int_t vertex_pos_counter = 0;
Long64_t stop_event_use_loop = stop_event_use;
if(stop_event_use_loop > file_entries_SE_ME[i_SE_ME]) stop_event_use_loop = file_entries_SE_ME[i_SE_ME];
for(Long64_t counter = start_event_use; counter < stop_event_use_loop; counter++)
{
if (counter != 0 && counter % 100 == 0)
cout << "." << flush;
if (counter != 0 && counter % 1000 == 0)
{
if((stop_event_use_loop-start_event_use) > 0)
{
Double_t event_percent = 100.0*((Double_t)(counter-start_event_use))/((Double_t)(stop_event_use_loop-start_event_use));
cout << " " << counter << " (" << event_percent << "%) " << "\n" << "==> Processing data " << flush;
}
}
if (!input_SE_ME[i_SE_ME]->GetEntry( counter )) // take the event -> information is stored in event
break; // end of data chunk
//-----------------------------------------------------------------------------
// Event information
Float_t prim_vertex_x = JetTrackEvent->getx();
Float_t prim_vertex_y = JetTrackEvent->gety();
Float_t prim_vertex_z = JetTrackEvent->getz();
Int_t RunId = JetTrackEvent->getid();
Float_t refMult = JetTrackEvent->getmult();
Float_t n_prim = JetTrackEvent->getn_prim();
Float_t n_non_prim = JetTrackEvent->getn_non_prim();
Int_t n_tofmatch_prim = JetTrackEvent->getn_tof_prim();
Int_t SE_ME_flag = JetTrackEvent->getSE_ME_flag();
Float_t ZDCx = JetTrackEvent->getZDCx();
Float_t BBCx = JetTrackEvent->getBBCx();
Float_t vzVPD = JetTrackEvent->getvzVpd();
Int_t N_Particles = JetTrackEvent->getNumParticle();
TVector2 QvecEtaPos = JetTrackEvent->getQvecEtaPos();
TVector2 QvecEtaNeg = JetTrackEvent->getQvecEtaNeg();
Int_t cent9 = JetTrackEvent->getcent9();
if(fabs(prim_vertex_z) > z_acceptance[eBeamTimeNum]) continue;
Double_t reweight = 1.0;
if(eMode != 311) // not PYTHIA
{
refmultCorrUtil->init(RunId);
refmultCorrUtil->initEvent(refMult, prim_vertex_z, ZDCx);
// Get centrality bins
// see StRefMultCorr.h for the definition of centrality bins
//erefMult_bin16 = refmultCorrUtil->getCentralityBin16();
//erefMult_bin = refmultCorrUtil->getCentralityBin9();
reweight = refmultCorrUtil->getWeight();
//cout << "Centrality reweight: " << reweight << endl;
}
Int_t cent9_eff_array[9] = {8,7,6,5,4,3,2,1,0}; // index for centrality was inverted for efficiency functions
Int_t cent9_eff = 0;
if(cent9 >= 0 && cent9 < 9) cent9_eff = cent9_eff_array[cent9];
Double_t Psi2 = 0.0;
Double_t EP_eta_pos_corr = -999.0; // angle
Double_t EP_eta_neg_corr = -999.0; // angle
Double_t EP_Qx_eta_pos_corr = -999.0;
Double_t EP_Qy_eta_pos_corr = -999.0;
Double_t EP_Qx_eta_neg_corr = -999.0;
Double_t EP_Qy_eta_neg_corr = -999.0;
if(eMode == 1) // Do a re-centering correction for the Q-vectors
{
Calc_Corr_EventPlane_Angle(JetTrackEvent, EP_eta_pos_corr, EP_eta_neg_corr, EP_Qx_eta_pos_corr,
EP_Qy_eta_pos_corr, EP_Qx_eta_neg_corr, EP_Qy_eta_neg_corr);
QvecEtaPos.Set(EP_Qx_eta_pos_corr,EP_Qy_eta_pos_corr);
QvecEtaNeg.Set(EP_Qx_eta_neg_corr,EP_Qy_eta_neg_corr);
Double_t EP_eta_full = TMath::ATan2(EP_Qy_eta_pos_corr+EP_Qy_eta_neg_corr,EP_Qx_eta_pos_corr+EP_Qx_eta_neg_corr);
EP_eta_full /= 2.0;
Psi2 = EP_eta_full;
}
else
{
EP_eta_pos_corr = TMath::ATan2(QvecEtaPos.Y(),QvecEtaPos.X());
EP_eta_pos_corr /= 2.0;
EP_eta_neg_corr = TMath::ATan2(QvecEtaNeg.Y(),QvecEtaNeg.X());
EP_eta_neg_corr /= 2.0;
Double_t EP_eta_full = TMath::ATan2(QvecEtaPos.Y()+QvecEtaNeg.Y(),QvecEtaPos.X()+QvecEtaNeg.X());
EP_eta_full /= 2.0;
Psi2 = EP_eta_full;
}
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Good/Bad run selection
Int_t flag_good_run = 1;
for(Int_t bad_run = 0; bad_run < n_bad_run_numbers[eBeamTimeNum]; bad_run++)
{
if(bad_run_numbers[bad_run] == (Int_t)RunId)
{
flag_good_run = 0;
break;
}
}
//if(!flag_good_run) cout << "bad run: " << (Int_t)RunId << endl;
//---------------------------------------------------------------------------
// Pileup protection
if(
fabs(vzVPD - prim_vertex_z) < 3.0 &&
n_tofmatch_prim > 1 &&
flag_good_run
)
{
Int_t z_bin = -1;
if(prim_vertex_z > vertex_z_start_stop_delta[eBeamTimeNum][0] && prim_vertex_z < vertex_z_start_stop_delta[eBeamTimeNum][1])
{
z_bin = (Int_t)((prim_vertex_z-vertex_z_start_stop_delta[eBeamTimeNum][0])/vertex_z_start_stop_delta[eBeamTimeNum][2]);
}
Int_t mult_bin = -1;
if(N_Particles > mult_start_stop_delta[eBeamTimeNum][0] && N_Particles < mult_start_stop_delta[eBeamTimeNum][1])
{
mult_bin = (Int_t)((N_Particles-mult_start_stop_delta[eBeamTimeNum][0])/mult_start_stop_delta[eBeamTimeNum][2]);
}
Int_t Psi_bin = -1;
if(Psi2 > Psi_start_stop_delta[eBeamTimeNum][0] && Psi2 < Psi_start_stop_delta[eBeamTimeNum][1])
{
Psi_bin = (Int_t)((Psi2-Psi_start_stop_delta[eBeamTimeNum][0])/Psi_start_stop_delta[eBeamTimeNum][2]);
}
//if(mult_bin == 7 && Psi_bin == 0 && z_bin == 10)
//{
//cout << "N_Particles = " << N_Particles << ", refMult = " << refMult << ", mult_bin = " << mult_bin << ", Psi_bin = " << Psi_bin << ", z_bin = " << z_bin << endl;
//cout << "start mult: " << mult_start_stop_delta[eBeamTimeNum][0] << ", Delta mult: " << mult_start_stop_delta[eBeamTimeNum][2] << endl;
//QvecEtaPos.Print();
//QvecEtaNeg.Print();
//}
Int_t global_bin = z_bin + mult_bin*N_z_vertex_bins + Psi_bin*N_z_vertex_bins*N_mult_bins;
if(eMode != 1) global_bin = ez_bin + emult_bin*N_z_vertex_bins + ePsi_bin*N_z_vertex_bins*N_mult_bins;
if(eMode == 11
//&& z_bin != -1 && mult_bin != -1 && Psi_bin != -1
)
{
Int_t N_Particles_below_threshold = 0;
Long64_t N_tracks_above_threshold = 0;
Long64_t N_tracks_above_threshold_array[N2D_tracks_above_threshold];
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
N_tracks_above_threshold_array[i_hist] = 0;
}
Long64_t N_tracks_above_trigger = 0;
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent ->getParticle(i_Particle);
Float_t dca = JetTrackParticle->get_dca_to_prim();
Float_t m2 = JetTrackParticle->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
Double_t track_pT = TLV_Particle_use.Pt();
if(track_pT != track_pT) continue; // that is a NaN test. It always fails if track_pT = nan.
Double_t track_eta = TLV_Particle_use.PseudoRapidity();
Double_t track_phi = TLV_Particle_use.Phi();
if(dca < 1.0 && nhitsfit > 14)
{
h_track_pT_cut ->Fill(TLV_Particle_use.Pt());
if(TLV_Particle_use.Pt() > max_pt_threshold) N_tracks_above_threshold++;
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
if(TLV_Particle_use.Pt() > (max_pt_threshold + 2.0*((Double_t)i_hist))) N_tracks_above_threshold_array[i_hist]++;
}
if(TLV_Particle_use.Pt() > 9.0 && TLV_Particle_use.Pt() <= max_pt_threshold) N_tracks_above_trigger++;
}
Int_t epT_bin = 0;
for(Int_t i_pT = 0; i_pT < N_track_pt_bins_eta_phi; i_pT++)
{
if(track_pT <= array_pt_bins_eta_phi[i_pT])
{
epT_bin = i_pT;
break;
}
}
//if(nSPi == -999.0) cout << "i_Particle = " << i_Particle << ", mother_pT = " << nSK << ", pT = " << TLV_Particle_use.Pt() << endl;
if(
(nSPi == -999.0 && nSK < max_pt_threshold) || // nSK stores in eMode = 4 the orignal pT before splitting
(nSPi != -999.0 && TLV_Particle_use.Pt() < max_pt_threshold)
)
{
h2D_track_eta_vs_phi[ez_bin][emult_bin][ePsi_bin][epT_bin]->Fill(track_phi,track_eta);
//cout << "eta = " << track_eta << ", phi = " << track_phi << endl;
N_Particles_below_threshold++;
}
//else
//{
// cout << "i_Particle = " << i_Particle << ", nSPi = " << nSPi << ", mother_pT = " << nSK << ", pT = " << TLV_Particle_use.Pt() << endl;
//}
}
h_tracks_above_threshold_per_event ->Fill(N_tracks_above_threshold);
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
h2D_tracks_above_threshold[i_hist] ->Fill(N_tracks_above_trigger,N_tracks_above_threshold_array[i_hist]);
}
h_tracks_vs_z_vertex_array[ez_bin][emult_bin] ->Fill(prim_vertex_z,N_Particles_below_threshold);
h_Psi_vs_z_vertex_array[ez_bin][ePsi_bin] ->Fill(prim_vertex_z,Psi2);
}
if(eMode == 0 && z_bin != -1)
{
//cout << "prim_vertex_z = " << prim_vertex_z << ", N_Particles = " << N_Particles << endl;
//h_tracks_vs_z_vertex->Fill(prim_vertex_z,N_Particles);
//h_Psi2 ->Fill(Psi2);
//-----------------------------------------------------------------------------
// Particle loop
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent ->getParticle(i_Particle);
Float_t dca = JetTrackParticle->get_dca_to_prim();
Float_t m2 = JetTrackParticle->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
Double_t track_pT = TLV_Particle_use.Pt();
if(track_pT != track_pT) continue; // that is a NaN test. It always fails if track_pT = nan.
Double_t track_eta = TLV_Particle_use.PseudoRapidity();
Double_t track_phi = TLV_Particle_use.Phi();
//h_Phi_vs_eta[z_bin] ->Fill(Eta,Phi);
Double_t ran_angle = ran_gen.Rndm()*TMath::Pi()*2.0;
TLV_Particle_use.SetPhi(ran_angle);
track_phi = TLV_Particle_use.Phi();
h_Phi_vs_eta_random_phi[z_bin] ->Fill(track_eta,track_phi);
}
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
if(eMode == 1)
{
// Fill event plane QA histograms
h_PsiA_vs_PsiB ->Fill(EP_eta_neg_corr,EP_eta_pos_corr);
h_PsiA ->Fill(EP_eta_pos_corr);
h_PsiB ->Fill(EP_eta_neg_corr);
h_Psi_Full ->Fill(Psi2);
}
//-----------------------------------------------------------------------------
if(eMode == 1 &&
z_bin == ez_bin &&
mult_bin == emult_bin &&
Psi_bin == ePsi_bin
//z_bin >= 0 && z_bin < N_z_vertex_bins &&
//mult_bin >= 0 && mult_bin < N_mult_bins &&
//Psi_bin >= 0 && Psi_bin < N_Psi_bins
//Psi_bin == ePsi_bin
)
{
//F_mixed_event[z_bin][mult_bin][Psi_bin] ->cd();
// Calculate biased Et
Double_t Et_total = 0.0;
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent->getParticle(i_Particle);
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
//if(TLV_Particle_use.Pt() < 2.5)
{
Et_total += TLV_Particle_use.Et();
}
}
h_Et[z_bin][mult_bin][Psi_bin] ->Fill(Et_total);
h_tracks_vs_z_vertex[z_bin][mult_bin][Psi_bin] ->Fill(prim_vertex_z,N_Particles);
h_Psi2[z_bin][mult_bin][Psi_bin] ->Fill(Psi2);
// Fill event information for d4s
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].clearParticleList();
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setx(prim_vertex_x);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].sety(prim_vertex_y);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setz(prim_vertex_z);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setid(RunId);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setmult(refMult);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setn_prim(n_prim);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setn_non_prim(n_non_prim);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setn_tof_prim(n_tofmatch_prim);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setSE_ME_flag(SE_ME_flag);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setZDCx(ZDCx);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setBBCx(BBCx);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setvzVpd(vzVPD);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setQvecEtaPos(QvecEtaPos);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setQvecEtaNeg(QvecEtaNeg);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setcent9(cent9);
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent ->getParticle(i_Particle);
Float_t dca = JetTrackParticle->get_dca_to_prim();
Float_t m2 = JetTrackParticle->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
Double_t track_pT = TLV_Particle_use.Pt();
if(track_pT != track_pT) continue; // that is a NaN test. It always fails if track_pT = nan.
Double_t Eta = TLV_Particle_use.PseudoRapidity();
Double_t Phi = TLV_Particle_use.Phi();
h_Phi_vs_eta[z_bin][mult_bin][Psi_bin] ->Fill(Eta,Phi);
h_Momentum[z_bin][mult_bin][Psi_bin] ->Fill(qp);
JetTrackParticle_Fill = JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].createParticle();
JetTrackParticle_Fill ->set_dca_to_prim(dca);
JetTrackParticle_Fill ->set_Particle_m2(m2);
JetTrackParticle_Fill ->set_Particle_nSigmaPi(nSPi);
JetTrackParticle_Fill ->set_Particle_nSigmaK(nSK);
JetTrackParticle_Fill ->set_Particle_nSigmaP(nSP);
JetTrackParticle_Fill ->set_Particle_qp(qp);
JetTrackParticle_Fill ->set_TLV_Particle_prim(TLV_Particle_prim);
JetTrackParticle_Fill ->set_TLV_Particle_glob(TLV_Particle_glob);
JetTrackParticle_Fill ->set_Particle_hits_fit(nhitsfit);
}
Tree_JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin] ->Fill();
}
if(eMode == 4 &&
z_bin == ez_bin &&
mult_bin == emult_bin &&
Psi_bin == ePsi_bin
)
{
// Calculate biased Et
Double_t Et_total = 0.0;
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent->getParticle(i_Particle);
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
//if(TLV_Particle_use.Pt() < 2.5)
{
Et_total += TLV_Particle_use.Et();
}
}
h_Et[z_bin][mult_bin][Psi_bin] ->Fill(Et_total);
h_tracks_vs_z_vertex[z_bin][mult_bin][Psi_bin] ->Fill(prim_vertex_z,N_Particles);
h_Psi2[z_bin][mult_bin][Psi_bin] ->Fill(Psi2);
// Fill event information for d4s
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].clearParticleList();
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setx(prim_vertex_x);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].sety(prim_vertex_y);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setz(prim_vertex_z);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setid(RunId);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setmult(refMult);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setn_prim(n_prim);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setn_non_prim(n_non_prim);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setn_tof_prim(n_tofmatch_prim);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setSE_ME_flag(SE_ME_flag);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setZDCx(ZDCx);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setBBCx(BBCx);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setvzVpd(vzVPD);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setQvecEtaPos(QvecEtaPos);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setQvecEtaNeg(QvecEtaNeg);
JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].setcent9(cent9);
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent->getParticle(i_Particle);
Float_t dca = JetTrackParticle->get_dca_to_prim();
Float_t m2 = JetTrackParticle->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
Double_t track_pT = TLV_Particle_use.Pt();
if(track_pT != track_pT) continue; // that is a NaN test. It always fails if track_pT = nan.
Float_t Phi = TLV_Particle_use.Phi();
Float_t Eta = TLV_Particle_use.PseudoRapidity();
Float_t Energy = TLV_Particle_use.E();
h_Phi_vs_eta[z_bin][mult_bin][Psi_bin] ->Fill(Eta,Phi);
h_Momentum[z_bin][mult_bin][Psi_bin] ->Fill(qp);
Float_t Pt = track_pT;
//if(Pt > 10.0)
//{
// cout << "Pt = " << Pt << ", Eta = " << Eta << ", Phi = " << Phi << ", m2 = " << m2
// << ", nSPi = " << nSPi << ", qp = " << qp << ", dca = " << dca << endl;
//}
if(Pt >= leading_pt_split_cut) // split the track into smaller pieces
{
Double_t N_d_split_tracks = Pt/leading_pt_split_val;
Int_t N_i_split_tracks = (Int_t)N_d_split_tracks; // number of split tracks
Double_t pt_split_val = Pt/((Double_t)N_i_split_tracks); // real pt value of split tracks
//cout << "Pt = " << Pt << ", Eta = " << Eta << ", Phi = " << Phi << ", N_i_split_tracks = " << N_i_split_tracks << ", pt_split_val = " << pt_split_val << endl;
for(Int_t i_split = 0; i_split < N_i_split_tracks; i_split++)
{
TLorentzVector TLV_Particle_split_prim = TLV_Particle_use;
Double_t Delta_eta = (ran_gen.Rndm()-0.5)*0.2;
Double_t Delta_phi = (ran_gen.Rndm()-0.5)*0.2;
Double_t Eta_split = TLV_Particle_use.PseudoRapidity() + Delta_eta;
Double_t Phi_split = TLV_Particle_use.Phi() + Delta_phi;
if(Eta_split > 1.2) Eta_split = 1.2 - ran_gen.Rndm()*0.1;
if(Eta_split < -1.2) Eta_split = -1.2 + ran_gen.Rndm()*0.1;
if(Phi_split > TMath::Pi()) Phi_split -= 2.0*TMath::Pi();
if(Phi_split < (-TMath::Pi())) Phi_split += 2.0*TMath::Pi();
Double_t E_split = TLV_Particle_use.E()/((Double_t)N_d_split_tracks);
TLV_Particle_split_prim.SetPtEtaPhiE(pt_split_val,Eta_split,Phi_split,E_split);
TLorentzVector TLV_Particle_split_glob = TLV_Particle_glob;
Delta_eta = (ran_gen.Rndm()-0.5)*0.2;
Delta_phi = (ran_gen.Rndm()-0.5)*0.2;
Eta_split = TLV_Particle_glob.PseudoRapidity() + Delta_eta;
Phi_split = TLV_Particle_glob.Phi() + Delta_phi;
if(Eta_split > 1.2) Eta_split = 1.2 - ran_gen.Rndm()*0.1;
if(Eta_split < -1.2) Eta_split = -1.2 + ran_gen.Rndm()*0.1;
if(Phi_split > TMath::Pi()) Phi_split -= 2.0*TMath::Pi();
if(Phi_split < (-TMath::Pi())) Phi_split += 2.0*TMath::Pi();
E_split = TLV_Particle_glob.E()/((Double_t)N_d_split_tracks);
TLV_Particle_split_glob.SetPtEtaPhiE(pt_split_val,Eta_split,Phi_split,E_split);
//cout << "i_split = " << i_split << ", Eta_split = " << Eta_split << ", Phi_split = " << Phi_split << endl;
JetTrackParticle_Fill = JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].createParticle();
JetTrackParticle_Fill ->set_dca_to_prim(dca);
JetTrackParticle_Fill ->set_Particle_m2(Phi);
JetTrackParticle_Fill ->set_Particle_nSigmaPi(-999.0);
JetTrackParticle_Fill ->set_Particle_nSigmaK(Pt);
JetTrackParticle_Fill ->set_Particle_nSigmaP(N_d_split_tracks);
JetTrackParticle_Fill ->set_Particle_qp(Eta);
JetTrackParticle_Fill ->set_TLV_Particle_prim(TLV_Particle_split_prim);
JetTrackParticle_Fill ->set_TLV_Particle_glob(TLV_Particle_split_glob);
JetTrackParticle_Fill ->set_Particle_hits_fit(nhitsfit);
}
}
else
{
JetTrackParticle_Fill = JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin].createParticle();
JetTrackParticle_Fill ->set_dca_to_prim(dca);
JetTrackParticle_Fill ->set_Particle_m2(m2);
JetTrackParticle_Fill ->set_Particle_nSigmaPi(nSPi);
JetTrackParticle_Fill ->set_Particle_nSigmaK(nSK);
JetTrackParticle_Fill ->set_Particle_nSigmaP(nSP);
JetTrackParticle_Fill ->set_Particle_qp(qp);
JetTrackParticle_Fill ->set_TLV_Particle_prim(TLV_Particle_prim);
JetTrackParticle_Fill ->set_TLV_Particle_glob(TLV_Particle_glob);
JetTrackParticle_Fill ->set_Particle_hits_fit(nhitsfit);
}
}
Tree_JetTrackEvent_Fill[z_bin][mult_bin][Psi_bin] ->Fill();
}
if(eMode == 3 || eMode == 31 || eMode == 32 || eMode == 312 || eMode == 311 || eMode == 42)
{
//-----------------------------------------------------------------------------
// Particle loop
std::vector< std::vector<PseudoJet> > particles; // original, smeared for PYTHIA
particles.resize(2);
vector<Float_t> particles_info;
Double_t Et_total = 0.0;
Int_t i_Particle_use = 0;
Double_t pt_Delta_pt = 0.0;
Double_t qp_Embed = 1.0;
if(eMode == 42) // Get embedding pt value for Delta pt calculation
{
//Int_t pt_bin_Delta_pt = ran_gen.Integer(N_Delta_pt_bins);
//pt_Delta_pt = array_pt_bins_Delta_pt[pt_bin_Delta_pt];
pt_Delta_pt = ran_gen.Rndm()*max_pt_val_embed;
}
std::vector< std::vector<Double_t> > vec_trigger_tracks; // eta, phi, pT
Long64_t N_tracks_above_threshold = 0;
Long64_t N_tracks_above_threshold_array[N2D_tracks_above_threshold];
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
N_tracks_above_threshold_array[i_hist] = 0;
}
Long64_t N_tracks_above_trigger = 0;
Int_t N_pos_neg_charges_reconstructed[2] = {0,0};
Int_t N_pos_neg_charges_reconstructed_Ach[2] = {0,0};
for(Int_t i_Particle = 0; i_Particle < N_Particles; i_Particle++)
{
// Particle information
JetTrackParticle = JetTrackEvent->getParticle(i_Particle);
Float_t dca = JetTrackParticle->get_dca_to_prim();
Float_t m2 = JetTrackParticle->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
Double_t track_phi = TLV_Particle_use.Phi();
Double_t track_pT = TLV_Particle_use.Pt();
if(track_pT != track_pT) continue; // that is a NaN test. It always fails if track_pT = nan.
Double_t track_eta = TLV_Particle_use.PseudoRapidity();
h_track_pT ->Fill(TLV_Particle_use.Pt());
#if 0
//---------------------------------------------------------------
// A_ch analysis -> CMW effect (nothing to do with jets)
// Cuts to determine Ach
Int_t charge = 0;
if(qp < 0.0) charge = 1;
if(
fabs(track_eta) < 1.0
&& track_pT > 0.15
&& track_pT < 12.0
&& !(track_pT < 0.4 && fabs(nSP) < 3.0)
&& dca < 1.0
&& nhitsfit >= 15
&& N_pos_neg_charges_reconstructed_Ach[charge] < max_tracks
)
{
N_pos_neg_charges_reconstructed_Ach[charge]++;
}
// Cuts to determine pion pT
if(
fabs(track_eta) < 1.0
&& track_pT > 0.15
&& track_pT < 0.5
&& dca < 1.0
&& nhitsfit >= 15
&& N_pos_neg_charges_reconstructed[charge] < max_tracks
&& fabs(nSPi) < 2.0
)
{
pt_tracks[charge][N_pos_neg_charges_reconstructed[charge]] = track_pT;
N_pos_neg_charges_reconstructed[charge]++;
}
//---------------------------------------------------------------
#endif
if(dca < 1.0 && nhitsfit > 14)
{
h_track_pT_cut ->Fill(TLV_Particle_use.Pt());
if(TLV_Particle_use.Pt() > max_pt_threshold) N_tracks_above_threshold++;
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
if(TLV_Particle_use.Pt() > (max_pt_threshold + 2.0*((Double_t)i_hist))) N_tracks_above_threshold_array[i_hist]++;
}
if(TLV_Particle_use.Pt() > 9.0 && TLV_Particle_use.Pt() <= max_pt_threshold) N_tracks_above_trigger++;
if(EP_eta_pos_corr > -999.0 && EP_eta_neg_corr > -999.0)
{
Double_t Psi2_use = EP_eta_pos_corr;
if(track_eta > 0.0) Psi2_use = EP_eta_neg_corr;
Double_t phi_use = track_phi;
// -pi/2..pi/2 -> 0..pi
if(Psi2_use < 0.0) Psi2_use += TMath::Pi();
// -pi..pi -> 0..pi
if(phi_use < 0.0) phi_use = phi_use + TMath::Pi();
// -pi..pi, delta_phi_angle: 0..pi
Double_t delta_phi_angle = phi_use - Psi2_use;
if(phi_use >= 0.0 && delta_phi_angle >= 0.0) delta_phi_angle = delta_phi_angle;
if(phi_use >= 0.0 && delta_phi_angle < 0.0) delta_phi_angle += TMath::Pi();
if(phi_use < 0.0 && delta_phi_angle >= -TMath::Pi()) delta_phi_angle += TMath::Pi();
if(phi_use < 0.0 && delta_phi_angle < -TMath::Pi()) delta_phi_angle += 2.0*TMath::Pi();
Double_t v2_val = TMath::Cos(2.0*delta_phi_angle);
//--------------------------------------------------------
if(eMode == 42)
{
p_v2_vs_pt ->Fill(track_pT,v2_val);
}
}
}
// if(fabs(track_eta) > 1.0) cout << "i_Particle: " << i_Particle << ", Track pT: " << TLV_Particle_use.Pt() << ", Track eta: " << track_eta << endl;
qp_Embed = qp;
//if(eRandom == 1)
//{
//Double_t ran_angle = ran_gen.Rndm()*TMath::Pi()*2.0;
//TLV_Particle_use.SetPhi(ran_angle);
//}
if(
(nSPi == -999.0 && nSK < max_pt_threshold) || // nSK stores in eMode = 4 the orignal pT before splitting
(nSPi == -999.0 && eIn_Mode == 24) ||
(nSPi != -999.0 && TLV_Particle_use.Pt() < max_pt_threshold) // remove tracks above max pT threshold
//(nSPi != -999.0)
)
{
if(dca < 1.0)
{
//----------------------------------------------
// Trigger particles
if(track_pT > 0.2 && track_pT < max_pt_threshold && fabs(track_eta) < 1.0)
{
std::vector<Double_t> vec_in;
vec_in.resize(3);
vec_in[0] = track_eta;
vec_in[1] = track_phi;
vec_in[2] = track_pT;
vec_trigger_tracks.push_back(vec_in);
}
//----------------------------------------------
if((eMode == 32 || eMode == 312) && TLV_Particle_use.Pt() > max_pt_downscale_threshold)
{
//cout << "Before: p = {" << TLV_Particle_use.Px() << ", " << TLV_Particle_use.Py() << ", " << TLV_Particle_use.Pz() << ", " << TLV_Particle_use.E() << "}" << endl;
TLV_Particle_use *= downscale_factor;
//cout << "After: p = {" << TLV_Particle_use.Px() << ", " << TLV_Particle_use.Py() << ", " << TLV_Particle_use.Pz() << ", " << TLV_Particle_use.E() << "}" << endl;
}
PseudoJet Fill_PseudoJet(TLV_Particle_use.Px(),TLV_Particle_use.Py(),TLV_Particle_use.Pz(),TLV_Particle_use.E());
Fill_PseudoJet.set_user_index(i_Particle_use);
//particles.push_back( PseudoJet(TLV_Particle_use.Px(),TLV_Particle_use.Py(),TLV_Particle_use.Pz(),TLV_Particle_use.E()) );
if(eMode != 312) particles[0].push_back(Fill_PseudoJet); // mode 312: save only original PYTHIA tracks (later) for particles[0] -> Calculate Delta pT with PYTHIA jets
if(eMode == 312)
{
particles[1].push_back(Fill_PseudoJet); //
}
particles_info.push_back(qp);
Et_total += TLV_Particle_use.Et();
//cout << "index = " << i_Particle_use << ", qp = " << qp << ", Et_total = " << Et_total << endl;
// Do momentum smearing and apply track efficiencies for PYTHIA
if(eMode == 311) // PYTHIA
{
// Apply momentum smearing and track reconstruction efficiency
PseudoJet Fill_PseudoJet_smear;
Int_t track_acc = Apply_mom_smearing_and_efficiency(eflab_prim_glob,qp,eCentrality,i_Particle_use,m2,ePYTHIA_eff_factor,TLV_Particle_use,Fill_PseudoJet_smear,f_EfficiencyVsPt);
if(track_acc)
{
particles[1].push_back(Fill_PseudoJet_smear);
}
}
i_Particle_use++;
}
}
} // end of track loop
#if 0
//---------------------------------------------------------------
// A_ch analysis -> CMW effect (nothing to do with jets)
if(N_pos_neg_charges_reconstructed_Ach[0] + N_pos_neg_charges_reconstructed_Ach[1] > 0)
{
Double_t Ach = ((Double_t)(N_pos_neg_charges_reconstructed_Ach[0] - N_pos_neg_charges_reconstructed_Ach[1]))/((Double_t)(N_pos_neg_charges_reconstructed_Ach[0] + N_pos_neg_charges_reconstructed_Ach[1]));
Double_t Mult = (Double_t)(N_pos_neg_charges_reconstructed_Ach[0] + N_pos_neg_charges_reconstructed_Ach[1]);
h_Ach ->Fill(Ach);
for(Int_t i_pos_neg = 0; i_pos_neg < 2; i_pos_neg++) // loop first over all positive and then over all negative charges
{
for(Int_t i_tracks = 0; i_tracks < N_pos_neg_charges_reconstructed[i_pos_neg]; i_tracks++)
{
p_pt_Ach[i_pos_neg] ->Fill(Ach,pt_tracks[i_pos_neg][i_tracks]);
}
}
}
//---------------------------------------------------------------
#endif
h_tracks_above_threshold_per_event->Fill(N_tracks_above_threshold);
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
h2D_tracks_above_threshold[i_hist] ->Fill(N_tracks_above_trigger,N_tracks_above_threshold_array[i_hist]);
}
Int_t Embed_user_index = i_Particle_use+1;
//---------------------------------------------------
// Single particle embedding for delta pt calculation
if(eMode == 42) // Delta pt calculation -> add one additional track
{
// Calculate pT bin for sampling distribution
Int_t epT_bin = 0;
for(Int_t i_pT = 0; i_pT < N_track_pt_bins_eta_phi; i_pT++)
{
if(pt_Delta_pt <= array_pt_bins_eta_phi[i_pT])
{
epT_bin = i_pT;
break;
}
}
// Sample eta and phi of the track based on same event distribution
Double_t track_phi;
Double_t track_eta;
h2D_track_eta_vs_phi[ez_bin][emult_bin][ePsi_bin][epT_bin]->GetRandom2(track_phi,track_eta);
//cout << "Embed pt = " << pt_Delta_pt << ", epT_bin = " << epT_bin << ", phi = " << track_phi << ", eta = " << track_eta << endl;
TLorentzVector TLV_Particle_Embed;
TLV_Particle_Embed.SetPtEtaPhiM(pt_Delta_pt,track_eta,track_phi,1.0);
PseudoJet Fill_PseudoJet(TLV_Particle_Embed.Px(),TLV_Particle_Embed.Py(),TLV_Particle_Embed.Pz(),TLV_Particle_Embed.E());
Fill_PseudoJet.set_user_index(Embed_user_index);
particles[0].push_back(Fill_PseudoJet);
particles_info.push_back(qp_Embed); // taken from previous real track
}
//---------------------------------------------------
//---------------------------------------------------
Double_t PYTHIA_hard_bin_index_weight = 1.0;
if(eMode == 312)
{
// PYTHIA embedding for closure test
// Get random hard bin
Int_t PYTHIA_hard_bin_index = (Int_t)(h_PYTHIA_hard_bin_high_pT_N_events->GetRandom()); // Number of PYTHIA events with at least one 9 GeV/c track
//Int_t PYTHIA_hard_bin_index = ran_gen.Integer(11);
// Get PYTHIA hard bin weighting factor
PYTHIA_hard_bin_index_weight = h_PYTHIA_hard_bin_weigh_factors->GetBinContent(PYTHIA_hard_bin_index + 1);
//cout << "PYTHIA embedding, index: " << PYTHIA_hard_bin_index << ", PYTHIA_hard_bin_index_weight: " << PYTHIA_hard_bin_index_weight << endl;
if(PYTHIA_hard_bin_index >= 0 && PYTHIA_hard_bin_index < 11)
{
if(counter_PYTHIA[PYTHIA_hard_bin_index] >= N_PYTHIA_events[PYTHIA_hard_bin_index]) // start from the first PYTHIA event if all events were already used
{
counter_PYTHIA[PYTHIA_hard_bin_index] = 0;
}
input_PYTHIA[PYTHIA_hard_bin_index]->GetEntry(counter_PYTHIA[PYTHIA_hard_bin_index]);
#if 0
cout << "" << endl;
cout << "PYTHIA embedding, index: " << PYTHIA_hard_bin_index << ", counter: " << counter_PYTHIA[PYTHIA_hard_bin_index]
<< ", PYTHIA_hard_bin_index_weight: " << PYTHIA_hard_bin_index_weight << endl;
#endif
Float_t N_Particles_PYTHIA = JetTrackEvent_PYTHIA[PYTHIA_hard_bin_index]->getNumParticle();
// Loop over the PYTHIA tracks
Int_t PYTHIA_user_index = 10000;
for(Int_t i_Particle_PYTHIA = 0; i_Particle_PYTHIA < N_Particles_PYTHIA; i_Particle_PYTHIA++)
{
// Particle information
JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index] = JetTrackEvent_PYTHIA[PYTHIA_hard_bin_index]->getParticle(i_Particle_PYTHIA);
Float_t dca_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_dca_to_prim();
Float_t m2_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_Particle_m2 ();
Float_t nSPi_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_Particle_nSigmaPi();
Float_t nSK_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_Particle_nSigmaK();
Float_t nSP_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_Particle_nSigmaP();
Float_t qp_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_Particle_qp();
Float_t nhitsfit_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob_PYTHIA = JetTrackParticle_PYTHIA[PYTHIA_hard_bin_index]->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use_PYTHIA = TLV_Particle_prim_PYTHIA;
if(eflab_prim_glob == 1) TLV_Particle_use_PYTHIA = TLV_Particle_glob_PYTHIA;
Double_t track_pT_PYTHIA = TLV_Particle_use_PYTHIA.Pt();
if(track_pT_PYTHIA != track_pT_PYTHIA) continue; // that is a NaN test. It always fails if track_pT = nan.
Double_t track_eta_PYTHIA = TLV_Particle_use_PYTHIA.PseudoRapidity();
Double_t track_phi_PYTHIA = TLV_Particle_use_PYTHIA.Phi();
TLorentzVector TLV_Particle_Embed;
TLV_Particle_Embed.SetPtEtaPhiM(track_pT_PYTHIA,track_eta_PYTHIA,track_phi_PYTHIA,1.0);
PseudoJet Fill_PseudoJet(TLV_Particle_Embed.Px(),TLV_Particle_Embed.Py(),TLV_Particle_Embed.Pz(),TLV_Particle_Embed.E());
Fill_PseudoJet.set_user_index(PYTHIA_user_index);
//particles[0].push_back(Fill_PseudoJet);
particles_info.push_back(qp_PYTHIA); // taken from previous real track
// Apply momentum smearing and track reconstruction efficiency
PseudoJet Fill_PseudoJet_smear_PYTHIA;
Int_t track_acc = Apply_mom_smearing_and_efficiency(eflab_prim_glob,qp_PYTHIA,eCentrality,PYTHIA_user_index,m2_PYTHIA,ePYTHIA_eff_factor,TLV_Particle_use_PYTHIA,Fill_PseudoJet_smear_PYTHIA,f_EfficiencyVsPt);
if(track_acc)
{
// Only difference for mode 312 is that [0] has no underlying heavy-ion event
particles[0].push_back(Fill_PseudoJet_smear_PYTHIA);
particles[1].push_back(Fill_PseudoJet_smear_PYTHIA);
//----------------------------------------------
// Trigger particles
if(track_pT_PYTHIA > 0.2 && track_pT_PYTHIA < max_pt_threshold && fabs(track_eta_PYTHIA) < 1.0)
{
std::vector<Double_t> vec_in;
vec_in.resize(3);
vec_in[0] = track_eta_PYTHIA;
vec_in[1] = track_phi_PYTHIA;
vec_in[2] = track_pT_PYTHIA;
vec_trigger_tracks.push_back(vec_in);
}
//----------------------------------------------
}
//cout << "i_Particle_PYTHIA: " << i_Particle_PYTHIA << ", pt: " << track_pT_PYTHIA << endl;
PYTHIA_user_index++;
Embed_user_index++;
}
counter_PYTHIA[PYTHIA_hard_bin_index]++;
}
else
{
cout << "ERROR: PYTHIA_hard_bin_index out of range!" << endl;
continue;
}
}
//---------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// choose a jet definition
JetDefinition jet_def(antikt_algorithm, jet_R);
// jet area definition
Double_t ghost_maxrap = 1.0; // Fiducial cut for background estimation
GhostedAreaSpec area_spec(ghost_maxrap);
//AreaDefinition area_def(active_area, area_spec);
AreaDefinition area_def(active_area_explicit_ghosts,GhostedAreaSpec(ghost_maxrap,1,0.01));
// Loop only activates for PYTHIA
vector<PseudoJet> jets[2]; // [not smeared, smeared] only for PYTHIA
Double_t jet_rho_array[2];
std::vector< std::vector< std::vector<Float_t> > > vec_jet_array;
std::vector< std::vector< std::vector< std::vector<Float_t> > > > vec_jet_const_array; // jet constituent information
vec_jet_array.resize(2); // [not smeared, smeared] only for PYTHIA
vec_jet_const_array.resize(2); // [not smeared, smeared] only for PYTHIA
#if 0
cout << "tracks original PYTHIA: " << particles[0].size() << ", tracks PYTHIA (smeared+eff): " << particles[1].size() << endl;
#endif
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
//AreaDefinition area_def(active_area, GhostedAreaSpec(ghost_maxrap));
//ClusterSequenceArea clust_seq(particles, jet_def, area_def);
ClusterSequenceArea clust_seq_hard(particles[i_orig_smear], jet_def, area_def);
// run the clustering, extract the jets
//ClusterSequence clust_seq(particles, jet_def);
double ptmin = 0.2;
vector<PseudoJet> jets_all = sorted_by_pt(clust_seq_hard.inclusive_jets(ptmin));
Selector Fiducial_cut_selector = SelectorAbsEtaMax(1.0 - jet_R); // Fiducial cut for jets
jets[i_orig_smear] = Fiducial_cut_selector(jets_all);
//vector<PseudoJet> jets[i_orig_smear] = sorted_by_pt(clust_seq.inclusive_jets());
// print out some info
//cout << "Clustered with " << jet_def.description() << endl;
// background estimation
//cout << "Define JetDefinition" << endl;
//JetDefinition jet_def_bkgd(kt_algorithm, 0.4);
JetDefinition jet_def_bkgd(kt_algorithm, jet_R_background); // <--
//JetDefinition jet_def_bkgd(antikt_algorithm, jet_R); // test
//cout << "Define AreaDefinition" << endl;
AreaDefinition area_def_bkgd(active_area_explicit_ghosts,GhostedAreaSpec(ghost_maxrap,1,0.01));
//AreaDefinition area_def_bkgd(active_area,GhostedAreaSpec(ghost_maxrap,1,0.005));
//cout << "Define selector" << endl;
//Selector selector = SelectorAbsRapMax(1.0) * (!SelectorNHardest(Remove_N_hardest)); // 2
Selector selector = SelectorAbsEtaMax(1.0) * (!SelectorNHardest(Remove_N_hardest)); // <--
//Selector selector = SelectorAbsEtaMax(1.0 - jet_R); // test
//cout << "Define JetMedianBackgroundEstimator" << endl;
JetMedianBackgroundEstimator bkgd_estimator(selector, jet_def_bkgd, area_def_bkgd); // <--
//JetMedianBackgroundEstimator bkgd_estimator(selector, jet_def, area_def); // test
//cout << "Define Subtractor" << endl;
Subtractor subtractor(&bkgd_estimator);
//cout << "Define bkgd_estimator" << endl;
bkgd_estimator.set_particles(particles[i_orig_smear]);
//cout << "Calculate jet_rho and jet_sigma" << endl;
Double_t jet_rho = bkgd_estimator.rho();
jet_rho_array[i_orig_smear] = jet_rho;
//cout << "jet_sigma" << endl;
Double_t jet_sigma = bkgd_estimator.sigma();
//cout << "jet_rho = " << jet_rho << ", jet_sigma = " << jet_sigma << endl;
/*
cout << "Jets above " << ptmin << " GeV in jets (" << jets.size() << " particles)" << endl;
cout << "---------------------------------------\n";
printf("%5s %15s %15s %15s %15s\n","jet #", "rapidity", "phi", "pt", "area");
for (unsigned int i = 0; i < jets.size(); i++) {
printf("%5u %15.8f %15.8f %15.8f %15.8f\n", i,
jets[i].rap(), jets[i].phi(), jets[i].perp(),
jets[i].area());
}
cout << endl;
*/
//h_jet_per_event[0] ->Fill(jets.size());
//----------------------------------------------------------------------------------------
// Calculate Et weight (SE and ME are different due to statistical average effect)
Float_t SE_ME_Et_val[2];
Float_t Et_weight_factor = 1.0;
if(eRandom != -1)
{
for(Int_t iSE_ME_Et = 0; iSE_ME_Et < 2; iSE_ME_Et++)
{
//SE_ME_Et_val[iSE_ME_Et] = h_jet_Et_array_In[ez_bin][emult_bin][ePsi_bin][iSE_ME_Et] ->GetBinContent(h_jet_Et_array_In[ez_bin][emult_bin][ePsi_bin][iSE_ME_Et]->FindBin(Et_total));
//SE_ME_Et_val[iSE_ME_Et] = h_tracks_per_event_array_In[ez_bin][emult_bin][ePsi_bin][iSE_ME_Et] ->GetBinContent(h_tracks_per_event_array_In[ez_bin][emult_bin][ePsi_bin][iSE_ME_Et] ->FindBin(N_Particles));
SE_ME_Et_val[iSE_ME_Et] = h2D_jet_rho_vs_mult_array_In[ez_bin][emult_bin][ePsi_bin][iSE_ME_Et] ->GetBinContent(h2D_jet_rho_vs_mult_array_In[ez_bin][emult_bin][ePsi_bin][iSE_ME_Et]->FindBin(N_Particles,jet_rho));
}
//cout << "SE_ME_Et_val[0] = " << SE_ME_Et_val[0] << ", SE_ME_Et_val[1] = " << SE_ME_Et_val[1] << endl;
if(SE_ME_Et_val[0] > 0.0 && SE_ME_Et_val[1] > 0.0)
{
Et_weight_factor = SE_ME_Et_val[0]/SE_ME_Et_val[1];
}
}
if(!(eIn_Mode == 2 || eIn_Mode == 24)) Et_weight_factor = 1.0; // only relevant for mixed event
//Et_weight_factor = 1.0;
Et_weight_factor *= reweight;
//cout << "Et_weight_factor = " << Et_weight_factor << endl;
//----------------------------------------------------------------------------------------
h_jet_rho[0][i_orig_smear] ->Fill(jet_rho);
if(i_orig_smear == 0)
{
h2D_jet_rho_vs_mult_array[ez_bin][emult_bin][ePsi_bin] ->Fill(N_Particles,jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_rho_array[ez_bin][emult_bin][ePsi_bin] ->Fill(jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_Et_array[ez_bin][emult_bin][ePsi_bin] ->Fill(Et_total,PYTHIA_hard_bin_index_weight);
h_jet_Et_array_weight[ez_bin][emult_bin][ePsi_bin] ->Fill(Et_total,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_rho_vs_Et ->Fill(Et_total,jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_per_event_array[ez_bin][emult_bin][ePsi_bin] ->Fill(jets[i_orig_smear].size(),Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_tracks_per_event_array[ez_bin][emult_bin][ePsi_bin] ->Fill(N_Particles,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
//cout << "jet_rho = " << jet_rho << ", N_Particles = " << N_Particles << ", i_orig_smear: " << i_orig_smear << endl;
// get the subtracted jets
Int_t jets_per_event[N_jet_areas];
Int_t dijets_per_event[N_jet_areas];
for(Int_t i_area = 0; i_area < N_jet_areas; i_area++)
{
jets_per_event[i_area] = 0;
dijets_per_event[i_area] = 0;
}
if(jet_rho >= 0.0)
{
//cout << "Accepted" << endl;
Int_t flag_save_to_ntuple = 0;
Int_t jets_above_threshold = 0;
for(Int_t i = 0; i < jets[i_orig_smear].size(); i++)
{
Float_t jet_pt = jets[i_orig_smear][i].perp();
Float_t jet_area = jets[i_orig_smear][i].area();
Float_t jet_pt_sub = jets[i_orig_smear][i].perp() - jet_rho*jet_area;
Float_t jet_eta = jets[i_orig_smear][i].eta();
Float_t jet_phi = jets[i_orig_smear][i].phi();
//cout << "i: " << i << ", jet_pt_sub: " << jet_pt_sub << ", jet_pt: " << jet_pt << endl;
if(jet_pt_sub > 9.0) jets_above_threshold++;
//if(jet_pt_sub > 2500.0) flag_save_to_ntuple = 1; // at least one jet candidate with high pt in event
//flag_save_to_ntuple = 1;
}
if(jets_above_threshold > 1)
{
flag_save_to_ntuple = 1;
//cout << "Jet candidate with " << jets_above_threshold << " jet(s) above threshold found in event " << counter << " -> will be stored in Ntuple" << endl;
}
flag_save_to_ntuple = 0;
//h_jet_per_event[1] ->Fill(jets[i_orig_smear].size());
//----------------------------------------------------------------------------------------
// Jet A loop
vec_jet_array[i_orig_smear].resize(jets[i_orig_smear].size());
vec_jet_const_array[i_orig_smear].resize(jets[i_orig_smear].size());
for(Int_t i = 0; i < jets[i_orig_smear].size(); i++)
{
Float_t jet_pt = jets[i_orig_smear][i].perp();
Float_t jet_area = jets[i_orig_smear][i].area();
Float_t jet_pt_sub = jets[i_orig_smear][i].perp() - jet_rho*jet_area;
Float_t jet_eta = jets[i_orig_smear][i].eta();
Float_t jet_phi = jets[i_orig_smear][i].phi();
vec_jet_array[i_orig_smear][i].push_back(jet_pt); // save the jet information in the array for later PYTHIA matching studies
vec_jet_array[i_orig_smear][i].push_back(jet_area); // save the jet information in the array for later PYTHIA matching studies
vec_jet_array[i_orig_smear][i].push_back(jet_pt_sub); // save the jet information in the array for later PYTHIA matching studies
vec_jet_array[i_orig_smear][i].push_back(jet_eta); // save the jet information in the array for later PYTHIA matching studies
vec_jet_array[i_orig_smear][i].push_back(jet_phi); // save the jet information in the array for later PYTHIA matching studies
h_area_vs_jet_pt ->Fill(jet_pt_sub,jet_area,PYTHIA_hard_bin_index_weight);
h_area ->Fill(jet_area,PYTHIA_hard_bin_index_weight);
vector<PseudoJet> jet_constituents = jets[i_orig_smear][i].constituents();
//cout << "jet " << i << ", jet_pt = " << jet_pt << ", number of constituents = " << jet_constituents.size() << endl;
Float_t leading_pt = 0.0;
Float_t sub_leading_pt = 0.0;
Float_t leading_phi = 0.0;
Float_t leading_eta = 0.0;
Int_t N_tracks_above_pT_assoc_threshold = 0;
// Determine leading and sub_leading pt values
vec_jet_const_array[i_orig_smear][i].resize(jet_constituents.size());
for(Int_t j = 0; j < jet_constituents.size(); j++)
{
Float_t jet_const_pt = jet_constituents[j].perp();
Float_t jet_const_phi = jet_constituents[j].phi();
Float_t jet_const_eta = jet_constituents[j].eta();
Int_t user_index = jet_constituents[j].user_index();
vec_jet_const_array[i_orig_smear][i][j].push_back(jet_const_pt);
vec_jet_const_array[i_orig_smear][i][j].push_back(jet_const_phi);
vec_jet_const_array[i_orig_smear][i][j].push_back(jet_const_eta);
vec_jet_const_array[i_orig_smear][i][j].push_back((Float_t)user_index);
Double_t Psi2_use = EP_eta_pos_corr;
if(jet_const_eta > 0.0) Psi2_use = EP_eta_neg_corr;
Double_t phi_use = jet_const_phi;
// -pi/2..pi/2 -> 0..pi
if(Psi2_use < 0.0) Psi2_use += TMath::Pi();
// -pi..pi -> 0..pi
if(phi_use < 0.0) phi_use = phi_use + TMath::Pi();
// -pi..pi, delta_phi_angle: 0..pi
Double_t delta_phi_angle = phi_use - Psi2_use;
if(phi_use >= 0.0 && delta_phi_angle >= 0.0) delta_phi_angle = delta_phi_angle;
if(phi_use >= 0.0 && delta_phi_angle < 0.0) delta_phi_angle += TMath::Pi();
if(phi_use < 0.0 && delta_phi_angle >= -TMath::Pi()) delta_phi_angle += TMath::Pi();
if(phi_use < 0.0 && delta_phi_angle < -TMath::Pi()) delta_phi_angle += 2.0*TMath::Pi();
Double_t v2_val = TMath::Cos(2.0*delta_phi_angle);
//--------------------------------------------------------
if(eMode == 42)
{
if(i_orig_smear == 0 && jet_const_pt > 0.15)
{
if(i == 0 && j == 0)
{
h_Psi_Full ->Fill(Psi2_use);
h_Psi_etapos ->Fill(EP_eta_pos_corr);
h_Psi_etaneg ->Fill(EP_eta_neg_corr);
}
p_v2_vs_pt_jet ->Fill(jet_const_pt,v2_val);
h_phi ->Fill(jet_const_phi);
}
// check if embedded particle is in the jet
if(user_index == Embed_user_index)
{
//cout << "Embedded particle: pt = " << jet_const_pt << ", phi = " << jet_const_phi << ", eta = " << jet_const_eta << endl;
Double_t Delta_pt = jet_pt_sub - jet_const_pt;
for(Int_t i_area = 0; i_area < N_jet_areas; i_area++)
{
if(jet_area > array_areas[i_area])
{
// Define weighting based on elliptic flow
Double_t v2_max = 0.1; // maximum v2 for 200 GeV 0-10%
if(eCentrality == 1) v2_max = 0.25;
Double_t EP_res = 0.465; // ~eta sub EP resolution for 0-10% and 60-80%
Double_t v2_high_pt = 0.04; // estimate of v2 at high pT
if(eCentrality == 1) v2_high_pt = 0.08;
Double_t v2_use = v2_max*(1.0/EP_res)*jet_const_pt/3.0; // linear increase of v2 with pT up to 3.0 GeV
if(jet_const_pt > 3.0 && jet_const_pt <= 7.0) // dropping v2 from max value to v2 at high pT value
{
Double_t slope_val = (v2_high_pt*(1.0/EP_res) - v2_max*(1.0/EP_res))/(7.0 - 3.0);
Double_t t_val = v2_max*(1.0/EP_res) - slope_val * 3.0;
v2_use = slope_val*jet_const_pt + t_val;
}
if(jet_const_pt > 7.0) // constant v2 at high pT
{
v2_use = v2_high_pt*(1.0/EP_res);
}
Double_t dNdDeltaphi = 1.0 + 2.0*0.1*TMath::Cos(2.0*jet_const_phi-2.0*Psi2_use); // weighting factor for embedded tracks with assumed v2 of 0.05 (EP resolution ~0.5 -> v2 factor here is 0.1)
//if(i_area == 0) cout << "pt: " << jet_const_pt << ", v2_use: " << v2_use << ", weight: " << dNdDeltaphi << endl;
h_Delta_pt_vs_embed_pt[i_area][i_orig_smear][ePsi_bin] ->Fill(jet_const_pt,Delta_pt,PYTHIA_hard_bin_index_weight);
h_Delta_pt_vs_embed_pt_weight[i_area][i_orig_smear][ePsi_bin] ->Fill(jet_const_pt,Delta_pt,PYTHIA_hard_bin_index_weight*dNdDeltaphi);
//cout << "i_area = " << i_area << ", epT_bin = " << epT_bin << ", i_orig_smear = " << i_orig_smear << ", ePsi_bin = " << ePsi_bin << ", Delta_pt = " << Delta_pt << endl;
}
}
}
}
//--------------------------------------------------------
//cout << "jet counter = " << i << ", track counter = " << j << ", track pt = " << jet_const_pt << endl;
Float_t qp_val = 1.0;
Int_t part_info_size = particles_info.size();
if(user_index >= 0 && user_index < part_info_size)
{
qp_val = particles_info[user_index];
if(qp_val > 0.0)
{
qp_val = 1.0;
}
else
{
qp_val = -1.0;
}
}
//cout << "user_index = " << user_index << ", qp_val = " << qp_val << ", part_info_size = " << part_info_size << endl;
if(flag_save_to_ntuple && i_orig_smear == 0)
{
// EventId:JetId:rho:area:Jetphi:Jeteta:Jetpt:TrackId:eta:phi:pt
ReCoil_Jet_NTDataArray[0] = (Float_t)counter;
ReCoil_Jet_NTDataArray[1] = (Float_t)i;
ReCoil_Jet_NTDataArray[2] = (Float_t)jet_rho;
ReCoil_Jet_NTDataArray[3] = (Float_t)jet_area;
ReCoil_Jet_NTDataArray[4] = (Float_t)jet_phi;
ReCoil_Jet_NTDataArray[5] = (Float_t)jet_eta;
ReCoil_Jet_NTDataArray[6] = (Float_t)jet_pt_sub;
ReCoil_Jet_NTDataArray[7] = (Float_t)j;
ReCoil_Jet_NTDataArray[8] = (Float_t)jet_const_eta;
ReCoil_Jet_NTDataArray[9] = (Float_t)jet_const_phi;
ReCoil_Jet_NTDataArray[10] = (Float_t)qp_val*jet_const_pt;
ReCoil_Jet_NTDataArray[11] = (Float_t)prim_vertex_x;
ReCoil_Jet_NTDataArray[12] = (Float_t)prim_vertex_y;
ReCoil_Jet_NTDataArray[13] = (Float_t)prim_vertex_z;
NT_ReCoil_Jet->Fill(ReCoil_Jet_NTDataArray);
}
if(jet_const_pt > leading_pt)
{
sub_leading_pt = leading_pt;
leading_pt = jet_const_pt;
leading_phi = jet_const_phi;
leading_eta = jet_const_eta;
}
//cout << "track " << j << ", track pt = " << jet_const_pt << ", phi = " << jet_const_phi << ", eta = " << jet_const_eta << endl;
if(jet_const_pt > track_pT_assoc_threshold)
{
N_tracks_above_pT_assoc_threshold++;
}
}
if(eMode == 32 || eMode == 312) // for eMode == 32 the high pT tracks are downscaled. Make sure all trigger pT bins are filled.
{
leading_pt *= ran_gen.Rndm()*max_pt_threshold; // Not used anymore
}
//cout << "leading_pt = " << leading_pt << ", sub_leading_pt = " << sub_leading_pt << endl;
if(sub_leading_pt > 0.0 && leading_pt > 0.0 && i_orig_smear == 0)
{
h_ratio_sub_lead_to_lead_pt_vs_lead_pt ->Fill(leading_pt,sub_leading_pt/leading_pt,PYTHIA_hard_bin_index_weight);
h_sub_lead_vs_lead_pt ->Fill(leading_pt,sub_leading_pt,PYTHIA_hard_bin_index_weight);
}
//----------------------------------------------------------------
if(eMode == 31 || eMode == 32 || eMode == 312 || eMode == 311 || eMode == 3)
{
if(i == 0)
{
#if 0
for(Int_t i_val = 0; i_val < vec_trigger_tracks.size(); i_val++) cout << "i before: " << i_val << ", eta: " << vec_trigger_tracks[i_val][0] << ", phi: " << vec_trigger_tracks[i_val][1] << ", pT: " << vec_trigger_tracks[i_val][2] << endl;
#endif
// sort the pT values
std::sort (vec_trigger_tracks.begin(), vec_trigger_tracks.end(), sortFunc);
#if 0
for(Int_t i_val = 0; i_val < vec_trigger_tracks.size(); i_val++) cout << "i after: " << i_val << ", eta: " << vec_trigger_tracks[i_val][0] << ", phi: " << vec_trigger_tracks[i_val][1] << ", pT: " << vec_trigger_tracks[i_val][2] << endl;
#endif
// loop over all defined trigger pt intervals
for(Int_t lead_pt_bin = 0; lead_pt_bin < N_leading_pt_bins; lead_pt_bin++)
{
if(lead_pt_bin >= 0)
{
h_N_tracks_dijet[lead_pt_bin][i_orig_smear] ->Fill(N_Particles,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_N_tracks_dijet[N_leading_pt_bins][i_orig_smear] ->Fill(N_Particles,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
if(global_bin >= 0 && global_bin < N_global_bin && lead_pt_bin >= 0)
{
h2D_mult_vs_global_bin[lead_pt_bin][i_orig_smear] ->Fill(global_bin,N_Particles,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h2D_mult_vs_global_bin[N_leading_pt_bins][i_orig_smear] ->Fill(global_bin,N_Particles,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
// Find first index of sorted pT vector which fits into trigger pT range
Int_t trigger_index_min = -1;
for(Int_t i_trigger = 0; i_trigger < vec_trigger_tracks.size(); i_trigger++)
{
if(vec_trigger_tracks[i_trigger][2] >= Array_leading_pt_bins[0][lead_pt_bin])
{
trigger_index_min = i_trigger;
break;
}
}
if(trigger_index_min == -1 && !(eMode == 32)) continue; // Skip event if it doesn't fit into trigger range
// Choose a random track within trigger pT range as trigger
Int_t random_trigger_index;
Int_t trigger_index_range = vec_trigger_tracks.size()-trigger_index_min;
if(eMode == 32) // for eMode == 32 the high pT tracks are downscaled. Make sure all trigger pT bins are filled.
{
random_trigger_index = ran_gen.Integer(vec_trigger_tracks.size());
trigger_index_range = 1;
trigger_index_min = 0;
}
else
{
random_trigger_index = ran_gen.Integer(trigger_index_range); // [0,trigger_index_range-1]
random_trigger_index += trigger_index_min;
}
#if 0
cout << "jetA: " << i << ", lead_pt_bin: " << lead_pt_bin << ", low val: " << Array_leading_pt_bins[0][lead_pt_bin]
<< ", trigger_index_min: " << trigger_index_min
<< ", pt val: " << vec_trigger_tracks[trigger_index_min][2]
<< ", trigger index range: " << vec_trigger_tracks.size()-trigger_index_min
<< ", random_trigger_index: " << random_trigger_index
<< endl;
#endif
if(random_trigger_index >= vec_trigger_tracks.size())
{
cout << "ERROR: random_trigger_index out of range!" << endl;
continue;
}
// Loop over ALL possible triggers in event, for i_trigger_use == 0 use the random trigger defined above
for(Int_t i_trigger_use = 0; i_trigger_use < trigger_index_range+1; i_trigger_use++)
{
if(i_trigger_use > 0 && lead_pt_bin < 4) break; // Do not fill the histograms for the low pT bins -> not needed, takes too much time
Int_t trigger_orig_smear = 0;
if(i_trigger_use > 0) // not the random trigger, loop overa ALL triggers in event
{
trigger_orig_smear = 2; // That is for all triggers, index = 0 and index 1 (i_orig_smear) is for random single trigger
random_trigger_index = trigger_index_min + i_trigger_use - 1; // loop over all good triggers
}
h_trigger_track[i_orig_smear+trigger_orig_smear] ->Fill(N_leading_pt_bins,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_trigger_track[i_orig_smear+trigger_orig_smear] ->Fill(lead_pt_bin,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_trigger_track_vs_global_bin[i_orig_smear+trigger_orig_smear]->Fill(global_bin,N_leading_pt_bins,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_trigger_track_vs_global_bin[i_orig_smear+trigger_orig_smear]->Fill(global_bin,lead_pt_bin,Et_weight_factor*PYTHIA_hard_bin_index_weight);
// Jet B loop
Int_t N_accepted_jets[N_jet_areas];
for(Int_t i_area_acc = 0; i_area_acc < N_jet_areas; i_area_acc++)
{
N_accepted_jets[i_area_acc] = 0;
}
for(Int_t iB = 0; iB < jets[i_orig_smear].size(); iB++)
{
//if(iB == i) continue; // Don't use the same jet candidate twice
Float_t jet_ptB = jets[i_orig_smear][iB].perp();
Float_t jet_areaB = jets[i_orig_smear][iB].area();
Float_t jet_pt_subB = jets[i_orig_smear][iB].perp() - jet_rho*jet_areaB;
Float_t jet_etaB = jets[i_orig_smear][iB].eta();
Float_t jet_phiB = jets[i_orig_smear][iB].phi();
Float_t jet_delta_eta = fabs(jet_etaB + vec_trigger_tracks[random_trigger_index][0]);
Float_t jet_delta_phi = fabs(jet_phiB - vec_trigger_tracks[random_trigger_index][1]);
if(jet_delta_phi > 2.0*Pi) jet_delta_phi -= 2.0*Pi;
Float_t dijet_delta_phi = jet_phiB-vec_trigger_tracks[random_trigger_index][1]; // -2*Pi..2*Pi
if(dijet_delta_phi < 0.0) dijet_delta_phi += 2.0*Pi; // 0..2*Pi
if(dijet_delta_phi > 1.5*Pi)
{
dijet_delta_phi = -0.5*Pi + (dijet_delta_phi-1.5*Pi); // -0.5*Pi..1.5*Pi
}
//cout << "leading_phi = " << leading_phi << ", jet_phiB = " << jet_phiB << ", dijet_delta_phi = " << dijet_delta_phi << endl;
//cout << "phiA = " << jet_phi << ", phiB =" << jet_phiB << ", jet_delta_phi = " << jet_delta_phi
// << ", etaA = " << jet_eta << ", etaB = " << jet_etaB << ", jet_delta_eta = " << jet_delta_eta << endl;
//--------------------------------------------------
// Di-jet histograms
if(
jet_delta_eta < jet_delta_eta_cut
)
{
for(Int_t i_area = 0; i_area < N_jet_areas; i_area++)
{
// Fill spectra
if(jet_areaB > array_areas[i_area])
{
h2D_dijet_pt_sub[i_area][N_leading_pt_bins][i_orig_smear+trigger_orig_smear] ->Fill(dijet_delta_phi,jet_pt_subB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h2D_dijet_pt[i_area][N_leading_pt_bins][i_orig_smear+trigger_orig_smear] ->Fill(dijet_delta_phi,jet_ptB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
if(lead_pt_bin != -1)
{
h2D_dijet_pt_sub[i_area][lead_pt_bin][i_orig_smear+trigger_orig_smear] ->Fill(dijet_delta_phi,jet_pt_subB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h2D_dijet_pt[i_area][lead_pt_bin][i_orig_smear+trigger_orig_smear] ->Fill(dijet_delta_phi,jet_ptB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
dijets_per_event[i_area]++;
}
}
}
//--------------------------------------------------
//--------------------------------------------------
// Recoil jet histograms
if(
jet_delta_eta < jet_delta_eta_cut
&& fabs(Pi-jet_delta_phi) < jet_delta_phi_cut
// && iB != i // Don't use the same jet candidate twice
)
{
//cout << "Et_weight_factor: " << Et_weight_factor << endl;
h_jet_area_array[ez_bin][emult_bin][ePsi_bin] ->Fill(jet_areaB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_rhoarea_array[ez_bin][emult_bin][ePsi_bin] ->Fill(jet_areaB*jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
if(i_orig_smear == 0 && trigger_orig_smear == 0)
{
//if(jet_rho > 0.001) cout << "iB: " << iB << ", rho: " << jet_rho << ", jet_areaB: " << jet_areaB << ", jet_pt_subB: " << jet_pt_subB << endl;
h_area_vs_recoil_jet_pt[N_leading_pt_bins] ->Fill(jet_pt_subB,jet_areaB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_rho[N_leading_pt_bins] ->Fill(jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
if(lead_pt_bin != -1)
{
h_area_vs_recoil_jet_pt[lead_pt_bin] ->Fill(jet_pt_subB,jet_areaB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_rho[lead_pt_bin] ->Fill(jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
}
for(Int_t i_area = 0; i_area < N_jet_areas; i_area++)
{
// Fill spectra
if(jet_areaB > array_areas[i_area])
{
//cout << "jet_ptB = " << jet_ptB << endl;
N_accepted_jets[i_area]++;
//cout << "Weight factor: " << Et_weight_factor*PYTHIA_hard_bin_index_weight << ", Et_weight_factor: " << Et_weight_factor << ", PYTHIA_hard_bin_index_weight: " << PYTHIA_hard_bin_index_weight << endl;
h_jet_pt_sub[i_area][N_leading_pt_bins][i_orig_smear+trigger_orig_smear] ->Fill(jet_pt_subB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_pt[i_area][N_leading_pt_bins][i_orig_smear+trigger_orig_smear] ->Fill(jet_ptB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
if(lead_pt_bin != -1)
{
//cout << "Fill spectra, PYTHIA_hard_bin_index_weight: " << PYTHIA_hard_bin_index_weight << endl;
h_jet_pt_sub[i_area][lead_pt_bin][i_orig_smear+trigger_orig_smear] ->Fill(jet_pt_subB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_pt[i_area][lead_pt_bin][i_orig_smear+trigger_orig_smear] ->Fill(jet_ptB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
h_jet_area[i_area][i_orig_smear+trigger_orig_smear] ->Fill(jet_areaB,Et_weight_factor*PYTHIA_hard_bin_index_weight);
//if(i_area == 4) cout << "i_orig_smear: " << i_orig_smear << ", i_area: " << i_area << ", lead_pt_bin: " << lead_pt_bin << ", jet_pt_subB: " << jet_pt_subB << ", jets_per_event: " << jets_per_event[i_area] << endl;
jets_per_event[i_area]++;
}
}
}
//--------------------------------------------------
} // end of jet B loop
if(i_trigger_use == 0)
{
for(Int_t i_area_acc = 0; i_area_acc < N_jet_areas; i_area_acc++)
{
h_N_accepted_recoil_jets[i_area_acc][lead_pt_bin] ->Fill(N_accepted_jets[i_area_acc]);
h_N_accepted_recoil_jets[i_area_acc][N_leading_pt_bins] ->Fill(N_accepted_jets[i_area_acc]);
#if 0
if(i_area_acc == 4) cout << "event: " << counter << ", i_area_acc: " << i_area_acc << ", N_recoil_jets: " << N_accepted_jets[i_area_acc]
<< ", jetA: " << i << ", lead_pt_bin: " << lead_pt_bin << ", i_orig_smear: " << i_orig_smear << endl;
#endif
}
}
} // end of trigger loop
//----------------------------------------------------------------
if(eMode == 3)
{
//cout << "leading_pt = " << leading_pt << ", lead_pt_bin = " << lead_pt_bin << endl;
h_jet_area_array[ez_bin][emult_bin][ePsi_bin] ->Fill(jet_area,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_rhoarea_array[ez_bin][emult_bin][ePsi_bin] ->Fill(jet_area*jet_rho,Et_weight_factor*PYTHIA_hard_bin_index_weight);
for(Int_t i_area = 0; i_area < N_jet_areas; i_area++)
{
if(jet_area > array_areas[i_area])
{
h_jet_pt_sub[i_area][N_leading_pt_bins][i_orig_smear] ->Fill(jet_pt_sub,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_pt[i_area][N_leading_pt_bins][i_orig_smear] ->Fill(jet_pt,Et_weight_factor*PYTHIA_hard_bin_index_weight);
if(lead_pt_bin != -1)
{
h_jet_pt_sub[i_area][lead_pt_bin][i_orig_smear] ->Fill(jet_pt_sub,Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_jet_pt[i_area][lead_pt_bin][i_orig_smear] ->Fill(jet_pt,Et_weight_factor*PYTHIA_hard_bin_index_weight);
}
h_jet_area[i_area][i_orig_smear] ->Fill(jet_area,Et_weight_factor*PYTHIA_hard_bin_index_weight);
jets_per_event[i_area]++;
}
}
}
// end eMode = 3
//----------------------------------------------------------------
} // end of trigger track loop
}
}
//----------------------------------------------------------------
}
// End jet A loop
//----------------------------------------------------------------------------------------
}
for(Int_t k = 0; k < N_jet_areas; k++)
{
h_jet_per_event[k][i_orig_smear] ->Fill(jets_per_event[k],Et_weight_factor*PYTHIA_hard_bin_index_weight);
h_dijet_per_event[k][i_orig_smear] ->Fill(dijets_per_event[k],Et_weight_factor*PYTHIA_hard_bin_index_weight);
//cout << "area: " << k << ", i_orig_smear: " << i_orig_smear << ", jet_per_event[area]: " << jets_per_event[k] << endl;
}
} // end i_orig_smear
//----------------------------------
// Calculate the jet matching/reconstrution efficiencies - only for mode 311 -> PYTHIA
if(eMode == 311 || eMode == 312)
{
//cout << "rho[0]: " << jet_rho_array[0] << ", rho[1]: " << jet_rho_array[1] << endl;
if(jet_rho_array[0] > 0.0 && jet_rho_array[1] > 0.0)
{
Int_t N_jets_PYTHIA[2] = {vec_jet_array[0].size(),vec_jet_array[1].size()};
#if 0
cout << "" << endl;
cout << "----------------------------------" << endl;
cout << "PYTHIA jets: " << N_jets_PYTHIA[0] << ", PYTHIA jets (smeared+eff): " << N_jets_PYTHIA[1] <<
", rho: " << jet_rho_array[0] << ", rho(smeared+eff): " << jet_rho_array[1] << endl;
#endif
// Loop over the original PYTHIA jets
for(Int_t i_jet = 0; i_jet < N_jets_PYTHIA[0]; i_jet++)
{
Float_t jet_pt = vec_jet_array[0][i_jet][0];
Float_t jet_area = vec_jet_array[0][i_jet][1];
Float_t jet_pt_sub = vec_jet_array[0][i_jet][2];
Float_t jet_eta = vec_jet_array[0][i_jet][3];
Float_t jet_phi = vec_jet_array[0][i_jet][4];
// Loop over the original PYTHIA jet constituent tracks
Float_t jet_sum_track_pt = 0.0;
vector<Int_t> vec_user_index;
for(Int_t j_track = 0; j_track < vec_jet_const_array[0][i_jet].size(); j_track++)
{
Float_t jet_const_pt = vec_jet_const_array[0][i_jet][j_track][0];
if(jet_const_pt < 0.15) continue; // remove ghost tracks
jet_sum_track_pt += jet_const_pt; // jet pt based only on the tracks which are later on matched
Float_t jet_const_phi = vec_jet_const_array[0][i_jet][j_track][1];
Float_t jet_const_eta = vec_jet_const_array[0][i_jet][j_track][2];
Int_t user_index = (Int_t)vec_jet_const_array[0][i_jet][j_track][3];
vec_user_index.push_back(user_index);
}
#if 0
cout << "PYTHIA jet: " << i_jet << ", jet_pT: " << jet_pt << ", tracks: " << vec_user_index.size() << endl;
#endif
// Loop over the smeared+eff PYTHIA jets
vector<Int_t> vec_index_counter; // stores the number of matched tracks for every smeared+eff PYTHIA jet
//std::vector< std::vector<Double_t> > vec_match_jet_info;
//vec_match_jet_info.resize(N_jets_PYTHIA[1]);
Double_t best_fraction_of_matched_tracks = 0.0; // keeps always the best fraction of matched tracks
Double_t best_jet_pt_smeared = 0.0; // keeps always the highest matched jet pT
Double_t best_jet_area_smeared = 0.0;
Double_t best_jet_pt_sub_smeared = 0.0;
for(Int_t i_jet_smeared = 0; i_jet_smeared < N_jets_PYTHIA[1]; i_jet_smeared++)
{
Float_t jet_pt_smeared = vec_jet_array[1][i_jet_smeared][0];
Float_t jet_area_smeared = vec_jet_array[1][i_jet_smeared][1];
Float_t jet_pt_sub_smeared = vec_jet_array[1][i_jet_smeared][2];
Float_t jet_eta_smeared = vec_jet_array[1][i_jet_smeared][3];
Float_t jet_phi_smeared = vec_jet_array[1][i_jet_smeared][4];
#if 0
cout << "i_jet_smeared: " << i_jet_smeared << ", rho: " << jet_rho_array[1] << ", area: " << jet_area_smeared
<< ", rho*area: " << jet_rho_array[1]*jet_area_smeared << ", jet_pt_smeared: " << jet_pt_smeared << ", jet_pt_sub_smeared: " << jet_pt_sub_smeared << endl;
#endif
// Loop over the smeared+eff PYTHIA jet constituent tracks
Int_t Index_counter = 0; // counts for this particular original PYTHIA jet - smeared+eff PYTHIA jet combination how many tracks are matched
Float_t jet_sum_track_pt_smeared = 0.0;
for(Int_t j_track_smeared = 0; j_track_smeared < vec_jet_const_array[1][i_jet_smeared].size(); j_track_smeared++)
{
Float_t jet_const_pt_smeared = vec_jet_const_array[1][i_jet_smeared][j_track_smeared][0];
if(jet_const_pt_smeared < 0.15) continue; // remove ghost tracks
Float_t jet_const_phi_smeared = vec_jet_const_array[1][i_jet_smeared][j_track_smeared][1];
Float_t jet_const_eta_smeared = vec_jet_const_array[1][i_jet_smeared][j_track_smeared][2];
Int_t user_index_smeared = (Int_t)vec_jet_const_array[1][i_jet_smeared][j_track_smeared][3];
// check if that user_index is in original PYTHIA jet
for(Int_t i_index = 0; i_index < vec_user_index.size(); i_index++)
{
if(user_index_smeared == vec_user_index[i_index]) // same track was found
{
Index_counter++;
jet_sum_track_pt_smeared += jet_const_pt_smeared; // use only matched tracks for the matched pt comparison
//cout << "user_index_smeared: " << user_index_smeared << endl;
}
}
}
vec_index_counter.push_back(Index_counter);
Double_t fraction_of_matched_tracks = 0.0;
if(vec_user_index.size() > 0)
{
fraction_of_matched_tracks = ((Double_t)Index_counter)/((Double_t)vec_user_index.size());
#if 0
cout << "PYTHIA jet (smeared+eff): " << i_jet_smeared << ", fraction of matched tracks: " << fraction_of_matched_tracks
<< ", matched tracks: " << Index_counter << ", tracks in original jet: " << vec_user_index.size() << ", pt-rho*A (smeared+eff): " << jet_pt_sub_smeared <<
", original jet pT: " << jet_sum_track_pt << ", matched tracks jet pT: " << jet_sum_track_pt_smeared << endl;
#endif
}
// Find the reconstructed jet with most matched tracks and highest matched energy
if(
fraction_of_matched_tracks >= best_fraction_of_matched_tracks
&& jet_sum_track_pt_smeared >= best_jet_pt_smeared
)
{
best_fraction_of_matched_tracks = fraction_of_matched_tracks;
best_jet_pt_smeared = jet_sum_track_pt_smeared;
best_jet_area_smeared = jet_area_smeared;
best_jet_pt_sub_smeared = jet_pt_sub_smeared;
}
//vec_match_jet_info[i_jet_smeared].push_back(jet_pt_sub,jet_pt_sub_smeared,fraction_of_matched_tracks);
}
Double_t Delta_pt = best_jet_pt_sub_smeared - jet_pt; // reconstructed jet pT - embedded jet pT
for(Int_t i_area = 0; i_area < N_jet_areas; i_area++)
{
if(best_jet_area_smeared > array_areas[i_area])
{
// Fill histogram for matched pT
h2D_Sim_matched_pT_vs_original_pT[i_area] ->Fill(jet_sum_track_pt,best_jet_pt_smeared);
h2D_Sim_original_pT_vs_matched_pT[i_area] ->Fill(best_jet_pt_smeared,jet_sum_track_pt);
h_matched_tracks_fraction[i_area] ->Fill(best_fraction_of_matched_tracks);
h2D_matched_tracks_fraction_vs_original_pT[i_area] ->Fill(jet_sum_track_pt,best_fraction_of_matched_tracks);
if(eMode == 312)
{
h_Delta_pt_vs_embed_pt[i_area][0][ePsi_bin] ->Fill(jet_pt,Delta_pt,PYTHIA_hard_bin_index_weight);
#if 0
if(i_area == 0) cout << "jet_pt (embed): " << jet_pt << ", rec jet_pt (matched): " << best_jet_pt_smeared << ", Delta_pt: " << Delta_pt << ", best_jet_pt_sub_smeared: "
<< best_jet_pt_sub_smeared << endl;
#endif
}
}
}
#if 0
cout << "i_jet: " << i_jet << ", N_tracks: " << vec_user_index.size() << ", best fraction of matched track: "
<< best_fraction_of_matched_tracks << ", matched pT: " << best_jet_pt_smeared << ", out of: " << jet_sum_track_pt << endl;
#endif
}
#if 0
cout << "----------------------------------" << endl;
cout << "" << endl;
#endif
}
}
// End of PYTHIA jet reconstruction efficiency calculation
//----------------------------------
}
//-----------------------------------------------------------------------------
}
}
}
}
if(eMode == 2) // eMode 2 is mixed event
{
cout << "Mixed event mode started" << endl;
Int_t vertex_pos_counter = 0;
Int_t i_SE_ME = 0;
Long64_t stop_event_use_loop = stop_event_use;
if(stop_event_use_loop > file_entries_SE_ME[i_SE_ME]) stop_event_use_loop = file_entries_SE_ME[i_SE_ME];
Int_t ME_event_counter = 0;
Two_dim_Int_vector ME_track_number_vector; // stores the track ids for every event which is mixed
ME_track_number_vector.resize(N_max_events);
for(Long64_t counter = start_event_use; counter < stop_event_use_loop; counter++)
{
if (counter != 0 && counter % 100 == 0)
cout << "." << flush;
if (counter != 0 && counter % 1000 == 0)
{
if((stop_event_use_loop-start_event_use) > 0)
{
Double_t event_percent = 100.0*((Double_t)(counter-start_event_use))/((Double_t)(stop_event_use_loop-start_event_use));
cout << " " << counter << " (" << event_percent << "%) " << "\n" << "==> Processing data " << flush;
}
}
if (!input_SE_ME[i_SE_ME]->GetEntry( counter )) // take the event -> information is stored in event
break; // end of data chunk
//-----------------------------------------------------------------------------
// Event information
Float_t prim_vertex_x = JetTrackEvent->getx();
Float_t prim_vertex_y = JetTrackEvent->gety();
Float_t prim_vertex_z = JetTrackEvent->getz();
Int_t RunId = JetTrackEvent->getid();
Float_t refMult = JetTrackEvent->getmult();
Float_t n_prim = JetTrackEvent->getn_prim();
Float_t n_non_prim = JetTrackEvent->getn_non_prim();
Int_t n_tofmatch_prim = JetTrackEvent->getn_tof_prim();
Int_t SE_ME_flag = JetTrackEvent->getSE_ME_flag();
Float_t ZDCx = JetTrackEvent->getZDCx();
Float_t BBCx = JetTrackEvent->getBBCx();
Float_t vzVPD = JetTrackEvent->getvzVpd();
Int_t N_Particles = JetTrackEvent->getNumParticle();
TVector2 QvecEtaPos = JetTrackEvent->getQvecEtaPos();
TVector2 QvecEtaNeg = JetTrackEvent->getQvecEtaNeg();
Int_t cent9 = JetTrackEvent->getcent9();
ME_track_number_vector[ME_event_counter].resize(N_Particles);
for(Int_t i_track = 0; i_track < N_Particles; i_track++)
{
ME_track_number_vector[ME_event_counter][i_track] = i_track;
}
if(fabs(prim_vertex_z) > z_acceptance[eBeamTimeNum]) continue;
Double_t reweight = 1.0;
if(eMode != 311) // not PYTHIA
{
refmultCorrUtil->init(RunId);
refmultCorrUtil->initEvent(refMult, prim_vertex_z, ZDCx);
// Get centrality bins
// see StRefMultCorr.h for the definition of centrality bins
//erefMult_bin16 = refmultCorrUtil->getCentralityBin16();
//erefMult_bin = refmultCorrUtil->getCentralityBin9();
reweight = refmultCorrUtil->getWeight();
}
//cout << "ME_event_counter = " << ME_event_counter << ", array size = " << ME_track_number_vector[ME_event_counter].size() << endl;
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Good/Bad run selection
Int_t flag_good_run = 1;
for(Int_t bad_run = 0; bad_run < n_bad_run_numbers[eBeamTimeNum]; bad_run++)
{
if(bad_run_numbers[bad_run] == (Int_t)RunId)
{
flag_good_run = 0;
break;
}
}
if(flag_good_run == 0) continue;
//---------------------------------------------------------------------------
// Fill event information for jet
JetTrackEvent_ME[ME_event_counter]->clearParticleList();
JetTrackEvent_ME[ME_event_counter]->setx(prim_vertex_x);
JetTrackEvent_ME[ME_event_counter]->sety(prim_vertex_y);
JetTrackEvent_ME[ME_event_counter]->setz(prim_vertex_z);
JetTrackEvent_ME[ME_event_counter]->setid(RunId);
JetTrackEvent_ME[ME_event_counter]->setmult(refMult);
JetTrackEvent_ME[ME_event_counter]->setn_prim(n_prim);
JetTrackEvent_ME[ME_event_counter]->setn_non_prim(n_non_prim);
JetTrackEvent_ME[ME_event_counter]->setn_tof_prim(n_tofmatch_prim);
JetTrackEvent_ME[ME_event_counter]->setSE_ME_flag(SE_ME_flag);
JetTrackEvent_ME[ME_event_counter]->setZDCx(ZDCx);
JetTrackEvent_ME[ME_event_counter]->setBBCx(BBCx);
JetTrackEvent_ME[ME_event_counter]->setvzVpd(vzVPD);
JetTrackEvent_ME[ME_event_counter]->setQvecEtaPos(QvecEtaPos);
JetTrackEvent_ME[ME_event_counter]->setQvecEtaNeg(QvecEtaNeg);
JetTrackEvent_ME[ME_event_counter]->setcent9(cent9);
Double_t Psi2 = 0.0;
for(Int_t i_track = 0; i_track < N_Particles; i_track++)
{
// Particle information
JetTrackParticle = JetTrackEvent->getParticle(i_track);
Float_t dca = JetTrackParticle->get_dca_to_prim();
Float_t m2 = JetTrackParticle->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
JetTrackParticle_ME = JetTrackEvent_ME[ME_event_counter]->createParticle();
JetTrackParticle_ME ->set_dca_to_prim(dca);
JetTrackParticle_ME ->set_Particle_m2(m2);
JetTrackParticle_ME ->set_Particle_nSigmaPi(nSPi);
JetTrackParticle_ME ->set_Particle_nSigmaK(nSK);
JetTrackParticle_ME ->set_Particle_nSigmaP(nSP);
JetTrackParticle_ME ->set_Particle_qp(qp);
JetTrackParticle_ME ->set_TLV_Particle_prim(TLV_Particle_prim);
JetTrackParticle_ME ->set_TLV_Particle_glob(TLV_Particle_glob);
JetTrackParticle_ME ->set_Particle_hits_fit(nhitsfit);
}
//cout << "ME_event_counter (A) = " << ME_event_counter << ", N_Particles = " << N_Particles << endl;
ME_event_counter++;
if(ME_event_counter == N_max_events) // event buffer is full, start to create mixed events
{
for(Int_t mix_loop = 0; mix_loop < N_max_events; mix_loop++)
{
if (mix_loop != 0 && mix_loop % 10 == 0)
cout << "-" << flush;
// Sample track number and z-vertex value
Double_t N_tracks_sample_d, N_z_vertex_sample, N_Psi_sample;
h_tracks_vs_z_vertex_array[ez_bin][emult_bin] ->GetRandom2(N_z_vertex_sample,N_tracks_sample_d);
h_Psi_vs_z_vertex_array[ez_bin][ePsi_bin] ->GetRandom2(N_z_vertex_sample,N_Psi_sample);
//h_tracks_vs_z_vertex_sample->GetRandom2(N_z_vertex_sample,N_tracks_sample_d);
Int_t N_tracks_sample = (Int_t)N_tracks_sample_d;
//cout << "global event = " << counter << ", mix_loop = " << mix_loop << ", N_z_vertex_sample = " << N_z_vertex_sample << ", N_tracks_sample = " << N_tracks_sample << endl;
if(N_tracks_sample > N_max_events)
{
cout << "Error: N_tracks_sample > N_max_events" << endl;
break;
}
Int_t z_bin = -1;
if(N_z_vertex_sample > vertex_z_start_stop_delta[eBeamTimeNum][0] && N_z_vertex_sample < vertex_z_start_stop_delta[eBeamTimeNum][1])
{
z_bin = (Int_t)((N_z_vertex_sample-vertex_z_start_stop_delta[eBeamTimeNum][0])/vertex_z_start_stop_delta[eBeamTimeNum][2]);
}
Int_t mult_bin = -1;
if(N_tracks_sample_d > mult_start_stop_delta[eBeamTimeNum][0] && N_tracks_sample_d < mult_start_stop_delta[eBeamTimeNum][1])
{
mult_bin = (Int_t)((N_tracks_sample_d-mult_start_stop_delta[eBeamTimeNum][0])/mult_start_stop_delta[eBeamTimeNum][2]);
}
Int_t Psi_bin = -1;
if(Psi2 > Psi_start_stop_delta[eBeamTimeNum][0] && N_Psi_sample < Psi_start_stop_delta[eBeamTimeNum][1])
{
Psi_bin = (Int_t)((N_Psi_sample-Psi_start_stop_delta[eBeamTimeNum][0])/Psi_start_stop_delta[eBeamTimeNum][2]);
}
//cout << "z_bin = " << z_bin << ", mult_bin = " << mult_bin << ", Psi_bin = " << Psi_bin << ", N_tracks_sample_d = " << N_tracks_sample_d << endl;
//if(z_bin == ez_bin && mult_bin == emult_bin && Psi_bin == ePsi_bin)
{
F_mixed_event[ez_bin][emult_bin][ePsi_bin] ->cd();
Int_t Fill_flag = 1; // if all events in the loop have some entries left over then fill the event later
Double_t Et_total = 0.0;
for(Int_t ME_loop_counter = 0; ME_loop_counter < N_tracks_sample; ME_loop_counter++)
{
//input_SE_ME[i_SE_ME]->GetEntry( counter - N_max_events + ME_loop_counter + 1 );
//JetTrackEvent_ME = *JetTrackEvent;
//-----------------------------------------------------------------------------
// Event information
Float_t prim_vertex_x = JetTrackEvent_ME[ME_loop_counter]->getx();
Float_t prim_vertex_y = JetTrackEvent_ME[ME_loop_counter]->gety();
Float_t prim_vertex_z = JetTrackEvent_ME[ME_loop_counter]->getz();
Int_t RunId = JetTrackEvent_ME[ME_loop_counter]->getid();
Float_t refMult = JetTrackEvent_ME[ME_loop_counter]->getmult();
Float_t n_prim = JetTrackEvent_ME[ME_loop_counter]->getn_prim();
Float_t n_non_prim = JetTrackEvent_ME[ME_loop_counter]->getn_non_prim();
Int_t n_tofmatch_prim = JetTrackEvent_ME[ME_loop_counter]->getn_tof_prim();
Int_t SE_ME_flag = JetTrackEvent_ME[ME_loop_counter]->getSE_ME_flag();
Float_t ZDCx = JetTrackEvent_ME[ME_loop_counter]->getZDCx();
Float_t BBCx = JetTrackEvent_ME[ME_loop_counter]->getBBCx();
Float_t vzVPD = JetTrackEvent_ME[ME_loop_counter]->getvzVpd();
Int_t N_Particles = JetTrackEvent_ME[ME_loop_counter]->getNumParticle();
TVector2 QvecEtaPos = JetTrackEvent_ME[ME_loop_counter]->getQvecEtaPos();
TVector2 QvecEtaNeg = JetTrackEvent_ME[ME_loop_counter]->getQvecEtaNeg();
Int_t cent9 = JetTrackEvent_ME[ME_loop_counter]->getcent9();
if((N_Particles-mix_loop) < 0) // at least one event in the loop is out of tracks, stop and don't fill the tree
{
Fill_flag = 0;
break;
}
if(ME_loop_counter == 0)
{
// Fill event information for jet
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].clearParticleList();
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setx(prim_vertex_x);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].sety(prim_vertex_y);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setz(prim_vertex_z);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setid(RunId);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setmult(refMult);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setn_prim(n_prim);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setn_non_prim(n_non_prim);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setn_tof_prim(n_tofmatch_prim);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setSE_ME_flag(SE_ME_flag);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setZDCx(ZDCx);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setBBCx(BBCx);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setvzVpd(vzVPD);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setQvecEtaPos(QvecEtaPos);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setQvecEtaNeg(QvecEtaNeg);
JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].setcent9(cent9);
h_tracks_vs_z_vertex[ez_bin][emult_bin][ePsi_bin] ->Fill(N_z_vertex_sample,N_tracks_sample_d);
h_Psi2[ez_bin][emult_bin][ePsi_bin] ->Fill(Psi2);
}
//-----------------------------------------------------------------------------
// select random track from this event
//cout << "ME_loop_counter = " << ME_loop_counter << ", N_Particles = " << N_Particles << ", mix_loop = " << mix_loop << endl;
Int_t track_num_random = (Int_t)ran.Integer(N_Particles-mix_loop);
//if(ME_loop_counter == 0) cout << "track_num_random = " << track_num_random << ", array size = " << ME_track_number_vector[ME_loop_counter].size() << endl;
Int_t track_id_num_random = ME_track_number_vector[ME_loop_counter][track_num_random];
ME_track_number_vector[ME_loop_counter][track_num_random] = ME_track_number_vector[ME_loop_counter][N_Particles-mix_loop-1];
//cout << "Test C, N_Particles = " << N_Particles << ", track_id_num_random = " << track_id_num_random << endl;
//JetTrackEvent_ME.resize(N_max_events);
//mult_start_stop_delta[eBeamTimeNum][1]
//file_entries_SE_ME[0]
// Particle information
JetTrackParticle_ME = JetTrackEvent_ME[ME_loop_counter]->getParticle(track_id_num_random);
Float_t dca = JetTrackParticle_ME->get_dca_to_prim();
Float_t m2 = JetTrackParticle_ME->get_Particle_m2 ();
Float_t nSPi = JetTrackParticle_ME->get_Particle_nSigmaPi();
Float_t nSK = JetTrackParticle_ME->get_Particle_nSigmaK();
Float_t nSP = JetTrackParticle_ME->get_Particle_nSigmaP();
Float_t qp = JetTrackParticle_ME->get_Particle_qp();
Float_t nhitsfit = JetTrackParticle_ME->get_Particle_hits_fit();
TLorentzVector TLV_Particle_prim = JetTrackParticle_ME->get_TLV_Particle_prim();
TLorentzVector TLV_Particle_glob = JetTrackParticle_ME->get_TLV_Particle_glob();
TLorentzVector TLV_Particle_use = TLV_Particle_prim;
if(eflab_prim_glob == 1) TLV_Particle_use = TLV_Particle_glob;
Et_total += TLV_Particle_use.Et();
JetTrackParticle_Fill = JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin].createParticle();
JetTrackParticle_Fill ->set_dca_to_prim(dca);
JetTrackParticle_Fill ->set_Particle_m2(m2);
JetTrackParticle_Fill ->set_Particle_nSigmaPi(nSPi);
JetTrackParticle_Fill ->set_Particle_nSigmaK(nSK);
JetTrackParticle_Fill ->set_Particle_nSigmaP(nSP);
JetTrackParticle_Fill ->set_Particle_qp(qp);
JetTrackParticle_Fill ->set_TLV_Particle_prim(TLV_Particle_prim);
JetTrackParticle_Fill ->set_TLV_Particle_glob(TLV_Particle_glob);
JetTrackParticle_Fill ->set_Particle_hits_fit(nhitsfit);
Double_t track_pT = TLV_Particle_use.Pt();
if(track_pT != track_pT) continue; // that is a NaN test. It always fails if track_pT = nan.
Float_t Phi = TLV_Particle_use.Phi();
Float_t Eta = TLV_Particle_use.PseudoRapidity();
h_Phi_vs_eta[ez_bin][emult_bin][ePsi_bin] ->Fill(Eta,Phi);
if(0)
{
cout << "mix_loop = " << mix_loop << ", ME_loop_counter = " << ME_loop_counter << ", track_id_num_random = " << track_id_num_random
<< ", track_num_random = " << track_num_random << ", Phi = " << Phi << ", Eta = " << Eta << ", refMult = " << refMult << endl;
}
}
h_Et[ez_bin][emult_bin][ePsi_bin] ->Fill(Et_total);
if(Fill_flag == 1)
{
Tree_JetTrackEvent_Fill[ez_bin][emult_bin][ePsi_bin] ->Fill();
}
}
}
ME_event_counter = 0;
}
}
}
return 1;
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
Int_t StJetAnalysis::Finish()
{
cout << "Finish started" << endl;
if(eMode == 0)
{
Outputfile->cd();
p_parameters ->Write();
p_jet_area_values ->Write();
//h_tracks_vs_z_vertex ->Write();
//h_Psi2 ->Write();
if(eMode == 0 || eMode == 1)
{
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
//h_Phi_vs_eta[i_z] ->Write();
h_Phi_vs_eta_random_phi[i_z] ->Write();
}
}
Outputfile->Close();
}
if(eMode == 42)
{
p_parameters ->Write();
p_jet_area_values ->Write();
p_v2_vs_pt_jet ->Write();
p_v2_vs_pt ->Write();
h_Psi_Full ->Write();
h_Psi_etapos ->Write();
h_Psi_etaneg ->Write();
h_phi ->Write();
Outputfile->cd();
Outputfile->mkdir("Delta_pt");
Outputfile->cd("Delta_pt");
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
for(Int_t i_Psi = ePsi_bin; i_Psi < ePsi_bin+1; i_Psi++)
{
h_Delta_pt_vs_embed_pt[i][i_orig_smear][i_Psi] ->Write();
h_Delta_pt_vs_embed_pt_weight[i][i_orig_smear][i_Psi] ->Write();
}
}
}
Outputfile->cd();
Outputfile->Close();
}
if(eMode == 3 || eMode == 31 || eMode == 32 || eMode == 312 || eMode == 311)
{
Outputfile->cd();
for(Int_t i_charge = 0; i_charge < 2; i_charge++)
{
HistName = "p_pt_Ach_";
HistName += i_charge;
p_pt_Ach[i_charge] -> Write();
}
h_Ach -> Write();
if(eMode == 312)
{
h_PYTHIA_hard_bin_weigh_factors ->Write();
h_PYTHIA_hard_bin_high_pT_N_events ->Write();
Outputfile->cd();
Outputfile->mkdir("Delta_pt");
Outputfile->cd("Delta_pt");
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
for(Int_t i_Psi = ePsi_bin; i_Psi < ePsi_bin+1; i_Psi++)
{
h_Delta_pt_vs_embed_pt[i][i_orig_smear][i_Psi] ->Write();
}
}
}
Outputfile->cd();
}
NT_ReCoil_Jet ->Write();
h_area_vs_jet_pt ->Write();
h_area ->Write();
h_track_pT ->Write();
h_track_pT_cut ->Write();
h_tracks_above_threshold_per_event ->Write();
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
h2D_tracks_above_threshold[i_hist] ->Write();
}
//c_3D ->Write();
p_parameters ->Write();
p_jet_area_values ->Write();
h_ratio_sub_lead_to_lead_pt_vs_lead_pt ->Write();
h_sub_lead_vs_lead_pt ->Write();
h_jet_rho_vs_Et ->Write();
if(eMode == 311 || eMode == 312)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
h2D_Sim_matched_pT_vs_original_pT[i] ->Write();
h2D_Sim_original_pT_vs_matched_pT[i] ->Write();
h_matched_tracks_fraction[i] ->Write();
h2D_matched_tracks_fraction_vs_original_pT[i] ->Write();
}
}
for(Int_t i = 0; i < 2; i++)
{
p_Array_leading_pt_bins[i] ->Write();
}
for(Int_t i_orig_smear = 0; i_orig_smear < 4; i_orig_smear++)
{
h_trigger_track[i_orig_smear] ->Write();
h_trigger_track_vs_global_bin[i_orig_smear] ->Write();
}
Outputfile->cd();
Outputfile->mkdir("Jet_vs_area");
Outputfile->cd("Jet_vs_area");
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
h_area_vs_recoil_jet_pt[ipt_lead] ->Write();
h_rho[ipt_lead] ->Write();
}
Outputfile->cd();
Outputfile->mkdir("Track_distributions");
Outputfile->cd("Track_distributions");
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
h_N_tracks_dijet[ipt_lead][i_orig_smear] ->Write();
h2D_mult_vs_global_bin[ipt_lead][i_orig_smear] ->Write();
}
}
Outputfile->cd();
Outputfile->mkdir("Jet_QA");
Outputfile->cd("Jet_QA");
for(Int_t i_orig_smear = 0; i_orig_smear < N_orig_smear; i_orig_smear++)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
h_jet_area[i][i_orig_smear] ->Write();
h_jet_rho[i][i_orig_smear] ->Write();
h_jet_per_event[i][i_orig_smear] ->Write();
h_dijet_per_event[i][i_orig_smear] ->Write();
}
}
Outputfile->cd();
Outputfile->mkdir("Jet_spectra");
Outputfile->cd("Jet_spectra");
for(Int_t i_orig_smear = 0; i_orig_smear < 4; i_orig_smear++)
{
for(Int_t i = 0; i < N_jet_areas; i++)
{
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
h_jet_pt[i][ipt_lead][i_orig_smear] ->Write();
h_jet_pt_sub[i][ipt_lead][i_orig_smear] ->Write();
h2D_dijet_pt[i][ipt_lead][i_orig_smear] ->Write();
h2D_dijet_pt_sub[i][ipt_lead][i_orig_smear] ->Write();
}
}
}
Outputfile->cd();
Outputfile->mkdir("QA_hist_arrays");
Outputfile->cd("QA_hist_arrays");
for(Int_t i_z = ez_bin; i_z < ez_bin+1; i_z++)
{
for(Int_t i_mult = emult_bin; i_mult < emult_bin+1; i_mult++)
{
for(Int_t i_Psi = ePsi_bin; i_Psi < ePsi_bin+1; i_Psi++)
{
//h_jet_area_array[i_z][i_mult][i_Psi] ->Write();
//h_jet_rhoarea_array[i_z][i_mult][i_Psi] ->Write();
//h_jet_rho_array[i_z][i_mult][i_Psi] ->Write();
//h_jet_Et_array[i_z][i_mult][i_Psi] ->Write();
//h_jet_Et_array_weight[i_z][i_mult][i_Psi] ->Write();
h_jet_per_event_array[i_z][i_mult][i_Psi] ->Write();
//h_tracks_per_event_array[i_z][i_mult][i_Psi] ->Write();
h2D_jet_rho_vs_mult_array[i_z][i_mult][i_Psi] ->Write();
}
}
}
Outputfile->cd();
Outputfile->mkdir("Acc_Recoil");
Outputfile->cd("Acc_Recoil");
for(Int_t i_area_acc = 0; i_area_acc < N_jet_areas; i_area_acc++)
{
for(Int_t ipt_lead = 0; ipt_lead < (N_leading_pt_bins+1); ipt_lead++)
{
h_N_accepted_recoil_jets[i_area_acc][ipt_lead] ->Write();
}
}
Outputfile->cd();
Outputfile->Close();
}
if(eMode == 1 || eMode == 2 || eMode == 4)
{
/*
cout << "destruct StJetTrackEvent" << endl;
for(Int_t mix_loop = 0; mix_loop < N_max_events; mix_loop++)
{
JetTrackEvent_ME[mix_loop].~StJetTrackEvent();
}
cout << "destruct vector" << endl;
JetTrackEvent_ME.~vector();
cout << "done" << endl;
*/
Int_t start_z = 0;
Int_t start_mult = 0;
Int_t start_Psi = 0;
//Int_t start_Psi = ePsi_bin;
Int_t stop_z = N_z_vertex_bins;
Int_t stop_mult = N_mult_bins;
Int_t stop_Psi = N_Psi_bins;
//Int_t stop_Psi = ePsi_bin+1;
if(eMode == 2
|| eMode == 1
)
{
start_z = ez_bin;
start_mult = emult_bin;
start_Psi = ePsi_bin;
stop_z = ez_bin+1;
stop_mult = emult_bin+1;
stop_Psi = ePsi_bin+1;
}
for(Int_t i_z = start_z; i_z < stop_z; i_z++)
{
for(Int_t i_mult = start_mult; i_mult < stop_mult; i_mult++)
{
for(Int_t i_Psi = start_Psi; i_Psi < stop_Psi; i_Psi++)
{
F_mixed_event[i_z][i_mult][i_Psi] ->cd();
p_parameters ->Write();
p_jet_area_values ->Write();
h_PsiA_vs_PsiB ->Write();
h_PsiA ->Write();
h_PsiB ->Write();
h_Psi_Full ->Write();
h_tracks_vs_z_vertex[i_z][i_mult][i_Psi] ->Write();
h_Psi2[i_z][i_mult][i_Psi] ->Write();
h_Et[i_z][i_mult][i_Psi] ->Write();
h_Momentum[i_z][i_mult][i_Psi] ->Write();
h_Phi_vs_eta[i_z][i_mult][i_Psi] ->Write();
Tree_JetTrackEvent_Fill[i_z][i_mult][i_Psi] ->Write("",TObject::kOverwrite);
if(eMode == 2) Inputfile ->Close();
F_mixed_event[i_z][i_mult][i_Psi] ->Close();
}
}
}
}
if(eMode == 11)
{
cout << "Save data to output file" << endl;
Outputfile->cd();
p_parameters ->Write();
p_jet_area_values ->Write();
h_tracks_above_threshold_per_event ->Write();
for(Int_t i_hist = 0; i_hist < N2D_tracks_above_threshold; i_hist++)
{
h2D_tracks_above_threshold[i_hist] ->Write();
}
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_mult = 0; i_mult < N_mult_bins; i_mult++)
{
h_tracks_vs_z_vertex_array[i_z][i_mult] ->Write();
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
for(Int_t i_pT = 0; i_pT < N_track_pt_bins_eta_phi; i_pT++)
{
h2D_track_eta_vs_phi[i_z][i_mult][i_Psi][i_pT] ->Write();
}
}
}
}
for(Int_t i_z = 0; i_z < N_z_vertex_bins; i_z++)
{
for(Int_t i_Psi = 0; i_Psi < N_Psi_bins; i_Psi++)
{
h_Psi_vs_z_vertex_array[i_z][i_Psi] ->Write();
}
}
Outputfile->Close();
}
return 1;
}
//------------------------------------------------------------------------------------------------------------------
| [
"bsmckinzie@lbl.gov"
] | bsmckinzie@lbl.gov |
7d2ef87c0c429bb3b2277e75ebf23e0c336b3210 | 4c0fcff6cbe0e4492c2df04743935037eb913566 | /osgEarth/MaskLayer | 3235a73029870e77ecc656f5a18ef2b7be2a7366 | [] | no_license | yzfx303/vxworks_osgEarth | b008856f0ea89baddc8137ec870269c76f797abc | 7edbcec888b583ac6697ec4a63d96177fc22ed22 | refs/heads/master | 2021-06-06T08:25:06.223717 | 2016-09-19T10:36:33 | 2016-09-19T10:36:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,784 | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2010 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#ifndef OSGEARTH_MASK_LAYER_H
#define OSGEARTH_MASK_LAYER_H 1
#include <osgEarth/Common>
#include <osgEarth/Layer>
#include <osgEarth/Config>
#include <osgEarth/MaskSource>
#include <osg/Node>
namespace osgEarth
{
class Map;
/**
* Configuration options for a MaskLayer.
*/
class OSGEARTH_EXPORT MaskLayerOptions : public ConfigOptions
{
public:
MaskLayerOptions( const ConfigOptions& options =ConfigOptions() );
MaskLayerOptions( const std::string& name, const MaskSourceOptions& driverOptions =MaskSourceOptions() );
/**
* The readable name of the layer.
*/
optional<std::string>& name() { return _name; }
const optional<std::string>& name() const { return _name; }
/**
* Options for the underlying model source driver.
*/
optional<MaskSourceOptions>& driver() { return _driver; }
const optional<MaskSourceOptions>& driver() const { return _driver; }
public:
virtual Config getConfig() const;
virtual void mergeConfig( const Config& conf );
private:
void fromConfig( const Config& conf );
void setDefaults();
optional<std::string> _name;
optional<MaskSourceOptions> _driver;
};
/**
* A MaskLayer is a specialized layer used to mask out a part of the terrain.
* Typically you would use this if you had a pre-built 3D terrain model for an inset area.
*/
class OSGEARTH_EXPORT MaskLayer : public Layer
{
public:
/**
* Constructs a new mask layer based on a configuration setup.
*/
MaskLayer( const MaskLayerOptions& options =MaskLayerOptions() );
/**
* Constructs a new mask layer with a user-provided driver options.
*/
MaskLayer( const std::string& name, const MaskSourceOptions& options );
/**
* Constructs a new mask layer with a user-provided mask source.
*/
MaskLayer(const MaskLayerOptions& options, MaskSource* source );
/**
* Access the underlying mask source.
*/
MaskSource* getMaskSource() const { return _maskSource.get(); }
public:
/**
* Gets the geometric boundary polygon representing the area of the
* terrain to mask out.
*/
osg::Vec3dArray* getOrCreateBoundary( float heightScale = 1.0, const SpatialReference* srs = NULL, ProgressCallback* progress =0L );
public:
void initialize( const std::string& referenceURI, const Map* map );
private:
std::string _referenceURI;
MaskLayerOptions _initOptions, _runtimeOptions;
osg::ref_ptr<MaskSource> _maskSource;
Revision _maskSourceRev;
osg::ref_ptr<osg::Vec3dArray> _boundary;
void copyOptions();
};
typedef std::vector< osg::ref_ptr<MaskLayer> > MaskLayerVector;
}
#endif // OSGEARTH_MASK_LAYER_H
| [
"geobeans@gmail.com"
] | geobeans@gmail.com | |
cb50f02c9c43b7927eb0324331c7dd4873c1041b | 2f97140d1b50c13ad7ac85970e6c41c30200c1b2 | /redux/Particles.cpp | cec6bf8f3d32ae4af52fa1a00eacd2d64769a915 | [] | no_license | mrdooz/codename_ch | 1b46d4b981551cbfd9eb7c63779d2820d403f52b | 4f6aa35ebc97ee4ebfabe740cda004d470edbd96 | refs/heads/master | 2016-09-06T10:35:57.357010 | 2010-02-23T20:21:41 | 2010-02-23T20:21:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,222 | cpp | #include "stdafx.h"
#include "Particles.hpp"
#include "Mesh.hpp"
#include "DebugRenderer.hpp"
#include "VertexBuffer.hpp"
#include "IndexBuffer.hpp"
using namespace std;
using namespace boost::assign;
extern ID3D10Device* g_d3d_device;
namespace
{
}
Particles::Particles(SystemInterface* system, EffectManager* effect_manager)
: _system(system)
, _effect_manager(effect_manager)
, animation_manager_(new AnimationManager())
, current_camera_(0)
, free_fly_camera_enabled_(true)
, _dynamic_mgr(new DebugRenderer(g_d3d_device))
, effect_(g_d3d_device)
{
//ib = new IndexBuffer<uint32_t>(g_d3d_device);
//vb = new VertexBuffer< mpl::vector<D3DXVECTOR3> >(g_d3d_device);
_system->add_renderable(this);
Serializer::instance().add_instance(this);
LOG_MGR.
EnableOutput(LogMgr::File).
OpenOutputFile("log.txt").
BreakOnError(true);
}
Particles::~Particles()
{
clear_vector(loaded_effects_);
clear_vector(loaded_materials_);
clear_vector(loaded_material_connections_);
effect_list_.clear();
effects_.clear();
delete(xchg_null(_dynamic_mgr));
container_delete(effect_connections_);
xchg_null(_system);
xchg_null(_effect_manager);
}
bool Particles::close()
{
return true;
}
#define RETURN_ON_FALSE(x) if (!(x)) { return false; } else {}
bool Particles::init()
{
RETURN_ON_FALSE(effect_.load("effects/Particles.fx"));
RETURN_ON_FALSE(_dynamic_mgr->init());
D3D10_PASS_DESC desc;
RETURN_ON_FALSE(effect_.get_pass_desc(desc, "render"));
return true;
}
void Particles::render(const int32_t time_in_ms, const int32_t delta)
{
}
void Particles::process_input_callback(const Input& input)
{
// TODO: For this to really work, we need to be able to get the key-up event, so we can use that to toggle
// switch between different cameras.
if (scene_.cameras_.empty()) {
free_fly_camera_enabled_ = true;
} else {
if (input.key_status['0']) {
free_fly_camera_enabled_ = true;
}
const uint32_t num_cameras = scene_.cameras_.size();
for (uint32_t i = 0; i < num_cameras; ++i) {
if (input.key_status['1' + i]) {
free_fly_camera_enabled_ = false;
current_camera_ = i;
break;
}
}
}
}
| [
"dooz@spotify.com"
] | dooz@spotify.com |
79f56291a22411f07b6509c269670edcb1d73406 | 5fbcb9b389dd4ad6f82c2d0c9f77b89527906275 | /Game/Include/Game/PhysicsComponent.h | 133ecd67b1abffe8aabaf91056dd4279898e3b1a | [] | no_license | Toopala/Spadengine | f5b32d7f661a0514a7fbeb8b094a57748fb4f8f6 | e41885884e1d816b04f8004b1b201278d752c607 | refs/heads/master | 2020-12-24T06:11:46.647175 | 2016-06-12T10:14:48 | 2016-06-12T10:14:48 | 49,644,872 | 6 | 5 | null | 2016-06-12T10:14:49 | 2016-01-14T12:05:42 | C++ | UTF-8 | C++ | false | false | 1,391 | h | #pragma once
#include "Component.h"
#include <Bullet/btBulletDynamicsCommon.h>
namespace sge
{
class PhysicsComponent : public Component
{
public:
PhysicsComponent(Entity* ent);
~PhysicsComponent();
void update();
/*void setBody(btRigidBody* bodyType)
{
body = bodyType;
}*/
/*void setShape(btCollisionShape* objectShape)
{
shape = objectShape;
}*/
template <typename T>
T* getBody()
{
return dynamic_cast<T*>(body);
}
template <typename T>
T* getShape()
{
return dynamic_cast<T*>(shape);
}
/*btCollisionObject* getBody()
{
return body;
}*/
btRigidBody* createBody(btCollisionShape* objectShape, btQuaternion& rotation, btVector3& location, btScalar& objectMass, btVector3& inertia);
private:
btTransform trans;
btRigidBody* body;
btCollisionShape* shape;
};
}
/*
btJokuVittu* createBody(btquaternion, btvector3, btscalar, jokusimpukka shape, btVector3 siika);
btDefaultMotionState* motistate
= new btdefaultmotionstate(btTransfrom(btquaternion, btvector3);
btScalar mass = jotain;
btVector3 fallInertia = siika;
btrigidbody::btrigidbodyconstructioninfo consinfo(mass, motistate, shape, inertia);
consinfo.m_restitution = restitution;
consinfo.m_friction = friction;
body = new btRigidBody(consinfo);
body->setActivationState(DISABLE_DEACTIVATION);
dynamicsWorld->addRigidBody(body);
return body;
*/
| [
"sarielirc@gmail.com"
] | sarielirc@gmail.com |
a37d248ff5e866483dccc7c19254a0daddc5b92b | a538a6605cdecbd3089445400a8ef7ef22296438 | /Code/PROJECT XYZ/Code/src/Engine/Graphics/Shapes/Triangle.cpp | c1edece85ae00b87813b77fe057af281978c97ad | [
"Unlicense"
] | permissive | Yavuz1234567890/Project-XYZ | c00c2ca6d323531d0969c51ee2461a172ed56dd2 | fa656c53b562e6cc4aceae1f3f51e205949b3e21 | refs/heads/master | 2023-04-06T17:35:56.050743 | 2021-04-14T19:46:26 | 2021-04-14T19:46:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,128 | cpp | #include "Graphics/Shapes/Triangle.hpp"
namespace Sonar
{
Triangle::Triangle( GameDataRef data ) : Drawable( data )
{
_object = &_shape;
_texture = new Texture( );
_shape.setPointCount( 3 );
SetInsideColor( Color::Black );
SetPosition( 0, 0 );
_globalBounds = _shape.getGlobalBounds( );
}
Triangle::Triangle( GameDataRef data, const glm::vec2 &point1, const glm::vec2 &point2, const glm::vec2 &point3 ) : Drawable( data )
{
_object = &_shape;
_texture = new Texture( );
_shape.setPointCount( 3 );
SetPoints( point1, point2, point3 );
SetInsideColor( Color::Black );
SetPosition( 0, 0 );
_globalBounds = _shape.getGlobalBounds( );
}
Triangle::~Triangle( ) { }
void Triangle::SetPosition( const glm::vec2 &position )
{
Drawable::SetPosition( position );
_shape.setPosition( position.x, position.y );
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::SetPosition( const float &x, const float &y )
{ SetPosition( glm::vec2( x, y ) ); }
void Triangle::SetPositionX( const float &x )
{ SetPosition( glm::vec2( x, GetPositionY( ) ) ); }
void Triangle::SetPositionY( const float &y )
{ SetPosition( glm::vec2( GetPositionX( ), y ) ); }
void Triangle::SetSize( const glm::vec2 &point1, const glm::vec2 &point2, const glm::vec2 &point3 )
{
float xMin = point1.x, xMax = point1.x;
float yMin = point1.y, yMax = point1.y;
if ( point2.x < xMin )
{ xMin = point2.x; }
else if ( point2.x > xMax )
{ xMax = point2.x; }
if ( point3.x < xMin )
{ xMin = point3.x; }
else if ( point3.x > xMax )
{ xMax = point3.x; }
if ( point2.y < yMin )
{ yMin = point2.y; }
else if ( point2.y > yMax )
{ yMax = point2.y; }
if ( point3.y < yMin )
{ yMin = point3.y; }
else if ( point3.y > yMax )
{ yMax = point3.y; }
float width = xMax - xMin;
float height = yMax - yMin;
Drawable::SetSize( width, height );
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::SetInsideColor( const Color &color )
{
Drawable::SetInsideColor( color );
_shape.setFillColor( color.GetColor( ) );
}
void Triangle::SetBorderColor( const Color &color )
{
Drawable::SetBorderColor( color );
_shape.setOutlineColor( color.GetColor( ) );
}
void Triangle::SetBorderThickness( const float &thickness )
{
Drawable::SetBorderThickness( thickness );
_shape.setOutlineThickness( thickness );
}
Color Triangle::GetInsideColor( ) const
{ return Color( _shape.getFillColor( ).r, _shape.getFillColor( ).g, _shape.getFillColor( ).b, _shape.getFillColor( ).a ); }
Color Triangle::GetBorderColor( ) const
{ return Color( _shape.getOutlineColor( ).r, _shape.getOutlineColor( ).g, _shape.getOutlineColor( ).b, _shape.getOutlineColor( ).a ); }
float Triangle::GetBorderThickness( ) const
{ return _shape.getOutlineThickness( ); }
void Triangle::Move( const glm::vec2 &offset )
{
Drawable::Move( offset );
_shape.move( offset.x, offset.y );
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::Move( const float &x, const float &y )
{ Move( glm::vec2( x, y ) ); }
void Triangle::MoveX( const float &x )
{ Move( glm::vec2( x, 0 ) ); }
void Triangle::MoveY( const float &y )
{ Move( glm::vec2( 0, y ) ); }
void Triangle::SetRotation( const float &angle )
{
Drawable::SetRotation( angle );
_shape.setRotation( angle );
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::Rotate( const float &angle )
{ SetRotation( GetRotation( ) + angle ); }
float Triangle::GetRotation( ) const
{ return _shape.getRotation( ); }
void Triangle::SetScale( const glm::vec2 &scale )
{
Drawable::SetScale( scale[0], scale[1] );
_shape.setScale( scale[0], scale[1] );
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::SetScale( const float &xScale, const float &yScale )
{ SetScale( glm::vec2( xScale, yScale ) ); }
void Triangle::SetScaleX( const float &xScale )
{ SetScale( glm::vec2( xScale, GetScaleY( ) ) ); }
void Triangle::SetScaleY( const float &yScale )
{ SetScale( glm::vec2( GetScaleX( ), yScale ) ); }
void Triangle::Scale( const glm::vec2 & scale )
{ SetScale( GetScaleX( ) * scale ); }
void Triangle::Scale( const float &xScale, const float &yScale )
{ SetScale( glm::vec2( GetScaleX( ) * xScale, GetScaleY( ) * yScale ) ); }
void Triangle::ScaleX( const float &xScale )
{ SetScale( glm::vec2( GetScaleX( ) * xScale, GetScaleY( ) ) ); }
void Triangle::ScaleY( const float &yScale )
{ SetScale( glm::vec2( GetScaleX( ), GetScaleY( ) * yScale ) ); }
void Triangle::SetPivot( const glm::vec2 &pivot )
{
Drawable::SetPivot( pivot );
_shape.setOrigin( pivot[0], pivot[1] );
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::SetPivot( const float &xPoint, const float &yPoint )
{ SetPivot( glm::vec2( xPoint, yPoint ) ); }
void Triangle::SetPivot( const OBJECT_POINTS &pivot )
{
switch ( pivot )
{
case OBJECT_POINTS::CENTER:
Drawable::SetPivot( OBJECT_POINTS::CENTER );
_shape.setOrigin( _shape.getLocalBounds( ).width * 0.5f, _shape.getLocalBounds( ).height * 0.5f );
break;
case OBJECT_POINTS::TOP_LEFT:
Drawable::SetPivot( OBJECT_POINTS::TOP_LEFT );
_shape.setOrigin( 0, 0 );
break;
case OBJECT_POINTS::TOP_RIGHT:
Drawable::SetPivot( OBJECT_POINTS::TOP_RIGHT );
_shape.setOrigin( _shape.getLocalBounds( ).width, 0 );
break;
case OBJECT_POINTS::BOTTOM_LEFT:
Drawable::SetPivot( OBJECT_POINTS::BOTTOM_LEFT );
_shape.setOrigin( 0, _shape.getLocalBounds( ).height );
break;
case OBJECT_POINTS::BOTTOM_RIGHT:
Drawable::SetPivot( OBJECT_POINTS::BOTTOM_RIGHT );
_shape.setOrigin( _shape.getLocalBounds( ).width, _shape.getLocalBounds( ).height );
break;
}
_globalBounds = _shape.getGlobalBounds( );
}
void Triangle::SetPivotX( const float &xPoint )
{ SetPivot( glm::vec2( xPoint, GetPivotY( ) ) ); }
void Triangle::SetPivotY( const float &yPoint )
{ SetPivot( glm::vec2( GetPivotX( ), yPoint ) ); }
void Triangle::Update( const float &dt )
{
Drawable::Update( dt );
SetScale( Drawable::GetScale( ) );
}
void Triangle::SetPoints( const glm::vec2 &point1, const glm::vec2 &point2, const glm::vec2 &point3 )
{
_shape.setPoint( 0, sf::Vector2f( point1.x, point1.y ) );
_shape.setPoint( 1, sf::Vector2f( point2.x, point2.y ) );
_shape.setPoint( 2, sf::Vector2f( point3.x, point3.y ) );
_points.push_back( point1 );
_points.push_back( point2 );
_points.push_back( point3 );
SetSize( point1, point2, point3 );
_globalBounds = _shape.getGlobalBounds( );
}
std::vector<glm::vec2> Triangle::GetPoints( )
{ return _points; }
void Triangle::SetTexture( const std::string &filepath, const bool &resetRect )
{
_texture->SetTexture( filepath );
_shape.setTexture( _texture->GetTexture( ), resetRect );
SetPosition( _shape.getPosition( ).x, _shape.getPosition( ).y );
}
void Triangle::SetTexture( Texture *texture, const bool &resetRect )
{
_texture = texture;
_shape.setTexture( _texture->GetTexture( ), resetRect );
SetPosition( _shape.getPosition( ).x, _shape.getPosition( ).y );
}
void Triangle::SetTextureRect( const glm::ivec4 &rectangle )
{ _shape.setTextureRect( sf::IntRect( rectangle.x, rectangle.y, rectangle.z, rectangle.w ) ); }
void Triangle::SetTextureRect( const int &left, const int &top, const int &width, const int &height )
{ SetTextureRect( glm::ivec4( left, top, width, height ) ); }
Texture *Triangle::GetTexture( ) const
{ return _texture; }
glm::ivec4 Triangle::GetTextureRect( ) const
{ return glm::ivec4( _shape.getTextureRect( ).left, _shape.getTextureRect( ).top, _shape.getTextureRect( ).width, _shape.getTextureRect( ).height ); }
glm::vec4 Triangle::GetLocalBounds( ) const
{ return glm::vec4( _shape.getLocalBounds( ).left, _shape.getLocalBounds( ).top, _shape.getLocalBounds( ).width, _shape.getLocalBounds( ).height ); }
glm::vec4 Triangle::GetGlobalBounds( ) const
{ return glm::vec4( _shape.getGlobalBounds( ).left, _shape.getGlobalBounds( ).top, _shape.getGlobalBounds( ).width, _shape.getGlobalBounds( ).height ); }
}
| [
"SonarSystems@users.noreply.github.com"
] | SonarSystems@users.noreply.github.com |
35e9dd56ce0021fabd04ce954b61b48f45a3082f | a96cbdb9aa0d96bc420f0847a8753a6d3f36bc3a | /Lesson_9/Sample9.cpp | d83e2e647198f3898b4fa5da0a3b579801d513fd | [] | no_license | KamonohashiPerry/cplusplus | e1901842e8a9b711a39c86557d81e9cc42e8b2ab | 970a73df4526c011b9098fcfeb67beab345d71b4 | refs/heads/master | 2023-02-06T16:48:21.376905 | 2020-12-27T06:37:22 | 2020-12-27T06:37:22 | 291,221,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cpp | #include <iostream>
using namespace std;
int main()
{
const char* str = "Hello";
cout << str << '\n';
return 0;
} | [
"economics.teru@gmail.com"
] | economics.teru@gmail.com |
0adecbbe7631f4da808524b48273b91642b1e427 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/ui/dvd/driver/dvdpldrv/Common/DVDAVDisk.h | d41084edb94a6703bd5def89a6577d326edcd8ae | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,739 | h | ////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2000-2001 STMicroelectronics, Inc. All Rights Reserved. //
// HIGHLY CONFIDENTIAL INFORMATION: This source code contains //
// confidential and proprietary information of STMicroelectronics, Inc. //
// This source code is provided to Microsoft Corporation under a written //
// confidentiality agreement between STMicroelectronics and Microsoft. This //
// software may not be reproduced, distributed, modified, disclosed, used, //
// displayed, stored in a retrieval system or transmitted in whole or in part,//
// in any form or by any means, electronic, mechanical, photocopying or //
// otherwise, except as expressly authorized by STMicroelectronics. THE ONLY //
// PERSONS WHO MAY HAVE ACCESS TO THIS SOFTWARE ARE THOSE PERSONS //
// AUTHORIZED BY RAVISENT, WHO HAVE EXECUTED AND DELIVERED A //
// WRITTEN CONFIDENTIALITY AGREEMENT TO STMicroelectronics, IN THE FORM //
// PRESCRIBED BY STMicroelectronics. //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//
// DVD Audio/Video specific Disk Information
//
////////////////////////////////////////////////////////////////////
#ifndef DVDAVDISK_H
#define DVDAVDISK_H
#include "DVDDisk.h"
#include "DVDAVHeader.h"
//////////////////////////////////////////////////////////////////////
//
// DVD Video Manager Menu Class
//
// Description:
// The VMGM represents the Title Menu.
//
//////////////////////////////////////////////////////////////////////
class DVDVMGM : public DVDMGM
{
protected:
DVDVMGMVOBS * vmgmVobs;
public:
DVDVMGM(DVDDiskPlayerFactory * factory);
virtual ~DVDVMGM(void);
Error Init(DVDFileSystem * dvdfs, WORD parentalCountryCode);
Error Identify(DVDManagerMenuType & mgmType);
Error HasFirstPlayPGC(BOOL & hasFPP);
Error GetFirstPlayPGCI(DVDGenericPGCI * & pgci);
Error HasMPGCIUT(BOOL & hasMPGCIUT);
Error GetMPGCIUT(DVDPGCIUT & pgciut);
Error GetSRPT(DVDSRPT * & srpt);
Error HasMGMVOBS(BOOL & hasMGMVOBS);
Error GetMGMVOBS(DVDMGMVOBS * & mgmVobs);
};
//////////////////////////////////////////////////////////////////////
//
// DVD Audio Manager Menu Class
//
// Description:
// DVD Audio Mananger Menu Class describes a table of contents for
// all Audio Title Sets (ATSs) which exist in DVD-Audio zone, and
// all Video Title Sets (VTSs) for Audio Titles, which exist in
// DVD-Video zone.
//
//////////////////////////////////////////////////////////////////////
class DVDAMGM : public DVDMGM
{
protected:
DVDAMGMVOBS * amgmVobs;
public:
DVDAMGM(DVDDiskPlayerFactory * factory);
virtual ~DVDAMGM(void);
Error Init(DVDFileSystem * dvdfs, WORD parentalCountryCode);
Error Identify(DVDManagerMenuType & mgmType);
Error HasFirstPlayPGC(BOOL & hasFPP);
Error GetFirstPlayPGCI(DVDGenericPGCI * & pgci);
Error HasMPGCIUT(BOOL & hasMPGCIUT);
Error GetMPGCIUT(DVDPGCIUT & pgciut);
Error GetSRPT(DVDSRPT * & srpt);
Error HasMGMVOBS(BOOL & hasMGMVOBS);
Error GetMGMVOBS(DVDMGMVOBS * & mgmvobs);
};
//////////////////////////////////////////////////////////////////////
//
// DVD Video Title Set Class
//
// Description:
// The Video Title Set Class describes the Video Title Set. This
// is a collection of Titles and VTSM.
//
//////////////////////////////////////////////////////////////////////
class DVDVTS : public DVDTS
{
protected:
DVDVTSMVOBS * vtsmVobs;
DVDVTSVOBS * vtsVobs;
public:
DVDVTS(DVDDiskPlayerFactory * factory);
virtual ~DVDVTS(void);
Error Init(DVDFileSystem * dvdfs, WORD ts, DVDPTLMAI ptlmai);
Error HasPTT(BOOL & hasPTT);
Error GetPTT(DVDPTT & ptt);
Error HasMPGCIUT(BOOL & hasMPGCIUT);
Error GetMPGCIUT(DVDPGCIUT & pgciut);
Error GetPGCIT(DVDPGCIT & pgcit);
DVDVTSMVOBS * GetVTSMVOBS(void) { return vtsmVobs; }
DVDVTSVOBS * GetVTSVOBS(void) { return vtsVobs; }
DVDOBS * GetTSOBS(void) { return vtsVobs; }
};
//////////////////////////////////////////////////////////////////////
//
// DVD Audio Title Set Class
//
// Description:
// ATS defines the Audio Only Titles (AOTTs) which is defined by
// the Navigation Data and the Audio Objects (AOBs) in the ATS,
// or by the Navigation Data in the ATS and the audio part of
// Video Objects (VOBs) in the VTS.
//
//////////////////////////////////////////////////////////////////////
class DVDATS : public DVDTS
{
protected:
DVDATSAOTTOBS * atsAottObs;
public:
DVDATS(DVDDiskPlayerFactory * factory);
virtual ~DVDATS(void);
Error Init(DVDFileSystem * dvdfs, WORD ts, DVDPTLMAI ptlmai);
virtual Error HasPTT(BOOL & hasPTT);
virtual Error GetPTT(DVDPTT & ptt);
virtual Error HasMPGCIUT(BOOL & hasMPGCIUT);
virtual Error GetMPGCIUT(DVDPGCIUT & pgciut);
virtual Error GetPGCIT(DVDPGCIT & pgcit);
virtual DVDATSAOTTOBS * GetATSAOBS(void) { return atsAottObs; }
DVDOBS * GetTSOBS(void) { return atsAottObs; }
};
//////////////////////////////////////////////////////////////////////
//
// DVD Video Disk Class
//
//////////////////////////////////////////////////////////////////////
class DVDVideoDisk : public DVDDisk
{
protected:
DVDVMGM * vmgm;
DVDVTS * currentVTS;
public:
DVDVideoDisk(DVDDiskPlayerFactory * factory);
virtual ~DVDVideoDisk(void);
Error Init(DVDFileSystem * diskfs, WORD parentalCountryCode);
DVDMGM * GetMGM(void) { return (DVDMGM *)vmgm; }
Error GetTS(WORD num, DVDTS * & titleSet);
Error GetTSExclusive(WORD num, DVDTS * & titleSet, BOOL & deleteIt);
};
//////////////////////////////////////////////////////////////////////
//
// DVD Audio Disk Class
//
// Description:
//
//////////////////////////////////////////////////////////////////////
class DVDAudioDisk : public DVDDisk
{
protected:
DVDAMGM * amgm;
DVDATS * currentATS;
public:
DVDAudioDisk(DVDDiskPlayerFactory * factory);
virtual ~DVDAudioDisk(void);
Error Init(DVDFileSystem * diskfs, WORD parentalCountryCode);
DVDMGM * GetMGM(void) { return (DVDMGM *)amgm; }
Error GetTS(WORD num, DVDTS * & titleSet);
Error GetTSExclusive(WORD num, DVDTS * & titleSet, BOOL & deleteIt);
};
#endif // DVDAVDISK_H
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
d59772b3ea7e35f5e1132888692bb74332d055c1 | 269abdb0c6479ce9c27477b5e0e59370b4292055 | /Array/mergeSortedArray.cpp | 6b3e6b021e73a7a134d0dacc07f81e83424cf12c | [] | no_license | sur4jsharma/CP | 3bcf9dce8915b71498c25b0b3d1eaab12d815fc9 | bc7a28186609735db1818a99c2032c10933e3b86 | refs/heads/master | 2022-10-11T16:37:21.079997 | 2020-06-12T08:53:21 | 2020-06-12T08:53:21 | 271,750,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,605 | cpp | #include<bits/stdc++.h>
using namespace std;
// void swap(int& x,int& y)
// {
// x^=y;
// y^=x;
// x^=y;
// }
void inplaceMerge(int arr1[],int arr2[],int n1,int n2)
{
int gap = n1+n2;
gap = (gap/2)+(gap%2);
int i,j;
int rem;
while(gap)
{
// cout<<"gap is:"<<gap<<endl;
i=0;
j=i+gap;
//(gap+1) is sliding window size, no of time loop runs is total size - window size
while(j<n1)
{
if(arr1[i] > arr1[j])
swap(arr1[i],arr1[j]);
i++;
j++;
}
j=0;
while(i<n1 && j<n2)
{
if(arr1[i] > arr2[j])
swap(arr1[i],arr2[j]);
i++;
j++;
}
i=0;
while(j<n2)
{
if(arr2[i] > arr2[j])
swap(arr2[i],arr2[j]);
i++;
j++;
}
if(gap==1)
break;
gap = (gap/2)+(gap%2);
}
for(int i=0;i<n1;i++)
cout<<arr1[i]<<" ";
for(int i=0;i<n2;i++)
cout<<arr2[i]<<" ";
cout<<endl;
}
int main()
{
//code
int t,n1,n2;
// cin>>t;
t=1;
while(t--)
{
// cin>>n1>>n2;
n1=50;
n2=10;
int arr1[n1];
int arr2[n2];
for(int i=0;i<n1;i++)
arr1[i]=i+1;
for(int i=0;i<n2;i++)
arr2[i]=i+1;
for(int i=0;i<n1;i++)
cout<<arr1[i]<<" ";
for(int i=0;i<n2;i++)
cout<<arr2[i]<<" ";
cout<<endl;
inplaceMerge(arr1,arr2,n1,n2);
}
return 0;
} | [
"sooraj@cse.iitb.ac.in"
] | sooraj@cse.iitb.ac.in |
28c8053f7d3b7bd9d9eaa46bc7f548fd3e8ae25e | c8438ae7fcf871fccdd76fe6f30fcff2c184efda | /external/indicators/color.hpp | 39ad01e72105331b4e1a175370a6ef5c1cd8b3e6 | [] | no_license | vetlewi/MiniballREX | 7a993b657ff87f16e324562a6b11db3ad2b5f564 | 9201b39323c1b5afe46b369c4c80ca29157e19be | refs/heads/master | 2023-04-09T08:04:13.931266 | 2022-02-14T11:38:02 | 2022-02-14T11:38:02 | 257,984,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | hpp |
#pragma once
#include <indicators/termcolor.hpp>
namespace indicators {
enum class Color { grey, red, green, yellow, blue, magenta, cyan, white, unspecified };
}
| [
"v.w.ingeberg@fys.uio.no"
] | v.w.ingeberg@fys.uio.no |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.