void initFlags(int *argcp, const char ***argvp, int ignoreargs) { int argc = *argcp; const char **argv = *argvp; map<string, LinkageData> &links = getLinkageSingleton(); for(map<string, LinkageData>::iterator itr = links.begin(); itr != links.end(); itr++) { if(itr->second.type == LinkageData::LINKAGE_BOOL) { *itr->second.bool_link = itr->second.bool_def; } else if(itr->second.type == LinkageData::LINKAGE_INT) { *itr->second.int_link = itr->second.int_def; } else if(itr->second.type == LinkageData::LINKAGE_STRING) { *itr->second.str_link = itr->second.str_def; } else if(itr->second.type == LinkageData::LINKAGE_FLOAT) { *itr->second.float_link = itr->second.float_def; } else { CHECK(0); } *itr->second.source = FS_DEFAULT; } for(map<string, LinkageData>::iterator itr = links.begin(); itr != links.end(); itr++) { if(itr->second.type == LinkageData::LINKAGE_BOOL) { //dprintf("Initted bool %s to %d\n", itr->first.c_str(), *itr->second.bool_link); } else if(itr->second.type == LinkageData::LINKAGE_INT) { //dprintf("Initted int %s to %d\n", itr->first.c_str(), *itr->second.int_link); } else if(itr->second.type == LinkageData::LINKAGE_STRING) { //dprintf("Initted string %s to %s\n", itr->first.c_str(), itr->second.str_link->c_str()); } else if(itr->second.type == LinkageData::LINKAGE_FLOAT) { //dprintf("Initted float %s to %f\n", itr->first.c_str(), *itr->second.float_link); } else { CHECK(0); } } vector<pair<string, FlagSource> > lines; { ifstream ifs("glorp/settings.local"); string dt; while(getLineStripped(ifs, &dt)) lines.push_back(make_pair(dt, FS_FILE)); } vector<const char *> remains; for(int i = 0; i < ignoreargs + 1; i++) remains.push_back(argv[i]); for(int i = ignoreargs + 1; i < argc; i++) { if(argv[i][0] == '-' && argv[i][1] == '-') { lines.push_back(make_pair(argv[i] + 2, FS_CLI)); } else { remains.push_back(argv[i]); } } remains.push_back(NULL); std::copy(remains.begin(), remains.end(), argv); for(int i = 0; i < lines.size(); i++) { const char *arg = lines[i].first.c_str(); bool isBoolNo = false; if(strlen(arg) >= 2 && tolower(arg[0]) == 'n' && tolower(arg[1]) == 'o') { isBoolNo = true; arg += 2; } const char *eq = strchr(arg, '='); string realarg; if(eq) { realarg = string(arg, eq); eq++; } else { realarg = arg; } realarg = canonize(realarg); if(!links.count(realarg)) { dprintf("Invalid commandline argument %s\n", arg); CHECK(0); continue; } LinkageData &ld = links[realarg]; if(ld.type == LinkageData::LINKAGE_BOOL) { CHECK(!eq || string(eq) == "true" || string(eq) == "false"); CHECK(!eq || !isBoolNo); CHECK(ld.bool_link); if(isBoolNo || (eq && string(eq) == "false")) { *ld.bool_link = false; } else { *ld.bool_link = true; } } else if(ld.type == LinkageData::LINKAGE_STRING) { CHECK(!isBoolNo && eq); CHECK(ld.str_link); *ld.str_link = eq; } else if(ld.type == LinkageData::LINKAGE_INT) { CHECK(!isBoolNo && eq); CHECK(ld.int_link); *ld.int_link = atoi(eq); } else if(ld.type == LinkageData::LINKAGE_FLOAT) { CHECK(!isBoolNo && eq); CHECK(ld.float_link); *ld.float_link = atof(eq); } else { CHECK(0); } *ld.source = lines[i].second; } for(int i = 0; i < getMassageSingleton().size(); i++) { (*getMassageSingleton()[i])(); delete getMassageSingleton()[i]; } getMassageSingleton().clear(); for(map<string, LinkageData>::iterator itr = links.begin(); itr != links.end(); itr++) { if(itr->second.type == LinkageData::LINKAGE_BOOL) { //dprintf("Set bool %s to %d\n", itr->first.c_str(), *itr->second.bool_link); } else if(itr->second.type == LinkageData::LINKAGE_INT) { //dprintf("Set int %s to %d\n", itr->first.c_str(), *itr->second.int_link); } else if(itr->second.type == LinkageData::LINKAGE_STRING) { //dprintf("Set string %s to %s\n", itr->first.c_str(), itr->second.str_link->c_str()); } else if(itr->second.type == LinkageData::LINKAGE_FLOAT) { //dprintf("Set float %s to %f\n", itr->first.c_str(), *itr->second.float_link); } else { CHECK(0); } } }
void proxmap_t::init_opencl(){ cerr<<"Initializing OpenCL...\n"; if(run_gpu){ // initialize the GPU if necessary //int platform_id = 0; int platform_id = config->platform_id; //int device_id = 0; int device_id = config->device_id; cerr<<"Initializing GPU with platform id "<<platform_id<< " and device id "<<device_id<<".\n"; vector<cl::Platform> platforms; err = cl::Platform::get(&platforms); cerr<<"Platform ID "<<platform_id<<" has name "<< platforms[platform_id].getInfo<CL_PLATFORM_NAME>().c_str()<<endl; cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[platform_id])(),0}; context = new cl::Context(CL_DEVICE_TYPE_GPU,cps); devices = context->getInfo<CL_CONTEXT_DEVICES>(); cerr<<"There are "<<devices.size()<<" devices\n"; cerr<<"Device ID "<<device_id<<" is a "; cl_device_type dtype = devices[device_id].getInfo<CL_DEVICE_TYPE>(); switch(dtype){ case CL_DEVICE_TYPE_GPU: cerr<<"GPU\n"; break; case CL_DEVICE_TYPE_CPU: cerr<<"CPU\n"; break; } commandQueue = new cl::CommandQueue(*context,devices[device_id],0,&err); vector<string> sources; sources.push_back("cl_constants.h"); sources.push_back("common.c"); ostringstream full_source_str; for(uint j=0;j<sources.size();++j){ ostringstream oss; oss<<config->kernel_base<<"/"<<sources[j]; string full_path = oss.str(); cerr<<"Opening "<<full_path<<endl; ifstream ifs(full_path.data()); clSafe(ifs.is_open()?CL_SUCCESS:-1,"kernel_path not found"); string source_str(istreambuf_iterator<char>(ifs),(istreambuf_iterator<char>())); full_source_str<<source_str; } string source_str = full_source_str.str(); // create a program object from kernel source cerr<<"Creating source\n"; cl::Program::Sources source(1,make_pair(source_str.c_str(),source_str.length()+1)); cerr<<"Creating program\n"; program = new cl::Program(*context,source); //const char * preproc; // if (geno_dim==PHASED_INPUT){ // preproc = "-Dphased"; // } else if(geno_dim==UNPHASED_INPUT){ // preproc = "-Dunphased"; // } err = program->build(devices); //err = program->build(devices,preproc); if(err!=CL_SUCCESS){ cerr<<"Build failed:\n"; string buffer; program->getBuildInfo(devices[0],CL_PROGRAM_BUILD_LOG,&buffer); cerr<<buffer<<endl; throw "Aborted from OpenCL build fail."; } cerr<<"GPU kernel arguments assigned.\n"; } }
void TMesh::Load(char *fname) { ifstream ifs(fname, ios::binary); if (ifs.fail()) { cerr << "INFO: cannot open file: " << fname << endl; return; } ifs.read((char*)&vertsN, sizeof(int)); char yn; ifs.read(&yn, 1); // always xyz if (yn != 'y') { cerr << "INTERNAL ERROR: there should always be vertex xyz data" << endl; return; } if (verts) delete verts; verts = new Vector3D[vertsN]; ifs.read(&yn, 1); // cols 3 floats if (cols) delete cols; cols = 0; if (yn == 'y') { cols = new Vector3D[vertsN]; } ifs.read(&yn, 1); // normals 3 floats //Vector3D *normals = 0; // don't have normals for now if (normals) delete normals; normals = 0; if (yn == 'y') { normals = new Vector3D[vertsN]; } ifs.read(&yn, 1); // texture coordinates 2 floats float *tcs = 0; // don't have texture coordinates for now if (tcs) delete tcs; tcs = 0; if (yn == 'y') { tcs = new float[vertsN*2]; } ifs.read((char*)verts, vertsN*3*sizeof(float)); // load verts if (cols) { ifs.read((char*)cols, vertsN*3*sizeof(float)); // load cols } if (normals) ifs.read((char*)normals, vertsN*3*sizeof(float)); // load normals if (tcs) ifs.read((char*)tcs, vertsN*2*sizeof(float)); // load texture coordinates ifs.read((char*)&trisN, sizeof(int)); if (tris) delete tris; tris = new unsigned int[trisN*3]; ifs.read((char*)tris, trisN*3*sizeof(unsigned int)); // read tiangles ifs.close(); cerr << "INFO: loaded " << vertsN << " verts, " << trisN << " tris from " << endl << " " << fname << endl; cerr << " xyz " << ((cols) ? "rgb " : "") << ((normals) ? "nxnynz " : "") << ((tcs) ? "tcstct " : "") << endl; /* float max_y = FLT_MIN; float min_y = FLT_MAX; float max_z = FLT_MIN; float min_z = FLT_MAX; for(int i = 0; i < vertsN; i++){ if(verts[i].coords[1] < min_y){ min_y = verts[i].coords[1]; }else if(verts[i].coords[1] > max_y){ max_y = verts[i].coords[1]; } if(verts[i].coords[2] < min_z){ min_z = verts[i].coords[2]; }else if(verts[i].coords[2] > max_z){ max_z = verts[i].coords[2]; } } float range_y = max_y - min_y; float range_z = max_z - min_z; //cout << min_y << endl; for(int i = 0; i < vertsN; i++){ float scale_y = (verts[i].coords[1]-min_y)/range_y; float scale_z = (verts[i].coords[2]-min_z)/range_z; cols[i] = Vector3D(0.0f, scale_y*scale_z, 0.0f); }*/ }
std::string LoadMtl( std::map<std::string, material_t>& material_map, const char* filename, const char* mtl_basepath) { material_map.clear(); std::stringstream err; std::string filepath; if (mtl_basepath) { filepath = std::string(mtl_basepath) + std::string(filename); } else { filepath = std::string(filename); } std::ifstream ifs(filepath.c_str()); if (!ifs) { err << "Cannot open file [" << filepath << "]" << std::endl; return err.str(); } material_t material; int maxchars = 8192; // Alloc enough size. std::vector<char> buf(maxchars); // Alloc enough size. while (ifs.peek() != -1) { ifs.getline(&buf[0], maxchars); std::string linebuf(&buf[0]); // Trim newline '\r\n' or '\r' if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // new mtl if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) { // flush previous material. material_map.insert(std::pair<std::string, material_t>(material.name, material)); // initial temporary material InitMaterial(material); // set new mtl name char namebuf[4096]; token += 7; sscanf(token, "%s", namebuf); material.name = namebuf; continue; } // ambient if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.ambient[0] = r; material.ambient[1] = g; material.ambient[2] = b; continue; } // diffuse if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.diffuse[0] = r; material.diffuse[1] = g; material.diffuse[2] = b; continue; } // specular if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.specular[0] = r; material.specular[1] = g; material.specular[2] = b; continue; } // transmittance if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.transmittance[0] = r; material.transmittance[1] = g; material.transmittance[2] = b; continue; } // ior(index of refraction) if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) { token += 2; material.ior = parseFloat(token); continue; } // emission if (token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.emission[0] = r; material.emission[1] = g; material.emission[2] = b; continue; } // shininess if (token[0] == 'N' && token[1] == 's' && isSpace(token[2])) { token += 2; material.shininess = parseFloat(token); continue; } // illum model if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) { token += 6; material.illum = parseInt(token); continue; } // dissolve if ((token[0] == 'd' && isSpace(token[1]))) { token += 1; material.dissolve = parseFloat(token); continue; } if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) { token += 2; material.dissolve = parseFloat(token); continue; } // ambient texture if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) { token += 7; material.ambient_texname = token; continue; } // diffuse texture if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) { token += 7; material.diffuse_texname = token; continue; } // specular texture if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) { token += 7; material.specular_texname = token; continue; } // normal texture if (IsBumpMap(token)) { while (*token == '-') { // parse bump map options... if ((0 == strncmp(token, "-bm", 3)) && isSpace(token[3])) { token += 4; material.bump_scale = parseFloat(token); } else { ParseUnsupportedBumpModifier(token, err); } // skip space token += strspn(token, " \t"); } material.normal_texname = token; continue; } // unknown parameter const char* _space = strchr(token, ' '); if (!_space) { _space = strchr(token, '\t'); } if (_space) { int len = _space - token; std::string key(token, len); std::string value = _space + 1; material.unknown_parameter.insert(std::pair<std::string, std::string>(key, value)); } } // flush last material. material_map.insert(std::pair<std::string, material_t>(material.name, material)); return err.str(); }
bool Consistency::check(Variable &dataVar, std::string entryID) { // return value is true, when there is not a project table, yet. // Search the project table for an entry // matching the varname and frequency (account also rotated). // Open project table. Mode: read std::string str0(projectTableFile.getFile()); std::ifstream ifs(str0.c_str(), std::ios::in); if( !ifs.is_open() ) // file does not exist return true; // causes writing of a new entry size_t sz_PV = entryID.size(); std::string t_md; bool notFound=true; while( getline(ifs, str0) ) { if( str0.substr(0,sz_PV) != entryID ) continue; // found a valid entry notFound=false; t_md = hdhC::stripSides(str0) ; // read aux-lines while( getline(ifs, str0) ) { str0 = hdhC::stripSides(str0) ; if( str0.substr(0,4) != "aux=" ) goto BREAK ; // found the end of the entry t_md += '\n'; t_md += str0 ; } } if(notFound) return true; // entry not found BREAK: // close the project table ifs.close(); // get meta data info from the file std::string f_md; getMetaData(dataVar, entryID, f_md); // Comparison of meta-data from the project table and the file, respectively. // Note that the direct comparison fails because of different spaces. // Deviating distribution of auxiliaries and attributes is tolerated. // Use index-vector for book-keeping. // Meaning: x=split, t=file, t=table, a=attribute, eq=(att-name,att-value) Split splt_xt(t_md, '\n'); Split splt_xf(f_md, '\n'); size_t xt_sz=splt_xt.size(); size_t xf_sz=splt_xf.size(); std::vector<std::string> xf; for( size_t i=0 ; i < xf_sz ; ++i ) xf.push_back( hdhC::stripSides(splt_xf[i]) ); std::vector<std::string> xt; for( size_t i=0 ; i < xt_sz ; ++i ) xt.push_back( hdhC::stripSides(splt_xt[i]) ); // simple test for identity if( xt_sz == xf_sz ) { bool is=true; for( size_t i=0 ; i < xt_sz ; ++i ) { if( xt[i] != xf[i] ) { is=false ; break; } } if( is ) return false; } // store indexes std::vector<int> xf_ix; for( size_t i=0 ; i < xf_sz ; ++i ) xf_ix.push_back( i ); std::vector<int> xt_ix; for( size_t i=0 ; i < xt_sz ; ++i ) xt_ix.push_back( i ); // At first, test whether total auxiliary entries are identical. for( size_t i=0 ; i < xt_sz ; ++i ) { for( size_t j=0 ; j < xf_sz ; ++j ) { // only test strings for indexes still to be checked if( xt_ix[i] > -1 && xf_ix[i] > -1 && xf[j] == xt[i] ) { xt_ix[i] = -1; xf_ix[j] = -1; break; } } } Split xf_a; // meta-data from file xf_a.setSeparator(','); Split xt_a; // from the table xt_a.setSeparator(','); Split xf_eq; xf_eq.setSeparator('='); Split xt_eq; xt_eq.setSeparator('='); bool isMissAux; for( size_t ixt=0 ; ixt < xt_ix.size() ; ++ixt ) { int jt=xt_ix[ixt]; if( jt < 0 ) continue; // passed already a check isMissAux=true; //split at comma xt_a = xt[jt] ; for( size_t ixf=0 ; ixf < xf_ix.size() ; ++ixf ) { int jf=xf_ix[ixf]; if( jf < 0 ) continue; // passed already a check //split at comma xf_a = xf[jf] ; // compare the names of the auxiliaries if( xf_a[0] != xt_a[0] ) continue; isMissAux=false; // scan the attributes for( size_t ita=1 ; ita < xt_a.size() ; ++ita ) { // split at '=' xt_eq = xt_a[ita] ; bool isAttMissing=true; for( size_t ifa=1 ; ifa < xf_a.size() ; ++ifa ) { // split at '=' xf_eq = xf_a[ifa] ; if( xt_eq[0] == xf_eq[0] ) // found identical attribute names { isAttMissing=false; if( xt_eq[1] == xf_eq[1] ) // found identical values break; // try the next attribute // this is a very special one for time: one wit separator T and/or Z // the other one without std::string auxName; if( xt_a[0].substr(0,4) == "aux=" ) auxName = xt_a[0].substr(4) ; else auxName = xt_a[0] ; if( auxName == "time" ) { Split x_tt(xt_eq[1]," TZ",true) ; Split x_ff(xf_eq[1]," TZ",true) ; if( x_tt.size() == x_ff.size() ) { bool is=true; for(size_t c=0 ; c < x_tt.size() ; ++c ) if( x_tt[c] != x_ff[c] ) is=false; if(is) break; } } // different values --> annotation status=true; std::string key("8_8"); if( notes->inq( key, dataVar.name ) ) { std::string capt; if( xt_a[0].substr(0,4) == "aux=" ) { capt = "auxiliary "; capt += hdhC::tf_var(auxName, hdhC::colon) ; } else capt += hdhC::tf_var(xt_a[0], hdhC::colon) ; if( xt_eq[0] == "values" ) capt += "data has changed"; else { capt += xt_eq[0] ; capt += " has changed from"; capt += hdhC::tf_val(xt_eq[1]) ; capt += " to"; capt += hdhC::tf_val(xf_eq[1]) ; } capt += " across experiment or sub-temporal files"; (void) notes->operate(capt) ; notes->setCheckMetaStr( "FAIL" ); } break; // try next } } if( isAttMissing ) { status=true; std::string key("8_7"); if( notes->inq( key, dataVar.name ) ) { std::string capt; if( xt_a[0].substr(0,4) == "aux=" ) { capt = "auxiliary "; capt += hdhC::tf_var(xt_a[0].substr(4), hdhC::colon) ; } else capt += hdhC::tf_var(xt_a[0], hdhC::colon) ; if( xt_eq[0] == "values" ) capt += "no data"; else { capt += hdhC::tf_att(xt_eq[0]); capt += "is missing " ; } if( qa->currQARec ) capt += "across sub-temporal files"; else capt += "across experiments"; (void) notes->operate(capt) ; notes->setCheckMetaStr( "FAIL" ); } } } } if( isMissAux ) { status=true; std::string key("8_4"); if( notes->inq( key, dataVar.name ) ) { std::string capt; if( xt_a[0].substr(0,4) == "aux=" ) { capt = "auxiliary "; capt += hdhC::tf_var(xt_a[0].substr(4), hdhC::colon) ; } else capt += hdhC::tf_var(xt_a[0], hdhC::colon) ; capt += "missing across experiments or sub-temporal files"; (void) notes->operate(capt) ; notes->setCheckMetaStr( "FAIL" ); } } } // test for missing attributes in the table (reversed for-loops) bool isAddAux=true; for( size_t ixf=0 ; ixf < xf_ix.size() ; ++ixf ) { int jf=xf_ix[ixf]; if( jf < 0 ) continue; // passed already a check isAddAux=true; //split at comma xf_a = xf[jf] ; for( size_t ixt=0 ; ixt < xt_ix.size() ; ++ixt ) { int jt=xt_ix[ixt]; if( jt < 0 ) continue; // passed already a check //split at comma xt_a = xt[jt] ; // compare the names of the auxiliaries if( xf_a[0] != xt_a[0] ) continue; // found identical auxiliaries isAddAux=false; // scan the attributes for( size_t ifa=1 ; ifa < xf_a.size() ; ++ifa ) { // split at '=' xf_eq = xf_a[ifa] ; bool isAddAtt=true; for( size_t ita=1 ; ita < xt_a.size() ; ++ita ) { // split at '=' xt_eq = xt_a[ita] ; if( xt_eq[0] == xf_eq[0] ) // found identical attribute names { isAddAtt=false; break; } } if( isAddAtt ) { status=true; // additional attribute of auxiliary in the file std::string key("8_6"); if( notes->inq( key, dataVar.name ) ) { std::string capt; if( xt_a[0].substr(0,4) == "aux=" ) { capt = "auxiliary "; capt += hdhC::tf_var(xf_a[0].substr(4), hdhC::colon) ; } else capt += hdhC::tf_var(xf_a[0], hdhC::colon) ; if( xt_eq[0] == "values" ) { capt += "additional data across experiments or sub-temporal files"; } else { capt += hdhC::tf_att(xf_eq[0]); capt += "is new across experiments or sub-temporal files"; } (void) notes->operate(capt) ; notes->setCheckMetaStr( "FAIL" ); } } } } if( isAddAux ) { status=true; std::string key("8_5"); if( notes->inq( key, dataVar.name) ) { std::string capt("additional auxiliary "); if( xf_a[0].size() > 4 ) capt += hdhC::tf_var(xf_a[0].substr(4)) ; else capt += hdhC::tf_var(xf_a[0]) ; capt += "across experiments or sub-temporal files"; (void) notes->operate(capt) ; notes->setCheckMetaStr( "FAIL" ); } } } return false; }
string DU_File::load2str(const string &sFullFileName) { ifstream ifs(sFullFileName.c_str()); return string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>()); }
void AircraftProperties::load(){ rotor.load(); std::ifstream ifs("/home/ken/UAVdata.csv"); if(!ifs){ std::cout<<"READ ERROR"<<std::endl; return; } std::string str; std::vector<double> aircraft_data; while(getline(ifs,str)){ std::istringstream stream(str); double val; stream >> val; aircraft_data.push_back(val); } I.xx = 0.008445; I.yy = 0.01011; I.zz = 0.004132; C.L0 = aircraft_data[0]; C.D0 = aircraft_data[1]; C.m0 = aircraft_data[2]; C.L.a = aircraft_data[3]; C.D.a = aircraft_data[4]; C.C.a = aircraft_data[5]; C.l.a = aircraft_data[6]; C.m.a = aircraft_data[7]; C.n.a = aircraft_data[8]; C.L.b = aircraft_data[9]; C.D.b = aircraft_data[10]; C.C.b = aircraft_data[11]; C.l.b = -aircraft_data[12]; C.m.b = aircraft_data[13]; C.n.b = -aircraft_data[14]; C.L.p = aircraft_data[15]; C.D.p = aircraft_data[16]; C.C.p = -aircraft_data[17]; C.l.p = aircraft_data[18]; C.m.p = aircraft_data[19]; C.n.p = -aircraft_data[20]; C.L.q = aircraft_data[21]; C.D.q = aircraft_data[22]; C.C.q = aircraft_data[23]; C.l.q = aircraft_data[24]; C.m.q = aircraft_data[25]; C.n.q = aircraft_data[26]; C.L.r = aircraft_data[27]; C.D.r = aircraft_data[28]; C.C.r = -aircraft_data[29]; C.l.r = aircraft_data[30]; C.m.r = aircraft_data[31]; C.n.r = aircraft_data[32]; C.L.de = aircraft_data[33]; C.D.de = aircraft_data[34]; C.C.de = aircraft_data[35]; C.l.de = aircraft_data[36]; C.m.de = aircraft_data[37]; C.n.de = aircraft_data[38]; C.L.da = aircraft_data[39]; C.D.da = aircraft_data[40]; C.C.da = aircraft_data[41]; C.l.da = aircraft_data[42]; C.m.da = aircraft_data[43]; C.n.da = aircraft_data[44]; C.L.dr = aircraft_data[45]; C.D.dr = aircraft_data[46]; C.C.dr = aircraft_data[47]; C.l.dr = aircraft_data[48]; C.m.dr = aircraft_data[49]; C.n.dr = aircraft_data[50]; T_arm = aircraft_data[51]; mass = aircraft_data[52]; Sref = aircraft_data[53]; Bref = aircraft_data[54]; Cref = aircraft_data[55]; Uref = aircraft_data[56]; }
IfStatement if_(const BoolExpression &exp) { IfStatement ifs(this); ifs.condition(exp); return ifs; }
void talk(const std::string& filename = "data.dat", const std::string& title = "CMSSM spectrum generator run-time") { std::ifstream ifs(filename.c_str()); std::string line; if (!ifs.good()) { cout << "Error: could not open file: " << filename << endl; return; } const int NSG = 5; const double range_start = 0., range_stop = 0.7; TH1D* combined[NSG]; TH1D* valid[NSG]; TH1D* invalid[NSG]; ULong64_t integral_valid[NSG]; ULong64_t integral_invalid[NSG]; ULong64_t integral_combined[NSG]; combined[0] = new TH1D("combined[0]", "Softsusy 3.6.2" , 20, range_start, range_stop); combined[1] = new TH1D("combined[1]", "FlexibleSUSY-CMSSM" , 20, range_start, range_stop); combined[2] = new TH1D("combined[2]", "SPheno 3.3.7" , 20, range_start, range_stop); combined[3] = new TH1D("combined[3]", "SPhenoMSSM" , 20, range_start, range_stop); combined[4] = new TH1D("combined[4]", "FlexibleSUSY-CMSSMNoFV", 20, range_start, range_stop); valid[0] = new TH1D("valid[0]", "Softsusy 3.6.2" , 20, range_start, range_stop); valid[1] = new TH1D("valid[1]", "FlexibleSUSY-CMSSM 1.2.0" , 20, range_start, range_stop); valid[2] = new TH1D("valid[2]", "SPheno 3.3.7" , 20, range_start, range_stop); valid[3] = new TH1D("valid[3]", "SPhenoMSSM 3.3.7/4.5.8" , 20, range_start, range_stop); valid[4] = new TH1D("valid[4]", "FlexibleSUSY-CMSSMNoFV 1.2.0", 20, range_start, range_stop); invalid[0] = new TH1D("invalid[0]", "Softsusy" , 20, range_start, range_stop); invalid[1] = new TH1D("invalid[1]", "FlexibleSUSY-CMSSM" , 20, range_start, range_stop); invalid[2] = new TH1D("invalid[2]", "SPheno" , 20, range_start, range_stop); invalid[3] = new TH1D("invalid[3]", "SPhenoMSSM" , 20, range_start, range_stop); invalid[4] = new TH1D("invalid[4]", "FlexibleSUSY-CMSSMNoFV", 20, range_start, range_stop); for (int i = 0; i < NSG; i++) { combined[i]->SetStats(0); valid[i]->SetStats(0); invalid[i]->SetStats(0); } // initialize integrals for (int i = 0; i < NSG; i++) { integral_valid[i] = 0; integral_invalid[i] = 0; integral_combined[i] = 0; } while (getline(ifs,line)) { std::istringstream input(line); std::string word; input >> word; if (word != "" && word[0] != '#') { std::istringstream kk(line); double m0, m12, tanb, sgnmu, a0; double time[NSG]; int error[NSG]; kk >> m0 >> m12 >> tanb >> sgnmu >> a0; for (int i = 0; i < NSG; i++) { try { kk >> time[i] >> error[i]; } catch (...) { cout << "Error: time and error are not convertible for" " spectrum generator " << i << endl; } } for (int i = 0; i < NSG; i++) { combined[i]->Fill(time[i]); integral_combined[i]++; if (error[i] == 0) { valid[i]->Fill(time[i]); integral_valid[i]++; } else { invalid[i]->Fill(time[i]); integral_invalid[i]++; } } } }
/********************************************************************* * * chkpt_m::backward_scan_log(lock_heap) * * Scans the log backwards, starting from _lsn until the t_chkpt_begin log record * corresponding to the latest completed checkpoint. * *********************************************************************/ void chkpt_t::scan_log() { init(); lsn_t scan_start = smlevel_0::log->durable_lsn(); if (scan_start == lsn_t(1,0)) { return; } log_i scan(*smlevel_0::log, scan_start, false); // false == backward scan logrec_t r; lsn_t lsn = lsn_t::max; // LSN of the retrieved log record // Set when scan finds begin of previous checkpoint lsn_t scan_stop = lsn_t(1,0); // CS TODO: not needed with file serialization // bool insideChkpt = false; while (lsn > scan_stop && scan.xct_next(lsn, r)) { if (r.is_skip() || r.type() == logrec_t::t_comment) { continue; } if (!r.tid().is_null()) { if (r.tid() > get_highest_tid()) { set_highest_tid(r.tid()); } if (r.is_page_update() || r.is_cpsn()) { mark_xct_active(r.tid(), lsn, lsn); if (is_xct_active(r.tid())) { if (!r.is_cpsn()) { acquire_lock(r); } } else if (r.xid_prev().is_null()) { // We won't see this xct again -- delete it delete_xct(r.tid()); } } } if (r.is_page_update()) { w_assert0(r.is_redo()); mark_page_dirty(r.pid(), lsn, lsn); if (r.is_multi_page()) { w_assert0(r.pid2() != 0); mark_page_dirty(r.pid2(), lsn, lsn); } } switch (r.type()) { case logrec_t::t_chkpt_begin: // CS TODO: not needed with file serialization // if (insideChkpt) { // // Signal to stop backward log scan loop now // scan_stop = lsn; // } { fs::path fpath = smlevel_0::log->get_storage()->make_chkpt_path(lsn); if (fs::exists(fpath)) { ifstream ifs(fpath.string(), ios::binary); deserialize_binary(ifs); ifs.close(); scan_stop = lsn; } } break; case logrec_t::t_chkpt_bf_tab: // CS TODO: not needed with file serialization // if (insideChkpt) { // const chkpt_bf_tab_t* dp = (chkpt_bf_tab_t*) r.data(); // for (uint i = 0; i < dp->count; i++) { // mark_page_dirty(dp->brec[i].pid, dp->brec[i].page_lsn, // dp->brec[i].rec_lsn); // } // } break; case logrec_t::t_chkpt_xct_lock: // CS TODO: not needed with file serialization // if (insideChkpt) { // const chkpt_xct_lock_t* dp = (chkpt_xct_lock_t*) r.data(); // if (is_xct_active(dp->tid)) { // for (uint i = 0; i < dp->count; i++) { // add_lock(dp->tid, dp->xrec[i].lock_mode, // dp->xrec[i].lock_hash); // } // } // } break; case logrec_t::t_chkpt_xct_tab: // CS TODO: not needed with file serialization // if (insideChkpt) { // const chkpt_xct_tab_t* dp = (chkpt_xct_tab_t*) r.data(); // for (size_t i = 0; i < dp->count; ++i) { // tid_t tid = dp->xrec[i].tid; // w_assert1(!tid.is_null()); // mark_xct_active(tid, dp->xrec[i].first_lsn, // dp->xrec[i].last_lsn); // } // } break; // CS TODO: not needed with file serialization // case logrec_t::t_chkpt_end: // checkpoints should not run concurrently // w_assert0(!insideChkpt); // insideChkpt = true; break; // CS TODO: why do we need this? Isn't it related to 2PC? // case logrec_t::t_xct_freeing_space: case logrec_t::t_xct_end: case logrec_t::t_xct_abort: mark_xct_ended(r.tid()); break; case logrec_t::t_xct_end_group: { // CS TODO: is this type of group commit still used? w_assert0(false); const xct_list_t* list = (xct_list_t*) r.data(); uint listlen = list->count; for(uint i=0; i<listlen; i++) { tid_t tid = list->xrec[i].tid; mark_xct_ended(tid); } } break; case logrec_t::t_page_write: { char* pos = r.data(); PageID pid = *((PageID*) pos); pos += sizeof(PageID); lsn_t clean_lsn = *((lsn_t*) pos); pos += sizeof(lsn_t); uint32_t count = *((uint32_t*) pos); PageID end = pid + count; while (pid < end) { mark_page_clean(pid, clean_lsn); pid++; } } break; case logrec_t::t_add_backup: { const char* dev = (const char*)(r.data_ssx()); add_backup(dev); } break; case logrec_t::t_chkpt_backup_tab: // CS TODO break; case logrec_t::t_restore_begin: case logrec_t::t_restore_end: case logrec_t::t_restore_segment: case logrec_t::t_chkpt_restore_tab: // CS TODO - IMPLEMENT! break; default: break; } //switch } //while w_assert0(lsn == scan_stop); cleanup(); }
void TestArchiveAlarcon2004OxygenBasedCellCycleModels() { OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "Alarcon2004OxygenBasedCellCycleModel.arch"; // Set up oxygen_concentration double oxygen_concentration = 1.0; { // We must set up SimulationTime to avoid memory leaks SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0, 1); // As usual, we archive via a pointer to the most abstract class possible AbstractCellCycleModel* const p_model = new Alarcon2004OxygenBasedCellCycleModel; p_model->SetDimension(1); p_model->SetBirthTime(-1.5); static_cast<Alarcon2004OxygenBasedCellCycleModel*>(p_model)->SetDt(0.085); // We must create a cell to be able to initialise the cell cycle model's ODE system MAKE_PTR(WildTypeCellMutationState, p_healthy_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); CellPtr p_cell(new Cell(p_healthy_state, p_model)); p_cell->SetCellProliferativeType(p_stem_type); p_cell->GetCellData()->SetItem("oxygen", oxygen_concentration); p_cell->InitialiseCellCycleModel(); std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); output_arch << p_model; // Note that here, deletion of the cell-cycle model is handled by the cell destructor SimulationTime::Destroy(); } { // We must set SimulationTime::mStartTime here to avoid tripping an assertion SimulationTime::Instance()->SetStartTime(0.0); AbstractCellCycleModel* p_model2; std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); input_arch >> p_model2; TS_ASSERT_EQUALS(p_model2->GetDimension(), 1u); TS_ASSERT_DELTA(p_model2->GetBirthTime(), -1.5, 1e-12); TS_ASSERT_DELTA(static_cast<Alarcon2004OxygenBasedCellCycleModel*>(p_model2)->GetDt(), 0.085, 1e-3); Alarcon2004OxygenBasedCellCycleModel* p_static_cast_model = static_cast<Alarcon2004OxygenBasedCellCycleModel*>(p_model2); Alarcon2004OxygenBasedCellCycleOdeSystem* p_ode_system = static_cast<Alarcon2004OxygenBasedCellCycleOdeSystem*>(p_static_cast_model->GetOdeSystem()); TS_ASSERT(p_ode_system != NULL); TS_ASSERT_EQUALS(p_ode_system->IsLabelled(), false); // Avoid memory leaks delete p_model2; } }
bool INI::load(string sFile) { ifstream ifs(sFile.c_str()); if(!ifs.is_open()) { cout << "error: cannot load ini file:" << sFile << endl; return false; } string line; string section; while(getline(ifs,line)) { // empty line. if(line.size() == 0) { INISortedEntry* se = new INISortedEntry("", INI_NEW_LINE); sorted_entries.push_back(se); continue; } // get key string key; int key_end = 0; for(int i = 0; i < line.size(); ++i) { if(line[i] == '=') { key_end = i+1; break; } else { if(line[i] != ' ') { key.push_back(line[i]); } } } // is it a comment? if(key.at(0) == '#') { INISortedEntry* sorted_entry = new INISortedEntry(line, INI_COMMENT); sorted_entries.push_back(sorted_entry); continue; } // is key a section? if(key.at(0) == '[') { section = ""; for(int i = 0; i < key.size(); ++i) { if(key[i] != '[' && key[i] != ']' && key[i] != 0x0D && key[i] != 0x0A) { section.push_back(key[i]); } } continue; } // get value. string val; for(int i = key_end; i < line.size(); ++i) { if(line[i] == '\r' || line[i] == '\n') { break; } val.push_back(line[i]); } // trim string key_copy = key; if(section != "") { key = "." +key; } string dict_key = section + key; INIEntry* entry = new INIEntry(key_copy, val, section); dict.insert(pair<string,INIEntry*>(dict_key,entry)); INISortedEntry* sorted_entry = new INISortedEntry(dict_key, INI_ENTRY); sorted_entries.push_back(sorted_entry); } return true; }
/* XWinManaged xwin(Dims(WIDTH,HEIGHT*2), 1, 1, "Test SIFT"); rutz::shared_ptr<VisualObject> objTop, objBottom; void showObjs(rutz::shared_ptr<VisualObject> obj1, rutz::shared_ptr<VisualObject> obj2){ //return ; Image<PixRGB<byte> > keyIma = rescale(obj1->getKeypointImage(), WIDTH, HEIGHT); objTop = obj1; if (obj2.is_valid()){ keyIma = concatY(keyIma, rescale(obj2->getKeypointImage(), WIDTH, HEIGHT)); objBottom = obj2; } xwin.drawImage(keyIma); } void showKeypoint(rutz::shared_ptr<VisualObject> obj, int keypi, Keypoint::CHANNEL channel = Keypoint::ORI){ char winTitle[255]; switch(channel){ case Keypoint::ORI: sprintf(winTitle, "Keypoint view (Channel ORI)"); break; case Keypoint::COL: sprintf(winTitle, "Keypoint view (Channel COL)"); break; default: sprintf(winTitle, "Keypoint view (Channel )"); break; } rutz::shared_ptr<Keypoint> keyp = obj->getKeypoint(keypi); float x = keyp->getX(); float y = keyp->getY(); float s = keyp->getS(); float o = keyp->getO(); float m = keyp->getM(); uint FVlength = keyp->getFVlength(channel); if (FVlength<=0) return; //dont show the Keypoint if we dont have a FV XWinManaged *xwinKey = new XWinManaged(Dims(WIDTH*2,HEIGHT), -1, -1, winTitle); //draw the circle around the keypoint const float sigma = 1.6F * powf(2.0F, s / float(6 - 3)); const float sig = 1.5F * sigma; const int rad = int(3.0F * sig); Image<PixRGB<byte> > img = obj->getImage(); Point2D<int> loc(int(x + 0.5F), int(y + 0.5F)); drawCircle(img, loc, rad, PixRGB<byte>(255, 0, 0)); drawDisk(img, loc, 2, PixRGB<byte>(255,0,0)); s=s*5.0F; //mag for scale if (s > 0.0f) drawLine(img, loc, Point2D<int>(int(x + s * cosf(o) + 0.5F), int(y + s * sinf(o) + 0.5F)), PixRGB<byte>(255, 0, 0)); char info[255]; sprintf(info, "(%0.2f,%0.2f) s=%0.2f o=%0.2f m=%0.2f", x, y, s, o, m); writeText(img, Point2D<int>(0, HEIGHT-20), info, PixRGB<byte>(255), PixRGB<byte>(127)); //draw the vectors from the features vectors Image<PixRGB<byte> > fvDisp(WIDTH, HEIGHT, NO_INIT); fvDisp.clear(PixRGB<byte>(255, 255, 255)); int xBins = int((float)WIDTH/4); int yBins = int((float)HEIGHT/4); drawGrid(fvDisp, xBins, yBins, 1, 1, PixRGB<byte>(0, 0, 0)); switch (channel){ case Keypoint::ORI: for (int xx=0; xx<4; xx++){ for (int yy=0; yy<4; yy++){ for (int oo=0; oo<8; oo++){ Point2D<int> loc(xBins/2+(xBins*xx), yBins/2+(yBins*yy)); byte mag = keyp->getFVelement(xx*32+yy*8+oo, channel); mag = mag/4; drawDisk(fvDisp, loc, 2, PixRGB<byte>(255, 0, 0)); drawLine(fvDisp, loc, Point2D<int>(int(loc.i + mag*cosf(oo*M_PI/4)), int(loc.j + mag*sinf(oo*M_PI/4))), PixRGB<byte>(255, 0, 0)); } } } break; case Keypoint::COL: for (int xx=0; xx<4; xx++){ for (int yy=0; yy<4; yy++){ for (int cc=0; cc<3; cc++){ Point2D<int> loc(xBins/2+(xBins*xx), yBins/2+(yBins*yy)); byte mag = keyp->getFVelement(xx*12+yy*3+cc, channel); mag = mag/4; drawDisk(fvDisp, loc, 2, PixRGB<byte>(255, 0, 0)); drawLine(fvDisp, loc, Point2D<int>(int(loc.i + mag*cosf(-1*cc*M_PI/2)), int(loc.j + mag*sinf(-1*cc*M_PI/2))), PixRGB<byte>(255, 0, 0)); } } } break; default: break; } Image<PixRGB<byte> > disp = img; disp = concatX(disp, fvDisp); xwinKey->drawImage(disp); while(!xwinKey->pressedCloseButton()){ usleep(100); } delete xwinKey; } void analizeImage(){ int key = -1; while(key != 24){ // q to quit window key = xwin.getLastKeyPress(); Point2D<int> point = xwin.getLastMouseClick(); if (point.i > -1 && point.j > -1){ //get the right object rutz::shared_ptr<VisualObject> obj; if (point.j < HEIGHT){ obj = objTop; } else { obj = objBottom; point.j = point.j - HEIGHT; } LINFO("ClickInfo: key = %i, p=%i,%i", key, point.i, point.j); //find the keypoint for(uint i=0; i<obj->numKeypoints(); i++){ rutz::shared_ptr<Keypoint> keyp = obj->getKeypoint(i); float x = keyp->getX(); float y = keyp->getY(); if ( (point.i < (int)x + 5 && point.i > (int)x - 5) && (point.j < (int)y + 5 && point.j > (int)y - 5)){ showKeypoint(obj, i, Keypoint::ORI); showKeypoint(obj, i, Keypoint::COL); } } } } } */ int main(const int argc, const char **argv) { MYLOGVERB = LOG_INFO; ModelManager manager("Test SIFT"); nub::ref<InputFrameSeries> ifs(new InputFrameSeries(manager)); manager.addSubComponent(ifs); nub::ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager)); manager.addSubComponent(ofs); if (manager.parseCommandLine( (const int)argc, (const char**)argv, "<database file> <trainingLabel>", 2, 2) == false) return 0; manager.start(); Timer masterclock; // master clock for simulations Timer timer; const char *vdbFile = manager.getExtraArg(0).c_str(); const char *trainingLabel = manager.getExtraArg(1).c_str(); int numMatches = 0; //the number of correct matches int totalObjects = 0; //the number of objects presented to the network int uObjId = 0; //a unique obj id for sift bool train = false; //load the database file // if (!train) vdb.loadFrom(std::string(vdbFile)); while(1) { Image< PixRGB<byte> > inputImg; const FrameState is = ifs->updateNext(); if (is == FRAME_COMPLETE) break; //grab the images GenericFrame input = ifs->readFrame(); if (!input.initialized()) break; inputImg = input.asRgb(); totalObjects++; ofs->writeRGB(inputImg, "Input", FrameInfo("Input", SRC_POS)); if (train) { //add the object to the database char objName[255]; sprintf(objName, "%s_%i", trainingLabel, uObjId); uObjId++; rutz::shared_ptr<VisualObject> vo(new VisualObject(objName, "NULL", inputImg, Point2D<int>(-1,-1), std::vector<float>(), std::vector< rutz::shared_ptr<Keypoint> >(), USECOLOR)); vdb.addObject(vo); } else { //get the object classification std::string objName; std::string tmpName = matchObject(inputImg); int i = tmpName.find("_"); objName.assign(tmpName, 0, i); LINFO("Object name %s", objName.c_str()); printf("%i %s\n", ifs->frame(), objName.c_str()); if (objName == trainingLabel) numMatches++; //printf("objid %i:class %i:rate=%0.2f\n", // objData.description.c_str(), objData.id, cls, // (float)numMatches/(float)totalObjects); } } if (train) { printf("Trained on %i objects\n", totalObjects); printf("Object in db %i\n" , vdb.numObjects()); vdb.saveTo(std::string(vdbFile)); } else { printf("Classification Rate: %i/%i %0.2f\n", numMatches, totalObjects, (float)numMatches/(float)totalObjects); } }
bool VehicleParam::loadFromFile(std::string fileName) { std::ifstream ifs(fileName.c_str()); if (ifs.bad()) return false; //std paramer if (!readLine(ifs, "LinearDamping", m_sVehicleParam.LinearDamping)) return false; if (!readLine(ifs, "AngularDamping", m_sVehicleParam.AngularDamping)) return false;; if (!readLine(ifs, "MotorTorque", m_sVehicleParam.MotorTorque)) return false;; if (!readLine(ifs, "SteerAngleRange", m_sVehicleParam.SteerAngleRange)) return false;; if (!readLine(ifs, "SteerSpeed", m_sVehicleParam.SteerSpeed)) return false;; std::string str; for (int i=0;i<2;i++) { str = i==0 ? "Front" : "Rear"; for (int j=0;j<2;j++) { for (int k=0;k<5;k++) { std::string ttfStr = j==0 ? "LNG" : "LAT"; switch(k) { case 0: ttfStr += "extremumSlip"; break; case 1: ttfStr += "extremumValue"; break; case 2: ttfStr += "asymptoteSlip"; break; case 3: ttfStr += "asymptoteValue"; break; case 4: ttfStr += "stiffnessFactor"; } if ( !readLine(ifs, str + ttfStr, getTTF(i, j, k))) return false; } } //deal with suspension NxSpringDesc& sup = i == 0 ? m_sVehicleParam.FrontSuspension: m_sVehicleParam.RearSuspension; if (!readLine(ifs, str+"SuspensionSpring", sup.spring)) return false; if (!readLine(ifs, str+"SuspensionDamping", sup.damper)) return false; if (!readLine(ifs, str+"SuspensionTargetValue", sup.targetValue)) return false; float& supTra = i==0 ? m_sVehicleParam.FrontSuspensionTravel: m_sVehicleParam.RearSuspensionTravel; if (!readLine(ifs, str+"SuspensionTravel", supTra)) return false; } ifs.close(); return true; }
void RunHardwareDetection() { TIMER(L"RunHardwareDetection"); ScriptInterface scriptInterface("Engine", "HWDetect", g_ScriptRuntime); JSContext* cx = scriptInterface.GetContext(); JSAutoRequest rq(cx); scriptInterface.RegisterFunction<void, bool, &SetDisableAudio>("SetDisableAudio"); scriptInterface.RegisterFunction<void, bool, &SetDisableS3TC>("SetDisableS3TC"); scriptInterface.RegisterFunction<void, bool, &SetDisableShadows>("SetDisableShadows"); scriptInterface.RegisterFunction<void, bool, &SetDisableShadowPCF>("SetDisableShadowPCF"); scriptInterface.RegisterFunction<void, bool, &SetDisableAllWater>("SetDisableAllWater"); scriptInterface.RegisterFunction<void, bool, &SetDisableFancyWater>("SetDisableFancyWater"); scriptInterface.RegisterFunction<void, bool, &SetEnableGLSL>("SetEnableGLSL"); scriptInterface.RegisterFunction<void, bool, &SetEnablePostProc>("SetEnablePostProc"); scriptInterface.RegisterFunction<void, bool, &SetEnableSmoothLOS>("SetEnableSmoothLOS"); scriptInterface.RegisterFunction<void, std::string, &SetRenderPath>("SetRenderPath"); // Load the detection script: const wchar_t* scriptName = L"hwdetect/hwdetect.js"; CVFSFile file; if (file.Load(g_VFS, scriptName) != PSRETURN_OK) { LOGERROR("Failed to load hardware detection script"); return; } std::string code = file.DecodeUTF8(); // assume it's UTF-8 scriptInterface.LoadScript(scriptName, code); // Collect all the settings we'll pass to the script: // (We'll use this same data for the opt-in online reporting system, so it // includes some fields that aren't directly useful for the hwdetect script) JS::RootedValue settings(cx); scriptInterface.Eval("({})", &settings); scriptInterface.SetProperty(settings, "os_unix", OS_UNIX); scriptInterface.SetProperty(settings, "os_bsd", OS_BSD); scriptInterface.SetProperty(settings, "os_linux", OS_LINUX); scriptInterface.SetProperty(settings, "os_android", OS_ANDROID); scriptInterface.SetProperty(settings, "os_macosx", OS_MACOSX); scriptInterface.SetProperty(settings, "os_win", OS_WIN); scriptInterface.SetProperty(settings, "arch_ia32", ARCH_IA32); scriptInterface.SetProperty(settings, "arch_amd64", ARCH_AMD64); scriptInterface.SetProperty(settings, "arch_arm", ARCH_ARM); scriptInterface.SetProperty(settings, "arch_aarch64", ARCH_AARCH64); #ifdef NDEBUG scriptInterface.SetProperty(settings, "build_debug", 0); #else scriptInterface.SetProperty(settings, "build_debug", 1); #endif scriptInterface.SetProperty(settings, "build_opengles", CONFIG2_GLES); scriptInterface.SetProperty(settings, "build_datetime", std::string(__DATE__ " " __TIME__)); scriptInterface.SetProperty(settings, "build_revision", std::wstring(svn_revision)); scriptInterface.SetProperty(settings, "build_msc", (int)MSC_VERSION); scriptInterface.SetProperty(settings, "build_icc", (int)ICC_VERSION); scriptInterface.SetProperty(settings, "build_gcc", (int)GCC_VERSION); scriptInterface.SetProperty(settings, "build_clang", (int)CLANG_VERSION); scriptInterface.SetProperty(settings, "gfx_card", gfx::CardName()); scriptInterface.SetProperty(settings, "gfx_drv_ver", gfx::DriverInfo()); scriptInterface.SetProperty(settings, "snd_card", std::wstring(snd_card)); scriptInterface.SetProperty(settings, "snd_drv_ver", std::wstring(snd_drv_ver)); ReportGLLimits(scriptInterface, settings); scriptInterface.SetProperty(settings, "video_xres", g_VideoMode.GetXRes()); scriptInterface.SetProperty(settings, "video_yres", g_VideoMode.GetYRes()); scriptInterface.SetProperty(settings, "video_bpp", g_VideoMode.GetBPP()); scriptInterface.SetProperty(settings, "video_desktop_xres", g_VideoMode.GetDesktopXRes()); scriptInterface.SetProperty(settings, "video_desktop_yres", g_VideoMode.GetDesktopYRes()); scriptInterface.SetProperty(settings, "video_desktop_bpp", g_VideoMode.GetDesktopBPP()); scriptInterface.SetProperty(settings, "video_desktop_freq", g_VideoMode.GetDesktopFreq()); struct utsname un; uname(&un); scriptInterface.SetProperty(settings, "uname_sysname", std::string(un.sysname)); scriptInterface.SetProperty(settings, "uname_release", std::string(un.release)); scriptInterface.SetProperty(settings, "uname_version", std::string(un.version)); scriptInterface.SetProperty(settings, "uname_machine", std::string(un.machine)); #if OS_LINUX { std::ifstream ifs("/etc/lsb-release"); if (ifs.good()) { std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); scriptInterface.SetProperty(settings, "linux_release", str); } } #endif scriptInterface.SetProperty(settings, "cpu_identifier", std::string(cpu_IdentifierString())); scriptInterface.SetProperty(settings, "cpu_frequency", os_cpu_ClockFrequency()); scriptInterface.SetProperty(settings, "cpu_pagesize", (u32)os_cpu_PageSize()); scriptInterface.SetProperty(settings, "cpu_largepagesize", (u32)os_cpu_LargePageSize()); scriptInterface.SetProperty(settings, "cpu_numprocs", (u32)os_cpu_NumProcessors()); #if ARCH_X86_X64 scriptInterface.SetProperty(settings, "cpu_numpackages", (u32)topology::NumPackages()); scriptInterface.SetProperty(settings, "cpu_coresperpackage", (u32)topology::CoresPerPackage()); scriptInterface.SetProperty(settings, "cpu_logicalpercore", (u32)topology::LogicalPerCore()); scriptInterface.SetProperty(settings, "cpu_numcaches", (u32)topology::NumCaches()); #endif scriptInterface.SetProperty(settings, "numa_numnodes", (u32)numa_NumNodes()); scriptInterface.SetProperty(settings, "numa_factor", numa_Factor()); scriptInterface.SetProperty(settings, "numa_interleaved", numa_IsMemoryInterleaved()); scriptInterface.SetProperty(settings, "ram_total", (u32)os_cpu_MemorySize()); scriptInterface.SetProperty(settings, "ram_total_os", (u32)os_cpu_QueryMemorySize()); scriptInterface.SetProperty(settings, "ram_free", (u32)os_cpu_MemoryAvailable()); #if ARCH_X86_X64 scriptInterface.SetProperty(settings, "x86_frequency", x86_x64::ClockFrequency()); scriptInterface.SetProperty(settings, "x86_vendor", (u32)x86_x64::Vendor()); scriptInterface.SetProperty(settings, "x86_model", (u32)x86_x64::Model()); scriptInterface.SetProperty(settings, "x86_family", (u32)x86_x64::Family()); u32 caps0, caps1, caps2, caps3; x86_x64::GetCapBits(&caps0, &caps1, &caps2, &caps3); scriptInterface.SetProperty(settings, "x86_caps[0]", caps0); scriptInterface.SetProperty(settings, "x86_caps[1]", caps1); scriptInterface.SetProperty(settings, "x86_caps[2]", caps2); scriptInterface.SetProperty(settings, "x86_caps[3]", caps3); JS::RootedValue tmpVal(cx); ConvertCaches(scriptInterface, x86_x64::L1I, &tmpVal); scriptInterface.SetProperty(settings, "x86_icaches", tmpVal); ConvertCaches(scriptInterface, x86_x64::L1D, &tmpVal); scriptInterface.SetProperty(settings, "x86_dcaches", tmpVal); ConvertTLBs(scriptInterface, &tmpVal); scriptInterface.SetProperty(settings, "x86_tlbs", tmpVal); #endif scriptInterface.SetProperty(settings, "timer_resolution", timer_Resolution()); // Send the same data to the reporting system g_UserReporter.SubmitReport("hwdetect", 11, scriptInterface.StringifyJSON(&settings, false)); // Run the detection script: JS::RootedValue global(cx, scriptInterface.GetGlobalObject()); scriptInterface.CallFunctionVoid(global, "RunHardwareDetection", settings); }
bool PhaseEstimator::LoadPhaseEstimationTrainSubset(const string& phase_file_name) { Json::Value json, temp_value; ifstream ifs(phase_file_name.c_str()); if (ifs.fail()) { cerr << "PhaseEstimator ERROR: Unable to load phase estimates from file: " << phase_file_name << endl; return false; } ifs >> json; ifs.close(); if (json["TrainSubset"].isNull()) { cerr << "PhaseEstimator WARNING: No TrainSubset available in file: " << phase_file_name << endl; return false; } train_subset_count_ = json["TrainSubset"]["TrainSubsetCount"].asInt(); if(train_subset_count_ < 1) { cerr << "PhaseEstimator ERROR: TrainSubsetCount in file " << phase_file_name << " is less than 1." << endl; return false; } else if ((int)json["TrainSubset"]["CFbyRegion"].size() != train_subset_count_ or (int)json["TrainSubset"]["IEbyRegion"].size() != train_subset_count_ or (int)json["TrainSubset"]["CFbyRegion"].size() != train_subset_count_){ cerr << "PhaseEstimator ERROR: Number of array elements in regions in does not match TrainSubsetCount." << endl; train_subset_count_ = 0; return false; } train_subset_cf_.resize(train_subset_count_); train_subset_ie_.resize(train_subset_count_); train_subset_dr_.resize(train_subset_count_); train_subset_regions_y_.resize(train_subset_count_); train_subset_regions_x_.resize(train_subset_count_); for(int i = 0; i < train_subset_count_; ++i) { train_subset_regions_y_[i] = json["TrainSubset"]["RegionRows"][i].asInt(); train_subset_regions_x_[i] = json["TrainSubset"]["RegionCols"][i].asInt(); int n = train_subset_regions_y_[i] * train_subset_regions_x_[i]; if (n==0 or (int)json["TrainSubset"]["CFbyRegion"][i].size() != n or (int)json["TrainSubset"]["IEbyRegion"][i].size() != n or (int)json["TrainSubset"]["DRbyRegion"][i].size() != n ){ cerr << "PhaseEstimator ERROR: Unexpected number of array elements for TrainSubset "<< i <<"." << endl; train_subset_count_ = 0; return false; } vector<float> cf; vector<float> ie; vector<float> dr; for(int j = 0; j < n; ++j) { cf.push_back(json["TrainSubset"]["CFbyRegion"][i][j].asFloat()); ie.push_back(json["TrainSubset"]["IEbyRegion"][i][j].asFloat()); dr.push_back(json["TrainSubset"]["DRbyRegion"][i][j].asFloat()); } train_subset_cf_[i] = cf; train_subset_ie_[i] = ie; train_subset_dr_[i] = dr; } // Transfer one of the train subsets to the results structure result_regions_y_ = train_subset_regions_y_[train_subset_count_ - 1]; result_regions_x_ = train_subset_regions_x_[train_subset_count_ - 1]; result_cf_ = train_subset_cf_[train_subset_count_ - 1]; result_ie_ = train_subset_ie_[train_subset_count_ - 1]; result_dr_ = train_subset_dr_[train_subset_count_ - 1]; average_cf_ = 0; average_ie_ = 0; average_dr_ = 0; int count = 0; for (int r = 0; r < result_regions_x_*result_regions_y_; r++) { if (result_cf_[r] || result_ie_[r] || result_dr_[r]) { average_cf_ += result_cf_[r]; average_ie_ += result_ie_[r]; average_dr_ += result_dr_[r]; count++; } } if (count > 0) { average_cf_ /= count; average_ie_ /= count; average_dr_ /= count; } cout << "PhaseEstimator: Successfully loaded phase estimates from file: " << phase_file_name << endl; return true; }
bool Sketch::loadVect(const char *path) { for (unsigned int i = 0; i < strokes_.size(); ++i) delete strokes_[i]; strokes_.clear(); delete active_polyline_; active_polyline_ = NULL; std::ifstream ifs(path); if (!ifs) { std::cerr << "Error: could not open sketch file for reading at " << path << "\n" << std::flush; return false; } else { bool succeded = false; std::string buffer; ifs >> buffer; if (buffer.compare("VECT") != 0) { std::cerr << "Error: This VECT is invalid since it does not starts with VECT" << "\n" << std::flush; succeded = false; } else { int num_strokes, total_num_points, num_colors; ifs >> num_strokes >> total_num_points >> num_colors; std::vector<int> stroke_point_counts(num_strokes, 0); for (int i = 0; i < num_strokes; ++i) ifs >> stroke_point_counts[i]; int color_count; for (int i = 0; i < num_strokes; ++i) ifs >> color_count; for (int i = 0; i < num_strokes; ++i) { Stroke *new_stroke = new Stroke (); new_stroke->read_text(ifs, stroke_point_counts[i]); addStroke(new_stroke); } //get colors int color[4]; for (int i = 0; i < num_colors; ++i) ifs >> color[0] >> color[1] >> color[2] >> color[3]; //get view frame camera_info_.read_text(ifs); // ifs >> view_position_[0] >> view_position_[1] >> view_position_[2]; // ifs >> view_direction_[0] >> view_direction_[1] >> view_direction_[2]; succeded = true; } ifs.close(); return succeded; } }
int main(int argc, char *argv[]) { setbuf(stdout, NULL); uint16_t nfiles = 0; uint8_t filter_systemid = 0xFF, filter_tmtype = 0xFF; bool filter_events = false; bool save_packets = false; char outfile[256]; for(int i = 1; i < argc; i++) { if(argv[i][0] == '-') { for(int j = 1; argv[i][j] != 0; j++) { switch(argv[i][j]) { case 'e': filter_events = true; j = strlen(&argv[i][0]) - 1; break; case 'f': if(argv[i][j+1] == 's') filter_systemid = atoi(&argv[i][j+2]); if(argv[i][j+1] == 't') filter_tmtype = atoi(&argv[i][j+2]); j = strlen(&argv[i][0]) - 1; break; case 'o': save_packets = true; strncpy(outfile, &argv[i][j+1], 256); outfile[255] = 0; j = strlen(&argv[i][0]) - 1; break; case '?': help_message(argv[0]); return -1; default: std::cerr << "Unknown option, use -? to list options\n"; return -1; } } } else { nfiles++; } } if(nfiles == 0) { help_message(argv[0]); return -1; } std::streampos cur; uint8_t buffer[TELEMETRY_PACKET_MAX_SIZE]; buffer[0] = 0x90; uint16_t length; uint32_t count[256][256]; uint32_t bad_checksum[256][256]; uint64_t amount[256][256]; uint16_t previous_frame_counter[256][256]; uint32_t gaps[256][256]; Clock first_systemtime = 0, last_systemtime = 0; bool not_coincident[16]; std::ofstream log; if (save_packets) { log.open(outfile, std::ofstream::binary); } TelemetryPacket tp(NULL); for(int i = 1; i < argc; i++) { memset(count, 0, sizeof(count)); memset(bad_checksum, 0, sizeof(bad_checksum)); memset(amount, 0, sizeof(amount)); memset(previous_frame_counter, 0xFF, sizeof(previous_frame_counter)); memset(gaps, 0, sizeof(gaps)); first_systemtime = last_systemtime = 0; memset(not_coincident, 0, sizeof(not_coincident)); if(argv[i][0] != '-') { std::cout << "Inspecting " << argv[i] << std::endl; uint8_t percent_completed = 0; std::ifstream ifs(argv[i]); if(ifs.good()) { ifs.seekg(0, ifs.end); std::streampos size = ifs.tellg(); ifs.seekg(0, ifs.beg); std::cout << size << " bytes: "; std::cout.flush(); while (ifs.good()) { if(ifs.get() == 0x90) { if(ifs.peek() == 0xeb) { cur = ifs.tellg(); // points one byte into sync word ifs.seekg(5, std::ios::cur); ifs.read((char *)&length, 2); if(length > TELEMETRY_PACKET_MAX_SIZE-16) continue; //invalid payload size ifs.seekg(cur); ifs.read((char *)buffer+1, length+15); tp = TelemetryPacket(buffer, length+16); uint8_t this_systemid = tp.getSystemID(); uint8_t this_tmtype = tp.getTmType(); if(((!filter_events) || (((this_systemid & 0xF0) == 0x80) && (this_tmtype == 0xF3))) && ((filter_systemid == 0xFF) || (this_systemid == filter_systemid)) && ((filter_tmtype == 0xFF) || (this_tmtype == filter_tmtype))) { if(tp.valid()) { cur += length+15; count[this_systemid][this_tmtype]++; amount[this_systemid][this_tmtype] += length+16; uint16_t this_frame_counter = tp.getCounter(); int16_t frame_counter_difference = this_frame_counter - previous_frame_counter[this_systemid][this_tmtype]; if((previous_frame_counter[this_systemid][this_tmtype] != 0xFFFF) && (frame_counter_difference > 1)) { // Make an exception for quicklook spectrum packets if(!((frame_counter_difference == 6) && (this_systemid == 0x10) && ((this_tmtype & 0xF0) == 0x10))) { gaps[this_systemid][this_tmtype]++; } } previous_frame_counter[this_systemid][this_tmtype] = this_frame_counter; if(((this_systemid & 0xF0) == 0x80) && (this_tmtype == 0xF3)) { if(((buffer[19] == 0) && (buffer[20] == 0) && (buffer[21] == 0)) || ((buffer[22] == 0) && (buffer[23] == 0) && (buffer[24] == 0))) { not_coincident[this_systemid & 0x0F] = true; } } if(first_systemtime == 0) first_systemtime = tp.getSystemTime(); last_systemtime = tp.getSystemTime(); if(save_packets && log.is_open()) { log.write((char *)buffer, length+16); } } else { bad_checksum[this_systemid][tp.getTmType()]++; } } if((((uint64_t)ifs.tellg())*100/size) > percent_completed) { percent_completed++; printf("%3u%%\b\b\b\b", percent_completed); } ifs.seekg(cur); } } } ifs.close(); std::cout << "\nPacket breakdown:\n"; for(int j = 0; j < 256; j++) { for(int k = 0; k < 256; k++) { if(count[j][k] > 0) { printf(" 0x%02x 0x%02x : [%4.1f%%] %lu", j, k, 100. * amount[j][k] / size, count[j][k]); if(((j & 0xF0) == 0x80) && (k == 0xF3) && not_coincident[j & 0x0F]) { printf(" (includes non-coincident data!)"); } if(bad_checksum[j][k] > 0) { printf(", plus %lu with bad checksums", bad_checksum[j][k]); } if(gaps[j][k] > 0) { printf(", plus %lu gaps", gaps[j][k]); } printf("\n"); } } } printf("Elapsed gondola time: %llu (%f minutes)\n\n", last_systemtime - first_systemtime, (last_systemtime - first_systemtime) * 1e-7 / 60); } } } if(save_packets && log.is_open()) { log.close(); } return 0; }
ifstream::pos_type DU_File::getFileSize(const string &sFullFileName) { ifstream ifs(sFullFileName.c_str()); ifs.seekg(0, ios_base::end); return ifs.tellg(); }
static bool HandleDebugSendOpcodeCommand(ChatHandler* handler, char const* /*args*/) { Unit* unit = handler->getSelectedUnit(); Player* player = NULL; if (!unit || (unit->GetTypeId() != TYPEID_PLAYER)) player = handler->GetSession()->GetPlayer(); else player = (Player*)unit; if (!unit) unit = player; std::ifstream ifs("opcode.txt"); if (ifs.bad()) return false; // remove comments from file std::stringstream parsedStream; while (!ifs.eof()) { char commentToken[2]; ifs.get(commentToken[0]); if (commentToken[0] == '/' && !ifs.eof()) { ifs.get(commentToken[1]); // /* comment if (commentToken[1] == '*') { while (!ifs.eof()) { ifs.get(commentToken[0]); if (commentToken[0] == '*' && !ifs.eof()) { ifs.get(commentToken[1]); if (commentToken[1] == '/') break; else ifs.putback(commentToken[1]); } } continue; } // line comment else if (commentToken[1] == '/') { std::string str; getline(ifs, str); continue; } // regular data else ifs.putback(commentToken[1]); } parsedStream.put(commentToken[0]); } ifs.close(); uint32 opcode; parsedStream >> opcode; WorldPacket data(opcode, 0); while (!parsedStream.eof()) { std::string type; parsedStream >> type; if (type == "") break; if (type == "uint8") { uint16 val1; parsedStream >> val1; data << uint8(val1); } else if (type == "uint16")
errcode DSA1Intro::a_create(Config* config) { std::ofstream ofs_dir(config->archive_name.c_str(), std::ios::binary); if (!ofs_dir.good()) { cerror << "could not write archive directory '" << config->archive_name << "'" << std::endl; exit(1); } // Dateigrößen feststellen CmdlineList::iterator f = config->fileList.begin(); while (f != config->fileList.end()) { std::ifstream ifs(f->second.name.c_str(), std::ios::binary); if (ifs.good()) { f->second.size = filesize(ifs); f++; } else { std::cerr << "Warning: Could not open "<< f->second.name << std::endl; CmdlineList::iterator temp = f; temp++; config->fileList.erase(f); f = temp; } ifs.close(); } // Header schreiben readMaster(config->archive_name); synchronize(config->fileList); write(ofs_dir); ofs_dir.close(); // Dateien schreiben for(FileList::iterator f = entries.begin(); f != entries.end(); f++) { DSA1Intro_Entry* entry = dynamic_cast<DSA1Intro_Entry*>(*f); assert(entry != 0); Cmdline_Entry cmde = config->fileList.find(entry->name)->second; std::ifstream ifs(cmde.name.c_str(), std::ios::binary); std::fstream ofs; string volname = ""; if (ifs.good()) { /*if (volname != entry->volname) { if (ofs.is_open()) ofs.close(); ofs.open(entry->volname.c_str(), std::ios::binary); if (!ofs.good()) { cerror << "could not write archive volume '" << config->archive_name << "'" << std::endl; exit(-1); } }*/ // TODO: Dieser Modus (app) bereitet Schwierigkeiten beim Überschreiben. ofs.open(entry->volname.c_str(), std::ios::binary | std::ios::out | std::ios::in); if (!ofs.good()) { cerror << "could not write archive volume '" << config->archive_name << "'" << std::endl; exit(-1); } ifs.seekg(0); ofs.seekp(entry->offset, std::ios::beg); std::cout << "writing from " << cmde.name << ":"<<ifs.tellg()<< " to " << entry->volname << ":"<<entry->offset<<" ["<<entry->size <<"]"<< std::endl; copy(ifs, ofs, entry->size); ofs.close(); } else { std::cerr << "Error reading file »" << cmde.name <<"«"<< std::endl; exit(0); } ofs.close(); ifs.close(); } return ERR_OK; }
// ------------------------------------------------------------------------------------------ Config_V GetConfigVal(string filename,string name,bool dbg) { char t_str[SIZE]; char did[10]; char moduleType[10]; int mod,channel; int pre,post; int threshold,sampleRate,sampleSize,streamNumber,detectorChannel, fullscale,delay,thresholdSign,used; float offset; // calculate a crate number char crateString[25]; strcpy(crateString,name.c_str()); if (dbg) cout << "crate name: " << crateString; int length=strlen(crateString); if (crateString[length-1]==':') { // delete ':' crateString[length-1]=0; length--; } if (crateString[length-1]=='g') { // the hosts may have the ending 'g', e.g. 'pcntof19g' g=gigabit crateString[length-1]=0; length--; } int crate; crate=atoi(&crateString[length-2]); if ((crateString[length-4]!='p') && (crateString[length-4]!='P')) crate+=100; if (dbg) cout << " number: " << crate << endl; Channel_Config readoutConfig; Config_V rconf_v; ifstream ifs(filename.c_str()); if( !ifs ) { // open failed cerr << "cannot open file " << filename << endl; exit(-1); } string nameOff,detectoridOff; string::size_type pos; while ( ifs.getline(t_str,SIZE)) { if(dbg) cout << "-->" << t_str << endl; string line = t_str; if (line.find_first_of("#") != (string::size_type)0 ) { if((pos = line.find(name)) != string::npos ) { // fist we hunt the name identifier nameOff = line.substr(pos + name.size(),line.size()); sscanf(nameOff.c_str(),"%s%d%d%d%d%d%d%d%d%s%d%d%d%d%f%d", did,&streamNumber,&mod,&channel,&pre,&post, &threshold,&sampleRate,&sampleSize,moduleType, &fullscale,&detectorChannel,&delay, &thresholdSign,&offset,&used ); if(dbg) printf("nameOff %s\n",nameOff.c_str()); if(dbg) printf("got %s m: %d ch: %d pre: %d post: %d thr: %d dch: %d\n",did,mod,channel,pre,post,threshold,detectorChannel); memcpy(&readoutConfig.id,did,4); memcpy(&readoutConfig.moduleType,moduleType,4); readoutConfig.clockState=(readoutConfig.moduleType==ACQD_as_int) ? INTC_as_int : EXTC_as_int; readoutConfig.str_crate_mod_ch = (streamNumber<<24) + (crate<<16) + (mod << 8) + channel; readoutConfig.detectorChannel = detectorChannel; readoutConfig.fullScale = fullscale; readoutConfig.threshold = threshold; readoutConfig.thresholdSign = thresholdSign; readoutConfig.delayTime = delay; readoutConfig.offset= offset; readoutConfig.pre = pre; readoutConfig.post = post; readoutConfig.sampleRate = sampleRate; readoutConfig.sampleSize = sampleSize; if ((readoutConfig.moduleType!=NONE_as_int) && (strcmp(did,"*NO*")) && (used>0)) rconf_v.push_back( readoutConfig ); } } // if } // while if (rconf_v.size()==0) cout << "No config data found for pc " << name.c_str() << endl; return rconf_v; }
std::string LoadObj( std::vector<shape_t>& shapes, const char* filename, const char* mtl_basepath) { shapes.clear(); std::stringstream err; std::ifstream ifs(filename); if (!ifs) { err << "Cannot open file [" << filename << "]" << std::endl; return err.str(); } std::vector<float> v; std::vector<float> vn; std::vector<float> vt; std::vector<std::vector<vertex_index> > faceGroup; std::string name; // material std::map<std::string, material_t> material_map; material_t material; int maxchars = 8192; // Alloc enough size. std::vector<char> buf(maxchars); // Alloc enough size. while (ifs.peek() != -1) { ifs.getline(&buf[0], maxchars); std::string linebuf(&buf[0]); // Trim newline '\r\n' or '\r' if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // vertex if (token[0] == 'v' && isSpace((token[1]))) { token += 2; float x, y, z; parseFloat3(x, y, z, token); v.push_back(x); v.push_back(y); v.push_back(z); continue; } // normal if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) { token += 3; float x, y, z; parseFloat3(x, y, z, token); vn.push_back(x); vn.push_back(y); vn.push_back(z); continue; } // texcoord if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) { token += 3; float x, y; parseFloat2(x, y, token); vt.push_back(x); vt.push_back(y); continue; } // face if (token[0] == 'f' && isSpace((token[1]))) { token += 2; token += strspn(token, " \t"); std::vector<vertex_index> face; while (!isNewLine(token[0])) { vertex_index vi = parseTriple(token, v.size() / 3, vn.size() / 3, vt.size() / 2); face.push_back(vi); int n = strspn(token, " \t\r"); token += n; } faceGroup.push_back(face); continue; } // use mtl if ((0 == strncmp(token, "usemtl", 6)) && isSpace((token[6]))) { char namebuf[4096]; token += 7; sscanf(token, "%s", namebuf); if (material_map.find(namebuf) != material_map.end()) { material = material_map[namebuf]; } else { // { error!! material not found } InitMaterial(material); } continue; } // load mtl if ((0 == strncmp(token, "mtllib", 6)) && isSpace((token[6]))) { char namebuf[4096]; token += 7; sscanf(token, "%s", namebuf); std::string err_mtl = LoadMtl(material_map, namebuf, mtl_basepath); if (!err_mtl.empty()) { faceGroup.clear(); // for safety return err_mtl; } continue; } // group name if (token[0] == 'g' && isSpace((token[1]))) { // flush previous face group. shape_t shape; bool ret = exportFaceGroupToShape(shape, v, vn, vt, faceGroup, material, name); if (ret) { shapes.push_back(shape); } faceGroup.clear(); std::vector<std::string> names; while (!isNewLine(token[0])) { std::string str = parseString(token); names.push_back(str); token += strspn(token, " \t\r"); // skip tag } assert(names.size() > 0); // names[0] must be 'g', so skipt 0th element. if (names.size() > 1) { name = names[1]; } else { name = ""; } continue; } // object name if (token[0] == 'o' && isSpace((token[1]))) { // flush previous face group. shape_t shape; bool ret = exportFaceGroupToShape(shape, v, vn, vt, faceGroup, material, name); if (ret) { shapes.push_back(shape); } faceGroup.clear(); // @todo { multiple object name? } char namebuf[4096]; token += 2; sscanf(token, "%s", namebuf); name = std::string(namebuf); continue; } // Ignore unknown command. } shape_t shape; bool ret = exportFaceGroupToShape(shape, v, vn, vt, faceGroup, material, name); if (ret) { shapes.push_back(shape); } faceGroup.clear(); // for safety return err.str(); }
int main( int argc, char *argv[] ) { // try { time_t programStartTime(time(NULL) ); boost::filesystem::path workingDir( boost::filesystem::current_path() ); // ========== PROGRAM PARAMETERS ========== std::string progName( "buildctree" ); std::string configFilename( "/home/raid2/moreno/Code/hClustering/config/"+progName+".cfg" ); // program parameters std::string roiFilename, inputFolder, outputFolder, tempFolder; float memory( 0.5 ), maxNbDist( 1 ), relativeThreshold( 0 ); unsigned int nbLevel( 26 ), threads( 0 ); bool keepDiscarded( false ), niftiMode( true ), debug( false ), noLog( false ); TC_GROWTYPE growType( TC_GROWOFF ); size_t baseSize( 0 ); // Declare a group of options that will be allowed only on command line boost::program_options::options_description genericOptions( "Generic options" ); genericOptions.add_options() ( "version", "Program version" ) ( "help,h", "Produce extended program help message" ) ( "roi-file,r", boost::program_options::value< std::string >(&roiFilename), "file with the seed voxels coordinates." ) ( "inputf,I", boost::program_options::value< std::string >(&inputFolder), "input data folder (seed tractograms)." ) ( "tempf,T", boost::program_options::value< std::string >(&tempFolder), "temporal folder (for mean tractogram storage)." ) ( "outputf,O", boost::program_options::value< std::string >(&outputFolder), "output folder" ) ( "threshold,t", boost::program_options::value< float >(&relativeThreshold)->implicit_value(0), "[opt] noise threshold for the tractograms relative to number of streamlines per tract. [0,1)." ) ( "maxnbdist,d", boost::program_options::value< float >(&maxNbDist)->implicit_value(1), "[opt] maximum dissimilarity a seed voxel tract must have to its most similar neighbor not be discarded. (0,1]." ) ( "cnbhood,c", boost::program_options::value< unsigned int >(&nbLevel)->implicit_value(26), "[opt] centroid method neighborhood level. Valid values: 6, 18, 26(default), 32, 96, 124." ) ( "basesize,S", boost::program_options::value< size_t >(&baseSize), "[opt] grow homogeneous base nodes (meta-leaves) of size S. (>=2)." ) ( "basenum,N", boost::program_options::value< size_t >(&baseSize), "[opt] grow N homogeneous base nodes (meta-leaves). (>=10)." ) ( "nolog", "use only linear normalization (input tracts must be also linearly normalized)" ) ; // Declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description configOptions( "Configuration" ); configOptions.add_options() ( "verbose,v", "[opt] verbose output." ) ( "vista", "[opt] use vista file format (default is nifti)." ) ( "cache-mem,m", boost::program_options::value< float >(&memory)->implicit_value(0.5), "[opt] maximum of memory (in GBytes) to use for tractogram cache memory. Default: 0.5." ) ( "keep-disc,k", "[opt] keep discarded voxels data in a section of the tree file." ) ( "debugout", "[opt] write additional detailed outputs meant for debug." ) ( "pthreads,p", boost::program_options::value< unsigned int >(&threads), "[opt] number of processing cores to run the program in. Default: all available." ) ; // Hidden options, will be allowed both on command line and in config file, but will not be shown to the user. boost::program_options::options_description hiddenOptions( "Hidden options" ); //hiddenOptions.add_options() ; boost::program_options::options_description cmdlineOptions; cmdlineOptions.add(genericOptions).add(configOptions).add(hiddenOptions); boost::program_options::options_description configFileOptions; configFileOptions.add(configOptions).add(hiddenOptions); boost::program_options::options_description visibleOptions( "Allowed options" ); visibleOptions.add(genericOptions).add(configOptions); boost::program_options::positional_options_description posOpt; //this arguments do not need to specify the option descriptor when typed in //posOpt.add( "roi-file", -1); boost::program_options::variables_map variableMap; store(boost::program_options::command_line_parser(argc, argv).options(cmdlineOptions).positional(posOpt).run(), variableMap); std::ifstream ifs(configFilename.c_str() ); store(parse_config_file(ifs, configFileOptions), variableMap); notify( variableMap); if ( variableMap.count( "help" ) ) { std::cout << "---------------------------------------------------------------------------" << std::endl; std::cout << std::endl; std::cout << " Project: hClustering" << std::endl; std::cout << std::endl; std::cout << " Whole-Brain Connectivity-Based Hierarchical Parcellation Project" << std::endl; std::cout << " David Moreno-Dominguez" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " www.cbs.mpg.de/~moreno" << std::endl; std::cout << std::endl; std::cout << " For more reference on the underlying algorithm and research they have been used for refer to:" << std::endl; std::cout << " - Moreno-Dominguez, D., Anwander, A., & Knösche, T. R. (2014)." << std::endl; std::cout << " A hierarchical method for whole-brain connectivity-based parcellation." << std::endl; std::cout << " Human Brain Mapping, 35(10), 5000-5025. doi: http://dx.doi.org/10.1002/hbm.22528" << std::endl; std::cout << " - Moreno-Dominguez, D. (2014)." << std::endl; std::cout << " Whole-brain cortical parcellation: A hierarchical method based on dMRI tractography." << std::endl; std::cout << " PhD Thesis, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig." << std::endl; std::cout << " ISBN 978-3-941504-45-5" << std::endl; std::cout << std::endl; std::cout << " hClustering is free software: you can redistribute it and/or modify" << std::endl; std::cout << " it under the terms of the GNU Lesser General Public License as published by" << std::endl; std::cout << " the Free Software Foundation, either version 3 of the License, or" << std::endl; std::cout << " (at your option) any later version." << std::endl; std::cout << " http://creativecommons.org/licenses/by-nc/3.0" << std::endl; std::cout << std::endl; std::cout << " hClustering is distributed in the hope that it will be useful," << std::endl; std::cout << " but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl; std::cout << " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << std::endl; std::cout << " GNU Lesser General Public License for more details." << std::endl; std::cout << std::endl; std::cout << "---------------------------------------------------------------------------" << std::endl << std::endl; std::cout << "buildctree" << std::endl << std::endl; std::cout << "Build a centroid hierarchical tree from a set of seed voxels and their corresponding tractograms." << std::endl << std::endl; std::cout << "* Arguments:" << std::endl << std::endl; std::cout << " --version: Program version." << std::endl << std::endl; std::cout << " -h --help: produce extended program help message." << std::endl << std::endl; std::cout << " -r --roi-file: a text file with the seed voxel coordinates and the corresponding tractogram index (if tractogram naming is based on index rather than coordinates)." << std::endl << std::endl; std::cout << " -I --inputf: input data folder (containing the compact tractograms)." << std::endl << std::endl; std::cout << " -T --tempf: mean tractogram folder location for centroid method. Will be used as temporary storage for intermediate tractogram results." << std::endl << std::endl; std::cout << " -O --outputf: output folder where tree files will be written." << std::endl << std::endl; std::cout << "[-t --threshold]: number of streamlines relative to the total generated that must pass through a tract voxel to be considered for tract similarity" << std::endl; std::cout << " (i.e.: minimum value of a normalized probabilistic tract in natural units to be considered above noise)." << std::endl; std::cout << " Valid values: [0,1) Use a value of 0 (default) if no thresholding is desired." << std::endl << std::endl; std::cout << "[-d --maxnbdist]: maximum dissimilarity a seed voxel tract must have to its most similar neighbor not be discarded." << std::endl; std::cout << " Valid values: (0,1] Use a value of 1 (default) if no discarding is desired." << std::endl << std::endl; std::cout << "[-c --cnbhood]: use centroid method with C neighborhood level. Valid values: 6, 18, 24(default), 32, 96, 124." << std::endl << std::endl; std::cout << "[-S --basesize]: merge homogeneous base nodes of size S. (mutually exclusive with -N option). Default: 0 (no homogeneous merging)." << std::endl << std::endl; std::cout << "[-N --basenum]: grow N homogeneous base nodes. (mutually exclusive with -S option). Default: 0 (no homogeneous merging)." << std::endl << std::endl; std::cout << "[--nolog]: Use linear normalization. Use if input tracts are only linearly normalized instead of logarithmically normalized (assumed by default)." << std::endl << std::endl; std::cout << "[-v --verbose]: verbose output (recommended)." << std::endl << std::endl; std::cout << "[--vista]: read/write vista (.v) files [default is nifti (.nii) and compact (.cmpct) files]." << std::endl << std::endl; std::cout << "[-m --cache-mem]: maximum amount of RAM memory (in GBytes) to use for temporal tractogram cache storing. Valid values [0.1,50]. Default: 0.5." << std::endl << std::endl; std::cout << "[-k --keep-disc]: keep discarded voxel information in a specialiced section of the tree." << std::endl << std::endl; std::cout << "[--debugout]: write additional detailed outputs meant to be used for debugging." << std::endl << std::endl; std::cout << "[-p --pthreads]: number of processing threads to run the program in parallel. Default: use all available processors." << std::endl << std::endl; std::cout << std::endl; std::cout << "* Usage example:" << std::endl << std::endl; std::cout << " buildctree -r roi_lh.txt -I tractograms/ -T /tmp/tracts -O results/ -t 0.001 -d 0.1 -c 26 -N 1000 -k -m 2 -v " << std::endl << std::endl; std::cout << std::endl; std::cout << "* Outputs (in output folder defined at option -O):" << std::endl << std::endl; std::cout << " - 'cX.txt' - (where X is the neighborhood level defined at option -c) Contains the output hierarchical tree." << std::endl; std::cout << " - 'baselist.txt' - Contains the IDs of the nodes corresponding to meta-leaves (and forming the maximum granularity level)." << std::endl; std::cout << " - 'success.txt' - An empty file created when the program has sucessfully exited after completion (to help for automatic re-running scripting after failure)." << std::endl; std::cout << " - 'buildctree_log.txt' - A text log file containing the parameter details and in-run and completion information of the program." << std::endl; std::cout << std::endl; std::cout << " [extra outputs when using --debugout option)" << std::endl << std::endl; std::cout << " - 'cX_bin_nmt.txt' - non-monotonic binary-branching hierarchical tree before tree processing." << std::endl; std::cout << " - 'baselist_bin.txt' - meta-leaves (base nodes) list with IDs corresponding to the binary tree files." << std::endl; std::cout << " - 'cX_bin_nmt_granlimit.txt' - non-monotonic hierarchical after granularity limitation (and meta-leaf formation)." << std::endl; std::cout << " - 'cX_bin.txt' -binary tree after granularity and monotonicity correction." << std::endl; std::cout << " - 'cX_Down.txt' - processed hierarchical tree but using a lower-limit monotonicity correction algorithm rather than the standard weighetd one." << std::endl; std::cout << " - 'cX_Up.txt' - processed hierarchical tree but using a Higher-limit monotonicity correction algorithm rather than the standard weighetd one." << std::endl; std::cout << " - 'cX_[*]debug.txt' - versions of the counterpart files without suffix with redundant information for debugging purposes." << std::endl; std::cout << " - 'baselist_bin_10k.txt' - IDs of the peak nodes at the building point where only 10k active node remained." << std::endl; std::cout << " - 'compact_[ID/COORD].nii(.v)' - compact tractogram corresponding to the tree root node (mean tractogram of all seeds included in the final tree)." << std::endl; std::cout << std::endl; exit(0); } if ( variableMap.count( "verbose" ) ) { std::cout << "verbose output" << std::endl; verbose=true; } if ( variableMap.count( "pthreads" ) ) { if ( threads == 1 ) { std::cout << "Using a single processor" << std::endl; } else if( threads == 0 || threads >= omp_get_num_procs() ) { threads = omp_get_num_procs(); std::cout << "Using all available processors ( " << threads << " )." << std::endl; } else { std::cout << "Using a maximum of " << threads << " processors " << std::endl; } omp_set_num_threads( threads ); } else { threads = omp_get_num_procs(); omp_set_num_threads( threads ); std::cout << "Using all available processors ( " << threads << " )." << std::endl; } if ( variableMap.count( "vista" ) ) { if( verbose ) { std::cout << "Using vista format" << std::endl; } fileManagerFactory fmf; fmf.setVista(); niftiMode = false; } else { if( verbose ) { std::cout << "Using nifti format" << std::endl; } fileManagerFactory fmf; fmf.setNifti(); niftiMode = true; } if ( variableMap.count( "debugout" ) ) { if( verbose ) { std::cout << "Debug output files activated" << std::endl; } debug = true; } if ( variableMap.count( "version" ) ) { std::cout << progName << ", version 2.0" << std::endl; exit(0); } if ( variableMap.count( "roi-file" ) ) { if( !boost::filesystem::is_regular_file( boost::filesystem::path( roiFilename ) ) ) { std::cerr << "ERROR: roi file \"" <<roiFilename<< "\" is not a regular file" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Seed voxels roi file: " << roiFilename << std::endl; } } else { std::cerr << "ERROR: no seed voxels roi file stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if( verbose ) { std::cout << "Tractogram relative threshold value: " << relativeThreshold << std::endl; } if ( relativeThreshold < 0 || relativeThreshold >= 1 ) { std::cerr << "ERROR: Threshold value used is out of bounds please use a value within [0,1)" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if ( relativeThreshold == 0 ) { std::cout << "No tractogram thresholding will be applied" << std::endl; } else if( verbose ) { std::cout << "Tractogram voxels visited by less than " << relativeThreshold * 100 << " % of the streamlines generated will be set to 0 before dissimilarity computation" << std::endl; } if( verbose ) { std::cout << "Maximum distance to most similar neighbor: " << maxNbDist << std::endl; } if ( maxNbDist <= 0 || maxNbDist > 1 ) { std::cerr << "ERROR: distance value used is out of bounds please use a value within (0,1]" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if ( maxNbDist == 1 && verbose ) { std::cout << "No neighbor distance restrictions will be applied" << std::endl; } else if( verbose ) { std::cout << "Seed voxels with no neighbors with tract dissimilarity lower than " << maxNbDist << " will be discarded as outliers" << std::endl; } if( verbose ) { std::cout << "Centroid neighborhood level: " << nbLevel << std::endl; } if ( ( nbLevel != 6 ) && ( nbLevel != 18 ) && ( nbLevel != 26 ) && ( nbLevel != 32 ) && ( nbLevel != 92 ) && ( nbLevel != 124 ) ) { std::cerr << "ERROR: invalid nbhood level, only (6,18,26,32,92,124) are accepted" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( ( variableMap.count( "basesize" ) && variableMap.count( "basenum" ) ) ) { std::cerr << "ERROR: options --basesize (-S) and --basenum (-N) are mutually exclusive" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( variableMap.count( "basesize" ) ) { if( baseSize <= 1 ) { std::cerr << "ERROR: base node (meta-leaf) size must be greater than 1" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else { if( verbose ) { std::cout << "Initial merging stage up to homogeneous base nodes of size: " << baseSize << std::endl; } growType = TC_GROWSIZE; } } if ( variableMap.count( "basenum" ) ) { if( baseSize < 10 ) { std::cerr << "ERROR: base node (meta-leaf) number must be equal or greater than 10" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else { if( verbose ) { std::cout << "Initial merging stage up to " << baseSize << " homogeneous base nodes (meta-leaves)" << std::endl; } growType = TC_GROWNUM; } } if( growType == TC_GROWOFF && verbose ) { std::cout << "No homogeneous merging stage" << std::endl; } if ( variableMap.count( "nolog" ) ) { std::cout << "Using only linear tract normalization:" << std::endl; noLog = true; } if ( variableMap.count( "keep-disc" ) ) { if( verbose ) { std::cout << "Discarded voxel coordinates will be saved in an special section fo the tree file" << std::endl; } keepDiscarded = true; } else { if( verbose ) { std::cout << "Discarded voxel coordinates will not be saved" << std::endl; } keepDiscarded = false; } if ( variableMap.count( "inputf" ) ) { if( !boost::filesystem::is_directory( boost::filesystem::path( inputFolder ) ) ) { std::cerr << "ERROR: input seed tractogram folder \"" <<inputFolder<< "\" is not a directory" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Input seed tractogram folder: " << inputFolder << std::endl; } } else { std::cerr << "ERROR: no input seed tractogram stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( variableMap.count( "outputf" ) ) { if( !boost::filesystem::is_directory( boost::filesystem::path( outputFolder ) ) ) { std::cerr << "ERROR: output folder \"" <<outputFolder<< "\" is not a directory" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Output folder: " << outputFolder << std::endl; } } else { std::cerr << "ERROR: no output folder stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( variableMap.count( "tempf" ) ) { if( !boost::filesystem::is_directory(boost::filesystem::path( tempFolder ) ) ) { std::cerr << "ERROR: temporal folder \"" <<tempFolder<< "\" is not a directory" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if( verbose ) { std::cout << "temporal folder: " << tempFolder << std::endl; } } else { std::cerr << "ERROR: no temporal folder stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( memory < 0.1 || memory > 50) { std::cerr << "ERROR: cache size must be a positive float between 0.1 and 50 (GB)" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Tractogram cache memory: " << memory << " GBytes" << std::endl; } std::string logFilename(outputFolder+"/"+progName+"_log.txt" ); std::ofstream logFile(logFilename.c_str() ); if(!logFile) { std::cerr << "ERROR: unable to open log file: \"" <<logFilename<< "\"" << std::endl; exit(-1); } logFile << "Start Time:\t" << ctime(&programStartTime) << std::endl; logFile << "Working directory:\t" << workingDir.string() << std::endl; logFile << "Verbose:\t" << verbose << std::endl; logFile << "Processors used:\t" << threads << std::endl; if( niftiMode ) { logFile << "Using nifti file format" << std::endl; } else { logFile << "Using vista file format" << std::endl; } logFile << "Roi file:\t" << roiFilename << std::endl; if( noLog ) { logFile << "Using only linear tract normalization" << std::endl; } logFile << "Relative threshold:\t" << relativeThreshold << std::endl; logFile << "Max nb distance:\t" << maxNbDist << std::endl; logFile << "Nbhood restriction level:\t" <<nbLevel<< std::endl; switch(growType) { case TC_GROWOFF: logFile << "Region growing: None" << std::endl; break; case TC_GROWSIZE: logFile << "Region growing: Size: " << baseSize << std::endl; break; case TC_GROWNUM: logFile << "Region growing: Number: " << baseSize << std::endl; break; } logFile << "Input seed tract folder:\t" << inputFolder << std::endl; logFile << "Output folder:\t" << outputFolder << std::endl; logFile << "Temp folder:\t" << tempFolder << std::endl; logFile << "Memory cache size:\t" << memory << " GB" << std::endl; logFile << "Debug outputr:\t" << debug << std::endl; logFile << "-------------" << std::endl; ///////////////////////////////////////////////////////////////// CnbTreeBuilder builder( roiFilename, relativeThreshold, maxNbDist, verbose, noLog ); logFile << "Roi size:\t" << builder.roiSize() << std::endl; builder.log( &logFile ); builder.setInputFolder( inputFolder ); builder.setOutputFolder( outputFolder ); builder.setTempFolder( tempFolder ); builder.setDebugOutput( debug ); builder.buildCentroid( nbLevel, memory, growType, baseSize, keepDiscarded ); ///////////////////////////////////////////////////////////////// // save and print total time time_t programEndTime(time(NULL) ); int totalTime( difftime(programEndTime,programStartTime) ); std::cout << "Program Finished, total time: " << totalTime/3600 << "h " << (totalTime%3600)/60 << "' " << ((totalTime%3600)%60) << "\" " << std::endl; logFile << "-------------" << std::endl; logFile << "Finish Time:\t" << ctime(&programEndTime) << std::endl; logFile << "Elapsed time : " << totalTime/3600 << "h " << (totalTime%3600)/60 << "' " << ((totalTime%3600)%60) << "\"" << std::endl; // create file that indicates process was finished successfully std::string successFilename(outputFolder+"/success.txt" ); std::ofstream successFile(successFilename.c_str() ); if(!successFile) { std::cerr << "ERROR: unable to create success file: \"" <<successFile<< "\"" << std::endl; exit(-1); } successFile << "success"; // } // catch(std::exception& e) // { // std::cout << e.what() << std::endl; // return 1; // } return 0; }
//============================================================================= //コンストラクタ //============================================================================= //[input] // name:データ名 // vPos:設定する座標 // filename:敵の動きのファイル名 //============================================================================= CEnemyAmeus::CEnemyAmeus( string name, Math::Vector3D vPos, string filename ) { m_DataName = name; m_eType = OBJ_ENEMY; m_IsVisible = true; m_IsStop = false; m_IsSetFlag = false; m_IsHit = false; float Scale = 1.0f; m_vPos = vPos; m_vOldPos = vPos; m_vRot.Set( 0, -DEG_TO_ANGLE(60), 0 ); m_vScale.Set( Scale, Scale, Scale ); m_pModel = NULL; for( int numActor = 0;numActor < S_MAX;++numActor ) { m_pActorModel[numActor] = NULL; } m_ActorIndex = 0; for( int Anim = 0;Anim < ANIM_MAX;++Anim ) { m_fAnimTime[Anim] = 0.0f; m_AnimID[Anim] = 0; } m_fKeyTime = 0.0f; m_fSpeed = 2.0f; std::ifstream ifs(filename.c_str()); vector< float > vecKeyX; vector< float > vecKeyZ; vector< float > vecKeyRotX; while( !ifs.eof() ) { float KeyTime = 0.0f; float KeyX = 0; float KeyZ = 0; float KeyRotX = 0; float fKeySpeed = 0; ifs >> fKeySpeed >> KeyX >> KeyZ >> KeyRotX; vecKeyX.push_back( KeyX ); vecKeyZ.push_back( KeyZ ); vecKeyRotX.push_back( KeyRotX ); m_vKeySpeed.push_back( fKeySpeed ); } Sint32 MaxKey = vecKeyX.size(); m_pAnimX = new Math::Animation(MaxKey); m_pAnimZ = new Math::Animation(MaxKey); m_pAnimRotX = new Math::Animation(MaxKey); m_pAnimSpeed = new Math::Animation(MaxKey); /*キー時間の最初を0に設定しておく*/ m_vDeltaKey.push_back( 0.0f ); /*キーの差分時間を求める*/ for( Sint32 i = 0;i < MaxKey - 1;++i ) { float Delta = Abs( vecKeyZ.at( i + 1 ) - vecKeyZ.at( i ) ); if( Delta <= 1.0f ) { Delta = 3.0f; } float KeyTime = Delta / m_fSpeed; m_vDeltaKey.push_back( KeyTime ); //float Delta = m_vKeyTime.at( i + 1 ) - m_vKeyTime.at( i ); // //m_vDeltaKey.push_back( Delta ); } /*キーをセット*/ for( int Key = 0;Key < MaxKey; ++Key ) { static float KeyTime = 0.0f; KeyTime += m_vDeltaKey.at(Key); m_vKeyTime.push_back( KeyTime ); m_pAnimX->SetKey( Key, KeyTime, vecKeyX.at(Key) ); m_pAnimZ->SetKey( Key, KeyTime, vecKeyZ.at(Key) ); m_pAnimRotX->SetKey( Key, KeyTime, vecKeyRotX.at(Key) ); m_pAnimSpeed->SetKey( Key, KeyTime, m_vKeySpeed.at(Key) ); if( Key == MaxKey - 1 ) { m_fMaxKeyTime = KeyTime; } } m_fWeight = 0.0f; m_KeyIndex = 0; m_IsChangeKeyTime = false; m_IsStopKeyTime = false; //m_pAnim->SetKey }
bool GitCommitLog::parseCommit(RCommit& commit) { std::string line; char filesizeBuf[256]; commit.username = ""; while(logf->getNextLine(line) && line.size()) { if(line.find("commit_id:") == 0) { commit.commit_id = line.substr(10); if(!logf->getNextLine(line)) return false; //username follows user prefix commit.username = line.substr(5); if(!logf->getNextLine(line)) return false; commit.timestamp = atol(line.c_str()); //this isnt a commit we are parsing, abort if(commit.timestamp == 0) return false; continue; } //should see username before files if(commit.username.empty()) return false; size_t tab = line.find('\t'); //incorrect log format if(tab == std::string::npos || tab == 0 || tab == line.size()-1) continue; std::string status = line.substr(tab - 1, 1); std::string file = line.substr(tab + 1); if(file.empty()) continue; //check for and remove double quotes if(file.find('"') == 0 && file.rfind('"') == file.size()-1) { if(file.size()<=2) continue; file = file.substr(1,file.size()-2); } std::string size_temp_file = temp_file + "_filesize"; memset(filesizeBuf, 0, sizeof(char) * 256); snprintf(filesizeBuf, sizeof(char) * 256, GitGetFileSizeCommand.c_str(), commit.commit_id.c_str(), file.c_str(), size_temp_file.c_str()); systemCommand(filesizeBuf); std::ifstream ifs ( size_temp_file ); std::string filesize_str; ifs >> filesize_str; size_t filesize = 0; if(!filesize_str.empty()) { filesize = std::stoi(filesize_str); } commit.addFile(file, status, filesize); } //check we at least got a username if(commit.username.empty()) return false; return true; }
void Raw::read(const std::string& fn) { if(mBuffer) delete[] mBuffer; mBuffer = NULL; // Read file into buffer. std::cout << "Reading " << fn << std::endl; std::ifstream ifs(fn.data(), std::ifstream::binary); if(ifs) { ifs.seekg(0, std::ifstream::end); std::size_t mSize = ifs.tellg(); ifs.seekg(0, std::ifstream::beg); mBuffer = new uint8_t[mSize]; ifs.read((char*) mBuffer, mSize); ifs.close(); } else { std::cerr << "Error reading " << fn << std::endl; ifs.close(); return; } // Get total number of blocks. int blocks = (mWidth / 4) * (mHeight / 4); std::cout << "Reading in " << blocks << " blocks" << std::flush; for(int i = 0; i < blocks; ++i) { if(i % (int)((blocks * 0.05) + 1) == 0) std::cout << "." << std::flush; Block<double> block; // We find the x- and y-offset of the block. int xOff = (i % (mWidth / 4)) * 4; int yOff = (i / (mWidth / 4)) * 4; // We find the locations in the buffer of the "left side" of the block. int l0 = (xOff % mWidth) + (yOff * mWidth); int l1 = l0 + mWidth; int l2 = l1 + mWidth; int l3 = l2 + mWidth; // Set the data. double newData[4][4] = { {(double)mBuffer[l0], (double)mBuffer[l0 + 1], (double)mBuffer[l0 + 2], (double)mBuffer[l0 + 3]}, {(double)mBuffer[l1], (double)mBuffer[l1 + 1], (double)mBuffer[l1 + 2], (double)mBuffer[l1 + 3]}, {(double)mBuffer[l2], (double)mBuffer[l2 + 1], (double)mBuffer[l2 + 2], (double)mBuffer[l2 + 3]}, {(double)mBuffer[l3], (double)mBuffer[l3 + 1], (double)mBuffer[l3 + 2], (double)mBuffer[l3 + 3]} }; block.data(newData); // balance around 0 for(int i = 0; i < 4; ++i) for(int j = 0; j < 4; ++j) block.data(i, j, block.data(i, j) - 128); mData.push_back(block); } delete[] mBuffer; mBuffer = NULL; std::cout << std::endl; }
bool Inventory::readRecipe(std::string recipeFile) { std::ifstream ifs(recipeFile.c_str()); if (ifs.fail()) { std::cerr << "Could not find: " << recipeFile << std::endl; ifs.close(); return false; } //LOG(INFO, "Inventory", "Reading: " + recipeFile); std::string temp; int height = 0, width = 0, outCount = 0; int16_t outType = 0, outHealth = 0; // Reading row at a time int del; bool readingRecipe = false; std::vector<std::string> line; std::vector<Item*> recipetable; std::string text; while (getline(ifs, temp)) { //If empty line if (temp.size() == 0) { continue; } // If commentline -> skip to next if (temp[0] == COMMENTPREFIX) { continue; } // Init vars del = 0; line.clear(); // Process line while (temp.length() > 0) { // Remove white spaces while (temp[0] == ' ') { temp = temp.substr(1); } // Split words del = temp.find(' '); if (del > -1) { line.push_back(temp.substr(0, del)); temp = temp.substr(del + 1); } else { line.push_back(temp); break; } } // Begin recipe if (line.size() == 1 && line[0] == "<-") { readingRecipe = true; continue; } // Begin recipe if (line.size() == 1 && line[0] == "->") { readingRecipe = false; continue; } if (readingRecipe) { for (unsigned int i = 0; i < line.size(); i++) { std::string data(line[i]); Item* item = new Item(); item->setCount(1); item->setHealth(-1); int location = data.find("x"); if (location > -1) { // Quantity before ID item->setCount(atoi(data.substr(0, location).c_str())); data = data.substr(location + 1, std::string::npos); } location = data.find(":"); if (location > -1) { // Meta after ID item->setHealth(atoi(data.substr(location + 1, std::string::npos).c_str())); data = data.substr(0, location); } item->setType(atoi(data.c_str())); recipetable.push_back(item); } continue; } else { // Keywords if (line[0] == "width") { width = atoi(line[1].c_str()); } if (line[0] == "height") { height = atoi(line[1].c_str()); } if (line[0] == "outputcount") { outCount = atoi(line[1].c_str()); } if (line[0] == "outputtype") { outType = atoi(line[1].c_str()); } if (line[0] == "outputhealth") { outHealth = atoi(line[1].c_str()); } } } ifs.close(); addRecipe(width, height, recipetable, outCount, outType, outHealth); // delete [] inrecipe; return true; }
void VDPMLoader::openVDPM_ServerRendering(const char *_filename) { unsigned int i; unsigned int value; unsigned int fvi[3]; char fileformat[16]; Vec3f p, normal; float radius, sin_square, mue_square, sigma_square; VHierarchyNodeHandleContainer roots; VertexHandle vertex_handle; VHierarchyNodeIndex node_index; VHierarchyNodeIndex lchild_node_index, rchild_node_index; VHierarchyNodeIndex fund_lcut_index, fund_rcut_index; VHierarchyNodeHandle node_handle; VHierarchyNodeHandle lchild_node_handle, rchild_node_handle; std::ifstream ifs(_filename, std::ios::binary); if (!ifs) { std::cerr << "read error\n"; exit(1); } // bool swap = Endian::local() != Endian::LSB; // read header ifs.read(fileformat, 10); fileformat[10] = '\0'; if (std::string(fileformat) != std::string("VDProgMesh")) { std::cerr << "Wrong file format.\n"; ifs.close(); exit(1); } IO::restore(ifs, n_base_vertices_, swap); IO::restore(ifs, n_base_faces_, swap); IO::restore(ifs, n_details_, swap); mesh_.clear(); vfront_.clear(); vhierarchy_.clear(); vhierarchy_.set_num_roots(n_base_vertices_); // load base mesh for (i=0; i<n_base_vertices_; ++i) { IO::restore(ifs, p, swap); IO::restore(ifs, radius, swap); IO::restore(ifs, normal, swap); IO::restore(ifs, sin_square, swap); IO::restore(ifs, mue_square, swap); IO::restore(ifs, sigma_square, swap); vertex_handle = mesh_.add_vertex(p); node_index = vhierarchy_.generate_node_index(i, 1); node_handle = vhierarchy_.add_node(); VHierarchyNode &node = vhierarchy_.node(node_handle); node.set_index(node_index); node.set_vertex_handle(vertex_handle); mesh_.data(vertex_handle).set_vhierarchy_node_handle(node_handle); node.set_radius(radius); node.set_normal(normal); node.set_sin_square(sin_square); node.set_mue_square(mue_square); node.set_sigma_square(sigma_square); mesh_.set_normal(vertex_handle, normal); index2handle_map[node_index] = node_handle; roots.push_back(node_handle); } vfront_.init(roots, n_details_); for (i=0; i<n_base_faces_; ++i) { IO::restore(ifs, fvi[0], swap); IO::restore(ifs, fvi[1], swap); IO::restore(ifs, fvi[2], swap); mesh_.add_face(mesh_.vertex_handle(fvi[0]), mesh_.vertex_handle(fvi[1]), mesh_.vertex_handle(fvi[2])); } vsplit_loaded.clear(); // load details for (i=0; i<n_details_; ++i) { Vsplit avs; // position of v0 IO::restore(ifs, p, swap); avs.v0 = p; // vsplit info. IO::restore(ifs, value, swap); node_index = VHierarchyNodeIndex(value); avs.node_index = value; IO::restore(ifs, value, swap); fund_lcut_index = VHierarchyNodeIndex(value); avs.fund_lcut_index = value; IO::restore(ifs, value, swap); fund_rcut_index = VHierarchyNodeIndex(value); avs.fund_rcut_index = value; node_handle = index2handle_map[node_index]; vhierarchy_.make_children(node_handle); VHierarchyNode &node = vhierarchy_.node(node_handle); VHierarchyNode &lchild = vhierarchy_.node(node.lchild_handle()); VHierarchyNode &rchild = vhierarchy_.node(node.rchild_handle()); node.set_fund_lcut(fund_lcut_index); node.set_fund_rcut(fund_rcut_index); vertex_handle = mesh_.add_vertex(p); lchild.set_vertex_handle(vertex_handle); rchild.set_vertex_handle(node.vertex_handle()); index2handle_map[lchild.node_index()] = node.lchild_handle(); index2handle_map[rchild.node_index()] = node.rchild_handle(); // view-dependent parameters IO::restore(ifs, radius, swap); IO::restore(ifs, normal, swap); IO::restore(ifs, sin_square, swap); IO::restore(ifs, mue_square, swap); IO::restore(ifs, sigma_square, swap); lchild.set_radius(radius); lchild.set_normal(normal); lchild.set_sin_square(sin_square); lchild.set_mue_square(mue_square); lchild.set_sigma_square(sigma_square); avs.l_radius = radius; avs.l_normal = normal; avs.l_mue_square = mue_square; avs.l_sigma_square = sigma_square; avs.l_sin_square = sin_square; IO::restore(ifs, radius, swap); IO::restore(ifs, normal, swap); IO::restore(ifs, sin_square, swap); IO::restore(ifs, mue_square, swap); IO::restore(ifs, sigma_square, swap); rchild.set_radius(radius); rchild.set_normal(normal); rchild.set_sin_square(sin_square); rchild.set_mue_square(mue_square); rchild.set_sigma_square(sigma_square); avs.r_radius = radius; avs.r_normal = normal; avs.r_mue_square = mue_square; avs.r_sigma_square = sigma_square; avs.r_sin_square = sin_square; vsplit_loaded.push_back(avs); } ifs.close(); //refine 100 vsplits int cc = 0; for ( vfront_.begin(); !vfront_.end() && cc < 100; ++cc) { VHierarchyNodeHandle node_handle = vfront_.node_handle(); if (vhierarchy_.is_leaf_node(node_handle) != true) { force_vsplit(node_handle, vsplits_to_send); } vfront_.next(); std::cout << "vfront_ size " << vfront_.size() <<std::endl; } //**********// // update face and vertex normals mesh_.update_face_normals(); // bounding box VDPMMesh::ConstVertexIter vIt(mesh_.vertices_begin()), vEnd(mesh_.vertices_end()); VDPMMesh::Point bbMin, bbMax; bbMin = bbMax = mesh_.point(vIt); for (; vIt!=vEnd; ++vIt) { bbMin.minimize(mesh_.point(vIt)); bbMax.maximize(mesh_.point(vIt)); } // set center and radius VDPMMesh::Point center = 0.5f * (bbMin + bbMax); set_scene_pos(0.5f*(bbMin + bbMax), 0.5*(bbMin - bbMax).norm()); // info std::cerr << mesh_.n_vertices() << " vertices, " << mesh_.n_edges() << " edge, " << mesh_.n_faces() << " faces, " << n_details_ << " detail vertices\n"; mesh_loaded = true; }
source::source() { ifstream ifs(getenv("idock_cl")); insert(begin(), istreambuf_iterator<char>(ifs), istreambuf_iterator<char>()); }