Beispiel #1
0
// Constructor
AppearanceGroup::AppearanceGroup(AppearanceGroupSet* appearanceGroupSet,
                       const char* user) :
//   mResource(resource),
   mAppearanceGroupSet(appearanceGroupSet),
   mSharedUser(user)
{
   Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                 "AppearanceGroup:: this = %p, mSharedUser = '******'",
                 this, mSharedUser.data());

   // Publish initial content (presumably empty)
   SipDialogEvent* lFullContent = new SipDialogEvent("full", mSharedUser.data());
   UtlHashMapIterator appitor(mAppearances);
   UtlString* handle;
   while ( (handle = dynamic_cast <UtlString*> (appitor())))
   {
      Appearance* inst = dynamic_cast <Appearance*> (appitor.value());
      inst->getDialogs(lFullContent);
   }
   lFullContent->buildBody();

  // Publish the content for this shared user to the Subscribe Server.
  // Make a copy, because mpSipPublishContentMgr will own it.
  HttpBody* pHttpBody = new HttpBody(*(HttpBody*)lFullContent);
  delete lFullContent;
  getAppearanceAgent()->getEventPublisher().publish(
        mSharedUser.data(),
        DIALOG_SLA_EVENT_TYPE, //eventTypeKey
        DIALOG_EVENT_TYPE,     //eventType
        1, &pHttpBody,
        TRUE, TRUE);

   startSubscription();
}
void
LinearGeometry::renderFaces(float alpha, Appearance& appearance)
{
  glBegin(GL_TRIANGLES);
  _register = appearance.getFaceColor();
  glColor4f(_register[0], _register[1], _register[2],
            _register[3] * alpha * appearance.getModifierAlpha());
  int number = getNumberTriangles();
  float*** triangles = getTriangles();
  for (int i = 0; i < number; i++) {
    _register = triangles[i][0];
    glVertex3f(_register[0], _register[1], _register[2]);
    _register = triangles[i][1];
    glVertex3f(_register[0], _register[1], _register[2]);
    _register = triangles[i][2];
    glVertex3f(_register[0], _register[1], _register[2]);
  }
  glEnd();

  glBegin(GL_QUADS);
  number = getNumberQuads();
  float*** quads = getQuads();
  for (int i = 0; i < number; i++) {
    _register = quads[i][0];
    glVertex3f(_register[0], _register[1], _register[2]);
    _register = quads[i][1];
    glVertex3f(_register[0], _register[1], _register[2]);
    _register = quads[i][2];
    glVertex3f(_register[0], _register[1], _register[2]);
    _register = quads[i][3];
    glVertex3f(_register[0], _register[1], _register[2]);
  }
  glEnd();

}
Beispiel #3
0
void InventoryDomain::processVisibilityForMovedEntity(const LocatedEntity& moved_entity, const Location& old_loc, OpVector & res)
{
    if (m_entity.m_contains) {

        std::vector<LocatedEntity*> visibleEntities;

        std::unordered_set<int> outfitted;
        LocatedEntity* rightHandWieldedEntity = nullptr;
        const OutfitProperty* outfitProperty = m_entity.getPropertyClass<OutfitProperty>("outfit");

        if (outfitProperty) {
            for (auto& entry : outfitProperty->data()) {
                outfitted.insert(entry.second->getIntId());
            }
        }
        const EntityProperty* rightHandWieldProperty = m_entity.getPropertyClass<EntityProperty>("right_hand_wield");
        if (rightHandWieldProperty) {
            rightHandWieldedEntity = rightHandWieldProperty->data().get();
        }

        for (auto childEntity : *m_entity.m_contains) {
            if (childEntity == rightHandWieldedEntity) {
                visibleEntities.push_back(childEntity);
            } else if (outfitted.find(childEntity->getIntId()) != outfitted.end()) {
                visibleEntities.push_back(childEntity);
            }
        }

        std::set<std::string> newVisibleEntities;
        for (auto visibleEntity : visibleEntities) {
            if (m_lastVisibleEntities.find(visibleEntity->getId()) == m_lastVisibleEntities.end()) {
                Anonymous ent;
                ent->setId(visibleEntity->getId());
                ent->setStamp(visibleEntity->getSeq());

                Appearance d;
                d->setArgs1(ent);
                res.push_back(d);
            } else {
                m_lastVisibleEntities.erase(visibleEntity->getId());
            }
            newVisibleEntities.insert(visibleEntity->getId());
        }
        for (auto entityId : m_lastVisibleEntities) {
            Anonymous ent;
            ent->setId(entityId);

            Disappearance d;
            d->setArgs1(ent);
            res.push_back(d);

        }

        m_lastVisibleEntities = std::move(newVisibleEntities);
    }
}
void DisplayList::drawPrims(string appearance) {
	vector<MyPrimitive *>::const_iterator it;

	for (it = prims.begin(); it != prims.end(); it++) {
		Appearance *app = Scene::getInstance()->getAppearance(appearance);
		app->apply();
		(*it)->setAppearance(appearance);
		(*it)->draw();
		(*it)->clearAppearance();
	}
}
		void TextureProjectorNode::removeAllScopes()
		{
			while (!m_oldTexUnitMap.empty())
			{
				MeshNode* meshNode = m_oldTexUnitMap.begin()->first;
				Appearance* appearance = meshNode->getAppearance();
				TextureUnitState* texUnit = m_oldTexUnitMap.begin()->second;
				appearance->setTextureUnitState(0,texUnit);
				m_oldTexUnitMap.erase(m_oldTexUnitMap.begin());
			}
		}
Beispiel #6
0
void AppearanceGroup::publish(bool bSendFullContent, bool bSendPartialContent, SipDialogEvent* lContent)
{
   Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
         "AppearanceGroup::publish sending NOTIFY for: '%s'", mSharedUser.data());
   if (bSendFullContent)
   {
      // Both the Full and the Partial dialog-infos are sent to the SIP Subscribe Server.
      // The Partial will then be sent out right away and the Full
      // will be stored in the Subscribe Server to be sent on any initial
      // SUBSCRIBEs and re-SUBSCRIBEs.
      // Note that the full-state publish() must be done before the partial-state
      // publish() to avoid race conditions with regard to starting a new
      // subscription.
      // The Full content is constructed from all dialogs being managed by all appearances.
      UtlHashMapIterator itor(mAppearances);
      SipDialogEvent* lFullContent = new SipDialogEvent("full", mSharedUser.data());
      UtlHashMapIterator appitor(mAppearances);
      UtlString* handle;
      while ( (handle = dynamic_cast <UtlString*> (appitor())))
      {
         Appearance* inst = dynamic_cast <Appearance*> (appitor.value());
         inst->getDialogs(lFullContent);
      }
      lFullContent->buildBody();

      // Publish the content to the subscribe server.
      // Make a copy, because SipPublishContentMgr will own it.
      HttpBody* pHttpBody = new HttpBody(*(HttpBody*)lFullContent);

      getAppearanceAgent()->getEventPublisher().publish(
            mSharedUser.data(),
            DIALOG_SLA_EVENT_TYPE, //eventTypeKey
            DIALOG_EVENT_TYPE,     //eventType
            1, &pHttpBody,
            TRUE, TRUE);
      delete lFullContent;
   }

   if ( bSendPartialContent )
   {
      // The Partial content is the incoming message, with unique dialog ids.
      lContent->setState(STATE_PARTIAL);
      lContent->buildBody();
      HttpBody* pPartialBody = new HttpBody(*(HttpBody*)lContent);
      getAppearanceAgent()->getEventPublisher().publish(
            mSharedUser.data(),
            DIALOG_SLA_EVENT_TYPE, //eventTypeKey
            DIALOG_EVENT_TYPE,     //eventType
            1, &pPartialBody,
            FALSE, FALSE);
   }

}
		void TextureProjectorNode::removeScope( MeshNode* meshNode )
		{
			// While removing the Meshnode from the scope list, we need to restore the original TextureUnit. 
			if ( m_oldTexUnitMap.find(meshNode) != m_oldTexUnitMap.end() )
			{
				Appearance* appearance = 0;
				appearance = meshNode->getAppearance();
				if ( appearance )
				{
				  appearance->setTextureUnitState(0,m_oldTexUnitMap.find(meshNode)->second);
				}
				m_oldTexUnitMap.erase(meshNode);
			}
		}
Beispiel #8
0
void XMLScene::processAppearances(TiXmlElement* appearancesElement)
{
	TiXmlElement* element= appearancesElement->FirstChildElement("appearance");
	float ambient[4],diffuse[4],specular[4],emissive[4],shininess,sWrap,tWrap;
	string textureRef,id;
	Appearance* appearance;
	while(element!=NULL)
	{
		id=element->Attribute("id"); 
		read1Float("shininess",element,shininess);
		if(element->Attribute("textureref")!=NULL)
			textureRef=element->Attribute("textureref");
		else textureRef="";

		TiXmlElement* component = element ->FirstChildElement();

		while(component != NULL){
			if(component->Attribute("type")=="ambient"){
				read4Float("value", element, ambient[0], ambient[1], ambient[2],
					ambient[3]);}

			if(component->Attribute("type")=="diffuse"){
				read4Float("value", element, diffuse[0], diffuse[1], diffuse[2],
					diffuse[3]);}

			if(component->Attribute("type")=="specular"){
				read4Float("value", element, specular[0], specular[1], specular[2],
					specular[3]);
			}
			component=component->NextSiblingElement();
		}

		if(textureRef!=""){

			Texture* temp = Textures[textureRef];
			appearance = new Appearance(ambient,diffuse,specular,emissive,shininess,temp->getSWrap(),temp->getTWrap(),textureRef);

			appearance->setTextureWrap(appearance->getSWrap(),appearance->getTWrap());
			appearance->setTexture(sceneTextures[textureRef]);

		}
		else
			appearance = new Appearance(ambient,diffuse,specular,emissive,shininess,1,1,textureRef);

		appearances[id]=appearance;

		element=element->NextSiblingElement("appearance");
	}
}
Beispiel #9
0
void ProjectScene::processDisplayLists(Node* n, Node* graphRoot){
	
	
	if (n->getAppearance() != NULL)
		n->getAppearance()->apply();
	int numFilhos = n->getDescendentes().size();
	for (int i = 0; i < numFilhos; i++){
		this->processDisplayLists(n->getDescendenteIndex(i), graphRoot);
	}


	if (n->getDisplayList()){
		//printf("nome do no: %s\n", n->getId().c_str());
		
		printf("---------------------------\nfazer lista:\n");

		Appearance*  temp = new Appearance();
		if (n->getAppearance() == NULL){
			//printf("vai procurar aparencia aos ascendentes\n");
			temp = getClosestParentAppearance(graphRoot, n);
		}
		else temp = n->getAppearance();
		
		if (temp != NULL) temp->apply();

		n->setAparencia(temp);
		printf("	nome aparencia: %s\n",temp->getId());




		if (n->getDisplayListID() == -1){
			int id = glGenLists(1);
			n->setDisplayListID(id);

			n->setDisplayList(false); //serve para forçar o drawAux a desenhar 
									  //este nó como um nó "normal" (sem lista)

			glNewList(n->getDisplayListID(), GL_COMPILE);
				this->drawAux(n);
			glEndList();

			n->setDisplayList(true); //restaura a "true" após o processamento do nó

			printf("fim lista:\n---------------------------\n");
		}
	
	}
}
void SysPref::onAppearance()
{
	Appearance *frm;
	if (nextWidget != NULL && nextWidget->moduleName == "Appearance") {
		frm = (Appearance *) nextWidget;
	} else {
		frm = new Appearance();
	}
	stack->addWidget(frm);
	frm->show();
	stack->setCurrentIndex(1);
	discardPrevious();
	nextWidget = NULL;
	setWindowTitle(frm->moduleName);	
}
Beispiel #11
0
// Dump the object's internal state.
void AppearanceGroup::dumpState()
{
   // indented 4
   Os::Logger::instance().log(FAC_SAA, PRI_INFO,
                 "\t    AppearanceGroup %p mSharedUser = '******', mSubscriptionEarlyDialogHandle = '%s'",
                 this, mSharedUser.data(), mSubscriptionEarlyDialogHandle.data());

   UtlHashMapIterator itor3(mAppearances);
   UtlString* handle;
   while ((handle = dynamic_cast <UtlString*> (itor3())))
   {
      Appearance* ss = dynamic_cast <Appearance*> (itor3.value());
      ss->dumpState();
   }
}
	void AppearanceManager::assignNode( const std::string& nodeid )
	{ 
        _lastId = nodeid;

        if ( !getAppearance< Appearance * >( nodeid ) )
            _appearancesMap[ nodeid ] = std::vector< Appearance* >(0);

		Appearance* currentAppearance = _appearances[ _appearances.size() - 1 ];
		ForSide side = currentAppearance->getIsFront() ? FS_FRONT : FS_BACK;
		if ( dynamic_cast< Texture* >( currentAppearance ) && !getAppearance< Texture* >( nodeid, side ) ||
			 dynamic_cast< Material* >( currentAppearance ) && !getAppearance< Material* >( nodeid, side ) )
		{
            _appearancesMap[ nodeid ].push_back( currentAppearance );
			if ( _lastCoords ) { assignTexCoords( _lastCoords ); _lastId = ""; }
		}
	}
void
LinearGeometry::renderEdges(float alpha, Appearance& appearance)
{
  glBegin(GL_LINES);
  _register = appearance.getEdgeColor();
  glColor4f(_register[0], _register[1], _register[2],
            _register[3] * alpha * appearance.getModifierAlpha());
  int numberEdges = getNumberEdges();
  float*** edges = getEdges();
  for (int i = 0; i < numberEdges; i++) {
    _register = edges[i][0];
    glVertex3f(_register[0], _register[1], _register[2]);
    _register = edges[i][1];
    glVertex3f(_register[0], _register[1], _register[2]);
  }
  glEnd();
}
void Appearance::setOwner(Object* owner)
{
	//-- keep track of owner object.
	m_owner = owner;

	// DBE - This was added to mimic the behavior of when the appearance-to-world 
	// transform was stored in Object instead of Appearance.
	if (owner)
	{
		Appearance *ownerAppearance = owner->getAppearance();
		if (!ownerAppearance)
		{
			setTransform_w(owner->getTransform_o2w());
		}
		else if (ownerAppearance!=this)
		{
			setTransform_w(ownerAppearance->getTransform_w());
		}
	}

	//-- retrieve customization data for new owner
	CustomizationData *customizationData = 0;

	if (owner)
	{
		// get the property
		CustomizationDataProperty *const property = safe_cast<CustomizationDataProperty*>(owner->getProperty(CustomizationDataProperty::getClassPropertyId()));
		if (property)
		{
			// retrieve the customization data from the property
			customizationData = property->fetchCustomizationData();
		}
	}

	//-- set the CustomizationData
	setCustomizationData(customizationData);

	//-- release local reference
	if (customizationData)
		customizationData->release();

	//-- clear the rendered frame number
	m_renderedFrameNumber = 0;
}
		void TextureProjectorNode::addScope( MeshNode* meshNode )
		{
			// Save TextureUnit of this meshNode, so that it can be recovered while removing this meshnode from the Scope.
			if( meshNode )
			{
				Appearance* appearance = 0;
				appearance = meshNode->getAppearance();
				TextureUnitState *texUnit = 0;
				if ( appearance )
				{
					// Save the old texture unit
					texUnit = appearance->getTextureUnitState(0);
					// Set the projector Texture Unit
					appearance->setTextureUnitState(0,projectorTexUnitState);
				}
				//if(texUnit)
				m_oldTexUnitMap[meshNode] = texUnit;
			}
		}
Beispiel #16
0
void YafFile::processAppearances(TiXmlElement* appearancesElement)
{
	TiXmlElement* element= appearancesElement->FirstChildElement("appearance");
	float ambient[4],diffuse[4],specular[4],emissive[4],shininess,sWrap,tWrap;
	string textureRef,id;
	while(element!=NULL)
	{
		id=element->Attribute("id"); 
		read4Float("ambient", element, ambient[0], ambient[1], ambient[2],
			ambient[3]);
		read4Float("emissive", element, emissive[0], emissive[1], emissive[2],
			emissive[3]);
		read4Float("diffuse", element, diffuse[0], diffuse[1], diffuse[2],
			diffuse[3]);
		read4Float("specular", element, specular[0], specular[1], specular[2],
			specular[3]);
		element->QueryFloatAttribute("shininess",&shininess);
		if(element->Attribute("texlength_t")!=NULL)
			element->QueryFloatAttribute("texlength_t",&tWrap);
		else tWrap=0;
		if(element->Attribute("texlength_s")!=NULL)
			element->QueryFloatAttribute("texlength_s",&sWrap);
		else sWrap=0;
		if(element->Attribute("textureref")!=NULL)
			textureRef=element->Attribute("textureref");
		else textureRef="";
		Appearance* appearance = new Appearance(ambient,diffuse,specular,emissive,shininess,sWrap,tWrap,textureRef);

		if(textureRef!="")
		{
			appearance->setTextureWrap(tWrap,sWrap);
			appearance->setTexture(sceneTextures[textureRef]);
		}
		appearances[id]=appearance;
		element=element->NextSiblingElement("appearance");
	}
}
Beispiel #17
0
Appearance* AppearanceGroup::findAppearance(UtlString app)
{
   Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                 "AppearanceGroup::findAppearance mSharedUser = '******', looking for '%s'",
                 mSharedUser.data(), app.data());
   Appearance *pApp = NULL;
   UtlHashMapIterator itor(mAppearances);
   UtlString* handle;
   while ( !pApp && (handle = dynamic_cast <UtlString*> (itor())))
   {
      Appearance* ss = dynamic_cast <Appearance*> (itor.value());
      if ( app == ss->getDialogHandle()->data() )
      {
         pApp = ss;
      }
   }
   if (pApp == NULL)
   {
      Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                    "AppearanceGroup::findAppearance mSharedUser = '******', looking for '%s': not found",
                    mSharedUser.data(), app.data());
   }
   return pApp;
}
Beispiel #18
0
/// Process an incoming NOTIFY from an Appearance.  Always sends a response.
void AppearanceGroup::handleNotifyRequest(const UtlString* dialogHandle,
                                          const SipMessage* msg)
{
   SipMessage response;
   Appearance* pThisAppearance = findAppearance(*dialogHandle);
   if ( !pThisAppearance )
   {
      UtlString swappedDialogHandle;
      mAppearanceGroupSet->swapTags(*dialogHandle, swappedDialogHandle);
      pThisAppearance = findAppearance(swappedDialogHandle);
      if ( !pThisAppearance )
      {
         // should never happen, since the NOTIFY was sent straight to the Appearance
         Os::Logger::instance().log(FAC_SAA, PRI_WARNING,
               "AppearanceGroup::handleNotifyRequest: ignoring NOTIFY from unknown subscription, dialogHandle %s",
               dialogHandle->data());
         response.setInterfaceIpPort(msg->getInterfaceIp(), msg->getInterfacePort());
         response.setResponseData(msg, 481, "Subscription does not exist");
         getAppearanceAgent()->getServerUserAgent().send(response);
         return;
      }
   }
   UtlString contactUri = pThisAppearance->getUri()->data();

   // check that event type is supported
   UtlString eventType;
   msg->getEventField(eventType);
   if (eventType != SLA_EVENT_TYPE)
   {
      Os::Logger::instance().log(FAC_SAA, PRI_INFO,
                    "AppearanceGroup::handleNotifyRequest: ignoring NOTIFY(%s): not an SLA event", eventType.data());
      response.setOkResponseData(msg, NULL);
      getAppearanceAgent()->getServerUserAgent().send(response);
      return;
   }

   // Get the NOTIFY content.
   const char* content;
   ssize_t l;
   const HttpBody* body = msg->getBody();
   if (body)
   {
      body->getBytes(&content, &l);
   }
   else
   {
      Os::Logger::instance().log(FAC_SAA, PRI_WARNING,
            "AppearanceGroup::handleNotifyRequest: could not get NOTIFY content, dialogHandle %s",
            dialogHandle->data());
      response.setInterfaceIpPort(msg->getInterfaceIp(), msg->getInterfacePort());
      response.setResponseData(msg, 493, "Undecipherable");
      getAppearanceAgent()->getServerUserAgent().send(response);
      return;
   }
   SipDialogEvent* lContent = new SipDialogEvent(content);

   UtlString state;
   UtlString entity;
   lContent->getState(state);
   lContent->getEntity(entity);

   UtlString dialogState = STATE_TERMINATED;
   UtlString event;
   UtlString code;
   UtlString appearanceId;

   if (state == STATE_TERMINATED)
   {
      // probably not needed now that SipSubscribeClient checks for NOTIFY with terminated state
      // our subscription to this Appearance has terminated.
      Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                    "AppearanceGroup::handleNotifyRequest: subscription to %s has been terminated",
                    contactUri.data());
      // terminate any non-held dialogs? or all dialogs?
   }

   Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                 "AppearanceGroup::handleNotifyRequest: %s update from %s",
                 state.data(), contactUri.data());

   // Assign each dialog a globally-unique ID, if not done yet
   UtlSListIterator* itor = lContent->getDialogIterator();
   Dialog* pDialog;
   while ( (pDialog = dynamic_cast <Dialog*> ((*itor)())) )
   {
      UtlString dialogId;
      UtlString uniqueDialogId;
      UtlString rendering;
      pDialog->getDialogId(dialogId);
      pDialog->getLocalParameter("x-line-id", appearanceId);
      pDialog->getLocalParameter("+sip.rendering", rendering);
      pDialog->getState(dialogState, event, code);

      // Ignore calls with no appearanceId -  these are considered "exclusive".
      // (e.g. MoH calls are private to the set involved)
      // These dialogs are not forwarded on to other sets in either partial or full updates.
      if ( appearanceId == "" )
      {
         Os::Logger::instance().log(FAC_SAA, PRI_DEBUG, "AppearanceGroup::handleNotifyRequest skipping call with no appearance info");
         delete lContent->removeDialog(pDialog);
         continue;
      }

      if ( dialogId.contains("@@") )
      {
         // this is one of our identifiers already
         uniqueDialogId = dialogId;
      }
      else
      {
         // make a guaranteed unique dialog id, by
         // prepending to each id value the call-id of the subscription
         // from which the dialog event was obtained, with "@@" as a separator
         msg->getCallIdField(&uniqueDialogId);
         uniqueDialogId.append("@@");
         uniqueDialogId.append(dialogId);
         pDialog->setDialogId(uniqueDialogId);
      }
      Os::Logger::instance().log(FAC_SAA, PRI_INFO,
                    "AppearanceGroup::handleNotifyRequest: "
                    "%s update from %s: dialogId %s, x-line-id %s, state %s(%s)",
                    state.data(), contactUri.data(), uniqueDialogId.data(),
                    appearanceId.data(), dialogState.data(), rendering.data());
   }
   delete itor;

   // Check to see if this appearance (of the Appearance) is available
   bool okToProceed = true;
   if ( state == "partial" && dialogState == "trying" )
   {
      UtlHashMapIterator appitor(mAppearances);
      UtlString* handle;
      while ( okToProceed && (handle = dynamic_cast <UtlString*> (appitor())))
      {
         Appearance* inst = dynamic_cast <Appearance*> (appitor.value());
         okToProceed = !inst->appearanceIdIsSeized(appearanceId);
      }
   }

   bool bSendPartialContent = false;
   bool bSendFullContent = false;

   // Send the response.
   if (okToProceed)
   {
      response.setOkResponseData(msg, NULL);
   }
   else
   {
      Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                    "AppearanceGroup::handleNotifyRequest '%s' appearanceId %s is busy",
                    entity.data(), appearanceId.data());
      response.setInterfaceIpPort(msg->getInterfaceIp(), msg->getInterfacePort());
      response.setResponseData(msg, 409, "Conflict");
   }
   getAppearanceAgent()->getServerUserAgent().send(response);

   if (okToProceed)
   {
      if (lContent)
      {
         // Send the content to the proper Appearance instance, so it can
         // save these dialogs, and set flag to indicate whether they should be sent in partial update
         bSendPartialContent = pThisAppearance->updateState(lContent, bSendFullContent);
      }
      // Publish full and partial updates to the SipPublishContentMgr
      publish(bSendFullContent, bSendPartialContent, lContent);
   }

   // Adjust the expiration of the subscription if the set has the line "seized"
   // and return it to the longer default if it does not.
   UtlHashMapIterator appitor(mAppearances);
   UtlString* handle;
   while ( (handle = dynamic_cast <UtlString*> (appitor())))
   {
      Appearance* inst = dynamic_cast <Appearance*> (appitor.value());

      // if set has line seized, use short subscription timer
      if ( inst->appearanceIsBusy() )
      {
         inst->setResubscribeInterval(true);
      }
      else
      {
         inst->setResubscribeInterval(false);
      }
   }

   if (lContent)
   {
      delete lContent;
   }
}
Beispiel #19
0
// Update the subscriptions we maintain to agree with the current contact state
void AppearanceGroup::updateSubscriptions()
{
   Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                 "AppearanceGroup::updateSubscriptions mUri = '%s'",
                 mSharedUser.data());

   // First, scan mSubscriptions to construct a list of all the
   // call-id/contact combinations.
   // (If a phone reboots and starts registering with a different Call-Id,
   // the call-id/contact combination will be different even if the contact
   // URI is unchanged.  So the new registration will appear to be different
   // to this machinery, and it will establish a new Appearance to
   // the contact URI.  This compensates for the fact that the previous
   // Appearance to the contact URI appears to the Appearance Agent to be
   // working but the phone no longer knows of the subscription.  The
   // reg events will eventually terminate the old combination and we
   // will delete its Appearance.)
   UtlHashBag callid_contacts;

   UtlHashMapIterator subs_itor(mSubscriptions);
   while (subs_itor())
   {
      if (Os::Logger::instance().willLog(FAC_SAA, PRI_DEBUG))
      {
         Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                       "AppearanceGroup::updateSubscriptions subscription '%s'",
                       (dynamic_cast <UtlString*> (subs_itor.key()))->data());
      }
      UtlHashMap* contact_state =
         dynamic_cast <UtlHashMap*> (subs_itor.value());
      Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                    "AppearanceGroup::updateSubscriptions contact_state = %p",
                    contact_state);
      UtlHashMapIterator contact_itor(*contact_state);
      while (contact_itor())
      {
         UtlString* contact =
            dynamic_cast <UtlString*> (contact_itor.value());
         if (Os::Logger::instance().willLog(FAC_SAA, PRI_DEBUG))
         {
            Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                          "AppearanceGroup::updateSubscriptions contact id '%s', Call-Id/URI '%s'",
                          (dynamic_cast <UtlString*> (contact_itor.key()))->data(),
                          contact->data());
         }
         // Check if the contact is already in callid_contacts.
         if (!callid_contacts.find(contact))
         {
            // If not, add it.
            UtlString* c = new UtlString(*contact);
            callid_contacts.insert(c);
            Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                          "AppearanceGroup::updateSubscriptions contact '%s' added", c->data());
         }
      }
   }

   // Now that we have a clean list of callid_contacts, update
   // Appearances to match it.

   // If we both terminate subscriptions and create subscriptions,
   // wait a short while to allow the terminations to complete.  This
   // should not be necessary, but it makes life easier on Polycom
   // phones which (at this time) cannot support two subscriptions at
   // a time, and if the termination of the old subscription arrives
   // after the initiation of the new subscription, the new
   // subscription will be lost.
   // This variable tracks whether such a wait is needed before a
   // subscription is started.
   bool subscription_ended_but_no_wait_done_yet = false;

   // Iterate through the list of Appearances and remove any that aren't
   // in callid_contacts.
   {
      UtlHashMapIterator itor(mAppearances);
      UtlString* ss;
      while ((ss = dynamic_cast <UtlString*> (itor())))
      {
         if (!callid_contacts.find(ss))
         {
            Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                          "AppearanceGroup::updateSubscriptions deleting subscription for '%s' in mUri = '%s'",
                          ss->data(), mSharedUser.data());
            // Terminate all dialogs for this Appearance, then publish - before we delete it
            bool bContentChanged = false;
            SipDialogEvent* lPartialContent = new SipDialogEvent("partial", mSharedUser.data());
            Appearance* inst = dynamic_cast <Appearance*> (itor.value());
            bContentChanged = inst->terminateDialogs(true); // terminate all dialogs
            inst->getDialogs(lPartialContent);
            if (bContentChanged)
            {
               lPartialContent->buildBody();
               publish(true, true, lPartialContent);
               delete lPartialContent;
            }
            mAppearances.destroy(ss);
            subscription_ended_but_no_wait_done_yet = true;
         }
         else
         {
            Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                          "AppearanceGroup::updateSubscriptions found subscription for '%s' in mUri = '%s'",
                          ss->data(), mSharedUser.data());
         }
      }
   }

   // Iterate through callid_contacts and add an Appearance for
   // any that aren't in mAppearances.
   // We don't limit the number of additions here, as the size of
   // callid_contacts is guarded by the tests in notifyEventCallback.
   {
      UtlHashBagIterator itor(callid_contacts);
      UtlString* callid_contact;
      while ((callid_contact = dynamic_cast <UtlString*> (itor())))
      {
         if (!mAppearances.find(callid_contact))
         {
            // If we both terminate subscriptions and create subscriptions,
            // wait a short while to allow the terminations to complete.
            if (SUBSCRIPTION_WAIT > 0)
            {
               if (subscription_ended_but_no_wait_done_yet)
               {
                  Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                                "AppearanceGroup::updateSubscriptions waiting for %d msec",
                                SUBSCRIPTION_WAIT);
                  OsTask::delay(SUBSCRIPTION_WAIT);
                  subscription_ended_but_no_wait_done_yet = false;
               }
            }

            Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                          "AppearanceGroup::updateSubscriptions adding subscription for '%s' in mUri = '%s'",
                          callid_contact->data(), mSharedUser.data());
            // Get the contact URI into a UtlString.
            UtlString uri(callid_contact->data() +
                          callid_contact->index(';') +
                          1);
            mAppearances.insertKeyAndValue(new UtlString(*callid_contact),
                                           new Appearance(getAppearanceAgent(), this,  uri)
                                           );
         }
         else
         {
            Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                          "AppearanceGroup::updateSubscriptions using existing subscription for '%s' in mUri = '%s'",
                          callid_contact->data(), mSharedUser.data());
         }
      }
   }

   // Free callid_contacts.
   callid_contacts.destroyAll();
}
Beispiel #20
0
XMLScene::XMLScene(char *filename,CGFapplication* app, Game* game, int connecting)
{
	seleccao = 0;
	tempoJogada = 8;
	ultimoTempo = -1;
	needConnection = connecting;
	inMovie = false;
	this->octi=game;
	this->app=app;
	
	glMatrixMode(GL_MODELVIEW); 

	GLfloat transformationMatrix[16];

	// Read XML from file
	//map<string,Node*> graph;

	doc=new TiXmlDocument( filename );
	bool loadOkay = doc->LoadFile();

	if ( !loadOkay )
	{
		printf( "Could not load file '%s'. Error='%s'. Exiting.\n", filename, doc->ErrorDesc() );
		system("pause");
		exit( 1 );
	}
	printf("Loading Files...\n");

	TiXmlElement* yafElement= doc->FirstChildElement( "yaf" );

	if (yafElement == NULL)
	{
		printf("Main yaf block element not found! Exiting!\n");
		exit(1);
	}

	globalsElement = yafElement->FirstChildElement( "globals" );

	scene = new YAFScene();
	scene->nextTheme = 1;

	//--------- Animations Parsing -----------
	animationsElement = yafElement->FirstChildElement( "animations" );

	if (animationsElement == NULL)
		printf("Animations block not found!\n");
	else
	{
		printf("Processing Animations...\n");
		TiXmlElement* singleAnimationElement = animationsElement->FirstChildElement("animation");

		while(singleAnimationElement){

			//printf("A new animation was found!\n");

			string id, type;
			float span;

			if (singleAnimationElement->QueryFloatAttribute("span",&span)==TIXML_SUCCESS &&
				singleAnimationElement->Attribute("id") != NULL &&
				singleAnimationElement->Attribute("type") != NULL)
			{
				id = singleAnimationElement->Attribute("id");
				type = singleAnimationElement->Attribute("type");

				/*
				printf("\tAnimation attributes:\n");
				printf("\t\t id: %s\n", id.c_str());
				printf("\t\t type: %s\n", type.c_str());
				printf("\t\t span: %f\n", span);
				*/
				if(type=="linear"){
					
					TiXmlElement* controlPointElement = singleAnimationElement->FirstChildElement("controlpoint");
					vector<ControlPoint> auxPoints;
					while(controlPointElement){
						float x,y,z;
						if (controlPointElement->QueryFloatAttribute("xx",&x)==TIXML_SUCCESS &&
							controlPointElement->QueryFloatAttribute("yy",&y)==TIXML_SUCCESS &&
							controlPointElement->QueryFloatAttribute("zz",&z)==TIXML_SUCCESS)
						{

						ControlPoint pontoAux(x,y,z);
						auxPoints.push_back(pontoAux);
						}
						controlPointElement = controlPointElement->NextSiblingElement();
					}

					Animation* aux = new LinearAnimation(id,span,auxPoints);
					scene->animationsComp.insert(pair<string,Animation*>(id,aux));
				}
				else{
					cout << "Other type different from Linear\n" << endl;
				}

										
			}
			else printf("Error parsing Animation Element\n");

			singleAnimationElement = singleAnimationElement->NextSiblingElement();
		}
	}

	//--------- Globals Parsing -----------
	if (globalsElement == NULL)
		printf("Globals block not found!\n");
	else
	{
		printf("Processing Globals...\n");

		string background, drawmode, cullface, shading, cullorder;

		if (globalsElement->Attribute("background")!=NULL &&
			globalsElement->Attribute("drawmode") != NULL &&
			globalsElement->Attribute("cullface") != NULL &&
			globalsElement->Attribute("shading") != NULL &&
			globalsElement->Attribute("cullorder") != NULL)
		{
			// TODO: Verificacoes dos valores de entrada

			background=globalsElement->Attribute("background");
			float a,b,c,d;
			sscanf_s(background.c_str(),"%f %f %f %f", &a, &b, &c, &d);
			scene->globalsComp.setBackground(a,b,c,d);
			//printf("\tBackground: %s \n", background.c_str());

			drawmode=globalsElement->Attribute("drawmode");
			scene->globalsComp.setDrawmode(drawmode);
			//printf("\tDrawmode: %s \n", drawmode.c_str());

			cullface=globalsElement->Attribute("cullface");
			scene->globalsComp.setCullface(cullface);
			//printf("\tCullface: %s \n", cullface.c_str());

			cullorder=globalsElement->Attribute("cullorder");
			scene->globalsComp.setCullorder(cullorder);
			//printf("\tCullorder: %s \n", cullorder.c_str());

			shading=globalsElement->Attribute("shading");
			scene->globalsComp.setShading(shading);
			//printf("\tShading: %s \n", shading.c_str());

		}
		else
			printf("Error parsing background\n");
	}

	//--------- Cameras Parsing -----------
	camerasElement = yafElement->FirstChildElement( "cameras" );

	if (camerasElement == NULL)
		printf("Cameras block not found!\n");
	else
	{
		printf("Processing Cameras...\n");

		string initial;
		if (camerasElement->Attribute("initial")!=NULL)
		{
			// TODO: Verificacoes dos valores de entrada
			initial=camerasElement->Attribute("initial");
			//printf("\tInitial: %s \n", initial.c_str());
		}

		TiXmlElement* cameraElement = camerasElement->FirstChildElement();
		while(cameraElement){

			if ((string)cameraElement->Value() == "perspective")
			{
				float near;
				float far;
				float angle;

				string pos,target;
				string id;

				Perspective* perspectiveAux = new Perspective();
				perspectiveAux->toanimate = false;

				if (cameraElement->QueryFloatAttribute("near",&near)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("far",&far)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("angle",&angle)==TIXML_SUCCESS &&
					cameraElement->Attribute("id") != NULL
					){
						id = cameraElement->Attribute("id");
						pos = cameraElement->Attribute("pos");
						target = cameraElement->Attribute("target");

						if(initial==id)
							perspectiveAux->setCInitial(true);
						//printf("\tPerspective attributes:\n");
						//printf("\t\tnear: %f far: %f angle: %f \n", near, far, angle);
						//printf("\t\tpos: %s target: %s id: %s\n", pos.c_str(), target.c_str(),id.c_str());

						float pa,pb,pc;
						float ta,tb,tc;
						sscanf_s(pos.c_str(),"%f %f %f", &pa, &pb, &pc);
						sscanf_s(target.c_str(),"%f %f%f", &ta, &tb, &tc);
						perspectiveAux->setX(pa);
						perspectiveAux->setY(pb);
						perspectiveAux->setZ(pc);

						perspectiveAux->setCTarget(ta,tb,tc);
						perspectiveAux->setCPrimary(id, near, far);
						perspectiveAux->setCAngle(angle);

						if(initial == perspectiveAux->getid()){
							perspectiveAux->setInitial(true);
						}
						else perspectiveAux->setInitial(false);

						scene->camerasComp.push_back(perspectiveAux);
				}
				else
					printf("Error parsing Perspective Element\n");
			}
			else if ((string)cameraElement->Value() == "ortho")
			{
				float near,far,left,right,top,bottom;
				string id;

				Ortho* orthoAux = new Ortho();

				if (cameraElement->QueryFloatAttribute("near",&near)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("far",&far)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("left",&left)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("right",&right)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("top",&top)==TIXML_SUCCESS &&
					cameraElement->QueryFloatAttribute("bottom",&bottom)==TIXML_SUCCESS &&
					cameraElement->Attribute("id") != NULL
					){
						id = cameraElement->Attribute("id");
						/*
						printf("\tOrtho attributes:\n");
						printf("\t\tnear: %f, far: %f, angle: %f \n", near, far, left);
						printf("\t\tpos: %f, target: %f, bottom: %f\n", right, top, bottom);
						printf("\t\tid: %s\n", id.c_str());
						*/
						if(initial==id)
							orthoAux->setCInitial(true);
						orthoAux->setCPrimary(id,near,far);
						orthoAux->setCFloatValues(left,right,top,bottom);


						if(initial == orthoAux->getid()){
							orthoAux->setInitial(true);
						}
						else orthoAux->setInitial(false);

						scene->camerasComp.push_back(orthoAux);

				}
				else
					printf("Error parsing Ortho Element\n");
			}
			else
				printf("Invalid Camera type.\n");

			cameraElement = cameraElement->NextSiblingElement();
		}
	}

	//--------- Lighting Parsing -----------
	lightingElement = yafElement->FirstChildElement( "lighting" );

	if (lightingElement == NULL)
		printf("Lighting block not found!\n");
	else
	{
		printf("Processing Lights...\n");

		string doublesided, local, enabled; //boolean
		string ambient;
		if (lightingElement->Attribute("doublesided") != NULL &&
			lightingElement->Attribute("local") != NULL &&
			lightingElement->Attribute("enabled") != NULL &&
			lightingElement->Attribute("ambient") != NULL)
		{
			// TODO: Verificacoes dos valores de entrada
			ambient = lightingElement->Attribute("ambient");
			doublesided = lightingElement->Attribute("doublesided");
			local = lightingElement->Attribute("local");
			enabled = lightingElement->Attribute("enabled");

			float x,y,z,p;


			Lighting* lightingConfig = new Lighting();

			if(doublesided == "true") lightingConfig->setDoublesided(true);
			else lightingConfig->setDoublesided(false);

			if(local == "true") lightingConfig->setLocal(true);
			else lightingConfig->setLocal(false);

			//if(enabled == "true") lightingConfig->setEnabled(true);
			//else lightingConfig->setEnabled(false);

			if(enabled== "true")
			{
				sscanf_s(ambient.c_str(),"%f %f %f %f",&x,&y,&z,&p);
			}
			else
			{
				x=0;
				y=0;
				z=0;
				p=0;
			}

			lightingConfig->setLightingAmbient(x,y,z,p);

			scene->setLightConfig(lightingConfig);
			/*
			printf("\tDoublesided: %s \n", doublesided.c_str());
			printf("\tLocal: %s \n", local.c_str());
			printf("\tEnabled: %s \n", enabled.c_str());
			printf("\tAmbient: %s \n", ambient.c_str());
			*/
		}

		int lightId = GL_LIGHT0;
		TiXmlElement* lightElement = lightingElement->FirstChildElement();
		while(lightElement){
			lightId++;
			//OMNI
			if ((string)lightElement->Value() == "omni"){

				string oenabled; //boolean
				string id;
				string location, oambient, odiffuse, ospecular;

				if (lightElement->Attribute("id") != NULL &&
					lightElement->Attribute("enabled") != NULL &&
					lightElement->Attribute("location") != NULL &&
					lightElement->Attribute("ambient") != NULL &&
					lightElement->Attribute("diffuse") != NULL &&
					lightElement->Attribute("specular") != NULL)
				{

					string location =  lightElement->Attribute("location");
					float omniLocation[4];
					omniLocation[3] = 1.0;
					sscanf_s(location.c_str(),"%f %f %f", &omniLocation[0], &omniLocation[1], &omniLocation[2]);

					float* dir = (float*) 0;
					Omni* omniAux = new Omni(lightId, omniLocation, NULL);

					id = lightElement->Attribute("id");
					oenabled = lightElement->Attribute("enabled");
					oambient = lightElement->Attribute("ambient");
					odiffuse = lightElement->Attribute("diffuse");
					ospecular = lightElement->Attribute("specular");

					omniAux->setIdS(id);

					omniAux->setIdI(lightId);

					if(oenabled == "true")  omniAux->enable();
					else omniAux->disable();

					float ambientArr[4];
					sscanf_s(oambient.c_str(),"%f %f %f %f", &ambientArr[0], &ambientArr[1], &ambientArr[2], &ambientArr[3]);
					omniAux->setAmbient(ambientArr);

					float specularArr[4];
					sscanf_s(ospecular.c_str(),"%f %f %f %f", &specularArr[0], &specularArr[1], &specularArr[2], &specularArr[3]);
					omniAux->setSpecular(specularArr);

					float diffuseArr[4];
					sscanf_s(odiffuse.c_str(),"%f %f %f %f", &diffuseArr[0], &diffuseArr[1], &diffuseArr[2], &diffuseArr[3]);
					omniAux->setDiffuse(diffuseArr);

					scene->lightsComp.push_back(omniAux);

				}
				else
					printf("Error parsing Omni Element\n");
			}
			else if ((string)lightElement->Value() == "spot")
			{
				string senabled; // boolean
				float angle, exponent;
				string id, direction;

				if (lightElement->QueryFloatAttribute("angle",&angle)==TIXML_SUCCESS &&
					lightElement->QueryFloatAttribute("exponent",&exponent)==TIXML_SUCCESS &&
					lightElement->Attribute("direction") != NULL &&
					lightElement->Attribute("enabled") != NULL &&
					lightElement->Attribute("ambient") != NULL &&
					lightElement->Attribute("diffuse") != NULL &&
					lightElement->Attribute("specular") != NULL &&
					lightElement->Attribute("id") != NULL &&
					lightElement->Attribute("location") !=NULL
					){

						string location;
						location = lightElement->Attribute("location");
						float locationArr[4];
						locationArr[3] = 1.0;
						sscanf_s(location.c_str(),"%f %f %f", &locationArr[0], &locationArr[1], &locationArr[2]);

						Spot* spotAux = new Spot(lightId, locationArr, NULL);

						id = lightElement->Attribute("id");
						spotAux->setIdS(id);
						spotAux->setIdI(lightId);

						direction = lightElement->Attribute("direction");
						float directionSpot[3];
						sscanf_s(direction.c_str(),"%f %f %f", &directionSpot[0], &directionSpot[1], &directionSpot[2]);
						spotAux->setSDirection(directionSpot);

						senabled = lightElement->Attribute("enabled");
						if(senabled == "true") spotAux->enable();
						else spotAux->disable();


						spotAux->setSExponent(exponent);
						spotAux->setSAngle(angle);
						spotAux->setAngle(angle);

						string sspecular, sdiffuse, sambient;
						sspecular = lightElement->Attribute("specular");
						sdiffuse = lightElement->Attribute("diffuse");
						sambient = lightElement->Attribute("ambient");

						float specular[4];
						sscanf_s(sspecular.c_str(),"%f %f %f %f", &specular[0], &specular[1], &specular[2], &specular[3]);
						spotAux->setSpecular(specular);

						float diffuse[4];
						sscanf_s(sdiffuse.c_str(),"%f %f %f %f", &diffuse[0], &diffuse[1], &diffuse[2], &diffuse[3]);
						spotAux->setDiffuse(diffuse);

						float ambient[4];
						sscanf_s(sambient.c_str(), "%f %f %f %f", &ambient[0], &ambient[1], &ambient[2], &ambient[3]); 
						spotAux->setAmbient(ambient);

						scene->lightsComp.push_back(spotAux);

				}
				else
					printf("Error parsing Spot Element\n");
			}
			else
				printf("Invalid Light type\n");

			lightElement = lightElement->NextSiblingElement();
		}
	}


	//--------- Textures Parsing -----------
	texturesElement = yafElement->FirstChildElement( "textures" );

	if (texturesElement == NULL)
		printf("Textures block not found!\n");
	else
	{
		printf("Processing Textures...\n");
		TiXmlElement* textureElement = texturesElement->FirstChildElement("texture");
		while(textureElement)
		{
			string id, file;
			if (textureElement->Attribute("id") != NULL &&
				textureElement->Attribute("file") != NULL
				){
					id = textureElement->Attribute("id");
					file = textureElement->Attribute("file");
					//printf("\tTexture attributes:\n");
					//printf("\t\tId: %s\n\t\tFile: %s\n", id.c_str(), file.c_str());

					//Texture* textureAux = new Texture();
					//ofstream fin("ola.txt");
					//fin.close();
					file =  file;
					Texture* textureAux = new Texture(file);
					textureAux->setTId(id);
					textureAux->setTPath(file);
					scene->texturesComp.push_back(textureAux);
			}
			else
				printf("Error parsing Texture Element\n");

			textureElement = textureElement->NextSiblingElement();
		}
	}

	//--------- Appearances Parsing -----------
	appearancesElement = yafElement->FirstChildElement( "appearances" );

	if (appearancesElement == NULL)
		printf("Appearances block not found!\n");
	else
	{
		printf("Processing Appearances...\n");
		TiXmlElement* appearanceElement = appearancesElement->FirstChildElement("appearance");
		while (appearanceElement)
		{

			Appearance* ap = new Appearance();
			string id, textureref;
			
			string emissiveS, ambientS, diffuseS, specularS;
			float shininess, texlength_s, texlength_t;

			if (appearanceElement->QueryFloatAttribute("shininess",&shininess)==TIXML_SUCCESS &&
				appearanceElement->Attribute("id") != NULL &&
				appearanceElement->Attribute("emissive") != NULL &&
				appearanceElement->Attribute("ambient") != NULL &&
				appearanceElement->Attribute("diffuse") != NULL &&
				appearanceElement->Attribute("specular") != NULL
				){
					id = appearanceElement->Attribute("id");
					ap->setIdS(id);

					emissiveS = appearanceElement->Attribute("emissive");
					float Aemissive[4];
					sscanf_s(emissiveS.c_str(),"%f %f %f %f", &Aemissive[0], &Aemissive[1], &Aemissive[2], &Aemissive[3]);
					ap->setEmissive(Aemissive);

					ambientS = appearanceElement->Attribute("ambient");
					float Aambient[4];
					sscanf_s(ambientS.c_str(),"%f %f %f %f", &Aambient[0], &Aambient[1], &Aambient[2], &Aambient[3]);
					ap->setAmbient(Aambient);

					diffuseS = appearanceElement->Attribute("diffuse");
					float Adiffuse[4];
					sscanf_s(diffuseS.c_str(),"%f %f %f %f", &Adiffuse[0], &Adiffuse[1], &Adiffuse[2], &Adiffuse[3]);
					ap->setDiffuse(Adiffuse);

					specularS = appearanceElement->Attribute("specular");
					float Aspecular[4];
					sscanf_s(specularS.c_str(),"%f %f %f %f", &Aspecular[0], &Aspecular[1], &Aspecular[2], &Aspecular[3]);
					ap->setSpecular(Aspecular);


					if(appearanceElement->Attribute("textureref") != NULL)
					{
						if(appearanceElement->QueryFloatAttribute("texlength_s",&texlength_s)==TIXML_SUCCESS &&
							appearanceElement->QueryFloatAttribute("texlength_t",&texlength_t)==TIXML_SUCCESS)
						{

							textureref = appearanceElement->Attribute("textureref");
							ap->setTextureReference(textureref);
							//ap->setTexture(textureref);

							ap->setTextureWrap(texlength_s,texlength_t);

							ap->setShininess(shininess);

							int itTexturesComp = 0;
							std::vector<Texture*>::iterator it = scene->texturesComp.begin();
							for(it; it != scene->texturesComp.end(); it++){
								if(textureref == scene->texturesComp.at(itTexturesComp)->getTId()){
									ap->setTexture((*it));
								}
								itTexturesComp++;
							}
						}
					}

					//printf("\tApearance attributes:\n");
					//printf("\t\tId: %s \n\t\tEmissive: %s \n\t\tAmbient: %s\n", id.c_str(), emissiveS.c_str(), ambientS.c_str());
					//printf("\t\tDiffuse: %s \n\t\tSpecular: %s \n\t\tTextureRef: %s \n\t\tShininess: %f\n", diffuseS.c_str(), specularS.c_str(), textureref.c_str(), shininess);
					if(textureref.length()==0){}
						//printf("\t\tTexLength S: %f \n\t\tTexLength T: %f\n", texlength_s, texlength_t);

					scene->appearancesComp.push_back(ap);

			}
			else
				printf("Error parsing Appearance Element\n");

			appearanceElement = appearanceElement->NextSiblingElement();

		}
	}

	//--------- Graph Parsing -----------
	graphElement = yafElement->FirstChildElement( "graph" );
	scene->rootid=graphElement->Attribute("rootid");

	if (graphElement == NULL)
		printf("Graph block not found!\n");
	else
	{
		TiXmlElement *node=graphElement->FirstChildElement("node");
		string id,picking;
		string flagDL;
		while (node)
		{
			Node *no = new Node();

			if(node->Attribute("id") != NULL){
				id = node->Attribute("id");
				no->setId(id);


				//printf("Node: %s\n", id.c_str());
			}
			if(node->Attribute("pickingid") != NULL){
				picking = node->Attribute("pickingid");
				int idInt = atoi(picking.c_str());
				no->setPicking(idInt);
				//printf("\t %s\n", picking.c_str());

				
				std::vector<Appearance*>::iterator it = scene->appearancesComp.begin();
				for(it; it != scene->appearancesComp.end(); it++){
					if((*it)->getIdS() == "appSelected"){
						no->highlighted = (*it);
					}
				}  
				

				octi->boardElements[idInt] = no;
			}
			else no->setPicking(-1);

			if(node->Attribute("displaylist") != NULL){
				flagDL = node->Attribute("displaylist");
				if(flagDL == "true") no->setIsDL(true);

				//cout << "DL: " << no->getIsDL() << endl;
			}

			// Transformacoes
			TiXmlElement* transformation = node->FirstChildElement("transforms");

			glPushMatrix(); 
			glLoadIdentity(); 
			glGetFloatv(GL_MODELVIEW_MATRIX, transformationMatrix);

			while(transformation){

				TiXmlElement* infoTrans = transformation->FirstChildElement();

				while(infoTrans){
					if((string)infoTrans->Value() == "translate"){
						string aux;

						float x,y,z;


						aux=infoTrans->Attribute("to");

						sscanf_s(aux.c_str(),"%f %f %f",&x,&y,&z);	

						glTranslated(x,y,z); 

						//cout<<"Saí"<<endl;

						//printf("\tEncontrou Translate\n");
					}
					else if((string)infoTrans->Value() == "rotate"){

						string aux;
						char x;
						float y;
						aux=infoTrans->Attribute("axis");

						sscanf_s(aux.c_str(),"%c",&x);
						aux=infoTrans->Attribute("angle");
						sscanf_s(aux.c_str(),"%f",&y);

						switch(x)
						{
						case 'x':
							glRotated(y,1,0,0);
							break;
						case 'y':

							glRotated(y,0,1,0);
							break;
						case 'z':
							glRotated(y,0,0,1);
							break;
						}

						//printf("\tEncontrou Rotation\n");
					}
					else if((string)infoTrans->Value() == "scale"){

						string aux;
						float x,y,z;
						aux=infoTrans->Attribute("factor");
						sscanf_s(aux.c_str(),"%f %f %f",&x,&y,&z);	

						glScaled(x,y,z); 
						//printf("\tEncontrou Scale\n");
					}

					infoTrans = infoTrans->NextSiblingElement();
				}

				transformation = transformation->NextSiblingElement();
			}
			glGetFloatv(GL_MODELVIEW_MATRIX, transformationMatrix);
			no->setmatrix(transformationMatrix);
			glPopMatrix();


			//Appearances
			string idAppearance;
			if(node->FirstChildElement("appearanceref") != NULL){
				TiXmlElement* appearanceRef = node->FirstChildElement("appearanceref");
				idAppearance = appearanceRef->Attribute("id");
				std::vector<Appearance*>::iterator it = scene->appearancesComp.begin();
				for(it; it != scene->appearancesComp.end(); it++){
					if((*it)->getIdS() == idAppearance){
						no->setAppearance((*it));
						no->notHighlighted = (*it);
					}
				}                     
				//printf("\tAppearance: %s\n", idAppearance.c_str());
			}

			//Animation
			string idAnimation;
			if(node->FirstChildElement("animationref") != NULL){
				TiXmlElement* animationRef = node->FirstChildElement("animationref");
				idAnimation = animationRef->Attribute("id");
				no->setAnimationid(idAnimation);
				//printf("\tAnimation: %s\n", idAnimation.c_str());
			}

			//Children
			TiXmlElement* children = node->FirstChildElement("children");
			while(children){
				TiXmlElement* infoChild = children->FirstChildElement();
				while(infoChild){
					if((string)infoChild->Value() == "noderef"){
						string idChild;
						idChild = infoChild->Attribute("id");
						no->insertstring(idChild);
						//printf("\tInseriu RefNode: %s\n", idChild.c_str());
					}
					 //<plane parts=”ii” />
					else if((string)infoChild->Value() == "plane"){
						//printf("\tEncontrou Plano\n");
						string partsAux;
						float parts;
						partsAux = infoChild->Attribute("parts");
						sscanf_s(partsAux.c_str(), "%i", &parts);

						Primitive* plane1 = new Plane(parts);
						no->insertprimitive(plane1);
						
					}
					else if((string)infoChild->Value() == "vehicle"){
						//printf("\tEncontrou Veiculo\n");
						Primitive* v1 = new Vehicle();
						no->insertprimitive(v1);
						
					}
					else if((string)infoChild->Value() == "waterline"){
						string heightmap = infoChild->Attribute("heightmap");
						string texturemap = infoChild->Attribute("texturemap");
						string fragmentshader = infoChild->Attribute("fragmentshader");
						string vertexshader = infoChild->Attribute("vertexshader");

						Primitive* wLine1 = new Waterline(heightmap, texturemap, fragmentshader, vertexshader);
						no->insertprimitive(wLine1);

					} 
					else if((string)infoChild->Value() == "patch"){
						int order, partsU, partsV;
						string compute = infoChild->Attribute("compute");

						string orderAux = infoChild->Attribute("order");
						sscanf_s(orderAux.c_str(), "%i", &order);

						string partsUAux = infoChild->Attribute("partsU");
						sscanf_s(partsUAux.c_str(), "%i", &partsU);

						string partsVAux = infoChild->Attribute("partsV");
						sscanf_s(partsVAux.c_str(), "%i", &partsV);
						/*
						cout << "o: " << order << endl;
						cout << "partsU: " << partsU << endl;
						cout << "partsV: " << partsV << endl;
						cout << "compute: " << compute << endl;
						*/
						TiXmlElement* controlPointElement = infoChild->FirstChildElement("controlpoint");
						vector<ControlPoint> auxPoints;
						while(controlPointElement){
							float x,y,z;
							if (controlPointElement->QueryFloatAttribute("x",&x)==TIXML_SUCCESS &&
								controlPointElement->QueryFloatAttribute("y",&y)==TIXML_SUCCESS &&
								controlPointElement->QueryFloatAttribute("z",&z)==TIXML_SUCCESS)
							{
								//cout << x << y << z << endl;
								ControlPoint pontoAux(x,y,z);
								auxPoints.push_back(pontoAux);
							}
							controlPointElement = controlPointElement->NextSiblingElement();
						}
						Primitive* patch1 = new Patch(order, partsU, partsV, compute, auxPoints);

						no->insertprimitive(patch1);
						
					}
					else if((string)infoChild->Value() == "hexagon"){

						//printf("\tEncontrou Hexagono\n");

						//Primitive* h1 = new Hexagon();

						//no->insertprimitive(h1);

					}
					else if((string)infoChild->Value() == "triangle"){

						//printf("\tEncontrou Triangulo\n");

						float p1x, p1y, p1z;
						string ponto1;
						ponto1 = infoChild->Attribute("xyz1");
						sscanf_s(ponto1.c_str(), "%f %f %f", &p1x, &p1y, &p1z);

						float p2x, p2y, p2z;
						string ponto2;
						ponto2 = infoChild->Attribute("xyz2");
						sscanf_s(ponto2.c_str(), "%f %f %f", &p2x, &p2y, &p2z);

						float p3x, p3y, p3z;
						string ponto3;
						ponto3 = infoChild->Attribute("xyz3");
						sscanf_s(ponto3.c_str(), "%f %f %f", &p3x, &p3y, &p3z);

						Primitive* t1 = new Triangle(p1x, p1y, p1z, p2x, p2y, p2z, p3x, p3y, p3z);

						no->insertprimitive(t1);

					}
					else if((string)infoChild->Value() == "cylinder"){

						//printf("\tEncontrou Cilindro\n");
						// TODO: IF's

						float base, top, height, slices, stacks;

						string aux;
						aux = infoChild->Attribute("base");
						sscanf_s(aux.c_str(), "%f", &base);

						aux = infoChild->Attribute("top");
						sscanf_s(aux.c_str(), "%f", &top);
						aux = infoChild->Attribute("height");
						sscanf_s(aux.c_str(), "%f", &height);
						aux = infoChild->Attribute("slices");
						sscanf_s(aux.c_str(), "%f", &slices);
						aux = infoChild->Attribute("stacks");
						sscanf_s(aux.c_str(), "%f", &stacks);



						Primitive* c1 = new Cylinder(base, top, height, slices, stacks);
						no->insertprimitive(c1);

					}
					else if((string)infoChild->Value() == "rectangle"){
						//printf("\tEncontrou Rectangulo\n");
						float x1, y1, x2, y2;
						string p1, p2;
						p1 = infoChild->Attribute("xy1");
						p2 = infoChild->Attribute("xy2");

						//cout<<"P1: "<<p1<<" P2: "<<p2<<endl;

						sscanf_s(p1.c_str(), "%f %f", &x1, &y1);
						sscanf_s(p2.c_str(), "%f %f", &x2, &y2);

						//cout<<"X1: "<<x1<<" X2: "<<x2<<" Y1: "<<y1<<" y2: "<<y2<<endl;

						Primitive* r1 = new Rectangle(x1,y1,x2,y2);
						no->insertprimitive(r1);
					}
					else if((string)infoChild->Value() == "sphere"){

						float radius, slices, stacks;

						string aux;

						aux = infoChild->Attribute("radius");
						sscanf_s(aux.c_str(), "%f", &radius);
						aux = infoChild->Attribute("slices");
						sscanf_s(aux.c_str(), "%f", &slices);
						aux = infoChild->Attribute("stacks");
						sscanf_s(aux.c_str(), "%f", &stacks);




						Sphere* e1 = new Sphere(radius, slices, stacks);
						no->insertprimitive(e1);
					}
					else if((string)infoChild->Value() == "torus")
					{
						float loops;
						float slices, inner,outer;



						string aux;

						aux = infoChild->Attribute("loops");
						sscanf_s(aux.c_str(), "%f", &loops);
						aux = infoChild->Attribute("slices");
						sscanf_s(aux.c_str(), "%f", &slices);
						aux = infoChild->Attribute("inner");
						sscanf_s(aux.c_str(), "%f", &inner);
						aux = infoChild->Attribute("outer");
						sscanf_s(aux.c_str(), "%f", &outer);



						Torus* t1 = new Torus(inner,outer,slices,loops);
						no->insertprimitive(t1);
					}

					infoChild = infoChild->NextSiblingElement();

				}

				children = children->NextSiblingElement();
			}

			
			int pickingId = (int)no->getPicking();
			if((pickingId > 10 && pickingId < 20) || (pickingId > 210 && pickingId < 220)){
				scene->bluePods.push_back(no);
			}
			else if(pickingId > 20 && pickingId < 30 || (pickingId > 220 && pickingId < 230)){
				scene->redPods.push_back(no);
			}
			else if(pickingId == 122 || pickingId == 124 || pickingId == 126 || pickingId == 162 || pickingId == 164 || pickingId == 166){
				scene->octiCells.push_back(no);
			}
			else if(pickingId > 110 && pickingId < 178){
				scene->tabCells.push_back(no);
			}
			else if(pickingId > 210 && pickingId < 219){
				scene->bPickProng.push_back(no);
			}
			else if(pickingId > 220 && pickingId < 229){
				scene->rPickProng.push_back(no);
			}
			if(no->getId() == "envolvente"){
				scene->envolente = no;
			}
			else if(no->getId() == "menuVitoria"){
				scene->menuVitoria = no;
			}

			scene->graph.insert(std::pair<string,Node*>(no->getId(),no));
			node=node->NextSiblingElement();
		}
	}

	
	//scene->setappearancesherity(scene->rootid);
	printf("");
	
}
Beispiel #21
0
HRESULT Application::Initialise(HINSTANCE hInstance, int nCmdShow)
{
    if (FAILED(InitWindow(hInstance, nCmdShow)))
	{
        return E_FAIL;
	}

    RECT rc;
    GetClientRect(_hWnd, &rc);
    _WindowWidth = rc.right - rc.left;
    _WindowHeight = rc.bottom - rc.top;

    if (FAILED(InitDevice()))
    {
        Cleanup();

        return E_FAIL;
    }

	CreateDDSTextureFromFile(_pd3dDevice, L"Resources\\stone.dds", nullptr, &_pTextureRV);
	CreateDDSTextureFromFile(_pd3dDevice, L"Resources\\floor.dds", nullptr, &_pGroundTextureRV);

	objMeshData = OBJLoader::Load("sphere.obj", _pd3dDevice);

    // Setup Camera
	XMFLOAT3 eye = XMFLOAT3(0.0f, 2.0f, -1.0f);
	XMFLOAT3 at = XMFLOAT3(0.0f, 2.0f, 0.0f);
	XMFLOAT3 up = XMFLOAT3(0.0f, 1.0f, 0.0f);

	_camera = new Camera(eye, at, up, (float)_renderWidth, (float)_renderHeight, 0.01f, 200.0f);

	// Setup the scene's light
	basicLight.AmbientLight = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
	basicLight.DiffuseLight = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	basicLight.SpecularLight = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
	basicLight.SpecularPower = 20.0f;
	basicLight.LightVecW = XMFLOAT3(0.0f, 1.0f, -1.0f);

	Geometry cubeGeometry;
	cubeGeometry.indexBuffer = _pIndexBuffer;
	cubeGeometry.vertexBuffer = _pVertexBuffer;
	cubeGeometry.numberOfIndices = 36;
	cubeGeometry.vertexBufferOffset = 0;
	cubeGeometry.vertexBufferStride = sizeof(SimpleVertex);

	Geometry planeGeometry;
	planeGeometry.indexBuffer = _pPlaneIndexBuffer;
	planeGeometry.vertexBuffer = _pPlaneVertexBuffer;
	planeGeometry.numberOfIndices = 6;
	planeGeometry.vertexBufferOffset = 0;
	planeGeometry.vertexBufferStride = sizeof(SimpleVertex);

	Geometry sphereGeometry;
	sphereGeometry.indexBuffer = objMeshData.IndexBuffer;
	sphereGeometry.vertexBuffer = objMeshData.VertexBuffer;
	sphereGeometry.numberOfIndices = objMeshData.IndexCount;
	sphereGeometry.vertexBufferOffset = objMeshData.VBOffset;
	sphereGeometry.vertexBufferStride = objMeshData.VBStride;

	Material shinyMaterial;
	shinyMaterial.ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f);
	shinyMaterial.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	shinyMaterial.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
	shinyMaterial.specularPower = 10.0f;

	Material noSpecMaterial;
	noSpecMaterial.ambient = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f);
	noSpecMaterial.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	noSpecMaterial.specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f);
	noSpecMaterial.specularPower = 0.0f;

	Appearance * floorAppearance = new Appearance(planeGeometry, noSpecMaterial);
	floorAppearance->SetTextureRV(_pGroundTextureRV);

	Appearance * crateAppearance = new Appearance(cubeGeometry, shinyMaterial);
	crateAppearance->SetTextureRV(_pTextureRV);

	Appearance * sphereAppearance = new Appearance(sphereGeometry, shinyMaterial);
	sphereAppearance->SetTextureRV(_pTextureRV);
	
	Transform * floorTransform = new Transform();
	floorTransform->SetPosition(0.0f, 0.0f, 0.0f);
	floorTransform->SetScale(15.0f, 15.0f, 15.0f);
	floorTransform->SetRotation(XMConvertToRadians(90.0f), 0.0f, 0.0f);

	Transform * sphereTransform = new Transform();
	sphereTransform->SetPosition(0.0f, 1.0f, 0.0f);

	ParticleModel * particleModel = new ParticleModel(floorTransform, false, XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f));

	GameObject * gameObject = new GameObject("Floor", floorAppearance, floorTransform, particleModel);

	_gameObjects.push_back(gameObject);

	for (auto i = 0; i < 5; i++)
	{
		Transform * cubeTransform = new Transform();
		cubeTransform->SetScale(0.5f, 0.5f, 0.5f);
		cubeTransform->SetPosition(-4.0f + (i * 2.0f), 0.5f, 10.0f);

		ParticleModel * particleModel = new ParticleModel(cubeTransform, true, XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f));

		gameObject = new GameObject("Cube " + i, crateAppearance, cubeTransform, particleModel);

		_gameObjects.push_back(gameObject);
	}

	ParticleModel * particleModel2 = new ParticleModel(sphereTransform, false, XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f));
	gameObject = new GameObject("Sphere", sphereAppearance, sphereTransform, particleModel2);
	_gameObjects.push_back(gameObject);

	// Setup specific cube behaviour
	_gameObjects[3]->GetParticleModel()->SetUsingConstAccel(false);
	_gameObjects[3]->GetParticleModel()->SetVelocity(0.0f, 0.1f, 0.0f);

	_gameObjects[4]->GetParticleModel()->SetAcceleration(0.0f, 0.1f, 0.0f);

	return S_OK;
}
Beispiel #22
0
void Application::Draw()
{
    //
    // Clear buffers
    //

	float ClearColor[4] = { 0.5f, 0.5f, 0.5f, 1.0f }; // red,green,blue,alpha
    _pImmediateContext->ClearRenderTargetView(_pRenderTargetView, ClearColor);
	_pImmediateContext->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

    //
    // Setup buffers and render scene
    //

	_pImmediateContext->IASetInputLayout(_pVertexLayout);

	_pImmediateContext->VSSetShader(_pVertexShader, nullptr, 0);
	_pImmediateContext->PSSetShader(_pPixelShader, nullptr, 0);

	_pImmediateContext->VSSetConstantBuffers(0, 1, &_pConstantBuffer);
	_pImmediateContext->PSSetConstantBuffers(0, 1, &_pConstantBuffer);
	_pImmediateContext->PSSetSamplers(0, 1, &_pSamplerLinear);

    ConstantBuffer cb;

	XMFLOAT4X4 viewAsFloats = _camera->GetView();
	XMFLOAT4X4 projectionAsFloats = _camera->GetProjection();

	XMMATRIX view = XMLoadFloat4x4(&viewAsFloats);
	XMMATRIX projection = XMLoadFloat4x4(&projectionAsFloats);

	cb.View = XMMatrixTranspose(view);
	cb.Projection = XMMatrixTranspose(projection);
	
	cb.light = basicLight;
	cb.EyePosW = _camera->GetPosition();

	// Render all scene objects
	for (auto gameObject : _gameObjects)
	{
		// Get render material
		Appearance * appearance = gameObject->GetAppearance();
		Material material = appearance->GetMaterial();

		// Copy material to shader
		cb.surface.AmbientMtrl = material.ambient;
		cb.surface.DiffuseMtrl = material.diffuse;
		cb.surface.SpecularMtrl = material.specular;

		// Set world matrix
		cb.World = XMMatrixTranspose(gameObject->GetTransform()->GetWorldMatrix());

		// Set texture
		if (appearance->HasTexture())
		{
			ID3D11ShaderResourceView * textureRV = appearance->GetTextureRV();
			_pImmediateContext->PSSetShaderResources(0, 1, &textureRV);
			cb.HasTexture = 1.0f;
		}
		else
		{
			cb.HasTexture = 0.0f;
		}

		// Update constant buffer
		_pImmediateContext->UpdateSubresource(_pConstantBuffer, 0, nullptr, &cb, 0, 0);

		// Draw object
		gameObject->Draw(_pImmediateContext);
	}

    //
    // Present our back buffer to our front buffer
    //
    _pSwapChain->Present(0, 0);
}
bool PraetoriansTerrainWater::loadPackedMedia(const char* path)
{
  unsigned int signature;
  unsigned short chunkid;
  unsigned int chunklength;
  unsigned int texturescount;///use one in this version
  unsigned int watercount;
  unsigned int vertexcount;
  unsigned int indexcount;
  
  Tuple3f* vertices;
  unsigned short* indices;
  Tuple4ub* colors;
  Tuple2f* txcoords;
  ArchivedFile* file;
  WaterDatabase* wdatabase;
  
  if (!(file = FileSystem::checkOut(path)))
    return Logger::writeErrorLog(String("Could not load -> ") + path);
    
  wdatabase = Gateway::getWaterDatabase();
  
  file->read(&signature, 4);
  
  file->read(&chunkid, 2);
  file->read(&chunklength, 4);
  file->read(&texturescount, 4);
  for (unsigned int i = 0; i < texturescount; i++)
    file->seek((256 * 256 * 4) + 6, SEEKD);
    
  file->read(&watercount, 4);
  for (unsigned int i = 0; i < watercount; i++)
  {
    file->read(&chunkid, 2);
    file->read(&chunklength, 4);
    file->seek(48, SEEKD);
    file->read(&vertexcount, 4);
    
    vertices = new Tuple3f[vertexcount];
    colors = new Tuple4ub[vertexcount];
    txcoords = new Tuple2f[vertexcount];
    for (unsigned int j = 0; j < vertexcount; j++)
    {
      file->read(vertices[j], 12);
      Swap(vertices[j].x, vertices[j].z);
      file->read(colors[j], 4);
      Swap(colors[j].x, colors[j].z);
      file->read(txcoords[j], 8);
    }
    
    file->read(&indexcount, 4);
    indices = new unsigned short[indexcount];
    file->read(indices, indexcount * 2);
    
    String watername = String("H2O_") + int(wdatabase->getWatersCount());
    Geometry* geometry;
    geometry = new Geometry(watername, indexcount, vertexcount);
    geometry->setIndices(indices, false);
    geometry->setVertices(vertices, false);
    geometry->setColors(colors, false);
    geometry->setTextureElements(txcoords, 2, false);
    geometry->computeBounds();
    
    Appearance* appearance = new Appearance();
    appearance->setBlendAttributes(BlendAttributes(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
    appearance->setTexture(0, wdatabase->getWaterTexture());
    
    Model* model = new Model();
    model->setAppearance(appearance);
    model->setGeometry(geometry);
    
    TransformGroup* group = new TransformGroup();
    group->addChild(model);
    group->updateBoundsDescriptor();
    wdatabase->addWaterModel(group);
    
    deleteArray(vertices);
    deleteArray(indices);
    deleteArray(colors);
    deleteArray(txcoords);
  }
  
  FileSystem::checkIn(file);
  
  return true;
}
Beispiel #24
0
void Commander::dispatch(const RootOperation& op)
{
    Appearance appear = smart_dynamic_cast<Appearance>(op);
    if (appear.isValid()) {
        assert(op->hasAttr("for"));
        Agent* ag = m_server->findAgentForEntity(op->getAttr("for").asString());
        if (ag) {
            ag->setEntityVisible(op->getTo(), true);
        } else {
            // doesn't exist yet, mark as visible if / when the agent is created
            Agent::setEntityVisibleForFutureAgent(op->getTo(), op->getAttr("for").asString());
        }
    }
    
    Disappearance disap = smart_dynamic_cast<Disappearance>(op);
    if (disap.isValid()) {
        assert(op->hasAttr("for"));
        Agent* ag = m_server->findAgentForEntity(op->getAttr("for").asString());
        if (ag) ag->setEntityVisible(op->getTo(), false);
    }
    
    Create cr = smart_dynamic_cast<Create>(op);
    if (cr.isValid()) {
        std::vector<Root> args(op->getArgs());
        assert(!args.empty());
        RootEntity ent = smart_dynamic_cast<RootEntity>(args.front());
        assert(ent.isValid());
        
        static int idCounter = 900;
        char buf[32];
        snprintf(buf, 32, "_created_%d", ++idCounter);
        std::string id(buf);
        
        ent->setId(id);
        std::string loc = ent->getLoc();
        assert(m_server->m_world.count(loc));
        
        StringList children(m_server->m_world[loc]->getContains());
        children.push_back(id);
        m_server->m_world[loc]->setContains(children);

        m_server->m_world[id] = ent;
        
        Create bcr(cr);
        bcr->setArgs1(ent);
        Agent::broadcastSight(bcr);
    }
    
    Delete del = smart_dynamic_cast<Delete>(op);
    if (del.isValid()) {
        std::vector<Root> args(op->getArgs());
        assert(!args.empty());
        
        std::string id = args.front()->getId();
        assert(m_server->m_world.count(id));
        m_server->m_world.erase(id);
        
        Agent::broadcastSight(op);
    }
    
    Move mv = smart_dynamic_cast<Move>(op);
    if (mv.isValid()) {
        RootEntity ent = m_server->getEntity(op->getTo());
        
        std::vector<Root> args(op->getArgs());
        
        if (args.front()->hasAttr("loc")) {
            std::string newLocId = args.front()->getAttr("loc").asString();
            
            RootEntity oldLoc = m_server->getEntity(ent->getLoc()),
                newLoc = m_server->getEntity(newLocId);
            
            ent->setLoc(newLocId);
            // modify stamps?
            oldLoc->modifyContains().remove(ent->getId());
            newLoc->modifyContains().push_back(ent->getId());
        }
        
        if (args.front()->hasAttr("pos"))
            ent->setPosAsList(args.front()->getAttr("pos").asList());
            
        // handle velocity changes
        Agent::broadcastSight(op);
        return;
    }
    
    Sound snd = smart_dynamic_cast<Sound>(op);
    if (snd.isValid()) {
        
        std::vector<Root> args(op->getArgs());
        assert(!args.empty());
        
        if (snd->hasAttr("broadcast")) {
            Agent::broadcastSound(smart_dynamic_cast<RootOperation>(args.front()));
        }
    }
    
    Sight st = smart_dynamic_cast<Sight>(op);
    if (st.isValid()) {
        if (st->hasAttr("broadcast")) {
            std::vector<Root> args(op->getArgs());
            assert(!args.empty());
            Agent::broadcastSight(smart_dynamic_cast<RootOperation>(args.front()));
        }
    }
    
    Set s = smart_dynamic_cast<Set>(op);
    if (s.isValid()) {
        
        std::vector<Root> args(op->getArgs());
        for (unsigned int A=0; A < args.size(); ++A) {
            std::string eid = args[A]->getId();
        
            RootEntity entity = m_server->getEntity(eid);
            Root::const_iterator I = args[A]->begin();
            
            for (; I != args[A]->end(); ++I) {
                if ((I->first == "id") || (I->first == "parents") || (I->first == "objtype")) {
                    continue;
                }
                
                assert(I->first != "loc");
                entity->setAttr(I->first, I->second);
            }
        }

        Agent::broadcastSight(s);
    }
    
    Action act = smart_dynamic_cast<Action>(op);
    if (act.isValid()) {
        std::vector<Root> args(op->getArgs());
        
        if (act->getParents().front() == "command") {
            std::string cid = args[0]->getAttr("cid").asString();
            
            if (cid == "socket-shutdown") {
                std::string acc = args[0]->getAttr("acc").asString();
                ClientConnection* cc = m_server->getConnectionForAccount(acc);
                assert(cc);
                cc->shutdown();
            } else if (cid == "add-many-objects") {
                m_server->addManyObjects(args[0]->getAttr("acc").asString());
            } else if (cid == "set-world-time") {
                /* double t = */ args[0]->getAttr("seconds").asFloat();
                
            } else {
                std::cerr << "unknown command " << cid << std::endl;
            }
        } // of command action case
    } // of action case
}
Beispiel #25
0
// Destructor
AppearanceGroup::~AppearanceGroup()
{
   Os::Logger::instance().log(FAC_SAA, PRI_DEBUG,
                 "AppearanceGroup::~ this = %p, mSharedUser = '******'",
                 this, mSharedUser.data());
   // Delete this AppearanceGroup from mSubscribeMap (for the "reg" subscription).
   getAppearanceAgent()->getAppearanceGroupSet().deleteSubscribeMapping(&mSubscriptionEarlyDialogHandle);

   // End the "reg" subscription.
   UtlBoolean ret;
   ret = getAppearanceAgent()->getSubscribeClient().
      endSubscriptionGroup(mSubscriptionEarlyDialogHandle);
   Os::Logger::instance().log(FAC_SAA,
                 ret ? PRI_INFO : PRI_WARNING,
                 "AppearanceGroup::~ endSubscriptionGroup %s mSharedUser = '******', mSubscriptionEarlyDialogHandle = '%s'",
                 ret ? "succeeded" : "failed",
                 mSharedUser.data(),
                 mSubscriptionEarlyDialogHandle.data());

   // Remove this AppearanceGroup from mNotifyMap for all subscriptions.
   {
      UtlHashMapIterator itor(mSubscriptions);
      UtlString* handle;
      while ((handle = dynamic_cast <UtlString*> (itor())))
      {
         getAppearanceAgent()->getAppearanceGroupSet().deleteNotifyMapping(handle);
      }
   }

   // Delete the contents of mSubscriptions.
   mSubscriptions.destroyAll();

   // Terminate all dialogs for this shared Appearance Group, then publish
   bool bContentChanged = false;
   SipDialogEvent* lPartialContent = new SipDialogEvent("partial", mSharedUser.data());
   {
      UtlHashMapIterator itor(mAppearances);
      UtlString* handle;
      while ( (handle = dynamic_cast <UtlString*> (itor())) )
      {
         Appearance* pApp = dynamic_cast <Appearance*> (itor.value());
         bContentChanged |= pApp->terminateDialogs(true); // terminate all dialogs
         pApp->getDialogs(lPartialContent);
      }
   }
   if (bContentChanged)
   {
      lPartialContent->buildBody();
      publish(true, true, lPartialContent);
   }
   delete lPartialContent;

   // Delete the subordinate Appearance's for the contacts.
   {
      // Have to use a loop to remove items individually, because
      // destroyAll() deadlocks with the access to mAppearances
      // during the the attempt to publish new status for the resource
      // as the Appearances are recursively deleted.
      int changeDelay = getAppearanceAgent()->getChangeDelay();
      UtlHashMapIterator itor(mAppearances);
      UtlContainable* k;
      while ((k = itor()))
      {
         UtlContainable* v = itor.value();
         mAppearances.removeReference(k);
         delete k;
         delete v;
         // Delay to allow the consequent processing to catch up.
         OsTask::delay(changeDelay);
      }
   }
}
   void AppearanceTest()
   {
      instantiateAllTestFixtures( "appearance-groups1.xml",
                                  "subscription1",
                                  "credential1",
                                  "177.0.0.1:54140");

      UtlString sharedUri = "sip:[email protected]:54140";
      UtlString app1uri = "sip:127.0.0.1:45141";
      UtlString dialogHandle;

      // receive the reg-info subscribe
      SipMessage request;
      UtlString b;
      ssize_t l;
      while(getNextMessageFromAppearanceAgentUnderTest( request, 5 ))
      {
         request.getBytes(&b, &l);
         OsSysLog::add(FAC_RLS, PRI_DEBUG, "got message %s", b.data());
         UtlString method;
         request.getRequestMethod(&method);
         if(!request.isResponse() &&
            0 == method.compareTo(SIP_SUBSCRIBE_METHOD) )
         {
            // Accept the Subscription, regardless of whether it for a 'dialog' or 'reg' event
            // in order to stop retransmissions
            SipMessage regResponse;
            regResponse.setResponseData(&request, 202, "Accepted", app1uri);
            SipMessage * dispatchedMessage = new SipMessage(regResponse);
            dispatchedMessage->getBytes(&b, &l);
            OsSysLog::add(FAC_RLS, PRI_DEBUG, "sent message %s", b.data());
            pAppearanceAgentUnderTest->mServerUserAgent.dispatch(dispatchedMessage);

            // Deal with the two events separately
            UtlString eventField;
            request.getEventField(eventField);
            if(0 == eventField.compareTo("reg"))
            {
               UtlString contactInfo;
               request.getContactUri(0, &contactInfo);
               UtlString callid;
               request.getCallIdField(&callid);
               int cseq;
               request.getCSeqField(&cseq, NULL);

               Url toField;
               regResponse.getToUrl(toField);

               SipMessage regNotify;
               regNotify.setNotifyData(&request, 1, "", "", "reg");
               UtlString regInfo ("<?xml version=\"1.0\"?>\r\n"
                                 "<reginfo xmlns=\"urn:ietf:params:xml:ns:reginfo\" "
                                 "xmlns:gr=\"urn:ietf:params:xml:ns:gruuinfo\" version=\"911\" state=\"full\">\r\n"
                                 "   <registration aor=\"sip:[email protected]:54140\" id=\"sip:[email protected]:54140\" state=\"active\">\r\n "
                                 "      <contact id=\"sip:[email protected]:54140@@&lt;");
               regInfo.append(contactInfo);
               regInfo.append("&gt;\" state=\"active\" event=\"registered\" q=\"1\" callid=\"");
               regInfo.append(callid);
               regInfo.append("\" cseq=\"");
               regInfo.appendNumber(cseq);
               regInfo.append("\">\r\n");
               regInfo.append("<uri>");
               regInfo.append(app1uri);
               regInfo.append("</uri>");
               regInfo.append("      </contact>\r\n"
                              "   </registration>\r\n"
                              "</reginfo>");
               HttpBody * newBody = new HttpBody (regInfo, strlen(regInfo), "application/reginfo+xml");
               regNotify.setContentType("application/reginfo+xml");
               regNotify.setBody(newBody);

               // Set the From field the same as the to field from the 202 response, as it
               // contains the dialog identifying to tags
               regNotify.setRawFromField(toField.toString().data());
               sendToAppearanceAgentUnderTest( regNotify );
               regNotify.getBytes(&b, &l);
               OsSysLog::add(FAC_RLS, PRI_DEBUG, "sent reg NOTIFY to AppAgent");
               OsSysLog::add(FAC_RLS, PRI_DEBUG, "sent message %s", b.data());
            }
            else if (0 == eventField.compareTo(SLA_EVENT_TYPE))
             {
                // should send empty NOTIFY, but no one will care
                // save dialogHandle for this subscription/Appearance (ignore retransmissions)
                if (dialogHandle.isNull())
                {
                   SipMessage fake(b);
                   fake.getDialogHandle(dialogHandle);
                   OsSysLog::add(FAC_RLS, PRI_DEBUG, "got SUBSCRIBE(sla) request: dialogHandle %s", dialogHandle.data());
                }
             }
         }
      }

      CPPUNIT_ASSERT( !dialogHandle.isNull() );
      OsSysLog::add(FAC_RLS, PRI_DEBUG, "we now have an Appearance - test it");
      AppearanceGroup* pAppGroup = pAppearanceAgentUnderTest->getAppearanceGroupSet().
         findAppearanceGroup(sharedUri);
      CPPUNIT_ASSERT( pAppGroup );

      Appearance* pApp = pAppGroup->findAppearance(dialogHandle);
      CPPUNIT_ASSERT( pApp );
      ASSERT_STR_EQUAL( app1uri.data(), pApp->getUri()->data() );

      // test adding a new dialog
      const char* dialogEventString =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"0\" state=\"partial\" entity=\"sip:[email protected]:54140\">\n"
            "<dialog id=\"1\" call-id=\"[email protected]\" local-tag=\"264460498\" remote-tag=\"1c10982\" direction=\"recipient\">\n"
            "<state>confirmed</state>\n"
            "<local>\n"
            "<identity>[email protected]:5120</identity>\n"
            "<target uri=\"sip:[email protected]:5120\">\n"
            "<param pname=\"x-line-id\" pval=\"0\"/>\n"
            "<param pname=\"+sip.rendering\" pval=\"yes\"/>\n"
            "</target>\n"
            "</local>\n"
            "<remote>\n"
            "<identity>[email protected]</identity>\n"
            "</remote>\n"
            "</dialog>\n"
            "</dialog-info>\n"
            ;
      SipDialogEvent dialogEvent(dialogEventString);
      bool bFullContentChanged = false;
      bool bPartialContentChanged = pApp->updateState(&dialogEvent, bFullContentChanged);
      CPPUNIT_ASSERT(bPartialContentChanged);
      CPPUNIT_ASSERT(bFullContentChanged);
      pApp->dumpState();
      CPPUNIT_ASSERT(pApp->appearanceIsBusy());
      CPPUNIT_ASSERT(pApp->appearanceIdIsSeized("0"));
      CPPUNIT_ASSERT(!pApp->appearanceIdIsSeized("1"));

      // simulate user putting the call on hold
      const char* dialogEventString2 =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"0\" state=\"partial\" entity=\"sip:[email protected]:54140\">\n"
            "<dialog id=\"1\" call-id=\"[email protected]\" local-tag=\"264460498\" remote-tag=\"1c10982\" direction=\"recipient\">\n"
            "<state>confirmed</state>\n"
            "<local>\n"
            "<identity>[email protected]:5120</identity>\n"
            "<target uri=\"sip:[email protected]:5120\">\n"
            "<param pname=\"x-line-id\" pval=\"0\"/>\n"
            "<param pname=\"+sip.rendering\" pval=\"no\"/>\n"
            "</target>\n"
            "</local>\n"
            "<remote>\n"
            "<identity>[email protected]</identity>\n"
            "</remote>\n"
            "</dialog>\n"
            "</dialog-info>\n"
            ;
      SipDialogEvent dialogEvent2(dialogEventString2);
      bPartialContentChanged = pApp->updateState(&dialogEvent2, bFullContentChanged);
      CPPUNIT_ASSERT(bPartialContentChanged);
      CPPUNIT_ASSERT(bFullContentChanged);
      pApp->dumpState();
      CPPUNIT_ASSERT(!pApp->appearanceIsBusy());
      CPPUNIT_ASSERT(pApp->appearanceIdIsSeized("0"));
      CPPUNIT_ASSERT(!pApp->appearanceIdIsSeized("1"));

      // test MESSAGE debug handling
      const char* message =
         "MESSAGE sip:[email protected]:54140 SIP/2.0\r\n"
         "From: <sip:[email protected]>;tag=17211757-9E4FBD78\r\n"
         "To: <sip:[email protected]:54140>\r\n"
         "CSeq: 1 MESSAGE\r\n"
         "Call-ID: 51405734-b9be4835-dcd9d196\r\n"
         "Contact: <sip:[email protected]>\r\n"
         "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, INFO, MESSAGE, SUBSCRIBE, NOTIFY, PRACK, UPDATE, REFER\r\n"
         "Event: dialog\r\n"
         "User-Agent: UnitTest\r\n"
         "Accept-Language: en\r\n"
         "Accept: application/dialog-info+xml\r\n"
         "Max-Forwards: 70\r\n"
         "Expires: 3600\r\n"
         "Content-Length: 0\r\n"
         "\r\n";

      // send the MESSAGE
      SipMessage messageRequest( message, strlen( message ) );
      CPPUNIT_ASSERT( sendToAppearanceAgentUnderTest( messageRequest ) );

      // receive the 200 OK response
      SipMessage response;
      CPPUNIT_ASSERT( getNextMessageFromAppearanceAgentUnderTest( response, 5 ) );
      CPPUNIT_ASSERT( response.isResponse() );
      CPPUNIT_ASSERT( response.getResponseStatusCode() == SIP_OK_CODE );
   }
Beispiel #27
0
Appearance *Option::parseAppearance(char *str)
{
	Appearance *app = 0;
	char *p;

	if (*str == '[') {
		char *tok;
		int mask = 0;
		int top, left, bottom, right;

		top = left = bottom = right = 0;

		p = strtok_r(str, "[] ,", &tok);
		app = parseAppearance(p);

		if (!(p = strtok_r(NULL, "[] ,", &tok))) goto err;
		top = strtol(p, 0, 10);
		if (strchr(p, '%'))
			mask |= PERPAD_TOP;

		if (!(p = strtok_r(NULL, "[] ,", &tok))) goto err;
		right = strtol(p, 0, 10);
		if (strchr(p, '%'))
			mask |= PERPAD_RIGHT;

		if ((p = strtok_r(NULL, "[] ,", &tok))) {
			bottom = strtol(p, 0, 10);
			if (strchr(p, '%'))
				mask |= PERPAD_BOT;

			if (!(p = strtok_r(NULL, "[] ,", &tok))) goto err;
			left = strtol(p, 0, 10);
			if (strchr(p, '%'))
				mask |= PERPAD_LEFT;
		}
		else {
			bottom = top;
			if (mask & PERPAD_TOP)
				mask |= PERPAD_BOT;

			right = left;
			if (mask & PERPAD_LEFT)
				mask |= PERPAD_RIGHT;
		}
		app->setPadding(Padding(mask, top, right, bottom, left));
	}
	else if ((p = strstr(str, "gradient"))) {
		int direction = 0;
		char *tok;
		p = strchr(p, '(');
		if (!p) goto err;
		p = strtok_r(p, ", ()", &tok);
		if (strcmp(p, "vert") == 0)
			direction = GRAD_VERT;
		else 
			direction = GRAD_HORZ;

		app = new GradientAppearance(direction);
		GradientAppearance *gapp = dynamic_cast<GradientAppearance *>(app);

		while((p = strtok_r(NULL, ", ()", &tok)) != NULL){
			gapp->addColor(atoc(p));
		}
	}
	else if ((p = strstr(str, "image"))) {
		char *tok;
		p = strchr(p, '(');
		if (!p) goto err;

		if (!(p = strtok_r(p, "(\")", &tok))) goto err;

		Setting *setting = Insune::getSingleton()->getSetting("style");
		const char *style = setting->getValue()->getString();
		char stylepath[256];
		snprintf(stylepath, 256, STYLEDIR "%s/%s", style, p);

		char *align = NULL;
		char *type = NULL;
		if ((p = strtok_r(NULL, "(\")", &tok))) {
			if (*p == '@') {
				align = p + 1;
				if ((p = strchr(p + 1, '!'))) {
					*p = '\0';
					type = p + 1;
				}
			} else if (*p == '!') {
				type = p + 1;
				if ((p = strchr(p + 1, '@'))) {
					*p = '\0';
					align = p + 1;
				}
			}
		}
		if (align && type)
			app = new ImageAppearance(stylepath, align, type);
		else if (align)
			app = new ImageAppearance(stylepath, align);
		else if (type)
			app = new ImageAppearance(stylepath, NULL, type);
		else
			app = new ImageAppearance(stylepath);

	}

	else {
		app = new SolidAppearance(atoc(str));
	}

	return app;
err:
	fprintf(stderr, "Error parsing appearances. Value:\n```%s'''\n", str);
	return NULL;
}