コード例 #1
0
ファイル: renderboxscene.cpp プロジェクト: dzw/kylin001v
	void RenderBoxScene::updateViewport()
	{
		// пр?нуле вылетает
		if ((mCanvas->getWidth() <= 1) || (mCanvas->getHeight() <= 1))
			return;

		if ((nullptr != mEntity) && (nullptr != mCamera))
		{
			// не ¤сн? нужн?ли раст¤гивать камеру, установленну?юзером
			mCamera->setAspectRatio((float)mCanvas->getWidth() / (float)mCanvas->getHeight());

			// вычисл¤ем рассто¤ни? чтоб?бы?виде?весь объект
			Ogre::AxisAlignedBox box;

			box.merge(mEntity->getBoundingBox().getMinimum() + mEntity->getParentSceneNode()->_getDerivedPosition());
			box.merge(mEntity->getBoundingBox().getMaximum() + mEntity->getParentSceneNode()->_getDerivedPosition());

			if (box.isNull()) return;

			Ogre::Vector3 vec = box.getSize();

			float width = sqrt(vec.x*vec.x + vec.z*vec.z); // само?длинно?- диагонал?(если крутит?модель)
			float len2 = width / mCamera->getAspectRatio();
			float height = vec.y;
			float len1 = height;
			if (len1 < len2) len1 = len2;
			len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view
			// цент?объект?по вертикал?+ отъехать та? чтоб?влезла ближ?¤ гран?BoundingBox'?+ чуть ввер??ещ?наза?дл¤ красот?
			Ogre::Vector3 result = box.getCenter() + Ogre::Vector3(0, 0, vec.z/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2);
			Ogre::Vector3 look = Ogre::Vector3(0, box.getCenter().y /*+ box.getCenter().y * (1-mCurrentScale)*/, 0);

			mCameraNode->setPosition(result);
			mCameraNode->lookAt(look, Ogre::Node::TS_WORLD);
		}
	}
コード例 #2
0
ファイル: EntityRenderer.cpp プロジェクト: adesst/freeorion
RenderedTexture::RenderedTexture(Ogre::Entity* entity,
                                 Ogre::SceneManager* sceneMgr,
                                 Ogre::uint8 renderQueueGroup) :
    sceneMgr(sceneMgr),
    entity(entity),
    entityKey(generateEntityKey(entity)),
    renderQueueGroup(renderQueueGroup)
{
    //Add self to list of RenderedTexture's
    typedef std::pair<std::string, RenderedTexture*> ListItem;
    selfList.insert(ListItem(entityKey, this));

    // TODO: use bounding sphere
    //Note - this radius calculation assumes the object is somewhat rounded (like trees/rocks/etc.)
    Ogre::Real tmp;
    Ogre::AxisAlignedBox boundingBox = entity->getBoundingBox();
    entityRadius = boundingBox.getMaximum().x - boundingBox.getCenter().x;
    tmp = boundingBox.getMaximum().y - boundingBox.getCenter().y;
    if (tmp > entityRadius)
        entityRadius = tmp;
    tmp = boundingBox.getMaximum().z - boundingBox.getCenter().z;
    if (tmp > entityRadius)
        entityRadius = tmp;

    entityCenter = boundingBox.getCenter();

    //Render impostor textures
    renderTextures();

    //Set up material
    material =
        Ogre::MaterialManager::getSingleton().create(
            getUniqueID("RenderedEntityMaterial"), "EntityRenderer");

    Ogre::Material* m = material.getPointer();
    Ogre::Pass* p = m->getTechnique(0)->getPass(0);

    p->createTextureUnitState(texture->getName());

    p->setLightingEnabled(false);
    m->setReceiveShadows(false);

    if (blendMode == ALPHA_REJECT_IMPOSTOR){
        p->setAlphaRejectSettings(Ogre::CMPF_GREATER_EQUAL, 128);
        //p->setAlphaRejectSettings(CMPF_GREATER_EQUAL, 64);
    } else if (blendMode == ALPHA_BLEND_IMPOSTOR){
        p->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
        p->setDepthWriteEnabled(false);  
    }
}
void CSceneEditorView::OnEditsceneAddentity()
{
	CEntityCreatorDlg EntityCreatorDlg;

	if (IDOK == EntityCreatorDlg.DoModal())
	{
		HTREEITEM Selected = m_SceneManagerDlg->m_SceneTree.GetSelectedItem();
		m_SceneManagerDlg->m_SceneTree.InsertItem(EntityCreatorDlg.m_EntityName, Selected);
		
		Ogre::String SceneNodeName = m_SceneManagerDlg->m_SceneTree.GetItemText(Selected);
		Ogre::Entity *Entity = m_SceneManager->createEntity(Ogre::String(EntityCreatorDlg.m_EntityName), Ogre::String(EntityCreatorDlg.m_MeshName));
		Ogre::SceneNode *SceneNode = m_SceneManager->getSceneNode(SceneNodeName);
		SceneNode->attachObject(Entity);
	
		Ogre::AxisAlignedBox Box = Entity->getBoundingBox();
		Ogre::Vector3 Center = Box.getCenter();
		m_Camera->lookAt(Center);

		m_SceneManagerDlg->m_SceneTree.Expand(Selected, TVE_EXPAND);
		
		if (m_Root != NULL)
		{
			m_Root->renderOneFrame();
		}
	}
}
コード例 #4
0
ファイル: WXBoxCenterMovable.cpp プロジェクト: gitrider/wxsj2
    void
    BoxCenterMovable::getBoundingBoxCenter()
    {
        if(object.lock()->hasProperty("bounding box") && object.lock()->hasProperty("position"))
        {
            Ogre::AxisAlignedBox aabb = VariantCast<Ogre::AxisAlignedBox>(object.lock()->getProperty("bounding box"));
            /*Ogre::Vector3 position = VariantCast<Ogre::Vector3>(object.lock()->getProperty("position"));
            Ogre::Matrix4 matTrans;
            matTrans.makeTrans( position );
            aabb.transformAffine(matTrans);*/

			Ogre::Matrix4 transform = Ogre::Matrix4::IDENTITY;

			Ogre::Matrix3 rot3x3;
			if (object.lock()->hasProperty("orientation"))
			{
				Ogre::Quaternion orientation = VariantCast<Ogre::Quaternion>(object.lock()->getProperty("orientation"));
				orientation.ToRotationMatrix(rot3x3);
			}
			else
			{
				rot3x3 = Ogre::Matrix3::IDENTITY;
			}

			Ogre::Matrix3 scale3x3;
			if (object.lock()->hasProperty("scale"))
			{
				Ogre::Vector3 scale = VariantCast<Ogre::Vector3>(object.lock()->getProperty("scale"));
				scale3x3 = Ogre::Matrix3::ZERO;
				scale3x3[0][0] = scale.x;
				scale3x3[1][1] = scale.y;
				scale3x3[2][2] = scale.z;
			}
			else
			{
				scale3x3 = Ogre::Matrix3::IDENTITY;
			}

			transform = rot3x3 * scale3x3;

			if (object.lock()->hasProperty("position"))
			{
				Ogre::Vector3 position = VariantCast<Ogre::Vector3>(object.lock()->getProperty("position"));
				transform.setTrans(position);
			}
			aabb.transformAffine(transform);

            mCenterPosWC = aabb.getCenter();
        }
    }
コード例 #5
0
ファイル: SimpleRenderContext.cpp プロジェクト: bregma/ember
void SimpleRenderContext::repositionCamera()
{
    mEntityNode->_update(true, true);
    Ogre::AxisAlignedBox bbox = mEntityNode->_getWorldAABB();
    if (mCameraPositionMode == CPM_OBJECTCENTER) {
        if (!bbox.isInfinite() && !bbox.isNull()) {
            Ogre::Vector3 center = bbox.getCenter();
            Ogre::Vector3 localCenter = center - mRootNode->getPosition();
            mCameraNode->setPosition(localCenter);
        }
    } else if (mCameraPositionMode == CPM_WORLDCENTER) {
        mCameraNode->setPosition(Ogre::Vector3::ZERO);
    } else {
    }
}
コード例 #6
0
ファイル: World.cpp プロジェクト: wangxun159123/MiniCraft
Ogre::Vector3 World::GetRandomPositionOnNavmesh()
{
	TileSelection bound = m_pDetourTileCache->getBounds();
	int tx = (int)(Ogre::Math::RangeRandom(0, 1) * bound.maxTx);
	int ty = (int)(Ogre::Math::RangeRandom(0, 1) * bound.maxTy);

	Ogre::AxisAlignedBox tileBounds = m_pDetourTileCache->getTileBounds(tx, ty);
	Ogre::Vector3 center = tileBounds.getCenter();  // Center of the specified tile
	//center.y = tileBounds.getMinimum().y;   // Place on the ground
	// TODO centering probably has the biggest change of the point clipping to the navmesh

	// Get random point in tile (in circle in the middle of the tile with radius of tilesize/2)
	Ogre::Real radius = m_pDetourTileCache->getTileSize()/2;
	return m_pRecast->getRandomNavMeshPointInCircle(center, radius-1);   // TODO I could also make RADIUS_EPSILON be a fraction of the tileSize
}
コード例 #7
0
ファイル: OgreLight.cpp プロジェクト: bsmr-c-cpp/ogre
    //-----------------------------------------------------------------------
    bool Light::isInLightRange(const Ogre::AxisAlignedBox& container) const
    {
        bool isIntersect = true;
        //Check the 2 simple / obvious situations. Light is directional or light source is inside the container
        if ((mLightType != LT_DIRECTIONAL) && (container.intersects(mDerivedPosition) == false))
        {
            //Check that the container is within the sphere of the light
            isIntersect = Math::intersects(Sphere(mDerivedPosition, mRange),container);
            //If this is a spotlight, do a more specific check
            if ((isIntersect) && (mLightType == LT_SPOTLIGHT) && (mSpotOuter.valueRadians() <= Math::PI))
            {
                //Create a rough bounding box around the light and check if
                Quaternion localToWorld = Vector3::NEGATIVE_UNIT_Z.getRotationTo(mDerivedDirection);

                Real boxOffset = Math::Sin(mSpotOuter * 0.5) * mRange;
                AxisAlignedBox lightBoxBound;
                lightBoxBound.merge(Vector3::ZERO);
                lightBoxBound.merge(localToWorld * Vector3(boxOffset, boxOffset, -mRange));
                lightBoxBound.merge(localToWorld * Vector3(-boxOffset, boxOffset, -mRange));
                lightBoxBound.merge(localToWorld * Vector3(-boxOffset, -boxOffset, -mRange));
                lightBoxBound.merge(localToWorld * Vector3(boxOffset, -boxOffset, -mRange));
                lightBoxBound.setMaximum(lightBoxBound.getMaximum() + mDerivedPosition);
                lightBoxBound.setMinimum(lightBoxBound.getMinimum() + mDerivedPosition);
                isIntersect = lightBoxBound.intersects(container);
                
                //If the bounding box check succeeded do one more test
                if (isIntersect)
                {
                    //Check intersection again with the bounding sphere of the container
                    //Helpful for when the light is at an angle near one of the vertexes of the bounding box
                    isIntersect = isInLightRange(Sphere(container.getCenter(), 
                        container.getHalfSize().length()));
                }
            }
        }
        return isIntersect;
    }
コード例 #8
0
ファイル: animation.cpp プロジェクト: Chiur/openmw
void Animation::addExtraLight(Ogre::SceneManager *sceneMgr, NifOgre::ObjectScenePtr objlist, const ESM::Light *light)
{
    const MWWorld::Fallback *fallback = MWBase::Environment::get().getWorld()->getFallback();

    const int clr = light->mData.mColor;
    Ogre::ColourValue color(((clr >> 0) & 0xFF) / 255.0f,
                            ((clr >> 8) & 0xFF) / 255.0f,
                            ((clr >> 16) & 0xFF) / 255.0f);
    const float radius = float(light->mData.mRadius);

    if((light->mData.mFlags&ESM::Light::Negative))
        color *= -1;

    objlist->mLights.push_back(sceneMgr->createLight());
    Ogre::Light *olight = objlist->mLights.back();
    olight->setDiffuseColour(color);

    Ogre::ControllerValueRealPtr src(Ogre::ControllerManager::getSingleton().getFrameTimeSource());
    Ogre::ControllerValueRealPtr dest(OGRE_NEW OEngine::Render::LightValue(olight, color));
    Ogre::ControllerFunctionRealPtr func(OGRE_NEW OEngine::Render::LightFunction(
        (light->mData.mFlags&ESM::Light::Flicker) ? OEngine::Render::LT_Flicker :
        (light->mData.mFlags&ESM::Light::FlickerSlow) ? OEngine::Render::LT_FlickerSlow :
        (light->mData.mFlags&ESM::Light::Pulse) ? OEngine::Render::LT_Pulse :
        (light->mData.mFlags&ESM::Light::PulseSlow) ? OEngine::Render::LT_PulseSlow :
        OEngine::Render::LT_Normal
    ));
    objlist->mControllers.push_back(Ogre::Controller<Ogre::Real>(src, dest, func));

    bool interior = !(mPtr.isInCell() && mPtr.getCell()->getCell()->isExterior());
    bool quadratic = fallback->getFallbackBool("LightAttenuation_OutQuadInLin") ?
                     !interior : fallback->getFallbackBool("LightAttenuation_UseQuadratic");

    // with the standard 1 / (c + d*l + d*d*q) equation the attenuation factor never becomes zero,
    // so we ignore lights if their attenuation falls below this factor.
    const float threshold = 0.03;

    if (!quadratic)
    {
        float r = radius * fallback->getFallbackFloat("LightAttenuation_LinearRadiusMult");
        float attenuation = fallback->getFallbackFloat("LightAttenuation_LinearValue") / r;
        float activationRange = 1.0f / (threshold * attenuation);
        olight->setAttenuation(activationRange, 0, attenuation, 0);
    }
    else
    {
        float r = radius * fallback->getFallbackFloat("LightAttenuation_QuadraticRadiusMult");
        float attenuation = fallback->getFallbackFloat("LightAttenuation_QuadraticValue") / std::pow(r, 2);
        float activationRange = std::sqrt(1.0f / (threshold * attenuation));
        olight->setAttenuation(activationRange, 0, 0, attenuation);
    }

    // If there's an AttachLight bone, attach the light to that, otherwise put it in the center,
    if(objlist->mSkelBase && objlist->mSkelBase->getSkeleton()->hasBone("AttachLight"))
        objlist->mSkelBase->attachObjectToBone("AttachLight", olight);
    else
    {
        Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
        for(size_t i = 0;i < objlist->mEntities.size();i++)
        {
            Ogre::Entity *ent = objlist->mEntities[i];
            bounds.merge(ent->getBoundingBox());
        }

        Ogre::SceneNode *node = bounds.isFinite() ? mInsert->createChildSceneNode(bounds.getCenter())
                                                  : mInsert->createChildSceneNode();
        node->attachObject(olight);
    }
}
コード例 #9
0
ファイル: RoomsManager.cpp プロジェクト: beorc/flare_star
bool RoomsManager::UpdateObject(Room::ObjectType* object)
{    
    bool updated=false, inrooms=false;
    Room *room;

    //std::vector<Room*>::iterator iPos=Rooms.begin(), iEnd=Rooms.end();
	inrooms=false;
    //for (size_t i=0;i<Rooms.Size;++i)
    Ogre::AxisAlignedBox box = object->GetRoomable()->GetBoundingBox(), *RoomBox;
    
	//assert()

	for (RoomsPool::ListNode *pos = Rooms.GetBegin(); pos!=NULL; pos=pos->Next)
    {
        room = pos->Value;        
        RoomBox = room->GetBox();
        if (RoomBox->intersects(box))
        {
            updated = room->UpdateObject(object);
            if (updated)
		    {           
			    inrooms=true;			
		    }
        }
    }

	if (!inrooms)
	{
		/*char log[100];
		sprintf(log,"Rooms 1: empty room set for object %d\n",object->GetScriptable()->GetID());
		Debugging::Log("Warnings.log",log);*/		
				
		IRoomable *rmbl = object->GetRoomable();
		IPhysical *phys = object->GetPhysical();
		if (rmbl)
		{
			rmbl->RemoveFromRooms();
			rmbl->GetRooms()->Clear();			
			switch (rmbl->GetRoomOnly())
			{
				case IRoomable::ROM_RESTORE:
					{						
						for (RoomsPool::ListNode *pos = Rooms.GetBegin(); pos!=NULL; pos=pos->Next)
						{
							Ogre::AxisAlignedBox *box = pos->Value->GetBox();
							Ogre::Vector3 center = box->getCenter();
							Ogre::Vector3 position = object->GetPosition();
							Ogre::Vector3 dist = position - center;

							int sqradius = AAUtilities::f2i(box->getHalfSize().squaredLength())+3*phys->GetRadius();
														
							int sqdist = AAUtilities::f2i(dist.squaredLength());
							if (sqradius>sqdist)
							{
								//GetPhysical()->SetForwardDirection(GetOrientation()*Vector3::UNIT_Z);
								//object->GetPhysical();
								//object->RestoreBackupPosition();								
								//Ogre::Vector3 newdir=phys->GetLastVelocity();
								//phys->Stop();
								phys->SetReplacingDirection(-dist.normalisedCopy()*10);
								break;
							}
						}
						AddOuterObject(object);
						//object->RestoreBackupPosition();
						break;
					}					
				case IRoomable::ROM_DESTROY:
					{
						CommonDeclarations::DeleteObjectRequest(object);
						break;
					}					
				case IRoomable::ROM_SCRIPT:
					{
						IScriptable *scr = object->GetScriptable();
						if (scr && scr->GetID()>0)
							ScriptManager::GetInstance()->Call("OnOutOfRooms", "i", false, object->GetScriptable()->GetID());
						break;
					}
				case IRoomable::ROM_NONE:
					{
						AddOuterObject(object);
						break;
					}

			};
		}
		
	}
    
    return inrooms;
}
void CManualObjectView::EngineSetup(void)
{
	Ogre::Root *Root = ((CManualObjectApp*)AfxGetApp())->m_Engine->GetRoot();
	m_SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "m_ManualObject");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("m_ManualObject");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("m_ManualObject", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = m_SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(200.0, 50.0, 100.0));
	m_Camera->lookAt(0.0, 0.0, 0.0);

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = m_SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(1.0f, 1.0f, 1.0f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	CreateManualObject();
	Ogre::AxisAlignedBox Box = m_ManualObject->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();
	m_Camera->lookAt(Center);
	m_Camera->setPosition(300, 100, 200);

//	m_Camera->setPolygonMode(Ogre::PM_WIREFRAME);
	Root->renderOneFrame();
}
コード例 #11
0
	void RenderBoxWrap::updateViewport()
	{
		// при нуле вылетает
		if ((mRenderBox->getWidth() <= 1) || (mRenderBox->getHeight() <= 1) ) return;

		if ((nullptr != mEntity) && (nullptr != mRttCam)) {
			// не ¤сно, нужно ли раст¤гивать камеру, установленную юзером
			mRttCam->setAspectRatio((float)mRenderBox->getWidth() / (float)mRenderBox->getHeight());

			//System::Console::WriteLine("Width {0}, Height {1}", getWidth(), getHeight());

			// вычисл¤ем рассто¤ние, чтобы был виден весь объект
			Ogre::AxisAlignedBox box;// = mNode->_getWorldAABB();//mEntity->getBoundingBox();

			VectorEntity::iterator iter = mVectorEntity.begin();

			while (iter != mVectorEntity.end())
			{
				box.merge((*iter)->getBoundingBox().getMinimum() + (*iter)->getParentSceneNode()->_getDerivedPosition());
				box.merge((*iter)->getBoundingBox().getMaximum() + (*iter)->getParentSceneNode()->_getDerivedPosition());
				iter++;
			}

			if (box.isNull()) return;

			//box.scale(Ogre::Vector3(1.41f,1.41f,1.41f));

			//System::Console::WriteLine("Minimum({0}), Maximum({1})",
			//	gcnew System::String(Ogre::StringConverter::toString(box.getMinimum()).c_str()),
			//	gcnew System::String(Ogre::StringConverter::toString(box.getMaximum()).c_str()));

			//box.getCenter();
			Ogre::Vector3 vec = box.getSize();

			// коррекци¤ под левосторонюю систему координат с осью Z направленную вверх
			#ifdef LEFT_HANDED_CS_UP_Z

				float width = sqrt(vec.x*vec.x + vec.y*vec.y); // самое длинное - диагональ (если крутить модель)
				float len2 = width; // mRttCam->getAspectRatio();
				float height = vec.z;
				float len1 = height;
				if (len1 < len2) len1 = len2;
				len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view
				// центр объекта по вертикали + отъехать так, чтобы влезла ближн¤¤ грань BoundingBox'а + чуть вверх и еще назад дл¤ красоты
				Ogre::Vector3 result = box.getCenter() - Ogre::Vector3(vec.y/2 + len1, 0, 0) - Ogre::Vector3(len1*0.2, 0, -height*0.1);
				result.x *= mCurrentScale;
				mCamNode->setPosition(result);

				Ogre::Vector3 x = Ogre::Vector3(0, 0, box.getCenter().z + box.getCenter().z * (1-mCurrentScale)) - mCamNode->getPosition();
				Ogre::Vector3 y = Ogre::Vector3(Ogre::Vector3::UNIT_Z).crossProduct(x);
				Ogre::Vector3 z = x.crossProduct(y);
				mCamNode->setOrientation(Ogre::Quaternion(
					x.normalisedCopy(),
					y.normalisedCopy(),
					z.normalisedCopy()));

			#else

				float width = sqrt(vec.x*vec.x + vec.z*vec.z); // самое длинное - диагональ (если крутить модель)
				float len2 = width / mRttCam->getAspectRatio();
				float height = vec.y;
				float len1 = height;
				if (len1 < len2) len1 = len2;
				len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view
				// центр объекта по вертикали + отъехать так, чтобы влезла ближн¤¤ грань BoundingBox'а + чуть вверх и еще назад дл¤ красоты
				Ogre::Vector3 result = box.getCenter() + Ogre::Vector3(0, 0, vec.z/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2);
				result.z *= mCurrentScale;
				Ogre::Vector3 look = Ogre::Vector3(0, box.getCenter().y /*+ box.getCenter().y * (1-mCurrentScale)*/, 0);

				mCamNode->setPosition(result);
				mCamNode->lookAt(look, Ogre::Node::TS_WORLD);

			#endif
		}
	}
void CSaveSceneView::EngineSetup(void)
{
	Ogre::Root *Root = ((CSaveSceneApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "SaveScene");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("SaveScene");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("SaveScene", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(200.0, 50.0, 100.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");
	CameraNode->attachObject(m_Camera);

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	RobotNode->attachObject(RobotEntity);


	Ogre::AxisAlignedBox Box = RobotEntity->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();
	m_Camera->lookAt(Center);

	int rc;

    xmlDocPtr doc;
   // Create a new Xmlm_XmlWriter for DOM, with no compression.
    m_XmlWriter = xmlNewTextWriterDoc(&doc, 0);
   // Start the document with the xml default for the version,
   // encoding ISO 8859-1 and the default for the standalone
   // declaration.
    xmlTextWriterStartDocument(m_XmlWriter, NULL, MY_ENCODING, NULL);
	
	SceneExplore(SceneManager);
   
	xmlTextWriterEndDocument(m_XmlWriter);
	xmlFreeTextWriter(m_XmlWriter);
    xmlSaveFileEnc("1.scene", doc, MY_ENCODING);
    xmlFreeDoc(doc);
}
コード例 #13
0
ファイル: Terrain.cpp プロジェクト: gitrider/wxsj2
void
Terrain::buildGeometry(Ogre::SceneNode* parent, bool editable)
{
    clearGeometry();	

    assert(parent);

    // NB: We must adjust world geometry bounding box, especially for OctreeSceneManager
    Ogre::AxisAlignedBox aabb = mData->getBoundBox();
    Ogre::Vector3 centre = aabb.getCenter();
    const Ogre::Vector3 adjust(2000, 10000, 2000);
    const Ogre::Real scale = 1.5f;
    aabb.setExtents(
        (aabb.getMinimum() - centre) * scale + centre - adjust,
        (aabb.getMaximum() - centre) * scale + centre + adjust);
    parent->getCreator()->setOption("Size", &aabb);

    mEditable = editable;

    if (!mData->mXSize || !mData->mZSize)
    {
        // Do nothing if it's empty terrain.
        return;
    }

    // Prepare atlas texture
    for (size_t pixmapId = 0, numPixmap = mData->mPixmaps.size(); pixmapId < numPixmap; ++pixmapId)
    {
        _getPixmapAtlasId(pixmapId);
    }

	prepareLightmapTexture();

    int depth = mData->mZSize;
    int width = mData->mXSize;
    int tileSize = mData->mTileSize;
    int numTilePerX = mData->mNumTilePerX;
    int numTilePerZ = mData->mNumTilePerZ;

    if (mEditable)
    {
        mGridTypeInfos.resize(2);
        mGridTypeInfos[0].material.setNull();
        mGridTypeInfos[1].material = Ogre::MaterialManager::getSingleton().getByName(
            "FairyEditor/GridType");
    }
    else
    {
        _initIndexBuffer(tileSize * tileSize);
    }

    mTiles.reserve(numTilePerX * numTilePerZ);
    for (int z = 0; z < numTilePerZ; ++z)
    {
        for (int x = 0; x < numTilePerX; ++x)
        {
            // Create the tile
            int tileX = x * tileSize;
            int tileZ = z * tileSize;
            int tileWidth = std::min(width - tileX, tileSize);
            int tileDepth = std::min(depth - tileZ, tileSize);
            TerrainTile* tile;
			if (mEditable)
				tile = new TerrainTileEditable(parent, this, tileX, tileZ, tileWidth, tileDepth);
			else
				tile = new TerrainTileOptimized(parent, this, tileX, tileZ, tileWidth, tileDepth);

            // Use the render queue that the world geometry associated with.
            tile->setRenderQueueGroup(parent->getCreator()->getWorldGeometryRenderQueue());

            // Attach it to the aux data
            mTiles.push_back(tile);
        }
    }
}
void CGeoImageView::EngineSetup(void)
{
	Ogre::Root *Root = ((CGeoImageApp*)AfxGetApp())->m_Engine->GetRoot();

	Ogre::SceneManager *SceneManager = NULL;

	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "MFCOgre");

    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);

	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Ogre in MFC");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Ogre in MFC", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
//	m_Camera->setPosition(Ogre::Vector3(320.0, 240.0, 500.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 1.0f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
		

	TIFF 	*Tif = (TIFF*)0;  /* TIFF-level descriptor */
  	GTIF	*GTif = (GTIF*)0; /* GeoKey-level descriptor */

	CString SourcePath = "C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\materials\\textures\\o41078a1.tif";
 int ImageWidth;
 int ImageHeight;

 double LowerLeftX;
 double LowerLeftY;

 double UpperRightX;
 double UpperRightY;

 int Xpos;
 int Ypos;

	Tif = XTIFFOpen((LPCSTR)SourcePath, "r");
	GTif = GTIFNew(Tif);
 
	GTIFDefn Definition;
	GTIFGetDefn(GTif, &Definition);
 
	GTIFPrint(GTif, 0, 0);

	TIFFGetField( Tif, TIFFTAG_IMAGEWIDTH, &ImageWidth);
 	TIFFGetField( Tif, TIFFTAG_IMAGELENGTH, &ImageHeight);

int res = 0;

 double LowerRightX = ImageWidth;
 double LowerRightY = ImageHeight;

 res = GTIFImageToPCS(GTif, &LowerRightX, &LowerRightY);
  //Lower Left
 LowerLeftX = 0.0;
 LowerLeftY = ImageHeight;

 res = GTIFImageToPCS(GTif, &LowerLeftX, &LowerLeftY);

 //Upper Right
 UpperRightX = ImageWidth;
 UpperRightY = 0.0;

 res = GTIFImageToPCS(GTif, &UpperRightX, &UpperRightY);

 double UpperLeftX = 0.0;
 double UpperLeftY = 0.0;

 res = GTIFImageToPCS(GTif, &UpperLeftX, &UpperLeftY);

  	Ogre::ManualObject *Terrain = SceneManager->createManualObject("Terrain");
	Terrain->setDynamic(false);
	Terrain->begin("Terrain", Ogre::RenderOperation::OT_TRIANGLE_FAN);

#define MIN(x,y)     (((x) < (y)) ? (x) : (y))
#define MAX(x,y)     (((x) > (y)) ? (x) : (y))

#define SW     0
#define NW     1
#define NE     2
#define SE     3

FILE *File = NULL;
char            Dummy[160];
char inText[24];
 char *Dest;
	int             base[2048];         /* array of base elevations */
char            mapLabel[145];
int             DEMlevel, elevationPattern, groundSystem, groundZone;
double          projectParams[15];
int             planeUnitOfMeasure, elevUnitOfMeasure, polygonSizes;
double          groundCoords[4][2], elevBounds[2], localRotation;
int             accuracyCode;
double          spatialResolution[3];
int             profileDimension[2];
int             firstRow, lastRow;
int             wcount = 0;

double          verticalScale = 1.0;      /* to stretch or shrink elevations */
double          deltaY;
char *junk;

double eastMost;
double westMost;
double southMost;
double northMost;

int  eastMostSample;
int  westMostSample;
int southMostSample;
int northMostSample;

int        rowCount, columnCount, r, c;
int	rowStr = 1;
int rowEnd;
int colStr = 1;
int colEnd;
int colInt = 1;
int rowInt = 1;
int outType = 0;
 int k,l ;
 double comp = 0.0;

     int 	   mod ;
    int             tempInt, lastProfile = 0;

    float           noValue = 0.0f;
    int             profileID[2], profileSize[2];
    double          planCoords[2], localElevation, elevExtremea[2];


 File = fopen("C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\geotiff\\karthaus_pa.dem", "r");

 fscanf(File, "%144c%6d%6d%6d%6d",
	     mapLabel,              /* 1 */
	     &DEMlevel,             /* 2 */
	     &elevationPattern,     /* 3 */
             &groundSystem,         /* 4 */
             &groundZone );         /* 5 */


    for (k=0; k<15 ; k++) 
	{
     fscanf(File,"%24c", inText);    /* 6 */
      Dest = strchr(inText,'D');  *Dest = 'E';
      projectParams[k]  = strtod(inText,&junk);
    }

    fscanf(File,"%6d%6d%6d",
             &planeUnitOfMeasure,   /* 7 */
             &elevUnitOfMeasure,    /* 8 */
             &polygonSizes);        /* 9 */

    for (k=0; k < 4 ; k++)
       for (l=0; l < 2 ; l++)
	   { 
        fscanf(File,"%24c", inText);    /* 6 */
        Dest = strchr(inText,'D');  *Dest = 'E';
        groundCoords[k][l]  = strtod(inText,&junk);
	   }

    fscanf(File,"%24c", inText);
    Dest = strchr(inText,'D');  *Dest = 'E';
    elevBounds[0] = strtod(inText,&junk);       /* 10 */
    fscanf(File,"%24c", inText);
    
	Dest = strchr(inText,'D');  *Dest = 'E';
    elevBounds[1] = strtod(inText,&junk);      /* 11 */
    fscanf(File,"%24c", inText);
    Dest = strchr(inText,'D');  *Dest = 'E';
    localRotation  = strtod(inText,&junk);      /* 12 */

   fscanf(File,"%1d%12le%12le%12le%6d%6d",
             &accuracyCode,             /* 13 */
	     &spatialResolution[0],     /* 14 */
             &spatialResolution[1],     /* 14 */
             &spatialResolution[2],     /* 14 */
             &profileDimension[0],      /* 15 */
             &profileDimension[1]);     /* 15 */

   fscanf(File, "%160c", Dummy);

    if (spatialResolution[0] == 3.0) 
	{
	 comp   = spatialResolution[0] - 1.0 ;
	 deltaY = spatialResolution[1] / 3600.  ;
    }
    else
	{
	 comp   = 0.;
	 deltaY = spatialResolution[1] ;
    }

    eastMost  = MAX(groundCoords[NE][0], groundCoords[SE][0]);
    westMost  = MIN(groundCoords[NW][0], groundCoords[SW][0]);
    northMost = MAX(groundCoords[NE][1], groundCoords[NW][1]);
    southMost = MIN(groundCoords[SW][1], groundCoords[SE][1]);
    eastMostSample =  ((int) (eastMost / spatialResolution[0]))
		     * (int) spatialResolution[0];
    westMostSample =  ((int) ((westMost + comp) / spatialResolution[0]))
		     * (int) spatialResolution[0] ;
    northMostSample = ((int) (northMost / spatialResolution[1]))
		     * (int) spatialResolution[1] ;
    southMostSample = ((int) ((southMost + comp) / spatialResolution[1]))
		     * (int) spatialResolution[1] ;
    
	columnCount = (eastMostSample  - westMostSample)
		  / (int) spatialResolution[0] + 1;
    rowCount    = (northMostSample - southMostSample)
		  / (int) spatialResolution[1] + 1;

    if (columnCount != profileDimension[1])
	  columnCount =MIN( profileDimension[1], columnCount);

for (c = 1; c <= columnCount; c++) 
 {
  fscanf(File, "%d%d%d%d",
		 &profileID[0],        /* 1 */
		 &profileID[1],        /* 1 */
		 &profileSize[0],      /* 2 */
		 &profileSize[1]);     /* 2 */

       fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       planCoords[0]   = strtod(inText,&junk);     /* 3 */
	  fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       planCoords[1]   = strtod(inText,&junk);     /* 3 */
	   fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       localElevation  = strtod(inText,&junk);     /* 4 */
	 fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       elevExtremea[0] = strtod(inText,&junk);     /* 5 */
	   fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       elevExtremea[1] = strtod(inText,&junk);     /* 5 */

       lastProfile =  profileID[1];

       firstRow = abs(((int) (planCoords[1] - southMostSample))
		 / (int) spatialResolution[1]);
       lastRow = firstRow + profileSize[0] - 1;

       for ( r = 0 ; r < firstRow  ; r++ ) 
		   base[r] = 0;

/*     read in all the data for this column */
       for (r = firstRow; r <= lastRow; r++ )
       {
	  fscanf(File, "%6d",	&tempInt);
	   base[r] = tempInt;
       }

    double          tempFloat;

   for (r = firstRow; r <= lastRow; r += rowInt) 
   {
    tempFloat = (float) base[r]  * verticalScale;
 	Terrain->position(planCoords[0], tempFloat, planCoords[1]);

	Ogre::Real u = 0.0;
	Ogre::Real v = 0.0;

	if (planCoords[0] > LowerLeftX && planCoords[0] < UpperRightX)
	{
		u = (planCoords[0] - LowerLeftX) / (UpperRightX - LowerLeftX);
	}

	if (planCoords[1] > LowerLeftY && planCoords[1] < UpperRightY)
	{
		v = (planCoords[1] - LowerLeftY) / (UpperRightY - LowerLeftY);
	}

	Terrain->textureCoord(u, v); 
	planCoords[1] += deltaY;
   }
 }

 Terrain->end();
 fclose(File);

	Ogre::SceneNode* node = SceneManager->getRootSceneNode()->createChildSceneNode();
	node->setPosition(0, 0, 0);
	node->attachObject(Terrain);

	Ogre::AxisAlignedBox Box = Terrain->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();

	Ogre::Vector3 Target = Center;
	Ogre::Vector3 Position = Center;

	Position[1] += 5000.0;
	m_Camera->setPosition(Position);
	m_Camera->lookAt(Target);
}
void CTerrainWalkingView::EngineSetup(void)
{
	Ogre::Root *Root = ((CTerrainWalkingApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Walking");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Walking", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(10);
	m_Camera->setFarClipDistance(10000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *TopographyNode = SceneManager->getRootSceneNode()->createChildSceneNode("Topography");
	Ogre::Entity *TopographyEntity = SceneManager->createEntity("Topography", "Topography.mesh");
	TopographyNode->attachObject(TopographyEntity);
	
	Ogre::AxisAlignedBox TopographyBox = TopographyEntity->getBoundingBox();
	
	Ogre::Vector3 Minimum = TopographyBox.getMinimum();
	Ogre::Vector3 Center = TopographyBox.getCenter();

	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode("Robot");
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	RobotNode->attachObject(RobotEntity);
	RobotEntity->getParentNode()->scale(10,10,10);
	Ogre::AxisAlignedBox RobotBox = RobotEntity->getBoundingBox();

	RobotNode->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + RobotBox.getSize()[1], Minimum[2]));

	m_Camera->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + 5000, Minimum[2]));
	m_Camera->lookAt(Center);
	
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);

	m_Animation = RobotEntity->getAnimationState("Walk");
	m_Animation->setEnabled(true);
	
	m_CollisionTools = new MOC::CollisionTools(SceneManager);

	Root->renderOneFrame();
}
コード例 #16
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());
    }
}
void CViewManagerView::On3dViews()
{
	int ViewIndex = CMFCRibbonGallery::GetLastSelectedItem(ID_3DVIEWS);
	CEngine *Engine = ((CViewManagerApp*)AfxGetApp())->m_Engine;
	Ogre::Root *Root = Engine->GetRoot();
	m_SceneManager->_updateSceneGraph(m_Camera);
	Ogre::SceneNode *CubeNode = m_SceneManager->getSceneNode("Cube");

	Ogre::AxisAlignedBox Box = m_SceneManager->getRootSceneNode()->_getWorldAABB();
	Ogre::Vector3 Center = Box.getCenter();
	Ogre::Vector3 Position;
	Ogre::Vector3 Destination;

	switch (ViewIndex)
	{
		case 0: //top

			Position = Center;
			Position.y += 4.0 * Box.getSize().y;
			Destination = Center;

		break;
		case 1://bottom
			
			Position = Center;
			Position.y -= 4.0 * Box.getSize().y;
			Destination = Center;

		break;
		case 2:

			Position = Center;
			Position.x += 4.0 * Box.getSize().x;
			Destination = Center;

		break;
		case 3:

			Position = Center;
			Position.x -= 4.0 * Box.getSize().x;
			Destination = Center;

		break;
		case 4:

			Position = Center;
			Position.z -= 4.0 * Box.getSize().z;
			Destination = Center;

		break;
		case 5:

			Position = Center;
			Position.z += 4.0 * Box.getSize().z;
			Destination = Center;

		break;

		case 9:

			CubeNode->roll(Ogre::Radian(-atan(sin(Ogre::Math::PI/4.0))));
			CubeNode->yaw(Ogre::Radian(Ogre::Math::PI/4.0));
			Destination = Center;
			Position = m_Camera->getPosition();

		break;
	}

	m_Camera->setPosition(Position);
	m_Camera->lookAt(Destination);
	Root->renderOneFrame();
}