Exemplo n.º 1
0
        private void PreparePass()
        {
            Technique technique = this.materialPtr.CreateTechnique();            ///UNDONE setShadowCasterMaterial

            this.Pass                   = technique.CreatePass();
            this.Pass.CullingMode       = CullingMode.CULL_NONE;
            this.Pass.DepthCheckEnabled = false;
            this.Pass.DepthWriteEnabled = false;
            this.Pass.LightingEnabled   = false;

            this.Pass.SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA);

            TextureUnitState tus = this.Pass.CreateTextureUnitState();

            tus.SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_WRAP);
        }
Exemplo n.º 2
0
        //创建场景
        private void CreateScene(int width, int height, string filename)
        {
            string planename = Guid.NewGuid().ToString("N");
            // 地面的法线方向。可以决定地面的朝向,
            Plane p;

            p.normal = Vector3.UNIT_Z;
            p.d      = 0;
            //判断地面模型是否已经创建,主要是处理新建场景后,关闭文档,在次打开时,模型已和纹理材质已创建,在次创建就会报错,在此做判断
            if (!MeshManager.Singleton.ResourceExists(planename))
            {
                //创建场景地面模型,通过指定的长和宽
                MeshManager.Singleton.CreatePlane(planename, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, p, width, height, 20, 20, true, 1, 1F, 1F, Vector3.UNIT_Y);
                //同上面
                if (!TextureManager.Singleton.ResourceExists(filename))
                {
                    //载入纹理
                    TexturePtr textureptr = TextureManager.Singleton.Load(filename, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);
                    //创建材质
                    MaterialPtr      materialptr = MaterialManager.Singleton.Load(filename, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);
                    TextureUnitState state       = materialptr.GetTechnique(0).GetPass(0).CreateTextureUnitState(filename);
                    //设置纹理的寻址模式,如果不设置。有可能在结边的时候出现缝隙
                    state.SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_MIRROR);
                    //材质相应设置,可参见API文档
                    materialptr.GetTechnique(0).GetPass(0).DepthWriteEnabled = false;
                    materialptr.GetTechnique(0).GetPass(0).DepthFunction     = CompareFunction.CMPF_LESS_EQUAL;
                }
            }
            EsdSceneManager.Singleton.MaterialPtr = MaterialManager.Singleton.GetByName(filename);
            Entity ent = EsdSceneManager.Singleton.SceneManager.CreateEntity("floor", planename);

            EsdSceneManager.Singleton.FloorNode = EsdSceneManager.Singleton.SceneManager.RootSceneNode.CreateChildSceneNode();
            EsdSceneManager.Singleton.FloorNode.AttachObject(ent);
            //设计材质
            ent.SetMaterialName(filename);
            //保存当前场景状态。
            EsdSceneManager.Singleton.ModelDataManage.modelEntry.场景地面图片 = filename;
            EsdSceneManager.Singleton.ModelDataManage.modelEntry.场景宽    = width;
            EsdSceneManager.Singleton.ModelDataManage.modelEntry.场景高    = height;
            EsdSceneManager.Singleton.ModelDataManage.modelEntry.模型名    = planename;

            //开始编辑标志
            EsdSceneManager.Singleton.IsStarEdit = true;
            EsdSceneManager.Singleton.OgreImage.UpdataCamera();
        }
Exemplo n.º 3
0
        public override bool PreAddToRenderState(TargetRenderState targetRenderState, Graphics.Pass srcPass,
                                                 Graphics.Pass dstPass)
        {
            if (srcPass.LightingEnabled == false || srcPass.Parent.Parent.ReceiveShadows == false)
            {
                return(false);
            }

            foreach (var it in this.shadowTextureParamsList)
            {
                TextureUnitState curShadowTexture = dstPass.CreateTextureUnitState();

                //TODO
                //curShadowTexture.ContentType = TextureUnitState.ContentShadow;
                curShadowTexture.SetTextureAddressingMode(TextureAddressing.Border);
                curShadowTexture.TextureBorderColor = Core.ColorEx.White;
                it.TextureSamplerIndex = dstPass.TextureUnitStatesCount - 1;
            }

            return(true);
        }
Exemplo n.º 4
0
        void CreateDefaultTechnique( out bool notSupported )
        {
            notSupported = false;

            string sourceFile = "Materials\\Common\\Water.cg_hlsl";

            string vertexSyntax;
            string fragmentSyntax;
            {
                if( RenderSystem.Instance.IsDirect3D() )
                {
                    if( RenderSystem.Instance.HasShaderModel3() )
                    {
                        vertexSyntax = "vs_3_0";
                        fragmentSyntax = "ps_3_0";
                    }
                    else
                    {
                        vertexSyntax = "vs_2_0";
                        fragmentSyntax = "ps_2_0";
                    }
                }
                else
                {
                    vertexSyntax = "arbvp1";
                    fragmentSyntax = "arbfp1";
                }
            }

            if( !RenderSystem.Instance.HasShaderModel2() ||
                !RenderSystem.Instance.Capabilities.UserClipPlanes )
            {
                notSupported = true;
                return;
            }

            BaseMaterial.ReceiveShadows = false;

            Technique tecnhique = BaseMaterial.CreateTechnique();
            Pass pass = tecnhique.CreatePass();

            //generate compileArguments and bind textures
            StringBuilder compileArguments = new StringBuilder( 128 );

            //transparent surface
            if( owner.DeepColor.Alpha != 1 || owner.ShallowColor.Alpha != 1 )
            {
                pass.SourceBlendFactor = SceneBlendFactor.SourceAlpha;
                pass.DestBlendFactor = SceneBlendFactor.OneMinusSourceAlpha;
                pass.DepthWrite = false;

                compileArguments.Append( " -DTRANSPARENT" );
            }

            //disable Direct3D standard fog features
            pass.SetFogOverride( FogMode.None, new ColorValue( 0, 0, 0 ), 0, 0, 0 );

            //bool direct3d = RenderSystem.Instance.Name.Contains( "Direct3D" );
            //compileArguments.Append( direct3d ? " -DDIRECT3D" : " -DOPENGL" );

            //Fog
            FogMode fogMode = SceneManager.Instance.GetFogMode();
            if( fogMode != FogMode.None )
            {
                compileArguments.Append( " -DFOG_ENABLED" );
                compileArguments.Append( " -DFOG_" + fogMode.ToString().ToUpper() );
            }

            //noiseMap
            {
                TextureUnitState state = pass.CreateTextureUnitState();
                state.SetTextureName( "Types\\Special\\WaterPlane\\WaterNoise.dds", Texture.Type.Type2D );
            }

            //reflectionMap
            if( owner.ReflectionLevel != WaterPlane.ReflectionLevels.None )
            {
                compileArguments.Append( " -DREFLECTION_MAP" );

                reflectionMapState = pass.CreateTextureUnitState();
                if( owner.ReflectionTexture != null )
                    reflectionMapState.SetTextureName( owner.ReflectionTexture.Name );
                reflectionMapState.SetTextureAddressingMode( TextureAddressingMode.Clamp );
                reflectionMapState.SetTextureFiltering( FilterOptions.Linear,
                    FilterOptions.Linear, FilterOptions.None );
            }

            //vertex program
            {
                string errorString;

                GpuProgram program = GpuProgramCacheManager.Instance.AddProgram(
                    "WaterPlane_Vertex_", GpuProgramType.VertexProgram, sourceFile,
                    "main_vp", vertexSyntax, compileArguments.ToString(), out errorString );

                if( !string.IsNullOrEmpty( errorString ) )
                    Log.Fatal( errorString );

                if( program != null )
                {
                    GpuProgramParameters parameters = program.DefaultParameters;
                    SetProgramAutoConstants( parameters );
                    pass.VertexProgramName = program.Name;
                }
            }

            //fragment program
            {
                string errorString;

                GpuProgram program = GpuProgramCacheManager.Instance.AddProgram(
                    "WaterPlane_Fragment_", GpuProgramType.FragmentProgram, sourceFile,
                    "main_fp", fragmentSyntax, compileArguments.ToString(), out errorString );

                if( !string.IsNullOrEmpty( errorString ) )
                    Log.Fatal( errorString );

                if( program != null )
                {
                    SetProgramAutoConstants( program.DefaultParameters );
                    pass.FragmentProgramName = program.Name;
                }
            }
        }
Exemplo n.º 5
0
        protected override void CreateScene()
        {
            mLog = LogManager.Singleton.createLog("RSQTest.log", false, true);
            mLog.LogMessage(string.Format("RSQTest log {0}", System.DateTime.Now));

            create4LineDebugOverLay();
            Show4LineDebugOverLay();

            //setup RenderTargetListenerDirector
            mRTListener = new RenderTargetListenerDirector();
            mRTListener.SubscribeEvents();
            mRTListener.evtPreRenderTargetUpdate  += new RenderTargetListenerDirector.RTLD_Delegate_RenderTargetUpdate(event_PreRenderTargetUpdate);
            mRTListener.evtPostRenderTargetUpdate += new RenderTargetListenerDirector.RTLD_Delegate_RenderTargetUpdate(event_PostRenderTargetUpdate);

            mSceneManager.SetAmbientLight(Converter.GetColor(0.2f, 0.2f, 0.2f));

            mSceneManager.SetSkyBox(true, "Examples/MorningSkyBox");

            // Create a light
            Light l = mSceneManager.CreateLight("MainLight");

            l.SetLightType(OgreDotNet.Light.LightTypes.Directional);
            Math3D.Vector3 dir = new Vector3(0.5f, -1.0f, 0.0f);
            dir.Normalize();
            l.SetDirection(dir);
            l.SetDiffuseColour(1.0f, 1.0f, 0.8f);
            l.SetSpecularColour(1.0f, 1.0f, 1.0f);

            // Create a prefab plane
            mPlane        = new MovablePlane("ReflectPlane");
            mPlane.D      = 0;
            mPlane.Normal = OgreVector3.FromVector3(Math3D.Vector3.UnitY);
            MeshManager.GetSingleton().CreatePlane("ReflectionPlane", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                   mPlane, 2000, 2000, 1, 1, true, 1, 1, 1, Vector3.UnitZ);
            mPlaneEnt = mSceneManager.CreateEntity("Plane", "ReflectionPlane");

            // Create an entity from a model (will be loaded automatically)
            Entity knotEnt = mSceneManager.CreateEntity("Knot", "knot.mesh");

            // Create an entity from a model (will be loaded automatically)
            Entity ogreHead = mSceneManager.CreateEntity("Head", "ogrehead.mesh");

            knotEnt.SetMaterialName("Examples/TextureEffect2");

            // Attach the rtt entity to the root of the scene
            SceneNode rootNode = mSceneManager.GetRootSceneNode();

            mPlaneNode = rootNode.CreateChildSceneNode();

            // Attach both the plane entity, and the plane definition
            mPlaneNode.AttachObject(mPlaneEnt);

            //multi Inheritence problem, use the static Get*From function to convert
            MovableObject mo = MovableObject.GetMovableObjectFrom(mPlane);

            mPlaneNode.AttachObject(mo);

            mPlaneNode.Translate(0.0f, -10.0f, 0.0f);

            // Tilt it a little to make it interesting
            //mPlaneNode.Roll( new Radian( new Degree( 5.0f)) );
            mPlaneNode.Roll(5.0f);

            rootNode.CreateChildSceneNode("Head").AttachObject(ogreHead);


            RenderTexture rttTex = mRoot.GetRenderSystem().CreateRenderTexture("RttTex", 512, 512,
                                                                               TextureType.TEX_TYPE_2D, PixelFormat.PF_R8G8B8);

            {            //new scope for some reason
                mReflectCam = mSceneManager.CreateCamera("ReflectCam");
                mReflectCam.SetNearClipDistance(mCamera.GetNearClipDistance());
                mReflectCam.SetFarClipDistance(mCamera.GetFarClipDistance());
                mReflectCam.SetAspectRatio(
                    (float)mRenderWindow.GetViewport(0).ActualWidth /
                    (float)mRenderWindow.GetViewport(0).ActualHeight);

                Viewport v = rttTex.AddViewport(mReflectCam);
                v.ClearEveryFrame = true;
                v.BackgroundColor = System.Drawing.Color.Black;                 //Converter.ToColor( ColourValue.Black );

                ResourcePtr resPtr = MaterialManager.Instance.Create("RttMat",
                                                                     ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);

                MaterialPtr mat = new MaterialPtr(ResourcePtr.getCPtr(resPtr).Handle, false);

                TextureUnitState t = mat.Get().GetTechnique(0).getPass(0).createTextureUnitState("RustedMetal.jpg");
                t = mat.Get().GetTechnique(0).getPass(0).createTextureUnitState("RttTex");
                // Blend with base texture
                t.setColourOperationEx(LayerBlendOperationEx.LBX_BLEND_MANUAL, LayerBlendSource.LBS_TEXTURE,
                                       LayerBlendSource.LBS_CURRENT, Color.White,
                                       Color.White, 0.25f);
                t.SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_CLAMP);
                t.setProjectiveTexturing(true, mReflectCam);
                rttTex.AddListener(mRTListener);

                // set up linked reflection
                mReflectCam.EnableReflection(mPlane);
                // Also clip
                mReflectCam.EnableCustomNearClipPlane(mPlane);
            }

            // Give the plane a texture
            mPlaneEnt.SetMaterialName("RttMat");


            // Add a whole bunch of extra transparent entities
            Entity cloneEnt;

            for (int n = 0; n < 10; ++n)
            {
                // Create a new node under the root
                SceneNode node = mSceneManager.CreateSceneNode();
                // Random translate
                Vector3 nodePos;
                nodePos.x = OgreMath.SymmetricRandom() * 750.0f;
                nodePos.y = OgreMath.SymmetricRandom() * 100.0f + 25.0f;
                nodePos.z = OgreMath.SymmetricRandom() * 750.0f;
                node.SetPosition(nodePos);
                rootNode.AddChild(node);
                // Clone knot
                string cloneName = string.Format("Knot{0}", n);
                cloneEnt = knotEnt.Clone(cloneName);
                // Attach to new node
                node.AttachObject(cloneEnt);
            }


            mCamera.SetPosition(new Vector3(-50.0f, 100.0f, 500.0f));
            mCamera.LookAt = new Vector3(0, 0, 0);
        }
Exemplo n.º 6
0
        protected override void load()
        {
            // clarabie - nov 18, 2008
            // modified this to check for an existing material instead of always
            // creating a new one. Allows more flexibility, but also specifically allows us to
            // solve the problem of XNA not having fixed function support

            this._material = (Material)MaterialManager.Instance.GetByName("Fonts/" + _name);

            if (this._material == null)
            {
                // create a material for this font
                this._material = (Material)MaterialManager.Instance.Create("Fonts/" + _name, Group);

                TextureUnitState unitState = null;
                var blendByAlpha           = false;

                if (this._fontType == FontType.TrueType)
                {
#if !(XBOX || XBOX360)
                    // create the font bitmap on the fly
                    createTexture();

                    // a texture layer was added in CreateTexture
                    unitState = this._material.GetTechnique(0).GetPass(0).GetTextureUnitState(0);

                    blendByAlpha = true;
#endif
                }
                else
                {
                    // load this texture
                    // TODO In general, modify any methods like this that throw their own exception rather than returning null, so the caller can decide how to handle a missing resource.

                    this._texture = TextureManager.Instance.Load(Source, Group, TextureType.TwoD, 0);

                    blendByAlpha = texture.HasAlpha;
                    // pre-created font images
                    unitState = Material.GetTechnique(0).GetPass(0).CreateTextureUnitState(Source);
                }

                // Make sure material is aware of colour per vertex.
                this._material.GetTechnique(0).GetPass(0).VertexColorTracking = TrackVertexColor.Diffuse;

                if (unitState != null)
                {
                    // Clamp to avoid fuzzy edges
                    unitState.SetTextureAddressingMode(TextureAddressing.Clamp);
                    // Allow min/mag filter, but no mip
                    unitState.SetTextureFiltering(FilterOptions.Linear, FilterOptions.Linear, FilterOptions.None);
                }

                // set up blending mode
                if (blendByAlpha)
                {
                    this._material.SetSceneBlending(SceneBlendType.TransparentAlpha);
                }
                else
                {
                    // assume black background here
                    this._material.SetSceneBlending(SceneBlendType.Add);
                }
            }
        }
Exemplo n.º 7
0
        // Just override the mandatory create scene method
        public override void CreateScene()
        {
            // Set ambient light
            sceneMgr.AmbientLight = new ColourValue(0.2f, 0.2f, 0.2f);
            // Skybox
            sceneMgr.SetSkyBox(true, "Examples/MorningSkyBox");

            // Create a light
            Light l = sceneMgr.CreateLight("MainLight");

            l.Type = Light.LightTypes.LT_DIRECTIONAL;
            Vector3 dir = new Vector3(0.5f, -1, 0);

            dir.Normalise();
            l.Direction      = dir;
            l.DiffuseColour  = new ColourValue(1.0f, 1.0f, 0.8f);
            l.SpecularColour = new ColourValue(1.0f, 1.0f, 1.0f);

            // Create a prefab plane
            mPlane = new MovablePlane(Vector3.UNIT_Y, 0);

            MeshManager.Singleton.CreatePlane("ReflectionPlane",
                                              ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                              mPlane._getDerivedPlane(), 2000, 2000,
                                              1, 1, true, 1, 1, 1, Vector3.UNIT_Z);
            mPlaneEnt = sceneMgr.CreateEntity("Plane", "ReflectionPlane");

            // Create an entity from a model (will be loaded automatically)
            Entity knotEnt = sceneMgr.CreateEntity("Knot", "knot.mesh");

            // Create an entity from a model (will be loaded automatically)
            Entity ogreHead = sceneMgr.CreateEntity("Head", "ogrehead.mesh");

            knotEnt.SetMaterialName("Examples/TextureEffect2");

            // Attach the rtt entity to the root of the scene
            SceneNode rootNode = sceneMgr.RootSceneNode;

            mPlaneNode = rootNode.CreateChildSceneNode();

            // Attach both the plane entity, and the plane definition
            mPlaneNode.AttachObject(mPlaneEnt);
            mPlaneNode.AttachObject(mPlane);
            mPlaneNode.Translate(0, -10, 0);
            // Tilt it a little to make it interesting
            mPlaneNode.Roll(new Degree(5));

            rootNode.CreateChildSceneNode("Head").AttachObject(ogreHead);

            TexturePtr texture = TextureManager.Singleton.CreateManual("RttTex",
                                                                       ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                                       TextureType.TEX_TYPE_2D,
                                                                       512, 512, 0,
                                                                       PixelFormat.PF_R8G8B8,
                                                                       (int)TextureUsage.TU_RENDERTARGET);
            RenderTarget rttTex = texture.GetBuffer().GetRenderTarget();

            mReflectCam = sceneMgr.CreateCamera("ReflectCam");
            mReflectCam.NearClipDistance = camera.NearClipDistance;
            mReflectCam.FarClipDistance  = camera.FarClipDistance;
            mReflectCam.AspectRatio      =
                (float)window.GetViewport(0).ActualWidth /
                (float)window.GetViewport(0).ActualHeight;
            mReflectCam.FOVy = camera.FOVy;

            Viewport v = rttTex.AddViewport(mReflectCam);

            v.SetClearEveryFrame(true);
            v.BackgroundColour = ColourValue.Black;

            MaterialPtr mat = MaterialManager.Singleton.Create("RttMat",
                                                               ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);
            TextureUnitState t = mat.GetTechnique(0).GetPass(0).CreateTextureUnitState("RustedMetal.jpg");

            t = mat.GetTechnique(0).GetPass(0).CreateTextureUnitState("RttTex");
            // Blend with base texture
            t.SetColourOperationEx(LayerBlendOperationEx.LBX_BLEND_MANUAL,
                                   LayerBlendSource.LBS_TEXTURE,
                                   LayerBlendSource.LBS_CURRENT,
                                   ColourValue.White,
                                   ColourValue.White, 0.25f);
            t.SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_CLAMP);
            t.SetProjectiveTexturing(true, mReflectCam);
            rttTex.PostRenderTargetUpdate += postRenderTargetUpdate;
            rttTex.PreRenderTargetUpdate  += preRenderTargetUpdate;

            // set up linked reflection
            mReflectCam.EnableReflection(mPlane);
            // Also clip
            mReflectCam.EnableCustomNearClipPlane(mPlane);


            // Give the plane a texture
            mPlaneEnt.SetMaterialName("RttMat");

            // Add a whole bunch of extra transparent entities
            Entity cloneEnt;

            for (int n = 0; n < 10; ++n)
            {
                // Create a new node under the root
                SceneNode node = sceneMgr.CreateSceneNode();
                // Random translate
                Vector3 nodePos;
                nodePos.x     = Mogre.Math.SymmetricRandom() * 750.0f;
                nodePos.y     = Mogre.Math.SymmetricRandom() * 100.0f + 25;
                nodePos.z     = Mogre.Math.SymmetricRandom() * 750.0f;
                node.Position = nodePos;
                rootNode.AddChild(node);
                // Clone knot
                string cloneName = "Knot" + n;
                cloneEnt = knotEnt.Clone(cloneName);
                // Attach to new node
                node.AttachObject(cloneEnt);
            }

            camera.Position = new Vector3(-50, 100, 500);
            camera.LookAt(0, 0, 0);
        }
Exemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        protected void Initialize()
        {
            // Create geometry
            int nvertices = this.slices * 4;           // n+1 planes
            int elemsize  = 3 * 3;
            int dsize     = elemsize * nvertices;
            int x;

            var indexData  = new IndexData();
            var vertexData = new VertexData();
            var vertices   = new float[dsize];

            var coords = new float[4, 2]
            {
                {
                    0.0f, 0.0f
                }, {
                    0.0f, 1.0f
                }, {
                    1.0f, 0.0f
                }, {
                    1.0f, 1.0f
                }
            };

            for (x = 0; x < this.slices; x++)
            {
                for (int y = 0; y < 4; y++)
                {
                    float xcoord = coords[y, 0] - 0.5f;
                    float ycoord = coords[y, 1] - 0.5f;
                    float zcoord = -((float)x / (float)(this.slices - 1) - 0.5f);
                    // 1.0f .. a/(a+1)
                    // coordinate
                    vertices[x * 4 * elemsize + y * elemsize + 0] = xcoord * (this.size / 2.0f);
                    vertices[x * 4 * elemsize + y * elemsize + 1] = ycoord * (this.size / 2.0f);
                    vertices[x * 4 * elemsize + y * elemsize + 2] = zcoord * (this.size / 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 * Utility.Sqrt(3.0f);
                    vertices[x * 4 * elemsize + y * elemsize + 7] = ycoord * Utility.Sqrt(3.0f);
                    vertices[x * 4 * elemsize + y * elemsize + 8] = zcoord * Utility.Sqrt(3.0f);
                }
            }

            var faces = new short[this.slices * 6];

            for (x = 0; x < this.slices; x++)
            {
                faces[x * 6 + 0] = (short)(x * 4 + 0);
                faces[x * 6 + 1] = (short)(x * 4 + 1);
                faces[x * 6 + 2] = (short)(x * 4 + 2);
                faces[x * 6 + 3] = (short)(x * 4 + 1);
                faces[x * 6 + 4] = (short)(x * 4 + 2);
                faces[x * 6 + 5] = (short)(x * 4 + 3);
            }

            //setup buffers
            vertexData.vertexStart = 0;
            vertexData.vertexCount = nvertices;

            VertexDeclaration   decl = vertexData.vertexDeclaration;
            VertexBufferBinding bind = vertexData.vertexBufferBinding;
            int offset = 0;

            offset += decl.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position).Size;
            offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Normal).Size;
            offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.TexCoords).Size;

            HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl, nvertices,
                                                                                                  BufferUsage.StaticWriteOnly);

            bind.SetBinding(0, vertexBuffer);

            HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, this.slices * 6,
                                                                                               BufferUsage.StaticWriteOnly);

            indexData.indexBuffer = indexBuffer;
            indexData.indexCount  = this.slices * 6;
            indexData.indexStart  = 0;

            indexBuffer.WriteData(0, indexBuffer.Size, faces, true);
            vertexBuffer.WriteData(0, vertexBuffer.Size, vertices);
            vertices = null;
            faces    = null;

            // Now make the render operation
            renderOperation.operationType = OperationType.TriangleList;
            renderOperation.indexData     = indexData;
            renderOperation.vertexData    = vertexData;
            renderOperation.useIndices    = true;

            // Create a brand new private material
            if (!ResourceGroupManager.Instance.GetResourceGroups().Contains("VolumeRendable"))
            {
                ResourceGroupManager.Instance.CreateResourceGroup("VolumeRendable");
            }

            var material = (Material)MaterialManager.Instance.Create(this.texture, "VolumeRendable");

            // 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(SceneBlendType.TransparentAlpha);
            pass.DepthWrite      = false;
            pass.CullingMode     = CullingMode.None;
            pass.LightingEnabled = false;
            textureUnit.SetTextureAddressingMode(TextureAddressing.Clamp);
            textureUnit.SetTextureName(this.texture, TextureType.ThreeD);
            textureUnit.SetTextureFiltering(TextureFiltering.Trilinear);

            this.unit     = textureUnit;
            base.material = material;
        }
Exemplo n.º 9
0
        void CreateDefaultTechnique()
        {
            string sourceFile = "Base\\Shaders\\Water.cg_hlsl";

            string vertexSyntax;
            string fragmentSyntax;
            {
                if( RenderSystem.Instance.IsDirect3D() )
                {
                    vertexSyntax = "vs_3_0";
                    fragmentSyntax = "ps_3_0";
                }
                else if( RenderSystem.Instance.IsOpenGLES() )
                {
                    vertexSyntax = "hlsl2glsl";
                    fragmentSyntax = "hlsl2glsl";
                }
                else
                {
                    vertexSyntax = "arbvp1";
                    fragmentSyntax = "arbfp1";
                }
            }

            BaseMaterial.ReceiveShadows = false;

            Technique tecnhique = BaseMaterial.CreateTechnique();
            Pass pass = tecnhique.CreatePass();

            bool transparent = owner.DeepColor.Alpha != 1 || owner.ShallowColor.Alpha != 1;

            //generate compileArguments and bind textures
            StringBuilder compileArguments = new StringBuilder( 128 );

            //general settings
            if( RenderSystem.Instance.IsDirect3D() )
                compileArguments.Append( " -DDIRECT3D" );
            if( RenderSystem.Instance.IsOpenGL() )
                compileArguments.Append( " -DOPENGL" );
            if( RenderSystem.Instance.IsOpenGLES() )
                compileArguments.Append( " -DOPENGL_ES" );
            if( !transparent )
                compileArguments.Append( " -DDEPTH_WRITE" );

            //transparent surface
            if( transparent )
            {
                pass.SourceBlendFactor = SceneBlendFactor.SourceAlpha;
                pass.DestBlendFactor = SceneBlendFactor.OneMinusSourceAlpha;
                pass.DepthWrite = false;

                compileArguments.Append( " -DTRANSPARENT" );
            }

            //disable Direct3D standard fog features
            pass.SetFogOverride( FogMode.None, new ColorValue( 0, 0, 0 ), 0, 0, 0 );

            //Fog
            if( owner.AllowFog )
            {
                FogMode fogMode = SceneManager.Instance.GetFogMode();
                if( fogMode != FogMode.None )
                {
                    compileArguments.Append( " -DFOG_ENABLED" );
                    compileArguments.Append( " -DFOG_" + fogMode.ToString().ToUpper() );
                }
            }

            //noiseMap
            {
                TextureUnitState state = pass.CreateTextureUnitState();
                state.SetTextureName( "Base\\Types\\Water Plane\\WaterNoise.dds", Texture.Type.Type2D );
            }

            //reflectionMap
            if( owner.ReflectionLevel != WaterPlane.ReflectionLevels.None &&
                RenderSystem.Instance.Capabilities.HardwareRenderToTexture )
            {
                compileArguments.Append( " -DREFLECTION_MAP" );

                reflectionMapState = pass.CreateTextureUnitState();
                reflectionMapState.SetTextureAddressingMode( TextureAddressingMode.Clamp );
                reflectionMapState.SetTextureFiltering( FilterOptions.Linear,
                    FilterOptions.Linear, FilterOptions.None );
            }

            //vertex program
            {
                string errorString;

                GpuProgram program = GpuProgramCacheManager.Instance.AddProgram(
                    "WaterPlane_Vertex_", GpuProgramType.Vertex, sourceFile,
                    "main_vp", vertexSyntax, compileArguments.ToString(), out errorString );

                if( !string.IsNullOrEmpty( errorString ) )
                    Log.Fatal( errorString );

                if( program != null )
                {
                    GpuProgramParameters parameters = program.DefaultParameters;
                    SetProgramAutoConstants( parameters );
                    pass.VertexProgramName = program.Name;
                }
            }

            //fragment program
            {
                string errorString;

                GpuProgram program = GpuProgramCacheManager.Instance.AddProgram(
                    "WaterPlane_Fragment_", GpuProgramType.Fragment, sourceFile,
                    "main_fp", fragmentSyntax, compileArguments.ToString(), out errorString );

                if( !string.IsNullOrEmpty( errorString ) )
                    Log.Fatal( errorString );

                if( program != null )
                {
                    SetProgramAutoConstants( program.DefaultParameters );
                    pass.FragmentProgramName = program.Name;
                }
            }
        }