Exemplo n.º 1
0
	//----------------------------------------------------------------------
	//
	//----------------------------------------------------------------------
	void LNFXManager::_analyzeXML( const char* xml, size_t size )
	{
		XML::Document xmlDoc;
		xmlDoc.Parse( xml, size );

		// まずは Technique → Pass と作成して、コンパイルする。この中で Variable も作る
		XML::Element* xmlElement = xmlDoc.FirstChildElement();
		while ( xmlElement != NULL )
		{
			// <Technique>
			if ( strcmp( xmlElement->Name(), TechniqueElementName ) == 0 ) {
				_analyzeXMLTechniqueElement( xmlElement );
			}

			xmlElement = xmlElement->NextSiblingElement();
		}

		// 次に、作成済みの Variable にアノテーションを割り振る
		xmlElement = xmlDoc.FirstChildElement();
		while ( xmlElement != NULL )
		{
			// <Variable>
			if ( strcmp( xmlElement->Name(), VariableElementName ) == 0 ) {
				_analyzeXMLVariableElement( xmlElement );
			}

			xmlElement = xmlElement->NextSiblingElement();
		}
	}
Exemplo n.º 2
0
/***************************************************************
* Function: CodeParser::parseCellArrayExpr()
* Purpose : Parse the XML code of a cell array expression
* Initial : Maxime Chevalier-Boisvert on February 23, 2009
****************************************************************
Revisions and bug fixes:
*/
Expression* CodeParser::parseCellArrayExpr(const XML::Element* pElement)
{
	// Declare a vector to store the rows
	CellArrayExpr::RowVector rowVector;

	// For each child element
	for (size_t i = 0; i < pElement->getNumChildren(); ++i)
	{
		// Declare a row to store elements
		CellArrayExpr::Row row;

		// Get a reference to this child element
		XML::Element* pRowElem = pElement->getChildElement(i);

		// If this is not a row element, throw an exception
		if (pRowElem->getName() != "Row")
			throw XML::ParseError("Invalid element found in cell array expression", pRowElem->getTextPos());

		// For each expression in this row
		for (size_t j = 0; j < pRowElem->getNumChildren(); ++j)
		{
			// Parse the expression and add it to the row
			row.push_back(parseExpression(pRowElem->getChildElement(j)));
		}

		// Add the row to the vector
		rowVector.push_back(row);
	}

	// Create and return the cell array expression
	return new CellArrayExpr(rowVector);
}
Exemplo n.º 3
0
/*!
 * Unsafe load
 *
 * \throws	ExceptionProtocol	the content of the vector is not serializable
 * \throws	ExceptionInvalidArgument	not a Vector
 * \throws	ExceptionRuntime	impossible to read an XML element
 * \throws	ExceptionNotFound	unknown type
 *
 * \param[in]	el	the element to load
 */
void Vector::Deserialize(xml::Element &el)
{
	if (el.GetValue() != getClassName())
	{
		throw ExceptionInvalidArgument(StringUTF8("void Vector::Deserialize(xml::Element &el): ") + 
				_("Wrong XML element."));
	}
	std::multimap<int, SObject> xmllist;
	for (xml::Element te = el.BeginElement(); te != el.EndElement(); ++te)
	{
		SObject d(nullptr);
		try
		{
			d = DataFactory::CreateData(te);
		}
		catch (crn::Exception &)
		{	// XXX throw?
			CRNWarning(String(U"void Vector::Deserialize"
						U"(xml::Element &el): ") + String(_("Unknown XML element: ")) +
					te.GetValue());
		}
		if (!d)
			continue;
		int index;
		try { index = te.GetAttribute<int>("vector_index", false); } catch (...) { index = int(xmllist.size()); }
		xmllist.insert(std::make_pair(index, d));
	}
	Clear();
	for (auto & elem : xmllist)
		data.push_back(elem.second);
	ShrinkToFit();
}
Exemplo n.º 4
0
/***************************************************************
* Function: CodeParser::parseStmtList()
* Purpose : Parse the XML code of a statement list
* Initial : Maxime Chevalier-Boisvert on November 7, 2008
****************************************************************
Revisions and bug fixes:
*/
StmtSequence* CodeParser::parseStmtList(const XML::Element* pElement)
{
	// Create a statement vector to store the statements
	StmtSequence::StmtVector stmtVector;

	// For each child element
	for (size_t i = 0; i < pElement->getNumChildren(); ++i)
	{
		// Get this child element
		XML::Element* pChildElement = pElement->getChildElement(i);

		// If this is a variable declaration
		if (pChildElement->getName() == "VariableDecl")
		{
			// Ignore for now
			continue;
		}

		// Parse this statement
		Statement* pStmt = parseStatement(pChildElement);

		// Add the statement to the vector
		stmtVector.push_back(pStmt);
	}

	// Return a new sequence statement
	return new StmtSequence(stmtVector);
}
Exemplo n.º 5
0
	//----------------------------------------------------------------------
	//
	//----------------------------------------------------------------------
	void LNFXManager::_analyzeXMLVariableElement( XML::Element* xmlElement )
	{
		// 属性
		const char* attrName		= xmlElement->Attribute( NameAttributeName );
		const char* attrSemantic	= xmlElement->Attribute( SemanticAttributeName );
		const bool attrShared		= xmlElement->BoolAttribute( SharedAttributeName );
		const char* attrTexture		= xmlElement->Attribute(TextureAttributeName);
		LN_THROW_InvalidFormat(attrName);

		// 適用試行
		IAnnotatedObject* var = mBuilder->OnTrySetVariableParam( attrName, attrSemantic, attrShared, attrTexture );
		if ( var != NULL )
		{
			// 子要素
			XML::Element* xmlChild = xmlElement->FirstChildElement();
			while ( xmlChild != NULL )
			{
				// <Annotation>
				if ( strcmp( xmlChild->Name(), AnnotationElementName ) == 0 ) {
					_analyzeXMLAnnotationElement( xmlChild, var );
				}

				xmlChild = xmlChild->NextSiblingElement();
			}
		}
	}
Exemplo n.º 6
0
/*! 
 * Initializes the object from an XML element. Unsafe.
 *
 * \throws	ExceptionInvalidArgument	not a StringUTF8
 * \throws	ExceptionDomain	no CDATA found
 *
 * \param[in]	el	the XML element to read
 */
void StringUTF8::Deserialize(xml::Element &el)
{
	if (el.GetValue() != "StringUTF8")
	{
		throw ExceptionInvalidArgument(StringUTF8("void StringUTF8::deserialize(xml::Element &el): ") + 
				_("Wrong XML element."));
	}
	xml::Node c(el.GetFirstChild());
	if (!c)
		return; // no content
	xml::Text t(c.AsText()); // may throw
	*this = t.GetValue();
	ShrinkToFit();
}
Exemplo n.º 7
0
/***************************************************************
* Function: CodeParser::parseScript()
* Purpose : Parse the XML code of a script
* Initial : Maxime Chevalier-Boisvert on November 4, 2008
****************************************************************
Revisions and bug fixes:
*/
IIRNode* CodeParser::parseScript(const XML::Element* pElement)
{
	// Declare a pointer for the sequence statement
	StmtSequence* pSequenceStmt = NULL;

	// For each child element
	for (size_t i = 0; i < pElement->getNumChildren(); ++i)
	{
		// Get a pointer to this element
		XML::Element* pFuncElement = pElement->getChildElement(i);

		// If this is a symbol table
		if (pFuncElement->getName() == "Symboltable")
		{
			// Ignore for now
		}

		// If this is the statement list
		else if (pFuncElement->getName() == "StmtList")
		{
			// If the statement list was already encountered, throw an exception
			if (pSequenceStmt != NULL)
				throw XML::ParseError("Duplicate statement list", pElement->getTextPos());

			// Parse the statement list
			pSequenceStmt = parseStmtList(pFuncElement);
		}

		// Otherwise
		else
		{
			// This is an invalid element type, throw an exception
			throw XML::ParseError("Invalid element type in script: \"" + pFuncElement->getName() + "\"", pFuncElement->getTextPos());
		}
	}

	// If the statement list is missing, throw an exception
	if (pSequenceStmt == NULL)
		throw XML::ParseError("Missing statement list", pElement->getTextPos());

	// Create and return a new program function object
	return new ProgFunction(
		"",
		ProgFunction::ParamVector(),
		ProgFunction::ParamVector(),
		ProgFunction::FuncVector(),
		pSequenceStmt,
		true
	);
}
Exemplo n.º 8
0
/***************************************************************
* Function: CodeParser::parseLambdaExpr()
* Purpose : Parse the XML code of a lambda expression
* Initial : Maxime Chevalier-Boisvert on February 25, 2009
****************************************************************
Revisions and bug fixes:
*/
Expression* CodeParser::parseLambdaExpr(const XML::Element* pElement)
{
	// Create a vector for the input parameters
	LambdaExpr::ParamVector inParams;

	// Declare a pointer for the body expression
	Expression* pBodyExpr = NULL;

	// For each child element
	for (size_t i = 0; i < pElement->getNumChildren(); ++i)
	{
		// Get a pointer to this child element
		XML::Element* pChildElem = pElement->getChildElement(i);

		// If this is a symbol
		if (pChildElem->getName() == "Name")
		{
			// Parse the symbol and add it to the input parameters
			inParams.push_back(SymbolExpr::getSymbol(pChildElem->getStringAttrib("nameId")));
		}

		// Otherwise, it must be the body expression
		else
		{
			// If the body expression was already parsed
			if (pBodyExpr != NULL)
			{
				// Throw an exception
				throw XML::ParseError("Duplicate body expression", pChildElem->getTextPos());
			}

			// Parse the body expression
			pBodyExpr = parseExpression(pChildElem);
		}
	}

	// If no body expression was found
	if (pBodyExpr == NULL)
	{
		// Throw an exception
		throw XML::ParseError("No body expression found", pElement->getTextPos());
	}

	// Create and return the new lambda expression
	return new LambdaExpr(
		inParams,
		pBodyExpr
	);
}
Exemplo n.º 9
0
/*! 
 * Internal. Initializes some internal data from an XML element. 
 *
 * \param[in]	el	the element that contains the serialized object
 */
void Savable::deserialize_internal_data(xml::Element &el)
{
	// read name if any
	const StringUTF8 nam = el.GetAttribute<StringUTF8>("name");

	xml::Element udel(el.GetFirstChildElement("Map"));
	while (udel)
	{ // look for a map containing user data
		const StringUTF8 role = udel.GetAttribute<StringUTF8>("role");
		// check role
		if (role == USERDATA_NAME)
		{ // found the user data
			if (!user_data)
			{ // create the object if needed
				user_data.reset(new Map());
			}
			else
			{ // clear the current user data if needed
				user_data->Clear();
			}
			// read the user data and quit the method
			user_data->Deserialize(udel);
			return;
		}
		udel = udel.GetNextSiblingElement("Map");
	}
}
Exemplo n.º 10
0
  void PostgresProvider::Init(const xml::Element& rConfig)
  {
    // initialize connection
    const xml::Element& rConnection = rConfig.GetChildElementByName("connection");

    m_pImpl->m_sHost = rConnection.GetChildElementByName("host").GetTextValue();
    m_pImpl->m_sPort = rConnection.GetChildElementByName("port").GetTextValue();
    m_pImpl->m_sDataBase = rConnection.GetChildElementByName("db").GetTextValue();
    m_pImpl->m_sLogin = rConnection.GetChildElementByName("login").GetTextValue();
    m_pImpl->m_sPassword = rConnection.GetChildElementByName("password").GetTextValue();

    STAFF_ASSERT(!m_pImpl->m_pConn, "Already connected");
    m_pImpl->m_pConn = PQsetdbLogin(m_pImpl->m_sHost.c_str(), m_pImpl->m_sPort.c_str(), "", "",
                                    m_pImpl->m_sDataBase.c_str(), m_pImpl->m_sLogin.c_str(),
                                    m_pImpl->m_sPassword.c_str());

    STAFF_ASSERT(m_pImpl->m_pConn, "Failed to set db login");
    if (PQstatus(m_pImpl->m_pConn) != CONNECTION_OK)
    {
      std::string sError = std::string("Failed to login: "******"UTF8");
    STAFF_ASSERT(nResult == 0, std::string("error setting encoding: ") + PQerrorMessage(m_pImpl->m_pConn));
  }
/*! 
 * Dumps the object to an XML element. Unsafe. 
 */
xml::Element FeatureExtractorProjection::serialize(xml::Element &parent) const
{
	xml::Element el(parent.PushBackElement(GetClassName()));
	el.SetAttribute("directions", int(dirs));
	el.SetAttribute("size", size);
	el.SetAttribute("maxval", maxval);
	return el;
}
Exemplo n.º 12
0
/*! 
 * Internal. Dumps some internal data to an XML element.
 *
 * \param[in]	el	the element that contains the serialized object
 */
void Savable::serialize_internal_data(xml::Element &el) const
{
	el.SetAttribute("name", name.CStr());
	if (user_data)
	{
		xml::Element udel = user_data->Serialize(el);
		udel.SetAttribute("role", USERDATA_NAME);
	}
}
Exemplo n.º 13
0
static void showElement(Xml::Element elt, const String& indent="") {
    cout << indent << "ELEMENT WITH TAG '" << elt.getElementTag() << "':\n";

    // Show attributes
    Xml::attribute_iterator ap = elt.attribute_begin();
    for (; ap != elt.attribute_end(); ++ap)
        cout << indent << "  ATTR '" << ap->getName() << "'='" 
             << ap->getValue() << "'\n";

    // Show all contents
    Xml::node_iterator p = elt.node_begin();
    for (; p != elt.node_end(); ++p) {
        cout << indent << p->getNodeTypeAsString() << endl;
        if (p->getNodeType() == Xml::ElementNode)
            showElement(Xml::Element::getAs(*p), indent + "  ");
    }
    cout << indent << "END OF ELEMENT.\n";
}
Exemplo n.º 14
0
void writeCppNs(xml::Element& node, const std::string& ns)
{
    const std::string& realNs = (ns.substr(0, 2) == "::") ? ns.substr(2) : ns;

    std::string startNs;
    std::string endNs;
    std::string::size_type pos = 0;
    std::string::size_type prevPos = 0;
    while((pos = realNs.find("::", pos)) != std::string::npos) {
        startNs += "namespace " + realNs.substr(prevPos, pos - prevPos) + " {\n";
        endNs += "}\n";
        pos += 2;
        prevPos = pos;
    }

    node.createElement("startCppNs", startNs);
    node.createElement("endCppNs", endNs);
}
Exemplo n.º 15
0
	//----------------------------------------------------------------------
	//
	//----------------------------------------------------------------------
	void LNFXManager::_analyzeXMLPassElement( XML::Element* xmlElement, IAnnotatedObject* parentTech )
	{
		// 属性
		const char* attrName = xmlElement->Attribute(NameAttributeName);
		LN_THROW_InvalidFormat(attrName);

		IAnnotatedObject* pass = mBuilder->OnCreatePass( parentTech, attrName );

		// 子要素
		XML::Element* xmlChild = xmlElement->FirstChildElement();
		while ( xmlChild != NULL )
		{
			// <VertexShader>
			if ( strcmp( xmlChild->Name(), VertexShaderElementName ) == 0 ) {
				attrName = xmlChild->Attribute( EntryPointAttributeName );
				GLSLCode* code = _findShaderCode(attrName);
				LN_THROW_InvalidFormat(code);
				mBuilder->OnCreateVertexShader( pass, code->Code.c_str(), code->Code.size() );
			}
			// <PixelShader>
			else if ( strcmp( xmlChild->Name(), PixelShaderElementName ) == 0 ) {
				attrName = xmlChild->Attribute( EntryPointAttributeName );
				GLSLCode* code = _findShaderCode(attrName);
				LN_THROW_InvalidFormat(code);
				mBuilder->OnCreatePixelShader( pass, code->Code.c_str(), code->Code.size() );
			}
			// <RenderState>
			else if ( strcmp( xmlChild->Name(), RenderStateElementName ) == 0 ) {
				attrName = xmlChild->Attribute(NameAttributeName);
				LN_THROW_InvalidFormat(attrName);
				const char* value = xmlChild->Attribute( ValueAttributeName );
				mBuilder->OnSetRenderState( pass, attrName, value );
			}
			// <Annotation>
			else if ( strcmp( xmlChild->Name(), AnnotationElementName ) == 0 ) {
				_analyzeXMLAnnotationElement( xmlChild, pass );
			}

			xmlChild = xmlChild->NextSiblingElement();
		}

		// link
		mBuilder->OnEndPass( pass );
	}
Exemplo n.º 16
0
/*!
 * Unsafe save
 * \throws	ExceptionProtocol	the content of the vector is not serializable
 *
 * \param[in]	parent	the parent element to which we will add the new element
 * \return The newly created element, nullptr if failed.
 */
xml::Element Vector::Serialize(xml::Element &parent) const
{
	xml::Element el(parent.PushBackElement(getClassName()));

	for (size_t tmp = 0; tmp < data.size(); tmp++)
	{
		xml::Element item = crn::Serialize(*data[tmp], el);
		item.SetAttribute("vector_index", int(tmp));
	}

	return el;
}
/*! 
 * Initializes the object from an XML element. Unsafe. 
 *
 * \throws	ExceptionInvalidArgument	not a FeatureExtractorProjection
 * \throws	ExceptionNotFound	attribute not found
 * \throws	ExceptionDomain	wrong attribute
 */
void FeatureExtractorProjection::deserialize(xml::Element &el)
{
	if (el.GetName() != GetClassName())
	{
		throw ExceptionInvalidArgument(StringUTF8("bool FeatureExtractorProjection::deserialize("
					"xml::Element &el): ") + _("Wrong XML element."));
	}
	int d = el.GetAttribute<int>("direction", false); // may throw
	int s = el.GetAttribute<int>("size", false); // may throw
	int m = el.GetAttribute<int>("maxval", false); // may throw
	dirs = Orientation(d);
	size = s;
	maxval = m;
}
Exemplo n.º 18
0
/*! 
 * Creates and initializes a CRNData from an XML element 
 *
 * \throws	ExceptionInvalidArgument	null XML element
 * \throws	ExceptionRuntime	impossible to read the XML element
 * \throws	ExceptionNotFound	unknown type
 *
 * \param[in]	el	the XML element to use for initialization
 * \return	a pointer to the newly created object, or nullptr if failed
 */
UObject DataFactory::CreateData(xml::Element &el)
{
	if (!el)
	{
		throw ExceptionInvalidArgument(StringUTF8("SObject DataFactory::CreateData(xml::Element &el): ") + 
				_("Null XML element."));
	}
	const StringUTF8 typ = el.GetValue();
	if (typ.IsEmpty())
	{
		throw ExceptionRuntime(StringUTF8("SObject DataFactory::CreateData(xml::Element &el): ") + _("Cannot read element."));
	}
	return getInstance().createObject(typ, el); // may throw
}
Exemplo n.º 19
0
	//----------------------------------------------------------------------
	//
	//----------------------------------------------------------------------
	void LNFXManager::_analyzeXMLTechniqueElement( XML::Element* xmlElement )
	{
		// 属性
		const char* attrName = xmlElement->Attribute( NameAttributeName );
		LN_THROW_InvalidFormat(attrName);

		IAnnotatedObject* tech = mBuilder->OnCreateTechnique( attrName );

		// 子要素
		XML::Element* xmlChild = xmlElement->FirstChildElement();
		while ( xmlChild != NULL )
		{
			// <Pass>
			if ( strcmp( xmlChild->Name(), PassElementName ) == 0 ) {
				_analyzeXMLPassElement( xmlChild, tech );
			}
			// <Annotation>
			else if ( strcmp( xmlChild->Name(), AnnotationElementName ) == 0 ) {
				_analyzeXMLAnnotationElement( xmlChild, tech );
			}

			xmlChild = xmlChild->NextSiblingElement();
		}
	}
Exemplo n.º 20
0
	bool TextureAtlas::load()
	{
		if (mLoaded)
		{
			return true;
		}

		XML::Document xml(mPath);

		if (!xml.isValid())
		{
			return false;
		}

		XML::Element e = xml.getElement("atlas");
		std::string texturePath = e.attribute("texture");
		GL_TextureManager::get().loadTexture(texturePath);
		mTexture = GL_TextureManager::get().acquireTexture(texturePath);

		for (e = e.first(); e.isValid(); e = e.next())
		{
			std::string key = e.name();

			if (key.compare("image") == 0)
			{
				ImageRect imageRect;
				e.attribute("x", imageRect.x);
				e.attribute("y", imageRect.y);
				e.attribute("w", imageRect.w);
				e.attribute("h", imageRect.h);
				mImageMap[e.attribute("name")] = imageRect;
			}
		}

		mLoaded = true;
		return true;

	}
Exemplo n.º 21
0
/***************************************************************
* Function: CodeParser::parseAssignStmt()
* Purpose : Parse the XML code of an assignment statement
* Initial : Maxime Chevalier-Boisvert on November 5, 2008
****************************************************************
Revisions and bug fixes:
*/
Statement* CodeParser::parseAssignStmt(const XML::Element* pElement)
{
	// Get the element corresponding to the left-expression
	XML::Element* pLeftElem = pElement->getChildElement(0);

	// Create a vector to store the left expressions
	AssignStmt::ExprVector leftExprs;

	// If the left expression is a matrix expression
	if (pLeftElem->getName() == "MatrixExpr")
	{
		// If the number of rows is not 1, throw an exception
		if (pLeftElem->getNumChildren() != 1)
			throw XML::ParseError("invalid matrix expression on assignment lhs");

		// Get the row element
		XML::Element* pRowElem = pLeftElem->getChildElement(0);

		// For each left expression element
		for (size_t i = 0; i < pRowElem->getNumChildren(); ++i)
		{
			// Get the child element for this expression
			XML::Element* pExprElem = pRowElem->getChildElement(i);

			// Parse this left-expression
			leftExprs.push_back(parseExpression(pExprElem));
		}
	}
	else
	{
		// Parse the left expression directly
		leftExprs.push_back(parseExpression(pLeftElem));
	}

	// Parse the right expression
	Expression* pRightExpr = parseExpression(pElement->getChildElement(1));

	// Get the output suppression flag
	bool suppressOut = pElement->getBoolAttrib("outputSuppressed");

	// Create and return the new assignment statement object
	return new AssignStmt(leftExprs, pRightExpr, suppressOut);
}
Exemplo n.º 22
0
void writeParam(xml::Element& elemParams, xml::Element& elemParam, const Param& param)
{
    elemParam.createElement("name", param.name);
    elemParam.createElement("description", param.description);
    elemParam.createElement("details", param.details);

    xml::Element& elemOptions = elemParam.createElement("options");
    for (StringMap::const_iterator itOption = param.options.begin();
         itOption != param.options.end(); ++itOption)
        elemOptions.createElement(itOption->first, itOption->second);
    elemParam.createElement("dataType") << param.dataType;

    std::string value = elemParams.getValue();
    if (!value.empty())
        value += ", ";

    dataTypeToString(value, param.dataType, true);
    value += " " + param.name;
    elemParams.setValue(value);
}
Exemplo n.º 23
0
/* Handle reading older formats/Versioning */
void InverseDynamicsTool::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
	int documentVersion = versionNumber;
	if ( documentVersion < XMLDocument::getLatestVersion()){
		std::string newFileName = getDocumentFileName();
		if (documentVersion < 20300){
			std::string origFilename = getDocumentFileName();
			newFileName=IO::replaceSubstring(newFileName, ".xml", "_v23.xml");
			cout << "Old version setup file encountered. Converting to new file "<< newFileName << endl;
			SimTK::Xml::Document doc = SimTK::Xml::Document(origFilename);
			doc.writeToFile(newFileName);
		}
		/*if (documentVersion < 20201) {
			AnalyzeTool updateAnalyzeTool(newFileName, false);
			updateAnalyzeTool.print(newFileName);
		}*/
		if (documentVersion < 20202){
			// get filename and use SimTK::Xml to parse it
			SimTK::Xml::Document doc = SimTK::Xml::Document(newFileName);
			Xml::Element oldRoot = doc.getRootElement();
			SimTK::Xml::Document newDoc;
			string prefix = "";
			if (oldRoot.getElementTag()=="AnalyzeTool"){
				// Make OpenSimDocument node and copy root underneath it
				newDoc.getRootElement().setElementTag("OpenSimDocument");
				newDoc.getRootElement().setAttributeValue("Version", "20201");
				prefix = oldRoot.getRequiredAttributeValueAs<string>("name");
				// Move all children of root to toolNode
				newDoc.getRootElement().insertNodeAfter(newDoc.getRootElement().node_end(), oldRoot.clone());
			}
			else
				newDoc = doc;
			Xml::Element root = newDoc.getRootElement();
			if (root.getElementTag()=="OpenSimDocument"){
				int curVersion = root.getRequiredAttributeValueAs<int>("Version");
				if (curVersion <= 20201) root.setAttributeValue("Version", "20300");
				Xml::element_iterator iterTool(root.element_begin("AnalyzeTool"));
				iterTool->setElementTag("InverseDynamicsTool");
				prefix = iterTool->getRequiredAttributeValueAs<string>("name");
				// Remove children <output_precision>, <initial_time>, <final_time>
				Xml::element_iterator initTimeIter(iterTool->element_begin("initial_time"));
				double tool_initial_time = initTimeIter->getValueAs<double>();
				if (initTimeIter->isValid()) iterTool->eraseNode(initTimeIter);
				Xml::element_iterator finalTimeIter(iterTool->element_begin("final_time"));
				double tool_final_time = finalTimeIter->getValueAs<double>();
				if (finalTimeIter->isValid()) iterTool->eraseNode(finalTimeIter);
				Xml::element_iterator precisionIter(iterTool->element_begin("output_precision"));
				if (precisionIter->isValid()) iterTool->eraseNode(precisionIter);
				bool use_model_forces=false;
				// Handle missing or uninitialized values after parsing the old InverseDynamics "Analysis"
				// Find Analyses underneath it AnalyzeTool
				Xml::element_iterator iterAnalysisSet(iterTool->element_begin("AnalysisSet"));
				Xml::element_iterator iterObjects(iterAnalysisSet->element_begin("objects"));
				Xml::element_iterator iterAnalysis(iterObjects->element_begin("InverseDynamics"));
				if (iterAnalysis!= iterObjects->element_end()){
					// move children to top level
					Xml::element_iterator p = iterAnalysis->element_begin();
					//std::vector<std::string> deprectaed({"on", "in_degrees", "step_interval"});
					for (; p!= iterAnalysis->element_end(); ++p) {
						// skip <on>, <step_interval>, <in_degrees>
						if (p->getElementTag()=="on" ||
							p->getElementTag()=="in_degrees" ||
							p->getElementTag()=="step_interval" ||
							p->getElementTag()=="start_time" ||
							p->getElementTag()=="end_time")
							continue;
						else if (p->getElementTag()=="use_model_force_set"){
							String use_model_forcesStr = p->getValueAs<String>();
							use_model_forces = (use_model_forcesStr=="true");
						}
						else
							iterTool->insertNodeAfter( iterTool->node_end(), p->clone());
					}
					// insert elements for "forces_to_exclude" & "time_range"
					std::ostringstream stream;
					stream << tool_initial_time << " " << tool_final_time;
					iterTool->insertNodeAfter( iterTool->node_end(), Xml::Element("time_range", stream.str()));
					iterTool->insertNodeAfter( iterTool->node_end(), Xml::Element("forces_to_exclude", use_model_forces?"":"Muscles"));
					iterTool->insertNodeAfter( iterTool->node_end(), Xml::Element("output_gen_force_file", prefix+"_InverseDynamics.sto"));
					iterTool->insertNodeAfter( iterTool->node_end(), Xml::Element("coordinates_in_degrees", "true"));
					iterTool->eraseNode(iterAnalysisSet);
				}
				newDoc.writeToFile(newFileName);
				setDocument(new XMLDocument(newFileName));
				aNode = updDocument()->getRootDataElement();
			}

		}
	}
	Object::updateFromXMLNode(aNode, versionNumber);
}
Exemplo n.º 24
0
 FundamentalType (XML::Element<C> const& e)
 {
   std::basic_stringstream<C> s;
   s << e.value ();
   s >> x_;
 }
Exemplo n.º 25
0
/*! 
 * Dumps the object to an XML element. Unsafe. 
 *
 * \param[in]	parent	the parent element to which we will add the new element
 * \return	The newly created element, nullptr if failed.
 */
xml::Element StringUTF8::Serialize(xml::Element &parent) const
{
	xml::Element el(parent.PushBackElement("StringUTF8"));
	el.PushBackText(*this);
	return el;
}
Exemplo n.º 26
0
/*!
 * Dumps the object to an XML element. Unsafe.
 *
 * \param[in]	parent	the parent element to which we will add the new element
 * \return	The newly created element, nullptr if failed.
 */
xml::Element String::Serialize(xml::Element &parent) const
{
	xml::Element el(parent.PushBackElement("String"));
	el.PushBackText(CStr());
	return el;
}
Exemplo n.º 27
0
/***************************************************************
* Function: CodeParser::parseScript()
* Purpose : Parse the XML root element
* Initial : Maxime Chevalier-Boisvert on November 18, 2008
****************************************************************
Revisions and bug fixes:
*/
CompUnits CodeParser::parseXMLRoot(const XML::Element* pTreeRoot)
{
	// Create a list to store parsed functions
	CompUnits functionList;

	// If the root tag is not the compilation units, throw an exception
	if (pTreeRoot->getName() != "CompilationUnits")
	{
		// TODO: implement error list parsing
		std::cout << "XML tree: " << pTreeRoot->toString(true, 0) << std::endl;
		
		throw XML::ParseError("Expected compilation units: \"" + pTreeRoot->getName() + "\"", pTreeRoot->getTextPos());
	}

	// If the verbose output flag is set
	if (ConfigManager::s_verboseVar.getBoolValue() == true)
	{
		// Log the number of compilation units
		std::cout << "Number of compilation units: " << pTreeRoot->getNumChildren() << std::endl;
	}

	// For each compilation unit
	for (size_t i = 0; i < pTreeRoot->getNumChildren(); ++i)
	{
		// Get a pointer to this element
		XML::Element* pUnitElement = pTreeRoot->getChildElement(i);

		// If this is a function list
		if (pUnitElement->getName() == "FunctionList")
		{
			// Get the list of functions
			const std::vector<XML::Node*>& functions = pUnitElement->getChildren();

			// For each function
			for (std::vector<XML::Node*>::const_iterator itr = functions.begin(); itr != functions.end(); ++itr)
			{
				// If this is not an XML element, throw an exception
				if ((*itr)->getType() != XML::Node::ELEMENT)
					throw XML::ParseError("Unexpected XML node type in function list");

				// Get a pointer to this element
				XML::Element* pFuncElement = (XML::Element*)*itr;

				// If this ia a function declaration
				if (pFuncElement->getName() == "Function")
				{
					// Parse the function
					IIRNode* pNewNode = parseFunction(pFuncElement);

					// Add the function to the list
					functionList.push_back(pNewNode);
				}

				// If this is a symbol table
				else if (pFuncElement->getName() == "Symboltable")
				{
					// Ignore for now
				}

				// Otherwise
				else
				{
					// This is an invalid element, throw an exception
					throw XML::ParseError("Invalid element in function list: \"" + pFuncElement->getName() + "\"", pFuncElement->getTextPos());
				}
			}
		}

		// If this is a script
		else if (pUnitElement->getName() == "Script")
		{
			// Parse the script
			IIRNode* pNewNode = parseScript(pUnitElement);

			// Add the function to the list
			functionList.push_back(pNewNode);
		}

		// Otherwise
		else
		{
			// This is an invalid element, throw an exception
			throw XML::ParseError("Invalid element in compilation unit list: \"" + pUnitElement->getName() + "\"", pUnitElement->getTextPos());
		}
	}

	// If the verbose output flag is set
	if (ConfigManager::s_verboseVar.getBoolValue() == true)
	{
		// Output parsed IIR
		std::cout << std::endl;
		std::cout << "Constructed IIR:" << std::endl;
		for (CompUnits::iterator itr = functionList.begin(); itr != functionList.end(); ++itr)
			std::cout << ((*itr) == NULL? "NULL":(*itr)->toString()) << std::endl << std::endl;
		std::cout << std::endl;

		// Log that the parsing was successful
		std::cout << "Parsing successful" << std::endl;
	}

	// Return the parsed function list
	return functionList;
}
Exemplo n.º 28
0
// Read a hex + alpha colour from xml //
Colour Loader::readColour(const XML::Element& e) const {
	const char* s = e.attribute("colour", "ffffff");
	Colour c = Loader::parseHex(s);
	c.a = e.attribute("alpha", 1.0f);
	return c;
}
Exemplo n.º 29
0
 Parser (XML::Element<C> const& e)
     : e_ (e.dom_element ()->getChildNodes ()), ei_ (0),
       a_ (e.dom_element ()->getAttributes ()), ai_ (0)
 {
 }
Exemplo n.º 30
0
/***************************************************************
* Function: CodeParser::parseFunction()
* Purpose : Parse the XML code of a function
* Initial : Maxime Chevalier-Boisvert on November 3, 2008
****************************************************************
Revisions and bug fixes:
*/
ProgFunction* CodeParser::parseFunction(const XML::Element* pElement)
{
	// Get the function name
	std::string funcName = pElement->getStringAttrib("name");

	// Declare a pointer for the sequence statement
	StmtSequence* pSequenceStmt = NULL;

	// Declare vectors for the input and output parameters
	ProgFunction::ParamVector inParams;
	ProgFunction::ParamVector outParams;

	// Declare a vector for the nested function list
	ProgFunction::FuncVector nestedFuncs;

	// For each child element
	for (size_t i = 0; i < pElement->getNumChildren(); ++i)
	{
		// Get a pointer to this element
		XML::Element* pFuncElement = pElement->getChildElement(i);

		// If this is a symbol table
		if (pFuncElement->getName() == "Symboltable")
		{
			// Ignore for now
		}

		// If this is a parameter declaration list
		else if (pFuncElement->getName() == "ParamDeclList")
		{
			// Ignore for now
		}

		// If this is an input parameter list
		else if (pFuncElement->getName() == "InputParamList")
		{
			// For each child element
			for (size_t i = 0; i < pFuncElement->getNumChildren(); ++i)
			{
				// Get the parameter name
				const std::string& paramName = pFuncElement->getChildElement(i)->getStringAttrib("nameId");

				// Add the parameter to the list
				inParams.push_back(SymbolExpr::getSymbol(paramName));
			}
		}

		// If this is an output parameter list
		else if (pFuncElement->getName() == "OutputParamList")
		{
			// For each child element
			for (size_t i = 0; i < pFuncElement->getNumChildren(); ++i)
			{
				// Get the parameter name
				const std::string& paramName = pFuncElement->getChildElement(i)->getStringAttrib("nameId");

				// Add the parameter to the list
				outParams.push_back(SymbolExpr::getSymbol(paramName));
			}
		}

		// If this is a nested function list
		else if (pFuncElement->getName() == "NestedFunctionList")
		{
			// For each child element
			for (size_t i = 0; i < pFuncElement->getNumChildren(); ++i)
			{
				// Parse this function declaration
				ProgFunction* pFunction = parseFunction(pFuncElement->getChildElement(i));

				// Add the nested function to the list
				nestedFuncs.push_back(pFunction);
			}
		}

		// If this is the statement list
		else if (pFuncElement->getName() == "StmtList")
		{
			// If the statement list was already encountered, throw an exception
			if (pSequenceStmt != NULL)
				throw XML::ParseError("Duplicate statement list", pElement->getTextPos());

			// Parse the statement list
			pSequenceStmt = parseStmtList(pFuncElement);
		}

		// Otherwise
		else
		{
			// This is an invalid element type, throw an exception
			throw XML::ParseError("Invalid element type in script: \"" + pFuncElement->getName() + "\"", pFuncElement->getTextPos());
		}
	}

	// If the statement list is missing, throw an exception
	if (pSequenceStmt == NULL)
		throw XML::ParseError("Missing statement list", pElement->getTextPos());

	// Create a new program function object
	ProgFunction* pNewFunc = new ProgFunction(
		funcName,
		inParams,
		outParams,
		nestedFuncs,
		pSequenceStmt
	);

	// For each nested function
	for (ProgFunction::FuncVector::iterator nestItr = nestedFuncs.begin(); nestItr != nestedFuncs.end(); ++nestItr)
	{
		// Set the parent pointer to the newly created function object
		(*nestItr)->setParent(pNewFunc);
	}

	// Return the new program function object
	return pNewFunc;
}