private void ClearTargets(RenderTargetBinding[] targets, SharpDX.Direct3D11.CommonShaderStage shaderStage)
        {
            // NOTE: We make the assumption here that the caller has
            // locked the d3dContext for us to use.

            // We assume 4 targets to avoid a loop within a loop below.
            var target0 = targets[0].RenderTarget;
            var target1 = targets[1].RenderTarget;
            var target2 = targets[2].RenderTarget;
            var target3 = targets[3].RenderTarget;

            // Make one pass across all the texture slots.
            for (var i = 0; i < _textures.Length; i++)
            {
                if (_textures[i] == null)
                    continue;

                if (_textures[i] != target0 &&
                    _textures[i] != target1 &&
                    _textures[i] != target2 &&
                    _textures[i] != target3)
                    continue;

                // Immediately clear the texture from the device.
                _dirty &= ~(1 << i);
                _textures[i] = null;
                shaderStage.SetShaderResource(i, null);
            }
        }
Exemple #2
0
        private MyShadowMapData TSMShadowMap(ScriptableRenderContext context, MyRenderingData renderingData,
                                             ShadowSettings settings, int lightIndex)
        {
            var camera = renderingData.camera;

            if (settings.debug)
            {
                camera = GameObject.Find("Main Camera").GetComponent <Camera>();
            }
            var(view, projection) = GetShadowViewProjection(settings, renderingData, lightIndex);

            var cmd = CommandBufferPool.Get();

            cmd.Clear();
            var depthBuf = IdentifierPool.Get();

            cmd.GetTemporaryRT(depthBuf, settings.resolution, settings.resolution, 32, FilterMode.Point,
                               RenderTextureFormat.Depth);

            RenderTargetBinding binding = new RenderTargetBinding();

            binding.depthRenderTarget = depthBuf;
            cmd.SetRenderTarget(depthBuf);
            cmd.ClearRenderTarget(true, true, Color.black);

            MyShadowMapData shadowMapData = new MyShadowMapData()
            {
                shadowMapIdentifier = depthBuf,
                bias        = settings.bias,
                shadowType  = ShadowAlgorithms.TSM,
                world2Light = GL.GetGPUProjectionMatrix(projection, true) * view,
            };

            var trapezoidalTransfrom = TSMTransform(camera, shadowMapData.world2Light, settings);

            shadowMapData.postTransform = trapezoidalTransfrom;


            cmd.SetViewProjectionMatrices(view, projection);
            cmd.SetGlobalDepthBias(settings.depthBias, settings.normalBias);
            cmd.SetGlobalMatrix("_ShadowPostTransform", trapezoidalTransfrom);
            cmd.SetGlobalFloat("_SlopeDepthBias", -settings.normalBias);
            cmd.SetGlobalFloat("_DepthBias", -Mathf.Pow(2, settings.depthBias));

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();


            DrawShadowCasters(context, renderingData, shadowMapData, PassTSM);

            cmd.SetViewProjectionMatrices(renderingData.camera.worldToCameraMatrix,
                                          renderingData.camera.projectionMatrix);

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();

            CommandBufferPool.Release(cmd);

            return(shadowMapData);
        }
Exemple #3
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            player.Sprite       = Content.Load <Texture2D>("Entities/ship_diffuse");
            player.SpriteNormal = Content.Load <Texture2D>("Entities/ship_normal");

            particles_d = Content.Load <Texture2D>("Particles/particles_diffuse");
            particles_n = Content.Load <Texture2D>("Particles/particles_normal");

            GameEffects.Effects.Add("NormalMappedSprite", Content.Load <Effect>("Effects/NormalMappedSprite"));

            ZBuffer        = new RenderTargetBinding[2];
            ZBufferTargets = new RenderTarget2D[2];

            vw = GraphicsDevice.Viewport.Width;
            vh = GraphicsDevice.Viewport.Height;

            cameraMatrix             = Matrix.Identity;
            cameraMatrix.Translation = new Vector3(vw / 4, vh / 4, 0);

            ZBufferTargets[0] = new RenderTarget2D(GraphicsDevice, vw / 2, vh / 2); // Diffuse
            ZBufferTargets[1] = new RenderTarget2D(GraphicsDevice, vw / 2, vh / 2); // Normal
            ZBuffer[0]        = new RenderTargetBinding(ZBufferTargets[0]);         // Diffuse
            ZBuffer[1]        = new RenderTargetBinding(ZBufferTargets[1]);         // Normal

            OutputTarget = new RenderTarget2D(GraphicsDevice, vw, vh);

            //MusicController.LoadMusic(Content);

            //MusicController.PlayMusic();
        }
Exemple #4
0
    public VXGIRenderer(VXGIRenderPipeline renderPipeline)
    {
        _command = new CommandBuffer {
            name = "VXGI.Renderer"
        };
        _eventCommand   = new CommandBuffer();
        _filterSettings = new FilterRenderersSettings(true);
        _renderPipeline = renderPipeline;

        _gBufferBinding = new RenderTargetBinding(
            new RenderTargetIdentifier[] { ShaderIDs._CameraGBufferTexture0, ShaderIDs._CameraGBufferTexture1, ShaderIDs._CameraGBufferTexture2, ShaderIDs._CameraGBufferTexture3 },
            new[] { RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare },
            new[] { RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare },
            ShaderIDs._CameraDepthTexture, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare
            );

        _renderScale = new float[] { 1f, 1f, 1f, 1f };

        _lightingPasses = new LightingShader[] {
            new LightingShader(LightingShader.Pass.Emission),
            new LightingShader(LightingShader.Pass.DirectDiffuseSpecular),
            new LightingShader(LightingShader.Pass.IndirectDiffuse),
            new LightingShader(LightingShader.Pass.IndirectSpecular)
        };

        _postProcessRenderContext = new PostProcessRenderContext();
    }
Exemple #5
0
        public override void SetWindowSize(Vector2 WindowSize)
        {
            try
            {
                if (GBufferTargets != null)
                {
                    GBufferTargets[0].RenderTarget.Dispose();
                    GBufferTargets[1].RenderTarget.Dispose();
                    LightMap.Dispose();
                    FinalTarget.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            if (GBufferTargets == null || GBufferTargets[0].RenderTarget.IsDisposed)
            {
                GBufferTargets = new RenderTargetBinding[2];
            }

            GBufferTargets[0] = new RenderTargetBinding(new RenderTarget2D(Game1.graphicsDevice, (int)WindowSize.X, (int)WindowSize.Y, false, SurfaceFormat.Color, DepthFormat.Depth24));
            GBufferTargets[1] = new RenderTargetBinding(new RenderTarget2D(Game1.graphicsDevice, (int)WindowSize.X, (int)WindowSize.Y, false, SurfaceFormat.Single, DepthFormat.Depth24));
            LightMap          = new RenderTarget2D(Game1.graphicsDevice, (int)WindowSize.X, (int)WindowSize.Y, false, SurfaceFormat.Rgba64, DepthFormat.Depth24);
            FinalTarget       = new RenderTarget2D(Game1.graphics.GraphicsDevice, (int)WindowSize.X, (int)WindowSize.Y, false, SurfaceFormat.Color, DepthFormat.Depth24);

            base.SetWindowSize(WindowSize);
        }
Exemple #6
0
        /// <summary>
        /// Load the GBuffer content
        /// </summary>

        public GBufferShader(RenderProfile profile, ContentManager content)
            : base(profile, content)
        {
            // Diffuse/albedo render target
            diffuseRT = profile.AddRenderTarget(
                (int)(backBufferWidth * bufferScaling),
                (int)(backBufferHeight * bufferScaling),
                SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 4);

            // Specular render target
            specularRT = profile.AddRenderTarget(
                (int)(backBufferWidth * bufferScaling),
                (int)(backBufferHeight * bufferScaling),
                SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 4);

            outputTargets    = new RenderTarget2D[4];
            outputTargets[0] = normalRT;
            outputTargets[1] = depthRT;
            outputTargets[2] = diffuseRT;
            //outputTargets[3] = specularRT;

            bindingTargets    = new RenderTargetBinding[3];
            bindingTargets[0] = outputTargets[0];
            bindingTargets[1] = outputTargets[1];
            bindingTargets[2] = outputTargets[2];
            //bindingTargets[3] = outputTargets[3];
        }
 private void GenerateTargetMips()
 {
     for (int i = 0; i < _targetsToMipMapCount; i++)
     {
         RenderTargetBinding binding = _targetsToMipMap[i];
         //Gen cube mips
         if (binding.IsRenderTargetCube)
         {
             RenderTargetCube rcube = binding.RenderTargetCube;
             D3D10Helper.CheckDisposed(rcube);
             if (rcube.MipCount > 1)
             {
                 D3D10TextureCubeImplementation impl = rcube.Implementation as D3D10TextureCubeImplementation;
                 _graphicsDevice.GenerateMips(impl.D3D10ShaderResourceView);
             }
             //Gen 2D tex mips
         }
         else
         {
             RenderTarget2D r2d = binding.RenderTarget2D;
             D3D10Helper.CheckDisposed(r2d);
             if (r2d.MipCount > 1)
             {
                 D3D10Texture2DImplementation impl = r2d.Implementation as D3D10Texture2DImplementation;
                 _graphicsDevice.GenerateMips(impl.D3D10ShaderResourceView);
             }
         }
     }
 }
Exemple #8
0
        public VideoPlayer()
        {
            // Initialize public members.
            IsDisposed = false;
            IsLooped   = false;
            IsMuted    = false;
            State      = MediaState.Stopped;
            Volume     = 1.0f;

            // Initialize private members.
            timer = new Stopwatch();

            // The VideoPlayer will use the GraphicsDevice that is set now.
            currentDevice = Game.Instance.GraphicsDevice;

            // Initialize this here to prevent null GetTexture returns.
            videoTexture    = new RenderTargetBinding[1];
            videoTexture[0] = new RenderTargetBinding(
                new RenderTarget2D(
                    currentDevice,
                    1280,
                    720,
                    false,
                    SurfaceFormat.Color,
                    DepthFormat.None,
                    0,
                    RenderTargetUsage.PreserveContents
                    )
                );

            // Initialize the other GL bits.
            GL_initialize();
        }
 public RenderTargetBinding[] GetOriginalRenderTargetBindingsForQuery()
 {
     for (int i = 0; i < MaxNumberOfRenderTargetBindings; i++)
     {
         _queriedBindings[i] = new RenderTargetBinding();
     }
     return(_queriedBindings);
 }
        private void CreateGBuffer(GraphicFactory factory)
        {
            //One of our premises is to do not use the PRESERVE CONTENTS flags,
            //that is supposed to be more expensive than DISCARD CONTENT.
            //We use a floating point (32bit) buffer for Z values, although our HW use only 24bits.
            //We could use some packing and use a 24bit buffer too, but lets start simpler
            _depthBuffer = factory.CreateRenderTarget(_width, _height, SurfaceFormat.Single, false,
                                                      DepthFormat.None, 0, RenderTargetUsage.DiscardContents);

            //the downsampled depth buffer must have the same format as the main one
            _halfDepth = factory.CreateRenderTarget(_width / 2, _height / 2,
                                                    SurfaceFormat.Single, false, DepthFormat.None, 0,
                                                    RenderTargetUsage.DiscardContents);

            //Our normal buffer stores encoded view-space normal into RG (10bit each) and the specular power in B.
            //Some engines encode the specular power with some log or ln functions. We will output
            //only the normal texture's alpha channel multiplied by a const value (100),
            //so we have specular power in the range [1..100].
            //Currently, A is not used (2bit).
            _normalBuffer = factory.CreateRenderTarget(_width, _height, SurfaceFormat.Color, false,
                                                       DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents);

            //This buffer stores all the "pure" lighting on the scene, no albedo applied to it. We use an floating
            //point format to allow us "overbright" some areas. Read the blog for more information. We use a depth buffer
            //to optimize light rendering.
            _lightBuffer = factory.CreateRenderTarget(_width, _height, SurfaceFormat.HdrBlendable, false,
                                                      DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents);

            //we need a separate texture for the specular, since the xbox doesnt allow a RGBA64 buffer
            _lightSpecularBuffer = factory.CreateRenderTarget(_width, _height,
                                                              SurfaceFormat.HdrBlendable, false, DepthFormat.None, 0,
                                                              RenderTargetUsage.DiscardContents);

            //We need another depth here because we need to render all objects again, to reconstruct their shading
            //using our light texture.
            _outputTexture = factory.CreateRenderTarget(_width, _height, SurfaceFormat.Color, false,
                                                        DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents);

            int halfRes = 2;

            _halfBuffer0 = factory.CreateRenderTarget(_width / halfRes, _height / halfRes,
                                                      SurfaceFormat.Color, false, DepthFormat.None, 0,
                                                      RenderTargetUsage.DiscardContents);
            _halfBuffer1 = factory.CreateRenderTarget(_width / halfRes, _height / halfRes,
                                                      SurfaceFormat.Color, false, DepthFormat.None, 0,
                                                      RenderTargetUsage.DiscardContents);

            _gBufferBinding[0] = new RenderTargetBinding(_normalBuffer);
            _gBufferBinding[1] = new RenderTargetBinding(_depthBuffer);

            _lightAccumBinding[0] = new RenderTargetBinding(_lightBuffer);
            _lightAccumBinding[1] = new RenderTargetBinding(_lightSpecularBuffer);

            target           = factory.CreateRenderTarget(ginfo.BackBufferWidth, ginfo.BackBufferHeight, SurfaceFormat.Color, ginfo.UseMipMap, DepthFormat.Depth24Stencil8, ginfo.MultiSample);
            target2          = factory.CreateRenderTarget(ginfo.BackBufferWidth, ginfo.BackBufferHeight, SurfaceFormat.Color, ginfo.UseMipMap, DepthFormat.Depth24Stencil8, ginfo.MultiSample);
            PostEffectTarget = target;
        }
        internal void ClearTargets(GraphicsDevice device, RenderTargetBinding[] targets)
        {
            if (_applyToVertexStage && !device.GraphicsCapabilities.SupportsVertexTextures)
                return;

            if (_applyToVertexStage)
                ClearTargets(targets, device._d3dContext.VertexShader);
            else
                ClearTargets(targets, device._d3dContext.PixelShader);
        }
 internal void ClearTargets(GraphicsDevice device, RenderTargetBinding[] targets)
 {
     if (_applyToVertexStage)
     {
         ClearTargets(targets, device._d3dContext.VertexShader);
     }
     else
     {
         ClearTargets(targets, device._d3dContext.PixelShader);
     }
 }
        /// <summary>
        /// Configure the pass before execution
        /// </summary>
        /// <param name="baseDescriptor">Current target descriptor</param>
        /// <param name="colorAttachmentHandle">Color attachment to render into</param>
        /// <param name="depthAttachmentHandle">Depth attachment to render into</param>
        /// <param name="configuration">Specific render configuration</param>
        public void Setup(
            RenderTextureDescriptor baseDescriptor,
            RenderTargetHandle colorAttachmentHandle,
            RenderTargetHandle depthAttachmentHandle,
            RendererConfiguration configuration,
            SampleCount samples)
        {
            this._ColorAttachmentHandle = colorAttachmentHandle;
            this._DepthAttachmentHandle = depthAttachmentHandle;
            _Descriptor            = baseDescriptor;
            _RendererConfiguration = configuration;

            if ((int)samples > 1)
            {
                baseDescriptor.bindMS      = false;
                baseDescriptor.msaaSamples = (int)samples;
            }

            baseDescriptor.colorFormat     = RenderTextureFormat.ARGBHalf;
            baseDescriptor.depthBufferBits = 0;
            _DescriptorAC = baseDescriptor;

            baseDescriptor.colorFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RHalf)
                ? RenderTextureFormat.RHalf
                : RenderTextureFormat.ARGBHalf;
            _DescriptorAA = baseDescriptor;

            _AccumColorHandle.Init("_AccumColor");
            _AccumGIHandle.Init("_AccumGI");
            _AccumAlphaHandle.Init("_AccumAlpha");

            _AccumBinding = new RenderTargetBinding(new RenderTargetIdentifier[]
            {
                _AccumColorHandle.Identifier(),
                _AccumGIHandle.Identifier(),
                _AccumAlphaHandle.Identifier(),
            },
                                                    new RenderBufferLoadAction[]
            {
                RenderBufferLoadAction.DontCare,
                RenderBufferLoadAction.DontCare,
                RenderBufferLoadAction.DontCare,
            },
                                                    new RenderBufferStoreAction[]
            {
                RenderBufferStoreAction.Store,
                RenderBufferStoreAction.Store,
                RenderBufferStoreAction.Store,
            },
                                                    _DepthAttachmentHandle.Identifier(),
                                                    RenderBufferLoadAction.Load,
                                                    RenderBufferStoreAction.DontCare);
        }
Exemple #14
0
 public RenderTargetBinding[] GetOriginalRenderTargetBindingsForQuery()
 {
     // Note by gitspathe
     //   Was originally < MaxNumberOfRenderTargetBindings.
     //   Changed to fix a bug which occured in Debug mode.
     _queriedBindings = new RenderTargetBinding[Engine.Device.RenderTargetCount];
     for (int i = 0; i < _queriedBindings.Length; i++)
     {
         _queriedBindings[i] = new RenderTargetBinding();
     }
     return(_queriedBindings);
 }
Exemple #15
0
 /// <summary>
 /// Sets a 2D render target to the first render target slot and unbinds
 /// all currently bound targets.
 /// Setting this to null
 /// unbinds all targets and sets the target to the currently active
 /// swap chain's back buffer.
 /// </summary>
 /// <param name="renderTarget">Render target to bind</param>
 public override void SetRenderTarget(RenderTarget2D renderTarget)
 {
     if (renderTarget == null)
     {
         _renderTargetManager.SetRenderTargets(null);
     }
     else
     {
         _tempTarget[0] = new RenderTargetBinding(renderTarget);
         _renderTargetManager.SetRenderTargets(_tempTarget);
     }
 }
Exemple #16
0
 /// <summary>
 /// Sets a Cube render target, to the first render target slot
 /// and unbinds all currently bound targets.
 /// Setting this to null unbinds all targets and sets the target to the currently active
 /// swap chain's back buffer.
 /// </summary>
 /// <param name="renderTarget">Render target to bind</param>
 /// <param name="cubeMapFace">Which face of the cube map to bind</param>
 public override void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace)
 {
     if (renderTarget == null)
     {
         _renderTargetManager.SetRenderTargets(null);
     }
     else
     {
         _tempTarget[0] = new RenderTargetBinding(renderTarget, cubeMapFace);
         _renderTargetManager.SetRenderTargets(_tempTarget);
     }
 }
        } // Fetch

        /// <summary>
        /// Release the multiple render target.
        /// </summary>
        public static void Release(RenderTargetBinding renderTargetBinding)
        {
            for (int i = 0; i < multipleRenderTargets.Count; i++)
            {
                if (renderTargetBinding == multipleRenderTargets[i])
                {
                    renderTargetBinding.RenderTargets[0].looked = false;
                    return;
                }
            }
            // If not do nothing.
            //throw new ArgumentException("Render Target: Cannot release multiple render target. The multiple render target is not present in the pool.");
        } // Release
        } // DisableCurrentRenderTargets

        #endregion

        #region Binding

        /// <summary>
        /// Bind render targets so that they could be set together without generate garbage in the process.
        /// </summary>
        public static RenderTargetBinding BindRenderTargets(RenderTarget renderTarget1, RenderTarget renderTarget2)
        {
            RenderTargetBinding renderTargetsBinding = new RenderTargetBinding
            {
                InternalBinding = new[]
                {
                    new Microsoft.Xna.Framework.Graphics.RenderTargetBinding(renderTarget1.renderTarget),
                    new Microsoft.Xna.Framework.Graphics.RenderTargetBinding(renderTarget2.renderTarget),
                },
                RenderTargets = new[] { renderTarget1, renderTarget2 }
            };
            renderTarget1.renderTargetBinding = renderTargetsBinding;
            renderTarget2.renderTargetBinding = renderTargetsBinding;
            return renderTargetsBinding;
        } // BindRenderTargets
Exemple #19
0
        private MyShadowMapData StandardShadowMap(ScriptableRenderContext context, MyRenderingData renderingData,
                                                  ShadowSettings settings, int lightIndex)
        {
            var cmd = CommandBufferPool.Get();

            cmd.Clear();
            var depthBuf = IdentifierPool.Get();

            cmd.GetTemporaryRT(depthBuf, settings.resolution, settings.resolution, 32, FilterMode.Point,
                               RenderTextureFormat.Depth);

            RenderTargetBinding binding = new RenderTargetBinding();

            binding.depthRenderTarget = depthBuf;
            cmd.SetRenderTarget(depthBuf);
            cmd.ClearRenderTarget(true, true, Color.black);

            MyShadowMapData shadowMapData = new MyShadowMapData()
            {
                shadowMapIdentifier = depthBuf,
                bias       = settings.bias,
                shadowType = ShadowAlgorithms.Standard,
            };

            var(view, projection) = GetShadowViewProjection(settings, renderingData, lightIndex);

            cmd.SetViewProjectionMatrices(view, projection);

            shadowMapData.world2Light = projection * view;

            cmd.SetGlobalDepthBias(settings.depthBias, settings.normalBias);

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();

            DrawShadowCasters(context, renderingData, shadowMapData, PassSimple);

            cmd.SetViewProjectionMatrices(renderingData.camera.worldToCameraMatrix,
                                          renderingData.camera.projectionMatrix);

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();


            CommandBufferPool.Release(cmd);

            return(shadowMapData);
        }
        } // EnableRenderTarget

        /// <summary>
        /// Enable multiple render targets.
        /// </summary>
        /// <param name="renderTargetBinding">
        /// This structure is used to set multiple render targets without generating garbage in the process.
        /// You can create it using the BindRenderTargets method.
        /// </param>
        public static void EnableRenderTargets(RenderTargetBinding renderTargetBinding)
        {
            if (currentRenderTarget[0] != null)
                throw new InvalidOperationException("Render Target: unable to set render target. Another render target is still set.");
            for (int i = 0; i < renderTargetBinding.RenderTargets.Length; i++)
            {
                currentRenderTarget[i] = renderTargetBinding.RenderTargets[i];
                renderTargetBinding.RenderTargets[i].alreadyResolved = false;
            }
            try
            {
                EngineManager.Device.SetRenderTargets(renderTargetBinding.InternalBinding);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Render Target. Unable to bind the render targets.", e);
            }
        } // EnableRenderTargets
Exemple #21
0
        /// <summary>
        /// Sets the active render targets in this order (Color, Normal, Light).
        /// </summary>
        /// <param name="renderTargetTypes">The render target types requested.</param>
        /// <param name="count">The number of render targets requested.</param>
        public void SetRenderTargets(RenderTargetTypes renderTargetTypes, int count)
        {
            if (renderTargetTypes == RenderTargetTypes.None)
            {
                this.GraphicsDevice.SetRenderTarget(null);
            }
            else
            {
                RenderTargetBinding[] renderTargets = new RenderTargetBinding[count];

                if (this.renderTargets.GetRenderTargets(renderTargetTypes, ref renderTargets) != count)
                {
                    Logger.Throw(Logger.Level.Fatal, new InvalidOperationException("Specified render target count differs from count received."));
                }

                this.GraphicsDevice.SetRenderTargets(renderTargets);
            }
        }
Exemple #22
0
        private void MakeRenderTargets()
        {
            if (DEFERRED_RENDERING)
            {
#if WINDOWS
                var POSITION_BUFFER = new RenderTargetBinding(MakeDefaultRenderTarget(SurfaceFormat.Vector4, DepthFormat.Depth24)); // for now, holds the depth, TODO: why can't I just use Single? adds weird alpha
                var NORMAL_BUFFER   = new RenderTargetBinding(MakeDefaultRenderTarget(SurfaceFormat.Vector4, DepthFormat.Depth24)); // for now, holds the normal relative to the camera (after perspective is applid)
                var ALBEDO_BUFFER   = new RenderTargetBinding(MakeDefaultRenderTarget());                                           // holds the color
                G_BUFFER = new[] { POSITION_BUFFER, NORMAL_BUFFER, ALBEDO_BUFFER };
#else
                var PNA_BUFFER = new RenderTargetBinding(MakeDefaultRenderTarget(SurfaceFormat.HalfVector4, DepthFormat.Depth24)); // holds everything
                G_BUFFER = new[] { PNA_BUFFER };
#endif
            }
            RENDER_BUFFER        = new[] { new RenderTargetBinding(MakeDefaultRenderTarget()) };
            TREE_DENSITY_BUFFER  = new[] { new RenderTargetBinding(MakeDefaultRenderTarget()) };
            GRASS_DENSITY_BUFFER = new[] { new RenderTargetBinding(MakeDefaultRenderTarget()) };
        }
Exemple #23
0
        private void RenderGBuffer(CameraFrustumQuery frustumQuery, RenderContext context)
        {
            // Create render targets for the G-buffer.
            context.GBuffer0 = GraphicsService.RenderTargetPool.Obtain2D(
                new RenderTargetFormat(
                    context.Viewport.Width,
                    context.Viewport.Height,
                    true, // Note: Only the SaoFilter for SSAO requires mipmaps to boost performance.
                    SurfaceFormat.Single,
                    DepthFormat.Depth24Stencil8));
            context.GBuffer1 = GraphicsService.RenderTargetPool.Obtain2D(
                new RenderTargetFormat(
                    context.Viewport.Width,
                    context.Viewport.Height,
                    false,
                    SurfaceFormat.Color,
                    DepthFormat.None));

            var graphicsDevice = GraphicsService.GraphicsDevice;

            _renderTargetBindings[0] = new RenderTargetBinding(context.GBuffer0);
            _renderTargetBindings[1] = new RenderTargetBinding(context.GBuffer1);
            graphicsDevice.SetRenderTargets(_renderTargetBindings);

            // Update the info in the render context. Some renderers or effects might use this info.
            context.RenderTarget = context.GBuffer0;
            context.Viewport     = graphicsDevice.Viewport;

            // Clear the depth-stencil buffer.
            graphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Stencil, Color.Black, 1, 0);

            // Reset the G-buffer to default values.
            _clearGBufferRenderer.Render(context);

            // Render the meshes using the "GBuffer" material pass.
            graphicsDevice.DepthStencilState = DepthStencilState.Default;
            graphicsDevice.RasterizerState   = RasterizerState.CullCounterClockwise;
            graphicsDevice.BlendState        = BlendState.Opaque;
            context.RenderPass = "******";
            _meshRenderer.Render(frustumQuery.SceneNodes, context);
            context.RenderPass = null;
        }
Exemple #24
0
        /// <summary>
        /// Begins the rendering of the scene using DepthNormalEffect.
        /// </summary>
        private void Begin(DrawingContext3D context)
        {
            if (hasSceneBegin || hasLightBegin)
            {
                throw new InvalidOperationException("Begin cannot be called until End has been successfully called.");
            }

            hasSceneBegin = true;

            CreateDepthNormalBuffers();

            // Maintain render target stack
            Nine.Graphics.GraphicsExtensions.PushRenderTarget(context.graphics, null);

            renderTargetBinding[0] = new RenderTargetBinding(depthBuffer);
            renderTargetBinding[1] = new RenderTargetBinding(normalBuffer);

            GraphicsDevice.SetRenderTargets(renderTargetBinding);
            GraphicsDevice.BlendState = BlendState.Opaque;

            ClearRenderTargets(context);
        }
    public VXGIRenderer(VXGIRenderPipeline renderPipeline)
    {
        _command = new CommandBuffer {
            name = "VXGIRenderer"
        };
        _filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.all
        };
        _renderPipeline = renderPipeline;

        _cameraDepthTextureID        = Shader.PropertyToID("_CameraDepthTexture");
        _cameraDepthNormalsTextureID = Shader.PropertyToID("_CameraDepthNormalsTexture");
        _cameraGBufferTexture0ID     = Shader.PropertyToID("_CameraGBufferTexture0");
        _cameraGBufferTexture1ID     = Shader.PropertyToID("_CameraGBufferTexture1");
        _cameraGBufferTexture2ID     = Shader.PropertyToID("_CameraGBufferTexture2");
        _cameraGBufferTexture3ID     = Shader.PropertyToID("_CameraGBufferTexture3");
        _dummyID       = Shader.PropertyToID("Dummy");
        _frameBufferID = Shader.PropertyToID("FrameBuffer");

        _gBufferBinding = new RenderTargetBinding(
            new RenderTargetIdentifier[] { _cameraGBufferTexture0ID, _cameraGBufferTexture1ID, _cameraGBufferTexture2ID, _cameraGBufferTexture3ID },
            new[] { RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare },
            new[] { RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare },
            _cameraDepthTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare
            );

        _renderScale = new float[] { 1f, 1f, 1f, 1f };

        _lightingPasses = new LightingShader[] {
            new LightingShader(LightingShader.Pass.Emission),
            new LightingShader(LightingShader.Pass.DirectDiffuseSpecular),
            new LightingShader(LightingShader.Pass.IndirectDiffuse),
            new LightingShader(LightingShader.Pass.IndirectSpecular)
        };

        _postProcessRenderContext = new PostProcessRenderContext();
    }
Exemple #26
0
        public static void updateSettings()
        {
            if (m_gBufferDiffuse != null)
            {
                m_gBufferDiffuse.Dispose();
                m_gBufferDepth.Dispose();
                m_gBufferNormal.Dispose();
            }

            // Color buffer
            m_gBufferDiffuse = new RenderTarget2D(m_device, m_device.Viewport.Width, m_device.Viewport.Height,
                                                  false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);
            // Depth buffer
            m_gBufferDepth = new RenderTarget2D(m_device, m_device.Viewport.Width, m_device.Viewport.Height,
                                                false, SurfaceFormat.Single, DepthFormat.None);
            // Normal buffer
            m_gBufferNormal = new RenderTarget2D(m_device, m_device.Viewport.Width, m_device.Viewport.Height,
                                                 false, SurfaceFormat.Color, DepthFormat.None);

            m_gBufferBindings[0] = new RenderTargetBinding(m_gBufferDiffuse);
            m_gBufferBindings[1] = new RenderTargetBinding(m_gBufferDepth);
            m_gBufferBindings[2] = new RenderTargetBinding(m_gBufferNormal);
        }
Exemple #27
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, screenWidth / screenHeight, 1.0f, 100.0f);

            renderTargetBindings    = new RenderTargetBinding[3];
            renderTargetBindings[0] = new RenderTargetBinding(new RenderTarget2D(GraphicsDevice, screenWidth, screenHeight, false, SurfaceFormat.Color, DepthFormat.Depth16));  //Color
            renderTargetBindings[1] = new RenderTargetBinding(new RenderTarget2D(GraphicsDevice, screenWidth, screenHeight, false, SurfaceFormat.Color, DepthFormat.Depth16));  //Normal
            renderTargetBindings[2] = new RenderTargetBinding(new RenderTarget2D(GraphicsDevice, screenWidth, screenHeight, false, SurfaceFormat.Single, DepthFormat.Depth16)); //Depth

            cubeMesh     = Mesh.CreateCubeMesh(0.4f);
            bricks       = Content.Load <Texture2D>("brickwork-texture");
            bricksNormal = Content.Load <Texture2D>("brickwork_normal-map");

            clearBufferEffect = Content.Load <Effect>("ClearGBuffer");

            deferredRenderEffect = Content.Load <Effect>("DeferredRenderEffect");
            deferredRenderEffect.Parameters["DiffuseTexture"].SetValue(bricks);
            deferredRenderEffect.Parameters["World"].SetValue(Matrix.Identity);
            deferredRenderEffect.Parameters["Projection"].SetValue(projectionMatrix);

            directionalLightEffect = Content.Load <Effect>("DirectionalLightEffect");
            directionalLightEffect.Parameters["DiffuseMap"].SetValue(renderTargetBindings[0].RenderTarget);
            directionalLightEffect.Parameters["NormalMap"].SetValue(renderTargetBindings[1].RenderTarget);
            directionalLightEffect.Parameters["DepthMap"].SetValue(renderTargetBindings[2].RenderTarget);
            directionalLightEffect.Parameters["lightDirection"].SetValue(-Vector3.UnitY);
            directionalLightEffect.Parameters["Color"].SetValue(Color.BlueViolet.ToVector3());
            directionalLightEffect.Parameters["halfPixel"].SetValue(new Vector2(0.5f / screenWidth, 0.5f / screenHeight));

            quadRenderer = new QuadRenderComponent(this);

            //ship = Content.Load<Model>("Models/ship1");
            //volleyBall = Content.Load<Model>("volleyBall");
            //e = new BasicEffect(GraphicsDevice);
        }
Exemple #28
0
        public void Play(Video video)
        {
            checkDisposed();

            // We need to assign this regardless of what happens next.
            Video = video;

            // FIXME: This is a part of the Duration hack!
            if (Video.needsDurationHack)
            {
                Video.Duration = TimeSpan.MaxValue;
            }

            // Check the player state before attempting anything.
            if (State != MediaState.Stopped)
            {
                return;
            }

            // Update the player state now, before initializing
            State = MediaState.Playing;

            // Carve out YUV buffer before doing any decoder work
            if (yuvData != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(yuvData);
            }
            yuvData = Marshal.AllocHGlobal(
                (Video.yWidth * Video.yHeight) +
                (Video.uvWidth * Video.uvHeight * 2)
                );

            // Hook up the decoder to this player
            InitializeTheoraStream();

            // Set up the texture data
            if (Theorafile.tf_hasvideo(Video.theora) == 1)
            {
                // The VideoPlayer will use the GraphicsDevice that is set now.
                if (currentDevice != Video.GraphicsDevice)
                {
                    GL_dispose();
                    currentDevice = Video.GraphicsDevice;
                    GL_initialize();
                }

                RenderTargetBinding overlap = videoTexture[0];
                videoTexture[0] = new RenderTargetBinding(
                    new RenderTarget2D(
                        currentDevice,
                        Video.yWidth,
                        Video.yHeight,
                        false,
                        SurfaceFormat.Color,
                        DepthFormat.None,
                        0,
                        RenderTargetUsage.PreserveContents
                        )
                    );
                if (overlap.RenderTarget != null)
                {
                    overlap.RenderTarget.Dispose();
                }
                GL_setupTextures(
                    Video.yWidth,
                    Video.yHeight,
                    Video.uvWidth,
                    Video.uvHeight
                    );
            }

            // The player can finally start now!
            timer.Start();
            if (audioStream != null)
            {
                audioStream.Play();
            }
        }
Exemple #29
0
        private void ProcessClipmap(TerrainNode node, TerrainClipmap clipmap, RenderContext context)
        {
            var graphicsDevice = context.GraphicsService.GraphicsDevice;
            var lodCameraNode  = context.LodCameraNode ?? context.CameraNode;

            bool isBaseClipmap = (node.BaseClipmap == clipmap);

            // Update the clipmap render targets if necessary.
            InitializeClipmapTextures(graphicsDevice, clipmap);

            // Update other clipmap data (origins, offsets, ...). No rendering.
            // (Data is stored in TerrainClipmap class.)
            UpdateClipmapData(node, clipmap, lodCameraNode, isBaseClipmap);

            // Compute which rectangular regions need to be updated.
            // (Data is stored in TerrainClipmap class.)
            ComputeInvalidRegions(node, clipmap, isBaseClipmap);

            // Abort if there are no invalid regions.
            int numberOfInvalidRegions = 0;

            for (int level = 0; level < clipmap.NumberOfLevels; level++)
            {
                numberOfInvalidRegions += clipmap.InvalidRegions[level].Count;
            }

            Debug.Assert(numberOfInvalidRegions > 0 || clipmap.UseIncrementalUpdate,
                         "If the clipmap update is not incremental, there must be at least one invalid region.");

            if (numberOfInvalidRegions == 0)
            {
                return;
            }

            // Set render target binding to render into all clipmap textures at once.
            int numberOfTextures = clipmap.Textures.Length;

            if (_renderTargetBindings[numberOfTextures] == null)
            {
                _renderTargetBindings[numberOfTextures] = new RenderTargetBinding[numberOfTextures];
            }

            for (int i = 0; i < numberOfTextures; i++)
            {
                _renderTargetBindings[numberOfTextures][i] = new RenderTargetBinding((RenderTarget2D)clipmap.Textures[i]);
            }

            switch (numberOfTextures)
            {
            case 1: context.Technique = "RenderTargets1"; break;

            case 2: context.Technique = "RenderTargets2"; break;

            case 3: context.Technique = "RenderTargets3"; break;

            case 4: context.Technique = "RenderTargets4"; break;

            default: context.Technique = null; break;
            }

            graphicsDevice.SetRenderTargets(_renderTargetBindings[numberOfTextures]);

            // The viewport covers the whole texture atlas.
            var viewport = graphicsDevice.Viewport;

            context.Viewport = viewport;

            Debug.Assert(_previousMaterialBinding == null);

            // Loop over all layers. Render each layer into all levels (if there is an invalid region).
            Aabb tileAabb = new Aabb(new Vector3(-Terrain.TerrainLimit), new Vector3(Terrain.TerrainLimit));

            ProcessLayer(graphicsDevice, context, clipmap, isBaseClipmap, _clearLayer, tileAabb);
            foreach (var tile in node.Terrain.Tiles)
            {
                tileAabb       = tile.Aabb;
                context.Object = tile;
                ProcessLayer(graphicsDevice, context, clipmap, isBaseClipmap, tile, tileAabb);

                foreach (var layer in tile.Layers)
                {
                    ProcessLayer(graphicsDevice, context, clipmap, isBaseClipmap, layer, tileAabb);
                }

                context.Object = null;
            }

            _previousMaterialBinding = null;

            ClearFlags(_clearLayer, context);
            foreach (var tile in node.Terrain.Tiles)
            {
                ClearFlags(tile, context);
                foreach (var layer in tile.Layers)
                {
                    ClearFlags(layer, context);
                }
            }

            // All invalid regions handled.
            for (int i = 0; i < clipmap.NumberOfLevels; i++)
            {
                clipmap.InvalidRegions[i].Clear();
            }

            // The next time we can update incrementally.
            clipmap.UseIncrementalUpdate = true;
        }
 internal void ClearTargets(GraphicsDevice device, RenderTargetBinding[] targets)
 {
     ClearTargets(targets, device._d3dContext.VertexShader);
     ClearTargets(targets, device._d3dContext.PixelShader);
 }
        public void Render(IList <SceneNode> sceneNodes, IList <SceneNode> decalNodes, RenderContext context)
        {
            var graphicsService  = context.GraphicsService;
            var graphicsDevice   = graphicsService.GraphicsDevice;
            var renderTargetPool = graphicsService.RenderTargetPool;
            var target           = context.RenderTarget;
            var viewport         = context.Viewport;

            // The G-buffer consists of two full-screen render targets into which we render
            // depth values, normal vectors and other information.
            var width  = context.Viewport.Width;
            var height = context.Viewport.Height;

            context.GBuffer0 = renderTargetPool.Obtain2D(new RenderTargetFormat(
                                                             width,
                                                             height,

                                                             true, // Note: Only the SaoFilter for SSAO requires mipmaps to boost performance.

                                                             SurfaceFormat.Single,
                                                             DepthFormat.Depth24Stencil8));
            context.GBuffer1 = renderTargetPool.Obtain2D(new RenderTargetFormat(width, height, false, SurfaceFormat.Color, DepthFormat.None));

            // Set the device render target to the G-buffer.
            _renderTargetBindings[0] = new RenderTargetBinding(context.GBuffer0);
            _renderTargetBindings[1] = new RenderTargetBinding(context.GBuffer1);
            graphicsDevice.SetRenderTargets(_renderTargetBindings);
            context.RenderTarget = context.GBuffer0;

            graphicsDevice.DepthStencilState = DepthStencilState.None;
            graphicsDevice.RasterizerState   = RasterizerState.CullNone;
            graphicsDevice.BlendState        = BlendState.Opaque;

            // Clear the z-buffer.
            graphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Stencil, Color.Black, 1, 0);

            // Initialize the G-buffer with default values.
            _clearGBufferRenderer.Render(context);

            // Render the scene nodes using the "GBuffer" material pass.
            context.RenderPass = "******";
            graphicsDevice.DepthStencilState = DepthStencilState.Default;
            graphicsDevice.RasterizerState   = RasterizerState.CullCounterClockwise;
            graphicsDevice.BlendState        = BlendState.Opaque;
            _sceneNodeRenderer.Render(sceneNodes, context);

            if (_decalRenderer != null && decalNodes.Count > 0)
            {
                // Render decal nodes using the "GBuffer" material pass.
                // Decals are rendered as "deferred decals". The geometry information is
                // read from GBuffer0 and the decal normals are blended with GBuffer1, which
                // has to be set as the first render target. (That means a new GBuffer1 is
                // created. The original GBuffer1 is recycled afterwards.)
                var renderTarget = renderTargetPool.Obtain2D(new RenderTargetFormat(width, height, false, SurfaceFormat.Color, DepthFormat.None));
                graphicsDevice.SetRenderTarget(renderTarget);
                context.RenderTarget = renderTarget;

                // Copy GBuffer1 to current render target and restore the depth buffer.
                var rebuildZBufferRenderer = (RebuildZBufferRenderer)context.Data[RenderContextKeys.RebuildZBufferRenderer];
                rebuildZBufferRenderer.Render(context, context.GBuffer1);

                // Blend decals with the render target.
                _decalRenderer.Render(decalNodes, context);

                // The new render target replaces the GBuffer1.
                renderTargetPool.Recycle(context.GBuffer1);
                context.GBuffer1 = renderTarget;
            }
            context.RenderPass = null;

            // The depth buffer is downsampled into a buffer of half width and half height.
            RenderTarget2D depthBufferHalf = renderTargetPool.Obtain2D(new RenderTargetFormat(width / 2, height / 2, false, context.GBuffer0.Format, DepthFormat.None));

            context.SourceTexture = context.GBuffer0;
            context.RenderTarget  = depthBufferHalf;
            context.Viewport      = new Viewport(0, 0, depthBufferHalf.Width, depthBufferHalf.Height);
            _downsampleFilter.Process(context);
            context.SourceTexture = null;

            // Store the result in the render context. Depending on the settings, the downsampled
            // depth buffer is used by the SsaoFilter (if SsaoFilter.DownsampleFactor == 2), or
            // by the BillboardRenderer (if EnableOffscreenRendering is set).
            context.Data[RenderContextKeys.DepthBufferHalf] = depthBufferHalf;

            context.RenderTarget     = target;
            context.Viewport         = viewport;
            _renderTargetBindings[0] = new RenderTargetBinding();
            _renderTargetBindings[1] = new RenderTargetBinding();
        }
    public void RenderDeferred(ScriptableRenderContext renderContext, Camera camera, VXGI vxgi)
    {
        ScriptableCullingParameters cullingParams;

        if (!CullResults.GetCullingParameters(camera, out cullingParams))
        {
            return;
        }
        CullResults.Cull(ref cullingParams, renderContext, ref _cullResults);

        _command.BeginSample(_command.name);

        _command.GetTemporaryRT(_propDepth, camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth);
        _command.GetTemporaryRT(_propDiffuse, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf);
        _command.GetTemporaryRT(_propNormal, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBFloat);
        _command.GetTemporaryRT(_propEmission, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf);
        _command.GetTemporaryRT(_propOther, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf);
        _command.GetTemporaryRT(_propIrradiance,
                                (int)(vxgi.diffuseResolutionScale * camera.pixelWidth),
                                (int)(vxgi.diffuseResolutionScale * camera.pixelHeight),
                                0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf
                                );

        var binding = new RenderTargetBinding(
            new RenderTargetIdentifier[] { _propDiffuse, _propNormal, _propEmission, _propOther },
            new[] { RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare },
            new[] { RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare },
            _propDepth, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare
            );

        _command.SetRenderTarget(binding);
        _command.ClearRenderTarget(true, true, Color.clear);
        renderContext.ExecuteCommandBuffer(_command);
        _command.Clear();

        var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("Deferred"));

        drawSettings.sorting.flags = SortFlags.CommonOpaque;

        renderContext.DrawRenderers(_cullResults.visibleRenderers, ref drawSettings, _filterSettings);

        if (vxgi.pass == Pass.ConeTracing)
        {
            renderContext.SetupCameraProperties(camera);
            renderContext.DrawSkybox(camera);
        }

        if (_gBufferType != vxgi.gBufferType)
        {
            _command.DisableShaderKeyword(GetGBufferKeyword(_gBufferType));
            _command.EnableShaderKeyword(GetGBufferKeyword(vxgi.gBufferType));
            _gBufferType = vxgi.gBufferType;
        }

        if (_coneType != vxgi.coneType)
        {
            var keyword = GetConeKeyword(_coneType);
            if (keyword != null)
            {
                _command.DisableShaderKeyword(keyword);
            }

            keyword = GetConeKeyword(vxgi.coneType);
            if (keyword != null)
            {
                _command.EnableShaderKeyword(keyword);
            }

            _coneType = vxgi.coneType;
        }

        if (vxgi.skybox == null)
        {
            _command.DisableShaderKeyword("REFLECT_SKYBOX");
        }
        else
        {
            _command.EnableShaderKeyword("REFLECT_SKYBOX");
            _command.SetGlobalTexture("Skybox", vxgi.skybox);
        }

        Matrix4x4 clipToWorld = camera.cameraToWorldMatrix * GL.GetGPUProjectionMatrix(camera.projectionMatrix, false).inverse;

        _command.SetGlobalVector("CameraPosition", camera.transform.position);
        _command.SetGlobalMatrix("ClipToWorld", clipToWorld);
        _command.SetGlobalMatrix("ClipToVoxel", vxgi.worldToVoxel * clipToWorld);
        _command.SetGlobalMatrix("WorldToVoxel", vxgi.worldToVoxel);
        _command.SetGlobalMatrix("VoxelToWorld", vxgi.voxelToWorld);

        _command.EndSample(_command.name);

        renderContext.ExecuteCommandBuffer(_command);

        _command.Clear();

        if (vxgi.pass == Pass.ConeTracing)
        {
            _commandDiffuse.BeginSample(_commandDiffuse.name);
            _commandDiffuse.Blit(_propDiffuse, _propIrradiance, material, (int)Pass.DiffuseConeTracing);
            _commandDiffuse.EndSample(_commandDiffuse.name);

            renderContext.ExecuteCommandBuffer(_commandDiffuse);

            _commandDiffuse.Clear();
        }

        _commandReflection.BeginSample(_commandReflection.name);
        _commandReflection.Blit(_propDiffuse, BuiltinRenderTextureType.CameraTarget, material, (int)vxgi.pass);
        _commandReflection.EndSample(_commandReflection.name);

        renderContext.ExecuteCommandBuffer(_commandReflection);

        _commandReflection.Clear();

        _command.BeginSample(_command.name);

        _command.ReleaseTemporaryRT(_propDepth);
        _command.ReleaseTemporaryRT(_propDiffuse);
        _command.ReleaseTemporaryRT(_propNormal);
        _command.ReleaseTemporaryRT(_propEmission);
        _command.ReleaseTemporaryRT(_propOther);
        _command.ReleaseTemporaryRT(_propIrradiance);

        _command.EndSample(_command.name);

        renderContext.ExecuteCommandBuffer(_command);

        _command.Clear();
    }
        public void Render(IList <SceneNode> lights, RenderContext context)
        {
            var graphicsService  = context.GraphicsService;
            var graphicsDevice   = graphicsService.GraphicsDevice;
            var renderTargetPool = graphicsService.RenderTargetPool;

            var target   = context.RenderTarget;
            var viewport = context.Viewport;
            var width    = viewport.Width;
            var height   = viewport.Height;

            // Render ambient occlusion info into a render target.
            var aoRenderTarget = renderTargetPool.Obtain2D(new RenderTargetFormat(
                                                               width / _ssaoFilter.DownsampleFactor,
                                                               height / _ssaoFilter.DownsampleFactor,
                                                               false,
                                                               SurfaceFormat.Color,
                                                               DepthFormat.None));

            // PostProcessors require that context.SourceTexture is set. But since
            // _ssaoFilter.CombineWithSource is set to false, the SourceTexture is not
            // used and we can set it to anything except null.
            context.SourceTexture = aoRenderTarget;
            context.RenderTarget  = aoRenderTarget;
            context.Viewport      = new Viewport(0, 0, aoRenderTarget.Width, aoRenderTarget.Height);
            _ssaoFilter.Process(context);
            context.SourceTexture = null;

            // The light buffer consists of two full-screen render targets into which we
            // render the accumulated diffuse and specular light intensities.
            var lightBufferFormat = new RenderTargetFormat(width, height, false, SurfaceFormat.HdrBlendable, DepthFormat.Depth24Stencil8);

            context.LightBuffer0 = renderTargetPool.Obtain2D(lightBufferFormat);
            context.LightBuffer1 = renderTargetPool.Obtain2D(lightBufferFormat);

            // Set the device render target to the light buffer.
            _renderTargetBindings[0] = new RenderTargetBinding(context.LightBuffer0); // Diffuse light accumulation
            _renderTargetBindings[1] = new RenderTargetBinding(context.LightBuffer1); // Specular light accumulation
            graphicsDevice.SetRenderTargets(_renderTargetBindings);
            context.RenderTarget = context.LightBuffer0;
            context.Viewport     = graphicsDevice.Viewport;

            // Clear the light buffer. (The alpha channel is not used. We can set it to anything.)
            graphicsDevice.Clear(new Color(0, 0, 0, 255));

            // Render all lights into the light buffers.
            LightRenderer.Render(lights, context);

            // Render the ambient occlusion texture using multiplicative blending.
            // This will darken the light buffers depending on the ambient occlusion term.
            // Note: Theoretically, this should be done after the ambient light renderer
            // and before the directional light renderer because AO should not affect
            // directional lights. But doing this here has more impact.
            context.SourceTexture     = aoRenderTarget;
            graphicsDevice.BlendState = GraphicsHelper.BlendStateMultiply;
            _copyFilter.Process(context);

            // Clean up.
            graphicsService.RenderTargetPool.Recycle(aoRenderTarget);
            context.RenderTarget = target;
            context.Viewport     = viewport;

#if MONOGAME
            graphicsDevice.SetRenderTarget(null); // Cannot clear _renderTargetbindings if it is still set in the MonoGame device.
#endif
            _renderTargetBindings[0] = new RenderTargetBinding();
            _renderTargetBindings[1] = new RenderTargetBinding();
        }
 /// <summary>
 /// Push a render target onto the current rendering context, making it
 /// the active target for rendering.  By using the PushRenderTarget / PopRenderTarget
 /// methods, this allows you to safely chain render target switches, without risk
 /// of losing the previous render target.  An example of where this can be used is
 /// if you want to capture the next frame, you can simply start with a PushRenderTarget
 /// and as long as all other render target switching uses these methods or respects the
 /// previous render target, then everything will be captured as intended.
 /// </summary>
 /// <param name="renderTarget">
 /// The render target instance to make active.
 /// </param>
 public void PushRenderTarget(RenderTargetBinding renderTarget)
 {
     this.m_RenderTargets.Push(new[] { renderTarget });
     this.GraphicsDevice.SetRenderTargets(renderTarget);
 }