Example #1
0
int Hundir::start() {
    _root = new Ogre::Root();

    if(!_root->restoreConfig()) {
        _root->showConfigDialog();
        _root->saveConfig();
    }
    Ogre::RenderWindow* window = _root->initialise(true,"Hundir Example");
    _sceneManager = _root->createSceneManager(Ogre::ST_GENERIC);
    Ogre::Camera* cam = _sceneManager->createCamera("MainCamera");
    cam->setPosition(Ogre::Vector3(-10,30,35));
    cam->lookAt(Ogre::Vector3(0,0,0));
    cam->setNearClipDistance(5);
    cam->setFarClipDistance(10000);

    Ogre::Viewport* viewport = window->addViewport(cam);
    viewport->setBackgroundColour(Ogre::ColourValue(0.0,0.0,0.0));
    double width = viewport->getActualWidth();
    double height = viewport->getActualHeight();
    cam->setAspectRatio(width / height);

    loadResources();
    createScene();

    _framelistener = new MyFrameListener(window, cam, _sceneManager);
    _root->addFrameListener(_framelistener);
    _root->startRendering();
    return 0;
}
Example #2
0
//-------------------------------------------------------------------------------------------
void MagickWidget::loadMesh(Ogre::MeshPtr pMesh)
{
    QString directory(OgitorsRoot::getSingletonPtr()->GetProjectOptions()->ProjectDir.c_str());
    if(directory.isEmpty())
        directory = "./";

    QDir(directory).mkpath("entitycache");

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "MeshMagickTex", 
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 
                   512, 512, 0, Ogre::PF_R8G8B8A8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "MeshMagickTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("MeshMagickCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0));

    Ogre::Entity *mEntity;

    mEntity = mSceneMgr->createEntity("scbDisplay", pMesh->getName());
    mSceneMgr->getRootSceneNode()->attachObject(mEntity);

    Ogre::Vector3 vSize = mEntity->getBoundingBox().getHalfSize();
    Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter(); 
    
    vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

    float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);
    
    vSize = Ogre::Vector3(0, 0, maxsize * 1.15f) + vCenter;
    
    RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
    RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

    rttTex->update();
    Ogre::String imagefile = OgitorsUtils::QualifyPath(directory.toStdString() + "/entitycache/meshmagick.png");
    rttTex->writeContentsToFile(imagefile);

    mEntity->detachFromParent();
    mSceneMgr->destroyEntity(mEntity);
    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    mDisplayWidget->setImage(QString(imagefile.c_str()));
}
Example #3
0
void GraphicsImpl::createCamera()
{
	camera = sceneMgr->createCamera("MainCamera");
	// Position it at 500 in Z direction
	camera->setPosition(Ogre::Vector3(0, 50, 100));
	// Look back along -Z
	camera->lookAt(Ogre::Vector3(0, -10, 0));
	camera->setNearClipDistance(5);
	camera->setFarClipDistance(0);
}
Example #4
0
void BaseApp::createCamera()
{
	Ogre::Camera* cam = mSceneMgr->createCamera("PlayerCam");
	cam->setPosition(0,0,0);
	cam->lookAt(0,0,0);
	//cam->setAutoAspectRatio(true);
	cam->setNearClipDistance(1);
	cam->setFarClipDistance(10000);
	mCameraMan = new OgreBites::SdkCameraMan(cam);
	mCameraMan->setTopSpeed(1000);
}
Example #5
0
 void ReliefApp::GenerateRelief()
 {
     //Get depth data
     Ogre::TexturePtr depthTex = Ogre::TextureManager::getSingleton().createManual(  
         "DepthTexture",      // name   
         Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,  
         Ogre::TEX_TYPE_2D,   // type   
         512,  // width   
         512,  // height   
         0,                   // number of mipmaps   
         //Ogre::PF_B8G8R8A8,   // pixel format
         Ogre::PF_FLOAT32_R,
         Ogre::TU_RENDERTARGET
         ); 
     Ogre::RenderTarget* pTarget = depthTex->getBuffer()->getRenderTarget();
     Ogre::Camera* pOrthCam = MagicCore::RenderSystem::GetSingleton()->GetMainCamera();
     pOrthCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
     pOrthCam->setOrthoWindow(3, 3);
     pOrthCam->setPosition(0, 0, 3);
     pOrthCam->lookAt(0, 0, 0);
     pOrthCam->setAspectRatio(1.0);
     pOrthCam->setNearClipDistance(0.5);
     pOrthCam->setFarClipDistance(5);
     Ogre::Viewport* pViewport = pTarget->addViewport(pOrthCam);
     pViewport->setDimensions(0, 0, 1, 1);
     MagicCore::RenderSystem::GetSingleton()->RenderLightMesh3D("RenderMesh", "Depth", mpLightMesh);
     MagicCore::RenderSystem::GetSingleton()->Update();
     Ogre::Image img;
     depthTex->convertToImage(img);
     std::vector<double> heightField(512 * 512);
     for(int x = 0; x < 512; x++)  
     {  
         for(int y = 0; y < 512; y++)  
         {
             heightField.at(x * 512 + y) = (img.getColourAt(x, 511 - y, 0))[1];
         }
     }
     Ogre::TextureManager::getSingleton().remove("DepthTexture");
     //
     MagicDGP::LightMesh3D* pReliefMesh = MagicDGP::ReliefGeneration::PlaneReliefFromHeightField(heightField, 511, 511);
     //MagicDGP::LightMesh3D* pReliefMesh = MagicDGP::ReliefGeneration::CylinderReliefFromHeightField(heightField, 511, 511);
     if (pReliefMesh != NULL)
     {
         delete mpLightMesh;
         mpLightMesh = pReliefMesh;
         mpLightMesh->UnifyPosition(2);
         mpLightMesh->UpdateNormal();
     }
     MagicCore::RenderSystem::GetSingleton()->SetupCameraDefaultParameter();
     MagicCore::RenderSystem::GetSingleton()->RenderLightMesh3D("RenderMesh", "MyCookTorrance", mpLightMesh);
 }
Example #6
0
void DotSceneLoader::processCamera(rapidxml::xml_node<>* XMLNode,
		Ogre::SceneNode *pParent) {
	// Process attributes
	Ogre::String name = getAttrib(XMLNode, "name");
	Ogre::String id = getAttrib(XMLNode, "id");
// Ogre::Real fov = getAttribReal(XMLNode, "fov", 45);
// Ogre::Real aspectRatio = getAttribReal(XMLNode, "aspectRatio", 1.3333);
	Ogre::String projectionType = getAttrib(XMLNode, "projectionType",
			"perspective");

	// Create the camera
	Ogre::Camera *pCamera = mSceneMgr->createCamera(name);

	// Set the projection type
	if (projectionType == "perspective")
		pCamera->setProjectionType(Ogre::PT_PERSPECTIVE);
	else if (projectionType == "orthographic")
		pCamera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

	rapidxml::xml_node<>* pElement;

	// Process clipping (?)
	pElement = XMLNode->first_node("clipping");
	if (pElement) {
		Ogre::Real nearDist = getAttribReal(pElement, "near");
		if (nearDist > 0)
		  pCamera->setNearClipDistance(nearDist);

		Ogre::Real farDist = getAttribReal(pElement, "far");
		pCamera->setFarClipDistance(farDist);
	}

	// Process position (?)
	pElement = XMLNode->first_node("position");
	if (pElement)
		pCamera->setPosition(parseVector3(pElement));

	// Process rotation (?)
	pElement = XMLNode->first_node("rotation");
	if (pElement)
		pCamera->setOrientation(parseQuaternion(pElement));

	// construct a scenenode is no parent
	if (!pParent) {
		Ogre::SceneNode* pNode = mAttachNode->createChildSceneNode(name);
		pNode->setPosition(pCamera->getPosition());
		pNode->setOrientation(pCamera->getOrientation());
		pNode->scale(1, 1, 1);
	}
}
Example #7
0
static void setupScene()
{
	LOGI("------->setupScene()");

	Ogre::ConfigFile cf;
	cf.load(openAPKFile("resources.cfg"));

	Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
	while (seci.hasMoreElements())
	{
		Ogre::String sec, type, arch;
		sec = seci.peekNextKey();
		Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext();
		Ogre::ConfigFile::SettingsMultiMap::iterator i;

		for (i = settings->begin(); i != settings->end(); i++)
		{
			type = i->first;
			arch = i->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(arch, type, sec);
		}
	}

	Ogre::ResourceGroupManager::getSingletonPtr()->initialiseResourceGroup(
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

	gSceneMgr = gRoot->createSceneManager(Ogre::ST_GENERIC);
	Ogre::Camera* camera = gSceneMgr->createCamera("MyCam");

	Ogre::Entity* pEntity = gSceneMgr->createEntity("SinbadInstance", "Sinbad.mesh");
	Ogre::SceneNode* pNode = gSceneMgr->getRootSceneNode()->createChildSceneNode();
	pNode->attachObject(pEntity);

	Ogre::Light* pDirLight = gSceneMgr->createLight();
	pDirLight->setDirection(Ogre::Vector3(0, -1, 0));
	pDirLight->setType(Ogre::Light::LT_DIRECTIONAL);
	pNode->attachObject(pDirLight);

	camera->setNearClipDistance(1.0f);
	camera->setFarClipDistance(100000.0f);
	camera->setPosition(0, 0, 20.0f);
	camera->lookAt(0, 0, 0);
	camera->setAutoAspectRatio(true);

	Ogre::Viewport* vp = gRenderWnd->addViewport(camera);
	vp->setBackgroundColour(Ogre::ColourValue(1, 0, 0));

	LOGI("<-------setupScene()");
}
//We're not sure whether return a reference to a vector is such a great idea. 
void
    CinematicManager::createPerspectiveCamera(Ogre::Real windowW, Ogre::Real windowH, const Ogre::Vector3 &initialPos,
    const Ogre::Quaternion &initialOrient, Control* control)
{
    Ogre::Camera* cam = _scnMgr->createCamera(PERSP_CAM_NAME + Ogre::StringConverter::toString(_camCurId));
    cam->setNearClipDistance(1.0f);
    cam->setFarClipDistance(400.0f);
    cam->setPosition(0.0f, 0.0f, 0.0f);
    cam->setAspectRatio(windowW / windowH);
    Ogre::SceneNode* defaultNode = _scnMgr->createSceneNode();
    defaultNode->setPosition(initialPos); //It's in local space.
    defaultNode->setOrientation(initialOrient);
    defaultNode->attachObject(cam);
    _camsVec.push_back(new ZCameraInfo(_camsVec.size(), "PERSPECTIVE", cam->getName(), control, cam));
}
Example #9
0
void
	Geometry::setupView() {
		Ogre::Camera * mCamera = OgreTrip::getCamera();
		// put camera at world center, so that it's difficult to reach the edge
		Vector3 worldCenter(
			(ENDLESS_PAGE_MAX_X + ENDLESS_PAGE_MIN_X) / 2 * TERRAIN_WORLD_SIZE,
			0,
			-(ENDLESS_PAGE_MAX_Y + ENDLESS_PAGE_MIN_Y) / 2 * TERRAIN_WORLD_SIZE
			);
		//mCamera->setPosition(mTerrainPos + worldCenter);
		//mCamera->lookAt(mTerrainPos);
		mCamera->setNearClipDistance(0.1);
		mCamera->setFarClipDistance(8000);
		/*
		if (OgreTrip::getRoot()->getRenderSystem()->getCapabilities()->hasCapability(RSC_INFINITE_FAR_PLANE)) {
			mCamera->setFarClipDistance(0);   // enable infinite far clip distance if we can
		}*/
}
Example #10
0
int MyApp::start() {
  _root = new Ogre::Root();
  
  if(!_root->restoreConfig()) {
    _root->showConfigDialog();
    _root->saveConfig();
  }

  _pTrackManager = new TrackManager;
  _pSoundFXManager = new SoundFXManager;
  
  Ogre::RenderWindow* window = _root->initialise(true,"MyApp Example");
  _sceneManager = _root->createSceneManager(Ogre::ST_GENERIC);
  
  Ogre::Camera* cam = _sceneManager->createCamera("MainCamera");
  cam->setPosition(Ogre::Vector3(7,10.5,8));
  cam->lookAt(Ogre::Vector3(0,3.5,0));
  cam->setNearClipDistance(5);
  cam->setFarClipDistance(10000);
  
  Ogre::Viewport* viewport = window->addViewport(cam);
  viewport->setBackgroundColour(Ogre::ColourValue(0.0,0.0,0.0));
  double width = viewport->getActualWidth();
  double height = viewport->getActualHeight();
  cam->setAspectRatio(width / height);
  
  loadResources();
  createScene();
  createOverlay();

  Ogre::SceneNode *node = _sceneManager->getSceneNode("Neptuno");
  
  _framelistener = new MyFrameListener(this, window, cam, node, _overlayManager, 
				       _sceneManager);
  _root->addFrameListener(_framelistener);
  
  // Reproducción del track principal...
  this->_mainTrack->play();

  _root->startRendering();
  return 0;
}
Example #11
0
//----------------------------------------------------------------------------------------
ImageConverter::ImageConverter(const size_t& width/*=128*/, const size_t& height/*=128*/)
{
    mWidth = width;
    mHeight = height;

    mResourceManager = Ogre::ResourceGroupManager::getSingletonPtr();
    mResourceManager->createResourceGroup("QTImageConverter");
    mResourceManager->initialiseResourceGroup("QTImageConverter");
    
    mSceneMgrPtr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "QTImageConverterSceneManager");
    mSceneMgrPtr->setAmbientLight(Ogre::ColourValue(1, 1, 1));

    Ogre::TexturePtr rendertexture = Ogre::TextureManager::getSingleton().createManual("RenderTex", 
                   "QTImageConverter", Ogre::TEX_TYPE_2D, 
                   mWidth, mHeight, 1, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET);

    mRttTex = rendertexture->getBuffer()->getRenderTarget();

    // create our plane to set a texture to
    Ogre::Plane plane(Ogre::Vector3::UNIT_Z, 0);
    Ogre::MeshManager::getSingleton().createPlane("terrain", "QTImageConverter",
        plane, 100, 100, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Y);

    // attach the plane to the scene manager and rotate it so the camera can see it
    mEntityTerrain = mSceneMgrPtr->createEntity("terrainEntity", "terrain");
    Ogre::SceneNode* node = mSceneMgrPtr->getRootSceneNode()->createChildSceneNode();
    node->attachObject(mEntityTerrain);
    mEntityTerrain->setCastShadows(false);    
    
    Ogre::Camera* RTTCam = mSceneMgrPtr->createCamera("QTImageConverterCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0, 0, 50);
    RTTCam->lookAt(0, 0, 0);
    
    Ogre::Viewport *v = mRttTex->addViewport(RTTCam);
    v->setBackgroundColour(Ogre::ColourValue(1, 1, 1));
    v->setClearEveryFrame(true);
}
Example #12
0
GameCamera* CameraFactory::make(const rapidjson::Value& jsonobj){

  // Create the sphere
  Ogre::Camera* camera = game_manager->GetSceneManager()->createCamera(jsonobj["name"].GetString());

  SpaceObject*spaceobj=game_manager->getSpaceObject(jsonobj["attached_object"].GetString());

  // Set the node's position
  Eigen::Vector3f positionVec=spaceobj->position.cast<float>();
  camera->setPosition(Ogre::Vector3( static_cast<Ogre::Real*>(positionVec.data()) ));

  // Set the node's orientation
  Eigen::Quaterniond attitude=spaceobj->attitude;
  camera->setOrientation(Ogre::Quaternion(attitude.w(),attitude.x(),attitude.y(),attitude.z() ));

  camera->setNearClipDistance(jsonobj["near_clip"].GetDouble());
  camera->setFarClipDistance(jsonobj["far_clip"].GetDouble());

  GameCamera* gamecamera=new GameCamera(camera,spaceobj);

  return gamecamera;
}
Example #13
0
void
OgreCameraSystem::update(int) {
    for (EntityId entityId : m_impl->m_entities.removedEntities()) {
        Ogre::Camera* camera = m_impl->m_cameras[entityId];
        if (camera) {
            Ogre::SceneNode* sceneNode = camera->getParentSceneNode();
            sceneNode->detachObject(camera);
            m_impl->m_sceneManager->destroyCamera(camera);
        }
        m_impl->m_cameras.erase(entityId);
    }
    for (auto& value : m_impl->m_entities.addedEntities()) {
        EntityId entityId = value.first;
        OgreSceneNodeComponent* sceneNodeComponent = std::get<0>(value.second);
        OgreCameraComponent* cameraComponent = std::get<1>(value.second);
        Ogre::Camera* camera = m_impl->m_sceneManager->createCamera(
            cameraComponent->name()
        );
        camera->setAutoAspectRatio(true);
        cameraComponent->m_camera = camera;
        m_impl->m_cameras[entityId] = camera;
        sceneNodeComponent->m_sceneNode->attachObject(camera);
    }
    m_impl->m_entities.clearChanges();
    for (auto& value : m_impl->m_entities) {
        OgreCameraComponent* cameraComponent = std::get<1>(value.second);
        auto& properties = cameraComponent->m_properties;
        if (properties.hasChanges()) {
            Ogre::Camera* camera = cameraComponent->m_camera;
            // Update camera
            camera->setPolygonMode(properties.polygonMode);
            camera->setFOVy(properties.fovY);
            camera->setNearClipDistance(properties.nearClipDistance);
            camera->setFarClipDistance(properties.farClipDistance);
            // Untouch
            properties.untouch();
        }
    }
}
Example #14
0
    void Channel::frameDraw(const eq::uint128_t &frame_id)
    {
        // Setup OpenGL state (view frustum etc.)
        eq::Channel::frameDraw(frame_id);

        // Get data
        const Config *config = static_cast<Config *>(getConfig());
        const Node *node = static_cast<Node *>(getNode());
        const InitData &init_data = node->getInitData();
        const Pipe *pipe = static_cast<Pipe *>(getPipe());
        const FrameData &frame_data = pipe->getFrameData();
        Window *window = static_cast<Window *>(getWindow());        

        Ogre::Camera *cam = pipe->_ogre->getCamera();

        // Set the projection matrix
        const eq::Frustumf & frustum = getFrustum();

        cam->setCustomProjectionMatrix(true, toOgreMatrix(frustum.compute_matrix()));

        const eq::Matrix4f eqViewMatrix = getHeadTransform();
        // Adjust the view matrix according to equalizer's view matrix
        Ogre::Matrix4 ogreViewMatrix = toOgreMatrix(eqViewMatrix);
        cam->setCustomViewMatrix(true, ogreViewMatrix);
        cam->setNearClipDistance(frustum.near_plane());
        cam->setFarClipDistance(frustum.far_plane());

        // Set the viewport
        eq::PixelViewport winPvp = window->getPixelViewport();
        eq::PixelViewport pvp	 = getPixelViewport();
        window->setViewport((float)pvp.x/(float)winPvp.w,
                          1.0f - (float)(pvp.h + pvp.y)/(float)winPvp.h,
                          (float)pvp.w/(float)winPvp.w,
                          (float)pvp.h/(float)winPvp.h);

        // Render
        window->render();
    }
Example #15
0
void OgreApplication::InitViewport(void){

    try {

        /* Retrieve scene manager and root scene node */
        Ogre::SceneManager* scene_manager = ogre_root_->createSceneManager(Ogre::ST_GENERIC, "MySceneManager");
        Ogre::SceneNode* root_scene_node = scene_manager->getRootSceneNode();

        /* Create camera object */
        Ogre::Camera* camera = scene_manager->createCamera("MyCamera");
        Ogre::SceneNode* camera_scene_node = root_scene_node->createChildSceneNode("MyCameraNode");
        camera_scene_node->attachObject(camera);

		camera->setNearClipDistance(camera_near_clip_distance_g);
        camera->setFarClipDistance(camera_far_clip_distance_g); 

		camera->setPosition(camera_position_g);
		camera->lookAt(camera_look_at_g);
		camera->setFixedYawAxis(true, camera_up_g);

        /* Create viewport */
        Ogre::Viewport *viewport = ogre_window_->addViewport(camera, viewport_z_order_g, viewport_left_g, viewport_top_g, viewport_width_g, viewport_height_g);

        viewport->setAutoUpdated(true);
        viewport->setBackgroundColour(viewport_background_color_g);

		/* Set aspect ratio */
		float ratio = float(viewport->getActualWidth()) / float(viewport->getActualHeight());
        camera->setAspectRatio(ratio);
    }
    catch (Ogre::Exception &e){
        throw(OgreAppException(std::string("Ogre::Exception: ") + std::string(e.what())));
    }
    catch(std::exception &e){
        throw(OgreAppException(std::string("std::Exception: ") + std::string(e.what())));
    }
}
Example #16
0
void EC_OgreEnvironment::UpdateVisualEffects(f64 frametime)
{
    if (renderer_.expired())
        return;
    RendererPtr renderer = renderer_.lock();
    Ogre::Camera *camera = renderer->GetCurrentCamera();
    Ogre::Viewport *viewport = renderer->GetViewport();
    Ogre::SceneManager *sceneManager = renderer->GetSceneManager();
        
#ifdef CAELUM
    // Set sunlight attenuation using diffuse multiplier.
    // Seems to be working ok, but feel free to fix if you find better logic and/or values.
    Ogre::ColourValue diffuseMultiplier(sunColorMultiplier_, sunColorMultiplier_, sunColorMultiplier_, 1);
    caelumSystem_->getSun()->setDiffuseMultiplier(diffuseMultiplier);

    Ogre::Light* sun = caelumSystem_->getSun()->getMainLight();
    Ogre::Light* moon = caelumSystem_->getMoon()->getMainLight();

    float sunDirZaxis = caelumSystem_->getSun()->getMainLight()->getDirection().z;
    if (sunDirZaxis > 0)
    {
        sunColorMultiplier_ -= 0.005f;
        if (sunColorMultiplier_ <= 0.05f)
            sunColorMultiplier_ = 0.05f;
    }
    else if(sunDirZaxis < 0)
    {
        sunColorMultiplier_ += 0.010f;
        if (sunColorMultiplier_ >= MAX_SUNLIGHT_MULTIPLIER)
            sunColorMultiplier_ = MAX_SUNLIGHT_MULTIPLIER;
    }
    
    if ( !fog_color_override_)
        fogColor_ = caelumSystem_->getGroundFog()->getColour();
#endif

#ifdef CAELUM
    // Update Caelum system.
    caelumSystem_->notifyCameraChanged(camera);
    caelumSystem_->updateSubcomponents(frametime);

    // Disable specular from the sun & moon for now, because it easily leads to too strong results
    sun->setSpecularColour(0.0f, 0.0f, 0.0f);
    moon->setSpecularColour(0.0f, 0.0f, 0.0f);
#endif

#ifdef HYDRAX
    
    // Update Hydrax system.
    hydraxSystem_->update(frametime);
    sunPos = camera->getPosition();
    sunPos -= caelumSystem_->getSun()->getLightDirection() * 80000;
    hydraxSystem_->setSunPosition(sunPos);


#endif

    Ogre::Entity* water = 0;
    
    cameraFarClip_ = renderer->GetViewDistance();
    
    if ( sceneManager->hasEntity("WaterEntity") )
        water = sceneManager->getEntity("WaterEntity");
              
    if (!water)
    {
        // No water entity, set fog value.
        Real fogStart = fogStart_;
        Real fogEnd = fogEnd_;
        ClampFog(fogStart, fogEnd, cameraFarClip_);
        
        sceneManager->setFog(Ogre::FOG_LINEAR, fogColor_, 0.001, fogStart, fogEnd);
        viewport->setBackgroundColour(fogColor_);
        camera->setFarClipDistance(cameraFarClip_);
    }
    else 
    {
        if(camera->getDerivedPosition().z >= water->getParentNode()->getPosition().z)
        {        
            // We're above the water.
            Real fogStart = fogStart_;
            Real fogEnd = fogEnd_;
            ClampFog(fogStart, fogEnd, cameraFarClip_);
        
#ifdef CAELUM
            caelumSystem_->forceSubcomponentVisibilityFlags(caelumComponents_);
#endif
            sceneManager->setFog(Ogre::FOG_LINEAR, fogColor_, 0.001, fogStart, fogEnd);
            viewport->setBackgroundColour(fogColor_);
            camera->setFarClipDistance(cameraFarClip_);
            cameraUnderWater_ = false;
        }
        else
        {
            // We're below the water.
            Real fogStart = waterFogStart_;
            Real fogEnd = waterFogEnd_;
            Real farClip = waterFogEnd_ + 10.f;
            if (farClip > cameraFarClip_)
                farClip = cameraFarClip_;            
            ClampFog(fogStart, fogEnd, farClip);            
#ifdef CAELUM
            // Hide the Caelum subsystems.
            caelumSystem_->forceSubcomponentVisibilityFlags(Caelum::CaelumSystem::CAELUM_COMPONENTS_NONE);
#endif
            sceneManager->setFog(Ogre::FOG_LINEAR, fogColor_ * waterFogColor_, 0.001, fogStart, fogEnd);
            viewport->setBackgroundColour(fogColor_ * waterFogColor_);
            camera->setFarClipDistance(farClip);
            cameraUnderWater_ = true;
        }
    }

#ifdef CAELUM 
    // If sun color and direction are controlled by user then their value are needed to override here. 
    // internally caelum calculates new values for those so they are needed to set again in each update loop.

    if ( override_flags_.testFlag(None) )
        return;

    if ( override_flags_.testFlag(AmbientLight))
    {   
        // Override ambient light.
        sceneManager->setAmbientLight(userAmbientLight_);
    }

    if ( override_flags_.testFlag(SunDirection) )
    {
        // Override sun direction.
        if ( sun != 0 )
            sun->setDirection(userSunDirection_);
    }

    if ( override_flags_.testFlag(SunColor) )
    {
        // Override sun color. 
        if ( sun != 0 )
            sun->setDiffuseColour(userSunColor_);
    }
#endif 

}
Example #17
0
int initOgreAR(aruco::CameraParameters camParams, unsigned char* buffer, std::string resourcePath)
{
	/// INIT OGRE FUNCTIONS
#ifdef _WIN32
  	root = new Ogre::Root(resourcePath + "plugins_win.cfg", resourcePath + "ogre_win.cfg");
#elif __x86_64__ || __ppc64__
	root = new Ogre::Root(resourcePath + "plugins_x64.cfg", resourcePath + "ogre.cfg");
#else
	root = new Ogre::Root(resourcePath + "plugins.cfg", resourcePath + "ogre.cfg");
#endif
  	if (!root->showConfigDialog()) return -1;
	Ogre::SceneManager* smgr = root->createSceneManager(Ogre::ST_GENERIC);


	/// CREATE WINDOW, CAMERA AND VIEWPORT
    Ogre::RenderWindow* window = root->initialise(true);
	Ogre::Camera *camera;
	Ogre::SceneNode* cameraNode;
	camera = smgr->createCamera("camera");
	camera->setNearClipDistance(0.01f);
	camera->setFarClipDistance(10.0f);
	camera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
	camera->setPosition(0, 0, 0);
	camera->lookAt(0, 0, 1);
	double pMatrix[16];
	camParams.OgreGetProjectionMatrix(camParams.CamSize,camParams.CamSize, pMatrix, 0.05,10, false);
	Ogre::Matrix4 PM(pMatrix[0], pMatrix[1], pMatrix[2] , pMatrix[3],
			pMatrix[4], pMatrix[5], pMatrix[6] , pMatrix[7],
			pMatrix[8], pMatrix[9], pMatrix[10], pMatrix[11],
			pMatrix[12], pMatrix[13], pMatrix[14], pMatrix[15]);
	camera->setCustomProjectionMatrix(true, PM);
	camera->setCustomViewMatrix(true, Ogre::Matrix4::IDENTITY);
	window->addViewport(camera);
	cameraNode = smgr->getRootSceneNode()->createChildSceneNode("cameraNode");
	cameraNode->attachObject(camera);


	/// CREATE BACKGROUND FROM CAMERA IMAGE
	int width = camParams.CamSize.width;
	int height = camParams.CamSize.height;
	// create background camera image
	mPixelBox = Ogre::PixelBox(width, height, 1, Ogre::PF_R8G8B8, buffer);
	// Create Texture
	mTexture = Ogre::TextureManager::getSingleton().createManual("CameraTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		      Ogre::TEX_TYPE_2D,width,height,0,Ogre::PF_R8G8B8,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

	//Create Camera Material
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("CameraMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique *technique = material->createTechnique();
	technique->createPass();
	material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
	material->getTechnique(0)->getPass(0)->createTextureUnitState("CameraTexture");

	Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
	rect->setCorners(-1.0, 1.0, 1.0, -1.0);
	rect->setMaterial("CameraMaterial");

	// Render the background before everything else
	rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);

	// Hacky, but we need to set the bounding box to something big, use infinite AAB to always stay visible
	Ogre::AxisAlignedBox aabInf;
	aabInf.setInfinite();
	rect->setBoundingBox(aabInf);

	// Attach background to the scene
	Ogre::SceneNode* node = smgr->getRootSceneNode()->createChildSceneNode("Background");
	node->attachObject(rect);


	/// CREATE SIMPLE OGRE SCENE
	// add sinbad.mesh
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(resourcePath + "Sinbad.zip", "Zip", "Popular");
 	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	for(int i=0; i<MAX_MARKERS; i++) {
	  Ogre::String entityName = "Marker_" + Ogre::StringConverter::toString(i);
	  Ogre::Entity* ogreEntity = smgr->createEntity(entityName, "Sinbad.mesh");
	  Ogre::Real offset = ogreEntity->getBoundingBox().getHalfSize().y;
	  ogreNode[i] = smgr->getRootSceneNode()->createChildSceneNode();
	  // add entity to a child node to correct position (this way, entity axis is on feet of sinbad)
	  Ogre::SceneNode *ogreNodeChild = ogreNode[i]->createChildSceneNode();
	  ogreNodeChild->attachObject(ogreEntity);
	  // Sinbad is placed along Y axis, we need to rotate to put it along Z axis so it stands up over the marker
	  // first rotate along X axis, then add offset in Z dir so it is over the marker and not in the middle of it
	  ogreNodeChild->rotate(Ogre::Vector3(1,0,0), Ogre::Radian(Ogre::Degree(90)));
	  ogreNodeChild->translate(0,0,offset,Ogre::Node::TS_PARENT);
	  // mesh is too big, rescale!
	  const float scale = 0.006675f;
	  ogreNode[i]->setScale(scale, scale, scale);

	    // Init animation
	  ogreEntity->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
	  if(i==0)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("HandsClosed");
        topAnim[i] = ogreEntity->getAnimationState("HandsRelaxed");
	  }
	  else if(i==1)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("Dance");
        topAnim[i] = ogreEntity->getAnimationState("Dance");
	  }
	  else if(i==2)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("RunBase");
        topAnim[i] = ogreEntity->getAnimationState("RunTop");
	  }
	  else
	  {
        baseAnim[i] = ogreEntity->getAnimationState("IdleBase");
        topAnim[i] = ogreEntity->getAnimationState("IdleTop");
	  }
	  baseAnim[i]->setLoop(true);
	  topAnim[i]->setLoop(true);
	  baseAnim[i]->setEnabled(true);
	  topAnim[i]->setEnabled(true);
	}


 	/// KEYBOARD INPUT READING
 	size_t windowHnd = 0;
 	window->getCustomAttribute("WINDOW", &windowHnd);
 	im = OIS::InputManager::createInputSystem(windowHnd);
 	keyboard = static_cast<OIS::Keyboard*>(im->createInputObject(OIS::OISKeyboard, true));

	return 1;
}
Example #18
0
bool Game::initializeOgre() {
	try {
		// setup ogre initialization filenames, setting config and plugins filenames to blank disables these features
		Ogre::String configFileName = "";
		Ogre::String pluginsFileName = "";
		Ogre::String logFileName = "Ogre.log";

		// create the root ogre object
		m_pRoot = new Ogre::Root(configFileName, pluginsFileName, logFileName);

		// load the necessary plugins
		std::vector<Ogre::String> pluginNames;
		pluginNames.push_back("/RenderSystem_GL");
		pluginNames.push_back("/Plugin_ParticleFX");
		//pluginNames.push_back("Plugin_CgProgramManager");
		//pluginNames.push_back("Plugin_PCZSceneManager");
		//pluginNames.push_back("Plugin_OctreeZone");
		pluginNames.push_back("/Plugin_OctreeSceneManager");
		//pluginNames.push_back("Plugin_BSPSceneManager");

		for( std::vector<Ogre::String>::iterator itr = pluginNames.begin(); itr != pluginNames.end(); itr++ ) {
			Ogre::String& pluginName = (*itr);
			if( OGRE_DEBUG_MODE ) {
				pluginName.append("_d");
			}
			m_pRoot->loadPlugin(OGRE_PLUGINDIR + pluginName);
		}

		// select the rendersystem from the loaded plugins
		const Ogre::RenderSystemList& renderSystemList = m_pRoot->getAvailableRenderers();
		if( renderSystemList.size() == 0 ) {
			std::cout << "Sorry, no rendersystem was found." << std::endl;
			throw(3);
		}

		Ogre::RenderSystem *renderSystem = renderSystemList[0];
		m_pRoot->setRenderSystem(renderSystem);

		// initialize the root but do not automatically create a window
		bool createAWindowAutomatically = false;
		Ogre::String windowTitle = "";
		Ogre::String customCapacities = "";
		m_pRoot->initialise(createAWindowAutomatically, windowTitle, customCapacities);

		// create a window
		// This is just an example of parameters that we can put. Check the API for more details.
		Ogre::NameValuePairList params;
		// fullscreen antialiasing.
		params["FSAA"] = "0";
		// vertical synchronisation
		params["vsync"] = "true";

		//save the window dimensions to help track mouse usage
		m_WindowWidth = 1024;
		m_WindowHeight = 768;
		m_Fullscreen = false;
		m_pWindow = m_pRoot->createRenderWindow("Doughnut", m_WindowWidth, m_WindowHeight, m_Fullscreen, &params);

		// cleaning of windows events managed by Ogre::WindowEventUtilities
		m_pRoot->clearEventTimes();

		// create the scene manager
		m_pScene = m_pRoot->createSceneManager(Ogre::ST_GENERIC,"TestScene");

		//grab the root node for future use
		m_pRootSceneNode = m_pScene->getRootSceneNode();

		// create the camera
		Ogre::Camera* pCamera = m_pScene->createCamera("MainCamera");

		// attach the camera to a new SceneNode
		m_pCameraNode = m_pRootSceneNode->createChildSceneNode("MainCameraNode",Ogre::Vector3(0.0f, 0.0f, 10.0f));
		m_pCameraNode->attachObject(pCamera);

		// create a viewport
		Ogre::Viewport* vp = m_pWindow->addViewport(pCamera, 100, 0.0f, 0.0f, 1.0f, 1.0f);
		vp->setAutoUpdated(true);
		vp->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f, 0.0f));
		m_pWindow->setActive(true);

		// choose the visual ratio of the camera based on the viewport
		float ratio = float(vp->getActualWidth()) / float(vp->getActualHeight());
		pCamera->setAspectRatio(ratio);

		// choose the clipping far & near planes, if far/near>2000, you can get z buffer problem
		pCamera->setNearClipDistance(1.5f);
		pCamera->setFarClipDistance(3000.0f);

		Ogre::String RGs[8] = {"schemes", "imagesets", "fonts", "layouts", "looknfeel", "lua_scripts", "meshes", "materials"};
		Ogre::ResourceGroupManager& lRgMgr = Ogre::ResourceGroupManager::getSingleton();
		for( int i = 0; i < 8; i++ ) {
			lRgMgr.createResourceGroup(RGs[i]);
			lRgMgr.addResourceLocation("datafiles/"+RGs[i], "FileSystem", RGs[i], false);
			lRgMgr.initialiseResourceGroup(RGs[i]);
		}

		m_pRoot->addFrameListener(this);

		Ogre::Light* light = m_pScene->createLight();
		light->setType(Ogre::Light::LT_DIRECTIONAL);
		light->setDiffuseColour(0.8f, 0.8f, 0.8f);
		light->setSpecularColour(1.0f, 1.0f, 1.0f);
		light->setDirection(Ogre::Vector3(0, 0, -1));
		Ogre::SceneNode* lightnode = m_pRootSceneNode->createChildSceneNode();
		lightnode->attachObject(light);
		m_pScene->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
	} catch(Ogre::Exception &e) {
		std::cout << "!!!!Ogre::Exception!!!!" << e.what() << std::endl;
	}

	return true;
}//Game:initializeOgre
void ZoneListWidget::_createImages(ImageMap& retlist)
{
    retlist.clear();

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "EntityTex",
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
                   256, 256, 0, Ogre::PF_A8R8G8B8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "EntityTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("EntityCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0,0));

    ModularZoneFactory* factory = dynamic_cast<ModularZoneFactory*>(OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory("Modular Zone Object"));
    if(!factory)return;
    factory->loadZoneTemplates();
    ZoneInfoMap zoneTemplates = factory->getZoneTemplateMap();

    Ogre::Entity *mEntity;

    unsigned char dataptr[300 * 300 * 6];
    unsigned char *dataptr2;
    Ogre::PixelBox pb(256,256,1,Ogre::PF_A8R8G8B8, dataptr);

    EntityMap entities;
    ZoneInfoMap::iterator zi;
    for(zi=zoneTemplates.begin();zi!=zoneTemplates.end();++zi)
    {
        Ogre::String addstr = (*zi).second.mMesh;
        if(entities.find((*zi).first) == entities.end())
            entities.insert(EntityMap::value_type((*zi).first,addstr));
    }

    EntityMap::const_iterator ite = entities.begin();

    while(ite != entities.end())
    {
        Ogre::String addstr = ite->second;

        mEntity = mSceneMgr->createEntity("MZP_Preview", addstr);

        mSceneMgr->getRootSceneNode()->attachObject(mEntity);

        //TODO: It would be nice to retrieve a Preview Camera Position from
        //the .zone file
        //TODO: also render portal outlines clearly so that the user can see
        //how the zone is laid out
        Ogre::Vector3 vSize = mEntity->getBoundingBox().getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_TOP);//.getHalfSize();//============
        Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter();

//FIXME ------ NICE PREVIEWS NEEDED - bigger

        vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

        float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);

        //vSize = Ogre::Vector3(0, 0, maxsize * 1.1f) + vCenter;
        vSize = Ogre::Vector3(maxsize * 0.5f, vSize.y, maxsize * 0.5f) + vCenter;
        //vSize.x +=vSize.x/2;//Maybe test to see which is larger x/2 or z/2 and use that?
        //vSize.z +=vSize.x/2;
        //RTTCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

        RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
        RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

        rttTex->update();
        rttTex->copyContentsToMemory(pb, Ogre::RenderTarget::FB_FRONT);


        dataptr2 = new unsigned char[96 * 96 * 4];
        Ogre::PixelBox pb2(96,96,1,Ogre::PF_A8R8G8B8, dataptr2);
        Ogre::Image::scale(pb,pb2);

        addstr.erase(addstr.length() - 5, 5);
        retlist.insert(ImageMap::value_type((*ite).first, dataptr2));

        mEntity->detachFromParent();
        mSceneMgr->destroyEntity(mEntity);

        ite++;
    }

    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    Ogre::TextureManager::getSingletonPtr()->unload(texture->getName());
    Ogre::TextureManager::getSingletonPtr()->remove(texture->getName());
}
Example #20
0
//!
//! Clones an Ogre::MovableObject.
//!
//! Is needed because OGRE does not provide clone functions for cameras and
//! lights.
//!
//! \param movableObject The object to clone.
//! \param name The name to use for the object.
//! \param sceneManager The scene manager to use for creating the object.
//! \return The cloned object.
//!
Ogre::MovableObject * OgreTools::cloneMovableObject ( Ogre::MovableObject *movableObject, const QString &name, Ogre::SceneManager *sceneManager /* =  0 */ )
{
    // make sure the given object is valid
    if (!movableObject) {
        Log::error("The given movable object is invalid.", "OgreTools::cloneMovableObject");
        return 0;
    }

    // make sure a valid scene manager is available
    if (!sceneManager)
        sceneManager = movableObject->_getManager();
    if (!sceneManager) {
        Log::error("No valid scene manager available.", "OgreTools::cloneMovableObject");
        return 0;
    }

    Ogre::MovableObject *result = 0;
    Ogre::String typeName = movableObject->getMovableType();
    if (typeName == "Entity") {
        // clone entity
        Ogre::Entity *entity = dynamic_cast<Ogre::Entity *>(movableObject);
        //movableObjectCopy = entity->clone(name.toStdString());
        Ogre::Entity *entityCopy = sceneManager->createEntity(name.toStdString(), entity->getMesh()->getName());
        Ogre::AnimationStateSet *animationStateSet = entity->getAllAnimationStates();
        Ogre::AnimationStateSet *animationStateSetCopy  = entityCopy->getAllAnimationStates();
        // set the same blend mode on entity copy
        if (entity && entityCopy) {
            if (entity->hasSkeleton() && entityCopy->hasSkeleton()) {
                Ogre::Skeleton *skeleton = entity->getSkeleton();
                Ogre::Skeleton *skeletonCopy = entityCopy->getSkeleton();
                skeletonCopy->setBlendMode(skeleton->getBlendMode());
            }
        }
        // copy all animation states
        if (animationStateSet && animationStateSetCopy) {
            Ogre::AnimationStateIterator animationStateIter = animationStateSet->getAnimationStateIterator();
            Ogre::AnimationStateIterator animationStateCopyIter = animationStateSetCopy->getAnimationStateIterator();
            while (animationStateIter.hasMoreElements()) {
                if (!animationStateCopyIter.hasMoreElements())
                    break;
                Ogre::AnimationState *animationState = animationStateIter.getNext();
                Ogre::AnimationState *animationStateCopy = animationStateCopyIter.getNext();
                animationStateCopy->setLoop(animationState->getLoop());
                //bool enabled = animationState->getEnabled();
                //animationStateCopy->setEnabled(animationState->getEnabled());
                animationStateCopy->setEnabled(true);
                animationStateCopy->setTimePosition(animationState->getTimePosition());
            }
        }

        // create a new container for the cloned entity
        OgreContainer *entityCopyContainer = new OgreContainer(entityCopy);
        entityCopy->setUserAny(Ogre::Any(entityCopyContainer));
        if (!entity->getUserAny().isEmpty()) {
            OgreContainer *entityContainer = Ogre::any_cast<OgreContainer *>(entity->getUserAny());
			if (entityContainer) {
                QObject::connect(entityContainer, SIGNAL(animationStateUpdated(const QString &, double)), entityCopyContainer, SLOT(updateAnimationState(const QString &, double)));
				QObject::connect(entityContainer, SIGNAL(boneTransformUpdated(const QString &, double, double, double, double, double, double)), entityCopyContainer, SLOT(updateBoneTransform(const QString &, double, double, double, double, double, double)));
			}
        }
        result = dynamic_cast<Ogre::MovableObject *>(entityCopy);
    } else if (typeName == "Light") {
        // clone light
        Ogre::Light *light = dynamic_cast<Ogre::Light *>(movableObject);
        Ogre::Light *lightCopy = sceneManager->createLight(name.toStdString());
        lightCopy->setType(light->getType());
        lightCopy->setDiffuseColour(light->getDiffuseColour());
        lightCopy->setSpecularColour(light->getSpecularColour());
        lightCopy->setAttenuation(light->getAttenuationRange(), light->getAttenuationConstant(), light->getAttenuationLinear(), light->getAttenuationQuadric());
        lightCopy->setPosition(light->getPosition());
        lightCopy->setDirection(light->getDirection());
        if (lightCopy->getType() == Ogre::Light::LT_SPOTLIGHT)
            lightCopy->setSpotlightRange(light->getSpotlightInnerAngle(), light->getSpotlightOuterAngle(), light->getSpotlightFalloff());
        lightCopy->setPowerScale(light->getPowerScale());
        lightCopy->setCastShadows(light->getCastShadows());

        // create a new container for the cloned light
        OgreContainer *lightCopyContainer = new OgreContainer(lightCopy);
        lightCopy->setUserAny(Ogre::Any(lightCopyContainer));
        if (!light->getUserAny().isEmpty()) {
            OgreContainer *lightContainer = Ogre::any_cast<OgreContainer *>(light->getUserAny());
            if (lightContainer)
                QObject::connect(lightContainer, SIGNAL(sceneNodeUpdated()), lightCopyContainer, SLOT(updateLight()));
        }
        result = dynamic_cast<Ogre::MovableObject *>(lightCopy);
    } else if (typeName == "Camera") {
        // clone camera
        Ogre::Camera *camera = dynamic_cast<Ogre::Camera *>(movableObject);
        Ogre::Camera *cameraCopy = sceneManager->createCamera(name.toStdString());
        //cameraCopy->setCustomParameter(0, camera->getCustomParameter(0));
        cameraCopy->setAspectRatio(camera->getAspectRatio());
        cameraCopy->setAutoAspectRatio(camera->getAutoAspectRatio());
        //cameraCopy->setAutoTracking(...);
        cameraCopy->setCastShadows(camera->getCastsShadows());
        //cameraCopy->setCullingFrustum(camera->getCullingFrustum());
        //cameraCopy->setCustomParameter(...);
        //cameraCopy->setCustomProjectionMatrix(..);
        //cameraCopy->setCustomViewMatrix(..);
        //cameraCopy->setDebugDisplayEnabled(...);
        //cameraCopy->setDefaultQueryFlags(...);
        //cameraCopy->setDefaultVisibilityFlags(...);
        cameraCopy->setDirection(camera->getDirection());
        //cameraCopy->setFixedYawAxis(...);
        cameraCopy->setFocalLength(camera->getFocalLength());
        cameraCopy->setFOVy(camera->getFOVy());

        //Ogre::Real left;
        //Ogre::Real right;
        //Ogre::Real top;
        //Ogre::Real bottom;
        //camera->getFrustumExtents(left, right, top, bottom);
        //cameraCopy->setFrustumExtents(left, right, top, bottom);
        //cameraCopy->setFrustumOffset(camera->getFrustumOffset());
        //cameraCopy->setListener(camera->getListener());
        cameraCopy->setLodBias(camera->getLodBias());
        //cameraCopy->setLodCamera(camera->getLodCamera());
        cameraCopy->setNearClipDistance(camera->getNearClipDistance());
        cameraCopy->setFarClipDistance(camera->getFarClipDistance());
        cameraCopy->setOrientation(camera->getOrientation());
        //cameraCopy->setOrthoWindow(...);
        //cameraCopy->setOrthoWindowHeight(...);
        //cameraCopy->setOrthoWindowWidth(...);
        cameraCopy->setPolygonMode(camera->getPolygonMode());
        cameraCopy->setPolygonModeOverrideable(camera->getPolygonModeOverrideable());
        cameraCopy->setPosition(camera->getPosition());
        cameraCopy->setProjectionType(camera->getProjectionType());
        cameraCopy->setQueryFlags(camera->getQueryFlags());
        cameraCopy->setRenderingDistance(camera->getRenderingDistance());
        cameraCopy->setRenderQueueGroup(camera->getRenderQueueGroup());
        //cameraCopy->setRenderSystemData(camera->getRenderSystemData());
        cameraCopy->setUseIdentityProjection(camera->getUseIdentityProjection());
        cameraCopy->setUseIdentityView(camera->getUseIdentityView());
        //cameraCopy->setUserAny(camera->getUserAny());
        cameraCopy->setUseRenderingDistance(camera->getUseRenderingDistance());
        //cameraCopy->setUserObject(camera->getUserObject());
        cameraCopy->setVisibilityFlags(camera->getVisibilityFlags());
        cameraCopy->setVisible(camera->getVisible());
        //cameraCopy->setWindow(...);

        if (!movableObject->getUserAny().isEmpty()) {
            CameraInfo *sourceCameraInfo = Ogre::any_cast<CameraInfo *>(movableObject->getUserAny());
            if (sourceCameraInfo) {
                CameraInfo *targetCameraInfo = new CameraInfo();
                targetCameraInfo->width = sourceCameraInfo->width;
                targetCameraInfo->height = sourceCameraInfo->height;
                dynamic_cast<Ogre::MovableObject *>(cameraCopy)->setUserAny(Ogre::Any(targetCameraInfo));
            }
        }

        //// Setup connections for instances
        //SceneNode *targetSceneNode = new SceneNode(cameraCopy);
        //((Ogre::MovableObject *)cameraCopy)->setUserAny(Ogre::Any(targetSceneNode));
        //if (!((Ogre::MovableObject *)camera)->getUserAny().isEmpty()) {
        //    SceneNode *sourceSceneNode = Ogre::any_cast<SceneNode *>(((Ogre::MovableObject *)camera)->getUserAny());
        //    if (sourceSceneNode) {
        //        QObject::connect(sourceSceneNode, SIGNAL(sceneNodeUpdated()), targetSceneNode, SLOT(updateSceneNode()));
        //    }
        //}

        result = dynamic_cast<Ogre::MovableObject *>(cameraCopy);
    }

    if (!result)
        Log::error(QString("Could not clone movable object \"%1\" of type \"%2\".").arg(movableObject->getName().c_str()).arg(typeName.c_str()), "OgreTools::cloneMovableObject");

    return result;
}
Camera::Camera(Event::Lane& lane,
               GameHandle cameraHandle, 
               Ogre::SceneNode* camNode, 
               Ogre::RenderTarget* renderTarget, 
               u32 width, 
               u32 height,
               const v3& position,
               const qv4& orientation,
               GameHandle parent) :
mSubLane(lane.createSubLane()),
mCameraNode(camNode),
mRenderTarget(renderTarget),
mHandle(cameraHandle),
mNodeCreated(false),
mRenderTargetCreated(false)
{
	Ogre::SceneManager* sceneMgr = Ogre::Root::getSingleton().getSceneManager(BFG_SCENEMANAGER);
	if (mCameraNode == NULL) // Create SceneNode
	{
		if (sceneMgr->hasSceneNode(stringify(mHandle)))
		{
			mCameraNode = sceneMgr->getSceneNode(stringify(mHandle));
		}
		else
		{
			mCameraNode = sceneMgr->getRootSceneNode()->createChildSceneNode(stringify(mHandle));
			mNodeCreated = true;
		}
	}
	mCameraNode->setOrientation(toOgre(orientation));
	mCameraNode->setPosition(toOgre(position));

	v3 target = toBFG(mCameraNode->getOrientation().zAxis());
	norm(target);

	Ogre::Camera* cam;
	cam = sceneMgr->createCamera(stringify(mHandle));

	cam->setFOVy(Ogre::Degree(60.0f));
	cam->setNearClipDistance(0.1f);
	cam->setFarClipDistance(250000.0f);
	cam->lookAt(toOgre(target)*10);
	mCameraNode->attachObject(cam);

	infolog << "Camera: " << stringify(mHandle) << " created.";

	if (mRenderTarget == NULL)
	{
		// Create renderToTexture RenderTarget

		if (width == 0 || height == 0)
		{
			throw std::logic_error("Too few information to create a render target.");
		}

		cam->setAspectRatio((f32)width / (f32)height);

		Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual
		(
			stringify(mHandle),
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			Ogre::TEX_TYPE_2D,
			width,
			height,
			0,
			Ogre::PF_R8G8B8,
			Ogre::TU_RENDERTARGET
		);

		mRenderTarget = texture->getBuffer()->getRenderTarget();

		prepareRenderTarget();

		mRenderTarget->addViewport(cam);

		mRenderTarget->getViewport(0)->setClearEveryFrame(true);
		mRenderTarget->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
		mRenderTarget->getViewport(0)->setOverlaysEnabled(false);

		Ogre::MaterialPtr mat =
			Ogre::MaterialManager::getSingleton().getByName(stringify(mHandle));
		if (mat.isNull())
		{
			mat = Ogre::MaterialManager::getSingleton().create(
			    stringify(mHandle), 
			    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		}
		Ogre::Technique* tech = mat->getTechnique(0);
		if (!tech)
		{
			tech = mat->createTechnique();
		}
		Ogre::Pass* pass = tech->getPass(0);
		if (!pass)
		{
			pass = tech->createPass();
		}
		pass->setLightingEnabled(false);

		if (pass->getNumTextureUnitStates() > 0)
		{
			Ogre::TextureUnitState* txState = NULL;
			txState = pass->getTextureUnitState(0);
			txState->setTextureName(stringify(mHandle));
		}
		else
		{
			pass->createTextureUnitState(stringify(mHandle));
		}

		mRenderTarget->setAutoUpdated(true);

		mRenderTargetCreated = true;

		infolog << "Rendertarget: " << stringify(mHandle) << " created.";
	}
	else
	{
		prepareRenderTarget();
		f32 width = static_cast<f32>(mRenderTarget->getWidth());
		f32 height = static_cast<f32>(mRenderTarget->getHeight());
		cam->setAspectRatio(width / height);
		mRenderTarget->addViewport(cam);
	}
	
// 	mSubLane->connect(ID::VE_UPDATE_POSITION, this, &Camera::updatePosition, mHandle);
// 	mSubLane->connect(ID::VE_UPDATE_ORIENTATION, this, &Camera::updateOrientation, mHandle);
	mSubLane->connect(ID::VE_SET_CAMERA_TARGET, this, &Camera::onSetTarget, mHandle);

	if (parent != NULL_HANDLE)
	{
		onSetTarget(parent);
	}
}
void CameraApp::createScene()
{
    /***************************************************************************/
    /* This create a scene with a textured plane and a penguin.  The camera    */
    /* is placed directly behind the penguin.  Both the camera and the penguin */
    /* are attached to the same scene node.  As a result, when the node is     */
    /* moved or rotated, the camera and the penguin move or rotate exactly the */
    /* same.  This gives you a first person camera that is always looking over */
    /* the shoulder of your character.                                         */
    /***************************************************************************/
    sceneMgr->setAmbientLight( Ogre::ColourValue( 1, 1, 1 ) );
    Ogre::Light *l = sceneMgr->createLight("MainLight");

    Ogre::Camera *camera = sceneMgr->createCamera("MainCam");
    camNode = sceneMgr->getRootSceneNode()->createChildSceneNode( "CameraNode" );
    camNode->attachObject(camera);
    camera->setPosition(0.0, 0.0, 0.0);

    int originX = -15;
    int distancebetween = 10;

    for (int i = 0; i < 4; i++)
    {
        Ogre::Entity *sinbadEntity = sceneMgr->createEntity("Sinbad" + i, "Sinbad.mesh");
        Ogre::SceneNode *sinbadNode = sceneMgr->getRootSceneNode()->createChildSceneNode("SinbadNode" + i);
        sinbadNode->attachObject(sinbadEntity);
        sinbadNode->setScale(1,1,1);
        sinbadNode->translate(originX + (distancebetween * i), 0, -40);
        switch (i)
        {
        case 1:
            sinbadNode->yaw(Ogre::Degree(90.0f));
            break;
        case 2:
            sinbadNode->pitch(Ogre::Degree(90.0f));

            break;
        case 3:
            sinbadNode->roll(Ogre::Degree(90.0f));
            break;
        }
    }

    Ogre::Entity *sinbadEntity = sceneMgr->createEntity("SinbadScaled", "Sinbad.mesh");
    Ogre::SceneNode *sinbadNode = sceneMgr->getRootSceneNode()->createChildSceneNode("SinbadScaledNode");
    sinbadNode->attachObject(sinbadEntity);
    sinbadNode->setScale(5,5,5);
    //sinbadNode->rotate(Ogre::Vector3(1,0,0), Ogre::Degree(90));
    //sinbadNode->rotate(Ogre::Vector3(0,0,1), Ogre::Degree(-90));
    sinbadNode->translate(0, 0, -60);



    Ogre::Viewport *vp = window->addViewport(camera);
    vp->setDimensions(0.0f, 0.0f, 1.0f, 1.0f);
    camera->setAspectRatio((float)vp->getActualWidth() / (float) vp->getActualHeight());
    camera->setFarClipDistance(1000.0f);
    camera->setNearClipDistance(5.0f);
    camera->lookAt(0,0,-10);
    setActiveCamera(camera);

    /*Ogre::Plane plane(Ogre::Vector3::UNIT_Y, -10);
    Ogre::MeshManager::getSingleton().createPlane("plane",
    	ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane,
    	1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);
    Ogre::Entity *planeEntity = sceneMgr->createEntity("PlaneEntity", "plane");
    sceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(planeEntity);
    planeEntity->setMaterialName("Examples/BeachStones");*/



}
Example #23
0
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();
}
		void SetUpCustomContent()
		{
			Ogre::String CustomCameraName = "TestRenderTargetCamera";
			Ogre::String CustomTextureName = "TestRenderTargetTexture";
			Ogre::String CustomMaterialName = "CustomRenderTargetMaterial";
			Ogre::String CustomWorkSpaceName = "TestCustomRenderTargetWorkSpaceName";

			m_CustomRTTCamera = mSceneManager->createCamera(CustomCameraName);
			m_CustomRTTCamera->setPosition(0, 30, 0);
			m_CustomRTTCamera->lookAt(0, 0, 0);
			m_CustomRTTCamera->setFarClipDistance(1000);
			m_CustomRTTCamera->setNearClipDistance(0.1);

			m_CustomRenderTexture = Ogre::TextureManager::getSingleton().createManual(CustomTextureName, 
				Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 
				512, 512, 1, Ogre::PF_A8B8G8R8, Ogre::TU_RENDERTARGET);
			m_CustomRenderTexture->load();

			Ogre::RenderTexture* rtt = m_CustomRenderTexture->getBuffer(0)->getRenderTarget();


			Ogre::CompositorManager2 *compositorManager = mRoot->getCompositorManager2();

			const Ogre::IdString workspaceName(CustomWorkSpaceName);
			if( !compositorManager->hasWorkspaceDefinition( workspaceName ) )
			{
				compositorManager->createBasicWorkspaceDef( workspaceName, mBackgroundColour,
					Ogre::IdString() );
			}

			m_CustomRenderTarget = compositorManager->addWorkspace( mSceneManager, (Ogre::RenderTarget*)rtt, m_CustomRTTCamera,
					workspaceName, false );
			//m_CustomRenderTarget->setEnabled(false);			// not auto update
#if 0
			// create manual object
			Ogre::MaterialPtr CustomMaterial = Ogre::MaterialManager::getSingleton().create(CustomMaterialName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
			CustomMaterial->getTechnique(0)->removeAllPasses();
			Ogre::Pass* pass = CustomMaterial->getTechnique(0)->createPass();
			Ogre::TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(CustomTextureName);
#endif
			Ogre::HlmsManager *hlmsManager = Ogre::Root::getSingleton().getHlmsManager();
			Ogre::Hlms *hlms = hlmsManager->getHlms( Ogre::HLMS_UNLIT );
			Ogre::HlmsDatablock *datablock = hlms->createDatablock( CustomMaterialName, CustomMaterialName,
				Ogre::HlmsMacroblock(), Ogre::HlmsBlendblock(), Ogre::HlmsParamVec() );
			Ogre::HlmsUnlitDatablock *unlitDb = static_cast<Ogre::HlmsUnlitDatablock*>( datablock );
			unlitDb->setTexture( 0, 0, m_CustomRenderTexture );
			
#if 1
			Ogre::ManualObject* CustomManualObject = mSceneManager->createManualObject();
			CustomManualObject->begin(CustomMaterialName);
			CustomManualObject->position(-100, -100, -100);
			CustomManualObject->textureCoord(0, 0);
			CustomManualObject->position(100, -100, -100);
			CustomManualObject->textureCoord(1, 0);
			CustomManualObject->position(100, 100, -100);
			CustomManualObject->textureCoord(1, 1);
			CustomManualObject->position(-100, 100, -100);
			CustomManualObject->textureCoord(0, 1);
			CustomManualObject->quad(0, 1, 2, 3);
			CustomManualObject->end();
//			CustomManualObject->setDatablock(0, CustomMaterialName);

			Ogre::SceneNode *sceneNodeLines = mSceneManager->getRootSceneNode( Ogre::SCENE_DYNAMIC )->
				createChildSceneNode( Ogre::SCENE_DYNAMIC );
			sceneNodeLines->attachObject(CustomManualObject);
			sceneNodeLines->scale(0.4f, 0.4f, 0.4f);
			sceneNodeLines->translate(0.0f, 0.0f, 0.0f, Ogre::SceneNode::TS_WORLD);
#endif
		}
Example #25
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);
}
Example #26
0
void camera_set_far_clip_distance(CoiHandle camera_handle, float d)
{
    Ogre::Camera* camera = reinterpret_cast<Ogre::Camera*>(camera_handle);
    camera->setFarClipDistance( d );
}
Example #27
0
    bool initialise()
    {
		mRoot = new Ogre::Root(PLUGINS_CFG, OGRE_CFG, OGRE_LOG);

		if (!mRoot->restoreConfig())
			if (!mRoot->showConfigDialog())
				return false;

		initResources();

        mWindow = mRoot->initialise(true, "CS Clone Editor v0.0");
        Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

		mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
		mSceneMgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7));
		mCamera = mSceneMgr->createCamera("camera");
        mWindow->addViewport(mCamera);
        mCamera->setAutoAspectRatio(true);
        mCamera->setNearClipDistance(0.1);
        mCamera->setFarClipDistance(10000);
        mCamera->setPosition(10, 10, 10);
//        mCamera->lookAt(0, 0, 0);

        mRoot->addFrameListener(this);

		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
//Initializing OIS
		Ogre::LogManager::getSingletonPtr()->logMessage("*-*-* OIS Initialising");

		OIS::ParamList pl;
		size_t windowHnd = 0;
		mWindow->getCustomAttribute("WINDOW", &windowHnd);
		pl.insert(std::make_pair(std::string("WINDOW"), Ogre::StringConverter::toString(windowHnd)));

#if OGRE_DEBUG_MODE == 1
	#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
		#define NO_EXCLUSIVE_INPUT
	#endif
#endif

#ifdef NO_EXCLUSIVE_INPUT
	#if defined OIS_WIN32_PLATFORM
		pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND" )));
		pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
		pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND")));
		pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE")));
	#elif defined OIS_LINUX_PLATFORM
		pl.insert(std::make_pair(std::string("x11_mouse_grab"), std::string("false")));
		pl.insert(std::make_pair(std::string("x11_mouse_hide"), std::string("false")));
		pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false")));
		pl.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
	#endif
#endif
		mInputManager = OIS::InputManager::createInputSystem(pl);

		mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
		mKeyboard->setEventCallback(this);
		mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));
		mMouse->setEventCallback(this);

		windowResized(mWindow);
//Initialising GUI
		Ogre::LogManager::getSingletonPtr()->logMessage("*-*-* MyGUI Initialising");
		mGUI = new MyGUI::Gui;
		mGUI->initialise(mWindow);
		mGUI->load("editor.layout");

		mMenuBar = mGUI->createWidget<MyGUI::MenuBar>("MenuBar",
			MyGUI::IntCoord(0, 0, mGUI->getViewWidth(), 28),
			MyGUI::ALIGN_TOP | MyGUI::ALIGN_HSTRETCH, "Overlapped");

		mMenuBar->addItem("File");
		mPopupMenuFile = mMenuBar->getItemMenu(0);
		mPopupMenuFile->addItem("New");
		mPopupMenuFile->addItem("Open ...");
		mPopupMenuFile->addItem("Save");
		mPopupMenuFile->addItem("Save as ...", false, true);
		mPopupMenuFile->addItem("Settings", false, true);
		mPopupMenuFile->addItem("Quit");

		mMenuBar->addItem("Help");
		mPopupMenuHelp = mMenuBar->getItemMenu(1);
		mPopupMenuHelp->addItem("Help");
		mPopupMenuHelp->addItem("About ...");

		return (true);
    }
void DotSceneLoader::processCamera(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent)
{
	// Process attributes
	Ogre::String name = getAttrib(XMLNode, "name");
	Ogre::String id = getAttrib(XMLNode, "id");
	Ogre::Real fov = getAttribReal(XMLNode, "fov", 45);
	Ogre::Real aspectRatio = getAttribReal(XMLNode, "aspectRatio", 1.3333);
	Ogre::String projectionType = getAttrib(XMLNode, "projectionType", "perspective");

	// Create the camera
	Ogre::Camera *pCamera = mSceneMgr->createCamera(name);

	//TODO: make a flag or attribute indicating whether or not the camera should be attached to any parent node.
	//if(pParent)
	//    pParent->attachObject(pCamera);

	// Set the field-of-view
	//! @todo Is this always in degrees?
	//pCamera->setFOVy(Ogre::Degree(fov));

	// Set the aspect ratio
	//pCamera->setAspectRatio(aspectRatio);

	// Set the projection type
	if (projectionType == "perspective")
		pCamera->setProjectionType(Ogre::PT_PERSPECTIVE);
	else if (projectionType == "orthographic")
		pCamera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

	rapidxml::xml_node<>* pElement;

	// Process clipping (?)
	pElement = XMLNode->first_node("clipping");
	if (pElement)
	{
		Ogre::Real nearDist = getAttribReal(pElement, "near");
		pCamera->setNearClipDistance(nearDist);

		Ogre::Real farDist = getAttribReal(pElement, "far");
		pCamera->setFarClipDistance(farDist);
	}

	// Process position (?)
	pElement = XMLNode->first_node("position");
	if (pElement)
		pCamera->setPosition(parseVector3(pElement));

	// Process rotation (?)
	pElement = XMLNode->first_node("rotation");
	if (pElement)
		pCamera->setOrientation(parseQuaternion(pElement));

	// Process normal (?)
	pElement = XMLNode->first_node("normal");
	if (pElement)
		;//!< @todo What to do with this element?

	// Process lookTarget (?)
	pElement = XMLNode->first_node("lookTarget");
	if (pElement)
		;//!< @todo Implement the camera look target

	// Process trackTarget (?)
	pElement = XMLNode->first_node("trackTarget");
	if (pElement)
		;//!< @todo Implement the camera track target

	// Process userDataReference (?)
	pElement = XMLNode->first_node("userDataReference");
	if (pElement)
		;//!< @todo Implement the camera user data reference

	// construct a scenenode is no parent
	if (!pParent)
	{
		Ogre::SceneNode* pNode = mAttachNode->createChildSceneNode(name);
		pNode->setPosition(pCamera->getPosition());
		pNode->setOrientation(pCamera->getOrientation());
		pNode->scale(1, 1, 1);
	}
}
Example #29
0
void camera_set_far_clip_distance(CameraHandle camera_handle, float d)
{
    Ogre::Camera* camera = static_cast<Ogre::Camera*>(camera_handle);
    camera->setFarClipDistance( d );
}
Example #30
0
int main(int argc, char* argv[])
{
	std::unique_ptr<ExecutionArgs> exArgs(new ExecutionArgs());
	if (!processCommandLineArgs(argc, argv, *exArgs)) {
		return -1;
	} else if (exArgs->helpPrompt) {
		std::cout << "Usage: sts [--help] || [--config]" << std::endl;
		std::cout << "Options:" << std::endl;
		std::cout << "\t --help - print this message;" << std::endl;
		std::cout << "\t --config - show config dialog." << std::endl;
		std::cout << std::endl;
		return 0;
	}

	try {
		Ogre::String lConfigFileName = "ogre.cfg";
		Ogre::String lPluginsFileName = "plugins.cfg";
		Ogre::String lLogFileName = "Ogre_STS.log";

		std::unique_ptr<Ogre::Root> lRoot(new Ogre::Root(lPluginsFileName, lConfigFileName, lLogFileName));

		if (exArgs->showConfigDialog) {
			if (!lRoot->showConfigDialog()) {
				return 0;
			}
		}

		Ogre::String lWindowTitle = "STS";
		Ogre::String lCustomCapacities = "";

		/* Check for the valid ogre.cfg */
		bool lCreateAWindowAutomatically = lRoot->restoreConfig();
		if (!lCreateAWindowAutomatically) {
			initSomeRenderSystem(lRoot);
		}
		Ogre::RenderWindow* lWindow = lRoot->initialise(lCreateAWindowAutomatically, lWindowTitle, lCustomCapacities);

		if (!lWindow) {
			/* ogre.cfg is not available - start with hardcoded parameters */
			unsigned int lSizeX = 800;
			unsigned int lSizeY = 600;
			bool lFullscreen = false;

			Ogre::NameValuePairList lParams;
			lParams["FSAA"] = "0";
			lParams["vsync"] = "true";
			lWindow = lRoot->createRenderWindow(lWindowTitle, lSizeX, lSizeY, lFullscreen, &lParams);
		}

		/* Create a scene manager */
		Ogre::SceneManager* lScene = lRoot->createSceneManager(Ogre::ST_GENERIC, "SceneManager");

		Ogre::SceneNode* lRootSceneNode = lScene->getRootSceneNode();

		/* Create camera */
		Ogre::Camera* lCamera = lScene->createCamera("MyCamera");

		/* Create viewport (camera <-> window) */
		Ogre::Viewport* vp = lWindow->addViewport(lCamera);

		vp->setAutoUpdated(true);
		vp->setBackgroundColour(Ogre::ColourValue(1, 0, 1));

		lCamera->setAspectRatio(float(vp->getActualWidth()) / vp->getActualHeight());
		lCamera->setPosition(Ogre::Vector3(0, 100, -1));
		lCamera->lookAt(Ogre::Vector3(0, 0, 0));

		/* Set clipping*/
		lCamera->setNearClipDistance(1.5f);
		lCamera->setFarClipDistance(3000.0f);

		/* Lighting */
		Ogre::Light* lLight = lScene->createLight("MainLight");
		lLight->setPosition(Ogre::Vector3(0, 100, 0));

		/* Resource manager */
		Ogre::String lRcGroupName = "Main group";
		initResourceMainGroup(lRcGroupName);

		/* Load model */
		Ogre::Entity* lShipEntity = lScene->createEntity("airship.mesh");
		lShipEntity->setCastShadows(false);

		Ogre::SceneNode* lShipNode = lRootSceneNode->createChildSceneNode();
		lShipNode->attachObject(lShipEntity);
		lShipNode->setScale(Ogre::Vector3(3.15f, 3.15f, 3.15f));

		/* Starship start point */
		Ogre::Vector3 razorSP(0, -200, -100);
		lShipNode->setPosition(razorSP);

		/* Sprite billboard */
		Ogre::SceneNode* lSpriteNode = lRootSceneNode->createChildSceneNode();
		Ogre::BillboardSet* lBillboardSet = lScene->createBillboardSet();
		lBillboardSet->setMaterialName("enemy_01", lRcGroupName);
		lBillboardSet->setTextureStacksAndSlices(1, 4);
		Ogre::Billboard* lSpriteBillboard = lBillboardSet->createBillboard(Ogre::Vector3(0, 0, 0));
		lSpriteBillboard->setDimensions(48.0f / 2.0f, 58.0f / 2.0f);
		lSpriteBillboard->setTexcoordIndex(1);
		lSpriteNode->attachObject(lBillboardSet);
		lSpriteNode->setPosition(Ogre::Vector3(0, -200, 100));

		/* Obtain the timer pointer */
		Ogre::Timer* lTimer = lRoot->getTimer();

		/* Skip all the messages */
		lWindow->setAutoUpdated(false);
		lRoot->clearEventTimes();

		while (!lWindow->isClosed()) {
			float angle = Ogre::Math::Sin(float(lTimer->getMilliseconds()) * Ogre::Math::PI / 2000.0f) * Ogre::Math::PI / 4.0f;
			float diplacement = Ogre::Math::Cos(float(lTimer->getMilliseconds()) * Ogre::Math::PI / 2000.0f) * 100.0f;
			lShipNode->setOrientation(Ogre::Quaternion(Ogre::Radian(angle), Ogre::Vector3(0, 0, 1)));
			lShipNode->setPosition(razorSP + Ogre::Vector3(diplacement, 0.0f, 0.0f));

			unsigned int spriteFrame = (lTimer->getMilliseconds() / 125) % 2;
			lSpriteBillboard->setTexcoordIndex(spriteFrame);

			lWindow->update(false);
			lWindow->swapBuffers();
			lRoot->renderOneFrame();

			Ogre::WindowEventUtilities::messagePump();
		}
		Ogre::LogManager::getSingleton().logMessage("Render window closed.");
	}
	catch (Ogre::Exception &e) {
		std::cerr << "Ogre::Exception: " << e.what() << std::endl;
	}
	catch (std::exception &e) {
		std::cerr << "std::exception: " << e.what() << std::endl;
	}

	return 0;
}