protected void BuildMaterial() { // If the highlight type changes, we need to use a different shader, so we load a // different material to go with it. if (typeChange) { if (material != null) { //LogManager.Instance.Write("Free Material: {0}", material.Name); MaterialManager.Instance.Unload(material); material.Dispose(); material = null; } materialName = String.Format("AutoSplat-{0}-{1}-{2}", pageX, pageZ, HighlightTypeString); //LogManager.Instance.Write("Create Material: {0}", materialName); Material tmpMaterial = MaterialManager.Instance.GetByName(HighlightMaterialName(highlightType)); if (tmpMaterial != null) { material = tmpMaterial.Clone(materialName); } typeChange = false; } if (material == null) { return; } Technique tech = material.GetTechnique(0); material.Load(); // Only do this stuff if we are using technique 0. Otherwise we are using the // fixed function fallback technique, so we don't want to do any shader stuff. if (tech.IsSupported) { // set the highlight mask texture int size = TerrainManager.Instance.PageSize; tech.GetPass(0).VertexProgramParameters.SetNamedConstant("pageSize", new Vector3(size * TerrainManager.oneMeter, size * TerrainManager.oneMeter, size * TerrainManager.oneMeter)); if (highlightType != TerrainPage.PageHilightType.None) { tech.GetPass(0).GetTextureUnitState(5).SetTextureName(highlightMask.Name); } //Page.SetShadeMask(hilightMaterial, 4); config.UpdateMaterial(material); } material.Load(); material.Lighting = true; dirty = false; }
private string BuildInstancedMaterial(string originalMaterialName) { // already instanced ? if (originalMaterialName.EndsWith("/instanced")) { return(originalMaterialName); } var originalMaterial = (Material)MaterialManager.Instance.GetByName(originalMaterialName); // if originalMat doesn't exists use "Instancing" material name string instancedMaterialName = (null == originalMaterial ? "Instancing" : originalMaterialName + "/Instanced"); var instancedMaterial = (Material)MaterialManager.Instance.GetByName(instancedMaterialName); // already exists ? if (null == instancedMaterial) { instancedMaterial = originalMaterial.Clone(instancedMaterialName); instancedMaterial.Load(); Technique t = instancedMaterial.GetBestTechnique(); for (int pItr = 0; pItr < t.PassCount; pItr++) { Pass p = t.GetPass(pItr); p.SetVertexProgram("Instancing", false); p.SetShadowCasterVertexProgram("InstancingShadowCaster"); } } instancedMaterial.Load(); return(instancedMaterialName); }
public override void Build() { mBatch.Build(); foreach (BatchedGeometry.SubBatch it in mBatch.SubBatches.Values) { BatchedGeometry.SubBatch subBatch = it; Material mat = subBatch.Material; //Disable specular unless a custom shader is being used. //This is done because the default shader applied by BatchPage //doesn't support specular, and fixed-function needs to look //the same as the shader (for computers with no shader support) for (int t = 0; t < mat.TechniqueCount; t++) { Technique tech = mat.GetTechnique(t); for (int p = 0; p < tech.PassCount; p++) { Pass pass = tech.GetPass(p); if (pass.VertexProgramName == "") { pass.Specular = new ColorEx(1, 0, 0, 0); } } } //store the original materials mUnfadedMaterials.Add(mat); } UpdateShaders(); }
private bool InitTextures(Application application, PixelFormat format, int width, int height) { bgTexture.Create(application, format, width, height, 0); uvTexture.Create(application, format, width, height, 1); vTexture.Create(application, format, width, height, 2); string shaderName = GetShaderName(format); // Update the material Technique technique = application.ResourceCache.GetTechnique("Techniques/Diff.xml"); for (uint i = 0; i < technique.NumPasses; i++) { Pass pass = technique.GetPass(i); if (pass != null) { pass.VertexShader = shaderName; pass.PixelShader = shaderName; } } Material.SetTechnique(0, technique); bgTexture.SetNameIfValid(Material, TextureUnit.Diffuse); uvTexture.SetNameIfValid(Material, TextureUnit.Normal); vTexture.SetNameIfValid(Material, TextureUnit.Specular); Material.CullMode = CullMode.None; this.initializedFormat = format; this.initializedWidth = width; this.initializedHeight = height; return(true); }
protected override void CreateScene() { mSceneMgr.AmbientLight = new ColourValue(1, 1, 1); //Entity ent = mSceneMgr.CreateEntity("Head", "ogrehead.mesh"); //SceneNode node = mSceneMgr.RootSceneNode.CreateChildSceneNode("HeadNode"); //node.AttachObject(ent); MaterialPtr mat = MaterialManager.Singleton.Create("BoxColor", "General", true); Technique tech = mat.GetTechnique(0); Pass pass = tech.GetPass(0); TextureUnitState tex = pass.CreateTextureUnitState(); tex.SetTextureName("sphax.jpg", TextureType.TEX_TYPE_2D); tex.NumMipmaps = 0; tex.TextureAnisotropy = 0; tex.SetTextureFiltering(FilterOptions.FO_POINT, FilterOptions.FO_POINT, FilterOptions.FO_POINT); //pass.DepthWriteEnabled=false; //pass.SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA); //pass.CullingMode = CullingMode.CULL_NONE; //mCamMan = new Tutorials.CameraMan(mCamera,mc); //mCameraMan = null; mCamera.SetPosition((float)mc.x, (float)mc.y, (float)mc.z); mCamera.Pitch(new Degree(mc.pitch).ValueRadians); mCamera.Yaw(new Degree(mc.yaw).ValueRadians); oldCamPos = mCamera.Position; }
public override void CreateScene() { // Setup animation default Animation.DefaultInterpolationMode = Animation.InterpolationMode.IM_LINEAR; Animation.DefaultRotationInterpolationMode = Animation.RotationInterpolationMode.RIM_LINEAR; // Set ambient light sceneMgr.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f); Entity ent = null; int row = 0; int column = 0; Random rnd = new Random(); for (int i = 0; i < NUM_ROBOTS; ++i, ++column) { if (column > ROW_COUNT) { ++row; column = 0; } ent = sceneMgr.CreateEntity("robot" + i, "robot.mesh"); sceneMgr.RootSceneNode.CreateChildSceneNode( new Vector3(-(row * 100), 0, (column * 50))).AttachObject(ent); _animState[i] = ent.GetAnimationState("Walk"); _animState[i].Enabled = true; _animationSpeed[i] = (float)(rnd.NextDouble() + 0.5); } // Give it a little ambience with lights Light l = null; l = sceneMgr.CreateLight("BlueLight"); l.SetPosition(-200, -80, -100); l.SetDiffuseColour(0.5f, 0.5f, 1.0f); l = sceneMgr.CreateLight("GreenLight"); l.SetPosition(0, 0, -100); l.SetDiffuseColour(0.5f, 1.0f, 0.5f); // Position the camera camera.SetPosition(100, 50, 100); camera.LookAt(-50, 50, 0); // Report whether hardware skinning is enabled or not Technique te = ent.GetSubEntity(0).GetMaterial().GetBestTechnique(); Pass p = te.GetPass(0); if (p.HasVertexProgram && p.GetVertexProgram().IsSkeletalAnimationIncluded) { mDebugText = "Hardware skinning is enabled"; } else { mDebugText = "Software skinning is enabled"; } }
/// <summary> /// /// </summary> /// <param name="visibleDist"></param> /// <param name="invisibleDist"></param> /// <returns></returns> private Material GetFadeMaterial(float visibleDist, float invisibleDist) { string materialSignature = string.Empty; materialSignature += mEntityName + "|"; materialSignature += visibleDist + "|"; materialSignature += invisibleDist + "|"; materialSignature += mMaterial.GetTechnique(0).GetPass(0).GetTextureUnitState(0).TextureScrollU + "|"; materialSignature += mMaterial.GetTechnique(0).GetPass(0).GetTextureUnitState(0).TextureScrollV + "|"; Material fadeMaterial = null; if (!mFadedMaterialMap.TryGetValue(materialSignature, out fadeMaterial)) { //clone the material fadeMaterial = mMaterial.Clone(GetUniqueID("ImpostorFade")); //And apply the fade shader for (int t = 0; t < fadeMaterial.TechniqueCount; t++) { Technique tech = fadeMaterial.GetTechnique(t); for (int p = 0; p < tech.PassCount; p++) { Pass pass = tech.GetPass(p); //Setup vertex program pass.SetVertexProgram("SpriteFade_vp"); GpuProgramParameters gparams = pass.VertexProgramParameters; gparams.SetNamedAutoConstant("worldViewProj", GpuProgramParameters.AutoConstantType.WorldViewProjMatrix, 0); gparams.SetNamedAutoConstant("uScroll", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("vScroll", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("preRotatedQuad[0]", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("preRotatedQuad[1]", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("preRotatedQuad[2]", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("preRotatedQuad[3]", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("camPos", GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace, 0); gparams.SetNamedAutoConstant("fadeGap", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedAutoConstant("invisibleDist", GpuProgramParameters.AutoConstantType.Custom, 0); //Set fade ranges gparams.SetNamedConstant("invisibleDist", invisibleDist); gparams.SetNamedConstant("fadeGap", invisibleDist - visibleDist); pass.SetSceneBlending(SceneBlendType.TransparentAlpha); } } //Add it to the list so it can be reused later mFadedMaterialMap.Add(materialSignature, fadeMaterial); } return(fadeMaterial); }
public static void setEntityOpacity(Entity ent, float val) { for (uint x = 0; x < ent.NumSubEntities; x++) { Mogre.MaterialPtr mat = ent.GetSubEntity(x).GetMaterial(); Technique t = mat.GetTechnique(0); // we are only bothering the fade with the first technique. //t.SetSceneBlending(SceneBlendFactor.SBF_DEST_ALPHA, SceneBlendFactor.SBF_ONE_MINUS_DEST_COLOUR); //sweet color invert effect t.SetSceneBlending(SceneBlendFactor.SBF_DEST_ALPHA, SceneBlendFactor.SBF_SOURCE_ALPHA); //works t.SetDepthWriteEnabled(false); t.SetSelfIllumination(ColourValue.Green); t.SetAmbient(ColourValue.Green); // iterate through passes and textureUnitStates, setting their opacity. for (ushort p = 0; p < t.NumPasses; p++) { for (ushort s = 0; s < t.GetPass(p).NumTextureUnitStates; s++) { t.GetPass(p).GetTextureUnitState(s).SetAlphaOperation(LayerBlendOperationEx.LBX_MODULATE, LayerBlendSource.LBS_MANUAL, LayerBlendSource.LBS_CURRENT, val); } } mat.Dispose(); } }
protected override void CreateScene() { // set some ambient light scene.TargetRenderSystem.LightingEnabled = true; scene.AmbientLight = ColorEx.Gray; Entity entity = null; // create the robot entity for (int i = 0; i < NumRobots; i++) { string robotName = string.Format("Robot{0}", i); entity = scene.CreateEntity(robotName, "robot.mesh"); scene.RootSceneNode.CreateChildSceneNode( new Vector3(0, 0, (i * 50) - (NumRobots * 50 / 2))).AttachObject(entity); animState[i] = entity.GetAnimationState("Walk"); animState[i].IsEnabled = true; animationSpeed[i] = MathUtil.RangeRandom(0.5f, 1.5f); } Light light = scene.CreateLight("BlueLight"); light.Position = new Vector3(-200, -80, -100); light.Diffuse = new ColorEx(1.0f, .5f, .5f, 1.0f); //light = scene.CreateLight("GreenLight"); //light.Position = new Vector3(0, 0, -100); //light.Diffuse = new ColorEx(1.0f, 0.5f, 1.0f, 0.5f); // setup the camera for a nice view of the robot camera.Position = new Vector3(100, 50, 100); camera.LookAt(new Vector3(0, 50, 0)); Technique t = entity.GetSubEntity(0).Material.GetBestTechnique(); Pass p = t.GetPass(0); if (p.HasVertexProgram && p.VertexProgram.IsSkeletalAnimationIncluded) { window.DebugText = "Hardware skinning is enabled."; } else { window.DebugText = "Software skinning is enabled."; } }
protected void BuildMaterial() { // If the highlight type changes, we need to use a different shader, so we load a // different material to go with it. if (typeChange) { if (material != null) { //LogManager.Instance.Write("Free Material: {0}", material.Name); MaterialManager.Instance.Unload(material); material.Dispose(); material = null; } materialName = String.Format("AlphaSplat-{0}-{1}-{2}", pageX, pageZ, HighlightTypeString); //LogManager.Instance.Write("Create Material: {0}", materialName); Material tmpMaterial = MaterialManager.Instance.GetByName(HighlightMaterialName(highlightType)); material = tmpMaterial.Clone(materialName); typeChange = false; } Technique tech = material.GetTechnique(0); material.Load(); if (tech.IsSupported) { Pass pass = tech.GetPass(0); // set the highlight mask texture int size = TerrainManager.Instance.PageSize; pass.VertexProgramParameters.SetNamedConstant("pageSize", new Vector3(size * TerrainManager.oneMeter, size * TerrainManager.oneMeter, size * TerrainManager.oneMeter)); if (highlightType != TerrainPage.PageHilightType.None) { pass.GetTextureUnitState(11).SetTextureName(highlightMask.Name); } //Page.SetShadeMask(hilightMaterial, 4); int pageSize = TerrainManager.Instance.PageSize; for (int index = 0; index < AlphaSplatTerrainConfig.NUM_ALPHA_MAPS; index++) { TextureMosaic alphaMap = config.GetAlphaMap(index); if (alphaMap != null) { // pass in the alpha texture names and the texture coord adjustment params. // The coord adjustment params are used to convert from a page relative texture // coordinate to the appropriate coords for the alpha texture. float u1, u2, v1, v2; string alphaTextureName = alphaMap.GetTexture( pageX * pageSize, pageZ * pageSize, pageSize, pageSize, out u1, out v1, out u2, out v2); pass.GetTextureUnitState(index).SetTextureName(alphaTextureName); string coordAdjustParam = "alpha" + index + "TextureCoordAdjust"; pass.VertexProgramParameters.SetNamedConstant( coordAdjustParam, new Vector4(u1, u2 - u1, v1, v2 - v1)); //todo: Disabled page logging because it slows down terrain edits // in the terrain editor. We should probably make this // logging be conditional. -Trev 9/4/08 // LogManager.Instance.Write("page[{0},{1}]: {2} : ({3},{4}) : ({5},{6})", pageX, pageZ, // alphaTextureName, u1, v1, u2, v2); } } } config.UpdateMaterial(material); material.Load(); material.Lighting = true; dirty = false; }
/// <see cref="Translator.Translate"/> public override void Translate(ScriptCompiler compiler, AbstractNode node) { throw new NotImplementedException(); #if UNREACHABLE_CODE ObjectAbstractNode obj = (ObjectAbstractNode)node; // It has to have one value identifying the texture source name if (obj.Values.Count == 0) { compiler.AddError(CompileErrorCode.StringExpected, node.File, node.Line, "texture_source requires a type value"); return; } // Set the value of the source //TODO: ExternalTextureSourceManager::getSingleton().setCurrentPlugIn(obj->values.front()->getValue()); // Set up the technique, pass, and texunit levels if (true /*TODO: ExternalTextureSourceManager::getSingleton().getCurrentPlugIn() != 0*/) { TextureUnitState texunit = (TextureUnitState)obj.Parent.Context; Pass pass = texunit.Parent; Technique technique = pass.Parent; Material material = technique.Parent; ushort techniqueIndex = 0, passIndex = 0, texUnitIndex = 0; for (ushort i = 0; i < material.TechniqueCount; i++) { if (material.GetTechnique(i) == technique) { techniqueIndex = i; break; } } for (ushort i = 0; i < technique.PassCount; i++) { if (technique.GetPass(i) == pass) { passIndex = i; break; } } for (ushort i = 0; i < pass.TextureUnitStageCount; i++) { if (pass.GetTextureUnitState(i) == texunit) { texUnitIndex = i; break; } } string tps = string.Format("{0} {1} {2}", techniqueIndex, passIndex, texUnitIndex); //TODO: ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()->setParameter( "set_T_P_S", tps ); foreach (AbstractNode i in obj.Children) { if (i is PropertyAbstractNode) { PropertyAbstractNode prop = (PropertyAbstractNode)i; // Glob the property values all together string str = string.Empty; foreach (AbstractNode j in prop.Values) { if (j != prop.Values[0]) { str += " "; } str = str + j.Value; } //TODO: ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()->setParameter(prop->name, str); } else if (i is ObjectAbstractNode) { _processNode(compiler, i); } } //TODO: ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()->createDefinedTexture(material->getName(), material->getGroup()); } #endif }
/// <summary> /// /// </summary> /// <param name="pageNum"></param> protected void ChangePage(int pageNum) { if (this.materialControlsContainer.Count == 0) { return; } this.currentPage = (pageNum == -1) ? (this.currentPage + 1) % this.numPages : pageNum; string pageText = string.Format("Parameters {0} / {1}", this.currentPage + 1, this.numPages); ((Button)TrayManager.GetWidget("PageButtonControl")).Caption = pageText; if (this.activeMaterial != null && this.activeMaterial.SupportedTechniques.Count > 0) { Technique currentTechnique = this.activeMaterial.SupportedTechniques[0]; if (currentTechnique != null) { this.activePass = currentTechnique.GetPass(0); if (this.activePass != null) { if (this.activePass.HasFragmentProgram) { this.activeFragmentProgram = this.activePass.FragmentProgram; this.activeFragmentParameters = this.activePass.FragmentProgramParameters; } if (this.activePass.HasVertexProgram) { this.activeVertexProgram = this.activePass.VertexProgram; this.activeVertexParameters = this.activePass.VertexProgramParameters; } int activeControlCount = this.materialControlsContainer[this.currentMaterial].ShaderControlsCount; int startControlIndex = this.currentPage * ControlsPerPage; int numControls = activeControlCount - startControlIndex; if (numControls <= 0) { this.currentPage = 0; startControlIndex = 0; numControls = activeControlCount; } for (int i = 0; i < ControlsPerPage; i++) { Slider shaderControlSlider = this.shaderControls[i]; if (i < numControls) { shaderControlSlider.Show(); int controlIndex = startControlIndex + i; ShaderControl activeShaderDef = this.materialControlsContainer[this.currentMaterial].GetShaderControl(controlIndex); shaderControlSlider.SetRange(activeShaderDef.MinVal, activeShaderDef.MaxVal, 50, false); shaderControlSlider.Caption = activeShaderDef.Name; shaderControlSlider.SliderMoved += new SliderMovedHandler(shaderControlSlider_SliderMoved); float uniformVal = 0.0f; switch (activeShaderDef.Type) { case ShaderType.GpuVertex: case ShaderType.GpuFragment: { GpuProgramParameters activeParameters = (activeShaderDef.Type == ShaderType.GpuVertex) ? this.activeVertexParameters : this.activeFragmentParameters; if (activeParameters != null) { throw new NotImplementedException("Fix this"); //int idx = activeParameters.GetParamIndex( activeShaderDef.ParamName ); //activeShaderDef.PhysicalIndex = idx; //uniformVal = activeParameters.GetNamedFloatConstant( activeShaderDef.ParamName ).val[ activeShaderDef.ElementIndex ]; } } break; case ShaderType.MatSpecular: { // get the specular values from the material pass ColorEx oldSpec = this.activePass.Specular; int x = activeShaderDef.ElementIndex; uniformVal = x == 0 ? oldSpec.r : x == 1 ? oldSpec.g : x == 2 ? oldSpec.b : x == 3 ? oldSpec.a : 0; } break; case ShaderType.MatDiffuse: { // get the specular values from the material pass ColorEx oldSpec = this.activePass.Diffuse; int x = activeShaderDef.ElementIndex; uniformVal = x == 0 ? oldSpec.r : x == 1 ? oldSpec.g : x == 2 ? oldSpec.b : x == 3 ? oldSpec.a : 0; } break; case ShaderType.MatAmbient: { // get the specular values from the material pass ColorEx oldSpec = this.activePass.Ambient; int x = activeShaderDef.ElementIndex; uniformVal = x == 0 ? oldSpec.r : x == 1 ? oldSpec.g : x == 2 ? oldSpec.b : x == 3 ? oldSpec.a : 0; } break; case ShaderType.MatShininess: { // get the specular values from the material pass uniformVal = this.activePass.Shininess; } break; } shaderControlSlider.Value = uniformVal; } } } } } }
//------------------------------------------------------------------------- public void SetupTerrainMaterial() { if (string.IsNullOrEmpty(this.mCustomMaterialName)) { // define our own material Options.terrainMaterial = (Material)MaterialManager.Instance.GetByName(TERRAIN_MATERIAL_NAME); // Make unique terrain material name string s = mName + "/Terrain"; Options.terrainMaterial = (Material)MaterialManager.Instance.GetByName(s); if (null == Options.terrainMaterial) { Options.terrainMaterial = (Material)MaterialManager.Instance.Create(s, ResourceGroupManager.Instance.WorldResourceGroupName); } else { Options.terrainMaterial.GetTechnique(0).GetPass(0).RemoveAllTextureUnitStates(); } Pass pass = Options.terrainMaterial.GetTechnique(0).GetPass(0); if (this.mWorldTextureName != "") { pass.CreateTextureUnitState(this.mWorldTextureName, 0); } if (this.mDetailTextureName != "") { pass.CreateTextureUnitState(this.mDetailTextureName, 1); } Options.terrainMaterial.Lighting = Options.lit; if (Options.lodMorph && mPCZSM.TargetRenderSystem.Capabilities.HasCapability(Capabilities.VertexPrograms) && GpuProgramManager.Instance.GetByName("Terrain/VertexMorph") == null) { // Create & assign LOD morphing vertex program String syntax; if (GpuProgramManager.Instance.IsSyntaxSupported("arbvp1")) { syntax = "arbvp1"; } else { syntax = "vs_1_1"; } // Get source, and take into account current fog mode FogMode fm = mPCZSM.FogMode; string source = new TerrainVertexProgram().getProgramSource(fm, syntax, false); GpuProgram prog = GpuProgramManager.Instance.CreateProgramFromString("Terrain/VertexMorph", ResourceGroupManager.Instance. WorldResourceGroupName, source, GpuProgramType.Vertex, syntax); // Attach pass.SetVertexProgram("Terrain/VertexMorph"); // Get params GpuProgramParameters paras = pass.VertexProgramParameters; // worldviewproj paras.SetAutoConstant(0, GpuProgramParameters.AutoConstantType.WorldViewProjMatrix); // morph factor paras.SetAutoConstant(4, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); // fog exp density(if relevant) if (fm == FogMode.Exp || fm == FogMode.Exp2) { paras.SetConstant(5, new Vector3(mPCZSM.FogDensity, 0, 0)); // Override scene fog since otherwise it's applied twice // Set to linear and we derive [0,1] fog value in the shader pass.SetFog(true, FogMode.Linear, mPCZSM.FogColor, 0, 1, 0); } // Also set shadow receiver program string source2 = new TerrainVertexProgram().getProgramSource(fm, syntax, true); prog = GpuProgramManager.Instance.CreateProgramFromString("Terrain/VertexMorphShadowReceive", ResourceGroupManager.Instance.WorldResourceGroupName, source2, GpuProgramType.Vertex, syntax); pass.SetShadowReceiverVertexProgram("Terrain/VertexMorphShadowReceive"); paras = pass.ShadowReceiverVertexProgramParameters; // worldviewproj paras.SetAutoConstant(0, GpuProgramParameters.AutoConstantType.WorldViewProjMatrix); // world paras.SetAutoConstant(4, GpuProgramParameters.AutoConstantType.WorldMatrix); // texture view / proj paras.SetAutoConstant(8, GpuProgramParameters.AutoConstantType.TextureViewProjMatrix); // morph factor paras.SetAutoConstant(12, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); // Set param index this.mLodMorphParamName = ""; this.mLodMorphParamIndex = 4; } Options.terrainMaterial.Load(); } else { // Custom material Options.terrainMaterial = (Material)MaterialManager.Instance.GetByName(this.mCustomMaterialName); Options.terrainMaterial.Load(); } // now set up the linkage between vertex program and LOD morph param if (Options.lodMorph) { Technique t = Options.terrainMaterial.GetBestTechnique(); for (ushort i = 0; i < t.PassCount; ++i) { Pass p = t.GetPass(i); if (p.HasVertexProgram) { // we have to assume vertex program includes LOD morph capability GpuProgramParameters paras = p.VertexProgramParameters; // Check to see if custom param is already there //GpuProgramParameters::AutoConstantIterator aci = params->getAutoConstantIterator(); bool found = false; foreach (GpuProgramParameters.AutoConstantEntry ace in paras.AutoConstantList) { if (ace.Type == GpuProgramParameters.AutoConstantType.Custom && ace.Data == TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID) { found = true; break; } } if (!found) { if (this.mLodMorphParamName != "") { paras.SetNamedAutoConstant(this.mLodMorphParamName, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); } else { paras.SetAutoConstant(this.mLodMorphParamIndex, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); } } } } } }
// Returns the number of geometry buckets public int Build(bool stencilShadows, bool logDetails) { int bucketCount = 0; // Create a node node = sceneMgr.RootSceneNode.CreateChildSceneNode(name, center); node.AttachObject(this); // We need to create enough LOD buckets to deal with the highest LOD // we encountered in all the meshes queued for (ushort lod = 0; lod < lodSquaredDistances.Count; ++lod) { LODBucket lodBucket = new LODBucket(this, lod, (float)lodSquaredDistances[lod]); lodBucketList.Add(lodBucket); // Now iterate over the meshes and assign to LODs // LOD bucket will pick the right LOD to use foreach (QueuedSubMesh qsm in queuedSubMeshes) { lodBucket.Assign(qsm, lod); } // now build bucketCount += lodBucket.Build(stencilShadows, logDetails); } // Do we need to build an edge list? if (stencilShadows) { EdgeListBuilder eb = new EdgeListBuilder(); foreach (LODBucket lod in lodBucketList) { foreach (MaterialBucket mat in lod.MaterialBucketMap.Values) { // Check if we have vertex programs here Technique t = mat.Material.GetBestTechnique(); if (null != t) { Pass p = t.GetPass(0); if (null != p) { if (p.HasVertexProgram) { vertexProgramInUse = true; } } } foreach (GeometryBucket geom in mat.GeometryBucketList) { bucketCount++; // Check we're dealing with 16-bit indexes here // Since stencil shadows can only deal with 16-bit // More than that and stencil is probably too CPU-heavy // in any case if (geom.IndexData.indexBuffer.Type != IndexType.Size16) { throw new AxiomException("Only 16-bit indexes allowed when using stencil shadows"); } eb.AddVertexData(geom.VertexData); eb.AddIndexData(geom.IndexData); } } } edgeList = eb.Build(); } return(bucketCount); }
/// <summary> /// /// </summary> private void UpdateShaders() { if (!mShadersSupported) { return; } int i = 0; foreach (BatchedGeometry.SubBatch it in mBatch.SubBatches.Values) { BatchedGeometry.SubBatch subBatch = it; Material mat = mUnfadedMaterials[i++]; //check ig lighting should be enabled bool lightningEnabled = false; for (int t = 0; t < mat.TechniqueCount; t++) { Technique tech = mat.GetTechnique(t); for (int p = 0; p < tech.PassCount; p++) { Pass pass = tech.GetPass(p); if (pass.LightingEnabled) { lightningEnabled = true; break; } if (lightningEnabled) { break; } } } //Compile the CG shader script based on various material / fade options string tmpName = string.Empty; tmpName += "BatchPage_"; if (mFadeEnabled) { tmpName += "fade_"; } if (lightningEnabled) { tmpName += "lit_"; } tmpName += "vp"; string vertexProgName = tmpName; //If the shader hasn't been created yet, create it if (HighLevelGpuProgramManager.Instance.GetByName(tmpName) == null) { string vertexProgSource = "void main( \n" + " float4 iPosition : POSITION, \n"+ " float3 normal : NORMAL, \n"+ " float2 iUV : TEXCOORD0, \n"+ " float4 iColor : COLOR, \n"+ " out float4 oPosition : POSITION, \n"+ " out float2 oUV : TEXCOORD0, \n"+ " out float4 oColor : COLOR, \n"+ " out float4 oFog : FOG, \n"; if (lightningEnabled) { vertexProgSource += " uniform float4 objSpaceLight, \n"+ " uniform float4 lightDiffuse, \n"+ " uniform float4 lightAmbient, \n"; } if (mFadeEnabled) { vertexProgSource += " uniform float3 camPos, \n"; } vertexProgSource += " uniform float4x4 worldViewProj, \n"+ " uniform float fadeGap, \n"+ " uniform float invisibleDist )\n" + "{ \n"; if (lightningEnabled) { vertexProgSource += //Perform lighting calculations (no specular) " float3 light = normalize(objSpaceLight.xyz - (iPosition.xyz * objSpaceLight.w)); \n"+ " float diffuseFactor = max(dot(normal, light), 0); \n"+ " oColor = (lightAmbient + diffuseFactor * lightDiffuse) * iColor; \n"; } else { vertexProgSource += " oColor = iColor; \n"; } if (mFadeEnabled) { vertexProgSource += //Fade out in the distance " float dist = distance(camPos.xz, iPosition.xz); \n"+ " oColor.a *= (invisibleDist - dist) / fadeGap; \n"; } vertexProgSource += " oUV = iUV; \n"+ " oPosition = mul(worldViewProj, iPosition); \n"+ " oFog.x = oPosition.z; \n"+ "}"; HighLevelGpuProgram vertexShader = HighLevelGpuProgramManager.Instance.CreateProgram( vertexProgName, ResourceGroupManager.DefaultResourceGroupName, "cg", GpuProgramType.Vertex); vertexShader.Source = vertexProgSource; vertexShader.SetParam("profiles", "vs_1_1 arbvp1"); vertexShader.SetParam("entry_point", "main"); vertexShader.Load(); } //Now that the shader is ready to be applied, apply it string materialSignature = string.Empty; materialSignature += "BatchMat|"; materialSignature += mat.Name + "|"; if (mFadeEnabled) { materialSignature += mVisibleDist + "|"; materialSignature += mInvisibleDist + "|"; } //Search for the desired material Material generatedMaterial = (Material)MaterialManager.Instance.GetByName(materialSignature); if (generatedMaterial == null) { //Clone the material generatedMaterial = mat.Clone(materialSignature); //And apply the fade shader for (int t = 0; t < generatedMaterial.TechniqueCount; t++) { Technique tech = generatedMaterial.GetTechnique(t); for (int p = 0; p < tech.PassCount; p++) { Pass pass = tech.GetPass(p); //Setup vertex program if (pass.VertexProgramName == "") { pass.VertexProgramName = vertexProgName; } try { GpuProgramParameters gparams = pass.VertexProgramParameters; if (lightningEnabled) { gparams.SetNamedAutoConstant("objSpaceLight", GpuProgramParameters.AutoConstantType.LightPositionObjectSpace, 0); gparams.SetNamedAutoConstant("lightDiffuse", GpuProgramParameters.AutoConstantType.LightDiffuseColor, 0); gparams.SetNamedAutoConstant("lightAmbient", GpuProgramParameters.AutoConstantType.AmbientLightColor, 0); } gparams.SetNamedAutoConstant("worldViewProj", GpuProgramParameters.AutoConstantType.WorldViewProjMatrix, 0); if (mFadeEnabled) { gparams.SetNamedAutoConstant("camPos", GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace, 0); //set fade ranges gparams.SetNamedAutoConstant("invisibleDist", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedConstant("invisibleDist", mInvisibleDist); gparams.SetNamedAutoConstant("fadeGap", GpuProgramParameters.AutoConstantType.Custom, 0); gparams.SetNamedConstant("fadeGap", mInvisibleDist - mVisibleDist); if (pass.AlphaRejectFunction == CompareFunction.AlwaysPass) { pass.SetSceneBlending(SceneBlendType.TransparentAlpha); } } } catch { throw new Exception("Error configuring batched geometry transitions." + "If you're using materials with custom vertex shaders, they will need to implement fade transitions to be compatible with BatchPage."); } } } } //Apply the material subBatch.Material = generatedMaterial; } }