internal static void Present()
        {
            if (m_swapchain != null)
            {
                GetRenderProfiler().StartProfilingBlock("Screenshot");
                if (m_screenshot.HasValue)
                {
                    if (m_screenshot.Value.SizeMult == VRageMath.Vector2.One)
                    {
                        MyCopyToRT.ClearAlpha(Backbuffer);
                        SaveScreenshotFromResource(Backbuffer.Resource);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }
                GetRenderProfiler().EndProfilingBlock();

                try
                {
                    MyManagers.OnFrameEnd();
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                    GetRenderProfiler().StartProfilingBlock("Waiting for present");
                    m_swapchain.Present(m_settings.VSync ? 1 : 0, 0);
                    GetRenderProfiler().EndProfilingBlock();
                    MyGpuProfiler.IC_EndBlock();

                    MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.Present, ref MyStatsUpdater.Timestamps.PreviousPresent);

                    if (VRage.OpenVRWrapper.MyOpenVR.Static != null)
                    {
                        MyGpuProfiler.IC_BeginBlock("OpenVR.FrameDone");
                        GetRenderProfiler().StartProfilingBlock("OpenVR.FrameDone");

                        /*var handle=MyOpenVR.GetOverlay("menu");
                         * MyOpenVR.SetOverlayTexture(handle, MyRender11.Backbuffer.m_resource.NativePointer);
                         */
                        VRage.OpenVRWrapper.MyOpenVR.FrameDone();
                        GetRenderProfiler().EndProfilingBlock();
                        MyGpuProfiler.IC_EndBlock();
                    }

                    m_consecutivePresentFails = 0;

                    GetRenderProfiler().StartProfilingBlock("Stopwatch");
                    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();
                    GetRenderProfiler().EndProfilingBlock();
                }
                catch (SharpDXException e)
                {
                    Log.WriteLine("Device removed - resetting device; reason: " + e.Message);
                    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().StartProfilingBlock("GPU profiler");
                MyGpuProfiler.EndFrame();
                MyGpuProfiler.StartFrame();
                m_profilingStarted = true;
                GetRenderProfiler().EndProfilingBlock();

                // waiting for change to fullscreen - window migh overlap or some other dxgi excuse to fail :(
                GetRenderProfiler().StartProfilingBlock("TryChangeToFullscreen");
                TryChangeToFullscreen();
                GetRenderProfiler().EndProfilingBlock();
            }
        }
        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();
        }
예제 #3
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.Resource,
                                              m_prevWorkCubemapPrefiltered.Resource);
                MyImmediateRC.RC.CopyResource(m_workCubemapPrefiltered.Resource, Cubemap.Resource);
                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();
        }
예제 #4
0
        internal static void Run(MyBindableResource depthRead)
        {
            // The maximum number of supported GPU particles
            SharpDX.Direct3D11.ShaderResourceView 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.SetDS(MyDepthStencilState.DefaultDepthState);
            RC.SetRS(MyRender11.m_nocullRasterizerState);
            RC.SetIL(null);
            RC.CSSetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            RC.DeviceContext.ComputeShader.SetSamplers(0, SamplerStates.StandardSamplers);
            RC.DeviceContext.PixelShader.SetSamplers(0, SamplerStates.StandardSamplers);
            RC.SetCB(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer);
            RC.DeviceContext.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, SamplerStates.m_shadowmap);
            RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray.SRV);
            RC.DeviceContext.VertexShader.SetSamplers(0, SamplerStates.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);
            MyGpuProfiler.IC_EndBlock();

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

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

            // 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
#if DEBUG
            m_numDeadParticlesAfterSimulation   = ReadCounter(m_deadListBuffer);
            m_numActiveParticlesAfterSimulation = ReadCounter(m_aliveIndexBuffer);
#endif

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

            RC.DeviceContext.ComputeShader.SetSamplers(0, SamplerStates.StandardSamplers);

            /*Debug.WriteLine(string.Format("dead particles @ start {0} dead after emit {1} dead after sim {2} active after sim {3}",
             *  m_numDeadParticlesOnInit, m_numDeadParticlesAfterEmit,
             *  m_numDeadParticlesAfterSimulation, m_numActiveParticlesAfterSimulation));*/
        }
예제 #5
0
        /// <summary>
        /// Creates shadowmap queries and appends them to the provided list
        /// </summary>
        internal unsafe void PrepareQueries(List <MyShadowmapQuery> appendShadowmapQueries)
        {
            Debug.Assert(appendShadowmapQueries != null, "Shadowmap query list cannot be null!");
            if (!MyRender11.Settings.EnableShadows || !MyRender11.DebugOverrides.Shadows || MyRender11.RenderSettings.ShadowQuality.GetShadowsQuality() == MyShadowsQuality.DISABLED)
            {
                return;
            }

            MyGpuProfiler.IC_BeginBlock("PrepareCascades");
            MyImmediateRC.RC.CopyResource(m_cascadeShadowmapArray, m_cascadeShadowmapBackup);

            bool        stabilize = true;
            const float DirectionDifferenceThreshold = 0.0175f;

            float shadowChangeDelayMultiplier = 180;

            for (int cascadeIndex = 0; cascadeIndex < m_initializedShadowCascadesCount; ++cascadeIndex)
            {
                ++m_shadowCascadeFramesSinceLightUpdate[cascadeIndex];

                if (m_shadowCascadeFramesSinceLightUpdate[cascadeIndex] > cascadeIndex * shadowChangeDelayMultiplier ||
                    MyRender11.Environment.Data.EnvironmentLight.SunLightDirection.Dot(m_shadowCascadeLightDirections[cascadeIndex]) < (1 - DirectionDifferenceThreshold))
                {
                    m_shadowCascadeLightDirections[cascadeIndex]        = MyRender11.Environment.Data.EnvironmentLight.SunLightDirection;
                    m_shadowCascadeFramesSinceLightUpdate[cascadeIndex] = 0;
                }
            }

            var globalMatrix = CreateGlobalMatrix();

            float cascadesNearClip = 1f;

            float backOffset    = MyRender11.RenderSettings.ShadowQuality.BackOffset();
            float shadowmapSize = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeResolution();

            for (int cascadeIndex = 0; cascadeIndex < ShadowCascadeSplitDepths.Length; ++cascadeIndex)
            {
                ShadowCascadeSplitDepths[cascadeIndex] = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeSplit(cascadeIndex);
            }

            double unitWidth  = 1.0 / MyRender11.Environment.Matrices.Projection.M11;
            double unitHeight = 1.0 / MyRender11.Environment.Matrices.Projection.M22;

            Vector3D *untransformedVertices = stackalloc Vector3D[4];

            untransformedVertices[0] = new Vector3D(-unitWidth, -unitHeight, -1);
            untransformedVertices[1] = new Vector3D(-unitWidth, unitHeight, -1);
            untransformedVertices[2] = new Vector3D(unitWidth, unitHeight, -1);
            untransformedVertices[3] = new Vector3D(unitWidth, -unitHeight, -1);

            MatrixD *cascadesMatrices = stackalloc MatrixD[MaxShadowCascades];

            for (int cascadeIndex = 0; cascadeIndex < m_initializedShadowCascadesCount; ++cascadeIndex)
            {
                for (int vertexIndex = 0; vertexIndex < 4; ++vertexIndex)
                {
                    m_frustumVerticesWS[vertexIndex]     = untransformedVertices[vertexIndex] * ShadowCascadeSplitDepths[cascadeIndex];
                    m_frustumVerticesWS[vertexIndex + 4] = untransformedVertices[vertexIndex] * ShadowCascadeSplitDepths[cascadeIndex + 1];
                }

                bool skipCascade = MyCommon.FrameCounter % (ulong)m_shadowCascadeUpdateIntervals[cascadeIndex].Item1 != (ulong)m_shadowCascadeUpdateIntervals[cascadeIndex].Item2;
                bool forceUpdate = ShadowCascadeSplitDepths[cascadeIndex] > 1000f && Vector3D.DistanceSquared(m_shadowCascadeUpdatePositions[cascadeIndex], MyRender11.Environment.Matrices.CameraPosition) > Math.Pow(1000, 2);
                //
                if (!forceUpdate && skipCascade && !Settings.Data.UpdateCascadesEveryFrame)
                {
                    continue;
                }
                if (Settings.ShadowCascadeFrozen[cascadeIndex])
                {
                    continue;
                }

                m_shadowCascadeUpdatePositions[cascadeIndex] = MyRender11.Environment.Matrices.CameraPosition;

                MatrixD invView = MyRender11.Environment.Matrices.InvView;
                Vector3D.Transform(m_frustumVerticesWS, ref invView, m_frustumVerticesWS);

                var bSphere = BoundingSphereD.CreateFromPoints(m_frustumVerticesWS);
                if (stabilize)
                {
                    bSphere.Center = bSphere.Center.Round();
                    bSphere.Radius = Math.Ceiling(bSphere.Radius);
                }

                var shadowCameraPosWS = bSphere.Center + m_shadowCascadeLightDirections[cascadeIndex] * (bSphere.Radius + cascadesNearClip);

                var lightView = VRageMath.MatrixD.CreateLookAt(shadowCameraPosWS, shadowCameraPosWS - m_shadowCascadeLightDirections[cascadeIndex], Math.Abs(Vector3.UnitY.Dot(m_shadowCascadeLightDirections[cascadeIndex])) < 0.99f ? Vector3.UnitY : Vector3.UnitX);
                var offset    = bSphere.Radius + cascadesNearClip + backOffset;

                Vector3D vMin = new Vector3D(-bSphere.Radius, -bSphere.Radius, cascadesNearClip);
                Vector3D vMax = new Vector3D(bSphere.Radius, bSphere.Radius, offset + bSphere.Radius);

                var cascadeProjection = MatrixD.CreateOrthographicOffCenter(vMin.X, vMax.X, vMin.Y, vMax.Y, vMax.Z, vMin.Z);
                cascadesMatrices[cascadeIndex] = lightView * cascadeProjection;

                var transformed = Vector3D.Transform(Vector3D.Zero, cascadesMatrices[cascadeIndex]) * shadowmapSize / 2;
                var smOffset    = (transformed.Round() - transformed) * 2 / shadowmapSize;

                // stabilize 1st cascade only
                if (stabilize)
                {
                    cascadeProjection.M41         += smOffset.X;
                    cascadeProjection.M42         += smOffset.Y;
                    cascadesMatrices[cascadeIndex] = lightView * cascadeProjection;
                }

                var inverseCascadeMatrix = MatrixD.Invert(cascadesMatrices[cascadeIndex]);
                var corner0 = Vector3D.Transform(Vector3D.Transform(new Vector3D(-1, -1, 0), inverseCascadeMatrix), globalMatrix);
                var corner1 = Vector3D.Transform(Vector3D.Transform(new Vector3D(1, 1, 1), inverseCascadeMatrix), globalMatrix);

                var diameter = corner1 - corner0;

                var cascadeScale = 1f / diameter;
                ShadowCascadeScales[cascadeIndex] = new Vector4D(cascadeScale, 0);

                var query = new MyShadowmapQuery();
                query.DepthBuffer = m_cascadeShadowmapArray.SubresourceDsv(cascadeIndex);
                query.Viewport    = new MyViewport(shadowmapSize, shadowmapSize);

                m_cascadeInfo[cascadeIndex].WorldCameraOffsetPosition = MyRender11.Environment.Matrices.CameraPosition;
                m_cascadeInfo[cascadeIndex].WorldToProjection         = cascadesMatrices[cascadeIndex];
                // todo: skip translation, recalculate matrix in local space, keep world space matrix only for bounding frustum
                m_cascadeInfo[cascadeIndex].LocalToProjection = Matrix.CreateTranslation(MyRender11.Environment.Matrices.CameraPosition) * cascadesMatrices[cascadeIndex];

                query.ProjectionInfo   = m_cascadeInfo[cascadeIndex];
                query.ProjectionDir    = m_shadowCascadeLightDirections[cascadeIndex];
                query.ProjectionFactor = (float)(shadowmapSize * shadowmapSize / (bSphere.Radius * bSphere.Radius * 4));

                query.QueryType = MyFrustumEnum.ShadowCascade;
                query.Index     = cascadeIndex;

                appendShadowmapQueries.Add(query);
            }

            DebugProcessFrustrums();

            FillConstantBuffer(m_csmConstants);

            MyGpuProfiler.IC_EndBlock();
        }
예제 #6
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();
        }
예제 #7
0
        internal static void Run(IRtvBindable target, ICustomTexture fxaaTarget, IDepthStencil depthStencilCopy)
        {
            if (!HasHighlights)
            {
                return;
            }

            ProfilerShort.Begin("MyHighlight.Run");
            MyGpuProfiler.IC_BeginBlock("MyHighlight.Run");
            // set resolved depth/ stencil
            // render all with proper depth-stencil state
            // blur
            // blend to main target testing with stencil again

            MyHighlightPass.Instance.ViewProjection = MyRender11.Environment.Matrices.ViewProjectionAt0;
            MyHighlightPass.Instance.Viewport       = new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);

            MyHighlightPass.Instance.PerFrame();
            MyHighlightPass.Instance.Begin();

            RC.VertexShader.SetSrvs(0, null, null, null, null, null, null);
            RC.GeometryShader.SetSrvs(0, null, null, null, null, null, null);
            RC.PixelShader.SetSrvs(0, null, null, null, null, null, null);
            RC.ComputeShader.SetSrvs(0, null, null, null, null, null, null);

            int samples = MyRender11.RenderSettings.AntialiasingMode.SamplesCount();
            IBorrowedRtvTexture rgba8_1 = MyManagers.RwTexturesPool.BorrowRtv("MyHighlight.Rgba8_1", Format.R8G8B8A8_UNorm_SRgb, samples);

            RC.ClearRtv(rgba8_1, new SharpDX.Color4(0, 0, 0, 0));
            RC.SetRtv(depthStencilCopy, MyDepthStencilAccess.DepthReadOnly, rgba8_1);

            float maxThickness = 0f;

            foreach (var pair in m_highlights)
            {
                foreach (MyHighlightDesc descriptor in pair.Value)
                {
                    maxThickness = Math.Max(maxThickness, descriptor.Thickness);
                }

                MyActor actor = MyIDTracker <MyActor> .FindByID(pair.Key);

                if (actor == null)
                {
                    MyRenderProxy.Fail("The actor cannot be found for highlight. This bug is outside of the renderer.");
                    continue;
                }
                MyRenderableComponent renderableComponent = actor.GetRenderable();
                MyInstanceComponent   instanceComponent   = actor.GetInstance();
                if (renderableComponent != null)
                {
                    DrawRenderableComponent(actor, renderableComponent, pair.Value);
                }
                else if (instanceComponent != null)
                {
                    DrawInstanceComponent(instanceComponent, pair.Value);
                }
                else
                {
                    // If an actor has been removed without removing outlines, just remove the outlines too
                    m_keysToRemove.Add(pair.Key);
                    MyRenderProxy.Fail("The actor has been removed, but the highligh is still active. This bug is caused by the issue out of the renderer.");
                }
            }

            MyHighlightPass.Instance.End();
            RC.SetBlendState(null);

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

            m_keysToRemove.SetSize(0);

            ISrvBindable initialSourceView = rgba8_1;
            IRtvBindable renderTargetview  = rgba8_1;

            if (maxThickness > 0)
            {
                IBorrowedRtvTexture rgba8_2 = MyManagers.RwTexturesPool.BorrowRtv("MyHighlight.Rgba8_2", Format.R8G8B8A8_UNorm_SRgb);
                MyBlur.Run(renderTargetview, rgba8_2, initialSourceView,
                           (int)Math.Round(maxThickness), MyBlur.MyBlurDensityFunctionType.Exponential, 0.25f,
                           MyDepthStencilStateManager.IgnoreDepthStencil);
                rgba8_2.Release();
            }

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

            BlendHighlight(target, rgba8_1, fxaaTarget, depthStencilCopy);
        }
예제 #8
0
        internal static void Render(MyUnorderedAccessTexture accumTarget, MyUnorderedAccessTexture coverageTarget)
        {
            ProfilerShort.Begin("Billboards");
            MyGpuProfiler.IC_BeginBlock("Billboards");
            if (MyRender11.MultisamplingEnabled)
            {
                MyBillboardRenderer.Render(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), MyScreenDependants.m_resolvedDepth, MyScreenDependants.m_resolvedDepth.Depth);
            }
            else
            {
                MyBillboardRenderer.Render(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), MyGBuffer.Main.DepthStencil, MyGBuffer.Main.DepthStencil.Depth);
            }
            MyGpuProfiler.IC_EndBlock();

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

            ProfilerShort.BeginNextBlock("GPU Particles");
            MyGpuProfiler.IC_BeginBlock("GPU Particles");
            if (MyRender11.DebugOverrides.GPUParticles)
            {
                if (MyRender11.MultisamplingEnabled)
                {
                    MyGPUParticleRenderer.Run(MyScreenDependants.m_resolvedDepth.Depth);
                }
                else
                {
                    MyGPUParticleRenderer.Run(MyGBuffer.Main.DepthStencil.Depth);
                }
            }
            MyGpuProfiler.IC_EndBlock();

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

            ProfilerShort.BeginNextBlock("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();

            ProfilerShort.End();
        }
예제 #9
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:
            {
                AddDebugQueueMessage("Frame render start");

                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();
                }

                AddDebugQueueMessage("Frame render end");
                ProcessDebugOutput();
                break;
            }
            }
        }
예제 #10
0
        internal static void Draw(bool draw = true)
        {
            //if (false) Debug.Assert(MyClipmap.LodLevel.DrewLastFrame);
            //MyClipmap.LodLevel.DrewLastFrame = false;

            try
            {
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                TransferLocalMessages();
                ProcessMessageQueue();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    MyRender11.ClearBackbuffer(MyEnvironment.BackgroundColor);
                    MyImmediateRC.RC.Clear();
                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    /*GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                     * ProcessDebugMessages();
                     * GetRenderProfiler().EndProfilingBlock();*/

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    //MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();

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

                if (m_profilingStarted)
                {
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                }

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

                m_drawQueue.Clear();
                m_debugDrawMessages.Clear();
            }
            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;
            }
        }
        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);
        }
예제 #12
0
        internal static void Render(IRtvTexture gbuffer1Copy)
        {
            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();

            var depthResource = MyGBuffer.Main.ResolvedDepthStencil;

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

            ProfilerShort.BeginNextBlock("Static glass");
            MyGpuProfiler.IC_BeginBlock("Static glass");
            m_glassWithDecals.Clear();
            MyStaticGlassRenderer.Render(HandleGlass);
            MyGpuProfiler.IC_EndBlock();

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

            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, MyGBuffer.Main.GBuffer1);
            }
            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("Glass - Depth Only");
                MyGpuProfiler.IC_BeginBlock("Glass - Depth Only");
                bool glassFound = MyStaticGlassRenderer.RenderGlassDepthOnly(depthResource, gbuffer1Copy, intervalMin, intervalMax);
                MyGpuProfiler.IC_EndBlock();

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

                    ProfilerShort.BeginNextBlock("Render decals - Transparent");
                    MyGpuProfiler.IC_BeginBlock("Render decals - Transparent");
                    MyScreenDecals.Draw(gbuffer1Copy, true, m_glassWithDecals);
                    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();
        }
예제 #13
0
        internal static void Present()
        {
            if (m_swapchain != null)
            {
                GetRenderProfiler().StartProfilingBlock("Screenshot");
                if (m_screenshot.HasValue)
                {
                    if (m_screenshot.Value.SizeMult == VRageMath.Vector2.One)
                    {
                        MyCopyToRT.ClearAlpha(Backbuffer);
                        SaveScreenshotFromResource(Backbuffer);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }
                GetRenderProfiler().EndProfilingBlock();

                try
                {
                    MyManagers.OnFrameEnd();
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                    GetRenderProfiler().StartProfilingBlock("Waiting for present");
                    m_swapchain.Present(m_settings.VSync ? 1 : 0, 0);
                    GetRenderProfiler().EndProfilingBlock();
                    MyGpuProfiler.IC_EndBlock();

                    MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.Present, ref MyStatsUpdater.Timestamps.PreviousPresent);

                    MyManagers.OnUpdate();

                    if (VRage.OpenVRWrapper.MyOpenVR.Static != null)
                    {
                        MyGpuProfiler.IC_BeginBlock("OpenVR.FrameDone");
                        GetRenderProfiler().StartProfilingBlock("OpenVR.FrameDone");

                        /*var handle=MyOpenVR.GetOverlay("menu");
                         * MyOpenVR.SetOverlayTexture(handle, MyRender11.Backbuffer.m_resource.NativePointer);
                         */
                        VRage.OpenVRWrapper.MyOpenVR.FrameDone();
                        GetRenderProfiler().EndProfilingBlock();
                        MyGpuProfiler.IC_EndBlock();
                    }
                }
                catch (SharpDXException e)
                {
                    Log.WriteLine("Graphics device error! Reason:\n" + e.Message);

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

                    Log.WriteLine("Exception stack trace:\n" + e.StackTrace);

                    StringBuilder sb = new StringBuilder();

                    foreach (var column in MyRenderStats.m_stats.Values)
                    {
                        foreach (var stats in column)
                        {
                            sb.Clear();
                            stats.WriteTo(sb);
                            Log.WriteLine(sb.ToString());
                        }
                    }

                    MyStatsUpdater.UpdateStats();
                    MyStatsDisplay.WriteTo(sb);
                    Log.WriteLine(sb.ToString());

                    throw;
                }

                GetRenderProfiler().StartProfilingBlock("GPU profiler");
                MyGpuProfiler.EndFrame();
                MyGpuProfiler.StartFrame();
                GetRenderProfiler().EndProfilingBlock();

                // waiting for change to fullscreen - window migh overlap or some other dxgi excuse to fail :(
                GetRenderProfiler().StartProfilingBlock("TryChangeToFullscreen");
                TryChangeToFullscreen();
                GetRenderProfiler().EndProfilingBlock();
            }
        }
예제 #14
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();
        }
예제 #15
0
 internal static CommandList JoinAndGetCommandList(MyRenderContext rc)
 {
     MyGpuProfiler.Join(rc.ProfilingQueries);
     return(rc.FinishCommandList(false));
 }
예제 #16
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, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    }

                    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);
                }

                // Include the stats
                m_exceptionBuilder.Clear();
                MyStatsUpdater.UpdateStats();
                MyStatsDisplay.WriteTo(m_exceptionBuilder);
                MyRender11.Log.WriteLine(m_exceptionBuilder.ToString());
                MyRender11.Log.Flush();
                MyRender11.Log.DecreaseIndent();
                throw;
            }
        }
        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();
        }
예제 #18
0
        internal static void Render(IRtvTexture gbuffer1Copy)
        {
            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.RenderGBuffer();
            }

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

            var depthResource = MyGBuffer.Main.ResolvedDepthStencil;

            // setup weighted blended OIT targets + blend states
            if (MyRender11.Settings.DrawBillboards)
            {
                ProfilerShort.BeginNextBlock("Billboards");
                MyGpuProfiler.IC_BeginNextBlock("Billboards");
                MyBillboardRenderer.Gather();

                MyBillboardRenderer.RenderAdditveBottom(depthResource.SrvDepth);

                SetupTargets(accumTarget, coverageTarget, true);

                MyBillboardRenderer.RenderStandard(depthResource.SrvDepth);
            }
            else
            {
                SetupTargets(accumTarget, coverageTarget, true);
            }

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

            // Render decals on transparent surfaces in 2 steps: first far, second proximity
            if (MyRender11.Settings.DrawGlass)
            {
                ProfilerShort.BeginNextBlock("Static glass");
                MyGpuProfiler.IC_BeginNextBlock("Static glass");
                m_glassWithDecals.Clear();
                MyStaticGlassRenderer.Render(HandleGlass);

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

                    ProfilerShort.BeginNextBlock("Glass - Depth Only");
                    MyGpuProfiler.IC_BeginNextBlock("Glass - Depth Only");
                    //TODO: This code should properly render glass decals, that they are visible when looking through window on another window
                    // Anyway, it is italian code and it doesnt work. Solve after Beta
                    bool glassFound = MyStaticGlassRenderer.RenderGlassDepthOnly(depthResource, gbuffer1Copy, intervalMin, intervalMax);

                    // if (glassFound)
                    {
                        SetupTargets(accumTarget, coverageTarget, false);

                        ProfilerShort.BeginNextBlock("Render decals - Transparent");
                        MyGpuProfiler.IC_BeginNextBlock("Render decals - Transparent");
                        MyScreenDecals.Draw(gbuffer1Copy, true /*, m_glassWithDecals*/);
                    }

                    intervalMax = intervalMin;
                }

                ProfilerShort.BeginNextBlock("New static glass");
                //MyManagers.GeometryRenderer.RenderGlass();
            }

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

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

            ProfilerShort.BeginNextBlock("Billboards");
            MyGpuProfiler.IC_BeginNextBlock("Billboards");
            if (MyRender11.Settings.DrawBillboards)
            {
                MyBillboardRenderer.RenderAdditveTop(depthResource.SrvDepth);
            }

            RC.SetRtv(null);

            MyGpuProfiler.IC_EndBlock();

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

            ProfilerShort.End();
        }
예제 #19
0
        // Returns the final image and copies it to renderTarget if non-null
        private static IRtvTexture DrawGameScene(IRtvBindable renderTarget, out IBorrowedRtvTexture debugAmbientOcclusion)
        {
            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();
            }

            ProfilerShort.Begin("MyLights.Update");
            MyLights.Update();
            ProfilerShort.End();

            ProfilerShort.Begin("DynamicGeometryRenderer");
            MyCullQuery cullQuery = m_dynamicGeometryRenderer.PrepareCullQuery(true); // it is used to share rendering settings between the old and the new pipeline

            ProfilerShort.End();

            MyGpuProfiler.IC_BeginBlock("NewGeometryRenderer");
            ProfilerShort.Begin("NewGeometryRenderer");
            IGeometrySrvStrategy geometrySrvStrategy = MyManagers.GeometrySrvResolver.GetGeometrySrvStrategy();

            if (MyDebugGeometryStage2.EnableNewGeometryPipeline)
            {
                MyManagers.GeometryRenderer.Render(cullQuery, geometrySrvStrategy);
            }
            ProfilerShort.End();
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("MyGeometryRenderer.Render");
            Debug.Assert(m_commandLists.Count == 0, "Not all command lists executed last frame!");
            ProfilerShort.Begin("DynamicGeometryRenderer");
            m_dynamicGeometryRenderer.Render(m_commandLists);
            ProfilerShort.End();    // End function block
            if (MyScene.SeparateGeometry)
            {
                ProfilerShort.Begin("StaticGeometryRenderer");
                m_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();

            IBorrowedRtvTexture gbuffer1Copy = MyGBuffer.Main.GetGbuffer1CopyRtv();

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

            IBorrowedDepthStencilTexture depthStencilCopy = null; // Highlights need the depth state before foliage
            if (MyHighlight.HasHighlights)
            {
                depthStencilCopy = MyGBuffer.Main.GetDepthStencilCopyRtv();
            }

            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();

            IBorrowedRtvTexture ambientOcclusionRtv = MyManagers.RwTexturesPool.BorrowRtv("MyScreenDependants.AmbientOcclusion",
                                                                                          ResolutionI.X, ResolutionI.Y, SharpDX.DXGI.Format.R8_UNorm);
            debugAmbientOcclusion = ambientOcclusionRtv; // Pass the texture to the outside

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

                MyGBuffer.Main.ResolveMultisample();

                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 && Settings.User.AmbientOcclusionEnabled &&
                    m_debugOverrides.Postprocessing && m_debugOverrides.SSAO)
                {
                    ProfilerShort.BeginNextBlock("SSAO");
                    MyGpuProfiler.IC_BeginBlockAlways("SSAO");
                    MySSAO.Run(ambientOcclusionRtv, MyGBuffer.Main);

                    if (MySSAO.Params.UseBlur)
                    {
                        IBorrowedRtvTexture ambientOcclusionHelper = MyManagers.RwTexturesPool.BorrowRtv("MyScreenDependants.AmbientOcclusionHelper",
                                                                                                         ResolutionI.X, ResolutionI.Y, SharpDX.DXGI.Format.R8_UNorm);

                        MyBlur.Run(ambientOcclusionRtv, ambientOcclusionHelper, ambientOcclusionRtv, clearColor: Color4.White);
                        ambientOcclusionHelper.Release();
                    }
                    MyGpuProfiler.IC_EndBlockAlways();
                }
                else if (MyHBAO.Params.Enabled && Settings.User.AmbientOcclusionEnabled &&
                         m_debugOverrides.Postprocessing && m_debugOverrides.SSAO)
                {
                    ProfilerShort.BeginNextBlock("HBAO");
                    MyGpuProfiler.IC_BeginBlock("HBAO");
                    MyHBAO.Run(ambientOcclusionRtv, MyGBuffer.Main);
                    MyGpuProfiler.IC_EndBlock();
                }
                else
                {
                    MyRender11.RC.ClearRtv(ambientOcclusionRtv, Color4.White);
                }

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

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

            ProfilerShort.BeginNextBlock("Occlusion Queries");
            MyGpuProfiler.IC_BeginBlock("Occlusion Queries");
            MyOcclusionQueryRenderer.Render(RC, MyGBuffer.Main.ResolvedDepthStencil, MyGBuffer.Main.LBuffer);
            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(gbuffer1Copy);
            }
            MyGpuProfiler.IC_EndBlockAlways();

            gbuffer1Copy.Release();

            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, MyGBuffer.Main.ResolvedDepthStencil.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 fxaaTarget = null;
            bool fxaa = MyRender11.FxaaEnabled;
            if (fxaa)
            {
                fxaaTarget = MyManagers.RwTexturesPool.BorrowCustom("MyRender11.FXAA.Rgb8");
                MyGpuProfiler.IC_BeginBlock("FXAA");
                MyFXAA.Run(fxaaTarget.Linear, tonemapped);
                MyGpuProfiler.IC_EndBlock();

                renderedImage = fxaaTarget.SRgb;
            }
            else
            {
                renderedImage = tonemapped;
            }


            ProfilerShort.Begin("MyHighlight.Run");
            MyHighlight.Run(renderedImage, fxaaTarget, depthStencilCopy);
            ProfilerShort.End();

            if (depthStencilCopy != null)
            {
                depthStencilCopy.Release();
            }

            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 (fxaaTarget != null)
            {
                fxaaTarget.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);
        }
예제 #20
0
        /// <param name="clearColor">Color used to clear render targets. Defaults to black</param>
        internal static void Run(IRtvBindable renderTarget, IRtvTexture intermediate, ISrvBindable initialResourceView,
                                 int maxOffset = 5, MyBlurDensityFunctionType densityFunctionType = MyBlurDensityFunctionType.Gaussian, float WeightParameter = 1.5f,
                                 IDepthStencilState depthStencilState = null, int stencilRef      = 0x0, Color4 clearColor = default(Color4),
                                 float depthDiscardThreshold          = 0.0f, MyViewport?viewport = null)
        {
            ProfilerShort.Begin("MyBlur.Run");
            MyGpuProfiler.IC_BeginBlock("MyBlur.Run");
            Debug.Assert(initialResourceView != null);
            Debug.Assert(intermediate != null);
            Debug.Assert(renderTarget != null);

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

            RC.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
            // NOTE: DepthStencilState is not used here because the resulted target
            // would not be usable to perform vertical pass. DepthStencil is stil
            // bindinded as SRV since it is sampled in the shader
            RC.ClearRtv(intermediate, clearColor);
            RC.SetRtv(intermediate);
            RC.PixelShader.SetSrv(0, MyGBuffer.Main.DepthStencil.SrvDepth);
            RC.PixelShader.SetSrv(4, MyGBuffer.Main.DepthStencil.SrvStencil);
            RC.SetDepthStencilState(MyDepthStencilStateManager.IgnoreDepthStencil);
            RC.PixelShader.SetSrv(5, initialResourceView);
            RC.PixelShader.Set(m_blurShaders[shaderKey].Item1);
            MyScreenPass.DrawFullscreenQuad(viewport);
            RC.PixelShader.SetSrv(5, null);

            // Vertical pass
            RC.ClearRtv(renderTarget, clearColor);
            if (depthStencilState == null)
            {
                RC.SetRtv(renderTarget);
            }
            else
            {
                RC.SetDepthStencilState(depthStencilState, stencilRef);
                RC.SetRtv(MyGBuffer.Main.DepthStencil, MyDepthStencilAccess.ReadOnly, renderTarget);
            }

            RC.PixelShader.SetSrv(5, intermediate);
            RC.PixelShader.Set(m_blurShaders[shaderKey].Item2);
            MyScreenPass.DrawFullscreenQuad(viewport);

            RC.PixelShader.SetSrv(0, null);
            RC.PixelShader.SetSrv(4, null);
            RC.PixelShader.SetSrv(5, null);
            RC.SetRtv(null);

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
        internal void GatherArray(IUavTexture postprocessTarget, ISrvBindable cascadeArray, MyProjectionInfo[] cascadeInfo, ConstantsBufferId cascadeConstantBuffer)
        {
            MyShadowsQuality shadowsQuality = MyRender11.RenderSettings.ShadowQuality.GetShadowsQuality();

            if (!MyRender11.Settings.EnableShadows || !MyRender11.DebugOverrides.Shadows || shadowsQuality == MyShadowsQuality.DISABLED)
            {
                RC.ClearUav(postprocessTarget, new RawInt4());
                return;
            }

            MarkCascadesInStencil(cascadeInfo);

            MyGpuProfiler.IC_BeginBlock("Cascades postprocess");

            if (shadowsQuality == MyShadowsQuality.LOW)
            {
                RC.ComputeShader.Set(m_gatherCS_LD);
            }
            else if (shadowsQuality == MyShadowsQuality.MEDIUM)
            {
                RC.ComputeShader.Set(m_gatherCS_MD);
            }
            else if (shadowsQuality == MyShadowsQuality.HIGH)
            {
                RC.ComputeShader.Set(m_gatherCS_HD);
            }

            RC.ComputeShader.SetUav(0, postprocessTarget);

            RC.ComputeShader.SetSrv(0, MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth.SrvDepth : MyGBuffer.Main.DepthStencil.SrvDepth);
            RC.ComputeShader.SetSrv(1, MyGBuffer.Main.DepthStencil.SrvStencil);
            RC.ComputeShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MySamplerStateManager.Shadowmap);
            if (!MyStereoRender.Enable)
            {
                RC.ComputeShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            }
            else
            {
                MyStereoRender.CSBindRawCB_FrameConstants(RC);
            }
            //RC.ComputeShader.SetConstantBuffer(4, MyManagers.Shadows.GetCsmConstantBufferOldOne());
            RC.ComputeShader.SetConstantBuffer(4, cascadeConstantBuffer);
            RC.ComputeShader.SetSrv(MyCommon.CASCADES_SM_SLOT, cascadeArray);
            //RC.ComputeShader.SetSrv(MyCommon.CASCADES_SM_SLOT, MyManagers.Shadow.GetCsmForGbuffer());

            Vector2I threadGroups = GetThreadGroupCount();

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

            RC.ComputeShader.SetUav(0, null);
            RC.ComputeShader.SetSrv(0, null);
            RC.ComputeShader.SetSrv(1, null);

            if (shadowsQuality == MyShadowsQuality.HIGH && MyShadowCascades.Settings.Data.EnableShadowBlur)
            {
                IBorrowedUavTexture helper = MyManagers.RwTexturesPool.BorrowUav("MyShadowCascadesPostProcess.Helper", Format.R8_UNorm);
                MyBlur.Run(postprocessTarget, helper, postprocessTarget,
                           depthStencilState: MyDepthStencilStateManager.IgnoreDepthStencil,
                           depthDiscardThreshold: 0.2f, clearColor: Color4.White);
                helper.Release();
            }

            MyGpuProfiler.IC_EndBlock();
        }
        // Returns the final image and copies it to renderTarget if non-null
        private static MyBindableResource DrawGameScene(MyBindableResource renderTarget)
        {
            ProfilerShort.Begin("DrawGameScene");

            PrepareGameScene();

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

            Debug.Assert(m_commandLists.Count == 0, "Not all command lists executed last frame!");
            DynamicGeometryRenderer.Render(m_commandLists, true);
            if (MyScene.SeparateGeometry)
            {
                StaticGeometryRenderer.Render(m_commandLists, false);
            }

            SendGlobalOutputMessages();
            ExecuteCommandLists(m_commandLists);
            MyEnvironmentProbe.FinalizeEnvProbes();

            // 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();
            }

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

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

            ProfilerShort.BeginNextBlock("MySceneMaterials.MoveToGPU");
            MySceneMaterials.MoveToGPU();

            ProfilerShort.BeginNextBlock("Postprocessing");
            MyGpuProfiler.IC_BeginBlock("Postprocessing");
            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);
            }

            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_BeginBlock("SSAO");
            if (Postprocess.EnableSsao)
            {
                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();


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

            ProfilerShort.BeginNextBlock("Billboards");
            MyGpuProfiler.IC_BeginBlock("Billboards");
            if (MyRender11.MultisamplingEnabled)
            {
                MyBillboardRenderer.Render(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), MyScreenDependants.m_resolvedDepth, MyScreenDependants.m_resolvedDepth.Depth);
            }
            else
            {
                MyBillboardRenderer.Render(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer), MyGBuffer.Main.DepthStencil, MyGBuffer.Main.DepthStencil.Depth);
            }

            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("Atmosphere");
            MyGpuProfiler.IC_BeginBlock("Atmosphere");
            MyAtmosphereRenderer.Render();
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.BeginNextBlock("Clouds");
            MyGpuProfiler.IC_BeginBlock("Clouds");
            MyCloudRenderer.Render();
            MyGpuProfiler.IC_EndBlock();

            ProfilerShort.End();

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

            if (MyRender11.MultisamplingEnabled)
            {
                MyRenderContext.Immediate.DeviceContext.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)
            {
                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");
            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, Postprocess.EnableTonemapping);
            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;
            }
            ProfilerShort.Begin("Outline");
            if (MyOutline.AnyOutline())
            {
                MyOutline.Run();

                MyGpuProfiler.IC_BeginBlock("Outline Blending");
                ProfilerShort.Begin("Outline Blending");
                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,
                        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)
            {
                MyHdrDebugTools.DisplayHistogram((renderTarget as IRenderTargetBindable).RTV, (avgLum as IShaderResourceBindable).SRV);
            }

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
            return(renderedImage);
        }
        private unsafe void MarkCascadesInStencil(MyProjectionInfo[] cascadeInfo)
        {
            MyGpuProfiler.IC_BeginBlock("MarkCascadesInStencil");

            //RC.SetRS(MyRasterizerState.CullCW);

            RC.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            RC.SetVertexBuffer(0, m_cascadesBoundingsVertices.Buffer, m_cascadesBoundingsVertices.Stride);
            RC.SetIndexBuffer(m_cubeIB.Buffer, m_cubeIB.Format);
            RC.SetInputLayout(m_inputLayout);
            RC.SetViewport(0, 0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);
            if (!MyStereoRender.Enable)
            {
                RC.AllShaderStages.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            }
            else
            {
                MyStereoRender.BindRawCB_FrameConstants(RC);
            }
            RC.SetRtv(MyGBuffer.Main.DepthStencil, MyDepthStencilAccess.DepthReadOnly);
            RC.VertexShader.Set(m_markVS);
            RC.PixelShader.Set(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 < MyShadowCascades.Settings.NewData.CascadesCount; ++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();

            if (MyStereoRender.Enable)
            {
                MyStereoRender.SetViewport(RC);
            }

            for (int cascadeIndex = 0; cascadeIndex < MyShadowCascades.Settings.NewData.CascadesCount; ++cascadeIndex)
            {
                RC.SetDepthStencilState(MyDepthStencilStateManager.MarkIfInsideCascade[cascadeIndex], 0xf - cascadeIndex);
                // mark ith bit on depth near

                RC.DrawIndexed(36, 0, 8 * cascadeIndex);
            }

            RC.SetRtv(null);

            RC.SetDepthStencilState(MyDepthStencilStateManager.DefaultDepthState);
            RC.SetRasterizerState(null);

            MyGpuProfiler.IC_EndBlock();
        }
예제 #24
0
        internal static IBorrowedRtvTexture 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 = MyRender11.Environment.Matrices.ViewProjectionAt0;
            MyOutlinePass.Instance.Viewport       = new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);

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

            RC.VertexShader.SetSrvs(0, null, null, null, null, null, null);
            RC.GeometryShader.SetSrvs(0, null, null, null, null, null, null);
            RC.PixelShader.SetSrvs(0, null, null, null, null, null, null);
            RC.ComputeShader.SetSrvs(0, null, null, null, null, null, null);

            int samples = MyRender11.RenderSettings.AntialiasingMode.SamplesCount();
            IBorrowedRtvTexture rgba8_1 = MyManagers.RwTexturesPool.BorrowRtv("MyOutline.Rgba8_1", Format.R8G8B8A8_UNorm_SRgb, samples);

            RC.ClearRtv(rgba8_1, new SharpDX.Color4(0, 0, 0, 0));
            RC.SetRtv(MyGBuffer.Main.DepthStencil, MyDepthStencilAccess.ReadWrite, rgba8_1);

            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.SetBlendState(null);

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

            m_keysToRemove.SetSize(0);

            ISrvBindable initialSourceView = rgba8_1;
            IRtvBindable renderTargetview  = rgba8_1;

            if (maxThickness > 0)
            {
                IBorrowedRtvTexture rgba8_2 = MyManagers.RwTexturesPool.BorrowRtv("MyOutline.Rgba8_2", Format.R8G8B8A8_UNorm_SRgb);
                MyBlur.Run(renderTargetview, rgba8_2, initialSourceView,
                           (int)Math.Round(maxThickness), MyBlur.MyBlurDensityFunctionType.Exponential, 0.25f,
                           MyDepthStencilStateManager.TestSkipGrassStencil, MyFoliageRenderingPass.GrassStencilMask);
                rgba8_2.Release();
            }

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

            return(rgba8_1);
        }
        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 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);
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            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.ShowLuminanceHistogram)
            {
                var src = MyGBuffer.Main.Get(MyGbufferSlot.LBuffer) as MyRenderTarget;
                MyLuminanceDebugTools.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);
            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;
            }

            m_finalImage = renderedImage;

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

            if (MyRender11.Settings.ShowLuminanceHistogram)
            {
                MyLuminanceDebugTools.DisplayHistogram(Backbuffer.m_RTV);
            }

            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();
        }
        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();
            }
        }
예제 #27
0
        internal static void Render()
        {
            MyLights.Update();

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

            RC.DeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            if (!MyStereoRender.Enable)
            {
                RC.CSSetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            }
            else
            {
                MyStereoRender.CSBindRawCB_FrameConstants(RC);
            }

            RC.BindGBufferForRead(0, MyGBuffer.Main);
            RC.BindRawSRV(MyCommon.MATERIAL_BUFFER_SLOT, MySceneMaterials.m_buffer);
            RC.SetBS(MyRender11.BlendAdditive);
            if (!MyStereoRender.Enable)
            {
                RC.SetDS(MyDepthStencilState.IgnoreDepthStencil);
            }
            else
            {
                RC.SetDS(MyDepthStencilState.StereoIgnoreDepthStencil);
            }
            RC.DeviceContext.PixelShader.SetSamplers(0, SamplerStates.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();

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

            // Because of BindGBufferForRead:
            RC.BindRawSRV(0, null);
            RC.BindRawSRV(1, null);
            RC.BindRawSRV(2, null);
            RC.BindRawSRV(3, null);
            RC.BindRawSRV(4, null);
            RC.CSBindRawSRV(0, null);
            RC.CSBindRawSRV(1, null);
            RC.CSBindRawSRV(2, null);
            RC.CSBindRawSRV(3, null);
            RC.CSBindRawSRV(4, null);
            RC.SetBS(null);
        }