ConditionalNode* AST::do_conditional(tinyxml2::XMLElement* conditional) { /* {{{ */ using namespace tinyxml2; ConditionalNode* ret = new ConditionalNode(); XMLElement* cond = conditional->FirstChildElement("cond"); if (cond == NULL || std::string(cond->Value()) != "cond") { std::cerr << "Condition has to come first in a conditional" << std::endl; exit(1); } // Add condition // Condition is an operation (e.g. +, -, <) if (cond->FirstChildElement("o") != NULL) { ret->set_condition(do_operator(cond->FirstChildElement("o"))); } // Condition is a variable else if (cond->FirstChildElement("v") != NULL) { // Set it to variable std::string var_name = cond->FirstChild()->Value(); ret->set_condition(new ValueNode(var_name, reg_number(var_name, VAR_REG))); } // Condition is a constant else if (cond->FirstChildElement("c") != NULL) { // Set it to variable (has to be int) std::string val(cond->FirstChild()->Value()); int i; // Parse int sscanf(val.c_str(), "%d", &i); ret->set_condition(new ValueNode(i)); } else { std::cerr << "Invalid condition in conditional" << std::endl; exit(1); } // Add first body (true) cond = cond->NextSiblingElement("body"); ret->set_body_true(process_node(cond->FirstChildElement())); // Add second body (false) cond = cond->NextSiblingElement("body"); ret->set_body_false(process_node(cond->FirstChildElement())); return ret; } /* }}} */
AssignmentNode* AST::do_assignment(tinyxml2::XMLElement* setq) { /* {{{ */ using namespace tinyxml2; AssignmentNode* ret = new AssignmentNode(); // Has to be assigned to a variable XMLElement* operand = setq->FirstChildElement("v"); if (left == NULL) { std::cerr << "Not an assignment to variable" << std::endl; exit(1); } // Set left operand // Get variable name std::string var_name(operand->FirstChild()->Value()); ret->set_left(new ValueNode(var_name, reg_number(var_name, VAR_REG))); // Set right operand // Focus on right operand operand = operand->NextSiblingElement(); // See what kind of operand it is (another operation, const, var?) std::string operand_type(operand->Value()); // Right operand is an operation (e.g. +, -, <) if (operand_type == "o") { ret->set_right(do_operator(operand)); } // Right operand is a variable else if (operand_type == "v") { // Set it to variable std::string var_name = operand->FirstChild()->Value(); ret->set_right(new ValueNode(var_name, reg_number(var_name, VAR_REG))); } // Right oprand is a constant else if (operand_type == "c") { // Set it to variable (has to be int) std::string val(operand->FirstChild()->Value()); int i; // Parse int sscanf(val.c_str(), "%d", &i); ret->set_right(new ValueNode(i)); } return ret; } /* }}} */
int CSettings::ParseOutputs(XMLElement *Outputs) { // Parse Outputs XMLElement *Output = Outputs->FirstChildElement("output"); int NumberOfOutputs = 0; while(Output) { OutputContainer OutputParse; NumberOfOutputs++; if(!Output->Attribute("name")) { Log.error("Output entry has no name\n"); return false; } // Check if there is a duplicate name OutputParse.name = Output->Attribute("name"); for(list<OutputContainer>::iterator i=OutputsDB.begin(); i != OutputsDB.end(); ++i) { if(OutputParse.name.compare((*i).name) == 0) { Log.error("Duplicate output name [%s]\n", OutputParse.name.c_str()); return false; } } OutputParse.type = Output->Attribute("type"); XMLNode *OutSettings = Output->FirstChild(); while(OutSettings) { if(OutSettings->Value() && OutSettings->ToElement()->GetText()) { OutputParse.settings[OutSettings->Value()] = OutSettings->ToElement()->GetText(); Log.debug("parsed [%s]=[%s]", OutSettings->Value(), OutputParse.settings[OutSettings->Value()].c_str()); } OutSettings = OutSettings->NextSibling(); } OutputsDB.push_back(OutputParse); Output = Output->NextSiblingElement("output"); } Log.log("Parsed %d outputs\n", NumberOfOutputs); return true; }
XMLElement& COption<float>::operator << (XMLElement& root) { XMLElement* optionNode = root.FirstChildElement(m_name); if (optionNode == NULL) { UseDefault: UseDefault(); return root; } XMLNode* content = optionNode->FirstChild(); if (content == NULL) goto UseDefault; LPCSTR value = content->ToText()->Value(); m_value = (float)atof(value); if (!IsValid(m_value)) UseDefault(); return root; }
int CTinyXMLParser::GetNodeText_len(LPCTSTR strNodeName,TCHAR *pDestBuffer,int nNode/*=0*/) { try { XMLElement * Rootelement = m_pXMLDom->RootElement(); if(Rootelement==NULL)return 0; XMLElement * pFindElement = Rootelement->FirstChildElement(strNodeName); if(pFindElement==NULL)return 0; const char * pValue = pFindElement->FirstChild()->Value(); int nLen = strlen(pValue); if(pDestBuffer==NULL){ pDestBuffer = new char[nLen+1]; } strcpy(pDestBuffer,pValue); pDestBuffer[nLen+1]='\0'; return nLen; /* HRESULT hr; MSXML2::IXMLDOMNodeListPtr List = m_pXMLDom->getElementsByTagName((_bstr_t)strNodeName); long lNodesCount = 0; hr = List->get_length(&lNodesCount); if(SUCCEEDED(hr) && (nNode<lNodesCount )) { MSXML2::IXMLDOMNodePtr Node = List->item[nNode]; int nLen = _tcslen(Node->text); if(pDestBuffer==NULL) { pDestBuffer = new TCHAR[nLen+1]; } _tcscpy(pDestBuffer,Node->text); pDestBuffer[nLen+1]='\0'; return nLen; } */ return 0; } catch (...) { } return 0; }
int example_3() { static const char* xml = "<?xml version=\"1.0\"?>" "<!DOCTYPE PLAY SYSTEM \"play.dtd\">" "<PLAY>" "<TITLE>A Midsummer Night's Dream</TITLE>" "</PLAY>"; XMLDocument doc; doc.Parse( xml ); XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" ); const char* title = titleElement->GetText(); printf( "Name of play (1): %s\n", title ); XMLText* textNode = titleElement->FirstChild()->ToText(); title = textNode->Value(); printf( "Name of play (2): %s\n", title ); return doc.ErrorID(); }
void XMLConfig::readXML(const char* path){ XMLDocument doc; cout << "Reading file at: " << path << endl; doc.LoadFile(path); // arquivosDeEntrada XMLElement* arquivosDeEntrada = doc.FirstChildElement("aplicacao")->FirstChildElement("arquivosDeEntrada"); XMLNode* arquivo = arquivosDeEntrada->FirstChild(); while(arquivo != NULL){ XMLElement* arq = arquivo->ToElement(); if(strcmp(arq->Name(),"arquivoDaArena") == 0){ this->arena = File(arq->Attribute("nome"), arq->Attribute("caminho"), arq->Attribute("tipo")); } arquivo = arquivo->NextSibling(); } cout << "OK!"<<endl; }
int CSettings::ParseInputs(XMLElement *Inputs) { // Parse Inputs XMLElement *Input = Inputs->FirstChildElement("input"); int NumberOfInputs = 0; while(Input) { InputContainer InputParse; NumberOfInputs++; if(!Input->Attribute("type") || !Input->Attribute("UUID")) return false; InputParse.uuid = Input->Attribute("UUID"); InputParse.type = Input->Attribute("type"); XMLElement *Interface = Input->FirstChildElement("iface"); if(!Interface || !Interface->Attribute("type")) return false; InputParse.iface = Interface->Attribute("type"); XMLNode *iSets = Interface->FirstChild(); while(iSets) { if(iSets->Value() || iSets->ToElement()->GetText()) { InputParse.ifaceSettings[iSets->Value()] = iSets->ToElement()->GetText(); Log.debug("parsed [%s]=[%s]", iSets->Value(), InputParse.ifaceSettings[iSets->Value()].c_str()); } iSets = iSets->NextSibling(); } XMLElement *Sensor = Input->FirstChildElement("sensors")->FirstChildElement("sensor"); int NumOfSensors = 0; while(Sensor) { if(!Sensor->Attribute("address")) return false; NumOfSensors++; InputParse.sensors.push_back(atol(Sensor->Attribute("address"))); Sensor = Sensor->NextSiblingElement("sensor"); } XMLElement *Output = Input->FirstChildElement("output"); if(!Output || !Output->Attribute("name")) return false; InputParse.output = Output->Attribute("name"); if(Output->Attribute("cache")) InputParse.cache = Output->Attribute("cache"); else Log.warn("No cache db set. This is not recommended\n"); InputsDB.push_back(InputParse); Log.debug("Parsed %s (%s - %s) with %d sensors\n", InputParse.uuid.c_str(), InputParse.type.c_str(), InputParse.iface.c_str(), NumOfSensors); Input = Input->NextSiblingElement("input"); } Log.debug("Parsed %d inputs\n", NumberOfInputs); return true; }
bool COLLADAImporter::LoadGeometry(XMLElement* geometryNode,boost::unordered_map<std::string, std::vector<float> >& floatarrays) { boost::unordered_map<std::string,Source> sources; XMLElement *mesh = XMLHelper::GetChildElement(geometryNode,"mesh"); if(mesh == NULL) mesh = XMLHelper::GetChildElement(geometryNode,"convex_mesh"); if(mesh == NULL) return false; // load all source elements under <mesh> std::vector<XMLElement*> xmlsources = XMLHelper::GetChildElements(mesh,"source"); for(std::vector<XMLElement*>::iterator it = xmlsources.begin();it != xmlsources.end(); it++) { Source s; if(s.parseXML(*it,floatarrays)) sources[s.getID()] = s; else return false; } XMLElement* xmlvertices = XMLHelper::GetChildElement(mesh,"vertices"); if(xmlvertices == NULL) return false; if(xmlvertices->Attribute("id") == NULL) return false; // get <vertrices> id std::string verticesid = xmlvertices->Attribute("id"); // get <vertices>, <input> with semantic="POSITION" XMLElement *positionInput = XMLHelper::GetChildElement(xmlvertices,"input","semantic","POSITION"); std::string positionid; if(!XMLHelper::GetElementAttribute(positionInput,"source",positionid)) return false; positionid = positionid.substr(1); // remove leading "#" Mesh mmesh; std::string geometryid; if(XMLHelper::GetElementAttribute(geometryNode,"id",geometryid)) mmesh.setID(geometryid); std::string geometryName; if(XMLHelper::GetElementAttribute(geometryNode,"name",geometryName)) mmesh.setName(geometryName); Source& vertices = sources[positionid]; int ucount = vertices.getUnitCount(); if(ucount < 3) return false; int vcount = vertices.getArrayValues().size() / ucount; for(int i=0;i<vcount;i++) { int idx = ucount*i; vec3 v(vertices.getArrayValues()[idx],vertices.getArrayValues()[idx+1],vertices.getArrayValues()[idx+2]); mmesh.getVertices().push_back(v); } // get <triangles> nodes std::vector<XMLElement*> xmltriangles = XMLHelper::GetChildElements(mesh,"triangles"); for(std::vector<XMLElement*>::iterator it = xmltriangles.begin();it!=xmltriangles.end();it++){ XMLElement * triangles = *it; if(triangles->Attribute("count") != NULL) { // get triangle count int tricount=0; if(!StringHelper::from_string<int>(tricount,std::string(triangles->Attribute("count")))) continue; std::string materialsymbol; if(!XMLHelper::GetElementAttribute(triangles,"material",materialsymbol)) materialsymbol = ""; std::string temp; int vertices_offset; // get vertices <input> XMLElement* verticesInput = XMLHelper::GetChildElement(triangles,"input","semantic","VERTEX"); if(!XMLHelper::GetElementAttribute(verticesInput,"source",temp)) return false; temp = temp.substr(1); if(temp != verticesid) // verify source is the same as vertices id loaded above in current mesh return false; if(!XMLHelper::GetElementAttribute(verticesInput,"offset",temp)) // get vertices offset in <p> element return false; if(!StringHelper::from_string(vertices_offset,temp)) return false; std::string normalid; int normal_offset; bool hasNormals; // get normals <input> XMLElement* normalInput = XMLHelper::GetChildElement(triangles,"input","semantic","NORMAL"); if(!XMLHelper::GetElementAttribute(normalInput,"source",normalid)) hasNormals = false; else { normalid = normalid.substr(1); hasNormals = true; } if(hasNormals && !XMLHelper::GetElementAttribute(normalInput,"offset",temp)) // get offset for normals in <p> element return false; else { if(!StringHelper::from_string<int>(normal_offset,temp)) return false; } XMLElement *pelement = XMLHelper::GetChildElement(triangles,"p"); if(pelement == NULL) return false; XMLText *innerText = pelement->FirstChild()->ToText(); if(innerText == NULL) return false; std::string tarray(innerText->Value()); std::vector<int> IndexArray = StringHelper::ConvertStringToTArray<int>(tarray); int indexcount = IndexArray.size(); if((indexcount % (3*tricount)) != 0) return false; int indexstride = indexcount/(3*tricount); TriangleGroup trigroup; trigroup.setMaterialSymbol(materialsymbol); // TODO: add check for positionid & normalid if(hasNormals) { Source& vertices = sources[normalid]; ucount = vertices.getUnitCount(); if(ucount < 3) return false; int vcount = vertices.getArrayValues().size() / ucount; for(int i=0;i<vcount;i++) { int idx = ucount*i; vec3 v(vertices.getArrayValues()[idx],vertices.getArrayValues()[idx+1],vertices.getArrayValues()[idx+2]); trigroup.getNormals().push_back(v); } } for(int i=0;i<tricount*3;i++) { int vpos = i*indexstride + vertices_offset; trigroup.getTriangleIndices().push_back(IndexArray[vpos]); if(hasNormals) { vpos = i*indexstride + normal_offset; trigroup.getNormalIndices().push_back(IndexArray[vpos]); } } mmesh.getTriangleGroups().push_back(trigroup); } else continue; } // get <polygons> nodes std::vector<XMLElement*> xmlpolygons = XMLHelper::GetChildElements(mesh,"polygons"); for(std::vector<XMLElement*>::iterator it = xmlpolygons.begin(); it != xmlpolygons.end(); it++) { XMLElement * polygons = *it; if(polygons->Attribute("count") != NULL) { // get polygon count int polycount=0; if(!StringHelper::from_string<int>(polycount,std::string(polygons->Attribute("count")))) continue; std::string materialsymbol; if(!XMLHelper::GetElementAttribute(polygons,"material",materialsymbol)) materialsymbol = ""; std::string temp; int vertices_offset; // get vertices <input> XMLElement* verticesInput = XMLHelper::GetChildElement(polygons,"input","semantic","VERTEX"); if(!XMLHelper::GetElementAttribute(verticesInput,"source",temp)) return false; temp = temp.substr(1); if(temp != verticesid) // verify source is the same as vertices id loaded above in current mesh return false; if(!XMLHelper::GetElementAttribute(verticesInput,"offset",temp)) // get vertices offset in <p> element return false; if(!StringHelper::from_string(vertices_offset,temp)) return false; std::string normalid; int normal_offset; bool hasNormals; // get normals <input> XMLElement* normalInput = XMLHelper::GetChildElement(polygons,"input","semantic","NORMAL"); if(!XMLHelper::GetElementAttribute(normalInput,"source",normalid)) hasNormals = false; else { normalid = normalid.substr(1); hasNormals = true; } if(hasNormals && !XMLHelper::GetElementAttribute(normalInput,"offset",temp)) // get offset for normals in <p> element return false; else { if(!StringHelper::from_string<int>(normal_offset,temp)) return false; } int stridepervertex = 0; std::vector<XMLElement*> inputs = XMLHelper::GetChildElements(polygons,"input"); for(std::vector<XMLElement*>::const_iterator it = inputs.begin(); it != inputs.end(); it++) { if(!XMLHelper::GetElementAttribute(*it,"offset",temp)) return false; int offset=0; if(!StringHelper::from_string<int>(offset,temp)) return false; stridepervertex = std::max(stridepervertex,offset); } stridepervertex ++; PolygonGroup polygroup; polygroup.setMaterialSymbol(materialsymbol); if(hasNormals) { Source& vertices = sources[normalid]; ucount = vertices.getUnitCount(); if(ucount < 3) // normals have at least 3 components (X,Y,Z) return false; int vcount = vertices.getArrayValues().size() / ucount; for(int i=0;i<vcount;i++) { int idx = ucount*i; vec3 v(vertices.getArrayValues()[idx],vertices.getArrayValues()[idx+1],vertices.getArrayValues()[idx+2]); polygroup.getNormals().push_back(v); } } std::vector<XMLElement *> pelements = XMLHelper::GetChildElements(polygons,"p"); for(std::vector<XMLElement*>::iterator it = pelements.begin(); it != pelements.end(); it++) { XMLElement *pelement = *it; XMLText *innerText = pelement->FirstChild()->ToText(); if(innerText == NULL) return false; std::string tarray(innerText->Value()); std::vector<int> IndexArray = StringHelper::ConvertStringToTArray<int>(tarray); if((IndexArray.size() % stridepervertex) != 0) continue; int currentIndexOffset = 0; int vertexCount = IndexArray.size() / stridepervertex; PPolygon poly; for(int i=0;i<vertexCount;i++) { poly.getVertexIndices().push_back(IndexArray[currentIndexOffset+vertices_offset]); if(hasNormals) { poly.getNormalIndices().push_back(IndexArray[currentIndexOffset+normal_offset]); } currentIndexOffset += stridepervertex; } polygroup.getPolygons().push_back(poly); } mmesh.getPolygonGroups().push_back(polygroup); } else continue; } // get <polylist> nodes std::vector<XMLElement*> xmlpolylist = XMLHelper::GetChildElements(mesh,"polylist"); for(std::vector<XMLElement*>::iterator it = xmlpolylist.begin();it!=xmlpolylist.end();it++){ XMLElement * polylist = *it; if(polylist->Attribute("count") != NULL) { // get polygon count int polycount=0; if(!StringHelper::from_string<int>(polycount,std::string(polylist->Attribute("count")))) continue; std::string materialsymbol; if(!XMLHelper::GetElementAttribute(polylist,"material",materialsymbol)) materialsymbol = ""; std::string temp; int vertices_offset; // get vertices <input> XMLElement* verticesInput = XMLHelper::GetChildElement(polylist,"input","semantic","VERTEX"); if(!XMLHelper::GetElementAttribute(verticesInput,"source",temp)) return false; temp = temp.substr(1); if(temp != verticesid) // verify source is the same as vertices id loaded above in current mesh return false; if(!XMLHelper::GetElementAttribute(verticesInput,"offset",temp)) // get vertices offset in <p> element return false; if(!StringHelper::from_string(vertices_offset,temp)) return false; std::string normalid; int normal_offset; bool hasNormals; // get normals <input> XMLElement* normalInput = XMLHelper::GetChildElement(polylist,"input","semantic","NORMAL"); if(!XMLHelper::GetElementAttribute(normalInput,"source",normalid)) hasNormals = false; else { normalid = normalid.substr(1); hasNormals = true; } if(hasNormals && !XMLHelper::GetElementAttribute(normalInput,"offset",temp)) // get offset for normals in <p> element return false; else { if(!StringHelper::from_string<int>(normal_offset,temp)) return false; } XMLElement *vcountelement = XMLHelper::GetChildElement(polylist,"vcount"); if(vcountelement == NULL) return false; XMLText *vcountinnerText = vcountelement->FirstChild()->ToText(); if(vcountinnerText == NULL) return false; std::string vcarray(vcountinnerText->Value()); std::vector<int> vCountArray = StringHelper::ConvertStringToTArray<int>(vcarray); if(vCountArray.size() != polycount) return false; int totalVertices = 0; for(std::vector<int>::const_iterator it = vCountArray.begin(); it != vCountArray.end(); it++) { totalVertices += *it; } XMLElement *pelement = XMLHelper::GetChildElement(polylist,"p"); if(pelement == NULL) return false; XMLText *innerText = pelement->FirstChild()->ToText(); if(innerText == NULL) return false; std::string tarray(innerText->Value()); std::vector<int> IndexArray = StringHelper::ConvertStringToTArray<int>(tarray); int indexcount = IndexArray.size(); if((indexcount % totalVertices) != 0) return false; PolygonGroup polygroup; polygroup.setMaterialSymbol(materialsymbol); // TODO: add check for positionid & normalid if(hasNormals) { Source& vertices = sources[normalid]; ucount = vertices.getUnitCount(); if(ucount < 3) // normals have at least 3 components (X,Y,Z) return false; int vcount = vertices.getArrayValues().size() / ucount; for(int i=0;i<vcount;i++) { int idx = ucount*i; vec3 v(vertices.getArrayValues()[idx],vertices.getArrayValues()[idx+1],vertices.getArrayValues()[idx+2]); polygroup.getNormals().push_back(v); } } int stridepervertex = 0; std::vector<XMLElement*> inputs = XMLHelper::GetChildElements(polylist,"input"); for(std::vector<XMLElement*>::const_iterator it = inputs.begin(); it != inputs.end(); it++) { if(!XMLHelper::GetElementAttribute(*it,"offset",temp)) return false; int offset=0; if(!StringHelper::from_string<int>(offset,temp)) return false; stridepervertex = std::max(stridepervertex,offset); } stridepervertex ++; if(IndexArray.size() != totalVertices*stridepervertex) return false; int currentIndexOffset = 0; for(int i=0;i<polycount;i++) { PPolygon poly; for(int j=0;j<vCountArray[i];j++) { poly.getVertexIndices().push_back(IndexArray[currentIndexOffset+vertices_offset]); if(hasNormals) { poly.getNormalIndices().push_back(IndexArray[currentIndexOffset+normal_offset]); } currentIndexOffset += stridepervertex; } polygroup.getPolygons().push_back(poly); } mmesh.getPolygonGroups().push_back(polygroup); } else continue; } if((mmesh.getTriangleGroups().size()>0) || (mmesh.getPolygonGroups().size() > 0)) { m_Meshes.push_back(mmesh); return true; } else return false; }
bool COLLADAImporter::LoadMaterial(XMLElement* colladaRootNode,const std::string& id) { if(m_Materials.find(id) != m_Materials.end()) // material already loaded return true; XMLElement *materials = XMLHelper::GetChildElement(colladaRootNode,"library_materials"); if(materials == NULL) return false; XMLElement *material = XMLHelper::GetChildElement(materials,"material","id",id); if(material == NULL) return false; XMLElement *effect = XMLHelper::GetChildElement(material,"instance_effect"); if(effect == NULL) return false; std::string effectid; if(!XMLHelper::GetElementAttribute(effect,"url",effectid)) return false; effectid = effectid.substr(1); // remove leading "#" XMLElement *effects = XMLHelper::GetChildElement(colladaRootNode,"library_effects"); if(effects == NULL) return false; effect = XMLHelper::GetChildElement(effects,"id",effectid); if(effect == NULL) return false; XMLElement *profile = XMLHelper::GetChildElement(effect,"profile_COMMON"); if(profile == NULL) return false; XMLElement *technique = XMLHelper::GetChildElement(profile,"technique"); if(technique == NULL) return false; XMLElement *bp = XMLHelper::GetChildElement(technique,"blinn"); if(bp == NULL) { bp = XMLHelper::GetChildElement(technique,"phong"); if(bp == NULL) { bp = XMLHelper::GetChildElement(technique,"lambert"); if(bp == NULL) return false; } } Material mat; // ambient XMLElement *ambient = XMLHelper::GetChildElement(bp,"ambient"); if(ambient != NULL) { XMLElement *color = XMLHelper::GetChildElement(ambient,"color"); if(color != NULL) { XMLText *value = color->FirstChild()->ToText(); if(value != NULL) { std::vector<float> c = StringHelper::ConvertStringToTArray<float>(value->Value()); if(c.size() >= 3 ) mat.m_Ambient = vec3(c[0],c[1],c[2]); } } } //diffuse XMLElement *diffuse = XMLHelper::GetChildElement(bp,"diffuse"); if(diffuse != NULL) { XMLElement* color = XMLHelper::GetChildElement(diffuse,"color"); if(color != NULL) { XMLText* value = color->FirstChild()->ToText(); if(value != NULL) { std::vector<float> c = StringHelper::ConvertStringToTArray<float>(value->Value()); if(c.size() >= 3 ) mat.m_Diffuse = vec3(c[0],c[1],c[2]); } } } //specular XMLElement *specular = XMLHelper::GetChildElement(bp,"specular"); if(specular != NULL) { XMLElement* color = XMLHelper::GetChildElement(specular,"color"); if(color != NULL) { XMLText* value = color->FirstChild()->ToText(); if(value != NULL) { std::vector<float> c = StringHelper::ConvertStringToTArray<float>(value->Value()); if(c.size() >= 3 ) mat.m_Specular = vec3(c[0],c[1],c[2]); } } } //emission XMLElement *emission = XMLHelper::GetChildElement(bp,"emission"); if(emission != NULL) { XMLElement* color = XMLHelper::GetChildElement(emission,"color"); if(color != NULL) { XMLText* value = color->FirstChild()->ToText(); if(value != NULL) { std::vector<float> c = StringHelper::ConvertStringToTArray<float>(value->Value()); if(c.size() >= 3 ) mat.m_Emmission = vec3(c[0],c[1],c[2]); } } } m_Materials[id] = mat; return true; }
bool FractalConfiguration::open(string filename) { if(invalidID()) return true; m_dirty = false; XMLDocument doc; // Parse file doc.LoadFile(filename.c_str()); if(doc.Error()) { m_last_error = doc.GetErrorStr1(); return true; } // Get data XMLElement *root = doc.RootElement(); string name = string(root->Name()); if(name != "fractal") { m_last_error = "Configuration file is invalid!"; return true; } if(root->Attribute("id", m_id.c_str())) { XMLNode *node = root->FirstChild(); // Loop over all properties while(node != NULL) { XMLElement *element = node->ToElement(); if(element == NULL) { m_last_error = "Configuration file is invalid!"; return true; } // Get name and type (attributes) const char* tmp_name = element->Attribute("name"); const char* tmp_type = element->Attribute("type"); if(tmp_name == NULL || tmp_type == NULL) { m_last_error = "Configuration file is invalid!"; return true; } string name(tmp_name); string type(tmp_type); // Get text const char* tmp_text = element->GetText(); string text = ""; if(tmp_text != NULL) text = tmp_text; // Set property if(type == "string") { if(setStringProperty(name, text)) return true; } else if(type == "int") { int value; if(stringToInt(text, &value)) { m_last_error = "Error in configuration: " + text + " should be an integer"; return true; } if(setIntProperty(name, value)) return true; } else if(type == "double") { double value; if(stringToDouble(text, &value)) { m_last_error = "Error in configuration: " + text + " should be a double"; return true; } if(setDoubleProperty(name, value)) return true; } else if(type == "bool") { bool value; if(text == "1") value = true; else if(text == "0") value = false; else { m_last_error = "Error in configuration: " + text + " should be boolean (0 or 1)"; return true; } if(setBoolProperty(name, value)) return true; } else { m_last_error = "Error in configuration: " + type + " is not a valid type"; return true; } // Next node node = node->NextSibling(); } } else { m_last_error = "File contains not the configuration of a fractal with ID " + m_id; return true; } resetDirty(); return false; }
bool XmlHandler::ReadFile(const char* fileName, OVR::Render::RenderDevice* pRender, OVR::Render::Scene* pScene, OVR::Array<Ptr<CollisionModel> >* pCollisions, OVR::Array<Ptr<CollisionModel> >* pGroundCollisions, bool srgbAware /*= false*/, bool anisotropic /*= false*/) { if(pXmlDocument->LoadFile(fileName) != 0) { return false; } // Extract the relative path to our working directory for loading textures filePath[0] = 0; intptr_t pos = 0; intptr_t len = strlen(fileName); for(intptr_t i = len; i > 0; i--) { if (fileName[i-1]=='\\' || fileName[i-1]=='/') { memcpy(filePath, fileName, i); filePath[i] = 0; break; } } // Load the textures OVR_DEBUG_LOG_TEXT(("Loading textures...")); XMLElement* pXmlTexture = pXmlDocument->FirstChildElement("scene")->FirstChildElement("textures"); OVR_ASSERT(pXmlTexture); if (pXmlTexture) { pXmlTexture->QueryIntAttribute("count", &textureCount); pXmlTexture = pXmlTexture->FirstChildElement("texture"); } for(int i = 0; i < textureCount; ++i) { const char* textureName = pXmlTexture->Attribute("fileName"); intptr_t dotpos = strcspn(textureName, "."); char fname[300]; if (pos == len) { OVR_sprintf(fname, 300, "%s", textureName); } else { OVR_sprintf(fname, 300, "%s%s", filePath, textureName); } int textureLoadFlags = 0; textureLoadFlags |= srgbAware ? TextureLoad_SrgbAware : 0; textureLoadFlags |= anisotropic ? TextureLoad_Anisotropic : 0; SysFile* pFile = new SysFile(fname); Ptr<Texture> texture; if (textureName[dotpos + 1] == 'd' || textureName[dotpos + 1] == 'D') { // DDS file Texture* tmp_ptr = LoadTextureDDSTopDown(pRender, pFile, textureLoadFlags); if(tmp_ptr) { texture.SetPtr(*tmp_ptr); } } else { Texture* tmp_ptr = LoadTextureTgaTopDown(pRender, pFile, textureLoadFlags, 255); if(tmp_ptr) { texture.SetPtr(*tmp_ptr); } } Textures.PushBack(texture); pFile->Close(); pFile->Release(); pXmlTexture = pXmlTexture->NextSiblingElement("texture"); } OVR_DEBUG_LOG_TEXT(("Done.\n")); // Load the models pXmlDocument->FirstChildElement("scene")->FirstChildElement("models")-> QueryIntAttribute("count", &modelCount); OVR_DEBUG_LOG(("Loading models... %i models to load...", modelCount)); XMLElement* pXmlModel = pXmlDocument->FirstChildElement("scene")-> FirstChildElement("models")->FirstChildElement("model"); for(int i = 0; i < modelCount; ++i) { if (i % 15 == 0) { OVR_DEBUG_LOG_TEXT(("%i models remaining...", modelCount - i)); } const char* name = pXmlModel->Attribute("name"); Models.PushBack(*new Model(Prim_Triangles, name)); bool isCollisionModel = false; pXmlModel->QueryBoolAttribute("isCollisionModel", &isCollisionModel); Models[i]->IsCollisionModel = isCollisionModel; if (isCollisionModel) { Models[i]->Visible = false; } bool tree_c = (strcmp(name, "tree_C") == 0) || (strcmp(name, "Object03") == 0); //read the vertices OVR::Array<Vector3f> *vertices = new OVR::Array<Vector3f>(); ParseVectorString(pXmlModel->FirstChildElement("vertices")->FirstChild()-> ToText()->Value(), vertices); for (unsigned int vertexIndex = 0; vertexIndex < vertices->GetSize(); ++vertexIndex) { vertices->At(vertexIndex).x *= -1.0f; if (tree_c) { // Move the terrace tree closer to the house vertices->At(vertexIndex).z += 0.5; } } //read the normals OVR::Array<Vector3f> *normals = new OVR::Array<Vector3f>(); ParseVectorString(pXmlModel->FirstChildElement("normals")->FirstChild()-> ToText()->Value(), normals); for (unsigned int normalIndex = 0; normalIndex < normals->GetSize(); ++normalIndex) { normals->At(normalIndex).z *= -1.0f; } //read the textures OVR::Array<Vector3f> *diffuseUVs = new OVR::Array<Vector3f>(); OVR::Array<Vector3f> *lightmapUVs = new OVR::Array<Vector3f>(); int diffuseTextureIndex = -1; int lightmapTextureIndex = -1; XMLElement* pXmlCurMaterial = pXmlModel->FirstChildElement("material"); while(pXmlCurMaterial != NULL) { if(pXmlCurMaterial->Attribute("name", "diffuse")) { pXmlCurMaterial->FirstChildElement("texture")-> QueryIntAttribute("index", &diffuseTextureIndex); if(diffuseTextureIndex > -1) { ParseVectorString(pXmlCurMaterial->FirstChildElement("texture")-> FirstChild()->ToText()->Value(), diffuseUVs, true); } } else if(pXmlCurMaterial->Attribute("name", "lightmap")) { pXmlCurMaterial->FirstChildElement("texture")-> QueryIntAttribute("index", &lightmapTextureIndex); if(lightmapTextureIndex > -1) { XMLElement* firstChildElement = pXmlCurMaterial->FirstChildElement("texture"); XMLNode* firstChild = firstChildElement->FirstChild(); XMLText* text = firstChild->ToText(); const char* value = text->Value(); ParseVectorString(value, lightmapUVs, true); } } pXmlCurMaterial = pXmlCurMaterial->NextSiblingElement("material"); } //set up the shader Ptr<ShaderFill> shader = *new ShaderFill(*pRender->CreateShaderSet()); shader->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Vertex, VShader_MVP)); if(diffuseTextureIndex > -1) { shader->SetTexture(0, Textures[diffuseTextureIndex]); if(lightmapTextureIndex > -1) { shader->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Fragment, FShader_MultiTexture)); shader->SetTexture(1, Textures[lightmapTextureIndex]); } else { shader->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Fragment, FShader_Texture)); } } else { shader->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Fragment, FShader_LitGouraud)); } Models[i]->Fill = shader; //add all the vertices to the model const size_t numVerts = vertices->GetSize(); for(size_t v = 0; v < numVerts; ++v) { if(diffuseTextureIndex > -1) { if(lightmapTextureIndex > -1) { Models[i]->AddVertex(vertices->At(v).z, vertices->At(v).y, vertices->At(v).x, Color(255, 255, 255), diffuseUVs->At(v).x, diffuseUVs->At(v).y, lightmapUVs->At(v).x, lightmapUVs->At(v).y, normals->At(v).x, normals->At(v).y, normals->At(v).z); } else { Models[i]->AddVertex(vertices->At(v).z, vertices->At(v).y, vertices->At(v).x, Color(255, 255, 255), diffuseUVs->At(v).x, diffuseUVs->At(v).y, 0, 0, normals->At(v).x, normals->At(v).y, normals->At(v).z); } } else { Models[i]->AddVertex(vertices->At(v).z, vertices->At(v).y, vertices->At(v).x, Color(255, 255, 255, 255), 0, 0, 0, 0, normals->At(v).x, normals->At(v).y, normals->At(v).z); } } // Read the vertex indices for the triangles const char* indexStr = pXmlModel->FirstChildElement("indices")-> FirstChild()->ToText()->Value(); size_t stringLength = strlen(indexStr); for(size_t j = 0; j < stringLength; ) { size_t k = j + 1; for(; k < stringLength; ++k) { if (indexStr[k] == ' ') break; } char text[20]; for(size_t l = 0; l < k - j; ++l) { text[l] = indexStr[j + l]; } text[k - j] = '\0'; Models[i]->Indices.PushBack((unsigned short)atoi(text)); j = k + 1; } // Reverse index order to match original expected orientation Array<uint16_t>& indices = Models[i]->Indices; size_t indexCount = indices.GetSize(); for (size_t revIndex = 0; revIndex < indexCount/2; revIndex++) { unsigned short itemp = indices[revIndex]; indices[revIndex] = indices[indexCount - revIndex - 1]; indices[indexCount - revIndex - 1] = itemp; } delete vertices; delete normals; delete diffuseUVs; delete lightmapUVs; pScene->World.Add(Models[i]); pScene->Models.PushBack(Models[i]); pXmlModel = pXmlModel->NextSiblingElement("model"); } OVR_DEBUG_LOG(("Done.")); //load the collision models OVR_DEBUG_LOG(("Loading collision models... ")); XMLElement* pXmlCollisionModel = pXmlDocument->FirstChildElement("scene")->FirstChildElement("collisionModels"); if (pXmlCollisionModel) { pXmlCollisionModel->QueryIntAttribute("count", &collisionModelCount); pXmlCollisionModel = pXmlCollisionModel->FirstChildElement("collisionModel"); } XMLElement* pXmlPlane = NULL; for(int i = 0; i < collisionModelCount; ++i) { Ptr<CollisionModel> cm = *new CollisionModel(); int planeCount = 0; OVR_ASSERT(pXmlCollisionModel != NULL); // collisionModelCount should guarantee this. if (pXmlCollisionModel) { pXmlCollisionModel->QueryIntAttribute("planeCount", &planeCount); pXmlPlane = pXmlCollisionModel->FirstChildElement("plane"); for(int j = 0; j < planeCount; ++j) { Vector3f norm; pXmlPlane->QueryFloatAttribute("nx", &norm.x); pXmlPlane->QueryFloatAttribute("ny", &norm.y); pXmlPlane->QueryFloatAttribute("nz", &norm.z); float D; pXmlPlane->QueryFloatAttribute("d", &D); D -= 0.5f; if (i == 26) D += 0.5f; // tighten the terrace collision so player can move right up to rail Planef p(norm.z, norm.y, norm.x * -1.0f, D); cm->Add(p); pXmlPlane = pXmlPlane->NextSiblingElement("plane"); } if (pCollisions) pCollisions->PushBack(cm); pXmlCollisionModel = pXmlCollisionModel->NextSiblingElement("collisionModel"); } } OVR_DEBUG_LOG(("done.")); //load the ground collision models OVR_DEBUG_LOG(("Loading ground collision models...")); pXmlCollisionModel = pXmlDocument->FirstChildElement("scene")->FirstChildElement("groundCollisionModels"); OVR_ASSERT(pXmlCollisionModel); if (pXmlCollisionModel) { pXmlCollisionModel->QueryIntAttribute("count", &groundCollisionModelCount); pXmlCollisionModel = pXmlCollisionModel->FirstChildElement("collisionModel"); pXmlPlane = NULL; for(int i = 0; i < groundCollisionModelCount; ++i) { Ptr<CollisionModel> cm = *new CollisionModel(); int planeCount = 0; pXmlCollisionModel->QueryIntAttribute("planeCount", &planeCount); pXmlPlane = pXmlCollisionModel->FirstChildElement("plane"); for(int j = 0; j < planeCount; ++j) { Vector3f norm; pXmlPlane->QueryFloatAttribute("nx", &norm.x); pXmlPlane->QueryFloatAttribute("ny", &norm.y); pXmlPlane->QueryFloatAttribute("nz", &norm.z); float D = 0.f; pXmlPlane->QueryFloatAttribute("d", &D); Planef p(norm.z, norm.y, norm.x * -1.0f, D); cm->Add(p); pXmlPlane = pXmlPlane->NextSiblingElement("plane"); } if (pGroundCollisions) pGroundCollisions->PushBack(cm); pXmlCollisionModel = pXmlCollisionModel->NextSiblingElement("collisionModel"); } } OVR_DEBUG_LOG(("done.")); return true; }
void ObtainCommands(XMLElement* registry, unsigned int* &functionCount, Function** &functions) { XMLElement* commands = registry->FirstChildElement("commands"); if(commands) { // reserve memory unsigned int commandAmount = 0; XMLElement* cmd = commands->FirstChildElement("command"); while(cmd) { ++commandAmount; // if (cmd->FirstChildElement("vecequiv")) // ++commandAmount; //if (cmd->FirstChildElement("alias")) // ++commandAmount; cmd = cmd->NextSiblingElement(); } // fill data *functionCount = commandAmount; *functions = new Function[commandAmount]; cmd = commands->FirstChildElement("command"); for(unsigned int i = 0; i < commandAmount; ++i) { (*functions)[i].Name = 0; (*functions)[i].Result = 0; XMLElement* proto = cmd->FirstChildElement("proto"); if(proto) { XMLElement* name = proto->FirstChildElement("name"); if(name) { int len = strlen(name->FirstChild()->Value()); (*functions)[i].Name = new char[len + 1]; strcpy((*functions)[i].Name, name->FirstChild()->Value()); } XMLElement* resultType = proto->FirstChildElement("ptype"); if(resultType) { int len = strlen(resultType->FirstChild()->Value()); (*functions)[i].Result = new char[len + 1]; strcpy((*functions)[i].Result, resultType->FirstChild()->Value()); } else { int len = strlen("void"); (*functions)[i].Result = new char[len +1]; strcpy((*functions)[i].Result, "void"); } } unsigned int parameterAmount = 0; XMLElement* param = cmd->FirstChildElement("param"); while(param && strcmp(param->Value(), "param") == 0) { ++parameterAmount; param = param->NextSiblingElement(); } (*functions)[i].ParameterCount = parameterAmount; (*functions)[i].Parameters = 0; if(parameterAmount) { (*functions)[i].Parameters = new Parameter[parameterAmount]; param = cmd->FirstChildElement("param"); for(unsigned int j = 0; j < parameterAmount; ++j) { (*functions)[i].Parameters[j].Name = 0; XMLElement* name = param->FirstChildElement("name"); if(name) { int len = strlen(name->FirstChild()->Value()); if(strcmp(name->FirstChild()->Value(), "residences") == 0) len = len; (*functions)[i].Parameters[j].Name = new char[len + 1]; strcpy((*functions)[i].Parameters[j].Name, name->FirstChild()->Value()); } (*functions)[i].Parameters[j].Type = 0; (*functions)[i].Parameters[j].PostType = 0; (*functions)[i].Parameters[j].ByteSize = 0; (*functions)[i].Parameters[j].IsConst = false; (*functions)[i].Parameters[j].IsPointer = false; XMLElement* type = param->FirstChildElement("ptype"); if(type) { int len = strlen(type->FirstChild()->Value()); (*functions)[i].Parameters[j].Type = new char[len + 1]; strcpy((*functions)[i].Parameters[j].Type, type->FirstChild()->Value()); if(type->PreviousSibling() && strstr(type->PreviousSibling()->Value(), "const") != 0) (*functions)[i].Parameters[j].IsConst = true; if(type->NextSibling() && strcmp(type->NextSibling()->Value(), "name") != 0) { int len = strlen(type->NextSibling()->Value()); (*functions)[i].Parameters[j].PostType = new char[len + 1]; strcpy((*functions)[i].Parameters[j].PostType, type->NextSibling()->Value()); if(strstr(type->NextSibling()->Value(), "*") != 0) (*functions)[i].Parameters[j].IsPointer = true; } (*functions)[i].Parameters[j].ByteSize = stringTypeToSize((*functions)[i].Parameters[j].Type, (*functions)[i].Parameters[j].IsPointer); } else if(param->FirstChild() && strcmp(param->FirstChild()->Value(), "name") != 0) { (*functions)[i].Parameters[j].Type = new char[5]; strcpy((*functions)[i].Parameters[j].Type, "void"); if(strstr(param->FirstChild()->Value(), "const") != 0) (*functions)[i].Parameters[j].IsConst = true; if(strstr(param->FirstChild()->Value(), "*") != 0) (*functions)[i].Parameters[j].IsPointer = true; const char* p = strstr(param->FirstChild()->Value(), "void"); if(p) { int len = strlen(p + 4); (*functions)[i].Parameters[j].PostType = new char[len + 1]; strcpy((*functions)[i].Parameters[j].PostType, p + 4); } } do { param = param->NextSiblingElement(); } while(param && strcmp(param->Value(), "param") != 0); } } (*functions)[i].FeatureCount = 0; (*functions)[i].Features = 0; (*functions)[i].ExtensionCount = 0; (*functions)[i].Extensions = 0; cmd = cmd->NextSiblingElement(); } } }
void LevelParser::parseTileLayer(XMLElement* pTileElement, Level *pLevel) { // New TileLayer instance TileLayer* pTileLayer = new TileLayer(m_tileSize, m_width, m_height, TheGame::Instance().getTilesets()); // local temporary variable bool collidable = false; // A multidimensional array of int values to hold our final decoded and uncompressed tile data std::vector<std::vector<int>> data; // xml data node XMLElement* pDataNode = nullptr; // to store base64 decoded information std::string decodedIDs; // We search for the node we need for (XMLElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { // check if layer has properties if (e->Value() == std::string("properties")) { for (XMLElement* property = e->FirstChildElement(); property != NULL; property = property->NextSiblingElement()) { if (property->Value() == std::string("property")) { // Check if it is a collision layer if (property->Attribute("name") == std::string("collidable")) { collidable = true; } } } } if (e->Value() == std::string("data")) { pDataNode = e; } } // Tile information not encoded nor compressed if (pDataNode->Attribute("encoding") == nullptr) { std::vector<int> layerRow(m_width); for (int rows = 0; rows < m_height; rows++) { data.push_back(layerRow); } XMLElement* tile = pDataNode->FirstChildElement(); int id; for (int rows = 0; rows < m_height; rows++) { for (int cols = 0; cols < m_width ; cols++) { tile->QueryAttribute("gid", &data[rows][cols]); tile = tile->NextSiblingElement(); } } } else { // We get the text (our encoded/compressed data) from the data node and use the base64 decoder to decode it for (XMLNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()) { XMLText* text = e->ToText(); std::string t = text->Value(); decodedIDs = base64_decode(t); } // We use the zlib library to decompress our data once again uLongf sizeofids = m_width * m_height * sizeof(int); std::vector<unsigned> gids(sizeofids); uncompress((Bytef*)&gids[0], &sizeofids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); // gids now contains all of our tile IDs, so we fill our data array with the correct values std::vector<int> layerRow(m_width); for (int j = 0; j < m_height; j++) { data.push_back(layerRow); } for (int rows = 0; rows < m_height; rows++) { for (int cols = 0; cols < m_width; cols++) { data[rows][cols] = gids[rows * m_width + cols]; } } } pTileLayer->setTileIDs(data); pTileLayer->setMapWidth(m_width); // push into collision array and mark the layer as collidable if necessary if (collidable) { pTileLayer->setCollidable(true); pLevel->getCollisionLayers()->push_back(pTileLayer); } pLevel->getLayers()->push_back(pTileLayer); }