Node * BehaviorTreeLoader:: CreateBehaviorTree(const std::string & btName) const { Node * pBehaviorTreeRoot = nullptr; for (auto pIt = _XMLDoc.FirstChildElement()->FirstChildElement(); pIt != nullptr; pIt = pIt->NextSiblingElement()) { if (strcmp(pIt->Value(), btName.c_str()) == 0) { auto pChild = pIt->FirstChildElement(); if (pChild == nullptr) continue; std::string name; pChild->QueryStringAttribute(DEFAULT_NODE_ATTRIBUTE, &name); pBehaviorTreeRoot = _NodeFactory.Create(name); if (pChild->NextSibling() != nullptr) std::cerr << "Warning, Behavior Tree [" << btName << "] has more than One Root!" << std::endl; CreateBehaviorTreeNode(pChild->FirstChildElement(), pBehaviorTreeRoot, pChild->Value()); break; } } if (!pBehaviorTreeRoot) std::cerr << "BehaviorTreeLoader::Cannot create BehaviorTree, " << btName << "!" << std::endl; return pBehaviorTreeRoot; }
void UMcf::parseUpdateXml(const XML::gcXMLDocument &xmlDocument) { auto uNode = xmlDocument.GetRoot("appupdate"); if (!uNode.IsValid()) return; auto mcfNode = uNode.FirstChildElement("mcf"); if (!mcfNode.IsValid()) return; const std::string appid = mcfNode.GetAtt("appid"); if (!appid.empty()) m_iAppId = Safe::atoi(appid.c_str()); else m_iAppId = 100; const std::string build = mcfNode.GetAtt("build"); if (!build.empty()) m_iAppBuild = Safe::atoi(build.c_str()); else m_iAppBuild = 0; mcfNode.GetChild("url", m_szUrl); parseXml(mcfNode.FirstChildElement("files")); }
const TiXmlElement* TiXmlNode::SearchFirstChildElement( const char * _value ) const { const char *pCur = NULL; const char *pNext = NULL; char buf[65]; const TiXmlElement* node = NULL; if(_value == NULL) { return NULL; } if(_value[0] == '/') { pCur = _value + 1; } else { pCur = _value; } do { pNext = strchr(pCur,'/'); if((pNext == NULL) || (pNext - pCur > 64)) { // �Ѿ������ڵ㣬���߳����?Χ��ֱ�ӷ��� if(node == NULL) { return FirstChildElement(pCur); } else { return node->FirstChildElement( pCur ); } } else if(pNext - pCur == 0) { // ��������'/',����node return node; } else { memcpy(buf,pCur,pNext - pCur); buf[pNext - pCur] = 0; if(node == NULL) { node = FirstChildElement(buf); } else { node = node->FirstChildElement( buf ); } } pCur = pNext + 1; }while((*pCur != 0) && (node != NULL)); return node; }
bool LanguageManager::loadFromFile(const char* file) { XML::gcXMLDocument doc(file); if (!doc.IsValid()) return false; auto cNode = doc.GetRoot("lang"); if (!cNode.IsValid()) return false; auto parseString = [this](const XML::gcXMLElement &xmlChild) { const std::string name = xmlChild.GetAtt("name"); const std::string val = xmlChild.GetText(); if (name.empty() || val.empty()) return; LanguageString* temp = dynamic_cast<LanguageString*>(this->BaseManager::findItem(name.c_str())); if (!temp) { temp = new LanguageString(name.c_str()); this->addItem( temp ); } #ifdef DESURA_OFFICIAL_BUILD temp->ustr = val; #else std::vector<std::string> res; UTIL::STRING::tokenize(gcString(val), res, "Desura"); gcString out; for (size_t x=0; x<res.size(); x++) { out += res[x]; if (x+1 != res.size()) out += PRODUCT_NAME; } temp->ustr = out; #endif }; #ifdef WIN32 const char* szPlatform = "windows"; #else const char* szPlatform = "linux"; #endif cNode.FirstChildElement("strings").for_each_child("str", parseString); cNode.FirstChildElement(szPlatform).for_each_child("str", parseString); return true; }
void Theme::parseFile(const char* file) { XML::gcXMLDocument doc(file); if (!doc.IsValid()) throw gcException(ERR_BADXML); auto mcNode = doc.GetRoot("theme"); if (!mcNode.IsValid()) throw gcException(ERR_XML_NOPRIMENODE); mcNode.GetChild("creator", m_szDev); mcNode.GetChild("name", m_szPName); UTIL::FS::Path path(file, "", true); auto iNode = mcNode.FirstChildElement("images"); if (iNode.IsValid()) LoadImages(path, iNode); auto wNode = mcNode.FirstChildElement("web"); if (wNode.IsValid()) LoadWeb(path, wNode); auto sNode = mcNode.FirstChildElement("sprites"); if (sNode.IsValid()) LoadSprites(sNode); auto cNode = mcNode.FirstChildElement("controls"); if (cNode.IsValid()) LoadControls(cNode); auto control = ControlList::findItem("default"); if (!control) { control = gcRefPtr<ThemeControlInfo>::create("default"); auto col1 = gcRefPtr<ThemeColorInfo>::create("bg"); auto col2 = gcRefPtr<ThemeColorInfo>::create("fg"); col1->color = Color(0); col2->color = Color(0xFFFFFF); control->add(col1); control->add(col2); ControlList::addItem( control ); } }
DialogueHelper* DialogueHelper::parseWithFile(const char *xmlFileName){ DialogueHelper* dialogueHelper = new DialogueHelper(); //读取文本 auto xmlFileUrl = String::createWithFormat("data/dialogue/%s.xml", xmlFileName); auto doc = new tinyxml2::XMLDocument(); log("is loading %s", xmlFileUrl->getCString()); doc->LoadFile(xmlFileUrl->getCString()); //解析 auto dialogues = doc->RootElement(); for (auto dialogue = dialogues->FirstChildElement("dialogue"); dialogue != NULL; dialogue = dialogue->NextSiblingElement()){ //循环添加序列组 std::vector<DialogueData> dialogueData;//对话序列组对象 int dialogueId = std::atoi(dialogue->Attribute("id"));//该对话序列组对象 const char* triggerPos = dialogue->Attribute("triggerPos");//暂时不保存 if (dialogueId == 0){ continue;//无id标识,跳过循环 } for (auto content = dialogue->FirstChildElement(); content; content = content->NextSiblingElement()){ //循环添加对话序列 DialogueData data;//直接使用对象。由系统维护生命周期防止内存泄露 std::string contentType = content->Name(); if (contentType == "string"){ data.type = DialogueType::string; data.speakerName = content->Attribute("name"); data.content = content->GetText(); } else if (contentType == "options") { data.type = DialogueType::option; std::vector<Option> options; for (auto option = content->FirstChildElement(); option; option = option->NextSiblingElement()){ Option _option; _option.text = option->GetText(); _option.toId = option->Attribute("toId") != NULL ? (int)option->Attribute("toId") : -1; options.push_back(_option); } data.options = options; } dialogueData.push_back(data); log("loading text: %s", content->GetText()); } dialogueHelper->_dialogueList[dialogueId] = dialogueData;//重复id后面会覆盖前面的 } return dialogueHelper; }
void ResourceLoader::loadResources() { //Load the xml file. tinyxml2::XMLDocument xmlDoc; xmlDoc.LoadFile(pimpl->m_ResourceListPath.c_str()); const auto rootElement = xmlDoc.RootElement(); assert(rootElement && "ResourceLoader::loadResource() failed to load xml file."); //Load various resources. //Textures and sounds must be loaded firstly because other resources may rely on them. pimpl->loadTextures(rootElement->FirstChildElement("TextureListPath")->Attribute("Value")); pimpl->loadTileDatas(rootElement->FirstChildElement("TileDataListPath")->Attribute("Value")); pimpl->loadUnitDatas(rootElement->FirstChildElement("UnitDataListPath")->Attribute("Value")); }
void Picking::displayIcon() { auto fileU = FileUtils::getInstance(); auto fileContent = fileU->getStringFromFile("data/animData.xml"); UserDefault* def = UserDefault::getInstance(); int key = def->getIntegerForKey(SaveDataKey[n_DataKeyNum::eMonsterData01 + m_battleNum].c_str()); doc.Parse(fileContent.c_str()); fileContent = fileU->getStringFromFile("data/monsterData.xml"); mData.Parse(fileContent.c_str()); m_HP = atoi(mData.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str())->FirstChildElement("HP")->GetText()); auto sprite = doc.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str()); key = def->getIntegerForKey(SaveDataKey[n_DataKeyNum::eEnemyMonster01 + m_battleNum].c_str()); m_enemyHP = atoi(mData.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str())->FirstChildElement("HP")->GetText()); //cut image to fit inside frame m_iconSprite = Sprite::create(sprite->FirstChildElement("spriteList")->FirstChildElement("animation")->FirstChildElement("stand")->GetText()); m_iconSprite->setScale(m_Mag * 1.5); m_iconSprite->setPosition(Vec2((m_visibleSize.width / 6) * 1.8, m_visibleSize.height / 2)); m_instance->addChild(m_iconSprite); }
void AttackLayer::nextMap(Ref * sender){ Bullets::getInstence()->deleteEnemyBulletsAll(); Bullets::getInstence()->deleteRoleBulletsAll(); SelectRole::getInstence()->EnemyClearaAll(); GameAttackScene *scene = dynamic_cast<GameAttackScene *>(Director::getInstance()->getRunningScene()); EnemyLayer *enemyLayer = dynamic_cast<EnemyLayer *>(scene->getEnemyLayer()); std::string imageName = enemyLayer->ReadEnemyXml(); if(imageName == "over"){ auto strFileName = FileUtils::getInstance()->getStringFromFile("MainRole.xml"); tinyxml2::XMLDocument doc; doc.Parse(strFileName.c_str()); auto rootElement = doc.RootElement(); auto element = rootElement->FirstChildElement(); element->SetAttribute("LEVEL", RoleAmrature::getInstance()->getRoleExp() / 1000 + 1); element->SetAttribute("EXP", RoleAmrature::getInstance()->getRoleExp()); element->SetAttribute("MONEY", RoleAmrature::getInstance()->getRoleMoney()); doc.SaveFile(strFileName.c_str()); Bullets::getInstence()->deleteEnemyBulletsAll(); Bullets::getInstence()->deleteRoleBulletsAll(); SelectRole::getInstence()->EnemyClearaAll(); SelectRole::getInstence()->RoleClearAll(); VectorItemImage::getInstance()->reset(); ChangeAttackScene *scene = ChangeAttackScene::create(); Director::getInstance()->replaceScene(scene); return; } setBg(imageName); for(int i = 0; i < SelectRole::getInstence()->getRoleArmatures().size();i++){ auto role = SelectRole::getInstence()->getRoleArmatures().at(i); role->setPositionX(-50 - i*-50); role->setArmaturestatic(moveStatic); } nextitem->setVisible(false); }
void Picking::displayEnemy() { auto fileU = FileUtils::getInstance(); auto fileContent = fileU->getStringFromFile("data/animData.xml"); doc.Parse(fileContent.c_str()); UserDefault* def = UserDefault::getInstance(); enemyMonster = def->getIntegerForKey(SaveDataKey[(n_DataKeyNum::eEnemyMonster01) + m_battleNum].c_str()); auto sprite = doc.FirstChildElement()->FirstChildElement(MonsterNameData[enemyMonster].c_str()); /* //CARD on the center m_enemySpecial = Sprite::create("img/UI/battle/UI_B_12.png"); m_enemySpecial->setScale(m_Mag * 0.8); m_enemySpecial->setPosition(Vec2(m_visibleSize.width / 2, m_visibleSize.height - m_enemySpecial->getBoundingBox().getMaxY() * 0.75)); m_instance->addChild(m_enemySpecial); m_enemySpecial->setVisible(false); //hidden for animation */ //Monster Sprite number 2 m_enemyCard = Sprite::create(sprite->FirstChildElement("spriteList")->FirstChildElement("animation")->FirstChildElement("stand")->GetText()); m_enemyCard->setScale(m_Mag * 1.5); m_enemyCard->setPosition(Vec2((m_visibleSize.width / 6) * 4.5, m_visibleSize.height /2)); m_instance->addChild(m_enemyCard); }
std::vector<Frame> developFrame(XMLElement* xml) { Frame tmpf; std::vector<Frame> tmp; // this is the xml elements first child. It will only be the <frame> tag auto framexml = xml->FirstChildElement(); while (framexml) { // this will always be frame. but if it isn't we don't wanna crash the game std::string defframe = framexml->Name(); if (defframe == "frame") { tmpf.clear(); // the xml element to parse each src of the frames auto sxml = framexml->FirstChildElement(); while (sxml) { std::string sname = sxml->Name(); if (sname == "src") { tmpf.push_back(std::make_pair(SpriteData(sxml->GetText(), vec2(0,0)), vec2(0,0))); } sxml = sxml->NextSiblingElement(); } tmp.push_back(tmpf); } // if it's not a frame we don't care // parse next frame framexml = framexml->NextSiblingElement(); } return tmp; }
Map* Map::buildFromXML(tinyxml2::XMLElement& mapXML, Logger& l) { std::vector<WorldBlock*> blocks; blocks_map idMap; WorldBlock::Factory fact; //reading Blocks l.dev("Loading Blocks..."); auto xmlBlocks = mapXML.FirstChildElement("Blocks"); l.throwIfTrue(xmlBlocks == nullptr, "<Blocks> element not found in <Map>!"); auto xmlBlock = xmlBlocks->FirstChildElement("WorldBlock"); while (xmlBlock != nullptr) { try { auto block = fact.buildFromXML(*xmlBlock, l); blocks.push_back(block); idMap.insert(std::make_pair(block->getID(), block)); } catch (const LoggedException&) { l.critS << "@up: WorldBlock ID: " << xmlBlock->Attribute("id") << "; up to that moment " << blocks.size() << " WorldBlocks were read." << l.end; } xmlBlock = xmlBlock->NextSiblingElement(); } l.fullS << "Loaded " << blocks.size() << " blocks" << l.end; l.dev("Blocks loaded. Loading Trains..."); //reading TrainList std::vector<Train*> trains; auto xmlTrains = mapXML.FirstChildElement("TrainList"); l.throwIfTrue(xmlTrains == nullptr, "<TrainList> element not found in <Map>!"); auto xmlTrain = xmlTrains->FirstChildElement("Train"); while (xmlTrain != nullptr) { try { auto train = Train::buildFromXML(*xmlTrain, idMap, l); trains.push_back(train); } catch (const LoggedException&) { l.critS << "@up: up to that moment " << trains.size() << " Trains were read." << l.end; } xmlTrain = xmlTrain->NextSiblingElement(); } l.dev("Trains loaded. Map will be created."); // setting up Map* map = new Map(blocks, trains, idMap); return map; }
bool TmxObjectGroup::parseElement(void* p) { _x = 0; _y = 0; _width = 0; _height = 0; _opacity = 1.0f; _visible = true; _name = ""; _properties.clear(); _objects.clear(); auto element = static_cast<tinyxml2::XMLElement*>(p); if(!element) { return false; } if(element->Attribute("name")) { _name = element->Attribute("name"); } element->QueryIntAttribute("x", &_x); element->QueryIntAttribute("y", &_y); element->QueryIntAttribute("width", &_width); element->QueryIntAttribute("height", &_height); element->QueryFloatAttribute("opacity", &_opacity); element->QueryBoolAttribute("visible", &_visible); auto propertiesElement = element->FirstChildElement("properties"); _properties.parseElement(propertiesElement); auto objectElement = element->FirstChildElement("object"); while(objectElement) { _objects.push_back(TmxObject()); _objects.back().parseElement(objectElement); objectElement = objectElement->NextSiblingElement("object"); } return true; }
void ResourceLoader::ResourceLoaderImpl::loadUnitDatas(const char * xmlPath) { //Load the xml file. tinyxml2::XMLDocument xmlDoc; xmlDoc.LoadFile(xmlPath); const auto rootElement = xmlDoc.RootElement(); assert(rootElement && "ResourceLoaderImpl::loadUnitDatas() failed to load xml file."); //Iterate through the list and load each UnitData. const auto listElement = rootElement->FirstChildElement("List"); for (auto tileDataElement = listElement->FirstChildElement("UnitDataPath"); tileDataElement; tileDataElement = tileDataElement->NextSiblingElement()) { auto unitData = createUnitDataFromXML(tileDataElement->Attribute("Value")); assert(m_UnitDatas.find(unitData->getType()) == m_UnitDatas.end() && "ResourceLoaderImpl::loadUnitDatas() load two UnitData with a same ID."); m_UnitDatas.emplace(unitData->getType(), std::move(unitData)); } }
/** Loads the objective settings from the given XML file */ std::unique_ptr<objective_settings> load_settings(std::string const& filepath) { TiXmlDocument doc(filepath.c_str()); if (!doc.LoadFile()) throw std::invalid_argument("Could not parse file: " + filepath); std::unique_ptr<objective_settings> settings = std::make_unique<objective_settings>(); auto settingsElem = doc.FirstChild("ObjectiveSettings"); settings->min_value = atof(settingsElem->FirstChildElement("MinValue")->GetText()); settings->max_value = atof(settingsElem->FirstChildElement("MaxValue")->GetText()); settings->objfunc_settings = std::unique_ptr<TiXmlElement>( settingsElem->FirstChildElement("ObjectiveFunctions")->Clone()->ToElement()); return settings; }
void ItemMgr::loadConfig(const char * configFile) { tinyxml2::XMLDocument doc; doc.LoadFile(configFile); auto root = doc.FirstChildElement("Items"); auto itemElement = root->FirstChildElement(); while (itemElement) { auto item = new ItemType(m_itemList.size()); item->setName(itemElement->FirstChildElement("name")->GetText()); item->setItemDescription(itemElement->FirstChildElement("description")->GetText()); auto resPath = std::string("items/res/"); resPath.append(itemElement->FirstChildElement("res_path")->GetText()); item->setResPath(resPath); m_itemList.push_back(item); itemElement = itemElement->NextSiblingElement(); } }
TEST(TestTinyXML, read_score) { tinyxml2::XMLDocument doc; EXPECT_EQ(doc.LoadFile("..\\autumn leaves.xml"), tinyxml2::XMLError::XML_SUCCESS); const auto root = doc.FirstChildElement("chord-score"); const auto score = root->FirstChildElement("score"); TestString(score->Name(), "score"); }
void readGPX(std::string inFile, std::vector<GPXPoint> &out) { tx::XMLDocument doc; doc.LoadFile( inFile.c_str() ); tx::XMLElement *gpx = doc.FirstChildElement("gpx"); for (auto *trks = gpx->FirstChildElement("trk"); trks; trks = trks->NextSiblingElement()) { for (auto segs = trks->FirstChildElement("trkseg"); segs; segs = segs->NextSiblingElement()) { for (auto pt = segs->FirstChildElement("trkpt"); pt; pt = pt->NextSiblingElement()) { std::string lat = pt->Attribute("lat"); std::string lon = pt->Attribute("lon"); tx::XMLElement *elevationTag = pt->FirstChildElement("ele"); tx::XMLElement *timeTag = pt->FirstChildElement("time"); GPXPoint tmp; tmp.lat = std::stod(lat); tmp.lon = std::stod(lon); tmp.ele = std::stod(elevationTag->GetText()); std::string fullTime = timeTag->GetText(); tmp.dateStamp = fullTime.substr(0,4) + ":" + fullTime.substr(5,2) + ":" + fullTime.substr(8,2); std::tm timeData; // 2013-06-27T00:50:39Z strptime(fullTime.c_str(), "%Y-%m-%dT%H:%M:%SZ", &timeData); tmp.hour = timeData.tm_hour; tmp.minute = timeData.tm_min; tmp.second = timeData.tm_sec; // tmp.timestamp = std::mktime(&timeData); tmp.timestamp = timegm(&timeData); // std::cout << tmp.hour << ":" << tmp.minute << ":" << tmp.second << "\n"; // std::cout << tmp.timestamp << "\n"; out.push_back(tmp); } } } std::sort(out.begin(), out.end(), [](const GPXPoint &a,const GPXPoint &b) { return a.timestamp < b.timestamp; }); }
void GpxTrkElement::SetSimpleExtension(const wxString &name, const wxString &value) { //FIXME: if the extensions don't exist, we should create them TiXmlElement * exts = FirstChildElement("extensions"); if (exts) { TiXmlElement * ext = exts->FirstChildElement(name.ToUTF8()); if (ext) exts->ReplaceChild(ext, GpxSimpleElement(name, value)); else exts->LinkEndChild(new GpxSimpleElement(name, value)); } }
void ResourceLoader::loadGameSettings(const char * xmlPath) { //Load the xml file. tinyxml2::XMLDocument xmlDoc; xmlDoc.LoadFile(xmlPath); const auto rootElement = xmlDoc.RootElement(); assert(rootElement && "ResourceLoader::loadGameSettings() failed to load xml file."); //Load the design resolution. auto resolutionElement = rootElement->FirstChildElement("DesignResolution"); pimpl->m_DesignResolution.width = resolutionElement->FloatAttribute("Width"); pimpl->m_DesignResolution.height = resolutionElement->FloatAttribute("Height"); //Load the grid size. auto gridSizeElement = rootElement->FirstChildElement("GridSize"); pimpl->m_DesignGridSize.width = gridSizeElement->FloatAttribute("Width"); pimpl->m_DesignGridSize.height = gridSizeElement->FloatAttribute("Height"); //Load other settings. pimpl->m_FramesPerSecond = rootElement->FirstChildElement("FramesPerSecond")->FloatAttribute("Value"); pimpl->m_ResourceListPath = rootElement->FirstChildElement("ResourceListPath")->Attribute("Value"); pimpl->m_InitialScenePath = rootElement->FirstChildElement("InitialScenePath")->Attribute("Value"); }
bool FileProcess::LoadLogicClass(std::string strFile) { //////////////////////////////////////////////////// tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument(); if (NULL == doc) { return false; } doc->LoadFile(strFile.c_str()); tinyxml2::XMLElement* root = doc->RootElement(); auto classElement = root->FirstChildElement("Class"); std::string strIObjectPath = classElement->Attribute("Path"); auto nodeElement = classElement->FirstChildElement(); if (nodeElement) { while (true) { std::string strID = nodeElement->Attribute("Id"); std::string sqlToWrite = "CREATE TABLE `" + strID + "` (\n"; sqlToWrite += "\t`ID` varchar(128) NOT NULL,\n"; sqlToWrite += "\tPRIMARY KEY (`ID`)\n"; sqlToWrite += ") ENGINE=InnoDB DEFAULT CHARSET=utf8;\n"; fwrite(sqlToWrite.c_str(), sqlToWrite.length(), 1, mysqlClassWriter); // 读取父节点内容 if (!LoadClass(strRelativePath + strIObjectPath, strID)) { return false; } // 读取自己节点内容 std::string strPath = nodeElement->Attribute("Path"); if (!LoadClass(strRelativePath + strPath, strID)) { return false; } fwrite("\n", 1, 1, mysqlClassWriter); if (nodeElement == classElement->LastChildElement()) { break; } nodeElement++; } } delete doc; return true; }
s_CFG::s_CFG(TiXmlDocument& doc) { TiXmlElement* root = doc.RootElement(); assert(root != nullptr); auto vars_el = root->FirstChildElement("Variables"); assert(vars_el != nullptr); for (auto s: split(std::string(vars_el->GetText()))) { this->V.insert(s); } this->S = std::string(vars_el->FirstChildElement("StartSymbol")->GetText()); auto term_el = root->FirstChildElement("Terminals"); assert(term_el != nullptr); for (auto s: split(std::string(term_el->GetText()))) { this->T.insert(s); } auto prod_el = root->FirstChildElement("Productions"); assert(prod_el != nullptr); for (TiXmlElement* rule_el = prod_el->FirstChildElement("Rule"); rule_el != nullptr; rule_el = rule_el->NextSiblingElement("Rule")) { std::string head = std::string(rule_el->Attribute("LHS")); std::string bodies = std::string(rule_el->Attribute("RHS")); std::string buf; for (char c: bodies) { if (c == '|') { this->P[head].insert(split(buf)); buf.clear(); } else { buf += c; } } this->P[head].insert(split(buf)); } }
void BehaviorTreeLoader:: CreateBehaviorTreeNode(const TiXmlElement* pFirstChild, Node * & pNode, const std::string & btName) const { for (auto pIt = pFirstChild; pIt != nullptr; pIt = pIt->NextSiblingElement()) { std::string name; pIt->QueryStringAttribute(DEFAULT_NODE_ATTRIBUTE, &name); Node * pChildNode = _NodeFactory.Create(name); if (btName == DEFAULT_NODE_COMPOSITE) dynamic_cast<Composite *>(pNode)->AddChildNode(pChildNode); else if (btName == DEFAULT_NODE_DECORATOR) dynamic_cast<Decorator *>(pNode)->SetChildNode(pChildNode); else std::cerr << "Error, Unknown BehaviorTree Node Type : " + btName << std::endl; CreateBehaviorTreeNode(pIt->FirstChildElement(), pChildNode, pIt->Value()); } }
void Input::LoadInput(const std::string& file) { TiXmlDocument doc; doc.LoadFile(file.c_str()); auto parent = doc.FirstChildElement(); int i = 0; for (auto e = parent->FirstChildElement(); e; e = e->NextSiblingElement()) { int code; auto name = e->Value(); e->QueryIntAttribute("code", &code); m_keysAndCode[name] = code; m_keysAndIndex[name] = i++; } m_lastState = std::vector<bool>(m_keysAndCode.size(), false); m_currentState = std::vector<bool>(m_keysAndCode.size(), false); }
void GpxTrkElement::SetProperty(const wxString &name, const wxString &value) { //FIXME: doesn't care about order so it can be absolutely wrong, have to redo this code if it has to be used by something else than the constructor //then it can be made public //FIXME: can be reused for route and track GpxSimpleElement *element = new GpxSimpleElement(name, value); TiXmlElement *curelement = FirstChildElement(); bool found = false; while(curelement) { if((const char *)curelement->Value() == (const char *)name.ToUTF8()) { ReplaceChild(curelement, *element); element->Clear(); delete element; break; } curelement = curelement->NextSiblingElement(); } if (!found) LinkEndChild(element); }
const bool _toTextImpl(TiXmlDocument* pInput, std::ofstream& pOutput) { if (!pInput) { return false; } auto spellsElement = pInput->FirstChildElement("spells"); if (!spellsElement) { return false; } // Iterate <spell> auto spellElement = spellsElement->FirstChildElement("spell"); while (spellElement) { // Iterate <spell> attributes. auto attribute = spellElement->FirstAttribute(); while (attribute) { pOutput << attribute->Value(); attribute = attribute->Next(); if (attribute) pOutput << "^"; } spellElement = spellElement->NextSiblingElement("spell"); pOutput << std::endl; } return true; }
bool TmxTileset::parseElement(void* p, const std::string& path) { _terrainTypes.clear(); _tiles.clear(); auto element = static_cast<tinyxml2::XMLElement*>(p); if(!element) { return false; } _path = ""; tinyxml2::XMLDocument tsxDocument; if(element->Attribute("source")) { _source = element->Attribute("source"); std::string tsxPath = path + _source; if(tsxDocument.LoadFile(tsxPath.c_str()) != tinyxml2::XML_NO_ERROR) { return false; } element = tsxDocument.FirstChildElement("tileset"); auto separatorPos = tsxPath.find_last_of("/\\"); if (separatorPos != std::string::npos) { _path = tsxPath.substr(0, separatorPos + 1); } } else { _source = ""; } if(element->Attribute("name")) { _name = element->Attribute("name"); } else { _name = ""; } _firstGid = 1; _tileWidth = 0; _tileHeight = 0; _spacing = 0; _margin = 0; _offsetX = 0; _offsetY = 0; _tileCount = 0; element->QueryIntAttribute("firstgid", &_firstGid); element->QueryIntAttribute("tilewidth", &_tileWidth); element->QueryIntAttribute("tileheight", &_tileHeight); element->QueryIntAttribute("spacing", &_spacing); element->QueryIntAttribute("margin", &_margin); element->QueryIntAttribute("tilecount", &_tileCount); auto propertiesElement = element->FirstChildElement("properties"); auto imageElement = element->FirstChildElement("image"); auto terrainTypesElement = element->FirstChildElement("terraintypes"); auto tileElement = element->FirstChildElement("tile"); auto tileOffsetElement = element->FirstChildElement("tileoffset"); if(tileOffsetElement) { tileOffsetElement->QueryIntAttribute("x", &_offsetX); tileOffsetElement->QueryIntAttribute("y", &_offsetY); } _image.parseElement(imageElement); _properties.parseElement(propertiesElement); while(tileElement) { _tiles.push_back(TmxTilesetTile()); _tiles.back().parseElement(tileElement); tileElement = tileElement->NextSiblingElement("tile"); } if(terrainTypesElement) { auto terrainTypeElement = terrainTypesElement->FirstChildElement("terrain"); while(terrainTypeElement) { _terrainTypes.push_back(TmxTerrainType()); _terrainTypes.back().parseElement(terrainTypeElement); terrainTypeElement = terrainTypeElement->NextSiblingElement("terraintype"); } } return true; }
void DialogSystem::receive(const MouseClickEvent &mce) { game::entities.each<Position, Solid, Dialog, Name>( [&](entityx::Entity e, Position &pos, Solid &dim, Dialog &d, Name &name) { static std::atomic_bool dialogRun; (void)e; (void)d; if (((mce.position.x > pos.x) & (mce.position.x < pos.x + dim.width)) && ((mce.position.y > pos.y) & (mce.position.y < pos.y + dim.height))) { if (!dialogRun.load()) { std::thread([&] { std::string questAssignedText; int newIndex; auto exml = game::engine.getSystem<WorldSystem>()->getXML()->FirstChildElement("Dialog"); dialogRun.store(true); if (e.has_component<Direction>()) d.talking = true; if (d.index == 9999) { ui::dialogBox(name.name, "", false, randomDialog[d.rindex % randomDialog.size()]); ui::waitForDialog(); } else if (exml != nullptr) { while (exml->StrAttribute("name") != name.name) exml = exml->NextSiblingElement(); exml = exml->FirstChildElement("text"); while (exml->IntAttribute("id") != d.index) exml = exml->NextSiblingElement(); auto oxml = exml->FirstChildElement("set"); if (oxml != nullptr) { do game::setValue(oxml->StrAttribute("id"), oxml->StrAttribute("value")); while ((oxml = oxml->NextSiblingElement())); game::briceUpdate(); } auto qxml = exml->FirstChildElement("quest"); if (qxml != nullptr) { const char *qname; auto qsys = game::engine.getSystem<QuestSystem>(); do { // assign quest qname = qxml->Attribute("assign"); if (qname != nullptr) { questAssignedText = qname; auto req = qxml->GetText(); qsys->assign(qname, qxml->StrAttribute("desc"), req ? req : ""); } // check / finish quest else { qname = qxml->Attribute("check"); if (qname != nullptr) { if (qname != nullptr && qsys->hasQuest(qname) && qsys->finish(qname) == 0) { d.index = 9999; } else { ui::dialogBox(name.name, "", false, "Finish my quest u nug"); ui::waitForDialog(); return; } // oldidx = d.index; // d.index = qxml->UnsignedAttribute("fail"); // goto COMMONAIFUNC; } } } while((qxml = qxml->NextSiblingElement())); } auto cxml = exml->FirstChildElement("content"); const char *content; if (cxml == nullptr) { content = randomDialog[d.rindex % randomDialog.size()].c_str(); } else { content = cxml->GetText() - 1; while (*++content && isspace(*content)); } ui::dialogBox(name.name, "", false, content); ui::waitForDialog(); if (!questAssignedText.empty()) ui::passiveImportantText(5000, ("Quest assigned:\n\"" + questAssignedText + "\"").c_str()); if (exml->QueryIntAttribute("nextid", &newIndex) == XML_NO_ERROR) d.index = newIndex; } d.talking = false; dialogRun.store(false); }).detach(); } } }); }
void MeshRenderer::readMaterial(tinyxml2::XMLElement *ele){ std::vector<std::string> defs; _useTex = false; auto texture = ele->FirstChildElement("texture"); if(texture){ LOG_DEBUG("Using texture"); defs.push_back("USETEXTURE"); _useTex = true; std::string textureSRC; textureName = texture->Attribute("name"); auto c = texture->Attribute("src"); textureSRC = (!c) ? "" : c; if(textureSRC.length()!=0) Texture::loadTexture(textureName,textureSRC); } auto material = ele->FirstChildElement("material"); if(material){ LOG_DEBUG("Using material"); auto diffuse = material->FirstChildElement("diffuse"); auto ambient = material->FirstChildElement("ambient"); auto specular = material->FirstChildElement("specular"); auto specularity = material->FirstChildElement("specularity"); if(diffuse){ LOG_DEBUG("Using diffuse "); auto c = diffuse->GetText(); std::istringstream iss(c); glm::vec4 col = glm::vec4(0,0,0,255); iss >> col.r>>col.g>>col.b>>col.a; col /= 255; _mat.setDiffuse(col); LOG_DEBUG("Using diffuse " << col << _mat.getDiffuse()); } if(ambient){ auto c = ambient->GetText(); std::istringstream iss(c); glm::vec3 col = glm::vec3(0,0,0); iss >> col.r >> col.g >> col.b; col /= 255; _mat.setAmbient(col); LOG_DEBUG("Using ambient " << col << _mat.getAmbient()); } if(specular){ auto c = specular->GetText(); std::istringstream iss(c); glm::vec3 col = glm::vec3(0,0,0); iss >> col.r >> col.g >> col.b; col /= 255; _mat.setSpecular(col); LOG_DEBUG("Using specular " << col << _mat.getSpecular()); } if(specularity){ auto c = specularity->GetText(); std::istringstream iss(c); float s = 0; iss >> s; _mat.setSpecularity(s); LOG_DEBUG("Using specularity " << s << _mat.getSpecularity()); } }else if(!texture){
void Tileset::load(const std::string& path) { DEBUG("Loading tileset file %s", path.c_str()); std::ifstream input(path.c_str()); if(!input) { T_T("Failed to open tileset file for reading."); } TiXmlDocument xmlDoc; input >> xmlDoc; if(xmlDoc.Error()) { DEBUG("Error occurred in tileset XML parsing: %s", xmlDoc.ErrorDesc()); T_T("Failed to parse tileset data."); } TiXmlElement* root = xmlDoc.RootElement(); if(strcmp(root->Value(), "tileset") != 0) { DEBUG("Unexpected root element name."); T_T("Failed to parse tileset data."); } TiXmlElement* imageElement = root->FirstChildElement("image"); if(imageElement == nullptr) { DEBUG("Expected image data in tileset."); T_T("Failed to parse tileset data."); } std::string imagePath = imageElement->Attribute("source"); DEBUG("Loading tileset image \"%s\"...", imagePath.c_str()); m_texture.reset(new Texture(std::string("data/tilesets/") + imagePath)); m_size = m_texture->getSize() / TileEngine::TILE_SIZE; m_collisionShapes.resize(m_size.getArea()); auto const* tileElement = root->FirstChildElement("tile"); for(;tileElement != nullptr; tileElement = tileElement->NextSiblingElement("tile")) { int tileNum = -1; tileElement->Attribute("id", &tileNum); if(tileNum < 0) { continue; } auto& collisionShape = m_collisionShapes[tileNum]; // Retrieve the collision shape information for this tile const auto objectGroupElement = tileElement->FirstChildElement("objectgroup"); if(objectGroupElement) { const auto collisionElement = objectGroupElement->FirstChildElement("object"); if(collisionElement) { collisionShape.left = std::stoi(collisionElement->Attribute("x")) / TileEngine::TILE_SIZE; collisionShape.top = std::stoi(collisionElement->Attribute("y")) / TileEngine::TILE_SIZE; const auto collisionWidth = std::stoi(collisionElement->Attribute("width")) / TileEngine::TILE_SIZE; const auto collisionHeight = std::stoi(collisionElement->Attribute("height")) / TileEngine::TILE_SIZE; collisionShape.right = collisionShape.left + collisionWidth; collisionShape.bottom = collisionShape.top + collisionHeight; } } } }