예제 #1
0
        internal static void Render()
        {
            MyGpuProfiler.IC_BeginBlock("Map lights to tiles");
            MyLightRendering.PreparePointLights();
            MyGpuProfiler.IC_EndBlock();

            RC.Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);

            RC.BindGBufferForRead(0, MyGBuffer.Main);
            RC.BindRawSRV(MyCommon.MATERIAL_BUFFER_SLOT, MySceneMaterials.m_buffer.Srv);
            RC.SetBS(MyRender11.BlendAdditive);

            MyGpuProfiler.IC_BeginBlock("Apply point lights");
            RenderPointlightsTiled();
            MyGpuProfiler.IC_EndBlock();


            MyGpuProfiler.IC_BeginBlock("Apply spotlights");
            RenderSpotlights();
            MyGpuProfiler.IC_EndBlock();

            DrawGlares();

            MyGpuProfiler.IC_BeginBlock("Apply directional light");
            RenderDirectionalEnvironmentLight();
            MyGpuProfiler.IC_EndBlock();
        }
예제 #2
0
        // Adds to commandLists the command lists containing the rendering commands for the renderables given in renderablesDBVH
        internal void Render(Queue <CommandList> commandLists, bool updateEnvironmentMap = false)
        {
            ProfilerShort.Begin("MyGeometryRenderer.Render");
            MyGpuProfiler.IC_BeginBlock("MyGeometryRenderer.Render");

            ProfilerShort.Begin("Culling");
            PrepareFrame();

            ProfilerShort.Begin("Prepare culling");
            var shadowmapQueries = m_shadowHandler.PrepareQueries();

            MyVisibilityCuller.PrepareCullQuery(m_cullQuery, shadowmapQueries, updateEnvironmentMap);

            ProfilerShort.BeginNextBlock("Perform culling");
            m_visibilityCuller.PerformCulling(m_cullQuery, m_renderablesDBVH);
            ProfilerShort.End();
            ProfilerShort.End();

            ProfilerShort.BeginNextBlock("Record command lists");
            m_renderingDispatcher.RecordCommandLists(m_cullQuery, commandLists);

            ProfilerShort.BeginNextBlock("Send output messages");
            SendOutputMessages(m_cullQuery);

            ProfilerShort.BeginNextBlock("Frame cleanup");
            EndFrame();

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();    // End function block
        }
예제 #3
0
        private static bool ProcessDrawSpritesQueue(string textureName)
        {
            List <MySpriteDrawRenderMessage> messages;

            if (!m_spriteTextureBatches.TryGetValue(textureName, out messages) || messages.Count == 0)
            {
                return(false);
            }

            GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");

            foreach (var message in messages)
            {
                ProfilerShort.Begin(message.MessageType.ToString());
                ProcessDrawMessage(message);
                ProfilerShort.End();
            }
            messages.Clear();

            if (textureName == DEFAULT_TEXTURE_TARGET && MyRenderProxy.DrawRenderStats >= MyRenderProxy.MyStatsState.Draw)
            {
                // Stats will be drawn one frame later
                ProfilerShort.Begin("MyRenderStatsDraw.Draw");
                MyGpuProfiler.IC_BeginBlock("MyRenderStatsDraw.Draw");

                if (!m_drawStatsSwitch)
                {
                    MyRenderStatsDraw.Draw(MyRenderStats.m_stats, 0.6f, VRageMath.Color.Yellow);
                }
                else
                {
                    MyStatsUpdater.UpdateStats();
                    MyStatsDisplay.Draw();
                }

                if (MyRenderProxy.DrawRenderStats == MyRenderProxy.MyStatsState.MoveNext)
                {
                    MyRenderProxy.DrawRenderStats = MyRenderProxy.MyStatsState.Draw;

                    if (!m_drawStatsSwitch)
                    {
                        m_drawStatsSwitch = !m_drawStatsSwitch;
                        // We finished cycling through the last page -- signal turning off of drawing stats on the next MoveNext
                        MyRenderProxy.DrawRenderStats = MyRenderProxy.MyStatsState.ShouldFinish;
                    }
                    else
                    {
                        m_drawStatsSwitch = MyStatsDisplay.MoveToNextPage(); // After the last page (returns false), switch to old stat display
                    }
                }

                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            GetRenderProfiler().EndProfilingBlock();
            return(true);
        }
예제 #4
0
        internal static void Test()
        {
            MyRender.GetRenderProfiler().StartProfilingBlock("SoftInstancingTest");
            MyGpuProfiler.IC_BeginBlock("SoftInstancingTest");
            DrawBatched();

            MyGpuProfiler.IC_EndBlock();
            MyRender.GetRenderProfiler().EndProfilingBlock();
        }
예제 #5
0
        internal static void Draw(bool draw = true)
        {
            try
            {
                MyGpuProfiler.IC_BeginBlock("Draw");
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                MyGpuProfiler.IC_BeginBlock("ProcessMessageQueue");
                TransferLocalMessages();
                ProcessMessageQueue();
                MyGpuProfiler.IC_EndBlock();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    m_drawScene = false;
                    DispatchDrawQueue();

                    if (m_drawScene)
                    {
                        DrawScene();
                    }

                    if (!(MyRender11.Settings.OffscreenSpritesRendering && m_drawScene))
                    {
                        ProcessDrawQueue();
                        DrawSprites(MyRender11.Backbuffer);
                    }

                    MyFileTextureManager texManager = MyManagers.FileTextures;
                    texManager.LoadAllRequested();

                    if (m_texturesToRender.Count > 0)
                    {
                        VRage.Render11.PostprocessStage.MySaveExportedTextures.RenderColoredTextures(m_texturesToRender);
                    }
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                MyGpuProfiler.IC_EndBlock();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
예제 #6
0
 private static void DrawSprites(IRtvBindable texture)
 {
     GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
     MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.PreDrawSprites_Draw);
     MyGpuProfiler.IC_BeginBlock("SpriteRenderer");
     MySpritesRenderer.Draw(texture, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
     MyGpuProfiler.IC_EndBlock();
     MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.PostDrawSprites_Draw);
     GetRenderProfiler().EndProfilingBlock();
 }
        private static void UpdateSceneFrame()
        {
            MySimpleProfiler.Begin("Textures");
            ProfilerShort.Begin("LoadMeshes");
            MyMeshes.Load();
            ProfilerShort.End();

            ProfilerShort.Begin("QueryTexturesFromEntities");
            QueryTexturesFromEntities();
            ProfilerShort.End();
            ProfilerShort.Begin("MyTextures.Load");
            MyManagers.FileTextures.LoadAllRequested();
            ProfilerShort.End();
            ProfilerShort.Begin("GatherTextures");
            GatherTextures();
            ProfilerShort.End();
            MySimpleProfiler.End("Textures");

            MyBillboardRenderer.OnFrameStart();

            UpdateActors();

            MyBigMeshTable.Table.MoveToGPU();

            ProfilerShort.Begin("Update merged groups");
            ProfilerShort.Begin("UpdateBeforeDraw");
            foreach (var r in MyComponentFactory <MyGroupRootComponent> .GetAll())
            {
                r.UpdateBeforeDraw();
            }
            ProfilerShort.End();

            ProfilerShort.Begin("MoveToGPU");
            foreach (var r in MyComponentFactory <MyGroupRootComponent> .GetAll())
            {
                foreach (var val in r.m_materialGroups.Values)
                {
                    // optimize: keep list+set for updating
                    val.MoveToGPU();
                }
            }
            ProfilerShort.End();
            ProfilerShort.End();

            ProfilerShort.Begin("Fill foliage streams");
            MyGpuProfiler.IC_BeginBlock("Fill foliage streams");
            m_foliageGenerator.PerFrame();
            m_foliageGenerator.Begin();
            MyFoliageComponents.Update();
            m_foliageGenerator.End();
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            MyCommon.MoveToNextFrame();
        }
예제 #8
0
        internal static void Run(RenderTargetView renderTarget, RenderTargetView intermediateRenderTarget, ShaderResourceView intermediateResourceView, ShaderResourceView initialResourceView,
                                 int maxOffset = 5, MyBlurDensityFunctionType densityFunctionType = MyBlurDensityFunctionType.Gaussian, float WeightParameter = 1.5f,
                                 DepthStencilState depthStencilState = null, int stencilRef       = 0x0, bool copyOnStencilFail = false,
                                 float depthDiscardThreshold         = 0.0f, MyViewport?viewport  = null)
        {
            ProfilerShort.Begin("MyBlur.Run");
            MyGpuProfiler.IC_BeginBlock("MyBlur.Run");
            Debug.Assert(initialResourceView != null);
            Debug.Assert(intermediateResourceView != null);
            Debug.Assert(intermediateRenderTarget != null);
            Debug.Assert(renderTarget != null);

            int shaderKey = InitShaders(densityFunctionType, maxOffset, copyOnStencilFail, depthDiscardThreshold);

            RC.DeviceContext.PixelShader.SetConstantBuffer(5, m_blurConstantBuffer);

            BlurConstants constants = new BlurConstants
            {
                DistributionWeight = WeightParameter,
                StencilRef         = stencilRef,
            };
            var mapping = MyMapping.MapDiscard(m_blurConstantBuffer);

            mapping.WriteAndPosition(ref constants);
            mapping.Unmap();

            // Horizontal pass
            MyRender11.DeviceContext.ClearRenderTargetView(intermediateRenderTarget, Color4.White);
            RC.DeviceContext.OutputMerger.SetTargets(intermediateRenderTarget);
            RC.SetDS(depthStencilState, stencilRef);
            RC.DeviceContext.PixelShader.SetShaderResource(0, MyGBuffer.Main.DepthStencil.m_SRV_depth);
            RC.DeviceContext.PixelShader.SetShaderResource(4, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
            RC.DeviceContext.PixelShader.SetShaderResource(5, initialResourceView);
            RC.SetPS(m_blurShaders[shaderKey].Item1);
            MyScreenPass.DrawFullscreenQuad(viewport);
            RC.DeviceContext.PixelShader.SetShaderResource(5, null);

            // Vertical pass
            MyRender11.DeviceContext.ClearRenderTargetView(renderTarget, Color4.White);
            RC.DeviceContext.OutputMerger.SetTargets(renderTarget);
            RC.SetDS(depthStencilState, stencilRef);
            RC.DeviceContext.PixelShader.SetShaderResource(0, MyGBuffer.Main.DepthStencil.m_SRV_depth);
            RC.DeviceContext.PixelShader.SetShaderResource(4, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
            RC.DeviceContext.PixelShader.SetShaderResource(5, intermediateResourceView);
            RC.SetPS(m_blurShaders[shaderKey].Item2);
            MyScreenPass.DrawFullscreenQuad(viewport);

            RC.DeviceContext.PixelShader.SetShaderResource(0, null);
            RC.DeviceContext.PixelShader.SetShaderResource(4, null);
            RC.DeviceContext.PixelShader.SetShaderResource(5, null);

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
예제 #9
0
        internal static void Combine(RwTexId targetArray, MyShadowCascades firstCascades, MyShadowCascades secondCascades)
        {
            if (!MyRender11.Settings.EnableShadows)
            {
                return;
            }

            ProfilerShort.Begin("MyShadowCascadesPostProcess.Combine");
            MyGpuProfiler.IC_BeginBlock("MyShadowCascadesPostProcess.Combine");

            firstCascades.FillConstantBuffer(firstCascades.CascadeConstantBuffer);
            secondCascades.FillConstantBuffer(secondCascades.CascadeConstantBuffer);
            secondCascades.PostProcessor.MarkCascadesInStencil(secondCascades.CascadeInfo);

            MyRenderContext renderContext = MyRenderContext.Immediate;
            DeviceContext   deviceContext = renderContext.DeviceContext;

            deviceContext.PixelShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            deviceContext.PixelShader.SetConstantBuffer(10, firstCascades.CascadeConstantBuffer);
            deviceContext.PixelShader.SetConstantBuffer(11, secondCascades.CascadeConstantBuffer);
            deviceContext.PixelShader.SetConstantBuffer(12, m_inverseConstants);

            for (int subresourceIndex = 0; subresourceIndex < targetArray.Description2d.ArraySize; ++subresourceIndex)
            {
                renderContext.BindGBufferForRead(0, MyGBuffer.Main);
                deviceContext.OutputMerger.SetTargets((DepthStencilView)null, (RenderTargetView)targetArray.SubresourceRtv(subresourceIndex));
                deviceContext.PixelShader.SetShaderResource(0, firstCascades.CascadeShadowmapArray.SubresourceSrv(subresourceIndex));
                deviceContext.PixelShader.SetShaderResource(1, secondCascades.CascadeShadowmapArray.ShaderView);
                //deviceContext.PixelShader.SetShaderResource(4, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
                renderContext.SetPS(m_combinePS);

                Matrix inverseCascadeMatrix = MatrixD.Transpose(MatrixD.Invert(firstCascades.CascadeInfo[subresourceIndex].CurrentLocalToProjection * MyMatrixHelpers.ClipspaceToTexture));
                var    mapping = MyMapping.MapDiscard(m_inverseConstants);
                mapping.WriteAndPosition(ref inverseCascadeMatrix);
                mapping.Unmap();

                MyScreenPass.DrawFullscreenQuad(new MyViewport(0, 0, targetArray.Description2d.Width, targetArray.Description2d.Height));
            }

            deviceContext.OutputMerger.SetTargets(null as DepthStencilView, null as RenderTargetView);
            deviceContext.PixelShader.SetShaderResource(0, null);
            deviceContext.PixelShader.SetShaderResource(1, null);
            deviceContext.PixelShader.SetShaderResource(2, null);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
예제 #10
0
        internal static unsafe void RunForwardPostprocess(IRtvBindable rt, IDsvBindable depthDsv, ISrvBindable depthSrv,
                                                          ref Matrix viewMatrix, ref Matrix projMatrix)
        {
            MyGpuProfiler.IC_BeginBlock("Postprocess");
            var viewMatrixT = Matrix.Transpose(viewMatrix);
            var projMatrixT = Matrix.Transpose(projMatrix);
            var mapping     = MyMapping.MapDiscard(RC, TransformConstants);

            mapping.WriteAndPosition(ref viewMatrixT);
            mapping.WriteAndPosition(ref projMatrixT);
            mapping.WriteAndPosition(ref MyRender11.Environment.Data.EnvironmentLight.SunLightDirection);
            mapping.Unmap();

            RC.AllShaderStages.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            RC.AllShaderStages.SetConstantBuffer(MyCommon.OBJECT_SLOT, TransformConstants);

            RC.SetDepthStencilState(MyDepthStencilStateManager.IgnoreDepthStencil);
            RC.SetRtv(rt);
            RC.PixelShader.SetSrv(0, depthSrv);
            MyFileTextureManager texManager = MyManagers.FileTextures;

            RC.PixelShader.SetSrv(MyCommon.SKYBOX_SLOT, texManager.GetTexture(MyRender11.Environment.Data.Skybox, MyFileTextureEnum.CUBEMAP, true));
            RC.PixelShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);
            RC.PixelShader.Set(m_ps);

            MyScreenPass.DrawFullscreenQuad(new MyViewport(m_viewportSize, m_viewportSize));
            MyGpuProfiler.IC_EndBlock();

            var nearestAtmosphereId = MyAtmosphereRenderer.GetNearestAtmosphereId();

            if (nearestAtmosphereId != null)
            {
                MyGpuProfiler.IC_BeginBlock("Atmosphere");
                RC.PixelShader.SetSrv(0, depthSrv);
                var viewProj = viewMatrix * projMatrix;
                MyAtmosphereRenderer.RenderEnvProbe(MyRender11.Environment.Matrices.CameraPosition, ref viewProj, nearestAtmosphereId.Value);

                MyGpuProfiler.IC_EndBlock();
            }

            RC.SetRtv(null);
        }
예제 #11
0
 static void BlendHighlight(IRtvBindable target, ISrvBindable outlined, ICustomTexture fxaaTarget, IDepthStencil depthStencilCopy)
 {
     MyGpuProfiler.IC_BeginBlock("Highlight Blending");
     ProfilerShort.Begin("Highlight Blending");
     if (fxaaTarget != null)
     {
         MyBlendTargets.RunWithStencil(
             fxaaTarget.SRgb,
             outlined,
             MyBlendStateManager.BlendAdditive,
             MyDepthStencilStateManager.TestHighlightOuterStencil,
             HIGHLIGHT_STENCIL_MASK,
             depthStencilCopy);
         MyBlendTargets.RunWithStencil(
             fxaaTarget.SRgb,
             outlined,
             MyBlendStateManager.BlendTransparent,
             MyDepthStencilStateManager.TestHighlightInnerStencil,
             HIGHLIGHT_STENCIL_MASK,
             depthStencilCopy);
     }
     else
     {
         if (MyRender11.MultisamplingEnabled)
         {
             MyBlendTargets.RunWithPixelStencilTest(target, outlined, MyBlendStateManager.BlendAdditive, false, depthStencilCopy);
             MyBlendTargets.RunWithPixelStencilTest(target, outlined, MyBlendStateManager.BlendTransparent, true, depthStencilCopy);
         }
         else
         {
             MyBlendTargets.RunWithStencil(target, outlined, MyBlendStateManager.BlendAdditive,
                                           MyDepthStencilStateManager.TestHighlightOuterStencil, HIGHLIGHT_STENCIL_MASK,
                                           depthStencilCopy);
             MyBlendTargets.RunWithStencil(target, outlined, MyBlendStateManager.BlendTransparent,
                                           MyDepthStencilStateManager.TestHighlightInnerStencil, HIGHLIGHT_STENCIL_MASK,
                                           depthStencilCopy);
         }
     }
     ProfilerShort.End();
     MyGpuProfiler.IC_EndBlock();
 }
예제 #12
0
        internal void GatherArray(RwTexId postprocessTarget, RwTexId cascadeArray, MyProjectionInfo[] cascadeInfo, ConstantsBufferId cascadeConstantBuffer)
        {
            if (!MyRenderProxy.Settings.EnableShadows)
            {
                return;
            }

            MarkCascadesInStencil(cascadeInfo);

            MyGpuProfiler.IC_BeginBlock("Cascades postprocess");

            MyRenderContext renderContext = MyRenderContext.Immediate;
            DeviceContext   deviceContext = renderContext.DeviceContext;

            renderContext.SetCS(m_gatherCS);
            ComputeShaderId.TmpUav[0] = postprocessTarget.Uav;
            deviceContext.ComputeShader.SetUnorderedAccessViews(0, ComputeShaderId.TmpUav, ComputeShaderId.TmpCount);

            deviceContext.ComputeShader.SetShaderResource(0, MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.m_SRV_depth : MyGBuffer.Main.DepthStencil.m_SRV_depth);
            deviceContext.ComputeShader.SetShaderResource(1, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
            deviceContext.ComputeShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState);
            deviceContext.ComputeShader.SetConstantBuffer(0, MyCommon.FrameConstants);
            deviceContext.ComputeShader.SetConstantBuffer(4, cascadeConstantBuffer);
            deviceContext.ComputeShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, cascadeArray.ShaderView);

            deviceContext.Dispatch(m_threadGroupCountX, m_threadGroupCountY, 1);

            ComputeShaderId.TmpUav[0] = null;
            renderContext.DeviceContext.ComputeShader.SetUnorderedAccessViews(0, ComputeShaderId.TmpUav, ComputeShaderId.TmpCount);
            deviceContext.ComputeShader.SetShaderResource(0, null);

            if (MyRender11.Settings.EnableShadowBlur)
            {
                MyBlur.Run(postprocessTarget.Rtv, MyRender11.CascadesHelper.Rtv, MyRender11.CascadesHelper.ShaderView, postprocessTarget.ShaderView, depthDiscardThreshold: 0.2f);
            }

            MyGpuProfiler.IC_EndBlock();
        }
예제 #13
0
        internal static void Render()
        {
            MyGpuProfiler.IC_BeginBlock("Map lights to tiles");
            if (MyRender11.DebugOverrides.PointLights)
            {
                PreparePointLights();
            }
            MyGpuProfiler.IC_EndBlock();

            RC.DeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);

            RC.BindGBufferForRead(0, MyGBuffer.Main);
            RC.BindRawSRV(MyCommon.MATERIAL_BUFFER_SLOT, MySceneMaterials.m_buffer.Srv);
            RC.SetBS(MyRender11.BlendAdditive);
            RC.SetDS(MyDepthStencilState.IgnoreDepthStencil);
            RC.DeviceContext.PixelShader.SetSamplers(0, MyRender11.StandardSamplers);

            MyGpuProfiler.IC_BeginBlock("Apply point lights");
            if (MyRender11.DebugOverrides.PointLights)
            {
                RenderPointlightsTiled();
            }
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("Apply spotlights");
            if (MyRender11.DebugOverrides.SpotLights)
            {
                RenderSpotlights();
            }
            MyGpuProfiler.IC_EndBlock();

            DrawGlares();

            MyGpuProfiler.IC_BeginBlock("Apply directional light");
            RenderDirectionalEnvironmentLight();
            MyGpuProfiler.IC_EndBlock();
        }
        internal unsafe static void RunForwardPostprocess(IRtvBindable rt, ISrvBindable depth, ref Matrix viewMatrix, uint?atmosphereId)
        {
            MyGpuProfiler.IC_BeginBlock("Postprocess");
            var transpose = Matrix.Transpose(viewMatrix);
            var mapping   = MyMapping.MapDiscard(RC, MyCommon.ProjectionConstants);

            mapping.WriteAndPosition(ref transpose);
            mapping.Unmap();

            RC.AllShaderStages.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            RC.AllShaderStages.SetConstantBuffer(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants);

            RC.SetDepthStencilState(MyDepthStencilStateManager.IgnoreDepthStencil);
            RC.SetRtv(rt);
            RC.PixelShader.SetSrv(0, depth);
            MyFileTextureManager texManager = MyManagers.FileTextures;

            RC.PixelShader.SetSrv(MyCommon.SKYBOX_SLOT, texManager.GetTexture(MyRender11.Environment.Data.Skybox, MyFileTextureEnum.CUBEMAP, true));
            RC.PixelShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);
            RC.PixelShader.Set(m_ps);

            MyScreenPass.DrawFullscreenQuad(new MyViewport(m_viewportSize, m_viewportSize));
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("Atmosphere");
            if (atmosphereId != null)
            {
                var atmosphere = MyAtmosphereRenderer.GetAtmosphere(atmosphereId.Value);
                var constants  = new AtmosphereConstants();
                //TODO(AF) These values are computed in MyAtmosphere as well. Find a way to remove the duplication
                var worldMatrix = atmosphere.WorldMatrix;
                worldMatrix.Translation -= MyRender11.Environment.Matrices.CameraPosition;

                double distance       = worldMatrix.Translation.Length();
                double atmosphereTop  = atmosphere.AtmosphereRadius * atmosphere.Settings.AtmosphereTopModifier * atmosphere.PlanetScaleFactor * atmosphere.Settings.RayleighTransitionModifier;
                float  rayleighHeight = atmosphere.Settings.RayleighHeight;
                float  t = 0.0f;
                if (distance > atmosphereTop)
                {
                    if (distance > atmosphereTop * 2.0f)
                    {
                        t = 1.0f;
                    }
                    else
                    {
                        t = (float)((distance - atmosphereTop) / atmosphereTop);
                    }
                }
                rayleighHeight = MathHelper.Lerp(atmosphere.Settings.RayleighHeight, atmosphere.Settings.RayleighHeightSpace, t);


                constants.PlanetCentre           = (Vector3)worldMatrix.Translation;
                constants.AtmosphereRadius       = atmosphere.AtmosphereRadius * atmosphere.Settings.AtmosphereTopModifier;
                constants.GroundRadius           = atmosphere.PlanetRadius * 1.01f * atmosphere.Settings.SeaLevelModifier;
                constants.BetaRayleighScattering = atmosphere.BetaRayleighScattering / atmosphere.Settings.RayleighScattering;
                constants.BetaMieScattering      = atmosphere.BetaMieScattering / atmosphere.Settings.MieColorScattering;
                constants.HeightScaleRayleighMie = atmosphere.HeightScaleRayleighMie * new Vector2(rayleighHeight, atmosphere.Settings.MieHeight);
                constants.MieG = atmosphere.Settings.MieG;
                constants.PlanetScaleFactor     = atmosphere.PlanetScaleFactor;
                constants.AtmosphereScaleFactor = atmosphere.AtmosphereScaleFactor;
                constants.Intensity             = atmosphere.Settings.Intensity;
                constants.FogIntensity          = atmosphere.Settings.FogIntensity;

                var cb = MyCommon.GetObjectCB(sizeof(AtmosphereConstants));

                mapping = MyMapping.MapDiscard(RC, cb);
                mapping.WriteAndPosition(ref constants);
                mapping.Unmap();

                RC.SetBlendState(MyBlendStateManager.BlendAdditive);
                RC.PixelShader.SetConstantBuffer(2, cb);
                RC.PixelShader.SetSrv(2, MyAtmosphereRenderer.GetAtmosphereLuts(atmosphereId.Value).TransmittanceLut);
                RC.PixelShader.Set(m_atmosphere);

                MyScreenPass.DrawFullscreenQuad(new MyViewport(MyEnvironmentProbe.CubeMapResolution, MyEnvironmentProbe.CubeMapResolution));
            }
            MyGpuProfiler.IC_EndBlock();

            RC.SetRtv(null);
        }
예제 #15
0
        internal static void Run()
        {
            ProfilerShort.Begin("MyOutline.Run");
            MyGpuProfiler.IC_BeginBlock("MyOutline.Run");
            // set resolved depth/ stencil
            // render all with proper depth-stencil state
            // blur
            // blend to main target testing with stencil again

            MyOutlinePass.Instance.ViewProjection = MyEnvironment.ViewProjectionAt0;
            MyOutlinePass.Instance.Viewport       = new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);

            MyOutlinePass.Instance.PerFrame();
            MyOutlinePass.Instance.Begin();

            RC.Clear();
            RC.DeviceContext.VertexShader.SetShaderResources(0, null, null, null, null, null, null);
            RC.DeviceContext.GeometryShader.SetShaderResources(0, null, null, null, null, null, null);
            RC.DeviceContext.PixelShader.SetShaderResources(0, null, null, null, null, null, null);
            RC.DeviceContext.ComputeShader.SetShaderResources(0, null, null, null, null, null, null);

            if (MyRender11.MultisamplingEnabled)
            {
                RC.DeviceContext.ClearRenderTargetView(MyRender11.m_rgba8_ms.m_RTV, new SharpDX.Color4(0, 0, 0, 0));

                RC.DeviceContext.OutputMerger.SetTargets(MyGBuffer.Main.DepthStencil.m_DSV, MyRender11.m_rgba8_ms.m_RTV);
            }
            else
            {
                RC.DeviceContext.ClearRenderTargetView(MyRender11.m_rgba8_1.m_RTV, new SharpDX.Color4(0, 0, 0, 0));

                RC.DeviceContext.OutputMerger.SetTargets(MyGBuffer.Main.DepthStencil.m_DSV, MyRender11.m_rgba8_1.m_RTV);
            }

            float maxThickness = 0f;

            foreach (var pair in m_outlines)
            {
                MyActor actor = MyIDTracker <MyActor> .FindByID(pair.Key);

                MyRenderableComponent renderableComponent;
                if (actor == null || (renderableComponent = actor.GetRenderable()) == null)
                {
                    // If an actor has been removed without removing outlines, just remove the outlines too
                    m_keysToRemove.Add(pair.Key);
                    continue;
                }

                var renderLod = renderableComponent.Lods[renderableComponent.CurrentLod];
                var model     = renderableComponent.GetModel();

                LodMeshId currentModelId;
                if (!MyMeshes.TryGetLodMesh(model, renderableComponent.CurrentLod, out currentModelId))
                {
                    Debug.Fail("Mesh for outlining not found!");
                    continue;
                }

                foreach (MyOutlineDesc descriptor in pair.Value)
                {
                    if (!renderableComponent.IsRenderedStandAlone)
                    {
                        MyGroupLeafComponent leafComponent  = actor.GetGroupLeaf();
                        MyGroupRootComponent groupComponent = leafComponent.RootGroup;
                        if (groupComponent != null)
                        {
                            RecordMeshPartCommands(model, actor, groupComponent, groupComponent.m_proxy, descriptor, ref maxThickness);
                        }

                        continue;
                    }

                    if (descriptor.SectionIndex == -1)
                    {
                        RecordMeshPartCommands(model, currentModelId, renderableComponent, renderLod, descriptor, ref maxThickness);
                    }
                    else
                    {
                        RecordMeshSectionCommands(model, currentModelId, renderableComponent, renderLod, descriptor, ref maxThickness);
                    }
                }
            }

            MyOutlinePass.Instance.End();
            RC.SetBS(null);

            foreach (var outlineKey in m_keysToRemove)
            {
                m_outlines.Remove(outlineKey);
            }

            m_keysToRemove.SetSize(0);

            ShaderResourceView initialSourceView = MyRender11.MultisamplingEnabled ? MyRender11.m_rgba8_ms.m_SRV : MyRender11.m_rgba8_1.m_SRV;
            RenderTargetView   renderTargetview  = MyRender11.MultisamplingEnabled ? MyRender11.m_rgba8_ms.m_RTV : MyRender11.m_rgba8_1.m_RTV;

            if (maxThickness > 0)
            {
                MyBlur.Run(renderTargetview, MyRender11.m_rgba8_2.m_RTV, MyRender11.m_rgba8_2.m_SRV, initialSourceView,
                           (int)Math.Round(5 * maxThickness),
                           MyBlur.MyBlurDensityFunctionType.Exponential, 0.25f,
                           null, MyFoliageRenderingPass.GrassStencilMask, MyRender11.Settings.BlurCopyOnDepthStencilFail);
            }

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
예제 #16
0
        private static void UpdateSceneFrame()
        {
            var desc = new RasterizerStateDescription();

            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.None;
            desc.IsFrontCounterClockwise = true;

            desc.DepthBias            = 25000;
            desc.DepthBiasClamp       = 2;
            desc.SlopeScaledDepthBias = 1;

            MyPipelineStates.Modify(m_shadowRasterizerState, desc);


            MyMeshes.Load();
            QueryTexturesFromEntities();
            MyTextures.Load();
            GatherTextures();
            MyComponents.UpdateCullProxies();
            MyComponents.ProcessEntities();
            MyComponents.SendVisible();

            MyBillboardRenderer.OnFrameStart();

            MyRender11.GetRenderProfiler().StartProfilingBlock("RebuildProxies");
            foreach (var renderable in MyComponentFactory <MyRenderableComponent> .GetAll())
            {
                renderable.RebuildRenderProxies();
            }
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("UpdateProxies");
            UpdateActors();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyBigMeshTable.Table.MoveToGPU();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Update merged groups");
            MyRender11.GetRenderProfiler().StartProfilingBlock("UpdateBeforeDraw");
            foreach (var r in MyComponentFactory <MyGroupRootComponent> .GetAll())
            {
                r.UpdateBeforeDraw();
            }
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("MoveToGPU");
            foreach (var r in MyComponentFactory <MyGroupRootComponent> .GetAll())
            {
                foreach (var val in r.m_materialGroups.Values)
                {
                    // optimize: keep list+set for updating
                    val.MoveToGPU();
                }
            }
            MyRender11.GetRenderProfiler().EndProfilingBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Fill foliage streams");
            MyGpuProfiler.IC_BeginBlock("Fill foliage streams");
            MyGPUFoliageGenerating.GetInstance().PerFrame();
            MyGPUFoliageGenerating.GetInstance().Begin();
            foreach (var foliage in MyComponentFactory <MyFoliageComponent> .GetAll())
            {
                if (foliage.m_owner.CalculateCameraDistance() < MyRender11.RenderSettings.FoliageDetails.GrassDrawDistance())
                {
                    foliage.FillStreams();
                }
                else
                {
                    foliage.InvalidateStreams();
                }
            }
            MyGPUFoliageGenerating.GetInstance().End();
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyCommon.MoveToNextFrame();
        }
예제 #17
0
        internal static void Present()
        {
            if (m_swapchain != null)
            {
                if (m_screenshot.HasValue)
                {
                    if (m_screenshot.Value.SizeMult == VRageMath.Vector2.One)
                    {
                        MyCopyToRT.ClearAlpha(Backbuffer);
                        SaveScreenshotFromResource(Backbuffer.m_resource);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }

                GetRenderProfiler().StartProfilingBlock("Waiting for present");

                try
                {
                    m_swapchain.Present(m_settings.VSync ? 1 : 0, 0);
                    m_consecutivePresentFails = 0;

                    if (m_presentTimer == null)
                    {
                        m_presentTimer = new Stopwatch();
                    }
                    else
                    {
                        m_presentTimer.Stop();

                        if (m_presentTimes.Count >= PresentTimesStored)
                        {
                            m_presentTimes.Dequeue();
                        }
                        m_presentTimes.Enqueue(m_presentTimer.ElapsedMilliseconds);
                    }

                    m_presentTimer.Restart();
                }
                catch (SharpDXException e)
                {
                    Log.WriteLine("Device removed - resetting device; reason: " + e.ToString());
                    HandleDeviceReset();
                    Log.WriteLine("Device removed - resetting completed");

                    m_consecutivePresentFails++;

                    if (m_consecutivePresentFails == 5)
                    {
                        Log.WriteLine("Present failed");
                        Log.IncreaseIndent();

                        if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                        {
                            Log.WriteLine("Device removed: " + Device.DeviceRemovedReason);
                        }

                        var timings = "";
                        while (m_presentTimes.Count > 0)
                        {
                            timings += m_presentTimes.Dequeue();
                            if (m_presentTimes.Count > 0)
                            {
                                timings += ", ";
                            }
                        }

                        Log.WriteLine("Last present timings = [ " + timings + " ]");
                        Log.DecreaseIndent();
                    }
                }

                GetRenderProfiler().EndProfilingBlock();

                if (m_profilingStarted)
                {
                    MyGpuProfiler.IC_EndBlock();
                }

                MyGpuProfiler.EndFrame();
                MyGpuProfiler.StartFrame();
                m_profilingStarted = true;

                // waiting for change to fullscreen - window migh overlap or some other dxgi excuse to fail :(
                TryChangeToFullscreen();
            }
        }
예제 #18
0
        internal void FinalizeEnvProbes()
        {
            if (MyRender11.IsIntelBrokenCubemapsWorkaround)
            {
                return;
            }

            ProfilerShort.Begin("FinalizeEnvProbes");
            MyGpuProfiler.IC_BeginBlock("FinalizeEnvProbes");
            if (m_lastUpdateTime == MyTimeSpan.Zero)
            {
                for (int i = 0; i < 6; i++)
                {
                    PostprocessProbe(i);
                }

                MyGpuProfiler.IC_BeginBlock("BuildMipmaps");
                MyEnvProbeProcessing.BuildMipmaps(m_workCubemap);
                MyGpuProfiler.IC_EndBlock();

                MyGpuProfiler.IC_BeginBlock("Prefilter");
                MyEnvProbeProcessing.Prefilter(m_workCubemap, m_workCubemapPrefiltered);
                MyGpuProfiler.IC_EndBlock();

                MyGpuProfiler.IC_BeginBlock("CopyResource");
                MyImmediateRC.RC.CopyResource(m_workCubemapPrefiltered, m_prevWorkCubemapPrefiltered);
                MyImmediateRC.RC.CopyResource(m_workCubemapPrefiltered, Cubemap);
                MyGpuProfiler.IC_EndBlock();

                m_lastUpdateTime = MyRender11.CurrentDrawTime;
            }
            else
            {
                if (m_state >= 6 && m_state < 12)
                {
                    PostprocessProbe(m_state - 6);
                }
                else if (m_state >= 12)
                {
                    MyGpuProfiler.IC_BeginBlock("BlendAllProbes");
                    BlendAllProbes();
                    MyGpuProfiler.IC_EndBlock();
                }

                if (m_state == 12)
                {
                    MyGpuProfiler.IC_BeginBlock("BuildMipmaps");
                    m_lastUpdateTime = MyRender11.CurrentDrawTime;
                    // whole cubemap is rendered and postprocessed, we can use it
                    MyEnvProbeProcessing.BuildMipmaps(m_workCubemap);
                    MyGpuProfiler.IC_EndBlock();

                    MyGpuProfiler.IC_BeginBlock("Prefilter");
                    MyEnvProbeProcessing.Prefilter(m_workCubemap, m_workCubemapPrefiltered);
                    MyGpuProfiler.IC_EndBlock();
                }

                m_state++;
                MyTimeSpan timeForNextCubemap = m_lastUpdateTime +
                                                MyTimeSpan.FromSeconds(MyEnvironmentProbe.MAX_BLEND_TIME_S);
                if (m_state > 12 && MyRender11.CurrentDrawTime > timeForNextCubemap)
                {
                    m_state = 0; // Time is up, we need to render another environment map
                }
            }
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
예제 #19
0
        private static void DrawGameScene(bool blitToBackbuffer)
        {
            ResetStats();
            MyCommon.UpdateFrameConstants();

            // todo: shouldn't be necessary
            if (true)
            {
                MyImmediateRC.RC.Clear();
                MyImmediateRC.RC.Context.ClearState();
            }

            MyRender11.GetRenderProfiler().StartProfilingBlock("MyGeometryRenderer.Render");
            MyGpuProfiler.IC_BeginBlock("MyGeometryRenderer.Render");
            MyGeometryRenderer.Render();
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            // cleanup context atfer deferred lists
            if (MyRender11.DeferredContextsEnabled)
            {
                MyImmediateRC.RC.Clear();
            }

            // todo: shouldn't be necessary
            if (true)
            {
                MyImmediateRC.RC.Clear();
                MyImmediateRC.RC.Context.ClearState();
            }

            MyRender11.GetRenderProfiler().StartProfilingBlock("Render decals");
            MyGpuProfiler.IC_BeginBlock("Render decals");
            MyRender11.CopyGbufferToScratch();
            MyScreenDecals.Draw();
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Render foliage");
            MyGpuProfiler.IC_BeginBlock("Render foliage");
            MyFoliageRenderer.Render();
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MySceneMaterials.MoveToGPU();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Postprocessing");
            MyGpuProfiler.IC_BeginBlock("Postprocessing");
            if (MultisamplingEnabled)
            {
                MyRender11.Context.ClearDepthStencilView(MyScreenDependants.m_resolvedDepth.m_DSV, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);
                MyGpuProfiler.IC_BeginBlock("MarkAAEdges");
                MyAAEdgeMarking.Run();
                MyGpuProfiler.IC_EndBlock();
                MyDepthResolve.Run(MyScreenDependants.m_resolvedDepth, MyGBuffer.Main.DepthStencil.Depth);
            }

            MyGpuProfiler.IC_BeginBlock("MarkCascades");
            MyShadows.MarkCascadesInStencil();
            MyGpuProfiler.IC_EndBlock();


            MyGpuProfiler.IC_BeginBlock("Shadows resolve");
            MyShadowsResolve.Run();
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("SSAO");
            if (Postprocess.EnableSsao)
            {
                MySSAO.Run(MyScreenDependants.m_ambientOcclusion, MyGBuffer.Main, MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.Depth : MyGBuffer.Main.DepthStencil.Depth);
            }
            else
            {
                MyRender11.Context.ClearRenderTargetView(MyScreenDependants.m_ambientOcclusion.m_RTV, Color4.White);
            }
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("Lights");
            MyLightRendering.Render();
            MyGpuProfiler.IC_EndBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Billboards");
            MyGpuProfiler.IC_BeginBlock("Billboards");
            MyRender11.Context.ClearRenderTargetView((MyScreenDependants.m_particlesRT as IRenderTargetBindable).RTV, new Color4(0, 0, 0, 0));
            if (MyRender11.MultisamplingEnabled)
            {
                MyBillboardRenderer.Render(MyScreenDependants.m_particlesRT, MyScreenDependants.m_resolvedDepth, MyScreenDependants.m_resolvedDepth.Depth);
            }
            else
            {
                MyBillboardRenderer.Render(MyScreenDependants.m_particlesRT, MyGBuffer.Main.DepthStencil, MyGBuffer.Main.DepthStencil.Depth);
            }

            MyBlendTargets.Run(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), MyScreenDependants.m_particlesRT, MyRender11.BlendAlphaPremult);
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyAtmosphereRenderer.Render();

            MyGpuProfiler.IC_BeginBlock("Luminance reduction");
            MyBindableResource avgLum = null;

            if (MyRender11.MultisamplingEnabled)
            {
                //MyLBufferResolve.Run(MyGBuffer.Main.Get(MyGbufferSlot.LBufferResolved), MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), MyGBuffer.Main.DepthStencil.Stencil);

                MyImmediateRC.RC.Context.ResolveSubresource(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer).m_resource, 0, MyGBuffer.Main.Get(MyGbufferSlot.LBufferResolved).m_resource, 0, SharpDX.DXGI.Format.R11G11B10_Float);
            }
            if (m_resetEyeAdaptation)
            {
                MyImmediateRC.RC.Context.ClearUnorderedAccessView(m_prevLum.m_UAV, Int4.Zero);
                m_resetEyeAdaptation = false;
            }
            avgLum = MyLuminanceAverage.Run(m_reduce0, m_reduce1, MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), m_prevLum, m_localLum);

            MyGpuProfiler.IC_EndBlock();

            if (MyRender11.Settings.DispalyHdrDebug)
            {
                var src = MyGBuffer.Main.Get(MyGbufferSlot.LBuffer) as MyRenderTarget;
                MyHdrDebugTools.CreateHistogram(src.m_SRV, src.m_resolution, src.m_samples.X);
            }


            MyGpuProfiler.IC_BeginBlock("Bloom");
            var bloom = MyBloom.Run(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), avgLum);

            MyGpuProfiler.IC_EndBlock();

            MyBindableResource tonemapped;

            if (MyRender11.FxaaEnabled)
            {
                tonemapped = m_rgba8_linear;
            }
            else
            {
                tonemapped = m_uav3;
            }

            MyGpuProfiler.IC_BeginBlock("Tone mapping");
            MyToneMapping.Run(tonemapped, MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), avgLum, bloom, MyRender11.Settings.EnableTonemapping && Postprocess.EnableTonemapping && MyRender11.RenderSettings.TonemappingEnabled);
            MyGpuProfiler.IC_EndBlock();

            MyBindableResource renderedImage;

            if (MyRender11.FxaaEnabled)
            {
                MyGpuProfiler.IC_BeginBlock("FXAA");
                MyFXAA.Run(m_rgba8_0.GetView(new MyViewKey {
                    Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm, View = MyViewEnum.RtvView
                }), tonemapped);
                MyGpuProfiler.IC_EndBlock();

                renderedImage = m_rgba8_0.GetView(new MyViewKey {
                    Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.SrvView
                });
            }
            else
            {
                //renderedImage = (tonemapped as MyCustomTexture).GetView(new MyViewKey { Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.SrvView });
                renderedImage = tonemapped;
            }

            if (MyOutline.AnyOutline())
            {
                MyOutline.Run();

                if (MyRender11.FxaaEnabled)
                {
                    MyBlendTargets.RunWithStencil(m_rgba8_0.GetView(new MyViewKey {
                        Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.RtvView
                    }), MyRender11.m_rgba8_1, MyRender11.BlendAdditive);
                }
                else
                {
                    if (MyRender11.MultisamplingEnabled)
                    {
                        MyBlendTargets.RunWithPixelStencilTest(tonemapped, MyRender11.m_rgba8_1, MyRender11.BlendAdditive);
                    }
                    else
                    {
                        MyBlendTargets.RunWithStencil(tonemapped, MyRender11.m_rgba8_1, MyRender11.BlendAdditive);
                    }
                }
            }

            m_finalImage = renderedImage;

            if (blitToBackbuffer)
            {
                MyCopyToRT.Run(Backbuffer, renderedImage);
            }

            if (MyRender11.Settings.DispalyHdrDebug)
            {
                MyHdrDebugTools.DisplayHistogram(Backbuffer.m_RTV, (avgLum as IShaderResourceBindable).SRV);
            }

            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();
        }
        internal static void Render()
        {
            IBorrowedUavTexture accumTarget    = MyManagers.RwTexturesPool.BorrowUav("MyTransparentRendering.AccumTarget", Format.R16G16B16A16_Float);
            IBorrowedUavTexture coverageTarget = MyManagers.RwTexturesPool.BorrowUav("MyTransparentRendering.CoverageTarget", Format.R16_UNorm);

            ProfilerShort.Begin("Atmosphere");
            MyGpuProfiler.IC_BeginBlock("Atmosphere");
            if (MyRender11.DebugOverrides.Atmosphere)
            {
                MyAtmosphereRenderer.Render();
            }

            ProfilerShort.BeginNextBlock("Clouds");
            MyGpuProfiler.IC_BeginNextBlock("Clouds");
            if (MyRender11.DebugOverrides.Clouds)
            {
                MyCloudRenderer.Render();
            }
            MyGpuProfiler.IC_EndBlock();

            // setup weighted blended OIT targets + blend states
            SetupTargets(accumTarget, coverageTarget, true);

            IDepthStencil depthResource;

            if (MyRender11.MultisamplingEnabled)
            {
                depthResource = MyScreenDependants.m_resolvedDepth;
            }
            else
            {
                depthResource = MyGBuffer.Main.DepthStencil;
            }

            m_windowsWithDecals.Clear();
            ProfilerShort.BeginNextBlock("Billboards");
            MyGpuProfiler.IC_BeginBlock("Billboards");
            bool resetBindings = MyBillboardRenderer.Gather(HandleWindow);

            if (resetBindings)
            {
                SetupTargets(accumTarget, coverageTarget, false);
            }

            MyBillboardRenderer.Render(depthResource.SrvDepth);

            ProfilerShort.BeginNextBlock("GPU Particles");
            MyGpuProfiler.IC_BeginNextBlock("GPU Particles");
            if (MyRender11.DebugOverrides.GPUParticles)
            {
                MyGPUParticleRenderer.Run(depthResource.SrvDepth);
            }
            MyGpuProfiler.IC_EndBlock();

            // Render decals on transparent surfaces in 2 steps: first far, second proximity
            float intervalMax = MyScreenDecals.VISIBLE_DECALS_SQ_TH;

            for (int it = 0; it < m_distances.Length; it++)
            {
                float intervalMin = m_distances[it];

                ProfilerShort.BeginNextBlock("Billboards - Depth Only");
                MyGpuProfiler.IC_BeginBlock("Billboards - Depth Only");
                bool windowsFound = MyBillboardRenderer.RenderWindowsDepthOnly(depthResource, MyGlobalResources.Gbuffer1Copy, intervalMin, intervalMax);
                MyGpuProfiler.IC_EndBlock();

                if (windowsFound)
                {
                    SetupTargets(accumTarget, coverageTarget, false);

                    ProfilerShort.BeginNextBlock("Render decals - Transparent");
                    MyGpuProfiler.IC_BeginBlock("Render decals - Transparent");
                    MyScreenDecals.Draw(true, m_windowsWithDecals);
                    MyGpuProfiler.IC_EndBlock();
                }

                intervalMax = intervalMin;
            }

            if (IsUsedOverlappingHeatMap())
            {
                DisplayOverlappingHeatMap(accumTarget, coverageTarget, MyRender11.Settings.DisplayTransparencyHeatMapInGrayscale);
            }

            MyGpuProfiler.IC_BeginBlock("OIT Resolve");
            // resolve weighted blended OIT in  accum / coverage to LBuffer
            if (MyRender11.DebugOverrides.OIT)
            {
                ResolveOIT(accumTarget, coverageTarget);
            }
            else
            {
                RC.SetRtv(null);
            }
            MyGpuProfiler.IC_EndBlock();

            coverageTarget.Release();
            accumTarget.Release();

            ProfilerShort.End();
        }
예제 #21
0
        private static void ProcessDrawMessage(MyRenderMessageBase drawMessage)
        {
            switch (drawMessage.MessageType)
            {
            case MyRenderMessageEnum.SpriteScissorPush:
            {
                var msg = drawMessage as MyRenderMessageSpriteScissorPush;

                MySpritesRenderer.ScissorStackPush(msg.ScreenRectangle);

                break;
            }

            case MyRenderMessageEnum.SpriteScissorPop:
            {
                MySpritesRenderer.ScissorStackPop();

                break;
            }

            case MyRenderMessageEnum.DrawSprite:
            {
                MyRenderMessageDrawSprite sprite = (MyRenderMessageDrawSprite)drawMessage;

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, sprite.Origin, sprite.RightVector, sprite.SourceRectangle, sprite.DestinationRectangle);

                break;
            }

            case MyRenderMessageEnum.DrawSpriteNormalized:
            {
                MyRenderMessageDrawSpriteNormalized sprite = (MyRenderMessageDrawSpriteNormalized)drawMessage;

                var rotation = sprite.Rotation;
                if (sprite.RotationSpeed != 0)
                {
                    rotation += sprite.RotationSpeed * (float)(MyRender11.CurrentDrawTime - MyRender11.CurrentUpdateTime).Seconds;
                }

                Vector2 rightVector = rotation != 0f ? new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) : sprite.RightVector;

                int safeGuiSizeY = MyRender11.ResolutionI.Y;
                int safeGuiSizeX = (int)(safeGuiSizeY * 1.3333f);             //  This will mantain same aspect ratio for GUI elements

                var   safeGuiRectangle = new VRageMath.Rectangle(MyRender11.ResolutionI.X / 2 - safeGuiSizeX / 2, 0, safeGuiSizeX, safeGuiSizeY);
                var   safeScreenScale  = (float)safeGuiSizeY / MyRenderGuiConstants.REFERENCE_SCREEN_HEIGHT;
                float fixedScale       = sprite.Scale * safeScreenScale;

                var tex = MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true);

                var normalizedCoord = sprite.NormalizedCoord;
                var screenCoord     = new Vector2(safeGuiRectangle.Left + safeGuiRectangle.Width * normalizedCoord.X,
                                                  safeGuiRectangle.Top + safeGuiRectangle.Height * normalizedCoord.Y);

                var sizeInPixels       = MyTextures.GetSize(tex);
                var sizeInPixelsScaled = sizeInPixels * fixedScale;

                Vector2 alignedScreenCoord = screenCoord;
                var     drawAlign          = sprite.DrawAlign;

                if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP)
                {
                    //  Nothing to do as position is already at this point
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER)
                {
                    //  Move position to the texture center
                    alignedScreenCoord -= sizeInPixelsScaled / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X / 2.0f;
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord -= sizeInPixelsScaled;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER)
                {
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X;
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y;        // *0.75f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_TOP)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X;
                }

                screenCoord = alignedScreenCoord;

                var     rect = new RectangleF(screenCoord.X, screenCoord.Y, fixedScale * sizeInPixels.X, fixedScale * sizeInPixels.Y);
                Vector2 origin;
                if (sprite.OriginNormalized.HasValue)
                {
                    origin = sprite.OriginNormalized.Value * sizeInPixels;
                }
                else
                {
                    origin = sizeInPixels / 2;
                }

                sprite.OriginNormalized = sprite.OriginNormalized ?? new Vector2(0.5f);

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, origin, rightVector, null, rect);

                break;
            }


            case MyRenderMessageEnum.DrawSpriteAtlas:
            {
                MyRenderMessageDrawSpriteAtlas sprite = (MyRenderMessageDrawSpriteAtlas)drawMessage;

                var tex         = MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true);
                var textureSize = MyTextures.GetSize(tex);

                Rectangle?sourceRect = new Rectangle(
                    (int)(textureSize.X * sprite.TextureOffset.X),
                    (int)(textureSize.Y * sprite.TextureOffset.Y),
                    (int)(textureSize.X * sprite.TextureSize.X),
                    (int)(textureSize.Y * sprite.TextureSize.Y));

                VRageMath.RectangleF destRect = new VRageMath.RectangleF(
                    (sprite.Position.X) * sprite.Scale.X,
                    (sprite.Position.Y) * sprite.Scale.Y,
                    sprite.HalfSize.X * sprite.Scale.X * 2,
                    sprite.HalfSize.Y * sprite.Scale.Y * 2);

                Vector2 origin = new Vector2(textureSize.X * sprite.TextureSize.X * 0.5f, textureSize.Y * sprite.TextureSize.Y * 0.5f);

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true), sprite.Color, origin, sprite.RightVector, sourceRect, destRect);

                break;
            }

            case MyRenderMessageEnum.DrawString:
            {
                var message = drawMessage as MyRenderMessageDrawString;

                var font = MyRender11.GetFont(message.FontIndex);
                font.DrawString(
                    message.ScreenCoord,
                    message.ColorMask,
                    message.Text,
                    message.ScreenScale,
                    message.ScreenMaxWidth);

                break;
            }

            case MyRenderMessageEnum.DrawScene:
            {
                UpdateSceneFrame();

                ProfilerShort.Begin("DrawScene");
                DrawGameScene(Backbuffer);
                ProfilerShort.Begin("TransferPerformanceStats");
                TransferPerformanceStats();
                ProfilerShort.End();
                ProfilerShort.End();

                ProfilerShort.Begin("Draw scene debug");
                MyGpuProfiler.IC_BeginBlock("Draw scene debug");
                DrawSceneDebug();
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                ProfilerShort.Begin("ProcessDebugMessages");
                ProcessDebugMessages();
                ProfilerShort.End();

                ProfilerShort.Begin("MyDebugRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
                MyDebugRenderer.Draw(MyRender11.Backbuffer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                var testingDepth = MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth : MyGBuffer.Main.DepthStencil;

                ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
                MyPrimitivesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                ProfilerShort.Begin("MyLinesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
                MyLinesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
                {
                    if (m_screenshot.Value.SizeMult == Vector2.One)
                    {
                        SaveScreenshotFromResource(Backbuffer.m_resource);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }

                ProfilerShort.Begin("MySpritesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MySpritesRenderer.Draw");
                MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                if (MyRenderProxy.DRAW_RENDER_STATS)
                {
                    MyRender11.GetRenderProfiler().StartProfilingBlock("MyRenderStatsDraw.Draw");
                    MyRenderStatsDraw.Draw(MyRenderStats.m_stats, 0.6f, VRageMath.Color.Yellow);
                    ProfilerShort.End();
                }

                break;
            }
            }
        }
        internal static void Render(MyUnorderedAccessTexture accumTarget, MyUnorderedAccessTexture coverageTarget)
        {
            ProfilerShort.Begin("Atmosphere");
            MyGpuProfiler.IC_BeginBlock("Atmosphere");
            if (MyRender11.DebugOverrides.Atmosphere)
            {
                MyAtmosphereRenderer.Render();
            }
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("Clouds");
            MyGpuProfiler.IC_BeginBlock("Clouds");
            if (MyRender11.DebugOverrides.Clouds)
            {
                MyCloudRenderer.Render();
            }
            MyGpuProfiler.IC_EndBlock();

            // setup weighted blended OIT targets + blend states
            if (MyRender11.DebugOverrides.OIT)
            {
                SetupOIT(accumTarget, coverageTarget, true);
            }
            else
            {
                SetupStandard();
            }

            MyDepthStencil depthResource;

            if (MyRender11.MultisamplingEnabled)
            {
                depthResource = MyScreenDependants.m_resolvedDepth;
            }
            else
            {
                depthResource = MyGBuffer.Main.DepthStencil;
            }

            ProfilerShort.BeginNextBlock("Billboards");
            MyGpuProfiler.IC_BeginBlock("Billboards");
            MyBillboardRenderer.Render(depthResource.Depth);
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("GPU Particles");
            MyGpuProfiler.IC_BeginBlock("GPU Particles");
            if (MyRender11.DebugOverrides.GPUParticles)
            {
                MyGPUParticleRenderer.Run(depthResource.Depth);
            }
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("Billboards - Depth Only");
            MyGpuProfiler.IC_BeginBlock("Billboards - Depth Only");
            bool windowsFound = MyBillboardRenderer.RenderWindowsDepthOnly(depthResource, MyRender11.Gbuffer1Copy);

            MyGpuProfiler.IC_EndBlock();

            if (MyRender11.DebugOverrides.OIT && windowsFound)
            {
                SetupOIT(accumTarget, coverageTarget, false);
            }

            ProfilerShort.BeginNextBlock("Render decals - Transparent");
            MyGpuProfiler.IC_BeginBlock("Render decals - Transparent");
            MyScreenDecals.Draw(true);
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("OIT Resolve");
            // resolve weighted blended OIT in  accum / coverage to LBuffer
            if (MyRender11.DebugOverrides.OIT)
            {
                ResolveOIT(accumTarget, coverageTarget);
            }
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.End();
        }
        internal static void Render(ISrvTexture postProcessedShadows)
        {
            MyLights.Update();

            MyGpuProfiler.IC_BeginBlock("Map lights to tiles");
            if (MyRender11.DebugOverrides.PointLights)
            {
                PreparePointLights();
            }
            MyGpuProfiler.IC_BeginNextBlock("Apply point lights");

            RC.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            if (!MyStereoRender.Enable)
            {
                RC.ComputeShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
                RC.PixelShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            }
            else
            {
                MyStereoRender.CSBindRawCB_FrameConstants(RC);
                MyStereoRender.PSBindRawCB_FrameConstants(RC);
            }

            RC.PixelShader.SetSrvs(0, MyGBuffer.Main);
            RC.AllShaderStages.SetRawSrv(MyCommon.MATERIAL_BUFFER_SLOT, MySceneMaterials.m_buffer.Srv);
            RC.SetBlendState(MyBlendStateManager.BlendAdditive);
            if (!MyStereoRender.Enable)
            {
                RC.SetDepthStencilState(MyDepthStencilStateManager.IgnoreDepthStencil);
            }
            else
            {
                RC.SetDepthStencilState(MyDepthStencilStateManager.StereoIgnoreDepthStencil);
            }
            RC.PixelShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);

            if (MyRender11.DebugOverrides.PointLights)
            {
                RenderPointlightsTiled();
            }

            MyGpuProfiler.IC_BeginNextBlock("Apply spotlights");
            if (MyRender11.DebugOverrides.SpotLights)
            {
                RenderSpotlights();
            }

            MyGpuProfiler.IC_BeginNextBlock("Apply directional light");
            if (MyRender11.DebugOverrides.EnvLight)
            {
                RenderDirectionalEnvironmentLight(postProcessedShadows);
            }
            MyGpuProfiler.IC_EndBlock();

            // Because of BindGBufferForRead:
            RC.AllShaderStages.SetSrv(0, null);
            RC.AllShaderStages.SetSrv(1, null);
            RC.AllShaderStages.SetSrv(2, null);
            RC.AllShaderStages.SetSrv(3, null);
            RC.AllShaderStages.SetSrv(4, null);
            RC.SetBlendState(null);
            RC.SetRtv(null);
        }
예제 #24
0
        internal void GatherArray(RwTexId postprocessTarget, RwTexId cascadeArray, MyProjectionInfo[] cascadeInfo, ConstantsBufferId cascadeConstantBuffer)
        {
            if (!MyRenderProxy.Settings.EnableShadows || !MyRender11.DebugOverrides.Shadows)
            {
                return;
            }

            MarkCascadesInStencil(cascadeInfo);

            MyGpuProfiler.IC_BeginBlock("Cascades postprocess");

            MyRenderContext renderContext = MyRenderContext.Immediate;
            DeviceContext   deviceContext = renderContext.DeviceContext;

            MyShadowsQuality shadowsQuality = MyRender11.RenderSettings.ShadowQuality.GetShadowsQuality();

            if (shadowsQuality == MyShadowsQuality.LOW)
            {
                renderContext.SetCS(m_gatherCS_LD);
            }
            else if (shadowsQuality == MyShadowsQuality.MEDIUM)
            {
                renderContext.SetCS(m_gatherCS_MD);
            }
            else if (shadowsQuality == MyShadowsQuality.HIGH)
            {
                renderContext.SetCS(m_gatherCS_HD);
            }

            ComputeShaderId.TmpUav[0] = postprocessTarget.Uav;
            deviceContext.ComputeShader.SetUnorderedAccessViews(0, ComputeShaderId.TmpUav, ComputeShaderId.TmpCount);

            deviceContext.ComputeShader.SetShaderResource(0, MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.m_SRV_depth : MyGBuffer.Main.DepthStencil.m_SRV_depth);
            deviceContext.ComputeShader.SetShaderResource(1, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
            deviceContext.ComputeShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, SamplerStates.m_shadowmap);
            if (!MyStereoRender.Enable)
            {
                deviceContext.ComputeShader.SetConstantBuffer(0, MyCommon.FrameConstants);
            }
            else
            {
                MyStereoRender.CSBindRawCB_FrameConstants(renderContext);
            }
            deviceContext.ComputeShader.SetConstantBuffer(4, cascadeConstantBuffer);
            deviceContext.ComputeShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, cascadeArray.SRV);

            Vector2I threadGroups = GetThreadGroupCount();

            deviceContext.Dispatch(threadGroups.X, threadGroups.Y, 1);

            ComputeShaderId.TmpUav[0] = null;
            renderContext.DeviceContext.ComputeShader.SetUnorderedAccessViews(0, ComputeShaderId.TmpUav, ComputeShaderId.TmpCount);
            deviceContext.ComputeShader.SetShaderResource(0, null);
            deviceContext.ComputeShader.SetShaderResource(1, null);

            if (shadowsQuality == MyShadowsQuality.HIGH && MyRender11.Settings.EnableShadowBlur)
            {
                MyBlur.Run(postprocessTarget.Rtv, MyRender11.CascadesHelper.Rtv, MyRender11.CascadesHelper.SRV, postprocessTarget.SRV, depthDiscardThreshold: 0.2f);
            }

            MyGpuProfiler.IC_EndBlock();
        }
예제 #25
0
        private static void DrawScene()
        {
            AddDebugQueueMessage("Frame render start");

            MyGpuProfiler.IC_BeginBlock("UpdateSceneFrame");
            UpdateSceneFrame();
            MyGpuProfiler.IC_EndBlock();

            var testingDepth = MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth : MyGBuffer.Main.DepthStencil;

            MyGpuProfiler.IC_BeginBlock("Clear");
            MyGBuffer.Main.Clear(VRageMath.Color.Black);
            MyGpuProfiler.IC_EndBlock();

            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.WaitForNextStart");
                MyOpenVR.WaitForNextStart();
                ProfilerShort.End();
            }

            ProfilerShort.Begin("DrawGameScene");
            DrawGameScene(Backbuffer);
            ProfilerShort.End();
            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.DisplayEye");
                MyGpuProfiler.IC_BeginBlock("OpenVR.DisplayEye");
                MyGBuffer.Main.Clear(VRageMath.Color.Black);//image is in HMD now, lets draw the rest for overlay
                MyOpenVR.Static.DisplayEye(MyRender11.Backbuffer.Resource.NativePointer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            ProfilerShort.Begin("Draw scene debug");
            MyGpuProfiler.IC_BeginBlock("Draw scene debug");
            DrawSceneDebug();
            ProfilerShort.End();

            ProfilerShort.Begin("ProcessDebugMessages");
            ProcessDebugMessages();
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyDebugRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
            MyDebugRenderer.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
            MyPrimitivesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyLinesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
            MyLinesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
            {
                ProfilerShort.Begin("Screenshot");
                if (m_screenshot.Value.SizeMult == Vector2.One)
                {
                    SaveScreenshotFromResource(Backbuffer.Resource);
                }
                else
                {
                    TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                }
                ProfilerShort.End();
            }

            ProfilerShort.Begin("ProcessDebugOutput");
            AddDebugQueueMessage("Frame render end");
            ProcessDebugOutput();
            ProfilerShort.End();
        }
예제 #26
0
        private unsafe void MarkCascadesInStencil(MyProjectionInfo[] cascadeInfo)
        {
            MyGpuProfiler.IC_BeginBlock("MarkCascadesInStencil");

            //RC.SetRS(MyRasterizerState.CullCW);

            MyRenderContext renderContext = MyRenderContext.Immediate;

            renderContext.DeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            renderContext.SetVB(0, m_cascadesBoundingsVertices.Buffer, m_cascadesBoundingsVertices.Stride);
            renderContext.SetIB(m_cubeIB.Buffer, m_cubeIB.Format);
            renderContext.SetIL(m_inputLayout);
            renderContext.DeviceContext.Rasterizer.SetViewport(0, 0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);
            renderContext.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            renderContext.BindDepthRT(MyGBuffer.Main.DepthStencil, DepthStencilAccess.DepthReadOnly, null);
            renderContext.SetVS(m_markVS);
            renderContext.SetPS(m_markPS);

            const int vertexCount = 8;

            Vector3D *frustumVerticesSS = stackalloc Vector3D[vertexCount];

            frustumVerticesSS[0] = new Vector3D(-1, -1, 0);
            frustumVerticesSS[1] = new Vector3D(-1, 1, 0);
            frustumVerticesSS[2] = new Vector3D(1, 1, 0);
            frustumVerticesSS[3] = new Vector3D(1, -1, 0);
            frustumVerticesSS[4] = new Vector3D(-1, -1, 1);
            frustumVerticesSS[5] = new Vector3D(-1, 1, 1);
            frustumVerticesSS[6] = new Vector3D(1, 1, 1);
            frustumVerticesSS[7] = new Vector3D(1, -1, 1);

            Vector3D *lightVertices    = stackalloc Vector3D[vertexCount];
            Vector3 * tmpFloatVertices = stackalloc Vector3[vertexCount];

            var mapping = MyMapping.MapDiscard(m_cascadesBoundingsVertices.Buffer);

            for (int cascadeIndex = 0; cascadeIndex < MyRender11.Settings.ShadowCascadeCount; ++cascadeIndex)
            {
                var inverseViewProj = MatrixD.Invert(cascadeInfo[cascadeIndex].CurrentLocalToProjection);
                for (int arrayIndex = 0; arrayIndex < vertexCount; ++arrayIndex)
                {
                    Vector3D.Transform(ref frustumVerticesSS[arrayIndex], ref inverseViewProj, out lightVertices[arrayIndex]);
                    tmpFloatVertices[arrayIndex] = lightVertices[arrayIndex];
                }

                for (int arrayIndex = 0; arrayIndex < vertexCount; ++arrayIndex)
                {
                    mapping.WriteAndPosition(ref tmpFloatVertices[arrayIndex]);
                }
            }
            mapping.Unmap();

            for (int cascadeIndex = 0; cascadeIndex < MyRender11.Settings.ShadowCascadeCount; ++cascadeIndex)
            {
                renderContext.SetDS(MyDepthStencilState.MarkIfInsideCascade[cascadeIndex], 1 << cascadeIndex);
                // mark ith bit on depth near
                renderContext.DeviceContext.DrawIndexed(36, 0, 8 * cascadeIndex);
            }

            renderContext.BindDepthRT(null, DepthStencilAccess.DepthReadOnly, null);

            renderContext.SetDS(null);
            renderContext.SetRS(null);

            MyGpuProfiler.IC_EndBlock();
        }
예제 #27
0
        private static void DrawScene()
        {
            AddDebugQueueMessage("Frame render start");

            MyGpuProfiler.IC_BeginBlock("UpdateSceneFrame");
            UpdateSceneFrame();
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("Clear");
            MyGBuffer.Main.Clear(VRageMath.Color.Black);
            MyGpuProfiler.IC_EndBlock();

            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.WaitForNextStart");
                MyOpenVR.WaitForNextStart();
                ProfilerShort.End();
            }

            IBorrowedRtvTexture debugAmbientOcclusion; // TODO: Think of another way to get this texture to the DebugRenderer...

            ProfilerShort.Begin("DrawGameScene");
            DrawGameScene(Backbuffer, out debugAmbientOcclusion);
            ProfilerShort.End();
            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.DisplayEye");
                MyGpuProfiler.IC_BeginBlock("OpenVR.DisplayEye");
                MyGBuffer.Main.Clear(VRageMath.Color.Black);//image is in HMD now, lets draw the rest for overlay
                MyOpenVR.Static.DisplayEye(MyRender11.Backbuffer.Resource.NativePointer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            ProfilerShort.Begin("Draw scene debug");
            MyGpuProfiler.IC_BeginBlock("Draw scene debug");
            DrawSceneDebug();
            ProfilerShort.End();

            ProfilerShort.Begin("ProcessDebugMessages");
            ProcessDebugMessages();
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyDebugRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
            MyDebugRenderer.Draw(MyRender11.Backbuffer, debugAmbientOcclusion);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            debugAmbientOcclusion.Release();

            ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
            MyPrimitivesRenderer.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyLinesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
            MyLinesRenderer.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
            {
                ProfilerShort.Begin("Screenshot");
                if (m_screenshot.Value.SizeMult == Vector2.One)
                {
                    SaveScreenshotFromResource(Backbuffer);
                }
                else
                {
                    TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                }
                ProfilerShort.End();
            }

            ProfilerShort.Begin("ProcessDebugOutput");
            AddDebugQueueMessage("Frame render end");
            ProcessDebugOutput();
            ProfilerShort.End();
        }
예제 #28
0
        internal static void Run(ISrvBindable depthRead, ISrvBindable gbufferNormalsRead)
        {
            // The maximum number of supported GPU particles
            ISrvBindable textureArraySrv;
            int          emitterCount = MyGPUEmitters.Gather(m_emitterData, out textureArraySrv);

            if (emitterCount == 0)
            {
                return;
            }

            // Unbind current targets while we run the compute stages of the system
            //RC.DeviceContext.OutputMerger.SetTargets(null);
            // global GPU particles setup
            RC.SetDepthStencilState(MyDepthStencilStateManager.DefaultDepthState);
            RC.SetRasterizerState(MyRasterizerStateManager.NocullRasterizerState);
            RC.SetInputLayout(null);
            RC.ComputeShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            RC.ComputeShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);
            RC.PixelShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);
            RC.AllShaderStages.SetConstantBuffer(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer);
            RC.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MySamplerStateManager.Shadowmap);
            RC.VertexShader.SetSrv(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray);
            RC.VertexShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);

            // If we are resetting the particle system, then initialize the dead list
            if (m_resetSystem)
            {
                ResetInternal();
                m_resetSystem = false;
            }

            MyGpuProfiler.IC_BeginBlock("Emit");
            // Emit particles into the system
            Emit(emitterCount, m_emitterData, depthRead);
            MyGpuProfiler.IC_EndBlock();

            // Run the simulation for this frame
            MyGpuProfiler.IC_BeginBlock("Simulate");
            Simulate(depthRead, gbufferNormalsRead);
            MyGpuProfiler.IC_EndBlock();

            // Copy the atomic counter in the alive list UAV into a constant buffer for access by subsequent passes
            RC.CopyStructureCount(m_activeListConstantBuffer, 0, m_aliveIndexBuffer);

            // Only read number of alive and dead particle back to the CPU in debug as we don't want to stall the GPU in release code

            ProfilerShort.Begin("Debug - ReadCounter");
            MyGpuProfiler.IC_BeginBlock("Debug - ReadCounter");
            int numActiveParticlesAfterSimulation = ReadCounter(m_aliveIndexBuffer);

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            MyGpuProfiler.IC_BeginBlock("Render");
            Render(textureArraySrv, depthRead);
            MyGpuProfiler.IC_EndBlock();

            RC.ComputeShader.SetSamplers(0, MySamplerStateManager.StandardSamplers);

            MyStatsDisplay.Write("GPU particles", "Live #", numActiveParticlesAfterSimulation);
        }
예제 #29
0
        // Returns the final image and copies it to renderTarget if non-null
        private static MyBindableResource DrawGameScene(MyBindableResource renderTarget)
        {
            MyGpuProfiler.IC_BeginBlock("Clear & Geometry Render");

            PrepareGameScene();

            // todo: shouldn't be necessary
            if (true)
            {
                ProfilerShort.Begin("Clear");
                MyRenderContext.Immediate.Clear();
                MyRenderContext.Immediate.DeviceContext.ClearState();
                ProfilerShort.End();
            }

            if (MyStereoRender.Enable && MyStereoRender.EnableUsingStencilMask)
            {
                ProfilerShort.Begin("MyStereoStencilMask.Draw");
                MyGpuProfiler.IC_BeginBlock("MyStereoStencilMask.Draw");
                MyStereoStencilMask.Draw();
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            MyGpuProfiler.IC_BeginBlock("MyGeometryRenderer.Render");
            Debug.Assert(m_commandLists.Count == 0, "Not all command lists executed last frame!");
            ProfilerShort.Begin("DynamicGeometryRenderer");
            DynamicGeometryRenderer.Render(m_commandLists, true);
            ProfilerShort.End();    // End function block
            if (MyScene.SeparateGeometry)
            {
                ProfilerShort.Begin("StaticGeometryRenderer");
                StaticGeometryRenderer.Render(m_commandLists, false);
                ProfilerShort.End();    // End function block
            }

            SendGlobalOutputMessages();
            ExecuteCommandLists(m_commandLists);
            MyGpuProfiler.IC_EndBlock();

#if !UNSHARPER_TMP
            MyEnvironmentProbe.FinalizeEnvProbes();
#endif

            // cleanup context atfer deferred lists
            if (MyRender11.DeferredContextsEnabled)
            {
                ProfilerShort.Begin("Clear2");
                MyRenderContext.Immediate.Clear();
                ProfilerShort.End();
            }

            // todo: shouldn't be necessary
            if (true)
            {
                ProfilerShort.Begin("Clear3");
                MyRenderContext.Immediate.Clear();
                MyRenderContext.Immediate.DeviceContext.ClearState();
                ProfilerShort.End();
            }

            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.Begin("Render decals - Opaque");
            MyGpuProfiler.IC_BeginBlock("Render decals - Opaque");
            MyRender11.CopyGbufferToScratch();
            MyScreenDecals.Draw(false);
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("Render foliage");
            MyGpuProfiler.IC_BeginBlock("Render foliage");
            m_foliageRenderer.Render();
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("GBuffer Resolve");
            ProfilerShort.BeginNextBlock("MySceneMaterials.MoveToGPU");
            MySceneMaterials.MoveToGPU();

            int nPasses = MyStereoRender.Enable ? 2 : 1;
            for (int i = 0; i < nPasses; i++)
            {
                if (MyStereoRender.Enable)
                {
                    MyStereoRender.RenderRegion = i == 0 ? MyStereoRegion.LEFT : MyStereoRegion.RIGHT;
                }

                if (MultisamplingEnabled)
                {
                    MyRender11.DeviceContext.ClearDepthStencilView(MyScreenDependants.m_resolvedDepth.m_DSV, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);
                    MyGpuProfiler.IC_BeginBlock("MarkAAEdges");
                    MyAAEdgeMarking.Run();
                    MyGpuProfiler.IC_EndBlock();
                    MyDepthResolve.Run(MyScreenDependants.m_resolvedDepth, MyGBuffer.Main.DepthStencil.Depth);
                }

                ProfilerShort.BeginNextBlock("Shadows");
                MyGpuProfiler.IC_BeginBlock("Shadows");
                if (MyScene.SeparateGeometry)
                {
                    MyShadowCascadesPostProcess.Combine(MyShadowCascades.CombineShadowmapArray, DynamicShadows.ShadowCascades, StaticShadows.ShadowCascades);
                    DynamicShadows.ShadowCascades.PostProcess(MyRender11.PostProcessedShadows, MyShadowCascades.CombineShadowmapArray);
                }
                else
                {
                    DynamicShadows.ShadowCascades.PostProcess(MyRender11.PostProcessedShadows, DynamicShadows.ShadowCascades.CascadeShadowmapArray);
                }
                MyGpuProfiler.IC_EndBlock();

                ProfilerShort.BeginNextBlock("SSAO");
                MyGpuProfiler.IC_BeginBlock("SSAO");
                if (Postprocess.EnableSsao && m_debugOverrides.Postprocessing && m_debugOverrides.SSAO)
                {
                    MySSAO.Run(MyScreenDependants.m_ambientOcclusion, MyGBuffer.Main, MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.Depth : MyGBuffer.Main.DepthStencil.Depth);

                    if (MySSAO.UseBlur)
                    {
                        MyBlur.Run(MyScreenDependants.m_ambientOcclusion, MyScreenDependants.m_ambientOcclusionHelper, MyScreenDependants.m_ambientOcclusion);
                    }
                }
                else
                {
                    MyRender11.DeviceContext.ClearRenderTargetView(MyScreenDependants.m_ambientOcclusion.m_RTV, Color4.White);
                }
                MyGpuProfiler.IC_EndBlock();

                ProfilerShort.BeginNextBlock("Lights");
                MyGpuProfiler.IC_BeginBlock("Lights");
                if (m_debugOverrides.Lighting)
                {
                    MyLightRendering.Render();
                }
                MyGpuProfiler.IC_EndBlock();

                if (MyRender11.DebugOverrides.Flares)
                {
                    MyLightRendering.DrawFlares();
                }
            }
            MyStereoRender.RenderRegion = MyStereoRegion.FULLSCREEN;
            MyGpuProfiler.IC_EndBlock();

            // Rendering for VR is solved inside of Transparent rendering
            ProfilerShort.BeginNextBlock("Transparent Pass");
            MyGpuProfiler.IC_BeginBlock("Transparent Pass");
            if (m_debugOverrides.Transparent)
            {
                MyTransparentRendering.Render(m_transparencyAccum, m_transparencyCoverage);
            }
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("PostProcess");
            MyGpuProfiler.IC_BeginBlock("PostProcess");
            MyGpuProfiler.IC_BeginBlock("Luminance reduction");
            MyBindableResource avgLum = null;

            if (m_resetEyeAdaptation)
            {
                MyRenderContext.Immediate.DeviceContext.ClearUnorderedAccessView(m_prevLum.m_UAV, Int4.Zero);
                m_resetEyeAdaptation = false;
            }

            avgLum = MyLuminanceAverage.Run(m_reduce0, m_reduce1, MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), m_prevLum);

            MyGpuProfiler.IC_EndBlock();

            if (MyRender11.Settings.DisplayHdrDebug)
            {
                var src = MyGBuffer.Main.Get(MyGbufferSlot.LBuffer) as MyRenderTarget;
                MyHdrDebugTools.CreateHistogram(src.m_SRV, src.m_resolution, src.m_samples.X);
            }


            MyGpuProfiler.IC_BeginBlock("Bloom");
            MyBindableResource bloom;
            if (m_debugOverrides.Postprocessing && m_debugOverrides.Bloom)
            {
                bloom = MyBloom.Run(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), avgLum);
            }
            else
            {
                MyRender11.DeviceContext.ClearRenderTargetView(MyRender11.EighthScreenUavHDR.m_RTV, Color4.Black);
                bloom = MyRender11.EighthScreenUavHDR;
            }
            MyGpuProfiler.IC_EndBlock();

            MyBindableResource tonemapped;
            bool fxaa = MyRender11.FxaaEnabled;
            if (fxaa)
            {
                tonemapped = m_rgba8_linear;
            }
            else
            {
                tonemapped = m_uav3;
            }

            MyGpuProfiler.IC_BeginBlock("Tone mapping");
            if (m_debugOverrides.Postprocessing && m_debugOverrides.Tonemapping)
            {
                MyToneMapping.Run(tonemapped, MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), avgLum, bloom, Postprocess.EnableTonemapping);
            }
            else
            {
                tonemapped = MyGBuffer.Main.Get(MyGbufferSlot.LBuffer);
                //MyRender11.DeviceContext.CopyResource(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer).m_resource, tonemapped.m_resource);
            }
            MyGpuProfiler.IC_EndBlock();

            MyBindableResource renderedImage;

            if (fxaa)
            {
                MyGpuProfiler.IC_BeginBlock("FXAA");
                MyFXAA.Run(m_rgba8_0.GetView(new MyViewKey {
                    Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm, View = MyViewEnum.RtvView
                }), tonemapped);
                MyGpuProfiler.IC_EndBlock();

                renderedImage = m_rgba8_0.GetView(new MyViewKey {
                    Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.SrvView
                });
            }
            else
            {
                //renderedImage = (tonemapped as MyCustomTexture).GetView(new MyViewKey { Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.SrvView });
                renderedImage = tonemapped;
            }
            ProfilerShort.Begin("Outline");
            if (MyOutline.AnyOutline())
            {
                MyOutline.Run();

                MyGpuProfiler.IC_BeginBlock("Outline Blending");
                ProfilerShort.Begin("Outline Blending");
                if (fxaa)
                {
                    MyBlendTargets.RunWithStencil(
                        m_rgba8_0.GetView(new MyViewKey {
                        Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.RtvView
                    }),
                        MyRender11.m_rgba8_1,
                        MyRender11.BlendAdditive,
                        MyDepthStencilState.TestOutlineMeshStencil,
                        0x40);
                    MyBlendTargets.RunWithStencil(
                        m_rgba8_0.GetView(new MyViewKey {
                        Fmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, View = MyViewEnum.RtvView
                    }),
                        MyRender11.m_rgba8_1,
                        MyRender11.BlendTransparent,
                        MyDepthStencilState.TestHighlightMeshStencil,
                        0x40);
                }
                else
                {
                    if (MyRender11.MultisamplingEnabled)
                    {
                        MyBlendTargets.RunWithPixelStencilTest(tonemapped, MyRender11.m_rgba8_ms, MyRender11.BlendAdditive);
                        MyBlendTargets.RunWithPixelStencilTest(tonemapped, MyRender11.m_rgba8_ms, MyRender11.BlendTransparent, true);
                    }
                    else
                    {
                        MyBlendTargets.RunWithStencil(tonemapped, MyRender11.m_rgba8_1, MyRender11.BlendAdditive, MyDepthStencilState.TestOutlineMeshStencil, 0x40);
                        MyBlendTargets.RunWithStencil(tonemapped, MyRender11.m_rgba8_1, MyRender11.BlendTransparent, MyDepthStencilState.TestHighlightMeshStencil, 0x40);
                    }
                }
                ProfilerShort.End();
                MyGpuProfiler.IC_EndBlock();
            }
            ProfilerShort.End();

            if (renderTarget != null)
            {
                MyCopyToRT.Run(renderTarget, renderedImage);
            }

            if (MyRender11.Settings.DisplayHdrDebug)
            {
                var target = renderTarget as IRenderTargetBindable;
                var lum    = avgLum as IShaderResourceBindable;
                if (target != null && lum != null)
                {
                    MyHdrDebugTools.DisplayHistogram(target.RTV, lum.SRV);
                }
            }
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            return(renderedImage);
        }
        // Returns the final image and copies it to renderTarget if non-null
        private static IRtvTexture DrawGameScene(IRtvBindable renderTarget)
        {
            MyGpuProfiler.IC_BeginBlockAlways("ClearAndGeometryRender");

            PrepareGameScene();


            // todo: shouldn't be necessary
            if (true)
            {
                ProfilerShort.Begin("Clear");
                MyRender11.RC.ClearState();
                ProfilerShort.End();
            }

            if (MyStereoRender.Enable && MyStereoRender.EnableUsingStencilMask)
            {
                ProfilerShort.Begin("MyStereoStencilMask.Draw");
                MyGpuProfiler.IC_BeginBlock("MyStereoStencilMask.Draw");
                MyStereoStencilMask.Draw();
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            MyGpuProfiler.IC_BeginBlock("MyGeometryRenderer.Render");
            Debug.Assert(m_commandLists.Count == 0, "Not all command lists executed last frame!");
            ProfilerShort.Begin("DynamicGeometryRenderer");
            DynamicGeometryRenderer.Render(m_commandLists, true);
            ProfilerShort.End();    // End function block
            if (MyScene.SeparateGeometry)
            {
                ProfilerShort.Begin("StaticGeometryRenderer");
                StaticGeometryRenderer.Render(m_commandLists, false);
                ProfilerShort.End();    // End function block
            }

            SendGlobalOutputMessages();
            ExecuteCommandLists(m_commandLists);
            MyGpuProfiler.IC_EndBlock();

#if !UNSHARPER_TMP
            MyManagers.EnvironmentProbe.FinalizeEnvProbes();
#endif

            // cleanup context atfer deferred lists
            if (true)
            {
                ProfilerShort.Begin("Clear3");
                MyRender11.RC.ClearState();
                ProfilerShort.End();
            }

            MyGpuProfiler.IC_EndBlockAlways();

            ProfilerShort.Begin("Render decals - Opaque");
            MyGpuProfiler.IC_BeginBlock("Render decals - Opaque");
            MyImmediateRC.RC.CopyResource(MyGBuffer.Main.GBuffer1.Resource, MyGlobalResources.Gbuffer1Copy.Resource); // copy gbuffer1
            MyScreenDecals.Draw(false);
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("Render foliage");
            MyGpuProfiler.IC_BeginBlockAlways("RenderFoliage");
            m_foliageRenderer.Render();
            MyGpuProfiler.IC_EndBlockAlways();

            MyGpuProfiler.IC_BeginBlock("GBuffer Resolve");
            ProfilerShort.BeginNextBlock("MySceneMaterials.MoveToGPU");
            MySceneMaterials.MoveToGPU();

            MyRender11.RC.ResetTargets();

            int nPasses = MyStereoRender.Enable ? 2 : 1;
            for (int i = 0; i < nPasses; i++)
            {
                if (MyStereoRender.Enable)
                {
                    MyStereoRender.RenderRegion = i == 0 ? MyStereoRegion.LEFT : MyStereoRegion.RIGHT;
                }

                if (MultisamplingEnabled)
                {
                    MyRender11.RC.ClearDsv(MyScreenDependants.m_resolvedDepth, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);
                    MyGpuProfiler.IC_BeginBlock("MarkAAEdges");
                    MyAAEdgeMarking.Run();
                    MyGpuProfiler.IC_EndBlock();
                    MyDepthResolve.Run(MyScreenDependants.m_resolvedDepth, MyGBuffer.Main.DepthStencil);
                }

                ProfilerShort.BeginNextBlock("Shadows");
                MyGpuProfiler.IC_BeginBlockAlways("Shadows");
                IBorrowedUavTexture postProcessedShadows;
                if (MyScene.SeparateGeometry)
                {
                    MyShadowCascadesPostProcess.Combine(MyShadowCascades.CombineShadowmapArray, DynamicShadows.ShadowCascades, StaticShadows.ShadowCascades);
                    postProcessedShadows = DynamicShadows.ShadowCascades.PostProcess(MyShadowCascades.CombineShadowmapArray);
                    //MyShadowCascadesPostProcess.Combine(MyShadowCascades.CombineShadowmapArray,
                    //    DynamicShadows.ShadowCascades, StaticShadows.ShadowCascades);
                    //postProcessedShadows =
                    //    DynamicShadows.ShadowCascades.PostProcess(MyShadowCascades.CombineShadowmapArray);
                }
                else
                {
                    postProcessedShadows = DynamicShadows.ShadowCascades.PostProcess(DynamicShadows.ShadowCascades.CascadeShadowmapArray);
                    //postProcessedShadows = MyManagers.Shadow.Evaluate();
                }
                MyGpuProfiler.IC_EndBlockAlways();

                if (MySSAO.Params.Enabled && m_debugOverrides.Postprocessing && m_debugOverrides.SSAO)
                {
                    ProfilerShort.BeginNextBlock("SSAO");
                    MyGpuProfiler.IC_BeginBlockAlways("SSAO");
                    MySSAO.Run(MyScreenDependants.m_ambientOcclusion, MyGBuffer.Main, MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.SrvDepth : MyGBuffer.Main.DepthStencil.SrvDepth);

                    if (MySSAO.Params.UseBlur)
                    {
                        MyBlur.Run(MyScreenDependants.m_ambientOcclusion, MyScreenDependants.m_ambientOcclusionHelper, MyScreenDependants.m_ambientOcclusion, clearColor: Color4.White);
                    }
                    MyGpuProfiler.IC_EndBlockAlways();
                }
                else if (MyHBAO.Params.Enabled && m_debugOverrides.Postprocessing && m_debugOverrides.SSAO)
                {
                    ProfilerShort.BeginNextBlock("HBAO");
                    MyGpuProfiler.IC_BeginBlock("HBAO");
                    MyHBAO.Run(MyScreenDependants.m_ambientOcclusion, MyGBuffer.Main,
                               MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.SrvDepth : MyGBuffer.Main.DepthStencil.SrvDepth);
                    MyGpuProfiler.IC_EndBlock();
                }
                else
                {
                    MyRender11.RC.ClearRtv(MyScreenDependants.m_ambientOcclusion, Color4.White);
                }

                ProfilerShort.BeginNextBlock("Lights");
                MyGpuProfiler.IC_BeginBlockAlways("Lights");
                if (m_debugOverrides.Lighting)
                {
                    MyLightRendering.Render(postProcessedShadows);
                }
                MyGpuProfiler.IC_EndBlockAlways();
                postProcessedShadows.Release();

                if (MyRender11.DebugOverrides.Flares)
                {
                    MyLightRendering.DrawFlares();
                }
            }
            MyStereoRender.RenderRegion = MyStereoRegion.FULLSCREEN;
            MyGpuProfiler.IC_EndBlock();

            // Rendering for VR is solved inside of Transparent rendering
            ProfilerShort.BeginNextBlock("Transparent Pass");
            MyGpuProfiler.IC_BeginBlockAlways("TransparentPass");
            if (m_debugOverrides.Transparent)
            {
                MyTransparentRendering.Render();
            }
            MyGpuProfiler.IC_EndBlockAlways();

            ProfilerShort.BeginNextBlock("PostProcess");
            MyGpuProfiler.IC_BeginBlockAlways("PostProcess");
            MyGpuProfiler.IC_BeginBlock("Luminance reduction");
            IBorrowedUavTexture avgLum = null;

            if (MyRender11.Postprocess.EnableEyeAdaptation)
            {
                if (m_resetEyeAdaptation)
                {
                    MyLuminanceAverage.Reset();
                    m_resetEyeAdaptation = false;
                }

                avgLum = MyLuminanceAverage.Run(MyGBuffer.Main.LBuffer);
            }
            else
            {
                avgLum = MyLuminanceAverage.Skip();
            }

            MyGpuProfiler.IC_EndBlock();

            IBorrowedUavTexture histogram = null;
            if (MyRender11.Settings.DisplayHistogram)
            {
                histogram = MyHdrDebugTools.CreateHistogram(MyGBuffer.Main.LBuffer, MyGBuffer.Main.SamplesCount);
            }
            if (MyRender11.Settings.DisplayHdrIntensity)
            {
                MyHdrDebugTools.DisplayHdrIntensity(MyGBuffer.Main.LBuffer);
            }

            MyGpuProfiler.IC_BeginBlock("Bloom");
            IBorrowedUavTexture bloom;
            if (m_debugOverrides.Postprocessing && m_debugOverrides.Bloom)
            {
                bloom = MyBloom.Run(MyGBuffer.Main.LBuffer, MyGBuffer.Main.GBuffer2,
                                    MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.SrvDepth : MyGBuffer.Main.DepthStencil.SrvDepth);
            }
            else
            {
                bloom = MyManagers.RwTexturesPool.BorrowUav("bloom_EightScreenUavHDR", MyRender11.ResolutionI.X / 8, MyRender11.ResolutionI.Y / 8, MyGBuffer.LBufferFormat);
                MyRender11.RC.ClearRtv(bloom, Color4.Black);
            }
            MyGpuProfiler.IC_EndBlock();


            MyGpuProfiler.IC_BeginBlock("Tone mapping");
            IBorrowedUavTexture tonemapped = MyToneMapping.Run(MyGBuffer.Main.LBuffer, avgLum, bloom, Postprocess.EnableTonemapping && m_debugOverrides.Postprocessing && m_debugOverrides.Tonemapping);
            bloom.Release();
            MyGpuProfiler.IC_EndBlock();

            IRtvTexture renderedImage;

            IBorrowedCustomTexture rgba8_0 = null;
            bool fxaa = MyRender11.FxaaEnabled;
            if (fxaa)
            {
                rgba8_0 = MyManagers.RwTexturesPool.BorrowCustom("MyRender11.Rgb8_0");
                MyGpuProfiler.IC_BeginBlock("FXAA");
                MyFXAA.Run(rgba8_0.Linear, tonemapped);
                MyGpuProfiler.IC_EndBlock();

                renderedImage = rgba8_0.SRgb;
            }
            else
            {
                renderedImage = tonemapped;
            }
            ProfilerShort.Begin("Outline");
            if (MyOutline.AnyOutline())
            {
                IBorrowedRtvTexture outlined = MyOutline.Run();

                MyGpuProfiler.IC_BeginBlock("Outline Blending");
                ProfilerShort.Begin("Outline Blending");
                if (fxaa)
                {
                    MyBlendTargets.RunWithStencil(
                        rgba8_0.SRgb,
                        outlined,
                        MyBlendStateManager.BlendAdditive,
                        MyDepthStencilStateManager.TestOutlineMeshStencil,
                        0x40);
                    MyBlendTargets.RunWithStencil(
                        rgba8_0.SRgb,
                        outlined,
                        MyBlendStateManager.BlendTransparent,
                        MyDepthStencilStateManager.TestHighlightMeshStencil,
                        0x40);
                }
                else
                {
                    if (MyRender11.MultisamplingEnabled)
                    {
                        MyBlendTargets.RunWithPixelStencilTest(tonemapped, outlined, MyBlendStateManager.BlendAdditive);
                        MyBlendTargets.RunWithPixelStencilTest(tonemapped, outlined, MyBlendStateManager.BlendTransparent, true);
                    }
                    else
                    {
                        MyBlendTargets.RunWithStencil(tonemapped, outlined, MyBlendStateManager.BlendAdditive, MyDepthStencilStateManager.TestOutlineMeshStencil, 0x40);
                        MyBlendTargets.RunWithStencil(tonemapped, outlined, MyBlendStateManager.BlendTransparent, MyDepthStencilStateManager.TestHighlightMeshStencil, 0x40);
                    }
                }
                ProfilerShort.End();
                MyGpuProfiler.IC_EndBlock();

                outlined.Release();
            }
            ProfilerShort.End();

            if (renderTarget != null)
            {
                MyCopyToRT.Run(renderTarget, renderedImage);
            }

            if (MyRender11.Settings.DisplayHistogram)
            {
                if (renderTarget != null && avgLum != null)
                {
                    MyHdrDebugTools.DisplayHistogram(renderTarget, avgLum, histogram);
                }
            }
            MyGpuProfiler.IC_EndBlockAlways();
            ProfilerShort.End();

            if (rgba8_0 != null)
            {
                rgba8_0.Release();
            }
            if (histogram != null)
            {
                histogram.Release();
            }
            avgLum.Release();
            tonemapped.Release();

            // HOTFIX: MyDebugTextureDisplay uses borrowed textures. If we place MyDebugTextureDisplay to the different location, we will have problem with borrowed textures (comment by Michal)
            ProfilerShort.Begin("MyDebugTextureDisplay.Draw");
            MyGpuProfiler.IC_BeginBlock("MyDebugTextureDisplay.Draw");
            MyDebugTextureDisplay.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            return(renderedImage);
        }