int main() { XMLNode* root = new XMLNode("root"); root->setAttribute("cmd","f**k"); root->setAttribute("abc","efg"); //root->setText("hello world"); XMLNode* node_1 = new XMLNode("abc"); node_1->setAttribute("bi","aaaa"); XMLNode* node_2 = new XMLNode("bcd"); node_2->setText("hello world"); root->addChild(node_1); root->addChild(node_2); node_1 = 0; node_2 = 0; XMLNode* n = root->getFirstChild(); if(n){ cout<<n->getName()<<endl; } XMLDoc* doc = new XMLDoc(); doc->setRoot(root); cout<<doc->toString()<<endl; return 0; }
const std::vector<GG::Clr>& EmpireColors() { static std::vector<GG::Clr> colors; if (colors.empty()) { XMLDoc doc; std::string file_name = "empire_colors.xml"; boost::filesystem::ifstream ifs(GetResourceDir() / file_name); if (ifs) { doc.ReadDoc(ifs); ifs.close(); } else { Logger().errorStream() << "Unable to open data file " << file_name; return colors; } for (int i = 0; i < doc.root_node.NumChildren(); ++i) { colors.push_back(XMLToClr(doc.root_node.Child(i))); } } if (colors.empty()) { colors.push_back(GG::Clr( 0, 255, 0, 255)); colors.push_back(GG::Clr( 0, 0, 255, 255)); colors.push_back(GG::Clr(255, 0, 0, 255)); colors.push_back(GG::Clr( 0, 255, 255, 255)); colors.push_back(GG::Clr(255, 255, 0, 255)); colors.push_back(GG::Clr(255, 0, 255, 255)); } return colors; }
void IntroScreen::OnCredits() { if (m_credits_wnd) { delete m_credits_wnd; m_credits_wnd = 0; return; } XMLDoc doc; boost::filesystem::ifstream ifs(GetResourceDir() / "credits.xml"); doc.ReadDoc(ifs); ifs.close(); if (!doc.root_node.ContainsChild("CREDITS")) return; XMLElement credits = doc.root_node.Child("CREDITS"); // only the area between the upper and lower line of the splash screen should be darkend // if we use another splash screen we have the change the following values GG::Y nUpperLine = ( 79 * GG::GUI::GetGUI()->AppHeight()) / 768; GG::Y nLowerLine = (692 * GG::GUI::GetGUI()->AppHeight()) / 768; int credit_side_pad(30); m_credits_wnd = new CreditsWnd(GG::X0, nUpperLine, GG::GUI::GetGUI()->AppWidth(), nLowerLine-nUpperLine, credits, credit_side_pad, 0, Value(m_menu->UpperLeft().x) - credit_side_pad, Value(nLowerLine-nUpperLine), Value((nLowerLine-nUpperLine))/2); m_splash->AttachChild(m_credits_wnd); }
bool MaterialResource::load(const char *data, int size) { if(!Resource::load(data, size)) return false; XMLDoc doc; doc.parseBuffer(data, size); if(doc.hasError()) return raiseError("XML parsing error"); XMLNode rootNode = doc.getRootNode(); if(strcmp(rootNode.getName(), "Material")!=0) return raiseError("Not a material resource file"); //Class _class = rootNode.getAttribute("class", ""); //Link if(strcmp(rootNode.getAttribute("link", ""), "")!=0) { uint32 mat = Modules::resMan().addResource( ResourceTypes::Material, rootNode.getAttribute("link"), 0, false); _matLink = (MaterialResource *)Modules::resMan().resolveResHandle(mat); if(_matLink == this) return raiseError("Illegal self link in material, causing infinite link loop"); } //Shader Flags XMLNode nodel = rootNode.getFirstChild("ShaderFlag"); while(!nodel.isEmpty()) { if(nodel.getAttribute("name")==0x0) return raiseError("Missing ShaderFlag attribute 'name'"); _shaderFlags.push_back(nodel.getAttribute("name")); nodel= nodel.getNextSibling("ShaderFlag"); } //Shader nodel = rootNode.getFirstChild("Shader"); if(!nodel.isEmpty()) { if(nodel.getAttribute("source")==0x0) return raiseError("Missing Shader attribute 'source'"); uint32 shader = Modules::resMan().addResource(ResourceTypes::Shader, nodel.getAttribute("source"), 0, false); _shaderRes = (ShaderResource *)Modules::resMan().resolveResHandle(shader); _combMask = ShaderResource::calcCombMask(_shaderFlags); _shaderRes->preLoadCombination(_combMask); } // //Texture samplers // //Vector uniforms return true; }
void IsoCurveParameters::putDataToDoc(XMLDoc &doc) { XMLNodePtr root = doc.createRoot(_T("IsoCurve")); doc.setValue( root, _T("expr" ), m_expr ); doc.setValue( root, _T("cellsize" ), m_cellSize ); setValue(doc, root, _T("boundingbox" ), m_boundingBox ); doc.setValue( root, _T("machinecode" ), m_machineCode ); doc.setValue( root, _T("includetime" ), m_includeTime ); if (m_includeTime) { setValue(doc, root, _T("timeinterval"), m_tInterval ); doc.setValue( root, _T("framecount" ), m_frameCount ); } }
bool Drumkit::save_file( const QString& dk_path, bool overwrite ) { INFOLOG( QString( "Saving drumkit definition into %1" ).arg( dk_path ) ); if( Filesystem::file_exists( dk_path, true ) && !overwrite ) { ERRORLOG( QString( "drumkit %1 already exists" ).arg( dk_path ) ); return false; } XMLDoc doc; doc.set_root( "drumkit_info", "drumkit" ); XMLNode root = doc.firstChildElement( "drumkit_info" ); save_to( &root ); return doc.write( dk_path ); }
void IsoCurveParameters::getDataFromDoc(XMLDoc &doc) { XMLNodePtr root = doc.getRoot(); checkTag(root, _T("IsoCurve")); doc.getValueLF(root, _T("expr" ), m_expr ); doc.getValue( root, _T("cellsize" ), m_cellSize ); getValue(doc, root, _T("boundingbox" ), m_boundingBox ); doc.getValue( root, _T("machinecode" ), m_machineCode ); doc.getValue( root, _T("includetime" ), m_includeTime ); if (m_includeTime) { getValue(doc, root, _T("timeinterval"), m_tInterval ); doc.getValue( root, _T("framecount" ), m_frameCount ); } }
Drumkit* Drumkit::load_file( const QString& dk_path, bool load_samples ) { XMLDoc doc; if( !doc.read( dk_path, Filesystem::drumkit_xsd() ) ) { return Legacy::load_drumkit( dk_path ); } XMLNode root = doc.firstChildElement( "drumkit_info" ); if ( root.isNull() ) { ERRORLOG( "drumkit_info node not found" ); return NULL; } Drumkit* drumkit = Drumkit::load_from( &root, dk_path.left( dk_path.lastIndexOf( "/" ) ) ); if( load_samples ) drumkit->load_samples(); return drumkit; }
bool Pattern::save_file( const QString& drumkit_name, const QString& author, const QString& license, const QString& pattern_path, bool overwrite ) const { INFOLOG( QString( "Saving pattern into %1" ).arg( pattern_path ) ); if( !overwrite && Filesystem::file_exists( pattern_path, true ) ) { ERRORLOG( QString( "pattern %1 already exists" ).arg( pattern_path ) ); return false; } XMLDoc doc; XMLNode root = doc.set_root( "drumkit_pattern", "drumkit_pattern" ); root.write_string( "drumkit_name", drumkit_name ); // FIXME loaded with LocalFileMng::getDrumkitNameForPattern(…) root.write_string( "author", author ); // FIXME this is never loaded back root.write_string( "license", license ); // FIXME this is never loaded back save_to( &root ); return doc.write( pattern_path ); }
static XMLDoc* readXMLDoc(const std::string& name, const std::string& dtdPath) { std::string p = path(name); std::string data = Reader::readString(name); xmlDtd* dtd = getDTD(dtdPath); if (!dtd || data.empty()) return NULL; XMLDoc* doc = new XMLDoc; if (!doc->init(p, data, dtd)) { delete doc; return NULL; } return doc; }
void OptionsDB::Commit() { if (!m_dirty) return; boost::filesystem::ofstream ofs(GetConfigPath()); if (ofs) { XMLDoc doc; GetOptionsDB().GetXML(doc); doc.WriteDoc(ofs); m_dirty = false; } else { std::cerr << UserString("UNABLE_TO_WRITE_CONFIG_XML") << std::endl; std::cerr << PathString(GetConfigPath()) << std::endl; ErrorLogger() << UserString("UNABLE_TO_WRITE_CONFIG_XML"); ErrorLogger() << PathString(GetConfigPath()); } }
void OptionsDB::SetFromFile(const boost::filesystem::path& file_path, const std::string& version) { XMLDoc doc; try { boost::filesystem::ifstream ifs(file_path); if (ifs) { doc.ReadDoc(ifs); if (version.empty() || (doc.root_node.ContainsChild("version-string") && doc.root_node.Child("version-string").Text() == version)) { GetOptionsDB().SetFromXML(doc); } } } catch (const std::exception&) { std::cerr << UserString("UNABLE_TO_READ_CONFIG_XML") << ": " << file_path << std::endl; } }
bool ParticleEffectResource::load( const char *data, int size ) { if( !Resource::load( data, size ) ) return false; XMLDoc doc; doc.parseBuffer( data, size ); if( doc.hasError() ) return raiseError( "XML parsing error" ); XMLNode rootNode = doc.getRootNode(); if( strcmp( rootNode.getName(), "ParticleEffect" ) != 0 ) return raiseError( "Not a particle effect resource file" ); if( rootNode.getAttribute( "lifeMin" ) == 0x0 ) return raiseError( "Missing ParticleConfig attribute 'lifeMin'" ); if( rootNode.getAttribute( "lifeMax" ) == 0x0 ) return raiseError( "Missing ParticleConfig attribute 'lifeMax'" ); _lifeMin = (float)atof( rootNode.getAttribute( "lifeMin" ) ); _lifeMax = (float)atof( rootNode.getAttribute( "lifeMax" ) ); XMLNode node1 = rootNode.getFirstChild( "ChannelOverLife" ); while( !node1.isEmpty() ) { if( node1.getAttribute( "channel" ) != 0x0 ) { if( _stricmp( node1.getAttribute( "channel" ), "moveVel" ) == 0 ) _moveVel.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "rotVel" ) == 0 ) _rotVel.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "drag" ) == 0 ) _drag.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "size" ) == 0 ) _size.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "colR" ) == 0 ) _colR.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "colG" ) == 0 ) _colG.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "colB" ) == 0 ) _colB.parse( node1 ); else if( _stricmp( node1.getAttribute( "channel" ), "colA" ) == 0 ) _colA.parse( node1 ); } else return raiseError( "Missing ChannelOverLife attribute 'channel'" ); node1 = node1.getNextSibling( "ChannelOverLife" ); } return true; }
bool SceneGraphResource::load( const char *data, int size ) { if( !Resource::load( data, size ) ) return false; XMLDoc doc; doc.parseBuffer( data, size ); if( doc.hasError() ) { return false; } // Parse scene nodes and load resources XMLNode rootNode = doc.getRootNode(); if( !rootNode.isEmpty() ) { parseNode( rootNode, 0x0 ); } else { return false; } return true; }
SpriteObj* Sprite_Create(const std::string& name, bool immediate) { immediate = immediate || !g_supportAsynchronousResourceLoading; SpriteResource* resource = static_cast<SpriteResource*>(Resource_Find("sprite", name)); if (resource) Resource_IncRefCount(resource); // Create sprite from XML else if (!strstr(name.c_str(), ".")) { const std::string path = name + ".sprite.xml"; XMLDoc doc; if (!doc.Load(path)) { Log::Error("Failed to load sprite resource from " + path); return NULL; } XMLNode* spriteNode = doc.AsNode()->GetFirstNode("sprite"); if (!spriteNode) { Log::Error("Failed to load sprite resource from " + path + ", reason: root node 'sprite' not found."); return NULL; } MaterialObj* material = NULL; if (const char* materialName = XMLNode_GetAttributeValue(spriteNode, "material")) { material = Material_Create(materialName); if (!material) { Log::Error("Failed to load sprite resource from " + path + ", reason: can't load material " + materialName); return NULL; } } resource = new SpriteResource(); resource->state = ResourceState_CreationInProgress; resource->name = name; Material_SetHandle(material, resource->material); Resource_IncRefCount(resource); // Load animations std::string defaultAnimationName; for (XMLNode* animNode = XMLNode_GetFirstNode(spriteNode, "animation"); animNode; animNode = XMLNode_GetNext(animNode, "animation")) { const std::string name = XMLNode_GetAttributeValue(animNode, "name"); SpriteResource::Animation& anim = map_add(resource->animations, name); anim.name = name; // Get frame time XMLNode_GetAttributeValueFloat(animNode, "frameTime", anim.frameTime, 0.1f); // Check blend mode //XMLNode_GetAttributeValueBool(animNode, "blending", anim->blendFrames); // Check if default bool isDefault; if (defaultAnimationName.empty() || (XMLNode_GetAttributeValueBool(animNode, "isDefault", isDefault) && isDefault)) defaultAnimationName = anim.name; // Load all frames and events float time = 0.0f; for (XMLNode* elemNode = XMLNode_GetFirstNode(animNode); elemNode; elemNode = XMLNode_GetNext(elemNode)) { const char* elemName = XMLNode_GetName(elemNode); if (!strcmp(elemName, "frame")) { SpriteResource::Frame& frame = vector_add(anim.frames); const char* textureName = XMLNode_GetAttributeValue(elemNode, "texture"); frame.texture.Create(textureName, immediate); if (!frame.texture.IsValid()) { Log::Error("Failed to load sprite resource from " + path + ", reason: failed to load texture " + textureName); delete resource; return NULL; } time += anim.frameTime; } else if (!strcmp(elemName, "event")) { SpriteResource::Event& ev = vector_add(anim.events); ev.time = time; ev.name = XMLNode_GetAttributeValue(elemNode, "name"); } } anim.totalTime = (float) anim.frames.size() * anim.frameTime; } resource->defaultAnimation = &resource->animations[defaultAnimationName]; SpriteResource_CheckCreated(resource); } // Create sprite from texture else { TextureObj* texture = Texture_Create(name, immediate); if (!texture) { Log::Error("Failed to create sprite resource from texture " + name); return NULL; } resource = new SpriteResource(); resource->state = ResourceState_CreationInProgress; resource->name = name; Resource_IncRefCount(resource); // Add simple animation with one animation frame SpriteResource::Animation& animation = map_add(resource->animations, resource->name); animation.frameTime = 1.0f; animation.totalTime = 1.0f; SpriteResource::Frame& frame = vector_add(animation.frames); Texture_SetHandle(texture, frame.texture); resource->defaultAnimation = &animation; SpriteResource_CheckCreated(resource); Texture_Destroy(texture); } if (!resource) return NULL; // Create sprite SpriteObj* sprite = new SpriteObj(); sprite->resource = resource; Sprite_PlayAnimation(sprite); return sprite; }
bool PipelineResource::load( const char *data, int size ) { if( !Resource::load( data, size ) ) return false; XMLDoc doc; doc.parseBuffer( data, size ); if( doc.hasError() ) return raiseError( "XML parsing error" ); XMLNode rootNode = doc.getRootNode(); if( strcmp( rootNode.getName(), "Pipeline" ) != 0 ) return raiseError( "Not a pipeline resource file" ); // Parse setup XMLNode node1 = rootNode.getFirstChild( "Setup" ); if( !node1.isEmpty() ) { XMLNode node2 = node1.getFirstChild( "RenderTarget" ); while( !node2.isEmpty() ) { if( !node2.getAttribute( "id" ) ) return raiseError( "Missing RenderTarget attribute 'id'" ); string id = node2.getAttribute( "id" ); if( !node2.getAttribute( "depthBuf" ) ) return raiseError( "Missing RenderTarget attribute 'depthBuf'" ); bool depth = false; if( _stricmp( node2.getAttribute( "depthBuf" ), "true" ) == 0 ) depth = true; if( !node2.getAttribute( "numColBufs" ) ) return raiseError( "Missing RenderTarget attribute 'numColBufs'" ); uint32 numBuffers = atoi( node2.getAttribute( "numColBufs" ) ); TextureFormats::List format = TextureFormats::BGRA8; if( node2.getAttribute( "format" ) != 0x0 ) { if( _stricmp( node2.getAttribute( "format" ), "RGBA8" ) == 0 ) format = TextureFormats::BGRA8; else if( _stricmp( node2.getAttribute( "format" ), "RGBA16F" ) == 0 ) format = TextureFormats::RGBA16F; else if( _stricmp( node2.getAttribute( "format" ), "RGBA32F" ) == 0 ) format = TextureFormats::RGBA32F; else return raiseError( "Unknown RenderTarget format" ); } int maxSamples = atoi( node2.getAttribute( "maxSamples", "0" ) ); uint32 width = atoi( node2.getAttribute( "width", "0" ) ); uint32 height = atoi( node2.getAttribute( "height", "0" ) ); float scale = (float)atof( node2.getAttribute( "scale", "1" ) ); addRenderTarget( id, depth, numBuffers, format, std::min( maxSamples, Modules::config().sampleCount ), width, height, scale ); node2 = node2.getNextSibling( "RenderTarget" ); } } // Parse commands node1 = rootNode.getFirstChild( "CommandQueue" ); if( !node1.isEmpty() ) { _stages.reserve( node1.countChildNodes( "Stage" ) ); XMLNode node2 = node1.getFirstChild( "Stage" ); while( !node2.isEmpty() ) { _stages.push_back( PipelineStage() ); string errorMsg = parseStage( node2, _stages.back() ); if( errorMsg != "" ) return raiseError( "Error in stage '" + _stages.back().id + "': " + errorMsg ); node2 = node2.getNextSibling( "Stage" ); } } // Create render targets if( !createRenderTargets() ) { return raiseError( "Failed to create render target" ); } return true; }
bool Controller::changeScene(const char* buf, uint32 size) { EngineModules::world()->clear(); XMLDoc doc; doc.parseBuffer( buf, size ); if( doc.hasError() ) { EngineModules::engineLogger()->writeError("Controller::changeScene(): scene parsing failed, %d@%s", __LINE__, __FILE__); return false; } sig_start_new_scn_.Emit(); XMLNode rootNode = doc.getRootNode(); if ( !rootNode.isEmpty() && (strcmp(rootNode.getName(), "Setup") == 0) ) { // load settings from setup file XMLNode xmlNode1 = rootNode.getFirstChild("Settings"); if (!xmlNode1.isEmpty()) { string set_xml = ""; rapidxml::print( back_inserter( set_xml ), *xmlNode1.getRapidXMLNode(), 0 ); EngineModules::engineLogger()->writeDebugInfo("Controller::changeScene(): " "loading scene specified settings"); EngineModules::engineConfig()->setExtraConfig(set_xml.c_str(), set_xml.length()); } // Parse children, and create the known component // add the created components to the root entity in the world IEntity *root_ent = EngineModules::world()->getEntity(0u); xmlNode1 = rootNode.getFirstChild(); while( !xmlNode1.isEmpty() ) { // skip node if (xmlNode1.getName() == 0x0 || _stricmp(xmlNode1.getName(), "Settings") == 0 || //_stricmp(xmlNode1.getName(), "EnginePath") == 0 || _stricmp(xmlNode1.getName(), "Editor") == 0 ) { xmlNode1 = xmlNode1.getNextSibling(); continue; } IComponent *com = manager_->createComponent(xmlNode1.getName()); if (com && root_ent->addComponent(com)) { string com_xml = ""; rapidxml::print( back_inserter( com_xml ), *xmlNode1.getRapidXMLNode(), 0 ); // set serialized data char *txt = new char[com_xml.length()]; memcpy(txt, com_xml.c_str(), com_xml.length()); com->loadFromXml(txt, com_xml.length()); delete []txt; } else { EngineModules::engineLogger()->writeWarning("Controller::changeScene():" " can not handle the node of '%s'", xmlNode1.getName()); if(com) com->Destroy(); } xmlNode1 = xmlNode1.getNextSibling(); } // Emit load scene signal for those unhandled or who need to know the gloabl information sig_load_scene_.Emit(buf, size); } else { EngineModules::engineLogger()->writeError("Controller::changeScene(): " "it's not a valid scene setup data, %d@%s", __LINE__, __FILE__); return false; } return true; }
int mainConfigOptionsSetup(const std::vector<std::string>& args) { InitDirs((args.empty() ? "" : *args.begin())); // read and process command-line arguments, if any try { // add entries in options DB that have no other obvious place GetOptionsDB().AddFlag('h', "help", UserStringNop("OPTIONS_DB_HELP"), false); GetOptionsDB().AddFlag('g', "generate-config-xml", UserStringNop("OPTIONS_DB_GENERATE_CONFIG_XML"), false); GetOptionsDB().AddFlag('f', "fullscreen", UserStringNop("OPTIONS_DB_FULLSCREEN"), STORE_FULLSCREEN_FLAG); GetOptionsDB().Add("reset-fullscreen-size", UserStringNop("OPTIONS_DB_RESET_FSSIZE"), true); GetOptionsDB().Add<bool>("fake-mode-change", UserStringNop("OPTIONS_DB_FAKE_MODE_CHANGE"), FAKE_MODE_CHANGE_FLAG); GetOptionsDB().Add<int>("fullscreen-monitor-id", UserStringNop("OPTIONS_DB_FULLSCREEN_MONITOR_ID"), 0, RangedValidator<int>(0, 5)); GetOptionsDB().AddFlag('q', "quickstart", UserStringNop("OPTIONS_DB_QUICKSTART"), false); GetOptionsDB().AddFlag("auto-quit", UserStringNop("OPTIONS_DB_AUTO_QUIT"), false); GetOptionsDB().Add<int>("auto-advance-n-turns", UserStringNop("OPTIONS_DB_AUTO_N_TURNS"), 0, RangedValidator<int>(0, 400), false); GetOptionsDB().Add<std::string>("load", UserStringNop("OPTIONS_DB_LOAD"), "", Validator<std::string>(), false); GetOptionsDB().Add("UI.sound.music-enabled", UserStringNop("OPTIONS_DB_MUSIC_ON"), true); GetOptionsDB().Add("UI.sound.enabled", UserStringNop("OPTIONS_DB_SOUND_ON"), true); GetOptionsDB().Add<std::string>("version-string", UserStringNop("OPTIONS_DB_VERSION_STRING"), FreeOrionVersionString(), Validator<std::string>(), true); GetOptionsDB().AddFlag('r', "render-simple", UserStringNop("OPTIONS_DB_RENDER_SIMPLE"), false); // Add the keyboard shortcuts Hotkey::AddOptions(GetOptionsDB()); // read config.xml and set options entries from it, if present { XMLDoc doc; try { boost::filesystem::ifstream ifs(GetConfigPath()); if (ifs) { doc.ReadDoc(ifs); // reject config files from out-of-date version if (doc.root_node.ContainsChild("version-string") && doc.root_node.Child("version-string").Text() == FreeOrionVersionString()) { GetOptionsDB().SetFromXML(doc); } } } catch (const std::exception&) { std::cerr << UserString("UNABLE_TO_READ_CONFIG_XML") << std::endl; } } // override previously-saved and default options with command line parameters and flags GetOptionsDB().SetFromCommandLine(args); // Handle the case where the resource-dir does not exist anymore // gracefully by resetting it to the standard path into the // application bundle. This may happen if a previous installed // version of FreeOrion was residing in a different directory. if (!boost::filesystem::exists(GetResourceDir()) || !boost::filesystem::exists(GetResourceDir() / "credits.xml") || !boost::filesystem::exists(GetResourceDir() / "data" / "art" / "misc" / "missing.png")) { DebugLogger() << "Resources directory from config.xml missing or does not contain expected files. Resetting to default."; GetOptionsDB().Set<std::string>("resource-dir", ""); // double-check that resetting actually fixed things... if (!boost::filesystem::exists(GetResourceDir()) || !boost::filesystem::exists(GetResourceDir() / "credits.xml") || !boost::filesystem::exists(GetResourceDir() / "data" / "art" / "misc" / "missing.png")) { DebugLogger() << "Default Resources directory missing or does not contain expected files. Cannot start game."; throw std::runtime_error("Unable to load game resources at default location: " + PathString(GetResourceDir()) + " : Install may be broken."); } } // did the player request generation of config.xml, saving the default (or current) options to disk? if (GetOptionsDB().Get<bool>("generate-config-xml")) { try { GetOptionsDB().Commit(); } catch (const std::exception&) { std::cerr << UserString("UNABLE_TO_WRITE_CONFIG_XML") << std::endl; } } if (GetOptionsDB().Get<bool>("render-simple")) { GetOptionsDB().Set<bool>("UI.galaxy-gas-background",false); GetOptionsDB().Set<bool>("UI.galaxy-starfields", false); GetOptionsDB().Set<bool>("show-fps", true); } } catch (const std::invalid_argument& e) { std::cerr << "main() caught exception(std::invalid_argument): " << e.what() << std::endl; boost::this_thread::sleep(boost::posix_time::seconds(3)); return 1; } catch (const std::runtime_error& e) { std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl; boost::this_thread::sleep(boost::posix_time::seconds(3)); return 1; } catch (const std::exception& e) { std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl; boost::this_thread::sleep(boost::posix_time::seconds(3)); return 1; } catch (...) { std::cerr << "main() caught unknown exception." << std::endl; return 1; } return 0; }
bool MaterialResource::load( const char *data, int size ) { if( !Resource::load( data, size ) ) return false; XMLDoc doc; doc.parseBuffer( data, size ); if( doc.hasError() ) return raiseError( "XML parsing error" ); XMLNode rootNode = doc.getRootNode(); if( strcmp( rootNode.getName(), "Material" ) != 0 ) return raiseError( "Not a material resource file" ); // Class _class = rootNode.getAttribute( "class", "" ); // Link if( strcmp( rootNode.getAttribute( "link", "" ), "" ) != 0 ) { uint32 mat = Modules::resMan().addResource( ResourceTypes::Material, rootNode.getAttribute( "link" ), 0, false ); _matLink = (MaterialResource *)Modules::resMan().resolveResHandle( mat ); if( _matLink == this ) return raiseError( "Illegal self link in material, causing infinite link loop" ); } // Shader Flags XMLNode node1 = rootNode.getFirstChild( "ShaderFlag" ); while( !node1.isEmpty() ) { if( node1.getAttribute( "name" ) == 0x0 ) return raiseError( "Missing ShaderFlag attribute 'name'" ); _shaderFlags.push_back( node1.getAttribute( "name" ) ); node1 = node1.getNextSibling( "ShaderFlag" ); } // Shader node1 = rootNode.getFirstChild( "Shader" ); if( !node1.isEmpty() ) { if( node1.getAttribute( "source" ) == 0x0 ) return raiseError( "Missing Shader attribute 'source'" ); uint32 shader = Modules::resMan().addResource( ResourceTypes::Shader, node1.getAttribute( "source" ), 0, false ); _shaderRes = (ShaderResource *)Modules::resMan().resolveResHandle( shader ); _combMask = ShaderResource::calcCombMask( _shaderFlags ); _shaderRes->preLoadCombination( _combMask ); } // Texture samplers node1 = rootNode.getFirstChild( "Sampler" ); while( !node1.isEmpty() ) { if( node1.getAttribute( "name" ) == 0x0 ) return raiseError( "Missing Sampler attribute 'name'" ); if( node1.getAttribute( "map" ) == 0x0 ) return raiseError( "Missing Sampler attribute 'map'" ); MatSampler sampler; sampler.name = node1.getAttribute( "name" ); ResHandle texMap; uint32 flags = 0; if( !Modules::config().loadTextures ) flags |= ResourceFlags::NoQuery; if( _stricmp( node1.getAttribute( "allowCompression", "true" ), "false" ) == 0 || _stricmp( node1.getAttribute( "allowCompression", "1" ), "0" ) == 0 ) flags |= ResourceFlags::NoTexCompression; if( _stricmp( node1.getAttribute( "mipmaps", "true" ), "false" ) == 0 || _stricmp( node1.getAttribute( "mipmaps", "1" ), "0" ) == 0 ) flags |= ResourceFlags::NoTexMipmaps; if( _stricmp( node1.getAttribute( "sRGB", "false" ), "true" ) == 0 || _stricmp( node1.getAttribute( "sRGB", "0" ), "1" ) == 0 ) flags |= ResourceFlags::TexSRGB; texMap = Modules::resMan().addResource( ResourceTypes::Texture, node1.getAttribute( "map" ), flags, false ); sampler.texRes = (TextureResource *)Modules::resMan().resolveResHandle( texMap ); _samplers.push_back( sampler ); node1 = node1.getNextSibling( "Sampler" ); } // Vector uniforms node1 = rootNode.getFirstChild( "Uniform" ); while( !node1.isEmpty() ) { if( node1.getAttribute( "name" ) == 0x0 ) return raiseError( "Missing Uniform attribute 'name'" ); MatUniform uniform; uniform.name = node1.getAttribute( "name" ); uniform.values[0] = (float)atof( node1.getAttribute( "a", "0" ) ); uniform.values[1] = (float)atof( node1.getAttribute( "b", "0" ) ); uniform.values[2] = (float)atof( node1.getAttribute( "c", "0" ) ); uniform.values[3] = (float)atof( node1.getAttribute( "d", "0" ) ); _uniforms.push_back( uniform ); node1 = node1.getNextSibling( "Uniform" ); } // Data (compute/texture) buffers node1 = rootNode.getFirstChild( "DataBuffer" ); while ( !node1.isEmpty() ) { if ( node1.getAttribute( "name" ) == 0x0 ) return raiseError( "Missing DataBuffer attribute 'name'" ); if ( node1.getAttribute( "source" ) == 0x0 ) return raiseError( "Missing DataBuffer attribute 'source'" ); MatBuffer buf; buf.name = node1.getAttribute( "name" ); uint32 compBuffer = Modules::resMan().addResource( ResourceTypes::ComputeBuffer, node1.getAttribute( "source" ), 0, false ); buf.compBufRes = ( ComputeBufferResource * ) Modules::resMan().resolveResHandle( compBuffer ); _buffers.push_back( buf ); node1 = node1.getNextSibling( "DataBuffer" ); } return true; }
int mainConfigOptionsSetup(int argc, char* argv[]) { InitDirs(argv[0]); // read and process command-line arguments, if any try { // add entries in options DB that have no other obvious place GetOptionsDB().AddFlag('h', "help", "OPTIONS_DB_HELP", false); GetOptionsDB().AddFlag('g', "generate-config-xml", "OPTIONS_DB_GENERATE_CONFIG_XML", false); GetOptionsDB().AddFlag('f', "fullscreen", "OPTIONS_DB_FULLSCREEN", STORE_FULLSCREEN_FLAG); GetOptionsDB().Add("reset-fullscreen-size", "OPTIONS_DB_RESET_FSSIZE", true); GetOptionsDB().AddFlag('q', "quickstart", "OPTIONS_DB_QUICKSTART", false); GetOptionsDB().AddFlag("auto-advance-first-turn", "OPTIONS_DB_AUTO_FIRST_TURN", false); GetOptionsDB().Add<std::string>("load", "OPTIONS_DB_LOAD", "", Validator<std::string>(),false); GetOptionsDB().Add("UI.sound.music-enabled", "OPTIONS_DB_MUSIC_ON", true); GetOptionsDB().Add("UI.sound.enabled", "OPTIONS_DB_SOUND_ON", true); GetOptionsDB().Add<std::string>("version-string", "OPTIONS_DB_VERSION_STRING", FreeOrionVersionString(), Validator<std::string>(),true); // read config.xml and set options entries from it, if present { XMLDoc doc; try { boost::filesystem::ifstream ifs(GetConfigPath()); if (ifs) { doc.ReadDoc(ifs); // reject config files from out-of-date version if (doc.root_node.ContainsChild("version-string") && doc.root_node.Child("version-string").Text() == FreeOrionVersionString()) { GetOptionsDB().SetFromXML(doc); } } } catch (const std::exception&) { std::cerr << UserString("UNABLE_TO_READ_CONFIG_XML") << std::endl; } } // override previously-saved and default options with command line parameters and flags GetOptionsDB().SetFromCommandLine(argc, argv); // Handle the case where the resource-dir does not exist anymore // gracefully by resetting it to the standard path into the // application bundle. This may happen if a previous installed // version of FreeOrion was residing in a different directory. if (!boost::filesystem::exists(GetResourceDir())) GetOptionsDB().Set<std::string>("resource-dir", ""); // did the player request generation of config.xml, saving the default (or current) options to disk? if (GetOptionsDB().Get<bool>("generate-config-xml")) { try { boost::filesystem::ofstream ofs(GetConfigPath()); if (ofs) { GetOptionsDB().GetXML().WriteDoc(ofs); } else { std::cerr << UserString("UNABLE_TO_WRITE_CONFIG_XML") << std::endl; std::cerr << GetConfigPath().string() << std::endl; } } catch (const std::exception&) { std::cerr << UserString("UNABLE_TO_WRITE_CONFIG_XML") << std::endl; } } } catch (const std::invalid_argument& e) { std::cerr << "main() caught exception(std::invalid_argument): " << e.what() << std::endl; Sleep(3000); return 1; } catch (const std::runtime_error& e) { std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl; Sleep(3000); return 1; } catch (const std::exception& e) { std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl; Sleep(3000); return 1; } catch (...) { std::cerr << "main() caught unknown exception." << std::endl; return 1; } return 0; }
int main(int argc, char* argv[]) { InitDirs(argv[0]); std::vector<std::string> args; for (int i = 0; i < argc; ++i) args.push_back(argv[i]); #else int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) { // copy UTF-16 command line arguments to UTF-8 vector std::vector<std::string> args; for (int i = 0; i < argc; ++i) { std::wstring argi16(argv[i]); std::string argi8; utf8::utf16to8(argi16.begin(), argi16.end(), std::back_inserter(argi8)); args.push_back(argi8); } InitDirs((args.empty() ? "" : *args.begin())); #endif try { GetOptionsDB().AddFlag('h', "help", "Print this help message."); // read config.xml and set options entries from it, if present XMLDoc doc; { boost::filesystem::ifstream ifs(GetConfigPath()); if (ifs) { doc.ReadDoc(ifs); GetOptionsDB().SetFromXML(doc); } } GetOptionsDB().SetFromCommandLine(args); if (GetOptionsDB().Get<bool>("help")) { GetOptionsDB().GetUsage(std::cerr); return 0; } parse::init(); ServerApp g_app; g_app(); // Calls ServerApp::Run() to run app (intialization and main process loop) } catch (const std::invalid_argument& e) { Logger().errorStream() << "main() caught exception(std::invalid_arg): " << e.what(); std::cerr << "main() caught exception(std::invalid_arg): " << e.what() << std::endl; return 1; } catch (const std::runtime_error& e) { Logger().errorStream() << "main() caught exception(std::runtime_error): " << e.what(); std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl; return 1; } catch (const std::exception& e) { Logger().errorStream() << "main() caught exception(std::exception): " << e.what(); std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl; return 1; } catch (...) { Logger().errorStream() << "main() caught unknown exception."; std::cerr << "main() caught unknown exception." << std::endl; return 1; } return 0; }
bool ColladaDocument::parseFile( const string &fileName ) { // Parse Collada file XMLDoc doc; if( !doc.parseFile( fileName.c_str() ) ) { log( "Error: file '" + fileName + "' not found" ); return false; } if( doc.hasError() ) { log( "Error: XML parsing error" ); return false; } XMLNode rootNode = doc.getRootNode(); if( strcmp( rootNode.getName(), "COLLADA" ) != 0 ) { log( "Error: not a COLLADA document" ); return false; } if( strcmp( rootNode.getAttribute( "version", "" ), "1.4.0") != 0 && strcmp( rootNode.getAttribute( "version", "" ), "1.4.1") != 0 ) { log( "Error: Unsupported Collada version" ); return false; } // Parse asset XMLNode node1 = rootNode.getFirstChild( "asset" ); if( !node1.isEmpty() ) { XMLNode node2 = node1.getFirstChild( "up_axis" ); if( !node2.isEmpty() && node2.getText() != 0x0 ) { if( strcmp( node2.getText(), "Y_UP" ) == 0 ) y_up = true; else if( strcmp( node2.getText(), "Z_UP" ) == 0 ) y_up = false; else log( "Warning: Unsupported up-axis" ); } } // Parse libraries libImages.parse( rootNode ); libEffects.parse( rootNode ); // Assign images for( unsigned int i = 0; i < libEffects.effects.size(); ++i ) { DaeEffect &effect = *libEffects.effects[i]; if( effect.diffuseMapId != "" ) { effect.diffuseMap = libImages.findImage( effect.diffuseMapId ); if( effect.diffuseMap == 0x0 ) log( "Warning: Image '" + effect.diffuseMapId + "' not found" ); } } libMaterials.parse( rootNode ); // Assign effects for( unsigned int i = 0; i < libMaterials.materials.size(); ++i ) { DaeMaterial &material = *libMaterials.materials[i]; material.effect = libEffects.findEffect( material.effectId ); if( material.effect == 0x0 ) log( "Warning: Effect '" + material.effectId + "' not found" ); } libGeometries.parse( rootNode ); libControllers.parse( rootNode ); libAnimations.parse( rootNode ); libVisScenes.parse( rootNode ); libNodes.parse( rootNode ); // Visual scene instance bool foundScene = false; node1 = rootNode.getFirstChild( "scene" ); if( !node1.isEmpty() ) { XMLNode node2 = node1.getFirstChild( "instance_visual_scene" ); if( !node2.isEmpty() ) { string sceneId = node2.getAttribute( "url", "" ); removeGate( sceneId ); scene = libVisScenes.findVisualScene( sceneId ); if( scene != 0x0 ) foundScene = true; node2.getFirstChild( "instance_visual_scene" ); if( !node2.getNextSibling( "instance_visual_scene" ).isEmpty() ) log( "Warning: Found more than one scene instance; ignoring following instances" ); } } if( !foundScene ) log( "Warning: No scene instance found" ); return true; }
Drumkit* Legacy::load_drumkit( const QString& dk_path ) { if ( version_older_than( 0, 9, 8 ) ) { ERRORLOG( QString( "this code should not be used anymore, it belongs to 0.9.6" ) ); } else { ERRORLOG( QString( "loading drumkit with legacy code" ) ); } XMLDoc doc; if( !doc.read( dk_path ) ) { return 0; } XMLNode root = doc.firstChildElement( "drumkit_info" ); if ( root.isNull() ) { ERRORLOG( "drumkit_info node not found" ); return 0; } QString drumkit_name = root.read_string( "name", "", false, false ); if ( drumkit_name.isEmpty() ) { ERRORLOG( "Drumkit has no name, abort" ); return 0; } Drumkit* drumkit = new Drumkit(); drumkit->set_path( dk_path.left( dk_path.lastIndexOf( "/" ) ) ); drumkit->set_name( drumkit_name ); drumkit->set_author( root.read_string( "author", "undefined author" ) ); drumkit->set_info( root.read_string( "info", "defaultInfo" ) ); drumkit->set_license( root.read_string( "license", "undefined license" ) ); XMLNode instruments_node = root.firstChildElement( "instrumentList" ); if ( instruments_node.isNull() ) { WARNINGLOG( "instrumentList node not found" ); drumkit->set_instruments( new InstrumentList() ); } else { InstrumentList* instruments = new InstrumentList(); XMLNode instrument_node = instruments_node.firstChildElement( "instrument" ); int count = 0; while ( !instrument_node.isNull() ) { count++; if ( count > MAX_INSTRUMENTS ) { ERRORLOG( QString( "instrument count >= %2, stop reading instruments" ).arg( MAX_INSTRUMENTS ) ); break; } Instrument* instrument = 0; int id = instrument_node.read_int( "id", EMPTY_INSTR_ID, false, false ); if ( id!=EMPTY_INSTR_ID ) { instrument = new Instrument( id, instrument_node.read_string( "name", "" ), 0 ); instrument->set_drumkit_name( drumkit_name ); instrument->set_volume( instrument_node.read_float( "volume", 1.0f ) ); instrument->set_muted( instrument_node.read_bool( "isMuted", false ) ); instrument->set_pan_l( instrument_node.read_float( "pan_L", 1.0f ) ); instrument->set_pan_r( instrument_node.read_float( "pan_R", 1.0f ) ); // may not exist, but can't be empty instrument->set_filter_active( instrument_node.read_bool( "filterActive", true, false ) ); instrument->set_filter_cutoff( instrument_node.read_float( "filterCutoff", 1.0f, true, false ) ); instrument->set_filter_resonance( instrument_node.read_float( "filterResonance", 0.0f, true, false ) ); instrument->set_random_pitch_factor( instrument_node.read_float( "randomPitchFactor", 0.0f, true, false ) ); float attack = instrument_node.read_float( "Attack", 0.0f, true, false ); float decay = instrument_node.read_float( "Decay", 0.0f, true, false ); float sustain = instrument_node.read_float( "Sustain", 1.0f, true, false ); float release = instrument_node.read_float( "Release", 1000.0f, true, false ); instrument->set_adsr( new ADSR( attack, decay, sustain, release ) ); instrument->set_gain( instrument_node.read_float( "gain", 1.0f, true, false ) ); instrument->set_mute_group( instrument_node.read_int( "muteGroup", -1, true, false ) ); instrument->set_midi_out_channel( instrument_node.read_int( "midiOutChannel", -1, true, false ) ); instrument->set_midi_out_note( instrument_node.read_int( "midiOutNote", MIDI_MIDDLE_C, true, false ) ); instrument->set_stop_notes( instrument_node.read_bool( "isStopNote", true ,false ) ); instrument->set_hihat_grp( instrument_node.read_int( "isHihat", -1, true ) ); instrument->set_lower_cc( instrument_node.read_int( "lower_cc", 0, true ) ); instrument->set_higher_cc( instrument_node.read_int( "higher_cc", 127, true ) ); for ( int i=0; i<MAX_FX; i++ ) { instrument->set_fx_level( instrument_node.read_float( QString( "FX%1Level" ).arg( i+1 ), 0.0 ), i ); } QDomNode filename_node = instrument_node.firstChildElement( "filename" ); if ( !filename_node.isNull() ) { DEBUGLOG( "Using back compatibility code. filename node found" ); QString sFilename = instrument_node.read_string( "filename", "" ); if( sFilename.isEmpty() ) { ERRORLOG( "filename back compability node is empty" ); } else { Sample* sample = new Sample( dk_path+"/"+sFilename ); bool p_foundMainCompo = false; for (std::vector<DrumkitComponent*>::iterator it = drumkit->get_components()->begin() ; it != drumkit->get_components()->end(); ++it) { DrumkitComponent* existing_compo = *it; if( existing_compo->get_name().compare("Main") == 0) { p_foundMainCompo = true; break; } } if ( !p_foundMainCompo ) { DrumkitComponent* dmCompo = new DrumkitComponent( 0, "Main" ); drumkit->get_components()->push_back(dmCompo); } InstrumentComponent* component = new InstrumentComponent( 0 ); InstrumentLayer* layer = new InstrumentLayer( sample ); component->set_layer( layer, 0 ); instrument->get_components()->push_back( component ); } } else { int n = 0; bool p_foundMainCompo = false; for (std::vector<DrumkitComponent*>::iterator it = drumkit->get_components()->begin() ; it != drumkit->get_components()->end(); ++it) { DrumkitComponent* existing_compo = *it; if( existing_compo->get_name().compare("Main") == 0) { p_foundMainCompo = true; break; } } if ( !p_foundMainCompo ) { DrumkitComponent* dmCompo = new DrumkitComponent( 0, "Main" ); drumkit->get_components()->push_back(dmCompo); } InstrumentComponent* component = new InstrumentComponent( 0 ); XMLNode layer_node = instrument_node.firstChildElement( "layer" ); while ( !layer_node.isNull() ) { if ( n >= MAX_LAYERS ) { ERRORLOG( QString( "n >= MAX_LAYERS (%1)" ).arg( MAX_LAYERS ) ); break; } Sample* sample = new Sample( dk_path+"/"+layer_node.read_string( "filename", "" ) ); InstrumentLayer* layer = new InstrumentLayer( sample ); layer->set_start_velocity( layer_node.read_float( "min", 0.0 ) ); layer->set_end_velocity( layer_node.read_float( "max", 1.0 ) ); layer->set_gain( layer_node.read_float( "gain", 1.0, true, false ) ); layer->set_pitch( layer_node.read_float( "pitch", 0.0, true, false ) ); component->set_layer( layer, n ); n++; layer_node = layer_node.nextSiblingElement( "layer" ); } instrument->get_components()->push_back( component ); } } if( instrument ) { ( *instruments ) << instrument; } else { ERRORLOG( QString( "Empty ID for instrument %1. The drumkit is corrupted. Skipping instrument" ).arg( count ) ); count--; } instrument_node = instrument_node.nextSiblingElement( "instrument" ); } drumkit->set_instruments( instruments ); } return drumkit; }