Beispiel #1
0
	void Font::loadFont( const char* xmlFile )
	{
		XMLParser parser( xmlFile );
		XMLDocument& doc = parser.getDocument();		
		
		if( !doc.Error() )
		{		
			XMLNode* root = doc.FirstChildElement( "FontDefinition" );
			XMLNode* fontInfo = root->FirstChildElement( "FontInfo" );
			m_fontName = parser.getXMLAttributeAsString( fontInfo, "name", "" );
			m_fontLocale = parser.getXMLAttributeAsString( fontInfo, "local", "en" );
			m_pixelHeight = parser.getXMLAttributeAsInt( fontInfo, "cellPixelHeight", 1 );


			XMLNode* element; 
			for( element = root->FirstChildElement( "Glyph" ); element != 0; element = element->NextSiblingElement( "Glyph" ) )
			{
				Glyph g = loadGlyph( parser, element );
				m_glyphs.insert( std::pair< unsigned char, Glyph >( g.ucsIndex, g ) );
			}
		}
		else
		{
			MonkyException::simpleErrorMessageBox( "Failed to load font", "File could not be opened" );
		}
	}
 void Rigidbody::deserialize(XMLNode* node) {
     XMLNode* t = node->FirstChildElement("Velocity");
     t->FirstChildElement("X")->QueryFloatText(&(this->velocity.x));
     t->FirstChildElement("Y")->QueryFloatText(&this->velocity.y);
     t = node->FirstChildElement("Acceleration");
     t->FirstChildElement("X")->QueryFloatText(&(this->acceleration.x));
     t->FirstChildElement("Y")->QueryFloatText(&this->acceleration.y);
     node->FirstChildElement("RadialVelocity")->QueryFloatText(&this->radialVelocity);
 }
//---------------------------------------------------------------------------------
SpriteAnimation::SpriteAnimation( const std::string& animationFile )
    :	m_frameRate( 0.0f )
    ,	m_isLoop( false )
    ,	m_material( "" )
    , 	m_isPlaying( false )
    ,	m_lastFrameTime( 0.0f )
    ,	m_currentFrameNumber( 0 )
{
    XMLParser parser( animationFile.c_str(), false );
    XMLDocument& doc = parser.getDocument();

    if( !doc.Error() )
    {
        consolePrintf( "Loading animation: %s", animationFile.c_str() );
        XMLNode* animation = doc.FirstChildElement( "Animation" );
        parser.validateXMLAttributes( animation, "frameRate,material", "isLooping,startPlaying" );
        parser.validateXMLChildElements( animation, "Frame", "" );

        float frameRate = parser.getXMLAttributeAsFloat( animation, "frameRate", 0.0f );
        bool isLooping = parser.getXMLAttributeAsBool( animation, "isLooping", false );
        bool startPlaying = parser.getXMLAttributeAsBool( animation, "startPlaying", false );
        std::string material = parser.getXMLAttributeAsString( animation, "material", "" );

        m_frameRate = frameRate;
        m_isLoop = isLooping;
        m_material = material;

        XMLNode* frame;
        for( frame = animation->FirstChildElement( "Frame" ); frame != nullptr; frame = frame->NextSiblingElement( "Frame" ) )
        {
            parser.validateXMLChildElements( frame, "TexCoords", "Material" );
            XMLNode* texCoords = frame->FirstChildElement( "TexCoords" );
            XMLNode* material = frame->FirstChildElement( "Material" );
            parser.validateXMLAttributes( texCoords, "topLeft,width,height", "" );
            vec2f topLeft = parser.getXMLAttributeAsVec2( texCoords, "topLeft", vec2f() );
            float width = parser.getXMLAttributeAsFloat( texCoords, "width", 1.0f );
            float height = parser.getXMLAttributeAsFloat( texCoords, "height", 1.0f );

            std::string materialName;
            if( material != nullptr )
            {
                parser.validateXMLAttributes( material, "name", "" );
                materialName = parser.getXMLAttributeAsString( material, "name", "" );

            }
            AddFrame( topLeft, width, height, materialName );
        }

        if( startPlaying )
        {
            Play();
        }
        consolePrintf( "Successfully loaded animation: %s", animationFile.c_str() );
    }
}
bool AudioResourceManager::initialize()
{
    srand(time(NULL));
    Ogre::String path = Ogre::macBundlePath() + "/Contents/Resources/media/config/audio_events.xml";
    //xml_document<> doc;    // character type defaults to char
    FILE *audioConfigFile = fopen(path.data(), "r");
    
    std::vector<char> buffer;
    int c;
    while (EOF !=(c=getc(audioConfigFile))){
        buffer.push_back(c);
    }
   
    
    char buf[buffer.size()];
    for (int i = 0; i < buffer.size(); i++){
        buf[i] = buffer[i];
    }
    XMLDocument doc;
    doc.Parse(buf);

    XMLElement *eventIter = doc.FirstChildElement()->FirstChildElement();
    
    
    unsigned int currentHandle = 0;
    
    while (eventIter != NULL)
    {
        XMLNode *unitIter = eventIter->FirstChildElement()->NextSiblingElement();
        std::string eventName = eventIter->FirstChildElement()->GetText();
        
        while (unitIter != NULL) {
            AudioResource unit;
            
            unit.filename = unitIter->FirstChildElement("filename")->GetText();// first_node("filename")->value();
            printf("filename: %s\n", unit.filename.c_str());
            unit.panning = atof(unitIter->FirstChildElement("panning")->GetText());
            unit.pitch = atof(unitIter->FirstChildElement("pitch")->GetText());
            unit.looping = atoi(unitIter->FirstChildElement("looping")->GetText());
            unit.gain = atof(unitIter->FirstChildElement("gain")->GetText());
            unit.bufferHandle = -1;
            unit.sourceHandle = -1;
            if ( eventName == "apply_force_left" || eventName == "apply_force_right" || eventName=="fall_off") unit.canStop = false;
            else unit.canStop = true;
            alGenSources(1, &unit.sourceHandle);
            resources[eventName].push_back(unit);
            
            unitIter = unitIter->NextSibling();
        }
        
        eventIter = eventIter->NextSiblingElement();
    }
    return true;
}
void BirdConfiguration::parseConfiguration(string number) {
	using namespace tinyxml2;
	XMLDocument configurationDoc;
	configurationDoc.LoadFile(file_path.c_str());
	XMLElement* element;
	XMLNode* node;
	XMLNode* rootNode = configurationDoc.FirstChild();
	node=rootNode;

	(*this)["Predator"] = "false";
	(*this)["Number"] = number;

	element = node->FirstChildElement();
	string elm_str;
	while(element){
		elm_str =element->GetText();

		elm_str.erase(std::remove_if(elm_str.begin(),
				elm_str.end(),
				[](char x){return isspace(x);}),
				elm_str.end());

		(*this)[element->Name()] = elm_str;
		element=element->NextSiblingElement();
	}
}
model::describe_snapshots_response::describe_snapshots_response(const string &xml_doc)
{
	XMLDocument doc;
	doc.Parse(xml_doc.c_str());
	//Root
	XMLNode *RootNode = doc.FirstChild();
	XMLElement *Element = RootNode->FirstChildElement("requestId");
	if(Element!=NULL)
	{
		request_id = Element->GetText();
		Element=Element->NextSiblingElement();
	}
	else cout<<"Error Parsing Request ID from XML describe_snapshots_response\n";
	XMLElement *ListElement = Element->FirstChildElement("item");
	XMLElement *SnapshotElement;
	string status, snapshot_id,  start_time, volume_id;
	float volume_size;
	while(ListElement != NULL)
	{
		SnapshotElement = ListElement->FirstChildElement("status");
		if(SnapshotElement!=NULL)
		{
			status = SnapshotElement->GetText();
			SnapshotElement = SnapshotElement->NextSiblingElement();
		}
		else cout<<"Error Parsing status from XML describe_snapshots_response\n";

		if(SnapshotElement!=NULL)
		{	
			snapshot_id = SnapshotElement->GetText();
			SnapshotElement=SnapshotElement->NextSiblingElement();
		}
		else cout<<"Error Parsing snapshot_id from XML describe_snapshots_response\n";

		if(SnapshotElement!=NULL)
		{
			SnapshotElement->QueryFloatText(&volume_size);
			SnapshotElement=SnapshotElement->NextSiblingElement();
		}
		else cout<<"Error Parsing volume_size from XML describe_snapshots_response\n";
		
		if(SnapshotElement!=NULL)
		{
			volume_id=SnapshotElement->GetText();
			SnapshotElement=SnapshotElement->NextSiblingElement();
		}
		else cout<<"Error Parsing volume_id from XML describe_snapshots_response\n";
		
		if(SnapshotElement!=NULL)
			if(SnapshotElement->GetText()!=NULL) start_time = SnapshotElement->GetText();
		else cout<<"Error Parsing start_time from XML describe_snapshots_response\n";
		//add to map
		model::snapshot data(status,snapshot_id,volume_size,volume_id,start_time);
		snapshot_set.push_back(data);
		ListElement=ListElement->NextSiblingElement();
	}

}
TestData readXMLDoc() {

    XMLDocument doc;
#ifdef WIN32
    XMLCheckResult(doc.LoadFile("../../test/mpw_tests.xml"));
#else
    XMLCheckResult(doc.LoadFile("mpw_tests.xml"));
#endif

    TestData data;
    XMLNode * pRoot = doc.FirstChild();
    if (pRoot == 0) return data;

    XMLElement * pListElement = pRoot->FirstChildElement("case");
    TestData testData;

    while (pListElement != 0) {
        //We have a test case. Allocate memory for it.
        TestCase testCase;

        //Get the ID of this case
        std::string id = pListElement->Attribute("id");
        std::cout << "ID: " << id << std::endl;

        //Now check if we have a parent.
        const char* pParent = pListElement->Attribute("parent");
        if (pParent) {
            testCase = testData.at(pParent);
        }

        //Now fill in the data from this node.
        XMLElement * pNodeListElement = pListElement->FirstChildElement();
        while (pNodeListElement != 0) {
            const char* name = pNodeListElement->Name();
            const char* value = pNodeListElement->GetText();
            if (value != 0) {
                testCase[name] = value;
                std::cout << name << ": " << testCase[name] << std::endl;
            }
            else {
                testCase[name] = "";
                std::cout << name << ": " << "null" << std::endl;
            }
            pNodeListElement = pNodeListElement->NextSiblingElement();
        }

        testData[id] = testCase;

        pListElement = pListElement->NextSiblingElement("case");
    }

    return testData;
}
Beispiel #8
0
	DatabaseRule::DatabaseRule( XMLNode* ruleNode )
		: m_ruleScore( 0 )
	{
		m_ruleName = getStringXMLAttribute( ruleNode, "name", "noRule" );
		XMLNode* criteriaListNode = ruleNode->FirstChildElement( "Criteria" );
		for( XMLNode* criteriaNode = criteriaListNode->FirstChildElement( "Criterion" ); criteriaNode; criteriaNode = criteriaNode->NextSiblingElement("Criterion") )
		{
			addCriteria( criteriaNode );
		}
		XMLNode* responseNode = ruleNode->FirstChildElement( "Response" );
		m_responseName = getStringXMLAttribute( responseNode, "name", "noname" );
	}
Beispiel #9
0
//read high scores XML ===============================
std::string loadScores ( int player )
{
	int counter=0;
	XMLDocument* doc = new XMLDocument();
	doc->LoadFile ( "highscore.xml" );
	int errorID = doc->ErrorID();
	std::string err = doc->ErrorName();
	std::string playerString[20][3];
	XMLPrinter printer;
	//std::cout << "Test file loaded. ErrorID = "<<errorID<<" "<<err<<std::endl;
	if ( errorID!=0 )
		return "";
	XMLNode* root = doc->FirstChildElement ( "players" );
	if ( root == NULL ) {
		std::cout<<"error xml root"<<std::endl;
		return "";
	}
	XMLElement* node = root->FirstChildElement ( "player" )->ToElement();
	if ( node == NULL ) {
		std::cout<<"error xml"<<std::endl;
		return "";
	}
	while ( node->NextSiblingElement() !=NULL && counter<=player ) {
		XMLElement* element = node->FirstChildElement ( "name" )->ToElement();
		if ( element == NULL ) {
			std::cout<<"error xml"<<std::endl;
			return "";
		}
		playerString[counter][0] = element->GetText();
		//std::cout <<"playerstring="<<playerString[counter][0]<<std::endl;
		element = element->NextSiblingElement ( "score" )->ToElement();
		if ( element == NULL ) {
			std::cout<<"error xml"<<std::endl;
			return "";
		}
		playerString[counter][1] = element->GetText();
		element = element->NextSiblingElement ( "mode" )->ToElement();
		if ( element == NULL ) {
			std::cout<<"error xml"<<std::endl;
			return "";
		}
		playerString[counter][2] = element->GetText();
		node = node->NextSiblingElement ( "player" )->ToElement();
		if ( node == NULL ) {
			std::cout<<"error xml"<<std::endl;
			return "";
		}
		counter++;
	}
	return playerString[player][0]+", "+playerString[player][1]+", "
		+playerString[player][2];
}
void PanelMundo::cargarNombreMundos() {
	/* En el directorio donde se encuentra el ejecutable, se almacenará un
	 * archivo donde se encuentran todos los mundos que ha creado el diseñador.
	 * Ese archivo se llamará "mundos.xml"
	 */
	XMLDocument doc;
	bool seAbrio = doc.LoadFile(pathFileMundos);
	// Si el archivo no existe, lo creo y salgo sin cargar mundos
	if (!seAbrio) {
		this->crearArchivoMundos();
		return;
	}

	// Obtengo el nodo raiz
	XMLNode* root = doc.RootElement();
	// Si es nulo, salgo sin realizar nada
	if (root == 0)
		return;

	// Obtengo el primer nodo del mundo
	const XMLNode* nodoMundo = root->FirstChildElement("Mundo");
	// Mientras el nodo de mundo no es nulo, cargo los mundos.
	while (nodoMundo != 0) {
		// Obtengo el nodo con el nombre del Mundo.
		const XMLNode* nodoNombre = nodoMundo->FirstChildElement("Nombre");
		std::string nombreMundo = nodoNombre->GetText();
		// Obtengo el atributo de la cantidad de jugadores
		int cantJugadores;
		const char* aCJ = nodoMundo->Attribute("cantJugadores", &cantJugadores);
		if (aCJ != 0) {
			std::string sCantJug = cfd::intToString(cantJugadores);
			nombreMundo += " (" + sCantJug;
			// Si la cantidad de jugadores es 1
			if (cantJugadores == 1) {
				nombreMundo += " jugador)";
			} else {
				nombreMundo += " jugadores)";
			}
		}
		// Obtengo el nodo con la ruta de archivo del mundo.
		const XMLNode* nodoRuta = nodoMundo->FirstChildElement("Ruta");
		// Si los nodos no son nulos, cargo el mundo a la tabla
		if ((nodoNombre != 0) && (nodoRuta != 0)) {
			nombreMundos[nombreMundo] = nodoRuta->GetText();
		}
		// Obtengo el siguiente nodo Mundo
		nodoMundo = nodoMundo->NextSiblingElement("Mundo");
	}
}
int parseDoc()
{
	XMLNode * root = doc.FirstChild();
	if(root == nullptr)
	{
		return XML_ERROR_FILE_READ_ERROR;
	}
	XMLElement * tuixml = root->FirstChildElement("tuixml");
	if(tuixml == nullptr)
	{
		return XML_ERROR_PARSING_ELEMENT;
	}
	XMLElement * temp = tuixml->FirstChildElement();
	layers.push_back(layer);
	createElementLayers(temp);
}
Beispiel #12
0
Level* LevelParser::parseLevel(const char* levelFile)
{
	// create a TinyXML document and load the XML level
	XMLDocument xmlDoc;
	if (xmlDoc.LoadFile(levelFile) != XML_SUCCESS)
	{
		std::cout << "Error: unable to load " << levelFile << std::endl;
		return nullptr;
	}

	// create the level object
	Level* pLevel = new Level();

	// get the root node
	XMLNode* pRoot = xmlDoc.RootElement();

	pRoot->ToElement()->QueryAttribute("tilewidth", &m_tileSize);
	pRoot->ToElement()->QueryAttribute("width", &m_width);
	pRoot->ToElement()->QueryAttribute("height", &m_height);
	pLevel->m_width = m_width;
	pLevel->m_height = m_height;
	pLevel->m_tileSize = m_tileSize;
	// Attribute() returns null if not found and std::string cannot be initialized with nullptr.
	const char* musicID = nullptr;
	musicID = pRoot->ToElement()->Attribute("musicID");
	if (musicID == nullptr) musicID = "";
	pLevel->setMusic(musicID);

	// parse object and tile layers
	for (XMLElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
	{
		if (e->Value() == std::string("objectgroup"))
		{
			parseObjLayer(e, pLevel);
		}
		else if (e->Value() == std::string("layer"))
		{
			parseTileLayer(e, pLevel);
		}
		else if (e->Value() == std::string("background"))
		{
			parseBckLayer(e, pLevel);
		}
	}

	return pLevel;
}
model::delete_snapshot_response::delete_snapshot_response(const string &xml_doc)
{
	XMLDocument doc;
	doc.Parse(xml_doc.c_str());
	//Root
	XMLNode *RootNode = doc.FirstChild();
	XMLElement *Element = RootNode->FirstChildElement("requestId");
	if(Element!=NULL)
	{	if(Element->GetText()!=NULL)request_id = Element->GetText();
		Element=Element->NextSiblingElement();
	}
	else cout<<"Error Parsing request_id from XML delete_snapshot_response\n";
	
	if(Element!=NULL)
		Element->QueryBoolText(&result);
	else cout<<"Error Parsing result from XML delete_snapshot_response\n";
}	
Beispiel #14
0
void Response::ParseStatus()
{
  int errorCode;
  std::string errorDescription;

  XMLNode *rootElement = m_document->RootElement();
  XMLElement *statusElement = rootElement->FirstChildElement(GetStatusElementName().c_str());

  // Not all response types always return the status element
  if (statusElement)
  {
    errorCode = xmltv::Utilities::QueryIntText(statusElement->FirstChildElement("ErrorCode"));
    errorDescription = statusElement->FirstChildElement("ErrorDescription")->GetText();

    m_error.code = static_cast<ErrorCode>(errorCode);
    m_error.description = errorDescription;
  }
}
model::describe_instance_types_response::describe_instance_types_response(const string &xml_doc)
{
	XMLDocument doc;
	doc.Parse(xml_doc.c_str());
	//Root
	XMLNode *RootNode = doc.FirstChild();
	XMLElement *Element = RootNode->FirstChildElement("requestId");
	if(Element!=NULL)
	{
		if(Element->GetText()!=NULL) request_id = Element->GetText();
		Element=Element->NextSiblingElement();
	}
	else cout<<"Error Parsing request_id from XML describe_instance_types_response\n";
	
	XMLElement *InstanceTypeElement,*ListElement = Element->FirstChildElement("item");
	float vcpus,ram;
	string id;
	while(ListElement != NULL)
	{
		InstanceTypeElement = ListElement->FirstChildElement("vcpus");
		if(InstanceTypeElement!=NULL)
		{
			InstanceTypeElement->QueryFloatText(&vcpus);
			InstanceTypeElement = InstanceTypeElement->NextSiblingElement();
		}
		else cout<<"Error Parsing VCPUS from XML describe_instance_types_response\n";
		if(InstanceTypeElement!=NULL)
		{	
			InstanceTypeElement->QueryFloatText(&ram);
			InstanceTypeElement = InstanceTypeElement->NextSiblingElement();
		}
		else cout<<"Error Parsing RAM data from XML describe_instance_types_response\n";

		if(InstanceTypeElement!=NULL)
			{if(InstanceTypeElement->GetText() != NULL)id = InstanceTypeElement->GetText();}
		else cout<<"Error Parsing instance_id from XML describe_instance_types_response\n";
		//Add to map
		model::instance_type data(vcpus, ram, id);
		instance_type_set.push_back(data);

		ListElement=ListElement->NextSiblingElement();
	}
}
model::start_instances_response::start_instances_response(const string &xml_doc)
{
	XMLDocument doc;
	doc.Parse(xml_doc.c_str());
	//Root
	XMLNode *RootNode = doc.FirstChild();
	XMLElement *Element = RootNode->FirstChildElement("requestId");
	if(Element!= NULL)
	{
		if(Element->GetText() != NULL)request_id = Element->GetText();
		Element = Element->NextSiblingElement();
	}	
	
	XMLElement *ListElement = Element->FirstChildElement("item");
	XMLElement *InstanceSetElement;
	string instance_id, current_state, previous_state; 
	while(ListElement != NULL)
	{
		InstanceSetElement = ListElement->FirstChildElement("instanceId");
		if(InstanceSetElement!=NULL)
		{
			if(InstanceSetElement->GetText()!=NULL)instance_id = InstanceSetElement->GetText();
			InstanceSetElement=InstanceSetElement->NextSiblingElement();
		}
		else cout<<"Error Parsing instance_id from start_instances_response";
		if(InstanceSetElement!=NULL)
		{	
			current_state = InstanceSetElement->GetText();
			InstanceSetElement=InstanceSetElement->NextSiblingElement();
		}
		else cout<<"Error Parsing current_state from XMl start_instances_response";
		
		if(InstanceSetElement!=NULL)
			{if(InstanceSetElement->GetText()!=NULL)previous_state = InstanceSetElement->GetText();}
		else cout<<"Error Parsing previous_state from XML start_instances_response";
		//Add to the map;
		model::instance_set data(instance_id, current_state, previous_state);
		instances.push_back(data);
		
		ListElement=ListElement->NextSiblingElement();
	}
}
Beispiel #17
0
	//------------------------------------------------
	void Sound::loadSoundsFromXMLFile( const std::string& filePath, const std::string& file )
	{
		std::string fullFilePath = filePath + file;
		XMLParser parser( fullFilePath.c_str() );
		XMLDocument& doc = parser.getDocument();

		if( !doc.Error() )
		{
			XMLNode* root = doc.FirstChildElement( "Sounds" );
			XMLNode* soundElement;
			for( soundElement = root->FirstChildElement( "Sound" ); soundElement != 0; soundElement = soundElement->NextSiblingElement( "Sound" ) )
			{
				parser.validateXMLAttributes( soundElement, "name,mode", "" );
				std::string soundName = parser.getXMLAttributeAsString( soundElement, "name", "" );
				std::string soundMode = parser.getXMLAttributeAsString( soundElement, "mode", "" );
				const char* soundFile = soundElement->GetText();
				Sound::createOrGetSound( soundName, filePath + std::string( soundFile ), getModeFromString( soundMode ) );
			}
		}
	}
Beispiel #18
0
	//----------------------------------------------------------------------
	void ReverbArea::loadReverbAreasFromXMLFile( const std::string& filePath, const std::string& file )
	{
		std::string fullFilePath = filePath + file;
		XMLParser parser( fullFilePath.c_str() );
		XMLDocument& doc = parser.getDocument();

		XMLNode* root = doc.FirstChildElement( "ReverbAreas" );
		XMLNode* reverbAreaElement = nullptr;
		for( reverbAreaElement = root->FirstChildElement( "ReverbArea" ); reverbAreaElement != nullptr; reverbAreaElement = reverbAreaElement->NextSiblingElement( "ReverbArea" ) )
		{
			parser.validateXMLAttributes( reverbAreaElement, "name,pos,minDist,maxDist", "preset" );
			std::string raName = parser.getXMLAttributeAsString( reverbAreaElement, "name", "" );
			vec3f pos = parser.getXMLAttributeAsVec3( reverbAreaElement, "pos", vec3f() );
			float minDist = parser.getXMLAttributeAsFloat( reverbAreaElement, "minDist", 0.0f );
			float maxDist = parser.getXMLAttributeAsFloat( reverbAreaElement, "maxDist", 0.1f );
			std::string preset = parser.getXMLAttributeAsString( reverbAreaElement, "preset", "MONKY_PRESET_OFF" );
			ReverbArea* ra = ReverbArea::createOrGetReverbArea( raName, getMonkyReverbPresetFromString( preset ) );
			ra->set3DAttributes( pos, minDist, maxDist );
		}
	}
Beispiel #19
0
	void MSMap::LoadObstacles( const std::string& fileName )
	{
		XMLParser parser( fileName.c_str() );
		XMLDocument& doc = parser.getDocument();

		if( !doc.Error() )
		{
			XMLNode* root = doc.FirstChildElement( "Obstacles" );
			XMLNode* obstacle = root->FirstChildElement( "Obstacle" );
			for( ; obstacle != nullptr; obstacle = obstacle->NextSiblingElement( "Obstacle" ) )
			{
				std::string material = parser.getXMLAttributeAsString( obstacle, "material", "" );
				vec2f dimensions = parser.getXMLAttributeAsVec2( obstacle, "dimensions", vec2f() );
				if( material != "" )
				{
					AddRandomObstacle( new Obstacle( material, aabb2f( vec2f(), dimensions.x, dimensions.y ) ) );
				}
			}
		}
	}
Beispiel #20
0
void emu::Settings::Load(char const * filename)
{
    XMLDocument xmlDoc;
    XMLError eResult = xmlDoc.LoadFile(filename);
    if (eResult != XML_SUCCESS)
    {
        //something went wrong with loading create a default one
        debugf(emu, "Can't load pspe4all.xml .Creating adefault one");
        CreateDefaultXml(filename);
        return;
    }
    XMLNode * pRoot = xmlDoc.FirstChild();
    XMLElement * pElement = pRoot->FirstChildElement("GeneralSettings");
    XMLElement * pListElement = pElement->FirstChildElement("CpuMode");
    cpumode = pListElement->GetText();
    pListElement = pListElement->NextSiblingElement("GeRenderer");
    gerenderer = pListElement->GetText();

    debugf(emu, "Loaded %s from pspe4all.xml", cpumode.c_str());
    debugf(emu, "Loaded %s from pspe4all.xml", gerenderer.c_str());
}
Beispiel #21
0
	//--------------------------------------------------------------
	void MapLoader::loadMap()
	{
		XMLParser parser( m_filePath.c_str() );
		XMLNode* map = parser.getDocument().FirstChildElement( "Map" );
		int width = parser.getXMLAttributeAsInt( map, "width", 0 );
		int height = parser.getXMLAttributeAsInt( map, "height", 0 );
		std::string theMap = parser.getXMLElementPCDataAsString( map );
		
		m_floorMesh = MeshFactory::generateAAPlaneXZ( width*WALL_WIDTH, height*WALL_WIDTH, "DirtFloorMat" );
		Actor* floorActor = new Actor( "The Floor", m_floorMesh );
		m_theGame->spawn( floorActor );

		int y = 0;
		for( XMLNode* row = map->FirstChildElement( "Row" ); row != nullptr; row = row->NextSiblingElement( "Row" ), ++y )
		{
			std::string strRow = parser.getXMLElementPCDataAsString( row );
			assertion( strRow.size() == width, "Number of tiles does not equal the specified width" );
			for( int x = 0; x < width; ++x )
			{
				char tileChar = strRow[ x ];
				Actor* actor = nullptr;
				switch( tileChar )
				{
				case '|':
					actor = new Actor( toString( x ) + toString( y ), m_wallMesh );
					actor->setScale( vec3f( WALL_DEPTH / WALL_WIDTH, 1.0f, 1.0f ) );
					break;
				case '-':
					actor = new Actor( toString( x ) + toString( y ), m_wallMesh );
					actor->setScale( vec3f( 1.0f, 1.0f, WALL_DEPTH / WALL_WIDTH ) );
					break;
				}
				if( actor != nullptr )
				{
					actor->setPosition( vec3f( x * WALL_WIDTH, 0.5f * WALL_WIDTH, y * WALL_WIDTH ) );
					m_theGame->spawn( actor );
				}
			}
		}
	}
Beispiel #22
0
int main( int argc, const char ** argv )
{
	#if defined( _MSC_VER ) && defined( DEBUG )
		_CrtMemCheckpoint( &startMemState );
	#endif

	#if defined(_MSC_VER) || defined(MINGW32) || defined(__MINGW32__)
		#if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR
			//MINGW64: both 32 and 64-bit
			mkdir( "resources/out/" );
                #else
                	_mkdir( "resources/out/" );
                #endif
	#else
		mkdir( "resources/out/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	#endif

	if ( argc > 1 ) {
		XMLDocument* doc = new XMLDocument();
		clock_t startTime = clock();
		doc->LoadFile( argv[1] );
		clock_t loadTime = clock();
		int errorID = doc->ErrorID();
		delete doc; doc = 0;
		clock_t deleteTime = clock();

		printf( "Test file '%s' loaded. ErrorID=%d\n", argv[1], errorID );
		if ( !errorID ) {
			printf( "Load time=%u\n",   (unsigned)(loadTime - startTime) );
			printf( "Delete time=%u\n", (unsigned)(deleteTime - loadTime) );
			printf( "Total time=%u\n",  (unsigned)(deleteTime - startTime) );
		}
		exit(0);
	}

	FILE* fp = fopen( "resources/dream.xml", "r" );
	if ( !fp ) {
		printf( "Error opening test file 'dream.xml'.\n"
				"Is your working directory the same as where \n"
				"the xmltest.cpp and dream.xml file are?\n\n"
	#if defined( _MSC_VER )
				"In windows Visual Studio you may need to set\n"
				"Properties->Debugging->Working Directory to '..'\n"
	#endif
			  );
		exit( 1 );
	}
	fclose( fp );

	XMLTest( "Example-1", 0, example_1() );
	XMLTest( "Example-2", 0, example_2() );
	XMLTest( "Example-3", 0, example_3() );
	XMLTest( "Example-4", true, example_4() );

	/* ------ Example 2: Lookup information. ---- */

	{
		static const char* test[] = {	"<element />",
										"<element></element>",
										"<element><subelement/></element>",
										"<element><subelement></subelement></element>",
										"<element><subelement><subsub/></subelement></element>",
										"<!--comment beside elements--><element><subelement></subelement></element>",
										"<!--comment beside elements, this time with spaces-->  \n <element>  <subelement> \n </subelement> </element>",
										"<element attrib1='foo' attrib2=\"bar\" ></element>",
										"<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>",
										"<element>Text inside element.</element>",
										"<element><b></b></element>",
										"<element>Text inside and <b>bolded</b> in the element.</element>",
										"<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>",
										"<element>This &amp; That.</element>",
										"<element attrib='This&lt;That' />",
										0
		};
		for( int i=0; test[i]; ++i ) {
			XMLDocument doc;
			doc.Parse( test[i] );
			doc.Print();
			printf( "----------------------------------------------\n" );
		}
	}
#if 1
	{
		static const char* test = "<!--hello world\n"
								  "          line 2\r"
								  "          line 3\r\n"
								  "          line 4\n\r"
								  "          line 5\r-->";

		XMLDocument doc;
		doc.Parse( test );
		doc.Print();
	}

	{
		static const char* test = "<element>Text before.</element>";
		XMLDocument doc;
		doc.Parse( test );
		XMLElement* root = doc.FirstChildElement();
		XMLElement* newElement = doc.NewElement( "Subelement" );
		root->InsertEndChild( newElement );
		doc.Print();
	}
	{
		XMLDocument* doc = new XMLDocument();
		static const char* test = "<element><sub/></element>";
		doc->Parse( test );
		delete doc;
	}
	{
		// Test: Programmatic DOM
		// Build:
		//		<element>
		//			<!--comment-->
		//			<sub attrib="1" />
		//			<sub attrib="2" />
		//			<sub attrib="3" >& Text!</sub>
		//		<element>

		XMLDocument* doc = new XMLDocument();
		XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) );

		XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) };
		for( int i=0; i<3; ++i ) {
			sub[i]->SetAttribute( "attrib", i );
		}
		element->InsertEndChild( sub[2] );
		XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) );
		element->InsertAfterChild( comment, sub[0] );
		element->InsertAfterChild( sub[0], sub[1] );
		sub[2]->InsertFirstChild( doc->NewText( "& Text!" ));
		doc->Print();
		XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() );
		XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) );
		XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) );
		XMLTest( "Programmatic DOM", "& Text!",
				 doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() );

		// And now deletion:
		element->DeleteChild( sub[2] );
		doc->DeleteNode( comment );

		element->FirstChildElement()->SetAttribute( "attrib", true );
		element->LastChildElement()->DeleteAttribute( "attrib" );

		XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) );
		int value = 10;
		int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value );
		XMLTest( "Programmatic DOM", result, (int)XML_NO_ATTRIBUTE );
		XMLTest( "Programmatic DOM", value, 10 );

		doc->Print();

		{
			XMLPrinter streamer;
			doc->Print( &streamer );
			printf( "%s", streamer.CStr() );
		}
		{
			XMLPrinter streamer( 0, true );
			doc->Print( &streamer );
			XMLTest( "Compact mode", "<element><sub attrib=\"1\"/><sub/></element>", streamer.CStr(), false );
		}
		doc->SaveFile( "./resources/out/pretty.xml" );
		doc->SaveFile( "./resources/out/compact.xml", true );
		delete doc;
	}
	{
		// Test: Dream
		// XML1 : 1,187,569 bytes	in 31,209 allocations
		// XML2 :   469,073	bytes	in    323 allocations
		//int newStart = gNew;
		XMLDocument doc;
		doc.LoadFile( "resources/dream.xml" );

		doc.SaveFile( "resources/out/dreamout.xml" );
		doc.PrintError();

		XMLTest( "Dream", "xml version=\"1.0\"",
						  doc.FirstChild()->ToDeclaration()->Value() );
		XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false );
		XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
						  doc.FirstChild()->NextSibling()->ToUnknown()->Value() );
		XMLTest( "Dream", "And Robin shall restore amends.",
						  doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
		XMLTest( "Dream", "And Robin shall restore amends.",
						  doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );

		XMLDocument doc2;
		doc2.LoadFile( "resources/out/dreamout.xml" );
		XMLTest( "Dream-out", "xml version=\"1.0\"",
						  doc2.FirstChild()->ToDeclaration()->Value() );
		XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false );
		XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
						  doc2.FirstChild()->NextSibling()->ToUnknown()->Value() );
		XMLTest( "Dream-out", "And Robin shall restore amends.",
						  doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );

		//gNewTotal = gNew - newStart;
	}


	{
		const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
							"<passages count=\"006\" formatversion=\"20020620\">\n"
							"    <wrong error>\n"
							"</passages>";

		XMLDocument doc;
		doc.Parse( error );
		XMLTest( "Bad XML", doc.ErrorID(), XML_ERROR_PARSING_ATTRIBUTE );
	}

	{
		const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

		XMLDocument doc;
		doc.Parse( str );

		XMLElement* ele = doc.FirstChildElement();

		int iVal, result;
		double dVal;

		result = ele->QueryDoubleAttribute( "attr0", &dVal );
		XMLTest( "Query attribute: int as double", result, (int)XML_NO_ERROR );
		XMLTest( "Query attribute: int as double", (int)dVal, 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XMLTest( "Query attribute: double as double", result, (int)XML_NO_ERROR );
		XMLTest( "Query attribute: double as double", (int)dVal, 2 );
		result = ele->QueryIntAttribute( "attr1", &iVal );
		XMLTest( "Query attribute: double as int", result, (int)XML_NO_ERROR );
		XMLTest( "Query attribute: double as int", iVal, 2 );
		result = ele->QueryIntAttribute( "attr2", &iVal );
		XMLTest( "Query attribute: not a number", result, (int)XML_WRONG_ATTRIBUTE_TYPE );
		result = ele->QueryIntAttribute( "bar", &iVal );
		XMLTest( "Query attribute: does not exist", result, (int)XML_NO_ATTRIBUTE );
	}

	{
		const char* str = "<doc/>";

		XMLDocument doc;
		doc.Parse( str );

		XMLElement* ele = doc.FirstChildElement();

		int iVal, iVal2;
		double dVal, dVal2;

		ele->SetAttribute( "str", "strValue" );
		ele->SetAttribute( "int", 1 );
		ele->SetAttribute( "double", -1.0 );

		const char* cStr = ele->Attribute( "str" );
		ele->QueryIntAttribute( "int", &iVal );
		ele->QueryDoubleAttribute( "double", &dVal );

		ele->QueryAttribute( "int", &iVal2 );
		ele->QueryAttribute( "double", &dVal2 );

		XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" );
		XMLTest( "Attribute round trip. c-string.", "strValue", cStr );
		XMLTest( "Attribute round trip. int.", 1, iVal );
		XMLTest( "Attribute round trip. double.", -1, (int)dVal );
		XMLTest( "Alternate query", true, iVal == iVal2 );
		XMLTest( "Alternate query", true, dVal == dVal2 );
	}

	{
		XMLDocument doc;
		doc.LoadFile( "resources/utf8test.xml" );

		// Get the attribute "value" from the "Russian" element and check it.
		XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" );
		const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU,
												0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };

		XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) );

		const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
														0xd1U, 0x81U, 0xd1U, 0x81U,
														0xd0U, 0xbaU, 0xd0U, 0xb8U,
														0xd0U, 0xb9U, 0 };
		const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

		XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText();
		XMLTest( "UTF-8: Browsing russian element name.",
				 russianText,
				 text->Value() );

		// Now try for a round trip.
		doc.SaveFile( "resources/out/utf8testout.xml" );

		// Check the round trip.
		int okay = 0;

		FILE* saved  = fopen( "resources/out/utf8testout.xml", "r" );
		FILE* verify = fopen( "resources/utf8testverify.xml", "r" );

		if ( saved && verify )
		{
			okay = 1;
			char verifyBuf[256];
			while ( fgets( verifyBuf, 256, verify ) )
			{
				char savedBuf[256];
				fgets( savedBuf, 256, saved );
				NullLineEndings( verifyBuf );
				NullLineEndings( savedBuf );

				if ( strcmp( verifyBuf, savedBuf ) )
				{
					printf( "verify:%s<\n", verifyBuf );
					printf( "saved :%s<\n", savedBuf );
					okay = 0;
					break;
				}
			}
		}
		if ( saved )
			fclose( saved );
		if ( verify )
			fclose( verify );
		XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay );
	}

	// --------GetText()-----------
	{
		const char* str = "<foo>This is  text</foo>";
		XMLDocument doc;
		doc.Parse( str );
		const XMLElement* element = doc.RootElement();

		XMLTest( "GetText() normal use.", "This is  text", element->GetText() );

		str = "<foo><b>This is text</b></foo>";
		doc.Parse( str );
		element = doc.RootElement();

		XMLTest( "GetText() contained element.", element->GetText() == 0, true );
	}


	// ---------- CDATA ---------------
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"I am > the rules!\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		XMLDocument doc;
		doc.Parse( str );
		doc.Print();

		XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(),
								 "I am > the rules!\n...since I make symbolic puns",
								 false );
	}

	// ----------- CDATA -------------
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"<b>I am > the rules!</b>\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		XMLDocument doc;
		doc.Parse( str );
		doc.Print();

		XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 false );
	}

	// InsertAfterChild causes crash.
	{
		// InsertBeforeChild and InsertAfterChild causes crash.
		XMLDocument doc;
		XMLElement* parent = doc.NewElement( "Parent" );
		doc.InsertFirstChild( parent );

		XMLElement* childText0 = doc.NewElement( "childText0" );
		XMLElement* childText1 = doc.NewElement( "childText1" );

		XMLNode* childNode0 = parent->InsertEndChild( childText0 );
		XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 );

		XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true );
	}

	{
		// Entities not being written correctly.
		// From Lynn Allen

		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
				" It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
			"</passages>";

		XMLDocument doc;
		doc.Parse( passages );
		XMLElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );
		const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

		XMLTest( "Entity transformation: read. ", expected, context, true );

		FILE* textfile = fopen( "resources/out/textfile.txt", "w" );
		if ( textfile )
		{
			XMLPrinter streamer( textfile );
			psg->Accept( &streamer );
			fclose( textfile );
		}

        textfile = fopen( "resources/out/textfile.txt", "r" );
		TIXMLASSERT( textfile );
		if ( textfile )
		{
			char buf[ 1024 ];
			fgets( buf, 1024, textfile );
			XMLTest( "Entity transformation: write. ",
					 "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
					 " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.\"/>\n",
					 buf, false );
			fclose( textfile );
		}
	}

	{
		// Suppress entities.
		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.\">Crazy &ttk;</psg>"
			"</passages>";

		XMLDocument doc( false );
		doc.Parse( passages );

		XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ),
				 "Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." );
		XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(),
				 "Crazy &ttk;" );
		doc.Print();
	}

	{
		const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>";

		XMLDocument doc;
		doc.Parse( test );
		XMLTest( "dot in names", doc.Error(), false );
		XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" );
		XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" );
	}

	{
		const char* test = "<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>";

		XMLDocument doc;
		doc.Parse( test );

		XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
		XMLTest( "Entity with one digit.",
				 text->Value(), "1.1 Start easy ignore fin thickness\n",
				 false );
	}

	{
		// DOCTYPE not preserved (950171)
		//
		const char* doctype =
			"<?xml version=\"1.0\" ?>"
			"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
			"<!ELEMENT title (#PCDATA)>"
			"<!ELEMENT books (title,authors)>"
			"<element />";

		XMLDocument doc;
		doc.Parse( doctype );
		doc.SaveFile( "resources/out/test7.xml" );
		doc.DeleteChild( doc.RootElement() );
		doc.LoadFile( "resources/out/test7.xml" );
		doc.Print();

		const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown();
		XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() );

	}

	{
		// Comments do not stream out correctly.
		const char* doctype =
			"<!-- Somewhat<evil> -->";
		XMLDocument doc;
		doc.Parse( doctype );

		XMLComment* comment = doc.FirstChild()->ToComment();

		XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
	}
	{
		// Double attributes
		const char* doctype = "<element attr='red' attr='blue' />";

		XMLDocument doc;
		doc.Parse( doctype );

		XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() );	// is an  error to tinyxml (didn't use to be, but caused issues)
		doc.PrintError();
	}

	{
		// Embedded null in stream.
		const char* doctype = "<element att\0r='red' attr='blue' />";

		XMLDocument doc;
		doc.Parse( doctype );
		XMLTest( "Embedded null throws error.", true, doc.Error() );
	}

	{
		// Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		XMLDocument doc;
		doc.Parse( str );
		XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
	}

	{
		// Low entities
		XMLDocument doc;
		doc.Parse( "<test>&#x0e;</test>" );
		const char result[] = { 0x0e, 0 };
		XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result );
		doc.Print();
	}

	{
		// Attribute values with trailing quotes not handled correctly
		XMLDocument doc;
		doc.Parse( "<foo attribute=bar\" />" );
		XMLTest( "Throw error with bad end quotes.", doc.Error(), true );
	}

	{
		// [ 1663758 ] Failure to report error on bad XML
		XMLDocument xml;
		xml.Parse("<x>");
		XMLTest("Missing end tag at end of input", xml.Error(), true);
		xml.Parse("<x> ");
		XMLTest("Missing end tag with trailing whitespace", xml.Error(), true);
		xml.Parse("<x></y>");
		XMLTest("Mismatched tags", xml.ErrorID(), XML_ERROR_MISMATCHED_ELEMENT);
	}


	{
		// [ 1475201 ] TinyXML parses entities in comments
		XMLDocument xml;
		xml.Parse("<!-- declarations for <head> & <body> -->"
				  "<!-- far &amp; away -->" );

		XMLNode* e0 = xml.FirstChild();
		XMLNode* e1 = e0->NextSibling();
		XMLComment* c0 = e0->ToComment();
		XMLComment* c1 = e1->ToComment();

		XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XMLTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}

	{
		XMLDocument xml;
		xml.Parse( "<Parent>"
						"<child1 att=''/>"
						"<!-- With this comment, child2 will not be parsed! -->"
						"<child2 att=''/>"
					"</Parent>" );
		xml.Print();

		int count = 0;

		for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild();
			 ele;
			 ele = ele->NextSibling() )
		{
			++count;
		}

		XMLTest( "Comments iterate correctly.", 3, count );
	}

	{
		// trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
		unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
		buf[60] = 239;
		buf[61] = 0;

		XMLDocument doc;
		doc.Parse( (const char*)buf);
	}


	{
		// bug 1827248 Error while parsing a little bit malformed file
		// Actually not malformed - should work.
		XMLDocument xml;
		xml.Parse( "<attributelist> </attributelist >" );
		XMLTest( "Handle end tag whitespace", false, xml.Error() );
	}

	{
		// This one must not result in an infinite loop
		XMLDocument xml;
		xml.Parse( "<infinite>loop" );
		XMLTest( "Infinite loop test.", true, true );
	}
#endif
	{
		const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
		XMLDocument doc;
		doc.Parse( pub );

		XMLDocument clone;
		for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
			XMLNode* copy = node->ShallowClone( &clone );
			clone.InsertEndChild( copy );
		}

		clone.Print();

		int count=0;
		const XMLNode* a=clone.FirstChild();
		const XMLNode* b=doc.FirstChild();
		for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
			++count;
			XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
		}
		XMLTest( "Clone and Equal", 4, count );
	}

	{
		// This shouldn't crash.
		XMLDocument doc;
		if(XML_NO_ERROR != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ))
		{
			doc.PrintError();
		}
		XMLTest( "Error in snprinf handling.", true, doc.Error() );
	}

	{
		// Attribute ordering.
		static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele = doc.FirstChildElement();

		const XMLAttribute* a = ele->FirstAttribute();
		XMLTest( "Attribute order", "1", a->Value() );
		a = a->Next();
		XMLTest( "Attribute order", "2", a->Value() );
		a = a->Next();
		XMLTest( "Attribute order", "3", a->Value() );
		XMLTest( "Attribute order", "attrib3", a->Name() );

		ele->DeleteAttribute( "attrib2" );
		a = ele->FirstAttribute();
		XMLTest( "Attribute order", "1", a->Value() );
		a = a->Next();
		XMLTest( "Attribute order", "3", a->Value() );

		ele->DeleteAttribute( "attrib1" );
		ele->DeleteAttribute( "attrib3" );
		XMLTest( "Attribute order (empty)", false, ele->FirstAttribute() ? true : false );
	}

	{
		// Make sure an attribute with a space in it succeeds.
		static const char* xml0 = "<element attribute1= \"Test Attribute\"/>";
		static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>";
		static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>";
		XMLDocument doc0;
		doc0.Parse( xml0 );
		XMLDocument doc1;
		doc1.Parse( xml1 );
		XMLDocument doc2;
		doc2.Parse( xml2 );

		XMLElement* ele = 0;
		ele = doc0.FirstChildElement();
		XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) );
		ele = doc1.FirstChildElement();
		XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) );
		ele = doc2.FirstChildElement();
		XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) );
	}

	{
		// Make sure we don't go into an infinite loop.
		static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement();
		XMLElement* ele1 = ele0->NextSiblingElement();
		bool equal = ele0->ShallowEqual( ele1 );

		XMLTest( "Infinite loop in shallow equal.", true, equal );
	}

	// -------- Handles ------------
	{
		static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
		XMLDocument doc;
		doc.Parse( xml );

		XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement();
		XMLTest( "Handle, success, mutable", ele->Value(), "sub" );

		XMLHandle docH( doc );
		ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
		XMLTest( "Handle, dne, mutable", false, ele != 0 );
	}

	{
		static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLConstHandle docH( doc );

		const XMLElement* ele = docH.FirstChildElement( "element" ).FirstChild().ToElement();
		XMLTest( "Handle, success, const", ele->Value(), "sub" );

		ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
		XMLTest( "Handle, dne, const", false, ele != 0 );
	}
	{
		// Default Declaration & BOM
		XMLDocument doc;
		doc.InsertEndChild( doc.NewDeclaration() );
		doc.SetBOM( true );

		XMLPrinter printer;
		doc.Print( &printer );

		static const char* result  = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		XMLTest( "BOM and default declaration", printer.CStr(), result, false );
		XMLTest( "CStrSize", printer.CStrSize(), 42, false );
	}
	{
		const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLTest( "Ill formed XML", true, doc.Error() );
	}

	// QueryXYZText
	{
		const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>";
		XMLDocument doc;
		doc.Parse( xml );

		const XMLElement* pointElement = doc.RootElement();

		int intValue = 0;
		unsigned unsignedValue = 0;
		float floatValue = 0;
		double doubleValue = 0;
		bool boolValue = false;

		pointElement->FirstChildElement( "y" )->QueryIntText( &intValue );
		pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue );
		pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue );
		pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue );
		pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue );


		XMLTest( "QueryIntText", intValue, 1,						false );
		XMLTest( "QueryUnsignedText", unsignedValue, (unsigned)1,	false );
		XMLTest( "QueryFloatText", floatValue, 1.2f,				false );
		XMLTest( "QueryDoubleText", doubleValue, 1.2,				false );
		XMLTest( "QueryBoolText", boolValue, true,					false );
	}

	{
		const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLTest( "Non-alpha element lead letter parses.", doc.Error(), false );
	}
    
    {
        const char* xml = "<element _attr1=\"foo\" :attr2=\"bar\"></element>";
        XMLDocument doc;
        doc.Parse( xml );
        XMLTest("Non-alpha attribute lead character parses.", doc.Error(), false);
    }
    
    {
        const char* xml = "<3lement></3lement>";
        XMLDocument doc;
        doc.Parse( xml );
        XMLTest("Element names with lead digit fail to parse.", doc.Error(), true);
    }

	{
		const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE";
		XMLDocument doc;
		doc.Parse( xml, 10 );
		XMLTest( "Set length of incoming data", doc.Error(), false );
	}

    {
        XMLDocument doc;
        doc.LoadFile( "resources/dream.xml" );
        doc.Clear();
        XMLTest( "Document Clear()'s", doc.NoChildren(), true );
    }
    
	// ----------- Whitespace ------------
	{
		const char* xml = "<element>"
							"<a> This \nis &apos;  text  &apos; </a>"
							"<b>  This is &apos; text &apos;  \n</b>"
							"<c>This  is  &apos;  \n\n text &apos;</c>"
						  "</element>";
		XMLDocument doc( true, COLLAPSE_WHITESPACE );
		doc.Parse( xml );

		const XMLElement* element = doc.FirstChildElement();
		for( const XMLElement* parent = element->FirstChildElement();
			 parent;
			 parent = parent->NextSiblingElement() )
		{
			XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() );
		}
	}

#if 0
	{
		// Passes if assert doesn't fire.
		XMLDocument xmlDoc;

	    xmlDoc.NewDeclaration();
	    xmlDoc.NewComment("Configuration file");

	    XMLElement *root = xmlDoc.NewElement("settings");
	    root->SetAttribute("version", 2);
	}
#endif

	{
		const char* xml = "<element>    </element>";
		XMLDocument doc( true, COLLAPSE_WHITESPACE );
		doc.Parse( xml );
		XMLTest( "Whitespace  all space", true, 0 == doc.FirstChildElement()->FirstChild() );
	}

#if 0		// the question being explored is what kind of print to use: 
			// https://github.com/leethomason/tinyxml2/issues/63
	{
		const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9'/>";
		XMLDocument doc;
		doc.Parse( xml );
		doc.FirstChildElement()->SetAttribute( "attrA", 123456789.123456789 );
		doc.FirstChildElement()->SetAttribute( "attrB", 1.001e9 );
		doc.Print();
	}
#endif

	{
		// An assert should not fire.
		const char* xml = "<element/>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele = doc.NewElement( "unused" );		// This will get cleaned up with the 'doc' going out of scope.
		XMLTest( "Tracking unused elements", true, ele != 0, false );
	}


	{
		const char* xml = "<parent><child>abc</child></parent>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele = doc.FirstChildElement( "parent")->FirstChildElement( "child");

		XMLPrinter printer;
		ele->Accept( &printer );
		XMLTest( "Printing of sub-element", "<child>abc</child>\n", printer.CStr(), false );
	}


	{
		XMLDocument doc;
		XMLError error = doc.LoadFile( "resources/empty.xml" );
		XMLTest( "Loading an empty file", XML_ERROR_EMPTY_DOCUMENT, error );
	}

	{
        // BOM preservation
        static const char* xml_bom_preservation  = "\xef\xbb\xbf<element/>\n";
        {
			XMLDocument doc;
			XMLTest( "BOM preservation (parse)", XML_NO_ERROR, doc.Parse( xml_bom_preservation ), false );
            XMLPrinter printer;
            doc.Print( &printer );

            XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
			doc.SaveFile( "resources/bomtest.xml" );
        }
		{
			XMLDocument doc;
			doc.LoadFile( "resources/bomtest.xml" );
			XMLTest( "BOM preservation (load)", true, doc.HasBOM(), false );

            XMLPrinter printer;
            doc.Print( &printer );
            XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
		}
	}

	{
		// Insertion with Removal
		const char* xml = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"</one>"
			"<two/>"
			"</root>";
		const char* xmlInsideTwo = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one/>"
			"<two>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"</two>"
			"</root>";
		const char* xmlAfterOne = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one/>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"<two/>"
			"</root>";
		const char* xmlAfterTwo = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one/>"
			"<two/>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"</root>";

		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
		XMLElement* two = doc.RootElement()->FirstChildElement("two");
		two->InsertFirstChild(subtree);
		XMLPrinter printer1( 0, true );
		doc.Accept( &printer1 );
		XMLTest( "Move node from within <one> to <two>", xmlInsideTwo, printer1.CStr());

		doc.Parse( xml );
		subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
		two = doc.RootElement()->FirstChildElement("two");
		doc.RootElement()->InsertAfterChild(two, subtree);
		XMLPrinter printer2( 0, true );
		doc.Accept( &printer2 );
		XMLTest( "Move node from within <one> after <two>", xmlAfterTwo, printer2.CStr(), false );

		doc.Parse( xml );
		XMLNode* one = doc.RootElement()->FirstChildElement("one");
		subtree = one->FirstChildElement("subtree");
		doc.RootElement()->InsertAfterChild(one, subtree);
		XMLPrinter printer3( 0, true );
		doc.Accept( &printer3 );
		XMLTest( "Move node from within <one> after <one>", xmlAfterOne, printer3.CStr(), false );

		doc.Parse( xml );
		subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
		two = doc.RootElement()->FirstChildElement("two");
		doc.RootElement()->InsertEndChild(subtree);
		XMLPrinter printer4( 0, true );
		doc.Accept( &printer4 );
		XMLTest( "Move node from within <one> after <two>", xmlAfterTwo, printer4.CStr(), false );
	}

	// ----------- Performance tracking --------------
	{
#if defined( _MSC_VER )
		__int64 start, end, freq;
		QueryPerformanceFrequency( (LARGE_INTEGER*) &freq );
#endif

		FILE* fp  = fopen( "resources/dream.xml", "r" );
		fseek( fp, 0, SEEK_END );
		long size = ftell( fp );
		fseek( fp, 0, SEEK_SET );

		char* mem = new char[size+1];
		fread( mem, size, 1, fp );
		fclose( fp );
		mem[size] = 0;

#if defined( _MSC_VER )
		QueryPerformanceCounter( (LARGE_INTEGER*) &start );
#else
		clock_t cstart = clock();
#endif
		static const int COUNT = 10;
		for( int i=0; i<COUNT; ++i ) {
			XMLDocument doc;
			doc.Parse( mem );
		}
#if defined( _MSC_VER )
		QueryPerformanceCounter( (LARGE_INTEGER*) &end );
#else
		clock_t cend = clock();
#endif

		delete [] mem;

		static const char* note =
#ifdef DEBUG
			"DEBUG";
#else
			"Release";
#endif

#if defined( _MSC_VER )
		printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) );
#else
		printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT );
#endif
	}

	#if defined( _MSC_VER ) &&  defined( DEBUG )
		_CrtMemCheckpoint( &endMemState );
		//_CrtMemDumpStatistics( &endMemState );

		_CrtMemState diffMemState;
		_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
		_CrtMemDumpStatistics( &diffMemState );
		//printf( "new total=%d\n", gNewTotal );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);

	return gFail;
}
Beispiel #23
0
int main( int /*argc*/, const char ** /*argv*/ )
{
	#if defined( _MSC_VER ) && defined( DEBUG )
		_CrtMemCheckpoint( &startMemState );
	#endif	

	#if defined(_MSC_VER)
	#pragma warning ( push )
	#pragma warning ( disable : 4996 )		// Fail to see a compelling reason why this should be deprecated.
	#endif

	FILE* fp = fopen( "dream.xml", "r" );
	if ( !fp ) {
		printf( "Error opening test file 'dream.xml'.\n"
				"Is your working directory the same as where \n"
				"the xmltest.cpp and dream.xml file are?\n\n"
	#if defined( _MSC_VER )
				"In windows Visual Studio you may need to set\n"
				"Properties->Debugging->Working Directory to '..'\n"
	#endif
			  );
		exit( 1 );
	}
	fclose( fp );

	#if defined(_MSC_VER)
	#pragma warning ( pop )
	#endif

	/* ------ Example 1: Load and parse an XML file. ---- */	
	{
		XMLDocument doc;
		doc.LoadFile( "dream.xml" );
	}
	
	/* ------ Example 2: Lookup information. ---- */	
	{
		XMLDocument doc;
		doc.LoadFile( "dream.xml" );

		// Structure of the XML file:
		// - Element "PLAY"			the root Element
		// - - Element "TITLE"		child of the root PLAY Element
		// - - - Text				child of the TITLE Element
		
		// Navigate to the title, using the convenience function, with a dangerous lack of error checking.
		const char* title = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->GetText();
		printf( "Name of play (1): %s\n", title );
		
		// Text is just another Node to TinyXML-2. The more general way to get to the XMLText:
		XMLText* textNode = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->FirstChild()->ToText();
		title = textNode->Value();
		printf( "Name of play (2): %s\n", title );
	}

	{
		static const char* test[] = {	"<element />",
									    "<element></element>",
										"<element><subelement/></element>",
									    "<element><subelement></subelement></element>",
									    "<element><subelement><subsub/></subelement></element>",
									    "<!--comment beside elements--><element><subelement></subelement></element>",
									    "<!--comment beside elements, this time with spaces-->  \n <element>  <subelement> \n </subelement> </element>",
									    "<element attrib1='foo' attrib2=\"bar\" ></element>",
									    "<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>",
										"<element>Text inside element.</element>",
										"<element><b></b></element>",
										"<element>Text inside and <b>bolded</b> in the element.</element>",
										"<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>",
										"<element>This &amp; That.</element>",
										"<element attrib='This&lt;That' />",
										0
		};
		for( int i=0; test[i]; ++i ) {
			XMLDocument doc;
			doc.Parse( test[i] );
			doc.Print();
			printf( "----------------------------------------------\n" );
		}
	}
#if 1
	{
		static const char* test = "<!--hello world\n"
			                      "          line 2\r"
			                      "          line 3\r\n"
			                      "          line 4\n\r"
			                      "          line 5\r-->";

		XMLDocument doc;
		doc.Parse( test );
		doc.Print();
	}

	{
		static const char* test = "<element>Text before.</element>";
		XMLDocument doc;
		doc.Parse( test );
		XMLElement* root = doc.FirstChildElement();
		XMLElement* newElement = doc.NewElement( "Subelement" );
		root->InsertEndChild( newElement );
		doc.Print();
	}
	{
		XMLDocument* doc = new XMLDocument();
		static const char* test = "<element><sub/></element>";
		doc->Parse( test );
		delete doc;
	}
	{
		// Test: Programmatic DOM
		// Build:
		//		<element>
		//			<!--comment-->
		//			<sub attrib="1" />
		//			<sub attrib="2" />
		//			<sub attrib="3" >& Text!</sub>
		//		<element>

		XMLDocument* doc = new XMLDocument();
		XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) );

		XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) };
		for( int i=0; i<3; ++i ) {
			sub[i]->SetAttribute( "attrib", i );
		}
		element->InsertEndChild( sub[2] );
		XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) );
		element->InsertAfterChild( comment, sub[0] );
		element->InsertAfterChild( sub[0], sub[1] );
		sub[2]->InsertFirstChild( doc->NewText( "& Text!" ));
		doc->Print();
		XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() );
		XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) );
		XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) );
		XMLTest( "Programmatic DOM", "& Text!", 
				 doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() );

		// And now deletion:
		element->DeleteChild( sub[2] );
		doc->DeleteNode( comment );

		element->FirstChildElement()->SetAttribute( "attrib", true );
		element->LastChildElement()->DeleteAttribute( "attrib" );

		XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) );
		int value = 10;
		int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value );
		XMLTest( "Programmatic DOM", result, XML_NO_ATTRIBUTE );
		XMLTest( "Programmatic DOM", value, 10 );

		doc->Print();

		XMLPrinter streamer;
		doc->Print( &streamer );
		printf( "%s", streamer.CStr() );

		delete doc;
	}
	{
		// Test: Dream
		// XML1 : 1,187,569 bytes	in 31,209 allocations
		// XML2 :   469,073	bytes	in    323 allocations
		//int newStart = gNew;
		XMLDocument doc;
		doc.LoadFile( "dream.xml" );

		doc.SaveFile( "dreamout.xml" );
		doc.PrintError();

		XMLTest( "Dream", "xml version=\"1.0\"",
			              doc.FirstChild()->ToDeclaration()->Value() );
		XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false );
		XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
						  doc.FirstChild()->NextSibling()->ToUnknown()->Value() );
		XMLTest( "Dream", "And Robin shall restore amends.",
			              doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
		XMLTest( "Dream", "And Robin shall restore amends.",
			              doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );

		XMLDocument doc2;
		doc2.LoadFile( "dreamout.xml" );
		XMLTest( "Dream-out", "xml version=\"1.0\"",
			              doc2.FirstChild()->ToDeclaration()->Value() );
		XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false );
		XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
						  doc2.FirstChild()->NextSibling()->ToUnknown()->Value() );
		XMLTest( "Dream-out", "And Robin shall restore amends.",
			              doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );

		//gNewTotal = gNew - newStart;
	}


	{
		const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
							"<passages count=\"006\" formatversion=\"20020620\">\n"
							"    <wrong error>\n"
							"</passages>";

		XMLDocument doc;
		doc.Parse( error );
		XMLTest( "Bad XML", doc.ErrorID(), XML_ERROR_PARSING_ATTRIBUTE );
	}

	{
		const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

		XMLDocument doc;
		doc.Parse( str );

		XMLElement* ele = doc.FirstChildElement();

		int iVal, result;
		double dVal;

		result = ele->QueryDoubleAttribute( "attr0", &dVal );
		XMLTest( "Query attribute: int as double", result, XML_NO_ERROR );
		XMLTest( "Query attribute: int as double", (int)dVal, 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XMLTest( "Query attribute: double as double", (int)dVal, 2 );
		result = ele->QueryIntAttribute( "attr1", &iVal );
		XMLTest( "Query attribute: double as int", result, XML_NO_ERROR );
		XMLTest( "Query attribute: double as int", iVal, 2 );
		result = ele->QueryIntAttribute( "attr2", &iVal );
		XMLTest( "Query attribute: not a number", result, XML_WRONG_ATTRIBUTE_TYPE );
		result = ele->QueryIntAttribute( "bar", &iVal );
		XMLTest( "Query attribute: does not exist", result, XML_NO_ATTRIBUTE );
	}

	{
		const char* str = "<doc/>";

		XMLDocument doc;
		doc.Parse( str );

		XMLElement* ele = doc.FirstChildElement();

		int iVal;
		double dVal;

		ele->SetAttribute( "str", "strValue" );
		ele->SetAttribute( "int", 1 );
		ele->SetAttribute( "double", -1.0 );

		const char* cStr = ele->Attribute( "str" );
		ele->QueryIntAttribute( "int", &iVal );
		ele->QueryDoubleAttribute( "double", &dVal );

		XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" );
		XMLTest( "Attribute round trip. c-string.", "strValue", cStr );
		XMLTest( "Attribute round trip. int.", 1, iVal );
		XMLTest( "Attribute round trip. double.", -1, (int)dVal );
	}

	{
		XMLDocument doc;
		doc.LoadFile( "utf8test.xml" );

		// Get the attribute "value" from the "Russian" element and check it.
		XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" );
		const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 
												0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };

		XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) );

		const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
														0xd1U, 0x81U, 0xd1U, 0x81U,
														0xd0U, 0xbaU, 0xd0U, 0xb8U,
														0xd0U, 0xb9U, 0 };
		const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

		XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText();
		XMLTest( "UTF-8: Browsing russian element name.",
				 russianText,
				 text->Value() );

		// Now try for a round trip.
		doc.SaveFile( "utf8testout.xml" );

		// Check the round trip.
		char savedBuf[256];
		char verifyBuf[256];
		int okay = 0;


#if defined(_MSC_VER)
#pragma warning ( push )
#pragma warning ( disable : 4996 )		// Fail to see a compelling reason why this should be deprecated.
#endif
		FILE* saved  = fopen( "utf8testout.xml", "r" );
		FILE* verify = fopen( "utf8testverify.xml", "r" );
#if defined(_MSC_VER)
#pragma warning ( pop )
#endif

		if ( saved && verify )
		{
			okay = 1;
			while ( fgets( verifyBuf, 256, verify ) )
			{
				fgets( savedBuf, 256, saved );
				NullLineEndings( verifyBuf );
				NullLineEndings( savedBuf );

				if ( strcmp( verifyBuf, savedBuf ) )
				{
					printf( "verify:%s<\n", verifyBuf );
					printf( "saved :%s<\n", savedBuf );
					okay = 0;
					break;
				}
			}
		}
		if ( saved )
			fclose( saved );
		if ( verify )
			fclose( verify );
		XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay );
	}

	// --------GetText()-----------
	{
		const char* str = "<foo>This is  text</foo>";
		XMLDocument doc;
		doc.Parse( str );
		const XMLElement* element = doc.RootElement();

		XMLTest( "GetText() normal use.", "This is  text", element->GetText() );

		str = "<foo><b>This is text</b></foo>";
		doc.Parse( str );
		element = doc.RootElement();

		XMLTest( "GetText() contained element.", element->GetText() == 0, true );
	}


	// ---------- CDATA ---------------
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"I am > the rules!\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		XMLDocument doc;
		doc.Parse( str );
		doc.Print();

		XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 false );
	}

	// ----------- CDATA -------------
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"<b>I am > the rules!</b>\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		XMLDocument doc;
		doc.Parse( str );
		doc.Print();

		XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 false );
	}

	// InsertAfterChild causes crash.
	{
		// InsertBeforeChild and InsertAfterChild causes crash.
		XMLDocument doc;
		XMLElement* parent = doc.NewElement( "Parent" );
		doc.InsertFirstChild( parent );

		XMLElement* childText0 = doc.NewElement( "childText0" );
		XMLElement* childText1 = doc.NewElement( "childText1" );

		XMLNode* childNode0 = parent->InsertEndChild( childText0 );
		XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 );

		XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true );
	}

	{
		// Entities not being written correctly.
		// From Lynn Allen

		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
				" It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
			"</passages>";

		XMLDocument doc;
		doc.Parse( passages );
		XMLElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );
		const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

		XMLTest( "Entity transformation: read. ", expected, context, true );

#if defined(_MSC_VER)
#pragma warning ( push )
#pragma warning ( disable : 4996 )		// Fail to see a compelling reason why this should be deprecated.
#endif
		FILE* textfile = fopen( "textfile.txt", "w" );
#if defined(_MSC_VER)
#pragma warning ( pop )
#endif
		if ( textfile )
		{
			XMLPrinter streamer( textfile );
			psg->Accept( &streamer );
			fclose( textfile );
		}
#if defined(_MSC_VER)
#pragma warning ( push )
#pragma warning ( disable : 4996 )		// Fail to see a compelling reason why this should be deprecated.
#endif
		textfile = fopen( "textfile.txt", "r" );
#if defined(_MSC_VER)
#pragma warning ( pop )
#endif
		TIXMLASSERT( textfile );
		if ( textfile )
		{
			char buf[ 1024 ];
			fgets( buf, 1024, textfile );
			XMLTest( "Entity transformation: write. ",
					 "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
					 " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.\"/>\n",
					 buf, false );
		}
		fclose( textfile );
	}

	{
		// Suppress entities.
		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.\">Crazy &ttk;</psg>"
			"</passages>";
		
		XMLDocument doc( false );
		doc.Parse( passages );

		XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ), 
				 "Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." );
		XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(),
				 "Crazy &ttk;" );
		doc.Print();
	}

	{
        const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>";

		XMLDocument doc;
        doc.Parse( test );
        XMLTest( "dot in names", doc.Error(), 0);
        XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" );
        XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" );
	}

	{
        const char* test = "<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>";

        XMLDocument doc;
		doc.Parse( test );

		XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
		XMLTest( "Entity with one digit.",
				 text->Value(), "1.1 Start easy ignore fin thickness\n",
				 false );
    }

	{
		// DOCTYPE not preserved (950171)
		// 
		const char* doctype =
			"<?xml version=\"1.0\" ?>"
			"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
			"<!ELEMENT title (#PCDATA)>"
			"<!ELEMENT books (title,authors)>"
			"<element />";

		XMLDocument doc;
		doc.Parse( doctype );
		doc.SaveFile( "test7.xml" );
		doc.DeleteChild( doc.RootElement() );
		doc.LoadFile( "test7.xml" );
		doc.Print();
		
		const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown();
		XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() );

	}

	{
		// Comments do not stream out correctly.
		const char* doctype = 
			"<!-- Somewhat<evil> -->";
		XMLDocument doc;
		doc.Parse( doctype );

		XMLComment* comment = doc.FirstChild()->ToComment();

		XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
	}
	{
		// Double attributes
		const char* doctype = "<element attr='red' attr='blue' />";

		XMLDocument doc;
		doc.Parse( doctype );
		
		XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() );	// is an  error to tinyxml (didn't use to be, but caused issues)
		doc.PrintError();
	}

	{
		// Embedded null in stream.
		const char* doctype = "<element att\0r='red' attr='blue' />";

		XMLDocument doc;
		doc.Parse( doctype );
		XMLTest( "Embedded null throws error.", true, doc.Error() );
	}

	{
		// Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		XMLDocument doc;
		doc.Parse( str );
		XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
	}

	{
		// Low entities
		XMLDocument doc;
		doc.Parse( "<test>&#x0e;</test>" );
		const char result[] = { 0x0e, 0 };
		XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result );
		doc.Print();
	}

	{
		// Attribute values with trailing quotes not handled correctly
		XMLDocument doc;
		doc.Parse( "<foo attribute=bar\" />" );
		XMLTest( "Throw error with bad end quotes.", doc.Error(), true );
	}

	{
		// [ 1663758 ] Failure to report error on bad XML
		XMLDocument xml;
		xml.Parse("<x>");
		XMLTest("Missing end tag at end of input", xml.Error(), true);
		xml.Parse("<x> ");
		XMLTest("Missing end tag with trailing whitespace", xml.Error(), true);
		xml.Parse("<x></y>");
		XMLTest("Mismatched tags", xml.ErrorID(), XML_ERROR_MISMATCHED_ELEMENT);
	} 


	{
		// [ 1475201 ] TinyXML parses entities in comments
		XMLDocument xml;
		xml.Parse("<!-- declarations for <head> & <body> -->"
				  "<!-- far &amp; away -->" );

		XMLNode* e0 = xml.FirstChild();
		XMLNode* e1 = e0->NextSibling();
		XMLComment* c0 = e0->ToComment();
		XMLComment* c1 = e1->ToComment();

		XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XMLTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}

	{
		XMLDocument xml;
		xml.Parse( "<Parent>"
						"<child1 att=''/>"
						"<!-- With this comment, child2 will not be parsed! -->"
						"<child2 att=''/>"
					"</Parent>" );
		xml.Print();

		int count = 0;

		for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild();
			 ele;
			 ele = ele->NextSibling() )
		{
			++count;
		}

		XMLTest( "Comments iterate correctly.", 3, count );
	}

	{
		// trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
		unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
		buf[60] = 239;
		buf[61] = 0;

		XMLDocument doc;
		doc.Parse( (const char*)buf);
	} 


	{
		// bug 1827248 Error while parsing a little bit malformed file
		// Actually not malformed - should work.
		XMLDocument xml;
		xml.Parse( "<attributelist> </attributelist >" );
		XMLTest( "Handle end tag whitespace", false, xml.Error() );
	}

	{
		// This one must not result in an infinite loop
		XMLDocument xml;
		xml.Parse( "<infinite>loop" );
		XMLTest( "Infinite loop test.", true, true );
	}
#endif
	{
		const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
		XMLDocument doc;
		doc.Parse( pub );

		XMLDocument clone;
		for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
			XMLNode* copy = node->ShallowClone( &clone );
			clone.InsertEndChild( copy );
		}

		clone.Print();

		int count=0;
		const XMLNode* a=clone.FirstChild();
		const XMLNode* b=doc.FirstChild();
		for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
			++count;
			XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
		}
		XMLTest( "Clone and Equal", 4, count );
	}

	// ----------- Performance tracking --------------
	{
#if defined( _MSC_VER )
		__int64 start, end, freq;
		QueryPerformanceFrequency( (LARGE_INTEGER*) &freq );
#endif

#if defined(_MSC_VER)
#pragma warning ( push )
#pragma warning ( disable : 4996 )		// Fail to see a compelling reason why this should be deprecated.
#endif
		FILE* fp  = fopen( "dream.xml", "r" );
#if defined(_MSC_VER)
#pragma warning ( pop )
#endif
		fseek( fp, 0, SEEK_END );
		long size = ftell( fp );
		fseek( fp, 0, SEEK_SET );

		char* mem = new char[size+1];
		fread( mem, size, 1, fp );
		fclose( fp );
		mem[size] = 0;

#if defined( _MSC_VER )
		QueryPerformanceCounter( (LARGE_INTEGER*) &start );
#else
		clock_t cstart = clock();
#endif
		static const int COUNT = 10;
		for( int i=0; i<COUNT; ++i ) {
			XMLDocument doc;
			doc.Parse( mem );
		}
#if defined( _MSC_VER )
		QueryPerformanceCounter( (LARGE_INTEGER*) &end );
#else
		clock_t cend = clock();
#endif

		delete [] mem;

		static const char* note = 
#ifdef DEBUG
			"DEBUG";
#else
			"Release";
#endif

#if defined( _MSC_VER )
		printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) );
#else
		printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT );
#endif
	}

	#if defined( _MSC_VER ) &&  defined( DEBUG )
		_CrtMemCheckpoint( &endMemState );  
		//_CrtMemDumpStatistics( &endMemState );

		_CrtMemState diffMemState;
		_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
		_CrtMemDumpStatistics( &diffMemState );
		//printf( "new total=%d\n", gNewTotal );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);
	return 0;
}
 void Transform::deserialize(XMLNode* node) {
     XMLNode* t = node->FirstChild();
     t->FirstChildElement("X")->QueryFloatText(&(this->transform.x));
     t->FirstChildElement("Y")->QueryFloatText(&this->transform.y);
     node->FirstChildElement("Rotation")->QueryFloatText(&this->rotation);
 }
bool MOOSAppDocumentation::parseXML(string &item_error)
{
    // Parsing...
    XMLElement *element;
    XMLNode *root = m_xml_doc->FirstChildElement("moosapp");
    if(root == NULL) {
        item_error = "moosapp";
        return false;
    }

    // Info section
    {
        XMLElement *info_section = root->FirstChildElement("info");
        if(info_section == NULL) {
            item_error = "info";
            return false;
        }

        // Organization
        element = info_section->FirstChildElement("organization");
        if(element == NULL) {
            item_error = "organization";
            return false;
        }
        m_info_organization = element->GetText();
        MOOSTrimWhiteSpace(m_info_organization);

        // Date
        element = info_section->FirstChildElement("date");
        if(element == NULL) {
            item_error = "date";
            return false;
        }
        m_info_date = element->GetText();
        MOOSTrimWhiteSpace(m_info_date);

        // Licence
        element = info_section->FirstChildElement("licence");
        if(element == NULL) {
            item_error = "licence";
            return false;
        }
        m_info_licence = element->GetText();
        MOOSTrimWhiteSpace(m_info_licence);

        // Authors
        element = info_section->FirstChildElement("authors");
        if(element == NULL) {
            item_error = "authors";
            return false;
        }
        XMLElement *author = element->FirstChildElement("author");
        while(author != NULL)
        {
            string author_name;
            author_name = author->GetText();
            MOOSTrimWhiteSpace(author_name);
            m_info_authors.push_back(author_name);
            author = author->NextSiblingElement("author");
        }
    }

    // Documentation section
    {
        XMLElement *documentation_section = root->FirstChildElement("documentation");
        if(documentation_section == NULL) {
            item_error = "documentation";
            return false;
        }

        // Synopsis
        element = documentation_section->FirstChildElement("synopsis");
        if(element == NULL) {
            item_error = "synopsis";
            return false;
        }
        m_synopsis = element->GetText();
        MOOSTrimWhiteSpace(m_synopsis);

        // Optional comments
        element = documentation_section->FirstChildElement("optional-comments");
        if(element == NULL) {
            item_error = "optional-comments";
            return false;
        }
        m_optional_comments = element->GetText();
        MOOSTrimWhiteSpace(m_optional_comments);

        // Suggested improvements
        element = documentation_section->FirstChildElement("suggested-improvements");
        if(element == NULL) {
            item_error = "suggested-improvements";
            return false;
        }
        m_suggested_improvements = element->GetText();
        MOOSTrimWhiteSpace(m_suggested_improvements);

        // Interface
        {
            XMLElement *interface_subsection = documentation_section->FirstChildElement("interface");
            if(interface_subsection == NULL) {
                item_error = "interface";
                return false;
            }

            // Subscriptions
            XMLElement *subscriptions_subsection = interface_subsection->FirstChildElement("subscriptions");
            if(subscriptions_subsection == NULL) {
                item_error = "subscriptions";
                return false;
            }
            XMLElement *moosvar_xml = subscriptions_subsection->FirstChildElement("moosvar");
            while(moosvar_xml != NULL)
            {
                MOOSVarDescription moosvar;
                if(!xmlToMoosvar(moosvar_xml, moosvar, item_error)) {
                    return false;
                }
                m_subscriptions.push_back(moosvar);
                moosvar_xml = moosvar_xml->NextSiblingElement("moosvar");
            }

            // Publications
            XMLElement *publications_subsection = interface_subsection->FirstChildElement("publications");
            if(publications_subsection == NULL) {
                item_error = "publications";
                return false;
            }
            moosvar_xml = publications_subsection->FirstChildElement("moosvar");
            while(moosvar_xml != NULL)
            {
                MOOSVarDescription moosvar;
                if(!xmlToMoosvar(moosvar_xml, moosvar, item_error)) {
                    return false;
                }
                m_publications.push_back(moosvar);
                moosvar_xml = moosvar_xml->NextSiblingElement("moosvar");
            }
        }
    }

    return true;
}
Beispiel #26
0
int Effect::loadEffect(const char* filepath)
{
	//load file
	XMLDocument doc;
	XMLError error = doc.LoadFile(filepath);
	XMLCheckResult(error);

	XMLNode* effectNode = doc.FirstChild();
	if (effectNode == nullptr) return XML_ERROR_FILE_READ_ERROR;

	XMLElement* emitterNode = effectNode->FirstChildElement("Emitter");
	while (emitterNode != nullptr)
	{
	/****Constructor stuff****/
		int outputType;
		XMLElement* item = emitterNode->FirstChildElement("OutputType");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryIntText(&outputType);
		XMLCheckResult(error);

		glm::vec3 position;
		item = emitterNode->FirstChildElement("Position");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryFloatAttribute("x", &position.x);
		XMLCheckResult(error);
		error = item->QueryFloatAttribute("y", &position.y);
		XMLCheckResult(error);
		error = item->QueryFloatAttribute("z", &position.z);
		XMLCheckResult(error);

		double emitterLifetime;
		item = emitterNode->FirstChildElement("EmitterLifetime");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryDoubleText(&emitterLifetime);
		XMLCheckResult(error);

		double emitFrequency;
		item = emitterNode->FirstChildElement("EmitFrequency");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryDoubleText(&emitFrequency);
		XMLCheckResult(error);

		int particlesPerEmit;
		item = emitterNode->FirstChildElement("ParticlesPerEmit");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryIntText(&particlesPerEmit);
		XMLCheckResult(error);

		double particleLifetime;
		item = emitterNode->FirstChildElement("ParticleLiftime");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryDoubleText(&particleLifetime);
		XMLCheckResult(error);

		bool particleMortal;
		item = emitterNode->FirstChildElement("ParticleMortal");
		if (item == nullptr) return XML_ERROR_PARSING_ELEMENT;
		error = item->QueryBoolText(&particleMortal);
		XMLCheckResult(error);

		//create an Emitter
		Emitter* emitter = new Emitter(outputType, position, emitterLifetime, 
			emitFrequency, particlesPerEmit, particleLifetime, particleMortal);

	/****other necessary stuff****/
		//Geometry Shader
		item = emitterNode->FirstChildElement("UseGeometryShader");
		if (item != nullptr){
			bool geom;
			error = item->QueryBoolText(&geom);
			XMLCheckResult(error);
			if (geom) emitter->switchToGeometryShader();
		}

		//Movable
		item = emitterNode->FirstChildElement("Movable");
		if (item != nullptr){
			bool mov;
			error = item->QueryBoolText(&mov);
			XMLCheckResult(error);
			if (mov) emitter->setMovable(mov);
		}

		//Start time
		item = emitterNode->FirstChildElement("StartTime");
		if (item != nullptr){
			double st;
			error = item->QueryDoubleText(&st);
			XMLCheckResult(error);
			emitter->setStartTime(st);
		}
			
		//Velocity
		item = emitterNode->FirstChildElement("Velocity");
		if (item != nullptr){
			int velocity;
			error = item->QueryIntText(&velocity);
			XMLCheckResult(error);
			emitter->setVelocity(velocity);
		}

		//Physic
		item = emitterNode->FirstChildElement("Physic");
		if (item != nullptr) 
		{
			XMLElement* physicType = item->FirstChildElement("Trajectory");
			if (physicType != nullptr){
				XMLElement* physicElement = physicType->FirstChildElement("Gravity");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				glm::vec4 gravity;
				error = physicElement->QueryFloatAttribute("x", &gravity.x);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("y", &gravity.y);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("z", &gravity.z);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("w", &gravity.w);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("Speed");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				float speed;
				error = physicElement->QueryFloatText(&speed);
				XMLCheckResult(error);

				emitter->usePhysicTrajectory(gravity, speed);
			} 
			physicType = item->FirstChildElement("DirectionGravity");
			if (physicType != nullptr){
				XMLElement* physicElement = physicType->FirstChildElement("Gravity");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				glm::vec4 gravity;
				error = physicElement->QueryFloatAttribute("x", &gravity.x);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("y", &gravity.y);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("z", &gravity.z);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("w", &gravity.w);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("Speed");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				float speed;
				error = physicElement->QueryFloatText(&speed);
				XMLCheckResult(error);

				emitter->usePhysicDirectionGravity(gravity, speed);
			}
			physicType = item->FirstChildElement("PointGravity");
			if (physicType != nullptr){
				XMLElement* physicElement = physicType->FirstChildElement("Point");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				glm::vec3 point;
				error = physicElement->QueryFloatAttribute("x", &point.x);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("y", &point.y);
				XMLCheckResult(error);
				error = physicElement->QueryFloatAttribute("z", &point.z);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("GravityImpact");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				float gravityImpact;
				error = physicElement->QueryFloatText(&gravityImpact);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("Speed");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				float speed;
				error = physicElement->QueryFloatText(&speed);
				XMLCheckResult(error);
			
				physicElement = physicType->FirstChildElement("GravityRange");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				float gravityRange;
				error = physicElement->QueryFloatText(&gravityRange);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("GravityFunction");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				int gravityFunction;
				error = physicElement->QueryIntText(&gravityFunction);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("BackToSource");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				bool backToSource;
				error = physicElement->QueryBoolText(&backToSource);
				XMLCheckResult(error);
				
				emitter->usePhysicPointGravity(point, gravityImpact, gravityRange, gravityFunction, speed, backToSource);
			}
			physicType = item->FirstChildElement("SwarmCircleMotion");
			if (physicType != nullptr){
				XMLElement* physicElement = physicType->FirstChildElement("MovementVertical");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				bool movementVertical;
				error = physicElement->QueryBoolText(&movementVertical);
				XMLCheckResult(error);
			
				physicElement = physicType->FirstChildElement("MovementHorizontalX");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				bool movementHorizontalX;
				error = physicElement->QueryBoolText(&movementHorizontalX);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("MovementHorizontalZ");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				bool movementHorizontalZ;
				error = physicElement->QueryBoolText(&movementHorizontalZ);
				XMLCheckResult(error);

				physicElement = physicType->FirstChildElement("Speed");
				if (physicElement == nullptr) return XML_ERROR_PARSING_ELEMENT;
				float speed;
				error = physicElement->QueryFloatText(&speed);
				XMLCheckResult(error);

				emitter->usePhysicSwarmCircleMotion(movementVertical, movementHorizontalX, movementHorizontalZ, speed);
			}
		}

		//Area Emitter
		item = emitterNode->FirstChildElement("AreaEmitter");
		if (item != nullptr){
			bool on;
			error = item->QueryBoolAttribute("on", &on);
			XMLCheckResult(error);
			if (on) {
				XMLElement* area = item->FirstChildElement("AreaXY");
				if (area == nullptr) return XML_ERROR_PARSING_ELEMENT;
				bool areaXY;
				error = area->QueryBoolText(&areaXY);
				XMLCheckResult(error);
				
				area = item->FirstChildElement("AreaXZ");
				bool areaXZ;
				error = area->QueryBoolText(&areaXZ);
				XMLCheckResult(error);

				area = item->FirstChildElement("Size");
				float size;
				error = area->QueryFloatText(&size);
				XMLCheckResult(error);

				area = item->FirstChildElement("Accuracy");
				int accuracy;
				error = area->QueryIntText(&accuracy);
				XMLCheckResult(error);

				emitter->setAreaEmitting(areaXY, areaXZ, size, accuracy);
			}
		}
		//Texures
		item = emitterNode->FirstChildElement("Texture");
		if (item != nullptr){
			//addTexture
			XMLElement* tex = item->FirstChildElement("Tex");
			while (tex != nullptr){
				std::string filepath = tex->GetText();
				std::string spath = RESOURCES_PATH + filepath;
				char* cpath = new char[spath.length() + 1];
				strcpy(cpath, spath.c_str());

				Texture* texture = new Texture(cpath);
				
				float time;
				error = tex->QueryFloatAttribute("time", &time);
				XMLCheckResult(error);
				
				emitter->addTexture(texture, time);

				tex = tex->NextSiblingElement("Tex");
			}

			//defineLook
			XMLElement* scaling = item->FirstChildElement("Scaling");
			if (scaling != nullptr) {
				bool useTexture;
				XMLElement* tex = scaling->FirstChildElement("UseTexture");
				error = tex->QueryBoolText(&useTexture);
				XMLCheckResult(error);

				std::vector<float> scalingSize;
				tex = scaling->FirstChildElement("ScalingSize");
				if (tex == nullptr) return XML_ERROR_PARSING_ELEMENT;
				XMLElement* temp = tex->FirstChildElement("Item");
				while (temp != nullptr){
					float value;
					error = temp->QueryFloatText(&value);
					XMLCheckResult(error);
					scalingSize.push_back(value);

					temp = temp->NextSiblingElement("Item");
				}
				
				std::vector<float> scalingMoment;
				tex = scaling->FirstChildElement("ScalingMoment");
				if (tex == nullptr) return XML_ERROR_PARSING_ELEMENT;
				temp = tex->FirstChildElement("Item");
				while (temp != nullptr){
					float value;
					error = temp->QueryFloatText(&value);
					XMLCheckResult(error);
					scalingMoment.push_back(value);

					temp = temp->NextSiblingElement("Item");
				}

				float birthTime;
				tex = scaling->FirstChildElement("BirthTime");
				error = tex->QueryFloatText(&birthTime);
				XMLCheckResult(error);
				
				float deathTime;
				tex = scaling->FirstChildElement("DeathTime");
				error = tex->QueryFloatText(&deathTime);
				XMLCheckResult(error);

				float blendingTime;
				tex = scaling->FirstChildElement("BlendingTime");
				error = tex->QueryFloatText(&blendingTime);
				XMLCheckResult(error);

				bool rotateLeft;
				tex = scaling->FirstChildElement("RotateLeft");
				error = tex->QueryBoolText(&rotateLeft);
				XMLCheckResult(error);

				float rotationSpeed;
				tex = scaling->FirstChildElement("RotationSpeed");
				error = tex->QueryFloatText(&rotationSpeed);
				XMLCheckResult(error);

				emitter->defineLook(useTexture, scalingSize, scalingMoment, 
					birthTime, deathTime, blendingTime, rotateLeft, rotationSpeed);
			}
			else {
				scaling = item->FirstChildElement("Size");
				if (scaling == nullptr) return XML_ERROR_PARSING_ELEMENT;
				
				bool useTexture;
				XMLElement* tex = scaling->FirstChildElement("UseTexture");
				error = tex->QueryBoolText(&useTexture);
				XMLCheckResult(error);

				float particleSize;
				tex = scaling->FirstChildElement("ParticleSize");
				error = tex->QueryFloatText(&particleSize);
				XMLCheckResult(error);

				float birthTime;
				tex = scaling->FirstChildElement("BirthTime");
				error = tex->QueryFloatText(&birthTime);
				XMLCheckResult(error);

				float deathTime;
				tex = scaling->FirstChildElement("DeathTime");
				error = tex->QueryFloatText(&deathTime);
				XMLCheckResult(error);

				float blendingTime;
				tex = scaling->FirstChildElement("BlendingTime");
				error = tex->QueryFloatText(&blendingTime);
				XMLCheckResult(error);

				bool rotateLeft;
				tex = scaling->FirstChildElement("RotateLeft");
				error = tex->QueryBoolText(&rotateLeft);
				XMLCheckResult(error);

				float rotationSpeed;
				tex = scaling->FirstChildElement("RotationSpeed");
				error = tex->QueryFloatText(&rotationSpeed);
				XMLCheckResult(error);

				emitter->defineLook(useTexture, particleSize,
					birthTime, deathTime, blendingTime, rotateLeft, rotationSpeed);
			}
			
		}

		//next Emitter
		emitterVec.push_back(emitter);
		emitterNode = emitterNode->NextSiblingElement("Emitter");
	}

	printf("EFFECT: loading Effect successfully\n");
	return XML_SUCCESS;
}
void GameWindows::loadData(Img* img) {
	XMLDocument doc;
	XMLError e = doc.LoadFile("conf/conf.xml");
	if (e == XML_NO_ERROR) {
		XMLNode * root = doc.RootElement();
		XMLElement * elementLevels = root->FirstChildElement("Levels");
		XMLElement * elementEnemies = root->FirstChildElement("Enemies");
		XMLElement * elementBosses = root->FirstChildElement("Bosses");
		if (elementLevels != NULL && elementEnemies != NULL && elementBosses != NULL) {
			XMLElement * elementLevel = elementLevels->FirstChildElement("Level");
			XMLElement * elementEnemy = elementEnemies->FirstChildElement("Enemy");
			XMLElement * elementBoss = elementBosses->FirstChildElement("Boss");
			do {
				if (elementLevel != NULL && elementEnemy != NULL && elementBoss != NULL) {
					XMLElement * elementNbEnemy = elementLevel->FirstChildElement("NbEnemy");
					XMLElement * elementUrl = elementLevel->FirstChildElement("UrlImageBackground");
					XMLElement * elementSpeed = elementLevel->FirstChildElement("SpeedEnemyFire");
					int nb = 0,speed = 0, life = 0, dommage = 0, sizeEscouad  = 0,lifeBoss = 0,dommageBoss =0;
					string url, urlboss;
					if (elementNbEnemy != NULL) {
						nb = atoi(elementNbEnemy->GetText());
					}
					if (elementUrl != NULL) {
						url = elementUrl->GetText();
					}
					if (elementSpeed != NULL) {
						speed = atoi(elementSpeed->GetText());
					}
					XMLElement * elementLife = elementEnemy->FirstChildElement("Life");
					XMLElement * elementDommage = elementEnemy->FirstChildElement("Dommage");
					XMLElement * elementSizeEscouade = elementEnemy->FirstChildElement("SizeEscouade");
					if (elementLife != NULL) {
						life = atoi(elementLife->GetText());
					}
					if (elementDommage != NULL) {
						dommage = atoi(elementDommage->GetText());
					}
					if (elementSizeEscouade != NULL) {
						sizeEscouad = atoi(elementSizeEscouade->GetText());
					}
					XMLElement * elementLifeBoss = elementBoss->FirstChildElement("Life");
					XMLElement * elementDommageBoss = elementBoss->FirstChildElement("Dommage");
					XMLElement * elementUrlBoss = elementBoss->FirstChildElement("UrlImage");
					if (elementLifeBoss != NULL) {
						lifeBoss = atoi(elementLifeBoss->GetText());
					}
					if (elementDommageBoss != NULL) {
						dommageBoss = atoi(elementDommageBoss->GetText());
					}
					if (elementUrlBoss != NULL) {
						urlboss = elementUrlBoss->GetText();
					}
					Boss * b = new Boss(lifeBoss, dommageBoss, img->getEnemy_t());
					TypeEnemy * type = new TypeEnemy(life, dommage, sizeEscouad);
					Level * l = new Level(nb, speed, type, b, url,urlboss);
 					this->levels.push_back(l);
					elementLevel = elementLevel->NextSiblingElement("Level");
					elementEnemy = elementEnemy->NextSiblingElement("Enemy");
					elementBoss = elementBoss->NextSiblingElement("Boss");
				}
			} while (elementLevel != NULL && elementEnemy != NULL && elementBoss != NULL);
		}
		cout <<"Nb Level Loaded : " <<this->levels.size() << endl;
	}
}
Beispiel #28
0
XMLElement* Response::GetReplyElement() const
{
  XMLNode *rootElement = m_document->RootElement();
  return rootElement->FirstChildElement("Reply");
}