Пример #1
0
//-----------------------------------------------------------------------
bool ShaderExReflectionMap::preAddToRenderState( RenderState* renderState, Pass* srcPass, Pass* dstPass )
{
	TextureUnitState* textureUnit;
	
	// Create the mask texture unit.
	textureUnit = dstPass->createTextureUnitState();
	textureUnit->setTextureName(mMaskMapTextureName);		
	mMaskMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1;

	// Create the reflection texture unit.
	textureUnit = dstPass->createTextureUnitState();

	if (mReflectionMapType == TEX_TYPE_2D)
	{
		textureUnit->setTextureName(mReflectionMapTextureName);	
	}
	else
	{
		textureUnit->setCubicTextureName(mReflectionMapTextureName, true);	
	}
		
	mReflectionMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1;

	return true;
}
Пример #2
0
	//------------------------------------------------------
	void MaterialService::prepareMaterialInstance(MaterialPtr& mat, unsigned int idx, int tag) {
		if (tag < 0) // Should not be here if the polygon is sky textured
			OPDE_EXCEPT("Non-instanced material instance requested", "MaterialService::prepareMaterialInstance");

		mat->setReceiveShadows(true);

		StringUtil::StrStreamType lightmapName;
		lightmapName << "@lightmap" << tag;

		Pass *shadPass = mat->getTechnique(0)->getPass(0);

		if (shadPass->getNumTextureUnitStates() <= 1) {
			// Lightmap texture is added here
			TextureUnitState* tex = shadPass->createTextureUnitState(lightmapName.str());


			// Blend
			tex->setColourOperation(LBO_MODULATE);
			// Use 2nd texture co-ordinate set
			tex->setTextureCoordSet(1);

			// Clamp
			tex->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);


			// Switch filtering off to see lmap pixels: TFO_NONE
			tex->setTextureFiltering(TFO_BILINEAR);
		} else {
			// There is a definition of the lightmapping pass already, we only update that definition
			TextureUnitState* tex = shadPass->getTextureUnitState(1);
			tex->setTextureName(lightmapName.str());
			tex->setTextureCoordSet(1);
		}
	}
 //-----------------------------------------------------------------------
 bool TriplanarTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass )
 {
     TextureUnitState* textureUnit;
 
     // Create the mapping textures
     textureUnit = dstPass->createTextureUnitState();
     textureUnit->setTextureName(mTextureNameFromX);		
     mTextureSamplerIndexFromX = dstPass->getNumTextureUnitStates() - 1;
 
     textureUnit = dstPass->createTextureUnitState();
     textureUnit->setTextureName(mTextureNameFromY);		
     mTextureSamplerIndexFromY = dstPass->getNumTextureUnitStates() - 1;
 
     textureUnit = dstPass->createTextureUnitState();
     textureUnit->setTextureName(mTextureNameFromZ);		
     mTextureSamplerIndexFromZ = dstPass->getNumTextureUnitStates() - 1;
     return true;
 }
Пример #4
0
int GameScript::setMaterialTextureName(const String &materialName, int techniqueNum, int passNum, int textureUnitNum, const String &textureName)
{
	TextureUnitState *tu = 0;
	int res = getSafeTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
	if (res == 0 && tu != 0)
	{
		// finally, set it
		tu->setTextureName(textureName);
	}
	return res;
}
Пример #5
0
void ImpostorTexture::updateMaterials()
{
	for (int o = 0; o < IMPOSTOR_YAW_ANGLES; ++o){
		for (int i = 0; i < IMPOSTOR_PITCH_ANGLES; ++i){
			Material *m = material[i][o].getPointer();
			Pass *p = m->getTechnique(0)->getPass(0);

			TextureUnitState *t = p->getTextureUnitState(0);

			t->setTextureName(texture->getName());
		}
	}
}
Пример #6
0
void MaterialFactory::setSoftParticleDepth(TexturePtr depthtexture)
{
	if(MaterialGenerator::MRTSupported())
	{
		for (std::vector<std::string>::iterator it=softMtrs.begin();
			it != softMtrs.end(); ++it)
		{
			MaterialPtr mat = MaterialManager::getSingleton().getByName( (*it) );
			TextureUnitState* tus =mat->getTechnique(0)->getPass(0)->getTextureUnitState("depthMap");
			tus->setTextureName(depthtexture->getName());
		}
	}
}
Пример #7
0
	// 替换指定纹理层的纹理
	bool TerrainImpl::setPaintTexutreName(size_t nPaintChannel , const String &strTextureName)
	{
		Technique *pTech = mMaterial->getTechnique(0);
		Pass *pass = pTech->getPass(nPaintChannel / SPLATTING_TEXTURE_NUM);
		if(pass)
		{
			TextureUnitState *texture = pass->getTextureUnitState(COVERAGE_TEXTURE_NUM + (nPaintChannel % SPLATTING_TEXTURE_NUM));
			if(texture)
			{
				texture->setTextureName(strTextureName);
				return texture->getTextureName() == strTextureName && !texture->_getTexturePtr().isNull() && texture->_getTexturePtr()->isLoaded();
			}
		}
		return false;
	}
Пример #8
0
	void DepthComposerInstance::notifyMaterialSetup(uint pass_id, Ogre::MaterialPtr &mat)
	{
        //LogManager::getSingleton ().logMessage (
        //            "Caelum::DepthComposer: Material setup");

        Pass* pass = mat->getBestTechnique ()->getPass (0);

        TextureUnitState *depthTus = pass->getTextureUnitState(1);
        if (depthTus->getTextureName () != mDepthRenderer->getDepthRenderTexture ()->getName()) {
            depthTus->setTextureName (mDepthRenderer->getDepthRenderTexture ()->getName ());
            LogManager::getSingleton ().logMessage (
                        "Caelum::DepthComposer: Assigned depth texture in compositor material");
        }

        mParams.setup(pass->getFragmentProgramParameters ());
	}
void CarModel::UpdateBraking()
{
	if (brakes)
		brakes->setVisible(bBraking && mbVisible);

	std::string texName = sDirname + (bBraking ? "_body00_brake.png" : "_body00_add.png");

	MaterialPtr mtr = MaterialManager::getSingleton().getByName(sMtr[Mtr_CarBody]);
	if (!mtr.isNull())
	{	Material::TechniqueIterator techIt = mtr->getTechniqueIterator();
		while (techIt.hasMoreElements())
		{	Technique* tech = techIt.getNext();
			Technique::PassIterator passIt = tech->getPassIterator();
			while (passIt.hasMoreElements())
			{	Pass* pass = passIt.getNext();
				Pass::TextureUnitStateIterator tusIt = pass->getTextureUnitStateIterator();
				while (tusIt.hasMoreElements())
				{
					TextureUnitState* tus = tusIt.getNext();
					if (tus->getName() == "diffuseMap")
					{	tus->setTextureName( texName );  return;  }
	}	}	}	}
}
Пример #10
0
void VolumeRenderable::initialise()
{
	// Create geometry
	size_t nvertices = mSlices*4; // n+1 planes
	size_t elemsize = 3*3;
	size_t dsize = elemsize*nvertices;
	size_t x;
	
	Ogre::IndexData *idata = new Ogre::IndexData();
	Ogre::VertexData *vdata = new Ogre::VertexData();
	
	// Create  structures
	float *vertices = new float[dsize];
	
	float coords[4][2] = {
		{0.0f, 0.0f},
		{0.0f, 1.0f},
		{1.0f, 0.0f},
		{1.0f, 1.0f}
	};
	for(x=0; x<mSlices; x++) 
	{
		for(size_t y=0; y<4; y++)
		{
			float xcoord = coords[y][0]-0.5;
			float ycoord = coords[y][1]-0.5;
			float zcoord = -((float)x/(float)(mSlices-1)  - 0.5f);
			// 1.0f .. a/(a+1)
			// coordinate
			vertices[x*4*elemsize+y*elemsize+0] = xcoord*(mSize/2.0f);
			vertices[x*4*elemsize+y*elemsize+1] = ycoord*(mSize/2.0f);
			vertices[x*4*elemsize+y*elemsize+2] = zcoord*(mSize/2.0f);
			// normal
			vertices[x*4*elemsize+y*elemsize+3] = 0.0f;
			vertices[x*4*elemsize+y*elemsize+4] = 0.0f;
			vertices[x*4*elemsize+y*elemsize+5] = 1.0f;
			// tex
			vertices[x*4*elemsize+y*elemsize+6] = xcoord*sqrtf(3.0f);
			vertices[x*4*elemsize+y*elemsize+7] = ycoord*sqrtf(3.0f);
			vertices[x*4*elemsize+y*elemsize+8] = zcoord*sqrtf(3.0f);
		} 
	}
	unsigned short *faces = new unsigned short[mSlices*6];
	for(x=0; x<mSlices; x++) 
	{
		faces[x*6+0] = x*4+0;
		faces[x*6+1] = x*4+1;
		faces[x*6+2] = x*4+2;
		faces[x*6+3] = x*4+1;
		faces[x*6+4] = x*4+2;
		faces[x*6+5] = x*4+3;
	}
	// Setup buffers
	vdata->vertexStart = 0;
	vdata->vertexCount = nvertices;
	
	VertexDeclaration* decl = vdata->vertexDeclaration;
	VertexBufferBinding* bind = vdata->vertexBufferBinding;

	size_t offset = 0;
	decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
	offset += VertexElement::getTypeSize(VET_FLOAT3);
	decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
	offset += VertexElement::getTypeSize(VET_FLOAT3);
	decl->addElement(0, offset, VET_FLOAT3, VES_TEXTURE_COORDINATES);
	offset += VertexElement::getTypeSize(VET_FLOAT3);

	HardwareVertexBufferSharedPtr vbuf = 
	HardwareBufferManager::getSingleton().createVertexBuffer(
		offset, nvertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	bind->setBinding(0, vbuf);

	vbuf->writeData(0, vbuf->getSizeInBytes(), vertices, true);
	
	HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton().
		createIndexBuffer(
			HardwareIndexBuffer::IT_16BIT, 
			mSlices*6, 
			HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	idata->indexBuffer = ibuf;
	idata->indexCount = mSlices*6;
	idata->indexStart = 0;
	ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);

	// Delete temporary buffers
	delete [] vertices;
	delete [] faces;
	
	// Now make the render operation
	mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
	mRenderOp.indexData = idata;
	mRenderOp.vertexData = vdata;
	mRenderOp.useIndexes = true;
	
	 // Create a brand new private material
	MaterialPtr material = 
		MaterialManager::getSingleton().create(mTexture, "VolumeRenderable",
			false, 0); // Manual, loader

	// Remove pre-created technique from defaults
	material->removeAllTechniques();
	
	// Create a techinique and a pass and a texture unit
 	Technique * technique = material->createTechnique();
	Pass * pass = technique->createPass();
	TextureUnitState * textureUnit = pass->createTextureUnitState();
	
	// Set pass parameters
	pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	pass->setDepthWriteEnabled(false);
	pass->setCullingMode(CULL_NONE);
	pass->setLightingEnabled(false);
	
	// Set texture unit parameters
	textureUnit->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
	textureUnit->setTextureName(mTexture, TEX_TYPE_3D);
	textureUnit->setTextureFiltering(TFO_TRILINEAR);
	
	mUnit = textureUnit;
	m_pMaterial = material;
}
Пример #11
0
void App::CreateHUD()
{	
	//  minimap from road img
	asp = 1.f;
	if (terrain)
	{
		ofsX=0; ofsY=0;
		float t = sc.td.fTerWorldSize*0.5;
		minX = -t;  minY = -t;  maxX = t;  maxY = t;

		float fMapSizeX = maxX - minX, fMapSizeY = maxY - minY;  // map size
		float size = std::max(fMapSizeX, fMapSizeY*asp);
		scX = 1.f / size;  scY = 1.f / size;

		//for (int c=0; c<2; ++c)
		String sMat = "circle_minimap";  //*/"road_minimap_inv";
		asp = 1.f;  //_temp
		ManualObject* m = Create2D(sMat,mSplitMgr->mHUDSceneMgr,1,true,true);  miniC = m;
		//asp = float(mWindow->getWidth())/float(mWindow->getHeight());
		m->setVisibilityFlags(RV_Hud);  m->setRenderQueueGroup(RQG_Hud1);
		
		///  change minimap image
		MaterialPtr mm = MaterialManager::getSingleton().getByName(sMat);
		Pass* pass = mm->getTechnique(0)->getPass(0);
		TextureUnitState* tus = pass->getTextureUnitState(0);
		if (tus)  tus->setTextureName(pSet->track + "_mini.png");
		tus = pass->getTextureUnitState(2);
		if (tus)  tus->setTextureName(pSet->track + "_ter.jpg");
		UpdMiniTer();
		

		float fHudSize = pSet->size_minimap;
		const float marg = 1.f + 0.05f;  // from border
		fMiniX = 1 - fHudSize * marg, fMiniY = 1 - fHudSize*asp * marg;

		ndMap = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(fMiniX,fMiniY,0));
		ndMap->scale(fHudSize, fHudSize*asp, 1);
		ndMap->attachObject(m);
		
		//  car pos dot - for all carModels (ghost and remote too)
		vMoPos.clear();
		vNdPos.clear();
		for (int i=0; i < /*pSet->local_players*/carModels.size(); ++i)
		{	vMoPos.push_back(0);
			vMoPos[i] = Create2D("hud/CarPos", mSplitMgr->mHUDSceneMgr, 0.4f, true, true);
			vMoPos[i]->setVisibilityFlags(RV_Hud);  vMoPos[i]->setRenderQueueGroup(RQG_Hud3);
			vNdPos.push_back(0);
			vNdPos[i] = ndMap->createChildSceneNode();
			vNdPos[i]->scale(fHudSize*1.5f, fHudSize*1.5f, 1);
			vNdPos[i]->attachObject(vMoPos[i]);  /*vNdPos[i]->setVisible(false);  */}
		ndMap->setVisible(false/*pSet->trackmap*/);
	}

	
	//  backgr  gauges
	ManualObject* mrpmB = Create2D("hud/rpm",mSplitMgr->mHUDSceneMgr,1);	mrpmB->setVisibilityFlags(RV_Hud);
	mrpmB->setRenderQueueGroup(RQG_Hud1);
	nrpmB = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nrpmB->attachObject(mrpmB);	nrpmB->setScale(0,0,0);  nrpmB->setVisible(false);

	ManualObject* mvelBk = Create2D("hud/kmh",mSplitMgr->mHUDSceneMgr,1);	mvelBk->setVisibilityFlags(RV_Hud);
	mvelBk->setRenderQueueGroup(RQG_Hud1);
	nvelBk = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nvelBk->attachObject(mvelBk);	nvelBk->setScale(0,0,0);  mvelBk->setVisible(false);
		
	ManualObject* mvelBm = Create2D("hud/mph",mSplitMgr->mHUDSceneMgr,1);	mvelBm->setVisibilityFlags(RV_Hud);
	mvelBm->setRenderQueueGroup(RQG_Hud1);
	nvelBm = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nvelBm->attachObject(mvelBm);	nvelBm->setScale(0,0,0);  mvelBm->setVisible(false);
		
	//  needles
	mrpm = Create2D("hud/needle",mSplitMgr->mHUDSceneMgr,1,true);  mrpm->setVisibilityFlags(RV_Hud);
	mrpm->setRenderQueueGroup(RQG_Hud3);
	nrpm = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nrpm->attachObject(mrpm);	nrpm->setScale(0,0,0);	nrpm->setVisible(false);
	
	mvel = Create2D("hud/needle",mSplitMgr->mHUDSceneMgr,1,true);  mvel->setVisibilityFlags(RV_Hud);
	mvel->setRenderQueueGroup(RQG_Hud3);
	nvel = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nvel->attachObject(mvel);	nvel->setScale(0,0,0);	nvel->setVisible(false);


	//  overlays
	OverlayManager& ovr = OverlayManager::getSingleton();
	ovCam = ovr.getByName("Car/CameraOverlay");

	ovGear = ovr.getByName("Hud/Gear");		hudGear = ovr.getOverlayElement("Hud/GearText");
	ovVel = ovr.getByName("Hud/Vel");		hudVel = ovr.getOverlayElement("Hud/VelText");
	ovBoost = ovr.getByName("Hud/Boost");	hudBoost = ovr.getOverlayElement("Hud/BoostText");
	ovAbsTcs = ovr.getByName("Hud/AbsTcs");	hudAbs = ovr.getOverlayElement("Hud/AbsText");
	ovCarDbg = ovr.getByName("Car/Stats");	hudTcs = ovr.getOverlayElement("Hud/TcsText");
	ovTimes = ovr.getByName("Hud/Times");	hudTimes = ovr.getOverlayElement("Hud/TimesText");

	ovOpp = ovr.getByName("Hud/Opponents"); hudOppB = ovr.getOverlayElement("Hud/OpponentsPanel");
	for (int o=0; o < 5; ++o)  for (int c=0; c < 3; ++c)  {
		hudOpp[o][c] = ovr.getOverlayElement("Hud/OppText"+toStr(o)+"_"+toStr(c));  hudOpp[o][c]->setCaption("");  }
	
	for (int o=0; o < carModels.size(); ++o)  // fill car names, not changed during play
	{
		const CarModel* cm = carModels[o];
		if (cm->eType != CarModel::CT_REPLAY)
		{
			hudOpp[o][2]->setCaption(cm->sDispName);
			hudOpp[o][2]->setColour(cm->color);
		}
	}

	ovWarnWin = ovr.getByName("Hud/WarnAndWin");
	hudWarnChk = ovr.getOverlayElement("Hud/Warning");
	hudWarnChk->setCaption(String(TR("#{WrongChk}")));
	hudWonPlace = ovr.getOverlayElement("Hud/WonPlace");

	//  dbg lines
	ovCarDbgTxt = ovr.getByName("Car/StatsTxt");  //ovCarDbgTxt->show();
	ovCarDbg = ovr.getByName("Car/Stats");  //ovCarDbg->show();  // bars
	for (int i=0; i < 5; i++)
	{	ovL[i] = ovr.getOverlayElement("L_"+toStr(i+1));
		ovR[i] = ovr.getOverlayElement("R_"+toStr(i+1));
		ovS[i] = ovr.getOverlayElement("S_"+toStr(i+1));
		ovU[i] = ovr.getOverlayElement("U_"+toStr(i+1));	}
		
	ShowHUD();  //_
	bSizeHUD = true;
	//SizeHUD(true);
}
	//---------------------------------------------------------------------
	void TerrainMaterialGeneratorC::SM2Profile::addTechnique(
		const MaterialPtr& mat, const Terrain* terrain, TechniqueType tt)
	{
		Technique* tech = mat->createTechnique();
		tech->setSchemeName("GBuffer");
 
		// Only supporting one pass
		Pass* pass = tech->createPass();
		//pass->setName("NO_DEFERRED");
 
		GpuProgramManager& gmgr = GpuProgramManager::getSingleton();
		HighLevelGpuProgramManager& hmgr = HighLevelGpuProgramManager::getSingleton();
		if (!mShaderGen)
		{
			if (hmgr.isLanguageSupported("cg"))
				mShaderGen = OGRE_NEW ShaderHelperCg();
			else
			{
				// todo
			}
 
			// check SM3 features
			mSM3Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_3_0");
			mSM4Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0");
 
		}
		HighLevelGpuProgramPtr vprog = mShaderGen->generateVertexProgram(this, terrain, tt);
		HighLevelGpuProgramPtr fprog = mShaderGen->generateFragmentProgram(this, terrain, tt);
 
		pass->setVertexProgram(vprog->getName());
		pass->setFragmentProgram(fprog->getName());
 
		if (tt == HIGH_LOD || tt == RENDER_COMPOSITE_MAP)
		{
			// global normal map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getTerrainNormalMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
 
			// global colour map
			if (terrain->getGlobalColourMapEnabled() && isGlobalColourMapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getGlobalColourMap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}
 
			// light map
			if (isLightmapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getLightmap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}
 
			// blend maps
			uint maxLayers = getMaxLayers(terrain);
			uint numBlendTextures = std::min(terrain->getBlendTextureCount(maxLayers), terrain->getBlendTextureCount());
			uint numLayers = std::min(maxLayers, static_cast<uint>(terrain->getLayerCount()));
			for (uint i = 0; i < numBlendTextures; ++i)
			{
				tu = pass->createTextureUnitState(terrain->getBlendTextureName(i));
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}
 
			// layer textures
			for (uint i = 0; i < numLayers; ++i)
			{
				// diffuse / specular
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 0));
 
				// normal / height
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 1));
			}
 
		}
		else
		{
			// LOW_LOD textures
			// composite map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getCompositeMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
 
			// That's it!
 
		}
	}
	//---------------------------------------------------------------------
	void TerrainMaterialGeneratorA::SM2Profile::addTechnique(
		const MaterialPtr& mat, const Terrain* terrain, TechniqueType tt)
	{
		Technique* tech = mat->createTechnique();

		// Only supporting one pass
		Pass* pass = tech->createPass();

		GpuProgramManager& gmgr = GpuProgramManager::getSingleton();
		HighLevelGpuProgramManager& hmgr = HighLevelGpuProgramManager::getSingleton();
		if (!mShaderGen)
		{
			bool check2x = mLayerNormalMappingEnabled || mLayerParallaxMappingEnabled;
			if (hmgr.isLanguageSupported("cg"))
            {
				mShaderGen = OGRE_NEW ShaderHelperCg();
            }
			else if (hmgr.isLanguageSupported("hlsl") &&
				((check2x && gmgr.isSyntaxSupported("ps_4_0")) ||
				(check2x && gmgr.isSyntaxSupported("ps_2_x")) ||
				(!check2x && gmgr.isSyntaxSupported("ps_2_0"))))
            {
				mShaderGen = OGRE_NEW ShaderHelperHLSL();
            }
			else if (hmgr.isLanguageSupported("glsl"))
            {
				mShaderGen = OGRE_NEW ShaderHelperGLSL();
            }
			else if (hmgr.isLanguageSupported("glsles"))
            {
				mShaderGen = OGRE_NEW ShaderHelperGLSLES();
            }
			
			// check SM3 features
			mSM3Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_3_0");
			mSM4Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0");
		}

		HighLevelGpuProgramPtr vprog = mShaderGen->generateVertexProgram(this, terrain, tt);
		HighLevelGpuProgramPtr fprog = mShaderGen->generateFragmentProgram(this, terrain, tt);

		pass->setVertexProgram(vprog->getName());
		pass->setFragmentProgram(fprog->getName());

		if (tt == HIGH_LOD || tt == RENDER_COMPOSITE_MAP)
		{
			// global normal map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getTerrainNormalMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

			// global colour map
			if (terrain->getGlobalColourMapEnabled() && isGlobalColourMapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getGlobalColourMap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}

			// light map
			if (isLightmapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getLightmap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}

			// blend maps
			uint maxLayers = getMaxLayers(terrain);
			uint numBlendTextures = std::min(terrain->getBlendTextureCount(maxLayers), terrain->getBlendTextureCount());
			uint numLayers = std::min(maxLayers, static_cast<uint>(terrain->getLayerCount()));
			for (uint i = 0; i < numBlendTextures; ++i)
			{
				tu = pass->createTextureUnitState(terrain->getBlendTextureName(i));
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}

			// layer textures
			for (uint i = 0; i < numLayers; ++i)
			{
				// diffuse / specular
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 0));
				// normal / height
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 1));
			}

		}
		else
		{
			// LOW_LOD textures
			// composite map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getCompositeMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

			// That's it!

		}

		// Add shadow textures (always at the end)
		if (isShadowingEnabled(tt, terrain))
		{
			uint numTextures = 1;
			if (getReceiveDynamicShadowsPSSM())
			{
				numTextures = (uint)getReceiveDynamicShadowsPSSM()->getSplitCount();
			}
			for (uint i = 0; i < numTextures; ++i)
			{
				TextureUnitState* tu = pass->createTextureUnitState();
				tu->setContentType(TextureUnitState::CONTENT_SHADOW);
				tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
				tu->setTextureBorderColour(ColourValue::White);
			}
		}

	}
Пример #14
0
///  Shadows config
//---------------------------------------------------------------------------------------------------
void App::changeShadows()
{	
	QTimer ti;  ti.update();  /// time
	
	//  get settings
	bool enabled = pSet->shadow_type != 0;
	bool bDepth = pSet->shadow_type == 3;
	
	pSet->shadow_size = std::max(0,std::min(ciShadowNumSizes-1, pSet->shadow_size));
	int fTex = /*2048*/ ciShadowSizesA[pSet->shadow_size], fTex2 = fTex/2;
	int num = /*3*/ pSet->shadow_count;
	
	// disable 4 shadow textures (does not work because no texcoord's left in shader)
	if (num == 4) num = 3;

	TerrainMaterialGeneratorB::SM2Profile* matProfile = 0;
	
	if (mTerrainGlobals)
	{
		matProfile = (TerrainMaterialGeneratorB::SM2Profile*) mTerrainGlobals->getDefaultMaterialGenerator()->getActiveProfile();
				
		matProfile->setReceiveDynamicShadowsEnabled(enabled);
		matProfile->setReceiveDynamicShadowsLowLod(true);
		matProfile->setGlobalColourMapEnabled(false);

		matProfile->setLayerSpecularMappingEnabled(pSet->ter_mtr >= 1);  // ter mtr
		matProfile->setLayerNormalMappingEnabled(  pSet->ter_mtr >= 2);
		matProfile->setLayerParallaxMappingEnabled(pSet->ter_mtr >= 3);
	}
	
	//  shadows old-
	if (pSet->shadow_type == 1)
	{
		//mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE);
		mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE);
		//mSceneMgr->setShadowTextureCount(2);
		//mSceneMgr->setShadowTexturePixelFormat(PF_L8);
		//mSceneMgr->setShadowTextureCasterMaterial(StringUtil::BLANK);
		//mSceneMgr->setShadowTextureSelfShadow(true);
		mSceneMgr->setShadowCasterRenderBackFaces(true);

		mSceneMgr->setShadowTextureSettings(fTex, 1, PF_L8);
		mSceneMgr->setShadowColour(ColourValue(0.4, 0.4, 0.4));
		mSceneMgr->setShadowFarDistance(pSet->shadow_dist / 50.f);  // 36 72
		mSceneMgr->setShadowDirLightTextureOffset(0.5);
		//-ShadowCameraSetupPtr mShadowCameraSetup = ShadowCameraSetupPtr(new PlaneOptimalShadowCameraSetup(mPlane));
			ShadowCameraSetupPtr mShadowCameraSetup = ShadowCameraSetupPtr(new LiSPSMShadowCameraSetup());
			mSceneMgr->setShadowCameraSetup(mShadowCameraSetup);/**/
		mSceneMgr->setShadowTextureCountPerLightType(Light::LT_DIRECTIONAL, 1);
		mSceneMgr->setShadowTextureCount(1);
		//return;  // !
	}


	if (!enabled)  {
		mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);  /*return;*/ }

	else
	{
		// General scene setup
		//mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED);
		mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED);
		mSceneMgr->setShadowFarDistance(pSet->shadow_dist);  // 3000
		mSceneMgr->setShadowTextureCountPerLightType(Light::LT_DIRECTIONAL, num);

		if (mPSSMSetup.isNull())
		{
			// shadow camera setup
			PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup();
			#ifndef ROAD_EDITOR
			pssmSetup->setSplitPadding(mSplitMgr->mCameras.front()->getNearClipDistance());
			//pssmSetup->setSplitPadding(10);
			pssmSetup->calculateSplitPoints(num, mSplitMgr->mCameras.front()->getNearClipDistance(), mSceneMgr->getShadowFarDistance());
			#else
			pssmSetup->setSplitPadding(mCamera->getNearClipDistance());
			//pssmSetup->setSplitPadding(10);
			pssmSetup->calculateSplitPoints(num, mCamera->getNearClipDistance(), mSceneMgr->getShadowFarDistance());
			#endif
			for (int i=0; i < num; ++i)
			{	int size = i==0 ? fTex : fTex2;
				const Real cAdjfA[5] = {2, 1, 0.5, 0.25, 0.125};
				pssmSetup->setOptimalAdjustFactor(i, cAdjfA[std::min(i, 4)]);
			}
			mPSSMSetup.bind(pssmSetup);
		}
		mSceneMgr->setShadowCameraSetup(mPSSMSetup);

		mSceneMgr->setShadowTextureCount(num);
		for (int i=0; i < num; ++i)
		{	int size = i==0 ? fTex : fTex2;
			mSceneMgr->setShadowTextureConfig(i, size, size, bDepth ? PF_FLOAT32_R : PF_X8B8G8R8);
		}
		
		mSceneMgr->setShadowTextureSelfShadow(bDepth ? true : false);  //-?
		mSceneMgr->setShadowCasterRenderBackFaces(bDepth ? true : false);
		mSceneMgr->setShadowTextureCasterMaterial(bDepth ? "PSSM/shadow_caster" : StringUtil::BLANK);

		if (matProfile && terrain)  {
			matProfile->setReceiveDynamicShadowsDepth(bDepth);
			matProfile->setReceiveDynamicShadowsPSSM(static_cast<PSSMShadowCameraSetup*>(mPSSMSetup.get()));
			MaterialPtr mtr = matProfile->generateForCompositeMap(terrain);
			//LogO(mtr->getBestTechnique()->getPass(0)->getTextureUnitState(0)->getName());
			//LogO(String("Ter mtr: ") + mtr->getName());

		}
		
		#if 0	// shadow tex overlay
		// add the overlay elements to show the shadow maps:
		// init overlay elements
		OverlayManager& mgr = OverlayManager::getSingleton();
		Overlay* overlay;
		
		// destroy if already exists
		if (overlay = mgr.getByName("DebugOverlay"))
			mgr.destroy(overlay);
			
		overlay = mgr.create("DebugOverlay");
		
		for (size_t i = 0; i < num; ++i) {
			TexturePtr tex = mSceneMgr->getShadowTexture(i);

			// Set up a debug panel to display the shadow
			
			if (MaterialManager::getSingleton().resourceExists("Ogre/DebugTexture" + toStr(i)))
				MaterialManager::getSingleton().remove("Ogre/DebugTexture" + toStr(i));
			MaterialPtr debugMat = MaterialManager::getSingleton().create(
				"Ogre/DebugTexture" + toStr(i), 
				ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
				
			debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false);
			TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(tex->getName());
			t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

			OverlayContainer* debugPanel;
			
			// destroy container if exists
			try
			{
				if (debugPanel = 
					static_cast<OverlayContainer*>(
						mgr.getOverlayElement("Ogre/DebugTexPanel" + toStr(i)
					)))
					mgr.destroyOverlayElement(debugPanel);
			}
			catch (Ogre::Exception&) {}
			
			debugPanel = (OverlayContainer*)
				(OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + StringConverter::toString(i)));
			debugPanel->_setPosition(0.8, i*0.25);
			debugPanel->_setDimensions(0.2, 0.24);
			debugPanel->setMaterialName(debugMat->getName());
			debugPanel->show();
			overlay->add2D(debugPanel);
			overlay->show();
		}
		#endif
	}
	
	materialFactory->setNumShadowTex(num);
	materialFactory->setShadows(pSet->shadow_type != 0);
	materialFactory->setShadowsDepth(bDepth);
	materialFactory->generate();
	
	// set terrain lightmap texture and terrainWorldSize for all materials that need it
	if (terrain) // naive check if a game has been started already
	{
		for (std::vector<std::string>::const_iterator it = materialFactory->terrainLightMapMtrs.begin();
			it != materialFactory->terrainLightMapMtrs.end(); ++it)
		{
			MaterialPtr mtr = MaterialManager::getSingleton().getByName( (*it) );
			
			if (!mtr.isNull())
			{	Material::TechniqueIterator techIt = mtr->getTechniqueIterator();
				while (techIt.hasMoreElements())
				{	Technique* tech = techIt.getNext();
					Technique::PassIterator passIt = tech->getPassIterator();
					while (passIt.hasMoreElements())
					{	Pass* pass = passIt.getNext();
						Pass::TextureUnitStateIterator tusIt = pass->getTextureUnitStateIterator();
						while (tusIt.hasMoreElements())
						{
							TextureUnitState* tus = tusIt.getNext();
							if (tus->getName() == "terrainLightMap")
							{
								tus->setTextureName( terrain->getLightmap()->getName() );
								pass->getFragmentProgramParameters()->setNamedConstant( "terrainWorldSize", Real( sc.td.fTerWorldSize ) );
							}
						}
			}	}	}
		}
	}
	
	// -------------------   update the paged-geom materials
	
	// grass is not cloned, just need to set new shader parameters
	if (grass)
	{
		GrassLoader *grassLoader = static_cast<GrassLoader*>(grass->getPageLoader());
		for (std::list<GrassLayer*>::iterator it= grassLoader->getLayerList().begin();
			it != grassLoader->getLayerList().end(); ++it)
		{
			GrassLayer* layer = (*it);
			layer->applyShader();
		}
	}
	
	// trees are more complicated since they are cloned
	if(trees)
	{
		trees->reloadGeometry();
		std::vector<ResourcePtr> reosurceToDelete;
		ResourceManager::ResourceMapIterator it = MaterialManager::getSingleton().getResourceIterator();
		while (it.hasMoreElements())
		{
			ResourcePtr material = it.getNext();
			String materialName = material->getName();
			std::string::size_type pos =materialName.find("BatchMat|");
			if( pos != std::string::npos ) {
				reosurceToDelete.push_back(material);
			}
		}
		for(int i=0;i<reosurceToDelete.size();i++)
		{
			MaterialManager::getSingleton().remove(reosurceToDelete[i]);
		}
	}
	UpdPSSMMaterials();

	ti.update();	/// time
	float dt = ti.dt * 1000.f;
	LogO(String("::: Time Shadows: ") + toStr(dt) + " ms");
}
Пример #15
0
void CarReflection::Create()
{
	bFirstFrame = true;
	if (pSet->refl_mode == "single")  cubetexName = "ReflectionCube"; // single: use 1st cubemap
	else if (pSet->refl_mode == "full")
	{
		cubetexName = "ReflectionCube" + toStr(iIndex);
		// first cubemap: no index
		if (cubetexName == "ReflectionCube0")
			cubetexName = "ReflectionCube";
	}
	else /* static */
		cubetexName = "ReflectionCube";
	
	TextureManager* tm = TextureManager::getSingletonPtr();
	int size = ciShadowSizesA[pSet->refl_size];  // /2 ?

	//  create cube render texture
	if (! (pSet->refl_mode == "single" && iIndex != 0) )
	{
		cubetex = tm->createManual(cubetexName, 
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_CUBE_MAP, 
			size,size, 0/*mips*/, PF_R8G8B8, TU_RENDERTARGET);
			//LogO("created rt cube");

		for (int face = 0; face < 6; face++)
		{
			Camera* mCam = pSceneMgr->createCamera("Reflect_" + toStr(iIndex) + "_" + toStr(face));
			mCam->setAspectRatio(1.0f);  mCam->setFOVy(Degree(90));
			mCam->setNearClipDistance(0.1);
			//mCam->setFarClipDistance(pSet->refl_dist);  //sky-

			RenderTarget* mRT = cubetex->getBuffer(face)->getRenderTarget();
			//LogO( "rt face Name: " + mRT->getName() );
			mRT->removeAllViewports();
			Viewport* vp = mRT->addViewport(mCam);
			vp->setOverlaysEnabled(false);
			vp->setVisibilityMask(RV_MaskReflect);
			mRT->setAutoUpdated(false);
			//mRT->addListener(this);  //-
			mCam->setPosition(Vector3::ZERO);

			Vector3 lookAt(0,0,0), up(0,0,0), right(0,0,0);  switch(face)
			{
				case 0:  lookAt.x =-1;  up.y = 1;  right.z = 1;  break;  // +X
				case 1:  lookAt.x = 1;  up.y = 1;  right.z =-1;  break;	 // -X
				case 2:  lookAt.y =-1;  up.z = 1;  right.x = 1;  break;	 // +Y
				case 3:  lookAt.y = 1;  up.z =-1;  right.x = 1;  break;	 // -Y
				case 4:  lookAt.z = 1;  up.y = 1;  right.x =-1;  break;	 // +Z
				case 5:  lookAt.z =-1;  up.y = 1;  right.x =-1;  break;	 // -Z
			}
			Quaternion orient( right, up, lookAt );  mCam->setOrientation( orient );
			pCams[face] = mCam;
			pRTs[face] = mRT;
		}
	}
	
	// Iterate through our materials and add an index to ReflectionCube texture reference
	for (int i=0; i < NumMaterials; i++)
	{
		MaterialPtr mtr = MaterialManager::getSingleton().getByName(sMtr[i]);
		if (!mtr.isNull())
		{	Material::TechniqueIterator techIt = mtr->getTechniqueIterator();
			while (techIt.hasMoreElements())
			{	Technique* tech = techIt.getNext();
				Technique::PassIterator passIt = tech->getPassIterator();
				while (passIt.hasMoreElements())
				{	Pass* pass = passIt.getNext();
					Pass::TextureUnitStateIterator tusIt = pass->getTextureUnitStateIterator();
					while (tusIt.hasMoreElements())
					{	
						TextureUnitState* tus = tusIt.getNext();
						if (tus->getTextureName() == "ReflectionCube")
							tus->setTextureName(cubetexName);
	}	}	}	}	}
}
Пример #16
0
void MaterialFactory::setShaderParams(MaterialPtr mat)
{
	if (mat.isNull()) return;
		
	Material::TechniqueIterator techIt = mat->getTechniqueIterator();
	while (techIt.hasMoreElements())
	{
		Technique* tech = techIt.getNext();
		Technique::PassIterator passIt = tech->getPassIterator();
		while (passIt.hasMoreElements())
		{
			Pass* pass = passIt.getNext();
								
			if (pass->hasFragmentProgram())
			{
				// shadow fading parameters
				if ( getShadowsFade()
					&& pass->getFragmentProgramParameters()->_findNamedConstantDefinition("fadeStart_farDist", false)
					&& mSceneMgr
				)
				{
					float fadeDist;
					if (mSceneMgr->getShadowFarDistance() != 0)
						fadeDist = getShadowsFadeDistance()/mSceneMgr->getShadowFarDistance();
					else
						fadeDist = 0.f;
														
					pass->getFragmentProgramParameters()->setNamedConstant("fadeStart_farDist", Vector3(
						fadeDist,
						mSceneMgr->getShadowFarDistance(),
						float(getShadowsFade())
					));
				}
				// terrain lightmap name & size
				if ( mTerrain && !mTerrain->getLightmap().isNull() )
				{
					if (pass->getFragmentProgramParameters()->_findNamedConstantDefinition("terrainWorldSize", false))
						pass->getFragmentProgramParameters()->setNamedConstant( "terrainWorldSize", Real( mTerrain->getWorldSize() ) );
					
					Pass::TextureUnitStateIterator tusIt = pass->getTextureUnitStateIterator();
					while (tusIt.hasMoreElements())
					{
						TextureUnitState* tus = tusIt.getNext();
						if (tus->getName() == "terrainLightMap")
						{
							tus->setTextureName( mTerrain->getLightmap()->getName() );
						}
					}
				}
				
				if (pass->getFragmentProgramParameters()->_findNamedConstantDefinition("invTerSize", false))
					pass->getFragmentProgramParameters()->setNamedConstant("invTerSize", 1.f / Real(pApp->sc.td.fTerWorldSize));

				// pssm split points
				if ( pass->getFragmentProgramParameters()->_findNamedConstantDefinition("pssmSplitPoints", false) && mPSSM)
				{
					const PSSMShadowCameraSetup::SplitPointList& splitPointList = mPSSM->getSplitPoints();
					Vector4 splitPoints;
					for (size_t i = 0; i < splitPointList.size(); ++i)
						splitPoints[i] = splitPointList[i];
						
					pass->getFragmentProgramParameters()->setNamedConstant("pssmSplitPoints", splitPoints);
				}
			}
		}
	}
}