String RemoveStringRange(const String& string, uint start, uint length) { String result = string; return result.erase(start, length); }
bool User_Program::Initial_Table (String &line) { int i, j, index, lnum, len; Int_Itr litr, litr0; double fnum; Dbl_Itr fitr, fitr0; String token; Str_Itr sitr, sitr0; string::iterator ch, ch0; i = cmd.token; j = cmd.value; for (;;) { //---- remove leading spaces ---- line.Trim_Left (" \t"); if (line.empty ()) return (false); ch = ch0 = line.begin (); //---- determine the token type ---- if ((*ch >= '0' && *ch <= '9') || (*ch == '.' && *(ch+1) != '.') || (*ch == '-' && (*(ch+1) >= '0' && *(ch+1) <= '9'))) { //---- process a number ---- if (*ch == '-') ch++; do { if (++ch == line.end ()) break; } while ((*ch >= '0' && *ch <= '9') || (*ch == '.' && *(ch+1) != '.')); len = (int) (ch - ch0); token = line.substr (0, len); line.erase (0, len); //---- set the table size ---- if (open_par) { lnum = token.Integer (); if (lnum < 1) { exe->Error (String ("%s Table %d Size %d is Out of Range") % Data_Type (i) % j % lnum); return (false); } if (table [i] [j].size () > 0) { exe->Write (1); exe->Warning (String ("%s Table %d is Redefined") % Data_Type (i) % j); table [i] [j].clear (); } table [i] [j].reserve (lnum); } else { if (table_type == STAB) { exe->Error ("Attempt to Assign a Number to a String Table"); return (false); } //---- search for the value in the list ---- if (table_type == ITAB) { lnum = token.Integer (); for (litr = litr0 = lvalue.begin (); litr != lvalue.end (); litr++) { if (*litr == lnum) break; } if (litr == lvalue.end ()) { index = (int) lvalue.size (); //---- 0 based ---- lvalue.push_back (lnum); } else { index = (int) (litr - litr0); //---- 0 based ---- } } else { fnum = token.Double (); for (fitr = fitr0 = fvalue.begin (); fitr != fvalue.end (); fitr++) { if (*fitr == fnum) break; } if (fitr == fvalue.end ()) { index = (int) fvalue.size (); //---- 0 based ---- fvalue.push_back (fnum); } else { index = (int) (fitr - fitr0); //---- 0 based ---- } } table [i] [j].push_back (index); } } else if (*ch == '"') { if (table_type != STAB) goto error; //---- process a string ---- ch++; token.clear (); while (ch != line.end () && *ch != '"') { token += *ch++; } ch++; line.erase (0, ch - ch0); for (sitr = sitr0 = svalue.begin (); sitr != svalue.end (); sitr++) { if (token.Equals (*sitr)) break; } if (sitr == svalue.end ()) { index = (int) svalue.size (); svalue.push_back (token); } else { index = (int) (sitr - sitr0); //---- 0 based ---- } table [i] [j].push_back (index); } else if ((*ch >= 'A' && *ch <= 'Z') || (*ch >= 'a' && *ch <= 'z')) { do { if (++ch == line.end ()) break; } while ((*ch >= 'A' && *ch <= 'Z') || (*ch >= 'a' && *ch <= 'z') || (*ch >= '0' && *ch <= '9') || (*ch == '.' && *(ch+1) != '.') || *ch == '_'); len = (int) (ch - ch0); token = line.substr (0, len); line.erase (0, len); if (token.Equals ("ENDTAB")) { table_flag = false; open_par = false; return (true); } else { goto error; } } else if (*ch == '(' || *ch == ')' || *ch == ',' || *ch == '=') { if (*ch == '(') { open_par = true; } else if (*ch == ')') { open_par = false; } else if (*ch == ',' || *ch == '=') { if (open_par) { goto error; } } ch++; line.erase (0, ch - ch0); } else { goto error; } } return (true); error: return (Syntax_Error ("Table Declaration")); }
/** parsing! */ ArsLexis::status_t TextToDefinitionParser::parse() { TextElement* textElement; using namespace std; String::size_type next = start_; String str; while (true) { next = inText_.find(_T('<'), start_); // skipping << next = skipDoubleChar(next,_T('<')); if (next > start_) { if (next > inLength_) str.assign(inText_, start_, next); else str.assign(inText_, start_, next-start_); doEscaping(str); if (!str.empty()) { elems_.push_back(textElement = new TextElement(str)); formatLastElement(); } } // exit if EOT if (next > inLength_) { //this is end of text (so far), so remove it from memory inLength_ = 0; inText_.clear(); start_ = 0; return errNone; } // detect what was found after < start_ = next; next = findEndOfTag(next); if (next == start_) { // not found, but text is not finished! assert(!finish_); inText_.erase(0,next); inLength_ -= next; start_ = 0; return errNone; } else if (next >= inLength_) { // do nothing... this looks like corrupted data? start_ = start_+1; //to skip '<' } else { if (inText_[start_+1] == _T('/')) { // closing tag str.assign(inText_, start_+2, next-start_-2); if (tags_.size() > 0) { TagCode tc = getTagCodeFromName(&str[0], str.length()); bool foundEqualStartTag = false; Tags_t::iterator founded = tags_.end(); Tags_t::iterator end = founded; for (Tags_t::iterator it = tags_.begin(); it != end; ++it) { if ((*it)->nameCode == tc) { founded = it; } } if (founded != end) { delete (*founded); tags_.erase(founded); foundEqualStartTag = true; } if (!foundEqualStartTag) assert(false); } else assert(false); } else { // start tag bool selfClosing = false; if (inText_[next-1] == _T('/')) { selfClosing = true; str.assign(inText_, start_+1, next-start_-2); } else str.assign(inText_, start_+1, next-start_-1); //add it to vector... (as name, args) String::size_type pos = str.find(_T(' '), 0); if (pos >= str.length()) pos = str.length(); TagStructure* ts = new TagStructure(); ts->nameCode = getTagCodeFromName(&str[0],pos); if (pos < str.length()) ts->args.assign(str,pos+1,str.npos); tags_.push_back(ts); performStartTagAction(selfClosing); } start_ = next + 1; } } return errNone; }
bool CRhodesModule::ParseCommandLine(LPCTSTR lpCmdLine, HRESULT* pnRetCode ) throw( ) { m_nRestarting = 1; LPCTSTR lpszToken = lpCmdLine; LPCTSTR nextToken; getRhoRootPath(); m_logPort = ""; m_isRhoConnectPush = false; while (lpszToken != NULL) { // skip leading spaces and double-quote (if present) bool doubleQuote = false; while ((*lpszToken != 0) && ((*lpszToken==' ') || ((!doubleQuote) && (*lpszToken=='"')))) { if (*lpszToken=='"') doubleQuote = true; lpszToken++; } // skip leading spaces and check for leading '/' or '-' of command line option bool isCmdLineOpt = false; while ((*lpszToken != 0) && ((*lpszToken==' ') || ((!isCmdLineOpt) && ((*lpszToken=='/') || (*lpszToken=='-'))))) { if ((*lpszToken=='/') || (*lpszToken=='-')) isCmdLineOpt = true; lpszToken++; } // finish command line processing on EOL if (*lpszToken == 0) break; // if option starts with double-quote, find its end by next double-quote; // otherwise the end will be found automatically nextToken = doubleQuote ? FindOneOf(lpszToken, _T("\"")) : NULL; //parseToken will allocate extra byte at the end of the returned token value LPTSTR value = parseToken( lpszToken, &nextToken ); if (isCmdLineOpt) { if (WordCmpI(lpszToken, _T("Restarting"))==0) { m_nRestarting = 10; } if (WordCmpI(lpszToken, _T("rhoconnectpush"))==0) { m_isRhoConnectPush = true; } else if (wcsncmp(lpszToken, _T("log"), 3)==0) { if (value) { m_logPort = convertToStringA(value); } else { m_logPort = rho::String("11000"); } } #if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME) else if (wcsnicmp(lpszToken, _T("s"),1)==0) { if (value) { // RhoElements v1.0 compatibility mode String strPath = convertToStringA(value); rho_wmimpl_set_startpage(strPath.c_str()); } } else if (wcsnicmp(lpszToken, _T("c"),1)==0) { if (value) { String strPath = convertToStringA(value); if (strPath.substr(0,7).compare("file://")==0) strPath.erase(0,7); rho_wmimpl_set_configfilepath(strPath.c_str()); } } #endif // APP_BUILD_CAPABILITY_SHARED_RUNTIME #if defined(OS_WINDOWS_DESKTOP) else if (wcsncmp(lpszToken, _T("http_proxy_url"),14)==0) { if (value) { m_strHttpProxy = convertToStringA(value); } else LOG(WARNING) + "invalid value for \"http_proxy_url\" cmd parameter"; } else if (wcsncmp(lpszToken, _T("approot"),7)==0) { if (value) { m_strRootPath = convertToStringA(value); String_replace(m_strRootPath, '\\', '/'); if (m_strRootPath.at(m_strRootPath.length()-1)!='/') m_strRootPath.append("/"); } } else if (wcsncmp(lpszToken, _T("rhodespath"),10)==0) { if (value) { m_strRhodesPath = convertToStringA(value); String_replace(m_strRhodesPath, '\\', '/'); } } /* else if (wcsncmp(lpszToken, _T("appname"),7)==0) { if (value) { m_strAppNameW = convertToStringW(value); } } else if (wcsncmp(lpszToken, _T("debughost"),9)==0) { if (value) { m_strDebugHost = convertToStringA(value); } } else if (wcsncmp(lpszToken, _T("debugport"),9)==0) { if (value) { m_strDebugPort = convertToStringA(value); } } */ #else else if (wcsnicmp(lpszToken, _T("approot"),7)==0) { if (value) { // RhoElements v2.0 Shared Runtime command line parameter m_strRootPath = convertToStringA(value); if (m_strRootPath.substr(0,7).compare("file://")==0) m_strRootPath.erase(0,7); String_replace(m_strRootPath, '\\', '/'); if (m_strRootPath.at(m_strRootPath.length()-1)!='/') m_strRootPath.append("/"); m_strRootPath.append("rho/"); #ifdef APP_BUILD_CAPABILITY_SHARED_RUNTIME rho_wmimpl_set_is_version2(m_strRootPath.c_str()); #endif } } #endif } if (value) free(value); lpszToken = nextToken; } return __super::ParseCommandLine(lpCmdLine, pnRetCode); }
void filterSentence(String &dst, const String &src) { int prev_lang = initCurrentLanguage(*(src.begin()), *(src.begin()+1)); int curr_lang = prev_lang; for(auto iter=src.begin(); iter!=src.end(); iter++) { if(!isTwoBytes(*iter)) { // Is a space or tab if(!(isWhiteSpace(*iter) < 0)) { curr_lang = BLANK; if(prev_lang == curr_lang) continue; } // ASCII letters and numbers else if(isASCIInumber(*iter) || isASCIIalphabet(*iter)) { curr_lang = ENGLISH; if(prev_lang != curr_lang) dst.push_back(ASCII_SPACE); dst.push_back(*iter); } else { curr_lang = OTHERS; #ifndef _INGORE_SYMBOLS_ dst.push_back(ASCII_SPACE); dst.push_back(*iter); #endif } prev_lang = curr_lang; } else { auto c1 = *iter; auto c2 = *(iter+1); if(!isKoreanSymbols(c1, c2)) // Korean, Janpaness, Hanja { if(isJapaness(c1, c2)) curr_lang = JAPANAESS; else if(isHanja(c1, c2)) curr_lang = HANJA; else curr_lang = KOREAN; if(prev_lang != curr_lang) dst.push_back(ASCII_SPACE); dst.push_back(c1); dst.push_back(c2); } else // Korean symbols { curr_lang = OTHERS; #ifndef _INGORE_SYMBOLS_ dst.push_back(ASCII_SPACE); dst.push_back(c1); dst.push_back(c2); #endif } iter++; prev_lang = curr_lang; } } if(isWhiteSpace(*(dst.begin())) == BLANK) dst.erase(dst.begin()); }
ConfigFile::LineType ConfigFile::parseLine(const char* fileName, const String& input, KeyType& key, String& value) { int inString = 0; String::size_type valStart = 0; String::size_type eol = String::npos; bool hasSub = false; const char* include = "include"; const unsigned incLen = strlen(include); for (String::size_type n = 0; n < input.length(); ++n) { switch (input[n]) { case '"': if (key.isEmpty()) // quoted string to the left of = doesn't make sense return LINE_BAD; if (inString >= 2) // one more quote after quoted string doesn't make sense return LINE_BAD; inString++; break; case '=': if (key.isEmpty()) { key = input.substr(0, n).ToNoCaseString(); key.rtrim(" \t\r"); if (key.isEmpty()) // not good - no key return LINE_BAD; valStart = n + 1; } else if (inString >= 2) // Something after the end of line return LINE_BAD; break; case '#': if (inString != 1) { eol = n; n = input.length(); // skip the rest of symbols } break; case ' ': case '\t': if (n == incLen && key.isEmpty()) { KeyType inc = input.substr(0, n).ToNoCaseString(); if (inc == include) { value = input.substr(n); value.alltrim(" \t\r"); if (!macroParse(value, fileName)) { return LINE_BAD; } return LINE_INCLUDE; } } // fall down ... case '\r': break; case '{': case '}': if (flags & HAS_SUB_CONF) { if (inString != 1) { if (input[n] == '}') // Subconf close mark not expected { return LINE_BAD; } hasSub = true; inString = 2; eol = n; } break; } // fall through .... default: if (inString >= 2) // Something after the end of line return LINE_BAD; break; } } if (inString == 1) // If we are still inside a string, it's error return LINE_BAD; if (key.isEmpty()) { key = input.substr(0, eol).ToNoCaseString(); key.rtrim(" \t\r"); value.erase(); } else { value = input.substr(valStart, eol - valStart); value.alltrim(" \t\r"); value.alltrim("\""); } // Now expand macros in value if (!macroParse(value, fileName)) { return LINE_BAD; } return hasSub ? LINE_START_SUB : LINE_REGULAR; }
int _tmain(int argc, _TCHAR* argv[]) { //paragrams const int rectLeftTopX = 200 ,rectLeftTopY = 200, rectWidth = 1648,rectHeight = 768; const int toplimit = 1000; const int hwin = 10,disparity_begin=-15,disparity_range=37; //variable int winPixTotal = (hwin+1)*(hwin+1); int *refer_img = new int[WH]; //存储参考图像 int *target_img = new int[WH]; //存储目标图像 int *refer_I = new int[disparity_range*WH]; //参考图像移位后的每个像素点对应矩形框内像素和 int *refer_MSI = new int[disparity_range*WH]; //参考图像移位后的每个像素点对应矩形框内像素和 int *refer_MSII = new int[disparity_range*WH]; //参考图像移位后的每个像素点对应矩形框内像素平方和 int *target_SI = new int[WH]; //目标图像的每个像素点对应矩形框内像素和 int *target_SII = new int[WH]; //目标图像的的每个像素点对应矩形框内像素平方和 int *DJ = new int[WH]; //参考图像的一阶积分图 int *DJJ = new int[WH]; //参考图像的二阶积分图 int *DIJ = new int[WH*disparity_range]; int *DT = new int[WH]; //目标图像的一阶积分图 int *DTT = new int[WH]; // int *DM = new int[WH]; //目标图像的一阶积分图 int *DMM = new int[WH]; //目标图像的二阶积分图 int *SIJ = new int[disparity_range*WH]; //参考图像与目标图像的点乘的积分图 float *DI = new float[WH]; //视差深度 // Variables for GPU float *costmatrix = new float[WH*disparity_range];//匹配代价 float *finalCost = new float[WH*disparity_range]; //匹配代价 String referImgName; //参考图像 String targetImgName; String SaveImgName; //指定原始数据的存储位置 referImgName = "TestData\\Reference\\reference.bmp"; targetImgName = "TestData\\Reference\\target\\"; SaveImgName = "TestData\\Reference\\result\\"; //参考图像数据读取 LoadImgFromFilePath(referImgName.c_str(),refer_img, rectLeftTopX,rectLeftTopY,rectWidth,rectHeight); //像素值阈值截断 PreProcess_Truncation(refer_img,toplimit); CalculateReferInteg(refer_img,DJ,DJJ,refer_I,refer_MSI,refer_MSII, hwin, disparity_begin, disparity_range); AdaptiveFilter_refer(refer_img, refer_MSI,winPixTotal); CalculateReferInteg(refer_img,DJ,DJJ,refer_I,refer_MSI,refer_MSII, hwin, disparity_begin, disparity_range); IplImage* depthShow=cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1); cvNamedWindow("depth",1); //遍历dir文件夹下所有jpg图像,作为目标图像进行三维重建 _finddata_t fileDir; char* dir="TestData\\Reference\\数据标定\\*.*"; long lfDir; if((lfDir = _findfirst(dir,&fileDir))==-1l) printf("No file is found\n"); else{ printf("file list:\n"); do{ printf("%s\n",fileDir.name); String fn = dir; fn.erase(fn.length()-3,fn.length()); fn = fn + fileDir.name; if (fn.find(".bmp") != -1) { //从目标图像中取出数据 LoadImgFromFilePath(fn.c_str(),target_img,rectLeftTopX,rectLeftTopY,rectWidth,rectHeight); clock_t start0, start; //声明两个时间点 //double time,time1,time2,time3,time4,time5,time6,timen; //定义运行时间 start0 = clock(); //获取开始时间 start = clock(); PreProcess_Truncation(target_img,toplimit); CalculateTargetInteg(target_img,DT,DTT,target_SI,target_SII, hwin); AdaptiveFilter_target(target_img, target_SI ,winPixTotal); CalculateTargetInteg(target_img,DM,DMM,target_SI,target_SII, hwin); printf( "TargetInteg待匹配图像积分图计算时间(CPU)为%.4f 秒\n",(double)(clock() - start) / CLOCKS_PER_SEC);//显示 start = clock(); //获取开始时间 CalculateReferTargetInteg(refer_I,target_img,DIJ,SIJ,hwin,disparity_range); printf( "Refer*TargetInteg参考图像与目标图像乘积积分图计算时间(CPU)为%.4f 秒\n",(double)(clock() - start) / CLOCKS_PER_SEC);//显示 start = clock(); CalculateAllCostMatrix(refer_MSI,refer_MSII,target_SI,target_SII,SIJ,costmatrix,disparity_range,winPixTotal); printf( "CalculateAllCostMatrixZNCC算子计算时间(CPU)为%.4f 秒\n",(double)(clock() - start) / CLOCKS_PER_SEC);//显示 start = clock(); blockWTA(costmatrix,finalCost,disparity_range); printf("blockWTA ZNCC滤波计算时间(CPU)为%.4f 秒\n",(double)(clock() - start) / CLOCKS_PER_SEC);//显示 start = clock(); WTA(finalCost,DI, hwin, disparity_begin, disparity_range); printf( "WTA 搜索最优ZNCC计算时间(CPU)为%.4f 秒\n",(double)(clock() - start) / CLOCKS_PER_SEC);//显示 start =clock(); TransDepthMap(DI,finalCost, disparity_begin, disparity_range); printf( "TransDepthMap 三角变换+插值计算时间(CPU)为%.4f 秒\n",(double)(clock() - start) / CLOCKS_PER_SEC); //CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,进行计算,完成的时间减去开始的时间获得算法运行时间 printf( "Total CPU运行时间为%.4f 秒\n",(double)(clock() - start0) / CLOCKS_PER_SEC);//显示 //对深度图像Resize,从1004x748变成1024x768 ResizeDepthImage(DI); //利用opencv存储和展示图片 for (int i=0;i<height;i++) { uchar *ptr = (uchar *) (depthShow->imageData + i * depthShow->widthStep); float *ptr1 = (float *) (DI + i*width); for (int j=0;j<width;j++) { ptr[j] = ptr1[width-1-j]; } } //解析存储文件名 fn.erase(fn.length()-4,fn.length()); SaveImgName = fn + "_result.jpg"; double blockDepthValue = 0; for(int i = width/2-hwin;i<width/2+hwin;i++) { for(int j = height/2-hwin; j< height/2+hwin;j++) { blockDepthValue += DI[i*height + j]; } } blockDepthValue /= winPixTotal; char blockDepthString[10]; sprintf(blockDepthString,"%f",blockDepthValue); CvFont font; double hScale=1; double vScale=1; int linewidth=2;// 相当于写字的线条 // 初始化字体 cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,linewidth);//初始化字体,准备写到图片上的 cvSaveImage(SaveImgName.c_str(),depthShow); cvShowImage("depth",depthShow); //cvWaitKey(-1); //把更高精度的深度图存储到txt里面去 String SaveTxtName = fn + ".txt"; SaveDepthMapInTxt(DI,SaveTxtName.c_str()); } }while( _findnext( lfDir, &fileDir ) == 0 ); } _findclose(lfDir); delete refer_img; delete target_img; delete refer_I; delete refer_MSI ; delete refer_MSII; delete target_SI ; delete target_SII ; delete DJ ; delete DJJ; delete DIJ; delete SIJ; delete DT; delete DTT; delete DM; delete DMM; delete costmatrix ; //按层存储 delete finalCost; delete DI ; // Comment the following two lines to disable waiting on exit. cerr << endl << "Press Enter to exit." << endl; while( cin.get() != '\n'); return 0; }
void StringUtils::Trim(String& str, const String& delims) { str.erase(str.find_last_not_of(delims)+1); str.erase(0, str.find_first_not_of(delims)); }
void StringUtils::TrimLeft(String& str, const String& delims) { str.erase(0, str.find_first_not_of(delims)); }
// This is all fancy because it only creates one directory at a time, // starting with the first missing subdirectory bool ff::CreateDirectory(StringRef path) { String szDrive; String szRealPath = CanonicalizePath(path); Vector<String> paths; if (szRealPath.empty()) { return false; } else if (!wcsncmp(szRealPath.c_str(), L"\\\\.\\", 4)) { // ignore physical paths return false; } else if (!wcsncmp(szRealPath.c_str(), L"\\\\", 2)) { // UNC share, find the slash after the share name const wchar_t *szSlash = wcschr(szRealPath.c_str() + 2, '\\'); szSlash = szSlash ? wcschr(szSlash + 1, '\\') : nullptr; if (!szSlash) { // can't create a server or share name return false; } szDrive = szRealPath.substr(0, szSlash - szRealPath.c_str() + 1); szRealPath.erase(0, szDrive.size()); } else if (isalpha(szRealPath[0]) && szRealPath[1] == ':' && szRealPath[2] == '\\') { // absolute drive path szDrive = szRealPath.substr(0, 3); szRealPath.erase(0, 3); } else if (szRealPath[0] == '\\') { // relative drive path szDrive = L"\\"; szRealPath.erase(0, 1); } else { // relative to the current directory } if (szRealPath.empty()) { // nothing to create return false; } // Create the chain of parent directories { LockMutex crit(GCS_FILE_UTIL); for (; szRealPath.size() && !DirectoryExists(szDrive + szRealPath); StripPathTail(szRealPath)) { paths.Push(szDrive + szRealPath); } for (size_t i = PreviousSize(paths.Size()); i != INVALID_SIZE; i = PreviousSize(i)) { szRealPath = CanonicalizePath(paths[i], true); if (!::CreateDirectory(szRealPath.c_str(), nullptr)) { assertRetVal(::GetLastError() == ERROR_ALREADY_EXISTS, false); } } } return true; }
//----------------------------------------------------------------------- void GLSLESProgramPipeline::extractLayoutQualifiers(void) { // Format is: // layout(location = 0) attribute vec4 vertex; if(mVertexProgram) { String shaderSource = mVertexProgram->getGLSLProgram()->getSource(); String::size_type currPos = shaderSource.find("layout"); while (currPos != String::npos) { VertexElementSemantic semantic; GLint index = 0; String::size_type endPos = shaderSource.find(";", currPos); if (endPos == String::npos) { // Problem, missing semicolon, abort break; } String line = shaderSource.substr(currPos, endPos - currPos); // Skip over 'layout' currPos += 6; // Skip until '=' String::size_type eqPos = line.find("="); String::size_type parenPos = line.find(")"); // Skip past '=' up to a ')' which contains an integer(the position). This could be a definition, does the preprocessor do replacement? String attrLocation = line.substr(eqPos + 1, parenPos - eqPos - 1); StringUtil::trim(attrLocation); GLint attrib = StringConverter::parseInt(attrLocation); // The rest of the line is a standard attribute definition. // Erase up to it then split the remainder by spaces. line.erase (0, parenPos + 1); StringUtil::trim(line); StringVector parts = StringUtil::split(line, " "); if(parts.size() < 3) { // This is a malformed attribute // It should contain 3 parts, i.e. "attribute vec4 vertex" break; } String attrName = parts[2]; // Special case for attribute named position if(attrName == "position") semantic = getAttributeSemanticEnum("vertex"); else semantic = getAttributeSemanticEnum(attrName); // Find the texture unit index String::size_type uvPos = attrName.find("uv"); if(uvPos != String::npos) { String uvIndex = attrName.substr(uvPos + 2, attrName.length() - 2); index = StringConverter::parseInt(uvIndex); } mCustomAttributesIndexes[semantic-1][index] = attrib; currPos = shaderSource.find("layout", currPos); } } }
/** * @brief Compare two files (as earlier specified). * @return DIFFCODE as a result of compare. */ int DiffUtils::diffutils_compare_files() { int bin_flag = 0; int bin_file = 0; // bitmap for binary files // Do the actual comparison (generating a change script) struct change *script = NULL; bool success = Diff2Files(&script, 0, &bin_flag, false, &bin_file); if (!success) { return DIFFCODE::FILE | DIFFCODE::TEXT | DIFFCODE::CMPERR; } UINT code = DIFFCODE::FILE | DIFFCODE::TEXT | DIFFCODE::SAME; // make sure to start counting diffs at 0 // (usually it is -1 at this point, for unknown) m_ndiffs = 0; m_ntrivialdiffs = 0; if (script) { struct change *next = script; struct change *thisob = 0, *end = 0; String asLwrCaseExt; String LowerCaseExt = CA2T(m_inf[0].name); int PosOfDot = LowerCaseExt.rfind('.'); if (PosOfDot != -1) { LowerCaseExt.erase(0, PosOfDot + 1); CharLower(&*LowerCaseExt.begin()); asLwrCaseExt = LowerCaseExt; } while (next) { /* Find a set of changes that belong together. */ thisob = next; end = find_change(next); /* Disconnect them from the rest of the changes, making them a hunk, and remember the rest for next iteration. */ next = end->link; end->link = 0; #ifdef _DEBUG debug_script(thisob); #endif { /* Determine range of line numbers involved in each file. */ int first0 = 0, last0 = 0, first1 = 0, last1 = 0, deletes = 0, inserts = 0; analyze_hunk(thisob, &first0, &last0, &first1, &last1, &deletes, &inserts); if (deletes || inserts || thisob->trivial) { /* Print the lines that the first file has. */ int trans_a0 = 0, trans_b0 = 0, trans_a1 = 0, trans_b1 = 0; translate_range(&m_inf[0], first0, last0, &trans_a0, &trans_b0); translate_range(&m_inf[1], first1, last1, &trans_a1, &trans_b1); //Determine quantity of lines in this block for both sides int QtyLinesLeft = (trans_b0 - trans_a0); int QtyLinesRight = (trans_b1 - trans_a1); if(m_pOptions->m_filterCommentsLines || m_pOptions->m_bIgnoreBlankLines || m_pOptions->m_bIgnoreCase) { OP_TYPE op = OP_NONE; if (!deletes && !inserts) op = OP_TRIVIAL; else op = OP_DIFF; DIFFOPTIONS options = {0}; options.nIgnoreWhitespace = m_pOptions->m_ignoreWhitespace; options.bIgnoreBlankLines = m_pOptions->m_bIgnoreBlankLines; options.bFilterCommentsLines = m_pOptions->m_filterCommentsLines; options.bIgnoreCase = m_pOptions->m_bIgnoreCase; options.bIgnoreEol = m_pOptions->m_bIgnoreEOLDifference; m_pDiffWrapper->SetOptions(&options); m_pDiffWrapper->PostFilter(thisob->line0, QtyLinesLeft+1, thisob->line1, QtyLinesRight+1, op, *m_FilterCommentsManager, asLwrCaseExt.c_str()); if(op == OP_TRIVIAL) { thisob->trivial = 1; } } // Match lines against regular expression filters // Our strategy is that every line in both sides must // match regexp before we mark difference as ignored. if(m_pFilterList && m_pFilterList->HasRegExps()) { bool match2 = false; bool match1 = RegExpFilter(thisob->line0, thisob->line0 + QtyLinesLeft, 0); if (match1) match2 = RegExpFilter(thisob->line1, thisob->line1 + QtyLinesRight, 1); if (match1 && match2) thisob->trivial = 1; } } /* Reconnect the script so it will all be freed properly. */ end->link = next; } } } // Free change script (which we don't want) if (script != NULL) { struct change *p, *e; for (e = script; e; e = p) { if (!e->trivial) ++m_ndiffs; else ++m_ntrivialdiffs; p = e->link; free(e); } if (m_ndiffs > 0) code = code & ~DIFFCODE::SAME | DIFFCODE::DIFF; } // diff_2_files set bin_flag to -1 if different binary // diff_2_files set bin_flag to +1 if same binary if (bin_flag != 0) { // Clear text-flag, set binary flag // We don't know diff counts for binary files code = code & ~DIFFCODE::TEXT; switch (bin_file) { case BINFILE_SIDE1: code |= DIFFCODE::BINSIDE1; break; case BINFILE_SIDE2: code |= DIFFCODE::BINSIDE2; break; case BINFILE_SIDE1 | BINFILE_SIDE2: code |= DIFFCODE::BIN; break; default: _RPTF1(_CRT_ERROR, "Invalid bin_file value: %d", bin_file); break; } m_ndiffs = CDiffContext::DIFFS_UNKNOWN; } if (bin_flag < 0) { // Clear same-flag, set diff-flag code = code & ~DIFFCODE::SAME | DIFFCODE::DIFF; } return code; }
void Execution_Service::XML_Help (void) { if (!XML_Flag () || help_set.size () == 0) return; //---- get the help file name ---- char *help_file = get_env ("TRANSIMS_HELP_FILE"); if (help_file == 0) { Warning ("TRANSIMS_HELP_FILE Environment Variable was Not Found"); return; } //---- open the help file ---- Db_File file; bool message_flag = Send_Messages (); Send_Messages (false); file.File_Type ("Help File"); file.File_Format (UNFORMATED); file.Clean_Flag (false); if (!file.Open (help_file)) { Send_Messages (message_flag); Warning (String ("Help File \"%s\" was Not Found") % help_file); return; } Send_Messages (message_flag); int line, code; bool flag = false; String text; XML (1, "<HELP_CODES>"); line = 1; //---- read the help file ---- while (file.Read ()) { text = file.Record_String (); if (text.Starts_With ("HELP_CODE=")) { if (flag) { XML (1, "</HELP>"); } text.erase (0, 10); code = text.Integer (); Int_Set_Itr itr = help_set.find (code); flag = (itr != help_set.end ()); if (flag) { XML (1, String ("<HELP CODE=\"%d\" >") % code); line = 1; } } else if (flag) { XML (1, String ("<LINE NUM=\"%d\" TEXT=\"%s\" />") % line % text); line++; } } if (flag) { XML (1, "</HELP>"); } XML (1, "</HELP_CODES>"); file.Close (); }
bool Execution_Service::Command_Line (Strings &commands) { bool banner_flag, syntax_flag, help_flag, command_flag, key_flag, param_flag, control_flag, exit_flag, doc_flag, user_flag; String message; Str_Itr str_itr; char ch, *config_file; banner_flag = syntax_flag = help_flag = command_flag = key_flag = param_flag = control_flag = exit_flag = doc_flag = user_flag = false; if ((int) commands.size () < 1) { Show_Banner (); Show_Syntax (); banner_flag = syntax_flag = true; Control_File (Get_Control_File ()); if (Control_File ().empty ()) return (false); } else { //---- process the command line ----- for (str_itr = commands.begin (); str_itr != commands.end (); str_itr++) { if (str_itr->at (0) == '-') { ch = str_itr->at (1); if (ch == 'Q' || ch == 'q') { if (Master ()) Quiet (true); } else if (ch == 'H' || ch == 'h') { if (Master ()) Syntax_Help (); help_flag = syntax_flag = banner_flag = true; } else if (ch == 'P' || ch == 'p') { if (Master ()) Pause_Flag (true); } else if (ch == 'N' || ch == 'n') { if (Master ()) No_Pause (true); } else if (ch == 'D' || ch == 'd' || ch == 'B' || ch == 'b') { //---- version 4.0 compatibility ---- if (Master ()) Detail (true); } else if (ch == 'K' || ch == 'k') { if (Master ()) key_flag = true; } else if (ch == 'X' || ch == 'x') { if (Master ()) { XML_Flag (true); if (str_itr->size () > 2 && (str_itr->at (2) == 'H' || str_itr->at (2) == 'h')) { XML_Help_Flag (true); } } } else if (ch == 'C' || ch == 'c') { if (Master ()) { control_flag = true; if (str_itr->size () > 2 && (str_itr->at (2) == 'X' || str_itr->at (2) == 'x')) { exit_flag = true; } } } else if (ch == 'R' || ch == 'r') { if (Master ()) { doc_flag = true; if (str_itr->size () > 2 && (str_itr->at (2) == 'U' || str_itr->at (2) == 'u')) { user_flag = true; } } } else { message ("Unrecognized Command Line Option = "); message += *str_itr ; goto error_message; } } else if (Control_File ().empty ()) { Control_File (*str_itr); } else if (Enable_Partitions ()) { if (First_Partition () >= 0) { message ("Too Many Partition Parameters"); goto error_message; } int low, high; str_itr->Range (low, high); if (low < 0 || low > high || high > 999) { if (low == high) { message ("Partition Number %d is Out of Range (0..999)") % low; } else { message ("Partition Range %d..%d is Out of Range (0..999)") % low % high; } } First_Partition (low); Last_Partition (high); } else if (Enable_Parameter ()) { if (!Parameter ().empty ()) { message ("Too Many Parameters"); goto error_message; } else { Parameter (*str_itr); param_flag = true; } } else { command_flag = true; } } if (Control_File ().empty ()) { if (XML_Flag ()) XML_Open (); if (control_flag) Write_Control_File (); if (doc_flag) Document (user_flag); if (help_flag) { if (command_flag) { message = Program (); message += " has Too Many Parameters"; Show_Warning (message); } Pause_Flag (true); Exit_Stat (DONE); return (false); } else if (XML_Flag () || control_flag || doc_flag) { Exit_Stat (DONE); return (false); } message ("No Control File"); goto error_message; } if (!banner_flag) { Show_Banner (); banner_flag = true; } } //---- check for a config file ---- config_file = get_env ("TRANSIMS_CONFIG_FILE"); if (config_file != 0) { if (!Read_Control_File (config_file)) { message ("Reading Configuration File: \"%s\"") % config_file; goto error_message; } } //---- read the control file ---- if (!Read_Control_File (Control_File ())) { if (control_flag) { Write_Control_File (); Exit_Stat (DONE); return (false); } else { message ("Reading Control File: \"%s\"") % Control_File (); goto error_message; } } if (control_flag) Write_Control_File (); if (XML_Flag ()) XML_Open (); if (doc_flag) Document (user_flag); if (exit_flag) { Exit_Stat (DONE); return (false); } //---- open the output report ---- if (Check_Control_Key (TITLE)) { Title (Get_Control_String (TITLE)); } #ifdef DEBUG_KEYS { #else if (Master ()) { #endif Open_Report (Get_Control_String (REPORT_DIRECTORY), Get_Control_String (REPORT_FILE), Set_Control_Flag (REPORT_FLAG)); } //---- show parameter warning ---- if (command_flag) { message (Program ()) += " has Too Many Parameters"; Warning (message); Write (1); } //---- show unrecognized control key warnings ---- if (key_flag) { Show_Extra_Keys (); } if (!Check_Keys ()) { Error ("Required Control Keys were Not Found"); } return (true); error_message: if (Master ()) { Quiet (false); if (!banner_flag) Show_Banner (); if (!syntax_flag) Show_Syntax (); Show_Error (message); } return (false); } //--------------------------------------------------------- // Program_Control //--------------------------------------------------------- void Execution_Service::Program_Control (void) { String key; Dtime increment; //---- override default page length ---- if (Check_Control_Key (PAGE_LENGTH)) { int len = Get_Control_Integer (PAGE_LENGTH); if (len == 0) len = MAX_INTEGER; Page_Size (Page_Width (), len); } //---- project directory ---- key = Get_Control_String (PROJECT_DIRECTORY); if (!key.empty ()) { Print_Filename (1, "Project Directory", key); Project_Directory (key); } //---- default file format ---- Default_Format (Format_Code (Get_Control_Text (DEFAULT_FILE_FORMAT))); //---- time of day format ---- Time_Format (Time_Code (Get_Control_Text (TIME_OF_DAY_FORMAT))); //---- model start time ---- Model_Start_Time (Get_Control_Text (MODEL_START_TIME)); //---- model end time ---- Model_End_Time (Get_Control_Text (MODEL_END_TIME)); //---- model time increment ---- increment = Get_Control_Time (MODEL_TIME_INCREMENT); time_periods.Set_Periods (increment, Model_Start_Time (), Model_End_Time ()); //---- units of measure ---- Metric_Flag (Measure_Code (Get_Control_Text (UNITS_OF_MEASURE)) == METRIC); //---- drive side of road ---- Left_Side_Flag (Drive_Side_Code (Get_Control_Text (DRIVE_SIDE_OF_ROAD)) == LEFT_SIDE); //---- random number seed ---- if (Control_Key_Status (RANDOM_NUMBER_SEED)) { key = Get_Control_String (RANDOM_NUMBER_SEED); if (!key.empty ()) { if (key.length () > 9) key.erase (9); random.Seed (key.Integer ()); } random_seed = random.Seed (); Output_Control_Label (RANDOM_NUMBER_SEED) << random_seed; } //---- warning messages ---- if (Control_Key_Status (MAX_WARNING_MESSAGES)) { Max_Warnings (Get_Control_Integer (MAX_WARNING_MESSAGES)); } Warning_Flag (Get_Control_Flag (MAX_WARNING_EXIT_FLAG)); //---- problem count ---- Max_Problems (Get_Control_Integer (MAX_PROBLEM_COUNT)); //---- number of threads ---- num_threads = Get_Control_Integer (NUMBER_OF_THREADS); if (num_threads > 1) { if (!Enable_Threads ()) { key (Program ()) += " is Not Thread Enabled"; Warning (key); Write (1); num_threads = 1; } } int num = Highest_Control_Group (USER_FUNCTIONS, 0); if (num > 0) { for (int i=1; i <= num; i++) { key = Get_Control_String (USER_FUNCTIONS, i); if (!key.empty ()) { functions.Add_Function (i, key); } } } }
int main(int argc, char *argv[]) { #ifdef RHODES_EMULATOR bool isJSApp; #endif CMainWindow* m_appWindow = CMainWindow::getInstance(); m_logPort = String("11000"); for (int i=1; i<argc; ++i) { g_strCmdLine += String(argv[i]) + " "; if (strncasecmp("-log",argv[i],4)==0) { char* port = parseToken(argv[i]); if (port) { String strLogPort = port; m_logPort = strLogPort; free(port); } } else if (strncasecmp("-http_proxy_url",argv[i],15)==0) { char *proxy = parseToken(argv[i]); if (proxy) { m_strHttpProxy = proxy; free(proxy); } else RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter"); #ifdef RHODES_EMULATOR } else if ((strncasecmp("-approot",argv[i],8)==0) || (isJSApp = (strncasecmp("-jsapproot",argv[i],10)==0))) { char* path = parseToken(argv[i]); if (path) { int len = strlen(path); if (!(path[len-1]=='\\' || path[len-1]=='/')) { path[len] = '/'; path[len+1] = 0; } m_strRootPath = path; free(path); if (m_strRootPath.substr(0,7).compare("file://")==0) m_strRootPath.erase(0,7); String_replace(m_strRootPath, '\\', '/'); } m_isJSApplication = isJSApp; } else if (strncasecmp("-rhodespath",argv[i],11)==0) { char* path = parseToken(argv[i]); if (path) { m_strRhodesPath = path; free(path); if (m_strRhodesPath.substr(0,7).compare("file://")==0) m_strRhodesPath.erase(0,7); String_replace(m_strRhodesPath, '\\', '/'); } #endif } else { RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]); } } #if defined(RHO_SYMBIAN) m_strRootPath = (QDir::currentPath()+"/").toUtf8().data(); #endif #ifndef RHODES_EMULATOR const QByteArray dir = QFileInfo(QCoreApplication::applicationFilePath()).absolutePath().toLatin1(); m_strRootPath = std::string(dir.constData(), dir.length()); m_strRootPath += "/rho/"; #endif // PreMessageLoop: rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str()); #ifdef RHODES_EMULATOR RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str()); RHOSIMCONF().loadFromFile(); if ( m_strRhodesPath.length() > 0 ) RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false ); RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false); RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false); String start_path = RHOSIMCONF().getString("start_path"); if ( start_path.length() > 0 ) RHOCONF().setString("start_path", start_path, false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false); #endif if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") ) { QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed")); RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key."); if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0) return 1; } RAWLOGC_INFO("Main", "Rhodes started"); if (m_strHttpProxy.length() > 0) { parseHttpProxyURI(m_strHttpProxy); } else { if (RHOCONF().isExist("http_proxy_url")) { parseHttpProxyURI(RHOCONF().getString("http_proxy_url")); } } #ifdef RHODES_EMULATOR if (RHOSIMCONF().getString("debug_host").length() > 0) #ifdef OS_WINDOWS_DESKTOP SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() ); #else // !OS_WINDOWS_DESKTOP setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 ); #endif // OS_WINDOWS_DESKTOP if (RHOSIMCONF().getString("debug_port").length() > 0) #ifdef OS_WINDOWS_DESKTOP SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() ); #else // RHODES_EMULATOR setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 ); #endif // OS_WINDOWS_DESKTOP #endif // RHODES_EMULATOR rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath); RHODESAPP().setJSApplication(m_isJSApplication); // Create the main application window #ifdef RHODES_EMULATOR m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str()); #else m_appWindow->Initialize(convertToStringW(RHODESAPP().getAppTitle()).c_str()); #endif RHODESAPP().startApp(); // Navigate to the "loading..." page m_appWindow->navigate(L"about:blank", -1); if (RHOCONF().getString("test_push_client").length() > 0 ) rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client"); // RunMessageLoop: m_appWindow->messageLoop(); // stopping Rhodes application rho_ringtone_manager_stop(); m_appWindow->DestroyUi(); rho::common::CRhodesApp::Destroy(); return 0; }
void StringUtils::TrimRight(String& str, const String& delims) { str.erase(str.find_last_not_of(delims)+1); }
//--------------------------------------------------------------------- void GLSLProgramManagerCommon::parseIndividualConstant(const String& src, GpuNamedConstants& defs, String::size_type currPos, const String& filename, GpuSharedParametersPtr sharedParams) { GpuConstantDefinition def; String paramName = ""; String::size_type endPos = src.find(";", currPos); String line = src.substr(currPos, endPos - currPos); // Remove spaces before opening square braces, otherwise // the following split() can split the line at inappropriate // places (e.g. "vec3 something [3]" won't work). for (String::size_type sqp = line.find (" ["); sqp != String::npos; sqp = line.find (" [")) line.erase (sqp, 1); // Split into tokens StringVector parts = StringUtil::split(line, ", \t\r\n"); for (StringVector::iterator i = parts.begin(); i != parts.end(); ++i) { // Is this a type? StringToEnumMap::iterator typei = mTypeEnumMap.find(*i); if (typei != mTypeEnumMap.end()) { completeDefInfo(typei->second, def); } else { // if this is not a type, and not empty, it should be a name StringUtil::trim(*i); if (i->empty()) continue; // Skip over precision keywords if(StringUtil::match((*i), "lowp") || StringUtil::match((*i), "mediump") || StringUtil::match((*i), "highp")) continue; String::size_type arrayStart = i->find("[", 0); if (arrayStart != String::npos) { // potential name (if butted up to array) String name = i->substr(0, arrayStart); StringUtil::trim(name); if (!name.empty()) paramName = name; String::size_type arrayEnd = i->find("]", arrayStart); String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1); StringUtil::trim(arrayDimTerm); // the array term might be a simple number or it might be // an expression (e.g. 24*3) or refer to a constant expression // we'd have to evaluate the expression which could get nasty // TODO def.arraySize = StringConverter::parseInt(arrayDimTerm); } else { paramName = *i; def.arraySize = 1; } // Name should be after the type, so complete def and add // We do this now so that comma-separated params will do // this part once for each name mentioned if (def.constType == GCT_UNKNOWN) { LogManager::getSingleton().logMessage("Problem parsing the following GLSL Uniform: '" + line + "' in file " + filename); // next uniform break; } // Special handling for shared parameters if(sharedParams.isNull()) { // Complete def and add // increment physical buffer location def.logicalIndex = 0; // not valid in GLSL if (def.isFloat()) { def.physicalIndex = defs.floatBufferSize; defs.floatBufferSize += def.arraySize * def.elementSize; } else { def.physicalIndex = defs.intBufferSize; defs.intBufferSize += def.arraySize * def.elementSize; } defs.map.insert(GpuConstantDefinitionMap::value_type(paramName, def)); // Generate array accessors defs.generateConstantDefinitionArrayEntries(paramName, def); } else { try { const GpuConstantDefinition &sharedDef = sharedParams->getConstantDefinition(paramName); (void)sharedDef; // Silence warning } catch (Exception& e) { // This constant doesn't exist so we'll create a new one sharedParams->addConstantDefinition(paramName, def.constType); } } } } }
// We assume a path name structure like this: // (1) Everything up to and including the final directory separator // character is the directory; the rest is the file name. On return // we fix the slashes in the directory name to suit the current // system ('\' for Windows, '/' otherwise). // (2) If the file name contains a ".", characters after the last // "." are the extension and the last "." is removed. // (3) What's left is the fileName. // We accept both "/" and "\" as separator characters. We leave the // case as it was supplied. // Leading and trailing white space is removed; embedded white space // remains. // Leading "X:" for some drive letter X is recognized on Windows as // a drive specification, otherwise the drive is the current drive. // That is then removed for further processing. // Absolute paths are designated like this: // Leading "/" means root relative (on the drive). // Leading "./" means current working directory relative (on the drive). // Leading "../" is interpreted as "./..". // Leading "@/" means relative to executable location. // Above leading characters are removed and replaced with the // full path name they represent, then the entire path is divided // into components. If a component is "." or "" (empty) it is // removed. If a component is ".." it and the previous component // if any are removed. (".." as a first component will report as // ill formed.) // If there is something ill-formed about the file name we'll return // false. void Pathname::deconstructPathname( const string& pathname, bool& dontApplySearchPath, string& directory, string& fileName, string& extension) { dontApplySearchPath = false; directory.erase(); fileName.erase(); extension.erase(); // Remove all the white space and make all the slashes be forward ones. // (For Windows they'll be changed to backslashes later.) String processed = String::trimWhiteSpace(pathname) .replaceAllChar('\\', '/'); if (processed.empty()) return; // pathname consisted only of white space string drive; removeDriveInPlace(processed, drive); // Now the drive if any has been removed and we're looking at // the beginning of the pathname. // If the pathname in its entirety is just one of these, append // a slash to avoid special cases below. if (processed == "." || processed == ".." || processed == "@") processed += "/"; // If the path begins with "../" we'll make it ./../ to simplify handling. if (processed.substr(0, 3) == "../") processed.insert(0, "./"); if (processed.substr(0, 1) == "/") { dontApplySearchPath = true; processed.erase(0, 1); if (drive.empty()) drive = getCurrentDriveLetter(); } else if (processed.substr(0, 2) == "./") { dontApplySearchPath = true; processed.replace(0, 2, getCurrentWorkingDirectory(drive)); removeDriveInPlace(processed, drive); } else if (processed.substr(0, 2) == "@/") { dontApplySearchPath = true; processed.replace(0, 2, getThisExecutableDirectory()); removeDriveInPlace(processed, drive); } else if (!drive.empty()) { // Looks like a relative pathname. But if it had an initial // drive specification, e.g. X:something.txt, that is supposed // to be interpreted relative to the current working directory // on drive X, just as though it were X:./something.txt. dontApplySearchPath = true; processed.insert(0, getCurrentWorkingDirectory(drive)); removeDriveInPlace(processed, drive); } // We may have picked up a new batch of backslashes above. processed.replaceAllChar('\\', '/'); // Now we have the full pathname if this is absolute, otherwise // we're looking at a relative pathname. In any case the last // component is the file name if it isn't empty, ".", or "..". // Process the ".." segments and eliminate meaningless ones // as we go through. Array_<string> segmentsInReverse; bool isFinalSegment = true; // first time around might be the fileName int numDotDotsSeen = 0; while (!processed.empty()) { string component; removeLastPathComponentInPlace(processed, component); if (component == "..") ++numDotDotsSeen; else if (!component.empty() && component != ".") { if (numDotDotsSeen) --numDotDotsSeen; // skip component else if (isFinalSegment) fileName = component; else segmentsInReverse.push_back(component); } isFinalSegment = false; } // Now we can put together the canonicalized directory. if (dontApplySearchPath) { if (!drive.empty()) directory = drive + ":"; directory += "/"; } for (int i = (int)segmentsInReverse.size() - 1; i >= 0; --i) directory += segmentsInReverse[i] + "/"; // Fix the slashes. makeNativeSlashesInPlace(directory); // If there is a .extension, strip it off. string::size_type lastDot = fileName.rfind('.'); if (lastDot != string::npos) { extension = fileName.substr(lastDot); fileName.erase(lastDot); } }
//--------------------------------------------------------------------- void CgProgram::recurseParams(CGparameter parameter, size_t contextArraySize) const { while (parameter != 0) { // Look for uniform (non-sampler) parameters only // Don't bother enumerating unused parameters, especially since they will // be optimised out and therefore not in the indexed versions CGtype paramType = cgGetParameterType(parameter); if (cgGetParameterVariability(parameter) == CG_UNIFORM && paramType != CG_SAMPLER1D && paramType != CG_SAMPLER2D && paramType != CG_SAMPLER3D && paramType != CG_SAMPLERCUBE && paramType != CG_SAMPLERRECT && cgGetParameterDirection(parameter) != CG_OUT && cgIsParameterReferenced(parameter)) { int arraySize; switch(paramType) { case CG_STRUCT: recurseParams(cgGetFirstStructParameter(parameter)); break; case CG_ARRAY: // Support only 1-dimensional arrays arraySize = cgGetArraySize(parameter, 0); recurseParams(cgGetArrayParameter(parameter, 0), (size_t)arraySize); break; default: // Normal path (leaf) String paramName = cgGetParameterName(parameter); size_t logicalIndex = cgGetParameterResourceIndex(parameter); // Get the parameter resource, to calculate the physical index CGresource res = cgGetParameterResource(parameter); bool isRegisterCombiner = false; size_t regCombinerPhysicalIndex = 0; switch (res) { case CG_COMBINER_STAGE_CONST0: // register combiner, const 0 // the index relates to the texture stage; store this as (stage * 2) + 0 regCombinerPhysicalIndex = logicalIndex * 2; isRegisterCombiner = true; break; case CG_COMBINER_STAGE_CONST1: // register combiner, const 1 // the index relates to the texture stage; store this as (stage * 2) + 1 regCombinerPhysicalIndex = (logicalIndex * 2) + 1; isRegisterCombiner = true; break; default: // normal constant break; } // Trim the '[0]' suffix if it exists, we will add our own indexing later if (StringUtil::endsWith(paramName, "[0]", false)) { paramName.erase(paramName.size() - 3); } GpuConstantDefinition def; def.arraySize = contextArraySize; mapTypeAndElementSize(paramType, isRegisterCombiner, def); if (def.constType == GCT_UNKNOWN) { LogManager::getSingleton().logMessage( "Problem parsing the following Cg Uniform: '" + paramName + "' in file " + mName); // next uniform parameter = cgGetNextParameter(parameter); continue; } if (isRegisterCombiner) { def.physicalIndex = regCombinerPhysicalIndex; } else { // base position on existing buffer contents if (def.isFloat()) { def.physicalIndex = mFloatLogicalToPhysical->bufferSize; } else { def.physicalIndex = mIntLogicalToPhysical->bufferSize; } } def.logicalIndex = logicalIndex; mConstantDefs->map.insert(GpuConstantDefinitionMap::value_type(paramName, def)); // Record logical / physical mapping if (def.isFloat()) { OGRE_LOCK_MUTEX(mFloatLogicalToPhysical->mutex) mFloatLogicalToPhysical->map.insert( GpuLogicalIndexUseMap::value_type(logicalIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL))); mFloatLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; mConstantDefs->floatBufferSize = mFloatLogicalToPhysical->bufferSize; } else { OGRE_LOCK_MUTEX(mIntLogicalToPhysical->mutex) mIntLogicalToPhysical->map.insert( GpuLogicalIndexUseMap::value_type(logicalIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL))); mIntLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; mConstantDefs->intBufferSize = mIntLogicalToPhysical->bufferSize; } // Deal with array indexing mConstantDefs->generateConstantDefinitionArrayEntries(paramName, def); break; } } // Get next parameter = cgGetNextParameter(parameter); } }
void Pathname::deconstructPathnameUsingSpecifiedWorkingDirectory (const std::string& swd, const std::string& pathname, std::string& directory, std::string& fileName, std::string& extension) { directory.erase(); fileName.erase(); extension.erase(); string pathdrive, swddrive, finaldrive; String processed; // Remove all the white space and make all the slashes be forward ones. // (For Windows they'll be changed to backslashes later.) String pathcleaned = String::trimWhiteSpace(pathname) .replaceAllChar('\\', '/'); // If pathname is absolute it is handled as though there were no swd. if (isAbsolutePath(pathcleaned) || isExecutableDirectoryPath(pathcleaned)) { deconstructAbsolutePathname(pathname, directory, fileName, extension); return; } if (pathcleaned.empty()) return; // pathname consisted only of white space removeDriveInPlace(pathcleaned, pathdrive); String swdcleaned = String::trimWhiteSpace(swd) .replaceAllChar('\\', '/'); // If swd was empty, then use the usual cwd method instead. if (swdcleaned.empty()) { deconstructAbsolutePathname(pathname, directory, fileName, extension); return; } // If swd wasn't empty, then add a trailing "/" if necessary. if (swdcleaned[swdcleaned.size() - 1] != '/') swdcleaned += '/'; removeDriveInPlace(swdcleaned, swddrive); /* PREPROCESSING THE SWD */ // Preprocess the swd if it leads with "/". Just grab current drive letter. if (swdcleaned.substr(0, 1) == "/") { if (swddrive.empty()) swddrive = getCurrentDriveLetter(); } // Preprocess the swd if it leads with a "./" else if (swdcleaned.substr(0, 2) == "./") { swdcleaned.replace(0, 2, getCurrentWorkingDirectory(swddrive)); removeDriveInPlace(swdcleaned, swddrive); } // Also preprocess if swd starts with something of the form "C:folder/". // Resolve by finding the current directory of this drive. else if (!swddrive.empty()) { swdcleaned.insert(0, getCurrentWorkingDirectory(swddrive)); removeDriveInPlace(swdcleaned, swddrive); } /* CHECKING IF THE SWD SHOULD BE PREPENDED TO THE PATH */ // If pathname starts with "/", use it for the whole path (but deal with // drive later). if (pathcleaned.substr(0, 1) == "/") { processed = pathcleaned; } // If path starts with "./": remove the "./", concatenate with swdcleaned. else if (pathcleaned.substr(0, 2) == "./") { pathcleaned.erase(0, 2); processed = swdcleaned + pathcleaned; } // Looks like a relative pathname (i.e. pathcleaned starts immediately with // a directory or file name). else { processed = swdcleaned + pathcleaned; } /* RESOLVING THE FULL PATH */ // May have picked up some backslashes through getCurrentWorkingDirectory(). processed.replaceAllChar('\\', '/'); // If the pathname in its entirety is just one of these, append // a slash to avoid special cases below. if (processed == "." || processed == ".." || processed == "@") processed += "/"; // If the path begins with "../" we'll make it ./../ to simplify handling. if (processed.substr(0, 3) == "../") processed.insert(0, "./"); // Full path is determined except for drive letter. Resolve drive letter // with swd, then path, then current drive. if (processed.substr(0, 1) == "/") { if (!swddrive.empty()) finaldrive = swddrive; else if (!pathdrive.empty()) finaldrive = pathdrive; else finaldrive = getCurrentDriveLetter(); } else if (processed.substr(0, 2) == "@/") { processed.replace(0, 2, getThisExecutableDirectory()); removeDriveInPlace(processed, finaldrive); } // Looks like a relative pathname. But if either path had // an initial drive specification, e.g. X:something.txt, that is // supposed to be interpreted relative to the current working directory // on drive X, just as though it were X:./something.txt. // Note that we do not need to check swd as it has either been preprocessed // (and thus has been taken care of in the "/" case) or is of the form // "folder/file.ext". else if (!pathdrive.empty()) { processed.insert(0, getCurrentWorkingDirectory(pathdrive)); removeDriveInPlace(processed, finaldrive); } // Must be a relative pathname. Just prepend the current working directory. else { processed.insert(0, getCurrentWorkingDirectory()); removeDriveInPlace(processed, finaldrive); } // Build up the final pathname, then use deconstructAbsolutePathname() to // find the final directory, fileName, and extension. if (processed.substr(0, 1) != "/") processed.insert(0, "/"); if (!finaldrive.empty()) processed.insert(0, finaldrive + ":"); deconstructAbsolutePathname(processed, directory, fileName, extension); }
void createParamFile_(ostream& os) { os << "# comet_version " << getStringOption_("comet_version") << "\n"; //required as first line in the param file os << "# Comet MS/MS search engine parameters file.\n"; os << "# Everything following the '#' symbol is treated as a comment.\n"; os << "database_name = " << getStringOption_("database") << "\n"; os << "decoy_search = " << 0 << "\n"; // 0=no (default), 1=concatenated search, 2=separate search os << "num_threads = " << getIntOption_("threads") << "\n"; // 0=poll CPU to set num threads; else specify num threads directly (max 64) // masses map<String,int> precursor_error_units; precursor_error_units["amu"] = 0; precursor_error_units["mmu"] = 1; precursor_error_units["ppm"] = 2; map<string,int> isotope_error; isotope_error["off"] = 0; isotope_error["-1/0/1/2/3"] = 1; isotope_error["-8/-4/0/4/8"] = 2; os << "peptide_mass_tolerance = " << getDoubleOption_("precursor_mass_tolerance") << "\n"; os << "peptide_mass_units = " << precursor_error_units[getStringOption_("precursor_error_units")] << "\n"; // 0=amu, 1=mmu, 2=ppm os << "mass_type_parent = " << 1 << "\n"; // 0=average masses, 1=monoisotopic masses os << "mass_type_fragment = " << 1 << "\n"; // 0=average masses, 1=monoisotopic masses os << "precursor_tolerance_type = " << 0 << "\n"; // 0=MH+ (default), 1=precursor m/z; only valid for amu/mmu tolerances os << "isotope_error = " << isotope_error[getStringOption_("isotope_error")] << "\n"; // 0=off, 1=on -1/0/1/2/3 (standard C13 error), 2= -8/-4/0/4/8 (for +4/+8 labeling) // search enzyme String enzyme_name = getStringOption_("enzyme"); String enzyme_number = String(ProteaseDB::getInstance()->getEnzyme(enzyme_name)->getCometID()); map<string,int> num_enzyme_termini; num_enzyme_termini["semi"] = 1; num_enzyme_termini["fully"] = 2; num_enzyme_termini["C-term unspecific"] = 8; num_enzyme_termini["N-term unspecific"] = 9; os << "search_enzyme_number = " << enzyme_number << "\n"; // choose from list at end of this params file os << "num_enzyme_termini = " << num_enzyme_termini[getStringOption_("num_enzyme_termini")] << "\n"; // 1 (semi-digested), 2 (fully digested, default), 8 C-term unspecific , 9 N-term unspecific os << "allowed_missed_cleavage = " << getIntOption_("allowed_missed_cleavages") << "\n"; // maximum value is 5; for enzyme search // Up to 9 variable modifications are supported // format: <mass> <residues> <0=variable/else binary> <max_mods_per_peptide> <term_distance> <n/c-term> <required> // e.g. 79.966331 STY 0 3 -1 0 0 vector<String> variable_modifications_names = getStringList_("variable_modifications"); vector<ResidueModification> variable_modifications = getModifications_(variable_modifications_names); if (variable_modifications.size() > 9) { throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Error: Comet only supports 9 variable modifications. " + String(variable_modifications.size()) + " provided."); } int max_variable_mods_in_peptide = getIntOption_("max_variable_mods_in_peptide"); Size var_mod_index = 0; // write out user specified modifications for (; var_mod_index < variable_modifications.size(); ++var_mod_index) { const ResidueModification mod = variable_modifications[var_mod_index]; double mass = mod.getDiffMonoMass(); String residues = mod.getOrigin(); //TODO support binary groups, e.g. for SILAC int binary_group = 0; //TODO support mod-specific limit (default for now is the overall max per peptide) int max_current_mod_per_peptide = max_variable_mods_in_peptide; //TODO support term-distances? int term_distance = -1; int nc_term = 0; //TODO support agglomeration of Modifications to same AA. Watch out for nc_term value then. if (mod.getTermSpecificity() == ResidueModification::C_TERM) { residues = "c"; term_distance = 0; // Since users need to specify mods that apply to multiple residues/terms separately // 3 and -1 should be equal for now. nc_term = 3; } else if (mod.getTermSpecificity() == ResidueModification::N_TERM) { residues = "n"; term_distance = 0; // Since users need to specify mods that apply to multiple residues/terms separately // 2 and -1 should be equal for now. nc_term = 2; } else if (mod.getTermSpecificity() == ResidueModification::PROTEIN_N_TERM) // not yet available { term_distance = 0; nc_term = 0; } else if (mod.getTermSpecificity() == ResidueModification::PROTEIN_C_TERM) // not yet available { term_distance = 0; nc_term = 1; } //TODO support required variable mods bool required = false; os << "variable_mod0" << var_mod_index+1 << " = " << mass << " " << residues << " " << binary_group << " " << max_current_mod_per_peptide << " " << term_distance << " " << nc_term << " " << required << "\n"; } // fill remaining modification slots (if any) in Comet with "no modification" for (; var_mod_index < 9; ++var_mod_index) { os << "variable_mod0" << var_mod_index+1 << " = " << "0.0 X 0 3 -1 0 0" << "\n"; } os << "max_variable_mods_in_peptide = " << getIntOption_("max_variable_mods_in_peptide") << "\n"; os << "require_variable_mod = " << (int) (getStringOption_("require_variable_mod") == "true") << "\n"; // fragment ion defaults // ion trap ms/ms: 1.0005 tolerance, 0.4 offset (mono masses), theoretical_fragment_ions = 1 // high res ms/ms: 0.02 tolerance, 0.0 offset (mono masses), theoretical_fragment_ions = 0 String instrument = getStringOption_("instrument"); double bin_tol = getDoubleOption_("fragment_bin_tolerance"); double bin_offset = getDoubleOption_("fragment_bin_offset"); if (instrument == "low_res" && (bin_tol < 0.9 || bin_offset <= 0.2)) { LOG_WARN << "Fragment bin size or tolerance is quite low for low res instruments." << "\n"; } else if (instrument == "high_res" && (bin_tol > 0.2 || bin_offset > 0.1)) { LOG_WARN << "Fragment bin size or tolerance is quite high for high res instruments." << "\n"; }; os << "fragment_bin_tol = " << bin_tol << "\n"; // binning to use on fragment ions os << "fragment_bin_offset = " << bin_offset << "\n"; // offset position to start the binning (0.0 to 1.0) os << "theoretical_fragment_ions = " << (int)(instrument == "low_res") << "\n"; // 0=use flanking bin, 1=use M bin only os << "use_A_ions = " << (int)(getStringOption_("use_A_ions")=="true") << "\n"; os << "use_B_ions = " << (int)(getStringOption_("use_B_ions")=="true") << "\n"; os << "use_C_ions = " << (int)(getStringOption_("use_C_ions")=="true") << "\n"; os << "use_X_ions = " << (int)(getStringOption_("use_X_ions")=="true") << "\n"; os << "use_Y_ions = " << (int)(getStringOption_("use_Y_ions")=="true") << "\n"; os << "use_Z_ions = " << (int)(getStringOption_("use_Z_ions")=="true") << "\n"; os << "use_NL_ions = " << (int)(getStringOption_("use_NL_ions")=="true") << "\n"; // 0=no, 1=yes to consider NH3/H2O neutral loss peaks // output os << "output_sqtstream = " << 0 << "\n"; // 0=no, 1=yes write sqt to standard output os << "output_sqtfile = " << 0 << "\n"; // 0=no, 1=yes write sqt file os << "output_txtfile = " << 0 << "\n"; // 0=no, 1=yes write tab-delimited txt file os << "output_pepxmlfile = " << 1 << "\n"; // 0=no, 1=yes write pep.xml file os << "output_percolatorfile = " << !getStringOption_("pin_out").empty() << "\n"; // 0=no, 1=yes write Percolator tab-delimited input file os << "output_outfiles = " << 0 << "\n"; // 0=no, 1=yes write .out files os << "print_expect_score = " << 1 << "\n"; // 0=no, 1=yes to replace Sp with expect in out & sqt os << "num_output_lines = " << getIntOption_("num_hits") << "\n"; // num peptide results to show os << "show_fragment_ions = " << 0 << "\n"; // 0=no, 1=yes for out files only os << "sample_enzyme_number = " << enzyme_number << "\n"; // Sample enzyme which is possibly different than the one applied to the search. // mzXML parameters map<string,int> override_charge; override_charge["keep any known"] = 0; override_charge["ignore known"] = 1; override_charge["ignore outside range"] = 2; override_charge["keep known search unknown"] = 3; int precursor_charge_min(0), precursor_charge_max(0); if (!parseRange_(getStringOption_("precursor_charge"), precursor_charge_min, precursor_charge_max)) { LOG_INFO << "precursor_charge range not set. Defaulting to 0:0 (disable charge filtering)." << endl; } os << "scan_range = " << "0 0" << "\n"; // start and scan scan range to search; 0 as 1st entry ignores parameter os << "precursor_charge = " << precursor_charge_min << " " << precursor_charge_max << "\n"; // precursor charge range to analyze; does not override any existing charge; 0 as 1st entry ignores parameter os << "override_charge = " << override_charge[getStringOption_("override_charge")] << "\n"; // 0=no, 1=override precursor charge states, 2=ignore precursor charges outside precursor_charge range, 3=see online os << "ms_level = " << getIntOption_("ms_level") << "\n"; // MS level to analyze, valid are levels 2 (default) or 3 os << "activation_method = " << getStringOption_("activation_method") << "\n"; // activation method; used if activation method set; allowed ALL, CID, ECD, ETD, PQD, HCD, IRMPD // misc parameters double digest_mass_range_min(600.0), digest_mass_range_max(5000.0); if (!parseRange_(getStringOption_("digest_mass_range"), digest_mass_range_min, digest_mass_range_max)) { LOG_INFO << "digest_mass_range not set. Defaulting to 600.0 5000.0." << endl; } os << "digest_mass_range = " << digest_mass_range_min << " " << digest_mass_range_max << "\n"; // MH+ peptide mass range to analyze os << "num_results = " << 100 << "\n"; // number of search hits to store internally os << "skip_researching = " << 1 << "\n"; // for '.out' file output only, 0=search everything again (default), 1=don't search if .out exists os << "max_fragment_charge = " << getIntOption_("max_fragment_charge") << "\n"; // set maximum fragment charge state to analyze (allowed max 5) os << "max_precursor_charge = " << getIntOption_("max_precursor_charge") << "\n"; // set maximum precursor charge state to analyze (allowed max 9) os << "nucleotide_reading_frame = " << 0 << "\n"; // 0=proteinDB, 1-6, 7=forward three, 8=reverse three, 9=all six os << "clip_nterm_methionine = " << (int)(getStringOption_("clip_nterm_methionine")=="true") << "\n"; // 0=leave sequences as-is; 1=also consider sequence w/o N-term methionine os << "spectrum_batch_size = " << getIntOption_("spectrum_batch_size") << "\n"; // max. // of spectra to search at a time; 0 to search the entire scan range in one loop os << "decoy_prefix = " << "--decoysearch-not-used--" << "\n"; // decoy entries are denoted by this string which is pre-pended to each protein accession os << "output_suffix = " << "" << "\n"; // add a suffix to output base names i.e. suffix "-C" generates base-C.pep.xml from base.mzXML input os << "mass_offsets = " << ListUtils::concatenate(getDoubleList_("mass_offsets"), " ") << "\n"; // one or more mass offsets to search (values subtracted from deconvoluted precursor mass) // spectral processing map<string,int> remove_precursor_peak; remove_precursor_peak["no"] = 0; remove_precursor_peak["yes"] = 1; remove_precursor_peak["charge_reduced"] = 2; remove_precursor_peak["phosphate_loss"] = 3; double clear_mz_range_min(0.0), clear_mz_range_max(0.0); if (!parseRange_(getStringOption_("clear_mz_range"), clear_mz_range_min, clear_mz_range_max)) { LOG_INFO << "clear_mz_range not set. Defaulting to 0:0 (disable m/z filter)." << endl; } os << "minimum_peaks = " << getIntOption_("minimum_peaks") << "\n"; // required minimum number of peaks in spectrum to search (default 10) os << "minimum_intensity = " << getDoubleOption_("minimum_intensity") << "\n"; // minimum intensity value to read in os << "remove_precursor_peak = " << remove_precursor_peak[getStringOption_("remove_precursor_peak")] << "\n"; // 0=no, 1=yes, 2=all charge reduced precursor peaks (for ETD) os << "remove_precursor_tolerance = " << getDoubleOption_("remove_precursor_tolerance") << "\n"; // +- Da tolerance for precursor removal os << "clear_mz_range = " << clear_mz_range_min << " " << clear_mz_range_max << "\n"; // for iTRAQ/TMT type data; will clear out all peaks in the specified m/z range // write fixed modifications - if not specified residue parameter is zero // Aminoacid: // add_AA.OneletterCode_AA.ThreeLetterCode = xxx // Terminus: // add_N/Cterm_peptide = xxx protein not available yet vector<String> fixed_modifications_names = getStringList_("fixed_modifications"); vector<ResidueModification> fixed_modifications = getModifications_(fixed_modifications_names); // Comet sets Carbamidometyl (C) as modification as default even if not specified // Therefor there is the need to set it to 0 if not set as flag if (fixed_modifications.empty()) { os << "add_C_cysteine = 0.0000" << endl; } else { for (vector<ResidueModification>::const_iterator it = fixed_modifications.begin(); it != fixed_modifications.end(); ++it) { String AA = it->getOrigin(); if ((AA!="N-term") && (AA!="C-term")) { const Residue* r = ResidueDB::getInstance()->getResidue(AA); String name = r->getName(); os << "add_" << r->getOneLetterCode() << "_" << name.toLower() << " = " << it->getDiffMonoMass() << endl; } else { os << "add_" << AA.erase(1,1) << "_peptide = " << it->getDiffMonoMass() << endl; } } } //TODO register cut_before and cut_after in Enzymes.xml plus datastructures to add all our Enzymes with our names instead. // COMET_ENZYME_INFO _must_ be at the end of this parameters file os << "[COMET_ENZYME_INFO]" << "\n"; os << "0. No_enzyme 0 - -" << "\n"; os << "1. Trypsin 1 KR P" << "\n"; os << "2. Trypsin/P 1 KR -" << "\n"; os << "3. Lys_C 1 K P" << "\n"; os << "4. Lys_N 0 K -" << "\n"; os << "5. Arg_C 1 R P" << "\n"; os << "6. Asp_N 0 D -" << "\n"; os << "7. CNBr 1 M -" << "\n"; os << "8. Glu_C 1 DE P" << "\n"; os << "9. PepsinA 1 FL P" << "\n"; os << "10. Chymotrypsin 1 FWYL P" << "\n"; }
//----------------------------------------------------------------------------// void D3D9Shader::parseParam(D3DXHANDLE parent, String prefix, unsigned int index) { D3DXHANDLE hConst = mpConstTable->GetConstant(parent, index); D3DXCONSTANT_DESC desc; uint numParams = 1; HRESULT hr = mpConstTable->GetConstantDesc(hConst, &desc, &numParams); if(FAILED(hr)) { TITAN_EXCEPT_API( "we can not get constants descriptions from shader"); } String paramName = desc.Name; // trim the odd '$' which appears at the start of the names in HLSL if (paramName.at(0) == '$') paramName.erase(paramName.begin()); // Also trim the '[0]' suffix if it exists, we will add our own indexing later if (StringUtil::endsWith(paramName, "[0]", false)) { paramName.erase(paramName.size() - 3); } if (desc.Class == D3DXPC_STRUCT) { prefix = prefix + paramName + "."; for(uint i = 0;i < desc.StructMembers; ++i) { parseParam(hConst, prefix, i); } } else { if (desc.Type == D3DXPT_FLOAT || desc.Type == D3DXPT_INT || desc.Type == D3DXPT_BOOL) { size_t paramIndex = desc.RegisterIndex; String name = prefix + paramName; ShaderConstantDef def; def.registerIndex = paramIndex; populateDef(desc, def); if (def.isFloat()) { def.physicalIndex = mFloatRegisterToPhysical->bufferSize; mFloatRegisterToPhysical->bufferMap.insert(ShaderRegisterIndexUseMap::value_type( paramIndex, ShaderRegisterIndexUse(def.physicalIndex,def.arraySize * def.elementSize))); mFloatRegisterToPhysical->bufferSize += def.arraySize * def.elementSize; mConstantDefs->floatBufferSize = mFloatRegisterToPhysical->bufferSize; } else { def.physicalIndex = mIntRegisterToPhysical->bufferSize; mIntRegisterToPhysical->bufferMap.insert(ShaderRegisterIndexUseMap::value_type( paramIndex, ShaderRegisterIndexUse(def.physicalIndex,def.arraySize * def.elementSize))); mIntRegisterToPhysical->bufferSize += def.arraySize * def.elementSize; mConstantDefs->intBufferSize = mIntRegisterToPhysical->bufferSize; } mConstantDefs->constantDefMap.insert(ShaderConstantDefMap::value_type(name, def)); mConstantDefs->genConstantDefArrayEntries(name, def); } } }
void TerrainPaintInfoContainer::addTextureInfo( TextureInfo &info ) { assert ( isTextureInfoOk(info) ); String brushName = info.brushName; String pathName = info.ownerTextureName; addTexNameAndBrushMapInfo(pathName,brushName); size_t pos = pathName.find_last_of('/'); if (pos != String::npos) { pathName.erase(pos+1); pathName.append(brushName); brushName = pathName; } String texTypeStr; // 找到该纹理的类型字符串 StringTexTypeMap::iterator itForStringTexTypeMap = mStringTexTypeMap.begin(); while ( itForStringTexTypeMap != mStringTexTypeMap.end() ) { if (itForStringTexTypeMap->second == info.textureType) { texTypeStr = itForStringTexTypeMap->first; break; } ++itForStringTexTypeMap; } assert (itForStringTexTypeMap != mStringTexTypeMap.end()); TextureInfoMap::iterator it = mTextureInfoMap.find(brushName); // 如果当前map中没有这个brush,说明是一组新的画刷 if ( it == mTextureInfoMap.end() ) { TextureInfos newInfos; // 自动生成纹理名称,名称格式为 “组名|当前组的纹理序号|纹理类型” String textureName = info.brushName + "|" + Ogre::StringConverter::toString(newInfos.size()) + "|" + texTypeStr; info.textureName = textureName; newInfos.push_back(info); std::pair<TextureInfoMap::iterator, bool> inserted = mTextureInfoMap.insert( TextureInfoMap::value_type(brushName, newInfos) ); assert (inserted.second); } else { // 自动生成纹理名称 String textureName = info.brushName + "|" + Ogre::StringConverter::toString(it->second.size()) + "|" + texTypeStr; info.textureName = textureName; it->second.push_back(info); } }
size_t Format::process(String& str, size_t minArg, size_t maxArg, FormatFlags& flags, FormatErrorHandling errortype) { size_t len(str.length()); size_t c = static_cast<size_t>(-1); bool err = false; size_t i = 0; size_t percentStart = 0; for (; (i < len) && (c == size_t(-1)) && !err; ++i) { if( str[i] == '%' ) { percentStart = i; if (i + 1 < len) { ++i; if( str[i] == '%' ) { oss.append('%'); } else if( str[i] == BRACE_OPEN ) { if( !processFormatSpecifier(str, i, c, flags) ) { // No close brace or some other error. err = true; } else { // Incremented next loop. --i; } } else if( isdigit(str[i]) ) { c = str[i] - '0'; } else { // Random junk after '%' err = true; } } else { err = true; } } else // anything other than a '%' { oss.append(str[i]); } } // for if ( (i <= len) && (c != size_t(-1))) { if( c > maxArg ) { String error = String("Parameter specifier ") + c + " is too large (>" + maxArg + ")"; if( errortype == E_FORMAT_EXCEPTION ) { BLOCXX_THROW(FormatException, error.c_str()); } oss.append("\n*** " + error); err = true; } else if( c < minArg ) { String error = String("Parameter specifier ") + c + " must be >= " + minArg; if( errortype == E_FORMAT_EXCEPTION ) { BLOCXX_THROW(FormatException, error.c_str()); } oss.append("\n*** " + error); err = true; } } if (err) { // Print the percent and all of the text causing the error. size_t textlength = std::max(i, percentStart + 1) - percentStart; String error = "Error in format string at \"" + str.substring(percentStart, textlength) + "\""; if( errortype == E_FORMAT_EXCEPTION ) { BLOCXX_THROW(FormatException, error.c_str()); } oss.append("\n*** " + error + "\n"); str.erase(); return '0'; } str.erase(0, i); return c; } // process
// check basename for texture, and try to return jpg or png file void CheckTexture(const char *baseName, String &textureFileName) { const char *ext = strrchr(baseName,'.'); // check if jpg exists textureFileName=baseName; if (!ext) { textureFileName+=".jpg"; if (ExistsFile(textureFileName.c_str())) return; } // check if png exists textureFileName=baseName; if (ext) // erase ext textureFileName.erase(textureFileName.size()-strlen(ext),strlen(ext)); textureFileName+=".png"; if (ExistsFile(textureFileName.c_str())) return; // check if tga exists textureFileName=baseName; if (ext) // erase ext textureFileName.erase(textureFileName.size()-strlen(ext),strlen(ext)); textureFileName+=".tga"; if (ExistsFile(textureFileName.c_str())) { // convert tga to png String outFileName=baseName; if (ext) // erase ext outFileName.erase(outFileName.size()-strlen(ext),strlen(ext)); outFileName+=".png"; // bmp.TGAToPNG(textureFileName.c_str(),outFileName.c_str()); int width, height, comp; unsigned char *data = stbi_load(textureFileName.c_str(), &width, &height, &comp , 0); stbi_write_png(outFileName.c_str(), width, height, comp, data, width*comp); stbi_image_free(data); textureFileName = outFileName; return; } // check if jpg exists textureFileName=baseName; if (ext) // erase ext textureFileName.erase(textureFileName.size()-strlen(ext),strlen(ext)); textureFileName+=".jpg"; if (ExistsFile(textureFileName.c_str())) return; printf("Texture file not found:'%s'\n",baseName); }
//--------------------------------------------------------------------- void GLSLESProgramManagerCommon::extractConstantDefs(const String& src, GpuNamedConstants& defs, const String& filename) { // Parse the output string and collect all uniforms // NOTE this relies on the source already having been preprocessed // which is done in GLSLESProgram::loadFromSource String line; String::size_type currPos = src.find("uniform"); while (currPos != String::npos) { GpuConstantDefinition def; String paramName; // Now check for using the word 'uniform' in a larger string & ignore bool inLargerString = false; if (currPos != 0) { char prev = src.at(currPos - 1); if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n' && prev != ';') inLargerString = true; } if (!inLargerString && currPos + 7 < src.size()) { char next = src.at(currPos + 7); if (next != ' ' && next != '\t' && next != '\r' && next != '\n') inLargerString = true; } // skip 'uniform' currPos += 7; if (!inLargerString) { // find terminating semicolon String::size_type endPos = src.find(";", currPos); if (endPos == String::npos) { // problem, missing semicolon, abort break; } line = src.substr(currPos, endPos - currPos); // Remove spaces before opening square braces, otherwise // the following split() can split the line at inappropriate // places (e.g. "vec3 something [3]" won't work). for (String::size_type sqp = line.find (" ["); sqp != String::npos; sqp = line.find (" [")) line.erase (sqp, 1); // Split into tokens StringVector parts = StringUtil::split(line, ", \t\r\n"); for (StringVector::iterator i = parts.begin(); i != parts.end(); ++i) { // Is this a type? StringToEnumMap::iterator typei = mTypeEnumMap.find(*i); if (typei != mTypeEnumMap.end()) { completeDefInfo(typei->second, def); } else { // if this is not a type, and not empty, it should be a name StringUtil::trim(*i); if (i->empty()) continue; // Skip over precision keywords if(StringUtil::match((*i), "lowp") || StringUtil::match((*i), "mediump") || StringUtil::match((*i), "highp")) continue; String::size_type arrayStart = i->find("[", 0); if (arrayStart != String::npos) { // potential name (if butted up to array) String name = i->substr(0, arrayStart); StringUtil::trim(name); if (!name.empty()) paramName = name; String::size_type arrayEnd = i->find("]", arrayStart); String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1); StringUtil::trim(arrayDimTerm); // the array term might be a simple number or it might be // an expression (e.g. 24*3) or refer to a constant expression // we'd have to evaluate the expression which could get nasty // TODO def.arraySize = StringConverter::parseUnsignedLong(arrayDimTerm); } else { paramName = *i; def.arraySize = 1; } // Name should be after the type, so complete def and add // We do this now so that comma-separated params will do // this part once for each name mentioned if (def.constType == GCT_UNKNOWN) { LogManager::getSingleton().logMessage( "Problem parsing the following GLSL Uniform: '" + line + "' in file " + filename); // next uniform break; } // Complete def and add // increment physical buffer location def.logicalIndex = 0; // not valid in GLSL if (def.isFloat()) { def.physicalIndex = defs.floatBufferSize; defs.floatBufferSize += def.arraySize * def.elementSize; } else { def.physicalIndex = defs.intBufferSize; defs.intBufferSize += def.arraySize * def.elementSize; } defs.map.insert(GpuConstantDefinitionMap::value_type(paramName, def)); // Generate array accessors defs.generateConstantDefinitionArrayEntries(paramName, def); } } } // not commented or a larger symbol // Find next one currPos = src.find("uniform", currPos); } }
String Path::CompressPath(String path) { // Remove "./" and "../" references. A ".." will also result in the // removal of the proceeding directory. // Also cleans separators as in CleanSeparators(). // Assumes there are no trailing "/" // Start by cleaning separators path = Path::CleanSeparators(path); U32 src = 0; U32 dst = 0; while (path[src]) { if (path[src] == '/' && path[src + 1] == '/') { src += 1; continue; } else if (path[src] == '.') { if (path[src + 1] == 0) { if (dst && path[dst - 1] == '/') dst--; src++; break; } else if (path[src + 1] == '/') { src += 2; continue; } else if (path[src + 1] == '.') { if (path[src + 2] == 0) { if (dst && path[dst - 1] == '/') dst = path.find('/', dst - 1, String::Right); src += 2; break; } if (dst && path[dst - 1] == '/') dst = path.find('/', dst - 1, String::Right) + 1; else dst += 3; src += 3; continue; } } if (dst != src) { String end = path.substr(src, path.length() - src); if (dst > 0 && end[(String::SizeType)0] == '/' && path[dst-1] == '/') end = end.substr(1, end.length() - 1); path.replace(dst, path.length() - dst, end); src = dst; } else { src++; dst++; } } if (src - dst) path.erase(dst, src - dst); return path; }
//--------------------------------------------------------------------- void CgProgram::recurseParams(CGparameter parameter, size_t contextArraySize) { while (parameter != 0) { // Look for uniform parameters only // Don't bother enumerating unused parameters, especially since they will // be optimised out and therefore not in the indexed versions CGtype paramType = cgGetParameterType(parameter); if (cgGetParameterVariability(parameter) == CG_UNIFORM && paramType != CG_SAMPLER1D && paramType != CG_SAMPLER2D && paramType != CG_SAMPLER3D && paramType != CG_SAMPLERCUBE && paramType != CG_SAMPLERRECT && cgGetParameterDirection(parameter) != CG_OUT && cgIsParameterReferenced(parameter)) { int arraySize; switch(paramType) { case CG_STRUCT: recurseParams(cgGetFirstStructParameter(parameter)); break; case CG_ARRAY: // Support only 1-dimensional arrays arraySize = cgGetArraySize(parameter, 0); recurseParams(cgGetArrayParameter(parameter, 0), (size_t)arraySize); break; default: // Normal path (leaf) String paramName = cgGetParameterName(parameter); size_t logicalIndex = cgGetParameterResourceIndex(parameter); // Get the parameter resource, to calculate the physical index CGresource res = cgGetParameterResource(parameter); bool isRegisterCombiner = false; size_t regCombinerPhysicalIndex = 0; switch (res) { case CG_COMBINER_STAGE_CONST0: // register combiner, const 0 // the index relates to the texture stage; store this as (stage * 2) + 0 regCombinerPhysicalIndex = logicalIndex * 2; isRegisterCombiner = true; break; case CG_COMBINER_STAGE_CONST1: // register combiner, const 1 // the index relates to the texture stage; store this as (stage * 2) + 1 regCombinerPhysicalIndex = (logicalIndex * 2) + 1; isRegisterCombiner = true; break; default: // normal constant break; } // Trim the '[0]' suffix if it exists, we will add our own indexing later if (StringUtil::endsWith(paramName, "[0]", false)) { paramName.erase(paramName.size() - 3); } GpuConstantDefinition def; def.arraySize = contextArraySize; mapTypeAndElementSize(paramType, isRegisterCombiner, def); if (def.constType == GCT_UNKNOWN) { LogManager::getSingleton().logMessage( "Problem parsing the following Cg Uniform: '" + paramName + "' in file " + mName); // next uniform parameter = cgGetNextParameter(parameter); continue; } if (isRegisterCombiner) { def.physicalIndex = regCombinerPhysicalIndex; } else { // base position on existing buffer contents if (def.isFloat()) { def.physicalIndex = mFloatLogicalToPhysical->bufferSize; } else { def.physicalIndex = mIntLogicalToPhysical->bufferSize; } } def.logicalIndex = logicalIndex; if( mParametersMap.find(paramName) == mParametersMap.end()) { mParametersMap.insert(GpuConstantDefinitionMap::value_type(paramName, def)); mParametersMapSizeAsBuffer += sizeof(size_t); mParametersMapSizeAsBuffer += paramName.size(); mParametersMapSizeAsBuffer += sizeof(GpuConstantDefinition); } // Record logical / physical mapping if (def.isFloat()) { OGRE_LOCK_MUTEX(mFloatLogicalToPhysical->mutex); mFloatLogicalToPhysical->map.insert( GpuLogicalIndexUseMap::value_type(def.logicalIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL))); mFloatLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; } else { OGRE_LOCK_MUTEX(mIntLogicalToPhysical->mutex); mIntLogicalToPhysical->map.insert( GpuLogicalIndexUseMap::value_type(def.logicalIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL))); mIntLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; } break; } } // now handle uniform samplers. This is needed to fix their register positions // if delegating to a GLSL shader. if (mDelegate && cgGetParameterVariability(parameter) == CG_UNIFORM && ( paramType == CG_SAMPLER1D || paramType == CG_SAMPLER2D || paramType == CG_SAMPLER3D || paramType == CG_SAMPLERCUBE || paramType == CG_SAMPLERRECT) && cgGetParameterDirection(parameter) != CG_OUT && cgIsParameterReferenced(parameter)) { String paramName = cgGetParameterName(parameter); CGresource res = cgGetParameterResource(parameter); int pos = -1; switch (res) { case CG_TEXUNIT0: pos = 0; break; case CG_TEXUNIT1: pos = 1; break; case CG_TEXUNIT2: pos = 2; break; case CG_TEXUNIT3: pos = 3; break; case CG_TEXUNIT4: pos = 4; break; case CG_TEXUNIT5: pos = 5; break; case CG_TEXUNIT6: pos = 6; break; case CG_TEXUNIT7: pos = 7; break; case CG_TEXUNIT8: pos = 8; break; case CG_TEXUNIT9: pos = 9; break; case CG_TEXUNIT10: pos = 10; break; case CG_TEXUNIT11: pos = 11; break; case CG_TEXUNIT12: pos = 12; break; case CG_TEXUNIT13: pos = 13; break; case CG_TEXUNIT14: pos = 14; break; case CG_TEXUNIT15: pos = 15; break; #if(CG_VERSION_NUM >= 3000) case CG_TEXUNIT16: pos = 16; break; case CG_TEXUNIT17: pos = 17; break; case CG_TEXUNIT18: pos = 18; break; case CG_TEXUNIT19: pos = 19; break; case CG_TEXUNIT20: pos = 20; break; case CG_TEXUNIT21: pos = 21; break; case CG_TEXUNIT22: pos = 22; break; case CG_TEXUNIT23: pos = 23; break; case CG_TEXUNIT24: pos = 24; break; case CG_TEXUNIT25: pos = 25; break; case CG_TEXUNIT26: pos = 26; break; case CG_TEXUNIT27: pos = 27; break; case CG_TEXUNIT28: pos = 28; break; case CG_TEXUNIT29: pos = 29; break; case CG_TEXUNIT30: pos = 30; break; case CG_TEXUNIT31: pos = 31; break; #endif default: break; } if (pos != -1) { mSamplerRegisterMap.insert(std::make_pair(paramName, pos)); } } // Get next parameter = cgGetNextParameter(parameter); } }
/** * @brief Read one (DOS or UNIX or Mac) line. * @param [out] line Line read. * @param [out] eol EOL bytes read (if any). * @param [out] lossy TRUE if there were lossy encoding. * @return true if there is more lines to read, false when last line is read. */ bool UniMemFile::ReadString(String & line, String & eol, bool * lossy) { line.erase(); eol.erase(); LPCTSTR pchLine = (LPCTSTR)m_current; // shortcut methods in case file is in the same encoding as our Strings if (m_unicoding == ucr::UCS2LE) { int cchLine = 0; // If there aren't any wchars left in the file, return FALSE to indicate EOF if (m_current - m_base + 1 >= m_filesize) return false; // Loop through wchars, watching for eol chars or zero while (m_current - m_base + 1 < m_filesize) { wchar_t wch = *(wchar_t *)m_current; INT64 wch_offset = (m_current - m_base); m_current += 2; if (wch == '\n' || wch == '\r') { eol += wch; if (wch == '\r') { if (m_current - m_base + 1 < m_filesize && *(wchar_t *)m_current == '\n') { eol += '\n'; m_current += 2; ++m_txtstats.ncrlfs; } else { ++m_txtstats.ncrs; } } else { ++m_txtstats.nlfs; } ++m_lineno; line.assign(pchLine, cchLine); return true; } if (!wch) { RecordZero(m_txtstats, wch_offset); } ++cchLine; } line.assign(pchLine, cchLine); return true; } if (m_current - m_base + (m_charsize - 1) >= m_filesize) return false; // Handle 8-bit strings in line chunks because of multibyte codings (eg, 936) if (m_unicoding == ucr::NONE) { bool eof = true; LPBYTE eolptr = 0; for (eolptr = m_current; (eolptr - m_base + (m_charsize - 1) < m_filesize); ++eolptr) { if (*eolptr == '\n' || *eolptr == '\r') { eof = false; break; } if (*eolptr == 0) { INT64 offset = (eolptr - m_base); RecordZero(m_txtstats, offset); } } bool success = ucr::maketstring(line, (LPCSTR)m_current, eolptr - m_current, m_codepage, lossy); if (!success) { return false; } if (lossy && *lossy) ++m_txtstats.nlosses; if (!eof) { eol += (TCHAR) * eolptr; ++m_lineno; if (*eolptr == '\r') { if (eolptr - m_base + (m_charsize - 1) < m_filesize && eolptr[1] == '\n') { eol += '\n'; ++m_txtstats.ncrlfs; } else ++m_txtstats.ncrs; } else ++m_txtstats.nlfs; } m_current = eolptr + eol.length(); // TODO: What do we do if save was lossy ? return !eof; } while (m_current - m_base + (m_charsize - 1) < m_filesize) { UINT ch = 0; UINT utf8len = 0; bool doneline = false; if (m_unicoding == ucr::UTF8) { // check for end in middle of UTF-8 character utf8len = ucr::Utf8len_fromLeadByte(*m_current); if (m_current - m_base + utf8len > m_filesize) { ch = '?'; m_current = m_base + m_filesize; doneline = true; } // Handle bad UTF-8 or UTF-8 outside of UCS-2 // (Convert bad bytes individually to '?' else if (utf8len < 1 || utf8len > 4) { ch = '?'; utf8len = 1; } else { ch = ucr::GetUtf8Char(m_current); } } else { ch = ucr::get_unicode_char(m_current, (ucr::UNICODESET)m_unicoding, m_codepage); if (!ch) doneline = true; } // convert from Unicode codepoint to TCHAR string // could be multicharacter if decomposition took place, for example bool lossy = false; // try to avoid lossy conversion String sch = ucr::maketchar(ch, lossy); if (lossy) ++m_txtstats.nlosses; if (sch.length() >= 1) ch = sch[0]; else ch = 0; if (ch == '\r') { eol = _T("\r"); doneline = true; bool crlf = false; // check for crlf pair if (m_current - m_base + 2 * m_charsize - 1 < m_filesize) { // For UTF-8, this ch will be wrong if character is non-ASCII // but we only check it against \n here, so it doesn't matter UINT ch = ucr::get_unicode_char(m_current + m_charsize, (ucr::UNICODESET)m_unicoding); if (ch == '\n') { crlf = true; } } if (crlf) { eol = _T("\r\n"); ++m_txtstats.ncrlfs; // advance an extra character to skip the following lf m_current += m_charsize; } else { ++m_txtstats.ncrs; } } else if (ch == '\n') { eol = _T("\n"); doneline = true; ++m_txtstats.nlfs; } else if (!ch) { INT64 offset = (m_current - m_base); RecordZero(m_txtstats, offset); } // always advance to next character if (m_unicoding == ucr::UTF8) { m_current += utf8len; } else { m_current += m_charsize; } if (doneline) { if (!eol.empty()) ++m_lineno; return true; } Append(line, sch.c_str(), sch.length()); } return true; }
//----------------------------------------------------------------------------------- void HlmsJsonPbs::saveTexture( const Vector3 &value, const ColourValue &bgDiffuse, const char *blockName, PbsTextureTypes textureType, bool writeValue, bool writeBgDiffuse, bool scalarValue, bool isFresnel, bool writeTexture, const HlmsPbsDatablock *datablock, String &outString ) { outString += ",\n\t\t\t\""; outString += blockName; outString += "\" :\n\t\t\t{\n"; const size_t currentOffset = outString.size(); if( isFresnel ) scalarValue = !datablock->hasSeparateFresnel(); if( writeValue ) { outString += "\t\t\t\t\"value\" : "; if( scalarValue ) outString += StringConverter::toString( value.x ); else { HlmsJson::toStr( value, outString ); } } if( writeBgDiffuse ) { outString += ",\n\t\t\t\t\"background\" : "; HlmsJson::toStr( bgDiffuse, outString ); } if( isFresnel ) { if( datablock->hasSeparateFresnel() ) outString += ",\n\t\t\t\t\"mode\" : \"coloured\""; else outString += ",\n\t\t\t\t\"mode\" : \"coeff\""; } if( textureType >= PBSM_DETAIL0 && textureType <= PBSM_DETAIL3_NM ) { if( textureType >= PBSM_DETAIL0 && textureType <= PBSM_DETAIL3 ) { PbsBlendModes blendMode = datablock->getDetailMapBlendMode( textureType - PBSM_DETAIL0 ); if( blendMode != PBSM_BLEND_NORMAL_NON_PREMUL ) { outString += ",\n\t\t\t\t\"mode\" : \""; outString += c_pbsBlendModes[blendMode]; outString += '"'; } } const Vector4 &offsetScale = datablock->getDetailMapOffsetScale( textureType - PBSM_DETAIL0 ); const Vector2 offset( offsetScale.x, offsetScale.y ); const Vector2 scale( offsetScale.z, offsetScale.w ); if( offset != Vector2::ZERO ) { outString += ",\n\t\t\t\t\"offset\" : "; HlmsJson::toStr( offset, outString ); } if( scale != Vector2::UNIT_SCALE ) { outString += ",\n\t\t\t\t\"scale\" : "; HlmsJson::toStr( scale, outString ); } } if( writeTexture ) { HlmsTextureManager::TextureLocation texLocation; texLocation.texture = datablock->getTexture( textureType ); if( !texLocation.texture.isNull() ) { texLocation.xIdx = datablock->_getTextureIdx( textureType ); texLocation.yIdx = 0; texLocation.divisor = 1; const String *texName = mHlmsManager->getTextureManager()->findAliasName( texLocation ); if( texName ) { outString += ",\n\t\t\t\t\"texture\" : \""; outString += *texName; outString += '"'; } } const HlmsSamplerblock *samplerblock = datablock->getSamplerblock( textureType ); if( samplerblock ) { outString += ",\n\t\t\t\t\"sampler\" : "; outString += HlmsJson::getName( samplerblock ); } if( textureType < NUM_PBSM_SOURCES && datablock->getTextureUvSource( textureType ) != 0 ) { outString += ",\n\t\t\t\t\"uv\" : "; outString += StringConverter::toString( datablock->getTextureUvSource( textureType ) ); } } if( !writeValue && outString.size() != currentOffset ) { //Remove an extra comma and newline characters. outString.erase( currentOffset, 2 ); } outString += "\n\t\t\t}"; }