void TerrainManager::fixCompositorClearColor()
{
	// hack
	// now with extensive error checking
	if (CompositorManager::getSingleton().hasCompositorChain(gEnv->mainCamera->getViewport()))
	{
		//	//CompositorManager::getSingleton().getCompositorChain(gEnv->ogreCamera->getViewport())->getCompositor(0)->getTechnique()->getOutputTargetPass()->getPass(0)->setClearColour(fade_color);
		CompositorInstance *co = CompositorManager::getSingleton().getCompositorChain(gEnv->mainCamera->getViewport())->_getOriginalSceneCompositor();
		if (co)
		{
			CompositionTechnique *ct = co->getTechnique();
			if (ct)
			{
				CompositionTargetPass *ctp = ct->getOutputTargetPass();
				if (ctp)
				{
					CompositionPass *p = ctp->getPass(0);
					if (p)
					{
						p->setClearColour(fade_color);
					}
				}
			}
		}
	}
}
//-----------------------------------------------------------------------
void CompositorChain::_compile()
{
	clearCompiledState();

	bool compositorsEnabled = false;

	// force default scheme so materials for compositor quads will determined correctly
	MaterialManager& matMgr = MaterialManager::getSingleton();
	String prevMaterialScheme = matMgr.getActiveScheme();
	matMgr.setActiveScheme(MaterialManager::DEFAULT_SCHEME_NAME);
	
    /// Set previous CompositorInstance for each compositor in the list
    CompositorInstance *lastComposition = mOriginalScene;
	mOriginalScene->mPreviousInstance = 0;
	CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0);
	pass->setClearBuffers(mViewport->getClearBuffers());
	pass->setClearColour(mViewport->getBackgroundColour());
    for(Instances::iterator i=mInstances.begin(); i!=mInstances.end(); ++i)
    {
        if((*i)->getEnabled())
        {
			compositorsEnabled = true;
            (*i)->mPreviousInstance = lastComposition;
            lastComposition = (*i);
        }
    }
    

    /// Compile misc targets
    lastComposition->_compileTargetOperations(mCompiledState);
    
    /// Final target viewport (0)
	mOutputOperation.renderSystemOperations.clear();
    lastComposition->_compileOutputOperation(mOutputOperation);

	// Deal with viewport settings
	if (compositorsEnabled != mAnyCompositorsEnabled)
	{
		mAnyCompositorsEnabled = compositorsEnabled;
		if (mAnyCompositorsEnabled)
		{
			// Save old viewport clearing options
			mOldClearEveryFrameBuffers = mViewport->getClearBuffers();
			// Don't clear anything every frame since we have our own clear ops
			mViewport->setClearEveryFrame(false);
		}
		else
		{
			// Reset clearing options
			mViewport->setClearEveryFrame(mOldClearEveryFrameBuffers > 0, 
				mOldClearEveryFrameBuffers);
		}
	}

	// restore material scheme
	matMgr.setActiveScheme(prevMaterialScheme);

    
    mDirty = false;
}
//---------------------------------------------------------------------
void CompositorManager::_reconstructAllCompositorResources()
{
    // In order to deal with shared resources, we have to disable *all* compositors
    // first, that way shared resources will get freed
    typedef vector<CompositorInstance*>::type InstVec;
    InstVec instancesToReenable;
    for (Chains::iterator i = mChains.begin(); i != mChains.end(); ++i)
    {
        CompositorChain* chain = i->second;
        CompositorChain::InstanceIterator instIt = chain->getCompositors();
        while (instIt.hasMoreElements())
        {
            CompositorInstance* inst = instIt.getNext();
            if (inst->getEnabled())
            {
                inst->setEnabled(false);
                instancesToReenable.push_back(inst);
            }
        }
    }

    //UVs are lost, and will never be reconstructed unless we do them again, now
    if( mRectangle )
        mRectangle->setDefaultUVs();

    for (InstVec::iterator i = instancesToReenable.begin(); i != instancesToReenable.end(); ++i)
    {
        CompositorInstance* inst = *i;
        inst->setEnabled(true);
    }
}
void TerrainManager::initHDR()
{
	Viewport *vp = gEnv->mainCamera->getViewport();
	CompositorInstance *instance = CompositorManager::getSingleton().addCompositor(vp, "HDR", 0);
	CompositorManager::getSingleton().setCompositorEnabled(vp, "HDR", true);

	// HDR needs a special listener
	hdr_listener = new HDRListener();
	instance->addListener(hdr_listener);
	hdr_listener->notifyViewportSize(vp->getActualWidth(), vp->getActualHeight());
	hdr_listener->notifyCompositor(instance);
}
Exemple #5
0
void DeferredShadingSystem::logCurrentMode(void)
{
  if(mActive == false)
  {
    LogManager::getSingleton().logMessage("No Compositor Enabled!");
    return;
  }

  CompositorInstance* ci = mInstance[mCurrentMode];
  assert(ci->getEnabled() == true);
  LogManager::getSingleton().logMessage("Current Mode: ");
  LogManager::getSingleton().logMessage(ci->getCompositor()->getName());
}
//-----------------------------------------------------------------------
void CompositorManager::removeCompositor(Viewport *vp, const String &compositor)
{
    CompositorChain *chain = getCompositorChain(vp);
    for(size_t pos=0; pos < chain->getNumCompositors(); ++pos)
    {
        CompositorInstance *instance = chain->getCompositor(pos);
        if(instance->getCompositor()->getName() == compositor)
        {
            chain->removeCompositor(pos);
            break;
        }
    }
}
//-----------------------------------------------------------------------
void CompositorManager::setCompositorEnabled(Viewport *vp, const String &compositor, bool value)
{
    CompositorChain *chain = getCompositorChain(vp);
    for(size_t pos=0; pos < chain->getNumCompositors(); ++pos)
    {
        CompositorInstance *instance = chain->getCompositor(pos);
        if(instance->getCompositor()->getName() == compositor)
        {
            chain->setCompositorEnabled(pos, value);
            break;
        }
    }
}
//-----------------------------------------------------------------------
void CompositorChain::setCompositorEnabled(size_t position, bool state)
{
	CompositorInstance* inst = getCompositor(position);
	if (!state && inst->getEnabled())
	{
		// If we're disabling a 'middle' compositor in a chain, we have to be
		// careful about textures which might have been shared by non-adjacent
		// instances which have now become adjacent. 
		CompositorInstance* nextInstance = getNextInstance(inst, true);
		if (nextInstance)
		{
			CompositionTechnique::TargetPassIterator tpit = nextInstance->getTechnique()->getTargetPassIterator();
			while(tpit.hasMoreElements())
			{
				CompositionTargetPass* tp = tpit.getNext();
				if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS)
				{
					if (nextInstance->getTechnique()->getTextureDefinition(tp->getOutputName())->pooled)
					{
						// recreate
						nextInstance->freeResources(false, true);
						nextInstance->createResources(false);
					}
				}

			}
		}

	}
    inst->setEnabled(state);
}
Exemple #9
0
void CameraBlurListener::notifyMaterialRender(uint32 pass_id, MaterialPtr &mat)
{
	if (pass_id == 999) 
	{
		if (mApp->pGame->pause == false)
		{
			//acquire the texture flipping attribute in the first frame
			if(compositorinstance)
			{
				mRequiresTextureFlipping  = compositorinstance->getRenderTarget("previousscene")->requiresTextureFlipping();
				compositorinstance=NULL;
			}
			// this is the camera you're using
			#ifndef SR_EDITOR
			Camera *cam = mApp->mSplitMgr->mCameras.front();
			#else
			Camera *cam = mApp->mCamera;
			#endif

			// get the pass
			Pass *pass = mat->getBestTechnique()->getPass(0);
			GpuProgramParametersSharedPtr  params = pass->getFragmentProgramParameters();

			const RenderTarget::FrameStats& stats =  mApp->getWindow()->getStatistics();
			float m_lastFPS =stats.lastFPS;

			Matrix4 projectionMatrix   = cam->getProjectionMatrix();
			if (mRequiresTextureFlipping)
			{
				// Because we're not using setProjectionMatrix, this needs to be done here
				// Invert transformed y
				projectionMatrix[1][0] = -projectionMatrix[1][0];
				projectionMatrix[1][1] = -projectionMatrix[1][1];
				projectionMatrix[1][2] = -projectionMatrix[1][2];
				projectionMatrix[1][3] = -projectionMatrix[1][3];
			}
			Matrix4 iVP = (projectionMatrix * cam->getViewMatrix()).inverse();

			if (params->_findNamedConstantDefinition("EPF_ViewProjectionInverseMatrix"))
				params->setNamedConstant("EPF_ViewProjectionInverseMatrix", iVP);
			if (params->_findNamedConstantDefinition("EPF_PreviousViewProjectionMatrix"))
				params->setNamedConstant("EPF_PreviousViewProjectionMatrix", prevviewproj);
			if (params->_findNamedConstantDefinition("intensity"))
				params->setNamedConstant("intensity", mApp->pSet->blur_int);

			float interpolationFactor = m_lastFPS * 0.03f ; //* m_timeScale m_timeScale is a multiplier to control motion blur interactively
			Quaternion current_orientation = cam->getDerivedOrientation();
			Vector3 current_position = cam->getDerivedPosition();
			Quaternion estimatedOrientation = Quaternion::Slerp(interpolationFactor, current_orientation, (m_pPreviousOrientation));
			Vector3 estimatedPosition    = (1-interpolationFactor) * current_position + interpolationFactor * (m_pPreviousPosition);
			Matrix4 prev_viewMatrix = Math::makeViewMatrix(estimatedPosition, estimatedOrientation);//.inverse().transpose();
			// compute final matrix
			prevviewproj = projectionMatrix * prev_viewMatrix;

			// update position and orientation for next update time
			m_pPreviousOrientation = current_orientation;
			m_pPreviousPosition = current_position;			
		}
	}
}
	virtual void execute(SceneManager *sm, RenderSystem *rs)
	{
		// Fire listener
		instance->_fireNotifyMaterialRender(pass_id, mat);

        Rectangle2D * mRectangle=static_cast<Rectangle2D *>(CompositorManager::getSingleton()._getTexturedRectangle2D());
        if (mQuadCornerModified)
        {
            // insure positions are using peculiar render system offsets 
            RenderSystem* rs = Root::getSingleton().getRenderSystem();
            Viewport* vp = rs->_getViewport();
            Real hOffset = rs->getHorizontalTexelOffset() / (0.5 * vp->getActualWidth());
            Real vOffset = rs->getVerticalTexelOffset() / (0.5 * vp->getActualHeight());
            mRectangle->setCorners(mQuadLeft + hOffset, mQuadTop - vOffset, mQuadRight + hOffset, mQuadBottom - vOffset);
        }
        
		// Queue passes from mat
		Technique::PassIterator i = technique->getPassIterator();
		while(i.hasMoreElements())
		{
			sm->_injectRenderWithPass(
				i.getNext(), 
				mRectangle,
				false // don't allow replacement of shadow passes
				);
		}
	}
Exemple #11
0
//---------------------------------------------------------------------
void CompositorManager::_reconstructAllCompositorResources()
{
	for (Chains::iterator i = mChains.begin(); i != mChains.end(); ++i)
	{
		CompositorChain* chain = i->second;
		CompositorChain::InstanceIterator instIt = chain->getCompositors();
		while (instIt.hasMoreElements())
		{
			CompositorInstance* inst = instIt.getNext();
			if (inst->getEnabled())
			{
				inst->setEnabled(false);
				inst->setEnabled(true);
			}
		}
	}
}
void DeferredShadingSystem::setupLightMaterials(void)
{
	assert( mLightMaterialsDirty 
		&& mCurrentMode == DSM_SHOWLIT
		&& mInstance[mCurrentMode]->getEnabled()==true);

	CompositorInstance* ci = mInstance[mCurrentMode];

	String mrt0 = ci->getTextureInstanceName("mrt_output", 0);
	String mrt1 = ci->getTextureInstanceName("mrt_output", 1);

	for(LightList::iterator it = mDirtyLightList.begin(); it != mDirtyLightList.end(); ++it)
	{
		MLight* light = *it;
		setupMaterial(light->getMaterial(), mrt0, mrt1);
	}

	mLightMaterialsDirty = false;
}
Exemple #13
0
//-----------------------------------------------------------------------------------
void Sample_Compositor::changePage(size_t pageNum)
{
	assert(pageNum < mNumCompositorPages);
	
	mActiveCompositorPage = pageNum;
	size_t maxCompositorsInPage = mCompositorNames.size() - (pageNum * COMPOSITORS_PER_PAGE);
	for (size_t i=0; i < COMPOSITORS_PER_PAGE; i++)
	{
		String checkBoxName = "Compositor_" + Ogre::StringConverter::toString(i);
		CheckBox* cb = static_cast<CheckBox*>(mTrayMgr->getWidget(TL_TOPLEFT, checkBoxName));
		if (i < maxCompositorsInPage)
		{
			String compositorName = mCompositorNames[pageNum * COMPOSITORS_PER_PAGE + i];
			CompositorInstance *tmpCompo = CompositorManager::getSingleton().getCompositorChain(mViewport)
				->getCompositor(compositorName);

			cb->setCaption(compositorName);

			if( tmpCompo )
			{
				cb->setChecked( tmpCompo->getEnabled(), false );
				cb->show();
			}
			else
			{
				cb->setChecked( false, false );
				cb->hide();
			}

		}
		else
		{
			cb->hide();
		}
	}

	OgreBites::Button* pageButton = static_cast<OgreBites::Button*>(mTrayMgr->getWidget(TL_TOPLEFT, "PageButton"));
	Ogre::StringStream ss;
	ss << "Compositors " << pageNum + 1 << "/" << mNumCompositorPages;
	pageButton->setCaption(ss.str());
}
void DeferredShadingSystem::logCurrentMode(void)
{
	if (mActive==false)
	{
		LogManager::getSingleton().logMessage("No Compositor Enabled!");
		return;
	}

	CompositorInstance* ci = mInstance[mCurrentMode];
	assert(ci->getEnabled()==true);

	LogManager::getSingleton().logMessage("Current Mode: ");
	LogManager::getSingleton().logMessage(ci->getCompositor()->getName());
		
	if (mCurrentMode==DSM_SHOWLIT)
	{			
		LogManager::getSingleton().logMessage("Current mrt outputs are:");
		LogManager::getSingleton().logMessage(ci->getTextureInstanceName("mrt_output", 0));
		LogManager::getSingleton().logMessage(ci->getTextureInstanceName("mrt_output", 1));
	}
}
	virtual void execute(SceneManager *sm, RenderSystem *rs)
	{
		// Fire listener
		instance->_fireNotifyMaterialRender(pass_id, mat);
		// Queue passes from mat
		Technique::PassIterator i = technique->getPassIterator();
		while(i.hasMoreElements())
		{
			sm->_injectRenderWithPass(
				i.getNext(), 
				CompositorManager::getSingleton()._getTexturedRectangle2D(),
				false // don't allow replacement of shadow passes
				);
		}
	}
	void BaseGame::Initialize()
	{
		ResourceGroupManager::getSingleton().addResourceLocation(Directories::GetContentDirectory() + "/Fonts", "FileSystem", "Essential");
		ResourceGroupManager::getSingleton().initialiseResourceGroup("Essential");

		// Create scene manager
		m_sceneMgr = m_root->createSceneManager(ST_GENERIC, "SceneManager");
		m_sceneMgr->setAmbientLight(ColourValue::Black);

		// Light
		m_light = m_sceneMgr->createLight();
		m_light->setType(Light::LT_DIRECTIONAL);
		m_light->setDirection(1.0f, 0.0f, 0.0f);

		// Space camera
		m_camera = new SpaceCamera(*this, Vector3(0, 0, -5));
		assert(m_camera);
		GetCamera().setFOVy(FieldOfView);
		GetCamera().setNearClipDistance(NearPlane);
		GetCamera().setFarClipDistance(FarPlane);

		m_viewport = m_renderWnd->addViewport(&GetCamera());
		m_viewport->setBackgroundColour(m_backgroundColour);

		GetCamera().setAspectRatio(Real(m_viewport->getActualWidth()) / Real(m_viewport->getActualHeight()));	
		m_viewport->setCamera(&GetCamera());

		// Ogre overlay
		m_textRenderer = new TextRenderer();

		Game::Initialize();

		// Player
		m_player = new Player(*this);

		// Sprite
		m_sceneMgr->getRenderQueue()->getQueueGroup(RENDER_QUEUE_MAIN + 1)->setShadowsEnabled(false);
		m_sprite = new Sprite();
		m_sprite->Init(m_sceneMgr, m_viewport, RENDER_QUEUE_MAIN + 1, true);
		m_sprite->SetSpriteLocation(Directories::GetContentDirectory() + "/Sprites");

		// Lens flare
		m_lensFlare = new LensFlare(*this, LensFlare::DefaultSunPos);

		//
		// Compositors
		//
		CompositorManager &compMgr = CompositorManager::getSingleton();

		// Bloom (crash on d3d if device lost occur)
		compMgr.addCompositor(m_viewport, "Bloom");
		if (m_root->getRenderSystem()->getName().find("Direct3D") == std::string::npos)
		{
			compMgr.setCompositorEnabled(m_viewport, "Bloom", true);
		}

		// Radial blur
		CompositorInstance *radialBlur = compMgr.addCompositor(m_viewport, "Radial Blur");
		radialBlur->addListener(new RadialBlurListener(*m_player));
		compMgr.setCompositorEnabled(m_viewport, "Radial Blur", true);

		//
		// CEGUI
		//
		m_ceguiLogger = new CEGUI::DefaultLogger();
		assert(m_ceguiLogger);
		CEGUI::Logger::getSingleton().setLogFilename(Directories::GetWritablePath("cegui.log"));

		m_renderer = &CEGUI::OgreRenderer::bootstrapSystem(*m_renderWnd);

		// Disable calls to beginFrame and endFrame, which also disables
		// default rendering: we will use a custom rendering method.
		m_renderer->setFrameControlExecutionEnabled(true);
		
		// Hook back into the rendering process
		//m_sceneMgr->addRenderQueueListener(new CEGUIRQListener(m_renderer, RENDER_QUEUE_OVERLAY, false));

		CEGUI::Imageset::setDefaultResourceGroup("GUI");
		CEGUI::Font::setDefaultResourceGroup("GUI");
		CEGUI::Scheme::setDefaultResourceGroup("GUI");
		CEGUI::WidgetLookManager::setDefaultResourceGroup("GUI");
		CEGUI::WindowManager::setDefaultResourceGroup("GUI");
		CEGUI::ScriptModule::setDefaultResourceGroup("GUI");

		CEGUI::SchemeManager::getSingleton().create("VanillaSkin.scheme");
		CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
		CEGUI::SchemeManager::getSingleton().create("InGame.scheme");

		// Set default font
		CEGUI::Font &font = CEGUI::FontManager::getSingleton().create("GameFont.font", "GUI");
		CEGUI::System::getSingleton().setDefaultFont(&font);

		// Set mouse cursor
		CEGUI::System::getSingleton().setDefaultMouseCursor("Vanilla-Images", "MouseArrow");
		CEGUI::MouseCursor::getSingleton().setImage(CEGUI::System::getSingleton().getDefaultMouseCursor());

		// Set initial cursor position		
		CEGUI::System::getSingleton().injectMousePosition((float)m_renderWnd->getWidth() / 2.0f + 1, (float)m_renderWnd->getHeight() / 2.0f);

		//
		// Sound
		//
		m_sound = new Sound();

		// FPS
		m_textRenderer->AddTextBox("txtFps", "Fps: ", 
			(Real)m_viewport->getActualLeft(), (Real)m_viewport->getActualTop(), 
			(Real)m_viewport->getActualWidth(), (Real)m_viewport->getActualHeight() + m_fpsOverlayHeight);

	}
//---------------------------------------------------------------------
void CompositorInstance::deriveTextureRenderTargetOptions(
	const String& texname, bool *hwGammaWrite, uint *fsaa)
{
	// search for passes on this texture def that either include a render_scene
	// or use input previous
	bool renderingScene = false;

	CompositionTechnique::TargetPassIterator it = mTechnique->getTargetPassIterator();
	while (it.hasMoreElements())
	{
		CompositionTargetPass* tp = it.getNext();
		if (tp->getOutputName() == texname)
		{
			if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS)
			{
				// this may be rendering the scene implicitly
				// Can't check mPreviousInstance against mChain->_getOriginalSceneCompositor()
				// at this time, so check the position
				CompositorChain::InstanceIterator instit = mChain->getCompositors();
				renderingScene = true;
				while(instit.hasMoreElements())
				{
					CompositorInstance* inst = instit.getNext();
					if (inst == this)
						break;
					else if (inst->getEnabled())
					{
						// nope, we have another compositor before us, this will
						// be doing the AA
						renderingScene = false;
					}
				}
				if (renderingScene)
					break;
			}
			else
			{
				// look for a render_scene pass
				CompositionTargetPass::PassIterator pit = tp->getPassIterator();
				while(pit.hasMoreElements())
				{
					CompositionPass* pass = pit.getNext();
					if (pass->getType() == CompositionPass::PT_RENDERSCENE)
					{
						renderingScene = true;
						break;
					}
				}
			}

		}
	}

	if (renderingScene)
	{
		// Ok, inherit settings from target
		RenderTarget* target = mChain->getViewport()->getTarget();
		*hwGammaWrite = target->isHardwareGammaEnabled();
		*fsaa = target->getFSAA();
	}
	else
	{
		*hwGammaWrite = false;
		*fsaa = 0;
	}

}
Exemple #18
0
//-----------------------------------------------------------------------------------
void Sample_Compositor::checkBoxToggled(OgreBites::CheckBox * box)
{
	if (Ogre::StringUtil::startsWith(box->getName(), "Compositor_", false))
	{
		String compositorName = box->getCaption();

		String activeTex = mDebugTextureSelectMenu->getSelectedItem();

		if (!box->isChecked())
		{
			//Remove the items from the debug menu and remove debug texture if from disabled compositor
			bool debuggingRemovedTex = StringUtil::startsWith(activeTex, compositorName, false);
			if (debuggingRemovedTex)
			{
				mDebugTextureTUS->setContentType(TextureUnitState::CONTENT_NAMED);
				mDebugTextureSelectMenu->selectItem(0, true);
			}
			for (unsigned int i = 1; i < mDebugTextureSelectMenu->getNumItems(); i++)
			{
				if (StringUtil::startsWith(mDebugTextureSelectMenu->getItems()[i], compositorName, false))
				{
					mDebugTextureSelectMenu->removeItem(i);
					i--;
				}
			}
			if (!debuggingRemovedTex)
			{
				//Selection clears itself when removing items. Restore.
				mDebugTextureSelectMenu->selectItem(activeTex, false);
			}
		}

		CompositorManager::getSingleton().setCompositorEnabled(mViewport, compositorName, box->isChecked());

		
		if (box->isChecked())
		{
			//Add the items to the selectable texture menu
			CompositorInstance* instance = CompositorManager::getSingleton().getCompositorChain(mViewport)->getCompositor(compositorName);
			if (instance)
			{
				CompositionTechnique::TextureDefinitionIterator it = instance->getTechnique()->getTextureDefinitionIterator();
				while (it.hasMoreElements())
				{
					CompositionTechnique::TextureDefinition* texDef = it.getNext();
					size_t numTextures = texDef->formatList.size();
					if (numTextures > 1)
					{
						for (size_t i=0; i<numTextures; i++)
						{
							//Dirty string composition. NOT ROBUST!
							mDebugTextureSelectMenu->addItem(compositorName + ";" + texDef->name + ";" + 
								Ogre::StringConverter::toString((Ogre::uint32)i));
						}
					}
					else
					{
						mDebugTextureSelectMenu->addItem(compositorName + ";" + texDef->name);
					}
				}
				mDebugTextureSelectMenu->selectItem(activeTex, false);
			}
		}
	}
}