Exemple #1
0
 void DrawGizmos(ScriptableRenderContext context, Camera camera)
 {
     if (Handles.ShouldRenderGizmos())
     {
         context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
         context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
     }
 }
 private void DrawGizmos() // ?? nothing happened, do not call this methods also has gizmos
 {
     if (Handles.ShouldRenderGizmos())
     {
         renderContext.DrawGizmos(camera, GizmoSubset.PreImageEffects);
         renderContext.DrawGizmos(camera, GizmoSubset.PostImageEffects);
     }
 }
Exemple #3
0
 void RenderGizmo(ScriptableRenderContext context, Camera camera, GizmoSubset type)
 {
     if (Handles.ShouldRenderGizmos() || camera.cameraType == CameraType.SceneView)
     {
         context.DrawGizmos(camera, type);
         context.DrawGizmos(camera, type);
     }
 }
 /// <summary>
 /// 绘制相机空间
 /// </summary>
 protected void drawGizmos()
 {
     if (Handles.ShouldRenderGizmos())
     {
         m_context.DrawGizmos(m_camera, GizmoSubset.PreImageEffects);
         m_context.DrawGizmos(m_camera, GizmoSubset.PostImageEffects);
     }
 }
 private void DrawGizmos()
 {
     if (Handles.ShouldRenderGizmos())
     {
         renderContext.DrawGizmos(camera, GizmoSubset.PreImageEffects);
         renderContext.DrawGizmos(camera, GizmoSubset.PostImageEffects);
     }
 }
        /// <summary>
        /// 绘制相机Gizmos
        /// </summary>
        /// <param name="context"></param>
        /// <param name="camera"></param>
        private void DrawGizmos(ScriptableRenderContext context, Camera camera)
        {
#if UNITY_EDITOR
            if (UnityEditor.Handles.ShouldRenderGizmos())
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
#endif
        }
Exemple #7
0
    void DefaultRenderFlow(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

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

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

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

        CmdBuff.BeginSample(camera.name);

        cullingResults = context.Cull(ref cullingParameters);

        SetShadow(context, camera);

        SetCamera(context, camera);

        ClearRenderBuffer(context, camera);

        SetLighting(context, camera);

        DrawDepthOnly(context, camera);

        DrawOpaque(context, camera);

        DrawSky(context, camera);

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

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

        CmdBuff.EndSample(camera.name);
        context.ExecuteCommandBuffer(CmdBuff);
        CmdBuff.Clear();
    }
Exemple #8
0
        private void PostProcessingRendering(ScriptableRenderContext context, Camera camera, PostProcessLayer ppLayer)
        {
            var cullResults = context.Cull(ref _cullParam);

            context.SetupCameraProperties(camera);

            var cmdBuf = CommandBufferPool.Get(_ppRenderCmdName);

            cmdBuf.GetTemporaryRT(_colorNameId, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32);
            cmdBuf.GetTemporaryRT(_depthNameId, camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            cmdBuf.SetRenderTarget(
                _colorNameId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                _depthNameId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
            cmdBuf.ClearRenderTarget(true, true, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            context.DrawRenderers(cullResults, ref _opaqueDrawing, ref _opaqueFiltering);
            context.DrawRenderers(cullResults, ref _transparentDrawing, ref _transparentFiltering);
#if UNITY_EDITOR
            if (CameraType.SceneView == camera.cameraType)
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
#endif

            _ppContext.Reset();
            _ppContext.camera       = camera;
            _ppContext.source       = _colorNameId;
            _ppContext.sourceFormat = RenderTextureFormat.ARGB32;
            _ppContext.destination  = BuiltinRenderTextureType.CameraTarget;
            _ppContext.command      = cmdBuf;
            _ppContext.flip         = true;
            ppLayer.Render(_ppContext);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            cmdBuf.ReleaseTemporaryRT(_colorNameId);
            cmdBuf.ReleaseTemporaryRT(_depthNameId);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            context.Submit();
        }
Exemple #9
0
        private void DrawGizmos(bool isBeforePostProcessing) // ?? nothing happened, do not call this methods also has gizmos
        {
            if (UnityEditor.Handles.ShouldRenderGizmos() == false)
            {
                return;
            }

            if (isBeforePostProcessing)
            {
                renderContext.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            }

            else
            {
                renderContext.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
        }
Exemple #10
0
    void RenderGizmos(ScriptableRenderContext renderContext, Camera camera, GizmoSubset gizmoSubset)
    {
#if UNITY_EDITOR
        if (UnityEditor.Handles.ShouldRenderGizmos())
        {
            renderContext.DrawGizmos(camera, gizmoSubset);
        }
#endif
    }
        protected virtual void RenderCamera(ScriptableRenderContext context, Camera camera)
        {
            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 renderingData = new RenderingData()
            {
                camera      = camera,
                cullResults = cullResults
            };

            context.SetupCameraProperties(camera, false);

            InitRenderQueue();

            context.DrawSkybox(camera);

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

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

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
            context.Submit();
        }
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            Camera camera = renderingData.cameraData.camera;

            if (Handles.ShouldRenderGizmos())
            {
                context.DrawGizmos(camera, this.renderLitGizmos ? GizmoSubset.PreImageEffects : GizmoSubset.PostImageEffects);
            }
#endif
        }
Exemple #13
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        context.InvokeOnRenderObjectCallback();

        BeginFrameRendering(context, cameras);

        _positionBufferPool.Swap();
        _colorBufferPool.Swap();

        foreach (var camera in cameras)
        {
            Profiler.BeginSample("Camera " + camera.name);
            context.SetupCameraProperties(camera);
            Render(context, camera);
            context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            Profiler.EndSample();
        }

        context.Submit();

        EndFrameRendering(context, cameras);
    }
        private void DrawCamera(ScriptableRenderContext context, Camera camera)
        {
            BeginCameraRendering(context, camera);
            context.SetupCameraProperties(camera);

            if (camera.cameraType != CameraType.SceneView)
            {
                DrawGameView(context, camera);
            }
            else
            {
                DrawSceneView(context, camera);
            }

#if UNITY_EDITOR
            if (UnityEditor.Handles.ShouldRenderGizmos())
            {
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            }
#endif
            EndCameraRendering(context, camera);
        }
Exemple #15
0
        private void NormalRendering(ScriptableRenderContext context, Camera camera)
        {
            var cullResults = context.Cull(ref _cullParam);

            context.SetupCameraProperties(camera);

            var cmdBuf = CommandBufferPool.Get(_normalCmdName);

            cmdBuf.ClearRenderTarget(true, false, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            context.DrawRenderers(cullResults, ref _opaqueDrawing, ref _opaqueFiltering);
            context.DrawRenderers(cullResults, ref _transparentDrawing, ref _transparentFiltering);
#if UNITY_EDITOR
            if (CameraType.SceneView == camera.cameraType)
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
#endif

            context.Submit();
        }
Exemple #16
0
        private void RayTrace()
        {
            _commandBuffer.Clear();

            var cameraTextureId        = new RenderTargetIdentifier(_camera.targetTexture);
            var cameraInstanceId       = _camera.GetInstanceID();
            var cameraInstanceIdHandle = GCHandle.Alloc(cameraInstanceId, GCHandleType.Pinned);

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

            string sampleName = "Trace rays";
            _commandBuffer.BeginSample(sampleName);
            _commandBuffer.IssuePluginEventAndData(PixelsForGlory.RayTracing.RayTracingPlugin.GetEventAndDataFunc(), (int)Events.TraceRays, cameraInstanceIdHandle.AddrOfPinnedObject());
            _commandBuffer.Blit(_targets[_camera.GetInstanceID()], cameraTextureId);
            _commandBuffer.EndSample(sampleName);

            _context.ExecuteCommandBuffer(_commandBuffer);

    #if UNITY_EDITOR
            if (_camera.cameraType == CameraType.SceneView)
            {
                _context.DrawGizmos(_camera, GizmoSubset.PreImageEffects);
                _context.DrawGizmos(_camera, GizmoSubset.PostImageEffects);
            }
    #endif
            _context.Submit();

            _commandBuffer.Clear();

            cameraInstanceIdHandle.Free();
        }
Exemple #17
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilingSampler.name);
            using (new ProfilingScope(cmd, m_ProfilingSampler))
            {
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();

                if (UnityEditor.Handles.ShouldRenderGizmos())
                {
                    context.DrawGizmos(renderingData.cameraData.camera, m_gizmoSubset);
                }
            }

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();
            CommandBufferPool.Release(cmd);
#endif
        }
Exemple #18
0
    //
    // <comment>
    // 本ソースでは流れを分かりやすくするため、描画関数のみにしてあります
    // 各処理はlbRenderPipelineInstance_sub.csを参照ください!
    //
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        // カメラごとに処理
        foreach (var camera in cameras)
        {
            // コマンドバッファを用意
            CommandBuffer cb = new CommandBuffer();

            //
            // <comment>
            // カメラプロパティ設定です
            // ここは定型文的な感じになるかと思います
            //
            context.SetupCameraProperties(camera);

            //
            // <comment>
            // カリング処理を行います
            // ここは定型文的な感じになるかと思います
            //
            {
                cullResults = new CullingResults();
                ScriptableCullingParameters cullingParameters;
                if (!camera.TryGetCullingParameters(false, out cullingParameters))
                {
                    continue;
                }

                cullingParameters.shadowDistance = Mathf.Min(20.0f, camera.farClipPlane);                               // シャドウの為の仮措置

                cullResults = context.Cull(ref cullingParameters);
            }

            //
            // <comment>
            // 各種RenderTextureを用意します
            // camera.TargetTextureには直接書き込まず、これらのRenderTextureに書いてから最終的にコピーするだけです
            //
            CreateRenderTexture(context, camera, cb);

            //
            // <comment>
            // シャドウマップのセットアップを行います
            // 講演でもお話しした投影テクスチャシャドウを行うため、R8バッファで作成しています
            //
            SetupShadowMap(context, camera, cb);

            //
            // <comment>
            // 講演内では省きましたが、カメラクリア処理をしないと絵が描けません
            //
            ClearModelRenderTexture(context, camera, cb);

            //
            // <comment>
            // ライトのセットアップを行います
            // 今回は適当な平行光源を1つのみで行います
            //
            SetupLights(context, camera, cb);

            //
            // <comment>
            // 不透明描画部分です
            // 3Dモデル用RenderTextureに不透明部分だけ書き込みます
            //
            DrawOpaque(context, camera, cb);

            //
            // <comment>
            // 最後の不透明であるSkyboxを書き込みます
            //
            if (camera.clearFlags == CameraClearFlags.Skybox)
            {
                context.DrawSkybox(camera);
            }

            //
            // <comment>
            // 今回のキモとなるブレンドバッファ描画
            // 小さめのバッファを用意しそこにパーティクルを書きます
            //
            DrawBlendBuffer(context, camera, cb);

            //
            // <comment>
            // パーティクル以外の半透明の描画部分です
            // 今回のシーンでは該当部分が無いので動作未確認です
            //
            DrawTransparent(context, camera, cb);

            //
            // <comment>
            // ここで一通りの絵が書けたので、camera.targetTextureにフィードバックします
            //
            RestoreCameraTarget(context, cb);

#if     UNITY_EDITOR
            //
            // <comment>
            // Gizmo描画その1です
            // イメージエフェクト前に描かないといけないものが該当するらしいです
            // (調査あまり出来ていません)
            //
            if (UnityEditor.Handles.ShouldRenderGizmos())                       // ←この判定をしないとGameビューでも描かれてしまう!
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            }
#endif

            //
            // <comment>
            // ここにポストフィルタの処理が挟まることになると思います
            //

#if     UNITY_EDITOR
            //
            // <comment>
            // Gizmo描画その1です
            // イメージエフェクト後に描かないといけないものが該当するらしいです
            // (調査あまり出来ていません)
            //
            if (UnityEditor.Handles.ShouldRenderGizmos())                       // ←この判定をしないとGameビューでも描かれてしまう!
            {
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
#endif

            //
            // <comment>
            // UIを描画します
            // 講演でお話しした通り、デフォルトUIシェーダも使えるようになっているはず
            // (ただSceneビューではなぜか表示されず。。LWRPでは出るのに。。)
            //
            // あとCanvasが「Screen Space - Overlay」のものはここでは書かれません
            // SRPで処理せず、全く別のところで描かれるようです
            //
            DrawUI(context, camera, cb);

            //
            // <comment>
            // 利用したRenderTextureを破棄します
            //
            ReleaseRenderTexture(context, cb);
        }

        // コンテキストのサブミット
        context.Submit();
    }
    private void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

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

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

        CullingResults cullResults = context.Cull(ref cullingParameters);

        context.SetupCameraProperties(camera, false);

        //建立RenderTexture,並指定其為RenderTarget
        RenderTextureDescriptor descriptor = CreateRenderTextureDescriptor(camera);

        if (_cameraColorAttachment.id == -1)
        {
            _cameraColorAttachment.Init("_CameraColorTexture");
        }

        cameraBuffer.GetTemporaryRT(_cameraColorAttachment.id,
                                    descriptor, FilterMode.Bilinear);

        RenderTargetIdentifier colorIdentifiy = _cameraColorAttachment.Identifier();

        cameraBuffer.SetRenderTarget(colorIdentifiy,
                                     RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);

        cameraBuffer.ClearRenderTarget(true, true, Color.clear);
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        SortingSettings sortingSettings = new SortingSettings(camera)
        {
            criteria = SortingCriteria.CommonOpaque
        };

        var drawSettings = new DrawingSettings(
            new ShaderTagId("SRPDefaultUnlit"), sortingSettings
            );

        var filterSettings = new FilteringSettings(RenderQueueRange.opaque);

        context.DrawRenderers(
            cullResults, ref drawSettings, ref filterSettings
            );
        _debugRTProcessor.Add(ref context, ref colorIdentifiy);

        context.DrawSkybox(camera);
        _debugRTProcessor.Add(ref context, ref colorIdentifiy);

        sortingSettings.criteria        = SortingCriteria.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(
            cullResults, ref drawSettings, ref filterSettings
            );
        _debugRTProcessor.Add(ref context, ref colorIdentifiy);

        //畫在後置特效之前的Gizmos
#if UNITY_EDITOR
        if (UnityEditor.Handles.ShouldRenderGizmos())
        {
            context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
        }
#endif
        //後置特效處理,在這裡做…

        //final blit to frame buffer(將目前的RenderTextures的結果
        //,用一個Quad畫回FrameBuffer
        if (camera.cameraType == CameraType.Game)
        {
            cameraBuffer.SetGlobalTexture("_BlitTex", colorIdentifiy);
            cameraBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget,
                                         RenderBufferLoadAction.DontCare,
                                         RenderBufferStoreAction.Store);
            cameraBuffer.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
            cameraBuffer.SetViewport(camera.pixelRect);
            cameraBuffer.DrawMesh(fullscreenMesh, Matrix4x4.identity, blitMaterial);
        }
        else
        {
            //因為工具的Camera是指向一個RenderTexture,要直接blitting過去,
            //否則會導致,Gizmos畫不出來。
            cameraBuffer.Blit(colorIdentifiy, BuiltinRenderTextureType.CameraTarget);
        }
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        //釋放RenderTexture
        cameraBuffer.ReleaseTemporaryRT(_cameraColorAttachment.id);
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        //畫在後置特效之後的Gizmos
#if UNITY_EDITOR
        if (UnityEditor.Handles.ShouldRenderGizmos())
        {
            context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
        }
#endif

        _debugRTProcessor.Render(ref context, camera, blitMaterial);
        context.Submit();
    }
Exemple #20
0
        private void RenderingContent(bool isSceneViewCam, Camera RenderCamera, CullingResults CullingData,
                                      ScriptableRenderContext RenderContent)
        {
            //////Draw PrePass
            ///设置FilterSetting以及DrawSetting
            FilteringSettings FilterSetting_My_PrePass = new FilteringSettings
            {
                renderingLayerMask = 1,
                layerMask          = RenderCamera.cullingMask,
                renderQueueRange   = RenderQueueRange.opaque
            };
            DrawingSettings DrawSetting_My_PrePass = new DrawingSettings(
                InfinityPassIDs.PreDepthPass, new SortingSettings(RenderCamera)
            {
                criteria = SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges
            })
            {
                enableInstancing      = true,
                enableDynamicBatching = true,
                perObjectData         = PerObjectData.Lightmaps
            };
            ///从CommandBufferPool来获得池化的CB并申请TemporalRT设置RenderTarget和ShaderPass后进行DrawRender
            CommandBuffer CommandList_PrePass = CommandBufferPool.Get(InfinityPassIDs.PreDepthPass.name);

            CommandList_PrePass.GetTemporaryRT(InfinityShaderIDs.RT_DepthBuffer, RenderCamera.pixelWidth, RenderCamera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth);
            CommandList_PrePass.SetRenderTarget(InfinityShaderIDs.ID_SceneDepth);
            CommandList_PrePass.ClearRenderTarget(true, true, RenderCamera.backgroundColor);
            RenderContent.ExecuteCommandBuffer(CommandList_PrePass);
            CommandBufferPool.Release(CommandList_PrePass);
            RenderContent.DrawRenderers(CullingData, ref DrawSetting_My_PrePass, ref FilterSetting_My_PrePass);


            //////Draw GBufferPass
            FilteringSettings FilterSetting_My_GBuffer = new FilteringSettings
            {
                renderingLayerMask = 1,
                layerMask          = RenderCamera.cullingMask,
                renderQueueRange   = RenderQueueRange.opaque,
            };
            DrawingSettings DrawSetting_My_GBuffer = new DrawingSettings(InfinityPassIDs.GBufferPass, new SortingSettings(RenderCamera)
            {
                criteria = SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges
            })
            {
                enableInstancing      = true,
                enableDynamicBatching = true,
                perObjectData         = PerObjectData.Lightmaps
            };
            CommandBuffer CommandList_GBufferPass = CommandBufferPool.Get(InfinityPassIDs.GBufferPass.name);

            CommandList_GBufferPass.GetTemporaryRT(InfinityShaderIDs.RT_GBufferBaseColor, RenderCamera.pixelWidth, RenderCamera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32);
            CommandList_GBufferPass.GetTemporaryRT(InfinityShaderIDs.RT_GBufferMicroface, RenderCamera.pixelWidth, RenderCamera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32);
            CommandList_GBufferPass.GetTemporaryRT(InfinityShaderIDs.RT_GBufferNormal, RenderCamera.pixelWidth, RenderCamera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB2101010);
            CommandList_GBufferPass.GetTemporaryRT(InfinityShaderIDs.RT_GBufferEmissive, RenderCamera.pixelWidth, RenderCamera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf);
            CommandList_GBufferPass.SetRenderTarget(InfinityShaderIDs.ID_GBuffer, InfinityShaderIDs.ID_SceneDepth);
            CommandList_PrePass.ClearRenderTarget(false, true, RenderCamera.backgroundColor);
            RenderContent.ExecuteCommandBuffer(CommandList_GBufferPass);
            CommandBufferPool.Release(CommandList_GBufferPass);
            RenderContent.DrawRenderers(CullingData, ref DrawSetting_My_GBuffer, ref FilterSetting_My_GBuffer);

            //////Draw SkyBox
            RenderContent.DrawSkybox(RenderCamera);

            //////Draw Gizmos on SceneView
#if UNITY_EDITOR
            if (isSceneViewCam)
            {
                RenderContent.DrawGizmos(RenderCamera, GizmoSubset.PostImageEffects);
            }
#endif

            //////Bilt To Screen
            CommandBuffer CommandList_BiltToCamera = CommandBufferPool.Get("InfinityCommandList");
            bool          IsGameView; //检测当前View是不是GameView
            if (RenderCamera.targetTexture != null)
            {
                IsGameView = false;
            }
            else
            {
                IsGameView = true;
            }

            CommandList_BiltToCamera.DrawFullScreen(IsGameView, InfinityShaderIDs.RT_GBufferBaseColor,
                                                    RenderCamera.targetTexture);
            ///释放所有RT
            CommandList_BiltToCamera.ReleaseTemporaryRT(InfinityShaderIDs.RT_DepthBuffer);
            CommandList_BiltToCamera.ReleaseTemporaryRT(InfinityShaderIDs.RT_GBufferBaseColor);
            CommandList_BiltToCamera.ReleaseTemporaryRT(InfinityShaderIDs.RT_GBufferMicroface);
            CommandList_BiltToCamera.ReleaseTemporaryRT(InfinityShaderIDs.RT_GBufferNormal);
            CommandList_BiltToCamera.ReleaseTemporaryRT(InfinityShaderIDs.RT_GBufferEmissive);
            RenderContent.ExecuteCommandBuffer(CommandList_BiltToCamera);
            CommandBufferPool.Release(CommandList_BiltToCamera);
        }
Exemple #21
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;

            //Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            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);
            DrawingSettings drawSettingsDefault = new DrawingSettings(m_PassNameDefault, sortingSettings);
            //This will let you draw shader passes without the LightMode,
            //thus it draws the default UGUI materials
            drawSettingsDefault.SetShaderPassName(1, m_PassNameDefault);
            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);

            //Opaque default
            context.DrawRenderers(cull, ref drawSettingsDefault, ref filterSettings);

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

            //Transparent default
            context.DrawRenderers(cull, ref drawSettingsDefault, 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();
        }
    }
        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);

                // Culling
                if (!camera.TryGetCullingParameters(false, out var cullingParameters))
                {
                    continue;
                }
                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();
        }
Exemple #23
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();
	}
    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();
    }
Exemple #25
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;
        }
Exemple #26
0
        protected override void Render(ScriptableRenderContext context, Camera[] cameras)
        {
            BeginFrameRendering(cameras);

            #region Rendering setup

            if (_renderersSorted == null)
            {
                GetRenderersForEffects();
            }

            // Constants used in the camera render loop.
            RenderTextureDescriptor rtDesc = new RenderTextureDescriptor(_settings.m_renderResolution.x, _settings.m_renderResolution.y, RenderTextureFormat.Default, 24);

            switch (_settings.m_fixedRenderResolution)
            {
            case RenderConstraintAxis.Horizontal:
                rtDesc.height = (int)(((float)Screen.height / (float)Screen.width) * (float)rtDesc.width);
                break;

            case RenderConstraintAxis.Vertical:
                rtDesc.width = (int)(((float)Screen.width / (float)Screen.height) * (float)rtDesc.height);
                break;

            case RenderConstraintAxis.None:
                rtDesc.width  = Screen.width;
                rtDesc.height = Screen.height;
                break;
            }

            var rtID = Shader.PropertyToID("_LowResScreen");

            if (_settings.m_simulateVertexPrecision)
            {
                Shader.EnableKeyword("VERTEX_PRECISION_ON");
                Shader.SetGlobalFloat("_VertexPrecision", _settings.m_vertexPrecision);
            }
            else
            {
                Shader.DisableKeyword("VERTEX_PRECISION_ON");
            }

            if (_settings.m_perspectiveCorrection)
            {
                Shader.EnableKeyword("PERSPECTIVE_CORRECTION_ON");
            }
            else
            {
                Shader.DisableKeyword("PERSPECTIVE_CORRECTION_ON");
            }

            #endregion

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

                var _cb = CommandBufferPool.Get();

                #region Per-camera setup

                // Set the camera up.
                context.SetupCameraProperties(camera);

                float fov         = _settings.m_viewModelFOV;
                bool  isSceneView = false;
#if UNITY_EDITOR
                if (camera.cameraType == CameraType.SceneView)
                {
                    fov         = camera.fieldOfView;
                    isSceneView = true;
                }
#endif
                _cb.SetGlobalVectorArray(k_visibleLightColorsId, visibleLightColors);
                _cb.SetGlobalVectorArray(k_visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions);
                _cb.SetGlobalVectorArray(k_visibleLightAttenuationsId, visibleLightAttenuations);
                _cb.SetGlobalVectorArray(k_visibleLightSpotDirectionsId, visibleLightSpotDirections);

                #region Volume stack setup

                VolumeStack stack = null;

                if (_volumeStacks.ContainsKey(camera))
                {
                    stack = _volumeStacks[camera];
                }
                else
                {
                    stack = VolumeManager.instance.CreateStack();
                    _volumeStacks.Add(camera, stack);
                }

                var stackLayer = camera.GetComponent <Retro3DVolumeLayer>();
                VolumeManager.instance.Update(stack, camera.transform, stackLayer ? stackLayer.layers : _settings.m_defaultVolumeLayerMask);

                #endregion

                var vm_matrix = Matrix4x4.Perspective(fov, camera.aspect, camera.nearClipPlane, camera.farClipPlane);
                _cb.SetGlobalMatrix("_ViewmodelProjMatrix", GL.GetGPUProjectionMatrix(vm_matrix, true));

                // Setup commands: Initialize the temporary render texture.
                _cb.name = "Setup";
                _cb.GetTemporaryRT(rtID, rtDesc.width, rtDesc.height, rtDesc.depthBufferBits, FilterMode.Point, rtDesc.colorFormat, RenderTextureReadWrite.Default, (int)_settings.m_antialiasing);
                _cb.SetRenderTarget(rtID);
                CoreUtils.ClearRenderTarget(_cb, ClearFlag.All, camera.backgroundColor);
                context.ExecuteCommandBuffer(_cb);
                _cb.Clear();

                #endregion

                PerformSceneRender(context, camera);

                if (isSceneView)
                {
                    context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
                }

                PerformPostProcessing(context, camera, stack);

                if (isSceneView)
                {
                    context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
                }

                PerformFinalBlit(context, rtID, _cb);

                context.Submit();

                EndCameraRendering(context, camera);

                CommandBufferPool.Release(_cb);
            }

            EndFrameRendering(context, cameras);
        }
Exemple #27
0
        protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
        {
            bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length];
            bool  needSubmit           = false;

            UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length);
            GraphicsSettings.useScriptableRenderPipelineBatching = resources.useSRPBatcher;
            SceneController.SetState();
            data.context   = renderContext;
            data.resources = resources;
#if UNITY_EDITOR
            int tempID = Shader.PropertyToID("_TempRT");
            foreach (var pair in bakeList)
            {
                PipelineCamera pipelineCam = pair.pipelineCamera;
                for (int i = 0; i < pair.worldToCamera.Length; ++i)
                {
                    pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i];
                    pipelineCam.cam.projectionMatrix    = pair.projection[i];
                    pipelineCam.cameraTarget            = tempID;
                    data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear);
                    Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags);
                    data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0);
                    data.buffer.ReleaseTemporaryRT(tempID);
                    data.ExecuteCommandBuffer();
                    renderContext.Submit();
                    needSubmit = false;
                }
                pair.worldToCamera.Dispose();
                pair.projection.Dispose();
                renderContext.ExecuteCommandBuffer(pair.buffer);
                pair.buffer.Clear();
                renderContext.Submit();
                needSubmit = false;
            }
            bakeList.Clear();
#endif
            foreach (var cam in preFrameRenderCamera)
            {
                Render(cam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
                renderContext.Submit();
                needSubmit = false;
            }
            preFrameRenderCamera.Clear();
            if (CustomDrawRequest.AllEvents.Count > 0 || JobProcessEvent.allEvents.Count > 0)
            {
                foreach (var i in CustomDrawRequest.AllEvents)
                {
                    i.PrepareJob(resources);
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.PrepareJob();
                }
                JobHandle.ScheduleBatchedJobs();
                foreach (var i in CustomDrawRequest.AllEvents)
                {
                    i.FinishJob();
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.FinishJob();
                }
            }
            if (useBeforeFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_beforeFrameBuffer);
                m_beforeFrameBuffer.Clear();
                needSubmit           = true;
                useBeforeFrameBuffer = false;
            }
            if (PipelineCamera.allCamera.isCreated)
            {
                foreach (var cam in cameras)
                {
                    PipelineCamera pipelineCam;
                    UIntPtr        pipelineCamPtr;
                    if (!PipelineCamera.allCamera.Get(cam.gameObject.GetInstanceID(), out pipelineCamPtr))
                    {
#if UNITY_EDITOR
                        renderingEditor = true;
                        var pos = cam.transform.eulerAngles;
                        pos.z = 0;
                        cam.transform.eulerAngles = pos;
                        if (!PipelineCamera.allCamera.Get(Camera.main.gameObject.GetInstanceID(), out pipelineCamPtr))
                        {
                            continue;
                        }
#else
                        continue;
#endif
                    }
                    else
                    {
                        renderingEditor = false;
                    }
                    pipelineCam = MUnsafeUtility.GetObject <PipelineCamera>(pipelineCamPtr.ToPointer());
                    Render(pipelineCam, ref renderContext, cam, propertyCheckedFlags);
                    data.ExecuteCommandBuffer();
#if UNITY_EDITOR
                    if (renderingEditor)
                    {
                        renderContext.DrawGizmos(cam, GizmoSubset.PostImageEffects);
                    }
#endif
                    renderContext.Submit();
                    needSubmit = false;
                }
            }
            if (useAfterFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_afterFrameBuffer);
                m_afterFrameBuffer.Clear();
                needSubmit          = true;
                useAfterFrameBuffer = false;
            }
            if (needSubmit)
            {
                renderContext.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);


        RenderTextureDescriptor descriptor = CreateRenderTextureDescriptor(camera, 1);
        var depthDescriptor = descriptor;

        depthDescriptor.colorFormat     = RenderTextureFormat.Depth;
        depthDescriptor.depthBufferBits = 32;
        depthDescriptor.bindMS          = false;
        _cameraBuffer.GetTemporaryRT(depthTargetTextureId, depthDescriptor, FilterMode.Point);

        var colorDescriptor = descriptor;

        descriptor.colorFormat = RenderTextureFormat.ARGB32;
        descriptor.bindMS      = false;
        _cameraBuffer.GetTemporaryRT(colorTargetTextureId, colorDescriptor, FilterMode.Bilinear);
        _cameraBuffer.SetRenderTarget(new RenderTargetIdentifier(colorTargetTextureId), new RenderTargetIdentifier(depthTargetTextureId));

        CameraClearFlags clearFlags = camera.clearFlags;

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

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

        var cullingResult = context.Cull(ref cullingParameters);

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

        //DrawDepthOnlyPass(camera, context, cullingResult);

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

        DebugLighting(camera);
        context.ExecuteCommandBuffer(_cameraBuffer);
        _cameraBuffer.Clear();

        _cameraBuffer.Blit(_debugTexture, BuiltinRenderTextureType.CameraTarget);
        //_cameraBuffer.Blit(new RenderTargetIdentifier(colorTargetTextureId), BuiltinRenderTextureType.CameraTarget);
        context.ExecuteCommandBuffer(_cameraBuffer);
        _cameraBuffer.Clear();
        context.Submit();
    }
        protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
        {
            currentFrameCamera.Clear();
            PipelineCamera.InitializeDict();
            foreach (var cam in cameras)
            {
                CameraSetting csg;
                ulong         pipelineCamPtr;
                if (!PipelineCamera.CameraSearchDict.Get(cam.gameObject.GetInstanceID(), out pipelineCamPtr))
                {
                    if (!cam.TryGetComponent(out csg.pipeCam))
                    {
#if UNITY_EDITOR
                        if (cam.cameraType == CameraType.SceneView)
                        {
                            csg.isRenderingEditor = true;
                            var pos = cam.transform.eulerAngles;
                            pos.z = 0;
                            cam.transform.eulerAngles = pos;
                            if (!Camera.main || !(csg.pipeCam = Camera.main.GetComponent <PipelineCamera>()))
                            {
                                continue;
                            }
                        }
                        else if (cam.cameraType == CameraType.Game)
                        {
                            csg.isRenderingEditor = false;
                            csg.pipeCam           = cam.gameObject.AddComponent <PipelineCamera>();
                        }
                        else
                        {
                            continue;
                        }
#else
                        csg.isRenderingEditor = false;
                        csg.pipeCam           = cam.gameObject.AddComponent <PipelineCamera>();
#endif
                    }
                    else
                    {
                        csg.isRenderingEditor = false;
                        csg.pipeCam.AddToDict();
                    }
                }
                else
                {
                    csg.isRenderingEditor = false;
                    csg.pipeCam           = MUnsafeUtility.GetObject <PipelineCamera>((void *)pipelineCamPtr);
                }
                csg.cam         = cam;
                csg.pipeCam.cam = cam;
                csg.pipeCam.BeforeFrameRendering();
                currentFrameCamera.Add(csg);
            }
            bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length];
            bool  needSubmit           = false;
            CustomDrawRequest.Initialize();
            UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length);
            SceneController.SetState();
            data.context   = renderContext;
            data.resources = resources;
            if (motionVectorMatricesBuffer == null || !motionVectorMatricesBuffer.IsValid())
            {
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            else if (motionVectorMatricesBuffer.count < MotionVectorDrawer.Capacity)
            {
                motionVectorMatricesBuffer.Dispose();
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            MotionVectorDrawer.ExecuteBeforeFrame(motionVectorMatricesBuffer);
            data.buffer.SetGlobalBuffer(ShaderIDs._LastFrameModel, motionVectorMatricesBuffer);

#if UNITY_EDITOR
            int tempID = Shader.PropertyToID("_TempRT");

            foreach (var pair in bakeList)
            {
                PipelineCamera pipelineCam = pair.pipelineCamera;
                for (int i = 0; i < pair.worldToCamera.Length; ++i)
                {
                    pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i];
                    pipelineCam.cam.projectionMatrix    = pair.projection[i];
                    pipelineCam.cameraTarget            = tempID;
                    data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear);
                    Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags);
                    data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0);
                    data.buffer.ReleaseTemporaryRT(tempID);
                    data.ExecuteCommandBuffer();
                    renderContext.Submit();
                    needSubmit = false;
                }
                pair.worldToCamera.Dispose();
                pair.projection.Dispose();
                renderContext.ExecuteCommandBuffer(pair.buffer);
                pair.buffer.Clear();
                renderContext.Submit();
                needSubmit = false;
            }
            bakeList.Clear();
#endif
            foreach (var cam in preFrameRenderCamera)
            {
                Render(cam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
                renderContext.Submit();
                needSubmit = false;
            }
            preFrameRenderCamera.Clear();
            if (CustomDrawRequest.allEvents.Count > 0 || JobProcessEvent.allEvents.Count > 0)
            {
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.PrepareJob(resources);
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.PrepareJob();
                }
                JobHandle.ScheduleBatchedJobs();
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.FinishJob();
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.FinishJob();
                }
            }
            if (Application.isPlaying && resources.clusterResources)
            {
                resources.clusterResources.UpdateData(data.buffer, resources);
            }
            resources.loadingThread.Update();
            if (useBeforeFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_beforeFrameBuffer);
                m_beforeFrameBuffer.Clear();
                needSubmit           = true;
                useBeforeFrameBuffer = false;
            }
            if (iRunnableObjects.isCreated)
            {
                foreach (var i in iRunnableObjects)
                {
                    IPipelineRunnable func = MUnsafeUtility.GetObject <IPipelineRunnable>((void *)i.value);
                    func.PipelineUpdate(ref data);
                }
            }
            if (cameras.Length > 0)
            {
                data.buffer.SetGlobalVector(ShaderIDs._SceneOffset, new float4(sceneOffset, 1));
            }
            foreach (var cam in currentFrameCamera)
            {
                renderingEditor = cam.isRenderingEditor;

                Render(cam.pipeCam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
#if UNITY_EDITOR
                if (renderingEditor)
                {
                    renderContext.DrawGizmos(cam.cam, GizmoSubset.PostImageEffects);
                    ScriptableRenderContext.EmitWorldGeometryForSceneView(cam.cam);
                }
#endif
                renderContext.Submit();
                needSubmit = false;
            }

            if (useAfterFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_afterFrameBuffer);
                m_afterFrameBuffer.Clear();
                needSubmit          = true;
                useAfterFrameBuffer = false;
            }
            if (needSubmit)
            {
                renderContext.Submit();
            }
            MotionVectorDrawer.ExecuteAfterFrame();
            sceneOffset = 0;
            foreach (var cam in currentFrameCamera)
            {
                cam.pipeCam.cam = cam.cam;
                cam.pipeCam.AfterFrameRendering();
            }
        }
        protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
        {
            bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length];
            bool  needSubmit           = false;

            CustomDrawRequest.Initialize();
            UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length);
            GraphicsSettings.useScriptableRenderPipelineBatching = resources.useSRPBatcher;
            SceneController.SetState();
            data.context   = renderContext;
            data.resources = resources;
            if (motionVectorMatricesBuffer == null || !motionVectorMatricesBuffer.IsValid())
            {
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            else if (motionVectorMatricesBuffer.count < MotionVectorDrawer.Capacity)
            {
                motionVectorMatricesBuffer.Dispose();
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            MotionVectorDrawer.ExecuteBeforeFrame(motionVectorMatricesBuffer);
            data.buffer.SetGlobalBuffer(ShaderIDs._LastFrameModel, motionVectorMatricesBuffer);

#if UNITY_EDITOR
            int tempID = Shader.PropertyToID("_TempRT");

            foreach (var pair in bakeList)
            {
                PipelineCamera pipelineCam = pair.pipelineCamera;
                for (int i = 0; i < pair.worldToCamera.Length; ++i)
                {
                    pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i];
                    pipelineCam.cam.projectionMatrix    = pair.projection[i];
                    pipelineCam.cameraTarget            = tempID;
                    data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear);
                    Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags);
                    data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0);
                    data.buffer.ReleaseTemporaryRT(tempID);
                    data.ExecuteCommandBuffer();
                    renderContext.Submit();
                    needSubmit = false;
                }
                pair.worldToCamera.Dispose();
                pair.projection.Dispose();
                renderContext.ExecuteCommandBuffer(pair.buffer);
                pair.buffer.Clear();
                renderContext.Submit();
                needSubmit = false;
            }
            bakeList.Clear();
#endif
            foreach (var cam in preFrameRenderCamera)
            {
                Render(cam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
                renderContext.Submit();
                needSubmit = false;
            }
            preFrameRenderCamera.Clear();

            if (CustomDrawRequest.allEvents.Count > 0 || JobProcessEvent.allEvents.Count > 0)
            {
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.PrepareJob(resources);
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.PrepareJob();
                }
                JobHandle.ScheduleBatchedJobs();
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.FinishJob();
                }
            }
            if (useBeforeFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_beforeFrameBuffer);
                m_beforeFrameBuffer.Clear();
                needSubmit           = true;
                useBeforeFrameBuffer = false;
            }
            foreach (var cam in cameras)
            {
                PipelineCamera pipelineCam = cam.GetComponent <PipelineCamera>();
                if (!pipelineCam)
                {
#if UNITY_EDITOR
                    if (cam.cameraType == CameraType.SceneView)
                    {
                        renderingEditor = true;
                        var pos = cam.transform.eulerAngles;
                        pos.z = 0;
                        cam.transform.eulerAngles = pos;
                        if (!Camera.main || !(pipelineCam = Camera.main.GetComponent <PipelineCamera>()))
                        {
                            continue;
                        }
                    }
                    else if (cam.cameraType == CameraType.Game)
                    {
                        renderingEditor = false;
                        pipelineCam     = cam.gameObject.AddComponent <PipelineCamera>();
                    }
                    else
                    {
                        continue;
                    }
#else
                    renderingEditor = false;
                    pipelineCam     = cam.gameObject.AddComponent <PipelineCamera>();
#endif
                }
                else
                {
                    renderingEditor = false;
                }
                Render(pipelineCam, ref renderContext, cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
#if UNITY_EDITOR
                if (renderingEditor)
                {
                    renderContext.DrawGizmos(cam, GizmoSubset.PostImageEffects);
                }
#endif
                renderContext.Submit();
                needSubmit = false;
            }

            if (useAfterFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_afterFrameBuffer);
                m_afterFrameBuffer.Clear();
                needSubmit          = true;
                useAfterFrameBuffer = false;
            }
            if (needSubmit)
            {
                renderContext.Submit();
            }
            MotionVectorDrawer.ExecuteAfterFrame();
            foreach (var i in JobProcessEvent.allEvents)
            {
                i.FinishJob();
            }
        }