// Main entry point for our scriptable render loop
    public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras)
    {
        bool stereoEnabled = XRSettings.isDeviceActive;

        foreach (Camera camera in cameras)
        {
            // Culling
            ScriptableCullingParameters cullingParams;

            // Stereo-aware culling parameters are configured to perform a single cull for both eyes
            if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams))
            {
                continue;
            }
            CullResults cull = new CullResults();
            CullResults.Cull(ref cullingParams, context, ref cull);

            // Setup camera for rendering (sets render target, view/projection matrices and other
            // per-camera built-in shader variables).
            // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets
            context.SetupCameraProperties(camera, stereoEnabled);

            // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine
            if (stereoEnabled)
            {
                context.StartMultiEye(camera);
            }

            // clear depth buffer
            CommandBuffer cmd = new CommandBuffer();
            cmd.ClearRenderTarget(true, false, Color.black);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            // Setup global lighting shader variables
            SetupLightShaderVariables(cull.visibleLights, context);

            // Draw skybox
            context.DrawSkybox(camera);

            // Setup DrawSettings and FilterSettings
            ShaderPassName          passName       = new ShaderPassName("BasicPass");
            DrawRendererSettings    drawSettings   = new DrawRendererSettings(camera, passName);
            FilterRenderersSettings filterSettings = new FilterRenderersSettings(true);

            //*************************************************************
            // Block
            RenderStateBlock rsb = new RenderStateBlock(RenderStateMask.Depth | RenderStateMask.Blend | RenderStateMask.Raster | RenderStateMask.Stencil);

            DepthState ds = rsb.depthState;//
            ds.writeEnabled    = true;
            ds.compareFunction = CompareFunction.LessEqual;
            rsb.depthState     = ds;                     //

            BlendState             bs  = rsb.blendState; //
            RenderTargetBlendState rs0 = bs.blendState0; //
            bs.alphaToMask                = false;
            rs0.sourceColorBlendMode      = BlendMode.SrcAlpha;
            rs0.destinationColorBlendMode = BlendMode.One;
            rs0.colorBlendOperation       = BlendOp.Add;
            rs0.sourceAlphaBlendMode      = BlendMode.Zero;
            rs0.destinationAlphaBlendMode = BlendMode.One;
            rs0.alphaBlendOperation       = BlendOp.Add;
            rs0.writeMask  = ColorWriteMask.All;
            bs.blendState0 = rs0;             //
            rsb.blendState = bs;              //

            RasterState rs = rsb.rasterState; //
            rs.cullingMode  = CullMode.Off;
            rs.depthClip    = false;
            rs.offsetFactor = 0;
            rs.offsetUnits  = 0;
            rsb.rasterState = rs;//


            StencilState ss = rsb.stencilState;//
            rsb.stencilReference    = 0;
            ss.compareFunction      = CompareFunction.Disabled;
            ss.compareFunctionBack  = CompareFunction.Disabled;
            ss.compareFunctionFront = CompareFunction.Disabled;
            ss.failOperation        = StencilOp.Keep;
            ss.failOperationBack    = StencilOp.Keep;
            ss.failOperationFront   = StencilOp.Keep;
            ss.passOperation        = StencilOp.Keep;
            ss.passOperationBack    = StencilOp.Keep;
            ss.passOperationFront   = StencilOp.Keep;
            ss.zFailOperation       = StencilOp.Keep;
            ss.zFailOperationBack   = StencilOp.Keep;
            ss.zFailOperationFront  = StencilOp.Keep;
            ss.readMask             = 255;
            ss.writeMask            = 255;
            ss.enabled       = true;
            rsb.stencilState = ss;//

            //**************************************************************
            //mapping

            RenderStateBlock rsb_opaque = new RenderStateBlock(RenderStateMask.Raster | RenderStateMask.Stencil);
            rsb_opaque.rasterState      = rsb.rasterState;
            rsb_opaque.stencilState     = rsb.stencilState;
            rsb_opaque.stencilReference = rsb.stencilReference;

            RenderStateBlock rsb_trans = new RenderStateBlock(RenderStateMask.Blend);
            rsb_trans.blendState = rsb.blendState;

            RenderStateBlock rsb_over = new RenderStateBlock(RenderStateMask.Raster | RenderStateMask.Depth | RenderStateMask.Stencil);
            rsb_over.depthState       = rsb.depthState;
            rsb_over.rasterState      = rsb.rasterState;
            rsb_over.stencilState     = rsb.stencilState;
            rsb_over.stencilReference = rsb.stencilReference;

            List <RenderStateMapping> rsm = new List <RenderStateMapping>
            {
                new RenderStateMapping("Opaque", rsb_opaque),
                new RenderStateMapping("Transparent", rsb_trans),
                new RenderStateMapping("Overlay", rsb_over)
            };

            //**************************************************************

            // Draw opaque objects using BasicPass shader pass
            filterSettings.layerMask        = LayerMask.GetMask("Default");
            drawSettings.sorting.flags      = SortFlags.CommonOpaque;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

            // WITH RENDERSTATEBLOCK OPAQUE
            filterSettings.layerMask        = LayerMask.GetMask("TransparentFX");
            drawSettings.sorting.flags      = SortFlags.CommonOpaque;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsb);

            // WITH RENDERSTATEMAPPING OPAQUE
            filterSettings.layerMask        = LayerMask.GetMask("Ignore Raycast");
            drawSettings.sorting.flags      = SortFlags.CommonOpaque;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsm);

            //**************************************************************

            // Draw transparent objects using BasicPass shader pass
            filterSettings.layerMask        = LayerMask.GetMask("Default");
            drawSettings.sorting.flags      = SortFlags.CommonTransparent;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

            // WITH RENDERSTATEBLOCK TRANSPARENT
            filterSettings.layerMask        = LayerMask.GetMask("TransparentFX");
            drawSettings.sorting.flags      = SortFlags.CommonTransparent;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsb);

            // WITH RENDERSTATEMAPPING TRANSPARENT
            filterSettings.layerMask        = LayerMask.GetMask("Ignore Raycast");
            drawSettings.sorting.flags      = SortFlags.CommonTransparent;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsm);

            //**************************************************************

            if (stereoEnabled)
            {
                context.StopMultiEye(camera);
                // StereoEndRender will reset state on the camera to pre-Stereo settings,
                // and invoke XR based events/callbacks.
                context.StereoEndRender(camera);
            }

            context.Submit();
        }
    }
Beispiel #2
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(context, cameras);

        foreach (Camera camera in cameras)
        {
            BeginCameraRendering(context, camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //Setup DrawSettings and FilterSettings
            SortingSettings   sortingSettings = new SortingSettings(camera);
            DrawingSettings   drawSettings    = new DrawingSettings(m_PassName, sortingSettings);
            FilteringSettings filterSettings  = new FilteringSettings(RenderQueueRange.all);

            //Skybox
            if (drawSkyBox)
            {
                context.DrawSkybox(camera);
            }

            //Opaque objects
            sortingSettings.criteria        = SortingCriteria.CommonOpaque;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Error Opaque
            //DrawErrorShader(context,sortingSettings,cull,filterSettings);

            //Transparent objects
            sortingSettings.criteria        = SortingCriteria.CommonTransparent;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Error Opaque+Transparent
            DrawErrorShader(context, sortingSettings, cull, filterSettings);

            context.Submit();

            EndCameraRendering(context, camera);
        }

        EndFrameRendering(context, cameras);
    }
Beispiel #3
0
    private void Render(ScriptableRenderContext context, Camera camera)
    {
        /* Attempt to cull the current camera.
         * If it fails to cull, don't render anything to this camera.
         */
        ScriptableCullingParameters cullingParameters;

        if (!camera.TryGetCullingParameters(out cullingParameters))
        {
            return;
        }

#if UNITY_EDITOR
        // For rendering UI in the scene view
        if (camera.cameraType == CameraType.SceneView)
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif

        cullingResults = context.Cull(ref cullingParameters);


        // Setup properties for a specific camera.
        context.SetupCameraProperties(camera);


        /* Creates a graphics command buffer.
         * This particular one is told to clear the depth buffer, not the colour, and to set the clear colour to transparent.
         * It finally releases the memory it has, as the commands have been sent to the internal buffer of the rendering context.
         */
        //var buffer = new CommandBuffer();
        //buffer.ClearRenderTarget(true, false, Color.clear);
        //context.ExecuteCommandBuffer(buffer);
        //buffer.Release();

        /* Creates a graphics command buffer.
         * This particular one is told to clear the depth buffer, not the colour, and to set the clear colour to transparent.
         * It finally releases the memory it has, as the commands have been sent to the internal buffer of the rendering context.
         */
        CameraClearFlags clearFlags = camera.clearFlags;
        buffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor);
        buffer.BeginSample("Render Camera");    // Start nested grouping for command buffer (For Frame Debugger)
        context.ExecuteCommandBuffer(buffer);
        //buffer.Release();
        buffer.Clear();


        // Once culling and clearing have been completed we can draw the appropriate renderers.
        var drawSettings   = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), new SortingSettings(camera));
        var filterSettings = FilteringSettings.defaultValue;
        // Only render the opaque objects first. To avoid transparent objects being drawn behind the skybox.
        filterSettings.renderQueueRange = RenderQueueRange.opaque;
        context.DrawRenderers(cullingResults, ref drawSettings, ref filterSettings);


        // Check for any problems drawing objects with custom pipeline.
        DrawDefaultPipeline(context, camera);


        // Draws a skybox to the specified camera.
        context.DrawSkybox(camera);


        // After all the opaque objects have been drawn, draw the transparent objects.
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(cullingResults, ref drawSettings, ref filterSettings);

        // End nested grouping for command buffer (For Frame Debugger)
        buffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(buffer);
        buffer.Clear();


        // Commands sent to the rendering context are just buffered. They are only excuted once we submit them.
        context.Submit();
    }
 /// <inheritdoc/>
 public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
 {
     context.DrawSkybox(renderingData.cameraData.camera);
 }
Beispiel #5
0
    void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

        if (!CullResults.GetCullingParameters(camera, out cullingParameters))
        {
            return;
        }

        cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane);

#if UNITY_EDITOR
        if (camera.cameraType == CameraType.SceneView)
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif
        CullResults.Cull(ref cullingParameters, context, ref cull);

        if (cull.visibleLights.Count > 0)
        {
            ConfigureLights();
            if (mainLightExist)
            {
                RendercascadeShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(cascadeShadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(cascadeShadowsSoftKeyword);
            }

            if (shadowTileCount > 0)
            {
                RenderShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
                cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
            }
        }
        else
        {
            cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero);
            cameraBuffer.DisableShaderKeyword(cascadeShadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(cascadeShadowsSoftKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
        }


        context.SetupCameraProperties(camera);

        var myPipelineCamera = camera.GetComponent <MyPipelineCamera>();
        MyPostprocessingStack activeStack = myPipelineCamera ?
                                            myPipelineCamera.PostProcessingStack : defaultStack;

        bool scaledRendering = (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game;
        int  renderWidth     = camera.pixelWidth;
        int  renderHeight    = camera.pixelHeight;
        if (scaledRendering)
        {
            renderWidth  = (int)(renderWidth * renderScale);
            renderHeight = (int)(renderHeight * renderScale);
        }

        int  renderSamples      = camera.allowMSAA ? msaaSamples : 1;
        bool renderToTexture    = scaledRendering || renderSamples > 1 || activeStack;
        bool needsDepth         = activeStack && activeStack.NeedsDepth;
        bool needsDirectDepth   = needsDepth && renderSamples == 1;
        bool needsDepthOnlyPass = needsDepth && renderSamples > 1;

        RenderTextureFormat format = allowHDR && camera.allowHDR ?
                                     RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;

        if (renderToTexture)
        {
            cameraBuffer.GetTemporaryRT(cameraColorTextureID, renderWidth, renderHeight, needsDirectDepth ? 0 : 24, FilterMode.Bilinear,
                                        format, RenderTextureReadWrite.Default, renderSamples);
            if (needsDepth)
            {
                cameraBuffer.GetTemporaryRT(cameraDepthTextureID, renderWidth, renderHeight, 24, FilterMode.Point, RenderTextureFormat.Depth,
                                            RenderTextureReadWrite.Linear, 1);
            }
            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
                                             cameraDepthTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
            }
            else
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
            }
        }

        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget(
            (clearFlags & CameraClearFlags.Depth) != 0,
            (clearFlags & CameraClearFlags.Color) != 0,
            camera.backgroundColor
            //new Color(0, 0, 0, 0)
            );
        cameraBuffer.BeginSample("Render Camera");
        cameraBuffer.SetGlobalVectorArray(visibleLightColorID, visibleLightColors);
        cameraBuffer.SetGlobalVectorArray(visibleLightDirectionOrPositionID, visibleLightDirectionsOrPositions);
        cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsID, visibleLightAttenuations);
        cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionID, visibleLightSpotDirections);
        cameraBuffer.SetGlobalVectorArray(visibleLightOcclusionMasksID, visibleLightOcclusionMasks);
        globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y;
        cameraBuffer.SetGlobalVector(globalShadowDataID, globalShadowData);
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        ShaderPassName passName = new ShaderPassName("SRPDefaultUnlit");

        var drawSettings = new DrawRendererSettings(camera, passName)
        {
            flags = drawFlags
        };

        if (cull.visibleLights.Count > 0)
        {
            drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8;
        }

        drawSettings.rendererConfiguration |=
            RendererConfiguration.PerObjectReflectionProbes |
            RendererConfiguration.PerObjectLightmaps |
            RendererConfiguration.PerObjectLightProbe |
            RendererConfiguration.PerObjectLightProbeProxyVolume |
            RendererConfiguration.PerObjectShadowMask |
            RendererConfiguration.PerObjectOcclusionProbe |
            RendererConfiguration.PerObjectOcclusionProbeProxyVolume;

        // drawSettings.flags = drawFlags;
        drawSettings.sorting.flags = SortFlags.CommonOpaque;

        var filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.opaque
        };
        context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

        context.DrawSkybox(camera);

        if (activeStack)
        {
            if (needsDepthOnlyPass)
            {
                var depthOnlyDrawSettings = new DrawRendererSettings(camera, new ShaderPassName("DepthOnly"))
                {
                    flags = drawFlags
                };
                depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque;
                cameraBuffer.SetRenderTarget(cameraDepthTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
                cameraBuffer.ClearRenderTarget(true, false, Color.clear);
                context.ExecuteCommandBuffer(cameraBuffer);
                cameraBuffer.Clear();
                context.DrawRenderers(cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings);
            }
            activeStack.RenderAfterOpaque(postProcessingBuffer, cameraColorTextureID, cameraDepthTextureID, renderWidth, renderHeight, renderSamples, format);
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                                             cameraDepthTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
            }
            else
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
            }
            context.ExecuteCommandBuffer(cameraBuffer);
            cameraBuffer.Clear();
        }

        drawSettings.sorting.flags      = SortFlags.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

        DrawDefaultPipeline(context, camera);

        if (renderToTexture)
        {
            if (activeStack)
            {
                activeStack.RenderAfterTransparent(postProcessingBuffer, cameraColorTextureID, cameraDepthTextureID, renderWidth, renderHeight, renderSamples, format);
                context.ExecuteCommandBuffer(postProcessingBuffer);
                postProcessingBuffer.Clear();
            }
            else
            {
                cameraBuffer.Blit(cameraColorTextureID, BuiltinRenderTextureType.CameraTarget);
            }
            cameraBuffer.ReleaseTemporaryRT(cameraColorTextureID);
            if (needsDepth)
            {
                cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureID);
            }
        }

        cameraBuffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        context.Submit();

        if (shadowMap)
        {
            RenderTexture.ReleaseTemporary(shadowMap);
            shadowMap = null;
        }

        if (cascadeShadowMap)
        {
            RenderTexture.ReleaseTemporary(cascadeShadowMap);
            cascadeShadowMap = null;
        }
    }
Beispiel #6
0
 public override void Render(ScriptableRenderContext context, Camera camera, ref CullingResults cullingResults)
 {
     context.DrawSkybox(camera);
 }
Beispiel #7
0
        public override void Render(ScriptableRenderContext context, Camera[] cameras)
        {
            base.Render(context, cameras);

            bool stereoEnabled = XRSettings.isDeviceActive;

            foreach (Camera camera in cameras)
            {
                m_CurrCamera = camera;

                ScriptableCullingParameters cullingParameters;
                if (!CullResults.GetCullingParameters(m_CurrCamera, stereoEnabled, out cullingParameters))
                {
                    continue;
                }

                cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance, m_CurrCamera.farClipPlane);
                CullResults.Cull(ref cullingParameters, context, ref m_CullResults);

                VisibleLight[] visibleLights = m_CullResults.visibleLights.ToArray();

                LightData lightData;
                InitializeLightData(visibleLights, out lightData);

                // Render Shadow Map
                if (lightData.shadowLightIndex > -1)
                {
                    lightData.shadowsRendered = RenderShadows(ref m_CullResults, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, ref context);
                }

                // Setup camera matrices and RT
                context.SetupCameraProperties(m_CurrCamera, stereoEnabled);

                // Setup light and shadow shader constants
                SetupShaderLightConstants(visibleLights, ref lightData, ref m_CullResults, ref context);
                if (lightData.shadowsRendered)
                {
                    SetupShadowShaderConstants(ref context, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, m_ShadowCasterCascadesCount);
                }
                SetShaderKeywords(ref lightData, ref context);

                RendererConfiguration configuration = RendererConfiguration.PerObjectReflectionProbes;
                if (m_Asset.EnableLightmap)
                {
                    configuration |= RendererConfiguration.PerObjectLightmaps;
                }

                if (m_Asset.EnableAmbientProbe)
                {
                    configuration |= RendererConfiguration.PerObjectLightProbe;
                }

                if (!lightData.isSingleDirectionalLight)
                {
                    configuration |= RendererConfiguration.PerObjectLightIndices8;
                }


                PostProcessLayer postProcessLayer   = GetCurrCameraPostProcessLayer();
                bool             postProcessEnabled = postProcessLayer != null && postProcessLayer.enabled;
                m_RenderToIntermediateTarget = postProcessEnabled || GetRenderToIntermediateTarget();

                BeginForwardRendering(ref context, stereoEnabled);

                var litDrawSettings = new DrawRendererSettings(m_CurrCamera, m_LitPassName);
                litDrawSettings.sorting.flags         = SortFlags.CommonOpaque;
                litDrawSettings.rendererConfiguration = configuration;

                var unlitDrawSettings = new DrawRendererSettings(m_CurrCamera, m_UnlitPassName);
                unlitDrawSettings.sorting.flags = SortFlags.CommonTransparent;

                // Render Opaques
                var opaqueFilterSettings = new FilterRenderersSettings(true)
                {
                    renderQueueRange = RenderQueueRange.opaque
                };

                context.DrawRenderers(m_CullResults.visibleRenderers, ref litDrawSettings, opaqueFilterSettings);

                // TODO: Check skybox shader
                context.DrawSkybox(m_CurrCamera);

                // Render Alpha blended
                var transparentFilterSettings = new FilterRenderersSettings(true)
                {
                    renderQueueRange = RenderQueueRange.transparent
                };

                litDrawSettings.sorting.flags = SortFlags.CommonTransparent;
                context.DrawRenderers(m_CullResults.visibleRenderers, ref litDrawSettings, transparentFilterSettings);
                context.DrawRenderers(m_CullResults.visibleRenderers, ref unlitDrawSettings, transparentFilterSettings);

                if (postProcessEnabled)
                {
                    RenderPostProcess(ref context, postProcessLayer);
                }

                EndForwardRendering(ref context, stereoEnabled, postProcessEnabled);

                // Release temporary RT
                var discardRT = CommandBufferPool.Get();
                discardRT.ReleaseTemporaryRT(m_ShadowMapProperty);
                discardRT.ReleaseTemporaryRT(m_CameraRTProperty);
                context.ExecuteCommandBuffer(discardRT);
                CommandBufferPool.Release(discardRT);
            }

            context.Submit();
        }
Beispiel #8
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(cameras);

        foreach (Camera camera in cameras)
        {
            BeginCameraRendering(camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //Set Depth texture temp RT
            CommandBuffer cmdTempId = new CommandBuffer();
            cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT";
            RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            depthRTDesc.colorFormat     = RenderTextureFormat.Depth;
            depthRTDesc.depthBufferBits = depthBufferBits;
            cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear);
            context.ExecuteCommandBuffer(cmdTempId);
            cmdTempId.Release();

            //Setup DrawSettings and FilterSettings
            var               sortingSettings   = new SortingSettings(camera);
            DrawingSettings   drawSettings      = new DrawingSettings(m_PassName, sortingSettings);
            FilteringSettings filterSettings    = new FilteringSettings(RenderQueueRange.all);
            DrawingSettings   drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings)
            {
                perObjectData             = PerObjectData.None,
                overrideMaterial          = depthOnlyMaterial,
                overrideMaterialPassIndex = 0
            };

            //Clear Depth Texture
            CommandBuffer cmdDepth = new CommandBuffer();
            cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag";
            cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture
            cmdDepth.ClearRenderTarget(true, true, Color.black);
            context.ExecuteCommandBuffer(cmdDepth);
            cmdDepth.Release();

            //Draw Depth with Opaque objects
            sortingSettings.criteria          = SortingCriteria.CommonOpaque;
            drawSettingsDepth.sortingSettings = sortingSettings;
            filterSettings.renderQueueRange   = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings);

            //To let shader has _CameraDepthTexture
            CommandBuffer cmdDepthTexture = new CommandBuffer();
            cmdDepthTexture.name = "(" + camera.name + ")" + "Depth Texture";
            cmdDepthTexture.SetGlobalTexture(m_DepthRTid, m_DepthRT);
            context.ExecuteCommandBuffer(cmdDepthTexture);
            cmdDepthTexture.Release();

            //Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); //Rember to reset target
            cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //Skybox
            if (drawSkyBox)
            {
                context.DrawSkybox(camera);
            }

            //Opaque objects
            sortingSettings.criteria        = SortingCriteria.CommonOpaque;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Transparent objects
            sortingSettings.criteria        = SortingCriteria.CommonTransparent;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Clean Up
            CommandBuffer cmdclean = new CommandBuffer();
            cmdclean.name = "(" + camera.name + ")" + "Clean Up";
            cmdclean.ReleaseTemporaryRT(m_DepthRTid);
            context.ExecuteCommandBuffer(cmdclean);
            cmdclean.Release();

            context.Submit();
        }
    }
Beispiel #9
0
 void DrawVisibleGeometry()
 {
     context.DrawSkybox(camera);
 }
Beispiel #10
0
 private void DrawSkyBox(ScriptableRenderContext pRenderContext, Camera pCamera)
 {
     pRenderContext.DrawSkybox(pCamera);
 }
Beispiel #11
0
        protected virtual void RenderCamera(ScriptableRenderContext context, Camera camera)
        {
            var p = Matrix4x4.Perspective(30, 16.0f / 9, .3f, 1000);
            var v = new Vector4(.5f, .5f, 10, 1);

            camera.TryGetCullingParameters(out var cullingParameters);

            var cmd = CommandBufferPool.Get(camera.name);

            cmd.Clear();

            if (camera.cameraType == CameraType.SceneView)
            {
                ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
            }

            var cullResults = context.Cull(ref cullingParameters);

            var projectionMat         = camera.projectionMatrix;
            var jitteredProjectionMat = projectionMat;

            jitteredProjectionMat.m02 += (projectionJitter.Current.x * 2 - 1) / camera.pixelWidth;
            jitteredProjectionMat.m12 += (projectionJitter.Current.x * 2 - 1) / camera.pixelHeight;

            var renderingData = new RenderingData()
            {
                camera                   = camera,
                cullResults              = cullResults,
                ColorTarget              = BuiltinRenderTextureType.CameraTarget,
                DepthTarget              = BuiltinRenderTextureType.CameraTarget,
                ColorBufferFormat        = RenderTextureFormat.Default,
                shadowMapData            = new Dictionary <Light, ShadowMapData>(),
                FrameID                  = frameID,
                DiscardFrameBuffer       = true,
                ViewMatrix               = camera.worldToCameraMatrix,
                ProjectionMatrix         = projectionMat,
                JitteredProjectionMatrix = jitteredProjectionMat,
                ProjectionJitter         = new Vector2(.5f, .5f),
                NextProjectionJitter     = new Vector2(.5f, .5f),
            };

            this.Setup(context, ref renderingData);
            context.SetupCameraProperties(camera, false);

            InitRenderQueue(camera);
            SetupLight(ref renderingData);

            /*RenderTargetBinding binding = new RenderTargetBinding();
             * binding.colorRenderTargets = new RenderTargetIdentifier[] { ColorTarget };
             * binding.colorLoadActions = new RenderBufferLoadAction[] { RenderBufferLoadAction.Clear };
             * binding.depthRenderTarget = DepthTarget;
             * binding.depthLoadAction = RenderBufferLoadAction.Clear;
             * binding.colorStoreActions = new RenderBufferStoreAction[] { RenderBufferStoreAction.Store };
             * binding.depthStoreAction = RenderBufferStoreAction.Store;*/
            cmd.SetRenderTarget(ColorTarget, DepthTarget);
            cmd.ClearRenderTarget(true, true, Color.black, 1);
            cmd.SetRenderTarget(DepthTarget, DepthTarget);
            cmd.ClearRenderTarget(true, true, Color.black, 1);
            cmd.SetRenderTarget(ColorTarget, DepthTarget);
            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();

            context.DrawSkybox(camera);

            foreach (var pass in RenderPassQueue)
            {
                pass.Setup(context, ref renderingData);
                pass.Render(context, ref renderingData);
            }

            // Draw global user passes
            foreach (var pass in globalUserPasses)
            {
                pass.Setup(context, ref renderingData);
                pass.Render(context, ref renderingData);
            }

            // Draw user passes
            var userPasses = camera.GetComponents <UserPass>();

            foreach (var pass in userPasses)
            {
                if (pass.Global)
                {
                    continue;
                }
                pass.Setup(context, ref renderingData);
                pass.Render(context, ref renderingData);
            }

            cmd.Blit(renderingData.ColorTarget, BuiltinRenderTextureType.CameraTarget);
            //cmd.CopyTexture(renderingData.DepthTarget, BuiltinRenderTextureType.CameraTarget);
            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();

            if (camera.cameraType == CameraType.SceneView)
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }

            foreach (var pass in RenderPassQueue)
            {
                pass.Cleanup(context, ref renderingData);
            }
            foreach (var pass in globalUserPasses)
            {
                pass.Cleanup(context, ref renderingData);
            }
            foreach (var pass in userPasses)
            {
                pass.Cleanup(context, ref renderingData);
            }


            this.Cleanup(context, ref renderingData);

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
            context.Submit();

            projectionJitter.Next = renderingData.NextProjectionJitter;
        }
Beispiel #12
0
	private void RenderScene(Camera camera) {
		// Clear the screen
		var clearFlags = camera.clearFlags;
		
		_currentBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor);
		
		// Set up view port, view matrix and projection matrix
		// context.SetupCameraProperties(camera);
		
		var cameraTransform = camera.transform;
		var cameraForward = cameraTransform.forward;
		var cameraPosition = cameraTransform.position;

		var viewPort = camera.pixelRect;
		var viewMatrix = camera.worldToCameraMatrix;
		var projectionMatrix = camera.projectionMatrix;
		
		_currentBuffer.SetViewport(viewPort);
		_currentBuffer.SetViewProjectionMatrices(viewMatrix, projectionMatrix);

		var farClipPlane = camera.farClipPlane;
		var nearClipPlane = camera.nearClipPlane;
		var clipDistance = farClipPlane - nearClipPlane;
		
		var zBufferParams = new Vector4(clipDistance / nearClipPlane, 1, clipDistance / (farClipPlane * nearClipPlane), 1 / farClipPlane);

		_currentBuffer.SetGlobalFloat(ShaderManager.ALPHA_TEST_DEPTH_CUTOFF, @params.alphaTestDepthCutoff);
		_currentBuffer.SetGlobalVector(ShaderManager.Z_BUFFER_PARAMS, zBufferParams);
		_currentBuffer.SetComputeVectorParam(@params.tbrComputeShader, ShaderManager.Z_BUFFER_PARAMS, zBufferParams);
		_currentBuffer.SetComputeMatrixParam(@params.tbrComputeShader, ShaderManager.UNITY_MATRIX_V, viewMatrix);
		_currentBuffer.SetComputeMatrixParam(@params.tbrComputeShader, ShaderManager.UNITY_INVERSE_P, projectionMatrix.inverse);

		ExecuteCurrentBuffer();

// Only need to construct UI meshes under Editor mode
#if UNITY_EDITOR
		if (camera.cameraType == CameraType.SceneView) ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
#endif
		
		// Object culling
		// todo maybe add gpu culling pipeline in the future (compute shader based, AABB/OBB intersection tests)
		if (!camera.TryGetCullingParameters(out var cullingParameters)) return;
		cullingParameters.shadowDistance = Mathf.Min(@params.sunlightParams.shadowDistance, farClipPlane);
		var cull = _context.Cull(ref cullingParameters);
		
		var sortingSettings = new SortingSettings(camera) { criteria = SortingCriteria.QuantizedFrontToBack | SortingCriteria.OptimizeStateChanges };

		// Render depth and normal textures
		var drawSettings = new DrawingSettings(ShaderTagManager.SRP_DEFAULT_UNLIT, sortingSettings) {
			enableDynamicBatching = @params.enableDynamicBatching,
			enableInstancing = @params.enableInstancing
		};

		var filterSettings = FilteringSettings.defaultValue;
		filterSettings.layerMask = camera.cullingMask;
		filterSettings.renderQueueRange = RenderQueueRange.transparent;
		
		var pixelWidth = camera.pixelWidth;
		var pixelHeight = camera.pixelHeight;
		
		GenerateRTs(pixelWidth, pixelHeight);
		
		ResetRenderTarget(OpaqueNormalId, DepthId, true, true, 1, Color.black);
		
		ExecuteCurrentBuffer();
		
		// Depth prepass (with opaque normal rendered)
		var depthNormalDrawSettings = new DrawingSettings(ShaderTagManager.DEPTH_NORMAL, sortingSettings) {
			enableDynamicBatching = @params.enableDynamicBatching,
			enableInstancing = @params.enableInstancing
		};

		filterSettings.renderQueueRange = ShaderManager.OPAQUE_RENDER_QUEUE_RANGE;
		_context.DrawRenderers(cull, ref depthNormalDrawSettings, ref filterSettings);

		sortingSettings.criteria = SortingCriteria.OptimizeStateChanges;
		depthNormalDrawSettings.sortingSettings = sortingSettings;
		filterSettings.renderQueueRange = ShaderManager.ALPHA_TEST_QUEUE_RANGE;
		_context.DrawRenderers(cull, ref depthNormalDrawSettings, ref filterSettings);

		var screenThreadGroupsX = pixelWidth / 8;
		var screenThreadGroupsY = pixelHeight / 8;
		if (pixelWidth % 8 != 0) screenThreadGroupsX++;
		if (pixelHeight % 8 != 0) screenThreadGroupsY++;

		var depthCopyKernel = @params.generalComputeShader.FindKernel("CopyDepth");
		_currentBuffer.SetComputeTextureParam(@params.generalComputeShader, depthCopyKernel, ShaderManager.DEPTH_TEXTURE, DepthId);
		_currentBuffer.SetComputeTextureParam(@params.generalComputeShader, depthCopyKernel, ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId);
		_currentBuffer.DispatchCompute(@params.generalComputeShader, depthCopyKernel, screenThreadGroupsX, screenThreadGroupsY, 1);
		
		_currentBuffer.SetGlobalTexture(ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId);

		// Stencil prepass
		ResetRenderTarget(OpaqueNormalId, DepthId, false, false, 1, Color.black);
		
		ExecuteCurrentBuffer();
		
		var stencilDrawSettings = new DrawingSettings(ShaderTagManager.STENCIL, sortingSettings) {
			enableDynamicBatching = @params.enableDynamicBatching,
			enableInstancing = @params.enableInstancing
		};
		
		filterSettings.renderQueueRange = RenderQueueRange.all;

		_context.DrawRenderers(cull, ref stencilDrawSettings, ref filterSettings);

		var transparentDepthDrawSettings = new DrawingSettings(ShaderTagManager.DEPTH, sortingSettings) {
			enableDynamicBatching = @params.enableDynamicBatching,
			enableInstancing = @params.enableInstancing
		};
		
		filterSettings.renderQueueRange = RenderQueueRange.transparent;
		_context.DrawRenderers(cull, ref transparentDepthDrawSettings, ref filterSettings);

		// Tile-based light culling
		var depthBoundTextureWidth = pixelWidth / @params.depthTileResolution;
		var depthBoundTextureHeight = pixelHeight / @params.depthTileResolution;
		if (pixelWidth % @params.depthTileResolution != 0) depthBoundTextureWidth++;
		if (pixelHeight % @params.depthTileResolution != 0) depthBoundTextureHeight++;
		var tileThreadGroupsX = depthBoundTextureWidth / 16;
		var tileThreadGroupsY = depthBoundTextureHeight / 9;
		if (depthBoundTextureWidth % 16 != 0) tileThreadGroupsX++;
		if (depthBoundTextureHeight % 9 != 0) tileThreadGroupsY++;
		
		// Debug.Log(pixelWidth + ", " + pixelHeight);

		var depthBoundKernel = @params.tbrComputeShader.FindKernel("GenerateDepthBound");
		_currentBuffer.SetComputeFloatParams(@params.tbrComputeShader, ShaderManager.TILE_NUMBER, (float) depthBoundTextureWidth, (float) depthBoundTextureHeight);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthBoundKernel, ShaderManager.DEPTH_TEXTURE, DepthId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthBoundKernel, ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthBoundKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId);
		_currentBuffer.DispatchCompute(@params.tbrComputeShader, depthBoundKernel, tileThreadGroupsX, tileThreadGroupsY, 1);

		ExecuteCurrentBuffer();

		var depthMaskKernel = @params.tbrComputeShader.FindKernel("GenerateDepthMask");
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.DEPTH_TEXTURE, DepthId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.DEPTH_MASK_TEXTURE, DepthMaskId);
		_currentBuffer.DispatchCompute(@params.tbrComputeShader, depthMaskKernel, tileThreadGroupsX, tileThreadGroupsY, 1);
		
		ExecuteCurrentBuffer();

		var depthFrustumKernel = @params.tbrComputeShader.FindKernel("GenerateDepthFrustum");
		_currentBuffer.SetComputeFloatParams(@params.tbrComputeShader, ShaderManager.CAMERA_FORWARD, cameraForward.x, cameraForward.y, cameraForward.z);
		_currentBuffer.SetComputeFloatParams(@params.tbrComputeShader, ShaderManager.CAMERA_POSITION, cameraPosition.x, cameraPosition.y, cameraPosition.z);
		// _currentBuffer.SetComputeVectorParam(@params.tbrComputeShader, ShaderManager.Z_BUFFER_PARAMS, zBufferParams);
		_currentBuffer.SetComputeMatrixParam(@params.tbrComputeShader, ShaderManager.UNITY_INVERSE_VP, (camera.projectionMatrix * camera.worldToCameraMatrix).inverse);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthFrustumKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthFrustumKernel, ShaderManager.DEPTH_FRUSTUM_TEXTURE, DepthFrustumId);
		_currentBuffer.DispatchCompute(@params.tbrComputeShader, depthFrustumKernel, tileThreadGroupsX, tileThreadGroupsY, 1);
		
		ExecuteCurrentBuffer();
		
		var allLights = cull.visibleLights;
		var lightIndexMap = cull.GetLightIndexMap(Allocator.Temp);
		
		var sunlightColor = new Vector4(0, 0, 0);
		var sunlightDirection = new Vector4(0, 0, 0);

		if (sunlight.Exists()) {
			sunlightDirection = sunlight.transform.localToWorldMatrix.GetDirectionFromLocalTransform();
			sunlightColor = sunlight.color * sunlight.intensity;
		}
		
		_currentBuffer.SetGlobalVector(ShaderManager.SUNLIGHT_COLOR, sunlightColor);
		_currentBuffer.SetGlobalVector(ShaderManager.SUNLIGHT_DIRECTION, sunlightDirection);

		var pointLightCountMax = @params.pointLightParams.enabled ? @params.pointLightParams.maxPerFrame : 0;
		var spotLightCountMax = @params.spotLightParams.enabled ? @params.spotLightParams.maxPerFrame : 0;

		var pointLightShadowMax = @params.pointLightParams.enabled ? @params.pointLightParams.maxShadowCount : 0;
		var spotLightShadowMax = @params.spotLightParams.enabled ? @params.spotLightParams.maxShadowCount : 0;

		var sunlightIndex = 0;

		var pointLightIndices = new int[pointLightShadowMax];
		var spotLightIndices = new int[spotLightShadowMax];

		var shadowPointLights = new Light[pointLightShadowMax];
		var shadowSpotLights = new Light[spotLightShadowMax];

		var pointLightIndex = 0;
		var spotLightIndex = 0;

		var pointLightShadowIndex = 0u;
		var spotLightShadowIndex = 0u;

		for (int i = 0, l = allLights.Length; i < l; i++) {
			var visibleLight = allLights[i];
			var lightType = allLights[i].lightType;
			switch (lightType) {
				case LightType.Point:
					if (pointLightIndex >= pointLightCountMax) continue;
					var originalPointLight = visibleLight.light;
					var pointLightColor = visibleLight.finalColor;
					var pointLight = new PointLight {
						// color = new float3(pointLightColor.r, pointLightColor.g, pointLightColor.b),
						sphere = new float4(visibleLight.light.transform.position, visibleLight.range)
					};

					if (originalPointLight.shadows != LightShadows.None && pointLightShadowIndex < pointLightShadowMax) {
						// pointLight.shadowStrength = originalPointLight.shadowStrength;
						pointLight.shadowIndex = pointLightShadowIndex + 1;
						pointLightIndices[pointLightShadowIndex] = lightIndexMap[i];
						shadowPointLights[pointLightShadowIndex] = originalPointLight;
						pointLightShadowIndex++;
					} else pointLight.shadowIndex = 0;

					_pointLights[pointLightIndex] = pointLight;
					pointLightIndex++;
					break;
				
				case LightType.Spot:
					if (spotLightIndex >= spotLightCountMax) continue;
					var originalSpotLight = visibleLight.light;
					var spotLightColor = visibleLight.finalColor;
					var spotLightDirection = visibleLight.localToWorldMatrix.GetDirectionFromLocalTransform();
					var spotLightAngle = Mathf.Deg2Rad * visibleLight.spotAngle * .5f;
					var spotLight = new SpotLight {
						// color = new float3(spotLightColor.r, spotLightColor.g, spotLightColor.b),
						cone = new Cone(visibleLight.localToWorldMatrix.GetPositionFromLocalTransform(), spotLightAngle, visibleLight.range, new float3(spotLightDirection.x, spotLightDirection.y, spotLightDirection.z)),
						// innerAngle = Mathf.Deg2Rad * originalSpotLight.innerSpotAngle * .5f,
						// nearClip = originalSpotLight.shadowNearPlane
					};

					if (originalSpotLight.shadows != LightShadows.None && spotLightShadowIndex < spotLightShadowMax) {
						// spotLight.shadowStrength = originalSpotLight.shadowStrength;
						spotLight.shadowIndex = spotLightShadowIndex + 1;
						spotLightIndices[spotLightShadowIndex] = lightIndexMap[i];
						shadowSpotLights[spotLightShadowIndex] = originalSpotLight;
						spotLightShadowIndex++;
					} else spotLight.shadowIndex = 0;

					_spotLights[spotLightIndex] = spotLight;
					spotLightIndex++;
					break;
				
				case LightType.Directional:
					if (allLights[i].light == sunlight) sunlightIndex = lightIndexMap[i];
					break;
			}
		}
		
		if (@params.sunlightParams.shadowOn && sunlight.Exists() && sunlight.shadows != LightShadows.None) {
			_currentBuffer.EnableShaderKeyword(ShaderManager.SUNLIGHT_SHADOWS);
			RenderCascadedDirectionalShadow(cull, sunlightIndex, sunlight, cullingParameters.shadowDistance);
		} else _currentBuffer.DisableShaderKeyword(ShaderManager.SUNLIGHT_SHADOWS);

		if (@params.pointLightParams.shadowOn) {
			_currentBuffer.EnableShaderKeyword(ShaderManager.POINT_LIGHT_SHADOWS);
			RenderPointLightShadow(cull, (int) pointLightShadowIndex, shadowPointLights, pointLightIndices);
			// if (pointLightShadowCount > 0) RenderPointLightShadow(context, cull, shadowPointLights[0], pointLightIndices[0]);
		} else _currentBuffer.DisableShaderKeyword(ShaderManager.POINT_LIGHT_SHADOWS);

		if (@params.spotLightParams.shadowOn) {
			_currentBuffer.EnableShaderKeyword(ShaderManager.SPOT_LIGHT_SHADOWS);
			RenderSpotLightShadow(cull, (int) spotLightShadowIndex, shadowSpotLights, spotLightIndices);
		} else _currentBuffer.DisableShaderKeyword(ShaderManager.SPOT_LIGHT_SHADOWS);
		
		Extensions.Resize(ref _pointLightBuffer, pointLightIndex);
		Extensions.Resize(ref _spotLightBuffer, spotLightIndex);
		
		_pointLightBuffer.SetData(_pointLights, 0, 0, pointLightIndex);
		_spotLightBuffer.SetData(_spotLights, 0, 0, spotLightIndex);

		var pointLightKernel = @params.tbrComputeShader.FindKernel("CullPointLight");
		_currentBuffer.SetComputeIntParam(@params.tbrComputeShader, ShaderManager.POINT_LIGHT_COUNT, pointLightIndex);
		_currentBuffer.SetComputeBufferParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.POINT_LIGHT_BUFFER, _pointLightBuffer);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.DEPTH_MASK_TEXTURE, DepthMaskId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.DEPTH_FRUSTUM_TEXTURE, DepthFrustumId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.CULLED_POINT_LIGHT_TEXTURE, CulledPointLightId);
		_currentBuffer.DispatchCompute(@params.tbrComputeShader, pointLightKernel, tileThreadGroupsX, tileThreadGroupsY, 1);
		
		var spotLightKernel = @params.tbrComputeShader.FindKernel("CullSpotLight");
		_currentBuffer.SetComputeIntParam(@params.tbrComputeShader, ShaderManager.SPOT_LIGHT_COUNT, spotLightIndex);
		_currentBuffer.SetComputeBufferParam(@params.tbrComputeShader, spotLightKernel, ShaderManager.SPOT_LIGHT_BUFFER, _spotLightBuffer);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, spotLightKernel, ShaderManager.DEPTH_FRUSTUM_TEXTURE, DepthFrustumId);
		_currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, spotLightKernel, ShaderManager.CULLED_SPOT_LIGHT_TEXTURE, CulledSpotLightId);
		_currentBuffer.DispatchCompute(@params.tbrComputeShader, spotLightKernel, tileThreadGroupsX, tileThreadGroupsY, 1);
		
		ExecuteCurrentBuffer();
		
		_currentBuffer.SetGlobalTexture(ShaderManager.CULLED_POINT_LIGHT_TEXTURE, CulledPointLightId);
		_currentBuffer.SetGlobalTexture(ShaderManager.CULLED_SPOT_LIGHT_TEXTURE, CulledSpotLightId);
		_currentBuffer.SetGlobalBuffer(ShaderManager.POINT_LIGHT_BUFFER, _pointLightBuffer);
		_currentBuffer.SetGlobalBuffer(ShaderManager.SPOT_LIGHT_BUFFER, _spotLightBuffer);
		
		ExecuteCurrentBuffer();

		_context.SetupCameraProperties(camera);
		
		ResetRenderTarget(ColorBufferId, OpaqueDepthId, false, true, 0, Color.black);
		
		ExecuteCurrentBuffer();
		
		// Opaque pass
		sortingSettings.criteria = SortingCriteria.OptimizeStateChanges;
		drawSettings.overrideMaterial = null;
		filterSettings.renderQueueRange = ShaderManager.OPAQUE_RENDER_QUEUE_RANGE;
		_context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

		// Alpha test pass
		sortingSettings.criteria = SortingCriteria.OptimizeStateChanges;
		filterSettings.renderQueueRange = ShaderManager.ALPHA_TEST_QUEUE_RANGE;
		_context.DrawRenderers(cull, ref drawSettings, ref filterSettings);
		
		// Skybox Pass
		if ((camera.clearFlags & CameraClearFlags.Skybox) != 0) _context.DrawSkybox(camera);
		
		ResetRenderTarget(ColorBufferId, DepthId, false, false, 1, Color.black);
		
		ExecuteCurrentBuffer();

		// Transparent Pass
		filterSettings.renderQueueRange = RenderQueueRange.transparent;
		_context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

		if (@params.ditherTransparentParams.blurOn && @params.ditherTransparentParams.blurMaterial != null) DitherTransparentBlur(pixelWidth >> @params.ditherTransparentParams.downSamples, pixelHeight >> @params.ditherTransparentParams.downSamples);
		
		// Blit color buffer to camera target (normally screen)
		_currentBuffer.Blit(ColorBufferId, BuiltinRenderTextureType.CameraTarget);

#if UNITY_EDITOR
		if (@params.testMaterialOn) {
			@params.testMaterial.SetInt("_TestInt", @params.testInt);
			_currentBuffer.Blit(BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CurrentActive, @params.testMaterial);
			// _currentBuffer.Blit(PointLightShadowmapId, BuiltinRenderTextureType.CurrentActive);
			if (@params.depthBoundOn) _currentBuffer.Blit(DepthBoundId, BuiltinRenderTextureType.CurrentActive);
		}
#endif
		
		ExecuteCurrentBuffer();

#if UNITY_EDITOR
		if (@params.gizmosOn) _context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
#endif
		
		// Release temporary render textures
		ReleaseRTs();
		
		// Release unmanaged objects
		// DisposeComputeBuffers();
		
		ExecuteCurrentBuffer();

		_context.Submit();
		
		// allLights.Dispose();
		lightIndexMap.Dispose();
	}
    void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

        if (!CullResults.GetCullingParameters(camera, out cullingParameters))
        {
            return;
        }
        cullingParameters.shadowDistance =
            Mathf.Min(shadowDistance, camera.farClipPlane);

#if UNITY_EDITOR
        if (camera.cameraType == CameraType.SceneView)
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif

        CullResults.Cull(ref cullingParameters, context, ref cull);
        if (cull.visibleLights.Count > 0)
        {
            ConfigureLights();
            if (mainLightExists)
            {
                RenderCascadedShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            }
            if (shadowTileCount > 0)
            {
                RenderShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
            }
        }
        else
        {
            cameraBuffer.SetGlobalVector(
                lightIndicesOffsetAndCountID, Vector4.zero
                );
            cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
        }

        context.SetupCameraProperties(camera);

        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget(
            (clearFlags & CameraClearFlags.Depth) != 0,
            (clearFlags & CameraClearFlags.Color) != 0,
            camera.backgroundColor
            );

        cameraBuffer.BeginSample("Render Camera");
        cameraBuffer.SetGlobalVectorArray(
            visibleLightColorsId, visibleLightColors
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightAttenuationsId, visibleLightAttenuations
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightSpotDirectionsId, visibleLightSpotDirections
            );
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        var drawSettings = new DrawRendererSettings(
            camera, new ShaderPassName("SRPDefaultUnlit")
            )
        {
            flags = drawFlags
        };
        if (cull.visibleLights.Count > 0)
        {
            drawSettings.rendererConfiguration =
                RendererConfiguration.PerObjectLightIndices8;
        }
        drawSettings.rendererConfiguration |=
            RendererConfiguration.PerObjectReflectionProbes |
            RendererConfiguration.PerObjectLightmaps |
            RendererConfiguration.PerObjectLightProbe |
            RendererConfiguration.PerObjectLightProbeProxyVolume;
        drawSettings.sorting.flags = SortFlags.CommonOpaque;

        var filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.opaque
        };

        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        context.DrawSkybox(camera);

        drawSettings.sorting.flags      = SortFlags.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        DrawDefaultPipeline(context, camera);

        cameraBuffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        context.Submit();

        if (shadowMap)
        {
            RenderTexture.ReleaseTemporary(shadowMap);
            shadowMap = null;
        }
        if (cascadedShadowMap)
        {
            RenderTexture.ReleaseTemporary(cascadedShadowMap);
            cascadedShadowMap = null;
        }
    }
Beispiel #14
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(context, cameras);

        foreach (Camera camera in cameras)
        {
            BeginCameraRendering(context, camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //Color Texture Descriptor
            RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            colorRTDesc.colorFormat       = m_ColorFormat;
            colorRTDesc.depthBufferBits   = depthBufferBits;
            colorRTDesc.sRGB              = (QualitySettings.activeColorSpace == ColorSpace.Linear);
            colorRTDesc.msaaSamples       = 1;
            colorRTDesc.enableRandomWrite = false;

            //Get Temp Texture for Color Texture
            CommandBuffer cmdTempId = new CommandBuffer();
            cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT";
            cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear);
            cmdTempId.SetRenderTarget(m_ColorRT); //so that result won't flip
            context.ExecuteCommandBuffer(cmdTempId);
            cmdTempId.Release();

            //Setup DrawSettings and FilterSettings
            var               sortingSettings = new SortingSettings(camera);
            DrawingSettings   drawSettings1   = new DrawingSettings(m_PassName1, sortingSettings);
            DrawingSettings   drawSettings2   = new DrawingSettings(m_PassName2, sortingSettings);
            FilteringSettings filterSettings  = new FilteringSettings(RenderQueueRange.all);

            //Native Arrays for Attachaments
            NativeArray <AttachmentDescriptor> renderPassAttachments = new NativeArray <AttachmentDescriptor>(4, Allocator.Temp);
            renderPassAttachments[0] = m_Albedo;
            renderPassAttachments[1] = m_Emission;
            renderPassAttachments[2] = m_Output;
            renderPassAttachments[3] = m_Depth;
            NativeArray <int> renderPassColorAttachments = new NativeArray <int>(2, Allocator.Temp);
            renderPassColorAttachments[0] = 0;
            renderPassColorAttachments[1] = 1;
            NativeArray <int> renderPassOutputAttachments = new NativeArray <int>(1, Allocator.Temp);
            renderPassOutputAttachments[0] = 2;

            //Clear Attachements
            m_Output.ConfigureTarget(m_ColorRT, false, true);
            m_Output.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1, 0);
            m_Albedo.ConfigureClear(camera.backgroundColor, 1, 0);
            m_Emission.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1, 0);
            m_Depth.ConfigureClear(new Color(), 1, 0);

            //More clean to use ScopedRenderPass instead of BeginRenderPass+EndRenderPass
            using (context.BeginScopedRenderPass(camera.pixelWidth, camera.pixelHeight, 1, renderPassAttachments, 3))
            {
                //Output to Albedo & Emission
                using (context.BeginScopedSubPass(renderPassColorAttachments, false))
                {
                    //Opaque objects
                    sortingSettings.criteria        = SortingCriteria.CommonOpaque;
                    drawSettings1.sortingSettings   = sortingSettings;
                    filterSettings.renderQueueRange = RenderQueueRange.opaque;
                    context.DrawRenderers(cull, ref drawSettings1, ref filterSettings);

                    //Transparent objects
                    sortingSettings.criteria        = SortingCriteria.CommonTransparent;
                    drawSettings1.sortingSettings   = sortingSettings;
                    filterSettings.renderQueueRange = RenderQueueRange.transparent;
                    context.DrawRenderers(cull, ref drawSettings1, ref filterSettings);
                }
                //Read from Albedo & Emission, then output to Output
                using (context.BeginScopedSubPass(renderPassOutputAttachments, renderPassColorAttachments))
                {
                    //Skybox
                    if (drawSkyBox)
                    {
                        context.DrawSkybox(camera);
                    }

                    //Opaque objects
                    sortingSettings.criteria        = SortingCriteria.CommonOpaque;
                    drawSettings2.sortingSettings   = sortingSettings;
                    filterSettings.renderQueueRange = RenderQueueRange.opaque;
                    context.DrawRenderers(cull, ref drawSettings2, ref filterSettings);

                    //Transparent objects
                    sortingSettings.criteria        = SortingCriteria.CommonTransparent;
                    drawSettings2.sortingSettings   = sortingSettings;
                    filterSettings.renderQueueRange = RenderQueueRange.transparent;
                    context.DrawRenderers(cull, ref drawSettings2, ref filterSettings);
                }
            }

            //Blit To Camera so that the CameraTarget has content and make sceneview works
            CommandBuffer cmd = new CommandBuffer();
            cmd.name = "Cam:" + camera.name + " BlitToCamera";
            cmd.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //CleanUp Texture
            CommandBuffer cmdclean = new CommandBuffer();
            cmdclean.name = "(" + camera.name + ")" + "Clean Up";
            cmdclean.ReleaseTemporaryRT(m_ColorRTid);
            context.ExecuteCommandBuffer(cmdclean);
            cmdclean.Release();

            //Submit the CommandBuffers
            context.Submit();

            //CleanUp NativeArrays
            renderPassAttachments.Dispose();
            renderPassColorAttachments.Dispose();
            renderPassOutputAttachments.Dispose();

            EndCameraRendering(context, camera);
        }

        EndFrameRendering(context, cameras);
    }
Beispiel #15
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(context, cameras);

        foreach (Camera camera in cameras)
        {
            BeginCameraRendering(context, camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //************************** Start Set TempRT ************************************
            CommandBuffer cmdTempId = new CommandBuffer();
            cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT";

            //Color
            RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            colorRTDesc.graphicsFormat  = camera.allowHDR ? m_ColorFormatHDR : m_ColorFormat;
            colorRTDesc.depthBufferBits = depthBufferBits;
            //colorRTDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear);
            colorRTDesc.msaaSamples       = camera.allowMSAA ? QualitySettings.antiAliasing : 1;
            colorRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear);

            context.ExecuteCommandBuffer(cmdTempId);
            cmdTempId.Release();

            //************************** End Set TempRT ************************************


            //Set RenderTarget & Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            cmd.SetRenderTarget(m_ColorRT); //Set CameraTarget to the color texture
            cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //Setup DrawSettings and FilterSettings
            var               sortingSettings = new SortingSettings(camera);
            DrawingSettings   drawSettings    = new DrawingSettings(m_PassName, sortingSettings);
            FilteringSettings filterSettings  = new FilteringSettings(RenderQueueRange.all);

            //Skybox
            if (drawSkyBox)
            {
                context.DrawSkybox(camera);
            }

            //Opaque objects
            sortingSettings.criteria        = SortingCriteria.CommonOpaque;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Transparent objects
            sortingSettings.criteria        = SortingCriteria.CommonTransparent;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Blit the content back to screen
            CommandBuffer cmdBlitToCam = new CommandBuffer();
            cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera";
            cmdBlitToCam.Blit(m_ColorRTid, BuiltinRenderTextureType.CameraTarget);
            context.ExecuteCommandBuffer(cmdBlitToCam);
            cmdBlitToCam.Release();

            //************************** Clean Up ************************************
            CommandBuffer cmdclean = new CommandBuffer();
            cmdclean.name = "(" + camera.name + ")" + "Clean Up";
            cmdclean.ReleaseTemporaryRT(m_ColorRTid);
            context.ExecuteCommandBuffer(cmdclean);
            cmdclean.Release();

            context.Submit();

            EndCameraRendering(context, camera);
        }

        EndFrameRendering(context, cameras);
    }
Beispiel #16
0
    public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, SRP07CustomParameter SRP07CP)
    {
        string tx = "";

        foreach (Camera camera in cameras)
        {
            ScriptableCullingParameters cullingParams;

            // Stereo-aware culling parameters are configured to perform a single cull for both eyes
            if (!CullResults.GetCullingParameters(camera, out cullingParams))
            {
                continue;
            }
            CullResults cull = new CullResults();
            CullResults.Cull(ref cullingParams, context, ref cull);

            // Setup camera for rendering (sets render target, view/projection matrices and other
            // per-camera built-in shader variables).
            context.SetupCameraProperties(camera);

            // clear depth buffer
            CommandBuffer cmd = new CommandBuffer();
            cmd.ClearRenderTarget(true, !SRP07CP.DrawSkybox, SRP07CP.ClearColor);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            // Setup global lighting shader variables
            SetupLightShaderVariables(cull.visibleLights, context);

            if (SRP07CP.DrawSkybox)
            {
                // Draw skybox
                context.DrawSkybox(camera);
            }

            // Setup DrawSettings and FilterSettings
            ShaderPassName          passName       = new ShaderPassName("BasicPass");
            DrawRendererSettings    drawSettings   = new DrawRendererSettings(camera, passName);
            FilterRenderersSettings filterSettings = new FilterRenderersSettings(true);

            // ////////////////////////////////////////////////////////////
            VisibleLight[]        ls = cull.visibleLights.ToArray();
            DrawShadowsSettings[] shadowsSettings = new DrawShadowsSettings[ls.Length];

            for (int i = 0; i < shadowsSettings.Length; i++)
            {
                shadowsSettings[i] = new DrawShadowsSettings(cull, i);
            }

            /*
             * if(camera == Camera.main) //Only generate result from main cam
             * {
             *  tx += "DrawShadowsSettings" + "\n"+ "\n";
             *
             *  for (int i=0; i<ls.Length; i++)
             *  {
             *      tx += "lightIndex = " + shadowsSettings[i].lightIndex + " (" + ls[i].light.name + ") " + "\n";
             *      tx += "splitData.cullingPlaneCount = " + shadowsSettings[i].splitData.cullingPlaneCount + "\n";
             *      tx += "splitData.cullingSphere = " + shadowsSettings[i].splitData.cullingSphere + "\n"+ "\n";
             *  }
             *
             *  // Output to text
             *  if (textMesh != null)
             *  {
             *      textMesh.text = tx;
             *      Debug.Log("<color=#0F0>TextMesh is updated</color>");
             *  }
             *  else
             *  {
             *      tx = "<color=#F00>TextMesh is null</color> Please hit play if you hasn't";
             *      Debug.Log(tx);
             *  }
             * }
             */
            // ////////////////////////////////////////////////////////////

            if (SRP07CP.DrawOpaque)
            {
                // Draw opaque objects using BasicPass shader pass
                drawSettings.sorting.flags      = SortFlags.CommonOpaque;
                filterSettings.renderQueueRange = RenderQueueRange.opaque;
                context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

                for (int i = 0; i < shadowsSettings.Length; i++)
                {
                    //if(ls[i].light.shadows != LightShadows.None)
                    //context.DrawShadows(ref shadowsSettings[i]);
                }
            }

            if (SRP07CP.DrawTransparent)
            {
                // Draw transparent objects using BasicPass shader pass
                drawSettings.sorting.flags      = SortFlags.CommonTransparent;
                filterSettings.renderQueueRange = RenderQueueRange.transparent;
                context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
            }

            context.Submit();
        }
    }
Beispiel #17
0
    void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

        if (!CullResults.GetCullingParameters(camera, out cullingParameters))
        {
            return;
        }

#if UNITY_EDITOR
        if (camera.cameraType == CameraType.SceneView)
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif

        CullResults.Cull(ref cullingParameters, context, ref cull);

        context.SetupCameraProperties(camera);

        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget(
            (clearFlags & CameraClearFlags.Depth) != 0,
            (clearFlags & CameraClearFlags.Color) != 0,
            camera.backgroundColor
            );

        if (cull.visibleLights.Count > 0)
        {
            ConfigureLights();
        }
        else
        {
            cameraBuffer.SetGlobalVector(
                lightIndicesOffsetAndCountID, Vector4.zero
                );
        }

        cameraBuffer.BeginSample("Render Camera");
        cameraBuffer.SetGlobalVectorArray(
            visibleLightColorsId, visibleLightColors
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightAttenuationsId, visibleLightAttenuations
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightSpotDirectionsId, visibleLightSpotDirections
            );
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        var drawSettings = new DrawRendererSettings(
            camera, new ShaderPassName("SRPDefaultUnlit")
            )
        {
            flags = drawFlags
        };
        if (cull.visibleLights.Count > 0)
        {
            drawSettings.rendererConfiguration =
                RendererConfiguration.PerObjectLightIndices8;
        }
        drawSettings.sorting.flags = SortFlags.CommonOpaque;

        var filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.opaque
        };

        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        context.DrawSkybox(camera);

        drawSettings.sorting.flags      = SortFlags.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        DrawDefaultPipeline(context, camera);

        cameraBuffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        context.Submit();
    }
Beispiel #18
0
 protected override void Render(ScriptableRenderContext context, Camera[] cameras)
 {
     context.DrawSkybox(cameras[0]);
     context.Submit();
 }
Beispiel #19
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CameraData cameraData = renderingData.cameraData;
            Camera     camera     = cameraData.camera;

            if ((DebugHandler != null) && DebugHandler.IsActiveForCamera(ref cameraData))
            {
                // TODO: The skybox needs to work the same as the other shaders, but until it does we'll not render it
                // when certain debug modes are active (e.g. wireframe/overdraw modes)
                if (DebugHandler.IsScreenClearNeeded)
                {
                    return;
                }
            }

#if ENABLE_VR && ENABLE_XR_MODULE
            // XRTODO: Remove this code once Skybox pass is moved to SRP land.
            if (cameraData.xr.enabled)
            {
                // Setup Legacy XR buffer states
                if (cameraData.xr.singlePassEnabled)
                {
                    // Setup legacy skybox stereo buffer
                    camera.SetStereoProjectionMatrix(Camera.StereoscopicEye.Left, cameraData.GetProjectionMatrix(0));
                    camera.SetStereoViewMatrix(Camera.StereoscopicEye.Left, cameraData.GetViewMatrix(0));
                    camera.SetStereoProjectionMatrix(Camera.StereoscopicEye.Right, cameraData.GetProjectionMatrix(1));
                    camera.SetStereoViewMatrix(Camera.StereoscopicEye.Right, cameraData.GetViewMatrix(1));

                    CommandBuffer cmd = CommandBufferPool.Get();

                    // Use legacy stereo instancing mode to have legacy XR code path configured
                    cmd.SetSinglePassStereo(SystemInfo.supportsMultiview ? SinglePassStereoMode.Multiview : SinglePassStereoMode.Instancing);
                    context.ExecuteCommandBuffer(cmd);
                    cmd.Clear();

                    // Calling into built-in skybox pass
                    context.DrawSkybox(camera);

                    // Disable Legacy XR path
                    cmd.SetSinglePassStereo(SinglePassStereoMode.None);
                    context.ExecuteCommandBuffer(cmd);
                    // We do not need to submit here due to special handling of stereo matrices in core.
                    // context.Submit();
                    CommandBufferPool.Release(cmd);

                    camera.ResetStereoProjectionMatrices();
                    camera.ResetStereoViewMatrices();
                }
                else
                {
                    camera.projectionMatrix    = cameraData.GetProjectionMatrix(0);
                    camera.worldToCameraMatrix = cameraData.GetViewMatrix(0);

                    context.DrawSkybox(camera);

                    // XRTODO: remove this call because it creates issues with nested profiling scopes
                    // See examples in UniversalRenderPipeline.RenderSingleCamera() and in ScriptableRenderer.Execute()
                    context.Submit(); // Submit and execute the skybox pass before resetting the matrices

                    camera.ResetProjectionMatrix();
                    camera.ResetWorldToCameraMatrix();
                }
            }
            else
#endif
            {
                context.DrawSkybox(camera);
            }
        }
Beispiel #20
0
        protected void RenderCamera(ScriptableRenderContext context, Camera camera)
        {
            m_CameraRender.Render(context, camera);
            return;



            BeginCameraRendering(context, camera);
            if (camera.cameraType == CameraType.SceneView)
            {
                ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
            }


            //setup camera



            //culling
            ScriptableCullingParameters cullingParams;

            camera.TryGetCullingParameters(out cullingParams);
            //setup shadow
            cullingParams.shadowDistance = Mathf.Min(m_PipelineConfig.ShadowSetting.maxDistance, camera.farClipPlane);


#if UNITY_EDITOR
            if (camera.cameraType == CameraType.SceneView)
            {
                ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
            }
#endif

            CullingResults cullResult = context.Cull(ref cullingParams);

            SetupRenderContext(ref context, ref cullResult, camera);



#if UNITY_EDITOR
            RenderGizmo(context, camera, GizmoSubset.PreImageEffects);
#endif

            RenderShadow(ref m_RenderContext);

            context.SetupCameraProperties(camera);
            cmd.Clear();
            cmd.ClearRenderTarget(true, true, Color.clear);
            context.ExecuteCommandBuffer(cmd);
            context.Submit();
            RenderObject(context, camera, ref cullResult);

            //draw skybox
            context.DrawSkybox(camera);

#if UNITY_EDITOR
            RenderGizmo(context, camera, GizmoSubset.PostImageEffects);
#endif


            Cleanup(ref m_RenderContext);
            context.Submit();

            EndCameraRendering(context, camera);
        }
Beispiel #21
0
    /// <summary>
    /// 描画処理
    /// </summary>
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        for (int i = 0; i < cameras.Length; i++)
        {
            var camera        = cameras[i];
            var commandBuffer = commandBuffers[i];

            // カメラプロパティ設定
            context.SetupCameraProperties(camera);

            // カメラからカリングのための情報を取得
            if (!camera.TryGetCullingParameters(false, out var cullingParameters))
            {
                continue;
            }
            // ScriptableCullingParametersに基づいてカリングをスケジュール
            cullingResults = context.Cull(ref cullingParameters);

            // RenderTexture作成
            CreateRenderTexture(context, camera, commandBuffer);

            // モデル描画用RTのClear
            ClearModelRenderTexture(context, camera, commandBuffer);

            // ライト情報のセットアップ
            SetupLights(context, camera, commandBuffer);

            // 不透明オブジェクト描画
            DrawOpaque(context, camera, commandBuffer);

            // Skybox描画
            if (camera.clearFlags == CameraClearFlags.Skybox)
            {
                context.DrawSkybox(camera);
            }

            // 半透明オブジェクト描画
            DrawTransparent(context, camera, commandBuffer);

            // CameraTargetに描画
            RestoreCameraTarget(context, commandBuffer);

#if UNITY_EDITOR
            // Gizmo
            if (UnityEditor.Handles.ShouldRenderGizmos())
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            }
#endif

            // PostProcessing

#if UNITY_EDITOR
            // Gizmo
            if (UnityEditor.Handles.ShouldRenderGizmos())
            {
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
#endif

            // RenderTexture解放
            ReleaseRenderTexture(context, commandBuffer);
        }

        context.Submit();
    }
    private void RenderCamera(ref ScriptableRenderContext context, Camera camera)
    {
        if (m_ShadowMap == null)
        {
            m_ShadowMap      = new RenderTexture(1024, 1024, 24, RenderTextureFormat.Shadowmap);
            m_ShadowMap.name = "Shadow Map";
            m_ShadowMap.Create();
        }

        if (camera.TryGetCullingParameters(out ScriptableCullingParameters cullingParameters))
        {
            // Start camera render
            RenderPipeline.BeginCameraRendering(context, camera);

            cullingParameters.shadowDistance = 30;

            // Perform culling operations
            CullingResults cullingResults = context.Cull(ref cullingParameters);

            // Shadow map rendering
            Matrix4x4 worldToShadowMatrix = Matrix4x4.identity;
            bool      didRenderShadowMap  = RenderShadowMaps(ref context, ref cullingResults, ref worldToShadowMatrix);

            // Setup camera for rendering
            context.SetupCameraProperties(camera);

            // Clear camera
            CommandBuffer cb_ClearCamera = new CommandBuffer();
            cb_ClearCamera.name = "ClearCamera";
            cb_ClearCamera.SetRenderTarget(camera.targetTexture);
            cb_ClearCamera.ClearRenderTarget(true, true, camera.backgroundColor);
            context.ExecuteCommandBuffer(cb_ClearCamera);

            // Draw opaque objects
            SortingSettings sortSettings = new SortingSettings(camera);
            sortSettings.criteria = SortingCriteria.CommonOpaque;

            FilteringSettings filterSettings = FilteringSettings.defaultValue;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;

            if (didRenderShadowMap)
            {
                CommandBuffer cb = new CommandBuffer();
                cb.name = "Set up shadow shader properties";
                cb.SetGlobalTexture("_ShadowMapTexture", m_ShadowMap);
                cb.SetGlobalMatrix("_WorldToShadowMatrix", worldToShadowMatrix);
                cb.SetGlobalVector("_LightDirection", -cullingResults.visibleLights[0].light.transform.forward); // Direction towards the light
                context.ExecuteCommandBuffer(cb);
            }

            DrawingSettings opaqueDrawSettings = new DrawingSettings(s_OpaquePassTag, sortSettings);
            context.DrawRenderers(cullingResults, ref opaqueDrawSettings, ref filterSettings);

            // Draw skybox
            context.DrawSkybox(camera);

            // Final submission
            context.Submit();

            // End camera render
            RenderPipeline.EndCameraRendering(context, camera);
        }
    }
    public void Render(ScriptableRenderContext context, Camera camera)
    {
        if (!CullResults.GetCullingParameters(camera, out var cullingParameters))
        {
            return;
        }

        cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane);

#if UNITY_EDITOR
        if (camera.cameraType == CameraType.SceneView)
        {
            //将UI几何体发射到“场景”视图中以进行渲染。
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
        else if (mainCamera == null && camera.cameraType == CameraType.Game && camera == Camera.main)
        {
            mainCamera = camera;
        }
#endif

        //CullResults cull = CullResults.Cull(ref cullingParameters, context);
        CullResults.Cull(ref cullingParameters, context, ref cull);

        if (cull.visibleLights.Count > 0)
        {
            ConfigureLights();
            if (mainLightExists)
            {
                RenderCascadedShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            }

            if (shadowTileCount > 0)
            {
                RenderShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
            }
        }
        else
        {
            cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero);
            cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
        }

        context.SetupCameraProperties(camera);

        var myPipelineCamera = camera.GetComponent <MyPipelineCamera>();
        MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack;
        activeStack.Setup(postProcessingAsset);

        bool scaledRendering = renderScale != 1f && camera.cameraType == CameraType.Game;

        int renderWidth  = camera.pixelWidth;
        int renderHeight = camera.pixelHeight;
        if (scaledRendering)
        {
            renderWidth  = (int)(renderWidth * renderScale);
            renderHeight = (int)(renderHeight * renderScale);
        }

        int  renderSamples   = camera.allowMSAA ? msaaSamples : 1;
        bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack;

        bool needsDepth = activeStack && activeStack.NeedsDepth;
        //如果MSAA != 1 , 则 主贴图需要 24位深度 用来ZTestWrite画
        bool needsDirectDepth = needsDepth && renderSamples == 1;
        //专门用DepthOnly 来画深度图
        bool needsDepthOnlyPass = needsDepth && renderSamples > 1;

        RenderTextureFormat format =
            allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;

        if (renderToTexture)
        {
            //需要深度进行处理的的时候  要单独的深度图   不让它进行MSAA
            //否则可以跟随主颜色进行MSAA
            cameraBuffer.GetTemporaryRT(cameraColorTextureID, renderWidth, renderHeight, needsDirectDepth ? 0 : 24
                                        , FilterMode.Bilinear, format, RenderTextureReadWrite.Default, renderSamples);

            if (needsDepth)
            {
                cameraBuffer.GetTemporaryRT(cameraDepthTextureID, renderWidth, renderHeight, 24
                                            , FilterMode.Point, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear, 1);
            }

            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.DontCare,
                                             RenderBufferStoreAction.Store, cameraDepthTextureID, RenderBufferLoadAction.DontCare,
                                             RenderBufferStoreAction.Store);
            }
            else
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.DontCare,
                                             RenderBufferStoreAction.Store);
            }
        }


        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0
                                       , (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor);


        cameraBuffer.BeginSample("Render Camera");

        cameraBuffer.SetGlobalVectorArray(visibleLightColorsID, visibleLightColors);
        cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsID, visibleLightDirectionsOrPositions);
        cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsID, visibleLightAttenuations);
        cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsID, visibleLightSpotDirections);
        cameraBuffer.SetGlobalVectorArray(visibleLightOcclusionMaskID, visibleLightOcclusionMasks);

        globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y;
        cameraBuffer.SetGlobalVector(globalShadowDataID, globalShadowData);
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        //这样就可以走SRP的SubShader 如果没有则都走
        //Shader SubShader Tags{"RenderPipeline"="MySRPPipeline"}
        //Shader.globalRenderPipeline = "MySRPPipeline";

        //我们必须通过提供相机和一个shader pass 作为draw setting的构造函数的参数。
        //这个相机用来设置排序和裁剪层级(culling layers),
        //而shader pass 控制使用那个shader pass进行渲染。
        //如果Pass未指定LightMode,Unity会自动将其设置为SRPDefaultUnlit
        var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit"))
        {
            flags = drawFlags,
            rendererConfiguration = RendererConfiguration.None
        };
        if (cull.visibleLights.Count > 0)
        {
            drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8;
        }

        drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes
                                              | RendererConfiguration.PerObjectLightmaps
                                              | RendererConfiguration.PerObjectLightProbe
                                              | RendererConfiguration.PerObjectLightProbeProxyVolume
                                              | RendererConfiguration.PerObjectShadowMask
                                              | RendererConfiguration.PerObjectOcclusionProbe
                                              | RendererConfiguration.PerObjectOcclusionProbeProxyVolume;

        drawSettings.sorting.flags = SortFlags.CommonOpaque;
        //因为 Unity 更喜欢将对象空间化地分组以减少overdraw
        var filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.opaque
        };
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings);



        context.DrawSkybox(camera);


        //        var moonOnlyDrawSettings = new DrawRendererSettings(
        //            camera, new ShaderPassName("MoonOnly"))
        //        {
        //            flags = drawFlags,
        //            sorting = {flags = SortFlags.CommonOpaque}
        //        };
        //        context.DrawRenderers(cull.visibleRenderers, ref moonOnlyDrawSettings, filterSettings);
        //
        //        var moon1OnlyDrawSettings = new DrawRendererSettings(
        //            camera, new ShaderPassName("MoonOnly1"))
        //        {
        //            flags = drawFlags,
        //            sorting = { flags = SortFlags.CommonOpaque }
        //        };
        //        context.DrawRenderers(cull.visibleRenderers, ref moon1OnlyDrawSettings, filterSettings);


        if (activeStack)
        {
            postProcessingBuffer.BeginSample("Render Other Objects");

            if (activeStack.stencil)
            {
                drawSettings.SetShaderPassName(0, new ShaderPassName("SRPStencil"));
                drawSettings.sorting.flags      = SortFlags.CommonOpaque;
                filterSettings.renderQueueRange = RenderQueueRange.all;
                context.DrawRenderers(
                    cull.visibleRenderers, ref drawSettings, filterSettings);
                drawSettings.SetShaderPassName(0, new ShaderPassName("SRPDefaultUnlit"));
            }

            activeStack.DrawSky(postProcessingBuffer, camera);
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            activeStack.DrawDistantRainShafts(postProcessingBuffer, camera);
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            activeStack.DrawMoon(postProcessingBuffer, camera);
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            activeStack.DrawLightnings(postProcessingBuffer, camera);
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            postProcessingBuffer.EndSample("Render Other Objects");


            if (needsDepth)
            {
                if (needsDepthOnlyPass)
                {
                    var depthOnlyDrawSettings = new DrawRendererSettings(
                        camera, new ShaderPassName("DepthOnly"))
                    {
                        flags = drawFlags, sorting = { flags = SortFlags.CommonOpaque }
                    };


                    cameraBuffer.SetRenderTarget(cameraDepthTextureID, RenderBufferLoadAction.DontCare,
                                                 RenderBufferStoreAction.Store);
                    cameraBuffer.ClearRenderTarget(true, false, Color.clear);
                    context.ExecuteCommandBuffer(cameraBuffer);
                    cameraBuffer.Clear();
                    context.DrawRenderers(cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings);
                }
            }

            activeStack.RenderAfterOpaque(
                postProcessingBuffer, cameraColorTextureID, cameraDepthTextureID
                , renderWidth, renderHeight, renderSamples, format);
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store
                    , cameraDepthTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
            }
            else
            {
                cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.Load,
                                             RenderBufferStoreAction.Store);
            }



            context.ExecuteCommandBuffer(cameraBuffer);
            cameraBuffer.Clear();
        }


        drawSettings.sorting.flags      = SortFlags.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings);

        DrawDefaultPipeline(context, camera);

        if (renderToTexture)
        {
            if (activeStack && camera.cameraType == CameraType.Game)
            {
                activeStack.RenderAfterTransparent(postProcessingBuffer, cameraColorTextureID, cameraDepthTextureID
                                                   , renderWidth, renderHeight, renderSamples, format);
                context.ExecuteCommandBuffer(postProcessingBuffer);
                postProcessingBuffer.Clear();
            }
            else
            {
                cameraBuffer.Blit(cameraColorTextureID, BuiltinRenderTextureType.CameraTarget);
            }


            cameraBuffer.ReleaseTemporaryRT(cameraColorTextureID);
            if (needsDepth)
            {
                cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureID);
            }
        }

        cameraBuffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        context.Submit();

        if (shadowMap)
        {
            RenderTexture.ReleaseTemporary(shadowMap);
            shadowMap = null;
        }

        if (cascadedShadowMap)
        {
            RenderTexture.ReleaseTemporary(cascadedShadowMap);
            cascadedShadowMap = null;
        }
    }
    // Main entry point for our scriptable render loop

    public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, bool useIntermediateBlitPath)
    {
        bool stereoEnabled = XRSettings.isDeviceActive;

        foreach (var camera in cameras)
        {
            // Culling
            ScriptableCullingParameters cullingParams;
            // Stereo-aware culling parameters are configured to perform a single cull for both eyes
            if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams))
            {
                continue;
            }
            CullResults cull = new CullResults();
            CullResults.Cull(ref cullingParams, context, ref cull);

            // Setup camera for rendering (sets render target, view/projection matrices and other
            // per-camera built-in shader variables).
            // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets
            context.SetupCameraProperties(camera, stereoEnabled);

            // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine
            if (stereoEnabled)
            {
                context.StartMultiEye(camera);
            }

            RenderTargetIdentifier intermediateRTID = new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive);
            bool isIntermediateRTTexArray           = false;
            if (useIntermediateBlitPath)
            {
                ConfigureAndBindIntermediateRenderTarget(context, camera, stereoEnabled, out intermediateRTID, out isIntermediateRTTexArray);
            }

            // clear depth buffer
            var cmd = CommandBufferPool.Get();
            cmd.ClearRenderTarget(true, false, Color.black);
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);

            // Setup global lighting shader variables
            SetupLightShaderVariables(cull.visibleLights, context);

            // Draw opaque objects using BasicPass shader pass
            var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("BasicPass"))
            {
                sorting = { flags = SortFlags.CommonOpaque }
            };
            var filterSettings = new FilterRenderersSettings(true)
            {
                renderQueueRange = RenderQueueRange.opaque
            };
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

            // Draw skybox
            context.DrawSkybox(camera);

            // Draw transparent objects using BasicPass shader pass
            drawSettings.sorting.flags      = SortFlags.CommonTransparent;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

            if (useIntermediateBlitPath)
            {
                BlitFromIntermediateToCameraTarget(context, intermediateRTID, isIntermediateRTTexArray);
            }

            if (stereoEnabled)
            {
                context.StopMultiEye(camera);
                // StereoEndRender will reset state on the camera to pre-Stereo settings,
                // and invoke XR based events/callbacks.
                context.StereoEndRender(camera);
            }

            context.Submit();
        }
    }
Beispiel #25
0
        //完整的基本的兰伯特光照脚本
        protected void Render_mutil_light(ScriptableRenderContext renderContext, Camera[] cameras)
        {
            //渲染开始后,创建CommandBuffer;
            if (myCommandBuffer == null)
            {
                myCommandBuffer = new CommandBuffer()
                {
                    name = "SRP Study CB"
                }
            }
            ;

            //将shader中需要的属性参数映射为ID,加速传参
            var D_LightDir   = Shader.PropertyToID("_DLightDir");
            var D_LightColor = Shader.PropertyToID("_DLightColor");
            //在设置灯光参数ID下面增加相机参数ID:
            var _CameraPos = Shader.PropertyToID("_CameraPos");

            var _PLightPos   = Shader.PropertyToID("_PLightPos");
            var _PLightColor = Shader.PropertyToID("_PLightColor");

            //所有相机开始逐次渲染
            foreach (var camera in cameras)
            {
                myCommandBuffer.BeginSample("Render " + camera.name);

                //设置渲染相关相机参数,包含相机的各个矩阵和剪裁平面等
                renderContext.SetupCameraProperties(camera);


                //清理myCommandBuffer,设置渲染目标的颜色为摄像机背景
                var flags = camera.clearFlags;

                //myCommandBuffer.ClearRenderTarget(true,true,camera.backgroundColor);

                myCommandBuffer.ClearRenderTarget((flags & CameraClearFlags.Depth) != 0, (flags & CameraClearFlags.Color) != 0, camera.backgroundColor);

#if UNITY_EDITOR
                //为了在场景视图中看到UI
                //尽管Unity帮我们适配了UI在游戏窗口中显示,但不会在场景窗口显示。
                //UI始终存在于场景窗口中的世界空间中,但是我们必须手动将其注入场景中。
                //通过调用static ScriptableRenderContext.EmitWorldGeometryForSceneView方法(以当前摄像机为参数)来添加UI 。
                //必须在cull之前完成此操作。
                //为了避免游戏窗口中第二次添加UI。我们仅在渲染场景窗口时才发出UI几何。
                //cameraType相机的等于时就是这种情况CameraType.SceneView。
                if (camera.cameraType == CameraType.SceneView)
                {
                    ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
                }
#endif


                //剔除:拿到场景中的所有渲染器,然后剔除那些在摄像机视锥范围之外的渲染器。

                //渲染器:它是附着在游戏对象上的组件,可将它们转变为可以渲染的东西。通常是一个MeshRenderer组件。
                ScriptableCullingParameters cullParam = new ScriptableCullingParameters();
                camera.TryGetCullingParameters(out cullParam);
                cullParam.isOrthographic = false;

                //TODO:避免没有任何可渲染的物体时,往下渲染
                CullingResults cullResults = renderContext.Cull(ref cullParam);
                renderContext.DrawSkybox(camera);

                //在剪裁结果中获取灯光并进行参数获取
                var lights = cullResults.visibleLights;

                int dLightIndex = 0;
                int pLightIndex = 0;
                foreach (var light in lights)
                {
                    //判断灯光类型
                    if (light.lightType == LightType.Directional)
                    {
                        //在限定的灯光数量下,获取参数
                        if (dLightIndex < maxDirectionalLights)
                        {
                            //获取灯光参数,平行光朝向即为灯光Z轴方向。矩阵第一到三列分别为xyz轴项,第四列为位置。
                            Vector4 lightpos = light.localToWorldMatrix.GetColumn(2);
                            //这边获取的灯光的finalColor是灯光颜色乘上强度之后的值,也正好是shader需要的值
                            DLightColors[dLightIndex]       = light.finalColor;
                            DLightDirections[dLightIndex]   = -lightpos;
                            DLightDirections[dLightIndex].w = 0;//方向光的第四个值(W值)为0,点为1.
                            dLightIndex++;
                        }
                    }
                    else
                    {
                        if (light.lightType != LightType.Point)
                        {
                            //其他类型光源部分
                            continue;
                        }
                        else
                        {
                            if (pLightIndex < maxPointLights)
                            {
                                PLightColors[pLightIndex] = light.finalColor;
                                //将点光源的距离设置塞到颜色的A通道
                                PLightColors[pLightIndex].w = light.range;
                                //矩阵第4列为位置
                                PLightPos[pLightIndex] = light.localToWorldMatrix.GetColumn(3);
                                pLightIndex++;
                            }
                        }
                    }
                }

                //传入相机参数。注意是世界空间位置。
                Vector4 cameraPos = camera.transform.position;
                myCommandBuffer.SetGlobalVector(_CameraPos, cameraPos);

                //利用CommandBuffer进将灯光参数组传入Shader
                myCommandBuffer.SetGlobalVectorArray(D_LightColor, DLightColors);
                myCommandBuffer.SetGlobalVectorArray(D_LightDir, DLightDirections);


                myCommandBuffer.SetGlobalVectorArray(_PLightColor, PLightColors);
                myCommandBuffer.SetGlobalVectorArray(_PLightPos, PLightPos);
                myCommandBuffer.EndSample("Render " + camera.name);
                //执行CommandBuffer中的指令
                renderContext.ExecuteCommandBuffer(myCommandBuffer);

                myCommandBuffer.Clear();

                //过滤:决定使用哪些渲染器
                FilteringSettings filtSet = new FilteringSettings(RenderQueueRange.opaque, -1);
                //filtSet.renderQueueRange = RenderQueueRange.opaque;
                //filtSet.layerMask = -1;


                //相机用于设置排序和剔除层,而DrawingSettings控制使用哪个着色器过程进行渲染。

                //决定使用何种渲染排序顺序 对应shader里的	Tags{ "Queue" = "Geometry" } 这属性(不是这个单一属性)
                //opaque涵盖了从0到2500(包括2500)之间的渲染队列。
                SortingSettings sortSet = new SortingSettings(camera)
                {
                    criteria = SortingCriteria.CommonOpaque
                };
                //决定使用何种light mode,对应shader的pass的tag中的LightMode
                DrawingSettings drawSet = new DrawingSettings(new ShaderTagId("BaseLit"), sortSet);


                //1.绘制不透明物体
                renderContext.DrawRenderers(cullResults, ref drawSet, ref filtSet);

                //2.绘制天空球,在不透明物体之后绘制。early-z避免不必要的overdraw。
                renderContext.DrawSkybox(camera);



                //3.绘制透明物体
                //,RenderQueueRange.transparent在渲染天空盒之后,将队列范围更改为从2501到5000,包括5000,然后再次渲染。
                filtSet.renderQueueRange = RenderQueueRange.transparent;
                sortSet.criteria         = SortingCriteria.CommonTransparent;
                //由于我们仅在管道中支持未照明的材质,因此我们将使用Unity的默认未照明通道,该通道由SRPDefaultUnlit标识。
                drawSet = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), sortSet);
                renderContext.DrawRenderers(cullResults, ref drawSet, ref filtSet);

                //绘制错误
                //由于我们的管道仅支持未着色的着色器,因此不会渲染使用不同着色器的对象,从而使它们不可见。尽管这是正确的,
                //但它掩盖了某些对象使用错误着色器的事实。如果我们使用Unity的错误着色器可视化这些对象,那将是很好的,
                //因此它们显示为明显不正确的洋红色形状。让我们DrawDefaultPipeline为此添加一个专用方法,其中包含一个上下文和一个camera参数。
                //在绘制透明形状之后,我们将在最后调用它。
                DrawErrorShaderObject(cullResults, renderContext, camera);


                //开始执行渲染内容
                renderContext.Submit();
            }
        }

        RenderTexture shadowMap;
        //void RenderShadows(ScriptableRenderContext context)
        //{
        //    shadowMap = RenderTexture.GetTemporary(512, 512, 16, RenderTextureFormat.Shadowmap);
        //    shadowMap.filterMode = FilterMode.Bilinear;
        //    shadowMap.wrapMode = TextureWrapMode.Clamp;
        //    CoreUtils.SetRenderTarget(shadowBuffer, shadowMap, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Depth);
        //    shadowBuffer.BeginSample("Render Shadows");
        //    context.ExecuteCommandBuffer(shadowBuffer);
        //    shadowBuffer.Clear();


        //    shadowBuffer.EndSample("Render shadows");
        //    context.ExecuteCommandBuffer(shadowBuffer);
        //    shadowBuffer.Clear();
        //}
    }
    void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

        if (!CullResults.GetCullingParameters(camera, out cullingParameters))
        {
            return;
        }

#if UNITY_EDITOR
        if (camera.cameraType == CameraType.SceneView)
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif

        CullResults.Cull(ref cullingParameters, context, ref cull);

        context.SetupCameraProperties(camera);

        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget(
            (clearFlags & CameraClearFlags.Depth) != 0,
            (clearFlags & CameraClearFlags.Color) != 0,
            camera.backgroundColor
            );

        cameraBuffer.BeginSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        var drawSettings = new DrawRendererSettings(
            camera, new ShaderPassName("SRPDefaultUnlit")
            );
        drawSettings.flags         = drawFlags;
        drawSettings.sorting.flags = SortFlags.CommonOpaque;

        var filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.opaque
        };

        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        context.DrawSkybox(camera);

        drawSettings.sorting.flags      = SortFlags.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        DrawDefaultPipeline(context, camera);

        cameraBuffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        context.Submit();
    }
Beispiel #27
0
    private static readonly ShaderPassName m_UnlitPassName = new ShaderPassName("SRPDefaultUnlit"); //For default shaders

    public static void Render(ScriptableRenderContext context, Camera[] cameras, SRP02CustomParameter SRP02CP)
    {
        RenderPipeline.BeginFrameRendering(cameras);

        foreach (Camera camera in cameras)
        {
            RenderPipeline.BeginCameraRendering(camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!CullResults.GetCullingParameters(camera, out cullingParams))
            {
                continue;
            }
            CullResults cull = new CullResults();
            CullResults.Cull(ref cullingParams, context, ref cull);

            context.SetupCameraProperties(camera);

            if (camera.renderingPath == RenderingPath.UsePlayerSettings)
            {
                // clear depth buffer
                CommandBuffer cmd = new CommandBuffer();
                cmd.ClearRenderTarget(true, !SRP02CP.DrawSkybox, SRP02CP.ClearColor);
                context.ExecuteCommandBuffer(cmd);
                cmd.Release();

                // Setup global lighting shader variables
                //SetupLightShaderVariables(cull.visibleLights, context);

                // Setup DrawSettings and FilterSettings
                ShaderPassName          passName       = new ShaderPassName("BasicPass");
                DrawRendererSettings    drawSettings   = new DrawRendererSettings(camera, passName);
                FilterRenderersSettings filterSettings = new FilterRenderersSettings(true);

                //Draw passes that has no light mode (default)
                ShaderPassName       passNameDefault     = new ShaderPassName("");
                DrawRendererSettings drawSettingsDefault = new DrawRendererSettings(camera, passNameDefault);
                drawSettingsDefault.SetShaderPassName(1, m_UnlitPassName);

                if (SRP02CP.DrawSkybox)
                {
                    context.DrawSkybox(camera);
                }

                if (SRP02CP.DrawOpaque)
                {
                    drawSettings.sorting.flags      = SortFlags.CommonOpaque;
                    filterSettings.renderQueueRange = RenderQueueRange.opaque;
                    context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
                }

                // Default
                drawSettingsDefault.sorting.flags = SortFlags.CommonOpaque;
                context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings);

                if (SRP02CP.DrawTransparent)
                {
                    drawSettings.sorting.flags      = SortFlags.CommonTransparent;
                    filterSettings.renderQueueRange = RenderQueueRange.transparent;
                    context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
                }

                // Default
                drawSettingsDefault.sorting.flags = SortFlags.CommonTransparent;
                context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings);
            }

            context.Submit();
        }
    }
    private void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

        if (!camera.TryGetCullingParameters(false, out cullingParameters))
        {
            return;
        }


        GraphicsSettings.lightsUseLinearIntensity = true;

        _cameraBuffer = CommandBufferPool.Get(camera.name);

        context.SetupCameraProperties(camera);
        CameraClearFlags clearFlags = camera.clearFlags;

        _cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor, 1.0f);

#if UNITY_EDITOR
        ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
#endif

        var cullingResult = context.Cull(ref cullingParameters);


        SetupCameraClusters(camera);
        UpdateLightBuffer(cullingResult);
        LightCulling(camera);
        //context.ExecuteCommandBuffer(cameraBuffer);
        //cameraBuffer.Clear();

        //SetupLights(cullingResult);

        //cameraBuffer.BeginSample("Render Camera");
        if (camera.cameraType == CameraType.SceneView)
        {
            //debugClusterRendering();
            //context.ExecuteCommandBuffer(cameraBuffer);
            //cameraBuffer.Clear();
        }

        //cameraBuffer.SetGlobalVectorArray(shaderVisibleLightColorsId, visibleLightColors);
        //cameraBuffer.SetGlobalVectorArray(shaderVisibleLightDirectionsId, visibleLightDirections);
        _ClusterXCount = Mathf.CeilToInt((float)Screen.width / clusterWidth);
        _ClusterYCount = Mathf.CeilToInt((float)Screen.height / clusterHeight);

        _cameraBuffer.SetGlobalBuffer("g_lights", _LightBuffer);
        _cameraBuffer.SetGlobalBuffer("g_lightIndexList", g_lightIndexList);
        _cameraBuffer.SetGlobalBuffer("g_lightGrid", g_lightGrid);
        _cameraBuffer.SetGlobalVector("clusterSize", new Vector2(clusterWidth, (float)clusterHeight));
        _cameraBuffer.SetGlobalVector("cb_clusterCount", new Vector3(_ClusterXCount, _ClusterYCount, clusterZCount));
        _cameraBuffer.SetGlobalVector("cb_clusterSize", new Vector3(clusterWidth, clusterHeight, Mathf.CeilToInt((camera.farClipPlane - camera.nearClipPlane) / clusterZCount)));
        _cameraBuffer.SetGlobalVector("cb_screenSize", new Vector4(Screen.width, Screen.height, 1.0f / Screen.width, 1.0f / Screen.height));


        context.ExecuteCommandBuffer(_cameraBuffer);
        _cameraBuffer.Clear();
        //cameraBuffer.EndSample("Render Camera");

        var drawSettings = new DrawingSettings(new ShaderTagId("ForwardLit"), new SortingSettings(camera)
        {
            criteria = SortingCriteria.QuantizedFrontToBack,
        });

        //drawSettings.enableInstancing = true;
        //drawSettings.perObjectData = PerObjectData.LightIndices;

        var filterSettings = new FilteringSettings(RenderQueueRange.opaque);
        context.DrawRenderers(cullingResult, ref drawSettings, ref filterSettings);


        context.DrawSkybox(camera);
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(cullingResult, ref drawSettings, ref filterSettings);

        if (camera.cameraType == CameraType.SceneView)
        {
            context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
        }

        context.Submit();
    }
Beispiel #29
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(cameras);

        foreach (Camera camera in cameras)
        {
            #if UNITY_EDITOR
            bool isSceneViewCam = camera.cameraType == CameraType.SceneView;
            if (isSceneViewCam)
            {
                ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);                //This makes the UI Canvas geometry appear on scene view
            }
            #endif

            BeginCameraRendering(camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //Setup DrawSettings and FilterSettings
            var               sortingSettings = new SortingSettings(camera);
            DrawingSettings   drawSettings    = new DrawingSettings(m_PassName, sortingSettings);
            FilteringSettings filterSettings  = new FilteringSettings(RenderQueueRange.all);

            //Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            cmd.name = "Cam:" + camera.name + " ClearFlag";
            cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //Skybox
            if (drawSkyBox)
            {
                context.DrawSkybox(camera);
            }

            //Opaque objects
            sortingSettings.criteria        = SortingCriteria.CommonOpaque;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //Transparent objects
            sortingSettings.criteria        = SortingCriteria.CommonTransparent;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //SceneView fix, so that it draws the gizmos on scene view
            #if UNITY_EDITOR
            if (isSceneViewCam)
            {
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
            #endif

            context.Submit();
        }
    }
Beispiel #30
0
    void Render(ScriptableRenderContext context, Camera camera)
    {
        // 剔除参数
        ScriptableCullingParameters cullingParameters;

        // 获取剔除参数
        if (!CullResults.GetCullingParameters(camera, out cullingParameters))
        {
            // 如果相机设定非法,直接返回
            return;
        }

        // 设置阴影参数
        cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane);

        // 仅在编辑模式下
#if UNITY_EDITOR
        // 仅在渲染场景视图时。否则游戏视图中的UI元素会被渲染两次
        if (camera.cameraType == CameraType.SceneView)
        {
            // 当canvas的渲染被设置在世界空间时,UI元素不会出现在场景视图中
            // 需要手动指定以使其正确显示
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif

        // 剔除
        CullResults.Cull(ref cullingParameters, context, ref cull);

        if (cull.visibleLights.Count > 0)
        {
            ConfigureLights();

            if (mainLightExists)
            {
                RenderCascadedShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            }

            if (shadowTileCount > 0)
            {
                RenderShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
            }
        }
        else
        {
            // 由于该值会被保留为上一个物体使用的值,因此需要手动设置
            cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero);

            cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
        }

        // 设置unity_MatrixVP,以及一些其他属性
        context.SetupCameraProperties(camera);

        // 获取摄像机的定制后处理栈
        var myPipelineCamera = camera.GetComponent <MyPipelineCamera>();
        MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack;

        // 只影响游戏摄像机
        bool scaledRendering = (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game;

        int renderWidth  = camera.pixelWidth;
        int renderHeight = camera.pixelHeight;
        if (scaledRendering)
        {
            renderWidth  = (int)(renderWidth * renderScale);
            renderHeight = (int)(renderHeight * renderScale);
        }

        // 摄像机是否开启MSAA
        int renderSamples = camera.allowMSAA ? msaaSamples : 1;

        // 开启渲染到纹理
        bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack;

        // 是否需要深度纹理(深度纹理不支持MSAA)
        bool needsDepth         = activeStack && activeStack.NeedsDepth;
        bool needsDirectDepth   = needsDepth && renderSamples == 1;       // 不使用MSAA
        bool needsDepthOnlyPass = needsDepth && renderSamples > 1;        // 使用MSAA、

        // 纹理格式
        RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;

        // 获取并设置渲染目标,用于后处理
        if (renderToTexture)
        {
            cameraBuffer.GetTemporaryRT(
                cameraColorTextureId, renderWidth, renderHeight, needsDirectDepth ? 0 : 24,
                FilterMode.Bilinear, format,
                RenderTextureReadWrite.Default, renderSamples
                );
            if (needsDepth)
            {
                cameraBuffer.GetTemporaryRT(
                    cameraDepthTextureId, renderWidth, renderHeight, 24,
                    FilterMode.Point, RenderTextureFormat.Depth,
                    RenderTextureReadWrite.Linear, 1                     // 1表示不使用MSAA
                    );
            }
            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
                    cameraDepthTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store
                    );
            }
            else
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store
                    );
            }
        }

        // 清空
        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor);

        // 设置采样标志,用于在Frame Debugger中组织结构
        cameraBuffer.BeginSample("HY Render Camera");

        // 设置光数据
        cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors);
        cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions);
        cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visibleLightAttenuations);
        cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsId, visibleLightSpotDirections);

        // 执行指令缓冲。这并不会立即执行指令,只是将指令拷贝到上下文的内部缓冲中
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        // 绘制设定
        // camera参数设定排序和剔除层,pass参数指定使用哪一个shader pass
        var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit"))
        {
            flags = drawFlags
        };
        // 仅在有可见光时设置,否则Unity会崩溃
        if (cull.visibleLights.Count > 0)
        {
            // 指定Unity为每个物体传输光索引数据
            drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8;
        }
        // 指定使用反射探针,如果场景中没有反射探针,则使用天空球的立方体贴图
        drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps;
        // 指定排序,从前往后
        drawSettings.sorting.flags = SortFlags.CommonOpaque;

        // 过滤设定
        // true表示包括所有物体
        var filterSettings = new FilterRenderersSettings(true)
        {
            // 绘制不透明物体,渲染队列为[0,2500]
            renderQueueRange = RenderQueueRange.opaque
        };

        context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

        // 绘制天空盒
        // camera参数仅用来判断是否绘制天空盒(根据camera的清空标志位)
        context.DrawSkybox(camera);

        // 后处理
        if (activeStack)
        {
            // depth-only pass
            if (needsDepthOnlyPass)
            {
                var depthOnlyDrawSettings = new DrawRendererSettings(
                    camera, new ShaderPassName("DepthOnly")
                    )
                {
                    flags = drawFlags
                };
                depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque;
                cameraBuffer.SetRenderTarget(
                    cameraDepthTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store
                    );
                cameraBuffer.ClearRenderTarget(true, false, Color.clear);
                context.ExecuteCommandBuffer(cameraBuffer);
                cameraBuffer.Clear();
                context.DrawRenderers(
                    cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings
                    );
            }

            activeStack.RenderAfterOpaque(
                postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId,
                renderWidth, renderHeight, renderSamples, format
                );
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                    cameraDepthTextureId,
                    RenderBufferLoadAction.Load, RenderBufferStoreAction.Store
                    );
            }
            else
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.Load, RenderBufferStoreAction.Store
                    );
            }
            context.ExecuteCommandBuffer(cameraBuffer);
            cameraBuffer.Clear();
        }

        // 指定排序,从后往前
        drawSettings.sorting.flags = SortFlags.CommonTransparent;
        // 绘制透明物体,渲染队列为[2501,5000]
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

        DrawDefaultPipeline(context, camera);

        // 后处理
        if (renderToTexture)
        {
            if (activeStack)
            {
                activeStack.RenderAfterTransparent(
                    postProcessingBuffer, cameraColorTextureId,
                    cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format
                    );
                context.ExecuteCommandBuffer(postProcessingBuffer);
                postProcessingBuffer.Clear();
            }
            else
            {
                cameraBuffer.Blit(
                    cameraColorTextureId, BuiltinRenderTextureType.CameraTarget
                    );
            }
            cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId);
            if (needsDepth)
            {
                cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId);
            }
        }

        cameraBuffer.EndSample("HY Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        // 提交指令
        context.Submit();

        // 释放阴影纹理
        if (shadowMap)
        {
            RenderTexture.ReleaseTemporary(shadowMap);
            shadowMap = null;
        }

        // 释放层级阴影纹理
        if (cascadedShadowMap)
        {
            RenderTexture.ReleaseTemporary(cascadedShadowMap);
            cascadedShadowMap = null;
        }
    }