예제 #1
0
//-----------------------------------------------------------------------------
// Add child node - STRING
XMLNode XMLNode::addChildNode(string _sNodeName, string _sText) 
{
	XMLNode res = addChildNode(_sNodeName);
	res.setContent(_sText);
	return res;
}
예제 #2
0
bool CLyricGetter::ProcessFile(const std::string& tempFile)
{
	std::string xml = "";
	SallyAPI::Network::NETWORK_RETURN errorCode = GetXML(&xml);

	if (errorCode != SallyAPI::Network::SUCCESS)
	{
		SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
		logger->Debug("CLyricGetter::ProcessFile::GetXML not successful");
		logger->Debug(errorCode);
		logger->Debug(GetRequestURL());

		switch (errorCode)
		{
		case SallyAPI::Network::ERROR_PREPARE:
			m_strErrorText = "Network preparation failed";
		case SallyAPI::Network::ERROR_OPEN:
			m_strErrorText = "Network open failed";
		case SallyAPI::Network::ERROR_HTTP_TIMEOUT:
			m_strErrorText = "HTTP Timeout";
		case SallyAPI::Network::ERROR_NOTHING_READ:
			m_strErrorText = "Nothing read";
		default:
			break;
		}

		return false;
	}

	if (xml.length() == 0)
	{
		m_strErrorText = "Invalide Server response";
		return false;
	}

	SallyAPI::File::FileHelper::AddLineToFile(tempFile, xml);

	if (!SallyAPI::File::FileHelper::FileExists(tempFile))
	{
		m_strErrorText = "Invalide Server response";
		return false;
	}

	XMLNode xMainNode = XMLNode::parseFile(tempFile.c_str());
	if (xMainNode.isEmpty())
	{
		m_strErrorText = "Invalide Server response";
		return false;
	}

	XMLNode itemGetLyricResult = xMainNode.getChildNode("GetLyricResult");
	if (itemGetLyricResult.isEmpty())
	{
		m_strErrorText = "No Lyric found";
		return false;
	}

	XMLNode lyric = itemGetLyricResult.getChildNode("Lyric");
	if (lyric.isEmpty())
	{
		m_strErrorText = "No Lyric found";
		return false;
	}

	const char* lyricsText = lyric.getText();

	if (lyricsText == NULL)
	{
		m_strErrorText = "No Lyric found";
		return false;
	}

	SallyAPI::GUI::SendMessage::CParameterKeyValue parameter(this->GetId(), lyricsText);
	m_pParent->SendMessageToParent(m_pParent, 0, GUI_APP_LYRICS_LOADED, &parameter);
	return true;
}
예제 #3
0
void iLedlif::xmlParseDevice(XMLNode deviceNode) {

    std::string name;
    std::string deviceClass;
    std::string deviceName;
    std::string deviceType;

    std::string devicePortName;
    std::string deviceBaudRate;
    std::string elementName;
    std::string deviceFilePath;
    std::string val;
    std::string deviceFilename;
    std::string helpedDevice;
    std::string deviceCommType;

    std::vector<lifLED*> leds;
    std::vector<lifTSDIOPin*> pins;

    //Variables for pin
    std::string pinName;
    std::string dirBase;
    std::string dirOffset;
    std::string valBase;
    std::string valOffset;
    std::string bitNum;
    std::string enLow;

    //Variables for LED
    std::string ledName;
    std::string ledWL;
    std::string LEDPower;


    //Start reading in device information
    deviceClass = deviceNode.getChildNode("Class").getText();
    deviceName = deviceNode.getChildNode("Name").getText();

    deviceType = deviceNode.getChildNode("Type").getText();
    deviceFilePath = deviceNode.getChildNode("Path_Name").getText();
    helpedDevice = deviceNode.getChildNode("Helped_Device").getText();

    //Check if there is a communication port entry for device
    if (deviceNode.nChildNode("Com_Port") > 0) {
        deviceCommType = deviceNode.getChildNode("Com_Port").getChildNode("Type").getText();
        if (deviceCommType == "Serial") {
            devicePortName = deviceNode.getChildNode("Com_Port").getChildNode("Port").getText();
            std::cout << deviceName << " " << devicePortName << std::endl;
            deviceBaudRate = deviceNode.getChildNode("Com_Port").getChildNode("Baud").getText();
        }
    }

    //Load any defined pins
    for (int i = 0; i < deviceNode.nChildNode("Pin"); i++) {
        pinName = deviceNode.getChildNode("Pin", i).getChildNode("Name").getText();
        dirBase = deviceNode.getChildNode("Pin", i).getChildNode("DirectionAddressBase").getText();
        dirOffset = deviceNode.getChildNode("Pin", i).getChildNode("DirectionAddressOffset").getText();
        valBase = deviceNode.getChildNode("Pin", i).getChildNode("ValueAddressBase").getText();
        valOffset = deviceNode.getChildNode("Pin", i).getChildNode("ValueAddressOffset").getText();
        bitNum = deviceNode.getChildNode("Pin", i).getChildNode("BitNumber").getText();
        enLow = deviceNode.getChildNode("Pin", i).getChildNode("EnabledLow").getText();
        pins.push_back(new lifTSDIOPin(pinName,
                                       string2int(bitNum),
                                       hexstring2int(dirBase),
                                       hexstring2int(dirOffset),
                                       hexstring2int(valBase),
                                       hexstring2int(valOffset),
                                       string2bool(enLow)));
    }

    //Load any LEDs
    for (int i = 0; i < deviceNode.nChildNode("LED"); i++) {
        ledName = deviceNode.getChildNode("LED", i).getChildNode("Name").getText();
        ledWL = deviceNode.getChildNode("LED", i).getChildNode("Wavelength").getText();
        LEDPower = deviceNode.getChildNode("LED", i).getChildNode("PowerSource").getText();
        leds.push_back(new lifLED(ledName, string2int(ledWL), LEDPower));
    }

    //declare device
    if (deviceClass == "Spectrometer") {
        std::cout << "iLedlif: Starting to load Spectrometer " << deviceName << std::endl;
        lifDevices.push_back((lifDevice*) (new lifSpectrometer(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed,
                                           deviceFilePath,
                                           devicePortName,
                                           string2int(deviceBaudRate),
                                           *pins.front())));
        std::cout << "iLedlif: Loaded Spectrometer " << deviceName << std::endl;
    } else if (deviceClass == "Main Com") {
        lifDevices.push_back((lifDevice*) (new lifMainComm(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed,
                                           devicePortName,
                                           string2int(deviceBaudRate))));
        std::cout << "iLedlif: Loaded Main Comm " << deviceName << std::endl;
    } else if (deviceClass == "LED Array") {
        lifDevices.push_back((lifDevice*) (new lifLEDArray(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed,
                                           leds)));
        std::cout << "iLedlif: Loaded LED Array " << deviceName << std::endl;
    } else if (deviceClass == "Spec Helper") {
        lifDevices.push_back((lifDevice*) (new lifSpecHelper(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed,
                                           helpedDevice)));
        std::cout << "iLedlif: Loaded Spec Helper " << deviceName << std::endl;
    } else if (deviceClass == "DIO Device") {
        lifDevices.push_back((lifDevice*) (new lifDIODevice(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed,
                                           pins)));
        std::cout << "iLedlif: Loaded DIO Device " << deviceName << std::endl;
    } else if (deviceClass == "SSP Controller") {
        lifDevices.push_back((lifDevice*) (new lifSSPController(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed)));
        std::cout << "iLedlif: Loaded SSP Controller " << deviceName << std::endl;
    } else if (deviceClass == "Generic Device") {
        lifDevices.push_back(new lifDevice(deviceName,
                                           deviceType,
                                           &mainMsgQueue,
                                           &mainMsgMutex,
                                           &mainMsgQueuePushed));
        std::cout << "Generic Device added" << std::endl;
    } else if (deviceClass == "Program Runner") {
        lifDevices.push_back((lifDevice*) (new lifProgramRunner(
                                               deviceName,
                                               deviceType,
                                               &mainMsgQueue,
                                               &mainMsgMutex,
                                               &mainMsgQueuePushed,
                                               deviceFilename)));
        std::cout << "iLedlif: Loaded ProgramRunner " << deviceName << std::endl;
    }
}
예제 #4
0
void XMLDocMerger::fill_defaults(
          YangNode* ynode,
          XMLNode*  new_node,
          XMLNode*  update_node,
          bool*     update_required
       )
{
  YangNode* yn = nullptr;
  XMLNode*  xchild = nullptr;

  for (YangNodeIter it = ynode->child_begin();
       it != ynode->child_end(); ++it) {
    yn = &(*it);
    const char* default_val = yn->get_default_value();
    if (!default_val && !yn->has_default()) {
      // Only default values or containers with default leaf descendents
      continue;
    }

    // Default values may be within a choice/case. Check if the choice has
    // another case. If the same case is present
    YangNode* ychoice = yn->get_choice();
    YangNode* ycase = yn->get_case();
    YangNode* other_choice = nullptr;
    YangNode* other_case   = nullptr;
    bool add_default = true;
    bool subtree_update = false;
    if (ychoice && ycase && (ychoice->get_default_case() != ycase)) {
      add_default = false;
    }

    for (XMLNodeIter xit = new_node->child_begin();
         xit != new_node->child_end(); ++xit) {
      xchild = &(*xit);
      if (xchild->get_local_name() == yn->get_name() &&
          xchild->get_name_space() == yn->get_ns()) {
        if (yn->get_stmt_type() == RW_YANG_STMT_TYPE_CONTAINER) {
          // The container has a default descendant node
          XMLNode* update_child = nullptr;
          bool created = false;
          if ((update_child = update_node->find(
                                yn->get_name(), yn->get_ns())) == nullptr) {
            update_child = update_node->add_child(yn);
            created = true;
          }
          fill_defaults(yn, xchild, update_child, &subtree_update);
          if (!subtree_update && created) {
            update_node->remove_child(update_child);
          }
          *update_required = (*update_required || subtree_update);
        }
        // Default node already present in the new-dom
        add_default = false;
        break;
      }
      
      if (!ychoice) {
        // Not part of a choice
        continue;
      }

      other_choice = xchild->get_yang_node()->get_choice();
      if (!other_choice || (other_choice != ychoice)) {
        // Other node is not a choice, or not the same choice, not conflicting
        continue;
      }

      other_case = xchild->get_yang_node()->get_case();
      if (other_case && (ycase != other_case)) {
        // There is a node with conflicting case. Hence no default
        add_default = false;
        break;
      }

      // Same case, in-case the case is not default, some-other node in the same
      // case is set. Then add this default, unless the same node is found in
      // the new-dom.
      add_default = true;
    }
    if (add_default) {
      XMLNode* xn = new_node->add_child(yn, default_val);
      RW_ASSERT(xn);
      XMLNode* un = update_node->add_child(yn, default_val);
      if (yn->get_stmt_type() == RW_YANG_STMT_TYPE_CONTAINER) {
        // The container has a default descendant node
        fill_defaults(yn, xn, un, &subtree_update);
        if (!subtree_update) {
          new_node->remove_child(xn);
          update_node->remove_child(un);
        }
        *update_required = (*update_required || subtree_update);
      } else {
        *update_required = true;
      }
    }
  }
}
예제 #5
0
/*
 * Creates a new ReactionGlyph from the given XMLNode
 */
ReactionGlyph::ReactionGlyph(const XMLNode& node, unsigned int l2version)
  : GraphicalObject(node,l2version)
   ,mReaction      ("")
   ,mSpeciesReferenceGlyphs(2,l2version)
   ,mCurve(2,l2version)
   ,mCurveExplicitlySet (false)
{
    const XMLAttributes& attributes=node.getAttributes();
    const XMLNode* child;
    ExpectedAttributes ea;
    addExpectedAttributes(ea);
    this->readAttributes(attributes,ea);
    unsigned int n=0,nMax = node.getNumChildren();
    while(n<nMax)
    {
        child=&node.getChild(n);
        const std::string& childName=child->getName();
        if(childName=="curve")
        {
            // since the copy constructor of ListOf does not make deep copies
            // of the objects, we have to add the individual curveSegments to the 
            // curve instead of just copying the whole curve.
            Curve* pTmpCurve=new Curve(*child);
            unsigned int i,iMax=pTmpCurve->getNumCurveSegments();
            for(i=0;i<iMax;++i)
            {
                this->mCurve.addCurveSegment(pTmpCurve->getCurveSegment(i));
            }
            // we also have to copy mAnnotations, mNotes, mCVTerms and mHistory
            if(pTmpCurve->isSetNotes()) this->mCurve.setNotes(new XMLNode(*pTmpCurve->getNotes()));
            if(pTmpCurve->isSetAnnotation()) this->mCurve.setAnnotation(new XMLNode(*pTmpCurve->getAnnotation()));
            if(pTmpCurve->getCVTerms()!=NULL)
            {
              iMax=pTmpCurve->getCVTerms()->getSize(); 
              for(i=0;i<iMax;++i)
              {
                this->mCurve.getCVTerms()->add(static_cast<CVTerm*>(pTmpCurve->getCVTerms()->get(i))->clone());
              }
            }
            delete pTmpCurve;
            mCurveExplicitlySet = true;
        }
        else if(childName=="listOfSpeciesReferenceGlyphs")
        {
            const XMLNode* innerChild;
            unsigned int i=0,iMax=child->getNumChildren();
            while(i<iMax)
            {
                innerChild=&child->getChild(i);
                const std::string innerChildName=innerChild->getName();
                if(innerChildName=="speciesReferenceGlyph")
                {
                    this->mSpeciesReferenceGlyphs.appendAndOwn(new SpeciesReferenceGlyph(*innerChild));
                }
                else if(innerChildName=="annotation")
                {
                    this->mSpeciesReferenceGlyphs.setAnnotation(new XMLNode(*innerChild));
                }
                else if(innerChildName=="notes")
                {
                    this->mSpeciesReferenceGlyphs.setNotes(new XMLNode(*innerChild));
                }
                else
                {
                    // throw
                }
                ++i;
            }
        }
        else
        {
            //throw;
        }
        ++n;
    }    

  connectToChild();
}
예제 #6
0
TEST (RwXML, Attributes)
{
  XMLManager::uptr_t mgr(xml_manager_create_xerces());
  TEST_DESCRIPTION ("Test Attribute support in RW XML");

  XMLDocument::uptr_t doc(mgr->create_document());
  ASSERT_TRUE(doc.get());
  
  XMLNode *root = doc->get_root_node();
  ASSERT_TRUE (root);
  
  XMLNode *child_1 = root->add_child("level1_1");
  ASSERT_TRUE (child_1);

  XMLNode *child_2 = root->add_child("level1_2");
  ASSERT_TRUE (child_2);

  XMLNodeList::uptr_t list_1(doc->get_elements ("level1_1"));
  ASSERT_TRUE (list_1.get());
  ASSERT_EQ (1, list_1->length());

  XMLNode *dup = list_1->at(0);
  ASSERT_EQ (dup, child_1);

  list_1 = root->get_children();
  ASSERT_EQ (2, list_1->length());

  XMLNode *ns_child_1 = root->add_child("level1_1", nullptr, "rwtest/NS-1", "NS1");
  ASSERT_TRUE (ns_child_1);

  XMLNode *ns_child_2 = root->add_child("level1_2", nullptr, "rwtest/NS-1", "NS1");
  ASSERT_TRUE (ns_child_2);
  
  list_1 = std::move(doc->get_elements ("level1_1"));
  ASSERT_TRUE (list_1.get());
  ASSERT_EQ (1, list_1->length());

  XMLAttributeList::uptr_t list_a1(child_1->get_attributes());
  ASSERT_TRUE (list_a1.get());
  ASSERT_EQ (0, list_a1->length());

  child_1->set_attribute("attr1", "value1");
  const char *ns = "http://www.riftio.com/namespace";
  child_1->set_attribute("attr2", "value2", ns, "ns");
  ASSERT_TRUE (child_1->has_attributes());
  ASSERT_TRUE (child_1->has_attribute("attr1"));
  //XMLAttribute::uptr_t attr = std::move(child_1->get_attribute("attr1"));
  //ASSERT_NE (nullptr, attr.get());
  list_a1 = std::move(child_1->get_attributes());
  ASSERT_TRUE (list_a1.get());
  ASSERT_EQ (2, list_a1->length());
#if 0
  for (uint32_t i = 0; i <  list_a1->length(); i++) {
    XMLAttribute *attr = list_a1->at(i);
    std::cout <<  attr->get_node_name().c_str() << " : " << attr->get_value().c_str() << std::endl;
  }
#endif

  EXPECT_STREQ(list_a1->at(0)->get_local_name().c_str(), "attr1");
  EXPECT_STREQ(list_a1->at(0)->get_value().c_str(), "value1");
  EXPECT_STREQ(list_a1->at(1)->get_local_name().c_str(), "attr2");
  EXPECT_STREQ(list_a1->at(1)->get_prefix().c_str(), "ns");
  EXPECT_STREQ(list_a1->at(1)->get_text_value().c_str(), "value2");
  EXPECT_STREQ(list_a1->at(1)->get_name_space().c_str(), "http://www.riftio.com/namespace");
  EXPECT_STREQ(list_a1->at(1)->get_value().c_str(), "value2");


  child_2->set_attribute("attr3", "value3");
  child_2->set_attribute("attr4", "value4");
  child_2->set_attribute("attr5", "value5");

  XMLAttributeList::uptr_t list_a2(child_2->get_attributes());
  ASSERT_TRUE (list_a2.get());
  ASSERT_EQ (3, list_a2->length());

  std::string tmp_str;
  std::string exp_str = "<data xmlns=\"http://riftio.com/ns/riftware-1.0/rw-base\"><level1_1 attr1=\"value1\" xmlns:ns=\"http://www.riftio.com/namespace\" ns:attr2=\"value2\"/><level1_2 attr3=\"value3\" attr4=\"value4\" attr5=\"value5\"/><NS1:level1_1 xmlns:NS1=\"rwtest/NS-1\"/><NS1:level1_2 xmlns:NS1=\"rwtest/NS-1\"/></data>";
  tmp_str = doc->to_string();
  ASSERT_EQ (tmp_str, exp_str);
}
예제 #7
0
// ATTN: This function seriously needs re-organization, will be done
// shortly.
rw_yang_netconf_op_status_t XMLDocMerger::do_edit(XMLNode* new_node, 
                XMLNode* delta_node,
                XMLNode* update_node,
                bool* update_required)
{
  rw_yang_netconf_op_status_t status = RW_YANG_NETCONF_OP_STATUS_OK;
  YangNode* ynode = new_node->get_descend_yang_node();
  XMLEditDefaultOperation parent_op = current_operation_;

  for(XMLNodeIter it = delta_node->child_begin();
      it != delta_node->child_end(); ++it)
  {
    XMLNode* delta_child = &(*it);
    std::string child_name = delta_child->get_local_name();
    std::string child_ns = delta_child->get_name_space();

    YangNode* child_ynode = ynode->search_child(child_name.c_str(), 
                                                child_ns.c_str());
    if (child_ynode == nullptr) {
      // Incoming node is not in our model and thus is an error
      std::string const err_msg = "Cannot find child ("+child_name+") of node ("+delta_node->get_local_name()+")";
      report_error(delta_node, RW_YANG_NETCONF_OP_STATUS_INVALID_VALUE, err_msg.c_str());
      return RW_YANG_NETCONF_OP_STATUS_INVALID_VALUE;
    }

    // Set the current node operation (default=merge)
    status = set_current_operation(delta_child);
    if (status !=  RW_YANG_NETCONF_OP_STATUS_OK) {
      return status;
    }

    bool subtree_update = false;

    XMLNode* new_child = new_node->find(child_name.c_str(), child_ns.c_str());
    if (new_child == nullptr) {
      // Node not found in existing config, edit-config on new node
      status = do_edit_new(child_ynode, new_node, delta_child, 
                           update_node, &subtree_update);
    } else {
      status = do_edit_existing(child_ynode, new_node, new_child, delta_child,
                           update_node, &subtree_update);
    }

    *update_required = (*update_required || subtree_update);

    if (status !=  RW_YANG_NETCONF_OP_STATUS_OK) {
      return status;
    }
    current_operation_ = parent_op;
  }

  if (current_operation_ == XML_EDIT_OP_REPLACE) {
    // Iterate thru the config dom node and find the elements not in delta
    // Those are marked for deletion.
    do_delete_missing(new_node, delta_node);
  }

  // Add defaults
  fill_defaults(ynode, new_node, update_node, update_required);

  if (!(*update_required)) {
    // No updates on this subtree. Either it is delete/remove operation or
    // the config is not changed. So remove the update subtree. 
    XMLNode* parent = update_node->get_parent();
    if (parent) {
      parent->remove_child(update_node);
    }
  }

  if (new_node->get_first_child() == nullptr &&
      ynode->get_stmt_type() == RW_YANG_STMT_TYPE_CONTAINER &&
      !ynode->is_presence()) {
    // No children for a non-presence container, they are only present to
    // maintain hierarchy. Remove it
    XMLNode* parent = new_node->get_parent();
    if (parent) {
      parent->remove_child(new_node);
    }
  }

  return status;
}
int main(int argc, char **argv)
{
	// run for selected COCO functions
	for(uint function = 1; function < 25; function++) {

		// read XML config
		std::ifstream fin(argv[1]);
		if (!fin) {
			throw std::string("Error opening file! ");
		}

		std::string xmlFile, temp;
		while (!fin.eof()) {
			getline(fin, temp);
			xmlFile += "\n" + temp;
		}
		fin.close();

		// set log and stats parameters
		std::string funcName = uint2str(function);
		std::string logName = "log", statsName = "stats";
		if(function < 10) {
			logName += "0";
			statsName += "0";
		}
		logName += uint2str(function) + ".txt";
		statsName += uint2str(function) + ".txt";

		// update in XML
		XMLResults results;
		XMLNode xConfig = XMLNode::parseString(xmlFile.c_str(), "ECF", &results);
		XMLNode registry = xConfig.getChildNode("Registry");

		XMLNode func = registry.getChildNodeWithAttribute("Entry", "key", "coco.function");
		func.updateText(funcName.c_str());
		XMLNode log = registry.getChildNodeWithAttribute("Entry", "key", "log.filename");
		log.updateText(logName.c_str());
		XMLNode stats = registry.getChildNodeWithAttribute("Entry", "key", "batch.statsfile");
		stats.updateText(statsName.c_str());

		// write back
		std::ofstream fout(argv[1]);
		fout << xConfig.createXMLString(true);
		fout.close();


		// finally, run ECF on single function
		StateP state (new State);

		//set newAlg
		MyAlgP alg = (MyAlgP) new MyAlg;
		state->addAlgorithm(alg);
		// set the evaluation operator
		state->setEvalOp(new FunctionMinEvalOp);

		state->initialize(argc, argv);
		state->run();
	}

	return 0;
}
// ----------------------------------------------------------------------------
TrackObjectPresentationLibraryNode::TrackObjectPresentationLibraryNode(
    TrackObject* parent,
    const XMLNode& xml_node,
    ModelDefinitionLoader& model_def_loader)
    : TrackObjectPresentationSceneNode(xml_node)
{
    std::string name;
    xml_node.get("name", &name);

    m_node = irr_driver->getSceneManager()->addEmptySceneNode();
#ifdef DEBUG
    m_node->setName(("libnode_" + name).c_str());
#endif

    XMLNode* libroot;
    std::string lib_path =
        file_manager->getAsset(FileManager::LIBRARY, name) + "/";

    bool create_lod_definitions = true;

    if (!model_def_loader.containsLibraryNode(name))
    {
        World* world = World::getWorld();
        Track* track = NULL;
        if (world != NULL)
            track = world->getTrack();
        std::string local_lib_node_path;
        std::string local_script_file_path;
        if (track != NULL)
        {
            local_lib_node_path = track->getTrackFile("library/" + name + "/node.xml");
            local_script_file_path = track->getTrackFile("library/" + name + "/scripting.as");
        }
        std::string lib_node_path = lib_path + "node.xml";
        std::string lib_script_file_path = lib_path + "scripting.as";

        if (local_lib_node_path.size() > 0 && file_manager->fileExists(local_lib_node_path))
        {
            lib_path = track->getTrackFile("library/" + name);
            libroot = file_manager->createXMLTree(local_lib_node_path);
            if (track != NULL)
                World::getWorld()->getScriptEngine()->loadScript(local_script_file_path, false);
        }
        else if (file_manager->fileExists(lib_node_path))
        {
            libroot = file_manager->createXMLTree(lib_node_path);
            if (track != NULL)
                World::getWorld()->getScriptEngine()->loadScript(lib_script_file_path, false);
        }
        else
        {
            Log::error("TrackObjectPresentationLibraryNode",
                "Cannot find library '%s'", lib_node_path.c_str());
            return;
        }

        if (libroot == NULL)
        {
            Log::error("TrackObjectPresentationLibraryNode",
                       "Cannot find library '%s'", lib_node_path.c_str());
            return;
        }

        file_manager->pushTextureSearchPath(lib_path + "/");
        file_manager->pushModelSearchPath(lib_path);
        material_manager->pushTempMaterial(lib_path + "/materials.xml");
        model_def_loader.addToLibrary(name, libroot);

        // Load LOD groups
        const XMLNode *lod_xml_node = libroot->getNode("lod");
        if (lod_xml_node != NULL)
        {
            for (unsigned int i = 0; i < lod_xml_node->getNumNodes(); i++)
            {
                const XMLNode* lod_group_xml = lod_xml_node->getNode(i);
                for (unsigned int j = 0; j < lod_group_xml->getNumNodes(); j++)
                {
                    model_def_loader.addModelDefinition(lod_group_xml->getNode(j));
                }
            }
        }
    }
    else
    {
        libroot = model_def_loader.getLibraryNodes()[name];
        assert(libroot != NULL);
        // LOD definitions are already created, don't create them again
        create_lod_definitions = false;
    }

    m_node->setPosition(m_init_xyz);
    m_node->setRotation(m_init_hpr);
    m_node->setScale(m_init_scale);
    m_node->updateAbsolutePosition();

    assert(libroot != NULL);
    World::getWorld()->getTrack()->loadObjects(libroot, lib_path, model_def_loader,
        create_lod_definitions, m_node, parent);
    m_parent = parent;
}   // TrackObjectPresentationLibraryNode
예제 #10
0
/** Constructor for a checkline.
 *  \param node XML node containing the parameters for this checkline.
 *  \param index Index of this check structure in the check manager.
 */
CheckLine::CheckLine(const XMLNode &node,  unsigned int index)
         : CheckStructure(node, index)
{
    // Note that when this is called the karts have not been allocated
    // in world, so we can't call world->getNumKarts()
    m_previous_sign.resize(race_manager->getNumberOfKarts());
    std::string p1_string("p1");
    std::string p2_string("p2");

    // In case of a cannon in a reverse track, we have to use the target line
    // as check line
    if(getType()==CT_CANNON && race_manager->getReverseTrack())
    {
        p1_string = "target-p1";
        p2_string = "target-p2";
    }
    core::vector2df p1, p2;
    if(node.get(p1_string, &p1)   &&
        node.get(p2_string, &p2)  &&
        node.get("min-height", &m_min_height))
    {
        m_left_point  = Vec3(p1.X, m_min_height, p1.Y);
        m_right_point = Vec3(p2.X, m_min_height, p2.Y);
    }
    else
    {
        node.get(p1_string, &m_left_point);
        p1 = core::vector2df(m_left_point.getX(), m_left_point.getZ());
        node.get(p2_string, &m_right_point);
        p2 = core::vector2df(m_right_point.getX(), m_right_point.getZ());
        m_min_height = std::min(m_left_point.getY(), m_right_point.getY());
    }
    m_line.setLine(p1, p2);
    if(UserConfigParams::m_check_debug)
    {
        video::SMaterial material;
        material.setFlag(video::EMF_BACK_FACE_CULLING, false);
        material.setFlag(video::EMF_LIGHTING, false);
        material.MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
        scene::IMesh *mesh = irr_driver->createQuadMesh(&material,
                                                        /*create mesh*/true);
        scene::IMeshBuffer *buffer = mesh->getMeshBuffer(0);
        assert(buffer->getVertexType()==video::EVT_STANDARD);
        irr::video::S3DVertex* vertices
            = (video::S3DVertex*)buffer->getVertices();
        vertices[0].Pos = core::vector3df(p1.X,
                                          m_min_height-m_under_min_height,
                                          p1.Y);
        vertices[1].Pos = core::vector3df(p2.X,
                                          m_min_height-m_under_min_height,
                                          p2.Y);
        vertices[2].Pos = core::vector3df(p2.X,
                                          m_min_height+m_over_min_height,
                                          p2.Y);
        vertices[3].Pos = core::vector3df(p1.X,
                                          m_min_height+m_over_min_height,
                                          p1.Y);
        for(unsigned int i=0; i<4; i++)
        {
            vertices[i].Color = m_active_at_reset
                              ? video::SColor(0, 255, 0, 0)
                              : video::SColor(0, 128, 128, 128);
        }
        buffer->recalculateBoundingBox();
        mesh->setBoundingBox(buffer->getBoundingBox());
        m_debug_node = irr_driver->addMesh(mesh);
        mesh->drop();
    }
    else
    {
        m_debug_node = NULL;
    }
}   // CheckLine
예제 #11
0
char* XMLNode::ParseDeep( char* p, StrPair* parentEnd )
{
    // This is a recursive method, but thinking about it "at the current level"
    // it is a pretty simple flat list:
    //        <foo/>
    //        <!-- comment -->
    //
    // With a special case:
    //        <foo>
    //        </foo>
    //        <!-- comment -->
    //
    // Where the closing element (/foo) *must* be the next thing after the opening
    // element, and the names must match. BUT the tricky bit is that the closing
    // element will be read by the child.
    //
    // 'endTag' is the end tag for this node, it is returned by a call to a child.
    // 'parentEnd' is the end tag for the parent, which is filled in and returned.

    while( p && *p ) {
        XMLNode* node = 0;

        p = document->Identify( p, &node );
        if ( p == 0 || node == 0 ) {
            break;
        }

        StrPair endTag;
        p = node->ParseDeep( p, &endTag );
        if ( !p ) {
            DELETE_NODE( node );
            node = 0;
            if ( !document->Error() ) {
                document->SetError( XML_ERROR_PARSING, 0, 0 );
            }
            break;
        }

        // We read the end tag. Return it to the parent.
        if ( node->ToElement() && node->ToElement()->ClosingType() == XMLElement::CLOSING ) {
            if ( parentEnd ) {
                *parentEnd = static_cast<XMLElement*>(node)->value;
            }
            DELETE_NODE( node );
            return p;
        }

        // Handle an end tag returned to this level.
        // And handle a bunch of annoying errors.
        XMLElement* ele = node->ToElement();
        if ( ele ) {
            if ( endTag.Empty() && ele->ClosingType() == XMLElement::OPEN ) {
                document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 );
                p = 0;
            }
            else if ( !endTag.Empty() && ele->ClosingType() != XMLElement::OPEN ) {
                document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 );
                p = 0;
            }
            else if ( !endTag.Empty() ) {
                if ( !XMLUtil::StringEqual( endTag.GetStr(), node->Value() )) {
                    document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 );
                    p = 0;
                }
            }
        }
        if ( p == 0 ) {
            DELETE_NODE( node );
            node = 0;
        }
        if ( node ) {
            this->InsertEndChild( node );
        }
    }
    return 0;
}
예제 #12
0
//-----------------------------------------------------------------------------	
// Add option - FLOAT
void XMLNode::addOption(string _sName, float32 _sText) 
{
	XMLNode node = addChildNode("Option");
	node.addAttribute("key", _sName);
	node.addAttribute("value", _sText);
}
예제 #13
0
//-----------------------------------------------------------------------------
// Add child node - LIST
XMLNode XMLNode::addChildNode(string _sNodeName, float32* _pfList, int _iSize) 
{
	XMLNode res = addChildNode(_sNodeName);
	res.setContent(_pfList, _iSize);
	return res;
}
예제 #14
0
//-----------------------------------------------------------------------------
// Add child node - FLOAT
XMLNode XMLNode::addChildNode(string _sNodeName, float32 _fValue) 
{
	XMLNode res = addChildNode(_sNodeName);
	res.setContent(_fValue);
	return res;
}
//---------------------------------------------------------------------------------------
// Initialize - Config
bool CReconstructionAlgorithm2D::initialize(const Config& _cfg)
{
	ASTRA_ASSERT(_cfg.self);
	ConfigStackCheck<CAlgorithm> CC("ReconstructionAlgorithm2D", this, _cfg);
	
	// projector
	XMLNode node = _cfg.self.getSingleNode("ProjectorId");
	ASTRA_CONFIG_CHECK(node, "Reconstruction2D", "No ProjectorId tag specified.");
	int id = boost::lexical_cast<int>(node.getContent());
	m_pProjector = CProjector2DManager::getSingleton().get(id);
	CC.markNodeParsed("ProjectorId");

	// sinogram data
	node = _cfg.self.getSingleNode("ProjectionDataId");
	ASTRA_CONFIG_CHECK(node, "Reconstruction2D", "No ProjectionDataId tag specified.");
	id = boost::lexical_cast<int>(node.getContent());
	m_pSinogram = dynamic_cast<CFloat32ProjectionData2D*>(CData2DManager::getSingleton().get(id));
	CC.markNodeParsed("ProjectionDataId");

	// reconstruction data
	node = _cfg.self.getSingleNode("ReconstructionDataId");
	ASTRA_CONFIG_CHECK(node, "Reconstruction2D", "No ReconstructionDataId tag specified.");
	id = boost::lexical_cast<int>(node.getContent());
	m_pReconstruction = dynamic_cast<CFloat32VolumeData2D*>(CData2DManager::getSingleton().get(id));
	CC.markNodeParsed("ReconstructionDataId");

	// fixed mask
	if (_cfg.self.hasOption("ReconstructionMaskId")) {
		m_bUseReconstructionMask = true;
		id = boost::lexical_cast<int>(_cfg.self.getOption("ReconstructionMaskId"));
		m_pReconstructionMask = dynamic_cast<CFloat32VolumeData2D*>(CData2DManager::getSingleton().get(id));
		ASTRA_CONFIG_CHECK(m_pReconstructionMask, "Reconstruction2D", "Invalid ReconstructionMaskId.");
	}
	CC.markOptionParsed("ReconstructionMaskId");

	// fixed mask
	if (_cfg.self.hasOption("SinogramMaskId")) {
		m_bUseSinogramMask = true;
		id = boost::lexical_cast<int>(_cfg.self.getOption("SinogramMaskId"));
		m_pSinogramMask = dynamic_cast<CFloat32ProjectionData2D*>(CData2DManager::getSingleton().get(id));
		ASTRA_CONFIG_CHECK(m_pSinogramMask, "Reconstruction2D", "Invalid SinogramMaskId.");
	}
	CC.markOptionParsed("SinogramMaskId");

	// Constraints - NEW
	if (_cfg.self.hasOption("MinConstraint")) {
		m_bUseMinConstraint = true;
		m_fMinValue = _cfg.self.getOptionNumerical("MinConstraint", 0.0f);
		CC.markOptionParsed("MinConstraint");
	} else {
		// Constraint - OLD
		m_bUseMinConstraint = _cfg.self.getOptionBool("UseMinConstraint", false);
		CC.markOptionParsed("UseMinConstraint");
		if (m_bUseMinConstraint) {
			m_fMinValue = _cfg.self.getOptionNumerical("MinConstraintValue", 0.0f);
			CC.markOptionParsed("MinConstraintValue");
		}
	}
	if (_cfg.self.hasOption("MaxConstraint")) {
		m_bUseMaxConstraint = true;
		m_fMaxValue = _cfg.self.getOptionNumerical("MaxConstraint", 255.0f);
		CC.markOptionParsed("MaxConstraint");
	} else {
		// Constraint - OLD
		m_bUseMaxConstraint = _cfg.self.getOptionBool("UseMaxConstraint", false);
		CC.markOptionParsed("UseMaxConstraint");
		if (m_bUseMaxConstraint) {
			m_fMaxValue = _cfg.self.getOptionNumerical("MaxConstraintValue", 0.0f);
			CC.markOptionParsed("MaxConstraintValue");
		}
	}

	// return success
	return _check();
}
TrackObjectPresentationSound::TrackObjectPresentationSound(const XMLNode& xml_node, scene::ISceneNode* parent) :
    TrackObjectPresentation(xml_node)
{
    // TODO: respect 'parent' if any

    m_sound = NULL;
    m_xyz = m_init_xyz;

    std::string sound;
    xml_node.get("sound", &sound);

    float rolloff = 0.5;
    xml_node.get("rolloff",  &rolloff );
    float volume = 1.0;
    xml_node.get("volume",   &volume );

    bool trigger_when_near = false;
    xml_node.get("play-when-near", &trigger_when_near);

    float trigger_distance = 1.0f;
    xml_node.get("distance", &trigger_distance);

    xml_node.get("conditions", &m_trigger_condition);

    float max_dist = 390.0f;
    xml_node.get("max_dist", &max_dist );

    // first try track dir, then global dir
    std::string soundfile = file_manager->getAsset(FileManager::MODEL,sound);
    if (!file_manager->fileExists(soundfile))
    {
        soundfile = file_manager->getAsset(FileManager::SFX, sound);
    }

    SFXBuffer* buffer = new SFXBuffer(soundfile,
                                      true /* positional */,
                                      rolloff,
                                      max_dist,
                                      volume);
    buffer->load();

    m_sound = sfx_manager->createSoundSource(buffer, true, true);
    if (m_sound != NULL)
    {
        m_sound->position(m_init_xyz);
        if (!trigger_when_near && m_trigger_condition.empty())
        {
            m_sound->setLoop(true);
            m_sound->play();
        }
    }
    else
    {
        fprintf(stderr,
             "[TrackObject] Sound emitter object could not be created\n");
    }

    if (trigger_when_near)
    {
        ItemManager::get()->newItem(m_init_xyz, trigger_distance, this);
    }
}
예제 #17
0
TEST (RwXML, CreateDestroy)
{
  XMLManager::uptr_t mgr(xml_manager_create_xerces());
  TEST_DESCRIPTION ("Create and Destroy a DOM");

  XMLDocument::uptr_t doc(mgr->create_document());
  ASSERT_TRUE(doc.get());
  
  XMLNode *root = doc->get_root_node();
  ASSERT_TRUE (root);
  
  XMLNode *child_1 = root->add_child("level1_1");
  ASSERT_TRUE (child_1);

  XMLNode *child_2 = root->add_child("level1_2");
  ASSERT_TRUE (child_2);

  XMLNodeList::uptr_t list_1(doc->get_elements ("level1_1"));
  ASSERT_TRUE (list_1.get());
  ASSERT_EQ (1, list_1->length());

  XMLNode *dup = list_1->at(0);
  ASSERT_EQ (dup, child_1);

  list_1 = root->get_children();
  ASSERT_EQ (2, list_1->length());

  dup = root->find("level1_1");
  ASSERT_EQ (dup, child_1);

  dup = root->find("level1_2");
  ASSERT_EQ (dup, child_2);

  dup = root->find("level2_2");
  ASSERT_EQ (dup, nullptr);

  XMLNode *ns_child_1 = root->add_child("level1_1", nullptr, "rwtest/NS-1", "NS1");
  ASSERT_TRUE (ns_child_1);

  XMLNode *ns_child_2 = root->add_child("level1_2", nullptr, "rwtest/NS-1", "NS1");
  ASSERT_TRUE (ns_child_2);
  
  list_1 = std::move(doc->get_elements ("level1_1"));
  ASSERT_TRUE (list_1.get());
  ASSERT_EQ (1, list_1->length());

  dup = list_1->at(0);
  ASSERT_EQ (dup, child_1);

  list_1 = std::move(doc->get_elements ("level1_1", "rwtest/NS-1"));
  ASSERT_TRUE (list_1.get());
  ASSERT_EQ (1, list_1->length());

  dup = list_1->at(0);
  ASSERT_EQ (dup, ns_child_1);

  std::string tmp_str;
  std::string exp_str = "<data xmlns=\"http://riftio.com/ns/riftware-1.0/rw-base\"><level1_1/><level1_2/><NS1:level1_1 xmlns:NS1=\"rwtest/NS-1\"/><NS1:level1_2 xmlns:NS1=\"rwtest/NS-1\"/></data>";

  tmp_str = doc->to_string();
  EXPECT_EQ (tmp_str, exp_str);

  CFMutableStringRef cf = CFStringCreateMutable (NULL, 0);
  rw_xml_document_to_cfstring ((rw_xml_document_t *) doc.get(),
                               cf);

  char from_cf[500];

  CFStringGetCString (cf, from_cf, sizeof (from_cf), kCFStringEncodingUTF8);

  EXPECT_STREQ (tmp_str.c_str(), from_cf);
  std::string error_out;
  XMLDocument::uptr_t dup_doc = mgr->create_document_from_string (tmp_str.c_str(), error_out, false);

  list_1 = std::move(dup_doc->get_elements ("level1_1"));
  ASSERT_TRUE (list_1.get());
  ASSERT_EQ (1, list_1->length());

  dup = list_1->at(0);

  XMLNode *child_1_1 = child_1->add_child("level1_1_1", "chi_1_1-val0");
  ASSERT_TRUE (child_1_1);

  XMLNode *child_1_2 = child_1->add_child("level1_1_1", "chi_1_1-val2");
  ASSERT_TRUE (child_1_2);
  
  tmp_str = root->to_string();
  std::cout << tmp_str << std::endl;

  rw_xml_node_to_cfstring ((rw_xml_node_t*) root, cf);
  CFStringGetCString (cf, from_cf, sizeof (from_cf), kCFStringEncodingUTF8);

  EXPECT_STREQ (tmp_str.c_str(), from_cf);
  
  bool remove_status = child_1->remove_child(child_1_2);
  ASSERT_TRUE(remove_status);

  tmp_str = root->to_string();
  std::cout << "Original after removal = "<< std::endl<<tmp_str << std::endl;

  root = dup_doc->get_root_node();

  std::cout << "Dup doc " << std::endl;
  tmp_str = root->to_stdout();
  std::cout << std::endl;
  CFRelease(cf);
}
예제 #18
0
GrandPrixData::GrandPrixData(const std::string filename) throw(std::logic_error)
{
    m_filename = filename;
    m_id       = StringUtils::getBasename(StringUtils::removeExtension(filename));

    XMLNode* root = file_manager->createXMLTree(file_manager->getAsset(FileManager::GRANDPRIX,filename));
    if (!root)
    {
        Log::error("GrandPrixData","Error while trying to read grandprix file '%s'", 
                    filename.c_str());
        throw std::logic_error("File not found");
    }

    bool foundName = false;

    if (root->getName() == "supertuxkart_grand_prix")
    {
        std::string temp_name;
        if (root->get("name", &temp_name) == 0)
        {
             Log::error("GrandPrixData", "Error while trying to read grandprix file '%s' : "
                    "missing 'name' attribute\n", filename.c_str());
            delete root;
            throw std::logic_error("File contents are incomplete or corrupt");
        }
        m_name = temp_name.c_str();
        foundName = true;
    }
    else
    {
        Log::error("GrandPrixData", "Error while trying to read grandprix file '%s' : "
                "Root node has an unexpected name\n", filename.c_str());
        delete root;
        throw std::logic_error("File contents are incomplete or corrupt");
    }


    const int amount = root->getNumNodes();
    for (int i=0; i<amount; i++)
    {
        const XMLNode* node = root->getNode(i);

        // read a track entry
        if (node->getName() == "track")
        {
            std::string trackID;
            int numLaps;
            bool reversed = false;

            const int idFound      = node->get("id",      &trackID  );
            const int lapFound     = node->get("laps",    &numLaps  );
            // Will stay false if not found
            node->get("reverse", &reversed );

            if (!idFound || !lapFound)
            {
                Log::error("GrandPrixData", "Error while trying to read grandprix file '%s' : "
                                "<track> tag does not have idi and laps reverse attributes. \n",
                                filename.c_str());
                delete root;
                throw std::logic_error("File contents are incomplete or corrupt");
            }

            // Make sure the track really is reversible
            Track* t = track_manager->getTrack(trackID);
            if (t != NULL && reversed)
            {
                reversed = t->reverseAvailable();
            }

            m_tracks.push_back(trackID);
            m_laps.push_back(numLaps);
            m_reversed.push_back(reversed);

            assert(m_tracks.size() == m_laps.size()    );
            assert(m_laps.size()   == m_reversed.size());
        }
        else
        {
            std::cerr << "Unknown node in Grand Prix XML file : " << node->getName().c_str() << std::endl;
            delete root;
            throw std::runtime_error("Unknown node in sfx XML file");
        }
    }// nend for

    delete root;

    // sanity checks
    if  (!foundName)
    {
        Log::error("GrandPrixData", "Error while trying to read grandprix file '%s' : "
                "missing 'name' attribute\n", filename.c_str());
        throw std::logic_error("File contents are incomplete or corrupt");
    }

}
예제 #19
0
파일: legacy.cpp 프로젝트: draekko/hydrogen
Drumkit* Legacy::load_drumkit( const QString& dk_path ) {
	if ( version_older_than( 0, 9, 8 ) ) {
		ERRORLOG( QString( "this code should not be used anymore, it belongs to 0.9.6" ) );
	} else {
		ERRORLOG( QString( "loading drumkit with legacy code" ) );
	}
	XMLDoc doc;
	if( !doc.read( dk_path ) ) {
		return 0;
	}
	XMLNode root = doc.firstChildElement( "drumkit_info" );
	if ( root.isNull() ) {
		ERRORLOG( "drumkit_info node not found" );
		return 0;
	}
	QString drumkit_name = root.read_string( "name", "", false, false );
	if ( drumkit_name.isEmpty() ) {
		ERRORLOG( "Drumkit has no name, abort" );
		return 0;
	}
	Drumkit* drumkit = new Drumkit();
	drumkit->set_path( dk_path.left( dk_path.lastIndexOf( "/" ) ) );
	drumkit->set_name( drumkit_name );
	drumkit->set_author( root.read_string( "author", "undefined author" ) );
	drumkit->set_info( root.read_string( "info", "defaultInfo" ) );
	drumkit->set_license( root.read_string( "license", "undefined license" ) );
	XMLNode instruments_node = root.firstChildElement( "instrumentList" );
	if ( instruments_node.isNull() ) {
		WARNINGLOG( "instrumentList node not found" );
		drumkit->set_instruments( new InstrumentList() );
	} else {
		InstrumentList* instruments = new InstrumentList();
		XMLNode instrument_node = instruments_node.firstChildElement( "instrument" );
		int count = 0;
		while ( !instrument_node.isNull() ) {
			count++;
			if ( count > MAX_INSTRUMENTS ) {
				ERRORLOG( QString( "instrument count >= %2, stop reading instruments" ).arg( MAX_INSTRUMENTS ) );
				break;
			}
			Instrument* instrument = 0;
			int id = instrument_node.read_int( "id", EMPTY_INSTR_ID, false, false );
			if ( id!=EMPTY_INSTR_ID ) {
				instrument = new Instrument( id, instrument_node.read_string( "name", "" ), 0 );
				instrument->set_drumkit_name( drumkit_name );
				instrument->set_volume( instrument_node.read_float( "volume", 1.0f ) );
				instrument->set_muted( instrument_node.read_bool( "isMuted", false ) );
				instrument->set_pan_l( instrument_node.read_float( "pan_L", 1.0f ) );
				instrument->set_pan_r( instrument_node.read_float( "pan_R", 1.0f ) );
				// may not exist, but can't be empty
				instrument->set_filter_active( instrument_node.read_bool( "filterActive", true, false ) );
				instrument->set_filter_cutoff( instrument_node.read_float( "filterCutoff", 1.0f, true, false ) );
				instrument->set_filter_resonance( instrument_node.read_float( "filterResonance", 0.0f, true, false ) );
				instrument->set_random_pitch_factor( instrument_node.read_float( "randomPitchFactor", 0.0f, true, false ) );
				float attack = instrument_node.read_float( "Attack", 0.0f, true, false );
				float decay = instrument_node.read_float( "Decay", 0.0f, true, false  );
				float sustain = instrument_node.read_float( "Sustain", 1.0f, true, false );
				float release = instrument_node.read_float( "Release", 1000.0f, true, false );
				instrument->set_adsr( new ADSR( attack, decay, sustain, release ) );
				instrument->set_gain( instrument_node.read_float( "gain", 1.0f, true, false ) );
				instrument->set_mute_group( instrument_node.read_int( "muteGroup", -1, true, false ) );
				instrument->set_midi_out_channel( instrument_node.read_int( "midiOutChannel", -1, true, false ) );
				instrument->set_midi_out_note( instrument_node.read_int( "midiOutNote", MIDI_MIDDLE_C, true, false ) );
				instrument->set_stop_notes( instrument_node.read_bool( "isStopNote", true ,false ) );
				instrument->set_hihat_grp( instrument_node.read_int( "isHihat", -1, true ) );
				instrument->set_lower_cc( instrument_node.read_int( "lower_cc", 0, true ) );
				instrument->set_higher_cc( instrument_node.read_int( "higher_cc", 127, true ) );
				for ( int i=0; i<MAX_FX; i++ ) {
					instrument->set_fx_level( instrument_node.read_float( QString( "FX%1Level" ).arg( i+1 ), 0.0 ), i );
				}
				QDomNode filename_node = instrument_node.firstChildElement( "filename" );
				if ( !filename_node.isNull() ) {
					DEBUGLOG( "Using back compatibility code. filename node found" );
					QString sFilename = instrument_node.read_string( "filename", "" );
					if( sFilename.isEmpty() ) {
						ERRORLOG( "filename back compability node is empty" );
					} else {

						Sample* sample = new Sample( dk_path+"/"+sFilename );

						bool p_foundMainCompo = false;
						for (std::vector<DrumkitComponent*>::iterator it = drumkit->get_components()->begin() ; it != drumkit->get_components()->end(); ++it) {
                            DrumkitComponent* existing_compo = *it;
                            if( existing_compo->get_name().compare("Main") == 0) {
                                p_foundMainCompo = true;
                                break;
                            }
                        }

						if ( !p_foundMainCompo ) {
                            DrumkitComponent* dmCompo = new DrumkitComponent( 0, "Main" );
                            drumkit->get_components()->push_back(dmCompo);
                        }

                        InstrumentComponent* component = new InstrumentComponent( 0 );
                        InstrumentLayer* layer = new InstrumentLayer( sample );
						component->set_layer( layer, 0 );
						instrument->get_components()->push_back( component );

					}
				} else {
					int n = 0;
					bool p_foundMainCompo = false;
                    for (std::vector<DrumkitComponent*>::iterator it = drumkit->get_components()->begin() ; it != drumkit->get_components()->end(); ++it) {
                        DrumkitComponent* existing_compo = *it;
                        if( existing_compo->get_name().compare("Main") == 0) {
                            p_foundMainCompo = true;
                            break;
                        }
                    }

                    if ( !p_foundMainCompo ) {
                        DrumkitComponent* dmCompo = new DrumkitComponent( 0, "Main" );
                        drumkit->get_components()->push_back(dmCompo);
                    }
					InstrumentComponent* component = new InstrumentComponent( 0 );

					XMLNode layer_node = instrument_node.firstChildElement( "layer" );
					while ( !layer_node.isNull() ) {
						if ( n >= MAX_LAYERS ) {
							ERRORLOG( QString( "n >= MAX_LAYERS (%1)" ).arg( MAX_LAYERS ) );
							break;
						}
						Sample* sample = new Sample( dk_path+"/"+layer_node.read_string( "filename", "" ) );
						InstrumentLayer* layer = new InstrumentLayer( sample );
						layer->set_start_velocity( layer_node.read_float( "min", 0.0 ) );
						layer->set_end_velocity( layer_node.read_float( "max", 1.0 ) );
						layer->set_gain( layer_node.read_float( "gain", 1.0, true, false ) );
						layer->set_pitch( layer_node.read_float( "pitch", 0.0, true, false ) );
						component->set_layer( layer, n );
						n++;
						layer_node = layer_node.nextSiblingElement( "layer" );
					}
					instrument->get_components()->push_back( component );
				}
			}
			if( instrument ) {
				( *instruments ) << instrument;
			} else {
				ERRORLOG( QString( "Empty ID for instrument %1. The drumkit is corrupted. Skipping instrument" ).arg( count ) );
				count--;
			}
			instrument_node = instrument_node.nextSiblingElement( "instrument" );
		}
		drumkit->set_instruments( instruments );
	}
	return drumkit;
}
예제 #20
0
/** Loads the static mesh.
 */
void Referee::init()
{
    assert(!m_st_referee_mesh);
    const std::string filename=file_manager->getAssetChecked(FileManager::MODEL,
                               "referee.xml", true);
    XMLNode *node = file_manager->createXMLTree(filename);
    if(!node)
    {
        Log::fatal("referee", "Can't read XML file referee.xml, aborting.");
    }
    if(node->getName()!="referee")
    {
        Log::fatal("referee", "The file referee.xml does not contain a referee"
                   "node, aborting.");
    }
    std::string model_filename;
    node->get("model", &model_filename);

    m_st_referee_mesh = irr_driver->getAnimatedMesh(
                            file_manager->getAsset(FileManager::MODEL,
                                    model_filename)      );
    if(!m_st_referee_mesh)
    {
        Log::fatal("referee", "Can't find referee model '%s', aborting.",
                   model_filename.c_str());
    }

    // Translate the mesh so that the x/z middle point
    // and for y the lowest point are at 0,0,0:
    Vec3 min,max;
    MeshTools::minMax3D(m_st_referee_mesh, &min, &max);
    Vec3 offset_from_center = -0.5f*(max+min);
    offset_from_center.setY(0);
    scene::IMeshManipulator *mani =
        irr_driver->getVideoDriver()->getMeshManipulator();

    core::matrix4 translate(core::matrix4::EM4CONST_IDENTITY);
    translate.setTranslation(offset_from_center.toIrrVector());
    mani->transform(m_st_referee_mesh, translate);
    node->get("first-rescue-frame", &m_st_first_rescue_frame);
    node->get("last-rescue-frame",  &m_st_last_rescue_frame );
    node->get("first-start-frame",  &m_st_first_start_frame );
    node->get("last-start-frame",   &m_st_last_start_frame  );
    node->get("start-offset",       &m_st_start_offset      );
    node->get("scale",              &m_st_scale             );
    node->get("start-rotation",     &m_st_start_rotation    );

    float angle_to_kart = atan2(m_st_start_offset.getX(),
                                m_st_start_offset.getZ())
                          * RAD_TO_DEGREE;
    m_st_start_rotation.setY(m_st_start_rotation.getY()+angle_to_kart);

    for(unsigned int i=0; i<m_st_referee_mesh->getMeshBufferCount(); i++)
    {
        scene::IMeshBuffer *mb = m_st_referee_mesh->getMeshBuffer(i);
        video::SMaterial &irrMaterial = mb->getMaterial();
        video::ITexture* t=irrMaterial.getTexture(0);
        if(!t) continue;

        std::string name=StringUtils::getBasename(t->getName()
                         .getInternalName().c_str());
        if (name == "traffic_light.png")
        {
            m_st_traffic_buffer = i;
            break;
        }
        else
        {
            irrMaterial.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
        }

    }

    delete node;
}   // init
예제 #21
0
rw_yang_netconf_op_status_t XMLDocMerger::do_delete(
                YangNode* child_ynode,
                XMLNode* new_node,
                XMLNode* new_child,
                XMLNode* delta_child)
{
  rw_yang_netconf_op_status_t status = RW_YANG_NETCONF_OP_STATUS_OK;
  
  // The deletion of last case node should add default-case default-values
  // This is taken care by fill_defaults()

  XMLNode* remove_node = new_child;
  xml_data_presence_t data_presence = check_if_data_exists(child_ynode,
                                              new_node, delta_child, &remove_node);
  switch(data_presence) {
    case XML_DATA_MISSING: {
      if (current_operation_ == XML_EDIT_OP_DELETE) {
        std::string const error_msg = "Node ("
                                      + new_node->get_local_name()
                                      + ") has missing data";
        report_error(delta_child, RW_YANG_NETCONF_OP_STATUS_DATA_MISSING, error_msg.c_str());
        return RW_YANG_NETCONF_OP_STATUS_DATA_MISSING;
      }
      return status;
    }
    case XML_DATA_EXISTS: {
      // If a leaf node has default value and is deleted, then don't report it,
      // just delete the node, the default value will added when fill_defaults
      // is invoked.
      if (child_ynode->get_default_value() == nullptr) {
        // Neither a leaf nor a leaf with default value
        report_delete(remove_node);
      } else {
        // has default value, if it is part of a case and is the last node, and
        // is not part of the default case then report deletion
        YangNode* ycase = child_ynode->get_case();
        YangNode* ychoice = child_ynode->get_choice();
        if (ychoice && ycase != ychoice->get_default_case()) {
          bool found = false;
          // Iterate thru the subtree to find if any node in the existing case
          // exists. If so, don't report
          for (XMLNodeIter it = new_node->child_begin();
               it != new_node->child_end(); ++it) {
            XMLNode* xnode = &(*it);
            if (xnode != remove_node && 
                xnode->get_yang_node()->get_case() == ycase) {
              found = true;
            }
          }
          if (!found) {
            report_delete(remove_node);
          }
        }
      }
      new_node->remove_child(remove_node);
      break;
    }
    case XML_DATA_LIST_EXISTS: {
      // remove all the data with the list name
      for (XMLNode* xchild = new_node->get_first_child(); xchild; ) {
        if (xchild->get_local_name() == child_ynode->get_name() &&
            xchild->get_name_space() == child_ynode->get_ns()) {
          XMLNode* next_node = xchild->get_next_sibling();

          // Multiple keyspecs, report the deletion and remove it from dom
          report_delete(xchild);
          new_node->remove_child(xchild);
          xchild = next_node;
        } else {
          xchild = xchild->get_next_sibling();
        }
      }
      break;
    }
  }

  return status;
}
예제 #22
0
  bool UNICOREClient::sstat(std::string& status) {

    std::string state, faultstring;
    logger.msg(INFO, "Creating and sending a service status request");

    PayloadSOAP req(unicore_ns);
    XMLNode jobref =
      req.NewChild("bes-factory:GetFactoryAttributesDocument");
    set_bes_factory_action(req, "GetFactoryAttributesDocument");
    WSAHeader(req).To(rurl.str());

    // Send status request
    PayloadSOAP *resp = NULL;
    if (client) {
      MCC_Status status =
        client->process("http://schemas.ggf.org/bes/2006/08/bes-factory/"
                        "BESFactoryPortType/GetFactoryAttributesDocument",
                        &req, &resp);
      if (resp == NULL) {
        logger.msg(VERBOSE, "There was no SOAP response");
        return false;
      }
    }
    else if (client_entry) {
      Message reqmsg;
      Message repmsg;
      MessageAttributes attributes_req;
      attributes_req.set("SOAP:ACTION", "http://schemas.ggf.org/bes/2006/08/"
                         "bes-factory/BESFactoryPortType/"
                         "GetFactoryAttributesDocument");
      MessageAttributes attributes_rep;
      MessageContext context;
      reqmsg.Payload(&req);
      reqmsg.Attributes(&attributes_req);
      reqmsg.Context(&context);
      repmsg.Attributes(&attributes_rep);
      repmsg.Context(&context);
      MCC_Status status = client_entry->process(reqmsg, repmsg);
      if (!status) {
        logger.msg(ERROR, "A service status request failed");
        return false;
      }
      logger.msg(INFO, "A service status request succeeded");
      if (repmsg.Payload() == NULL) {
        logger.msg(VERBOSE, "There was no response to a service status request");
        return false;
      }
      try {
        resp = dynamic_cast<PayloadSOAP*>(repmsg.Payload());
      } catch (std::exception&) {}
      if (resp == NULL) {
        logger.msg(ERROR, "The response of a service status request was "
                   "not a SOAP message");
        delete repmsg.Payload();
        return false;
      }
    }
    else {
      logger.msg(ERROR, "There is no connection chain configured");
      return false;
    }
    XMLNode st;
    logger.msg(DEBUG, "Response:\n%s", (std::string)(*resp));
    (*resp)["GetFactoryAttributesDocumentResponse"]
    ["FactoryResourceAttributesDocument"].New(st);
    st.GetDoc(state, true);
    delete resp;
    if (state == "") {
      logger.msg(ERROR, "The service status could not be retrieved");
      return false;
    }
    else {
      status = state;
      return true;
    }
  }
int
SBMLLevelVersionConverter::convert()
{
  SBMLNamespaces *ns = getTargetNamespaces();
  if (ns == NULL)
  {
    return LIBSBML_CONV_INVALID_TARGET_NAMESPACE;
  }
  bool hasValidNamespace = ns->isValidCombination();
  if (hasValidNamespace == false)
  {
    return LIBSBML_CONV_INVALID_TARGET_NAMESPACE;
  }
  
  if (mDocument == NULL)
  {
    return LIBSBML_OPERATION_FAILED;
  }
  bool strict = getValidityFlag();

  //bool success = mDocument->setLevelAndVersion(mTargetNamespaces->getLevel(), 
  //  mTargetNamespaces->getVersion(), false);
  /* mDocument->check we are not already the level and version */

  unsigned int currentLevel = mDocument->getLevel();
  unsigned int currentVersion = mDocument->getVersion();
  unsigned int targetLevel = getTargetLevel(); 
  unsigned int targetVersion = getTargetVersion();

  if (currentLevel == targetLevel && currentVersion == targetVersion)
  {
    return LIBSBML_OPERATION_SUCCESS;
  }

  /* since this function will write to the error log we should
   * clear anything in the log first
   */
  mDocument->getErrorLog()->clearLog();
  Model * currentModel = mDocument->getModel();

  bool conversion = false;

  bool ignorePackages = getProperties()->getBoolValue("ignorePackages");

  /* if model has extensions we cannot convert */
  if (!ignorePackages && mDocument->getNumPlugins() > 0)
  {

    // disable all unused packages
    SBMLExtensionRegistry::getInstance().disableUnusedPackages(mDocument);
    if (mDocument->getNumPlugins() > 0)
    {
      // if there are still plugins enabled fail
      mDocument->getErrorLog()->logError(PackageConversionNotSupported, 
                                         currentLevel, currentVersion);
      return LIBSBML_CONV_PKG_CONVERSION_NOT_AVAILABLE;

    }
  }


  // deal with the case where a package that libsbml does not know about
  // has been read in
  // the model is not L3V1 core ONLY and so should not be
  // converted by this function

  // TO DO - SK Comment

  //if (mDocument->mAttributesOfUnknownPkg.isEmpty())
  //{
  //  mDocument->getErrorLog()->logError(PackageConversionNotSupported, 
  //                                     currentLevel, currentVersion);
  //  return LIBSBML_CONV_PKG_CONVERSION_NOT_AVAILABLE;
  //}
  unsigned char origValidators = mDocument->getApplicableValidators();
  unsigned char convValidators = mDocument->getConversionValidators();
  /* if strict = true we will only convert a valid model
   * to a valid model with a valid internal representation
   */
  /* see whether the unit validator is on */
  //bool strictSBO   = ((convValidators & 0x04) == 0x04);
  bool strictUnits = strict && ((convValidators & UnitsCheckON) == UnitsCheckON);
  
  if (strict == true)
  {
    /* use validators that the user has selected
    */
    /* hack to catch errors caught at read time */
    char* doc = writeSBMLToString(mDocument);
    SBMLDocument *d = readSBMLFromString(doc);
    util_free(doc);
    unsigned int errors = d->getNumErrors();

    for (unsigned int i = 0; i < errors; i++)
    {
      mDocument->getErrorLog()->add(*(d->getError(i)));
    }
    delete d;

    errors += mDocument->checkConsistency();
    errors = mDocument->getErrorLog()->getNumFailsWithSeverity(LIBSBML_SEV_ERROR);

    /* if the current model is not valid dont convert 
    */
    if (errors > 0)
    {
      return LIBSBML_CONV_INVALID_SRC_DOCUMENT;
    }

    mDocument->getErrorLog()->clearLog();
  }

  unsigned int i;
  bool duplicateAnn = false;
  //look at annotation on sbml element - since validation only happens on the model :-(
  XMLNode *ann = mDocument->getAnnotation();
  if (ann != NULL)
  {
    for (i = 0; i < ann->getNumChildren(); i++)
    {
      std::string name = ann->getChild(i).getPrefix();
      for( unsigned int n= i+1; n < ann->getNumChildren(); n++)
      {
        if (ann->getChild(n).getPrefix() == name)
          duplicateAnn = true;
      }
    }
  }

  if (currentModel != NULL)
  {
    unsigned int origLevel;
    unsigned int origVersion;
    Model *origModel;
    if (strict)
    {
      /* here we are strict and only want to do
       * conversion if output will be valid
       *
       * save a copy of the model so it can be restored
       */
      origLevel = currentLevel;
      origVersion = currentVersion;
      origModel = currentModel->clone();
    }

    conversion = performConversion(strict, strictUnits, duplicateAnn);
      
    if (conversion == false)
    {
      /* if we were strict restore original model */

      if (strict)
      {
        delete origModel;
        mDocument->setApplicableValidators(origValidators);
        mDocument->updateSBMLNamespace("core", origLevel, origVersion);
      }
    }
    else
    {
      if (strict)
      {
        /* now we want to mDocument->check whether the resulting model is valid
         */
        mDocument->validateSBML();
        unsigned int errors = 
           mDocument->getErrorLog()->getNumFailsWithSeverity(LIBSBML_SEV_ERROR);
        if (errors > 0)
        { /* error - we dont covert
           * restore original values and return
           */
          conversion = false;
          /* undo any changes */
          currentModel = origModel->clone();
          mDocument->updateSBMLNamespace("core", origLevel, origVersion);
          mDocument->setApplicableValidators(origValidators);
          delete origModel;
        }
        else
        {
          delete origModel;
        }
      }
    }
  }
  else
  {
    mDocument->updateSBMLNamespace("core", targetLevel, targetVersion);
    conversion = true;
  }

  /* restore original value */
  mDocument->setApplicableValidators(origValidators); 
  

  if (conversion)
    return LIBSBML_OPERATION_SUCCESS;
  else
    return LIBSBML_OPERATION_FAILED;
}
예제 #24
0
  bool UNICOREClient::clean(const std::string& jobid) {

    std::string result, faultstring;
    logger.msg(INFO, "Creating and sending request to terminate a job");

    PayloadSOAP req(unicore_ns);
    XMLNode op = req.NewChild("a-rex:ChangeActivityStatus");
    XMLNode jobref = op.NewChild(XMLNode(jobid));
    XMLNode jobstate = op.NewChild("a-rex:NewStatus");
    jobstate.NewAttribute("bes-factory:state") = "Finished";
    jobstate.NewChild("a-rex:state") = "Deleted";
    // Send clean request
    PayloadSOAP *resp = NULL;
    if (client) {
      MCC_Status status = client->process("", &req, &resp);
      if (resp == NULL) {
        logger.msg(VERBOSE, "There was no SOAP response");
        return false;
      }
    }
    else if (client_entry) {
      Message reqmsg;
      Message repmsg;
      MessageAttributes attributes_req;
      MessageAttributes attributes_rep;
      MessageContext context;
      reqmsg.Payload(&req);
      reqmsg.Attributes(&attributes_req);
      reqmsg.Context(&context);
      repmsg.Attributes(&attributes_rep);
      repmsg.Context(&context);
      MCC_Status status = client_entry->process(reqmsg, repmsg);
      if (!status) {
        logger.msg(ERROR, "A job cleaning request failed");
        return false;
      }
      logger.msg(INFO, "A job cleaning request succeed");
      if (repmsg.Payload() == NULL) {
        logger.msg(VERBOSE, "There was no response to a job cleaning request");
        return false;
      }
      try {
        resp = dynamic_cast<PayloadSOAP*>(repmsg.Payload());
      } catch (std::exception&) {}
      if (resp == NULL) {
        logger.msg(ERROR, "The response of a job cleaning request was not "
                   "a SOAP message");
        delete repmsg.Payload();
        return false;
      }
    }
    else {
      logger.msg(ERROR, "There is no connection chain configured");
      return false;
    }

    if (!((*resp)["ChangeActivityStatusResponse"])) {
      delete resp;
      XMLNode fs;
      (*resp)["Fault"]["faultstring"].New(fs);
      faultstring = (std::string)fs;
      if (faultstring != "") {
        logger.msg(ERROR, faultstring);
        return false;
      }
      if (result != "true") {
        logger.msg(ERROR, "Job termination failed");
        return false;
      }
    }
    delete resp;
    return true;
  }
예제 #25
0
int main( int argc, const char ** argv )
{
	#if defined( _MSC_VER ) && defined( DEBUG )
		_CrtMemCheckpoint( &startMemState );
		// Enable MS Visual C++ debug heap memory leaks dump on exit
		_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	#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

	{
		TIXMLASSERT( true );
	}

	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 );
	}


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

		element->SetText("darkness.");
		XMLTest( "SetText() normal use (open/close).", "darkness.", element->GetText() );

		element->SetText("blue flame.");
		XMLTest( "SetText() replace.", "blue flame.", element->GetText() );

		str = "<foo/>";
		doc.Parse( str );
		element = doc.RootElement();

		element->SetText("The driver");
		XMLTest( "SetText() normal use. (self-closing)", "The driver", element->GetText() );

		element->SetText("<b>horses</b>");
		XMLTest( "SetText() replace with tag-like text.", "<b>horses</b>", element->GetText() );
		//doc.Print();

		str = "<foo><bar>Text in nested element</bar></foo>";
		doc.Parse( str );
		element = doc.RootElement();
		
		element->SetText("wolves");
		XMLTest( "SetText() prefix to nested non-text children.", "wolves", element->GetText() );

		str = "<foo/>";
		doc.Parse( str );
		element = doc.RootElement();
		
		element->SetText( "str" );
		XMLTest( "SetText types", "str", element->GetText() );

		element->SetText( 1 );
		XMLTest( "SetText types", "1", element->GetText() );

		element->SetText( 1U );
		XMLTest( "SetText types", "1", element->GetText() );

		element->SetText( true );
		XMLTest( "SetText types", "1", element->GetText() ); // TODO: should be 'true'?

		element->SetText( 1.5f );
		XMLTest( "SetText types", "1.5", element->GetText() );

		element->SetText( 1.5 );
		XMLTest( "SetText types", "1.5", element->GetText() );
	}


	// ---------- 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() );
	}

	{
		// Documents with all whitespaces should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		XMLDocument doc;
		doc.Parse( str );
		XMLTest( "All whitespaces 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;
        XMLTest( "Document is initially empty", doc.NoChildren(), true );
        doc.Clear();
        XMLTest( "Empty is empty after Clear()", doc.NoChildren(), true );
        doc.LoadFile( "resources/dream.xml" );
        XMLTest( "Document has something to Clear()", doc.NoChildren(), false );
        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() );
	}

	{
		// 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 );
		XMLTest( "Loading an empty file and ErrorName as string", "XML_ERROR_EMPTY_DOCUMENT", doc.ErrorName() );
		doc.PrintError();
	}

	{
        // 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);
	}

	{
		const char* xml = "<svg width = \"128\" height = \"128\">"
			"	<text> </text>"
			"</svg>";
		XMLDocument doc;
		doc.Parse(xml);
		doc.Print();
	}

	{
		// Test that it doesn't crash.
		const char* xml = "<?xml version=\"1.0\"?><root><sample><field0><1</field0><field1>2</field1></sample></root>";
		XMLDocument doc;
		doc.Parse(xml);
		doc.PrintError();
	}

#if 1
		// 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' attrC='1.0e-10' attrD='1001000000.000000' attrE='0.1234567890123456789'/>";
		const char* xml = "<element/>";
		XMLDocument doc;
		doc.Parse( xml );
		doc.FirstChildElement()->SetAttribute( "attrA-f64", 123456789.123456789 );
		doc.FirstChildElement()->SetAttribute( "attrB-f64", 1.001e9 );
		doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e9 );
		doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e20 );
		doc.FirstChildElement()->SetAttribute( "attrD-f64", 1.0e-10 );
		doc.FirstChildElement()->SetAttribute( "attrD-f64", 0.123456789 );

		doc.FirstChildElement()->SetAttribute( "attrA-f32", 123456789.123456789f );
		doc.FirstChildElement()->SetAttribute( "attrB-f32", 1.001e9f );
		doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e9f );
		doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e20f );
		doc.FirstChildElement()->SetAttribute( "attrD-f32", 1.0e-10f );
		doc.FirstChildElement()->SetAttribute( "attrD-f32", 0.123456789f );

		doc.Print();

		/* The result of this test is platform, compiler, and library version dependent. :("
		XMLPrinter printer;
		doc.Print( &printer );
		XMLTest( "Float and double formatting.", 
			"<element attrA-f64=\"123456789.12345679\" attrB-f64=\"1001000000\" attrC-f64=\"1e+20\" attrD-f64=\"0.123456789\" attrA-f32=\"1.2345679e+08\" attrB-f32=\"1.001e+09\" attrC-f32=\"1e+20\" attrD-f32=\"0.12345679\"/>\n",
			printer.CStr(), 
			true );
		*/
	}
#endif
    
    {
        // Issue #184
        // If it doesn't assert, it passes. Caused by objects
        // getting created during parsing which are then
        // inaccessible in the memory pools.
        {
            XMLDocument doc;
            doc.Parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>");
        }
        {
            XMLDocument doc;
            doc.Parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>");
            doc.Clear();
        }
    }
    
    {
        // If this doesn't assert in DEBUG, all is well.
        tinyxml2::XMLDocument doc;
        tinyxml2::XMLElement *pRoot = doc.NewElement("Root");
        doc.DeleteNode(pRoot);
    }

	{
		// Should not assert in DEBUG
		XMLPrinter printer;
	}

	{
		// Issue 291. Should not crash
		const char* xml = "&#0</a>";
		XMLDocument doc;
		doc.Parse( xml );

		XMLPrinter printer;
		doc.Print( &printer );
	}
	{
		// Issue 299. Can print elements that are not linked in. 
		// Will crash if issue not fixed.
		XMLDocument doc;
		XMLElement* newElement = doc.NewElement( "printme" );
		XMLPrinter printer;
		newElement->Accept( &printer );
		// Delete the node to avoid possible memory leak report in debug output
		doc.DeleteNode( newElement );
	}
	{
		// Issue 302. Clear errors from LoadFile/SaveFile
		XMLDocument doc;
		XMLTest( "Issue 302. Should be no error initially", "XML_SUCCESS", doc.ErrorName() );
		doc.SaveFile( "./no/such/path/pretty.xml" );
		XMLTest( "Issue 302. Fail to save", "XML_ERROR_FILE_COULD_NOT_BE_OPENED", doc.ErrorName() );
		doc.SaveFile( "./resources/out/compact.xml", true );
		XMLTest( "Issue 302. Subsequent success in saving", "XML_SUCCESS", doc.ErrorName() );
	}

	{
		// If a document fails to load then subsequent
		// successful loads should clear the error
		XMLDocument doc;
		XMLTest( "Should be no error initially", false, doc.Error() );
		doc.LoadFile( "resources/no-such-file.xml" );
		XMLTest( "No such file - should fail", true, doc.Error() );

		doc.LoadFile( "resources/dream.xml" );
		XMLTest( "Error should be cleared", false, doc.Error() );
	}

	// ----------- 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 );

		_CrtMemState diffMemState;
		_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
		_CrtMemDumpStatistics( &diffMemState );
	#endif

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

	return gFail;
}
예제 #26
0
  bool UNICOREClient::submit(const JobDescription& jobdesc, XMLNode& id,
                             bool delegate) {

    std::string faultstring;

    logger.msg(INFO, "Creating and sending request");

    // Create job request
    /*
       bes-factory:CreateActivity
         bes-factory:ActivityDocument
           jsdl:JobDefinition
     */
    PayloadSOAP req(unicore_ns);
    XMLNode op = req.NewChild("bes-factory:CreateActivity");
    XMLNode act_doc = op.NewChild("bes-factory:ActivityDocument");
    set_bes_factory_action(req, "CreateActivity");
    WSAHeader(req).To(rurl.str());
    //XMLNode proxyHeader = req.Header().NewChild("u6:Proxy");
    if (true) {
      std::string pem_str;
      std::ifstream proxy_file(proxyPath.c_str()/*, ifstream::in*/);
      std::getline<char>(proxy_file, pem_str, 0);
      req.Header().NewChild("u6:Proxy") = pem_str;
      //std::cout << "\n----\n" << "pem_str = " << pem_str << "\n----\n"; //debug code, remove!
    }
    //std::string jsdl_str;
    //std::getline<char>(jsdl_file, jsdl_str, 0);
    std::string jsdl_str;
    if (!jobdesc.UnParse(jsdl_str, "nordugrid:jsdl")) {
      logger.msg(INFO, "Unable to submit job. Job description is not valid in the %s format", "nordugrid:jsdl");
      return false;
    }
    XMLNode jsdl_doc = act_doc.NewChild(XMLNode(jsdl_str));
    //std::cout << "\n----\n" << jsdl_str << "\n----\n"; //Debug line to verify the activity document
    jsdl_doc.Namespaces(unicore_ns); // Unify namespaces
    PayloadSOAP *resp = NULL;

    XMLNode ds =
      act_doc["jsdl:JobDefinition"]["jsdl:JobDescription"]["jsdl:DataStaging"];
    for (; (bool)ds; ds = ds[1]) {
      // FilesystemName - ignore
      // CreationFlag - ignore
      // DeleteOnTermination - ignore
      XMLNode source = ds["jsdl:Source"];
      XMLNode target = ds["jsdl:Target"];
      if ((bool)source) {
        std::string s_name = ds["jsdl:FileName"];
        if (!s_name.empty()) {
          XMLNode x_url = source["jsdl:URI"];
          std::string s_url = x_url;
          if (s_url.empty())
            s_url = "./" + s_name;
          else {
            URL u_url(s_url);
            if (!u_url) {
              if (s_url[0] != '/')
                s_url = "./" + s_url;
            }
            else {
              if (u_url.Protocol() == "file") {
                s_url = u_url.Path();
                if (s_url[0] != '/')
                  s_url = "./" + s_url;
              }
              else
                s_url.resize(0);
            }
          }
          if (!s_url.empty())
            x_url.Destroy();
        }
      }
    }
    act_doc.GetXML(jsdl_str);
    logger.msg(DEBUG, "Job description to be sent: %s", jsdl_str);

    // Try to figure out which credentials are used
    // TODO: Method used is unstable beacuse it assumes some predefined
    // structure of configuration file. Maybe there should be some
    // special methods of ClientTCP class introduced.
    std::string deleg_cert;
    std::string deleg_key;
    if (delegate) {
      client->Load(); // Make sure chain is ready
      XMLNode tls_cfg = find_xml_node((client->GetConfig())["Chain"],
                                      "Component", "name", "tls.client");
      if (tls_cfg) {
        deleg_cert = (std::string)(tls_cfg["ProxyPath"]);
        if (deleg_cert.empty()) {
          deleg_cert = (std::string)(tls_cfg["CertificatePath"]);
          deleg_key = (std::string)(tls_cfg["KeyPath"]);
        }
        else
          deleg_key = deleg_cert;
      }
      if (deleg_cert.empty() || deleg_key.empty()) {
        logger.msg(ERROR, "Failed to find delegation credentials in "
                   "client configuration");
        return false;
      }
    }
    // Send job request + delegation
    if (client) {
      if (delegate) {
        DelegationProviderSOAP deleg(deleg_cert, deleg_key);
        logger.msg(INFO, "Initiating delegation procedure");
        if (!deleg.DelegateCredentialsInit(*(client->GetEntry()),
                                           &(client->GetContext()))) {
          logger.msg(ERROR, "Failed to initiate delegation");
          return false;
        }
        deleg.DelegatedToken(op);
      }
      MCC_Status status =
        client->process("http://schemas.ggf.org/bes/2006/08/bes-factory/"
                        "BESFactoryPortType/CreateActivity", &req, &resp);
      if (!status) {
        logger.msg(ERROR, "Submission request failed");
        return false;
      }
      if (resp == NULL) {
        logger.msg(VERBOSE, "There was no SOAP response");
        return false;
      }
    }
    else if (client_entry) {
      Message reqmsg;
      Message repmsg;
      MessageAttributes attributes_req;
      attributes_req.set("SOAP:ACTION", "http://schemas.ggf.org/bes/2006/08/"
                         "bes-factory/BESFactoryPortType/CreateActivity");
      MessageAttributes attributes_rep;
      MessageContext context;

      if (delegate) {
        DelegationProviderSOAP deleg(deleg_cert, deleg_key);
        logger.msg(INFO, "Initiating delegation procedure");
        if (!deleg.DelegateCredentialsInit(*client_entry, &context)) {
          logger.msg(ERROR, "Failed to initiate delegation");
          return false;
        }
        deleg.DelegatedToken(op);
      }
      reqmsg.Payload(&req);
      reqmsg.Attributes(&attributes_req);
      reqmsg.Context(&context);
      repmsg.Attributes(&attributes_rep);
      repmsg.Context(&context);
      MCC_Status status = client_entry->process(reqmsg, repmsg);
      if (!status) {
        logger.msg(ERROR, "Submission request failed");
        return false;
      }
      logger.msg(INFO, "Submission request succeed");
      if (repmsg.Payload() == NULL) {
        logger.msg(VERBOSE, "There was no response to a submission request");
        return false;
      }
      try {
        resp = dynamic_cast<PayloadSOAP*>(repmsg.Payload());
      } catch (std::exception&) {}
      if (resp == NULL) {
        logger.msg(ERROR, "A response to a submission request was not "
                   "a SOAP message");
        delete repmsg.Payload();
        return false;
      }
    }
    else {
      logger.msg(ERROR, "There is no connection chain configured");
      return false;
    }
    //XMLNode id;
    SOAPFault fs(*resp);
    if (!fs) {
      (*resp)["CreateActivityResponse"]["ActivityIdentifier"].New(id);
      //id.GetDoc(jobid);
      //std::cout << "\n---\nActivityIdentifier:\n" << (std::string)((*resp)["CreateActivityResponse"]["ActivityIdentifier"]) << "\n---\n";//debug code
      delete resp;

      UNICOREClient luc((std::string)id["Address"], client_config); //local unicore client
      //std::cout << "\n---\nid element containing (?) Job Address:\n" << (std::string)id << "\n---\n";//debug code
      return luc.uasStartJob();
      //return true;
    }
    else {
      faultstring = fs.Reason();
      std::string s;
      resp->GetXML(s);
      delete resp;
      logger.msg(DEBUG, "Submission returned failure: %s", s);
      logger.msg(ERROR, "Submission failed, service returned: %s", faultstring);
      return false;
    }
  }
예제 #27
0
/** Constructor for a checkline.
 *  \param node XML node containing the parameters for this checkline.
 *  \param index Index of this check structure in the check manager.
 */
CheckLine::CheckLine(const XMLNode &node,  unsigned int index)
         : CheckStructure(node, index)
{
    m_ignore_height = false;
    // Note that when this is called the karts have not been allocated
    // in world, so we can't call world->getNumKarts()
    m_previous_sign.resize(race_manager->getNumberOfKarts());
    std::string p1_string("p1");
    std::string p2_string("p2");

    // In case of a cannon in a reverse track, we have to use the target line
    // as check line
    if(getType()==CT_CANNON && race_manager->getReverseTrack())
    {
        p1_string = "target-p1";
        p2_string = "target-p2";
    }
    core::vector2df p1, p2;
    if(node.get(p1_string, &p1)   &&
        node.get(p2_string, &p2)  &&
        node.get("min-height", &m_min_height))
    {
        m_left_point  = Vec3(p1.X, m_min_height, p1.Y);
        m_right_point = Vec3(p2.X, m_min_height, p2.Y);
    }
    else
    {
        node.get(p1_string, &m_left_point);
        p1 = core::vector2df(m_left_point.getX(), m_left_point.getZ());
        node.get(p2_string, &m_right_point);
        p2 = core::vector2df(m_right_point.getX(), m_right_point.getZ());
        m_min_height = std::min(m_left_point.getY(), m_right_point.getY());
    }
    m_line.setLine(p1, p2);
    if(UserConfigParams::m_check_debug && !ProfileWorld::isNoGraphics())
    {
#ifndef SERVER_ONLY
        m_debug_dy_dc = std::make_shared<SP::SPDynamicDrawCall>
            (scene::EPT_TRIANGLE_STRIP,
            SP::SPShaderManager::get()->getSPShader("additive"),
            material_manager->getDefaultSPMaterial("additive"));
        SP::addDynamicDrawCall(m_debug_dy_dc);
        m_debug_dy_dc->getVerticesVector().resize(4);
        auto& vertices = m_debug_dy_dc->getVerticesVector();
        vertices[0].m_position = core::vector3df(p1.X,
            m_min_height - m_under_min_height, p1.Y);
        vertices[1].m_position = core::vector3df(p2.X,
            m_min_height - m_under_min_height, p2.Y);
        vertices[2].m_position = core::vector3df(p1.X,
            m_min_height + m_over_min_height, p1.Y);
        vertices[3].m_position = core::vector3df(p2.X,
            m_min_height + m_over_min_height, p2.Y);
        for(unsigned int i = 0; i < 4; i++)
        {
            vertices[i].m_color = m_active_at_reset
                               ? video::SColor(128, 255, 0, 0)
                               : video::SColor(128, 128, 128, 128);
        }
        m_debug_dy_dc->recalculateBoundingBox();
#endif
    }
}   // CheckLine
예제 #28
0
SCENEGRAPHPLUGINEXP void dllLoadScene( const char* sceneFile )
{
	GameLog::logMessage("Setting Horde3D Configuration");
	
	XMLResults results;
	XMLNode scene = XMLNode::parseFile( sceneFile, "Configuration", &results);
	const XMLNode& engineSettings(scene.getChildNode("EngineConfig"));
	if ( !engineSettings.isEmpty() )
	{
		int maxLogLevel = atoi(engineSettings.getAttribute("maxLogLevel", "4"));
		GameLog::logMessage("MaxLogLevel: %d", maxLogLevel);
		h3dSetOption( H3DOptions::MaxLogLevel, float( maxLogLevel ) );

		int maxNumMessages = atoi(engineSettings.getAttribute("maxNumMessages", "1024"));
		GameLog::logMessage("MaxNumMessages: %d", maxNumMessages);
		h3dSetOption( H3DOptions::MaxNumMessages, float( maxNumMessages ) );

		int trilinearFiltering = atoi(engineSettings.getAttribute("trilinearFiltering", "1"));
		GameLog::logMessage("TrilinearFiltering: %d", trilinearFiltering);
		h3dSetOption( H3DOptions::TrilinearFiltering, float( trilinearFiltering ) );

		int maxAnisotropy = atoi(engineSettings.getAttribute("maxAnisotropy", "1"));
		GameLog::logMessage("MaxAnisotropy: %d", maxAnisotropy);
		h3dSetOption( H3DOptions::MaxAnisotropy, float( maxAnisotropy ) );

		bool sRGBLinearization = 
			_stricmp(engineSettings.getAttribute("sRGBLinearization", "0"), "true") == 0 ||
			_stricmp(engineSettings.getAttribute("sRGBLinearization", "0"), "1") == 0;
		GameLog::logMessage("SRGBLinearization: %s", sRGBLinearization ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::SRGBLinearization, sRGBLinearization );

		bool texCompression = 
			_stricmp(engineSettings.getAttribute("texCompression", "0"), "true") == 0 ||
			_stricmp(engineSettings.getAttribute("texCompression", "0"), "1") == 0;
		GameLog::logMessage("TexCompression: %s", texCompression ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::TexCompression, texCompression );

		bool loadTextures = 
			_stricmp(engineSettings.getAttribute("loadTextures", "1"), "1") == 0
			|| _stricmp(engineSettings.getAttribute("loadTextures", "1"), "true") == 0;
		GameLog::logMessage("LoadTextures: %s", loadTextures ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::LoadTextures, loadTextures ? 1.0f : 0.0f );

		const XMLNode& pathes(scene.getChildNode("EnginePath"));
		if (!pathes.isEmpty())
		{
			GameLog::logMessage("AnimationPath: %s", pathes.getAttribute("animationpath", "animations"));
			h3dutSetResourcePath(H3DResTypes::Animation, pathes.getAttribute("animationpath", "animations"));
		}
		const XMLNode& engineSettings(scene.getChildNode("EngineConfig"));
		if ( !engineSettings.isEmpty() )
		{				
			bool fastAnim = 
				_stricmp(engineSettings.getAttribute("fastAnimation", "false"), "true") == 0 ||
				_stricmp(engineSettings.getAttribute("fastAnimation", "0"), "1") == 0;
			GameLog::logMessage("FastAnimation: %s", fastAnim ? "enabled" : "disabled");
			h3dSetOption( H3DOptions::FastAnimation, fastAnim ? 1.0f : 0.0f );
		}

		int shadowMapSize = atoi(engineSettings.getAttribute("shadowMapSize", "1024"));					
		GameLog::logMessage("ShadowMapSize: %d", shadowMapSize);
		h3dSetOption( H3DOptions::ShadowMapSize, float( shadowMapSize) );

		int sampleCount = atoi(engineSettings.getAttribute("sampleCount", "0"));					
		GameLog::logMessage("SampleCount: %d", sampleCount);
		h3dSetOption( H3DOptions::SampleCount, float( sampleCount) );

		bool wireframeMode = 
			_stricmp(engineSettings.getAttribute("wireframeMode", "0"), "1") == 0 ||
			_stricmp(engineSettings.getAttribute("wireframeMode", "0"), "true") == 0;
		GameLog::logMessage("WireframeMode: %s", wireframeMode ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::WireframeMode, wireframeMode );

		bool debugViewMode = 
			_stricmp(engineSettings.getAttribute("debugViewMode", "0"), "1") == 0 ||
			_stricmp(engineSettings.getAttribute("debugViewMode", "0"), "true") == 0;
		GameLog::logMessage("DebugViewMode: %s", debugViewMode ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::DebugViewMode, debugViewMode );

		bool dumpFailedShaders = 
			_stricmp(engineSettings.getAttribute("dumpFailedShaders", "0"), "1") == 0 ||
			_stricmp(engineSettings.getAttribute("dumpFailedShaders", "0"), "true") == 0;
		GameLog::logMessage("DumpFailedShaders: %s", dumpFailedShaders ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::DumpFailedShaders, dumpFailedShaders );

		bool gatherTimeStats = 
			_stricmp(engineSettings.getAttribute("gatherTimeStats", "1"), "1") == 0 ||
			_stricmp(engineSettings.getAttribute("gatherTimeStats", "1"), "true") == 0;
		GameLog::logMessage("GatherTimeStats: %s", gatherTimeStats ? "enabled" : "disabled");
		h3dSetOption( H3DOptions::GatherTimeStats, gatherTimeStats );

	}

	const XMLNode& stereoSettings(scene.getChildNode("StereoscopyConfig"));
	if ( !stereoSettings.isEmpty() )
	{
		const char* modeC = stereoSettings.getAttribute("mode", "0");
		unsigned int mode = 0;
		if (_stricmp(modeC, "0") == 0 || _stricmp(modeC, "disabled") == 0)
			mode = 0;
		else if (_stricmp(modeC, "1") == 0 || _stricmp(modeC, "sideBySide") == 0)
			mode = 1;
		else if (_stricmp(modeC, "2") == 0 || _stricmp(modeC, "quadBuffering") == 0)
			mode = 2;
		SceneGraphManager::instance()->setStereoscopyMode(mode);

		const char* methodC = stereoSettings.getAttribute("method", "0");
		unsigned int method = 0;
		if (_stricmp(methodC, "0") == 0 || _stricmp(methodC, "toedIn") == 0)
			method = 0;
		else if (_stricmp(methodC, "1") == 0 || _stricmp(methodC, "asymmetricFrustum") == 0)
			method = 1;
		SceneGraphManager::instance()->setStereoscopyMethod(method);

		SceneGraphManager::instance()->setStereoscopyParams((float)atof(stereoSettings.getAttribute("eyeOffset", "0.05")),
			(float)atof(stereoSettings.getAttribute("strabismus", "2.5")), (float)atof(stereoSettings.getAttribute("focalLength", "1")));

		const char* stereoPipeline = stereoSettings.getAttribute("renderPipeline");
		if (stereoPipeline)
		{
			int resID = h3dAddResource( H3DResTypes::Pipeline, stereoPipeline, 0 );
			h3dutLoadResourcesFromDisk( "." );
			if (resID > 0)
				SceneGraphManager::instance()->setStereoPipelineResource(resID);
		}
		const char* stereoOverlayMaterial = stereoSettings.getAttribute("overlayMaterial");
		if (stereoOverlayMaterial)
		{
			int materialId = h3dAddResource( H3DResTypes::Material, stereoOverlayMaterial, 0 );
			h3dutLoadResourcesFromDisk( "." );
			if (materialId > 0)
				SceneGraphManager::instance()->setStereoOverlayMaterial(materialId);
		}
	}

	// Loading scene graph
	const XMLNode& sceneGraph(scene.getChildNode("SceneGraph"));
	if ( sceneGraph.isEmpty() )
		GameLog::errorMessage("No Scene Graph Node found!");
	else
	{
		GameLog::logMessage("Loading SceneGraph %s", sceneGraph.getAttribute("path"));
		// Environment
		H3DRes sceneGraphID = h3dAddResource( H3DResTypes::SceneGraph, sceneGraph.getAttribute("path"), 0 );
		GameLog::logMessage("Loading Resources...");
		// Load resources
		h3dutLoadResourcesFromDisk( "." );
		GameLog::logMessage("Adding scene graph to root node");
		// Add scene nodes	
		H3DNode newSceneID = h3dAddNodes( H3DRootNode, sceneGraphID);
		SceneGraphManager::instance()->addNewHordeNode( newSceneID );
	}
	// Use the specified render cam
	if (scene.getChildNode("ActiveCamera").getAttribute("name") && h3dFindNodes( H3DRootNode, scene.getChildNode("ActiveCamera").getAttribute("name"), H3DNodeTypes::Camera ) > 0)
		SceneGraphManager::instance()->setActiveCam( h3dGetNodeFindResult(0) );

}
예제 #29
0
void iLedlif::loadDevices(std::string configPath) {

    const char * filename = configPath.c_str();
    //XMLResults * pResults;

    // this opens and parse the XML file:
    XMLNode xMainNode = XMLNode::openFileHelper(filename, "iLedlif");
    XMLNode xDevicesNode = xMainNode.getChildNode("Devices");

    //Error handling to make sure devices listed in config file
    if (xDevicesNode.isEmpty()) {
        std::cout << "No Devices in configuration file.";
        //throw some error
    }

    //Parse each device in configuration file
    for (int i = 0; i < xDevicesNode.nChildNode("Device"); i++) {
        xmlParseDevice(xDevicesNode.getChildNode("Device", i));
    }

    //Parse messages in configuration file
    XMLNode xMessagesNode = xMainNode.getChildNode("Messages");
    if (!xMessagesNode.isEmpty()) {
        for (int i = 0; i < xMessagesNode.nChildNode("Message"); i++) {
            xmlParseMsg(xMessagesNode.getChildNode("Message", i));
        }
    }

    std::cout << "iLedlif: Done loading devices." << std::endl;
}
예제 #30
0
void VisusMetricData::localXMLVariables(XMLNode& parent) const
{
  parent.addAttribute("unit", mUnit);
  mMatrix.toXML(parent);
}