Esempio n. 1
0
void LagomPlayerBase::AddConstructionCapability(LagomActorFactory* f)
{
	if(!f)
		return;
	if(_actorFactories.find(f) != _actorFactories.end())
		return;
	
	Ogre::SceneManager* manager = _state.GetSceneManager();
	
	Ogre::SceneNode* node = manager->createSceneNode();
	Ogre::Entity*	constructionObject = manager->createEntity(f->Mesh.c_str());

	Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(getIntFactory().ConstructingMaterial);
	materialPtr->setSelfIllumination(1.0f,1.0f,1.0f);
	constructionObject->setCastShadows(false);
	constructionObject->setRenderQueueGroup(RENDER_QUEUE_SKIES_LATE);
	constructionObject->setMaterialName(getIntFactory().ConstructingMaterial);
	node->attachObject(constructionObject);
	node->setScale( f->MeshScale );

	_actorFactories.insert(FactoryMap::value_type(f,node));

	
	if(	_selectedActorFactory ==_actorFactories.end())
		_selectedActorFactory=_actorFactories.begin();
}
	//-----------------------------------------------------------------------
	void EntityRenderer::_prepare(ParticleTechnique* technique)
	{
		/** 
			- This renderer is a ´hacky´ solution to display geometry-based particles. It pre-creates a 
			number of SceneNodes (childs of the parent Node to which the ParticleSystem is attached) and 
			Entities and uses these pools to display the particles. There are better solutions, but 
			this one is simple and fast enough, although it has some drawbacks.
			- Future solutions should rather make use of hardware instancing to display a large number of
			geometry-based particles at once.
		*/

		// Use the given technique, although it should be the same as mParentTechnique (must be set already)
		if (!technique || mRendererInitialised)
			return;

		std::stringstream ss; 
		ss << this;
		mEntityName = mMeshName + ss.str();
		mQuota = technique->getVisualParticleQuota();
		Ogre::SceneNode* parentNode = technique->getParentSystem()->getParentSceneNode();
		Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().load(mMeshName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		Ogre::Mesh* meshPointer = mesh.getPointer();
		Vector3 size = meshPointer->getBounds().getSize();
		mBoxWidth = size.x == 0.0f ? 1.0f : size.x;
		mBoxHeight = size.y == 0.0f ? 1.0f : size.y;
		mBoxDepth = size.z == 0.0f ? 1.0f : size.z;

		if (parentNode)
		{
			// Create number of VisualData objects including SceneNodes
			String sceneNodeName;
			for (size_t i = 0; i < mQuota; i++)
			{
				sceneNodeName = "ParticleUniverse" + ss.str() + StringConverter::toString(i);
				EntityRendererVisualData* visualData = 
					PU_NEW_T(EntityRendererVisualData, MEMCATEGORY_SCENE_OBJECTS)(parentNode->createChildSceneNode(sceneNodeName));

				mAllVisualData.push_back(visualData); // Managed by this renderer
				mVisualData.push_back(visualData); // Used to assign to a particle
			}

			// Create number of Entities
			Ogre::Entity* entity = technique->getParentSystem()->getSceneManager()->createEntity(mEntityName, mMeshName); // Base entity
			vector<EntityRendererVisualData*>::const_iterator it;
			vector<EntityRendererVisualData*>::const_iterator itEnd = mAllVisualData.end();
			size_t j;
			for (it = mAllVisualData.begin(), j = 0; it != itEnd; ++it, ++j)
			{
				Ogre::Entity* clonedEntity = entity->clone(mEntityName + StringConverter::toString(j));
				clonedEntity->setMaterialName(technique->getMaterialName());
				clonedEntity->setRenderQueueGroup(mQueueId);
				mEntities.push_back(clonedEntity);
				(*it)->node->attachObject(clonedEntity);
			}
			technique->getParentSystem()->getSceneManager()->destroyEntity(mEntityName);
		}

		_makeNodesVisible(false);
		mRendererInitialised = true;
	}
Esempio n. 3
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);
            }
        }
    }
}
Esempio n. 4
0
void CombatSetupWnd::HandleMouseMoves(const GG::Pt& pt) {
    if (Ogre::SceneNode* node = PlaceableShipNode()) {
        std::pair<bool, Ogre::Vector3> intersection = m_intersect_mouse_with_ecliptic(pt);
        if (intersection.first) {
            Ship* ship = *Ogre::any_cast<Ship*>(&node->getUserAny());
            bool valid_location = ValidPlacement(ship, intersection.second);
            node->setVisible(true);
            node->setPosition(intersection.second);
            node->setOrientation(StarwardOrientationForPosition(intersection.second));
            if (valid_location) {
                Ogre::SceneNode::ObjectIterator iterator = node->getAttachedObjectIterator();
                assert(iterator.hasMoreElements());
                Ogre::Entity* entity = boost::polymorphic_downcast<Ogre::Entity*>(iterator.getNext());
                entity->setMaterialName(ShipMaterialName(*ship->Design(), ship->Owner()));
                entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAIN);
            } else {
                std::string base_material_name = ShipMaterialName(*ship->Design(), ship->Owner());
                std::string material_name = UNPLACEABLE_MATERIAL_PREFIX + base_material_name;
                if (!Ogre::MaterialManager::getSingleton().resourceExists(material_name)) {
                    Ogre::MaterialPtr unmodified_material =
                        Ogre::MaterialManager::getSingleton().getByName(base_material_name);
                    Ogre::MaterialPtr material = unmodified_material->clone(material_name);
                    Ogre::Pass* pass = material->getTechnique(0)->getPass(1);
                    assert(pass->hasFragmentProgram());
                    pass->getFragmentProgramParameters()->setNamedConstant("alpha", 0.25f);
                }
                Ogre::SceneNode::ObjectIterator iterator = node->getAttachedObjectIterator();
                assert(iterator.hasMoreElements());
                Ogre::Entity* entity = boost::polymorphic_downcast<Ogre::Entity*>(iterator.getNext());
                entity->setMaterialName(material_name);
                entity->setRenderQueueGroup(ALPHA_OBJECTS_QUEUE);
            }
        } else {
            node->setVisible(false);
        }
    }
}
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);
	}
}
Esempio n. 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];

            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);
    }
}
Esempio n. 7
0
	/**
	 * @brief Ctor.
	 * @param entity The entity which the marker is attached to.
	 * @param sceneManager A scene manager used to create nodes and entities.
	 * @param terrainManager Provides height data.
	 * @param point The location which will be marked.
	 */
	EntityPointMarker(Eris::Entity& entity, Ogre::SceneManager& sceneManager, const IHeightProvider& heightProvider, const WFMath::Point<3>& point) :
			mEntity(entity), mMarkerEntity(0), mMarkerNode(0), mMarkerDirectionIndicator(0), mHeightProvider(heightProvider), mPoint(point)
	{
		mMarkerNode = sceneManager.getRootSceneNode()->createChildSceneNode();
		try {
			mMarkerEntity = sceneManager.createEntity("3d_objects/primitives/models/sphere.mesh");
			//start out with a normal material
			mMarkerEntity->setMaterialName("/global/authoring/point");
			//The material is made to ignore depth checks, so if we put it in a later queue we're
			//making sure that the marker is drawn on top of everything else, making it easier to interact with.
			mMarkerEntity->setRenderQueueGroup(Ogre::RENDER_QUEUE_9);
			mMarkerEntity->setRenderingDistance(300);
			mMarkerEntity->setQueryFlags(MousePicker::CM_NONPICKABLE);
			mMarkerNode->attachObject(mMarkerEntity);
		} catch (const std::exception& ex) {
			S_LOG_WARNING("Error when creating marker node." << ex);
			return;
		}
		mMarkerNode->setVisible(true);

		mMarkerDirectionIndicator = new ShapeVisual(*sceneManager.getRootSceneNode(), false);

		mEntity.Moved.connect(sigc::mem_fun(*this, &EntityPointMarker::entityMoved));
	}
Esempio n. 8
0
ObjectEditHandler::ObjectEditHandler(SceneDoc *Owner)
{
	mOwner = Owner;
	mMode = OEM_NONE;
	mAxisMode = AM_NONE;
	mTarget = NULL;
	mObjectEditNode = mOwner->getSceneManager()->getRootSceneNode()->createChildSceneNode();
	mRayQuery = mOwner->getSceneManager()->createRayQuery(Ogre::Ray());

	mMaterials[0] = Ogre::MaterialManager::getSingletonPtr()->getByName("Editor/RedMat");
	mMaterials[1] = Ogre::MaterialManager::getSingletonPtr()->getByName("Editor/GreenMat");
	mMaterials[2] = Ogre::MaterialManager::getSingletonPtr()->getByName("Editor/BlueMat");
	mMaterials[3] = Ogre::MaterialManager::getSingletonPtr()->getByName("Editor/ObjectIndicatorWhiteMat");
	mMaterials[4] = Ogre::MaterialManager::getSingletonPtr()->getByName("Editor/ObjectIndicatorYellowMat");

	//////////////////////////////////////////////////
	// 碰撞检测
	//////////////////////////////////////////////////

	mCollisionManager = new OgreOpcode::CollisionManager(Owner->getSceneManager());
	mCollisionManager->addCollClass("Object");
	mCollisionManager->addCollType("Object", "Object", OgreOpcode::COLLTYPE_IGNORE);
	mCollisionContext = mCollisionManager->createContext("SceneObject");

	Ogre::MovableObjectFactory* Factory = 
		Ogre::Root::getSingleton().getMovableObjectFactory(Ogre::EntityFactory::FACTORY_TYPE_NAME);
	Ogre::NameValuePairList Params;

	//////////////////////////////////////////////////
	// 平移放缩指示器
	//////////////////////////////////////////////////

	mIndicatorContext = mCollisionManager->createContext("TransScale");

	mTransScaleNode = mObjectEditNode->createChildSceneNode("TransScaleIndicator");
	mTransScaleNode->setScale(200.0f, 200.0f, 200.0f);

	// x
	Ogre::SceneNode *SubNode = mTransScaleNode->createChildSceneNode();
	SubNode->roll(Ogre::Degree(-90.0f));

	Ogre::Entity *Entity = Owner->getSceneManager()->createEntity("TransScaleXLine", "MoveArrowLineVisible.mesh");
	//Entity->setQueryFlags(0); // 参与查询
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[0]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_TRANS_SCALE_X] = Entity;

	Entity = Owner->getSceneManager()->createEntity("TransScaleXCone", "MoveArrowConeVisible.mesh");
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[0]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);

	Params["mesh"] = "MoveArrowCollision.mesh";
	Entity = (Ogre::Entity*)Factory->createInstance("TransScaleXCol", Owner->getSceneManager(), &Params);
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);

	Entity->setVisible(false);
	SubNode->attachObject(Entity);

	OgreOpcode::CollisionObject *CollisionObject = 
		AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_TRANS_SCALE_X;

	// y
	SubNode = mTransScaleNode;

	Entity = Owner->getSceneManager()->createEntity("TransScaleYLine", "MoveArrowLineVisible.mesh");
	//Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[1]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_TRANS_SCALE_Y] = Entity;

	Entity = Owner->getSceneManager()->createEntity("TransScaleYCone", "MoveArrowConeVisible.mesh");
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[1]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);

	Params["mesh"] = "MoveArrowCollision.mesh";
	Entity = (Ogre::Entity*)Factory->createInstance("TransScaleYCol", Owner->getSceneManager(), &Params);
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);

	Entity->setVisible(false);
	SubNode->attachObject(Entity);

	CollisionObject = AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_TRANS_SCALE_Y;

	// z
	SubNode = mTransScaleNode->createChildSceneNode();
	SubNode->pitch(Ogre::Degree(90));

	Entity = Owner->getSceneManager()->createEntity("TransScaleZLine", "MoveArrowLineVisible.mesh");
	//Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[2]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_TRANS_SCALE_Z] = Entity;

	Entity = Owner->getSceneManager()->createEntity("TransScaleZCone", "MoveArrowConeVisible.mesh");
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[2]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);

	Params["mesh"] = "MoveArrowCollision.mesh";
	Entity = (Ogre::Entity*)Factory->createInstance("TransScaleZCol", Owner->getSceneManager(), &Params);
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);

	Entity->setVisible(false);
	SubNode->attachObject(Entity);

	CollisionObject = AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_TRANS_SCALE_Z;

	// box
	SubNode = mTransScaleNode;

	Params["mesh"] = "Box1m.mesh";
	Entity =(Ogre::Entity*)Factory->createInstance("TransScaleAll", Owner->getSceneManager(), &Params);
	//Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[3]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_TRANS_SCALE_ALL] = Entity;

	CollisionObject = AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_TRANS_SCALE_ALL;

	mIndicatorContext->reset();
	mObjectEditNode->removeChild(mTransScaleNode);

	//////////////////////////////////////////////////
	// 旋转指示器
	//////////////////////////////////////////////////

	mIndicatorContext = mCollisionManager->createContext("Rotate");

	mRotateNode = mObjectEditNode->createChildSceneNode("RotateIndicator");
	mRotateNode->setScale(200.0f, 200.0f, 200.0f);

	// x
	SubNode = mRotateNode->createChildSceneNode();
	SubNode->roll(Ogre::Degree(90));

	Entity = Owner->getSceneManager()->createEntity("RotateX", "RotationRingVisible.mesh");
	//Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[0]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_ROTATE_X] = Entity;

	Params["mesh"] = "RotationRingCollision.mesh";
	Entity =(Ogre::Entity*)Factory->createInstance("RotateXCol", Owner->getSceneManager(), &Params);
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);

	Entity->setVisible(false);
	SubNode->attachObject(Entity);

	CollisionObject = AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_ROTATE_X;

	// y
	SubNode = mRotateNode;
	Entity = Owner->getSceneManager()->createEntity("RotateY", "RotationRingVisible.mesh");
	//Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[1]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_ROTATE_Y] = Entity;

	Params["mesh"] = "RotationRingCollision.mesh";
	Entity =(Ogre::Entity*)Factory->createInstance("RotateYCol", Owner->getSceneManager(), &Params);
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);

	Entity->setVisible(false);
	SubNode->attachObject(Entity);
	
	CollisionObject = AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_ROTATE_Y;

	// z
	SubNode = mRotateNode->createChildSceneNode();
	SubNode->pitch(Ogre::Degree(90.0f));

	Entity = Owner->getSceneManager()->createEntity("RotateZ", "RotationRingVisible.mesh");
	//Entity->setQueryFlags(0);
	Entity->setCastShadows(false);
	Entity->setMaterial(mMaterials[2]);
	Entity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
	SubNode->attachObject(Entity);
	mTransformEntities[AM_ROTATE_Z] = Entity;

	Params["mesh"] = "RotationRingCollision.mesh";
	Entity =(Ogre::Entity*)Factory->createInstance("RotateZCol", Owner->getSceneManager(), &Params);
	Entity->setQueryFlags(0);
	Entity->setCastShadows(false);

	Entity->setVisible(false);
	SubNode->attachObject(Entity);

	CollisionObject = AddCollisionEntity(mIndicatorContext, Entity);
	mCollisionObjectToAxisMode[CollisionObject] = AM_ROTATE_Z;

	mIndicatorContext->reset();
	mObjectEditNode->removeChild(mRotateNode);
}
Esempio n. 9
0
void RenderedTexture::renderTextures()
{
    //Set up RTT texture
    Ogre::TexturePtr renderTexture;
    if (renderTexture.isNull()) {
        renderTexture = Ogre::TextureManager::getSingleton().createManual(
            getUniqueID("RenderedEntityMaterial"), "EntityRenderer",
            Ogre::TEX_TYPE_2D, textureSize, textureSize, 0,
            Ogre::PF_A8R8G8B8, Ogre::TU_RENDERTARGET, 0);
    }
    renderTexture->setNumMipmaps(0);

    //Set up render target
    Ogre::RenderTexture* renderTarget = renderTexture->getBuffer()->getRenderTarget(); 
    renderTarget->setAutoUpdated(false);

    //Set up camera
    Ogre::SceneNode* camNode = sceneMgr->getSceneNode("EntityRenderer::cameraNode");
    Ogre::Camera* renderCamera = sceneMgr->createCamera(getUniqueID("EntityRendererCam"));
    camNode->attachObject(renderCamera);
    renderCamera->setLodBias(1000.0f);

    Ogre::Viewport* renderViewport = renderTarget->addViewport(renderCamera);
    renderViewport->setOverlaysEnabled(false);
    renderViewport->setClearEveryFrame(true);
    renderViewport->setShadowsEnabled(false);
    renderViewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f, 0.0f));

    //Set up scene node
    Ogre::SceneNode* node = sceneMgr->getSceneNode("EntityRenderer::renderNode");

    Ogre::SceneNode* oldSceneNode = entity->getParentSceneNode();
    if (oldSceneNode)
        oldSceneNode->detachObject(entity);
    node->attachObject(entity);
    node->setPosition(-entityCenter);

    //Set up camera FOV
    const Ogre::Real objDist = entityRadius * 100;
    const Ogre::Real nearDist = objDist - (entityRadius + 1); 
    const Ogre::Real farDist = objDist + (entityRadius + 1);

    renderCamera->setAspectRatio(1.0f);
    renderCamera->setFOVy(Ogre::Math::ATan(2.0 * entityRadius / objDist));
    renderCamera->setNearClipDistance(nearDist);
    renderCamera->setFarClipDistance(farDist);

    //Disable mipmapping (without this, masked textures look bad)
    Ogre::MaterialManager* mm = Ogre::MaterialManager::getSingletonPtr();
    Ogre::FilterOptions oldMinFilter = mm->getDefaultTextureFiltering(Ogre::FT_MIN);
    Ogre::FilterOptions oldMagFilter = mm->getDefaultTextureFiltering(Ogre::FT_MAG);
    Ogre::FilterOptions oldMipFilter = mm->getDefaultTextureFiltering(Ogre::FT_MIP);
    mm->setDefaultTextureFiltering(Ogre::FO_POINT, Ogre::FO_LINEAR,Ogre:: FO_NONE);

    //Disable fog
    Ogre::FogMode oldFogMode = sceneMgr->getFogMode();
    Ogre::ColourValue oldFogColor = sceneMgr->getFogColour();
    Ogre::Real oldFogDensity = sceneMgr->getFogDensity();
    Ogre::Real oldFogStart = sceneMgr->getFogStart();
    Ogre::Real oldFogEnd = sceneMgr->getFogEnd();
    sceneMgr->setFog(Ogre::FOG_NONE);

    // Get current status of the queue mode
    Ogre::SceneManager::SpecialCaseRenderQueueMode OldSpecialCaseRenderQueueMode =
        sceneMgr->getSpecialCaseRenderQueueMode();
    //Only render the entity
    sceneMgr->setSpecialCaseRenderQueueMode(Ogre::SceneManager::SCRQM_INCLUDE); 
    sceneMgr->addSpecialCaseRenderQueue(renderQueueGroup);

    Ogre::uint8 oldRenderQueueGroup = entity->getRenderQueueGroup();
    entity->setRenderQueueGroup(renderQueueGroup);
    bool oldVisible = entity->getVisible();
    entity->setVisible(true);
    float oldMaxDistance = entity->getRenderingDistance();
    entity->setRenderingDistance(0);

    //Calculate the filename hash used to uniquely identity this render
    std::string strKey = entityKey;
    char key[32] = {0};
    Ogre::uint32 i = 0;
    for (std::string::const_iterator it = entityKey.begin(); it != entityKey.end(); ++it) {
        key[i] ^= *it;
        i = (i+1) % sizeof(key);
    }
    for (i = 0; i < sizeof(key); ++i)
        key[i] = (key[i] % 26) + 'A';

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
        GetUserDir().string(), "FileSystem", "BinFolder");
    std::string fileNamePNG =
        "Rendered." + std::string(key, sizeof(key)) + '.' +
        Ogre::StringConverter::toString(textureSize) + ".png";

    //Attempt to load the pre-render file if allowed
    bool needsRegen = false;
    if (!needsRegen) {
        try{
            texture = Ogre::TextureManager::getSingleton().load(
                fileNamePNG, "BinFolder", Ogre::TEX_TYPE_2D, 0);
        } catch (...) {
            needsRegen = true;
        }
    }

    if (needsRegen) {
        //If this has not been pre-rendered, do so now

        //Position camera
        camNode->setPosition(0, 0, 0);
        // TODO camNode->setOrientation(Quaternion(yaw, Vector3::UNIT_Y) * Quaternion(-pitch, Vector3::UNIT_X));
        camNode->translate(Ogre::Vector3(0, 0, objDist), Ogre::Node::TS_LOCAL);
						
        renderTarget->update();

        //Save RTT to file
        renderTarget->writeContentsToFile((GetUserDir() / fileNamePNG).string());

        //Load the render into the appropriate texture view
        texture = Ogre::TextureManager::getSingleton().load(fileNamePNG, "BinFolder", Ogre::TEX_TYPE_2D, 0);

        ggTexture = ClientUI::GetTexture(GetUserDir() / fileNamePNG);
    }

    entity->setVisible(oldVisible);
    entity->setRenderQueueGroup(oldRenderQueueGroup);
    entity->setRenderingDistance(oldMaxDistance);
    sceneMgr->removeSpecialCaseRenderQueue(renderQueueGroup);
    // Restore original state
    sceneMgr->setSpecialCaseRenderQueueMode(OldSpecialCaseRenderQueueMode); 

    //Re-enable mipmapping
    mm->setDefaultTextureFiltering(oldMinFilter, oldMagFilter, oldMipFilter);

    //Re-enable fog
    sceneMgr->setFog(oldFogMode, oldFogColor, oldFogDensity, oldFogStart, oldFogEnd);

    //Delete camera
    renderTarget->removeViewport(0);
    renderCamera->getSceneManager()->destroyCamera(renderCamera);

    //Delete scene node
    node->detachAllObjects();
    if (oldSceneNode)
        oldSceneNode->attachObject(entity);

    //Delete RTT texture
    assert(!renderTexture.isNull());
    std::string texName2(renderTexture->getName());

    renderTexture.setNull();
    if (Ogre::TextureManager::getSingletonPtr())
        Ogre::TextureManager::getSingleton().remove(texName2);
}
Esempio n. 10
0
void World::Init()
{
	using namespace Ogre;

	SceneManager* sm = m_pRenderSystem->m_pSceneMgr;
	Camera* cam = m_pRenderSystem->m_pMainCamera;

	m_pSceneQuery = sm->createAABBQuery(AxisAlignedBox());
	m_pRaySceneQuery = sm->createRayQuery(Ray());
	m_pRaySceneQuery->setSortByDistance(true);

	Ogre::MovableObject::setDefaultQueryFlags(eQueryType_Default);

	m_cameraMan = new OgreBites::SdkCameraMan(cam);
	m_cameraMan->setStyle(OgreBites::CS_FREELOOK);

	//RTS锁死视角
	cam->setPosition(0, 24, 0);
	cam->lookAt(0, 0, 8);
	//cam->setFOVy(Degree(30));

	//初始化行为库
	aiBehaviorTreeTemplateManager& btMgr = aiBehaviorTreeTemplateManager::GetSingleton();
	btMgr.AddBehavior("Idle", new aiBehaviorIdle);
	btMgr.AddBehavior("MoveToEnemyBase", new aiBehaviorMoveToEnemyBase);
	//加载所有行为树模板
	btMgr.LoadAll();

	//测试两个AI
	m_player[eGameRace_Terran] = new FactionAI(eGameRace_Terran);
	m_player[eGameRace_Zerg] = new FactionAI(eGameRace_Zerg);
	m_player[eGameRace_Terran]->SetEnemy(m_player[eGameRace_Zerg]);
	m_player[eGameRace_Zerg]->SetEnemy(m_player[eGameRace_Terran]);
	m_player[eGameRace_Terran]->SetTeamColor(COLOR::Blue);
	m_player[eGameRace_Zerg]->SetTeamColor(COLOR::Red);

	GameDataDefManager::GetSingleton().LoadAllData();

	//初始化Recast库
	OgreRecastConfigParams recastParams = OgreRecastConfigParams();
	recastParams.setCellSize(1);
	recastParams.setCellHeight(0.16f);
	recastParams.setAgentMaxSlope(15);
	recastParams.setAgentHeight(1.5f);
	recastParams.setAgentMaxClimb(0.5f);
	recastParams.setAgentRadius(0.4f);
	recastParams.setEdgeMaxLen(2);
	recastParams.setEdgeMaxError(1.3f);
	recastParams.setVertsPerPoly(6);
	recastParams.setRegionMinSize(2);
	recastParams.setRegionMergeSize(3);
	recastParams.setDetailSampleDist(6);
	recastParams.setDetailSampleMaxError(1);

	m_pRecast = new OgreRecast(sm, recastParams);
	m_pDetourTileCache = new OgreDetourTileCache(m_pRecast);

	//加载编辑器导出的导航网格数据
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(
		"NavMesh.Bin", "General", false);
	assert(m_pDetourTileCache->loadAll(stream));

	//m_pDetourTileCache->drawNavMesh();

	//初始化Detour寻路库
	m_pDetourCrowd = new OgreDetourCrowd(m_pRecast);

	g_Environment.m_pRecast = m_pRecast;
	g_Environment.m_pCrowd = m_pDetourCrowd;

	//加载测试场景
	m_pTestScene = new Kratos::Scene();
	m_pTestScene->Load("MyStarCraft.Scene", "General", this);

	//UI for test
	Ogre::Entity* pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleTerran_0.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode1 = sm->getRootSceneNode()->createChildSceneNode("UIConsoleNode");
	m_pUISceneNode1->attachObject(pEntConsole);
	m_pConsoleAnim1 = pEntConsole->getAnimationState("Birth");
	assert(m_pConsoleAnim1);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleTerran_1.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode2 = m_pUISceneNode1->createChildSceneNode("InfoPanelNode");
	m_pUISceneNode2->attachObject(pEntConsole);
	m_pConsoleAnim2 = pEntConsole->getAnimationState("Birth");
	assert(m_pConsoleAnim2);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleTerran_2.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode3 = m_pUISceneNode1->createChildSceneNode("CmdPanelNode");
	m_pUISceneNode3->attachObject(pEntConsole);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleProtoss_6.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode4 = m_pUISceneNode1->createChildSceneNode("PortraitPanelNode");
	m_pUISceneNode4->attachObject(pEntConsole);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	m_cmdPanel->Init();
	m_infoPanel->Init();
	m_portraitPanel->Init();

	CEGUI::WindowManager& wndMgr = CEGUI::WindowManager::getSingleton();
	CEGUI::Window* pRoot = wndMgr.getWindow("Root");
	assert(pRoot);
	GUIMANAGER.SetGUISheet(pRoot);
	pRoot->addChildWindow(wndMgr.getWindow("InfoPanelFrame"));
}
Esempio n. 11
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);
        }
    }
}
Esempio n. 12
0
void RoR::GfxEnvmap::SetupEnvMap()
{
    m_rtt_texture = Ogre::TextureManager::getSingleton().getByName("EnvironmentTexture");

    for (int face = 0; face < NUM_FACES; face++)
    {
        m_render_targets[face] = m_rtt_texture->getBuffer(face)->getRenderTarget();
        m_cameras[face] = gEnv->sceneManager->createCamera("EnvironmentCamera-" + TOSTRING(face));
        m_cameras[face]->setAspectRatio(1.0);
        m_cameras[face]->setProjectionType(Ogre::PT_PERSPECTIVE);
        m_cameras[face]->setFixedYawAxis(false);
        m_cameras[face]->setFOVy(Ogre::Degree(90));
        m_cameras[face]->setNearClipDistance(0.1f);
        m_cameras[face]->setFarClipDistance(gEnv->mainCamera->getFarClipDistance());

        Ogre::Viewport* v = m_render_targets[face]->addViewport(m_cameras[face]);
        v->setOverlaysEnabled(false);
        v->setClearEveryFrame(true);
        v->setBackgroundColour(gEnv->mainCamera->getViewport()->getBackgroundColour());
        m_render_targets[face]->setAutoUpdated(false);
    }

    m_cameras[0]->setDirection(+Ogre::Vector3::UNIT_X);
    m_cameras[1]->setDirection(-Ogre::Vector3::UNIT_X);
    m_cameras[2]->setDirection(+Ogre::Vector3::UNIT_Y);
    m_cameras[3]->setDirection(-Ogre::Vector3::UNIT_Y);
    m_cameras[4]->setDirection(-Ogre::Vector3::UNIT_Z);
    m_cameras[5]->setDirection(+Ogre::Vector3::UNIT_Z);

    if (App::diag_envmap.GetActive())
    {
        // create fancy mesh for debugging the envmap
        Ogre::Overlay* overlay = Ogre::OverlayManager::getSingleton().create("EnvMapDebugOverlay");
        if (overlay)
        {
            Ogre::Vector3 position = Ogre::Vector3::ZERO;
            float scale = 1.0f;

            Ogre::MeshPtr mesh = Ogre::MeshManager::getSingletonPtr()->createManual("cubeMapDebug", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            // create sub mesh
            Ogre::SubMesh* sub = mesh->createSubMesh();

            // Initialize render operation
            sub->operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
            //
            sub->useSharedVertices = true;
            mesh->sharedVertexData = new Ogre::VertexData;
            sub->indexData = new Ogre::IndexData;

            // Create vertex declaration
            size_t offset = 0;
            mesh->sharedVertexData->vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
            offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
            mesh->sharedVertexData->vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_TEXTURE_COORDINATES);

            // Create and bind vertex buffer
            mesh->sharedVertexData->vertexCount = 14;
            Ogre::HardwareVertexBufferSharedPtr vertexBuffer =
                Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
                    mesh->sharedVertexData->vertexDeclaration->getVertexSize(0),
                    mesh->sharedVertexData->vertexCount,
                    Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
            mesh->sharedVertexData->vertexBufferBinding->setBinding(0, vertexBuffer);

            // Vertex data
            static const float vertexData[] = {
                // Position      Texture coordinates    // Index
                0.0, 2.0, -1.0, 1.0, 1.0, //  0
                0.0, 1.0, -1.0, -1.0, 1.0, //  1
                1.0, 2.0, -1.0, 1.0, -1.0, //  2
                1.0, 1.0, -1.0, -1.0, -1.0, //  3
                2.0, 2.0, 1.0, 1.0, -1.0, //  4
                2.0, 1.0, 1.0, -1.0, -1.0, //  5
                3.0, 2.0, 1.0, 1.0, 1.0, //  6
                3.0, 1.0, 1.0, -1.0, 1.0, //  7
                4.0, 2.0, -1.0, 1.0, 1.0, //  8
                4.0, 1.0, -1.0, -1.0, 1.0, //  9
                1.0, 3.0, -1.0, 1.0, 1.0, // 10
                2.0, 3.0, 1.0, 1.0, 1.0, // 11
                1.0, 0.0, -1.0, -1.0, 1.0, // 12
                2.0, 0.0, 1.0, -1.0, 1.0, // 13
            };

            // Fill vertex buffer
            float* pData = static_cast<float*>(vertexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD));
            for (size_t vertex = 0, i = 0; vertex < mesh->sharedVertexData->vertexCount; vertex++)
            {
                // Position
                *pData++ = position.x + scale * vertexData[i++];
                *pData++ = position.y + scale * vertexData[i++];
                *pData++ = 0.0;

                // Texture coordinates
                *pData++ = vertexData[i++];
                *pData++ = vertexData[i++];
                *pData++ = vertexData[i++];
            }
            vertexBuffer->unlock();

            // Create index buffer
            sub->indexData->indexCount = 36;
            Ogre::HardwareIndexBufferSharedPtr indexBuffer =
                Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(
                    Ogre::HardwareIndexBuffer::IT_16BIT,
                    sub->indexData->indexCount,
                    Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
            sub->indexData->indexBuffer = indexBuffer;

            // Index data
            static const Ogre::uint16 indexData[] = {
                // Indices         // Face
                 0,  1,  2,        //  0
                 2,  1,  3,        //  1
                 2,  3,  4,        //  2
                 4,  3,  5,        //  3
                 4,  5,  6,        //  4
                 6,  5,  7,        //  5
                 6,  7,  8,        //  6
                 8,  7,  9,        //  7
                10,  2, 11,        //  8
                11,  2,  4,        //  9
                 3, 12,  5,        // 10
                 5, 12, 13,        // 11
            };

            // Fill index buffer
            indexBuffer->writeData(0, indexBuffer->getSizeInBytes(), indexData, true);

            mesh->_setBounds(Ogre::AxisAlignedBox::BOX_INFINITE);
            mesh->_setBoundingSphereRadius(10);
            mesh->load();

            Ogre::Entity* e = gEnv->sceneManager->createEntity(mesh->getName());
            e->setCastShadows(false);
            e->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1);
            e->setVisible(true);

            e->setMaterialName("tracks/EnvMapDebug");
            Ogre::SceneNode* mDebugSceneNode = new Ogre::SceneNode(gEnv->sceneManager);
            mDebugSceneNode->attachObject(e);
            mDebugSceneNode->setPosition(Ogre::Vector3(0, 0, -5));
            mDebugSceneNode->setFixedYawAxis(true, Ogre::Vector3::UNIT_Y);
            mDebugSceneNode->setVisible(true);
            mDebugSceneNode->_update(true, true);
            mDebugSceneNode->_updateBounds();
            overlay->add3D(mDebugSceneNode);
            overlay->show();
        }
    }
}
Esempio n. 13
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();
}