Exemple #1
0
BodyPart * MDLReader::processBodyPart(std::istream * str, int offset)
{
    int              i;
    MDLBodyPart *    part;
    BodyPart *       partNode;
    Model *          modelNode;

    // Seek to the body part
    str->seekg(offset);

    // Read it
    part = new MDLBodyPart;
    str->read((char *) part, sizeof(MDLBodyPart));

    // Create the body part node
    partNode = new BodyPart(part);

    // Process the models
    for (i = 0; i < part->num_models; i++)
    {
        // Process the model
        modelNode = processModel(str, offset + part->model_offset +
                                      (i * sizeof(MDLModel)));

        // Add the model to the body part
        partNode->addModel(modelNode);
    }

    // Return the new node
    return partNode;
}
Exemple #2
0
void Body::makeDownstreamPartList(string part_uuid, std::vector<string>* child_list)
{
	boost::shared_ptr<Part> part = getPartByUUID(part_uuid);
	if (part == nullptr)
	{
		return;
	}

	//Part is an Organ: Add all connected organs to the list
	if (part->getType() == TYPE_ORGAN){
		Organ* o = static_cast<Organ*>(part.get());
		for (auto it = o->getConnectedOrgansRW()->begin(); it != o->getConnectedOrgansRW()->end(); it++)
		{
			child_list->push_back(*it);
			makeDownstreamPartList(*it, child_list);
		}
	}

	//Part is a BodyPart: Add all children to the list and call this function on them
	if (part->getType() == TYPE_BODYPART)
	{
		BodyPart* bp = static_cast<BodyPart*>(part.get());
		for (auto it = bp->getChildListRW()->begin(); it != bp->getChildListRW()->end(); it++)
		{
			child_list->push_back(*it);
			makeDownstreamPartList(*it, child_list);
		}
	}
}
Exemple #3
0
int MailMessage::parseBodyParts(StringBuffer &rfcBody) {

    BodyPart part;
    // The boundary is the one defined in the headers preceded by
    // a newline and two hypens
    StringBuffer bound("\n--");
    bound += boundary;

    LOG.debug("parseBodyParts START");

    size_t nextBoundary = rfcBody.find(bound);
    getBodyPart(rfcBody, bound, body, nextBoundary, false);

    if (contentType.ifind("multipart/alternative") == StringBuffer::npos) {
        // If it's not multipart/alternative, get the other parts
        while( getBodyPart(rfcBody, bound, part, nextBoundary, true) ) {
            // some problem in the attachment?
            if( part.getContent() ) {
                attachments.add(part);
            }
            else LOG.error("Empty content in attachment.");
            part = BodyPart();
        }
    }

    LOG.debug("parseBodyParts END");
    return 0;
}
Exemple #4
0
	BodyPart *BodyParts::getNextWeaponPart(bool &looped)
	{
		int len = static_cast<int>(mPartList.size());
		int startIndex = mAttackIndex;
		looped = false;
		if (startIndex < 0 || startIndex >= len)
		{
			startIndex = len - 1;
		}
		mAttackIndex++;
		if (mAttackIndex >= len)
		{
			mAttackIndex = 0;
		}

		BodyPart *result = nullptr;
		while (mAttackIndex != startIndex)
		{
			BodyPart *part = mPartList[mAttackIndex];
			// Has to be a weapon part and not currently holding something else.
			if (part->isWeaponPart() && !part->isHoldingOnto())
			{
				result = part;
				break;
			}
			mAttackIndex++;
			if (mAttackIndex >= len)
			{
				mAttackIndex = 0;
				looped = true;
			}
		}
		return result;
	}
Exemple #5
0
void Body::buildPartList(std::vector<GuiObjectLink*>* list, Part* p, int depth)
{
	//debug_print("Depth: %i, Part: %s \n", depth, p->getId());
	if (p->getType() == PartType::TYPE_ORGAN)
	{
		//Append to end of list "gui_list_indent_char [times depth] ORGAN_NAME"
		std::string str = "";

		for (int i = 0; i <= depth; i++)
		{
			str.append(gui_list_indent_char);
		}

		str.append(p->getName());

		list->push_back(
			new GuiObjectLink(
			p->getUUID(),
			new ColoredText(str, part_gui_list_color_organ)
			)
			);

		return;
	}
	if (p->getType() == PartType::TYPE_BODYPART)
	{
		//Append to end of list "gui_list_indent_char [times depth] BODYPART_NAME"
		BodyPart *bp = (BodyPart*)p;
		std::string str = "";

		for (int i = 0; i <= depth; i++)
		{
			str.append(gui_list_indent_char);
		}

		str.append(bp->getName());

		list->push_back(
			new GuiObjectLink(
			bp->getUUID(),
			new ColoredText(str, part_gui_list_color_bodypart)
			)
			);

		//Call this function on all children of the BodyPart
		for (auto it = bp->getChildListRW()->begin(); it != bp->getChildListRW()->end(); it++)
		{
			boost::shared_ptr<Part> part = getPartByUUID(*it);
			if (part == nullptr) { continue; }
			buildPartList(list, part.get(), depth + 1);
		}

		bp = nullptr;

		return;
	}

	debug_error("ERROR: Tried to call recursive part list building function on invalid Part* (neither TYPE_BODYPART nor TYPE_ORGAN)!\n");
	return;
}
Exemple #6
0
	base::ReturnCode BodyParts::getLinkedParts(BodyPart *linkedTo, PartList &result) const
	{
		if (!linkedTo)
		{
			return base::NULL_PARAMETER;
		}
		if (!hasBodyPart(linkedTo))
		{
			return base::BODY_PART_NOT_FOUND;
		}

		for (size_t i = 0; i < mPartList.size(); i++)
		{
			BodyPart *part = mPartList[i];
			if (part == linkedTo)
			{
				continue;
			}
			if (part->getCanHoldOnto() == linkedTo)
			{
				result.push_back(part);
			}
		}
		return base::SUCCESS;
	}
Exemple #7
0
	//
	//	add a number of parts
	//
	void Serpent::addParts(int numParts )
	{
		int partsToAdd = numParts;
		if( partsToAdd <= 0 )
		{
			return;
		}

		//	se adauga parti pana la limita maxima

		if( getLength() + numParts > maxlength )
		{
			partsToAdd = maxlength - getLength();
		}

		for( int i=0; i<partsToAdd; i++ )
		{
			BodyPart * myBodyPart = new BodyPart();
			myBodyPart->setSize( spawnBodyPartSize );
			System::Diagnostics::Trace::WriteLine("Adding bodypart; size=" + spawnBodyPartSize.x + "," + spawnBodyPartSize.y );

			bodyParts.add( myBodyPart );

			this->onAddedBodyPart();
		}
	}
Exemple #8
0
	Item *BodyParts::getItemOnPart(const char *partName) const
	{
		BodyPart *part = getBodyPart(partName);
		if (part)
		{
			return part->getEquippedItem();
		}
		return nullptr;
	}
Exemple #9
0
    void Creature::loadConnectionTransform(const BodyPart& body, const Constraint& constraint, btTransform & trans) {
        if (body.getId() == constraint.getIdBodyA()) {
            Constraint::locateConnectionOrigin(body, constraint.getConnectionA(), trans);
        } else {

            assert(body.getId() == constraint.getIdBodyB());
            Constraint::locateConnectionOrigin(body, constraint.getConnectionB(), trans);
        }
        trans = body.getRigidBody()->getCenterOfMassTransform() * trans;
    }
Exemple #10
0
std::string evalute::evalute_BodyPart(Watch* watch)
{
    std::string name = watch->MemberName;
    std::string result = "";
    BodyPart* part = boost::get<BodyPart*>(watch->Object);

    if( name == "MaxKindleLevel") result = FloatToStr(part->getMaxKindleLevel());
    else if( name == "MaxDampness") result = FloatToStr(part->getMaxDampness());
    else if( name == "AcceptsCord") result = BoolToStr(part->getAcceptsCord());
    else if( name == "Name") result = part->getName();

    if(result == "") result = "Can't evalute";
    return result;
}
    void MainWindow::showBodyDetails( const Creature& creature, const BodyPart& body ) {
        getUiInspector().lst_body_details->addItem(QString(
                body.getName().c_str()));
        getUiInspector().lst_body_details->addItem(QString(
                ("  Mass: " + TO_STRING(body.getMass())).c_str()));
        getUiInspector().lst_body_details->addItem(QString(
                ("  Torque: " + TO_STRING(body.getMaxTorque())).c_str()));
        getUiInspector().lst_body_details->addItem(QString(
                std::string("  Size").c_str()));
        getUiInspector().lst_body_details->addItem(QString(
                ("  [x]: " + TO_STRING(body.getSizeX())).c_str()));
        getUiInspector().lst_body_details->addItem(QString(
                ("  [y]: " + TO_STRING(body.getSizeY())).c_str()));
        getUiInspector().lst_body_details->addItem(QString(
                ("  [z]: " + TO_STRING(body.getSizeZ())).c_str()));
        //Angles

        BodyPart* parent = body.getParentId() == Creature::B_NONE
                ? NULL : &creature.getBodyPart(body.getParentId());
        if (parent) {
            getUiInspector().lst_body_details->addItem(QString(
                    ("  Parent: " + parent->getName()).c_str()));
            //            getUiInspector().lst_body_details->addItem(QString(std::string("  Angles:").c_str()));
            //            getUiInspector().lst_body_details->addItem(QString(
            //                    ("   XY:" + TO_STRING(
            //                    MathUtil::getAngle(MathUtil::XY,
            //                    parent->getRigidBody()->getCenterOfMassPosition(),
            //                    body.getRigidBody()->getCenterOfMassPosition()))).c_str()));
            //            getUiInspector().lst_body_details->addItem(QString(
            //                    ("   YZ:" + TO_STRING(
            //                    MathUtil::getAngle(MathUtil::YZ,
            //                    parent->getRigidBody()->getCenterOfMassPosition(),
            //                    body.getRigidBody()->getCenterOfMassPosition()))).c_str()));
            //            getUiInspector().lst_body_details->addItem(QString(
            //                    ("   ZX:" + TO_STRING(
            //                    MathUtil::getAngle(MathUtil::ZX,
            //                    parent->getRigidBody()->getCenterOfMassPosition(),
            //                    body.getRigidBody()->getCenterOfMassPosition()))).c_str()));
        }
    }
Exemple #12
0
/**
 * Get the next bodypart from the message body string.
 *
 * @param rfcBody  (in)  - message content
 * @param boundary (in)  - mime boundary string
 * @param ret      (out) - parsed BodyPart
 * @param next     (i/o) - offset of the new boundary
 * @param isAttach (in)  - says if the current body part is an attachment or not
 */
static bool getBodyPart(StringBuffer &rfcBody, StringBuffer &boundary,
                       BodyPart &ret, size_t &next, bool isAttach)
{
    LOG.debug("getBodyPart START");
    StringBuffer newline;

    // The part starts on the next line
    size_t begin = findNewLine(rfcBody, next);
    if (begin == StringBuffer::npos)
       return false;
    // find the end of the part
    next = rfcBody.find(boundary, begin);
    if (next == StringBuffer::npos)
       return false;
    // get the part
    StringBuffer part = rfcBody.substr(begin, next-begin);
    // If it is a multipart alternative part, get the text part only.
    // check only until the first new line not on all the message (it could be
    // a message inside another message)
    size_t headers_len = getHeadersLen(part, newline);
    StringBuffer headers_part = part.substr(0, headers_len);
    if (headers_part.ifind("Content-Type: multipart/alternative") != StringBuffer::npos) {
        if(part.ifind("Content-Type: multipart/alternative") != StringBuffer::npos) {
            size_t b_pos = part.ifind("boundary=");
            if( b_pos != StringBuffer::npos ) {
                size_t begin = part.find("=\"", b_pos) + 2 ;
                size_t end = part.find("\"", begin) ;

                StringBuffer inner_boundary("\n--");
                inner_boundary += part.substr( begin, end-begin );

                begin = part.find(inner_boundary, end);
                begin += inner_boundary.length();
                end = part.find(inner_boundary, begin);
                if (begin != StringBuffer::npos && end != StringBuffer::npos) {
                    part = part.substr(begin, end-begin);
                    LOG.debug("Bodypart is multipart/alternative: "
                        "getting first alternative only: \n%s\n", part.c_str() );
                }
            }
        }
    }

    // Split headers and body
    size_t hdrlen = getHeadersLen(part, newline);

    // Get headers
    StringBuffer headers = part.substr(0, hdrlen);

    // Join header parts using \t or 8 blank
    StringBuffer joinlinetab("\t");
    headers.replaceAll(joinlinetab, " ");
    StringBuffer joinlinespaces(newline);
    joinlinespaces+=" ";  // 8 blanks
    headers.replaceAll(joinlinespaces, " ");

    ArrayList lines;
    const StringBuffer *line;

    // parse the bodypart headers
    headers.split(lines, newline);

    for ( line=(StringBuffer *)lines.front();
          line;
          line=(StringBuffer *)lines.next() ) {
        if( *line == "\r" )
            continue;
        // The first empty line marks the end of the header section
        //if( line->empty() ){
        //    break;
        //}
        // Process the headers
        if( line->ifind(MIMETYPE) == 0 ) {  // it must at the beginning
            ret.setMimeType(getTokenValue(line, MIMETYPE));
            if (line->ifind(CT_NAME) != StringBuffer::npos) {
                ret.setName(MailMessage::decodeHeader(getTokenValue(line, CT_NAME,false)));
            }
            if (line->ifind(CT_CHARSET) != StringBuffer::npos ) {
                ret.setCharset(getTokenValue(line, CT_CHARSET));
            }
        }   
        else if( line->ifind(DISPOSITION) == 0 ) {
            ret.setDisposition( getTokenValue(line, DISPOSITION));
            if (line->ifind(CD_FILENAME) != StringBuffer::npos ) {
                ret.setFilename( MailMessage::decodeHeader(  getTokenValue(line, CD_FILENAME, false) ) );
            }
        }

        else if( line->ifind(ENCODING) == 0 ) {
            ret.setEncoding( getTokenValue(line, ENCODING));
        }

    }
    // move to the beginning of the content
    hdrlen += strlen(newline) + strlen(newline); // added 2 new line that separate the bodyparts
    // get bodypart content
    if( isAttach == false) { // || !ret.getFilename() ) {
        // this is not an attachment
        if(ret.getEncoding() && strcmp(ret.getEncoding(), "quoted-printable") == 0 ) {
            char *decoded = qp_decode( part.substr(hdrlen) );
            ret.setContent ( decoded );
            delete [] decoded;
        }
        else if (ret.getEncoding() && strcmp(ret.getEncoding(), "base64") == 0 ) {
            char *decoded = "";
            size_t len = 0;
            if( uudecode( part.substr(hdrlen), &decoded, &len ) ) {
                LOG.error("Error decoding content");
            }
            ret.setContent ( decoded );
            delete [] decoded;
        }
        else {
            bool found = true;
            if (part.substr(hdrlen).length() < 6) {
                StringBuffer s(part.substr(hdrlen));
                for (unsigned int i = 0; i < s.length(); i++) {
                    if (s.c_str()[i] != '\r' && s.c_str()[i] != '\n') {
                        found = true;
                        break;
                    } else {
                        found = false;
                    }
                }
            }
            if (found) {
                ret.setContent ( part.substr(hdrlen) );
            }
        }
    }
    else {
        LOG.debug("Attachment");
        ret.setContent( mkTempFileName( ret.getFilename() ) );
        LOG.debug("%s", ret.getContent());
        StringBuffer p = part.substr(hdrlen);
        if (p.length()) {
            LOG.debug("Saving...");
            if( convertAndSave(ret.getContent(), p.c_str(), ret.getEncoding()) ) {
                LOG.error("Error in convertAndSave");
            }
            else {
                LOG.debug("convertAndSave success");
            }
        }
    }
    LOG.debug("getBodyPart END");

    // return true if there are more parts
    return (next != StringBuffer::npos);
}
Exemple #13
0
void Body::removePart(std::string part_uuid) {
	//Get shared pointer of the Part to be removed
	boost::shared_ptr<Part> part = getPartByUUID(part_uuid);
	
	//TODO: Handle removal of root BP or root Organ
	if (part == nullptr || part->getId() == "ROOT" || part->getId() == "UPPER_TORSO")
	{
		return;
	}

	debug_print("Removing Part %s...\n", part->getId().c_str());

	//Create a list of all parts to be removed 
	std::vector<string>* rem_list = new std::vector<string>();

	//Add the part given to the function...
	rem_list->push_back(part_uuid);
	//...and everything that lies downstream of it (Organs and Bodyparts)
	makeDownstreamPartList(part_uuid, rem_list);

	//Remove duplicates from the list
	std::sort(rem_list->begin(), rem_list->end());
	rem_list->erase(std::unique(rem_list->begin(), rem_list->end()), rem_list->end());

#ifdef _DEBUG
	for (auto it = rem_list->begin(); it != rem_list->end(); it++)
	{
		debug_print("UUID %s is Part %s \n", getPartByUUID(*it)->getUUID().c_str(), getPartByUUID(*it)->getId().c_str());
	}
#endif

	//Make a temporary list, in which UUIDs of empty bodyparts are stored.
	// Its contents are later added to the rem_list
	std::vector<string>* bp_rem = new std::vector<string>();

	//Iterate over all parts to be removed...
	for (auto it_rl = rem_list->begin(); it_rl != rem_list->end(); it_rl++)
	{
		//...if the part is an Organ, remove it from its connectors connected_organs list
		if (getPartByUUID(*it_rl)->getType() == TYPE_ORGAN)
		{
			Organ *o = static_cast<Organ*>(getPartByUUID(*it_rl).get());
			Organ *con = static_cast<Organ*>(getPartByUUID(o->getConnectorUUID()).get());

			con->removeConnectedOrgan(*it_rl);
		}

		//..for all parts: remove from super part child list.
		// If the super part is found to be empty (removeChild() returns true), add it
		// to the temporary bp_rem list. 
		BodyPart* super = static_cast<BodyPart*>(getPartByUUID(getPartByUUID(*it_rl)->getSuperPartUUID()).get());
		BodyPart* old_super;
		if (super->removeChild(*it_rl))
		{
			debug_print("BodyPart %s is empty, add to unregister\n", super->getId().c_str());
			bp_rem->push_back(super->getUUID());
			bool done = false;

			//For every BodyPart that is to be deleted as empty, remove it from its own
			// super BodyPart and check wheter it needs to be removed as well!
			while (!done)
			{
				old_super = super;
				super = static_cast<BodyPart*>(getPartByUUID(super->getSuperPartUUID()).get());
				if (super->removeChild(old_super->getUUID()))
				{
					debug_print("BodyPart %s is empty, add to unregister\n", super->getId().c_str());
					bp_rem->push_back(super->getUUID());
				}
				else {
					done = true;
				}
			}
		}
	}

	//Merge the temporary removal list into the rem_list
	rem_list->insert(rem_list->end(), bp_rem->begin(), bp_rem->end());

	//Remove duplicates again
	std::sort(rem_list->begin(), rem_list->end());
	rem_list->erase(std::unique(rem_list->begin(), rem_list->end()), rem_list->end());

	//Unregister the Parts, causing the shared pointers to destroy their references and themselves.
	unregisterParts(rem_list);

	//Clear the part variable. This should cause the last use of the shared pointer
	// to the part to be freed, therefore destroying the part.
	part.reset();
	
	//Refresh all lists and maps
	refreshLists();

#ifdef _DEBUG
	printBodyMap("body_mt.gv", root.get());
#endif

	debug_print("done.\n");
	
}
Exemple #14
0
string Body::loadBody(const char *filename){
	
	//###XML FILE HANDLING###
	using namespace rapidxml;
	char *buffer;

	//Load XML file
	try{
	std::ifstream is (filename);

	if (is) {
		//Get file length
		is.seekg(0, is.end);

		int length = is.tellg();
		is.seekg(0, is.beg);

		buffer = new char[length];

		is.read(buffer, length);
		//buffer now holds entire XML file
	} else { return false; }

	//Parse XML file
	// WARNING: FILE MUST BE NULL-TERMINATED!

	xml_document<> doc;
	doc.parse<0>(buffer);


	//###TISSUE DATA###

	//Temporary variables
	char *id = nullptr, *name = nullptr;
	float pain = -1.0f, blood_flow = -1.0f, resistance = -1.0f, impairment = -1.0f; //Initialize with illegal values

	//Load the tissue data (First first_node() is "body_def",
	// data starts with second level "tissues")
	xml_node<> *tissues = doc.first_node()->first_node("tissues");

	char *_name;

	//Iterate through all tissue definitions
	for (xml_node<> *tissue = tissues->first_node();
			tissue;
			tissue = tissue->next_sibling())
	{
		//Iterate through the tissue attributes
		for (xml_node<> *attr = tissue->first_node();
				attr;
				attr = attr->next_sibling())
		{

			_name = attr->name();
			if (!strcmp(_name,"id")){ id = attr->value(); }
			else if (!strcmp(_name,"name")){ name = attr->value(); }
			else if (!strcmp(_name,"pain")){ pain = atof(attr->value()); }
			else if (!strcmp(_name,"blood_flow")){ blood_flow = atof(attr->value()); }
			else if (!strcmp(_name,"resistance")){ resistance = atof(attr->value()); }
			else if (!strcmp(_name,"impairment")){ impairment = atof(attr->value()); }
		}

		debug_print("Read Tissue:\n\tID: %s \n\tName: %s \n\tBlood Flow: %f \n\tResistance: %f \n\tImpairment: %f\n",
				id, name, blood_flow, resistance, impairment);

		//Create a new Tissue and store the shared pointer to it in the tissue map
		boost::shared_ptr<Tissue> t_tissue(new Tissue(id, name, pain, blood_flow, resistance, impairment));
		tissue_map->insert(std::pair<std::string, boost::shared_ptr<Tissue>>(std::string(id), t_tissue));
	}

	//###BODYPART DATA###

	//maps for child linking and organ linking
	//K: UUID of the child, V: UUID of the parent
	std::map<string, string>* child_map = new std::map<string, string>();
	//K: UUID of the organ, V: IID(!) of its connector
	std::map<string, string>* organ_link_map = new std::map<string, string>();

	//Load the bodypart data (First first_node() is "body_def", 
	// data starts with the second level "body" 
	xml_node<> *body = doc.first_node()->first_node("body");
	string root_uuid = enter(body->first_node(), child_map, organ_link_map);

	//Destroy the XML data in memory
	delete[] buffer;

	//Build IID<->UUID map, which is required for linking 
	makeIdMap();

	//Link children and organs
	for (std::map<string, string>::iterator ch_it = child_map->begin();
		ch_it != child_map->end(); ch_it++) 
	{
		if (getPartByUUID(ch_it->first) == nullptr)
		{
			debug_error("ERROR during body part linking: Part UUID %s was requested, but is not in part map!\n",
				ch_it->first.c_str());
			return nullptr;
		}
		if (getPartByUUID(ch_it->second) == nullptr)
		{
			debug_error("ERROR during body part linking: Part UUID %s was requested, but is not in part map!\n",
				ch_it->second.c_str());
			return nullptr;
		}
		
		BodyPart* parent = dynamic_cast<BodyPart*>(getPartByUUID(ch_it->second).get());
		if (parent == nullptr) 
		{
			debug_error("ERROR during body part linking: Casting from Part* to BodyPart* on Part %s failed!\n",
				ch_it->second.c_str());
			return nullptr;
		}

		parent->addChild(ch_it->first);
	}

	for (std::map<string, string>::iterator or_it = organ_link_map->begin();
		or_it != organ_link_map->end(); or_it++)
	{
		if (getPartByUUID(or_it->first) == nullptr)
		{
			debug_error("ERROR during body part linking: Part UUID %s was requested, but is not in part map!\n",
				or_it->first.c_str());
			return nullptr;
		}
		if (getPartByIID(or_it->second) == nullptr)
		{
			debug_error("ERROR during body part linking: Part IID %s was requested, but is not in part map!\n",
				or_it->second.c_str());
			return nullptr;
		}
		Part* temp = getPartByIID(or_it->second).get();
		Organ* connector = dynamic_cast<Organ*>(temp);
		if (connector == nullptr){
			debug_error("ERROR during body part linking: Casting from Part* to Organ* on Part %s failed!\n",
				or_it->second.c_str());
			return nullptr;
		}
		connector->addConnectedOrgan(or_it->first);
	}

	//Successfully parsed the body definition file!
	//Return the address of the newly created body part.
	return root_uuid;

	} catch (std::exception& e) {
		debug_error("ERROR: %s \n", e.what());
		return NULL;
	}
	catch (bdef_parse_error& pe) {
		debug_error("ERROR: %s \n", pe.what());
		return NULL;
	}

	return NULL;
}
Exemple #15
0
string Body::enter(rapidxml::xml_node<> *node, std::map<string, string>* child_map, std::map<string, string>* organ_link_map) {
	using namespace rapidxml;

	int organ_count, bodyparts, it;
	xml_node<> *temp;
	xml_node<> **organ_node_list;

	char *id = nullptr, *name = nullptr, *_name = nullptr;
	float surface = 0.0f;

	//Make a count of the body_part nodes in this node and parse all standard
	// nodes for the bodypart of this node
	temp = node->first_node();
	bodyparts = 0;
	while (temp != nullptr){
		_name = temp->name();

		if (!strcmp(_name, "body_part")) { bodyparts++; }

		if (!strcmp(_name, "id")) { id = temp->value(); }
		if (!strcmp(_name, "name")) { name = temp->value(); }
		if (!strcmp(_name, "surface")) { surface = atof(temp->value()); }


		temp = temp->next_sibling();
	}

	//if any of the mandatory vars for bodyparts are NULL, ERROR!
	if (id == nullptr || name == nullptr){
		throw new bdef_parse_error("Not all mandatory BodyPart variables defined!", node);
	}

	//make the bodypart, make the pointer to it shared and store it in the part_map
	BodyPart* bp = new BodyPart((string)id, (string)name, surface, this);

	boost::shared_ptr<BodyPart> p (bp);

	part_map->insert(
		std::pair<std::string, boost::shared_ptr<Part>>(
		bp->getUUID(), boost::static_pointer_cast<Part>(p)));

	//reset temporary variables for reuse with the organs
	id = nullptr; name = nullptr;

	//DEBUG: Print new BodyPart
	debug_print("New BodyPart created: \n\tID: %s \n\tName: %s \n\tSurface: %f\n",
			bp->getId().c_str(), bp->getName().c_str(), bp->getSurface());

	//If there are no body_part nodes...
	if (bodyparts == 0){
		//...there must be organs instead!
		// variables
		Organ **organs;
		xml_attribute<> *attr;
		xml_node<> *tdef_node;

		char *connector = nullptr;
		bool symmetrical = false;

		it = 0;

		//  temp vars for tissue definitions
		char *tdef_id, *tdef_custom_id, *tdef_name;
		float tdef_hit_prob;

		tissue_def *tdefs = nullptr;
		int tdef_count = 0, tdef_it = 0;


		//Reset back to the first node in the given node
		temp = node->first_node();

		//scan for organ nodes in the given node
		organ_count = 0;
		while (temp != nullptr){
			if (!strcmp(temp->name(),"organ")) { organ_count++; }
			temp = temp->next_sibling();
		}

		//If there are no organs AND no bodyparts, ERROR!
		if (organ_count == 0){
			throw bdef_parse_error("No body part and no organ definition!", node);
		}

		//compile a list of nodes holding the organ definitions
		//and parse the remaining nodes to make the bodypart
		organ_node_list = new xml_node<>*[organ_count];
		temp = node->first_node();

		while (temp != nullptr){
			_name = temp->name();

			if (!strcmp(_name,"organ")) {
				organ_node_list[it] = temp;
				it++;
			}

			temp = temp->next_sibling();
		}

		//create temporary organ array
		organs = new Organ*[organ_count];

		//parse each organ definition in the list
		for (int i=0; i < organ_count; i++){
			//Enter into organ node
			temp = organ_node_list[i]->first_node();

			//Iterate through all nodes within the organ node
			while (temp != nullptr){
				_name = temp->name();

				//Parse standard tags
				if (!strcmp(_name,"id")) { id = temp->value(); }
				if (!strcmp(_name,"name")) { name = temp->value(); }
				if (!strcmp(_name,"surface")) { surface = atof(temp->value()); }
				if (!strcmp(_name,"connector")) { connector = temp->value(); }

				//Parse the organ tissue definitions, create (or rather link) them
				// and add to the organs
				if (!strcmp(_name,"organ_tissue")) {
					attr = temp->first_attribute();
					if (attr != nullptr && !strcmp(attr->name(), "symmetrical")){
						symmetrical = true;
					}

					attr = nullptr;

					//Get the count of tissue defs
					tdef_count = 0;
					tdef_node = temp->first_node();

					while (tdef_node != nullptr)
					{
						//If any other node than tissue_def, ERROR!
						if (strcmp(tdef_node->name(), "tissue_def")) {
							throw bdef_parse_error("Invalid node for organ tissue (only tissue_def allowed)!", temp);
						}

						tdef_count++;

						tdef_node = tdef_node->next_sibling();
					}

					//Create organ tissue array, double size if organ is symmetrical
					tdefs = new tissue_def[tdef_count * (symmetrical+1)];

					//Enter the organ_tissue node, create the tissue_def for
					// each tissue_def child and store it in tdefs[] array
					tdef_it = 0;
					tdef_node = temp->first_node();
					while (tdef_node != nullptr){
						//The value of a tissue_def node is the id of the tissue (e.g. M_ARTERY)
						tdef_id = tdef_node->value();

						tdef_hit_prob = 0;
						tdef_name = nullptr;
						tdef_custom_id = nullptr;

						//Get the other parameters
						attr = tdef_node->first_attribute();
						while (attr != nullptr){

							if (!strcmp(attr->name(), "hit_prob")){ tdef_hit_prob = atof(attr->value()); }
							if (!strcmp(attr->name(), "name")) { tdef_name = attr->value(); }
							if (!strcmp(attr->name(), "custom_id")) {
								tdef_custom_id = attr->value();
							}

							attr = attr->next_attribute();
						}


						//Store the parameters in the tissue definition
						if (tdef_custom_id != nullptr) {
							tdefs[tdef_it].custom_id = string(tdef_custom_id);
						}
						else { tdefs[tdef_it].custom_id = ""; }

						if (tdef_name != nullptr) {
							tdefs[tdef_it].name = string(tdef_name);
						}
						else { tdefs[tdef_it].name = ""; }
						
						tdefs[tdef_it].hit_prob = tdef_hit_prob;

						//Link the tissue definition to it's base tissue
						// NOTE: the tissue_map variable is a POINTER to the
						//  actual tissue map which is defined in the loadBody (super)
						//  function, therefore it must be dereferenced before use.
						//If the base tissue cannot be linked, ERROR!

						std::string key = tdef_id;

						std::map<std::string, boost::shared_ptr<Tissue>>::const_iterator pos
							= tissue_map->find(key);

						if (pos == tissue_map->end()){ throw bdef_parse_error("Tissue not found!", tdef_node); }
						tdefs[tdef_it].tissue = pos->second;

						tdef_it++;
						tdef_node = tdef_node->next_sibling();
					}
				}
				temp = temp->next_sibling();
			}

			//Check whether all necessary data for organ creation has been read
			// if not, ERROR!
			if (id == nullptr || name == nullptr || connector == nullptr || tdefs == nullptr){
				throw bdef_parse_error("Not all necessary data for organ creation found.", organ_node_list[i]);
			}

			//if organ is symmetrical, create the symmetry by duplicating all entries but the last
			// and appending them in reverse order
			int d;
			for (int j=tdef_count-2; j >= 0; j--)
			{
				d = (j - (tdef_count - 1))*-1;
				tdefs[(tdef_count-1)+d] = tdefs[j];
			}

			//Create the organ
			organs[i] = new Organ(string(id), string(name), surface, this, tdefs, tdef_count, connector, !strcmp(connector, "_ROOT"));

			//DEBUG: Print Organ
#ifdef _DEBUG
			debug_print("\tNew Organ created:\n\t\tID: %s \n\t\tName: %s \n\t\tSurface: %f \n\t\tRoot: %s \n\t\tTissues:",
				organs[i]->getId().c_str(), organs[i]->getName().c_str(), organs[i]->getSurface(), connector);

			for (int di = 0; di < (tdef_count * (symmetrical+1))-1; di++){
				debug_print("\n\t\t\tBase Tissue Name: %s \n\t\t\t\tHit Prob.: %f",
					tdefs[di].tissue->getName().c_str(), tdefs[di].hit_prob);

				if (!tdefs[di].name.empty()){ debug_print("\n\t\t\t\tCustom Name: %s", tdefs[di].name.c_str()); }
				if (!tdefs[di].custom_id.empty()){ debug_print("\n\t\t\t\tCustom ID: %s", tdefs[di].custom_id.c_str()); }
			}

			debug_print("\n\tEND Organ.\n");
#endif
		}

		//...and add all organs to the part map. Add the "child note"
		// between the organs and the new bodypart to the child_map.
		// Add the "connector note" between the organs and their connectors to 
		// the organ_link_map.
		for (int i = 0; i < organ_count; i++){
			part_map->insert(
				std::pair<string, boost::shared_ptr<Part>>(
				organs[i]->getUUID(),
				boost::static_pointer_cast<Part>(boost::make_shared<Organ>(*(organs[i])))
				));

			child_map->insert(
				std::pair<string, string>(
				organs[i]->getUUID(),
				bp->getUUID()
				));

			if (organs[i]->getConnectorId() != "_ROOT"){
				organ_link_map->insert(
					std::pair<string, string>(
					organs[i]->getUUID(),
					dynamic_cast<Organ*>(organs[i])->getConnectorId()
					));
			}
		}
		

	} else {
		//...its another BodyPart

		//Go through all nodes and call this function on every
		// node containing a part definition, add the returned BodyPart/Organ
		// to this ones' children (per child_map)
		temp = node->first_node();

		it = 0;
		while (temp != nullptr){
			_name = temp->name();

			if (!strcmp(_name, "body_part")) {
				string child_uuid = enter(temp, child_map, organ_link_map);
				child_map->insert(
					std::pair<string, string>(
					child_uuid,
					bp->getUUID()
					));
				//bp->addChild(enter(temp));
			}

			temp = temp->next_sibling();
		}
	}

	//return this bodyparts uuid
	return bp->getUUID();
}
Exemple #16
0
    void Creature::calculateMaxTorque() {
        double gravity = Math::abs(BulletSimulator::getSingleton().getWorld().getGravity().y());
        int terminal[getNumberOfBodyParts()];
        for (int i = 0; i < getNumberOfBodyParts(); ++i) {
            terminal[i] = 0;
            getBodyPart(i).setMaxTorque(0.0);
        }
        //Determinar nodos terminales (sum == 1)
        for (int i = 0; i < getNumberOfConstraints(); ++i) {
            assert(getConstraint(i).getIdBodyA() < getNumberOfBodyParts() &&
                    getConstraint(i).getIdBodyA() >= 0);
            assert(getConstraint(i).getIdBodyB() < getNumberOfBodyParts() &&
                    getConstraint(i).getIdBodyB() >= 0);
            //            if (!getBodyPart(getConstraint(i).getIdBodyA()).isRoot()) {
            ++terminal[getConstraint(i).getIdBodyA()];
            //            }
            //            if (!getBodyPart(getConstraint(i).getIdBodyB()).isRoot()) {
            ++terminal[getConstraint(i).getIdBodyB()];
            //            }
        }
        for (int e = 0; e < getNumberOfBodyParts(); ++e) {
            if (terminal[e] != 1) continue;
            int count = 0;
            BodyPart * body = &getBodyPart(e);
            std::vector<BodyPart*> extremities;
            while (body != &getRoot() && count++ < getNumberOfBodyParts()) {
                extremities.push_back(body);
                body = &getBodyPart(body->getParentId());
            }
            extremities.push_back(body);

            double arm_length = 0.0;
            btTransform trans;
            btVector3 center_of_mass;
            btVector3 connection;
            // A  0  B  1  C  2  Root  3
            // |-----|-----|-----|-----|
            for (int i = extremities.size() - 2; i >= 0; --i) {
                //                DEBUG(extremity[i]->getName() + " ; " + extremity[i+1]->getName());
                Constraint* constraint = getConstraint(*extremities[i], *extremities[i + 1]);
                assert(constraint);
                center_of_mass = extremities[i]->getRigidBody()->getCenterOfMassPosition();
                loadConnectionTransform(*extremities[i], *constraint, trans);
                connection = btVector3(trans.getOrigin().x(), trans.getOrigin().y(), trans.getOrigin().z());
                arm_length = (center_of_mass - connection).length();
                //                BDEBUG("arm=" + TO_STRING(arm_length));
                extremities[i]->addMaxTorque(arm_length * extremities[i]->getMass() * gravity);

                for (int j = i - 1; j >= 0; --j) {
                    constraint = getConstraint(*extremities[j], *extremities[i]);
                    if (!constraint) {
                        //                        DEBUG("NOT FOUND: " + extremity[i]->getName() + " ; " + extremity[i + 1]->getName());

                        continue;
                    }
                    //                    DEBUG("FOUND (" + constraint->getName() + "): " + extremity[i]->getName() + " ; " + extremity[i + 1]->getName());
                    assert(constraint);
                    center_of_mass = extremities[i]->getRigidBody()->getCenterOfMassPosition();
                    loadConnectionTransform(*extremities[i], *constraint, trans);
                    connection = btVector3(trans.getOrigin().x(), trans.getOrigin().y(), trans.getOrigin().z());
                    arm_length += (center_of_mass - connection).length();

                    center_of_mass = extremities[j]->getRigidBody()->getCenterOfMassPosition();
                    loadConnectionTransform(*extremities[j], *constraint, trans);
                    connection = btVector3(trans.getOrigin().x(), trans.getOrigin().y(), trans.getOrigin().z());
                    arm_length += (center_of_mass - connection).length();

                    extremities[i]->addMaxTorque(arm_length * extremities[j]->getMass() * gravity);
                }
            }
        }
    }
    void MainWindow::applyForce( eForceType type ) {
        bool play = getSimulationThread().getSimulator().isPlaying();
        if (play) {
            pause();
        }
        getSimulationThread().wait();
        getSimulationThread().getSimulator().getLock().lockForRead();
        Creature* creature = getSimulationThread().getSimulator().currentCreature();
        if (creature) {

            if (type == FT_NONE) {
                for (int i = 0; i < creature->getNumberOfBodyParts(); ++i) {
                    creature->getBodyPart(i).getRigidBody()->clearForces();
                }
                getUiInspector().sbx_force_x->setValue(0.0);
                getUiInspector().sbx_force_y->setValue(0.0);
                getUiInspector().sbx_force_z->setValue(0.0);
            } else {
                std::vector<btRigidBody*>& bodies = getRendererThread().getRenderer().getSelectedBodyParts();
                btVector3 forces(getUiInspector().sbx_force_x->value(),
                        getUiInspector().sbx_force_y->value(),
                        getUiInspector().sbx_force_z->value());

                for (std::vector<btRigidBody*>::iterator it = bodies.begin();
                        it != bodies.end(); ++it) {
                    btRigidBody* rigid_body = *it;
                    BodyPart* body = NULL;
                    for (int i = 0; i < creature->getNumberOfBodyParts(); ++i) {
                        if (creature->getBodyPart(i).getRigidBody() == rigid_body) {
                            body = &creature->getBodyPart(i);
                            break;
                        }
                    }
                    assert(body);
                    rigid_body->activate(true);
                    switch (type) {
                        case FT_CENTRAL_FORCE: rigid_body->applyCentralForce(forces);
                            break;
                        case FT_CENTRAL_TORQUE: rigid_body->applyTorque(forces);
                            break;
                        case FT_IMPULSE_FORCE: rigid_body->applyCentralImpulse(forces);
                            break;
                        case FT_IMPULSE_TORQUE: rigid_body->applyTorqueImpulse(forces);
                            break;
                        case FT_RELATIVE_FORCE:
                            break;
                        case FT_RELATIVE_IMPULSE:
                            rigid_body->applyImpulse(forces, btVector3(0, -body->getSizeY() / 2.0, 0));
                            break;
                        case FT_EACH_STEP:
//                            creature->setTmpValueX(forces.x());
//                            creature->setTmpValueY(forces.y());
//                            creature->setTmpValueZ(forces.z());
                            break;
                        default:
                            BDEBUG(TO_STRING(type));
                            assert(0);
                    }
                }
            }

        }
        getSimulationThread().getSimulator().getLock().unlock();
        if (play) {
            this->play();
        }
    }
Exemple #18
0
int main(int argc, char** argv)
#endif
{
    size_t msglen=0;
    WCHAR *name[10], *msg=0;
    int i;
    const WCHAR *attach;

#ifdef _WIN32_WCE
    name[0] = stringdup(TEXT("message.xml"));
    name[1] = stringdup(TEXT("text.xml"));
    name[2] = NULL;
    attach = TEXT("/synclog.txt");
#else
    for(i=1; i<argc; i++)
       name[i-1] = utf82wc(argv[i]);
    name[i-1] = NULL;
    attach = TEXT("c:/windows/temp/synclog.txt");
#endif
    LOG.setLevel(LOG_LEVEL_DEBUG); // Force debug level for this test.

    // Test parse/format loop if names were given on cmdline
    for (i=0; name[i]; i++) {
        msg = loadAndConvert(name[i]);
        if( !msg ){
            WCHAR dbg[256];
            wsprintf(dbg, TEXT("Can't open file %s\n"), name[i]);
	        LOG.error("%s", dbg);
            continue;
        }

    	EmailData em;

        if (em.parse(msg))
            fprintf(stderr, "Parse failed on: %S\n", name[i]);

        delete [] msg;

        WCHAR outname[10];
        wsprintf(outname, TEXT("msgout%d.xml"), i);
        if ( convertAndSave( outname, em.format() ) ) {
            fprintf(stderr, "Error in convertAndSave(em)\n");
        }
    }

    // Try to send a new mail with attachment
    EmailData newmail;
    MailMessage n;
    BodyPart body;

    body.setContent(TEXT("Ma che bella la città!"));

    n.setFrom(TEXT("*****@*****.**"));
    n.setTo(TEXT("*****@*****.**"));
    n.setSubject(TEXT("Test"));
    n.setBody(body);

	BodyPart a;
	a.setFilename( TEXT("pippo.txt") );
	a.setContent( attach );
	a.setEncoding( TEXT("base64") );
    n.addAttachment(a);

    newmail.setRead(true);
    newmail.setEmailItem(n);

    if ( convertAndSave( L"attachment.xml", newmail.format() ) ) {
        fprintf(stderr, "Error in convertAndSave(newmail)\n");
    }
    //extern size_t StringBuffer_memcount;
    //fprintf(stderr, "Memcount: %ld\n", StringBuffer_memcount);
    //getchar();
	return 0;
}
   IMAPFetchParser::BodyPart
   IMAPFetchParser::_ParseBODY(const String &sString)
   {
      BodyPart oPart;
      
      // Set the description.

      String sNewName = sString;
      sNewName.ReplaceNoCase(_T("BODY.PEEK["), _T("BODY["));

      oPart.SetDescription(sNewName);

      // Locate the start of the peek-part.
      long lBodyStart = sNewName.Find(_T("[")) + 1;
      
      // Locate the end of the part.
      long lBodyEnd = sNewName.Find(_T("]"), lBodyStart) - 1;

      if (sNewName.Find(_T("<"), lBodyEnd) == lBodyEnd +2)
      {
         int iStart = lBodyEnd+3;
         int iEnd = sNewName.Find(_T(">"), iStart);

         String sPartial = sNewName.Mid(iStart, iEnd - iStart);
         int iDotPos = sPartial.Find(_T("."));
         
         oPart.m_iOctetStart = _ttoi(sPartial.Mid(0, iDotPos));
         oPart.m_iOctetCount = _ttoi(sPartial.Mid(iDotPos+1));

         // Remove the octets part from the description.
         String sBefore = sNewName.Mid(0, iStart - 1);
         String sAfter = sNewName.Mid(iEnd + 1);

         String sDescWithoutOctets = sBefore + sAfter;

         oPart.SetDescription(sDescWithoutOctets);
      }

      // Extract the body  part.
      long lBodyLen = lBodyEnd - lBodyStart +1 ;
      String sBody = sNewName.Mid(lBodyStart, lBodyLen);

      if (sBody.IsEmpty())
      {
         oPart.SetShowBodyFull(true);
         m_bSetSeen = true;
      }
      else
      {
         // Determine what to look at.
         long lTemp  = 0;

         // Should we show all header fields except for...
         lTemp = sBody.FindNoCase(_T("HEADER.FIELDS.NOT"));
         if (lTemp >= 0)
         {
            int lStart = sBody.Find(_T("("), lTemp) + 1;
            int lEnd = sBody.Find(_T(")"), lStart) ;
            int lLength = lEnd - lStart;
            
            String sFields = sBody.Mid(lStart, lLength);
            oPart.GetHeaderFieldsNOT() = StringParser::SplitString(sFields, " ");
            oPart.SetShowBodyHeaderFieldsNOT(true);

            // Strip away the header fields part from the Body.
            // If we don't do this, we will parse the same string
            // as header.fields below.
            String sBefore = sBody.Mid(0, lTemp);
            String sAfter = sBody.Mid(lEnd + 2);
            sBody = sBefore + sAfter;

         }

         // Should we show header fields?
         lTemp = sBody.FindNoCase(_T("HEADER.FIELDS"));
         if (lTemp >= 0)
         {
            int lStart = sBody.Find(_T("("), lTemp) + 1;
            int lEnd = sBody.Find(_T(")"), lStart) ;
            int lLength = lEnd - lStart;
            
            String sFields = sBody.Mid(lStart, lLength);
            oPart.GetHeaderFields() = StringParser::SplitString(sFields, " ");
            oPart.SetShowBodyHeaderFields(true);

            // Strip away the header fields part from the Body.
            String sBefore = sBody.Mid(0, lTemp);
            String sAfter = sBody.Mid(lEnd + 2);
            sBody = sBefore + sAfter;
         }

         lTemp = sBody.FindNoCase(_T("HEADER"));
         if (lTemp >= 0)
         {
            oPart.SetShowBodyHeader(true);
            
            String sBefore = sBody.Mid(0, lTemp);
            String sAfter = sBody.Mid(lTemp + 7);
            sBody = sBefore + sAfter;
         }

         lTemp = sBody.FindNoCase(_T("MIME"));
         if (lTemp >= 0)
         {
            oPart.SetShowBodyHeader(true);

            String sBefore = sBody.Mid(0, lTemp);
            String sAfter = sBody.Mid(lTemp + 7);
            sBody = sBefore + sAfter;
         }

         lTemp = sBody.FindNoCase(_T("TEXT"));
         if (lTemp >= 0)
         {
            oPart.SetShowBodyText(true);
            
            String sBefore = sBody.Mid(0, lTemp);
            String sAfter = sBody.Mid(lTemp + 5);
            sBody = sBefore + sAfter;

            m_bSetSeen = true;
         }

         if (!oPart.GetShowBodyText() &&
             !oPart.GetShowBodyHeader() &&
             !oPart.GetShowBodyHeaderFields() &&
             !oPart.GetShowBodyHeaderFieldsNOT())
         {
             oPart.SetShowBodyText(true);
             m_bSetSeen = true;
         }
         
         sBody = sBody.TrimLeft(_T("."));
         sBody = sBody.TrimRight(_T("."));

         oPart.SetName(sBody);
      }

      return oPart;

   }
    void ResourceManager::loadBodyParts(const std::string &filename)
    {
        XMLFile file;
        int size;
        char *data = loadFile(filename, size);

		if (data && file.parse(data))
		{
		    // set size
		    file.setElement("size");
		    mBodyWidth = file.readInt("size", "width");
		    mBodyHeight = file.readInt("size", "height");

            // set defaults
            file.setElement("default");
		    mDefaultBody = file.readInt("default", "body");
            mDefaultFemale = file.readInt("default", "female");
		    mDefaultHair = file.readInt("default", "hair");
		    mDefaultChest = file.readInt("default", "chest");
		    mDefaultLegs = file.readInt("default", "legs");
		    mDefaultFeet = file.readInt("default", "feet");

            // add all the body parts
            file.setElement("body");
            do
            {
                file.setSubElement("image");
                int id = file.readInt("body", "id");
                std::string icon = file.readString("body", "icon");
                int part = file.readInt("body", "part");
                std::string colour = file.readString("body", "colour");

                Texture *iconTex = NULL;
                if (icon != "")
                {
                    if (getDataPath(icon).find(".zip") == std::string::npos)
                    {
                        iconTex = graphicsEngine->loadTexture(getDataPath(icon));
                    }
                    else
                    {
                        int iconBufSize = 0;
                        char *buffer = loadFile(icon, iconBufSize);
                        iconTex = graphicsEngine->loadTexture(icon, buffer, iconBufSize);
                        free(buffer);
                    }

                    if (iconTex == NULL)
                    {
                        logger->logError("Unable to load icon: " + icon);
                    }
                }

                BodyPart *body = new BodyPart(id, part, iconTex);

                do
                {
                    int dir = -1;
                    // check if img is in a content update
                    std::string img = file.readString("image", "file");
                    std::string dirstr = file.readString("image", "dir");

                    if (dirstr == "SE")
                        dir = DIRECTION_SOUTHEAST;
                    else if (dirstr == "SW")
                        dir = DIRECTION_SOUTHWEST;
                    else if (dirstr == "NE")
                        dir = DIRECTION_NORTHEAST;
                    else if (dirstr == "NW")
                        dir = DIRECTION_NORTHWEST;

                    std::string path = getDataPath(img);
                    size_t found = path.find(".zip");
                    if (found == std::string::npos)
                    {
                        body->addTexture(dir, path);
                    }
                    else
                    {
                        int imgBufSize = 0;
                        char *buffer = loadFile(img, imgBufSize);
                        body->addTexture(dir, img, buffer, imgBufSize);
                        free(buffer);
                    }

                } while (file.nextSubElement("image"));

                mBodyParts.push_back(body);
                file.clear("image");

            } while (file.nextElement("body"));
		}
    }
Exemple #21
0
static StringBuffer formatBodyPart(const BodyPart &part)
{
    StringBuffer ret;    
    LOG.debug("FormatBodyPart START");

    ret = MIMETYPE;
    
    ret += part.getMimeType(); ret += ";";
    if (!part.getFilename()) {
        LOG.debug("It doesn't contains an attachment. It is the body");
        ret +=" "; ret += CT_CHARSET; ret += part.getCharset(); 
    }
    ret += NL;
    
    if( part.getFilename() ) {
        ret += "        "; ret += CT_NAME; ret += "\""; ret += part.getFilename(); ret += "\"\n";
    }
    if( part.getEncoding() ) {
        ret += ENCODING; ret += part.getEncoding(); ret += NL;
    }
    if( part.getFilename() ) {
        if( part.getDisposition() ) {
            ret += DISPOSITION; ret += part.getDisposition(); ret += ";\n";
        }
        else {
            ret += DISPOSITION; ret += "attachment;\n";
        }

        ret += "      "; ret += CD_FILENAME; ret += "\""; ret += part.getFilename();
        ret += "\"\n";
    }
    // End of part headers
    ret += NL;
    // Content
    if( part.getFilename() ) {
        char *content = loadAndConvert(part.getContent(), part.getEncoding());
        ret += content;
        delete [] content;
    }
    else
        ret += part.getContent();

    LOG.debug("FormatBodyPart END");
    return ret;
}
Exemple #22
0
std::vector<float> PosEst::weightGPU(MatrixXf boundBox, float gridSize)
{
    int numSceneP, numModelF;
    numSceneP = scene->numPC();
    if(DEBUG_ALGORITHM) cout<<"# of all faces: "<<model->numFace()<<endl;
    if(DEBUG_ALGORITHM) cout<<"# of all filtered faces: "<<model->numFilteredFace()<<endl;
    numModelF = model->numFilteredFace();

    float3 maxBound, minBound;
    maxBound.x = boundBox(0,0);
    minBound.x = boundBox(0,1);
    maxBound.y = boundBox(1,0);
    minBound.y = boundBox(1,1);
    maxBound.z = boundBox(2,0);
    minBound.z = boundBox(2,1);

    ParticleScoreGPU scoreGPU(numParticles, numSceneP, numModelF, gridSize);
    *scoreGPU.minBound = minBound;
    *scoreGPU.maxBound = maxBound;

    // copy data
    if(DEBUG_ALGORITHM) cout<<"copy scene data: "<<numSceneP<<endl;
    for(int i=0;i<numSceneP;i++){
        scoreGPU.scenePos[i].x = scene->getPCFocus_back()->points.at(i).x;
        scoreGPU.scenePos[i].y = scene->getPCFocus_back()->points.at(i).y;
        scoreGPU.scenePos[i].z = scene->getPCFocus_back()->points.at(i).z;

        //        scoreGPU.sceneNorm[i].x = scene->getPCNorm()->points.at(i).x;
        //        scoreGPU.sceneNorm[i].y = scene->getPCNorm()->points.at(i).y;
        //        scoreGPU.sceneNorm[i].z = scene->getPCNorm()->points.at(i).z;
    }

    int nFace = 0;
    int nVert = 0;
    if(DEBUG_ALGORITHM) cout<<"copy model data"<<endl;
    for(int n=0;n<model->filteredParts.size();n++){
        BodyPart *part = model->bodyPart(model->filteredParts.at(n));
        Mesh* mesh = part->meshFocused();
        for(int i=0;i<mesh->numMesh();i++){
            for(int j=0;j<mesh->numFilteredFaces(i);j++){
                int faceId = mesh->filteredFaceId(i,j);
                //                Vector3f faceNorm = mesh->faceNorm(i,faceId);
                for(int k=0;k<3;k++){
                    scoreGPU.modelVertPos[nVert].x = mesh->vertex(i,mesh->face(i,faceId)->mIndices[k])->m_pos[0];
                    scoreGPU.modelVertPos[nVert].y = mesh->vertex(i,mesh->face(i,faceId)->mIndices[k])->m_pos[1];
                    scoreGPU.modelVertPos[nVert].z = mesh->vertex(i,mesh->face(i,faceId)->mIndices[k])->m_pos[2];
                    if(USENORM){
                        scoreGPU.modelVertNorm[nVert].x = mesh->vertex(i,mesh->face(i,faceId)->mIndices[k])->m_normal[0];
                        scoreGPU.modelVertNorm[nVert].y = mesh->vertex(i,mesh->face(i,faceId)->mIndices[k])->m_normal[1];
                        scoreGPU.modelVertNorm[nVert].z = mesh->vertex(i,mesh->face(i,faceId)->mIndices[k])->m_normal[2];
                    }
                    nVert ++;
                }
                //                scoreGPU.modelFaceNorm[nFace].x = faceNorm[0];
                //                scoreGPU.modelFaceNorm[nFace].y = faceNorm[1];
                //                scoreGPU.modelFaceNorm[nFace].z = faceNorm[2];
                nFace ++;
            }
        }
    }

    for(int i=0;i<numParticles;i++){
        scoreGPU.particlePos[i].x = particles[i].x;
        scoreGPU.particlePos[i].y = particles[i].y;
        scoreGPU.particlePos[i].z = particles[i].z;
        scoreGPU.particleRPY[i].x = particles[i].roll;
        scoreGPU.particleRPY[i].y = particles[i].pitch;
        scoreGPU.particleRPY[i].z = particles[i].yaw;
    }

    float3 *crspdFacesPos = (float3 *)malloc(numSceneP * sizeof(float3));
    if(DEBUG_ALGORITHM) cout<<"particle filtering"<<endl;
    std::vector<float> out = scoreGPU.compute(crspdFacesPos);

    //    out_crspdFacesPos.resize(numSceneP);
    //    for (size_t i=0; i<numSceneP; i++){
    //        out_crspdFacesPos[i] = crspdFacesPos[i];
    //    }

    free(crspdFacesPos);

    //    crspdFacesPos = scoreGPU.compute();
    return (out);
}
Exemple #23
0
int main(int argc, char**argv)
{
  Arguments info;
  if(!parseOptions (argc, argv, info))
    return 1;

  ESMReader esm;
  esm.setEncoding(info.encoding);

  string filename = info.filename;
  cout << "\nFile: " << filename << endl;

  try {

  if(info.raw_given)
    {
      cout << "RAW file listing:\n";

      esm.openRaw(filename);

      printRaw(esm);

      return 0;
    }

  bool quiet = info.quiet_given;
  bool loadCells = info.loadcells_given;

  esm.open(filename);

  cout << "Author: " << esm.getAuthor() << endl;
  cout << "Description: " << esm.getDesc() << endl;
  cout << "File format version: " << esm.getFVer() << endl;
  cout << "Special flag: " << esm.getSpecial() << endl;
  cout << "Masters:\n";
  ESMReader::MasterList m = esm.getMasters();
  for(unsigned int i=0;i<m.size();i++)
    cout << "  " << m[i].name << ", " << m[i].size << " bytes\n";

  // Loop through all records
  while(esm.hasMoreRecs())
    {
      NAME n = esm.getRecName();
      esm.getRecHeader();
      string id = esm.getHNOString("NAME");
      if(!quiet)
        cout << "\nRecord: " << n.toString()
             << " '" << id << "'\n";

      switch(n.val)
        {
        case REC_ACTI:
          {
            Activator ac;
            ac.load(esm);
            if(quiet) break;
            cout << "  Name: " << ac.name << endl;
            cout << "  Mesh: " << ac.model << endl;
            cout << "  Script: " << ac.script << endl;
            break;
          }
        case REC_ALCH:
          {
            Potion p;
            p.load(esm);
            if(quiet) break;
            cout << "  Name: " << p.name << endl;
            break;
          }
        case REC_APPA:
          {
            Apparatus p;
            p.load(esm);
            if(quiet) break;
            cout << "  Name: " << p.name << endl;
            break;
          }
        case REC_ARMO:
          {
            Armor am;
            am.load(esm);
            if(quiet) break;
            cout << "  Name: " << am.name << endl;
            cout << "  Mesh: " << am.model << endl;
            cout << "  Icon: " << am.icon << endl;
            cout << "  Script: " << am.script << endl;
            cout << "  Enchantment: " << am.enchant << endl;
            cout << "  Type: " << am.data.type << endl;
            cout << "  Weight: " << am.data.weight << endl;
            break;
          }
        case REC_BODY:
          {
            BodyPart bp;
            bp.load(esm);
            if(quiet) break;
            cout << "  Name: " << bp.name << endl;
            cout << "  Mesh: " << bp.model << endl;
            break;
          }
        case REC_BOOK:
          {
            Book b;
            b.load(esm);
            if(quiet) break;
            cout << "  Name: " << b.name << endl;
            cout << "  Mesh: " << b.model << endl;
            break;
          }
        case REC_BSGN:
          {
            BirthSign bs;
            bs.load(esm);
            if(quiet) break;
            cout << "  Name: " << bs.name << endl;
            cout << "  Texture: " << bs.texture << endl;
            cout << "  Description: " << bs.description << endl;
            break;
          }
        case REC_CELL:
          {
            Cell b;
            b.load(esm);
            if(!quiet)
              {
                cout << "  Name: " << b.name << endl;
                cout << "  Region: " << b.region << endl;
              }
            if(loadCells)
              loadCell(b, esm, quiet);
            break;
          }
        case REC_CLAS:
          {
            Class b;
            b.load(esm);
            if(quiet) break;
            cout << "  Name: " << b.name << endl;
            cout << "  Description: " << b.description << endl;
            break;
          }
        case REC_CLOT:
          {
            Clothing b;
            b.load(esm);
            if(quiet) break;
            cout << "  Name: " << b.name << endl;
            break;
          }
        case REC_CONT:
          {
            Container b;
            b.load(esm);
            if(quiet) break;
            cout << "  Name: " << b.name << endl;
            break;
          }
        case REC_CREA:
          {
            Creature b;
            b.load(esm, id);
            if(quiet) break;
            cout << "  Name: " << b.name << endl;
            break;
          }
        case REC_DIAL:
          {
            Dialogue b;
            b.load(esm);
            break;
          }
        case REC_DOOR:
          {
            Door d;
            d.load(esm);
            if(quiet) break;
            cout << "  Name: " << d.name << endl;
            cout << "  Mesh: " << d.model << endl;
            cout << "  Script: " << d.script << endl;
            cout << "  OpenSound: " << d.openSound << endl;
            cout << "  CloseSound: " << d.closeSound << endl;
            break;
          }
        case REC_ENCH:
          {
            Enchantment b;
            b.load(esm);
            break;
          }
        case REC_GMST:
          {
            GameSetting b;
            b.id = id;
            b.load(esm);
            if(quiet) break;
            cout << "  Value: ";
            if(b.type == VT_String)
              cout << "'" << b.str << "' (string)";
            else if(b.type == VT_Float)
              cout << b.f << " (float)";
            else if(b.type == VT_Int)
              cout << b.i << " (int)";
            cout << "\n  Dirty: " << b.dirty << endl;
            break;
          }
        case REC_INFO:
          {
            DialInfo p;
            p.load(esm);
            if(quiet) break;
            cout << "  Id: " << p.id << endl;
            cout << "  Text: " << p.response << endl;
            break;
          }
        case REC_SOUN:
          {
            Sound d;
            d.load(esm);
            if(quiet) break;
            cout << "  Sound: " << d.sound << endl;
            cout << "  Volume: " << (int)d.data.volume << endl;
            break;
          }
        case REC_SPEL:
          {
            Spell s;
            s.load(esm);
            if(quiet) break;
            cout << "  Name: " << s.name << endl;
            break;
          }
        default:
          esm.skipRecord();
          if(quiet) break;
          cout << "  Skipping\n";
        }
    }

  } catch(exception &e)
    {
      cout << "\nERROR:\n\n  " << e.what() << endl;
      return 1;
    }

  return 0;
}
Exemple #24
0
 bool BodyPart::operator==(const BodyPart &bp) const
 {
   return this->getPartID() == bp.getPartID();
 }