TEST_F(IdfFixture, IdfObject_StringFieldGetterWithReturnDefaultOption) { // NON-EXTENSIBLE OBJECT std::stringstream text; text << "Refrigeration:Condenser:AirCooled," << std::endl << " MyCondenser," << std::endl << " ," << std::endl << " ," << std::endl // default is 0.0 << " ," << std::endl // default is "Fixed" << " 125.0;"; // default is 250.0 // default is 0.2 // // default is "General" // default is 0.0 // default is 0.0 // default is 0.0 OptionalIdfObject oObj = IdfObject::load(text.str()); ASSERT_TRUE(oObj); IdfObject object = *oObj; // returns set values OptionalString idfField = object.getString(0,true); ASSERT_TRUE(idfField); EXPECT_EQ("MyCondenser",*idfField); idfField = object.getString(1,true); ASSERT_TRUE(idfField); EXPECT_EQ("",*idfField); idfField = object.getString(4,true); ASSERT_TRUE(idfField); EXPECT_EQ("125.0",*idfField); // returns default for fields behind fields with set values idfField = object.getString(2,true); ASSERT_TRUE(idfField); EXPECT_EQ("0.0",*idfField); idfField = object.getString(3,true); ASSERT_TRUE(idfField); EXPECT_EQ("Fixed",*idfField); // returns default for non-existent fields idfField = object.getString(6,true); EXPECT_FALSE(idfField); idfField = object.getString(7,true); ASSERT_TRUE(idfField); EXPECT_EQ("General",*idfField); idfField = object.getString(8,true); ASSERT_TRUE(idfField); EXPECT_EQ("0.0",*idfField); idfField = object.getString(10,true); ASSERT_TRUE(idfField); EXPECT_EQ("0.0",*idfField); idfField = object.getString(11,true); EXPECT_FALSE(idfField); // EXTENSIBLE OBJECT text.str(""); text << "DaylightingDevice:Tubular," << std::endl << " MyTDD," << std::endl << " MyDome," << std::endl << " MyDiffuser," << std::endl << " MyConstruction," << std::endl << " 1.0," << std::endl << " 2.0;"; // \default 0.28 // Transition Zone 1 Name // Transition Zone 1 Length // ... (extensible 2) oObj = IdfObject::load(text.str()); ASSERT_TRUE(oObj); object = *oObj; EXPECT_EQ(7u,object.numFields()); // returns set values idfField = object.getString(0,true); ASSERT_TRUE(idfField); EXPECT_EQ("MyTDD",*idfField); idfField = object.getString(5,true); ASSERT_TRUE(idfField); EXPECT_EQ("2.0",*idfField); // returns default for empty fields idfField = object.getString(6,true); ASSERT_TRUE(idfField); EXPECT_EQ("0.28",*idfField); EXPECT_EQ(7u,object.numFields()); idfField = object.getString(6); EXPECT_TRUE(idfField); StringVector newGroup; newGroup.push_back("MyFirstTransistionZone"); newGroup.push_back("1.5"); ASSERT_FALSE(object.pushExtensibleGroup(newGroup).empty()); // returns default for fields behind fields with set values idfField = object.getString(6,true); ASSERT_TRUE(idfField); EXPECT_EQ("0.28",*idfField); idfField = object.getString(6); ASSERT_TRUE(idfField); EXPECT_TRUE(idfField->empty()); // return evaluates to false for extensible fields that do not exist idfField = object.getString(10); EXPECT_FALSE(idfField); }
void EditorFileList::AcceptMessage(const Message &message) { #ifdef ENGINE_TARGET_WIN32 if (message.is("KeyPress")) { int data = utils::lexical_cast<int>(message.getData()); char key = data; if (key == -VK_LEFT) { if (_cursorPos > 0) { _cursorPos--; } _cursorTime = 0.f; } else if (key == -VK_RIGHT) { if (_cursorPos < static_cast<int>(_fileName.length())) { _cursorPos++; } _cursorTime = 0.f; } else if (key == -VK_UP) { _cursorPos = static_cast<int>(_fileName.length()); _cursorTime = 0.f; } else if (key == -VK_DOWN) { _cursorPos = 0; _cursorTime = 0.f; } else if (data > 0 && key > ' ' && _fileName.length() < 20) { _fileName.insert(static_cast<size_t>(_cursorPos), 1, key); _cursorPos++; _cursorTime = 0.f; } else if (key == 8) { if (_cursorPos > 0) { _cursorPos--; _fileName.erase(static_cast<size_t>(_cursorPos), 1); } } } else #endif if (message.is("Init")) { _names.clear(); StringVector vec = File::DirectoryListing::Get("Levels/*.*"); size_t count = vec.size(); _names.reserve(count); int fnd0; int fnd1; for(size_t i=0;i<count;i++){ fnd0 = vec[i].find("/"); fnd1 = vec[i].find(".xml"); if( fnd0>0 && fnd1 > 0){ _names.push_back( vec[i].substr(fnd0+1,fnd1-fnd0-1)); } } /*} else if (message.is("SetDestLayer")) { _destLayer = message.getData(); } else if (message.is("SetDestWidget")) { _destWidget = message.getData();*/ } else if (message.is("SetLevelName")) { _fileName = message.getData(); _cursorPos = (int) _fileName.length(); } else if (message.is("AddItem")) { _names.push_back(message.getData()); } else if (message.is("Load")){ if (_currentName >= 0) { _fileName = _names[_currentName]; _cursorPos = (int) _fileName.length(); GUI::Widget *target = Core::guiManager.getLayer(_destLayer) -> getWidget(_destWidget); target -> AcceptMessage(Message("LoadLevelForEdit", _fileName)); Core::messageManager.putMessage(Message("Return", "press")); } } else if (message.is("Save")) { bool f = false; for (size_t i = 0; i<_names.size(); i++) { if (_fileName == _names[i]) { f = true; } } if (f) { Core::guiManager.getLayer("ConfirmRewriteLevel")->getWidget("ConfirmText")-> AcceptMessage(Message("SetString", "Do you really want to rewrite " + _fileName + "?")); Core::messageManager.putMessage(Message("ShowConfirmRewrite")); } else { Core::guiManager.getLayer(_destLayer)->getWidget(_destWidget)->AcceptMessage(Message("SaveLevel", _fileName)); Core::messageManager.putMessage(Message("Return", "press")); } } else if (message.is("SaveAlways")) { Core::guiManager.getLayer(_destLayer)->getWidget(_destWidget)->AcceptMessage(Message("SaveLevel", _fileName)); Core::messageManager.putMessage(Message("Return", "press")); } else if (message.is("Delete")) { size_t i = static_cast<size_t>(_currentName); if(i >= _names.size()) { return; } std::string filename = _names[i]; if (filename == _fileName) { Log::log.WriteInfo("ะั ะฝะต ะผะพะถะตัะต ัะดะฐะปะธัั ัะตะบััะธะน ะทะฐะณััะถะตะฝัะน ััะพะฒะตะฝั!"); return; } std::string full_name = "Levels/" + filename + ".xml"; if(File::Exists(full_name)){ File::rm(full_name); AcceptMessage(Message("Init")); } } else if (message.is("ResaveAll")) { //ะพัะบัััั ะธ ะฟะตัะตัะพั ัะฐะฝะธัั ะฒัะต ัะฐะนะปั GUI::Widget *target = Core::guiManager.getLayer(_destLayer) -> getWidget(_destWidget); for (auto filename: _names) { target -> AcceptMessage(Message("LoadLevelForEdit", filename)); target -> AcceptMessage(Message("SaveLevel", filename)); } //target -> AcceptMessage(Message("LoadLevelForEdit", _fileName)); } }
void X11EGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams) { if (miscParams) { NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); mExternalWindow = 0; mNativeDisplay = mGLSupport->getNativeDisplay(); mParentWindow = DefaultRootWindow((Display*)mNativeDisplay); if ((opt = miscParams->find("parentWindowHandle")) != end) { //vector<String>::type tokens = StringUtil::split(opt->second, " :"); StringVector tokens = StringUtil::split(opt->second, " :"); if (tokens.size() == 3) { // deprecated display:screen:xid format mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]); } else { // xid format mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[0]); } } else if ((opt = miscParams->find("externalWindowHandle")) != end) { //vector<String>::type tokens = StringUtil::split(opt->second, " :"); StringVector tokens = StringUtil::split(opt->second, " :"); LogManager::getSingleton().logMessage( "EGLWindow::create: The externalWindowHandle parameter is deprecated.\n" "Use the parentWindowHandle or currentGLContext parameter instead."); if (tokens.size() == 3) { // Old display:screen:xid format // The old EGL code always created a "parent" window in this case: mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]); } else if (tokens.size() == 4) { // Old display:screen:xid:visualinfo format mExternalWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]); } else { // xid format mExternalWindow = (Window)StringConverter::parseUnsignedLong(tokens[0]); } } } // Ignore fatal XErrorEvents during parameter validation: oldXErrorHandler = XSetErrorHandler(safeXErrorHandler); // Validate parentWindowHandle if (mParentWindow != DefaultRootWindow((Display*)mNativeDisplay)) { XWindowAttributes windowAttrib; if (!XGetWindowAttributes((Display*)mNativeDisplay, mParentWindow, &windowAttrib) || windowAttrib.root != DefaultRootWindow((Display*)mNativeDisplay)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid parentWindowHandle (wrong server or screen)", "EGLWindow::create"); } } // Validate externalWindowHandle if (mExternalWindow != 0) { XWindowAttributes windowAttrib; if (!XGetWindowAttributes((Display*)mNativeDisplay, mExternalWindow, &windowAttrib) || windowAttrib.root != DefaultRootWindow((Display*)mNativeDisplay)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid externalWindowHandle (wrong server or screen)", "EGLWindow::create"); } mEglConfig = 0; mEglSurface = createSurfaceFromWindow(mEglDisplay, (NativeWindowType)mExternalWindow); } XSetErrorHandler(oldXErrorHandler); mIsTopLevel = (!mIsExternal && mParentWindow == DefaultRootWindow((Display*)mNativeDisplay)); }
osg::Shader* LandCoverLayer::createPredicateShader(const Coverage* coverage) const { const char* defaultCode = "int oe_landcover_getBiomeIndex(in vec4 coords) { return -1; }\n"; std::stringstream buf; buf << "#version 330\n"; osg::ref_ptr<ImageLayer> layer; if ( !coverage ) { buf << defaultCode; OE_INFO << LC << "No coverage; generating default coverage predicate\n"; } else if ( !coverage->getLegend() ) { buf << defaultCode; OE_INFO << LC << "No legend; generating default coverage predicate\n"; } else if ( !coverage->lockLayer(layer) ) { buf << defaultCode; OE_INFO << LC << "No classification layer; generating default coverage predicate\n"; } else { const std::string& sampler = layer->shareTexUniformName().get(); const std::string& matrix = layer->shareTexMatUniformName().get(); buf << "uniform sampler2D " << sampler << ";\n" << "uniform mat4 " << matrix << ";\n" << "int oe_landcover_getBiomeIndex(in vec4 coords) { \n" << " float value = textureLod(" << sampler << ", (" << matrix << " * coords).st, 0).r;\n"; for(int biomeIndex=0; biomeIndex<getBiomes().size(); ++biomeIndex) { const LandCoverBiome* biome = getBiomes().at(biomeIndex).get(); if ( !biome->getClasses().empty() ) { StringVector classes; StringTokenizer(biome->getClasses(), classes, " ", "\"", false); for(int i=0; i<classes.size(); ++i) { std::vector<const CoverageValuePredicate*> predicates; if ( coverage->getLegend()->getPredicatesForClass(classes[i], predicates) ) { for(std::vector<const CoverageValuePredicate*>::const_iterator p = predicates.begin(); p != predicates.end(); ++p) { const CoverageValuePredicate* predicate = *p; if ( predicate->_exactValue.isSet() ) { buf << " if (value == " << predicate->_exactValue.get() << ") return " << biomeIndex << "; \n"; } else if ( predicate->_minValue.isSet() && predicate->_maxValue.isSet() ) { buf << " if (value >= " << predicate->_minValue.get() << " && value <= " << predicate->_maxValue.get() << ") return " << biomeIndex << "; \n"; } else if ( predicate->_minValue.isSet() ) { buf << " if (value >= " << predicate->_minValue.get() << ") return " << biomeIndex << "; \n"; } else if ( predicate->_maxValue.isSet() ) { buf << " if (value <= " << predicate->_maxValue.get() << ") return " << biomeIndex << "; \n"; } else { OE_WARN << LC << "Class \"" << classes[i] << "\" found, but no exact/min/max value was set in the legend\n"; } } } else { OE_WARN << LC << "Class \"" << classes[i] << "\" not found in the legend!\n"; } } } } buf << " return -1; \n"; buf << "}\n"; } osg::Shader* shader = new osg::Shader(); shader->setName("oe Landcover predicate function"); shader->setShaderSource( buf.str() ); return shader; }
void RenderSystemCapabilitiesSerializer::parseCapabilitiesLines(CapabilitiesLinesList& lines) { StringVector tokens; for (CapabilitiesLinesList::iterator it = lines.begin(), end = lines.end(); it != end; ++it) { // restore the current line information for debugging mCurrentLine = &(it->first); mCurrentLineNumber = it->second; tokens = StringUtil::split(it->first); // check for incomplete lines if(tokens.size() < 2) { logParseError("No parameters given for the capability keyword"); continue; } // the first token must the the keyword identifying the capability // the remaining tokens are the parameters String keyword = tokens[0]; String everythingElse = ""; for(unsigned int i = 1; i < tokens.size() - 1; i ++) { everythingElse = everythingElse + tokens[i] + " "; } everythingElse = everythingElse + tokens[tokens.size() - 1]; CapabilityKeywordType keywordType = getKeywordType(keyword); switch(keywordType) { case UNDEFINED_CAPABILITY_TYPE: logParseError("Unknown capability keyword: " + keyword); break; case SET_STRING_METHOD: callSetStringMethod(keyword, everythingElse); break; case SET_INT_METHOD: { ushort integer = (ushort)StringConverter::parseInt(tokens[1]); callSetIntMethod(keyword, integer); break; } case SET_BOOL_METHOD: { bool b = StringConverter::parseBool(tokens[1]); callSetBoolMethod(keyword, b); break; } case SET_REAL_METHOD: { Real real = StringConverter::parseReal(tokens[1]); callSetRealMethod(keyword, real); break; } case ADD_SHADER_PROFILE_STRING: { addShaderProfile(tokens[1]); break; } case SET_CAPABILITY_ENUM_BOOL: { bool b = StringConverter::parseBool(tokens[1]); setCapabilityEnumBool(tokens[0], b); break; } } } }
void Logger::initialise( const std::string &id, const Options &options ) { char *envPtr; if ( !id.empty() ) this->id( id ); std::string tempLogFile; if ( options.mLogPath.size() ) { mLogPath = options.mLogPath; tempLogFile = mLogPath+"/"+mId+".log"; } if ( options.mLogFile.size() ) tempLogFile = options.mLogFile; else tempLogFile = mLogPath+"/"+mId+".log"; if ( (envPtr = getTargettedEnv( "LOG_FILE" )) ) tempLogFile = envPtr; Level tempLevel = INFO; Level tempTermLevel = mTermLevel; Level tempDatabaseLevel = mDatabaseLevel; Level tempFileLevel = mFileLevel; Level tempSyslogLevel = mSyslogLevel; if ( options.mTermLevel != NOOPT ) tempTermLevel = options.mTermLevel; if ( options.mDatabaseLevel != NOOPT ) tempDatabaseLevel = options.mDatabaseLevel; else tempDatabaseLevel = config.log_level_database >= DEBUG1 ? DEBUG9 : config.log_level_database; if ( options.mFileLevel != NOOPT ) tempFileLevel = options.mFileLevel; else tempFileLevel = config.log_level_file >= DEBUG1 ? DEBUG9 : config.log_level_file; if ( options.mSyslogLevel != NOOPT ) tempSyslogLevel = options.mSyslogLevel; else tempSyslogLevel = config.log_level_syslog >= DEBUG1 ? DEBUG9 : config.log_level_syslog; // Legacy if ( (envPtr = getenv( "LOG_PRINT" )) ) tempTermLevel = atoi(envPtr) ? DEBUG9 : NOLOG; if ( (envPtr = getTargettedEnv( "LOG_LEVEL" )) ) tempLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_TERM" )) ) tempTermLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_DATABASE" )) ) tempDatabaseLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_FILE" )) ) tempFileLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_SYSLOG" )) ) tempSyslogLevel = atoi(envPtr); if ( config.log_debug ) { StringVector targets = split( config.log_debug_target, "|" ); for ( int i = 0; i < targets.size(); i++ ) { const std::string &target = targets[i]; if ( target == mId || target == "_"+mId || target == "_"+mIdRoot || target == "_"+mIdRoot || target == "" ) { if ( config.log_debug_level > NOLOG ) { tempLevel = config.log_debug_level; if ( config.log_debug_file[0] ) { tempLogFile = config.log_debug_file; tempFileLevel = tempLevel; } } } } } logFile( tempLogFile ); termLevel( tempTermLevel ); databaseLevel( tempDatabaseLevel ); fileLevel( tempFileLevel ); syslogLevel( tempSyslogLevel ); level( tempLevel ); mFlush = (envPtr = getenv( "LOG_FLUSH")) ? atoi( envPtr ) : false; //mRuntime = (envPtr = getenv( "LOG_RUNTIME")) ? atoi( envPtr ) : false; { struct sigaction action; memset( &action, 0, sizeof(action) ); action.sa_handler = usrHandler; action.sa_flags = SA_RESTART; if ( sigaction( SIGUSR1, &action, 0 ) < 0 ) { Fatal( "sigaction(), error = %s", strerror(errno) ); } if ( sigaction( SIGUSR2, &action, 0 ) < 0) { Fatal( "sigaction(), error = %s", strerror(errno) ); } } mInitialised = true; Debug( 1, "LogOpts: level=%s/%s, screen=%s, database=%s, logfile=%s->%s, syslog=%s", smCodes[mLevel].c_str(), smCodes[mEffectiveLevel].c_str(), smCodes[mTermLevel].c_str(), smCodes[mDatabaseLevel].c_str(), smCodes[mFileLevel].c_str(), mLogFile.c_str(), smCodes[mSyslogLevel].c_str() ); }
//---------------------------------------------------------------------------------------------------------------- void CConfiguration::LoadItemClasses() { good::string_buffer sbBuffer(szMainBuffer, iMainBufferSize, false); sbBuffer = CMod::sModName; // Load health /armor / object entity classes. for ( TItemType iType = 0; iType < EItemTypeTotal; ++iType ) { // TODO: shouldn't load weapons/ammo. // Get mod item section, i.e. [HalfLife2Deathmatch.items.health]. sbBuffer.erase( CMod::sModName.size() ); sbBuffer << ".items."; sbBuffer << CTypeToString::EntityTypeToString(iType); good::ini_file::const_iterator it = m_iniFile.find( sbBuffer ); if ( it == m_iniFile.end() ) continue; // Iterate throught key values. for ( good::ini_section::const_iterator itemIt = it->begin(); itemIt != it->end(); ++itemIt ) { // String instances will live until plugin is unloaded. CItemClass cEntityClass; cEntityClass.sClassName.assign( itemIt->key.c_str(), itemIt->key.size() ); // Get item flags. StringVector aArguments; good::split(itemIt->value, aArguments, ',', true); for ( int i=0; i < aArguments.size(); ++i ) { StringVector aCurrent; good::split<good::vector>(aArguments[i], aCurrent); int iFlag = CTypeToString::EntityClassFlagsFromString(aCurrent[0]); if ( iFlag == -1 ) { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Invalid entity flag %s for %s.", aArguments[i].c_str(), itemIt->key.c_str()); } else { FLAG_SET(iFlag, cEntityClass.iFlags); /*if ( iFlag == FEntityRespawnable ) // Check respawn time. { if ( aCurrent.size() == 2 ) { int iValue = -1; sscanf(aCurrent[1].c_str(), "%d", &iValue); if ( iValue > 0 ) SET_2ND_WORD(iValue, cEntityClass.iFlags); else BLOG_E("File \"%s\", section [%s], invalid respawn time for: %s.", m_iniFile.name.c_str(), it->name.c_str(), itemIt->key.c_str()); } else if ( aCurrent.size() > 2 ) BLOG_E("File \"%s\", section [%s], invalid arguments count for: %s.", m_iniFile.name.c_str(), it->name.c_str(), itemIt->key.c_str()); }*/ } } CItems::AddItemClassFor( iType, cEntityClass ); } } // Load object models. sbBuffer = CMod::sModName; sbBuffer << ".items.object.models"; good::ini_file::const_iterator it = m_iniFile.find( sbBuffer ); if ( it != m_iniFile.end() ) { // Iterate throught key values. for ( good::ini_section::const_iterator itemIt = it->begin(); itemIt != it->end(); ++itemIt ) { int iValue = CTypeToString::EntityClassFlagsFromString(itemIt->value); if ( iValue > 0 ) CItems::SetObjectFlagForModel(iValue, itemIt->key); else { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Invalid object model flag: %s.", itemIt->value.c_str() ); BLOG_E( " Can be one of: %s", CTypeToString::EntityClassFlagsToString(FEntityAll).c_str() ); } } } }
// Extract reads from an FM-index that have a k-mer match to any given haplotypes // Returns true if the reads were successfully extracted, false if there are // more reads than maxReads bool HapgenUtil::extractHaplotypeReads(const StringVector& haplotypes, const BWTIndexSet& indices, int k, bool doReverse, size_t maxReads, int64_t maxIntervalSize, SeqRecordVector* pOutReads, SeqRecordVector* pOutMates) { PROFILE_FUNC("HapgenUtil::extractHaplotypeReads") // Extract the set of reads that have at least one kmer shared with these haplotypes // This is a bit of a lengthy procedure with a few steps: // 1) extract all the kmers in the haplotypes // 2) find the intervals for the kmers in the fm-index // 3) compute the set of read indices of the reads from the intervals (using the sampled suffix array) // 4) finally, extract the read sequences from the index // Make a set of kmers from the haplotypes std::set<std::string> kmerSet; for(size_t i = 0; i < haplotypes.size(); ++i) { const std::string& h = haplotypes[i]; if((int)h.size() < k) continue; for(size_t j = 0; j < h.size() - k + 1; ++j) { std::string ks = h.substr(j, k); if(doReverse) ks = reverseComplement(ks); kmerSet.insert(ks); } } // Compute suffix array intervals for the kmers std::vector<BWTInterval> intervals; for(std::set<std::string>::const_iterator iter = kmerSet.begin(); iter != kmerSet.end(); ++iter) { BWTInterval interval = BWTAlgorithms::findInterval(indices, *iter); if(interval.size() < maxIntervalSize) intervals.push_back(interval); } // Compute the set of reads ids std::set<int64_t> readIndices; for(size_t i = 0; i < intervals.size(); ++i) { BWTInterval interval = intervals[i]; for(int64_t j = interval.lower; j <= interval.upper; ++j) { // Get index from sampled suffix array SAElem elem = indices.pSSA->calcSA(j, indices.pBWT); readIndices.insert(elem.getID()); } } // Check if we have hit the limit of extracting too many reads if(readIndices.size() > maxReads) return false; for(std::set<int64_t>::const_iterator iter = readIndices.begin(); iter != readIndices.end(); ++iter) { int64_t idx = *iter; // Extract the read std::stringstream namer; namer << "idx-" << idx; SeqRecord record; record.id = namer.str(); record.seq = BWTAlgorithms::extractString(indices.pBWT, idx); assert(indices.pQualityTable != NULL); record.qual = indices.pQualityTable->getQualityString(idx, record.seq.length()); if(!record.seq.empty()) pOutReads->push_back(record); // Optionally extract its mate // If the index is constructed properly, // paired reads are in adjacent indices with the // first read at even indices if(pOutMates != NULL) { int64_t mateIdx = idx; if(idx % 2 == 0) mateIdx += 1; else mateIdx -= 1; std::stringstream mateName; mateName << "idx-" << mateIdx; SeqRecord mateRecord; mateRecord.id = mateName.str(); mateRecord.seq = BWTAlgorithms::extractString(indices.pBWT, mateIdx); mateRecord.qual = indices.pQualityTable->getQualityString(mateIdx, mateRecord.seq.length()); if(!record.seq.empty() && !mateRecord.seq.empty()) pOutMates->push_back(mateRecord); } } return true; }
void StringTokenizer::tokenize( const std::string& input, StringVector& output ) const { output.clear(); std::stringstream buf; bool quoted = false; for( std::string::const_iterator i = input.begin(); i != input.end(); ++i ) { char c = *i; TokenMap::const_iterator q = _quotes.find( c ); if ( quoted ) { if ( q != _quotes.end() ) { quoted = false; if ( q->second ) buf << c; } else { buf << c; } } else { if ( q != _quotes.end() ) { quoted = true; if ( q->second ) buf << c; } else { TokenMap::const_iterator d = _delims.find( c ); if ( d == _delims.end() ) { buf << c; } else { std::string token = _trimTokens ? trim(buf.str()) : buf.str(); if ( _allowEmpties || !token.empty() ) output.push_back( token ); if ( d->second == true ) { output.push_back( std::string(1, c) ); } buf.str(""); } } } } std::string last = _trimTokens ? trim(buf.str()) : buf.str(); if ( !last.empty() ) output.push_back( last ); }
int main (int argc, const char** argv) { if (argc < 2) { printf ("USAGE: hlsl2glsltest testfolder\n"); return 1; } bool hasOpenGL = InitializeOpenGL (); clock_t time0 = clock(); Hlsl2Glsl_Initialize (); std::string baseFolder = argv[1]; static const char* kTypeName[2] = { "vertex", "fragment" }; size_t tests = 0; size_t errors = 0; for (int type = 0; type < 2; ++type) { printf ("testing %s...\n", kTypeName[type]); std::string testFolder = baseFolder + "/" + kTypeName[type]; StringVector inputFiles = GetFiles (testFolder, "-in.txt"); size_t n = inputFiles.size(); tests += n; for (size_t i = 0; i < n; ++i) { std::string inname = inputFiles[i]; printf ("test %s\n", inname.c_str()); std::string outname = inname.substr (0,inname.size()-7) + "-out.txt"; std::string outnameES = inname.substr (0,inname.size()-7) + "-outES.txt"; bool ok = TestFile (type==0, testFolder + "/" + inname, testFolder + "/" + outname, false, hasOpenGL); if (ok) { ok = TestFile (type==0, testFolder + "/" + inname, testFolder + "/" + outnameES, true, false); } if (!ok) { ++errors; } } } clock_t time1 = clock(); float t = float(time1-time0) / float(CLOCKS_PER_SEC); if (errors != 0) printf ("%i tests, %i FAILED, %.2fs\n", tests, errors, t); else printf ("%i tests succeeded, %.2fs\n", tests, t); return errors ? 1 : 0; }
bool Materials::loadExtensions(FileName directoryName, wxString& error, wxArrayString& warnings) { directoryName.Mkdir(0755, wxPATH_MKDIR_FULL); // Create if it doesn't exist wxDir ext_dir(directoryName.GetPath()); if(ext_dir.IsOpened() == false) { error = wxT("Could not open extensions directory."); return false; } wxString filename; if(!ext_dir.GetFirst(&filename)) { // No extensions found return true; } do { FileName fn; fn.SetPath(directoryName.GetPath()); fn.SetFullName(filename); if(fn.GetExt() != wxT("xml")) continue; xmlDocPtr doc = xmlParseFile(fn.GetFullPath().mb_str()); if(doc) { xmlNodePtr root = xmlDocGetRootElement(doc); if(xmlStrcmp(root->name,(const xmlChar*)"materialsextension") != 0){ xmlFreeDoc(doc); warnings.push_back(filename + wxT(": Invalid rootheader.")); continue; } std::string ext_name, ext_url, ext_author, ext_author_link, ext_desc, ext_client_str; StringVector clientVersions; if( !readXMLValue(root, "name", ext_name) || !readXMLValue(root, "author", ext_author) || !readXMLValue(root, "description", ext_desc)) { warnings.push_back(filename + wxT(": Couldn't read extension attributes (name, author, description).")); continue; } readXMLValue(root, "url", ext_url); ext_url.erase(std::remove(ext_url.begin(), ext_url.end(), '\''), ext_url.end()); readXMLValue(root, "authorurl", ext_author_link); ext_author_link.erase(std::remove(ext_author_link.begin(), ext_author_link.end(), '\''), ext_author_link.end()); MaterialsExtension* me = newd MaterialsExtension(ext_name, ext_author, ext_desc); me->url = ext_url; me->author_url = ext_author_link; if(readXMLValue(root, "client", ext_client_str)) { size_t last_pos = std::numeric_limits<size_t>::max(); size_t pos; do { size_t to_pos = (last_pos == std::numeric_limits<size_t>::max()? 0 : last_pos+1); pos = ext_client_str.find(';', to_pos); if(size_t(pos) != std::string::npos) { clientVersions.push_back(ext_client_str.substr(to_pos, pos-(to_pos))); last_pos = pos; } else { clientVersions.push_back(ext_client_str.substr(to_pos)); break; } } while(true); for(StringVector::iterator iter = clientVersions.begin(); iter != clientVersions.end(); ++iter) { me->addVersion(*iter); } std::sort(me->version_list.begin(), me->version_list.end(), VersionComparisonPredicate); me->version_list.erase(std::unique(me->version_list.begin(), me->version_list.end()), me->version_list.end()); } else { warnings.push_back(filename + wxT(": Extension is not available for any version.")); } extensions.push_back(me); if(me->isForVersion(gui.GetCurrentVersionID())) { unserializeMaterials(filename, root, error, warnings); } } else { warnings.push_back(wxT("Could not open ") + filename + wxT(" (file not found or syntax error)")); continue; } } while(ext_dir.GetNext(&filename)); return true; }
int main (int argc, const char** argv) { if (argc < 2) { printf ("USAGE: glsloptimizer testfolder\n"); return 1; } bool hasOpenGL = InitializeOpenGL (); glslopt_ctx* ctx[2] = { glslopt_initialize(true), glslopt_initialize(false), }; std::string baseFolder = argv[1]; clock_t time0 = clock(); static const char* kTypeName[2] = { "vertex", "fragment" }; size_t tests = 0; size_t errors = 0; for (int type = 0; type < 2; ++type) { std::string testFolder = baseFolder + "/" + kTypeName[type]; static const char* kAPIName[2] = { "OpenGL ES 2.0", "OpenGL" }; static const char* kApiIn [2] = {"-inES.txt", "-in.txt"}; static const char* kApiIR [2] = {"-irES.txt", "-ir.txt"}; static const char* kApiOut[2] = {"-outES.txt", "-out.txt"}; for (int api = 0; api < 2; ++api) { printf ("\n** running %s tests for %s...\n", kTypeName[type], kAPIName[api]); StringVector inputFiles = GetFiles (testFolder, kApiIn[api]); size_t n = inputFiles.size(); for (size_t i = 0; i < n; ++i) { std::string inname = inputFiles[i]; //if (inname != "ast-in.txt") // continue; std::string hirname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiIR[api]; std::string outname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiOut[api]; bool ok = TestFile (ctx[api], type==0, inname, testFolder + "/" + inname, testFolder + "/" + hirname, testFolder + "/" + outname, api==0, hasOpenGL); if (!ok) { ++errors; } ++tests; } } } clock_t time1 = clock(); float timeDelta = float(time1-time0)/CLOCKS_PER_SEC; if (errors != 0) printf ("\n**** %i tests (%.2fsec), %i !!!FAILED!!!\n", tests, timeDelta, errors); else printf ("\n**** %i tests (%.2fsec) succeeded\n", tests, timeDelta); // 3.25s // with builtin call linking, 3.84s for (int i = 0; i < 2; ++i) glslopt_cleanup (ctx[i]); return errors ? 1 : 0; }
bool NucleusGridFunction:: readCellNucleusFile( const std::string cn_filename, const std::string gridFileName/* = ""*/ ) { bool okFlag=false; clearGrid2NucleusMap(); clearNucleus2GridMap(); FILE *fp=fopen( cn_filename.c_str(),"r"); if( !fp ) { okFlag=false; return( okFlag ); } DPrintf(DebugSolver,"reading file '%s'...\n",cn_filename.c_str()); DPrintf(DebugSolver,"------------------------------\n"); const int bufferLength=1000; char buffer[bufferLength]; while( fgets( buffer, bufferLength, fp)) { const int lineLength=strlen(buffer); typedef std::vector<std::string> StringVector; StringVector tokens; if( lineLength>0 ) { if( buffer[0]=='#' ) { buffer[lineLength-1]=0; DPrintf(DebugSolver,"comment< %s >\n", buffer); } else { using namespace std; Nucleus thisNuc; buffer[lineLength-1]=0; //printf("regular< %s >\n", buffer); string line(buffer); //cout << "<"<<line<<">\n"; typedef boost::tokenizer<>::iterator TokIterator; typedef boost::char_delimiters_separator<char> TokSeparator; //see boost::tokenizer 'char_delimiters_separator' docs // sep( returnable=false, returned="", separators=0) // --> separators=0 means anything for which iswhitespace() // is true is a separator TokSeparator sep(false,"",0); boost::tokenizer< TokSeparator> tok(line, sep); for (TokIterator it=tok.begin(); it!=tok.end(); ++it) { //DPrintf(DebugSolver,"<%s> ", it->c_str()); tokens.push_back( *it ); } //..INPUT FILE FORMAT FOR .cwn // format: <nucleus #> <radius> <x y z of center> <grid ID(s)> // lines with '#' in column 1 are comments int nID; const int idIndex=0; double rad; const int idRadius=1; double x,y,z; const int idX=2, idY=3, idZ=4; //std::vector<int> gridIDs; sscanf(tokens[idIndex].c_str(), "%d", &nID); sscanf(tokens[idRadius].c_str(), "%lg", &rad); sscanf(tokens[idX].c_str(), "%lg", &x); sscanf(tokens[idY].c_str(), "%lg", &y); sscanf(tokens[idZ].c_str(), "%lg", &z); DPrintf(DebugSolver," #tokens=%d, ztoken=%s -- ", tokens.size(), tokens[idZ].c_str()); DPrintf(DebugSolver,"id=%d, R=%f, x=%f, y=%f, z=%f,",nID,rad,x,y,z); DPrintf(DebugSolver,"\n"); thisNuc.setID( nID); thisNuc.setCenter(x,y,z); thisNuc.setRadius(rad); Nucleus::NucleusShape nucleusShape=Nucleus::SphericalNucleus; thisNuc.setShape( nucleusShape ); thisNuc.setBoundaryThickness( nucleusBoundaryThickness ); nucleus.push_back( thisNuc ); DPrintf(DebugSolver,"gridIDs for nucleus # %d=",nID); for( int i=idZ+1; i<tokens.size(); ++i ) { int gID=-1; sscanf(tokens[i].c_str(), "%d", &gID); DPrintf(DebugSolver," %d ",gID); grid2NucleusMap.insert( std::make_pair(gID,nID)); nucleus2GridMap.insert( std::make_pair(nID,gID)); } DPrintf(DebugSolver,"\n"); } }; } DPrintf(DebugSolver,"-------------done-------------\n"); fclose(fp); okFlag=true; return( okFlag ); }
//**************************************************************************************************** ERMsg CEnvCanGribForecast::Execute(CCallback& callback) { ERMsg msg; //string outputPath = GetDir(WORKING_DIR); callback.AddMessage(GetString(IDS_UPDATE_DIR)); callback.AddMessage(m_workingDir, 1); callback.AddMessage(GetString(IDS_UPDATE_FROM)); callback.AddMessage(SERVER_NAME, 1); callback.AddMessage(""); //delete old files msg = RemoveOldForecast(callback); if (!msg) return msg; CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME, pConnection, pSession); if (!msg) return msg; //size_t type = as<size_t>(TYPE); size_t delta_h = m_type == GT_HRDPS ? 1 : 3; callback.PushTask("Download gribs list", (MAX_FORECAST_HOURS / delta_h) ); StringVector fileList; //for (size_t HH = 0; HH < 24 && msg; HH+=6) size_t HH = GetLatestHH(pConnection); if (HH!=NOT_INIT) { for (size_t hhh = 0; hhh <= MAX_FORECAST_HOURS && msg; hhh += delta_h) { string remotePath = CEnvCanGribForecast::GetRemoteFilePath(HH, hhh, "*.grib2"); CFileInfoVector fileListTmp; msg = FindFiles(pConnection, remotePath, fileListTmp); //keep only some variables for (CFileInfoVector::iterator it = fileListTmp.begin(); it != fileListTmp.end(); it++) { string fileName = GetFileName(it->m_filePath); size_t hhh = Gethhh(fileName); size_t vv = GetVariable(fileName); if (hhh <= 48 && vv != NOT_INIT) fileList.push_back(it->m_filePath); } msg += callback.StepIt(); } } callback.PopTask(); callback.AddMessage("Number of gribs to download: " + ToString(fileList.size())); callback.PushTask("Download gribs (" + ToString(fileList.size()) +")", fileList.size()); int nbDownload = 0; for (size_t i = 0; i < fileList.size() && msg; i++) { string outputFilePath = GetOutputFilePath(GetFileName(fileList[i])); CreateMultipleDir(GetPath(outputFilePath)); msg = CopyFile(pConnection, fileList[i], outputFilePath.c_str(), INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE); if (msg) nbDownload++; msg += callback.StepIt(); } pConnection->Close(); pSession->Close(); callback.AddMessage("Number of gribs downloaded: " + ToString(nbDownload)); callback.PopTask(); return msg; }
//--------------------------------------------------------------------- void FontManager::parseAttribute(const String& line, FontPtr& pFont) { vector<String>::type params = StringUtil::split(line); String& attrib = params[0]; StringUtil::toLowerCase(attrib); if (attrib == "type") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set StringUtil::toLowerCase(params[1]); if (params[1] == "truetype") { pFont->setType(FT_TRUETYPE); } else { pFont->setType(FT_IMAGE); } } else if (attrib == "source") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setSource(params[1]); } else if (attrib == "glyph") { // Check params if (params.size() != 6) { logBadAttrib(line, pFont); return; } // Set // Support numeric and character glyph specification Font::CodePoint cp; if (params[1].at(0) == 'u' && params[1].size() > 1) { // Unicode glyph spec String trimmed = params[1].substr(1); cp = StringConverter::parseUnsignedInt(trimmed); } else { // Direct character cp = params[1].at(0); } pFont->setGlyphTexCoords( cp, StringConverter::parseReal(params[2]), StringConverter::parseReal(params[3]), StringConverter::parseReal(params[4]), StringConverter::parseReal(params[5]), 1.0 ); // assume image is square } else if (attrib == "size") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setTrueTypeSize( StringConverter::parseReal(params[1])); } else if (attrib == "character_spacer") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setCharacterSpacer( StringConverter::parseUnsignedInt(params[1])); } else if (attrib == "resolution") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setTrueTypeResolution( (uint)StringConverter::parseReal(params[1]) ); } else if (attrib == "antialias_colour") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setAntialiasColour(StringConverter::parseBool(params[1])); } else if (attrib == "code_points") { for (size_t c = 1; c < params.size(); ++c) { String& item = params[c]; StringVector itemVec = StringUtil::split(item, "-"); if (itemVec.size() == 2) { pFont->addCodePointRange(Font::CodePointRange( StringConverter::parseLong(itemVec[0]), StringConverter::parseLong(itemVec[1]))); } } } }
/*! * Extracts and stores logical lines of code. * Determines and extract logical SLOC to place in the result variable * using addSLOC function. Each time the addSLOC function is called, * a new logical SLOC is added. This function assumes that the directive * is handled before it is called. * * \param result counter results * \param line processed physical line of code * \param lineBak original physical line of code * \param strLSLOC processed logical string * \param strLSLOCBak original logical string * \param paren_cnt count of parenthesis * \param forflag found for flag * \param found_forifwhile found for, if, or while flag * \param found_while found while flag * \param prev_char previous character * \param data_continue continuation of a data declaration line * \param temp_lines tracks physical line count * \param phys_exec_lines number of physical executable lines * \param phys_data_lines number of physical data lines * \param inArrayDec marks an array declaration * \param found_for found for loop * \param openBrackets number of open brackets (no matching close bracket) * \param loopLevel nested loop level */ void CCJavaCsCounter::LSLOC(results* result, string line, size_t lineNumber, string lineBak, string &strLSLOC, string &strLSLOCBak, unsigned int &paren_cnt, bool &forflag, bool &found_forifwhile, bool &found_while, char &prev_char, bool &data_continue, unsigned int &temp_lines, unsigned int &phys_exec_lines, unsigned int &phys_data_lines, bool &inArrayDec, bool &found_for, unsigned int &openBrackets, StringVector &loopLevel) { // paren_cnt is used with 'for' statement only size_t start = 0; //starting index of the working string size_t i = 0, strSize; bool found_do, found_try, found_else, trunc_flag = false; string exclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$:"; string dataExclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$:()."; // avoid double count of casts as data and executable lines (e.g. set { m_uiValue = (uint)value; } unsigned int cnt = 0; string tmp = CUtil::TrimString(strLSLOC); // do, try found_do = (CUtil::FindKeyword(tmp, "do") != string::npos); found_try = (CUtil::FindKeyword(tmp, "try") != string::npos); // else is treated differently, else is included in SLOC, do and try are not found_else = (CUtil::FindKeyword(tmp, "else") != string::npos); // there may be more than 1 logical SLOC in this line while (i < line.length()) { switch (line[i]) { case ';': case '{': // LSLOC terminators // ';' for normal executable or declaration statement // '{' for starting a function or 'do' stmt or a block (which is counted) // get the previous logical mark until i-1 index is the new LSLOC // except 'do' precedes '{' // except '}' precedes ';' ?? // do nothing inside 'for' statement if (found_for == true && paren_cnt > 0 && line[i] == ';') break; // record open bracket for nested loop processing if (print_cmplx) { if (line[i] == '{') { openBrackets++; if ((unsigned int)loopLevel.size() < openBrackets) loopLevel.push_back(""); } else { if ((unsigned int)loopLevel.size() > openBrackets && openBrackets > 0) loopLevel.pop_back(); } } // case 'while(...);', 'while(...) {', and '} while(...);' // this case is handled in case ')' if (found_while && found_forifwhile) { found_while = false; found_forifwhile = false; start = i + 1; break; } if (line[i] == '{') { if (prev_char == '=') inArrayDec = true; // continue until seeing ';' if (inArrayDec) break; // case for(...); and if (...) { // these specials are handled if (found_forifwhile) { found_forifwhile = false; start = i + 1; break; } // check if 'do' precedes '{' if (!found_do && !found_try && !found_else) { // find for 'do' in string before tmp string tmp = CUtil::TrimString(line.substr(start, i - start)); found_do = (tmp == "do"); // found 'do' statement found_try = (tmp == "try"); // found 'try' statement // same as else found_else = (tmp == "else"); // found 'else' statement } if (found_do || found_try || found_else) { if (found_do && print_cmplx) { if (loopLevel.size() > 0) loopLevel.pop_back(); loopLevel.push_back("do"); } found_do = false; found_try = false; if (!found_else) { // everything before 'do', 'try' are cleared strLSLOC = ""; strLSLOCBak = ""; start = i + 1; } break; // do not store '{' following 'do' } } // wrong, e.g., a[]={1,2,3}; if (line[i] == ';' && prev_char == '}') { // check if in array declaration or not // if no, skip, otherwise, complete the SLOC containing array declaration if (!inArrayDec) { start = i + 1; break; } } inArrayDec = false; // check for empty statement (=1 LSLOC) if (CUtil::TrimString(line.substr(start, i + 1 - start)) == ";" && strLSLOC.length() < 1) { strLSLOC = ";"; strLSLOCBak = ";"; } else { strSize = CUtil::TruncateLine(i + 1 - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag); if (strSize > 0) { strLSLOC += line.substr(start, strSize); strLSLOCBak += lineBak.substr(start, strSize); } } if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag)) { cnt = 0; CUtil::CountTally(strLSLOC, data_name_list, cnt, 1, dataExclude, "", "", &result->data_name_count); temp_lines++; if (data_continue == true && line[i] == ';') { result->data_lines[LOG]++; phys_data_lines = temp_lines; } else { if (cnt > 0 && line[i] == ';') { result->data_lines[LOG]++; phys_data_lines = temp_lines; } else { result->exec_lines[LOG]++; phys_exec_lines = temp_lines; } } } else if (data_continue == true && line[i] == ';') phys_data_lines = temp_lines; else phys_exec_lines = temp_lines; data_continue = false; temp_lines = 0; strLSLOC = strLSLOCBak = ""; start = i + 1; // reset some flagging parameters forflag = false; paren_cnt = 0; found_while = false; found_forifwhile = false; found_for = false; break; case '(': if (forflag) paren_cnt++; else { // handle 'for', 'foreach', 'while', 'if' the same way tmp = CUtil::TrimString(line.substr(start, i)); if (CUtil::FindKeyword(tmp, "for") != string::npos || CUtil::FindKeyword(tmp, "foreach") != string::npos || CUtil::FindKeyword(tmp, "while") != string::npos || CUtil::FindKeyword(tmp, "if") != string::npos) { forflag = true; paren_cnt++; if (print_cmplx && (unsigned int)loopLevel.size() > openBrackets && openBrackets > 0) loopLevel.pop_back(); if (CUtil::FindKeyword(tmp, "for") != string::npos) { if (print_cmplx) loopLevel.push_back("for"); found_for = true; } else if (CUtil::FindKeyword(tmp, "while") != string::npos) { if (print_cmplx) loopLevel.push_back("while"); found_while = true; } else if (print_cmplx && CUtil::FindKeyword(tmp, "foreach") != string::npos) loopLevel.push_back("foreach"); // record nested loop level if (print_cmplx) { if (CUtil::FindKeyword(tmp, "if") == string::npos) { unsigned int loopCnt = 0; for (StringVector::iterator lit = loopLevel.begin(); lit < loopLevel.end(); lit++) { if ((*lit) != "") loopCnt++; } if ((unsigned int)result->cmplx_nestloop_count.size() < loopCnt) result->cmplx_nestloop_count.push_back(1); else result->cmplx_nestloop_count[loopCnt-1]++; } } } } break; case ')': if (forflag) { if (paren_cnt > 0) paren_cnt--; if (paren_cnt == 0) { // handle 'for', 'foreach', 'while', 'if' strSize = CUtil::TruncateLine(i + 1 - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag); if (strSize > 0) { strLSLOC += line.substr(start, strSize); strLSLOCBak += lineBak.substr(start, strSize); } if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag)) result->exec_lines[LOG]++; strLSLOCBak = strLSLOC = ""; phys_exec_lines = temp_lines; temp_lines = 0; start = i + 1; found_forifwhile = true; forflag = false; found_for = false; } } break; case '}': // skip '}' when found ';' and then '}' because '{' is counted already // also, {} is also skipped, counted if (prev_char == ';' || prev_char == '{' || prev_char == '}') if (!inArrayDec) start = i + 1; // record close bracket for nested loop processing if (print_cmplx) { if (openBrackets > 0) openBrackets--; if (loopLevel.size() > 0) loopLevel.pop_back(); } break; } if (line[i] != ' ' && line[i] != '\t') { // if ;}}} --> don't count }}} at all // also, if {}}} --> don't count }}} at all // if ( !(line[i] == '}' && (prev_char == ';' || prev_char == '{'))) // see case '}' above prev_char = line[i]; // change to not found if a char appears before if (line[i] != ')' && found_forifwhile) found_forifwhile = false; } i++; } tmp = CUtil::TrimString(line.substr(start, i - start)); strSize = CUtil::TruncateLine(tmp.length(), strLSLOC.length(), this->lsloc_truncate, trunc_flag); if (strSize > 0) { strLSLOC += tmp.substr(0, strSize); tmp = CUtil::TrimString(lineBak.substr(start, i - start)); strLSLOCBak += tmp.substr(0, strSize); // drop continuation symbol if (strLSLOC[strLSLOC.length()-1] == '\\') { strLSLOC = strLSLOC.substr(0, strLSLOC.length()-1); strLSLOCBak = strLSLOCBak.substr(0, strLSLOCBak.length()-1); } } // make sure that we are not beginning to process a new data line cnt = 0; CUtil::CountTally(strLSLOC, data_name_list, cnt, 1, exclude, "", "", NULL); if (cnt > 0) data_continue = true; if (data_continue) temp_lines++; if (temp_lines == 0 && phys_data_lines == 0 && phys_exec_lines == 0) phys_exec_lines = 1; }
//simulated annaling void CClimaticModel::AddSAResult(const StringVector& header, const StringVector& data) { if (header.size() == 12) { std::vector<double> obs(4); CTRef TRef(ToShort(data[2]), ToShort(data[3]) - 1, ToShort(data[4]) - 1, ToShort(data[5])); for (int i = 0; i < 4; i++) obs[i] = ToDouble(data[i + 6]); ASSERT(obs.size() == 4); m_SAResult.push_back(CSAResult(TRef, obs)); } /*if( header.size()==26) { std::vector<double> obs(24); for(int h=0; h<24; h++) obs[h] = data[h+2].ToDouble(); ASSERT( obs.size() == 24 ); m_SAResult.push_back( CSAResult(CTRef(), obs ) ); } else if( header.size()==13) { std::vector<double> obs(7); CTRef TRef(data[2].ToShort(),data[3].ToShort()-1,data[4].ToShort()-1,data[5].ToShort()); for(int c=0; c<7; c++) obs[c] = data[c+6].ToDouble(); ASSERT( obs.size() == 7 ); m_SAResult.push_back( CSAResult(TRef, obs ) ); } else if( header.size()==12) { std::vector<double> obs(7); CTRef TRef(data[2].ToShort(),data[3].ToShort()-1,data[4].ToShort()-1); for(int c=0; c<7; c++) obs[c] = data[c+5].ToDouble(); ASSERT( obs.size() == 7 ); m_SAResult.push_back( CSAResult(TRef, obs ) ); } else if( header.size()==11) { std::vector<double> obs(7); CTRef TRef(data[2].ToShort(),data[3].ToShort()-1); for(int c=0; c<7; c++) obs[c] = data[c+4].ToDouble(); ASSERT( obs.size() == 7 ); m_SAResult.push_back( CSAResult(TRef, obs ) ); }*/ }
void PathPlannerRecast::cmdSaveToObjFile( const StringVector & args ) { if ( mFlags.mViewMode == 0 ) return; if ( args.size() < 2 ) { EngineFuncs::ConsoleError( "nav_saveobj filename" ); return; } //size_t totalTriangles = 0; //for ( size_t m = 0; m < mModels.size(); ++m ) //{ // const ModelCache & model = mModels[ m ]; // // skip models not currently active // switch ( mModels[ m ].mActiveState ) // { // case StateCollidable: // break; // case StateUnknown: // default: // continue; // } // totalTriangles += model.mModel->GetNumTris(); //} //RenderBuffer::TriList triangles; //triangles.reserve( totalTriangles ); //for ( size_t m = 0; m < mModels.size(); ++m ) //{ // const ModelCache & model = mModels[ m ]; // // skip models not currently active // switch ( mModels[ m ].mActiveState ) // { // case StateCollidable: // break; // case StateUnknown: // default: // continue; // } // // // for now use all triangles for testing // for ( size_t t = 0; t < model.mModel->GetNumTris(); ++t ) // { // size_t materialIndex; // RenderBuffer::Triangle tri; // tri.c = COLOR::GREEN; // model.mModel->GetTriangle( model.mTransform, t, tri.v[ 0 ], tri.v[ 1 ], tri.v[ 2 ], materialIndex ); // const Material & mat = model.mModel->GetMaterial( materialIndex ); // if ( mat.mSurface & ( SURFACE_NONSOLID | SURFACE_IGNORE | SURFACE_SKY ) ) // continue; // triangles.push_back( tri ); // } //} //const std::string objfilename = args[ 1 ] + ".obj"; //const std::string matfilename = args[ 1 ] + ".mat"; //File objFile, matFile; //if ( objFile.OpenForWrite( objfilename.c_str(), File::Text, false ) && // matFile.OpenForWrite( matfilename.c_str(), File::Text, false ) ) //{ // // material // matFile.WriteString( va( "# Materials Navmesh - %s\n\n", gEngineFuncs->GetMapName() ).c_str() ); // matFile.WriteString( "Kd 0.000 1.000 0.000 # green" ); // // Mesh // objFile.WriteString( va( "# Navmesh - %s\n\n", gEngineFuncs->GetMapName() ).c_str() ); // objFile.WriteString( va( "mltlib %s\n", matfilename.c_str() ).c_str() ); // objFile.WriteString( va( "# Vertices %d\n", triangles.size() * 3 ).c_str() ); // // for ( size_t t = 0; t < triangles.size(); ++t ) // { // for ( size_t i = 0; i < 3; ++i ) // { // Vector3f vecRecast = /*localToRc*/( triangles[ t ].v[ i ] ); // objFile.WriteString( va( "v %f %f %f\n", // vecRecast.X(), // vecRecast.Y(), // vecRecast.Z() ).c_str() ); // } // } // objFile.WriteString( va( "\n# Faces %d\n", triangles.size() ).c_str() ); // for ( size_t t = 0; t < triangles.size(); ++t ) // { // objFile.WriteString( va( "f %d %d %d\n", t * 3 + 1, t * 3 + 2, t * 3 + 3 ).c_str() ); // } //} }
bool ScriptCommandExecutor::Exec( const StringVector & args, const gmVariable &_this ) { const bool bPrintUsage = args.size() > 1 && args[ 1 ] == "?"; if ( mCommandTable ) { DisableGCInScope gcEn( mMachine ); gmVariable vEntry = mCommandTable->Get( mMachine, args[ 0 ].c_str() ); gmFunctionObject *pFn = vEntry.GetFunctionObjectSafe(); if ( !pFn ) { // See if it's new style, and in a table. gmTableObject *pTbl = vEntry.GetTableObjectSafe(); if ( pTbl ) { pFn = pTbl->Get( mMachine, "Func" ).GetFunctionObjectSafe(); bool bRunImmediate = false; if ( !pTbl->Get( mMachine, "RunImmediate" ).GetBoolSafe( bRunImmediate, false ) ) bRunImmediate = false; if ( bPrintUsage ) { gmVariable vHelp = pTbl->Get( mMachine, "Help" ); const char *pHelpString = vHelp.GetCStringSafe( 0 ); if ( pHelpString ) { EngineFuncs::ConsoleMessage( pHelpString ); } else { gmTableObject *pUsageTbl = vHelp.GetTableObjectSafe(); if ( pUsageTbl ) { gmTableIterator tIt; gmTableNode *pNode = pUsageTbl->GetFirst( tIt ); while ( pNode ) { const char *pHelp = pNode->m_value.GetCStringSafe( 0 ); if ( pHelp ) EngineFuncs::ConsoleMessage( pHelp ); pNode = pUsageTbl->GetNext( tIt ); } } } return true; } } } if ( bPrintUsage ) { EngineFuncs::ConsoleError( va( "No Usage Info For Command: %s", args[ 0 ].c_str() ) ); return true; } if ( pFn ) { gmCall call; if ( call.BeginFunction( mMachine, pFn, _this, true ) ) { // Add all the params gmTableObject *pParamTable = mMachine->AllocTableObject(); if ( args.size() > 1 ) { for ( uint32_t i = 1; i < args.size(); ++i ) { char *endPtr; const char *startPtr = args[ i ].c_str(); long iNum = strtol( startPtr, &endPtr, 10 ); double dNum; if ( endPtr != startPtr && !*endPtr ) { pParamTable->Set( mMachine, i - 1, gmVariable( (int)iNum ) ); } else if ( Utils::ConvertString( args[ i ], dNum ) ) { pParamTable->Set( mMachine, i - 1, gmVariable( (float)dNum ) ); } else { pParamTable->Set( mMachine, i - 1, gmVariable( mMachine->AllocStringObject( args[ i ].c_str() ) ) ); } } } call.AddParamTable( pParamTable ); call.End(); return true; } } return false; } return false; }
void GetObjectResponse::ParseMultiPart(RetsHttpResponsePtr httpResponse, bool ignoreMalformedHeaders) { string contentType = httpResponse->GetContentType(); string boundary = FindBoundary(contentType); string delimiter = "\r\n--"; delimiter.append(boundary).append("\r\n"); string closeDelimiter = "\r\n--"; closeDelimiter.append(boundary).append("--"); string content = readIntoString(httpResponse->GetInputStream()); StringVector parts; string::size_type partStart; string::size_type partEnd; /* * libCURL appears to have a problem when handling a chunked encoded multi-part * response where the chunk length follows the CRLF that delineates the message * text from the message headers. That CRLF according to the RFCs is supposed to * be considered as part of the boundary, but in this case, libCURL fails to * include it in the data. So, we need to check to see if our content starts * with a boundary missing that leading CRLF. */ if (ignoreMalformedHeaders && !(content.substr(0,2) == "\r\n")) { content = "\r\n" + content; } partStart = content.find(delimiter); if (partStart == string::npos) { LIBRETS_THROW(RetsException, ("First delimiter not found: " + boundary)); } partStart += delimiter.size(); bool done = false; while (!done) { partEnd = content.find(delimiter, partStart); if (partEnd == string::npos) { partEnd = content.find(closeDelimiter, partStart); if (partEnd == string::npos) { if (!ignoreMalformedHeaders) LIBRETS_THROW( RetsException, ("Cound not find another delimiter: " + boundary)); /* * See if we can find some semblance of a trailing boundary. If so * exclude it from the data. Otherwise, include everything up to the * end of the data stream. */ closeDelimiter = "--"; closeDelimiter.append(boundary); partEnd = content.find(closeDelimiter, partStart); } done = true; } parts.push_back(string(content, partStart, (partEnd - partStart))); partStart = partEnd + delimiter.size(); } StringVector::iterator i; for (i = parts.begin(); i != parts.end(); i++) { istreamPtr partStream( new istringstream(*i)); ParsePartStream(partStream, ignoreMalformedHeaders); } }
//---------------------------------------------------------------------------------------------------------------- void CConfiguration::LoadWeapons( good::ini_file::const_iterator it ) { good::string_buffer sbBuffer(szMainBuffer, iMainBufferSize, false); CWeapons::Clear(); // Iterate throught key-values of weapons section. BLOG_D("Weapons:"); for ( good::ini_section::const_iterator itemIt = it->begin(); itemIt != it->end(); ++itemIt ) { sbBuffer = itemIt->value; good::escape(sbBuffer); StringVector aParams; good::split((good::string)sbBuffer, aParams, ',', true); good::vector<good::string> aAmmos[2]; good::vector<int> aAmmosCount[2]; CWeapon* pWeapon = new CWeapon(); StringVector aCurrent; aCurrent.reserve(4); bool bError = false; int iSecondary = 0; for ( StringVector::iterator paramsIt = aParams.begin(); paramsIt != aParams.end(); ++paramsIt ) { int iValue = -1; bool bProcessed = true; aCurrent.clear(); good::split(*paramsIt, aCurrent); BASSERT( aCurrent.size() > 0, exit(1) ); if ( aCurrent[0] == "class" ) { if ( aCurrent.size() > 1 ) { for ( int i=1; i<aCurrent.size(); ++i ) { TClass iClass = CTypeToString::ClassFromString(aCurrent[i]); if ( iClass == -1 ) { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Weapon %s, invalid class: %s.", itemIt->key.c_str(), aCurrent[1].c_str() ); bError = true; break; } FLAG_SET(1 << iClass, pWeapon->iClass); } if ( bError ) break; } else { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Weapon %s, class not specified.", itemIt->key.c_str() ); bError = true; break; } } else if ( aCurrent.size() == 1 ) { if ( aCurrent[0] == "secondary" ) iSecondary = CWeapon::SECONDARY; else { TWeaponFlags iFlag = CTypeToString::WeaponFlagsFromString(aCurrent[0]); if ( iFlag == -1 ) bProcessed = false; else FLAG_SET(iFlag, pWeapon->iFlags[iSecondary]); } } else if ( aCurrent.size() == 2 ) { if ( aCurrent[0] == "type" ) { int iType = CTypeToString::WeaponTypeFromString(aCurrent[1]); if ( iType == -1 ) { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Weapon %s, invalid type: %s.", itemIt->key.c_str(), aCurrent[1].c_str() ); bError = true; break; } pWeapon->iType = iType; // Set weapon default parameters. switch (iType) { case EWeaponMelee: case EWeaponPhysics: pWeapon->iAttackBullets[0] = pWeapon->iAttackBullets[1] = 0; break; case EWeaponRocket: case EWeaponGrenade: case EWeaponRemoteDetonation: pWeapon->iClipSize[0] = 1; break; } } else if ( aCurrent[0] == "preference" ) { iValue = CTypeToString::PreferenceFromString(aCurrent[1]); if ( iValue == -1 ) bProcessed = false; else pWeapon->iBotPreference = iValue; } else if ( aCurrent[0] == "team" ) { iValue = CMod::GetTeamIndex(aCurrent[1]); if ( iValue == -1 ) { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Weapon %s, invalid team: %s.", itemIt->key.c_str(), aCurrent[1].c_str() ); bError = true; break; } pWeapon->iTeam = 1 << iValue; } else if ( aCurrent[0] == "aim" ) { TWeaponAim iAim = CTypeToString::WeaponAimFromString(aCurrent[1]); if ( iAim == -1 ) bProcessed = false; else pWeapon->iAim[iSecondary] = iAim; } else { sscanf(aCurrent[1].c_str(), "%d", &iValue); if ( iValue < 0 ) { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Weapon %s, invalid number: %s for parameter %s.", itemIt->key.c_str(), aCurrent[1].c_str(), aCurrent[0].c_str() ); bError = true; break; } if ( aCurrent[0] == "clip" ) pWeapon->iClipSize[iSecondary] = iValue; else if ( aCurrent[0] == "damage" ) pWeapon->fDamage[iSecondary] = iValue; else if ( aCurrent[0] == "delay" ) pWeapon->fShotTime[iSecondary] = iValue / 1000.0f; else if ( aCurrent[0] == "hold" ) pWeapon->fHoldTime[iSecondary] = iValue / 1000.0f; else if ( aCurrent[0] == "reload_by" ) pWeapon->iReloadBy[iSecondary] = iValue; else if ( aCurrent[0] == "reload" ) pWeapon->fReloadTime[iSecondary] = iValue / 1000.0f; else if ( aCurrent[0] == "reload_start" ) pWeapon->fReloadStartTime[iSecondary] = iValue / 1000.0f; else if ( aCurrent[0] == "holster" ) pWeapon->fHolsterTime = iValue / 1000.0f; else if ( aCurrent[0] == "default_ammo" ) pWeapon->iDefaultAmmo[iSecondary] = iValue; else if ( aCurrent[0] == "max_ammo" ) pWeapon->iMaxAmmo[iSecondary] = iValue; else if ( aCurrent[0] == "bullets" ) pWeapon->iAttackBullets[iSecondary] = iValue; else if ( aCurrent[0] == "default_ammo" ) pWeapon->iDefaultAmmo[iSecondary] = iValue; else if ( aCurrent[0] == "zoom_distance" ) pWeapon->fMinDistanceSqr[1] = SQR(iValue); else if ( aCurrent[0] == "zoom_time" ) pWeapon->fShotTime[1] = iValue / 1000.0f; else bProcessed = false; } } else if ( aCurrent.size() == 3 ) { if ( aCurrent[0] == "ammo" ) { aAmmos[iSecondary].reserve(4); int iValue = -1; sscanf(aCurrent[2].c_str(), "%d", &iValue); if ( iValue <= 0 ) // Ammo count can't be 0. { BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_E( " Weapon %s, invalid parameter for '%s' ammo's count: %s.", itemIt->key.c_str(), aCurrent[1].c_str(), aCurrent[2].c_str()); bError = true; break; } good::string sAmmo(aCurrent[1], true); aAmmos[iSecondary].push_back(sAmmo); aAmmosCount[iSecondary].push_back(iValue); } else { int iValue1 = -1, iValue2 = -1; sscanf(aCurrent[1].c_str(), "%d", &iValue1); sscanf(aCurrent[2].c_str(), "%d", &iValue2); if ( (iValue1 < 0) || (iValue2 < 0) || (iValue1 >= CUtil::iMaxMapSize) || (iValue1 >= CUtil::iMaxMapSize) ) bProcessed = false; else { if ( aCurrent[0] == "parabolic" ) { pWeapon->iParabolicDistance0[iSecondary] = iValue1; pWeapon->iParabolicDistance45[iSecondary] = iValue2; } else if ( aCurrent[0] == "range" ) { pWeapon->fMinDistanceSqr[iSecondary] = SQR(iValue1); if ( iValue2 == 0 ) pWeapon->fMaxDistanceSqr[iSecondary] = CUtil::iMaxMapSizeSqr; else pWeapon->fMaxDistanceSqr[iSecondary] = SQR(iValue2); } else bProcessed = false; } } } else bProcessed = false; if ( !bProcessed ) { BLOG_W( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() ); BLOG_W( " Weapon %s, unknown keyword %s or invalid parameters, skipping.", itemIt->key.c_str(), aCurrent[0].c_str() ); } } if ( bError ) delete pWeapon; else { BLOG_D( " %s", itemIt->key.c_str() ); pWeapon->iId = CWeapons::Size(); BLOG_D( " id %d", pWeapon->iId ); if ( pWeapon->iTeam ) { BLOG_D( " team %s", CTypeToString::TeamFlagsToString(pWeapon->iTeam).c_str() ); //if ( FLAGS_SOME_SET(FDeathmatchTeamAllWeapons, CMod::iDeathmatchFlags) ) pWeapon->iTeam |= 1 << CMod::iUnassignedTeam; } else pWeapon->iTeam = -1; // Mark to use by any flag. if ( CMod::aClassNames.size() ) BLOG_D( " class %s", CTypeToString::ClassFlagsToString(pWeapon->iClass).c_str() ); else pWeapon->iClass = -1; // Mark to use by any flag. // If reload_by is not specified, assume reload refill the clip. for ( int i=0; i < 2; ++i ) if ( pWeapon->iReloadBy[i] == 0 ) pWeapon->iReloadBy[i] = pWeapon->iClipSize[i]; // Add weapon class. CItemClass cEntityClass; cEntityClass.sClassName.assign(itemIt->key, true); pWeapon->pWeaponClass = CItems::AddItemClassFor( EItemTypeWeapon, cEntityClass ); // Add ammo classes. pWeapon->aAmmos[0].reserve(aAmmos[0].size()); pWeapon->aAmmos[1].reserve(aAmmos[1].size()); for ( int iSec=0; iSec < 2; ++iSec ) for ( int i=0; i < aAmmos[iSec].size(); ++i ) { const good::string& sAmmo = aAmmos[iSec][i]; const CItemClass* pAmmoClass = CItems::GetItemClass( EItemTypeAmmo, sAmmo ); if ( !pAmmoClass ) { CItemClass cAmmoClass; cAmmoClass.sClassName = sAmmo; pAmmoClass = CItems::AddItemClassFor( EItemTypeAmmo, cAmmoClass ); } pWeapon->aAmmos[iSec].push_back( pAmmoClass ); pWeapon->aAmmosCount[iSec].push_back( aAmmosCount[iSec][i] ); BLOG_D( " ammo %s (%u bullets)", pWeapon->aAmmos[iSec][i]->sClassName.c_str(), pWeapon->aAmmosCount[iSec][i] ); } CWeaponWithAmmo cWeapon(pWeapon); CWeapons::Add(cWeapon); } } }
void Skeleton::_mergeSkeletonAnimations(const Skeleton* src, const BoneHandleMap& boneHandleMap, const StringVector& animations) { ushort handle; ushort numSrcBones = src->getNumBones(); ushort numDstBones = this->getNumBones(); if (boneHandleMap.size() != numSrcBones) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Number of bones in the bone handle map must equal to " "number of bones in the source skeleton.", "Skeleton::_mergeSkeletonAnimations"); } bool existsMissingBone = false; // Check source skeleton structures compatible with ourself (that means // identically bones with identical handles, and with same hierarchy, but // not necessary to have same number of bones and bone names). for (handle = 0; handle < numSrcBones; ++handle) { const Bone* srcBone = src->getBone(handle); ushort dstHandle = boneHandleMap[handle]; // Does it exists in target skeleton? if (dstHandle < numDstBones) { Bone* destBone = this->getBone(dstHandle); // Check both bones have identical parent, or both are root bone. const Bone* srcParent = static_cast<Bone*>(srcBone->getParent()); Bone* destParent = static_cast<Bone*>(destBone->getParent()); if ((srcParent || destParent) && (!srcParent || !destParent || boneHandleMap[srcParent->getHandle()] != destParent->getHandle())) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Source skeleton incompatible with this skeleton: " "difference hierarchy between bone '" + srcBone->getName() + "' and '" + destBone->getName() + "'.", "Skeleton::_mergeSkeletonAnimations"); } } else { existsMissingBone = true; } } // Clone bones if need if (existsMissingBone) { // Create missing bones for (handle = 0; handle < numSrcBones; ++handle) { const Bone* srcBone = src->getBone(handle); ushort dstHandle = boneHandleMap[handle]; // The bone is missing in target skeleton? if (dstHandle >= numDstBones) { Bone* dstBone = this->createBone(srcBone->getName(), dstHandle); // Sets initial transform dstBone->setPosition(srcBone->getInitialPosition()); dstBone->setOrientation(srcBone->getInitialOrientation()); dstBone->setScale(srcBone->getInitialScale()); dstBone->setInitialState(); } } // Link new bones to parent for (handle = 0; handle < numSrcBones; ++handle) { const Bone* srcBone = src->getBone(handle); ushort dstHandle = boneHandleMap[handle]; // Is new bone? if (dstHandle >= numDstBones) { const Bone* srcParent = static_cast<Bone*>(srcBone->getParent()); if (srcParent) { Bone* destParent = this->getBone(boneHandleMap[srcParent->getHandle()]); Bone* dstBone = this->getBone(dstHandle); destParent->addChild(dstBone); } } } // Derive root bones in case it was changed this->deriveRootBone(); // Reset binding pose for new bones this->reset(true); this->setBindingPose(); } // // We need to adapt animations from source to target skeleton, but since source // and target skeleton bones bind transform might difference, so we need to alter // keyframes in source to suit to target skeleton. // // For any given animation time, formula: // // LocalTransform = BindTransform * KeyFrame; // DerivedTransform = ParentDerivedTransform * LocalTransform // // And all derived transforms should be keep identically after adapt to // target skeleton, Then: // // DestDerivedTransform == SrcDerivedTransform // DestParentDerivedTransform == SrcParentDerivedTransform // ==> // DestLocalTransform = SrcLocalTransform // ==> // DestBindTransform * DestKeyFrame = SrcBindTransform * SrcKeyFrame // ==> // DestKeyFrame = inverse(DestBindTransform) * SrcBindTransform * SrcKeyFrame // // We define (inverse(DestBindTransform) * SrcBindTransform) as 'delta-transform' here. // // Calculate delta-transforms for all source bones. vector<DeltaTransform>::type deltaTransforms(numSrcBones); for (handle = 0; handle < numSrcBones; ++handle) { const Bone* srcBone = src->getBone(handle); DeltaTransform& deltaTransform = deltaTransforms[handle]; ushort dstHandle = boneHandleMap[handle]; if (dstHandle < numDstBones) { // Common bone, calculate delta-transform Bone* dstBone = this->getBone(dstHandle); deltaTransform.translate = srcBone->getInitialPosition() - dstBone->getInitialPosition(); deltaTransform.rotate = dstBone->getInitialOrientation().Inverse() * srcBone->getInitialOrientation(); deltaTransform.scale = srcBone->getInitialScale() / dstBone->getInitialScale(); // Check whether or not delta-transform is identity const Real tolerance = 1e-3f; Vector3 axis; Radian angle; deltaTransform.rotate.ToAngleAxis(angle, axis); deltaTransform.isIdentity = deltaTransform.translate.positionEquals(Vector3::ZERO, tolerance) && deltaTransform.scale.positionEquals(Vector3::UNIT_SCALE, tolerance) && Math::RealEqual(angle.valueRadians(), 0.0f, tolerance); } else { // New bone, the delta-transform is identity deltaTransform.translate = Vector3::ZERO; deltaTransform.rotate = Quaternion::IDENTITY; deltaTransform.scale = Vector3::UNIT_SCALE; deltaTransform.isIdentity = true; } } // Now copy animations ushort numAnimations; if (animations.empty()) numAnimations = src->getNumAnimations(); else numAnimations = static_cast<ushort>(animations.size()); for (ushort i = 0; i < numAnimations; ++i) { const Animation* srcAnimation; if (animations.empty()) { // Get animation of source skeleton by the given index srcAnimation = src->getAnimation(i); } else { // Get animation of source skeleton by the given name const LinkedSkeletonAnimationSource* linker; srcAnimation = src->_getAnimationImpl(animations[i], &linker); if (!srcAnimation || linker) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + animations[i], "Skeleton::_mergeSkeletonAnimations"); } } // Create target animation Animation* dstAnimation = this->createAnimation(srcAnimation->getName(), srcAnimation->getLength()); // Copy interpolation modes dstAnimation->setInterpolationMode(srcAnimation->getInterpolationMode()); dstAnimation->setRotationInterpolationMode(srcAnimation->getRotationInterpolationMode()); // Copy track for each bone for (handle = 0; handle < numSrcBones; ++handle) { const DeltaTransform& deltaTransform = deltaTransforms[handle]; ushort dstHandle = boneHandleMap[handle]; if (srcAnimation->hasNodeTrack(handle)) { // Clone track from source animation const NodeAnimationTrack* srcTrack = srcAnimation->getNodeTrack(handle); NodeAnimationTrack* dstTrack = dstAnimation->createNodeTrack(dstHandle, this->getBone(dstHandle)); dstTrack->setUseShortestRotationPath(srcTrack->getUseShortestRotationPath()); ushort numKeyFrames = srcTrack->getNumKeyFrames(); for (ushort k = 0; k < numKeyFrames; ++k) { const TransformKeyFrame* srcKeyFrame = srcTrack->getNodeKeyFrame(k); TransformKeyFrame* dstKeyFrame = dstTrack->createNodeKeyFrame(srcKeyFrame->getTime()); // Adjust keyframes to match target binding pose if (deltaTransform.isIdentity) { dstKeyFrame->setTranslate(srcKeyFrame->getTranslate()); dstKeyFrame->setRotation(srcKeyFrame->getRotation()); dstKeyFrame->setScale(srcKeyFrame->getScale()); } else { dstKeyFrame->setTranslate(deltaTransform.translate + srcKeyFrame->getTranslate()); dstKeyFrame->setRotation(deltaTransform.rotate * srcKeyFrame->getRotation()); dstKeyFrame->setScale(deltaTransform.scale * srcKeyFrame->getScale()); } } } else if (!deltaTransform.isIdentity) { // Create 'static' track for this bone NodeAnimationTrack* dstTrack = dstAnimation->createNodeTrack(dstHandle, this->getBone(dstHandle)); TransformKeyFrame* dstKeyFrame; dstKeyFrame = dstTrack->createNodeKeyFrame(0); dstKeyFrame->setTranslate(deltaTransform.translate); dstKeyFrame->setRotation(deltaTransform.rotate); dstKeyFrame->setScale(deltaTransform.scale); dstKeyFrame = dstTrack->createNodeKeyFrame(dstAnimation->getLength()); dstKeyFrame->setTranslate(deltaTransform.translate); dstKeyFrame->setRotation(deltaTransform.rotate); dstKeyFrame->setScale(deltaTransform.scale); } } } }
//----------------------------------------------------------------------- void RenderSystemCapabilitiesSerializer::parseScript(DataStreamPtr& stream) { // reset parsing data to NULL mCurrentLineNumber = 0; mCurrentLine = 0; mCurrentStream.setNull(); mCurrentCapabilities = 0; mCurrentStream = stream; // parser operating data String line; ParseAction parseAction = PARSE_HEADER; StringVector tokens; bool parsedAtLeastOneRSC = false; // collect capabilities lines (i.e. everything that is not header, "{", "}", // comment or empty line) for further processing CapabilitiesLinesList capabilitiesLines; // for reading data char tmpBuf[OGRE_STREAM_TEMP_SIZE]; // TODO: build a smarter tokenizer so that "{" and "}" // don't need separate lines while (!stream->eof()) { stream->readLine(tmpBuf, OGRE_STREAM_TEMP_SIZE-1); line = String(tmpBuf); StringUtil::trim(line); // keep track of parse position mCurrentLine = &line; mCurrentLineNumber++; tokens = StringUtil::split(line); // skip empty and comment lines // TODO: handle end of line comments if (tokens[0] == "" || tokens[0].substr(0,2) == "//") continue; switch (parseAction) { // header line must look like this: // render_system_capabilities "Vendor Card Name Version xx.xxx" case PARSE_HEADER: if(tokens[0] != "render_system_capabilities") { logParseError("The first keyword must be render_system_capabilities. RenderSystemCapabilities NOT created!"); return; } else { // the rest of the tokens are irrevelant, beause everything between "..." is one name String rscName = line.substr(tokens[0].size()); StringUtil::trim(rscName); // the second argument must be a "" delimited string if (!StringUtil::match(rscName, "\"*\"")) { logParseError("The argument to render_system_capabilities must be a quote delimited (\"...\") string. RenderSystemCapabilities NOT created!"); return; } else { // we have a valid header // remove quotes rscName = rscName.substr(1); rscName = rscName.substr(0, rscName.size() - 1); // create RSC mCurrentCapabilities = OGRE_NEW RenderSystemCapabilities(); // RSCManager is responsible for deleting mCurrentCapabilities RenderSystemCapabilitiesManager::getSingleton()._addRenderSystemCapabilities(rscName, mCurrentCapabilities); LogManager::getSingleton().logMessage("Created RenderSystemCapabilities" + rscName); // do next action parseAction = FIND_OPEN_BRACE; parsedAtLeastOneRSC = true; } } break; case FIND_OPEN_BRACE: if (tokens[0] != "{" || tokens.size() != 1) { logParseError("Expected '{' got: " + line + ". Continuing to next line."); } else { parseAction = COLLECT_LINES; } break; case COLLECT_LINES: if (tokens[0] == "}") { // this render_system_capabilities section is over // let's process the data and look for the next one parseCapabilitiesLines(capabilitiesLines); capabilitiesLines.clear(); parseAction = PARSE_HEADER; } else capabilitiesLines.push_back(CapabilitiesLinesList::value_type(line, mCurrentLineNumber)); break; } } // Datastream is empty // if we are still looking for header, this means that we have either // finished reading one, or this is an empty file if(parseAction == PARSE_HEADER && parsedAtLeastOneRSC == false) { logParseError ("The file is empty"); } if(parseAction == FIND_OPEN_BRACE) { logParseError ("Bad .rendercaps file. Were not able to find a '{'"); } if(parseAction == COLLECT_LINES) { logParseError ("Bad .rendercaps file. Were not able to find a '}'"); } }
void VideoRegionsConfigDialog::apply() { // FIXME: Bad code AutoLock al(m_config); // // Clear old video classes names container // StringVector *videoClasses = m_config->getVideoClassNames(); videoClasses->clear(); std::vector<Rect> *videoRects = m_config->getVideoRects(); videoRects->clear(); // // Split text from text area to string array // StringStorage classNames; m_videoClasses.getText(&classNames); size_t count = 0; TCHAR delimiters[] = _T(" \n\r\t,;"); classNames.split(delimiters, NULL, &count); if (count != 0) { std::vector<StringStorage> chunks(count); classNames.split(delimiters, &chunks.front(), &count); for (size_t i = 0; i < count; i++) { if (!chunks[i].isEmpty()) { videoClasses->push_back(chunks[i].getString()); } } } StringStorage videoRectsStringStorage; m_videoRects.getText(&videoRectsStringStorage); count = 0; videoRectsStringStorage.split(delimiters, NULL, &count); if (count != 0) { std::vector<StringStorage> chunks(count); videoRectsStringStorage.split(delimiters, &chunks.front(), &count); for (size_t i = 0; i < count; i++) { if (!chunks[i].isEmpty()) { try { videoRects->push_back(RectSerializer::toRect(&chunks[i])); } catch (...) { // Ignore wrong formatted strings } } } } // // TODO: Create parseUInt method // StringStorage vriss; m_videoRecognitionInterval.getText(&vriss); int interval; StringParser::parseInt(vriss.getString(), &interval); m_config->setVideoRecognitionInterval((unsigned int)interval); }
void NumericExpression::init() { StringTokenizer tokenizer( "", "'\"" ); tokenizer.addDelims( "[],()%*/+-", true ); tokenizer.keepEmpties() = false; StringVector t; tokenizer.tokenize( _src, t ); //tokenize(_src, t, "[],()%*/+-", "'\"", false, true); // identify tokens: AtomVector infix; bool invar = false; for( unsigned i=0; i<t.size(); ++i ) { if ( t[i] == "[" && !invar ) { invar = true; } else if ( t[i] == "]" && invar ) { invar = false; infix.push_back( Atom(VARIABLE,0.0) ); _vars.push_back( Variable(t[i-1],0) ); } else if ( t[i] == "(" ) infix.push_back( Atom(LPAREN,0.0) ); else if ( t[i] == ")" ) infix.push_back( Atom(RPAREN,0.0) ); else if ( t[i] == "," ) infix.push_back( Atom(COMMA,0.0) ); else if ( t[i] == "%" ) infix.push_back( Atom(MOD,0.0) ); else if ( t[i] == "*" ) infix.push_back( Atom(MULT,0.0) ); else if ( t[i] == "/" ) infix.push_back( Atom(DIV,0.0) ); else if ( t[i] == "+" ) infix.push_back( Atom(ADD,0.0) ); else if ( t[i] == "-" ) infix.push_back( Atom(SUB,0.0) ); else if ( t[i] == "min" ) infix.push_back( Atom(MIN,0.0) ); else if ( t[i] == "max" ) infix.push_back( Atom(MAX,0.0) ); else if ( t[i][0] >= '0' && t[i][0] <= '9' ) infix.push_back( Atom(OPERAND,as<double>(t[i],0.0)) ); // note: do nothing for a comma } // convert to RPN: // http://en.wikipedia.org/wiki/Shunting-yard_algorithm AtomStack s; unsigned var_i = 0; for( unsigned i=0; i<infix.size(); ++i ) { Atom& a = infix[i]; if ( a.first == LPAREN ) { s.push( a ); } else if ( a.first == RPAREN ) { while( s.size() > 0 ) { Atom top = s.top(); s.pop(); if ( top.first == LPAREN ) break; else _rpn.push_back( top ); } } else if ( a.first == COMMA ) { while( s.size() > 0 && s.top().first != LPAREN ) { _rpn.push_back( s.top() ); s.pop(); } } else if ( IS_OPERATOR(a) ) { if ( s.empty() || a.first > s.top().first ) { s.push( a ); } else { while( s.size() > 0 && a.first < s.top().first && IS_OPERATOR(s.top()) ) { _rpn.push_back( s.top() ); s.pop(); } s.push( a ); } } else if ( a.first == MIN || a.first == MAX ) { s.push( a ); } else if ( a.first == OPERAND ) { _rpn.push_back( a ); } else if ( a.first == VARIABLE ) { _rpn.push_back( a ); _vars[var_i++].second = _rpn.size()-1; // store the index } } while( s.size() > 0 ) { _rpn.push_back( s.top() ); s.pop(); } }
RenderWindow* Win32GLSupport::createWindow(bool autoCreateWindow, GL3PlusRenderSystem* renderSystem, const String& windowTitle) { if (autoCreateWindow) { ConfigOptionMap::iterator opt = mOptions.find("Full Screen"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find full screen options!", "Win32GLSupport::createWindow"); bool fullscreen = (opt->second.currentValue == "Yes"); opt = mOptions.find("Video Mode"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find video mode options!", "Win32GLSupport::createWindow"); String val = opt->second.currentValue; String::size_type pos = val.find('x'); if (pos == String::npos) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid Video Mode provided", "Win32GLSupport::createWindow"); unsigned int w = StringConverter::parseUnsignedInt(val.substr(0, pos)); unsigned int h = StringConverter::parseUnsignedInt(val.substr(pos + 1)); // Parse optional parameters NameValuePairList winOptions; opt = mOptions.find("Colour Depth"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find Colour Depth options!", "Win32GLSupport::createWindow"); unsigned int colourDepth = StringConverter::parseUnsignedInt(opt->second.currentValue); winOptions["colourDepth"] = StringConverter::toString(colourDepth); opt = mOptions.find("VSync"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find VSync options!", "Win32GLSupport::createWindow"); bool vsync = (opt->second.currentValue == "Yes"); winOptions["vsync"] = StringConverter::toString(vsync); opt = mOptions.find("VSync Interval"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find VSync Interval options!", "Win32GLSupport::createWindow"); winOptions["vsyncInterval"] = opt->second.currentValue; opt = mOptions.find("Display Frequency"); if (opt != mOptions.end()) { unsigned int displayFrequency = StringConverter::parseUnsignedInt(opt->second.currentValue); winOptions["displayFrequency"] = StringConverter::toString(displayFrequency); } opt = mOptions.find("FSAA"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find FSAA options!", "Win32GLSupport::createWindow"); StringVector aavalues = StringUtil::split(opt->second.currentValue, " ", 1); unsigned int multisample = StringConverter::parseUnsignedInt(aavalues[0]); String multisample_hint; if (aavalues.size() > 1) multisample_hint = aavalues[1]; opt = mOptions.find("Fixed Pipeline Enabled"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find Fixed Pipeline enabled options!", "Win32GLSupport::createWindow"); bool enableFixedPipeline = (opt->second.currentValue == "Yes"); renderSystem->setFixedPipelineEnabled(enableFixedPipeline); winOptions["FSAA"] = StringConverter::toString(multisample); winOptions["FSAAHint"] = multisample_hint; opt = mOptions.find("sRGB Gamma Conversion"); if (opt == mOptions.end()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find sRGB options!", "Win32GLSupport::createWindow"); bool hwGamma = (opt->second.currentValue == "Yes"); winOptions["gamma"] = StringConverter::toString(hwGamma); return renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &winOptions); } else { // XXX What is the else? return NULL; } }
int RtspThread::run() { std::string message; std::string response; response.reserve( ZM_NETWORK_BUFSIZ ); if ( !mRtspSocket.connect( mHost.c_str(), strtol( mPort.c_str(), NULL, 10 ) ) ) Fatal( "Unable to connect RTSP socket" ); //Select select( 0.25 ); //select.addReader( &mRtspSocket ); //while ( select.wait() ) //{ //mRtspSocket.recv( response ); //Debug( 4, "Drained %d bytes from RTSP socket", response.size() ); //} if ( mMethod == RTP_RTSP_HTTP ) { if ( !mRtspSocket2.connect( mHost.c_str(), strtol( mPort.c_str(), NULL, 10 ) ) ) Fatal( "Unable to connect auxiliary RTSP/HTTP socket" ); //Select select( 0.25 ); //select.addReader( &mRtspSocket2 ); //while ( select.wait() ) //{ //mRtspSocket2.recv( response ); //Debug( 4, "Drained %d bytes from HTTP socket", response.size() ); //} message = "GET "+mPath+" HTTP/1.0\r\n"; message += "X-SessionCookie: "+mHttpSession+"\r\n"; if ( !mAuth.empty() ) message += stringtf( "Authorization: Basic %s\r\n", mAuth64.c_str() ); message += "\r\n"; Debug( 2, "Sending HTTP message: %s", message.c_str() ); if ( mRtspSocket.send( message.c_str(), message.size() ) != (int)message.length() ) { Error( "Unable to send message '%s': %s", message.c_str(), strerror(errno) ); return( -1 ); } if ( mRtspSocket.recv( response ) < 0 ) { Error( "Recv failed; %s", strerror(errno) ); return( -1 ); } Debug( 2, "Received HTTP response: %s (%zd bytes)", response.c_str(), response.size() ); float respVer = 0; int respCode = -1; char respText[256]; if ( sscanf( response.c_str(), "HTTP/%f %3d %[^\r\n]\r\n", &respVer, &respCode, respText ) != 3 ) { if ( isalnum(response[0]) ) { Error( "Response parse failure in '%s'", response.c_str() ); } else { Error( "Response parse failure, %zd bytes follow", response.size() ); if ( response.size() ) Hexdump( Logger::ERROR, response.data(), min(response.size(),16) ); } return( -1 ); } if ( respCode != 200 ) { Error( "Unexpected response code %d, text is '%s'", respCode, respText ); return( -1 ); } message = "POST "+mPath+" HTTP/1.0\r\n"; message += "X-SessionCookie: "+mHttpSession+"\r\n"; if ( !mAuth.empty() ) message += stringtf( "Authorization: Basic %s\r\n", mAuth64.c_str() ); message += "Content-Length: 32767\r\n"; message += "Content-Type: application/x-rtsp-tunnelled\r\n"; message += "\r\n"; Debug( 2, "Sending HTTP message: %s", message.c_str() ); if ( mRtspSocket2.send( message.c_str(), message.size() ) != (int)message.length() ) { Error( "Unable to send message '%s': %s", message.c_str(), strerror(errno) ); return( -1 ); } } std::string localHost = ""; int localPorts[2] = { 0, 0 }; //message = "OPTIONS * RTSP/1.0\r\n"; //sendCommand( message ); //recvResponse( response ); message = "DESCRIBE "+mUrl+" RTSP/1.0\r\n"; sendCommand( message ); sleep( 1 ); recvResponse( response ); const std::string endOfHeaders = "\r\n\r\n"; size_t sdpStart = response.find( endOfHeaders ); if( sdpStart == std::string::npos ) return( -1 ); sdpStart += endOfHeaders.length(); std::string sdp = response.substr( sdpStart ); Debug( 1, "Processing SDP '%s'", sdp.c_str() ); SessionDescriptor *sessDesc = 0; try { sessDesc = new SessionDescriptor( mUrl, sdp ); mFormatContext = sessDesc->generateFormatContext(); } catch( const Exception &e ) { Error( e.getMessage().c_str() ); return( -1 ); } #if 0 // New method using ffmpeg native functions std::string authUrl = mUrl; if ( !mAuth.empty() ) authUrl.insert( authUrl.find( "://" )+3, mAuth+"@" ); if ( av_open_input_file( &mFormatContext, authUrl.c_str(), NULL, 0, NULL ) != 0 ) { Error( "Unable to open input '%s'", authUrl.c_str() ); return( -1 ); } #endif uint32_t rtpClock = 0; std::string trackUrl = mUrl; #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(54,25,0) enum AVCodecID codecId; #else enum CodecID codecId; #endif if ( mFormatContext->nb_streams >= 1 ) { for ( unsigned int i = 0; i < mFormatContext->nb_streams; i++ ) { SessionDescriptor::MediaDescriptor *mediaDesc = sessDesc->getStream( i ); #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(51,2,1) if ( mFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ) #else if ( mFormatContext->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO ) #endif { trackUrl += "/"+mediaDesc->getControlUrl(); rtpClock = mediaDesc->getClock(); codecId = mFormatContext->streams[i]->codec->codec_id; // Hackery pokery //rtpClock = mFormatContext->streams[i]->codec->sample_rate; break; } } } switch( mMethod ) { case RTP_UNICAST : { localPorts[0] = requestPorts(); localPorts[1] = localPorts[0]+1; message = "SETUP "+trackUrl+" RTSP/1.0\r\nTransport: RTP/AVP;unicast;client_port="+stringtf( "%d", localPorts[0] )+"-"+stringtf( "%d", localPorts[1] )+"\r\n"; break; } case RTP_MULTICAST : { message = "SETUP "+trackUrl+" RTSP/1.0\r\nTransport: RTP/AVP;multicast\r\n"; break; } case RTP_RTSP : case RTP_RTSP_HTTP : { message = "SETUP "+trackUrl+" RTSP/1.0\r\nTransport: RTP/AVP/TCP;unicast\r\n"; break; } default: { Panic( "Got unexpected method %d", mMethod ); break; } } if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); StringVector lines = split( response, "\r\n" ); char *session = 0; int timeout = 0; char transport[256] = ""; for ( size_t i = 0; i < lines.size(); i++ ) { sscanf( lines[i].c_str(), "Session: %a[0-9a-fA-F]; timeout=%d", &session, &timeout ); sscanf( lines[i].c_str(), "Transport: %s", transport ); } if ( !session ) Fatal( "Unable to get session identifier from response '%s'", response.c_str() ); Debug( 2, "Got RTSP session %s, timeout %d secs", session, timeout ); if ( !transport[0] ) Fatal( "Unable to get transport details from response '%s'", response.c_str() ); Debug( 2, "Got RTSP transport %s", transport ); std::string method = ""; int remotePorts[2] = { 0, 0 }; int remoteChannels[2] = { 0, 0 }; std::string distribution = ""; unsigned long ssrc = 0; StringVector parts = split( transport, ";" ); for ( size_t i = 0; i < parts.size(); i++ ) { if ( parts[i] == "unicast" || parts[i] == "multicast" ) distribution = parts[i]; else if ( startsWith( parts[i], "server_port=" ) ) { method = "RTP/UNICAST"; StringVector subparts = split( parts[i], "=" ); StringVector ports = split( subparts[1], "-" ); remotePorts[0] = strtol( ports[0].c_str(), NULL, 10 ); remotePorts[1] = strtol( ports[1].c_str(), NULL, 10 ); } else if ( startsWith( parts[i], "interleaved=" ) ) { method = "RTP/RTSP"; StringVector subparts = split( parts[i], "=" ); StringVector channels = split( subparts[1], "-" ); remoteChannels[0] = strtol( channels[0].c_str(), NULL, 10 ); remoteChannels[1] = strtol( channels[1].c_str(), NULL, 10 ); } else if ( startsWith( parts[i], "port=" ) ) { method = "RTP/MULTICAST"; StringVector subparts = split( parts[i], "=" ); StringVector ports = split( subparts[1], "-" ); localPorts[0] = strtol( ports[0].c_str(), NULL, 10 ); localPorts[1] = strtol( ports[1].c_str(), NULL, 10 ); } else if ( startsWith( parts[i], "destination=" ) ) { StringVector subparts = split( parts[i], "=" ); localHost = subparts[1]; } else if ( startsWith( parts[i], "ssrc=" ) ) { StringVector subparts = split( parts[i], "=" ); ssrc = strtoll( subparts[1].c_str(), NULL, 16 ); } } Debug( 2, "RTSP Method is %s", method.c_str() ); Debug( 2, "RTSP Distribution is %s", distribution.c_str() ); Debug( 2, "RTSP SSRC is %lx", ssrc ); Debug( 2, "RTSP Local Host is %s", localHost.c_str() ); Debug( 2, "RTSP Local Ports are %d/%d", localPorts[0], localPorts[1] ); Debug( 2, "RTSP Remote Ports are %d/%d", remotePorts[0], remotePorts[1] ); Debug( 2, "RTSP Remote Channels are %d/%d", remoteChannels[0], remoteChannels[1] ); message = "PLAY "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\nRange: npt=0.000-\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); lines = split( response, "\r\n" ); char *rtpInfo = 0; for ( size_t i = 0; i < lines.size(); i++ ) { sscanf( lines[i].c_str(), "RTP-Info: %as", &rtpInfo ); } if ( !rtpInfo ) Fatal( "Unable to get RTP Info identifier from response '%s'", response.c_str() ); Debug( 2, "Got RTP Info %s", rtpInfo ); int seq = 0; unsigned long rtpTime = 0; parts = split( rtpInfo, ";" ); for ( size_t i = 0; i < parts.size(); i++ ) { if ( startsWith( parts[i], "seq=" ) ) { StringVector subparts = split( parts[i], "=" ); seq = strtol( subparts[1].c_str(), NULL, 10 ); } else if ( startsWith( parts[i], "rtptime=" ) ) { StringVector subparts = split( parts[i], "=" ); rtpTime = strtol( subparts[1].c_str(), NULL, 10 ); } } Debug( 2, "RTSP Seq is %d", seq ); Debug( 2, "RTSP Rtptime is %ld", rtpTime ); switch( mMethod ) { case RTP_UNICAST : { RtpSource *source = new RtpSource( mId, "", localPorts[0], mHost, remotePorts[0], ssrc, seq, rtpClock, rtpTime, codecId ); mSources[ssrc] = source; RtpDataThread rtpDataThread( *this, *source ); RtpCtrlThread rtpCtrlThread( *this, *source ); rtpDataThread.start(); rtpCtrlThread.start(); while( !mStop ) { usleep( 100000 ); } #if 0 message = "PAUSE "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); #endif message = "TEARDOWN "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); rtpDataThread.stop(); rtpCtrlThread.stop(); //rtpDataThread.kill( SIGTERM ); //rtpCtrlThread.kill( SIGTERM ); rtpDataThread.join(); rtpCtrlThread.join(); delete mSources[ssrc]; mSources.clear(); releasePorts( localPorts[0] ); break; } case RTP_RTSP : case RTP_RTSP_HTTP : { RtpSource *source = new RtpSource( mId, "", remoteChannels[0], mHost, remoteChannels[0], ssrc, seq, rtpClock, rtpTime, codecId ); mSources[ssrc] = source; // These never actually run RtpDataThread rtpDataThread( *this, *source ); RtpCtrlThread rtpCtrlThread( *this, *source ); Select select( double(config.http_timeout)/1000.0 ); select.addReader( &mRtspSocket ); Buffer buffer( ZM_NETWORK_BUFSIZ ); time_t lastKeepalive = time(NULL); std::string keepaliveMessage = "OPTIONS * RTSP/1.0\r\n"; std::string keepaliveResponse = "RTSP/1.0 200 OK\r\n"; while ( !mStop && select.wait() >= 0 ) { Select::CommsList readable = select.getReadable(); if ( readable.size() == 0 ) { Error( "RTSP timed out" ); break; } static char tempBuffer[ZM_NETWORK_BUFSIZ]; ssize_t nBytes = mRtspSocket.recv( tempBuffer, sizeof(tempBuffer) ); buffer.append( tempBuffer, nBytes ); Debug( 4, "Read %zd bytes on sd %d, %d total", nBytes, mRtspSocket.getReadDesc(), buffer.size() ); while( buffer.size() > 0 ) { if ( buffer[0] == '$' ) { if ( buffer.size() < 4 ) break; unsigned char channel = buffer[1]; unsigned short len = ntohs( *((unsigned short *)(buffer+2)) ); Debug( 4, "Got %d bytes left, expecting %d byte packet on channel %d", buffer.size(), len, channel ); if ( (unsigned short)buffer.size() < (len+4) ) { Debug( 4, "Missing %d bytes, rereading", (len+4)-buffer.size() ); break; } if ( channel == remoteChannels[0] ) { Debug( 4, "Got %d bytes on data channel %d, packet length is %d", buffer.size(), channel, len ); Hexdump( 4, (char *)buffer, 16 ); rtpDataThread.recvPacket( buffer+4, len ); Debug( 4, "Received" ); } else if ( channel == remoteChannels[1] ) { // len = ntohs( *((unsigned short *)(buffer+2)) ); // Debug( 4, "Got %d bytes on control channel %d", nBytes, channel ); Debug( 4, "Got %d bytes on control channel %d, packet length is %d", buffer.size(), channel, len ); Hexdump( 4, (char *)buffer, 16 ); rtpCtrlThread.recvPackets( buffer+4, len ); } else { Error( "Unexpected channel selector %d in RTSP interleaved data", buffer[1] ); buffer.clear(); break; } buffer.consume( len+4 ); nBytes -= len+4; } else { if ( keepaliveResponse.compare( 0, keepaliveResponse.size(), (char *)buffer, keepaliveResponse.size() ) == 0 ) { Debug( 4, "Got keepalive response '%s'", (char *)buffer ); //buffer.consume( keepaliveResponse.size() ); if ( char *charPtr = (char *)memchr( (char *)buffer, '$', buffer.size() ) ) { int discardBytes = charPtr-(char *)buffer; buffer -= discardBytes; } else { buffer.clear(); } } else { if ( char *charPtr = (char *)memchr( (char *)buffer, '$', buffer.size() ) ) { int discardBytes = charPtr-(char *)buffer; Warning( "Unexpected format RTSP interleaved data, resyncing by %d bytes", discardBytes ); Hexdump( -1, (char *)buffer, discardBytes ); buffer -= discardBytes; } else { Warning( "Unexpected format RTSP interleaved data, dumping %d bytes", buffer.size() ); Hexdump( -1, (char *)buffer, 32 ); buffer.clear(); } } } } if ( (timeout > 0) && ((time(NULL)-lastKeepalive) > (timeout-5)) ) { if ( !sendCommand( message ) ) return( -1 ); lastKeepalive = time(NULL); } buffer.tidy( 1 ); } #if 0 message = "PAUSE "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); #endif message = "TEARDOWN "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); delete mSources[ssrc]; mSources.clear(); break; } case RTP_MULTICAST : { RtpSource *source = new RtpSource( mId, localHost, localPorts[0], mHost, remotePorts[0], ssrc, seq, rtpClock, rtpTime, codecId ); mSources[ssrc] = source; RtpDataThread rtpDataThread( *this, *source ); RtpCtrlThread rtpCtrlThread( *this, *source ); rtpDataThread.start(); rtpCtrlThread.start(); while( !mStop ) { usleep( 100000 ); } #if 0 message = "PAUSE "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); #endif message = "TEARDOWN "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; if ( !sendCommand( message ) ) return( -1 ); if ( !recvResponse( response ) ) return( -1 ); rtpDataThread.stop(); rtpCtrlThread.stop(); rtpDataThread.join(); rtpCtrlThread.join(); delete mSources[ssrc]; mSources.clear(); releasePorts( localPorts[0] ); break; } default: { Panic( "Got unexpected method %d", mMethod ); break; } } return( 0 ); }
void ycom::NullTermArray::eraseAppended (StringVector const &values) { typedef typename StringVector::iterator SVIterator; SVIterator storedNewStringsEnd = priv->storedNewStrings.end (); /* Start search from at least values.size () from the end */ auto searchStartPoint = storedNewStringsEnd - (values.size ()); SVIterator firstStoredNewStringsIterator = std::find (searchStartPoint, storedNewStringsEnd, values.front ()); if (firstStoredNewStringsIterator != storedNewStringsEnd) { typedef typename StringVector::const_iterator CSVIterator; auto stringsEqual = [](SVIterator const &lhs, CSVIterator const &rhs) -> bool { return *lhs == *rhs; }; auto lastStoredNewStringIterator = rangeMatchingPredicate (values, firstStoredNewStringsIterator, storedNewStringsEnd, stringsEqual); typedef std::vector <char const *>::iterator CVIterator; /* Handle the duplicate-pointers edge case by * starting from end - distance (first, last) - 1 */ CVIterator vectorEnd = priv->vector.end (); auto searchStartPoint = vectorEnd - std::distance (firstStoredNewStringsIterator, lastStoredNewStringIterator) - 1; auto pointerInVectorMatchingRawStringPointer = [&firstStoredNewStringsIterator](char const *str) -> bool { /* We want to compare the pointers, as it was pointers * that were inserted, not new values */ return firstStoredNewStringsIterator->c_str () == str; }; CVIterator firstPointerInVector = std::find_if (searchStartPoint, vectorEnd, pointerInVectorMatchingRawStringPointer); if (firstPointerInVector != vectorEnd) { auto stringEqualsCharacterArray = [](CVIterator const &lhs, CSVIterator const &rhs) -> bool { return *lhs == rhs->c_str (); }; auto lastPointerInVector = rangeMatchingPredicate (values, firstPointerInVector, vectorEnd, stringEqualsCharacterArray); /* Erase this from the vector of pointers */ priv->vector.erase (firstPointerInVector, lastPointerInVector); } /* Erase this block from the vector of stored * new strings */ priv->storedNewStrings.erase (firstStoredNewStringsIterator, lastStoredNewStringIterator); } }
void CModelFormItem::OnPaint() { CPaintDC dc(this); // device context for painting CRect rectItem; //GetWindowRect(rectItem); //ScreenToClient(rectItem); //rectItem-=rectItem.TopLeft(); //CRect clientRect; GetClientRect(rectItem); //rectItem+=CPoint(2,2); HFONT hfnt, hOldFont; hfnt = (HFONT)GetStockObject(DEFAULT_GUI_FONT); // SYSTEM_FONT ANSI_VAR_FONT hOldFont = (HFONT)dc.SelectObject(hfnt); if (m_param.GetType() != CModelInputParameterDef::kMVLine && m_param.GetType() != CModelInputParameterDef::kMVTitle && m_param.GetType() != CModelInputParameterDef::kMVStaticText) { CRect rectCaption(rectItem); rectCaption.left += CModelInputParameterDef::MARGIN_HORZ; rectCaption.right = m_param.GetEndFirstField(); dc.DrawText(CString(m_param.GetCaption().c_str()), rectCaption, DT_VCENTER | DT_SINGLELINE | DT_LEFT); } switch (m_param.GetType()) { case CModelInputParameterDef::kMVInt: case CModelInputParameterDef::kMVReal: case CModelInputParameterDef::kMVString: { CRect rectValue(rectItem); rectValue.left = m_param.GetBeginSecondField() + 2; rectValue.right -= CModelInputParameterDef::MARGIN_HORZ; dc.DrawText(CString(m_param.GetTypeName()), rectValue, DT_VCENTER | DT_SINGLELINE | DT_LEFT); DrawField(dc); break; } case CModelInputParameterDef::kMVBool: case CModelInputParameterDef::kMVListByPos: case CModelInputParameterDef::kMVListByString: { CRect rectValue(rectItem); rectValue.bottom -= 1; rectValue.left = m_param.GetBeginSecondField(); rectValue.right = rectItem.right - CModelInputParameterDef::MARGIN_HORZ; dc.MoveTo(rectValue.left, rectValue.top); dc.LineTo(rectValue.right, rectValue.top); dc.LineTo(rectValue.right, rectValue.bottom); dc.LineTo(rectValue.left, rectValue.bottom); dc.LineTo(rectValue.left, rectValue.top); rectValue.right -= 16; if (rectValue.right - rectValue.left >= 0) { dc.MoveTo(rectValue.right, rectValue.top); dc.LineTo(rectValue.right, rectValue.bottom); POINT lpPoints[3] = { { rectValue.right + 4, rectValue.top + 4 }, { rectValue.right + 12, rectValue.top + 4 }, { rectValue.right + 8, rectValue.bottom - 4 } }; CBrush brush(RGB(0, 0, 0)); CBrush* oldBrush = (CBrush*)dc.SelectObject(&brush); dc.Polygon(lpPoints, 3); dc.SelectObject(oldBrush); } rectValue.left += 2; rectValue.top += 1; rectValue.bottom -= 1; if (m_param.GetType() == CModelInputParameterDef::kMVBool) { CString strValue; bool bDefault = WBSF::ToBool(m_param.m_default); if (bDefault) strValue.LoadString(IDS_STR_TRUE); else strValue.LoadString(IDS_STR_FALSE); dc.DrawText(strValue, rectValue, DT_VCENTER | DT_SINGLELINE | DT_LEFT); } else // it's a list { //CString strValue; string str; int defPos = WBSF::ToInt(m_param.m_default); StringVector listOfParam = m_param.GetList(); if (defPos < (int)listOfParam.size()) { str = listOfParam[defPos]; } dc.DrawText(UtilWin::Convert(str), rectValue, DT_VCENTER | DT_SINGLELINE | DT_LEFT); } DrawField(dc); break; } case CModelInputParameterDef::kMVFile: { CRect rectValue(rectItem); rectValue.left = m_param.GetBeginSecondField() + 2; rectValue.right = rectItem.right - CModelInputParameterDef::MARGIN_HORZ - CModelInputParameterDef::WIDTH_BUTTON_BROWSE; CString strValue; strValue.LoadString(IDS_STR_FILENAME); dc.DrawText(strValue, rectValue, DT_VCENTER | DT_SINGLELINE | DT_LEFT); rectValue.left = rectValue.right; rectValue.right = rectItem.right - CModelInputParameterDef::MARGIN_HORZ; rectValue.bottom -= 1; rectValue.top += 1; CBrush brush(RGB(0, 0, 0)); dc.FrameRect(rectValue, &brush); rectValue.bottom -= 1; rectValue.top += 1; dc.DrawText(_T("ยทยทยท"), rectValue, DT_VCENTER | DT_SINGLELINE | DT_CENTER); DrawField(dc); break; } case CModelInputParameterDef::kMVLine: { dc.MoveTo(0, rectItem.Height() / 2); dc.LineTo(rectItem.right, rectItem.Height() / 2); break; } case CModelInputParameterDef::kMVTitle: case CModelInputParameterDef::kMVStaticText: { CRect rectCaption(rectItem); rectCaption.left += CModelInputParameterDef::MARGIN_HORZ; rectCaption.right -= CModelInputParameterDef::MARGIN_HORZ; dc.DrawText(UtilWin::Convert(m_param.GetCaption()), rectCaption, DT_VCENTER | DT_SINGLELINE | DT_LEFT); break; } default: TRACE("Erreur: mauvait type. CModelFormItem::OnPaint().\n"); } dc.SelectObject(hOldFont); // Do not call CWnd::OnPaint() for painting messages }
int main (int argc, const char** argv) { if (argc < 2) { printf ("USAGE: hlsl2glsltest testfolder\n"); return 1; } bool hasOpenGL = InitializeOpenGL (); if (!hasOpenGL) printf("NOTE: will not check GLSL with actual driver (no GL/GLSL)\n"); clock_t time0 = clock(); Hlsl2Glsl_Initialize (); std::string baseFolder = argv[1]; size_t tests = 0; size_t errors = 0; for (int type = 0; type < NUM_RUN_TYPES; ++type) { printf ("TESTING %s...\n", kTypeName[type]); const ETargetVersion version1 = kTargets1[type]; const ETargetVersion version2 = kTargets2[type]; const ETargetVersion version3 = kTargets3[type]; std::string testFolder = baseFolder + "/" + kTypeName[type]; StringVector inputFiles = GetFiles (testFolder, "-in.txt"); size_t n = inputFiles.size(); tests += n; for (size_t i = 0; i < n; ++i) { std::string inname = inputFiles[i]; //if (inname != "non-matching-type-init-in.txt") // continue; bool ok = true; printf ("test %s\n", inname.c_str()); if (type == BOTH) { ok = TestCombinedFile(testFolder + "/" + inname, version1, hasOpenGL); if (ok && version2 != ETargetVersionCount) ok = TestCombinedFile(testFolder + "/" + inname, version2, hasOpenGL); } else { ok = TestFile(TestRun(type), testFolder + "/" + inname, version1, 0, hasOpenGL); if (ok && version2 != ETargetVersionCount) ok = TestFile(TestRun(type), testFolder + "/" + inname, version2, ETranslateOpEmitGLSL120ArrayInitWorkaround, hasOpenGL); if (ok && version3 != ETargetVersionCount) ok = TestFile(TestRun(type), testFolder + "/" + inname, version3, 0, hasOpenGL); } if (!ok) ++errors; } } clock_t time1 = clock(); float t = float(time1-time0) / float(CLOCKS_PER_SEC); if (errors != 0) printf ("%i tests, %i FAILED, %.2fs\n", (int)tests, (int)errors, t); else printf ("%i tests succeeded, %.2fs\n", (int)tests, t); Hlsl2Glsl_Shutdown(); CleanupOpenGL(); return errors ? 1 : 0; }