Error WasmObjectFile::parseUserSection(wasm::WasmSection &Sec, const uint8_t *Ptr, size_t Length) { Sec.Name = readString(Ptr); return Error::success(); }
std::string BinaryInput::readString32() { int len = readUInt32(); return readString(len); }
int waitForSearchResult(int sock){ // Get result of search from server int sizeOfResult; if(readInt(sock, &sizeOfResult) < 0){ puts("Failed to receive size of result"); return -1; } // Get Result and Display char result[sizeOfResult]; if(readString(sock, sizeOfResult, &result[0]) < 0){ puts("Failed to receive result array."); return -1; } printf("Result is:\n %s\n",result); // Select which file you want from the result char c; // Ask user if any file is to be retrieved printf("Do you want to retrieve a file (Y/N)? "); char input[2]; fgets(input, sizeof(input), stdin); if(input[0] == 'N' || input[0] == 'n'){ // Exit if(sendInt(sock, -1) < 0){ puts("Failed to send retrieval status"); return -1; } //flushing input stream while((c = getchar()) != '\n' && c != EOF); return 1; }else if(input[0] == 'Y' || input[0] == 'y'){ // Continue to retrieval if(sendInt(sock, 1) < 0){ puts("Failed to send retrieval status"); return -1; } }else{ // Invalid input exit // Exit if(sendInt(sock, -1) < 0){ puts("Failed to send retrieval status"); return -1; } //flushing input stream while((c = getchar()) != '\n' && c != EOF); return 1; } //flushing input stream while((c = getchar()) != '\n' && c != EOF); char answer[100]; printf("Which File do you want to retrieve: "); fgets(answer, sizeof(answer), stdin); int index; for(index = 0; index < 100; index++){ if(answer[index] == '\n'){ answer[index] = '\0'; break; } } // Send the file to retrieve if(sendString(sock, 100, &answer[0]) < 0){ puts("Sending Retrieve request failed."); return -1; } // Wait for response if the file was found int fileFound; if(readInt(sock, &fileFound) < 0){ puts("Receiving file found status from server failed"); return -1; } if(fileFound < 0){ puts("File requested was not found | Please check file name"); return 1; } // Receive the file size int fileSize = 0; // Get the file size if(readInt(sock, &fileSize) < 0){ puts("Receiving file size from server failed."); return -1; } printf("File Size = %d\n",fileSize); // Initialize file FILE *fp; fp = fopen(answer, "w+"); if(fp == NULL){ printf("%s : Error opening file",answer); return -1; } // Get File int bytesRead = 0; char buffer[1024]; while(bytesRead < fileSize){ // Read the first 1 KB if(readString(sock, 1024, &buffer[0]) < 0){ puts("Failed receiving file contents."); return -1; }else{ //Write to file fputs(buffer, fp); } // Add bytes read from length of buffer bytesRead = bytesRead + strlen(buffer); //printf("Length of buffer read for file = %d\n",bytesRead); } if(sendAck(sock) < 0){ return -1; } puts("Got the file from server\n"); // Close the file fclose(fp); return 1; }
void readMesh(IOReadBase* pRead, iModelData* pModelData) { bool skeletallyAnimated; pRead->Read(&skeletallyAnimated,sizeof(bool)); // Find all substreams if (!pRead->IsEof()) { CSubMesh sharedSubMesh; unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); while(!pRead->IsEof() && (streamID == M_GEOMETRY || streamID == M_SUBMESH || streamID == M_MESH_SKELETON_LINK || streamID == M_MESH_BONE_ASSIGNMENT || streamID == M_MESH_LOD || streamID == M_MESH_BOUNDS || streamID == M_SUBMESH_NAME_TABLE || streamID == M_EDGE_LISTS || streamID == M_POSES || streamID == M_ANIMATIONS || streamID == M_TABLE_EXTREMES)) { switch(streamID) { case M_GEOMETRY: { //MessageBoxW(NULL, L"M_GEOMETRY", L"readMesh",0); readGeometry(pRead, sharedSubMesh); } break; case M_SUBMESH: readSubMesh(pRead, pModelData, sharedSubMesh); break; case M_MESH_SKELETON_LINK: { std::string skelName = readString(pRead); // if(listener) // listener->processSkeletonName(pMesh, &skelName); // // pMesh->setSkeletonName(skelName); //readSkeletonLink(stream, pMesh, listener); } break; case M_MESH_BONE_ASSIGNMENT: //readMeshBoneAssignment(stream, pMesh); { VertexBoneAssignment assign; // unsigned int vertexIndex; pRead->Read(&(assign.vertexIndex),sizeof(unsigned int)); // unsigned short boneIndex; pRead->Read(&(assign.boneIndex),sizeof(unsigned short)); // float weight; pRead->Read(&(assign.weight),sizeof(float)); //sub->addBoneAssignment(assign); } break; case M_MESH_LOD: MessageBoxW(NULL,L"M_MESH_LOD",0,0); //readMeshLodInfo(stream, pMesh); break; case M_MESH_BOUNDS: //readBoundsInfo(stream, pMesh); { Vec3D min, max; // float minx, miny, minz pRead->Read(&min,sizeof(Vec3D)); // float maxx, maxy, maxz pRead->Read(&max,sizeof(Vec3D)); //AxisAlignedBox box(min, max); //pMesh->_setBounds(box, true); // float radius float radius; pRead->Read(&radius,sizeof(float)); //pMesh->_setBoundingSphereRadius(radius); } break; case M_SUBMESH_NAME_TABLE: MessageBoxW(NULL,L"M_SUBMESH_NAME_TABLE",0,0); //readSubMeshNameTable(stream, pMesh); break; case M_EDGE_LISTS: MessageBoxW(NULL,L"M_EDGE_LISTS",0,0); //readEdgeList(stream, pMesh); break; case M_POSES: MessageBoxW(NULL,L"M_POSES",0,0); //readPoses(stream, pMesh); break; case M_ANIMATIONS: MessageBoxW(NULL,L"M_ANIMATIONS",0,0); //readAnimations(stream, pMesh); break; case M_TABLE_EXTREMES: MessageBoxW(NULL,L"M_TABLE_EXTREMES",0,0); //readExtremes(stream, pMesh); break; } if (!pRead->IsEof()) { pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); } } if (!pRead->IsEof()) { // Backpedal back to start of non-submesh stream pRead->Move(-STREAM_OVERHEAD_SIZE); } } }
int UJSON_parse(PT_uJson pJson) { int c; T_UJSON_State state = UJSON_ST_NONE; if (!pJson || !pJson->getChar || !pJson->pPair || !pJson->pValue) return -1; while (1) { // read next character c = getChar(pJson); if (c < 0) break; // skip spaces if (isspace(c)) continue; switch (c) { // start of object case '{': state = UJSON_ST_NONE; pJson->objectDepth++; if (pJson->startObject) pJson->startObject(pJson); break; // end of object case '}': pJson->objectDepth--; if (pJson->endObject) pJson->endObject(pJson); break; // start of array case '[': state = UJSON_ST_ARRAY; if (pJson->startArray) pJson->startArray(pJson); break; // end of array case ']': if (pJson->endArray) pJson->endArray(pJson); state = UJSON_ST_NONE; break; // start of a pair or value case '"': if (state == UJSON_ST_NONE) { // start of pair c = readString(pJson, pJson->pPair, pJson->pairSize); if (pJson->startPair) pJson->startPair(pJson, pJson->pPair); } else if (state == UJSON_ST_VALUE || state == UJSON_ST_ARRAY) { // start of value c = readString(pJson, pJson->pValue, pJson->valueSize); if (pJson->value) pJson->value(pJson, pJson->pPair, pJson->pValue); // if we are in an array there may be more values coming if (state != UJSON_ST_ARRAY) state = UJSON_ST_NONE; } break; // value coming case ':': state = UJSON_ST_VALUE; break; // next value inside an array coming case ',': if (state != UJSON_ST_ARRAY) state = UJSON_ST_NONE; break; default: if (state == UJSON_ST_VALUE || state == UJSON_ST_ARRAY) { c = readValue(pJson, pJson->pValue, pJson->valueSize, c); if (pJson->value) pJson->value(pJson, pJson->pPair, pJson->pValue); } break; } if (c < 0) break; } return 0; }
long long IniParser::readInt64(const string §Str, const string &keyStr) { string str = readString(sectStr, keyStr); return atoll(str.c_str()); }
int readText(const char* context, const char* key, string* pvalue=nullptr, time_t* pexpiration=nullptr, int version=0) { return readString(context, key, pvalue, pexpiration, version); }
OBJ js_read(OBJ inStream){ OBJ retVal; prompt_off(); char ch = skipWhiteSpace(inStream); if( ch == -1){ retVal = js_eof; unreadChar(inStream, ch); } else if(ch == '('){ retVal = readList(inStream); } else if(ch =='\''){ OBJ expr = js_read(inStream); // (quote (expr* (nil))) -> expr must be a cons return newCons(symbolTableGetOrAdd("quote"), newCons(expr, js_nil)); } else if(ch == '"'){ retVal = readString(inStream); } else if(isDigit(ch)){ retVal = readNumber(inStream, ch, 0); }else if(ch == '-'){ /* * TO-DO refactor: implement proper read ahead solution */ // simple read ahead to catch negative numbers char nextCh = nextChar(inStream); if(isDigit(nextCh)){ retVal = readNumber(inStream, nextCh, 1); }else{ unreadChar(inStream, nextCh); retVal = readSymbol(inStream, ch); } } #ifdef DEBUG else if(ch == '%'){ ch = nextChar(inStream); OBJ debugOption; if(ch == '\n' ){ unreadChar(inStream, ch); debugOption = newSymbol(""); }else{ debugOption = readSymbol(inStream, ch); } switchDebugOptions( debugOption ); retVal = js_void; } #endif else { retVal = readSymbol(inStream, ch); } if(thisIsTheEnd(inStream)){ prompt_on(); }; return retVal; }
void OgreMeshReader::readSubMesh(SubMeshStore &subMeshInfo, VertexElementStore &sharedVertexElements, bool skelAnim ) { OSG_OGRE_LOG(("OgreMeshReader::readSubMesh\n")); subMeshInfo.push_back((SubMeshInfo())); SubMeshInfo &smInfo = subMeshInfo.back(); smInfo.matName = readString(_is); smInfo.sharedVertex = readBool (_is); UInt32 idxCount = readUInt32(_is); bool idx32Bit = readBool (_is); OSG_OGRE_LOG(("OgreMeshReader::readSubMesh: matName '%s' sharedVert '%d' " "idxCount '%d' idx32Bit '%d'\n", smInfo.matName.c_str(), smInfo.sharedVertex, idxCount, idx32Bit)); smInfo.skelAnim = skelAnim; smInfo.meshOp = SMO_TRIANGLE_LIST; if(idx32Bit == true) { GeoUInt32PropertyUnrecPtr pi = GeoUInt32Property::create(); pi->resize(idxCount); _is.read(reinterpret_cast<Char8 *>(&pi->editField().front()), idxCount * sizeof(UInt32)); smInfo.propIdx = pi; } else { GeoUInt16PropertyUnrecPtr pi = GeoUInt16Property::create(); pi->resize(idxCount); _is.read(reinterpret_cast<Char8 *>(&pi->editField().front()), idxCount * sizeof(UInt16)); smInfo.propIdx = pi; } Int16 boneIdxVE = -1; Int16 boneWeightVE = -1; bool stop = false; while(_is) { readChunkHeader(_is); switch(_header.chunkId) { case CHUNK_GEOMETRY: readGeometry(smInfo.vertexElements); break; case CHUNK_SUBMESH_OPERATION: readSubMeshOperation(smInfo); break; case CHUNK_SUBMESH_BONE_ASSIGNMENT: readSubMeshBoneAssignment(smInfo, boneIdxVE, boneWeightVE); break; case CHUNK_SUBMESH_TEXTURE_ALIAS: readSubMeshTextureAlias(); break; default: OSG_OGRE_LOG(("OgreMeshReader::readSubMesh: Unknown chunkId '0x%x'\n", _header.chunkId)); stop = true; break; }; if(stop == true) { skip(_is, -_chunkHeaderSize); break; } } if(boneIdxVE >= 0 || boneWeightVE >= 0) { verifyBoneAssignment(smInfo.vertexElements, boneIdxVE, boneWeightVE); } }
std::string NewickTreeReader::readName(std::istream &in) const { return readString(in); }
double NewickTreeReader::readNumber(std::istream &in) const { return atof(readString(in).c_str()); }
void getText(T& val) const { readString(text_, val);}
int readMaterial() { printInt(8); printInt(2); //Placeholder for length printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); readNothing("*MATERIAL"); openBracket(); int matRefNo = readInt("*MATERIAL_REF_NO"); char* matName = readString("*MATERIAL_NAME"); char* matClass = readString("*MATERIAL_CLASS"); char* matAmbient = readRGB("*MATERIAL_AMBIENT"); char* matDiffuse = readRGB("*MATERIAL_DIFFUSE"); char* matSpecular = readRGB("*MATERIAL_SPECULAR"); float matShine = readFloat("*MATERIAL_SHINE"); float matShineStrength = readFloat("*MATERIAL_SHINESTRENGTH"); float matTransparency = readFloat("*MATERIAL_TRANSPARENCY"); /*float matTransparency; bracketize(); char* buffer = (char*) malloc(sizeof(char)* 24); int offset = ftell(input);*/ float matWireSize = readFloat("*MATERIAL_WIRESIZE"); char* matShading = readString("*MATERIAL_SHADING"); float matXPFallof = readFloat("*MATERIAL_XP_FALLOF"); float matSelfIllum = readFloat("*MATERIAL_SELFILLUM"); char* matFallof = readString("*MATERIAL_FALLOF"); char* matXPType = readString("*MATERIAL_XP_TYPE"); printInt(matRefNo); printString(matName); printString(matClass); printBytes(matAmbient, 4); printBytes(matDiffuse, 4); printBytes(matSpecular, 4); printFloat(matShine); printFloat(matShineStrength); printFloat(matTransparency); printFloat(matWireSize); if(!strncmp(matShading, "Blinn", 5)) printInt(12); else printInt(0); printFloat(matXPFallof); printFloat(matSelfIllum); if(!strncmp(matFallof, "In", 2)) printInt(1); else printInt(0); if(!strncmp(matXPType, "Filter", 6)) printInt(1); else printInt(0); char* nextType = (char*)malloc(sizeof(char)*32); int numMaterials = 0; int numTextures = 0; int tParsed = 0; int mParsed = 0; while(1) { int currentOffset = ftell(input); fscanf(input, "%s\n", nextType); if(!strncmp(nextType, "*TEXTURE_LIST", 14) && tParsed == 0) { //Placeholder for number of textures int numTexturesOffset = ftell(output); printBytes("\xDE\xAD\xBE\xEF", 4); numTextures += readTextureList(); int afterTextureList = ftell(output); fseek(output, numTexturesOffset, 0); printInt(numTextures); fseek(output, afterTextureList, 0); mParsed = 1; } else if(tParsed == 0) { tParsed = 1; printInt(0); } if(!strncmp(nextType, "*MATERIAL_LIST", 14) && mParsed == 0) { //Placeholder for number of textures int numMaterialsOffset = ftell(output); printBytes("\xDE\xAD\xBE\xEF", 4); numMaterials += readMaterialList(); int afterMaterialList = ftell(output); fseek(output, numMaterialsOffset, 0); printInt(numMaterials); fseek(output, afterMaterialList, 0); mParsed = 1; } else if (mParsed == 0) { mParsed = 1; printInt(0); } if(!strncmp(nextType, "}", 1)) { fseek(input, currentOffset, 0); break; } } closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(size); fseek(output, endOffset, 0); return 0; }
int readTexture() { printInt(15); printInt(4); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); readNothing("*TEXTURE"); openBracket(); char* mapName = readString("*MAP_NAME"); char* mapClass = readString("*MAP_CLASS"); char* mapBitmap = readString("*BITMAP"); float mapAmount = readFloat("*MAP_AMOUNT"); char* mapStyle = (char*)malloc(sizeof(char)*32); bracketize(); fscanf(input, "%s\n", mapStyle); char* mapType = readString("*MAP_TYPE"); float mapUO = readFloat("*UVW_U_OFFSET"); float mapVO = readFloat("*UVW_V_OFFSET"); float mapUT = readFloat("*UVW_U_TILING"); float mapVT = readFloat("*UVW_V_TILING"); float mapAngle = readFloat("*UVW_ANGLE"); float mapBlur = readFloat("*UVW_BLUR"); float mapBlurOffset = readFloat("*UVW_BLUR_OFFSET"); float mapNoiseAmount = readFloat("*UVW_NOISE_AMT"); float mapNoiseSize = readFloat("*UVW_NOISE_SIZE"); int mapNoiseLevel = readInt("*UVW_NOISE_LEVEL"); float mapNoisePhase = readFloat("*UVW_NOISE_PHASE"); char* mapBitmapFilter = readString("*BITMAP_FILTER"); int mapBitmapMapChannel = readInt("*BITMAP_MAP_CHANNEL"); printString(mapName); printString(mapClass); printString(mapBitmap); printFloat(mapAmount); if (!strncmp(mapStyle, "*MAP_DIFFUSE", 12)) printInt(1); else if (!strncmp(mapStyle, "*MAP_SELFILLUM", 14)) printInt(5); else if (!strncmp(mapStyle, "*MAP_OPACITY", 12)) printInt(6); else printInt(1); if (!strncmp(mapType, "Screen", 6)) printInt(4); else printInt(0); printFloat(mapUO); printFloat(mapVO); printFloat(mapUT); printFloat(mapVT); printFloat(mapAngle); printFloat(mapBlur); printFloat(mapBlurOffset); printFloat(mapNoiseAmount); printFloat(mapNoiseSize); printInt(mapNoiseLevel); printFloat(mapNoisePhase); if (!strncmp(mapBitmapFilter, "SAT", 3)) { printInt(0); printInt(0); printInt(1); } else { printInt(0); printInt(0); printInt(0); } printInt(mapBitmapMapChannel); printInt(0); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(size); fseek(output, endOffset, 0); return 0; }
std::string RemotePluginClient::getMaker() { writeOpcode(m_controlRequestFd, RemotePluginGetMaker); return readString(m_controlResponseFd); }
bool WalkingEngineKick::load(const char* filePath, char* buf) { initialized = false; int lineNumber = 0; bool error = false; for(int i = 0; i < numOfTracks; ++i) { tracks[i].clear(); addPhase(Track(i), 0); } while(*buf) { ++lineNumber; try { while(*buf == ' ' || *buf == '\t') ++buf; if(*buf != '#' && *buf != ';' && *buf != '\r' && *buf != '\n') { String str = readString(buf); if(str == "setType") { String str = readString(buf); if(str == "standing") standKick = true; else if(str == "walking") standKick = false; else throw ParseException("expected 'standing' or 'walking'"); } else if(str == "setPreStepSize") { preStepSizeXValue = readValue(buf); preStepSizeYValue = readValue(buf); preStepSizeZValue = readValue(buf); readValue(buf); readValue(buf); preStepSizeRValue = readValue(buf); } else if(str == "setStepSize") { stepSizeXValue = readValue(buf); stepSizeYValue = readValue(buf); stepSizeZValue = readValue(buf); readValue(buf); readValue(buf); stepSizeRValue = readValue(buf); } else if(str == "setDuration") { durationValue = readValue(buf); } else if(str == "setRefX") { refXValue = readValue(buf); } else if(str == "proceed") { Value* value = readValue(buf); for(int i = 0; i < numOfTracks; ++i) { Phase& lastPhase = tracks[i].back(); if(!lastPhase.lengthValue) lastPhase.lengthValue = value; else lastPhase.lengthValue = new PlusExpression(*lastPhase.lengthValue, *value, *this); } } else if(str == "setLeg") { addPhase(footTranslationX, readValue(buf)); addPhase(footTranslationY, readValue(buf)); addPhase(footTranslationZ, readValue(buf)); addPhase(footRotationX, readValue(buf)); addPhase(footRotationY, readValue(buf)); addPhase(footRotationZ, readValue(buf)); } else if(str == "setArms") { addPhase(lShoulderPitch, readValue(buf)); addPhase(lShoulderRoll, readValue(buf)); addPhase(lElbowYaw, readValue(buf)); addPhase(lElbowRoll, readValue(buf)); addPhase(rShoulderPitch, readValue(buf)); addPhase(rShoulderRoll, readValue(buf)); addPhase(rElbowYaw, readValue(buf)); addPhase(rElbowRoll, readValue(buf)); } else if(str == "setHead") { addPhase(headYaw, readValue(buf)); addPhase(headPitch, readValue(buf)); } else throw ParseException("expected keyword"); while(*buf == ' ' || *buf == '\t') ++buf; } if(*buf == '#' || *buf == ';') { ++buf; while(*buf && *buf != '\r' && *buf != '\n') ++buf; } if(*buf && *buf != '\r' && *buf != '\n') throw ParseException("expected end of line"); } catch(ParseException e) { // OUTPUT(idText, text, filePath << ":" << lineNumber << ": " << e.message); (void)e; error = true; } while(*buf && *buf != '\r' && *buf != '\n') ++buf; if(*buf == '\r' && buf[1] == '\n') buf += 2; else if(*buf) ++buf; } if(error) { for(int i = 0; i < numOfTracks; ++i) tracks[i].clear(); // OUTPUT(idText, text, filePath << ": failed to load file"); return false; } for(int i = 0; i < numOfTracks; ++i) addPhase(Track(i), 0); return true; }
int IniParser::readInt32(const string §Str, const string &keyStr) { string str = readString(sectStr, keyStr); return atoi(str.c_str()); }
void setOrderStreet(Order *orders, int pos) { readString(orders[pos].address.street, O_STREET_LENGTH, O_MSG_STREET); }
double IniParser::readDouble(const string §Str, const string &keyStr) { string str = readString(sectStr, keyStr); return atof(str.c_str()); }
void setOrderCity(Order *orders, int pos) { readString(orders[pos].address.city, O_CITY_LENGTH, O_MSG_CITY); }
Token::Type CssTokenizer::readNextToken(){ if (in == NULL) { currentToken.type = Token::EOS; return Token::EOS; } currentToken.clear(); switch (lastRead) { case '@': currentToken.type = Token::ATKEYWORD; currentToken.add(lastRead); readChar(); if (!readIdent()) { currentToken.type = Token::OTHER; } break; case '#': currentToken.type = Token::HASH; currentToken.add(lastRead); readChar(); if (!readName()) { throw new ParseException(&lastRead, "name following '#'"); } break; case '-': currentToken.add(lastRead); readChar(); if (readNum(true)) { currentToken.type = Token::NUMBER; readNumSuffix(); } else if (readIdent()) { currentToken.type = Token::IDENTIFIER; } else currentToken.type = Token::OTHER; break; case '~': currentToken.add(lastRead); readChar(); if (lastRead == '=') { currentToken.add(lastRead); readChar(); currentToken.type = Token::INCLUDES; } else currentToken.type = Token::OTHER; break; case '|': currentToken.add(lastRead); readChar(); if (lastRead == '=') { currentToken.add(lastRead); readChar(); currentToken.type = Token::DASHMATCH; } else currentToken.type = Token::OTHER; break; case '/': currentToken.add(lastRead); readChar(); if (readComment()) currentToken.type = Token::COMMENT; else currentToken.type = Token::OTHER; break; case ';': currentToken.type = Token::DELIMITER; currentToken.add(lastRead); readChar(); break; case ':': currentToken.type = Token::COLON; currentToken.add(lastRead); readChar(); break; case '{': currentToken.type = Token::BRACKET_OPEN; currentToken.add(lastRead); readChar(); break; case '}': currentToken.type = Token::BRACKET_CLOSED; currentToken.add(lastRead); readChar(); break; case '(': currentToken.type = Token::PAREN_OPEN; currentToken.add(lastRead); readChar(); break; case ')': currentToken.type = Token::PAREN_CLOSED; currentToken.add(lastRead); readChar(); break; case '[': currentToken.type = Token::BRACE_OPEN; currentToken.add(lastRead); readChar(); break; case ']': currentToken.type = Token::BRACE_CLOSED; currentToken.add(lastRead); readChar(); break; case '.': currentToken.add(lastRead); readChar(); if (readNum(false)) { currentToken.type = Token::NUMBER; readNumSuffix(); } break; default: if (readString()) currentToken.type = Token::STRING; else if (readNum(true)) { currentToken.type = Token::NUMBER; readNumSuffix(); } else if (readIdent()) { currentToken.type = Token::IDENTIFIER; if (currentToken.str == "url" && readUrl()) currentToken.type = Token::URL; else if (currentToken.str == "u" && lastReadEq('+')) { currentToken.add(lastRead); readChar(); currentToken.type = Token::UNICODE_RANGE; readUnicodeRange(); } } else if (readWhitespace()) { currentToken.type = Token::WHITESPACE; while (readWhitespace()) {}; } else { currentToken.add(lastRead); readChar(); } break; } return currentToken.type; }
int openAndReadCompanyFile(char * path, company ** cmp, int index, graph * map) { FILE * file = fopen(path, "r"); char * num = NULL; int airplaneQty = 0; int counter = 0; cmp[index] = NULL; char * str = NULL; if (file == NULL) return parserError(NULL, cmp[index], FILE_ERROR, file); num = readString(file, '\n'); if (!isdigit(*num)) { free(num); return parserError(NULL, cmp[index], FILE_ERROR, file); } airplaneQty = atoi(num); cmp[index] = malloc(sizeof(company)); if (cmp[index] == NULL) return parserError(NULL, cmp[index], MALLOC_ERROR, file); if (initializeCompany(cmp[index], airplaneQty) != EXIT_SUCCESS) return parserError(NULL, cmp[index], MALLOC_ERROR, file); if (readBlankLine(file) != EXIT_SUCCESS) return parserError(NULL, cmp[index], FILE_ERROR, file); for (counter = 0; counter < airplaneQty; counter++) { medList * list = NULL; int read = 0; str = readString(file, '\n'); if (str == NULL) return parserError(NULL, cmp[index], FILE_ERROR, file); if (existsCity(str, map) == -1) return parserError(NULL, cmp[index], FILE_ERROR, file); if (addActualCity(cmp[index], str, counter) != EXIT_SUCCESS) return parserError(NULL, cmp[index], FILE_ERROR, file); list = createList(); while ((read = fgetc(file)) != '\n' && read != EOF) { if (read != '\r') { char * medName = NULL; char * amount = NULL; fseek(file, -1, SEEK_CUR); medName = readString(file, ' '); amount = readString(file, '\n'); if (medName == NULL || amount == NULL || !isdigit(*amount)) { if (amount != NULL) free(amount); if (medName != NULL) free(medName); if (list != NULL) freeMedList(list); return parserError(NULL, cmp[index], FILE_ERROR, file); } addMed(medName, atoi(amount), list); free(amount); } } addMedListToCompany(cmp[index], list, counter); } fclose(file); free(num); return EXIT_SUCCESS; }
void readSubMesh(IOReadBase* pRead, iModelData* pModelData, const CSubMesh& sharedSubMesh) { iLodMesh* pMesh = &pModelData->getMesh(); std::string strMaterialName = readString(pRead); int nSubID=pMesh->getSubCount(); pModelData->setRenderPass(nSubID,nSubID,strMaterialName); // if(listener) // listener->processMaterialName(pMesh, &materialName); // sm->setMaterialName(materialName); // bool useSharedVertices bool useSharedVertices; pRead->Read(&useSharedVertices,sizeof(bool)); CSubMesh& subMesh=pMesh->addSubMesh(); if (useSharedVertices) { subMesh.pos =sharedSubMesh.pos; subMesh.weight =sharedSubMesh.weight; subMesh.bone =sharedSubMesh.bone; subMesh.normal =sharedSubMesh.normal; subMesh.color =sharedSubMesh.color; subMesh.texcoord =sharedSubMesh.texcoord; subMesh.texcoord2 =sharedSubMesh.texcoord2; } // sm->indexData->indexStart = 0; unsigned int indexCount = 0; pRead->Read(&indexCount,sizeof(unsigned int)); //sm->indexData->indexCount = indexCount; // bool indexes32Bit bool idx32bit; pRead->Read(&idx32bit,sizeof(bool)); if (idx32bit) { MessageBoxW(0,L"Can't read idx32bit",L"Error",0); VertexIndex vertexIndex; for (size_t i=0;i<indexCount;++i) { unsigned int uVertexIndex; pRead->Read(&uVertexIndex,sizeof(unsigned int)); vertexIndex.p=uVertexIndex; vertexIndex.n=uVertexIndex; vertexIndex.c=uVertexIndex; vertexIndex.uv1=uVertexIndex; vertexIndex.b=uVertexIndex; vertexIndex.w=uVertexIndex; subMesh.m_setVertexIndex.push_back(vertexIndex); } } else // 16-bit { VertexIndex vertexIndex; for (size_t i=0;i<indexCount;++i) { unsigned short uVertexIndex; pRead->Read(&uVertexIndex,sizeof(unsigned short)); vertexIndex.p=uVertexIndex; vertexIndex.n=uVertexIndex; vertexIndex.c=uVertexIndex; vertexIndex.uv1=uVertexIndex; vertexIndex.b=uVertexIndex; vertexIndex.w=uVertexIndex; subMesh.m_setVertexIndex.push_back(vertexIndex); } } // M_GEOMETRY stream (Optional: present only if useSharedVertices = false) if (!useSharedVertices) { unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); if (streamID != M_GEOMETRY) { MessageBoxW(0,L"Missing geometry data in mesh file",L"readSubMesh",0); } readGeometry(pRead, subMesh); } // Find all bone assignments, submesh operation, and texture aliases (if present) if (!pRead->IsEof()) { unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); while(!pRead->IsEof() && (streamID == M_SUBMESH_BONE_ASSIGNMENT || streamID == M_SUBMESH_OPERATION || streamID == M_SUBMESH_TEXTURE_ALIAS)) { switch(streamID) { case M_SUBMESH_OPERATION: // readSubMeshOperation(stream, pMesh, sm); // unsigned short operationType unsigned short opType; pRead->Read(&opType,sizeof(unsigned short)); //sm->operationType = static_cast<RenderOperation::OperationType>(opType); break; case M_SUBMESH_BONE_ASSIGNMENT: { //readSubMeshBoneAssignment(stream, pMesh, sm); VertexBoneAssignment assign; // unsigned int vertexIndex; pRead->Read(&(assign.vertexIndex),sizeof(unsigned int)); // unsigned short boneIndex; pRead->Read(&(assign.boneIndex),sizeof(unsigned short)); // float weight; pRead->Read(&(assign.weight),sizeof(float)); break; unsigned long uBone = 0; unsigned long uWeight = 0; // get subMesh.getBone(assign.vertexIndex,uBone); subMesh.getWeight(assign.vertexIndex,uWeight); // add for (size_t i=0;i<4;++i) { if (((unsigned char*)&uWeight)[i]==0) { ((unsigned char*)&uWeight)[i] = assign.weight*255; ((unsigned char*)&uBone)[i] = assign.boneIndex; break; } } // set subMesh.setBone(assign.vertexIndex,uBone); subMesh.setWeight(assign.vertexIndex,uWeight); //sub->addBoneAssignment(assign); } break; case M_SUBMESH_TEXTURE_ALIAS: //readSubMeshTextureAlias(stream, pMesh, sm); std::string aliasName = readString(pRead); std::string textureName = readString(pRead); //sub->addTextureAlias(aliasName, textureName); break; } if (!pRead->IsEof()) { pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); } } if (!pRead->IsEof()) { // Backpedal back to start of non-submesh stream pRead->Move(-STREAM_OVERHEAD_SIZE); } } }
int main(int argc, char** argv) { /*Check arguments to make sure you got a file*/ //There must be at least some arguments to get a file if(errno != 0){ perror("Unknown Error at start"); errno = 0; } const char* filename = NULL; const char* outfile = NULL; bool gui = false; float nodeCharge = 3; bool output = true; bool isFile = true; layout_params* params = (layout_params*) malloc(sizeof(layout_params)); params->ke = 500; params->kh = 0.0005; params->kl = -0.05; params->width = 1920; params->height = 1080; params->iterations = 10000; params->mass = 1; params->time = 1; params->coefficientOfRestitution = -0.9; params->mus = 0.2; params->muk = 0.04; params->kw = 3; params->kg = 0.06; params->wellMass = 1; params->edgeCharge = nodeCharge; params->forcemode = COULOMBS_LAW | HOOKES_LAW_SPRING | FRICTION | DRAG | BOUNCY_WALLS; params->cpuLoop = false; if (argc < 2) { usage(); return EXIT_FAILURE; } for (int i = 1; i < argc; i++) { if(errno != 0){ fprintf(stderr, "On Iter: %d ", i); perror("Unknown Error"); errno = 0; } if (strcmp(argv[i], "-f") == 0) { if (filename != NULL) { printf( "An input directory has already been provided (%s).\nCan only use one of -f and -d.\n", filename); exit(-1); } filename = readString(argc, argv, ++i); isFile = true; } else if (strcmp(argv[i], "-d") == 0) { if (filename != NULL) { printf( "An input file has already been provided (%s).\nCan only use one of -f and -d.\n", filename); exit(-1); } filename = readString(argc, argv, ++i); isFile = false; } else if (strcmp(argv[i], "-o") == 0) { outfile = readString(argc, argv, ++i); } else if (strcmp(argv[i], "-Ke") == 0) { params->ke = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-Kh") == 0) { params->kh = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-Kl") == 0) { params->kl = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-nodeCharge") == 0) { nodeCharge = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-edgeCharge") == 0) { params->edgeCharge = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-Kg") == 0) { params->kg = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-nm") == 0) { params->wellMass = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-mus") == 0) { params->mus = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-muk") == 0) { params->muk = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-i") == 0) { params->iterations = readInt(argc, argv, ++i); } else if (strcmp(argv[i], "-width") == 0) { params->width = readInt(argc, argv, ++i); } else if (strcmp(argv[i], "-height") == 0) { params->height = readInt(argc, argv, ++i); } else if (strcmp(argv[i], "-gui") == 0) { gui = true; } else if (strcmp(argv[i], "-cpuLoop") == 0) { params->cpuLoop = true; } else if (strcmp(argv[i], "-noOutput") == 0) { output = false; } else if (strcmp(argv[i], "-t") == 0) { params->time = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-m") == 0) { params->mass = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-cRest") == 0) { params->coefficientOfRestitution = readFloat(argc, argv, ++i); } else if (strcmp(argv[i], "-friction") == 0) { int fricForce = readInt(argc, argv, ++i); params->forcemode = params->forcemode & ~(FRICTION | DRAG); params->forcemode = params->forcemode | (fricForce << 2); } else if (strcmp(argv[i], "-spring") == 0) { int springForce = readInt(argc, argv, ++i); params->forcemode = params->forcemode & ~(HOOKES_LAW_SPRING | LOG_SPRING); params->forcemode = params->forcemode | (springForce); } else if (strcmp(argv[i], "-walls") == 0) { int wallForce = readInt(argc, argv, ++i); params->forcemode = params->forcemode & ~(BOUNCY_WALLS | CHARGED_WALLS | GRAVITY_WELL); params->forcemode = params->forcemode | (wallForce << 4); } else if (strcmp(argv[i], "-forces") == 0) { int primForce = readInt(argc, argv, ++i); params->forcemode = params->forcemode & ~(COULOMBS_LAW | DEGREE_BASED_CHARGE | CHARGED_EDGE_CENTERS | WRAP_AROUND_FORCES); params->forcemode = params->forcemode | (primForce << 7); } else { fprintf(stderr, "Unknown option %s\n", argv[i]); return EXIT_FAILURE; } } if (filename == NULL) { fprintf(stderr, "You must include a filename\n"); usage(); return EXIT_FAILURE; } graph** g; int graphCount = 0; if (isFile) { debug("Reading graph: %s\n", filename); g = (graph**) malloc(sizeof(graph*)); g[0] = readFile(filename); graphCount = 1; } else { g = readDir(filename, &graphCount); } if (g == NULL || graphCount < 1) { fprintf(stderr, "Creating a graph failed. Terminating\n"); usage(); return EXIT_FAILURE; } for (int i = 0; i < graphCount; i++) { graph_initRandom(g[i], 20, 10, params->width, params->height, nodeCharge); } if (gui && isFile) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowSize(params->width, params->height); glutCreateWindow("Force Directed Layout"); glutDisplayFunc(display); //glutReshapeFunc(reshape); glutIdleFunc(idle); setLight(); initCamera(params->width, params->height); glGraph = g; glParams = params; glutMainLoop(); } else if (gui) { printf("Cannot use gui mode with a directory.\n"); exit(-1); } /* The graph is now is a legal state. * It is not using the GUI. * It is possible to lay it out now */ struct timeval tstart, tend; gettimeofday(&tstart, NULL); graph_layout(g, graphCount, params); gettimeofday(&tend, NULL); long start = tstart.tv_sec * 1000000 + tstart.tv_usec; long end = tend.tv_sec * 1000000 + tend.tv_usec; long msElapsed = end - start; debug("Elapsed Time (us): %ld\n", msElapsed); if (outfile == NULL && isFile) { outfile = "after.svg"; } if (output && (outfile != NULL)) { for (int i = 0; i < graphCount; i++) { #define BUFF_SIZE 1024 char thisOutFile[BUFF_SIZE]; strncpy(thisOutFile,outfile,BUFF_SIZE); if(!isFile){ //Does it end on a / int len = strlen(thisOutFile); if(thisOutFile[len-1] != '/'){ if(len < BUFF_SIZE - 2){ //Keep enough space for the '\0' thisOutFile[len++] = '/'; thisOutFile[len] = '\0'; }else{ fprintf(stderr,"File name too long (%s [/] %s [/] %s)\n. Not creating svg.\n", outfile, (g[i])->dir, g[i]->filename); continue; } } //Now concatenate the dir name if(g[i]->dir != NULL){ int len2 = strlen(g[i]->dir); if(len + len2 +1 > BUFF_SIZE){ fprintf(stderr,"File name too long (%s [/] %s [/] %s)\n. Not creating svg.\n", outfile, (g[i])->dir, g[i]->filename); continue; } strcat(thisOutFile, g[i]->dir + (g[i]->dir[0]=='/'? 1: 0)); } //Now the file name int len2 = strlen(g[i]->filename); if(len + len2 + 1 > BUFF_SIZE){ fprintf(stderr,"File name too long (%s [/] %s [/] %s)\n. Not creating svg.\n", outfile, (g[i])->dir, g[i]->filename); continue; } strcat(thisOutFile,g[i]->filename); char* extension = strstr(thisOutFile, ".graphml"); if(extension ==NULL){ fprintf(stderr,"Something went wrong. Could not find .graphml in %s\nTerminating\n", thisOutFile); exit(EXIT_FAILURE); } strcpy(extension, ".svg"); //Now the filename is finally right! } graph_toSVG(g[i], thisOutFile, params->width, params->height, (params->forcemode & (BOUNCY_WALLS | CHARGED_WALLS)) != 0, msElapsed, params); } } //Free all the graphs and the structure that holds it free(g[0]->nodes); bitarray_free(g[0]->edges); for (int i = 0; i < graphCount; i++) { graph_free(g[i]); } free(g); free(params); return EXIT_SUCCESS; }
void RemotePluginServer::dispatchControlEvents() { RemotePluginOpcode opcode = RemotePluginNoOpcode; static float *parameterBuffer = 0; tryRead(m_controlRequestFd, &opcode, sizeof(RemotePluginOpcode)); switch (opcode) { case RemotePluginGetVersion: writeFloat(m_controlResponseFd, getVersion()); break; case RemotePluginGetName: writeString(m_controlResponseFd, getName()); break; case RemotePluginGetMaker: writeString(m_controlResponseFd, getMaker()); break; case RemotePluginTerminate: terminate(); break; case RemotePluginGetInputCount: m_numInputs = getInputCount(); writeInt(m_controlResponseFd, m_numInputs); break; case RemotePluginGetOutputCount: m_numOutputs = getOutputCount(); writeInt(m_controlResponseFd, m_numOutputs); break; case RemotePluginGetParameterCount: writeInt(m_controlResponseFd, getParameterCount()); break; case RemotePluginGetParameterName: writeString(m_controlResponseFd, getParameterName(readInt(m_controlRequestFd))); break; case RemotePluginGetParameter: writeFloat(m_controlResponseFd, getParameter(readInt(m_controlRequestFd))); break; case RemotePluginGetParameterDefault: writeFloat(m_controlResponseFd, getParameterDefault(readInt(m_controlRequestFd))); break; case RemotePluginGetParameters: { if (!parameterBuffer) { parameterBuffer = new float[getParameterCount()]; } int p0 = readInt(m_controlRequestFd); int pn = readInt(m_controlRequestFd); getParameters(p0, pn, parameterBuffer); tryWrite(m_controlResponseFd, parameterBuffer, (pn - p0 + 1) * sizeof(float)); break; } case RemotePluginHasMIDIInput: { bool m = hasMIDIInput(); tryWrite(m_controlResponseFd, &m, sizeof(bool)); break; } case RemotePluginGetProgramCount: writeInt(m_controlResponseFd, getProgramCount()); break; case RemotePluginGetProgramName: writeString(m_controlResponseFd, getProgramName(readInt(m_controlRequestFd))); break; case RemotePluginIsReady: { if (!m_shm) sizeShm(); bool b(isReady()); std::cerr << "isReady: returning " << b << std::endl; tryWrite(m_controlResponseFd, &b, sizeof(bool)); } case RemotePluginSetDebugLevel: { RemotePluginDebugLevel newLevel = m_debugLevel; tryRead(m_controlRequestFd, &newLevel, sizeof(RemotePluginDebugLevel)); setDebugLevel(newLevel); m_debugLevel = newLevel; break; } case RemotePluginWarn: { bool b = warn(readString(m_controlRequestFd)); tryWrite(m_controlResponseFd, &b, sizeof(bool)); break; } case RemotePluginShowGUI: { showGUI(readString(m_controlRequestFd)); break; } case RemotePluginHideGUI: { hideGUI(); break; } //Deryabin Andrew: vst chunks support case RemotePluginGetVSTChunk: { std::vector<char> chunk = getVSTChunk(); writeRaw(m_controlResponseFd, chunk); break; } case RemotePluginSetVSTChunk: { std::vector<char> chunk = readRaw(m_controlRequestFd); setVSTChunk(chunk); break; } //Deryabin Andrew: vst chunks support: end code case RemotePluginNoOpcode: break; case RemotePluginReset: reset(); break; default: std::cerr << "WARNING: RemotePluginServer::dispatchControlEvents: unexpected opcode " << opcode << std::endl; } }
bool initSludge (char * filename) { int a = 0; mouseCursorAnim = makeNullAnim (); FILE * fp = openAndVerify (filename, 'G', 'E', ERROR_BAD_HEADER, gameVersion); if (! fp) return false; if (fgetc (fp)) { numBIFNames = get2bytes (fp); allBIFNames = new char * [numBIFNames]; if (! checkNew (allBIFNames)) return false; for (int fn = 0; fn < numBIFNames; fn ++) { allBIFNames[fn] = readString (fp); } numUserFunc = get2bytes (fp); allUserFunc = new char * [numUserFunc]; if (! checkNew (allUserFunc)) return false; for (int fn = 0; fn < numUserFunc; fn ++) { allUserFunc[fn] = readString (fp); } if (gameVersion >= VERSION(1,3)) { numResourceNames = get2bytes (fp); allResourceNames = new char * [numResourceNames]; if (! checkNew (allResourceNames)) return false; for (int fn = 0; fn < numResourceNames; fn ++) { allResourceNames[fn] = readString (fp); } } } winWidth = get2bytes (fp); winHeight = get2bytes (fp); specialSettings = fgetc (fp); desiredfps = 1000/fgetc (fp); delete[] readString (fp); // Unused - was used for registration purposes. size_t bytes_read = fread (& fileTime, sizeof (FILETIME), 1, fp); if (bytes_read != sizeof (FILETIME) && ferror (fp)) { debugOut("Reading error in initSludge.\n"); } char * dataFol = (gameVersion >= VERSION(1,3)) ? readString(fp) : joinStrings ("", ""); gameSettings.numLanguages = (gameVersion >= VERSION(1,3)) ? (fgetc (fp)) : 0; makeLanguageTable (fp); if (gameVersion >= VERSION(1,6)) { fgetc(fp); // aaLoad fgetc (fp); getFloat (fp); getFloat (fp); } char * checker = readString (fp); if (strcmp (checker, "okSoFar")) return fatal (ERROR_BAD_HEADER, filename); delete checker; checker = NULL; unsigned char customIconLogo = fgetc (fp); if (customIconLogo & 1) { // There is an icon - read it! int n; long file_pointer = ftell (fp); png_structp png_ptr; png_infop info_ptr, end_info; int fileIsPNG = true; // Is this a PNG file? char tmp[10]; bytes_read = fread(tmp, 1, 8, fp); if (bytes_read != 8 && ferror (fp)) { debugOut("Reading error in initSludge.\n"); } if (png_sig_cmp((png_byte *) tmp, 0, 8)) { // No, it's old-school HSI fileIsPNG = false; fseek(fp, file_pointer, SEEK_SET); iconW = get2bytes (fp); iconH = get2bytes (fp); } else { // Read the PNG header png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { return false; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); return false; } end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); return false; } png_init_io(png_ptr, fp); // Tell libpng which file to read png_set_sig_bytes(png_ptr, 8); // 8 bytes already read png_read_info(png_ptr, info_ptr); png_uint_32 width, height; int bit_depth, color_type, interlace_type, compression_type, filter_method; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); iconW = width; iconH = height; if (bit_depth < 8) png_set_packing(png_ptr); png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); if (bit_depth == 16) png_set_strip_16(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); png_read_update_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); } gameIcon = new unsigned char [iconW*iconH*4]; if (! gameIcon) return fatal ("Can't reserve memory for game icon."); int32_t transCol = 63519; Uint8 *p = (Uint8 *) gameIcon; if (fileIsPNG) { unsigned char * row_pointers[iconH]; for (int i = 0; i<iconH; i++) row_pointers[i] = p + 4*i*iconW; png_read_image(png_ptr, (png_byte **) row_pointers); png_read_end(png_ptr, NULL); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); } else { for (int t2 = 0; t2 < iconH; t2 ++) { int t1 = 0; while (t1 < iconW) { unsigned short c = (unsigned short) get2bytes (fp); if (c & 32) { n = fgetc (fp) + 1; c -= 32; } else { n = 1; } while (n --) { *p++ = (Uint8) redValue(c); *p++ = (Uint8) greenValue(c); *p++ = (Uint8) blueValue(c); *p++ = (Uint8) (c == transCol) ? 0 : 255; t1++; } } } } } if (customIconLogo & 2) { // There is an logo - read it! int n; long file_pointer = ftell (fp); png_structp png_ptr; png_infop info_ptr, end_info; int fileIsPNG = true; // Is this a PNG file? char tmp[10]; bytes_read = fread(tmp, 1, 8, fp); if (bytes_read != 8 && ferror (fp)) { debugOut("Reading error in initSludge.\n"); } if (png_sig_cmp((png_byte *) tmp, 0, 8)) { // No, it's old-school HSI fileIsPNG = false; fseek(fp, file_pointer, SEEK_SET); logoW = get2bytes (fp); logoH = get2bytes (fp); } else { // Read the PNG header png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { return false; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); return false; } end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); return false; } png_init_io(png_ptr, fp); // Tell libpng which file to read png_set_sig_bytes(png_ptr, 8); // 8 bytes already read png_read_info(png_ptr, info_ptr); png_uint_32 width, height; int bit_depth, color_type, interlace_type, compression_type, filter_method; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); logoW = width; logoH = height; if (bit_depth < 8) png_set_packing(png_ptr); png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); if (bit_depth == 16) png_set_strip_16(png_ptr); #ifdef WIN32 // Windows wants a BGR bitmap if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) png_set_bgr(png_ptr); #endif png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); png_read_update_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); } if ((logoW != 310) || (logoH != 88)) return fatal ("Game logo have wrong dimensions. (Should be 310x88)"); gameLogo = new unsigned char [logoW*logoH*4]; if (! gameLogo) return fatal ("Can't reserve memory for game logo."); // int32_t transCol = 63519; Uint8 *p = (Uint8 *) gameLogo; if (fileIsPNG) { unsigned char * row_pointers[logoH]; for (int i = 0; i<logoH; i++) row_pointers[i] = p + 4*i*logoW; png_read_image(png_ptr, (png_byte **) row_pointers); png_read_end(png_ptr, NULL); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); } else { for (int t2 = 0; t2 < logoH; t2 ++) { int t1 = 0; while (t1 < logoW) { unsigned short c = (unsigned short) get2bytes (fp); if (c & 32) { n = fgetc (fp) + 1; c -= 32; } else { n = 1; } while (n --) { #ifdef WIN32 // Windows wants a BGR bitmap *p++ = (Uint8) blueValue(c); *p++ = (Uint8) greenValue(c); *p++ = (Uint8) redValue(c); #else *p++ = (Uint8) redValue(c); *p++ = (Uint8) greenValue(c); *p++ = (Uint8) blueValue(c); #endif *p++ = (Uint8) /*(c == transCol) ? 0 :*/ 255; t1++; } } } } } numGlobals = get2bytes (fp); globalVars = new variable[numGlobals]; if (! checkNew (globalVars)) return false; for (a = 0; a < numGlobals; a ++) initVarNew (globalVars[a]); // Get the original (untranslated) name of the game and convert it to Unicode. // We use this to find saved preferences and saved games. setFileIndices (fp, gameSettings.numLanguages, 0); char * gameNameOrig = getNumberedString(1); char * gameName = encodeFilename (gameNameOrig); delete gameNameOrig; changeToUserDir (); #ifdef _WIN32 mkdir (gameName); #else mkdir (gameName, 0000777); #endif if (chdir (gameName)) return fatal ("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName); delete [] gameName; // Get user settings readIniFile (filename); // There's no startup window on Linux and respecting this // option from the ini file would disable commandline options. #if defined __unix__ && !(defined __APPLE__) if (! showSetupWindow()) return 0; saveIniFile (filename); #else if (! gameSettings.noStartWindow) { if (! showSetupWindow()) return 0; saveIniFile (filename); } #endif // Now set file indices properly to the chosen language. languageNum = getLanguageForFileB (); if (languageNum < 0) return fatal ("Can't find the translation data specified!"); setFileIndices (NULL, gameSettings.numLanguages, languageNum); if (dataFol[0]) { char *dataFolder = encodeFilename(dataFol); #ifdef _WIN32 mkdir (dataFolder); #else mkdir (dataFolder, 0000777); #endif if (chdir (dataFolder)) return fatal ("This game's data folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", dataFolder); delete dataFolder; } positionStatus (10, winHeight - 15); return true; }
bool Reader::readToken( Token &token ) { skipSpaces(); token.start_ = current_; Char c = getNextChar(); bool ok = true; switch ( c ) { case '{': token.type_ = tokenObjectBegin; break; case '}': token.type_ = tokenObjectEnd; break; case '[': token.type_ = tokenArrayBegin; break; case ']': token.type_ = tokenArrayEnd; break; case '"': token.type_ = tokenString; ok = readString(); break; case '/': token.type_ = tokenComment; ok = readComment(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': token.type_ = tokenNumber; readNumber(); break; case 't': token.type_ = tokenTrue; ok = match( "rue", 3 ); break; case 'f': token.type_ = tokenFalse; ok = match( "alse", 4 ); break; case 'n': token.type_ = tokenNull; ok = match( "ull", 3 ); break; case ',': token.type_ = tokenArraySeparator; break; case ':': token.type_ = tokenMemberSeparator; break; case 0: token.type_ = tokenEndOfStream; break; default: ok = false; break; } if ( !ok ) token.type_ = tokenError; token.end_ = current_; return true; }
static void AddFontResources( WResID * name, ResMemFlags flags, const char * filename ) /**************************************************************/ { FontInfo info; char * devicename; char * facename; WResFileID handle; RcStatus ret; int err_code; ReadStrErrInfo readstr_err; if( name->IsName ) { RcError( ERR_FONT_NAME ); return; } handle = RcIoOpenInput( filename, O_RDONLY | O_BINARY ); if( handle == NIL_HANDLE) goto FILE_OPEN_ERROR; ret = readFontInfo( handle, &info, &err_code ); if( ret != RS_OK) goto READ_HEADER_ERROR; ret = copyFont( &info, handle, name, flags, &err_code ); if( ret != RS_OK ) goto COPY_FONT_ERROR; devicename = readString( handle, info.dfDevice, &readstr_err ); if( devicename == NULL ) { ret = readstr_err.status; err_code = readstr_err.err_code; goto READ_HEADER_ERROR; } facename = readString( handle, info.dfFace, &readstr_err ); if( facename == NULL ) { ret = readstr_err.status; err_code = readstr_err.err_code; RCFREE( devicename ); goto READ_HEADER_ERROR; } AddFontToDir( &info, devicename, facename, name ); RCFREE( devicename ); RCFREE( facename ); RCCLOSE( handle ); return; FILE_OPEN_ERROR: RcError( ERR_CANT_OPEN_FILE, filename, strerror( errno ) ); ErrorHasOccured = true; RCFREE( name ); return; READ_HEADER_ERROR: ReportCopyError( ret, ERR_READING_FONT, filename, err_code ); ErrorHasOccured = true; RCFREE( name ); RCCLOSE( handle ); return; COPY_FONT_ERROR: ReportCopyError( ret, ERR_READING_FONT, filename, err_code ); ErrorHasOccured = true; RCCLOSE( handle ); return; }
BPN::BPN(const char* file, int thrs) { std::ifstream fin; fin.open(file, std::ifstream::in); if(!fin.is_open()) { ConstructDefault(thrs); return; } unsigned i; max_threads = thrs < 0 ? 0 : thrs; readString(fin); fin>>initial_scale; readString(fin); fin>>eta; readString(fin); fin>>alpha; readString(fin); fin>>scale_factor; readString(fin); fin>>size; if(size >0) { unsigned f, layersize, prevsize=0; bool bias; // input layer - no bias readString(fin); readString(fin); fin>>layersize; readString(fin); fin>>bias; readString(fin); fin>>f; bias = false; layers = new bpnLayer*[size]; layers[0] = new bpnLayer(layersize, prevsize, bias, (outFunction) f, max_threads + 1); prevsize = layersize; for(i=1; i<size; ++i) { // itterate all layer above input readString(fin); readString(fin); fin>>layersize; readString(fin); fin>>bias; readString(fin); fin>>f; layers[i] = new bpnLayer(layersize, prevsize, bias, (outFunction) f, max_threads + 1); prevsize = layersize; } unsigned lowerSize = layers[size-1]->size; if(lowerSize > 0) { train_output = new double[lowerSize]; for(i=0; i < lowerSize; ++i) { train_output[i] = 0.0f; } } char ch; fin>>ch; if(ch =='x') { fin.close(); InitializeWeights(); return; } for(i=0; i<size; ++i) { LoadLayer(layers[i], fin); } }
void QWbXmlReader::nextToken() { char ch; int fullTag; again: // Bail out if we already saw EOF previously. if ( d->sawEOF ) return; // Get the next character and check for EOF. if ( ! ( d->input->getChar(&ch) ) ) { d->tokenType = QWbXmlToken_EOF; d->sawEOF = true; return; } // Determine the kind of token that we have. switch (ch) { case WBXML_SWITCH_PAGE: { if ( d->tagMode ) d->tagPage = readByte() << 6; else d->attrPage = readByte() << 8; goto again; } // Not reached. case WBXML_END: { // End of current tag or attribute context. if ( d->tagMode ) { d->tokenType = QWbXmlToken_EndTag; } else if ( d->hasContent ) { d->tokenType = QWbXmlToken_EndAttrs; d->tagMode = true; } else { d->tokenType = QWbXmlToken_EndTag; d->tagMode = true; } } break; case WBXML_ENTITY: { // Unicode character entity. d->tokenType = QWbXmlToken_String; d->tokenValue = QString( QChar( (ushort)readInt() ) ); } break; case WBXML_STR_I: { // Inline string value. d->tokenType = QWbXmlToken_String; d->tokenValue = readString(); } break; case WBXML_EXT_I_0: case WBXML_EXT_I_1: case WBXML_EXT_I_2: { // Inline string extension token - not used at present. readString(); goto again; } // Not reached. case WBXML_PI: { // Processing instruction, which is followed by attributes. d->tokenType = QWbXmlToken_PI; d->tagMode = false; d->hasContent = false; } break; case WBXML_EXT_T_0: case WBXML_EXT_T_1: case WBXML_EXT_T_2: { // Integer-based extension token - not used at present. readInt(); goto again; } // Not reached. case WBXML_STR_T: { // Reference into the string table. d->tokenType = QWbXmlToken_String; d->tokenValue = getIndexedString( readInt() ); } break; case WBXML_EXT_0: case WBXML_EXT_1: case WBXML_EXT_2: { // Byte-based extension token - not used at present. goto again; } // Not reached. case WBXML_OPAQUE: { // Opaque binary data - read and resolve it. QByteArray opaque; int len = readInt(); while ( len > 0 && !(d->sawEOF) ) { if ( ! d->input->getChar(&ch) ) { d->sawEOF = true; } else { opaque.resize( opaque.size() + 1 ); opaque[opaque.size() - 1] = ch; } --len; } d->tokenType = QWbXmlToken_String; d->tokenValue = resolveOpaque( d->currentAttr, opaque ); } break; default: { if ( d->tagMode ) { // Handle tag names. if ( (ch & WBXML_TAG_MASK) == WBXML_LITERAL ) { d->tokenValue = getIndexedString( readInt() ); } else { fullTag = (ch & WBXML_TAG_MASK) | d->tagPage; if ( d->tags.contains( fullTag ) ) { d->tokenValue = d->tags[fullTag]; } else { d->tokenValue = "x-tag-" + QString::number( fullTag ); } } d->tokenType = QWbXmlToken_Tag; if ( ( ch & WBXML_HAS_ATTRS ) != 0 ) { d->tagMode = false; } if ( ( ch & WBXML_HAS_CONTENT ) != 0 ) { d->hasContent = true; } else { d->hasContent = false; } } else { // Handle attribute names. if ( ch == WBXML_LITERAL ) { d->tokenType = QWbXmlToken_AttrStart; d->tokenValue = getIndexedString( readInt() ); } else { fullTag = ( ch & 0xFF ) | d->attrPage; if ( d->attrs.contains( fullTag ) ) { d->tokenValue = d->attrs[fullTag]; } else { d->tokenValue = "x-attr-" + QString::number( fullTag ); } if ( ( ch & 0x80 ) == 0 ) d->tokenType = QWbXmlToken_AttrStart; else d->tokenType = QWbXmlToken_String; } } } break; } }