예제 #1
0
    void RttManager::CDepthListener::preRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
    {
		Hydrax *mHydrax = mRttManager->mHydrax;

        Ogre::SceneManager::MovableObjectIterator EntityIterator = 
			mHydrax->getSceneManager()->getMovableObjectIterator("Entity");
        Ogre::Entity* CurrentEntity;
		unsigned int k;

        mMaterials.empty();

        while (EntityIterator.hasMoreElements())
        {
            CurrentEntity = static_cast<Ogre::Entity*>(EntityIterator.peekNextValue());

			for(k = 0; k < CurrentEntity->getNumSubEntities(); k++)
			{
				mMaterials.push(CurrentEntity->getSubEntity(k)->getMaterialName());

			    CurrentEntity->getSubEntity(k)->setMaterialName(mHydrax->getMaterialManager()->getMaterial(MaterialManager::MAT_DEPTH)->getName());
			}

            EntityIterator.moveNext();
        }

		if (Ogre::Math::Abs(mHydrax->getPosition().y - mHydrax->getCamera()->getDerivedPosition().y) > mHydrax->getPlanesError())
		{
			if (mHydrax->_isCurrentFrameUnderwater())
		    {
				mRttManager->mPlanes[RTT_DEPTH]->normal = -mRttManager->mPlanes[RTT_DEPTH]->normal;
                mRttManager->mPlanes[RTT_DEPTH]->getParentNode()->translate(0,-mHydrax->getPlanesError(),0);
		    }
		    else
		    {
			    mRttManager->mPlanes[RTT_DEPTH]->getParentNode()->translate(0,mHydrax->getPlanesError(),0);
				mHydrax->getCamera()->enableCustomNearClipPlane(mRttManager->mPlanes[RTT_DEPTH]);
		    }   
		}

		if (mHydrax->_isCurrentFrameUnderwater())
		{
            mHydrax->getMesh()->getEntity()->setVisible(true);
			mHydrax->getMesh()->getEntity()->setMaterialName(
				mHydrax->getMaterialManager()->getMaterial(MaterialManager::MAT_SIMPLE_RED)->
				     getName());
			mHydrax->getMesh()->getEntity()->setRenderQueueGroup(Ogre::RENDER_QUEUE_SKIES_EARLY);
			mHydrax->getGodRaysManager()->setVisible(true);
		}
		else
		{
			mHydrax->getMesh()->getEntity()->setVisible(false);
		}
    }
예제 #2
0
	void RttManager::CDepthReflectionListener::preRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
    {
		Hydrax *mHydrax = mRttManager->mHydrax;

		mHydrax->getMesh()->getEntity()->setVisible(false);

        Ogre::SceneManager::MovableObjectIterator EntityIterator = 
			mHydrax->getSceneManager()->getMovableObjectIterator("Entity");
        Ogre::Entity* CurrentEntity;
		unsigned int k;

        mMaterials.empty();

        while (EntityIterator.hasMoreElements())
        {
            CurrentEntity = static_cast<Ogre::Entity*>(EntityIterator.peekNextValue());

			for(k = 0; k < CurrentEntity->getNumSubEntities(); k++)
			{
				mMaterials.push(CurrentEntity->getSubEntity(k)->getMaterialName());

			    CurrentEntity->getSubEntity(k)->setMaterialName(mHydrax->getMaterialManager()->getMaterial(MaterialManager::MAT_DEPTH)->getName());
			}

            EntityIterator.moveNext();
        }

        mRttManager->mPlanes[RTT_DEPTH_REFLECTION]->getParentNode()->translate(0,-mHydrax->getPlanesError(),0);
		
        bool IsInUnderwaterError = false;

		if (mHydrax->getCamera()->getDerivedPosition().y > mRttManager->mPlanes[RTT_DEPTH_REFLECTION]->getParentNode()->getPosition().y)
		{
			mCameraPlaneDiff = 0;
			IsInUnderwaterError = true;
		}
		else
		{
			mCameraPlaneDiff = 0;
		}

        mHydrax->getCamera()->enableReflection(mRttManager->mPlanes[RTT_DEPTH_REFLECTION]);

		if (!IsInUnderwaterError)
		{
            mHydrax->getCamera()->enableCustomNearClipPlane(mRttManager->mPlanes[RTT_DEPTH_REFLECTION]);
		}
    }
예제 #3
0
// 设置正常的外观颜色.
void CEditDobject_NT::SetUnSelLook()
{
	if(0 == m_materilaOldVector.size())
	{
		return;
	}

	int iCount = m_EntityList.size();
	Ogre::Entity* pEntity = NULL;

	int iIndex = 0;

	for(int i = 0; i < iCount; i++)
	{
		pEntity = m_EntityList[i].pEntity;
		if(pEntity)
		{
			Ogre::SubEntity* pSubEntiy = pEntity->getSubEntity(0);
			if(pSubEntiy)
			{
				if(iIndex >= (int)m_materilaOldVector.size())
				{
					continue;
				}
			
				std::string strMaterialName = m_materilaOldVector[iIndex]->getName();
				pSubEntiy->setMaterialName(strMaterialName);
				iIndex++;
				
			}

		}
	}

}
예제 #4
0
// 设置模型的透明度
// 0 -- 完全透明。
// 1 -- 不透明。
void CEditDobject_NT::SetTransparence(float Transparence)
{
	int iCount = m_EntityList.size();
	Ogre::Entity* pEntity = NULL;

	for(int i = 0; i < iCount; i++)
	{
		pEntity = m_EntityList[i].pEntity;
		if(pEntity)
		{
			 Ogre::SubEntity* pSubEntiy = pEntity->getSubEntity(0);
			
			 if(pSubEntiy)
			 {
				Ogre::MaterialPtr material1 = pSubEntiy->getMaterial();
				Ogre::Technique* t1 = material1->getBestTechnique();
				Ogre::Pass* p1 = t1->getPass(0);

				p1->setSceneBlending(Ogre::SBT_ADD  );
				p1->setSceneBlending(Ogre::SBF_SOURCE_ALPHA , Ogre::SBF_ONE_MINUS_SOURCE_ALPHA );
				Ogre::TextureUnitState* pTextureState = p1->getTextureUnitState(0);
				pTextureState->setAlphaOperation(Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1, Transparence, 1);
				 
				//Ogre::ColourValue color(1,0.0,0.0,0.1) ;
				//pTextureState->setColourOperationEx(LBX_ADD , LBS_TEXTURE , LBS_MANUAL, color, color );
				
			 }

		}
	}
}
예제 #5
0
void RttManager::CDepthReflectionListener::postRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
{
  Hydrax *mHydrax = mRttManager->mHydrax;

  Ogre::SceneManager::MovableObjectIterator EntityIterator = mHydrax->getSceneManager()->getMovableObjectIterator("Entity");
  Ogre::Entity* CurrentEntity;
  unsigned int k;

  while (EntityIterator.hasMoreElements()) {
    CurrentEntity = static_cast<Ogre::Entity*>(EntityIterator.peekNextValue());

    for (k = 0; k < CurrentEntity->getNumSubEntities(); k++) {
      CurrentEntity->getSubEntity(k)->setMaterialName(mMaterials.front());

      mMaterials.pop();
    }

    EntityIterator.moveNext();
  }

  mHydrax->getMesh()->getEntity()->setVisible(true);

  if (mCameraPlaneDiff != 0) {
    mRttManager->mPlanes[RTT_DEPTH_REFLECTION]->getParentNode()->translate(0, mCameraPlaneDiff, 0);
  }

  mRttManager->mPlanes[RTT_DEPTH_REFLECTION]->getParentNode()->translate(0, mHydrax->getPlanesError(), 0);

  mHydrax->getCamera()->disableReflection();
  mHydrax->getCamera()->disableCustomNearClipPlane();
}
예제 #6
0
ActivatorAnimation::ActivatorAnimation(const MWWorld::Ptr &ptr)
  : Animation(ptr)
{
    MWWorld::LiveCellRef<ESM::Activator> *ref = mPtr.get<ESM::Activator>();

    assert (ref->mBase != NULL);
    if(!ref->mBase->mModel.empty())
    {
        std::string mesh = "meshes\\" + ref->mBase->mModel;

        createEntityList(mPtr.getRefData().getBaseNode(), mesh);
        for(size_t i = 0;i < mEntityList.mEntities.size();i++)
        {
            Ogre::Entity *ent = mEntityList.mEntities[i];

            for(unsigned int j=0; j < ent->getNumSubEntities(); ++j)
            {
                Ogre::SubEntity* subEnt = ent->getSubEntity(j);
                subEnt->setRenderQueueGroup(subEnt->getMaterial()->isTransparent() ? RQG_Alpha : RQG_Main);
            }

            ent->setVisibilityFlags(RV_Misc);
        }
        setAnimationSource(mesh);
    }
}
예제 #7
0
파일: Cube.cpp 프로젝트: 0xc0dec/yarc
void Cube::save(Ogre::String file)
{
  if (rndCounter == 0)
  {
    std::ofstream output(file.c_str());

    // Write cube size
    output << size << std::endl;

    for (int i = 0; i < size; ++i)
      for (int j = 0; j < size; ++j)
        for (int k = 0; k < size; ++k)
        {
          CubeElement *e = data[i][j][k];
          Ogre::Entity *ent = static_cast<Ogre::Entity*>(e->node->getAttachedObject(0));
          Ogre::SceneNode *node = e->node;
          // Write name, indexes and position
          output << node->getName() << "\n"
                 << "\t" << i << " " << j << " " << k << "\n" // index in data array
                 << "\t" << node->getPosition().x << " " << node->getPosition().y << " " << node->getPosition().z << "\n"; // position
          // Write orientation
          Ogre::Vector3 orient_axis;
          Ogre::Degree orient_angle;
          node->getOrientation().ToAngleAxis(orient_angle, orient_axis);
          output << "\t" << orient_axis.x << " " << orient_axis.y << " " << orient_axis.z << " " // orientation axis
                 << orient_angle.valueDegrees() << "\n"; // orientation angle
          output << "\t" << ent->getSubEntity(0)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(1)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(2)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(3)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(4)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(5)->getMaterialName() << "\n";
          // Write pivot info
          output << "\t" << e->isPivot << "\n";
          if (e->isPivot)
          {
            // pivot indexes
            output << "\t" << e->pivotArrays[0] << " " << e->pivotArrayIndexes[0] << "\n"
                   << "\t" << e->pivotArrays[1] << " " << e->pivotArrayIndexes[1] << "\n";
          }
          // flush
          output << std::endl;
        }

    output.close();
  }
}
bool 
CGrassSticks::buildGrassSticks(Ogre::SceneManager* sceneMgr, btDynamicsWorld* dynamicsWorld, btSoftBodyWorldInfo &softBodyWorldInfo)
{    
    // create our grass mesh, and create a grass entity from it
    if (!sceneMgr->hasEntity(GRASS_MESH_NAME))
    {
	    createGrassMesh();
    } // End if

    const int		n=16;
	const int		sg=4;    
	const btScalar	sz=16;
	const btScalar	hg=4;
	const btScalar	in=1/(btScalar)(n-1);
    int             index = 0;

	for(int y=0;y<n;++y)
	{
		for(int x=0;x<n;++x)
		{
			const btVector3	org(-sz+sz*2*x*in,
				1,
				-sz+sz*2*y*in);
			btSoftBody*		psb=btSoftBodyHelpers::CreateRope(softBodyWorldInfo, org,
				org+btVector3(hg*0.001f,hg,0),
				sg,
				1);
			psb->m_cfg.kDP		=	0.005f;
			psb->m_cfg.kCHR		=	0.1f;
			for(int i=0;i<3;++i)
			{
				psb->generateBendingConstraints(2+i);
			}
			psb->setMass(1,0);
			psb->setTotalMass(0.01f);
                       
            static_cast<btSoftRigidDynamicsWorld*>(dynamicsWorld)->addSoftBody(psb);
            
            const Ogre::String& strIndex = Ogre::StringConverter::toString(index++);
            Ogre::Entity* grass = sceneMgr->createEntity("Grass" + strIndex, GRASS_MESH_NAME);
            Ogre::SceneNode* node = sceneMgr->getRootSceneNode()->createChildSceneNode("node_grass_" + strIndex
                ,Ogre::Vector3(org.getX(), org.getY(), org.getZ())
                ,Ogre::Quaternion(Ogre::Degree(0), Vector3::UNIT_Y));
            node->attachObject(grass);
            node->scale(1.0f, Ogre::Math::RangeRandom(0.85f, 1.15f), 1.0f);
            node->setVisible(true);
                                    
            psb->setUserPointer((void*)(grass->getSubEntity(0)));
		} // End for
	} // End for

    dynamicsWorld->setInternalTickCallback(&CGrassSticks::simulationTickCallback);
    
    return true;
}
예제 #9
0
  void GodRaysManager::DepthMapListener::preRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
  {
    Ogre::SceneManager::MovableObjectIterator EntityIterator = mGodRaysManager->mHydrax->getSceneManager()->getMovableObjectIterator("Entity");
    Ogre::Entity * CurrentEntity = NULL;
    unsigned int k = 0;
    mMaterials.empty();
    mGodRaysManager->mHydrax->getMesh()->getEntity()->setVisible(false);

    while(EntityIterator.hasMoreElements())
    {
      CurrentEntity = static_cast<Ogre::Entity *>(EntityIterator.peekNextValue());

      for(k = 0; k < CurrentEntity->getNumSubEntities(); k++)
      {
        mMaterials.push(CurrentEntity->getSubEntity(k)->getMaterialName());
        CurrentEntity->getSubEntity(k)->setMaterialName(_def_GodRaysDepth_Material_Name);
      }

      EntityIterator.moveNext();
    }
  }
예제 #10
0
CreatureAnimation::CreatureAnimation(const MWWorld::Ptr& ptr): Animation()
{
    mInsert = ptr.getRefData().getBaseNode();
    MWWorld::LiveCellRef<ESM::Creature> *ref = ptr.get<ESM::Creature>();

    assert (ref->mBase != NULL);
    if(!ref->mBase->mModel.empty())
    {
        std::string mesh = "meshes\\" + ref->mBase->mModel;

        mEntityList = NifOgre::NIFLoader::createEntities(mInsert, &mTextKeys, mesh);
        for(size_t i = 0; i < mEntityList.mEntities.size(); i++)
        {
            Ogre::Entity *ent = mEntityList.mEntities[i];
            ent->setVisibilityFlags(RV_Actors);

            bool transparent = false;
            for (unsigned int j=0; j < ent->getNumSubEntities() && !transparent; ++j)
            {
                Ogre::MaterialPtr mat = ent->getSubEntity(j)->getMaterial();
                Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
                while (techIt.hasMoreElements() && !transparent)
                {
                    Ogre::Technique* tech = techIt.getNext();
                    Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                    while (passIt.hasMoreElements() && !transparent)
                    {
                        Ogre::Pass* pass = passIt.getNext();

                        if (pass->getDepthWriteEnabled() == false)
                            transparent = true;
                    }
                }
            }
            ent->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
        }

        if(mEntityList.mSkelBase)
        {
            Ogre::AnimationStateSet *aset = mEntityList.mSkelBase->getAllAnimationStates();
            Ogre::AnimationStateIterator as = aset->getAnimationStateIterator();
            while(as.hasMoreElements())
            {
                Ogre::AnimationState *state = as.getNext();
                state->setEnabled(true);
                state->setLoop(false);
            }
        }
    }
}
예제 #11
0
void BallApp::createBall(std::string entName, std::string nodeName, 
                        int x, int y, int z,
                        int vx, int vy, int vz) {
  
  Ogre::Entity *entity = mSceneMgr->createEntity(entName, "sphere.mesh");
  entity->setCastShadows(true);
  
  Ogre::SceneNode *newNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(nodeName);
  newNode->attachObject(entity);

  mPhysics->addRigidSphere(entity, newNode, 0.1f, 1.0f, btVector3(0,0,0), btVector3(x,y,z), new btQuaternion(1.0f, 1.0f, 0, 0))->setLinearVelocity(btVector3(vx, vy, vz));

  // Change Entity Color
  Ogre::MaterialPtr mat = entity->getSubEntity(0)->getMaterial();
  Ogre::Pass *pass = mat->getTechnique(0)->getPass(0);
  pass->setDiffuse(0,1,0,0.1);
  pass->setSpecular(1,1,1,0.4);
  entity->setMaterialName(mat->getName());
}
예제 #12
0
void Level::processEntity(TiXmlElement *XMLNode, Ogre::SceneNode *parent)
{
	Ogre::String name = getAttribute(XMLNode, "name");
	Ogre::String meshFile = getAttribute(XMLNode, "meshFile");

	TiXmlElement *element;
	Ogre::Entity *entity = 0;

	try
	{
		entity = mSceneMgr->createEntity(name, meshFile);
		entity->setCastShadows(true);

		PhysicsManager::instance()->createConvexMesh(entity);

		element = XMLNode->FirstChildElement("subentities");
		if(element)
		{
			element = element->FirstChildElement("subentity");
			while (element)
			{
				Ogre::SubEntity *subEnt;

				Ogre::String materialFile = getAttribute(element, "materialName");
				unsigned int index = Ogre::StringConverter::parseInt(getAttribute(element,"index"));

				subEnt = entity->getSubEntity(index);
				subEnt->setMaterialName(materialFile);

				element = element->NextSiblingElement("subentity");		
			}
		}
		entity->setRenderingDistance(1000);
		parent->attachObject(entity);

	}
	catch(Ogre::Exception e)
	{
		Ogre::LogManager::getSingleton().logMessage("Error loading an entity!");
	}
	element = XMLNode->FirstChildElement("userDataReference");
}
void FvXMLAnimationModelSerializerImpl::ReadEntity( 
	FvXMLSectionPtr spSection, Ogre::SceneNode* pkNode, FvAnimationModel* pkDest )
{
	Ogre::SceneManager *pkSceneManager = Ogre::Root::getSingleton().
		_getCurrentSceneManager();
	FV_ASSERT(pkSceneManager);

	FvString kMeshIdentifier = spSection->ReadString("identifier");
	FvString kMeshFile = spSection->ReadString("mesh");

	Ogre::Entity *pkEntity = pkSceneManager->createEntity(
		pkNode->getName() + "_" + kMeshIdentifier,kMeshFile);
	FV_ASSERT(pkEntity);
	pkEntity->setCastShadows(pkDest->m_bCastShadows);
	pkNode->attachObject(pkEntity);
	
	pkDest->m_akNodes[pkDest->m_u32CurrentLodLevel].m_kEntityList.push_back(pkEntity);
	pkEntity->setRenderQueueGroup(RENDER_QUEUE_MAX);
	AnimationStateSet *pkAnimations = pkEntity->getAllAnimationStates();
	if(pkAnimations)
	{
		AnimationStateIterator kIt = pkAnimations->getAnimationStateIterator();
		while (kIt.hasMoreElements())
		{
			AnimationState *pkAnim= kIt.getNext();
			if(pkDest->GetAnimation(pkAnim->getAnimationName()) == NULL)
				pkDest->m_kModelAnimations.insert(std::make_pair(pkAnim->getAnimationName(),pkAnim));
		}
	}

	std::vector<FvXMLSectionPtr> kSubentities;
	spSection->OpenSections("subentities/subentity",kSubentities);
	std::vector<FvXMLSectionPtr>::iterator kSubIt = kSubentities.begin();
	for(; kSubIt != kSubentities.end(); ++kSubIt)
	{
		int iIndex = (*kSubIt)->ReadInt("index",-1);
		FvString kMaterialName = (*kSubIt)->ReadString("materialName");
		Ogre::SubEntity *pkSubEntity = pkEntity->getSubEntity(iIndex);
		if(pkSubEntity && !kMaterialName.empty())
			pkSubEntity->setMaterialName(kMaterialName);
	}
}
예제 #14
0
		void MaterialChain::build(){
			Parent::build();
			Ogre::Entity* entity = mGo->getEntity();
			int j=entity->getNumManualLodLevels();

			for (int i=-1;i<j;i++){
				Ogre::Entity* lodEnt;
				if (i > -1){
					lodEnt  = entity->getManualLodLevel(i);
				}else{
					lodEnt  = entity;
				}
				for (int k=0;k<lodEnt->getNumSubEntities();k++){
					Ogre::SubEntity* subEnt = lodEnt->getSubEntity(k);
					if (subEnt->getMaterialName() == mSource){
						mEntityToReplace.push_back(subEnt);
					}
				}
			}
		}
예제 #15
0
ActivatorAnimation::ActivatorAnimation(const MWWorld::Ptr &ptr)
  : Animation(ptr)
{
    MWWorld::LiveCellRef<ESM::Activator> *ref = mPtr.get<ESM::Activator>();

    assert (ref->mBase != NULL);
    if(!ref->mBase->mModel.empty())
    {
        std::string mesh = "meshes\\" + ref->mBase->mModel;

        createEntityList(mPtr.getRefData().getBaseNode(), mesh);
        for(size_t i = 0;i < mEntityList.mEntities.size();i++)
        {
            Ogre::Entity *ent = mEntityList.mEntities[i];

            bool transparent = false;
            for (unsigned int j=0;j < ent->getNumSubEntities() && !transparent; ++j)
            {
                Ogre::MaterialPtr mat = ent->getSubEntity(j)->getMaterial();
                Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
                while (techIt.hasMoreElements() && !transparent)
                {
                    Ogre::Technique* tech = techIt.getNext();
                    Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                    while (passIt.hasMoreElements() && !transparent)
                    {
                        Ogre::Pass* pass = passIt.getNext();

                        if (pass->getDepthWriteEnabled() == false)
                            transparent = true;
                    }
                }
            }
            ent->setVisibilityFlags(RV_Misc);
            ent->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
        }
        setAnimationSource(mesh);
    }
}
bool np::HubConstructionComponent::addToConstruction( np::NeuroPlayer* player, double amount)
{
    std::list<np::HubConstructionSlot>::iterator iterator;

    iterator = slots.begin();
    while ( iterator != slots.end())
    {
        np::HubConstructionSlot& slot = *iterator;

        if ( slot.player == player)
        {
            slot.amount += amount;

            np::GraphicComponent* graphic = slot.proxyHub->getComponent<np::GraphicComponent>();

            Ogre::Entity* entity = graphic->entities.front();
            Ogre::MaterialPtr material = entity->getSubEntity(0)->getMaterial();
            material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setAlphaOperation(
                Ogre::LBX_SOURCE1,
                Ogre::LBS_MANUAL,
                Ogre::LBS_CURRENT,
                ( slot.amount / 60.0) * 0.6);
            entity->setMaterial( material);

            if ( slot.amount >= 60.0)
            {
                return true;
            }

            return false;
        }

        iterator++;
    }

    return false;
}
예제 #17
0
bool GameNeedleComponent::load(Ogre::SceneNode * node)
{

	using namespace Ogre;
	Ogre::SceneManager * sm = Orz::OgreGraphicsManager::getSingleton().getSceneManager();
	Ogre::Entity * needle = sm->createEntity("needle", "poniter.mesh");
	node->createChildSceneNode(Ogre::Vector3(0, 0 , 0))->attachObject(needle);
	_semi.reset(new SubEntityMaterialInstance(needle->getSubEntity(1)));
	
	//needle->getSubEntity(1)->getMaterial()->addListener;
	CGameFlowerInterface * flower = _flowerComp->queryInterface<CGameFlowerInterface>();
	/*Ogre::SceneNode * sn = node->createChildSceneNode(Ogre::Vector3(310, 180, 0));
	Light* light;

	light = sm->createLight();
	light->setType(Ogre::Light::LT_POINT);
	light->setAttenuation(80, 1, 0, 0);
	light->setDiffuseColour(Ogre::ColourValue::White);
	sn->attachObject(light);*/
	//sn->attachObject(sm->createEntity("ogrehe", "ogrehead.mesh"));
	flower->load(node);

	return true;
}
예제 #18
0
NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWorld::InventoryStore& _inv, int visibilityFlags)
    : Animation(), mStateID(-1), mInv(_inv), timeToChange(0), mVisibilityFlags(visibilityFlags),
    robe(mInv.end()), helmet(mInv.end()), shirt(mInv.end()),
    cuirass(mInv.end()), greaves(mInv.end()),
    leftpauldron(mInv.end()), rightpauldron(mInv.end()),
    boots(mInv.end()),
    leftglove(mInv.end()), rightglove(mInv.end()), skirtiter(mInv.end()),
    pants(mInv.end())
{
    MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();

    for (int init = 0; init < 27; init++)
    {
        mPartslots[init] = -1;  //each slot is empty
        mPartPriorities[init] = 0;
    }

    const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
    const ESM::Race *race = store.races.find(ref->base->mRace);

    std::string hairID = ref->base->mHair;
    std::string headID = ref->base->mHead;
    headModel = "meshes\\" + store.bodyParts.find(headID)->mModel;
    hairModel = "meshes\\" + store.bodyParts.find(hairID)->mModel;
    npcName = ref->base->mName;

    isFemale = !!(ref->base->mFlags&ESM::NPC::Female);
    isBeast = !!(race->mData.mFlags&ESM::Race::Beast);

    bodyRaceID = "b_n_"+ref->base->mRace;
    std::transform(bodyRaceID.begin(), bodyRaceID.end(), bodyRaceID.begin(), ::tolower);


    mInsert = node;
    assert(mInsert);

    std::string smodel = (!isBeast ? "meshes\\base_anim.nif" : "meshes\\base_animkna.nif");

    mEntityList = NifOgre::NIFLoader::createEntities(mInsert, &mTextKeys, smodel);
    for(size_t i = 0;i < mEntityList.mEntities.size();i++)
    {
        Ogre::Entity *base = mEntityList.mEntities[i];

        base->getUserObjectBindings ().setUserAny (Ogre::Any(-1));

        base->setVisibilityFlags(mVisibilityFlags);
        bool transparent = false;
        for(unsigned int j=0;j < base->getNumSubEntities();++j)
        {
            Ogre::MaterialPtr mat = base->getSubEntity(j)->getMaterial();
            Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
            while (techIt.hasMoreElements())
            {
                Ogre::Technique* tech = techIt.getNext();
                Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                while (passIt.hasMoreElements())
                {
                    Ogre::Pass* pass = passIt.getNext();
                    if (pass->getDepthWriteEnabled() == false)
                        transparent = true;
                }
            }
        }
        base->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
    }

    if(mEntityList.mSkelBase)
    {
        Ogre::AnimationStateSet *aset = mEntityList.mSkelBase->getAllAnimationStates();
        Ogre::AnimationStateIterator as = aset->getAnimationStateIterator();
        while(as.hasMoreElements())
        {
            Ogre::AnimationState *state = as.getNext();
            state->setEnabled(true);
            state->setLoop(false);
        }
    }

    float scale = race->mData.mHeight.mMale;
    if (isFemale) {
        scale = race->mData.mHeight.mFemale;
    }
    mInsert->scale(scale, scale, scale);

    updateParts();
}
예제 #19
0
NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWorld::InventoryStore& inv, int visibilityFlags, bool headOnly)
  : Animation(ptr),
    mStateID(-1),
    mTimeToChange(0),
    mVisibilityFlags(visibilityFlags),
    mRobe(inv.end()),
    mHelmet(inv.end()),
    mShirt(inv.end()),
    mCuirass(inv.end()),
    mGreaves(inv.end()),
    mPauldronL(inv.end()),
    mPauldronR(inv.end()),
    mBoots(inv.end()),
    mPants(inv.end()),
    mGloveL(inv.end()),
    mGloveR(inv.end()),
    mSkirtIter(inv.end()),
    mHeadOnly(headOnly)
{
    mNpc = mPtr.get<ESM::NPC>()->mBase;

    for(size_t i = 0;i < sPartListSize;i++)
    {
        mPartslots[i] = -1;  //each slot is empty
        mPartPriorities[i] = 0;
    }

    const MWWorld::ESMStore &store =
        MWBase::Environment::get().getWorld()->getStore();
    const ESM::Race *race = store.get<ESM::Race>().find(mNpc->mRace);

    float scale = race->mData.mHeight.mMale;
    if(!mNpc->isMale())
        scale = race->mData.mHeight.mFemale;
    node->scale(Ogre::Vector3(scale));

    mHeadModel = "meshes\\" + store.get<ESM::BodyPart>().find(mNpc->mHead)->mModel;
    mHairModel = "meshes\\" + store.get<ESM::BodyPart>().find(mNpc->mHair)->mModel;

    mBodyPrefix = "b_n_" + mNpc->mRace;
    Misc::StringUtils::toLower(mBodyPrefix);

    bool isBeast = (race->mData.mFlags & ESM::Race::Beast) != 0;
    std::string smodel = (!isBeast ? "meshes\\base_anim.nif" : "meshes\\base_animkna.nif");

    createEntityList(node, smodel);
    for(size_t i = 0;i < mEntityList.mEntities.size();i++)
    {
        Ogre::Entity *base = mEntityList.mEntities[i];

        base->getUserObjectBindings().setUserAny(Ogre::Any(-1));
        if (mVisibilityFlags != 0)
            base->setVisibilityFlags(mVisibilityFlags);

        for(unsigned int j=0; j < base->getNumSubEntities(); ++j)
        {
            Ogre::SubEntity* subEnt = base->getSubEntity(j);
            subEnt->setRenderQueueGroup(subEnt->getMaterial()->isTransparent() ? RQG_Alpha : RQG_Main);
        }
    }

    std::vector<std::string> skelnames(1, smodel);
    if(!mNpc->isMale() && !isBeast)
        skelnames.push_back("meshes\\base_anim_female.nif");
    else if(mBodyPrefix.find("argonian") != std::string::npos)
        skelnames.push_back("meshes\\argonian_swimkna.nif");
    if(mNpc->mModel.length() > 0)
        skelnames.push_back("meshes\\"+Misc::StringUtils::lowerCase(mNpc->mModel));
    setAnimationSources(skelnames);

    updateParts(true);
}
예제 #20
0
파일: objects.cpp 프로젝트: darkf/openmw
void Objects::insertMesh (const MWWorld::Ptr& ptr, const std::string& mesh, bool light)
{
    Ogre::SceneNode* insert = ptr.getRefData().getBaseNode();
    assert(insert);

    Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
    NifOgre::ObjectList objects = NifOgre::Loader::createObjects(insert, mesh);
    for(size_t i = 0;i < objects.mEntities.size();i++)
        bounds.merge(objects.mEntities[i]->getWorldBoundingBox(true));

    Ogre::Vector3 extents = bounds.getSize();
    extents *= insert->getScale();
    float size = std::max(std::max(extents.x, extents.y), extents.z);

    bool small = (size < Settings::Manager::getInt("small object size", "Viewing distance")) && Settings::Manager::getBool("limit small object distance", "Viewing distance");

    // do not fade out doors. that will cause holes and look stupid
    if (ptr.getTypeName().find("Door") != std::string::npos)
        small = false;

    if (mBounds.find(ptr.getCell()) == mBounds.end())
        mBounds[ptr.getCell()] = Ogre::AxisAlignedBox::BOX_NULL;
    mBounds[ptr.getCell()].merge(bounds);

    bool anyTransparency = false;
    for(size_t i = 0;!anyTransparency && i < objects.mEntities.size();i++)
    {
        Ogre::Entity *ent = objects.mEntities[i];
        for(unsigned int i=0;!anyTransparency && i < ent->getNumSubEntities(); ++i)
        {
            anyTransparency = ent->getSubEntity(i)->getMaterial()->isTransparent();
        }
    }

    if(!mIsStatic || !Settings::Manager::getBool("use static geometry", "Objects") ||
       anyTransparency || objects.mParticles.size() > 0)
    {
        for(size_t i = 0;i < objects.mEntities.size();i++)
        {
            Ogre::Entity *ent = objects.mEntities[i];
            for(unsigned int i=0; i < ent->getNumSubEntities(); ++i)
            {
                Ogre::SubEntity* subEnt = ent->getSubEntity(i);
                subEnt->setRenderQueueGroup(subEnt->getMaterial()->isTransparent() ? RQG_Alpha : RQG_Main);
            }
            ent->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            ent->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        }
        for(size_t i = 0;i < objects.mParticles.size();i++)
        {
            Ogre::ParticleSystem *part = objects.mParticles[i];
            // TODO: Check the particle system's material for actual transparency
            part->setRenderQueueGroup(RQG_Alpha);
            part->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            part->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        }
    }
    else
    {
        Ogre::StaticGeometry* sg = 0;

        if (small)
        {
            if( mStaticGeometrySmall.find(ptr.getCell()) == mStaticGeometrySmall.end())
            {
                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometrySmall[ptr.getCell()] = sg;

                sg->setRenderingDistance(Settings::Manager::getInt("small object distance", "Viewing distance"));
            }
            else
                sg = mStaticGeometrySmall[ptr.getCell()];
        }
        else
        {
            if( mStaticGeometry.find(ptr.getCell()) == mStaticGeometry.end())
            {

                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometry[ptr.getCell()] = sg;
            }
            else
                sg = mStaticGeometry[ptr.getCell()];
        }

        // This specifies the size of a single batch region.
        // If it is set too high:
        //  - there will be problems choosing the correct lights
        //  - the culling will be more inefficient
        // If it is set too low:
        //  - there will be too many batches.
        sg->setRegionDimensions(Ogre::Vector3(2500,2500,2500));

        sg->setVisibilityFlags(small ? RV_StaticsSmall : RV_Statics);

        sg->setCastShadows(true);

        sg->setRenderQueueGroup(RQG_Main);

        std::vector<Ogre::Entity*>::reverse_iterator iter = objects.mEntities.rbegin();
        while(iter != objects.mEntities.rend())
        {
            Ogre::Node *node = (*iter)->getParentNode();
            sg->addEntity(*iter, node->_getDerivedPosition(), node->_getDerivedOrientation(), node->_getDerivedScale());

            (*iter)->detachFromParent();
            mRenderer.getScene()->destroyEntity(*iter);
            iter++;
        }
    }

    if (light)
    {
        insertLight(ptr, objects.mSkelBase, bounds.getCenter() - insert->_getDerivedPosition());
    }
}
예제 #21
0
void DivBoxLevel::makeElementBoxes(
    const QWebElement &document,
    Ogre::Real scale,
    std::vector<QString> tags,
    Ogre::String meshName,
    Ogre::SceneManager * sceneManager) {

  DotSceneLoader* pDotSceneLoader = new DotSceneLoader();
  pDotSceneLoader->parseDotScene("papercraft_man_line_running.scene",
      "General", sceneManager, sceneManager->getRootSceneNode());
  delete pDotSceneLoader;

  Animation::Instance().animationStates.clear();
  Animation::Instance().init(sceneManager, "arm_left");
  Animation::Instance().init(sceneManager, "arm_right");
  Animation::Instance().init(sceneManager, "chest");
  Animation::Instance().init(sceneManager, "leg_left");
  Animation::Instance().init(sceneManager, "leg_right");
  Animation::Instance().init(sceneManager, "pants");

  QWebElementCollection elements;
  foreach(QString tag, tags)
    elements.append(document.findAll(tag));

  Ogre::Vector3 position = Ogre::Vector3(0.0, 1000.0, 0.0);

  int elementCount = 0;
  foreach(QWebElement element, elements) {
      if (fits(&element, 10, 4096)) {
        Ogre::String textureName =
            "PageTex"  + element.tagName().toStdString()
            + Ogre::StringConverter::toString(elementCount);

        Box box;
        box.width = element.geometry().width()*scale;
        box.height = element.geometry().height()*scale;

        box.sceneNode = sceneManager->createSceneNode(textureName);

        element.setStyleProperty("background-color", "white");

        Ogre::Entity* cube = sceneManager->createEntity(meshName);

        makeOgreImage(&element, textureName);
        Ogre::MaterialPtr material =
            makeMaterial("PageMat" + Ogre::StringConverter::toString(position),
            textureName, 1.3);
        cube->getSubEntity(1)->setMaterial(material);
        box.sceneNode->attachObject(cube);
        box.sceneNode->setScale(box.width, box.height, box.width);

        if (box.width > 50)
          bigBoxes.push_back(box);
        else if (box.width > 5)
          smallBoxes.push_back(box);

        elementCount++;
      }
  }

  int smallBoxIndex = 0;

  for (int i = 0; i < bigBoxes.size(); i++) {
    CollisionActor* actor = simulation->terrainFactory->createActor()
       ->addPoint(bigBoxes[i].width, bigBoxes[i].height)
       ->addPoint(-bigBoxes[i].width, -bigBoxes[i].height)
       ->createCollisionShape(CollisionShape2::DEF_AABB);

    if (i == 0) {
// FIRST PLANE-----------------------
      actor->teleport(100.0, 100.0);

      characterSceneNode = simulation->characterFactory->createActor()
          ->addPoint(4.0, 30.0)
          ->addPoint(-4.0, -10.0)
          ->createCollisionShape(CollisionShape2::DEF_CONVEX)
          ->teleport(100.0, bigBoxes[i].height * 2 + 200.0)
          ->sceneNode;

      Ogre::SceneNode* sn = sceneManager->getSceneNode("Armature");
      sceneManager->getRootSceneNode()->removeChild(sn);
      characterSceneNode->addChild(sn);
      sn->scale(0.4, 0.4, 0.4);
      sn->translate(0, 10, 0);
      sn->setOrientation(
          Ogre::Quaternion(Ogre::Degree(90.0), Ogre::Vector3::UNIT_Y));

    } else {
// FURTHER PLANES--------------------
      float lX = bigBoxes[i - 1].sceneNode->_getDerivedPosition().x;
      float lY = bigBoxes[i - 1].sceneNode->_getDerivedPosition().y;
      float lW = bigBoxes[i - 1].width;
      float lH = bigBoxes[i - 1].height;
      float cX = bigBoxes[i].sceneNode->_getDerivedPosition().x;
      float cY = bigBoxes[i].sceneNode->_getDerivedPosition().y;
      float cW = bigBoxes[i].width;
      float cH = bigBoxes[i].height;

      if (cH - lH > 50.0 && smallBoxes.size() - 1 - smallBoxIndex > 1) {
        // current is mutch higher then last
        actor->teleport(lX + lW + cW, 100.0);

        float sX = smallBoxes[smallBoxIndex].sceneNode->_getDerivedPosition().x;
        float sY = smallBoxes[smallBoxIndex].sceneNode->_getDerivedPosition().y;
        float sW = smallBoxes[smallBoxIndex].width;
        float sH = smallBoxes[smallBoxIndex].height;
        CollisionActor* hoverplane = simulation->hoverplaneFactory
            ->createActor()
            ->addPoint(sW, sH)
            ->addPoint(-sW, -sH)
            ->createCollisionShape(CollisionShape2::DEF_AABB);
        static_cast<Hoverplane*>(hoverplane)
                      ->setSpeed(0.2 + static_cast<float>
                  (static_cast<int>(lX * cX * cW) % 5) * 0.1)
            ->setPath(lX + lW - sW - 100.0, lY + lH - sH + 10.0,
                lX + lW - sW - 100.0, lY + lH - sH + cH - lH);
        hoverplane->sceneNode->addChild(smallBoxes[smallBoxIndex].sceneNode);
        smallBoxIndex++;
      } else {
        if (lH - cH > 50.0 && smallBoxes.size() - 1 - smallBoxIndex > 1) {
          actor->teleport(lX + lW + cW, 100.0);

          float sX = smallBoxes[smallBoxIndex].sceneNode->
              _getDerivedPosition().x;
          float sY = smallBoxes[smallBoxIndex].sceneNode->
              _getDerivedPosition().y;
          float sW = smallBoxes[smallBoxIndex].width;
          float sH = smallBoxes[smallBoxIndex].height;

          CollisionActor* hoverplane = simulation->hoverplaneFactory
              ->createActor()
              ->addPoint(sW, sH)
              ->addPoint(-sW, -sH)
              ->createCollisionShape(CollisionShape2::DEF_AABB);
          static_cast<Hoverplane*>(hoverplane)
                      ->setSpeed(0.2 + static_cast<float>
                  (static_cast<int>(lX * cX * cW) % 5) * 0.1)
              ->setPath(cX, cY + cH + sH + 10.0,
                  cX, cY + cH + sH + lH);
          hoverplane->sceneNode->addChild(smallBoxes[smallBoxIndex].sceneNode);
          smallBoxIndex++;
        } else {
          if (i%3 == 2 && smallBoxes.size() - 1 - smallBoxIndex > 3) {
            actor->teleport(lX + lW + cW +
                smallBoxes[smallBoxIndex].sceneNode
                ->_getDerivedPosition().x +
                smallBoxes[smallBoxIndex+1].sceneNode
                ->_getDerivedPosition().x +
                smallBoxes[smallBoxIndex+2].sceneNode
                ->_getDerivedPosition().x
                + 400.0,
                100.0);
            {
              float sX = smallBoxes[smallBoxIndex].sceneNode->
                  _getDerivedPosition().x;
              float sY = smallBoxes[smallBoxIndex].sceneNode->
                  _getDerivedPosition().y;
              float sW = smallBoxes[smallBoxIndex].width;
              float sH = smallBoxes[smallBoxIndex].height;
              CollisionActor* hoverplane = simulation->hoverplaneFactory
                  ->createActor()
                  ->addPoint(sW, sH)
                  ->addPoint(-sW, -sH)
                  ->createCollisionShape(CollisionShape2::DEF_AABB);
              static_cast<Hoverplane*>(hoverplane)
                      ->setSpeed(0.1 + static_cast<float>
                  (static_cast<int>(lX * cX * sW) % 5) * 0.1)
                  ->setPath(lX + lW + 100.0, lY + lH - sH,
                      lX + lW + 100.0, lY + lH + cH + 200.0);
              hoverplane->sceneNode
              ->addChild(smallBoxes[smallBoxIndex].sceneNode);
            }
            {
              float sX = smallBoxes[smallBoxIndex+1].sceneNode->
                  _getDerivedPosition().x;
              float sY = smallBoxes[smallBoxIndex+1].sceneNode->
                  _getDerivedPosition().y;
              float sW = smallBoxes[smallBoxIndex+1].width;
              float sH = smallBoxes[smallBoxIndex+1].height;
              CollisionActor* hoverplane = simulation->hoverplaneFactory
                  ->createActor()
                  ->addPoint(sW, sH)
                  ->addPoint(-sW, -sH)
                  ->createCollisionShape(CollisionShape2::DEF_AABB);
              static_cast<Hoverplane*>(hoverplane)
                      ->setSpeed(0.2 + static_cast<float>
                  (static_cast<int>(lX * cX * sW) % 5) * 0.1)
                  ->setPath(lX + lW + 200.0, lY + lH - sH,
                      lX + lW + 200.0, lY + lH + cH + 200.0);
              hoverplane->sceneNode
              ->addChild(smallBoxes[smallBoxIndex+1].sceneNode);
            }
            {
              float sX = smallBoxes[smallBoxIndex+2].sceneNode->
                  _getDerivedPosition().x;
              float sY = smallBoxes[smallBoxIndex+2].sceneNode->
                  _getDerivedPosition().y;
              float sW = smallBoxes[smallBoxIndex+2].width;
              float sH = smallBoxes[smallBoxIndex+2].height;
              CollisionActor* hoverplane = simulation->hoverplaneFactory
                  ->createActor()
                  ->addPoint(sW, sH)
                  ->addPoint(-sW, -sH)
                  ->createCollisionShape(CollisionShape2::DEF_AABB);
              static_cast<Hoverplane*>(hoverplane)
                  ->setSpeed(0.15 + static_cast<float>
              (static_cast<int>(lX * cX * sW) % 5) * 0.1)
                  ->setPath(lX + lW + 300.0, lY + lH - sH,
                      lX + lW + 300.0, lY + lH + cH + 200.0);
              hoverplane->sceneNode
              ->addChild(smallBoxes[smallBoxIndex+2].sceneNode);
            }

            smallBoxIndex += 3;
          } else {
            actor->teleport(lX + lW + cW + 100.0, 100.0);
          }
        }
      }
    }
    actor->sceneNode->addChild(bigBoxes[i].sceneNode);
    qDebug() << "dooors" << doors.size() << "\n\n";
    if ((i == (bigBoxes.size()-1) / 2 || i == bigBoxes.size()-1)
        && this->doors.size() >= 1) {
      CollisionActor* door;

      if (i == (bigBoxes.size()-1) / 2) {
        door = this->doors[0];
        qDebug() << "dooors0\n\n\n\n\n";
      } else {
        door = this->doors[0];
        qDebug() << "dooors1\n\n\n\n\n";
      }
      door
          ->addPoint(0.0, 0.0)
          ->addPoint(40., 60.)
          ->createCollisionShape(CollisionShape2::DEF_AABB)
          ->teleport(
              bigBoxes[i].sceneNode->_getDerivedPosition().x,
              bigBoxes[i].sceneNode->_getDerivedPosition().y
              + bigBoxes[i].height);

      Ogre::Entity* doorEntity = sceneManager->createEntity("door.mesh");
      door->sceneNode->attachObject(doorEntity);
      door->sceneNode->setScale(20, 30, 20);
      door->sceneNode->setOrientation(
              Ogre::Quaternion(Ogre::Degree(180.0), Ogre::Vector3::UNIT_Y));
    }
  }
}
예제 #22
0
Entity Factory::createTank(entityx::ptr<entityx::EntityManager> entityMgr, std::string prefix,Ogre::Real velocity,Ogre::Real angularVelocity ,Ogre::Vector3 overHating,int health,bool ai)
{
    DotSceneLoader loader;
    Ogre::SceneManager* sceneMgr = RenderManager::getPtr()->getSceneManager();

    loader.parseDotScene("tank.scene", "General", sceneMgr, 0, prefix);

    Ogre::SceneNode* ctl = sceneMgr->getSceneNode(prefix + "TankControl");
    Ogre::SceneNode* body = sceneMgr->getSceneNode(prefix + "TankBody");
    Ogre::SceneNode* turret = sceneMgr->getSceneNode(prefix + "TankTurret");
    Ogre::SceneNode* cannon = sceneMgr->getSceneNode(prefix +"TankCannon");

    Entity tankEmptyControl = entityMgr->create();
    Entity tankTurret = entityMgr->create();
    Entity tankBody = entityMgr->create();
    Entity tankCannon = entityMgr->create();

    tankEmptyControl.assign<Position>(ctl->getPosition());
    tankEmptyControl.assign<Orientation>(ctl->getOrientation());
    tankEmptyControl.assign<Velocity>(0, 0, velocity);
    tankEmptyControl.assign<AngularVelocity>(0, angularVelocity, 0);
    tankEmptyControl.assign<Renderable>(ctl);
    tankEmptyControl.assign<OverHeating>(overHating.x,overHating.y,overHating.z);
    tankEmptyControl.assign<Destroyable>(health,health);
    tankEmptyControl.assign<Collidable>();
    tankEmptyControl.assign<Name>(prefix);
    if(ai){
        tankEmptyControl.assign<AI>();
        Ogre::Entity *model = static_cast<Ogre::Entity*>(body->getAttachedObject(0));
        model->getSubEntity(1)->setMaterialName("Red");

        model = static_cast<Ogre::Entity*>(turret->getAttachedObject(0));
        model->getSubEntity(1)->setMaterialName("Red");

        model = static_cast<Ogre::Entity*>(cannon->getAttachedObject(0));
        model->getSubEntity(1)->setMaterialName("Red");

    }

    ptr<Children> child = tankEmptyControl.assign<Children>();
    child->children["body"] = tankBody;
    child->children["turret"] = tankTurret;
    //child->children.push_back(tankBody);
    //child->children.push_back(tankTurret);

    tankTurret.assign<Position>(turret->getPosition());
    tankTurret.assign<Orientation>(turret->getOrientation());
    tankTurret.assign<Renderable>(turret);
    child = tankTurret.assign<Children>();
    child->children["cannon"] = tankCannon;

    tankBody.assign<Position>(body->getPosition());
    tankBody.assign<Orientation>(body->getOrientation());
    tankBody.assign<Renderable>(body);

    tankCannon.assign<Position>(cannon->getPosition());
    tankCannon.assign<Renderable>(cannon);
    tankCannon.assign<Orientation>(cannon->getOrientation());


    ctl->scale(.35, .55, .35);
    return tankEmptyControl;
}
예제 #23
0
파일: main.cpp 프로젝트: Heartbroken/heart
void test()
{
	Ogre::Root* pOgre = new Ogre::Root("", "");

    pOgre->loadPlugin(RENDER_SYSTEM);
	pOgre->setRenderSystem(pOgre->getAvailableRenderers().front());

	pOgre->initialise(false);
	
	Ogre::NameValuePairList lArgs;
	//lArgs["externalWindowHandle"] = bk::format("%d", (bk::uint)l_window.get_handle()).astr;
	Ogre::RenderWindow* pWindow = pOgre->createRenderWindow("Heart|Dockyard", 1024, 768, false, &lArgs);

	Ogre::SceneManager* pSceneManager = pOgre->createSceneManager(Ogre::ST_GENERIC,"SceneManager");
	pSceneManager->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
	pSceneManager->setShadowCameraSetup(Ogre::ShadowCameraSetupPtr(new Ogre::FocusedShadowCameraSetup()));
	pSceneManager->setAmbientLight(Ogre::ColourValue(0.1f, 0.1f, 0.1f));

	Ogre::Camera* pCamera = pSceneManager->createCamera("Camera");
	pCamera->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z);
	pCamera->setPosition(Ogre::Vector3(0.0f, 50.0f, 20.0f));
	pCamera->lookAt(Ogre::Vector3(0.0f, 0.0f, 0.0f)); 
	pCamera->setNearClipDistance(0.1f);
	pCamera->setFarClipDistance(100.0f);
	Ogre::Viewport* pViewport = pWindow->addViewport(pCamera);
	pViewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
	pCamera->setAspectRatio(Ogre::Real(pViewport->getActualWidth()) / Ogre::Real(pViewport->getActualHeight()));

	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../data/dockyard.zip", "Zip", "Dockyard", true);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	Ogre::MeshManager::getSingleton().createPlane("GroundPlane", "Dockyard", Ogre::Plane(0.0f, 0.0f, 1.0f, 0.0f), 100.0f, 100.0f, 100, 100, true, 1, 3.0f, 3.0f);
	Ogre::Entity* pGroundEntity = pSceneManager->createEntity("GroundPlane");
	pGroundEntity->setMaterialName("Examples/Rockwall");
	pGroundEntity->setCastShadows(false);
	pGroundEntity->getSubEntity(0)->getMaterial()->setShadingMode(Ogre::SO_PHONG);
	Ogre::SceneNode* pGroundNode = pSceneManager->getRootSceneNode()->createChildSceneNode();
	pGroundNode->attachObject(pGroundEntity);

	Ogre::Entity* pCubeEntity = pSceneManager->createEntity("Cube", Ogre::SceneManager::PT_CUBE);
	pCubeEntity->setMaterialName("Examples/10PointBlock");
	pCubeEntity->setCastShadows(true);
	Ogre::SceneNode* pCubeNode = pSceneManager->getRootSceneNode()->createChildSceneNode();
	pCubeNode->attachObject(pCubeEntity);
	pCubeNode->setPosition(0.0f, 0.0f, 5.f);
	pCubeNode->setScale(0.1f, 0.1f, 0.1f);

	Ogre::ColourValue lColour1(1.0f, 1.0f, 1.0f);
	Ogre::ColourValue lColour2(1.0f, 1.0f, 1.0f);
	Ogre::ColourValue lColour3(1.0f, 1.0f, 1.0f);
	Ogre::Light* pLight1 = pSceneManager->createLight();
	pLight1->setType(Ogre::Light::LT_SPOTLIGHT);
	pLight1->setPosition(30.0f, 30.0f, 30.0f);
	pLight1->setDirection(-1.0f, -1.0f, -1.0f);
	pLight1->setSpotlightRange(Ogre::Degree(30), Ogre::Degree(50));
	pLight1->setDiffuseColour(lColour1 * 0.5f);
	Ogre::Light* pLight2 = pSceneManager->createLight();
	pLight2->setType(Ogre::Light::LT_SPOTLIGHT);
	pLight2->setPosition(-30.0f, 30.0f, 30.0f);
	pLight2->setDirection(1.0f, -1.0f, -1.0f);
	pLight2->setSpotlightRange(Ogre::Degree(30), Ogre::Degree(50));
	pLight2->setDiffuseColour(lColour2 * 0.5f);
	Ogre::Light* pLight3 = pSceneManager->createLight();
	pLight3->setType(Ogre::Light::LT_SPOTLIGHT);
	pLight3->setPosition(30.0f, -30.0f, 30.0f);
	pLight3->setDirection(-1.0f, 1.0f, -1.0f);
	pLight3->setSpotlightRange(Ogre::Degree(30), Ogre::Degree(50));
	pLight3->setDiffuseColour(lColour3 * 0.5f);

	Ogre::Overlay* pMenuOverlay = Ogre::OverlayManager::getSingleton().create("Menu");
	Ogre::OverlayElement* pMenu = Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "Menu");
    pMenu->setMetricsMode(Ogre::GMM_PIXELS);
    pMenu->setWidth(200);
    pMenu->setHeight(200);
    pMenu->setTop(30);
    pMenu->setLeft(30);
    pMenu->setMaterialName("Examples/BumpyMetal");
	if (pMenu->isContainer()) pMenuOverlay->add2D(static_cast<Ogre::OverlayContainer*>(pMenu));
	pMenuOverlay->show();

	pOgre->startRendering();
}
예제 #24
0
// 设置选中的外观颜色.
void CEditDobject_NT::SetSelectLook(Ogre::ColourValue color)
{

	if(0 == m_materialSelVector.size())
	{
		// 选中材质的名字.
		Ogre::String strCloneName;
		int iCount = m_EntityList.size();
		Ogre::Entity* pEntity = NULL;

		for(int i = 0; i < iCount; i++)
		{
			pEntity = m_EntityList[i].pEntity;
			if(pEntity)
			{
				Ogre::SubEntity* pSubEntiy = pEntity->getSubEntity(0);
				if(pSubEntiy)
				{
					
					Ogre::MaterialPtr pMaterial = pSubEntiy->getMaterial();
					
					if(pMaterial.isNull())
					{
						return;
					}//

					const Ogre::String& strName = pMaterial->getName();

					if("BaseWhite" == strName)
					{
						continue;
					}

					strCloneName = strName;
					strCloneName += "_select";
					
					Ogre::MaterialManager* pMaterialManager = (Ogre::MaterialManager*)(pMaterial->getCreator());

					if(NULL == pMaterialManager)
					{
						return;
					}

					Ogre::MaterialPtr pMaterialClone = pMaterialManager->getByName(strCloneName); 
						
					if(pMaterialClone.isNull())
					{
						pMaterialClone = pMaterial->clone(strCloneName);
					}
					//if(!pMaterialClone)
					//{
					//	return;
					//}//

					Ogre::Technique* pTechnique = pMaterialClone->getBestTechnique();
					Ogre::Pass* pPass = pTechnique->getPass(0);

					//pPass->setSceneBlending(SBT_ADD);
					//pPass->setSceneBlending(SBF_SOURCE_ALPHA , SBF_ONE_MINUS_SOURCE_ALPHA );
					//pTextureState->setAlphaOperation(LBX_MODULATE, LBS_TEXTURE, LBS_MANUAL, 1, Transparence, 1);//
				
					Ogre::TextureUnitState* pTextureState = pPass->getTextureUnitState(0);
					pTextureState->setColourOperationEx(Ogre::LBX_ADD , Ogre::LBS_TEXTURE , Ogre::LBS_MANUAL, color, color );
					pSubEntiy->setMaterialName(strCloneName);
					m_materialSelVector.push_back(pMaterialClone);
					m_materilaOldVector.push_back(pMaterial);
					
				}

			}
		}
	}
	else
	{
		int iIndex = 0;

		int iCount = m_EntityList.size();
		Ogre::Entity* pEntity = NULL;

		for(int i = 0; i < iCount; i++)
		{
			pEntity = m_EntityList[i].pEntity;
			if(pEntity)
			{
				Ogre::SubEntity* pSubEntiy = pEntity->getSubEntity(0);
				
				if(pSubEntiy)
				{
					if(iIndex >= (int)m_materialSelVector.size())
					{
						continue;
					}

					std::string strMaterialName = m_materialSelVector[iIndex]->getName();
					pSubEntiy->setMaterialName(strMaterialName);	
					iIndex++;
				}

			}
		}
	}
}
예제 #25
0
VBOOL VLogicModel::_setEntityMaterial(const VString &entityName, const VString &matName)
{
    if (matName.empty())
    {
        return VTRUE;
    }
    else
    {
        VEntityMap::iterator itr = mEntities.find(entityName);

        if (itr == mEntities.end())
        {
            Ogre::LogManager::getSingleton().logMessage( "Logic Model Entity with name '" + entityName + "' dosen't exists! " +
                    "LogicModel::_setEntityMaterial " + mName );
            return VFALSE;
        }

        VEntityValue &entValue = itr->second;
        Ogre::Entity *entity = entValue.mEntity;
        assert(entity);

        if (matName.find(";") != VString::npos)
        {
            Ogre::StringVector matNames = Ogre::StringUtil::split(matName, ";");
            assert(matName.size() > 1);

            for (VUINT32 i = 0; i < entity->getNumSubEntities(); ++i)
            {
                Ogre::SubEntity *subEntity = entity->getSubEntity(i);
                assert(subEntity);

                VString subMatName;

                if (i < matNames.size())
                {
                    subMatName = matNames[i];
                }
                else
                {
                    subMatName = matNames[0];
                }

                const Ogre::MaterialPtr subMat = Ogre::MaterialManager::getSingleton().getByName(subMatName);
                if (!subMat.isNull())
                {
                    subEntity->setMaterialName(subMatName);
                }
            }
        }
        else
        {
            const Ogre::MaterialPtr entityMat = Ogre::MaterialManager::getSingleton().getByName(matName);
            if (!entityMat.isNull())
            {
                entity->setMaterialName(matName);
            }
        }
    }

    return VTRUE;
}
예제 #26
0
파일: Cube.cpp 프로젝트: 0xc0dec/yarc
void Cube::reset(int _size)
{
  // Reset only if not currently randomizing
  if (rndCounter == 0)
  {
    // Available sizes - from 3 to 10
    if (_size < 3 || _size > 10)
      return;

    // Clear old data
    clear();

    // Calc new parameters
    size = _size;
    elemVisualSize = (visualSize - (size - 1) * elemSpacing) / (float)size;

    // Create assembled cube
    Ogre::Vector3 pos(-visualSize / 2.0 + elemVisualSize / 2.0);
    std::stack<Ogre::Vector3> tmp;
    data.resize(size);
    for (int i = 0; i < size; ++i) // x
    {
      tmp.push(pos);
      data[i].resize(size);
      for (int j = 0; j < size; ++j) // y
      {
        tmp.push(pos);
        data[i][j].resize(size);
        for (int k = 0; k < size; ++k) // z
        {
          // Create entity
          std::ostringstream name;
          name << "Element_" << i << '.' << j << '.' << k;
          Ogre::Entity * ent = smgr->createEntity(name.str(), modelMesh);

          // Apply materials
          ent->getSubEntity(0)->setMaterialName(i == 0 ? material + "_0" : material + "_blank");        // X min
          ent->getSubEntity(1)->setMaterialName(i == size - 1 ? material + "_1" : material + "_blank"); // X max
          ent->getSubEntity(2)->setMaterialName(j == 0 ? material + "_2" : material + "_blank");        // Y min
          ent->getSubEntity(3)->setMaterialName(j == size - 1 ? material + "_3" : material + "_blank"); // Y max
          ent->getSubEntity(4)->setMaterialName(k == 0 ? material + "_4" : material + "_blank");        // Z min
          ent->getSubEntity(5)->setMaterialName(k == size - 1 ? material + "_5" : material + "_blank"); // Z max

          // Create node
          Ogre::SceneNode *node = cubeRootNode->createChildSceneNode(name.str());
          node->setScale(Ogre::Vector3(elemVisualSize));
          node->setPosition(pos);
          node->attachObject(ent);

          // Save element
          CubeElement *e = new CubeElement(node, i, j, k);
          data[i][j][k] = e;

          // Save pivot points
          if (i == 0 && k == 0)
          {
            pivots[0].push_back(e);
            e->isPivot = true;
            e->pivotArrays[0] = 0;
            e->pivotArrayIndexes[0] = pivots[0].size() - 1;
          }
          if (i == size - 1 && k == size - 1)
          {
            pivots[3].push_back(e);
            e->isPivot = true;
            e->pivotArrays[0] = 3;
            e->pivotArrayIndexes[0] = pivots[3].size() - 1;
          }
          if (i == k)
          {
            if (j == 0)
            {
              pivots[2].push_back(e);
              e->isPivot = true;
              e->pivotArrays[e->pivotArrays[0] != -1 ? 1 : 0] = 2;
              e->pivotArrayIndexes[e->pivotArrayIndexes[0] != -1 ? 1 : 0] = pivots[2].size() - 1;
            }
            else if (j == size - 1)
            {
              pivots[1].push_back(e);
              e->isPivot = true;
              e->pivotArrays[e->pivotArrays[0] != -1 ? 1 : 0] = 1;
              e->pivotArrayIndexes[e->pivotArrayIndexes[0] != -1 ? 1 : 0] = pivots[1].size() - 1;
            }
          }
          // Increment position
          pos.z += elemSpacing + elemVisualSize;
        }
        pos = tmp.top();
        pos.y += elemSpacing + elemVisualSize;
        tmp.pop();
      }
      pos = tmp.top();
      pos.x += elemSpacing + elemVisualSize;
      tmp.pop();
    }
    cursor = new CubeCursor(this);
  }
}
예제 #27
0
void saveAsDotScene(const QString& path, QFile& file, Ogre::SceneManager* sceneManager)
{
    Ogre::MeshSerializer* mMeshSerializer = new Ogre::MeshSerializer();
    Ogre::MaterialSerializer* mMaterialSerializer = new Ogre::MaterialSerializer();

    int idCounter = 3;
    if (!file.open(QIODevice::WriteOnly))
    {
        /* show wrror message if not able to open file */
        QMessageBox::warning(0, "Read only", "The file is in read only mode");
    }
    else
    {
        Ogre::SceneManager::MovableObjectIterator iterator = sceneManager->getMovableObjectIterator("Entity");
        QXmlStreamWriter* xmlWriter = new QXmlStreamWriter();
        xmlWriter->setAutoFormatting(true);
        xmlWriter->setDevice(&file);
        xmlWriter->writeStartElement("scene");
        xmlWriter->writeAttribute("formatVersion","");

        xmlWriter->writeStartElement("nodes");
        while(iterator.hasMoreElements())
        {
            Ogre::Entity* e = static_cast<Ogre::Entity*>(iterator.getNext());
            Ogre::Any any = e->getParentNode()->getUserAny();
            Ogre::String widgetType("");
            if(!any.isEmpty()){
                widgetType = any_cast<Ogre::String>(any);
            }
            Ogre::String tmp(widgetType + ":" + e->getParentNode()->getName());
            QString nodeName(tmp.c_str());
            xmlWriter->writeStartElement("node");
            xmlWriter->writeAttribute("name", nodeName);
            xmlWriter->writeAttribute("id", QString::number(idCounter++));


            xmlWriter->writeStartElement("position");
            xmlWriter->writeAttribute("x", QString::number(e->getParentNode()->getPosition().x));
            xmlWriter->writeAttribute("y", QString::number(e->getParentNode()->getPosition().y));
            xmlWriter->writeAttribute("z", QString::number(e->getParentNode()->getPosition().z));
            xmlWriter->writeEndElement();

            xmlWriter->writeStartElement("scale");
            xmlWriter->writeAttribute("x", QString::number(e->getParentNode()->getScale().x));
            xmlWriter->writeAttribute("y", QString::number(e->getParentNode()->getScale().y));
            xmlWriter->writeAttribute("z", QString::number(e->getParentNode()->getScale().z));
            xmlWriter->writeEndElement();

            xmlWriter->writeStartElement("entity");
            xmlWriter->writeAttribute("name", nodeName);
            xmlWriter->writeAttribute("meshFile", nodeName.toLower() + QString(".mesh") );
            xmlWriter->writeAttribute("static", QString("false"));
            xmlWriter->writeEndElement();

            const Mesh* mesh = e->getMesh().getPointer();


            mMeshSerializer->exportMesh(mesh,String(path.toStdString() +
                                                    nodeName.toLower().toStdString() +
                                                    ".mesh" ));


            std::cout << "numeber" <<  mesh->getNumSubMeshes() << std::endl;


            for(int i = 0; i < e->getNumSubEntities(); i++){


                Ogre::Material *mat = static_cast<Ogre::Material*>
                        (Ogre::MaterialManager::getSingletonPtr()->getByName(e->getSubEntity(i)->getMaterialName()).getPointer());

                //e->getMesh().get()->getSubMesh()
                if(mat->getTechnique(0)->getPass(0)->getNumTextureUnitStates() !=0){
                Ogre::String str = mat->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureName();

            Ogre::MaterialPtr mMatPtr =e->getSubEntity(i)->getMaterial()    ;

            mMaterialSerializer->exportMaterial(mMatPtr ,
                                                String(path.toStdString() +
                                                       nodeName.toLower().toStdString() +
                                                       QString::number(i).toStdString() + ".material" ));
            Ogre::TexturePtr* mTexPtr = new Ogre::TexturePtr(Ogre::TextureManager::getSingletonPtr()->getByName(str));
            Ogre::Texture* mTex = mTexPtr->getPointer();
            Ogre::PixelFormat pxf = mTex->getFormat();
            Ogre::Image mImage;
            mTex->convertToImage(mImage);
            std::cout << str << std::endl;
            mImage.save(String(path.toStdString() +
                                 str));
                }
}
            //material file merge

            for(int i = 0; i < e->getNumSubEntities(); i++){
                Ogre::Material *mat = static_cast<Ogre::Material*>
                        (Ogre::MaterialManager::getSingletonPtr()->getByName(e->getSubEntity(i)->getMaterialName()).getPointer());


                QString mMatFilePath = QString((path.toStdString() +
                                               nodeName.toLower().toStdString() +
                                                ".material").c_str()) ;


                 QFile mFile(mMatFilePath);
                 if (!mFile.open(QIODevice::Append))
                 {
                     /* show wrror message if not able to open file */
                     QMessageBox::warning(0, "Read only", "The file is in read only mode");
                 }
                 else{
                     QTextStream out(&mFile);

                     QString mTempMatPath = QString((path + nodeName.toLower() + QString::number(i) + ".material"));

                     QFile mTempMatFile(mTempMatPath);
                     mTempMatFile.open(QIODevice::ReadOnly);

                     QTextStream src(&mTempMatFile);

                     mFile.write(src.readAll().toStdString().c_str());
                     mTempMatFile.remove();

                 }



            }


            xmlWriter->writeEndElement();


        }

        xmlWriter->writeEndElement();
        xmlWriter->writeEndDocument();
        delete xmlWriter;
    }

    delete mMeshSerializer;
    delete mMaterialSerializer;
}
예제 #28
0
bool LevelGeometryLoader::processEntityStaticGeoemtry(TiXmlElement *XMLNode,
		Ogre::StaticGeometry *sgeo)
{
	ASSERT(XMLNode);
	ASSERT(sgeo);

	// Process attributes
	Ogre::String meshFile = Ogre::DotSceneLoader::getAttrib(XMLNode, "meshFile");
	Ogre::Vector3 position = Ogre::Vector3::ZERO;
	Ogre::Quaternion rotation = Ogre::Quaternion::IDENTITY;
	Ogre::Vector3 scale = Ogre::Vector3::UNIT_SCALE;
	std::vector<Ogre::String> subEntities;


	// parse the entity

	// get the origin
	TiXmlElement *auxPElem = XMLNode->FirstChildElement("position");
	if(auxPElem) {
		position = Ogre::DotSceneLoader::parseVector3(auxPElem);
	}

	// get the rotation
	auxPElem = XMLNode->FirstChildElement("rotation");
	if(auxPElem) {
		rotation = Ogre::DotSceneLoader::parseQuaternion(auxPElem);
	}

	// get the scale
	auxPElem = XMLNode->FirstChildElement("scale");
	if(auxPElem) {
		scale = Ogre::DotSceneLoader::parseVector3(auxPElem);
	}

	size_t count = 0;
	// load the subentities
	TiXmlElement *pElement = XMLNode->FirstChildElement("subentities");
	if(pElement){
		auxPElem = pElement->FirstChildElement("subentity");
		// ugly! very
		while(auxPElem) {
			auxPElem = auxPElem->NextSiblingElement("subentity");
			count++;
		}
		subEntities.resize(count);
		pElement = pElement->FirstChildElement("subentity");
		while(pElement){
			int index = Ogre::DotSceneLoader::getAttribInt(pElement, "index");

			subEntities[index] = Ogre::DotSceneLoader::getAttrib(pElement, "materialName");

			pElement = pElement->NextSiblingElement("subentity");
		}
	}

	// creates the entity
	Ogre::Entity *ent = 0;
	try {
		ent = Common::GlobalObjects::sceneManager->createEntity("entity_" + meshFile, meshFile);
	} catch (...) {
		return false;
	}

	// set the subentities config
	size_t subentityCount = std::min(subEntities.size(), (size_t)ent->getNumSubEntities());
	for (size_t subentityIndex = 0; subentityIndex < subentityCount; subentityIndex++)
	{
		Ogre::SubEntity* subentity = ent->getSubEntity((unsigned int)subentityIndex);
		subentity->setMaterialName(subEntities[subentityIndex]);
	}

	// add the entitie to the static geometry
	sgeo->addEntity(ent, position, rotation, scale);
	Common::GlobalObjects::sceneManager->destroyEntity(ent);


	return true;
}
예제 #29
0
void Objects::insertMesh (const MWWorld::Ptr& ptr, const std::string& mesh)
{
    Ogre::SceneNode* insert = ptr.getRefData().getBaseNode();
    assert(insert);

    Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
    NifOgre::EntityList entities = NifOgre::NIFLoader::createEntities(insert, NULL, mesh);
    for(size_t i = 0;i < entities.mEntities.size();i++)
    {
        const Ogre::AxisAlignedBox &tmp = entities.mEntities[i]->getBoundingBox();
        bounds.merge(Ogre::AxisAlignedBox(insert->_getDerivedPosition() + tmp.getMinimum(),
                                          insert->_getDerivedPosition() + tmp.getMaximum())
        );
    }
    Ogre::Vector3 extents = bounds.getSize();
    extents *= insert->getScale();
    float size = std::max(std::max(extents.x, extents.y), extents.z);

    bool small = (size < Settings::Manager::getInt("small object size", "Viewing distance")) && Settings::Manager::getBool("limit small object distance", "Viewing distance");

    // do not fade out doors. that will cause holes and look stupid
    if (ptr.getTypeName().find("Door") != std::string::npos)
        small = false;

    if (mBounds.find(ptr.getCell()) == mBounds.end())
        mBounds[ptr.getCell()] = Ogre::AxisAlignedBox::BOX_NULL;
    mBounds[ptr.getCell()].merge(bounds);

    bool transparent = false;
    for(size_t i = 0;i < entities.mEntities.size();i++)
    {
        Ogre::Entity *ent = entities.mEntities[i];
        for (unsigned int i=0; i<ent->getNumSubEntities(); ++i)
        {
            Ogre::MaterialPtr mat = ent->getSubEntity(i)->getMaterial();
            Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
            while (techIt.hasMoreElements())
            {
                Ogre::Technique* tech = techIt.getNext();
                Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                while (passIt.hasMoreElements())
                {
                    Ogre::Pass* pass = passIt.getNext();

                    if (pass->getDepthWriteEnabled() == false)
                        transparent = true;
                }
            }
        }
    }

    if(!mIsStatic || !Settings::Manager::getBool("use static geometry", "Objects") || transparent)
    {
        for(size_t i = 0;i < entities.mEntities.size();i++)
        {
            Ogre::Entity *ent = entities.mEntities[i];

            ent->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            ent->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
            ent->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
        }
    }
    else
    {
        Ogre::StaticGeometry* sg = 0;

        if (small)
        {
            if( mStaticGeometrySmall.find(ptr.getCell()) == mStaticGeometrySmall.end())
            {
                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometrySmall[ptr.getCell()] = sg;

                sg->setRenderingDistance(Settings::Manager::getInt("small object distance", "Viewing distance"));
            }
            else
                sg = mStaticGeometrySmall[ptr.getCell()];
        }
        else
        {
            if( mStaticGeometry.find(ptr.getCell()) == mStaticGeometry.end())
            {

                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometry[ptr.getCell()] = sg;
            }
            else
                sg = mStaticGeometry[ptr.getCell()];
        }

        // This specifies the size of a single batch region.
        // If it is set too high:
        //  - there will be problems choosing the correct lights
        //  - the culling will be more inefficient
        // If it is set too low:
        //  - there will be too many batches.
        sg->setRegionDimensions(Ogre::Vector3(2500,2500,2500));

        sg->setVisibilityFlags(small ? RV_StaticsSmall : RV_Statics);

        sg->setCastShadows(true);

        sg->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);

        for(size_t i = 0;i < entities.mEntities.size();i++)
        {
            Ogre::Entity *ent = entities.mEntities[i];
            insert->detachObject(ent);
            sg->addEntity(ent,insert->_getDerivedPosition(),insert->_getDerivedOrientation(),insert->_getDerivedScale());

            mRenderer.getScene()->destroyEntity(ent);
        }
    }
}
예제 #30
0
파일: Cube.cpp 프로젝트: 0xc0dec/yarc
bool Cube::load(Ogre::String file)
{
  if (rndCounter == 0)
  {
    // Open file. If failed - return false
    std::ifstream input(file.c_str());
    if (!input.is_open())
      return false;

    // Clear first
    clear();

    // Read size
    input >> size;
    // Calculate visual parameters
    elemVisualSize = (visualSize - (size - 1) * elemSpacing) / (float)size;

    // Prepare pivot arrays
    for (int i = 0; i < 4; ++i)
      pivots[i].resize(size);

    data.resize(size);
    for (int i = 0; i < size; ++i)
    {
      data[i].resize(size);
      for (int j = 0; j < size; ++j)
      {
        data[i][j].resize(size);
        for (int k = 0; k < size; ++k)
        {
          // Read name
          Ogre::String name("");
          input >> name;

          // Create node and position it
          Ogre::SceneNode *node = cubeRootNode->createChildSceneNode(name);
          // Read indexes
          int i_pos, j_pos, k_pos;
          input >> i_pos >> j_pos >> k_pos;
          // Read position
          Ogre::Vector3 pos = Ogre::Vector3::ZERO;
          input >> pos.x >> pos.y >> pos.z;
          // Read orientation
          Ogre::Vector3 orient_axis = Ogre::Vector3::ZERO;
          float orient_angle = 0;
          input >> orient_axis.x >> orient_axis.y >> orient_axis.z >> orient_angle;
          Ogre::Quaternion orient(Ogre::Radian(Ogre::Degree(orient_angle)), orient_axis);
          node->setPosition(pos);
          node->setOrientation(orient);
          node->setScale(Ogre::Vector3(elemVisualSize));

          // Create entity and setup it
          Ogre::Entity *ent = smgr->createEntity(name, modelMesh);
          Ogre::String mat("");
          for (int s = 0; s < 6; ++s)
          {
            input >> mat;
            ent->getSubEntity(s)->setMaterialName(mat);
          }
          node->attachObject(ent);

          // Finally, create element
          CubeElement *e = new CubeElement(node, i_pos, j_pos, k_pos);
          input >> e->isPivot;
          if (e->isPivot)
          {
            input >> e->pivotArrays[0] >> e->pivotArrayIndexes[0] >> e->pivotArrays[1] >> e->pivotArrayIndexes[1];
            pivots[e->pivotArrays[0]][e->pivotArrayIndexes[0]] = e;
            if (e->pivotArrays[1] != -1)
              pivots[e->pivotArrays[1]][e->pivotArrayIndexes[1]] = e;
          }
          data[i_pos][j_pos][k_pos] = e;
        }
      }
    }