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; }
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; }
int TestCountElements(const tinyxml2::XMLElement* elem, const char* str) { int count = 0; for (auto p = elem; p != nullptr; p = p->NextSiblingElement(str)) ++count; return count; }
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; }
Vec4 Framework::GetTileUV(const char* fileName, Texture2D* tex) { Vec4 UVCoords = Vec4(0, 0, 0, 0); tinyxml2::XMLDocument doc; if(doc.LoadFile("./images/spritesheets/sheet.xml") == tinyxml2::XML_NO_ERROR) { const char * width = doc.FirstChildElement("TextureAtlas")->FirstChildElement("SubTexture")->Attribute("width"); auto element = doc.FirstChildElement("TextureAtlas")->FirstChildElement(); while(element != NULL) { if(strcmp(fileName, element->Attribute("name")) == 0) { UVCoords = Vec4(tex->GetHeight() - atoi(element->Attribute("y")), tex->GetHeight() - (atoi(element->Attribute("y")) + atoi(element->Attribute("height"))), atoi(element->Attribute("x")), atoi(element->Attribute("x")) + atoi(element->Attribute("width")) ); break; } element = element->NextSiblingElement(); } } return UVCoords; }
void PowerLawWidgetManager::loadFromXml(TiXmlElement *_root) { std::vector < PowerLawWidget * > widgets; double valFactor, valExponent, valOffset, valMin, valMax; for (auto child = _root->FirstChildElement("PowerLawParameters"); child; child = child->NextSiblingElement()) { auto r0 = child->QueryDoubleAttribute("factor", &valFactor); auto r1 = child->QueryDoubleAttribute("exponent", &valExponent); auto r2 = child->QueryDoubleAttribute("offset", &valOffset); auto r3 = child->QueryDoubleAttribute("rangeMin", &valMin); auto r4 = child->QueryDoubleAttribute("rangeMax", &valMax); if (r0 == TIXML_SUCCESS && r1 == TIXML_SUCCESS && r2 == TIXML_SUCCESS && r3 == TIXML_SUCCESS && r4 == TIXML_SUCCESS) { auto w = new PowerLawWidget(); w->setFactor(valFactor); w->setExponent(valExponent); w->setOffset(valOffset); w->setMin(valMin); w->setMax(valMax); widgets.push_back(w); } else { QMessageBox::warning(0, "failed to load power laws", "could not load power laws: invalid file structure."); return; } } setPowerLawWidgets(widgets); }
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; }
inline bool getValue(const tinyxml2::XMLElement& elt, std::unordered_map<std::string, T>& values) { values.clear(); for(auto pChildElement = elt.FirstChildElement(); pChildElement; pChildElement = pChildElement->NextSiblingElement()) { if(!getValue(*pChildElement, values[pChildElement->Name()])) { return false; } } return true; }
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; }); }
TEST(TestTinyXML, read_part) { tinyxml2::XMLDocument doc; EXPECT_EQ(doc.LoadFile("..\\autumn leaves.xml"), tinyxml2::XMLError::XML_SUCCESS); const auto part = doc.FirstChildElement("chord-score")->FirstChildElement("score")->FirstChildElement("part"); EXPECT_EQ(part->IntAttribute("repeat"), 2); const auto next = part->NextSiblingElement("part"); EXPECT_EQ(next->IntAttribute("repeat"), 0); }
//============================================================================== void transformElementNamesToLowerCasesRecurse(tinyxml2::XMLElement* ele) { std::string eleName = ele->Name(); ele->SetName(toLowerCases(eleName).c_str()); auto childEle = ele->FirstChildElement(); while (childEle) { transformElementNamesToLowerCasesRecurse(childEle); childEle = childEle->NextSiblingElement(); } }
void TabContainer::loadFromXml(const tinyxml2::XMLElement *data) { BaseMenuObject::loadFromXml(data); auto el = data->FirstChildElement("Tab"); while (el != nullptr) { const char *name = "Unnamed"; el->QueryStringAttribute("name", &name); addTab(name); containers.at(containers.size() - 1)->loadFromXml(el); el = el->NextSiblingElement("Tab"); } }
WaveController::WaveController(tinyxml2::XMLElement* xml, std::function<void(std::shared_ptr<Minion>)> const& spawnUnitCallback) : mTimeSinceWave(0.f), mWaveQueue(), mFactory(), mSpawnUnitCallback(spawnUnitCallback) { //For each <Wave> element... for (auto wave = xml->FirstChildElement("Wave"); nullptr != wave; wave = wave->NextSiblingElement("Wave")) { //...create a wave and add it to the queue mWaveQueue.emplace(wave); } }
inline bool getValue(const tinyxml2::XMLElement& elt, std::vector<T>& values) { values.clear(); auto i = 0u; auto pChildElement = elt.FirstChildElement("v0"); while(pChildElement) { T value; if(!getValue(*pChildElement, value)) { return false; } values.emplace_back(value); ++i; pChildElement = pChildElement->NextSiblingElement((std::string("v") + toString(i)).c_str()); } return true; }
std::vector<SDL_Surface*> ResourceCache::LoadTextures( const TiXmlHandle& hndl, const std::string& name, const Size size ) { std::vector<SDL_Surface*> textures; for (auto elem = hndl.FirstChild(name).Element(); elem; elem = elem->NextSiblingElement(name)) { textures.push_back(LoadTexture(elem->GetText(), size)); } return textures; }
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 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(); } }
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 loadLights(Scene& scene, const tinyxml2::XMLElement* pLightElt) { if(pLightElt) { for(auto pLight = pLightElt->FirstChildElement(); pLight; pLight = pLight->NextSiblingElement()) { auto lightType = toString(pLight->Name()); if(lightType == "PointLight") { scene.addLight(makeShared<PointLight>(loadPointLight(*pLight))); } else if(lightType == "DirectionalLight") { scene.addLight(makeShared<DirectionalLight>(loadDirectionalLight(scene, *pLight))); } else if(lightType == "EnvironmentLight") { scene.addLight(makeShared<EnvironmentLight>(loadEnvironmentLight(scene, *pLight))); } else { std::cerr << "Unrecognized light type" << lightType << std::endl; } } } }
void PhysicDataHill::initWithXmlNode( const XMLNode* hill ) { mHillModel.resize(0); for (const XMLNode* node=hill->FirstChild(); node; node = node->NextSibling()) { Triangle tri; int count = 0; for (auto ele = node->FirstChildElement(); ele; ele = ele->NextSiblingElement()) { float x=0; float y= 0; for (auto attr = ele->FirstAttribute(); attr; attr = attr->Next()) { if (std::string(attr->Name()) == "x") { x = attr->FloatValue(); } if (std::string(attr->Name()) == "y") { y = attr->FloatValue(); } } tri.p[count].setPoint(x,y); if ( ++count == 3) break; } mHillModel.push_back(tri); } mStartPoint.x = 100000; mEndPoint.x = -100000; for (int i=0; i<mHillModel.size(); i++) { Triangle t = mHillModel[i]; for (int i=0; i<3; i++) { if (t.p[i].x < mStartPoint.x) mStartPoint = t.p[i]; if (t.p[i].x > mEndPoint.x) mEndPoint = t.p[i]; } } }
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 zerokernel::Select::loadFromXml(const tinyxml2::XMLElement *data) { BaseMenuObject::loadFromXml(data); const char *target; if (tinyxml2::XML_SUCCESS == data->QueryStringAttribute("target", &target)) { auto var = settings::Manager::instance().lookup(target); if (!var) { printf("WARNING: Creating Select element: could not find settings " "'%s'\n", target); } else { zerokernel::special::SettingsManagerList::markVariable(target); variable = var; } } auto child = data->FirstChildElement(nullptr); while (child != nullptr) { if (!strcmp("Option", child->Name())) { const char *name; const char *value; const char *tooltip; if (child->QueryStringAttribute("name", &name) || child->QueryStringAttribute("value", &value)) continue; printf("adding %s: %s\n", name, value); auto has_tooltip = !(child->QueryStringAttribute("tooltip", &tooltip)); options.push_back(option{ name, value, has_tooltip ? std::optional<std::string>(tooltip) : std::nullopt }); }; child = child->NextSiblingElement(nullptr); } }
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 XMLTransformationReader::readOperations(TiXmlElement* element, std::vector<DimensionDesc>& dimensions) { const char *tagName = element->Value(); // const char *name = element->Attribute("name"); if (!tagName || strcmp("operations", tagName) != 0) { _log->error("Invalid tag '%v' for operations tag", tagName); return false; } for (TiXmlElement* cElement = element->FirstChildElement(); cElement; cElement = cElement->NextSiblingElement()) { const char *child = cElement->Value(); if (!child) { _log->error("Invalid child '%v' of operations", child); return nullptr; } else if (strcmp("dimension", child) == 0) { auto e = cElement->FirstChildElement(); const char *eName = e->Value(); DimensionDesc desc; desc.name = std::string(cElement->Attribute("name")); if (strcmp("use", eName) == 0) { desc.type = XMLDimensionOperations::XML_USE; desc.sourceId = std::stoi(e->Attribute("id")); desc.path = std::string(e->Attribute("path")); } else if (strcmp("default", eName) == 0) { desc.type = XMLDimensionOperations::XML_DEFAULT; desc.value = std::string(e->Attribute("value")); } else if (strcmp("formula", eName) == 0) { desc.type = XMLDimensionOperations::XML_FORMULA; desc.formula = std::string(e->Attribute("formula")); const auto fc = e->FirstChild(); if (fc != nullptr) { /* If there are multiple variables defined */ for (auto velem = fc; velem != nullptr; velem = velem->NextSiblingElement()) { auto e = velem->ToElement(); desc.varmap[std::string(e->Attribute("name"))] = std::make_pair(std::string(e->Attribute("path")), std::stoi(e->Attribute("id"))); } } else { desc.varmap[std::string(e->Attribute("varname"))] = std::make_pair(std::string(e->Attribute("path")), std::stoi(e->Attribute("id"))); } } else if (strcmp("operations", eName) == 0) { desc.type = XMLDimensionOperations::XML_COMPLEX; bool result = this->readOperations(e, desc.dims); if (false == result) return false; } else { _log->warn("Unknown child '%v' in dimension '%v', will be ignored", child, desc.name); } dimensions.push_back(desc); } } 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 Map::parseNPCGroup(const TiXmlElement* npcGroupElement) { DEBUG("Loading NPC layer."); if(npcGroupElement != nullptr) { geometry::Point2D topLeft; geometry::Size size; int width; int height; std::string npcName; std::string spritesheet; geometry::Direction direction; const TiXmlElement* objectElement = npcGroupElement->FirstChildElement("object"); while(objectElement != nullptr) { objectElement->Attribute("x", &topLeft.x); objectElement->Attribute("y", &topLeft.y); // Attribute doesn't support unsigned ints, so we need to cast explicitly. objectElement->Attribute("width", &width); objectElement->Attribute("height", &height); size = { static_cast<unsigned int>(std::max(width, 0)), static_cast<unsigned int>(std::max(height, 0)) }; npcName = objectElement->Attribute("name"); direction = geometry::Direction::DOWN; const auto propertiesElement = objectElement->FirstChildElement("properties"); auto propertyElement = propertiesElement->FirstChildElement("property"); while(propertyElement != nullptr) { if(std::string(propertyElement->Attribute("name")) == "spritesheet") { spritesheet = propertyElement->Attribute("value"); break; } else if(std::string(propertyElement->Attribute("name")) == "direction") { direction = geometry::toDirection(propertyElement->Attribute("value")); if(direction == geometry::Direction::NONE) { direction = geometry::Direction::DOWN; } } propertyElement = propertyElement->NextSiblingElement("property"); } DEBUG("Found NPC %s at %d,%d with spritesheet %s, width %d and height %d.", npcName.c_str(), topLeft.x, topLeft.y, spritesheet.c_str(), size.width, size.height); if(size.width > 0 && size.height > 0 && !npcName.empty() && !spritesheet.empty()) { m_npcsToSpawn.emplace_back(NPCSpawnMarker{npcName, spritesheet, topLeft, size, direction}); } objectElement = objectElement->NextSiblingElement("object"); } } }
bool RulesLoader::ParseFacilityDefinition(Framework &fw, Rules &rules, tinyxml2::XMLElement *root) { std::ignore = fw; FacilityDef def; if (UString(root->Name()) != "facilitydef") { LogError("Called on unexpected node \"%s\"", root->Name()); return false; } def.id = root->Attribute("id"); def.name = root->Attribute("name"); for (auto node = root->FirstChildElement(); node != nullptr; node = node->NextSiblingElement()) { UString tag = node->Name(); if (tag == "buildCost") { if (node->QueryIntText(&def.buildCost) != tinyxml2::XMLError::XML_SUCCESS) { LogError("Failed to read facility 'buildCost' attribute"); return false; } } else if (tag == "buildTime") { if (node->QueryIntText(&def.buildTime) != tinyxml2::XMLError::XML_SUCCESS) { LogError("Failed to read facility 'buildTime' attribute"); return false; } } else if (tag == "weeklyCost") { if (node->QueryIntText(&def.weeklyCost) != tinyxml2::XMLError::XML_SUCCESS) { LogError("Failed to read facility 'weeklyCost' attribute"); return false; } } else if (tag == "capacityType") { if (!ReadText(node, std::map<UString, FacilityDef::Capacity>{ {"none", FacilityDef::Capacity::None}, {"quarters", FacilityDef::Capacity::Quarters}, {"stores", FacilityDef::Capacity::Stores}, {"medical", FacilityDef::Capacity::Medical}, {"training", FacilityDef::Capacity::Training}, {"psi", FacilityDef::Capacity::Psi}, {"repair", FacilityDef::Capacity::Repair}, {"chemistry", FacilityDef::Capacity::Chemistry}, {"physics", FacilityDef::Capacity::Physics}, {"workshop", FacilityDef::Capacity::Workshop}, {"aliens", FacilityDef::Capacity::Aliens}}, def.capacityType)) { LogError("Failed to read facility 'capacityType' attribute"); return false; } } else if (tag == "capacityAmount") { if (node->QueryIntText(&def.capacityAmount) != tinyxml2::XMLError::XML_SUCCESS) { LogError("Failed to read facility 'capacityAmount' attribute"); return false; } } else if (tag == "sprite") { def.sprite = node->GetText(); } else if (tag == "size") { if (node->QueryIntText(&def.size) != tinyxml2::XMLError::XML_SUCCESS) { LogError("Failed to read facility 'size' attribute"); return false; } } else { LogWarning("Unknown facility tag \"%s\"", tag.c_str()); } } rules.facilities.emplace(def.id, def); 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)); } }
SpriteAnimDefinition* SpriteAnimDefinition::createFromFile(const std::string& filename, onut::ContentManager* pContentManager) { SpriteAnimDefinition* pRet = new SpriteAnimDefinition(); pRet->m_filename = pContentManager->find(filename); if (pRet->m_filename.empty()) { pRet->m_filename = filename; } tinyxml2::XMLDocument doc; doc.LoadFile(pRet->m_filename.c_str()); auto pXMLSheet = doc.FirstChildElement("sheet"); assert(pXMLSheet); std::string textureName = pXMLSheet->Attribute("texture"); onut::Texture* pTexture = pContentManager->getResource<onut::Texture>(textureName); assert(pTexture); int spriteW = pTexture->getSize().x; int spriteH = pTexture->getSize().y; int originX = 0; int originY = 0; pXMLSheet->QueryAttribute("spriteWidth", &spriteW); pXMLSheet->QueryAttribute("spriteHeight", &spriteH); pXMLSheet->QueryAttribute("originX", &originX); pXMLSheet->QueryAttribute("originY", &originY); Vector2 origin((float)originX / (float)spriteW, (float)originY / (float)spriteH); for (auto pXMLAnim = pXMLSheet->FirstChildElement("anim"); pXMLAnim; pXMLAnim = pXMLAnim->NextSiblingElement("anim")) { std::string name = pXMLAnim->Attribute("name"); auto& anim = pRet->m_anims[name]; int fps = 30; pXMLAnim->QueryAttribute("fps", &fps); pXMLAnim->QueryAttribute("loop", &anim.loop); Frame frame; frame.pTexture = pTexture; frame.origin = origin; for (auto pXMLFrame = pXMLAnim->FirstChildElement("frame"); pXMLFrame; pXMLFrame = pXMLFrame->NextSiblingElement("frame")) { int repeat = 1; int id = 0; pXMLFrame->QueryAttribute("id", &id); pXMLFrame->QueryAttribute("repeat", &repeat); int col = id % (pTexture->getSize().x / spriteW); int row = id / (pTexture->getSize().x / spriteW); col *= spriteW; row *= spriteH; frame.UVs = Vector4( (float)col / (float)pTexture->getSize().x, (float)row / (float)pTexture->getSize().y, (float)(col + spriteW) / (float)pTexture->getSize().x, (float)(row + spriteH) / (float)pTexture->getSize().y); for (auto i = 0; i < repeat; ++i) { anim.frames.push_back(frame); } } anim.frames.push_back(frame); // Repeat last frame anim.duration = (float)anim.frames.size() / (float)fps; } return pRet; }
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; }