Exemple #1
0
        /// <inheritdoc />
        public override void Draw(GameTime gameTime)
        {
            #region Pass 1

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            // Set the render target as our shadow map, we are drawing the depth into this texture
            GraphicsDevice.SetRenderTarget(SceneRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0);

            Model.Draw(Matrix.Identity, Camera.View, Camera.Projection);

            #endregion

            #region Pass 2

            // No depth needed
            GraphicsDevice.DepthStencilState = DepthStencilState.None;
            // Set the render target to null, we are drawing to the screen
            GraphicsDevice.SetRenderTarget(null);

            Effect.Parameters["baseTexture"].SetValue(SceneRenderTarget);
            FullScreenQuad.Draw(Effect);

            #endregion


            base.Draw(gameTime);
        }
 private void OnPreCull()
 {
     if ((UnityEngine.Object)renderProxy != (UnityEngine.Object)null)
     {
         quad.Draw(renderProxy.Textures[0]);
     }
 }
        public void TestBasicShaderCustomInclude()
        {
            BasicShader    shader = null;
            FullScreenQuad quad   = null;
            XNAGame        game   = new XNAGame();

            game.InitializeEvent += delegate
            {
                shader = new BasicShader(game);
                shader.AddCustomIncludeHandler("testInclude.fx",
                                               delegate
                {
                    var byteArray = Encoding.ASCII.GetBytes("float getColor(){return 1;}");
                    return(new MemoryStream(byteArray));
                });
                shader.InitFromEmbeddedFile(game,
                                            typeof(GraphicsTest).Assembly, "MHGameWork.TheWizards.Tests.Graphics.Files.TestShaderInclude.fx",
                                            "..\\..\\Unit Tests\\Graphics\\Files\\TestShaderInclude.fx",
                                            new EffectPool());
                shader.SetTechnique("Technique1");
                quad = new FullScreenQuad(game.GraphicsDevice);
            };

            game.DrawEvent += () => shader.RenderMultipass(() => quad.Draw());
            game.Run();
        }
Exemple #4
0
        /// <summary>
        /// Renders the shadowOcclusion.
        /// This is actually only used for testing
        /// </summary>
        public void RenderShadowOcclusion(ICamera mainCamera, ShaderResourceView depthTextureRV)
        {
            // Set the device to render to our shadow occlusion texture, and to use
            // the original DepthStencilSurface
            //graphicsDevice.SetRenderTarget( 0, shadowOcclusion );
            //graphicsDevice.DepthStencilBuffer = oldDS;

            Matrix cameraTransform;

            cameraTransform = mainCamera.ViewInverse;
            //mainCamera.GetWorldMatrix( out cameraTransform );

            // Setup the Effect
            shadowMapShader.SetTechnique(shadowOcclusionTechniques[(int)filteringType]);
            shadowMapShader.Effect.GetVariableByName("g_matProj").AsMatrix().SetMatrix(Matrix.Invert(mainCamera.Projection));
            shadowMapShader.Effect.GetVariableByName("g_vFrustumCornersVS").AsVector().Set(farFrustumCornersVS.Select(o => new Vector4(o, 1)).ToArray());
            shadowMapShader.Effect.GetVariableByName("DepthTexture").AsResource().SetResource(depthTextureRV);
            shadowMapShader.Effect.GetVariableByName("g_bShowSplitColors").AsScalar().Set(showCascadeSplits);

            SetShadowOcclusionShaderVariables(shadowMapShader, mainCamera);

            shadowMapShader.GetCurrentPass(0).Apply(context);
            // Draw the full screen quad
            fullScreenQuad.Draw(layout);


            // Set to render to the back buffer
            //graphicsDevice.SetRenderTarget( 0, null );
            UnSetShadowOcclusionShaderVariables(shadowMapShader);

            shadowMapShader.Effect.GetVariableByName("ShadowMap").AsResource().SetResource(null);
            shadowMapShader.Effect.GetVariableByName("DepthTexture").AsResource().SetResource(null);
            shadowMapShader.GetCurrentPass(0).Apply(context);
        }
Exemple #5
0
        protected void ResizeViewTo(GLTextuer2D inc, GLTextuer2D o, int owidth, int oheight, int nwidth, int nheight)
        {
            float wp = (float)nwidth / (float)owidth;
            float hp = (float)nheight / (float)oheight;

            float fp = wp < hp ? wp : hp;

            Matrix4 proj        = Matrix4.CreateOrthographic(nwidth, nheight, 0.03f, 1000f);
            Matrix4 translation = Matrix4.CreateTranslation(0, 0, 0);
            //half width/height for scale as it is centered based
            Matrix4 sm    = Matrix4.CreateScale(fp * (float)(owidth * 0.5f), -fp * (float)(oheight * 0.5f), 1);
            Matrix4 model = sm * translation;
            Matrix4 view  = Matrix4.LookAt(new Vector3(0, 0, 1), Vector3.Zero, Vector3.UnitY);

            resizeProcessor.Model      = model;
            resizeProcessor.View       = view;
            resizeProcessor.Projection = proj;

            resizeProcessor.Bind(inc);

            if (renderQuad != null)
            {
                renderQuad.Draw();
            }

            resizeProcessor.Unbind();

            o.Bind();
            o.CopyFromFrameBuffer(nwidth, nheight);
            GLTextuer2D.Unbind();
        }
Exemple #6
0
        public void TestBasicShaderIncludeRoot()
        {
            BasicShader    shader = null;
            FullScreenQuad quad   = null;
            var            game   = new DX11Game();

            game.InitDirectX();

            var fi      = new FileInfo("../../Common.Core/Shaders/TestAutoReload.fx");
            var include = new FileInfo("../../Common.Core/Shaders/IncludeTest.fx");


            using (var fs = new StreamWriter(fi.OpenWrite()))
            {
                fs.WriteLine("float4 Color = float4(1,0,0,1);");
            }
            using (var fs = new StreamWriter(include.OpenWrite()))
            {
                fs.WriteLine("float4 Color2 = float4(0,0,0,1);");
            }

            shader = BasicShader.LoadAutoreload(game, fi);
            shader.SetTechnique("TestAutoReload");
            quad = new FullScreenQuad(game.Device);



            var inputLayout = FullScreenQuad.CreateInputLayout(game.Device, shader.GetCurrentPass(0));
            var time        = 0f;

            game.GameLoopEvent += delegate
            {
                shader.Apply();
                quad.Draw(inputLayout);

                if (time > 2 && time < 3)
                {
                    using (var fs = new StreamWriter(fi.OpenWrite()))
                    {
                        fs.WriteLine("float4 Color = float4(1,1,0,1);");
                        time = 5;
                    }
                }


                if (time > 6 && time < 7)
                {
                    using (var fs = new StreamWriter(include.OpenWrite()))
                    {
                        fs.WriteLine("float4 Color2 = float4(-1,0,0,1);");
                        time = 10;
                    }
                }

                time += game.Elapsed;
            };
            game.Run();
        }
        private void Glview_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            if (glview == null)
            {
                return;
            }

            ViewContext.VerifyContext(glview);
            ViewContext.Context.MakeCurrent(glview.WindowInfo);

            GL.Disable(EnableCap.CullFace);

            GL.Viewport(0, 0, glview.Width, glview.Height);
            GL.ClearColor(0.1f, 0.1f, 0.1f, 1);
            GL.Clear(ClearBufferMask.ColorBufferBit);
            GL.Clear(ClearBufferMask.DepthBufferBit);

            Matrix4 proj        = Matrix4.CreateOrthographic(glview.Width, glview.Height, 0.03f, 1000f);
            Matrix4 translation = Matrix4.CreateTranslation((float)pan.X, (float)-pan.Y, 0);
            //half width/height for scale as it is centered based
            Matrix4 sm    = Matrix4.CreateScale(scale * (float)(vw * 0.5f), scale * (float)(vh * 0.5f), 1);
            Matrix4 model = sm * translation;
            Matrix4 view  = Matrix4.LookAt(new Vector3(0, 0, 1), Vector3.Zero, Vector3.UnitY);

            processor.FlipY      = true;
            processor.Model      = model;
            processor.View       = view;
            processor.Projection = proj;

            if (current != null && current.Node != null && current.Node.GetActiveBuffer() != null && current.Node.GetActiveBuffer().Id != 0)
            {
                processor.Bind(current.Node.GetActiveBuffer());
            }
            else if (blankTexture != null)
            {
                processor.Bind(blankTexture);
            }

            if (quad != null)
            {
                quad.Draw();
            }

            processor.Unbind();

            if (uvs != null && showUV)
            {
                uvs.View       = view;
                uvs.Projection = proj;
                uvs.Model      = model;
                uvs.Draw();
            }

            GL.Enable(EnableCap.CullFace);

            glview.SwapBuffers();
        }
        public void DrawUpdatedLogLuminance()
        {
            context.ClearState();
            context.OutputMerger.SetTargets(luminanceRTV);
            context.Rasterizer.SetViewports(new Viewport(0, 0, luminanceMap.Description.Width,
                                                         luminanceMap.Description.Height));
            shader.SetTechnique("CalculateLuminance");

            shader.Effect.GetVariableByName("hdrImage").AsResource().SetResource(hdrImage);

            shader.Apply();
            quad.Draw(layout);

            shader.Effect.GetVariableByName("hdrImage").AsResource().SetResource(null);
            shader.Apply();

            //TODO: Do not use GenerateMips, generate the manually. This might solve the NAN problem
            generateMips();
        }
        private void DrawWithCombineMaterial(DrawingContext context, IList <IDrawableObject> drawables)
        {
            RenderTargetPool.Lock(InputTexture as RenderTarget2D);

            int i, p;

            for (p = 0; p < passes.Count; p++)
            {
                passes[p].GetActivePasses(workingPasses);

                RenderTarget2D intermediate = InputTexture as RenderTarget2D;
                for (i = 0; i < workingPasses.Count; ++i)
                {
                    var workingPass = (PostEffect)workingPasses[i];

                    RenderTarget2D previous = intermediate;
                    RenderTargetPool.Lock(previous);
                    intermediate = workingPass.PrepareRenderTarget(context.graphics, intermediate, null);
                    intermediate.Begin();

                    workingPass.InputTexture = previous;
                    workingPass.Draw(context, drawables);

                    intermediate.End();
                    RenderTargetPool.Unlock(previous);
                }

                passResults.Add(intermediate);
                workingPasses.Clear();
            }

            RenderTargetPool.Unlock(InputTexture as RenderTarget2D);

            if (fullScreenQuad == null)
            {
                fullScreenQuad = new FullScreenQuad(context.graphics);
            }

            context.graphics.BlendState = BlendState.Opaque;
            Material.texture            = InputTexture;

            for (i = 0, p = 0; p < passes.Count; p++)
            {
                if (passes[p].Enabled)
                {
                    Material.SetTexture(passes[p].TextureUsage, passResults[i]);
                    i++;
                }
            }

            fullScreenQuad.Draw(context, Material);

            lastEffects.Clear();
            passResults.Clear();
        }
Exemple #10
0
        protected void ApplyTransformNoAuto(GLTextuer2D inc, GLTextuer2D o, int owidth, int oheight, MVector translation, MVector scale, float angle, MVector pivot)
        {
            Matrix4 proj    = Matrix4.CreateOrthographic(owidth, oheight, 0.03f, 1000f);
            Matrix4 pTrans  = Matrix4.CreateTranslation(-pivot.X, -pivot.Y, 0);
            Matrix4 iPTrans = Matrix4.CreateTranslation(pivot.X, pivot.Y, 0);
            Matrix4 trans   = Matrix4.CreateTranslation(translation.X, translation.Y, 0);
            Matrix4 sm      = Matrix4.CreateScale(scale.X, scale.Y, 1);
            Matrix4 rot     = Matrix4.CreateRotationZ(angle);
            Matrix4 model   = pTrans * sm * rot * iPTrans * trans;

            Matrix4 view = Matrix4.LookAt(new Vector3(0, 0, 1), Vector3.Zero, Vector3.UnitY);

            IGL.Primary.Viewport(0, 0, owidth, oheight);

            resizeProcessor.Model      = model;
            resizeProcessor.View       = view;
            resizeProcessor.Projection = proj;
            resizeProcessor.Luminosity = Luminosity;

            resizeProcessor.Bind(inc);

            inc.ClampToEdge();

            if (renderQuad != null)
            {
                renderQuad.Draw();
            }

            inc.Repeat();
            resizeProcessor.Unbind();

            o.Bind();
            o.Repeat();
            GLTextuer2D.Unbind();

            Blit(o, owidth, oheight);

            /*o.Bind();
             * o.Repeat();
             * o.CopyFromFrameBuffer(owidth, oheight);
             * GLTextuer2D.Unbind();*/
        }
 private void OnPreCull()
 {
     if (quad == null)
     {
         quad = new FullScreenQuad("CameraReferenceTexture", GetComponent <Camera>(), referenceCamera.GetComponent <CameraRenderTexture>().ShouldFlip());
     }
     if ((Object)referenceCamera != (Object)null)
     {
         quad.Draw(referenceCamera.GetComponent <CameraRenderTexture>().GetTexture());
     }
 }
Exemple #12
0
        public void Draw()
        {
            BasicShader shader;

            if (ShadowsEnabled)
            {
                shader = shadowsShader;
                shader.Effect.GetVariableByName("shadowMap").AsResource().SetResource(ShadowCubeMapRv);
                shader.Effect.GetVariableByName("ShadowMapProjection").AsMatrix().SetMatrix(shadowMapProjection);
            }
            else
            {
                shader = noShadowsShader;
            }

            //compute the light world matrix
            //scale according to light radius, and translate it to light position
            Matrix sphereWorldMatrix = Matrix.Scaling(new Vector3(1, 1, 1) * LightRadius) * Matrix.Translation(LightPosition);

            shader.Effect.GetVariableByName("World").AsMatrix().SetMatrix(sphereWorldMatrix);
            shader.Effect.GetVariableByName("View").AsMatrix().SetMatrix(game.Camera.View);
            shader.Effect.GetVariableByName("Projection").AsMatrix().SetMatrix(game.Camera.Projection);
            //light position
            shader.Effect.GetVariableByName("lightPosition").AsVector().Set(LightPosition);
            //set the color, radius and Intensity
            shader.Effect.GetVariableByName("Color").AsVector().Set(color);
            shader.Effect.GetVariableByName("lightRadius").AsScalar().Set(LightRadius);
            shader.Effect.GetVariableByName("lightIntensity").AsScalar().Set(LightIntensity);
            //parameters for specular computations
            shader.Effect.GetVariableByName("cameraPosition").AsVector().Set(game.Camera.ViewInverse.GetTranslation());
            shader.Effect.GetVariableByName("InvertViewProjection").AsMatrix().SetMatrix(Matrix.Invert(game.Camera.View * game.Camera.Projection));
            //size of a halfpixel, for texture coordinates alignment
            //pointLightShader.Effect.GetVariableByName("halfPixel").AsVector().Set(halfPixel);

            //calculate the distance between the camera and light center
            float cameraToCenter = Vector3.Distance(game.Camera.ViewInverse.GetTranslation(), LightPosition);

            //if we are inside the light volume, draw the sphere's inside face
            //if (cameraToCenter < lightRadius)
            //    GraphicsDevice.RenderState.CullMode = CullMode.CullClockwiseFace;
            //else
            //    GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;


            gBuffer.SetToShader(shader);

            shader.Apply();
            //drawSpherePrimitives();
            quad.Draw(layout);

            gBuffer.UnsetFromShader(shader);

            shader.Apply();
        }
Exemple #13
0
        /// <inheritdoc />
        public override void Draw(GameTime gameTime)
        {
            Game.Background = Color.Black;

            var viewProjection = Camera.View * Camera.Projection;

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            GraphicsDevice.SetRenderTarget(DepthRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            DrawSpheres(DrawDepthEffect, viewProjection);


            // Set the render target as null, we are drawing on the screen!
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            DrawSpheres(Effect, viewProjection);

            RasterizerState rasterizerState = new RasterizerState();

            rasterizerState.CullMode       = CullMode.None;
            GraphicsDevice.RasterizerState = rasterizerState;

            if (ShowArrows)
            {
                Arrows.ForEach(arrow => arrow.Draw(Matrix.Identity, Camera.View, Camera.Projection));
            }


            // Debug our shadowmap!
            // Show a simple quad with the texture
            DebugTextureEffect.Parameters["World"].SetValue(Matrix.CreateScale(0.2f) * Matrix.CreateTranslation(new Vector3(-0.75f, -0.75f, 0f)));
            DebugTextureEffect.Parameters["baseTexture"].SetValue(DepthRenderTarget);
            FullScreenQuad.Draw(DebugTextureEffect);

            Game.SpriteBatch.Begin();
            Game.SpriteBatch.DrawString(SpriteFont, "Con la tecla 'J' se prende y apaga el modo Wireframe",
                                        new Vector2(50, 50), Color.Yellow);
            Game.SpriteBatch.DrawString(SpriteFont, "Con la tecla 'K' se prenden y apagan las flechas", new Vector2(50, 80),
                                        Color.LightYellow);
            Game.SpriteBatch.DrawString(SpriteFont, "Con la tecla 'L' se habilita y deshabilita el back-face culling", new Vector2(50, 110),
                                        Color.LightGreen);
            Game.SpriteBatch.End();

            AxisLines.Draw(Camera.View, Camera.Projection);
            base.Draw(gameTime);
        }
Exemple #14
0
        public void DrawCombined(ShaderResourceView ambientOcclusionRV)
        {
            shader.Effect.GetVariableByName("colorMap").AsResource().SetResource(gBuffer.DiffuseRV);
            shader.Effect.GetVariableByName("lightMap").AsResource().SetResource(LightAccumulationRV);
            shader.Effect.GetVariableByName("ambientOcclusionMap").AsResource().SetResource(ambientOcclusionRV);


            shader.Apply();
            quad.Draw(layout);

            shader.Effect.GetVariableByName("colorMap").AsResource().SetResource(null);
            shader.Effect.GetVariableByName("lightMap").AsResource().SetResource(null);
            shader.Effect.GetVariableByName("ambientOcclusionMap").AsResource().SetResource(null);
            shader.Apply();
        }
        /// <summary>
        ///     Draws the scene with a simple, single-pass blur.
        /// </summary>
        private void DrawSimpleBlur()
        {
            #region Pass 1

            // Use the default blend and depth configuration
            Game.Background = Color.CornflowerBlue;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            // Set the main render target as our render target
            GraphicsDevice.SetRenderTarget(MainRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0);

            Model.Draw(Matrix.Identity, Camera.View, Camera.Projection);

            #endregion

            #region Pass 2

            // Set the depth configuration as none, as we don't use depth in this pass
            GraphicsDevice.DepthStencilState = DepthStencilState.None;

            // Set the render target as null, we are drawing into the screen now!
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);

            // Set the technique to our blur technique
            // Then draw a texture into a full-screen quad
            // using our rendertarget as texture

            Effect.CurrentTechnique = Effect.Techniques["Blur"];
            Effect.Parameters["baseTexture"].SetValue(MainRenderTarget);
            FullScreenQuad.Draw(Effect);

            #endregion
        }
        /// <summary>
        /// averageLuminance is a texture when sampled at 0,0 contains the average luminance in the r channel
        /// </summary>
        /// <param name="hdrImage"></param>
        /// <param name="averageLuminance"></param>
        public void DrawTonemapped(ShaderResourceView hdrImage, ShaderResourceView averageLuminance)
        {
            shader.Effect.GetVariableByName("finalMap").AsResource().SetResource(hdrImage);
            shader.Effect.GetVariableByName("lumAvgMap").AsResource().SetResource(averageLuminance);


            shader.Apply();
            quad.Draw(layout);

            shader.Effect.GetVariableByName("finalMap").AsResource().SetResource(null);
            shader.Apply();



        }
Exemple #17
0
        public override void Render(GLTextuer2D[] inputs, out GLTextuer2D[] outputs)
        {
            outputs = null;

            if (shader == null)
            {
                return;
            }

            if (inputs == null)
            {
                return;
            }

            if (inputs.Length < 2)
            {
                return;
            }

            blur.Intensity = Intensity;
            blur.Process(width, height, inputs[1], inputs[1]);
            blur.Complete();

            Vector2 tiling = new Vector2(1);

            shader.Use();
            shader.SetUniform("MainTex", 0);
            shader.SetUniform("Bloom", 1);
            shader.SetUniform2("tiling", ref tiling);

            IGL.Primary.ActiveTexture((int)TextureUnit.Texture0);
            inputs[0].Bind();

            IGL.Primary.ActiveTexture((int)TextureUnit.Texture1);
            inputs[1].Bind();

            //ensure polygon is actually rendered instead of wireframe during this step
            IGL.Primary.PolygonMode((int)MaterialFace.FrontAndBack, (int)PolygonMode.Fill);

            IGL.Primary.Disable((int)EnableCap.CullFace);

            quad.Draw();

            IGL.Primary.Enable((int)EnableCap.CullFace);

            GLTextuer2D.Unbind();
        }
Exemple #18
0
        private void ClearRenderTargets(DrawingContext context)
        {
            if (clearMaterial == null)
            {
                clearMaterial = new ClearMaterial(GraphicsDevice);
                clearQuad     = new FullScreenQuad(GraphicsDevice);
            }

            clearMaterial.effect.CurrentTechnique.Passes[0].Apply();

            GraphicsDevice.SamplerStates[0]  = SamplerState.PointClamp;
            GraphicsDevice.DepthStencilState = DepthStencilState.None;

            clearQuad.Draw(context, clearMaterial);

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        }
Exemple #19
0
        /// <summary>
        /// Draws this pass using the specified drawing context.
        /// </summary>
        public override void Draw(DrawingContext context, IList <IDrawableObject> drawables)
        {
            RenderTargetPool.Lock(InputTexture as RenderTarget2D);

            if (fullScreenQuad == null)
            {
                fullScreenQuad = new FullScreenQuad(context.graphics);
            }

            context.graphics.BlendState        = BlendState;
            context.graphics.DepthStencilState = DepthStencilState.None;

            Material.texture = InputTexture;
            fullScreenQuad.Draw(context, Material);

            RenderTargetPool.Unlock(InputTexture as RenderTarget2D);
        }
Exemple #20
0
        /*public void AddNewParticle(Vector4[] positions, Vector4[] velocities, int start)
         * {
         *
         *  getOldPosition().SetData<Vector4>(positions, start, positions.Length, SetDataOptions.None);
         *
         *  getOldPosition().SetData<Vector4>(velocities, start, velocities.Length, SetDataOptions.None);
         * }*/

        public void RenderUpdate(float elapsed, Vector3 position)
        {
            context.ClearState();

            //game.GraphicsDevice.RenderState.AlphaBlendEnable = false;

            shader.SetTechnique("particleSimulation");
            shader.Effect.GetVariableByName("size").AsScalar().Set(size);
            shader.Effect.GetVariableByName("elapsed").AsScalar().Set(elapsed);
            shader.Effect.GetVariableByName("center").AsVector().Set(position);
            shader.Effect.GetVariableByName("oldPositionTex").AsResource().SetResource(getOldPositionSRV());
            shader.Effect.GetVariableByName("oldVelocityTex").AsResource().SetResource(getOldVelocitySRV());

            //Viewport oldPort = game.GraphicsDevice.Viewport;
            //game.GraphicsDevice.Viewport = newPort;
            context.Rasterizer.SetViewports(newPort, newPort);
            context.OutputMerger.SetTargets(getNewRenderTargetPosition(), getNewRenderTargetVelocity());
            //game.GraphicsDevice.SetRenderTarget(0, getNewRenderTargetPosition());
            //game.GraphicsDevice.SetRenderTarget(1, getNewRenderTargetVelocity());
            shader.Apply();
            quad.Draw(layout);

            context.OutputMerger.SetTargets(new RenderTargetView[2] {
                null, null
            });

            /*game.GraphicsDevice.SetRenderTarget(0, null);
            *  game.GraphicsDevice.SetRenderTarget(1, null);*/
            shader.Effect.GetVariableByName("oldPositionTex").AsResource().SetResource(null);
            shader.Effect.GetVariableByName("oldVelocityTex").AsResource().SetResource(null);
            shader.Apply();
            //game.GraphicsDevice.Viewport = oldPort;

            SwitchTextures();

            /*var g = (XNAGame)game;
             *
             * g.SpriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Texture, SaveStateMode.SaveState);
             * g.SpriteBatch.Draw(getOldPosition(), Vector2.Zero, Color.White);
             * g.SpriteBatch.Draw(getOldVelocity(), new Vector2(150, 0), Color.White);
             * g.SpriteBatch.End();*/
            game.SetBackbuffer();
            game.TextureRenderer.Draw(getOldPositionSRV(), Vector2.Zero, new Vector2(150, 150));
            game.TextureRenderer.Draw(getOldVelocitySRV(), new Vector2(150, 0), new Vector2(150, 150));
        }
Exemple #21
0
        public override void Render(GLTextuer2D[] inputs, out GLTextuer2D[] outputs)
        {
            outputs = null;

            if (shader == null)
            {
                return;
            }

            if (inputs == null)
            {
                return;
            }

            if (inputs.Length < 2)
            {
                return;
            }

            blur.Intensity = Intensity;
            blur.Process(width, height, inputs[1], inputs[1]);
            blur.Complete();

            Vector2 tiling = new Vector2(1);

            shader.Use();
            shader.SetUniform("MainTex", 0);
            shader.SetUniform("Bloom", 1);
            shader.SetUniform2("tiling", ref tiling);

            IGL.Primary.ActiveTexture((int)TextureUnit.Texture0);
            inputs[0].Bind();

            IGL.Primary.ActiveTexture((int)TextureUnit.Texture1);
            inputs[1].Bind();

            IGL.Primary.Disable((int)EnableCap.CullFace);

            quad.Draw();

            IGL.Primary.Enable((int)EnableCap.CullFace);

            GLTextuer2D.Unbind();
        }
        public void PostProcessFog(ShaderResourceView input, GBuffer gBuffer, RenderTargetView target)
        {
            global::SlimDX.Performance.BeginEvent(new Color4(), "Fog!");
            context.OutputMerger.SetTargets(target);
            shader.Effect.GetVariableByName("inputMap").AsResource().SetResource(input);
            shader.Effect.GetVariableByName("InvertProjection").AsMatrix().SetMatrix(
                Matrix.Invert(game.Camera.Projection));

            gBuffer.SetToShader(shader);


            shader.Apply();
            quad.Draw(layout);

            shader.Effect.GetVariableByName("inputMap").AsResource().SetResource(null);
            shader.Apply();

            global::SlimDX.Performance.EndEvent();
        }
        /// <summary>
        /// Draws Perlin noise to render target.
        /// </summary>
        /// <param name="time">Time value.</param>
        /// <param name="brightness">Brightness of clouds.</param>
        private void GeneratePerlinNoise(float time, float brightness)
        {
            if (cloudMap.IsContentLost)
            {
                // Re-create clouds render target
                cloudMap = new RenderTarget2D(
                    graphicsDevice,
                    (int)cloudMapResolution.X,
                    (int)cloudMapResolution.Y,
                    false,
                    SurfaceFormat.Color,
                    DepthFormat.None);
            }

            // Save viewport
            Viewport viewport = graphicsDevice.Viewport;

            // Set render target
            graphicsDevice.SetRenderTarget(cloudMap);
            graphicsDevice.Clear(Color.Transparent);

            // Setup effect
            perlinEffect.CurrentTechnique = perlinEffect.Techniques["PerlinNoise"];
            perlinEffect.Parameters["Texture"].SetValue(staticMap);
            perlinEffect.Parameters["Overcast"].SetValue(1.4f);
            perlinEffect.Parameters["Brightness"].SetValue(brightness);
            perlinEffect.Parameters["Time"].SetValue(time / 1000.0f);

            // Draw effect
            perlinEffect.CurrentTechnique.Passes[0].Apply();
            quadRenderer.Draw(graphicsDevice);

            // Reset render target
            graphicsDevice.SetRenderTarget(null);

            // Restore viewport
            graphicsDevice.Viewport = viewport;
        }
Exemple #24
0
        public void TestFullscreenQuad()
        {
            BasicShader    shader = null;
            FullScreenQuad quad   = null;
            var            game   = new DX11Game();

            game.InitDirectX();

            var device = game.Device;

            var bytecode  = ShaderBytecode.CompileFromFile("../../Common.Core/Shaders/FullScreenQuad.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect    = new Effect(game.Device, bytecode);
            var technique = effect.GetTechniqueByName("TestQuadTextured");
            var pass      = technique.GetPassByIndex(0);

            quad = new FullScreenQuad(game.Device);

            var diffuseShaderVariable = effect.GetVariableByName("txDiffuse").AsResource();

            var texturePath = Wallpaper001_png;

            var diffuseTexture = Texture2D.FromFile(device, texturePath);

            var diffuseTextureRv = new ShaderResourceView(device, diffuseTexture);

            diffuseShaderVariable.SetResource(diffuseTextureRv);

            var inputLayout = FullScreenQuad.CreateInputLayout(device, pass);

            game.GameLoopEvent += delegate
            {
                pass.Apply(game.Device.ImmediateContext);

                quad.Draw(inputLayout);
            };
            game.Run();
        }
        /// <summary>
        ///
        /// </summary>
        public void Draw()
        {
            BasicShader shader;

            if (ShadowsEnabled)
            {
                shader = shadowsShader;

                CSMRenderer.SetShadowOcclusionShaderVariables(shader, game.Camera);
                shader.Effect.GetVariableByName("InvertProjection").AsMatrix().SetMatrix(
                    Matrix.Invert(game.Camera.Projection));
            }
            else
            {
                shader = noShadowsShader;
            }

            shader.Effect.GetVariableByName("cameraPosition").AsVector().Set(game.Camera.ViewInverse.GetTranslation());
            shader.Effect.GetVariableByName("InvertViewProjection").AsMatrix().SetMatrix(Matrix.Invert(game.Camera.ViewProjection));
            shader.Effect.GetVariableByName("lightDirection").AsVector().Set(lightDirection);
            shader.Effect.GetVariableByName("Color").AsVector().Set(color);

            gBuffer.SetToShader(shader);

            shader.Apply();
            quad.Draw(layout);

            gBuffer.UnsetFromShader(shader);
            if (ShadowsEnabled)
            {
                CSMRenderer.UnSetShadowOcclusionShaderVariables(shader);
            }


            shader.Apply();
        }
        public override void Draw(GameTime gameTime)
        {
            #region Pass 1

            // Use the default blend and depth configuration
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            // Set the main render target, here we'll draw the base scene
            GraphicsDevice.SetRenderTarget(MainSceneRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            Player.Draw(gameTime);

            foreach (var room in Rooms)
            {
                room.Draw(gameTime);
            }

            foreach (var bullet in Bullets)
            {
                if (bullet.isInitialized())
                {
                    bullet.Draw(gameTime);
                }
                else
                {
                    bullet.Initialize(_game);
                    bullet.Load();
                }
            }

            foreach (var enemy in Enemies)
            {
                enemy.Draw(gameTime);
            }

            Lamp.Draw(gameTime);

            Lamp2.Draw(gameTime);

            UI.Draw(gameTime, Player);

            #endregion

            #region Pass 2

            // Set the render target as our bloomRenderTarget, we are drawing the bloom color into this texture
            GraphicsDevice.SetRenderTarget(FirstPassBloomRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            if (Game.godMode)
            {
                Player.Draw(gameTime);
            }
            else
            {
                Player.DrawBlack(gameTime);
            }

            foreach (var room in Rooms)
            {
                room.DrawBlack(gameTime);
            }

            foreach (var enemy in Enemies)
            {
                enemy.DrawBlack(gameTime);
            }

            Lamp.DrawBloom(gameTime);

            Lamp2.DrawBloom(gameTime);

            UI.Draw(gameTime, Player);

            #endregion

            #region Multipass Bloom

            // Now we apply a blur effect to the bloom texture
            // Note that we apply this a number of times and we switch
            // the render target with the source texture
            // Basically, this applies the blur effect N times
            BlurEffect.CurrentTechnique = BlurEffect.Techniques["Blur"];

            var bloomTexture           = FirstPassBloomRenderTarget;
            var finalBloomRenderTarget = SecondPassBloomRenderTarget;

            for (var index = 0; index < PassCount; index++)
            {
                //Exchange(ref SecondaPassBloomRenderTarget, ref FirstPassBloomRenderTarget);

                // Set the render target as null, we are drawing into the screen now!
                GraphicsDevice.SetRenderTarget(finalBloomRenderTarget);
                GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

                BlurEffect.Parameters["baseTexture"].SetValue(bloomTexture);
                FullScreenQuad.Draw(BlurEffect);

                if (index != PassCount - 1)
                {
                    var auxiliar = bloomTexture;
                    bloomTexture           = finalBloomRenderTarget;
                    finalBloomRenderTarget = auxiliar;
                }
            }

            #endregion

            #region Final Pass

            // Set the depth configuration as none, as we don't use depth in this pass
            GraphicsDevice.DepthStencilState = DepthStencilState.None;

            // Set the render target as null, we are drawing into the screen now!
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);

            // Set the technique to our blur technique
            // Then draw a texture into a full-screen quad
            // using our rendertarget as texture
            IntegrateEffect.CurrentTechnique = IntegrateEffect.Techniques["Integrate"];
            IntegrateEffect.Parameters["baseTexture"]?.SetValue(MainSceneRenderTarget);
            IntegrateEffect.Parameters["bloomTexture"]?.SetValue(FirstPassBloomRenderTarget);
            FullScreenQuad.Draw(IntegrateEffect);

            #endregion
        }
Exemple #27
0
        /// <summary>
        ///     Se llama cada vez que hay que refrescar la pantalla.
        ///     Escribir aquí todo el código referido al renderizado.
        /// </summary>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);



            if (State == GameState.Playing)
            {
                #region Pass 1

                // Use the default blend and depth configuration
                GraphicsDevice.DepthStencilState = DepthStencilState.Default;
                GraphicsDevice.BlendState        = BlendState.Opaque;

                // Set the main render target, here we'll draw the base scene
                GraphicsDevice.SetRenderTarget(MainSceneRenderTarget);
                GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

                DrawCheckpoints();
                DrawSkybox();

                // Assign the basic effect and draw
                foreach (var modelMesh in SpaceShipModelMK1.Meshes)
                {
                    foreach (var part in modelMesh.MeshParts)
                    {
                        part.Effect = SpaceShipEffect;
                    }
                }
                SpaceShipModelMK1.Draw(
                    Matrix.CreateScale(0.005f) *
                    Matrix.CreateFromQuaternion(_spaceshipRotation) *
                    Matrix.CreateTranslation(_spaceshipPosition)
                    , View, Projection);

                EM.Draw(View, Projection);
                EM.DrawEnemigoVigilante(View, Projection, _spaceshipPosition, _spaceshipRotation, _cameraPosition, _cameraDirection, Graphics);

                _trench.Draw(View, Projection, _lightDirection, Graphics);

                _laserManager.DrawLasers(View, Projection, _cameraPosition, _cameraDirection, Graphics);

                DrawHUD();
                GraphicsDevice.DepthStencilState = DepthStencilState.Default;

                #endregion

                DrawShadows(SpaceShipModelMK1, Matrix.CreateScale(0.005f) *
                            Matrix.CreateFromQuaternion(_spaceshipRotation) *
                            Matrix.CreateTranslation(_spaceshipPosition), SpaceShipEffect);

                #region Pass 2

                // Set the render target as our bloomRenderTarget, we are drawing the bloom color into this texture
                GraphicsDevice.SetRenderTarget(FirstPassBloomRenderTarget);
                GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

                BloomEffect.CurrentTechnique = BloomEffect.Techniques["BloomPass"];
                BloomEffect.Parameters["baseTexture"].SetValue(SpaceShipEffect.Texture);

                // We get the base transform for each mesh
                var modelMeshesBaseTransforms = new Matrix[SpaceShipModelMK1.Bones.Count];
                SpaceShipModelMK1.CopyAbsoluteBoneTransformsTo(modelMeshesBaseTransforms);
                foreach (var modelMesh in SpaceShipModelMK1.Meshes)
                {
                    foreach (var part in modelMesh.MeshParts)
                    {
                        part.Effect = BloomEffect;
                    }

                    // We set the main matrices for each mesh to draw
                    var worldMatrix = modelMeshesBaseTransforms[modelMesh.ParentBone.Index];

                    // WorldViewProjection is used to transform from model space to clip space
                    BloomEffect.Parameters["WorldViewProjection"].SetValue(worldMatrix * Matrix.CreateScale(0.005f) *
                                                                           Matrix.CreateFromQuaternion(_spaceshipRotation) *
                                                                           Matrix.CreateTranslation(_spaceshipPosition) * View * Projection);

                    // Once we set these matrices we draw
                    modelMesh.Draw();
                }

                #endregion

                #region Multipass Bloom

                BlurEffect.CurrentTechnique = BlurEffect.Techniques["Blur"];

                var bloomTexture           = FirstPassBloomRenderTarget;
                var finalBloomRenderTarget = SecondPassBloomRenderTarget;

                for (var index = 0; index < PassCount; index++)
                {
                    GraphicsDevice.SetRenderTarget(finalBloomRenderTarget);
                    GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

                    BlurEffect.Parameters["baseTexture"].SetValue(bloomTexture);
                    FullScreenQuad.Draw(BlurEffect);

                    if (index != PassCount - 1)
                    {
                        var auxiliar = bloomTexture;
                        bloomTexture           = finalBloomRenderTarget;
                        finalBloomRenderTarget = auxiliar;
                    }
                }

                #endregion

                #region Final Pass

                GraphicsDevice.DepthStencilState = DepthStencilState.None;

                GraphicsDevice.SetRenderTarget(null);
                GraphicsDevice.Clear(Color.Black);

                BloomEffect.CurrentTechnique = BloomEffect.Techniques["Integrate"];
                BloomEffect.Parameters["baseTexture"].SetValue(MainSceneRenderTarget);
                BloomEffect.Parameters["bloomTexture"].SetValue(finalBloomRenderTarget);
                FullScreenQuad.Draw(BloomEffect);

                #endregion
            }
            else
            if (State == GameState.Win)
            {
                SpriteBatch.Begin(samplerState: GraphicsDevice.SamplerStates[0],
                                  rasterizerState: GraphicsDevice.RasterizerState);
                SpriteBatch.Draw(Victory,
                                 new Rectangle(200, 100, 600, 600),
                                 Color.White);
                SpriteBatch.End();
            }
            else
            if (State == GameState.GameOver)
            {
                SpriteBatch.Begin(samplerState: GraphicsDevice.SamplerStates[0],
                                  rasterizerState: GraphicsDevice.RasterizerState);
                SpriteBatch.Draw(GameOver,
                                 new Rectangle(200, 100, 600, 600), Color.White);
                SpriteBatch.End();
            }

            base.Draw(gameTime);
        }
        /// <summary>
        ///     Draws the scene with shadows.
        /// </summary>
        private void DrawShadows()
        {
            #region Pass 1

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            // Set the render target as our shadow map, we are drawing the depth into this texture
            GraphicsDevice.SetRenderTarget(ShadowMapRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            Effect.CurrentTechnique = Effect.Techniques["DepthPass"];

            // We get the base transform for each mesh
            var modelMeshesBaseTransforms = new Matrix[Model.Bones.Count];
            Model.CopyAbsoluteBoneTransformsTo(modelMeshesBaseTransforms);
            foreach (var modelMesh in Model.Meshes)
            {
                foreach (var part in modelMesh.MeshParts)
                {
                    part.Effect = Effect;
                }

                // We set the main matrices for each mesh to draw
                var worldMatrix = modelMeshesBaseTransforms[modelMesh.ParentBone.Index];

                // WorldViewProjection is used to transform from model space to clip space
                Effect.Parameters["WorldViewProjection"]
                .SetValue(worldMatrix * TargetLightCamera.View * TargetLightCamera.Projection);

                // Once we set these matrices we draw
                modelMesh.Draw();
            }

            #endregion

            #region Pass 2

            // Set the render target as null, we are drawing on the screen!
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0);

            Effect.CurrentTechnique = Effect.Techniques["DrawShadowedPCF"];
            Effect.Parameters["baseTexture"].SetValue(BasicEffect.Texture);
            Effect.Parameters["shadowMap"].SetValue(ShadowMapRenderTarget);
            Effect.Parameters["lightPosition"].SetValue(LightPosition);
            Effect.Parameters["shadowMapSize"].SetValue(Vector2.One * ShadowmapSize);
            Effect.Parameters["LightViewProjection"].SetValue(TargetLightCamera.View * TargetLightCamera.Projection);
            foreach (var modelMesh in Model.Meshes)
            {
                foreach (var part in modelMesh.MeshParts)
                {
                    part.Effect = Effect;
                }

                // We set the main matrices for each mesh to draw
                var worldMatrix = modelMeshesBaseTransforms[modelMesh.ParentBone.Index];

                // WorldViewProjection is used to transform from model space to clip space
                Effect.Parameters["WorldViewProjection"].SetValue(worldMatrix * Camera.View * Camera.Projection);
                Effect.Parameters["World"].SetValue(worldMatrix);
                Effect.Parameters["InverseTransposeWorld"].SetValue(Matrix.Transpose(Matrix.Invert(worldMatrix)));

                // Once we set these matrices we draw
                modelMesh.Draw();
            }

            LightBox.Draw(Matrix.CreateTranslation(LightPosition), Camera.View, Camera.Projection);

            #endregion

            // Debug our shadowmap!
            // Show a simple quad with the texture
            DebugTextureEffect.Parameters["World"].SetValue(QuadShadowsWorld);
            DebugTextureEffect.Parameters["baseTexture"].SetValue(ShadowMapRenderTarget);
            FullScreenQuad.Draw(DebugTextureEffect);
        }
Exemple #29
0
        /// <summary>
        ///     Draws the scene with a multiple-light bloom.
        /// </summary>
        private void DrawBloom()
        {
            #region Pass 1

            // Use the default blend and depth configuration
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            // Set the main render target, here we'll draw the base scene
            GraphicsDevice.SetRenderTarget(MainSceneRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            // Assign the basic effect and draw
            foreach (var modelMesh in Model.Meshes)
            {
                foreach (var part in modelMesh.MeshParts)
                {
                    part.Effect = BasicEffect;
                }
            }
            Model.Draw(Matrix.Identity, Camera.View, Camera.Projection);

            #endregion

            #region Pass 2

            // Set the render target as our bloomRenderTarget, we are drawing the bloom color into this texture
            GraphicsDevice.SetRenderTarget(FirstPassBloomRenderTarget);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

            Effect.CurrentTechnique = Effect.Techniques["BloomPass"];
            Effect.Parameters["baseTexture"].SetValue(BasicEffect.Texture);

            // We get the base transform for each mesh
            var modelMeshesBaseTransforms = new Matrix[Model.Bones.Count];
            Model.CopyAbsoluteBoneTransformsTo(modelMeshesBaseTransforms);
            foreach (var modelMesh in Model.Meshes)
            {
                foreach (var part in modelMesh.MeshParts)
                {
                    part.Effect = Effect;
                }

                // We set the main matrices for each mesh to draw
                var worldMatrix = modelMeshesBaseTransforms[modelMesh.ParentBone.Index];

                // WorldViewProjection is used to transform from model space to clip space
                Effect.Parameters["WorldViewProjection"].SetValue(worldMatrix * Camera.View * Camera.Projection);

                // Once we set these matrices we draw
                modelMesh.Draw();
            }

            #endregion

            #region Multipass Bloom

            // Now we apply a blur effect to the bloom texture
            // Note that we apply this a number of times and we switch
            // the render target with the source texture
            // Basically, this applies the blur effect N times
            BlurEffect.CurrentTechnique = BlurEffect.Techniques["Blur"];

            var bloomTexture           = FirstPassBloomRenderTarget;
            var finalBloomRenderTarget = SecondPassBloomRenderTarget;

            for (var index = 0; index < PassCount; index++)
            {
                //Exchange(ref SecondaPassBloomRenderTarget, ref FirstPassBloomRenderTarget);

                // Set the render target as null, we are drawing into the screen now!
                GraphicsDevice.SetRenderTarget(finalBloomRenderTarget);
                GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0);

                BlurEffect.Parameters["baseTexture"].SetValue(bloomTexture);
                FullScreenQuad.Draw(BlurEffect);

                if (index != PassCount - 1)
                {
                    var auxiliar = bloomTexture;
                    bloomTexture           = finalBloomRenderTarget;
                    finalBloomRenderTarget = auxiliar;
                }
            }

            #endregion

            #region Final Pass

            // Set the depth configuration as none, as we don't use depth in this pass
            GraphicsDevice.DepthStencilState = DepthStencilState.None;

            // Set the render target as null, we are drawing into the screen now!
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);

            // Set the technique to our blur technique
            // Then draw a texture into a full-screen quad
            // using our rendertarget as texture
            Effect.CurrentTechnique = Effect.Techniques["Integrate"];
            Effect.Parameters["baseTexture"].SetValue(MainSceneRenderTarget);
            Effect.Parameters["bloomTexture"].SetValue(finalBloomRenderTarget);
            FullScreenQuad.Draw(Effect);

            #endregion

            // Debug our scene texture!
            // Show a simple quad with the texture
            DebugTextureEffect.Parameters["World"].SetValue(QuadSceneWorld);
            DebugTextureEffect.Parameters["baseTexture"].SetValue(MainSceneRenderTarget);
            FullScreenQuad.Draw(DebugTextureEffect);

            // Debug our bloom texture!
            // Show a simple quad with the texture
            DebugTextureEffect.Parameters["World"].SetValue(QuadBloomWorld);
            DebugTextureEffect.Parameters["baseTexture"].SetValue(finalBloomRenderTarget);
            FullScreenQuad.Draw(DebugTextureEffect);

            // Set the render targets as they were
            // Exchange(ref SecondPassBloomRenderTarget, ref FirstPassBloomRenderTarget);
        }
Exemple #30
0
        /// <summary>
        ///     Draws the scene with an environment map.
        /// </summary>
        private void DrawEnvironmentMap()
        {
            #region Pass 1-6

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            // Draw to our cubemap from the robot position
            for (var face = CubeMapFace.PositiveX; face <= CubeMapFace.NegativeZ; face++)
            {
                // Set the render target as our cubemap face, we are drawing the scene in this texture
                GraphicsDevice.SetRenderTarget(EnvironmentMapRenderTarget, face);
                GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0);

                SetCubemapCameraForOrientation(face);
                CubeMapCamera.BuildView();

                // Draw our scene. Do not draw our tank as it would be occluded by itself
                // (if it has backface culling on)
                Scene.Draw(Matrix.Identity, CubeMapCamera.View, CubeMapCamera.Projection);
            }

            #endregion

            #region Pass 7

            // Set the render target as null, we are drawing on the screen!
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0);


            // Draw our scene with the default effect and default camera
            Scene.Draw(Matrix.Identity, Camera.View, Camera.Projection);

            // Draw our sphere

            #region Draw Sphere

            Effect.CurrentTechnique = Effect.Techniques["EnvironmentMapSphere"];
            Effect.Parameters["environmentMap"].SetValue(EnvironmentMapRenderTarget);
            Effect.Parameters["eyePosition"].SetValue(Camera.Position);

            var sphereWorld = Matrix.CreateTranslation(SpherePosition);

            // World is used to transform from model space to world space
            Effect.Parameters["World"].SetValue(sphereWorld);
            // InverseTransposeWorld is used to rotate normals
            Effect.Parameters["InverseTransposeWorld"]?.SetValue(Matrix.Transpose(Matrix.Invert(sphereWorld)));
            // WorldViewProjection is used to transform from model space to clip space
            Effect.Parameters["WorldViewProjection"].SetValue(sphereWorld * Camera.View * Camera.Projection);

            Sphere.Draw(Effect);

            #endregion


            #region Draw Robot

            // Set up our Effect to draw the robot
            Effect.CurrentTechnique = Effect.Techniques["EnvironmentMap"];
            Effect.Parameters["baseTexture"].SetValue(BasicEffect.Texture);

            // We get the base transform for each mesh
            var modelMeshesBaseTransforms = new Matrix[Robot.Bones.Count];
            Robot.CopyAbsoluteBoneTransformsTo(modelMeshesBaseTransforms);

            var worldMatrix = Matrix.CreateTranslation(RobotPosition);
            // World is used to transform from model space to world space
            Effect.Parameters["World"].SetValue(worldMatrix);
            // InverseTransposeWorld is used to rotate normals
            Effect.Parameters["InverseTransposeWorld"]?.SetValue(Matrix.Transpose(Matrix.Invert(worldMatrix)));

            // WorldViewProjection is used to transform from model space to clip space
            Effect.Parameters["WorldViewProjection"].SetValue(worldMatrix * Camera.View * Camera.Projection);

            Robot.Meshes.FirstOrDefault().Draw();

            #endregion


            // Debug our cubemap!
            // Show a quad
            DebugTextureEffect.Parameters["World"].SetValue(QuadWorld);
            DebugTextureEffect.Parameters["cubeMapTexture"]?.SetValue(EnvironmentMapRenderTarget);
            FullScreenQuad.Draw(DebugTextureEffect);

            #endregion
        }