Exemple #1
0
int seqspec_IDset (Seqspec this1, char *seqID) {
  /**
     Set ID of 'this1' sequence segment
     @param[in] this1 - the Seqspec object
     @param[in] seqID - name of UNIX file containing a sequence (filename must
                        not contain ':') or sequence identifier in the form
                        db:seq
     @param[out] this1 - dbseqname always set; dbname and seqname only set if
                         database sequence; if 0 returned then dbseqname,
                         dbname, seqname are undefined
     @param[out] seqID - destroyed
     @return 1 if parsed ok, 0 else if seqspec_filesOk(1) is in effect,
             file names are considered ok, else only seqIDs of the form
             db:seq are ok
  */
  char *seqname;
  strReplace (&this1->dbseqname,seqID);
  if (strchr (seqID,':')) {
    toupperStr (seqID); // DBNAME:SEQNAME
    if ((seqname = dbseqDissect (seqID)) == NULL)
      return 0;
    strReplace (&this1->dbname,seqID);
    strReplace (&this1->seqname,seqname);
  }
  else { // assume file name
    if (gFilesOk) {
      hlr_free (this1->dbname);
      hlr_free (this1->seqname);
    }
    else
      return 0;
  }
  return 1;
}
Exemple #2
0
void AsmPass1(Assembler *a, char *text) {             // 第一階段的組譯           
  int i, address = 0, number;                                                 
  Array* lines = split(text, "\r\n", REMOVE_SPLITER); // 將組合語言分割成一行一行
  ArrayEach(lines, strPrintln);                       // 印出以便觀察           
  printf("=================PASS1================\n");               
  for (i=0; i<lines->count; i++) {                    // 對於每一行                        
      strReplace(lines->item[i], ";", '\0');
      strReplace(lines->item[i], "\t", ' ');
      AsmCode *code = AsmCodeNew(lines->item[i]);     // 建立指令物件
      if (code == NULL) continue;
      code->address = address;                        // 設定該行的位址      
      Op *op = NULL;
      if (code->op != NULL) {
        op = HashTableGet(opTable, code->op);           // 查詢運算碼            
        if (op != NULL) {                               // 如果查到
          code->opCode = op->code;                      //    設定運算碼
          code->type = op->type;                        //    設定型態
        }                                                  
      }
      if (code->label != NULL)                        // 如果有標記符號
        HashTablePut(a->symTable, code->label, code); //    加入符號表中
      ArrayAdd(a->codes, code);                       //  建構指令物件陣列
      AsmCodePrintln(code);                           //    印出觀察
      code->size = AsmCodeSize(code);                 //  計算指令大小
      address += code->size;                          //  計算下一個指令位址
  }                                                                           
  ArrayFree(lines, strFree);                          // 釋放記憶體
}
	const std::string tokenizeUrl(const std::string& url)
	{
		std::string ret(url.c_str());
		strReplace(ret, "+", "-");
		strReplace(ret, "*", "");
		strReplace(ret, ",", "");
		strReplace(ret, "%", "");
		return ret;
	}
Exemple #4
0
void CWebTV::loadChannels(void)
{
	readChannellist(g_settings.userBouquet);
	
	title = std::string(rindex(g_settings.userBouquet.c_str(), '/') + 1);
	strReplace(title, ".xml", "");
	strReplace(title, ".tv", "");
	strReplace(title, ".m3u", "");
	strReplace(title, "userbouquet.", "");
}
Exemple #5
0
END_TEST

START_TEST(test_strReplace)
{
    char *string;

    string = strCreate();
    strCopy(string, "foobarfoo");
    strReplace(string, "foo", "xyz");
    fail_unless(strEquals(string, "xyzbarxyz"), NULL);
    strCopy(string, "foobarfoo");
    strReplace(string, "bar", "xyz");
    fail_unless(strEquals(string, "fooxyzfoo"), NULL);
    strCopy(string, "foobar");
    strReplace(string, "foo", "xyz");
    fail_unless(strEquals(string, "xyzbar"), NULL);
    strReplace(string, "foo", "xyz");
    fail_unless(strEquals(string, "xyzbar"), NULL);
    strReplace(string, "xyz", "");
    fail_unless(strEquals(string, "bar"), NULL);
    strReplace(string, "bar", "foo");
    fail_unless(strEquals(string, "foo"), NULL);
    strReplace(string, "foo", "");
    fail_unless(strEquals(string, ""), NULL);
    strReplace(string, "foo", "bar");
    fail_unless(strEquals(string, ""), NULL);
}
Exemple #6
0
String
strNReplace(String txt, String orig, String repl)
{
	String s = strReplace(txt, orig, repl);
	strFree(txt);
	return s;
}
Exemple #7
0
int main(int argc, char *[])
{
	char srcStr[] = {"aaabaaaab"};
	XString mainStr;
	mainStr.ch = NULL;
	mainStr.length = 0;
	
	char desStr[] = {"aaaab"};
	XString subStr;
	subStr.ch = NULL;
	subStr.length = 0;

	char repStr[] = {"cd"};
	XString rep;
	rep.ch = NULL;
	rep.length = 0;

	strAssign(mainStr, srcStr);
	strAssign(subStr, desStr);
	strAssign(rep, repStr);
	printf("mainStr len: %d, mainStr: %s\n", mainStr.length, mainStr.ch);
	printf("subStr len: %d, subStr: %s\n", subStr.length, subStr.ch);
	printf("rep len: %d, rep: %s\n", rep.length, rep.ch);

	int index = indexStr(mainStr, subStr, 0);
	printf("index: %d\n", index);

	strReplace(mainStr, subStr, rep);

	printf("new len: %d, new mainStr: %s\n", mainStr.length, mainStr.ch);

	return 0;
}
Exemple #8
0
/* ****************************************************************************
*
* StatusCode::render -
*/
std::string StatusCode::render(Format format, const std::string& indent, bool comma, bool showTag)
{
    std::string  out  = "";

    if (strstr(details.c_str(), "\"") != NULL)
    {
        int    len = details.length() * 2;
        char*  s2    = (char*) calloc(1, len + 1);

        strReplace(s2, len, details.c_str(), "\"", "\\\"");
        details = s2;
        free(s2);
    }

    if (code == SccNone)
    {
        fill(SccReceiverInternalError, "");
        details += " - ZERO code set to 500";
    }

    out += startTag(indent, tag, format, showTag);
    out += valueTag(indent + "  ", "code", code, format, true);
    out += valueTag(indent + "  ", "reasonPhrase", reasonPhrase, format, details != "");

    if (details != "")
    {
        out += valueTag(indent + "  ", "details", details, format, false);
    }

    out += endTag(indent, tag, format, comma);

    return out;
}
Exemple #9
0
/**
 * Writes a real (double) variable to the DXF file.
 *
 * @param gc Group code.
 * @param value Double value
 */
void DL_WriterA::dxfReal(int gc, double value) const {
    char str[256];
    sprintf(str, "%.16lf", value);

    // fix for german locale:
    strReplace(str, ',', '.');

    // Cut away those zeros at the end:
    bool dot = false;
    int end = -1;
    for (unsigned int i=0; i<strlen(str); ++i) {
        if (str[i]=='.') {
            dot = true;
            end = i+2;
            continue;
        } else if (dot && str[i]!='0') {
            end = i+1;
        }
    }
    if (end>0 && end<(int)strlen(str)) {
        str[end] = '\0';
    }

    dxfString(gc, str);
    m_ofile.flush();
}
Exemple #10
0
const char* FileMgr::workDir()
{
   const int kBufLen = 1024;
   char buf[kBufLen];
   _getcwd(buf, kBufLen);
   strReplace(buf, '\\', '/');
   return strCat(buf, "/");
}
Exemple #11
0
/**
 * Get the next BlastQuery.
 * @pre The module has been initialized using blastParser_init().
 */
BlastQuery* blastParser_nextQuery (void)
{
    char *line,*pos;
    static char *queryName = NULL;
    static char *prevBlastQueryName = NULL;
    static BlastQuery *currBlastQuery = NULL;
    int first;

    if (!ls_isEof (ls)) {
        blastParser_freeQuery (currBlastQuery);
        currBlastQuery = NULL;
        AllocVar (currBlastQuery);
        currBlastQuery->entries = arrayCreate (5,BlastEntry);
        first = 1;
        while (line = ls_nextLine (ls)) {
            if (line[0] == '\0') {
                continue;
            }
            pos = strchr (line,'\t');
            *pos = '\0';
            strReplace (&queryName,line);
            if (first == 1 || strEqual (prevBlastQueryName,queryName)) {
                blastParser_processLine (pos + 1,currBlastQuery);
            }
            else {
                ls_back (ls,1);
                return currBlastQuery;
            }
            if (first == 1) {
                currBlastQuery->qName = hlr_strdup (queryName);
                first = 0;
            }
            strReplace(&prevBlastQueryName,queryName);
        }
        if (first == 1) {
            return NULL;
        }
        else {
            return currBlastQuery;
        }
    }
    blastParser_freeQuery (currBlastQuery);
    currBlastQuery = NULL;
    return NULL;
}
Exemple #12
0
    /** @brief Create a double precision kernel out of a single precision kernel
    *
    * @param source          The source string
    * @param fp_extension    An info string that specifies the OpenCL double precision extension
    * @return   The double precision kernel
    */
    inline std::string make_double_kernel(std::string const & source, std::string const & fp_extension)
    {
      std::stringstream ss;
      ss << "#pragma OPENCL EXTENSION " << fp_extension << " : enable\n\n";

      std::string result = ss.str();
      result.append(strReplace(source, "float", "double"));
      return result;
    }
Exemple #13
0
 /** @brief Create a double precision kernel out of a single precision kernel
 *
 * @param source   The source string
 * @return   The double precision kernel
 */
 std::string make_double_kernel(std::string const & source)
 {
   #ifdef VIENNACL_EXPERIMENTAL_DOUBLE_PRECISION_WITH_STREAM_SDK
     std::string result = "#pragma OPENCL EXTENSION cl_amd_fp64 : enable\n\n";
   #else
     std::string result = "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n\n";
   #endif
   result.append(strReplace(source, "float", "double"));
   return result;
 }
Exemple #14
0
  const std::string tokenize(const std::string& token)
  {
		std::string ret(token.c_str());
		std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
		for (unsigned i=0;i<stripCount;i++)
		{
			strReplace(ret, std::string(stripChars[i]), "");
		}
    
		return ret;
  }
Exemple #15
0
//
// findWord()
//   Search for a character string using a binary search.
//   Returns the index of the word on success, or -1 on 
//   failure.
//
bool WordsFile::findWord(const char* str, int& index) throw(AiksaurusException)
{  
    // Create copy of str, so that we can turn spaces into colons.
    // We only need to copy the first s_wordlen + 1 bytes to ensure
    // that we will get a correct match.
    char* s = new char[maxWordLength() + 2];          
    s[maxWordLength() + 1] = 0;               
    for(int i = 0; i < (maxWordLength() + 2); ++i)
    {
        s[i] = str[i];
        if (!str[i]) break;
    } 
   
    // In the datafile, spaces are stored as colons.  Convert spaces
    // on search word into colons so that we can do a simple case 
    // insensitive compare. 
    strReplace(s, ASCII_SPACE, ASCII_COLON);
    
    // Initialize low/high for classic binary search.   
    int low = 0, high = getSize() - 1;    
    index = -1;
    
    // Perform our binary search.
    while(low <= high)
    {
        int mid = (high + low) / 2;
        
        loadWord(mid);
        
        int compare = AsciiCompare(s, d_word);
        
        if (compare < 0) 
            high = mid - 1;
        
        else if (compare > 0)
            low = mid + 1;
        
        else {
            index = mid;
            break;
        }
    }

	delete[] s;
    bool ret = true;
    
    if (index == -1)
    { 
        index = low;
        return false;
    }
    
    return ret;
}
Exemple #16
0
static void extractCoordinates (char *string, int *start, int *end)
{
	static char* stringCopy = NULL; 
	char *pos1,*pos2;

	strReplace (&stringCopy,string);
	pos1 = strchr (stringCopy,':');
	pos2 = strchr (stringCopy,'-');
	*pos2 = '\0';
	*start = atoi (pos1 + 1);
	*end = atoi (pos2 + 1);
}
std::string CStringChecker::ReplaceDirName( LPCTSTR str, LPCTSTR strRe )
{
	std::string strTemp(str);
	std::string strReplace(strRe);
	std::string strReturn;

	if(strTemp.empty()) return strReturn;

	for(int i = 0; i < (int)strTemp.length(); i++)
	{
		UCHAR c = strTemp[i];
		BOOL b = TRUE;
		if(c < 0xB0 && CString(CHAR(c)).FindOneOf(CStringCheckerConfig::CheckFilterReplace) != -1)
		{//字符查找
			b = FALSE;
		}
		else if(CString(strTemp.substr(i, 2).c_str()).FindOneOf(CStringCheckerConfig::CheckFilterReplace) != -1)
		{//汉字查找
			i++;
			b = FALSE;
		}
		else if((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_' )
		{
			if(c >= 0xB0 && c<= 0xF7 && UCHAR(strTemp[i + 1]) >= 0xA1 && UCHAR(strTemp[i + 1]) <= 0xFE)
			{//属于汉字范围
				strReturn += strTemp.substr(i, 2);
				i++;
				continue;
			}
			if(c >= 0x80)
			{//是全角符号
				strReturn += strTemp.substr(i, 2);
				i++;
				continue;
			}
			b = FALSE;
		}

		if(b)
		{//加上原字符
			strReturn += c;
		}
		else
		{//加上替换字符串
			strReturn += strRe;
		}

	}

	return strReturn;
}
Exemple #18
0
bool cacheCdromIndex(string vol_id, string rep_location)
{
	//mDebug("Caching index for ["+vol_id+"] in with location [" + rep_location+"]");
	string rep_location_id = rep_location;
	strReplace(&rep_location_id, "/", "_");
	bool ret = false;
	if (system("mkdir -p /var/mpkg/index_cache/"+vol_id + "~" + rep_location_id)==0 && system("cp -f /var/log/mount/" +rep_location+"/packages.xml.gz /var/mpkg/index_cache/"+vol_id + "~" + rep_location_id + "/")==0) ret = true;
	if (setupMode && FileExists("/var/log/mount/" +rep_location+"/setup_variants.list")) {
		system("cp -f /var/log/mount/" +rep_location+"/setup_variants.list /var/mpkg/index_cache/"+vol_id + "~" + rep_location_id + "/");
		system("mkdir -p /var/mpkg/index_cache/"+vol_id + "~" + rep_location_id + "/setup_variants");
		system("cp -f /var/log/mount/" +rep_location+"/setup_variants/* /var/mpkg/index_cache/"+vol_id + "~" + rep_location_id + "/setup_variants/");
	}
	return ret;
}
Exemple #19
0
int setver_package(const string& filename, const string& version) {
	SourcePackage spkg;
	BinaryPackage pkg;
	bool binary_pkg = false;
	string xml_path;
	string pkgType = getExtension(filename);
	if (pkgType=="tgz" || pkgType=="tbz" || pkgType=="txz" || pkgType=="tlz") {
		binary_pkg = true;
		pkg.setInputFile(filename);
		pkg.unpackFile();
		xml_path = pkg.getDataFilename();
	}
	if (filename.find(".spkg")!=std::string::npos) {

		spkg.setInputFile(filename);
		spkg.unpackFile();
		xml_path = spkg.getDataFilename();
	}
	if (!FileExists(xml_path)) return -2;
	XMLResults xmlErrCode;
	XMLNode _node = XMLNode::parseFile(xml_path.c_str(), "package", &xmlErrCode);
	if (xmlErrCode.error != eXMLErrorNone)
	{
		mError("parse error");
		fprintf(stderr, "%s\n", _node.getError(xmlErrCode.error));
		return -1;
	}
	mDebug("File opened");
	if (_node.nChildNode("version")==0)
	{
		mError("Invalid package");
		return -1;
	}
	string old_ver = _node.getChildNode("version").getText();
	_node.getChildNode("version").updateText(version.c_str());
	string url;
	if (_node.nChildNode("mbuild")!=0 && _node.getChildNode("mbuild").nChildNode("url")!=0) {
		url = _node.getChildNode("mbuild").getChildNode("url").getText();
		strReplace(&url, old_ver, version);
		_node.getChildNode("mbuild").getChildNode("url").updateText(url.c_str());
	}
	_node.writeToFile(xml_path.c_str());
	if (binary_pkg) pkg.packFile();
	else spkg.packFile();
	return 0;


}
Exemple #20
0
int lr_replace( const char *lrparam, char *findstr, char *replacestr )
{
int res = 0;
char *result_str;
char lrp[1024];
 
sprintf( lrp, "{%s}", lrparam);
 
result_str = strReplace( lr_eval_string(lrp), findstr, replacestr );
 
if (result_str != 0 )
{
lr_save_string( result_str, lrparam );
free( result_str );
res = 1;
}
return res;
}  
Exemple #21
0
// full_list.txt를 쓴다.
// int XMain::WriteFullList( XArrayLinear<XPatch::XRES_INFO>& aryAll )
int XMain::WriteFullList( const XVector<XPatch::XRES_INFO>& aryAll )
{
    char cPath[ 1024 ];
    strcpy_s( cPath, SZ2C( XE::_GetPathPackageRoot() ) );
    strcat_s( cPath, "full_list.txt" );
    FILE *fp = NULL;
    fopen_s( &fp, cPath, "wt" );
    if( fp == NULL )
        return 0;
    char cBuff[ 1024 ];
//	XARRAYLINEAR_LOOP( aryAll, XPatch::XRES_INFO, info )
    for( auto& info : aryAll ) {
        strcpy_s( cBuff, SZ2C( info.strFile.c_str() ) );
        strReplace( cBuff, '\\', '/' );
        fprintf_s( fp, "\"%s\"\t%d\t%llu\n", cBuff, info.size, info.llChecksum );
    }
    fprintf_s( fp, "// num files %d \n", aryAll.size() );
    fclose( fp );
    return 1;
}
Exemple #22
0
// core_list.txt를 쓴다.
//int XMain::WriteCoreList( XArrayLinear<_tstring>& aryCore )
int XMain::WriteCoreList( const XVector<_tstring>& aryCore )
{
    char cPath[ 1024 ];
    strcpy_s( cPath, SZ2C( XE::_GetPathPackageRoot() ) );
    strcat_s( cPath, "core_list.txt" );
    FILE *fp = NULL;
    fopen_s( &fp, cPath, "wt" );
    if( fp == NULL )
        return 0;
    char cBuff[ 1024 ];
//	XARRAYLINEAR_LOOP( aryCore, _tstring, strRes )
    for( auto& strRes : aryCore ) {
        strcpy_s( cBuff, SZ2C( strRes.c_str() ) );
        strReplace( cBuff, '\\', '/' );
        fprintf_s( fp, "\"%s\"\n", cBuff );
        //		fprintf_s( fp, "\"%s\"\n", SZ2C( strRes.c_str() ) );
    }
    fprintf_s( fp, "// num files %d \n", aryCore.size() );
    fclose( fp );
    return 1;
}
Exemple #23
0
bool CDVDFileInfo::AddExternalSubtitleToDetails(const std::string &path, CStreamDetails &details, const std::string& filename, const std::string& subfilename)
{
  std::string ext = URIUtils::GetExtension(filename);
  std::string vobsubfile = subfilename;
  if(ext == ".idx")
  {
    if (vobsubfile.empty())
      vobsubfile = URIUtils::ReplaceExtension(filename, ".sub");

    CDVDDemuxVobsub v;
    if (!v.Open(filename, STREAM_SOURCE_NONE, vobsubfile))
      return false;

    int count = v.GetNrOfStreams();

    for(int i = 0; i < count; i++)
    {
      CStreamDetailSubtitle *dsub = new CStreamDetailSubtitle();
      CDemuxStream* stream = v.GetStream(i);
      std::string lang = stream->language;
      dsub->m_strLanguage = g_LangCodeExpander.ConvertToISO6392T(lang);
      details.AddStream(dsub);
    }
    return true;
  }
  if(ext == ".sub")
  {
    std::string strReplace(URIUtils::ReplaceExtension(filename,".idx"));
    if (XFILE::CFile::Exists(strReplace))
      return false;
  }

  CStreamDetailSubtitle *dsub = new CStreamDetailSubtitle();
  ExternalStreamInfo info;
  CUtil::GetExternalStreamDetailsFromFilename(path, filename, info);
  dsub->m_strLanguage = g_LangCodeExpander.ConvertToISO6392T(info.language);
  details.AddStream(dsub);

  return true;
}
Exemple #24
0
int seqspec_split2continous (Seqspec this1) {
  /**
     If 'this1' sequence segment is of the form 'db:seq_n begin:b end:e'
     it is transformed into 'db:seq begin:b1 end:e1'
     where b1=b+n*100000, e1=e+n*100000
     which means the GCG type split is removed
     @param[in] this1 - the Seqspec object
     @param[out] this1 - the Seqspec object possibly modified
     @return 1 if 'this1' changed, else 0
  */
  static char *seqname = NULL;
  static Stringa dbseqname = NULL;
  int nameLen;
  char *cp;
  int offset;
  int segnum;

  stringCreateClear (dbseqname,40);
  strReplace (&seqname,this1->seqname);
  nameLen = strlen (seqname);
  if (nameLen < 3)
    return 0;
  if ((cp = strrchr(seqname, '_')) == NULL)
    return 0;
  if (*(cp+1) == '\0' || strlen (cp+1) > 2)
    return 0;
  segnum = atoi (cp+1);
  *cp = 0;
  offset = segnum * FRAGMENT_LENGTH;
  this1->begin += offset;
  if (this1->end != 0)
    this1->end += offset;
  stringCpy (dbseqname,this1->dbname);
  stringCat (dbseqname,":");
  stringCat (dbseqname,seqname);
  seqspec_IDset (this1,string (dbseqname));
  return 1;
}
/* ****************************************************************************
*
* StatusCode::toJson -
*
* For version 2 of the API, the unnecessary 'reasonPhrase' is removed.
*/
std::string StatusCode::toJson(bool isLastElement)
{
  std::string  out  = "";

  if (strstr(details.c_str(), "\"") != NULL)
  {
    int    len = details.length() * 2;
    char*  s    = (char*) calloc(1, len + 1);

    strReplace(s, len, details.c_str(), "\"", "\\\"");
    details = s;
    free(s);
  }

  char codeV[STRING_SIZE_FOR_INT];

  snprintf(codeV, sizeof(codeV), "%d", code);

  out += "{";

  out += std::string("\"code\":\"") + codeV + "\"";
  
  if (details != "")
  {
    out += ",\"details\":\"" + details + "\"";
  }

  out += "}";

  if (!isLastElement)
  {
    out += ",";
  }

  return out;
}
Exemple #26
0
void AsmSaveObjFile(Assembler *a, char *objFile) {
  printf("==========Save to ObjFile:%s==========\n", objFile);
  FILE *file = fopen(objFile, "wb");
  int i;
  for (i=0; i<a->codes->count; i++) {
    AsmCode *code = a->codes->item[i];
    char *objPtr = code->objCode;
    while (*objPtr != '\0') {
      int x;
      sscanf(objPtr, "%2x", &x);
      assert(x >= 0 && x < 256);
      BYTE b = (BYTE) x;
      fwrite(&b, sizeof(BYTE), 1, file);
      objPtr += 2;
      char bstr[3];
      sprintf(bstr, "%2x", b);
      strReplace(bstr, " ", '0');
      strToUpper(bstr);
      printf("%s", bstr);
    }
  }
  printf("\n");
  fclose(file);
}
Exemple #27
0
	static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
	{
		char ch = _options.shaderType;
		const glslopt_shader_type type = ch == 'f'
			? kGlslOptShaderFragment
			: (ch == 'c' ? kGlslOptShaderCompute : kGlslOptShaderVertex);

		glslopt_target target = kGlslTargetOpenGL;
		switch (_version)
		{
		case BX_MAKEFOURCC('M', 'T', 'L', 0):
			target = kGlslTargetMetal;
			break;

		case 2:
			target = kGlslTargetOpenGLES20;
			break;

		case 3:
			target = kGlslTargetOpenGLES30;
			break;

		default:
			target = kGlslTargetOpenGL;
			break;
		}

		glslopt_ctx* ctx = glslopt_initialize(target);

		glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);

		if (!glslopt_get_status(shader) )
		{
			const char* log = glslopt_get_log(shader);
			int32_t source  = 0;
			int32_t line    = 0;
			int32_t column  = 0;
			int32_t start   = 0;
			int32_t end     = INT32_MAX;

			bool found = false
				|| 3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
				|| 2 == sscanf(log, "(%u,%u):", &line, &column)
				;

			if (found
			&&  0 != line)
			{
				start = bx::uint32_imax(1, line-10);
				end   = start + 20;
			}

			printCode(_code.c_str(), line, start, end, column);
			fprintf(stderr, "Error: %s\n", log);
			glslopt_shader_delete(shader);
			glslopt_cleanup(ctx);
			return false;
		}

		const char* optimizedShader = glslopt_get_output(shader);

		// Trim all directives.
		while ('#' == *optimizedShader)
		{
			optimizedShader = bx::strnl(optimizedShader);
		}

		{
			char* code = const_cast<char*>(optimizedShader);
			strReplace(code, "gl_FragDepthEXT", "gl_FragDepth");

			strReplace(code, "texture2DLodARB", "texture2DLod");
			strReplace(code, "texture2DLodEXT", "texture2DLod");
			strReplace(code, "texture2DGradARB", "texture2DGrad");
			strReplace(code, "texture2DGradEXT", "texture2DGrad");

			strReplace(code, "textureCubeLodARB", "textureCubeLod");
			strReplace(code, "textureCubeLodEXT", "textureCubeLod");
			strReplace(code, "textureCubeGradARB", "textureCubeGrad");
			strReplace(code, "textureCubeGradEXT", "textureCubeGrad");

			strReplace(code, "texture2DProjLodARB", "texture2DProjLod");
			strReplace(code, "texture2DProjLodEXT", "texture2DProjLod");
			strReplace(code, "texture2DProjGradARB", "texture2DProjGrad");
			strReplace(code, "texture2DProjGradEXT", "texture2DProjGrad");

			strReplace(code, "shadow2DARB", "shadow2D");
			strReplace(code, "shadow2DEXT", "shadow2D");
			strReplace(code, "shadow2DProjARB", "shadow2DProj");
			strReplace(code, "shadow2DProjEXT", "shadow2DProj");
		}

		UniformArray uniforms;

		if (target != kGlslTargetMetal)
		{
			const char* parse = optimizedShader;

			while (NULL != parse
				&&  *parse != '\0')
			{
				parse = bx::strws(parse);
				const char* eol = bx::strFind(parse, ';');
				if (NULL != eol)
				{
					const char* qualifier = parse;
					parse = bx::strws(bx::strSkipWord(parse) );

					if (0 == bx::strCmp(qualifier, "attribute", 9)
					||  0 == bx::strCmp(qualifier, "varying",   7)
					||  0 == bx::strCmp(qualifier, "in",        2)
					||  0 == bx::strCmp(qualifier, "out",       3)
					   )
					{
						// skip attributes and varyings.
						parse = eol + 1;
						continue;
					}

					if (0 == bx::strCmp(parse, "tmpvar", 6) )
					{
						// skip temporaries
						parse = eol + 1;
						continue;
					}

					if (0 != bx::strCmp(qualifier, "uniform", 7) )
					{
						// end if there is no uniform keyword.
						parse = NULL;
						continue;
					}

					const char* precision = NULL;
					const char* typen = parse;

					if (0 == bx::strCmp(typen, "lowp", 4)
					||  0 == bx::strCmp(typen, "mediump", 7)
					||  0 == bx::strCmp(typen, "highp", 5) )
					{
						precision = typen;
						typen = parse = bx::strws(bx::strSkipWord(parse) );
					}

					BX_UNUSED(precision);

					char uniformType[256];
					parse = bx::strSkipWord(parse);

					if (0 == bx::strCmp(typen, "sampler", 7) )
					{
						bx::strCopy(uniformType, BX_COUNTOF(uniformType), "int");
					}
					else
					{
						bx::strCopy(uniformType, int32_t(parse-typen+1), typen);
					}

					const char* name = parse = bx::strws(parse);

					char uniformName[256];
					uint8_t num = 1;
					const char* array = bx::strFind(bx::StringView(name, int32_t(eol-parse) ), "[");
					if (NULL != array)
					{
						bx::strCopy(uniformName, int32_t(array-name+1), name);

						char arraySize[32];
						const char* end = bx::strFind(bx::StringView(array, int32_t(eol-array) ), "]");
						bx::strCopy(arraySize, int32_t(end-array), array+1);
						num = uint8_t(atoi(arraySize) );
					}
					else
					{
						bx::strCopy(uniformName, int32_t(eol-name+1), name);
					}

					Uniform un;
					un.type = nameToUniformTypeEnum(uniformType);

					if (UniformType::Count != un.type)
					{
						BX_TRACE("name: %s (type %d, num %d)", uniformName, un.type, num);

						un.name = uniformName;
						un.num = num;
						un.regIndex = 0;
						un.regCount = num;
						uniforms.push_back(un);
					}

					parse = eol + 1;
				}
			}
		}
		else
		{
			const char* parse = bx::strFind(optimizedShader, "struct xlatMtlShaderUniform {");
			const char* end   = parse;
			if (NULL != parse)
			{
				parse += bx::strLen("struct xlatMtlShaderUniform {");
				end   =  bx::strFind(parse, "};");
			}

			while ( parse < end
			&&     *parse != '\0')
			{
				parse = bx::strws(parse);
				const char* eol = bx::strFind(parse, ';');
				if (NULL != eol)
				{
					const char* typen = parse;

					char uniformType[256];
					parse = bx::strSkipWord(parse);
					bx::strCopy(uniformType, int32_t(parse-typen+1), typen);
					const char* name = parse = bx::strws(parse);

					char uniformName[256];
					uint8_t num = 1;
					const char* array = bx::strFind(bx::StringView(name, int32_t(eol-parse) ), "[");
					if (NULL != array)
					{
						bx::strCopy(uniformName, int32_t(array-name+1), name);

						char arraySize[32];
						const char* arrayEnd = bx::strFind(bx::StringView(array, int32_t(eol-array) ), "]");
						bx::strCopy(arraySize, int32_t(arrayEnd-array), array+1);
						num = uint8_t(atoi(arraySize) );
					}
					else
					{
						bx::strCopy(uniformName, int32_t(eol-name+1), name);
					}

					Uniform un;
					un.type = nameToUniformTypeEnum(uniformType);

					if (UniformType::Count != un.type)
					{
						BX_TRACE("name: %s (type %d, num %d)", uniformName, un.type, num);

						un.name = uniformName;
						un.num = num;
						un.regIndex = 0;
						un.regCount = num;
						uniforms.push_back(un);
					}

					parse = eol + 1;
				}
			}
		}

		uint16_t count = (uint16_t)uniforms.size();
		bx::write(_writer, count);

		for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
		{
			const Uniform& un = *it;
			uint8_t nameSize = (uint8_t)un.name.size();
			bx::write(_writer, nameSize);
			bx::write(_writer, un.name.c_str(), nameSize);
			uint8_t uniformType = uint8_t(un.type);
			bx::write(_writer, uniformType);
			bx::write(_writer, un.num);
			bx::write(_writer, un.regIndex);
			bx::write(_writer, un.regCount);

			BX_TRACE("%s, %s, %d, %d, %d"
				, un.name.c_str()
				, getUniformTypeName(un.type)
				, un.num
				, un.regIndex
				, un.regCount
				);
		}

		uint32_t shaderSize = (uint32_t)bx::strLen(optimizedShader);
		bx::write(_writer, shaderSize);
		bx::write(_writer, optimizedShader, shaderSize);
		uint8_t nul = 0;
		bx::write(_writer, nul);

		if (_options.disasm )
		{
			std::string disasmfp = _options.outputFilePath + ".disasm";
			writeFile(disasmfp.c_str(), optimizedShader, shaderSize);
		}

		glslopt_shader_delete(shader);
		glslopt_cleanup(ctx);

		return true;
	}
Exemple #28
0
void dEngine_ReadConfig(void)
{
	filehandle_t* config;
	int currentSceneId=0;
	
    
    
	config = FS_OpenFile(CONFIG_PATH, "rt");
	FS_UploadToRAM(config);
	
	if (!config)
	{
		Log_Printf("Configuration file: data/config.cfg not found");
		exit(0);
	}
	
	//renderer.resolution = 1;

	LE_pushLexer();
	LE_init(config);
	
	while (LE_hasMoreData()) 
	{
		LE_readToken();

		if (!strcmp("scenes", LE_getCurrentToken()))
		{
			LE_readToken(); // {
			LE_readToken(); // numScenes
			while (LE_hasMoreData() && strcmp("}", LE_getCurrentToken()))
			{
				if (!strcmp("numScenes", LE_getCurrentToken()))
				{
					engine.numScenes = LE_readReal();
				}
				else 
				if (!strcmp("scene", LE_getCurrentToken()))
				{
					currentSceneId = LE_readReal();
					
					LE_readToken(); //The name of the scene, here only to help developer to keep track of config.cfg
					strReplace(LE_getCurrentToken(), '_', ' ');
					strcpy(engine.scenes[currentSceneId].name, LE_getCurrentToken());
					
					LE_readToken();
					strcpy(engine.scenes[currentSceneId].path, LE_getCurrentToken());
					
					Log_Printf("Read scene %d, name %s, path %s\n",currentSceneId,engine.scenes[currentSceneId].name,engine.scenes[currentSceneId].path);
					
					
				}
				
				LE_readToken();
				
			}
		}
		else if (!strcmp("fx", LE_getCurrentToken()))
		{
			LE_readToken(); //{
			while (LE_hasMoreData() && strcmp("}", LE_getCurrentToken()))
			{
				LE_readToken();
				
				if (!strcmp("impactTextureName", LE_getCurrentToken()))
				{
					LE_readToken();
	//			explosionTexture.path = calloc(strlen(LE_getCurrentToken())+1, sizeof(char));
					strcpy(explosionTexture.path, LE_getCurrentToken());
				}
				else 
				if (!strcmp("smokeTextureName", LE_getCurrentToken()))
				{
					LE_readToken();
	//				smokeTexture.path = calloc(strlen(LE_getCurrentToken())+1, sizeof(char));
					strcpy(smokeTexture.path, LE_getCurrentToken());
				}
				else 
				if (!strcmp("ghostTextureName", LE_getCurrentToken()))
				{
					LE_readToken();
	//				ghostTexture.path = calloc(strlen(LE_getCurrentToken())+1, sizeof(char));
					strcpy(ghostTexture.path, LE_getCurrentToken());
				}
			}
		}
		/*
		else if (!strcmp("video", LE_getCurrentToken()))
		{
			
			LE_readToken(); // {
			LE_readToken();
			while (strcmp("}", LE_getCurrentToken()))
			{
				if (!strcmp("record", LE_getCurrentToken()))
				{
					engine.recordVideo = LE_readReal();
				}
				LE_readToken();
			}
		}
		*/
		else if (!strcmp("players", LE_getCurrentToken()))
		{
			LE_readToken();	//{
			LE_readToken();
			while (LE_hasMoreData() && strcmp("}", LE_getCurrentToken()))
			{
				if (!strcmp("model1", LE_getCurrentToken()))
				{
					LE_readToken();
					strcpy(players[1].modelPath, LE_getCurrentToken());
				}
				else 
				if (!strcmp("model0", LE_getCurrentToken()))
				{
					LE_readToken();
					strcpy(players[0].modelPath, LE_getCurrentToken());
				}
				else 
					if (!strcmp("bulletTextureName", LE_getCurrentToken()))
				{
					LE_readToken();
//					bulletConfig.bulletTexture.path = calloc(strlen(LE_getCurrentToken())+1, sizeof(char));
					strcpy(bulletConfig.bulletTexture.path, LE_getCurrentToken());
				}
				else 
				if (!strcmp("ttl", LE_getCurrentToken()))
				{
					bulletConfig.ttl = LE_readReal();
				}
				else 
				if (!strcmp("heightRatio", LE_getCurrentToken()))
				{
					bulletConfig.heightRatio = LE_readReal();
				}
				else 
				if (!strcmp("widthRatio", LE_getCurrentToken()))
				{
					bulletConfig.widthRatio = LE_readReal();
				}
				else 
				if (!strcmp("screenSpaceXDeltaRatio", LE_getCurrentToken()))
				{
					bulletConfig.screenSpaceXDeltaRatio = LE_readReal();
				}
				else 
				if (!strcmp("screenSpaceYDeltaRatio", LE_getCurrentToken()))
				{
					bulletConfig.screenSpaceYDeltaRatio = LE_readReal();
				}
				else 
				if (!strcmp("flashHeightRatio", LE_getCurrentToken()))
				{
					bulletConfig.flashHeightRatio = LE_readReal();
				}
				else 
				if (!strcmp("flashWidthRatio", LE_getCurrentToken()))
				{
					bulletConfig.flashWidthRatio = LE_readReal();
				}
				else 
				if (!strcmp("flashScreenSpaceXDeltaRatio", LE_getCurrentToken()))
				{
					bulletConfig.flashScreenSpaceXDeltaRatio = LE_readReal();
				}
				else 
				if (!strcmp("flashScreenSpaceYDeltaRatio", LE_getCurrentToken()))
				{
					bulletConfig.flashScreenSpaceYDeltaRatio = LE_readReal();
				}
				
				LE_readToken();
			}
			
		}
		
	}
	
	
	LE_popLexer();
	FS_CloseFile(config);
	
	
}
Exemple #29
0
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nShowCmd ) {
	HINSTANCE hVM;
	int result;
	char line[LINEMAXLEN];
	char jarfile[LINEMAXLEN];
	char classpath[LINEMAXLEN];
	char classname[LINEMAXLEN];
	char errorStr[LINEMAXLEN];
	char downloadStr[LINEMAXLEN];
	char cmd[2*LINEMAXLEN];
	char versionmin[30];
	int versmin = 0;
	int version;
	char *p;
	char *pExt;
	int error = 0;
	char *arg = NULL;

	*jarfile = '\0';
	*classpath = '\0';
	*classname = '\0';
	*versionmin = '\0';

	hInst = hInstance;

	// Possible situations:
	// 1) Jarx is opened because a .jar is double clicked:
	//		Read manifest and execute
	// 2) Jarx is opened because a .jarx is double clicked:
	//		Read jarx and execute
	// 2) Jarx is opened because some other file is double clicked
	//		Try to read a default.jarx in the app map
	// Else: show Jarx dialog box

	// Remove dblquotes from cmdline
	getCmdParam( lpCmdLine, line, sizeof( line ) - 1 );
	GetLongPathName( line, cmd, sizeof( cmd ) - 1 );

	// Find extension
	pExt = strrchr( cmd, '.' );
	if ( pExt != NULL && stricmp( pExt, ".jarx" ) == 0 ) {
		// it's .jarx - read and parse .jarx file
		readConfig( cmd, jarfile, classpath, classname, versionmin );
	} else if ( pExt != NULL && stricmp( pExt, ".jar" ) == 0 ) {
		// it's .jar
		// Only use filename (without path)
		// p = strrchr( cmd, '\\' );
		//if ( p != NULL )
		//	strcpy( classpath, p+1 );
		//else
		strcpy( jarfile, cmd );
	} else {
		// It's not a .jar or .jarx - try to get the default.jarx from the application map
		getCmdParam( GetCommandLine(), cmd, sizeof(cmd) );
		p = strrchr( cmd, '\\' );
		if ( p != NULL ) {
			*p = '\0';
			_chdir( cmd );
		}
		readConfig( DEFAULTJARX, jarfile, classpath, classname, versionmin );
		getCmdParam( lpCmdLine, cmd, sizeof(cmd) );
		if ( strlen( cmd ) > 0 )
			arg = cmd;
	}

	// Still no jarfile found? Show JARX dialog
	if ( *jarfile == '\0' ) {
		DialogBox( hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, aboutCallback );
		return 0;
	}

	// No classpath? -> use jarfile as classpath
	if ( *classpath == '\0' )
		strcpy( classpath, jarfile );

	// Versionmin set?
	if ( *versionmin != '\0' )
		versmin = parseVersion( versionmin );
	else
		versmin = 0;

	// try to load a JVM
	hVM = getJVM( &version );

	if ( hVM == NULL ) {
		error = IDS_NOTINSTALLED;
	} else {
		// execute class in JVM
		result = execJVM( hVM, hInstance, jarfile, classpath, classname, arg, version, versmin );
		switch( result ) {
			case JVM_PROBLEM:
				error = IDS_CANTCREATEJVM;
				break;
			case JVM_VERSIONTOOSMALL:
				error = IDS_JAVATOOOLD;
				break;
			case JVM_CLASSERR:
				// Probably MS JVM
				// Just execute jview
				if ( *classname != '\0' ) {
					strReplace( classname, '/', '.' );
					sprintf( cmd, "jview /cp \"%s\" %s", classpath, classname );
					result = execute( cmd );
					if ( !result )
						error = IDS_NOJVIEW;
					break;

				} else
					error = IDS_NOJVIEW;
		}
	}

	// Error occured
	if ( error != 0 ) {
		LoadString( hInst, error, errorStr, sizeof( errorStr ) - 1 );
		LoadString( hInst, IDS_DOWNLOAD, downloadStr, sizeof( downloadStr ) - 1 );
		sprintf( line, downloadStr, errorStr );
		result = MessageBox( NULL, line, "JARX", MB_OKCANCEL | MB_ICONEXCLAMATION );
		if ( result == IDOK )
			ShellExecute(NULL, "open", JAVADOWNLOAD, NULL, NULL, SW_SHOWNORMAL);
		return 1;
	}
	return 0;
}
Exemple #30
0
//
// getWord()
//   Return the word that was read in the last successful call to 
//   loadWord().  If loadWord failed, then this will just be the 
//   last requested word that succeeded, or the empty string if no
//   calls to loadWord() were ever successful.
//
const char* WordsFile::getWord() const throw()
{
    strReplace(d_word, ASCII_COLON, ASCII_SPACE);
    return d_word;
}