//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RiuWellImportWizard::updateFieldsModel() { QString fileName = jsonFieldsFilePath(); if (QFile::exists(fileName)) { JsonReader jsonReader; QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(fileName); QStringList regions; QStringList fields; QStringList edmIds; QMapIterator<QString, QVariant> it(jsonMap); while (it.hasNext()) { it.next(); // If we have an array, skip to next node if (it.key() == "length") continue; QMap<QString, QVariant> fieldMap = it.value().toMap(); regions.push_back(fieldMap["region"].toString()); fields.push_back(fieldMap["name"].toString()); edmIds.push_back(fieldMap["edmId"].toString()); } m_wellPathImportObject->updateRegions(regions, fields, edmIds); m_wellPathImportObject->updateConnectedEditors(); } }
bool APIController::preprocess() { izenelib::driver::Value requestV; JsonReader reader; if (reader.read(raw_req(), requestV)) { request().assignTmp(requestV); } forward_mgr_ = FibpForwardManager::get(); return forward_mgr_ != NULL; }
bool Id3v2TagFrameIO::putFrameData(ByteBuffer* src) { bool rval = true; // read until frame buffer is full if(!mFrameBuffer.isFull()) { src->get(&mFrameBuffer, src->length(), false); } // process frame buffer if it is full if(mFrameBuffer.isFull()) { // only interested in XBMC frame if(strcmp(mCurrentHeader->getId(), "XBMC") == 0) { // skip 4 bytes of uncompressed size // (part of id3v2 compressed frame standard) mFrameBuffer.clear(4); ByteArrayInputStream bais(&mFrameBuffer, false); // decompress zlib-compressed data Deflater def; def.startInflating(false); MutatorInputStream mis(&bais, false, &def, false); // create/clear contract as necessary if(mContract.isNull()) { mContract = Contract(); } else { mContract->clear(); } // decompress JSON-formatted contract JsonReader reader; reader.start(mContract); rval = (reader.read(&mis) && reader.finish()); mis.close(); // set media mMedia.setNull(); if(mContract->hasMember("media")) { mMedia = mContract["media"]; } } } return rval; }
FileTemplates::FileTemplates(QObject *parent) : QObject(parent) { m_menu.setTitle(tr("New")); templateDir = QCoreApplication::applicationDirPath()+QDir::toNativeSeparators("/templates/"); QFile file(templateDir + "file.json"); file.open(QIODevice::ReadOnly); QTextStream stream ( &file ); JsonReader reader; reader.parse(stream.readAll()); if(reader.errorString().isEmpty()) buildMenu(reader.result()); }
bool Skin::parseManifest() { QFile skinConfig(m_config); if (!skinConfig.open(QIODevice::ReadOnly)) { qWarning() << "Can't read " << m_config << " of skin " << m_name; return false; } JsonReader reader; if (!reader.parse(skinConfig.readAll())) { qWarning() << "Failed to parse config file " << m_config << reader.errorString(); return false; } const QVariantMap root = reader.result().toMap(); m_version = root["version"].toString(); if (m_version.isEmpty()) qWarning() << "Skin has no version"; m_defaultResolution = root["default_resolution"].toString(); if (m_defaultResolution.isEmpty()) qWarning() << "Skin has no default resolution"; m_resolutions = root["resolutions"].toMap(); if (m_resolutions.isEmpty()) qWarning() << "Skin does not declare any supported resolutions"; m_screenshot = root["screenshot"].toString(); if (m_screenshot.isEmpty()) qWarning() << "Skin does not have any screenshot"; m_website = root["website"].toString(); if (m_website.isEmpty()) qWarning() << "Skin does not have any website"; // load default settings const QVariantList settings = root["settings"].toList(); foreach (const QVariant &s, settings) { const QVariantMap entry = s.toMap(); m_settings->addOptionEntry(entry.value("name").toString(), entry.value("default_value").toString(), entry.value("doc").toString()); } const QString configFilePath = QFileInfo(QSettings().fileName()).absolutePath() + QLatin1String("/") + name() + QLatin1String(".conf"); m_settings->loadConfigFile(configFilePath); m_settings->parseArguments(qApp->arguments()); return true; }
QVariant ImportProfileCommand::importProfileData(const QString &path, bool includeKeys) { JsonReader reader; Json::Value backup = reader.read(path.toStdString().c_str()); if(backup.empty()||!backup.isMember("profile")||!backup.isMember("key")||!backup.isMember("stealth")) { return QVariant::fromValue(false); } if(includeKeys) { importKeys(backup["key"], EthereumKeySerializer(), _ethereumKeys); importKeys(backup["stealth"], StealthKeySerializer(), _stealthKeys); } _bitprofiles.insert(BitProfile::ProfileDescriptor(backup["profile"])); return QVariant::fromValue(true); }
//-------------------------------------------------------------------------------------------------- /// Read JSON file containing well path data //-------------------------------------------------------------------------------------------------- void RimWellPath::readJsonWellPathFile() { RigWellPath* wellPathGeom = new RigWellPath(); JsonReader jsonReader; QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(filepath); // General well info name = jsonMap["name"].toString(); id = jsonMap["id"].toString(); sourceSystem = jsonMap["sourceSystem"].toString(); utmZone = jsonMap["utmZone"].toString(); updateUser = jsonMap["updateUser"].toString(); setSurveyType(jsonMap["surveyType"].toString()); // Convert updateDate from the following format: // "Number of milliseconds elapsed since midnight Coordinated Universal Time (UTC) // of January 1, 1970, not counting leap seconds" QString updateDateStr = jsonMap["updateDate"].toString().trimmed(); uint updateDateUint = updateDateStr.toULongLong() / 1000; // should be within 32 bit, maximum number is 4294967295 which corresponds to year 2106 QDateTime updateDateTime; updateDateTime.setTime_t(updateDateUint); updateDate = updateDateTime.toString("d MMMM yyyy"); // Well path points double datumElevation = jsonMap["datumElevation"].toDouble(); QList<QVariant> pathList = jsonMap["path"].toList(); foreach (QVariant point, pathList) { QMap<QString, QVariant> coordinateMap = point.toMap(); cvf::Vec3d vec3d(coordinateMap["east"].toDouble(), coordinateMap["north"].toDouble(), -(coordinateMap["tvd"].toDouble() - datumElevation)); wellPathGeom->m_wellPathPoints.push_back(vec3d); double measuredDepth = coordinateMap["md"].toDouble(); wellPathGeom->m_measuredDepths.push_back(measuredDepth); }
void fromJson( _T &v, JsonReader &json ) const { if( json.type() == JsonReader::START_OBJECT ) { match( json, JsonReader::START_OBJECT ); if( json.type() == JsonReader::END_OBJECT ) throw json_parse_failure(); while( !match0( json, JsonReader::END_OBJECT ) ) { if( matchField0( "circle", json ) ) v.set_circle(circle_s()->fromJson( json )); else if( matchField0( "rectangle", json ) ) v.set_rectangle(rectangle_s()->fromJson( json )); else if( matchField0( "composed", json ) ) v.set_composed(composed_s()->fromJson( json )); else if( matchField0( "translated", json ) ) v.set_translated(translated_s()->fromJson( json )); else throw json_parse_failure(); } return; } throw json_parse_failure(); }
void OvrVideosMetaData::ExtractExtendedData( const JsonReader & jsonDatum, OvrMetaDatum & datum ) const { OvrVideosMetaDatum * videoData = static_cast< OvrVideosMetaDatum * >( &datum ); if ( videoData ) { videoData->Title = jsonDatum.GetChildStringByName( TITLE_INNER ); videoData->Author = jsonDatum.GetChildStringByName( AUTHOR_INNER ); videoData->ThumbnailUrl = jsonDatum.GetChildStringByName( THUMBNAIL_URL_INNER ); videoData->StreamingType = jsonDatum.GetChildStringByName( STREAMING_TYPE_INNER ); videoData->StreamingProxy = jsonDatum.GetChildStringByName( STREAMING_PROXY_INNER ); videoData->StreamingSecurityLevel = jsonDatum.GetChildStringByName( STREAMING_SECURITY_LEVEL_INNER ); if ( videoData->Title.IsEmpty() ) { videoData->Title = ExtractFileBase( datum.Url.ToCStr() ); } if ( videoData->Author.IsEmpty() ) { videoData->Author = DEFAULT_AUTHOR_NAME; } } }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RiuWellImportWizard::parseWellsResponse(RimOilFieldEntry* oilFieldEntry) { QStringList surveyNames; QStringList planNames; if (QFile::exists(oilFieldEntry->wellsFilePath)) { JsonReader jsonReader; QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(oilFieldEntry->wellsFilePath); QMapIterator<QString, QVariant> it(jsonMap); while (it.hasNext()) { it.next(); // If we have an array, skip to next node if (it.key() == "length") continue; QMap<QString, QVariant> rootMap = it.value().toMap(); if (m_wellPathImportObject->wellTypeSurvey) { QMap<QString, QVariant> surveyMap = rootMap["survey"].toMap(); QString name = surveyMap["name"].toString(); if (!oilFieldEntry->find(name, RimWellPathEntry::WELL_SURVEY)) { QMap<QString, QVariant> linksMap = surveyMap["links"].toMap(); QString requestUrl = m_webServiceAddress + linksMap["entity"].toString(); QString surveyType = surveyMap["surveyType"].toString(); RimWellPathEntry* surveyWellPathEntry = RimWellPathEntry::createWellPathEntry(name, surveyType, requestUrl, m_destinationFolder, RimWellPathEntry::WELL_SURVEY); oilFieldEntry->wells.push_back(surveyWellPathEntry); } surveyNames.push_back(name); } if (m_wellPathImportObject->wellTypePlans) { QList<QVariant> plansList = rootMap["plans"].toList(); QListIterator<QVariant> planIt(plansList); while (planIt.hasNext()) { QMap<QString, QVariant> planMap = planIt.next().toMap(); QString name = planMap["name"].toString(); if (!oilFieldEntry->find(name, RimWellPathEntry::WELL_PLAN)) { QMap<QString, QVariant> linksMap = planMap["links"].toMap(); QString requestUrl = m_webServiceAddress + linksMap["entity"].toString(); QString surveyType = planMap["surveyType"].toString(); RimWellPathEntry* surveyWellPathEntry = RimWellPathEntry::createWellPathEntry(name, surveyType, requestUrl, m_destinationFolder, RimWellPathEntry::WELL_PLAN); oilFieldEntry->wells.push_back(surveyWellPathEntry); } planNames.push_back(name); } } } } // Delete the well path entries in the model that are not part of the reply from the web service std::vector<RimWellPathEntry*> wellsToRemove; for (size_t i = 0; i < oilFieldEntry->wells.size(); i++) { RimWellPathEntry* wellPathEntry = oilFieldEntry->wells[i]; if (wellPathEntry->wellPathType == RimWellPathEntry::WELL_PLAN) { if (!planNames.contains(wellPathEntry->name)) { wellsToRemove.push_back(wellPathEntry); } } else { if (!surveyNames.contains(wellPathEntry->name)) { wellsToRemove.push_back(wellPathEntry); } } } for (size_t i = 0; i < wellsToRemove.size(); i++) { oilFieldEntry->wells.removeChildObject(wellsToRemove[i]); delete wellsToRemove[i]; } WellSelectionPage* wellSelectionPage = dynamic_cast<WellSelectionPage*>(page(m_wellSelectionPageId)); if (wellSelectionPage) wellSelectionPage->buildWellTreeView(); }
bool deserialize(const std::string& filename, value_type& value) { JsonReader reader; JsonNode root = reader.Parse(filename.c_str()); return deserialize(root, value); }
//============================== // FontInfoType::LoadFromBuffer bool FontInfoType::LoadFromBuffer( void const * buffer, size_t const bufferSize ) { char const * errorMsg = NULL; OVR::JSON * jsonRoot = OVR::JSON::Parse( reinterpret_cast< char const * >( buffer ), &errorMsg ); if ( jsonRoot == NULL ) { LOG( "JSON Error: %s", ( errorMsg != NULL ) ? errorMsg : "<NULL>" ); return false; } int32_t maxCharCode = -1; // currently we're only supporting the first unicode plane up to 65k. If we were to support other planes // we could conceivably end up with a very sparse 1,114,111 byte type for mapping character codes to // glyphs and if that's the case we may just want to use a hash, or use a combination of tables for // the first 65K and hashes for the other, less-frequently-used characters. static const int MAX_GLYPHS = 0xffff; // load the glyphs const JsonReader jsonGlyphs( jsonRoot ); if ( !jsonGlyphs.IsObject() ) { jsonRoot->Release(); return false; } int Version = jsonGlyphs.GetChildFloatByName( "Version" ); if ( Version != FNT_FILE_VERSION ) { jsonRoot->Release(); return false; } FontName = jsonGlyphs.GetChildStringByName( "FontName" ); CommandLine = jsonGlyphs.GetChildStringByName( "CommandLine" ); ImageFileName = jsonGlyphs.GetChildStringByName( "ImageFileName" ); const int numGlyphs = jsonGlyphs.GetChildInt32ByName( "NumGlyphs" ); if ( numGlyphs < 0 || numGlyphs > MAX_GLYPHS ) { OVR_ASSERT( numGlyphs > 0 && numGlyphs <= MAX_GLYPHS ); jsonRoot->Release(); return false; } NaturalWidth = jsonGlyphs.GetChildFloatByName( "NaturalWidth" ); NaturalHeight = jsonGlyphs.GetChildFloatByName( "NaturalHeight" ); // we scale everything after loading integer values from the JSON file because the OVR JSON writer loses precision on floats double nwScale = 1.0f / NaturalWidth; double nhScale = 1.0f / NaturalHeight; HorizontalPad = jsonGlyphs.GetChildFloatByName( "HorizontalPad" ) * nwScale; VerticalPad = jsonGlyphs.GetChildFloatByName( "VerticalPad" ) * nhScale; FontHeight = jsonGlyphs.GetChildFloatByName( "FontHeight" ) * nhScale; CenterOffset = jsonGlyphs.GetChildFloatByName( "CenterOffset" ); TweakScale = jsonGlyphs.GetChildFloatByName( "TweakScale", 1.0f ); LOG( "FontName = %s", FontName.ToCStr() ); LOG( "CommandLine = %s", CommandLine.ToCStr() ); LOG( "HorizontalPad = %.4f", HorizontalPad ); LOG( "VerticalPad = %.4f", VerticalPad ); LOG( "FontHeight = %.4f", FontHeight ); LOG( "CenterOffset = %.4f", CenterOffset ); LOG( "TweakScale = %.4f", TweakScale ); LOG( "ImageFileName = %s", ImageFileName.ToCStr() ); LOG( "Loading %i glyphs.", numGlyphs ); /// HACK: this is hard-coded until we do not have a dependcy on reading the font from Home if ( OVR_stricmp( FontName.ToCStr(), "korean.fnt" ) == 0 ) { TweakScale = 1.4f; CenterOffset = -0.02f; } /// HACK: end hack Glyphs.Resize( numGlyphs ); const JsonReader jsonGlyphArray( jsonGlyphs.GetChildByName( "Glyphs" ) ); double totalWidth = 0.0; if ( jsonGlyphArray.IsArray() ) { for ( int i = 0; i < Glyphs.GetSizeI() && !jsonGlyphArray.IsEndOfArray(); i++ ) { const JsonReader jsonGlyph( jsonGlyphArray.GetNextArrayElement() ); if ( jsonGlyph.IsObject() ) { FontGlyphType & g = Glyphs[i]; g.CharCode = jsonGlyph.GetChildInt32ByName( "CharCode" ); g.X = jsonGlyph.GetChildFloatByName( "X" ); g.Y = jsonGlyph.GetChildFloatByName( "Y" ); g.Width = jsonGlyph.GetChildFloatByName( "Width" ); g.Height = jsonGlyph.GetChildFloatByName( "Height" ); g.AdvanceX = jsonGlyph.GetChildFloatByName( "AdvanceX" ); g.AdvanceY = jsonGlyph.GetChildFloatByName( "AdvanceY" ); g.BearingX = jsonGlyph.GetChildFloatByName( "BearingX" ); g.BearingY = jsonGlyph.GetChildFloatByName( "BearingY" ); g.X *= nwScale; g.Y *= nhScale; g.Width *= nwScale; g.Height *= nhScale; g.AdvanceX *= nwScale; g.AdvanceY *= nhScale; g.BearingX *= nwScale; g.BearingY *= nhScale; totalWidth += g.Width; maxCharCode = Alg::Max( maxCharCode, g.CharCode ); } } } double averageGlyphWidth = totalWidth / numGlyphs; // this is the average width in uv space of characters in the ClearSans font. This is used to // compute a scaling factor for other fonts. double const DEFAULT_GLYPH_UV_WIDTH = 0.047458650262793022; float const DEFAULT_TEXT_SCALE = 0.0025f; float const widthScaleFactor = static_cast< float >( DEFAULT_GLYPH_UV_WIDTH / averageGlyphWidth ); ScaleFactor = DEFAULT_SCALE_FACTOR * DEFAULT_TEXT_SCALE * widthScaleFactor * TweakScale; // This is not intended for wide or ucf character sets -- depending on the size range of // character codes lookups may need to be changed to use a hash. if ( maxCharCode >= MAX_GLYPHS ) { OVR_ASSERT( maxCharCode <= MAX_GLYPHS ); maxCharCode = MAX_GLYPHS; } // resize the array to the maximum glyph value CharCodeMap.Resize( maxCharCode + 1 ); for ( int i = 0; i < Glyphs.GetSizeI(); ++i ) { FontGlyphType const & g = Glyphs[i]; CharCodeMap[g.CharCode] = i; } jsonRoot->Release(); return true; }
int main(int argc, char* argv[]) { System::init(); /* * Byte buffer * */ ByteBuffer buffer(5); char abc[4] = "abc"; buffer.write(abc,3); buffer.reset(); buffer.resize(3,true); printf("%c\n",buffer.readByte()); printf("%c\n",buffer.readByte()); printf("%c\n",buffer.readByte()); buffer.reset(); /* * Canvas */ Canvas canvas(640,480); if (!canvas.getSurface()) { return -1; } Thread thread("test thread", &testFunc, (void*)NULL); /* * Json Reader. */ JsonReader reader; reader.read("res/config.json"); Json::Value value = reader.getRoot(); std::cout << reader.getRoot().get("verson", "1.2") << std::endl; JsonWriter writer; writer.write("res/1.json", reader.getRoot(), true); writer.write("res/2.json", reader.getRoot(), false); Shader vertex("res/shaders/vertex.glsl",Shader::ShaderType::VERTEX_SHADER); Shader fragment("res/shaders/fragment.glsl",Shader::ShaderType::FRAGMENT_SHADER); ShaderProgram shaderProgram; shaderProgram.addShader(&vertex); shaderProgram.addShader(&fragment); shaderProgram.link(); Shader vertexRadialBlur("res/shaders/radialblur_vertex.glsl",Shader::ShaderType::VERTEX_SHADER); Shader fragmentRadialBlur("res/shaders/radialblur_fragment.glsl",Shader::ShaderType::FRAGMENT_SHADER); ShaderProgram radialBlur; radialBlur.addShader(&vertexRadialBlur); radialBlur.addShader(&fragmentRadialBlur); radialBlur.link(); ResourcesManager resourcesManager; resourcesManager.loadTexture("lama1","res/lama1.png"); resourcesManager.loadTexture("spritesheet","res/ch.png"); resourcesManager.loadTexture("courrier","res/courrier_0.png"); Sprite sprite2(resourcesManager.getTexture("lama1")); Rect<float> texCoords[] = { Rect<float>(32,0,32,32), Rect<float>(0,0,32,32), Rect<float>(32,0,32,32), Rect<float>(64,0,32,32)}; unsigned int durations[] = { 100, 100, 100, 100 }; Sprite sprite(resourcesManager.getTexture("spritesheet")); sprite.addAnimation("down", 4, durations, texCoords); sprite.setSize(128,128); sprite.setAnimation("down"); SimpleScene2D scene2D(640,480); shared_ptr<SceneNode> node = shared_ptr<SceneNode>(new SceneNode(&vertex,&fragment)); scene2D.addNode(node); for (int i = 0; i < 1; i++) { shared_ptr<SpriteActor> s = shared_ptr<SpriteActor>(new SpriteActor(sprite2)); if (s) { node->addActor(s); } } node->addActor(shared_ptr<SpriteActor>(new SpriteActor(sprite))); BMFontReader fontReader("res/courrier.fnt"); FontActorCreator fontActorCreator(resourcesManager,fontReader.read()); shared_ptr<FontActor> fontActor = fontActorCreator.createFontActor("courrier", "This IS A TEXT TEST ! Hehehe", 1, 2, 2.0f, Vector4d<float>(0.2f,0.5f,1.0f,0.2f)); node->addActor(fontActor); /* for (int i = 0; i < 5000; i++) { shared_ptr<SpriteActor> s = shared_ptr<SpriteActor>(new SpriteActor(sprite)); if (s) { node->addActor(s); } } */ InputDevicesManager& idm = canvas.getInputDevicesManager(); idm.update(); printf("%i %i\n",idm.getMouseX(),idm.getMouseY()); if (idm.keyPressed(SDLK_SPACE)) { printf("SPACE!\n"); } if (idm.leftButton()) { printf("left button\n"); } if (idm.middleButton()) { printf("middle button\n"); } if (idm.rightButton()) { printf("right button\n"); } long t = System::currentTime()+1000; float nbFrame = 0.0f; scene2D.update(); printf("scene 2D updated\n"); char title[10]; Sound snd("res/music.ogg"); Sound snd2("res/boump.ogg"); AudioSystem system; system.play(&snd,true); while (1) { canvas.clear(0.0f,0.0f,0.0f,1.0f); scene2D.update(); scene2D.render(); canvas.flip(); idm.update(); if (idm.leftButton()) { printf("left button\n"); } if (idm.keyPressed(SDLK_ESCAPE)) { break; } else if (idm.keyPressed(SDLK_LEFT)) { sprite.setPosition(sprite.getX()-5.0f, sprite.getY()); } else if (idm.keyPressed(SDLK_RIGHT)) { sprite.setPosition(sprite.getX()+5.0f, sprite.getY()); } else if (idm.keyPressed(SDLK_DOWN)) { sprite.setPosition(sprite.getX(), sprite.getY()-5.0f); } else if (idm.keyPressed(SDLK_UP)) { sprite.setPosition(sprite.getX(), sprite.getY()+5.0f); } else if (idm.keyPressed(SDLK_SPACE)) { system.play(&snd2,false); } else if (idm.keyPressed(SDLK_o)) { sprite.setTint(sprite.getTint().x(), sprite.getTint().y(), sprite.getTint().z(), sprite.getTint().i() <= 0.9f ? sprite.getTint().i()+0.1f : 1.0f); } else if (idm.keyPressed(SDLK_l)) { sprite.setTint(sprite.getTint().x(), sprite.getTint().y(), sprite.getTint().z(), sprite.getTint().i() > 0.0f ? sprite.getTint().i()-0.1f : 0.0f); } nbFrame = nbFrame + 1.0f; if (t < System::currentTime()) { sprintf(title,"%.2f fps",nbFrame); canvas.setTitle(title); printf("%s\n",gluErrorString(glGetError())); nbFrame = 0.0f; t = System::currentTime()+1000; } System::sleep(16); } System::deinit(); return 0; }
// FIXME: This code has an issue if the config file has a changed id or // FIXME: changed contents since it was first loaded. Just assuming this code // FIXME: is the only code that manages the file for now. bool NodeConfigManager::saveSystemUserConfig() { bool rval; Config cfg = getNodeConfig(); const char* suPath; string path; rval = !cfg.isNull(); if(rval) { // get system user config and expand any home path suPath = cfg["systemUserConfig"]->getString(); rval = expandBitmunkHomePath(suPath, path); } if(rval) { // FIXME: do we need locking for load/save/get/remove? MO_CAT_DEBUG(BM_NODE_CAT, "NodeConfigManager: save system user config: path=%s", path.c_str()); // read File file(path.c_str()); // new config Config c; if(file->exists()) { FileInputStream fis(file); JsonReader reader; reader.start(c); rval = reader.read(&fis) && reader.finish(); fis.close(); } else { c[ConfigManager::VERSION] = MO_DEFAULT_CONFIG_VERSION; c[ConfigManager::ID] = "custom system user"; c[ConfigManager::GROUP] = "system user"; } // update if(rval && getConfigManager()->hasConfig(c[ConfigManager::ID]->getString())) { // get old raw config Config active = getConfigManager()->getConfig( c[ConfigManager::ID]->getString(), true); c.merge(active, false); } // backup old file if(rval && file->exists()) { string backupPath = path + ".bak"; File backupFile(backupPath.c_str()); rval = file->rename(backupFile); } // make sure dirs exist rval = rval && file->mkdirs(); // write if(rval) { FileOutputStream fos(file); JsonWriter writer; writer.setCompact(false); rval = writer.write(c, &fos); fos.close(); } } if(!rval) { ExceptionRef e = new Exception( "Could not save system user config.", "bitmunk.node.NodeConfigManager.ConfigError"); e->getDetails()["path"] = path.c_str(); Exception::push(e); } return rval; }
//--------------------------------------------------------------------------------------------------------- void Checking::OnRequestResourceList( BohgeEngine::IBaseHandle* h ) { if ( IWebProperty::HS_OK != h->GetStatusCode() ) { DEBUGLOG("Can not connect server!\r\n"); } else { ResourceList Reslist; ASSERT( IWebProperty::JS_FINISH == h->GetState() ); JsonReader webreader; webreader.Parse( static_cast<IPostHandle*>(h)->GetResult() ); JsonEntryInfo webinfo; webreader.Read( webinfo ); m_LocalPath = string( DefaultResource::RESOURCE_PATH ) + webinfo.m_Bundle + PLANTFORMDELIMITER; string infopath = m_LocalPath + DefaultResource::LITE_INFO_FILE; if ( webinfo.m_isValid ) { IFile* file = IIOSystem::Instance()->FileFactory( infopath ); file->OpenFile( IFile::AT_READ ); if ( !file->isOpen() )//如果没打卡,则从新下载相应资源 { _AllResource( Reslist, webinfo ); } else//如果打开了则对比一下 { eastl::string locallif; locallif.resize( file->GetSize() ); file->ReadFile( &locallif[0], file->GetSize() ); file->CloseFile(); IIOSystem::Instance()->RecycleBin( file ); JsonReader loacalreader; if( loacalreader.Parse( locallif ) )//可能本地json被损坏导致无法读取 { loacalreader.Read( m_LocalResourceList ); _CompareResource( Reslist, webinfo ); } else { DEBUGLOG("Resource list is invaild"); _AllResource( Reslist, webinfo ); } } } else { ASSERT( false && "Application's version is not valiable!\n" ); } if ( !Reslist.empty() ) { DEBUGLOG("Need download resource\n"); m_pJsonWriter->Open( DefaultResource::APP_VERSION_INT, infopath ); _DownloadResources( Reslist ); } else { m_pMutex->Lock(); m_isFinish = true; m_ReleaseList.push_back( h ); m_pMutex->Unlock(); } } }
void ParseModelsJsonTest( const char * jsonFileName, const char * binFileName ) { const BinaryReader bin( binFileName, NULL ); if ( bin.ReadUInt32() != 0x6272766F ) { return; } JSON * json = JSON::Load( jsonFileName ); if ( json == NULL ) { return; } const JsonReader models( json ); if ( models.IsObject() ) { // // Render Model // const JsonReader render_model( models.GetChildByName( "render_model" ) ); if ( render_model.IsObject() ) { const JsonReader texture_array( render_model.GetChildByName( "textures" ) ); if ( texture_array.IsArray() ) { while ( !texture_array.IsEndOfArray() ) { const JsonReader texture( texture_array.GetNextArrayElement() ); if ( texture.IsObject() ) { const String name = texture.GetChildStringByName( "name" ); const String usage = texture.GetChildStringByName( "usage" ); const String occlusion = texture.GetChildStringByName( "occlusion" ); } } } const JsonReader joint_array( render_model.GetChildByName( "joints" ) ); if ( joint_array.IsArray() ) { while ( !joint_array.IsEndOfArray() ) { const JsonReader joint( joint_array.GetNextArrayElement() ); if ( joint.IsObject() ) { struct Joint { String name; Matrix4f transform; String animation; Vector3f parameters; float timeOffset; float timeScale; } newJoint; newJoint.name = joint.GetChildStringByName( "name" ); newJoint.animation = joint.GetChildStringByName( "animation" ); StringUtils::StringTo( newJoint.transform, joint.GetChildStringByName( "transform" ) ); newJoint.parameters.x = joint.GetChildFloatByName( "parmX" ); newJoint.parameters.y = joint.GetChildFloatByName( "parmY" ); newJoint.parameters.z = joint.GetChildFloatByName( "parmZ" ); newJoint.timeScale = joint.GetChildFloatByName( "timeScale" ); newJoint.timeOffset = joint.GetChildFloatByName( "timeOffset" ); } } } const JsonReader tag_array( render_model.GetChildByName( "tags" ) ); if ( tag_array.IsArray() ) { while ( !tag_array.IsEndOfArray() ) { const JsonReader tag( tag_array.GetNextArrayElement() ); if ( tag.IsObject() ) { struct Tag { String name; Matrix4f matrix; Vector4i jointIndices; Vector4f jointWeights; } newTag; const String name = tag.GetChildStringByName( "name" ); StringUtils::StringTo( newTag.matrix, tag.GetChildStringByName( "matrix" ) ); StringUtils::StringTo( newTag.jointIndices, tag.GetChildStringByName( "jointIndices" ) ); StringUtils::StringTo( newTag.jointWeights, tag.GetChildStringByName( "jointWeights" ) ); } } } const JsonReader surface_array( render_model.GetChildByName( "surfaces" ) ); if ( surface_array.IsArray() ) { while ( !surface_array.IsEndOfArray() ) { struct Surface { String name; String materialType; int diffuseTexture; int normalTexture; int specularTexture; int emissiveTexture; Bounds3f bounds; Array< Vector3f > position; Array< Vector3f > normal; Array< Vector3f > tangent; Array< Vector3f > binormal; Array< Vector4f > color; Array< Vector2f > uv0; Array< Vector2f > uv1; Array< Vector4f > jointWeights; Array< Vector4i > jointIndices; Array< uint16_t > indices; } newSurface; const JsonReader surface( surface_array.GetNextArrayElement() ); if ( surface.IsObject() ) { const JsonReader source( surface.GetChildByName( "source" ) ); if ( source.IsArray() ) { while ( !source.IsEndOfArray() ) { if ( newSurface.name.GetLength() ) { newSurface.name += ";"; } newSurface.name += source.GetNextArrayString(); } } const JsonReader material( surface.GetChildByName( "material" ) ); if ( material.IsObject() ) { newSurface.materialType = material.GetChildStringByName( "type" ); newSurface.diffuseTexture = material.GetChildInt32ByName( "diffuse", -1 ); newSurface.normalTexture = material.GetChildInt32ByName( "normal", -1 ); newSurface.specularTexture = material.GetChildInt32ByName( "specular", -1 ); newSurface.emissiveTexture = material.GetChildInt32ByName( "emissive", -1 ); } StringUtils::StringTo( newSurface.bounds, surface.GetChildStringByName( "bounds" ) ); // // Vertices // const JsonReader vertices( surface.GetChildByName( "vertices" ) ); if ( vertices.IsObject() ) { const int vertexCount = vertices.GetChildInt32ByName( "vertexCount" ); ReadModelArray( newSurface.position, vertices.GetChildStringByName( "position" ), bin, vertexCount ); ReadModelArray( newSurface.normal, vertices.GetChildStringByName( "normal" ), bin, vertexCount ); ReadModelArray( newSurface.tangent, vertices.GetChildStringByName( "tangent" ), bin, vertexCount ); ReadModelArray( newSurface.binormal, vertices.GetChildStringByName( "binormal" ), bin, vertexCount ); ReadModelArray( newSurface.color, vertices.GetChildStringByName( "color" ), bin, vertexCount ); ReadModelArray( newSurface.uv0, vertices.GetChildStringByName( "uv0" ), bin, vertexCount ); ReadModelArray( newSurface.uv1, vertices.GetChildStringByName( "uv1" ), bin, vertexCount ); ReadModelArray( newSurface.jointIndices, vertices.GetChildStringByName( "jointIndices" ), bin, vertexCount ); ReadModelArray( newSurface.jointWeights, vertices.GetChildStringByName( "jointWeights" ), bin, vertexCount ); } // // Triangles // const JsonReader triangles( surface.GetChildByName( "triangles" ) ); if ( triangles.IsObject() ) { const int indexCount = triangles.GetChildInt32ByName( "indexCount" ); ReadModelArray( newSurface.indices, triangles.GetChildStringByName( "indices" ), bin, indexCount ); } } } } } // // Collision Model // const JsonReader collision_model( models.GetChildByName( "collision_model" ) ); if ( collision_model.IsArray() ) { while ( !collision_model.IsEndOfArray() ) { Array< Planef > planes; const JsonReader polytope( collision_model.GetNextArrayElement() ); if ( polytope.IsObject() ) { const String name = polytope.GetChildStringByName( "name" ); StringUtils::StringTo( planes, polytope.GetChildStringByName( "planes" ) ); } } } // // Ground Collision Model // const JsonReader ground_collision_model( models.GetChildByName( "ground_collision_model" ) ); if ( ground_collision_model.IsArray() ) { while ( !ground_collision_model.IsEndOfArray() ) { Array< Planef > planes; const JsonReader polytope( ground_collision_model.GetNextArrayElement() ); if ( polytope.IsObject() ) { const String name = polytope.GetChildStringByName( "name" ); StringUtils::StringTo( planes, polytope.GetChildStringByName( "planes" ) ); } } } // // Ray-Trace Model // const JsonReader raytrace_model( models.GetChildByName( "raytrace_model" ) ); if ( raytrace_model.IsObject() ) { ModelTrace traceModel; traceModel.header.numVertices = raytrace_model.GetChildInt32ByName( "numVertices" ); traceModel.header.numUvs = raytrace_model.GetChildInt32ByName( "numUvs" ); traceModel.header.numIndices = raytrace_model.GetChildInt32ByName( "numIndices" ); traceModel.header.numNodes = raytrace_model.GetChildInt32ByName( "numNodes" ); traceModel.header.numLeafs = raytrace_model.GetChildInt32ByName( "numLeafs" ); traceModel.header.numOverflow = raytrace_model.GetChildInt32ByName( "numOverflow" ); StringUtils::StringTo( traceModel.header.bounds, raytrace_model.GetChildStringByName( "bounds" ) ); ReadModelArray( traceModel.vertices, raytrace_model.GetChildStringByName( "vertices" ), bin, traceModel.header.numVertices ); ReadModelArray( traceModel.uvs, raytrace_model.GetChildStringByName( "uvs" ), bin, traceModel.header.numUvs ); ReadModelArray( traceModel.indices, raytrace_model.GetChildStringByName( "indices" ), bin, traceModel.header.numIndices ); if ( !bin.ReadArray( traceModel.nodes, traceModel.header.numNodes ) ) { const JsonReader nodes_array( raytrace_model.GetChildByName( "nodes" ) ); if ( nodes_array.IsArray() ) { while ( !nodes_array.IsEndOfArray() ) { const UPInt index = traceModel.nodes.AllocBack(); const JsonReader node( nodes_array.GetNextArrayElement() ); if ( node.IsObject() ) { traceModel.nodes[index].data = (UInt32) node.GetChildInt64ByName( "data" ); traceModel.nodes[index].dist = node.GetChildFloatByName( "dist" ); } } } } if ( !bin.ReadArray( traceModel.leafs, traceModel.header.numLeafs ) ) { const JsonReader leafs_array( raytrace_model.GetChildByName( "leafs" ) ); if ( leafs_array.IsArray() ) { while ( !leafs_array.IsEndOfArray() ) { const UPInt index = traceModel.leafs.AllocBack(); const JsonReader leaf( leafs_array.GetNextArrayElement() ); if ( leaf.IsObject() ) { StringUtils::StringTo( traceModel.leafs[index].triangles, RT_KDTREE_MAX_LEAF_TRIANGLES, leaf.GetChildStringByName( "triangles" ) ); StringUtils::StringTo( traceModel.leafs[index].ropes, 6, leaf.GetChildStringByName( "ropes" ) ); StringUtils::StringTo( traceModel.leafs[index].bounds, leaf.GetChildStringByName( "bounds" ) ); } } } } ReadModelArray( traceModel.overflow, raytrace_model.GetChildStringByName( "overflow" ), bin, traceModel.header.numOverflow ); } } json->Release(); assert( bin.IsAtEnd() ); }