예제 #1
0
    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();
    }
        public override void Execute(ScriptableRenderContext context, ref UnityEngine.Rendering.Universal.RenderingData renderingData)
        {
            SortingCriteria sortingCriteria = (renderQueueType == RenderQueueType.Transparent)
                ? SortingCriteria.CommonTransparent
                : renderingData.cameraData.defaultOpaqueSortFlags;

            DrawingSettings drawingSettings =
                CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortingCriteria);

            drawingSettings.overrideMaterial          = overrideMaterial;
            drawingSettings.overrideMaterialPassIndex = overrideMaterialPassIndex;

            GraphicsFence portalsRenderedFence;

            Camera        camera       = renderingData.cameraData.camera;
            float         cameraAspect = (float)camera.pixelWidth / (float)camera.pixelHeight;
            CommandBuffer cmd          = CommandBufferPool.Get(m_ProfilerTag);

            using (new ProfilingSample(cmd, m_ProfilerTag))
            {
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();
                cmd.SetRandomWriteTarget(1, portalRenderContext.computeBuffer);


                if (m_CameraSettings.overrideCamera)
                {
                    //Matrix4x4 projectionMatrix = Matrix4x4.Perspective(m_CameraSettings.cameraFieldOfView, cameraAspect,
                    //    camera.nearClipPlane, camera.farClipPlane);

                    //Matrix4x4 viewMatrix = camera.worldToCameraMatrix;
                    //Vector4 cameraTranslation = viewMatrix.GetColumn(3);
                    //viewMatrix.SetColumn(3, cameraTranslation + m_CameraSettings.offset);

                    //cmd.SetViewProjectionMatrices(viewMatrix, projectionMatrix);
                    portalRenderContext.exitPortal = GameObject.FindGameObjectWithTag("ExitPortal");
                    Camera     exitCam = portalRenderContext.exitPortal.GetComponentInChildren <Camera>();
                    GameObject entryGO = GameObject.FindGameObjectWithTag("EntryPortal");

                    //Vector3 normal = exitCam.transform.forward;
                    //Vector3 pos = exitCam.transform.position;

                    //Vector4 clipPlaneWorldSpace = new Vector4(normal.x, normal.y, normal.z, -Vector3.Dot(normal, pos));
                    //Vector4 clipPlaneCameraSpace = exitCam.worldToCameraMatrix * clipPlaneWorldSpace;

                    Matrix4x4 projectionMatrix = camera.projectionMatrix;//exitCam.CalculateObliqueMatrix(clipPlaneCameraSpace);

                    Matrix4x4 destView = camera.worldToCameraMatrix * entryGO.transform.localToWorldMatrix
                                         * Matrix4x4.Rotate(entryGO.transform.rotation)
                                         * exitCam.transform.localToWorldMatrix.inverse;
                    //* glm::rotate(glm::mat4(1.0f), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f) * portal.orientation())
                    //* glm::inverse(portal.destination()->modelMat());

                    projectionMatrix = clippedProjMat(destView, projectionMatrix, entryGO.transform.position, entryGO.transform.rotation);


                    //cmd.Clear();
                    cmd.SetViewProjectionMatrices(destView, projectionMatrix);
                    context.ExecuteCommandBuffer(cmd);
                    cmd.Clear();
                }



                context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref m_FilteringSettings,
                                      ref m_RenderStateBlock);

                //ScriptableCullingParameters param;

                //context.Cull()

                if (m_CameraSettings.overrideCamera && m_CameraSettings.restoreCamera)
                {
                    Matrix4x4 projectionMatrix = Matrix4x4.Perspective(camera.fieldOfView, cameraAspect,
                                                                       camera.nearClipPlane, camera.farClipPlane);

                    cmd.Clear();
                    cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, projectionMatrix);
                }
                //portalsRenderedFence = cmd.CreateGraphicsFence(GraphicsFenceType.CPUSynchronisation,
                //    SynchronisationStageFlags.PixelProcessing);
                //if (PortalDebugRenderOverlay.Instance?.renderTarget)
                //{
                //    PortalDebugRenderOverlay.Instance?.renderTarget = new RenderTexture(depthAttachment)
                //}
                //PortalDebugRenderOverlay.Instance?.fullscreenOverlay?.mainTexture = this.depthAttachment;
            }

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

            context.Submit();

            //Debug.Log("Fence support:"+ SystemInfo.supportsGraphicsFence);
            //while (!portalsRenderedFence.passed) ;

            //Int32[] perPortalPixelCount = new Int32[255];
            //portalRenderContext.computeBuffer.GetData(perPortalPixelCount, 0, 0, 255);
            //for (int i = 0; i < 5; i++)
            //{
            //    Debug.Log(i + "Portal count: " + perPortalPixelCount[i]);
            //}
            //portalRenderContext.computeBuffer.SetData(new Int32[255]);
        }
예제 #3
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            if (!renderingData.shadowData.supportsDeepShadowMaps)
            {
                return;
            }
            LightData lightData        = renderingData.lightData;
            int       shadowLightIndex = lightData.mainLightIndex;

            if (shadowLightIndex == -1)
            {
                return;
            }


            VisibleLight shadowLight = lightData.visibleLights[shadowLightIndex];
            ShadowData   shadowData  = renderingData.shadowData;

            if (!GetVPMatrix(shadowLight.light))
            {
                return;
            }

            if (null == _ResetCompute)
            {
                _ResetCompute     = renderer.GetCompute(ComputeHandle.ResetDeepShadowDataCompute);
                KernelResetBuffer = _ResetCompute.FindKernel("KernelResetBuffer");
            }

            CommandBuffer cmd = CommandBufferPool.Get(k_RenderDeepShadowCaster);

            using (new ProfilingSample(cmd, k_RenderDeepShadowCaster))
            {
                int deepShadowMapsSize  = shadowData.deepShadowMapsSize;
                int deepShadowMapsDepth = shadowData.deepShadowMapsDepth;
                // Reset
                cmd.SetComputeBufferParam(_ResetCompute, KernelResetBuffer, "_CountBuffer", _CountBuffer);
                cmd.SetComputeBufferParam(_ResetCompute, KernelResetBuffer, "_DataBuffer", _DataBuffer);
                cmd.SetComputeIntParam(_ResetCompute, "_DeepShadowMapSize", deepShadowMapsSize);
                cmd.SetComputeIntParam(_ResetCompute, "_DeepShadowMapDepth", deepShadowMapsDepth);
                cmd.DispatchCompute(_ResetCompute, KernelResetBuffer, deepShadowMapsSize / 8, deepShadowMapsSize / 8, 1);

                _Temp = RenderTexture.GetTemporary(deepShadowMapsSize, deepShadowMapsSize, 0, RenderTextureFormat.R8); //Without rt, the second row of the vp matrix is negated

                // Cast
                SetRenderTarget(cmd, _Temp, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare,
                                ClearFlag.Color, Color.black, TextureDimension.Tex2D);
                cmd.SetViewport(new Rect(Vector2.zero, Vector2.one * deepShadowMapsSize));

                Vector4 shadowBias = ShadowUtils.GetShadowBias(ref shadowLight, shadowLightIndex, ref shadowData, _ProjMatrix, shadowData.deepShadowMapsSize);
                ShadowUtils.SetupShadowCasterConstantBuffer(cmd, ref shadowLight, shadowBias);

                cmd.SetViewProjectionMatrices(_ViewMatrix, _ProjMatrix);
                cmd.SetRandomWriteTarget(1, _CountBuffer);
                cmd.SetRandomWriteTarget(2, _DataBuffer);
                cmd.SetGlobalInt("_DeepShadowMapSize", deepShadowMapsSize);
                cmd.SetGlobalInt("_DeepShadowMapDepth", deepShadowMapsDepth);

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

                //foreach (var r in _Renderers)
                //{
                //    for (int i = 0, imax = r.sharedMaterials.Length; i < imax; i++)
                //    {
                //        cmd.DrawRenderer(r, r.sharedMaterials[i], i, r.sharedMaterials[i].FindPass("DeepShadowCaster"));
                //    }
                //}

                ShadowSliceData slice = new ShadowSliceData()
                {
                    offsetX    = 0,
                    offsetY    = 0,
                    resolution = deepShadowMapsSize,
                };

                cmd.SetGlobalMatrix("_DeepShadowMapsWorldToShadow", _DeepShadowMatrix);
                DrawShadowsSettings settings = new DrawShadowsSettings(renderingData.cullResults, shadowLightIndex);
                settings.splitData.cullingSphere = _CullingSphere;

                cmd.EnableShaderKeyword("_DEEP_SHADOW_CASTER");
                cmd.SetGlobalInt("_ShadowCasterZWrite", 0);
                ShadowUtils.RenderShadowSlice(cmd, ref context, ref slice, ref settings, _ProjMatrix, _ViewMatrix);
                cmd.DisableShaderKeyword("_DEEP_SHADOW_CASTER");
                cmd.SetGlobalInt("_ShadowCasterZWrite", 1);

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

                // For Resolve
                SetupDeepShadowMapResolverConstants(cmd, ref shadowData, shadowLight);
                cmd.ClearRandomWriteTargets();
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
        void RenderAdditionalShadowmapAtlas(ref ScriptableRenderContext context, ref CullingResults cullResults, ref LightData lightData, ref ShadowData shadowData)
        {
            NativeArray <VisibleLight> visibleLights = lightData.visibleLights;

            bool additionalLightHasSoftShadows = false;
            // NOTE: Do NOT mix ProfilingScope with named CommandBuffers i.e. CommandBufferPool.Get("name").
            // Currently there's an issue which results in mismatched markers.
            CommandBuffer cmd = CommandBufferPool.Get();

            using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.AdditionalLightsShadow)))
            {
                bool anyShadowSliceRenderer = false;
                int  shadowSlicesCount      = m_AdditionalShadowCastingLightIndices.Count;
                for (int i = 0; i < shadowSlicesCount; ++i)
                {
                    // we do the shadow strength check here again here because when using
                    // the uniform array path we might have zero strength shadow lights.
                    // In that case we need the shadow data buffer but we can skip
                    // rendering them to shadowmap.
                    if (!m_UseStructuredBuffer && Mathf.Approximately(m_AdditionalLightsShadowParams[i].x, 0.0f))
                    {
                        continue;
                    }

                    // Index of the VisibleLight
                    int          shadowLightIndex = m_AdditionalShadowCastingLightIndices[i];
                    VisibleLight shadowLight      = visibleLights[shadowLightIndex];

                    ShadowSliceData shadowSliceData = m_AdditionalLightSlices[i];

                    var     settings   = new ShadowDrawingSettings(cullResults, shadowLightIndex);
                    Vector4 shadowBias = ShadowUtils.GetShadowBias(ref shadowLight, shadowLightIndex,
                                                                   ref shadowData, shadowSliceData.projectionMatrix, shadowSliceData.resolution);
                    ShadowUtils.SetupShadowCasterConstantBuffer(cmd, ref shadowLight, shadowBias);
                    ShadowUtils.RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings);
                    additionalLightHasSoftShadows |= shadowLight.light.shadows == LightShadows.Soft;
                    anyShadowSliceRenderer         = true;
                }

                // We share soft shadow settings for main light and additional lights to save keywords.
                // So we check here if pipeline supports soft shadows and either main light or any additional light has soft shadows
                // to enable the keyword.
                // TODO: In PC and Consoles we can upload shadow data per light and branch on shader. That will be more likely way faster.
                bool mainLightHasSoftShadows = shadowData.supportsMainLightShadows &&
                                               lightData.mainLightIndex != -1 &&
                                               visibleLights[lightData.mainLightIndex].light.shadows ==
                                               LightShadows.Soft;

                bool softShadows = shadowData.supportsSoftShadows &&
                                   (mainLightHasSoftShadows || additionalLightHasSoftShadows);

                CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.AdditionalLightShadows, anyShadowSliceRenderer);
                CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.SoftShadows, softShadows);

                if (anyShadowSliceRenderer)
                {
                    SetupAdditionalLightsShadowReceiverConstants(cmd, ref shadowData, softShadows);
                }
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #5
0
        public override void Enable(bool fromInspector)
        {
            base.Enable(fromInspector);

            node = nodeTarget as PreviewNode;

            var colorPickerValues = new Label();

            colorPickerValues.AddToClassList("Indent");
            if (!fromInspector)
            {
                controlsContainer.Add(colorPickerValues);

                // Stop right click when the mouse is over the preview because we use it for light position
                previewContainer.RegisterCallback <ContextualMenuPopulateEvent>(e => {
                    e.StopImmediatePropagation();
                }, TrickleDown.TrickleDown);
                previewContainer.AddManipulator(new ContextualMenuManipulator(evt => {}));
            }
            else
            {
                owner.graph.afterCommandBufferExecuted += UpdateViewData;
                controlsContainer.RegisterCallback <DetachFromPanelEvent>(e => {
                    owner.graph.afterCommandBufferExecuted -= UpdateViewData;
                });
                var histogram = new HistogramView(node.histogramData, owner);
                controlsContainer.Add(histogram);
            }

            void UpdateViewData()
            {
                if (node.output != null)
                {
                    // Update histogram
                    var cmd = CommandBufferPool.Get("Update Histogram");
                    HistogramUtility.ComputeHistogram(cmd, node.output, node.histogramData);
                    Graphics.ExecuteCommandBuffer(cmd);

                    // Update color picker data
                    UpdateColorPickerValues();
                }
            }

            void UpdateColorPickerValues()
            {
                int texturePosX = Mathf.RoundToInt(node.mousePosition.x * node.output.width);
                int texturePosY = Mathf.RoundToInt(node.mousePosition.y * node.output.height);

                texturePosX = Mathf.Clamp(texturePosX, 0, node.output.width - 1);
                texturePosY = Mathf.Clamp(texturePosY, 0, node.output.height - 1);

                var a = AsyncGPUReadback.Request(node.output, 0, texturePosX, 1, texturePosY, 1, 0, 1, (data) => {
                    var colors = data.GetData <Color>();
                    if (data.hasError || colors.Length == 0)
                    {
                        return;
                    }
                    var pixel = colors[0];
                    colorPickerValues.text = $"R: {pixel.r:F3} G: {pixel.g:F3} B: {pixel.b:F3} A: {pixel.a:F3}";
                });

                schedule.Execute(() => {
                    a.Update();
                }).Until(() => a.done);
            }

            var preview = previewContainer.Q("ImGUIPreview");

            preview.RegisterCallback <MouseMoveEvent>(e => {
                var localPos       = GetPreviewMousePositionRatio(e.mousePosition);
                node.mousePosition = localPos;
                UpdateColorPickerValues();

                if (e.imguiEvent.button == 1)
                {
                    NotifyNodeChanged();
                    node.lightPosition = (new Vector2(localPos.x, 1 - localPos.y) * 2 - Vector2.one) * node.tiling;
                }
            });

            // TODO: add source mip slider

            UpdateViewData();
            UpdateColorPickerValues();
        }
        protected override void Render(ScriptableRenderContext RenderContext, Camera[] Views)
        {
            //Init FrameContext
            GPUScene.Gather(GetWorld().GetMeshBatchColloctor(), true);
            //Debug.Log("X : " + Screen.width + "__" + "Y : " + Screen.height);
            RTHandles.Initialize(Screen.width, Screen.height, false, MSAASamples.None);

            //Render Pipeline
            BeginFrameRendering(RenderContext, Views);
            for (int ViewIndex = 0; ViewIndex < Views.Length; ViewIndex++)
            {
                //Init View
                Camera          View      = Views[ViewIndex];
                CommandBuffer   CmdBuffer = CommandBufferPool.Get("");
                CameraComponent HDView    = View.GetComponent <CameraComponent>();

                //Render View
                BeginCameraRendering(RenderContext, View);
                {
                    using (new ProfilingScope(CmdBuffer, HDView ? HDView.ViewProfiler : ProfilingSampler.Get(ERGProfileId.InfinityRenderer)))
                    {
                        #region InitViewContext
                        bool bSceneView    = View.cameraType == CameraType.SceneView;
                        bool bRendererView = View.cameraType == CameraType.Game || View.cameraType == CameraType.Reflection || View.cameraType == CameraType.SceneView;

                            #if UNITY_EDITOR
                        if (bSceneView)
                        {
                            ScriptableRenderContext.EmitWorldGeometryForSceneView(View);
                        }
                            #endif

                        VFXManager.PrepareCamera(View);
                        ViewUnifrom.UnpateBufferData(false, View);
                        ViewUnifrom.BindGPUParameter(CmdBuffer);
                        RenderContext.SetupCameraProperties(View);
                        VFXManager.ProcessCameraCommand(View, CmdBuffer);

                        //Culling Context
                        FCullingData CullingData = new FCullingData();
                        { CullingData.bRendererView = bRendererView; }
                        ScriptableCullingParameters CullingParameters;
                        View.TryGetCullingParameters(out CullingParameters);
                        CullingResults CullingResult = RenderContext.Cull(ref CullingParameters);     //Unity Culling
                        RenderContext.DispatchCull(GPUScene, ref CullingParameters, ref CullingData); //Infinity Culling
                        #endregion                                                                    //InitViewContext

                        #region InitViewCommand
                        RenderOpaqueDepth(View, CullingData, CullingResult);
                        RenderOpaqueGBuffer(View, CullingData, CullingResult);
                        RenderOpaqueMotion(View, CullingData, CullingResult);
                        RenderOpaqueForward(View, CullingData, CullingResult);
                        RenderSkyBox(View);
                        RenderGizmo(View, GizmoSubset.PostImageEffects);
                        RenderPresentView(View, GraphBuilder.ScopeTexture(InfinityShaderIDs.DiffuseBuffer), View.targetTexture);
                        #endregion //InitViewCommand

                        #region ExecuteViewRender
                        GraphBuilder.Execute(RenderContext, GetWorld(), CmdBuffer, ViewUnifrom.FrameIndex);
                        #endregion //ExecuteViewRender

                        #region ReleaseViewContext
                        CullingData.Release();
                        ViewUnifrom.UnpateBufferData(true, View);
                        #endregion //ReleaseViewContext
                    }
                }
                EndCameraRendering(RenderContext, View);

                //Submit View
                RenderContext.ExecuteCommandBuffer(CmdBuffer);
                CommandBufferPool.Release(CmdBuffer);
                RenderContext.Submit();
            }
            EndFrameRendering(RenderContext, Views);

            //Release FrameContext
            GPUScene.Release();
        }
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (containerVis == null)
            {
                return;
            }

            var cmd = CommandBufferPool.Get(k_CloudWithGodRayPass);

            using (new ProfilingScope(cmd, profilingSampler))
            {
                var pos      = containerVis.transform.position;
                var halfSize = containerVis.transform.lossyScale / 2.0f;
                cloudMaterial.SetVector(BoundsMin_ID, value: pos - halfSize);
                cloudMaterial.SetVector(BoundsMax_ID, pos + halfSize);

                cloudMaterial.SetTexture(NoiseTex_ID, shapeTexture);
                cloudMaterial.SetTexture(NoiseDetail3D_ID, detailTexture);
                cloudMaterial.SetTexture(WeatherMap_ID, weatherMap);
                cloudMaterial.SetTexture(MaskNoise_ID, maskNoise);
                cloudMaterial.SetTexture(BlueNoise_ID, blueNoise);

                Vector4 screenUV = new Vector4(1, 1, 0, 0);
                if (blueNoise != null)
                {
                    screenUV.x = (float)cameraTextureDescriptor.width / blueNoise.width;
                    screenUV.y = (float)cameraTextureDescriptor.height / blueNoise.height;
                }

                cloudMaterial.SetVector(BlueNoiseCoords_ID, screenUV);


                cloudMaterial.SetFloat(ShapeTiling_ID, cloudSettings.shapeTiling.value);
                cloudMaterial.SetFloat(DetailTiling_ID, cloudSettings.detailTiling.value);

                cloudMaterial.SetFloat(Step_ID, cloudSettings.step.value);
                cloudMaterial.SetFloat(RayStep_ID, cloudSettings.rayStep.value);

                cloudMaterial.SetFloat(DensityOffset_ID, cloudSettings.densityOffset.value);
                cloudMaterial.SetFloat(DensityMultiplier_ID, cloudSettings.densityMultiplier.value);


                cloudMaterial.SetColor(ColA_ID, cloudSettings.colA.value);
                cloudMaterial.SetColor(ColB_ID, cloudSettings.colB.value);
                cloudMaterial.SetFloat(ColorOffset1_ID, cloudSettings.colorOffset1.value);
                cloudMaterial.SetFloat(ColorOffset2_ID, cloudSettings.colorOffset2.value);
                cloudMaterial.SetFloat(LightAbsorptionTowardSun_ID,
                                       cloudSettings.lightAbsorptionTowardSun.value);
                cloudMaterial.SetFloat(LightAbsorptionThroughCloud_ID,
                                       cloudSettings.lightAbsorptionThroughCloud.value);
                cloudMaterial.SetFloat(DarknessThreshold_ID,
                                       cloudSettings.darknessThreshold.value);

                cloudMaterial.SetFloat(RayOffsetStrength_ID, cloudSettings.rayOffsetStrength.value);
                cloudMaterial.SetVector(PhaseParams_ID, cloudSettings.phaseParams.value);
                cloudMaterial.SetVector(XY_Speed_ZW_Warp_ID, cloudSettings.xy_Speed_zw_Warp.value);

                cloudMaterial.SetVector(ShapeNoiseWeights_ID, cloudSettings.shapeNoiseWeights.value);
                cloudMaterial.SetFloat(HeightWeights_ID, cloudSettings.heightWeights.value);


                cloudMaterial.SetFloat(DetailWeights_ID, cloudSettings.detailWeights.value);
                cloudMaterial.SetFloat(DetailNoiseWeight_ID, cloudSettings.detailNoiseWeight.value);
                cloudMaterial.SetVector(DetailNoiseWeights_ID, cloudSettings.detailNoiseWeights.value);

                //URP 7.5.3之后  cameraData.GetGPUProjectionMatrix() 进行y翻转
                var cameraData = renderingData.cameraData;
                if (cameraData.IsCameraProjectionMatrixFlipped())
                {
                    Matrix4x4 viewAndProjectionMatrix = GL.GetGPUProjectionMatrix(cameraData.GetProjectionMatrix(), false) * cameraData.GetViewMatrix();
                    Matrix4x4 inverseViewProjection   = Matrix4x4.Inverse(viewAndProjectionMatrix);
                    cmd.SetGlobalMatrix(inverseViewAndProjectionMatrix, inverseViewProjection);
                }

                //降深度采样
                cmd.GetTemporaryRT(DownsampleDepthTex_ID
                                   , cameraTextureDescriptor.width / cloudSettings.downsample.value
                                   , cameraTextureDescriptor.height / cloudSettings.downsample.value
                                   , 0, FilterMode.Point, RenderTextureFormat.R16);
                cmd.SetRenderTarget(DownsampleDepthTex_RTI, RenderBufferLoadAction.DontCare,
                                    RenderBufferStoreAction.Store);
                CoreUtils.DrawFullScreen(cmd, cloudMaterial, null, 1);
                cmd.SetGlobalTexture(DownsampleDepthTex_ID, DownsampleDepthTex_RTI);

                //降cloud分辨率 并使用第1个pass 渲染云
                cmd.GetTemporaryRT(DownsampleColorTex_ID
                                   , cameraTextureDescriptor.width / cloudSettings.downsample.value
                                   , cameraTextureDescriptor.height / cloudSettings.downsample.value
                                   , 0, FilterMode.Point, RenderTextureFormat.ARGB32);
                cmd.SetRenderTarget(DownsampleColorTex_RTI, RenderBufferLoadAction.DontCare,
                                    RenderBufferStoreAction.Store);
                CoreUtils.DrawFullScreen(cmd, cloudMaterial, null, 0);
                //降分辨率后的云设置回_DownsampleColor
                cmd.SetGlobalTexture(DownsampleColorTex_ID, DownsampleColorTex_RTI);


                //使用第2个Pass 合成
                cmd.SetRenderTarget(CameraColorTex_RTI);
                CoreUtils.DrawFullScreen(cmd, cloudMaterial, null, 2);


                cmd.ReleaseTemporaryRT(DownsampleDepthTex_ID);
                cmd.ReleaseTemporaryRT(DownsampleColorTex_ID);
            }



            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #8
0
        private bool RenderShadows(ref CullResults cullResults, ref VisibleLight shadowLight, int shadowLightIndex, ref ScriptableRenderContext context)
        {
            m_ShadowCasterCascadesCount = m_ShadowSettings.directionalLightCascadeCount;

            if (shadowLight.lightType == LightType.Spot)
            {
                m_ShadowCasterCascadesCount = 1;
            }

            int shadowResolution = GetMaxTileResolutionInAtlas(m_ShadowSettings.shadowAtlasWidth, m_ShadowSettings.shadowAtlasHeight, m_ShadowCasterCascadesCount);

            Bounds bounds;

            if (!cullResults.GetShadowCasterBounds(shadowLightIndex, out bounds))
            {
                return(false);
            }

            var setRenderTargetCommandBuffer = CommandBufferPool.Get();

            setRenderTargetCommandBuffer.name = "Render packed shadows";
            setRenderTargetCommandBuffer.GetTemporaryRT(m_ShadowMapProperty, m_ShadowSettings.shadowAtlasWidth,
                                                        m_ShadowSettings.shadowAtlasHeight, kShadowDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
            setRenderTargetCommandBuffer.SetRenderTarget(m_ShadowMapRTID);
            setRenderTargetCommandBuffer.ClearRenderTarget(true, true, Color.black);
            context.ExecuteCommandBuffer(setRenderTargetCommandBuffer);
            CommandBufferPool.Release(setRenderTargetCommandBuffer);

            float   shadowNearPlane = m_Asset.ShadowNearOffset;
            Vector3 splitRatio      = m_ShadowSettings.directionalLightCascades;

            Matrix4x4 view, proj;
            var       settings      = new DrawShadowsSettings(cullResults, shadowLightIndex);
            bool      needRendering = false;

            if (shadowLight.lightType == LightType.Spot)
            {
                needRendering = cullResults.ComputeSpotShadowMatricesAndCullingPrimitives(shadowLightIndex, out view, out proj,
                                                                                          out settings.splitData);

                if (!needRendering)
                {
                    return(false);
                }

                SetupShadowSliceTransform(0, shadowResolution, proj, view);
                RenderShadowSlice(ref context, 0, proj, view, settings);
            }
            else if (shadowLight.lightType == LightType.Directional)
            {
                for (int cascadeIdx = 0; cascadeIdx < m_ShadowCasterCascadesCount; ++cascadeIdx)
                {
                    needRendering = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(shadowLightIndex,
                                                                                                     cascadeIdx, m_ShadowCasterCascadesCount, splitRatio, shadowResolution, shadowNearPlane, out view, out proj,
                                                                                                     out settings.splitData);

                    m_DirectionalShadowSplitDistances[cascadeIdx]    = settings.splitData.cullingSphere;
                    m_DirectionalShadowSplitDistances[cascadeIdx].w *= settings.splitData.cullingSphere.w;

                    if (!needRendering)
                    {
                        return(false);
                    }

                    SetupShadowSliceTransform(cascadeIdx, shadowResolution, proj, view);
                    RenderShadowSlice(ref context, cascadeIdx, proj, view, settings);
                }
            }
            else
            {
                Debug.LogWarning("Only spot and directional shadow casters are supported in lightweight pipeline");
                return(false);
            }

            return(true);
        }
예제 #9
0
        private void BeginForwardRendering(ref ScriptableRenderContext context, bool stereoEnabled)
        {
            if (stereoEnabled)
            {
                context.StartMultiEye(m_CurrCamera);
            }

            var cmd = CommandBufferPool.Get("SetCameraRenderTarget");

            if (m_RenderToIntermediateTarget)
            {
                if (m_CurrCamera.activeTexture == null)
                {
                    m_IntermediateTextureArray = false;
                    if (stereoEnabled)
                    {
                        RenderTextureDescriptor xrDesc = XRSettings.eyeTextureDesc;
                        xrDesc.depthBufferBits = kCameraDepthBufferBits;
                        xrDesc.colorFormat     = m_ColorFormat;
                        xrDesc.msaaSamples     = m_Asset.MSAASampleCount;

                        m_IntermediateTextureArray = (xrDesc.dimension == TextureDimension.Tex2DArray);

                        cmd.GetTemporaryRT(m_CameraRTProperty, xrDesc, FilterMode.Bilinear);
                    }
                    else
                    {
                        cmd.GetTemporaryRT(m_CameraRTProperty, Screen.width, Screen.height, kCameraDepthBufferBits,
                                           FilterMode.Bilinear, m_ColorFormat, RenderTextureReadWrite.Default, m_Asset.MSAASampleCount);
                    }

                    if (m_IntermediateTextureArray)
                    {
                        cmd.SetRenderTarget(m_CameraRTID, 0, CubemapFace.Unknown, -1);
                    }
                    else
                    {
                        cmd.SetRenderTarget(m_CameraRTID);
                    }
                }
                else
                {
                    cmd.SetRenderTarget(new RenderTargetIdentifier(m_CurrCamera.activeTexture));
                }
            }
            else
            {
                cmd.SetRenderTarget(BuiltinRenderTextureType.CurrentActive);
            }

            // Clear RenderTarget to avoid tile initialization on mobile GPUs
            // https://community.arm.com/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers
            if (m_CurrCamera.clearFlags != CameraClearFlags.Nothing)
            {
                bool clearDepth = (m_CurrCamera.clearFlags != CameraClearFlags.Nothing);
                bool clearColor = (m_CurrCamera.clearFlags == CameraClearFlags.Color);
                cmd.ClearRenderTarget(clearDepth, clearColor, m_CurrCamera.backgroundColor);
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #10
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();
        }
예제 #11
0
        private void SetupShaderLightListConstants(VisibleLight[] lights, ref LightData lightData, ref ScriptableRenderContext context)
        {
            int maxLights = Math.Min(kMaxVisibleLights, lights.Length);

            for (int i = 0; i < maxLights; ++i)
            {
                VisibleLight currLight = lights [i];
                if (currLight.lightType == LightType.Directional)
                {
                    Vector4 dir = -currLight.localToWorld.GetColumn(2);
                    m_LightPositions [i] = new Vector4(dir.x, dir.y, dir.z, 0.0f);
                }
                else
                {
                    Vector4 pos = currLight.localToWorld.GetColumn(3);
                    m_LightPositions [i] = new Vector4(pos.x, pos.y, pos.z, 1.0f);
                }

                m_LightColors[i] = currLight.finalColor;

                float rangeSq   = currLight.range * currLight.range;
                float quadAtten = (currLight.lightType == LightType.Directional) ? 0.0f : 25.0f / rangeSq;

                if (currLight.lightType == LightType.Spot)
                {
                    Vector4 dir = currLight.localToWorld.GetColumn(2);
                    m_LightSpotDirections [i] = new Vector4(-dir.x, -dir.y, -dir.z, 0.0f);

                    float spotAngle     = Mathf.Deg2Rad * currLight.spotAngle;
                    float cosOuterAngle = Mathf.Cos(spotAngle * 0.5f);
                    float cosInneAngle  = Mathf.Cos(spotAngle * 0.25f);
                    float angleRange    = cosInneAngle - cosOuterAngle;
                    m_LightAttenuations [i] = new Vector4(cosOuterAngle,
                                                          Mathf.Approximately(angleRange, 0.0f) ? 1.0f : angleRange, quadAtten, rangeSq);
                }
                else
                {
                    m_LightSpotDirections [i] = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
                    m_LightAttenuations [i]   = new Vector4(-1.0f, 1.0f, quadAtten, rangeSq);
                }
            }

            // Lightweight pipeline only upload kMaxVisibleLights to shader cbuffer.
            // We tell the pipe to disable remaining lights by setting it to -1.
            int[] lightIndexMap = m_CullResults.GetLightIndexMap();
            for (int i = kMaxVisibleLights; i < lightIndexMap.Length; ++i)
            {
                lightIndexMap[i] = -1;
            }
            m_CullResults.SetLightIndexMap(lightIndexMap);

            CommandBuffer cmd = CommandBufferPool.Get("SetupShadowShaderConstants");

            cmd.SetGlobalVector("globalLightCount", new Vector4(lightData.pixelLightsCount, lightData.vertexLightsCount, 0.0f, 0.0f));
            cmd.SetGlobalVectorArray("globalLightPos", m_LightPositions);
            cmd.SetGlobalVectorArray("globalLightColor", m_LightColors);
            cmd.SetGlobalVectorArray("globalLightAtten", m_LightAttenuations);
            cmd.SetGlobalVectorArray("globalLightSpotDir", m_LightSpotDirections);
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #12
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);
            }
        }
        public override void Render(ScriptableRenderContext context, ref MyRenderingData renderingData)
        {
            if (!asset.enablePass)
            {
                return;
            }


            if (renderingData.camera.cameraType == CameraType.Preview)
            {
                return;
            }

            if (!asset.material || !screenMesh)
            {
                return;
            }

            var cmd = CommandBufferPool.Get(k_profilingTag);

            using (new ProfilingScope(cmd, profilingSampler))
            {
                if (curlNoiseMotionRenderer != null)
                {
                    //不运行
                    var buffer = curlNoiseMotionRenderer.Update(cmd);
                    cmd.SetGlobalBuffer("_MotionPosBuffer", buffer);
                    var size = curlNoiseMotionRenderer.size;
                    cmd.SetGlobalVector("_MotionPosBufferSize", new Vector3(size.x, size.y, size.z));
                }

                cmd.SetGlobalVector("_WorldCameraPos", renderingData.camera.transform.position);
                cmd.SetGlobalVector("_CameraClipPlane",
                                    new Vector3(renderingData.camera.nearClipPlane, renderingData.camera.farClipPlane,
                                                renderingData.camera.farClipPlane - renderingData.camera.nearClipPlane));
                cmd.SetGlobalMatrix("_ViewProjectionInverseMatrix",
                                    RenderUtils.ProjectionToWorldMatrix(renderingData.camera));

                //Resources.FindObjectsOfTypeAll 在内存中的资源
                var curlNoiseMotion = Resources.FindObjectsOfTypeAll <CurlNoiseMotion2D>().FirstOrDefault();
                if (curlNoiseMotion)
                {
                    cmd.SetGlobalTexture("_CurlNoiseMotionTex", curlNoiseMotion.currentMotionTexture);
                }

                if (asset.drawFullScreen)
                {
                    cmd.DrawMesh(screenMesh, RenderUtils.ProjectionToWorldMatrix(renderingData.camera), asset.material,
                                 0,
                                 0);
                }
                else
                {
                    //美术效果不是很好  而且有问题算了
                    var cubes = Object.FindObjectsOfType <VolumetricCloudCube>();
                    foreach (var cube in cubes)
                    {
                        cmd.SetGlobalVector("_CubeSize", cube.transform.localScale);
                        cmd.SetGlobalVector("_CubePos", cube.transform.position);
                        cmd.DrawRenderer(cube.GetComponent <MeshRenderer>(), asset.material, 0, 1);
                    }
                }
            }

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();
            CommandBufferPool.Release(cmd);
        }
예제 #14
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (m_CopyDepthMaterial == null)
            {
                Debug.LogErrorFormat("Missing {0}. {1} render pass will not execute. Check for missing reference in the renderer resources.", m_CopyDepthMaterial, GetType().Name);
                return;
            }
            CommandBuffer cmd = CommandBufferPool.Get();

            using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.CopyDepth)))
            {
                RenderTextureDescriptor descriptor = renderingData.cameraData.cameraTargetDescriptor;
                int cameraSamples = descriptor.msaaSamples;

                CameraData cameraData = renderingData.cameraData;

                switch (cameraSamples)
                {
                case 8:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                case 4:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                case 2:
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                // MSAA disabled
                default:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;
                }

                cmd.SetGlobalTexture("_CameraDepthAttachment", source.Identifier());


#if ENABLE_VR && ENABLE_XR_MODULE
                // XR uses procedural draw instead of cmd.blit or cmd.DrawFullScreenMesh
                if (renderingData.cameraData.xr.enabled)
                {
                    // XR flip logic is not the same as non-XR case because XR uses draw procedure
                    // and draw procedure does not need to take projection matrix yflip into account
                    // We y-flip if
                    // 1) we are bliting from render texture to back buffer and
                    // 2) renderTexture starts UV at top
                    // XRTODO: handle scalebias and scalebiasRt for src and dst separately
                    bool    isRenderToBackBufferTarget = destination.Identifier() == cameraData.xr.renderTarget && !cameraData.xr.renderTargetIsRenderTexture;
                    bool    yflip       = isRenderToBackBufferTarget && SystemInfo.graphicsUVStartsAtTop;
                    float   flipSign    = (yflip) ? -1.0f : 1.0f;
                    Vector4 scaleBiasRt = (flipSign < 0.0f)
                        ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f)
                        : new Vector4(flipSign, 0.0f, 1.0f, 1.0f);
                    cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBiasRt);

                    cmd.DrawProcedural(Matrix4x4.identity, m_CopyDepthMaterial, 0, MeshTopology.Quads, 4);
                }
                else
#endif
                {
                    // Blit has logic to flip projection matrix when rendering to render texture.
                    // Currently the y-flip is handled in CopyDepthPass.hlsl by checking _ProjectionParams.x
                    // If you replace this Blit with a Draw* that sets projection matrix double check
                    // to also update shader.
                    // scaleBias.x = flipSign
                    // scaleBias.y = scale
                    // scaleBias.z = bias
                    // scaleBias.w = unused
                    float   flipSign    = (cameraData.IsCameraProjectionMatrixFlipped()) ? -1.0f : 1.0f;
                    Vector4 scaleBiasRt = (flipSign < 0.0f)
                        ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f)
                        : new Vector4(flipSign, 0.0f, 1.0f, 1.0f);
                    cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBiasRt);

                    cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, m_CopyDepthMaterial);
                }
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #15
0
        void RenderDirectionalCascadeShadowmap(ref ScriptableRenderContext context, ref CullResults cullResults, ref LightData lightData, ref ShadowData shadowData)
        {
            LightShadows shadowQuality    = LightShadows.None;
            int          shadowLightIndex = lightData.mainLightIndex;

            if (shadowLightIndex == -1)
            {
                return;
            }

            VisibleLight shadowLight = lightData.visibleLights[shadowLightIndex];
            Light        light       = shadowLight.light;

            Debug.Assert(shadowLight.lightType == LightType.Directional);

            if (light.shadows == LightShadows.None)
            {
                return;
            }

            Bounds bounds;

            if (!cullResults.GetShadowCasterBounds(shadowLightIndex, out bounds))
            {
                return;
            }

            CommandBuffer cmd = CommandBufferPool.Get(k_RenderDirectionalShadowmapTag);

            using (new ProfilingSample(cmd, k_RenderDirectionalShadowmapTag))
            {
                m_ShadowCasterCascadesCount = shadowData.directionalLightCascadeCount;

                int   shadowResolution = LightweightShadowUtils.GetMaxTileResolutionInAtlas(shadowData.directionalShadowAtlasWidth, shadowData.directionalShadowAtlasHeight, m_ShadowCasterCascadesCount);
                float shadowNearPlane  = light.shadowNearPlane;

                Matrix4x4 view, proj;
                var       settings = new DrawShadowsSettings(cullResults, shadowLightIndex);

                m_DirectionalShadowmapTexture = RenderTexture.GetTemporary(shadowData.directionalShadowAtlasWidth,
                                                                           shadowData.directionalShadowAtlasHeight, k_ShadowmapBufferBits, m_ShadowmapFormat);
                m_DirectionalShadowmapTexture.filterMode = FilterMode.Bilinear;
                m_DirectionalShadowmapTexture.wrapMode   = TextureWrapMode.Clamp;
                SetRenderTarget(cmd, m_DirectionalShadowmapTexture, RenderBufferLoadAction.DontCare,
                                RenderBufferStoreAction.Store, ClearFlag.Depth, Color.black, TextureDimension.Tex2D);

                bool success = false;
                for (int cascadeIndex = 0; cascadeIndex < m_ShadowCasterCascadesCount; ++cascadeIndex)
                {
                    success = LightweightShadowUtils.ExtractDirectionalLightMatrix(ref cullResults, ref shadowData, shadowLightIndex, cascadeIndex, shadowResolution, shadowNearPlane, out m_CascadeSplitDistances[cascadeIndex], out m_CascadeSlices[cascadeIndex], out view, out proj);
                    if (success)
                    {
                        LightweightShadowUtils.SetupShadowCasterConstants(cmd, ref shadowLight, proj, shadowResolution);
                        LightweightShadowUtils.RenderShadowSlice(cmd, ref context, ref m_CascadeSlices[cascadeIndex], proj,
                                                                 view, settings);
                    }
                }

                if (success)
                {
                    shadowQuality = (shadowData.supportsSoftShadows) ? light.shadows : LightShadows.Hard;
                    SetupDirectionalShadowReceiverConstants(cmd, ref shadowData, shadowLight);
                }
            }
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);

            // TODO: We should have RenderingData as a readonly but currently we need this to pass shadow rendering to litpass
            shadowData.renderedDirectionalShadowQuality = shadowQuality;
        }
예제 #16
0
            // Here you can implement the rendering logic.
            // Use <c>ScriptableRenderContext</c> to issue drawing commands or execute command buffers
            // https://docs.unity3d.com/ScriptReference/Rendering.ScriptableRenderContext.html
            // You don't have to call ScriptableRenderContext.submit, the render pipeline will call it at specific points in the pipeline.
            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                var cmd = CommandBufferPool.Get(profilerSampler.name);

                renderBounds   = StylizedGrassRenderer.Instance.bounds;
                frustrumPlanes = GeometryUtility.CalculateFrustumPlanes(StylizedGrassRenderer.Instance.renderCam);

                using (new ProfilingScope(cmd, profilerSampler))
                {
                    foreach (KeyValuePair <int, List <GrassBender> > layer in StylizedGrassRenderer.GrassBenders)
                    {
                        foreach (GrassBender b in layer.Value)
                        {
                            if (b.enabled == false)
                            {
                                continue;
                            }

                            props.SetVector("_Params", new Vector4(b.strength, b.heightOffset, b.pushStrength, b.scaleMultiplier));

                            if (b.benderType == GrassBenderBase.BenderType.Trail)
                            {
                                if (!b.trailRenderer)
                                {
                                    continue;
                                }

                                if (!b.trailRenderer.emitting)
                                {
                                    continue;
                                }

                                if (!GeometryUtility.TestPlanesAABB(frustrumPlanes, b.trailRenderer.bounds))
                                {
                                    continue;
                                }

                                m_TrailRenderer = b.trailRenderer;
                                m_TrailRenderer.SetPropertyBlock(props);

                                //Trail
                                m_TrailRenderer.emitting             = b.gameObject.activeInHierarchy;
                                m_TrailRenderer.generateLightingData = true;
                                m_TrailRenderer.widthMultiplier      = b.trailRadius;
                                m_TrailRenderer.time = b.trailLifetime;
                                m_TrailRenderer.minVertexDistance = b.trailAccuracy;
                                m_TrailRenderer.widthCurve        = b.widthOverLifetime;
                                m_TrailRenderer.colorGradient     = GrassBenderBase.GetGradient(b.strengthOverLifetime);

                                //If disabled, temporarly enable in order to bake mesh
                                trailEnabled = m_TrailRenderer.enabled ? true : false;
                                if (!trailEnabled)
                                {
                                    m_TrailRenderer.enabled = true;
                                }

                                if (b.bakedMesh == null)
                                {
                                    b.bakedMesh = new Mesh();
                                }
                                m_TrailRenderer.BakeMesh(b.bakedMesh, renderingData.cameraData.camera, false);

                                cmd.DrawMesh(b.bakedMesh, Matrix4x4.identity, GrassBenderBase.TrailMaterial, 0, 0, props);

                                //Note: Faster, but crashed when trails are disabled (Case 1200430)
                                //cmd.DrawRenderer(m_TrailRenderer, GrassBenderBase.TrailMaterial, 0, 0);

                                if (!trailEnabled)
                                {
                                    m_TrailRenderer.enabled = false;
                                }

                                //trailMesh.Clear();
                            }
                            if (b.benderType == GrassBenderBase.BenderType.ParticleSystem)
                            {
                                if (!b.particleSystem)
                                {
                                    continue;
                                }

                                if (!GeometryUtility.TestPlanesAABB(frustrumPlanes, b.particleRenderer.bounds))
                                {
                                    continue;
                                }

                                m_ParticleRenderer = b.particleRenderer;
                                m_ParticleRenderer.SetPropertyBlock(props);

                                var grad = b.particleSystem.colorOverLifetime;
                                grad.enabled = true;
                                grad.color   = GrassBenderBase.GetGradient(b.strengthOverLifetime);
                                bool localSpace = b.particleSystem.main.simulationSpace == ParticleSystemSimulationSpace.Local;

                                //Note: DrawRenderes with particle systems appear to be broken. Only renders to scene cam when it redraws. Bake the mesh down and render it instead.
                                //Todo: Create repo project and file bug report.
                                //cmd.DrawRenderer(m_ParticleRenderer, m_Material, 0, 0);
                                if (!b.bakedMesh)
                                {
                                    b.bakedMesh = new Mesh();
                                }
                                m_ParticleRenderer.BakeMesh(b.bakedMesh, renderingData.cameraData.camera);

                                cmd.DrawMesh(b.bakedMesh, localSpace ? m_ParticleRenderer.localToWorldMatrix : Matrix4x4.identity, GrassBenderBase.MeshMaterial, 0, b.alphaBlending ? 1 : 0, props);

                                //Also draw particle trails
                                if (b.hasParticleTrails)
                                {
                                    if (!b.particleTrailMesh)
                                    {
                                        b.particleTrailMesh = new Mesh();
                                    }

                                    m_ParticleRenderer.BakeTrailsMesh(b.particleTrailMesh, renderingData.cameraData.camera);
                                    cmd.DrawMesh(b.particleTrailMesh, m_ParticleRenderer.localToWorldMatrix, GrassBenderBase.TrailMaterial, 1, 0, props);
                                    //cmd.DrawRenderer(m_ParticleRenderer, GrassBenderBase.TrailMaterial, 1, 0);
                                }
                            }
                            if (b.benderType == GrassBenderBase.BenderType.Mesh)
                            {
                                if (!b.meshRenderer)
                                {
                                    continue;
                                }

                                if (!GeometryUtility.TestPlanesAABB(frustrumPlanes, b.meshRenderer.bounds))
                                {
                                    continue;
                                }

                                m_MeshRenderer = b.meshRenderer;
                                m_MeshRenderer.SetPropertyBlock(props);

                                cmd.DrawRenderer(m_MeshRenderer, GrassBenderBase.MeshMaterial, 0, b.alphaBlending ? 1 : 0);
                            }
                        }
                    }

                    //Mask edges of bend area, avoids streaking at edges
                    if (enableEdgeMasking)
                    {
                        cmd.SetGlobalTexture("_BendMapInput", BuiltinRenderTextureType.CurrentActive);
                        cmd.Blit(BuiltinRenderTextureType.CurrentActive, bendVectorID, m_MaskMat);
                        cmd.SetGlobalTexture(StylizedGrassRenderer.VECTOR_MAP_PARAM, bendVectorID);
                    }
                }
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
            }
        protected override void Render(ScriptableRenderContext RenderContext, Camera[] RenderCameras)
        {
            //Gather MeshBatch
            NativeList <FMeshBatch> MeshBatchList = GetWorld().GetMeshBatchColloctor().GetMeshBatchList();

            //Render Pipeline
            BeginFrameRendering(RenderContext, RenderCameras);
            foreach (Camera RenderCamera in RenderCameras)
            {
                RenderCamera.allowHDR = true;

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

                //Prepare VisualEffects
                VFXManager.PrepareCamera(RenderCamera);

                //Prepare ViewUnifrom
                ViewUnifrom.UnpateBufferData(false, RenderCamera);

                //View RenderFamily
                CommandBuffer CmdBuffer = CommandBufferPool.Get("");

                //Binding ViewParameter
                BeginCameraRendering(RenderContext, RenderCamera);
                CmdBuffer.DisableScissorRect();
                ViewUnifrom.BindGPUProperty(CmdBuffer);
                RenderContext.SetupCameraProperties(RenderCamera);

                //Binding VisualEffects
                VFXManager.ProcessCameraCommand(RenderCamera, CmdBuffer);

                //Culling MeshBatch
                NativeArray <FPlane>            ViewFrustum          = new NativeArray <FPlane>(6, Allocator.Persistent);
                NativeArray <FVisibleMeshBatch> VisibleMeshBatchList = new NativeArray <FVisibleMeshBatch>(MeshBatchList.Length, Allocator.TempJob);

                Plane[] FrustumPlane = GeometryUtility.CalculateFrustumPlanes(RenderCamera);
                for (int PlaneIndex = 0; PlaneIndex < 6; PlaneIndex++)
                {
                    ViewFrustum[PlaneIndex] = FrustumPlane[PlaneIndex];
                }

                CullMeshBatch CullTask = new CullMeshBatch();
                {
                    CullTask.ViewFrustum          = ViewFrustum;
                    CullTask.ViewOrigin           = RenderCamera.transform.position;
                    CullTask.MeshBatchList        = MeshBatchList;
                    CullTask.VisibleMeshBatchList = VisibleMeshBatchList;
                }
                JobHandle CullTaskHandle = CullTask.Schedule(MeshBatchList.Length, 256);

                /*SortMeshBatch SortTask = new SortMeshBatch();
                 * {
                 *  SortTask.VisibleMeshBatchList = VisibleMeshBatchList;
                 * }
                 * JobHandle SortTaskHandle = SortTask.Schedule(CullTaskHandle);*/

                //Culling Context
                ScriptableCullingParameters CullingParameter;
                RenderCamera.TryGetCullingParameters(out CullingParameter);
                CullingResults CullingResult = RenderContext.Cull(ref CullingParameter);

                CullTaskHandle.Complete();
                //SortTaskHandle.Complete();

                //Render Family
                RenderOpaqueDepth(RenderCamera, CullingResult);
                RenderOpaqueGBuffer(RenderCamera, CullingResult, VisibleMeshBatchList);
                RenderOpaqueMotion(RenderCamera, CullingResult);
                RenderSkyAtmosphere(RenderCamera);
                RenderPresentView(RenderCamera, GraphBuilder.ScopeTexture(InfinityShaderIDs.RT_ThinGBufferA), RenderCamera.targetTexture);

                //Draw DrawGizmos
                #if UNITY_EDITOR
                if (Handles.ShouldRenderGizmos())
                {
                    RenderGizmo(RenderCamera, GizmoSubset.PostImageEffects);
                }
                #endif

                //Execute RenderGraph
                GraphBuilder.Execute(RenderContext, GetWorld(), CmdBuffer, ViewUnifrom.FrameIndex);
                EndCameraRendering(RenderContext, RenderCamera);

                //Execute ViewRender
                RenderContext.ExecuteCommandBuffer(CmdBuffer);
                CommandBufferPool.Release(CmdBuffer);
                RenderContext.Submit();

                //Prepare ViewUnifrom
                ViewUnifrom.UnpateBufferData(true, RenderCamera);

                //Release View
                ViewFrustum.Dispose();
                VisibleMeshBatchList.Dispose();
            }
            EndFrameRendering(RenderContext, RenderCameras);
        }
예제 #18
0
        public static void SetPerCameraShaderVariables(ScriptableRenderContext context, Camera camera, bool renderIntoTexture = true)
        {
            Rect  pixelRect    = camera.pixelRect;
            float cameraWidth  = (float)pixelRect.width;
            float cameraHeight = (float)pixelRect.height;

            Matrix4x4 projMatrix     = GL.GetGPUProjectionMatrix(camera.projectionMatrix, renderIntoTexture);
            Matrix4x4 viewMatrix     = camera.worldToCameraMatrix;
            Matrix4x4 viewProjMatrix = projMatrix * viewMatrix;

            Matrix4x4 invViewMatrix       = Matrix4x4.Inverse(viewMatrix);
            Matrix4x4 invProjectionMatrix = Matrix4x4.Inverse(projMatrix);
            Matrix4x4 invViewProjMatrix   = Matrix4x4.Inverse(viewProjMatrix);

            float projectionFlip = SystemInfo.graphicsUVStartsAtTop ? -1.0f : 1.0f;

            float near           = camera.nearClipPlane;
            float far            = camera.farClipPlane;
            float invNear        = Mathf.Approximately(near, 0.0f) ? 0.0f : 1.0f / near;
            float invFar         = Mathf.Approximately(far, 0.0f) ? 0.0f : 1.0f / far;
            float isOrthographic = camera.orthographic ? 1.0f : 0.0f;

            // From http://www.humus.name/temp/Linearize%20depth.txt
            // But as depth component textures on OpenGL always return in 0..1 range (as in D3D), we have to use
            // the same constants for both D3D and OpenGL here.
            // OpenGL would be this:
            // zc0 = (1.0 - far / near) / 2.0;
            // zc1 = (1.0 + far / near) / 2.0;
            // D3D is this:
            float zc0 = 1.0f - far * invNear;
            float zc1 = far * invNear;

            Vector4 zBufferParams = new Vector4(zc0, zc1, zc0 * invFar, zc1 * invFar);

            if (SystemInfo.usesReversedZBuffer)
            {
                zBufferParams.y += zBufferParams.x;
                zBufferParams.x  = -zBufferParams.x;
                zBufferParams.w += zBufferParams.z;
                zBufferParams.z  = -zBufferParams.z;
            }

            Vector4 projectionParams = new Vector4(projectionFlip, near, far, 1.0f * invFar);
            Vector4 orthoParams      = new Vector4(camera.orthographicSize * camera.aspect, camera.orthographicSize, 0.0f, isOrthographic);

            CommandBuffer cmd = CommandBufferPool.Get(kPerCameraShaderVariablesTag);

            cmd.SetGlobalVector(ShaderBindings.worldSpaceCameraPos, camera.transform.position);
            cmd.SetGlobalVector(ShaderBindings.projectionParams, projectionParams);
            cmd.SetGlobalVector(ShaderBindings.screenParams, new Vector4(cameraWidth, cameraHeight, 1.0f + 1.0f / cameraWidth, 1.0f + 1.0f / cameraHeight));
            cmd.SetGlobalVector(ShaderBindings.screenSize, new Vector4(cameraWidth, cameraHeight, 1.0f / cameraWidth, 1.0f / cameraHeight));
            cmd.SetGlobalVector(ShaderBindings.zBufferParams, zBufferParams);
            cmd.SetGlobalVector(ShaderBindings.orthoParams, orthoParams);
            // TODO: missing unity_CameraWorldClipPlanes[6], currently set by context.SetupCameraProperties

            cmd.SetGlobalMatrix(ShaderBindings.matrixV, viewMatrix);
            cmd.SetGlobalMatrix(ShaderBindings.matrixP, projMatrix);
            cmd.SetGlobalMatrix(ShaderBindings.matrixVP, viewProjMatrix);

            cmd.SetGlobalMatrix(ShaderBindings.matrixIV, invViewMatrix);
            cmd.SetGlobalMatrix(ShaderBindings.matrixIP, viewMatrix);
            cmd.SetGlobalMatrix(ShaderBindings.matrixIVP, invViewProjMatrix);
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #19
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            // NOTE: Do NOT mix ProfilingScope with named CommandBuffers i.e. CommandBufferPool.Get("name").
            // Currently there's an issue which results in mismatched markers.
            CommandBuffer cmd = CommandBufferPool.Get();

            using (new ProfilingScope(cmd, m_ProfilingSampler))
            {
                // Global render pass data containing various settings.
                // x,y,z are currently unused
                // w is used for knowing whether the object is opaque(1) or alpha blended(0)
                Vector4 drawObjectPassData = new Vector4(0.0f, 0.0f, 0.0f, (m_IsOpaque) ? 1.0f : 0.0f);
                cmd.SetGlobalVector(s_DrawObjectPassDataPropID, drawObjectPassData);

                // scaleBias.x = flipSign
                // scaleBias.y = scale
                // scaleBias.z = bias
                // scaleBias.w = unused
                float   flipSign  = (renderingData.cameraData.IsCameraProjectionMatrixFlipped()) ? -1.0f : 1.0f;
                Vector4 scaleBias = (flipSign < 0.0f)
                    ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f)
                    : new Vector4(flipSign, 0.0f, 1.0f, 1.0f);
                cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBias);

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

                Camera camera    = renderingData.cameraData.camera;
                var    sortFlags = (m_IsOpaque) ? renderingData.cameraData.defaultOpaqueSortFlags : SortingCriteria.CommonTransparent;
                if (renderingData.cameraData.renderer.useDepthPriming && m_IsOpaque && (renderingData.cameraData.renderType == CameraRenderType.Base || renderingData.cameraData.clearDepth))
                {
                    sortFlags = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges | SortingCriteria.CanvasOrder;
                }

                var filterSettings = m_FilteringSettings;

                #if UNITY_EDITOR
                // When rendering the preview camera, we want the layer mask to be forced to Everything
                if (renderingData.cameraData.isPreviewCamera)
                {
                    filterSettings.layerMask = -1;
                }
                #endif

                DrawingSettings drawSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags);

                var activeDebugHandler = GetActiveDebugHandler(renderingData);
                if (activeDebugHandler != null)
                {
                    activeDebugHandler.DrawWithDebugRenderState(context, cmd, ref renderingData, ref drawSettings, ref filterSettings, ref m_RenderStateBlock,
                                                                (ScriptableRenderContext ctx, ref RenderingData data, ref DrawingSettings ds, ref FilteringSettings fs, ref RenderStateBlock rsb) =>
                    {
                        ctx.DrawRenderers(data.cullResults, ref ds, ref fs, ref rsb);
                    });
                }
                else
                {
                    context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings, ref m_RenderStateBlock);

                    // Render objects that did not match any shader pass with error shader
                    RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
                }
            }
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #20
0
        public override void Enable(bool fromInspector)
        {
            levelsNode = nodeTarget as Levels;

            base.Enable(fromInspector);

            var slider = new MinMaxSlider("Luminance", levelsNode.min, levelsNode.max, 0, 1);

            sliders.Add(slider);
            slider.RegisterValueChangedCallback(e => {
                owner.RegisterCompleteObjectUndo("Changed Luminance remap");
                levelsNode.min = e.newValue.x;
                levelsNode.max = e.newValue.y;
                foreach (var s in sliders)
                {
                    if (s != null && s.parent != null)
                    {
                        s.SetValueWithoutNotify(e.newValue);
                    }
                }
                NotifyNodeChanged();
            });
            controlsContainer.Add(slider);

            var mode = this.Q <EnumField>();

            mode.RegisterValueChangedCallback((m) => {
                UpdateMinMaxSliderVisibility((Levels.Mode)m.newValue);
            });
            UpdateMinMaxSliderVisibility(levelsNode.mode);

            // Compute histogram only when the inspector is selected
            if (fromInspector)
            {
                owner.graph.afterCommandBufferExecuted += UpdateHistogram;
                controlsContainer.RegisterCallback <DetachFromPanelEvent>(e => {
                    owner.graph.afterCommandBufferExecuted -= UpdateHistogram;
                });
            }

            void UpdateHistogram()
            {
                if (levelsNode.output != null)
                {
                    var cmd = CommandBufferPool.Get("Update Histogram");
                    HistogramUtility.ComputeHistogram(cmd, levelsNode.output, levelsNode.histogramData);
                    Graphics.ExecuteCommandBuffer(cmd);
                }
            }

            UpdateHistogram();

            void UpdateMinMaxSliderVisibility(Levels.Mode mode)
            {
                if (mode == Levels.Mode.Automatic)
                {
                    slider.style.display = DisplayStyle.None;
                }
                else
                {
                    slider.style.display = DisplayStyle.Flex;
                }
            }

            if (fromInspector)
            {
                var histogram = new HistogramView(levelsNode.histogramData, owner);
                controlsContainer.Add(histogram);
            }
        }
        public static void RenderSingleCamera(LightweightRenderPipeline pipelineInstance, ScriptableRenderContext context, Camera camera, ref CullResults cullResults, IRendererSetup setup = null)
        {
            if (pipelineInstance == null)
            {
                Debug.LogError("Trying to render a camera with an invalid render pipeline instance.");
                return;
            }

            CommandBuffer cmd = CommandBufferPool.Get(k_RenderCameraTag);

            using (new ProfilingSample(cmd, k_RenderCameraTag))
            {
                CameraData         cameraData;
                PipelineSettings   settings = pipelineInstance.settings;
                ScriptableRenderer renderer = pipelineInstance.renderer;
                InitializeCameraData(settings, camera, out cameraData);
                SetupPerCameraShaderConstants(cameraData);

                ScriptableCullingParameters cullingParameters;
                if (!CullResults.GetCullingParameters(camera, cameraData.isStereoEnabled, out cullingParameters))
                {
                    CommandBufferPool.Release(cmd);
                    return;
                }

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

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

#if UNITY_EDITOR
                // Emit scene view UI
                if (cameraData.isSceneViewCamera)
                {
                    ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
                }
#endif
                CullResults.Cull(ref cullingParameters, context, ref cullResults);

                RenderingData renderingData;
                InitializeRenderingData(settings, ref cameraData, ref cullResults,
                                        renderer.maxVisibleAdditionalLights, renderer.maxPerObjectAdditionalLights, out renderingData);

                var setupToUse = setup;
                if (setupToUse == null)
                {
                    setupToUse = defaultRendererSetup;
                }

                renderer.Clear();
                setupToUse.Setup(renderer, ref renderingData);
                renderer.Execute(context, ref renderingData);

                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
                context.Submit();
#if UNITY_EDITOR
                Handles.DrawGizmos(camera);
#endif
            }
        }
        public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            CommandBuffer cmd = CommandBufferPool.Get(_kRenderOITTag);

            using (new ProfilingSample(cmd, _kRenderOITTag))
            {
                cmd.GetTemporaryRT(_B0Handle.id, _DescriptorFloat);
                cmd.GetTemporaryRT(_B1Handle.id, _DescriptorFloat4);
                if (MomentsCount._8 == _MomentsCount)
                {
                    cmd.GetTemporaryRT(_B2Handle.id, _DescriptorFloat4);
                }
                else if (MomentsCount._6 == _MomentsCount)
                {
                    cmd.GetTemporaryRT(_B2Handle.id, _DescriptorFloat2);
                }
                CoreUtils.SetKeyword(cmd, "_MOMENT6", MomentsCount._6 == _MomentsCount);
                CoreUtils.SetKeyword(cmd, "_MOMENT8", MomentsCount._8 == _MomentsCount);
                CoreUtils.SetKeyword(cmd, "_MOMENT_HALF_PRECISION", FloatPrecision._Half == _MomentsPrecision);
                CoreUtils.SetKeyword(cmd, "_TRIGONOMETRIC", _Trigonometric);

                cmd.SetRenderTarget(_GMBinding);
                cmd.ClearRenderTarget(false, true, Color.black);

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

                Vector2 logViewDepthMinDelta = new Vector2(Mathf.Log(_ViewDepthMinMax.x), Mathf.Log(_ViewDepthMinMax.y));
                logViewDepthMinDelta.y = logViewDepthMinDelta.y - logViewDepthMinDelta.x;
                cmd.SetGlobalVector("_LogViewDepthMinDelta", logViewDepthMinDelta);
                //cmd.SetGlobalFloat("_Overestimation", 0.25f);
                //cmd.SetGlobalFloat("_MomentBias", 0);

                if (_Trigonometric)
                {
                    Vector4 _WrappingZoneParameters = new Vector4();
                    _WrappingZoneParameters.x = 3.14f;
                    _WrappingZoneParameters.y = 3.14f - 0.5f * _WrappingZoneParameters.x;
                    float a = _WrappingZoneParameters.y * 2;
                    float x = Mathf.Cos(a);
                    float y = Mathf.Sin(a);
                    float r = Mathf.Abs(y) - Mathf.Abs(x);
                    r = (x < 0) ? (2.0f - r) : r;
                    r = (y < 0) ? (6.0f - r) : r;
                    _WrappingZoneParameters.z = 1 / (7 - r);
                    _WrappingZoneParameters.w = 1 - 7 * _WrappingZoneParameters.z;
                    cmd.SetGlobalVector("_WrappingZoneParameters", _WrappingZoneParameters);
                }

                Camera camera       = renderingData.cameraData.camera;
                var    drawSettings = CreateDrawRendererSettings(camera, SortFlags.None, _RendererConfiguration, renderingData.supportsDynamicBatching);

                context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, _OITFilterSettings);

                // Render objects that did not match any shader pass with error shader
                renderer.RenderObjectsWithError(context, ref renderingData.cullResults, camera, _OITFilterSettings, SortFlags.None);
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();

                cmd.GetTemporaryRT(_MOITHandle.id, _Descriptor);
                if (renderingData.shadowData.supportsDeepShadowMaps)
                {
                    cmd.GetTemporaryRT(_GIALHandle.id, _Descriptor);
                    cmd.SetRenderTarget(_RMBinding);
                    cmd.ClearRenderTarget(false, true, Color.black);
                }
                else
                {
                    CoreUtils.SetRenderTarget(cmd,
                                              _MOITHandle.Identifier(), RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
                                              _DepthAttachmentHandle.Identifier(), RenderBufferLoadAction.Load, RenderBufferStoreAction.DontCare,
                                              ClearFlag.Color, Color.black);
                }
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();

                cmd.SetGlobalTexture("_b0", _B0Handle.id);
                cmd.SetGlobalTexture("_b1", _B1Handle.id);
                if (MomentsCount._4 != _MomentsCount)
                {
                    cmd.SetGlobalTexture("_b2", _B2Handle.id);
                }

                drawSettings.SetShaderPassName(0, new ShaderPassName("ResolveMoments"));
                context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, _OITFilterSettings);
                // Render objects that did not match any shader pass with error shader
                renderer.RenderObjectsWithError(context, ref renderingData.cullResults, camera, _OITFilterSettings, SortFlags.None);
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();


                CoreUtils.SetRenderTarget(cmd,
                                          _ColorAttachmentHandle.Identifier(), RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                                          ClearFlag.None);
                cmd.Blit(_ColorAttachmentHandle.Identifier(), _ColorAttachmentHandle.Identifier(), renderer.GetMaterial(MaterialHandle.MomentOITComposite));
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #23
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            bool isLitView = true;

#if UNITY_EDITOR
            if (renderingData.cameraData.isSceneViewCamera)
            {
                isLitView = UnityEditor.SceneView.currentDrawingSceneView.sceneLighting;
            }

            if (renderingData.cameraData.camera.cameraType == CameraType.Preview)
            {
                isLitView = false;
            }

            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;


            bool isSceneLit = Light2D.IsSceneLit(camera);
            if (isSceneLit)
            {
                m_Renderer2DData.InitializeTransient();

                CommandBuffer cmd = CommandBufferPool.Get();
                cmd.Clear();

                using (new ProfilingScope(cmd, m_ProfilingSampler))
                {
                    this.CreateNormalMapRenderTexture(renderingData, cmd);

                    cmd.SetGlobalFloat("_HDREmulationScale", m_Renderer2DData.hdrEmulationScale);
                    cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_Renderer2DData.hdrEmulationScale);
                    cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
                    cmd.SetGlobalColor("_RendererColor", Color.white);
                    this.SetShapeLightShaderGlobals(cmd);

                    context.ExecuteCommandBuffer(cmd);

                    DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);
                    DrawingSettings normalsDrawSettings  = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

                    SortingSettings sortSettings = combinedDrawSettings.sortingSettings;
                    GetTransparencySortingMode(camera, ref sortSettings);
                    combinedDrawSettings.sortingSettings = sortSettings;
                    normalsDrawSettings.sortingSettings  = sortSettings;

                    var blendStylesCount = m_Renderer2DData.lightBlendStyles.Length;
                    for (var i = 0; i < s_SortingLayers.Length;)
                    {
                        var layerToRender = s_SortingLayers[i].id;
                        var lightStats    = Light2D.GetLightStatsByLayer(layerToRender, camera);

                        cmd.Clear();
                        for (int blendStyleIndex = 0; blendStyleIndex < blendStylesCount; blendStyleIndex++)
                        {
                            uint blendStyleMask = (uint)(1 << blendStyleIndex);
                            bool blendStyleUsed = (lightStats.blendStylesUsed & blendStyleMask) > 0;

                            if (blendStyleUsed && !m_Renderer2DData.lightBlendStyles[blendStyleIndex].hasRenderTarget)
                            {
                                this.CreateBlendStyleRenderTexture(renderingData, cmd, blendStyleIndex);
                            }

                            RendererLighting.EnableBlendStyle(cmd, blendStyleIndex, blendStyleUsed);
                        }

                        context.ExecuteCommandBuffer(cmd);

                        // find the highest layer that share the same set of lights as this layer
                        var upperLayerInBatch = FindUpperBoundInBatch(i);
                        // Some renderers override their sorting layer value with short.MinValue or short.MaxValue.
                        // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue.
                        // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue.
                        var startLayerValue = (short)s_SortingLayers[i].value;
                        var lowerBound      = (i == 0) ? short.MinValue : startLayerValue;
                        var endLayerValue   = (short)s_SortingLayers[upperLayerInBatch].value;
                        var upperBound      = (upperLayerInBatch == s_SortingLayers.Length - 1) ? short.MaxValue : endLayerValue;
                        // renderer within this range share the same set of lights so they should be rendered together
                        filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound);

                        // Start Rendering
                        if (lightStats.totalNormalMapUsage > 0)
                        {
                            this.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings, depthAttachment);
                        }

                        cmd.Clear();
                        if (lightStats.totalLights > 0)
                        {
                            this.RenderLights(renderingData, cmd, layerToRender, lightStats.blendStylesUsed);
                        }
                        else
                        {
                            this.ClearDirtyLighting(cmd, lightStats.blendStylesUsed);
                        }

                        CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                        context.ExecuteCommandBuffer(cmd);

                        Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers");
                        context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings);
                        Profiler.EndSample();

                        if (lightStats.totalVolumetricUsage > 0)
                        {
                            cmd.Clear();
                            this.RenderLightVolumes(renderingData, cmd, layerToRender, colorAttachment, depthAttachment, lightStats.blendStylesUsed);
                            context.ExecuteCommandBuffer(cmd);
                            cmd.Clear();
                        }

                        // move on to the next one
                        i = upperLayerInBatch + 1;
                    }

                    cmd.Clear();
                    Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
                    this.ReleaseRenderTextures(cmd);
                    Profiler.EndSample();
                }

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

                filterSettings.sortingLayerRange = SortingLayerRange.all;
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
            else
            {
                DrawingSettings unlitDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData,
                                                                          SortingCriteria.CommonTransparent);

                CommandBuffer cmd = CommandBufferPool.Get();
                using (new ProfilingScope(cmd, m_ProfilingSamplerUnlit))
                {
                    CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                    cmd.SetGlobalTexture("_ShapeLightTexture0", Texture2D.blackTexture);
                    cmd.SetGlobalTexture("_ShapeLightTexture1", Texture2D.blackTexture);
                    cmd.SetGlobalTexture("_ShapeLightTexture2", Texture2D.blackTexture);
                    cmd.SetGlobalTexture("_ShapeLightTexture3", Texture2D.blackTexture);
                    cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
                    cmd.SetGlobalColor("_RendererColor", Color.white);
                    cmd.EnableShaderKeyword("USE_SHAPE_LIGHT_TYPE_0");
                }

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

                Profiler.BeginSample("Render Sprites Unlit");
                context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings);
                Profiler.EndSample();

                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
        }
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;
            RendererLighting.Setup(m_RendererData);

            CommandBuffer cmd = CommandBufferPool.Get("Render 2D Lighting");

            Profiler.BeginSample("RenderSpritesWithLighting - Create Render Textures");
            RendererLighting.CreateRenderTextures(cmd, camera);
            Profiler.EndSample();

            cmd.SetGlobalFloat("_LightIntensityScale", m_RendererData.lightIntensityScale);
            cmd.SetGlobalFloat("_InverseLightIntensityScale", 1.0f / m_RendererData.lightIntensityScale);
            RendererLighting.SetShapeLightShaderGlobals(cmd);

            context.ExecuteCommandBuffer(cmd);

            Profiler.BeginSample("RenderSpritesWithLighting - Prepare");
            DrawingSettings drawSettings = CreateDrawingSettings(k_CombinedRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;
            Profiler.EndSample();

            bool cleared = false;
            for (int i = 0; i < s_SortingLayers.Length; i++)
            {
                short layerValue = (short)s_SortingLayers[i].value;
                filterSettings.sortingLayerRange = new SortingLayerRange(layerValue, layerValue);

                RendererLighting.RenderNormals(context, renderingData.cullResults, drawSettings, filterSettings);

                cmd.Clear();
                int layerToRender = s_SortingLayers[i].id;
                RendererLighting.RenderLights(camera, cmd, layerToRender);

                // This should have an optimization where I can determine if this needs to be called.
                // And the clear is only needed if no previous pass has cleared the camera RT yet.
                var clearFlag  = cleared ? ClearFlag.None : ClearFlag.All;
                var clearColor = renderingData.cameraData.camera.backgroundColor;
                cleared = true;
                SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, clearFlag, clearColor, TextureDimension.Tex2D);

                context.ExecuteCommandBuffer(cmd);

                Profiler.BeginSample("RenderSpritesWithLighting - Draw Renderers");
                context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings);
                Profiler.EndSample();

                cmd.Clear();
                RendererLighting.RenderLightVolumes(camera, cmd, layerToRender);
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();
            }

            Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
            RendererLighting.ReleaseRenderTextures(cmd);
            Profiler.EndSample();

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

            filterSettings.sortingLayerRange = SortingLayerRange.all;
            RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
        }
예제 #25
0
        /// <summary>
        /// Execute the custom post processing renderers
        /// </summary>
        /// <param name="context">The scriptable render context</param>
        /// <param name="renderingData">Current rendering data</param>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            // Copy camera target description for intermediate RTs. Disable multisampling and depth buffer for the intermediate targets.
            m_IntermediateDesc                 = renderingData.cameraData.cameraTargetDescriptor;
            m_IntermediateDesc.msaaSamples     = 1;
            m_IntermediateDesc.depthBufferBits = 0;

            CommandBuffer cmd = CommandBufferPool.Get(m_PassName);

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

            int width  = m_IntermediateDesc.width;
            int height = m_IntermediateDesc.height;

            cmd.SetGlobalVector("_ScreenSize", new Vector4(width, height, 1.0f / width, 1.0f / height));

            // The variable will be true if the last renderer couldn't blit to destination.
            // This happens if there is only 1 renderer and the source is the same as the destination.
            bool requireBlitBack = false;
            // The current intermediate RT to use as a source.
            int intermediateIndex = 0;

            for (int index = 0; index < m_ActivePostProcessRenderers.Count; ++index)
            {
                var rendererIndex = m_ActivePostProcessRenderers[index];
                var renderer      = m_PostProcessRenderers[rendererIndex];

                RenderTargetIdentifier source, destination;
                if (index == 0)
                {
                    // If this is the first renderers then the source will be the external source (not intermediate).
                    source = m_Source;
                    if (m_ActivePostProcessRenderers.Count == 1)
                    {
                        // There is only one renderer, check if the source is the same as the destination
                        if (m_Source == m_Destination)
                        {
                            // Since we can't bind the same RT as a texture and a render target at the same time, we will blit to an intermediate RT.
                            destination = GetIntermediate(cmd, 0);
                            // Then we will blit back to the destination.
                            requireBlitBack = true;
                        }
                        else
                        {
                            // Otherwise, we can directly blit from source to destination.
                            destination = m_Destination;
                        }
                    }
                    else
                    {
                        // If there is more than one renderer, we will need to the intermediate RT anyway.
                        destination = GetIntermediate(cmd, intermediateIndex);
                    }
                }
                else
                {
                    // If this is not the first renderer, we will want to the read from the intermediate RT.
                    source = GetIntermediate(cmd, intermediateIndex);
                    if (index == m_ActivePostProcessRenderers.Count - 1)
                    {
                        // If this is the last renderer, blit to the destination directly.
                        destination = m_Destination;
                    }
                    else
                    {
                        // Otherwise, flip the intermediate RT index and set as destination.
                        // This will act as a ping pong process between the 2 RT where color data keeps moving back and forth while being processed on each pass.
                        intermediateIndex = 1 - intermediateIndex;
                        destination       = GetIntermediate(cmd, intermediateIndex);
                    }
                }

                using (new ProfilingScope(cmd, m_ProfilingSamplers[rendererIndex]))
                {
                    // If the renderer was not already initialized, initialize it.
                    if (!renderer.Initialized)
                    {
                        renderer.InitializeInternal();
                    }
                    // Execute the renderer.
                    renderer.Render(cmd, source, destination, ref renderingData, injectionPoint);
                }
            }

            // If blit back is needed, blit from the intermediate RT to the destination (see above for explanation)
            if (requireBlitBack)
            {
                Blit(cmd, m_Intermediate[0].Identifier(), m_Destination);
            }

            // Release allocated Intermediate RTs.
            CleanupIntermediate(cmd);

            // Send command buffer for execution, then release it.
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
        public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (null == renderer)
            {
                throw new ArgumentException("renderer");
            }

            _MainLightFilteredSMDescriptor.width  = renderingData.shadowData.mainLightShadowmapWidth;
            _MainLightFilteredSMDescriptor.height = renderingData.shadowData.mainLightShadowmapHeight;

            if (renderingData.shadowData.requiresScreenSpaceShadowResolve)
            {
                _MainLightFilteredSMDescriptor.autoGenerateMips = false;
                _MainLightFilteredSMDescriptor.useMipMap        = false;
            }

            CommandBuffer cmd = CommandBufferPool.Get(_FilterEVSM);

            if (!CheckEnabled(ref renderingData))
            {
                foreach (var kvp in _TypeKeywords)
                {
                    CoreUtils.SetKeyword(cmd, kvp.Value, false);
                }
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
                return;
            }
            using (new ProfilingSample(cmd, _FilterEVSM))
            {
                foreach (var kvp in _TypeKeywords)
                {
                    CoreUtils.SetKeyword(cmd, kvp.Value, kvp.Key == _ShadowMapsType);
                }

                CoreUtils.SetKeyword(cmd, _KeywordESMLogFilter, _LogFilterESM);
                CoreUtils.SetKeyword(cmd, _KeywordShadowMapsPrecision, _ShadowMapsPrecision == ShadowMapsPrecision.Single);

                cmd.SetGlobalVector(_UniformEVSMExponent, _EVSMExponent);
                cmd.GetTemporaryRT(_FilteredMainLightSMHandle.id, _MainLightFilteredSMDescriptor, FilterMode.Bilinear);
                cmd.GetTemporaryRT(_TmpMainLightSMHandle.id, _MainLightFilteredSMDescriptor, FilterMode.Bilinear);
                RenderTargetIdentifier srti = _TmpMainLightSMHandle.Identifier();
                RenderTargetIdentifier drti = _FilteredMainLightSMHandle.Identifier();

                CoreUtils.SetKeyword(cmd, _KeywordFirstFilter, true);

                cmd.SetGlobalVector(_UniformHorizontalVertical, Vector2.right);
                SetRenderTarget(cmd, srti, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Color, Color.black, TextureDimension.Tex2D);
                cmd.Blit(srti, srti, _Material);

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

                CoreUtils.SetKeyword(cmd, _KeywordFirstFilter, false);

                cmd.SetGlobalTexture(_UniformMainTex, srti);
                cmd.SetGlobalVector(_UniformHorizontalVertical, Vector2.up);
                SetRenderTarget(cmd, drti, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Color, Color.black, TextureDimension.Tex2D);
                cmd.Blit(srti, drti, _Material);

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

                //for (int i = 1; i <= 1; i++)
                //{
                //    int p = 1 << i;
                //    cmd.SetGlobalVector("_HorizontalVertical", Vector2.right * p);
                //    SetRenderTarget(cmd, srti, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Color, Color.black, TextureDimension.Tex2D);
                //    cmd.SetGlobalTexture("_MainTex", drti);
                //    cmd.Blit(drti, srti, _Material);

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

                //    cmd.SetGlobalVector("_HorizontalVertical", Vector2.up * p);
                //    SetRenderTarget(cmd, drti, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Color, Color.black, TextureDimension.Tex2D);
                //    cmd.SetGlobalTexture("_MainTex", srti);
                //    cmd.Blit(srti, drti, _Material);

                //    context.ExecuteCommandBuffer(cmd);
                //    cmd.Clear();
                //}
            }
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
예제 #27
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (m_CopyDepthMaterial == null)
            {
                Debug.LogErrorFormat("Missing {0}. {1} render pass will not execute. Check for missing reference in the renderer resources.", m_CopyDepthMaterial, GetType().Name);
                return;
            }

            CommandBuffer cmd = CommandBufferPool.Get();

            using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.CopyDepth)))
            {
                RenderTargetIdentifier depthSurface     = source.Identifier();
                RenderTargetIdentifier copyDepthSurface = destination.Identifier();

                RenderTextureDescriptor descriptor = renderingData.cameraData.cameraTargetDescriptor;
                int cameraSamples = descriptor.msaaSamples;

                CameraData cameraData = renderingData.cameraData;

                switch (cameraSamples)
                {
                case 8:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                case 4:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                case 2:
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                // MSAA disabled
                default:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;
                }

                cmd.SetGlobalTexture("_CameraDepthAttachment", source.Identifier());

                // Blit has logic to flip projection matrix when rendering to render texture.
                // Currently the y-flip is handled in CopyDepthPass.hlsl by checking _ProjectionParams.x
                // If you replace this Blit with a Draw* that sets projection matrix double check
                // to also update shader.
                // scaleBias.x = flipSign
                // scaleBias.y = scale
                // scaleBias.z = bias
                // scaleBias.w = unused
                float   flipSign    = (cameraData.IsCameraProjectionMatrixFlipped()) ? -1.0f : 1.0f;
                Vector4 scaleBiasRt = (flipSign < 0.0f)
                    ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f)
                    : new Vector4(flipSign, 0.0f, 1.0f, 1.0f);
                cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBiasRt);

                cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, m_CopyDepthMaterial);
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
        public override void Render(ScriptableRenderContext context, Camera[] cameras)
        {
            if (m_IsCameraRendering)
            {
                Debug.LogWarning("Nested camera rendering is forbidden. If you are calling camera.Render inside OnWillRenderObject callback, use BeginCameraRender callback instead.");
                return;
            }
            pipelineAsset.savedXRGraphicsConfig.renderScale   = pipelineAsset.renderScale;
            pipelineAsset.savedXRGraphicsConfig.viewportScale = 1.0f; // Placeholder until viewportScale is all hooked up
            // Apply any changes to XRGConfig prior to this point
            pipelineAsset.savedXRGraphicsConfig.SetConfig();

            base.Render(context, cameras);
            BeginFrameRendering(cameras);

            GraphicsSettings.lightsUseLinearIntensity = true;
            SetupPerFrameShaderConstants();

            // Sort cameras array by camera depth
            Array.Sort(cameras, m_CameraComparer);

            foreach (Camera camera in cameras)
            {
                BeginCameraRendering(camera);
                string        renderCameraTag = "Render " + camera.name;
                CommandBuffer cmd             = CommandBufferPool.Get(renderCameraTag);
                using (new ProfilingSample(cmd, renderCameraTag))
                {
                    CameraData cameraData;
                    InitializeCameraData(camera, out cameraData);
                    SetupPerCameraShaderConstants(cameraData);

                    ScriptableCullingParameters cullingParameters;
                    if (!CullResults.GetCullingParameters(camera, cameraData.isStereoEnabled, out cullingParameters))
                    {
                        CommandBufferPool.Release(cmd);
                        continue;
                    }

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

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

#if UNITY_EDITOR
                    try
#endif
                    {
                        m_IsCameraRendering = true;
#if UNITY_EDITOR
                        // Emit scene view UI
                        if (cameraData.isSceneViewCamera)
                        {
                            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
                        }
#endif
                        CullResults.Cull(ref cullingParameters, context, ref m_CullResults);
                        List <VisibleLight> visibleLights = m_CullResults.visibleLights;

                        RenderingData renderingData;
                        InitializeRenderingData(ref cameraData, visibleLights,
                                                m_Renderer.maxSupportedLocalLightsPerPass, m_Renderer.maxSupportedVertexLights,
                                                out renderingData);

                        var setup = cameraData.camera.GetComponent <IRendererSetup>();
                        if (setup == null)
                        {
                            setup = defaultRendererSetup;
                        }

                        setup.Setup(m_Renderer, ref context, ref m_CullResults, ref renderingData);
                        m_Renderer.Execute(ref context, ref m_CullResults, ref renderingData);
                    }
#if UNITY_EDITOR
                    catch (Exception)
                    {
                        CommandBufferPool.Release(cmd);
                        throw;
                    }
                    finally
#endif
                    {
                        m_IsCameraRendering = false;
                    }
                }
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
                context.Submit();
            }
        }
        // Here you can implement the rendering logic.
        // Use <c>ScriptableRenderContext</c> to issue drawing commands or execute command buffers
        // https://docs.unity3d.com/ScriptReference/Rendering.ScriptableRenderContext.html
        // You don't have to call ScriptableRenderContext.submit, the render pipeline will call it at specific points in the pipeline.
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cb = CommandBufferPool.Get("SSPR");

            int dispatchThreadGroupXCount = GetRTWidth() / SHADER_NUMTHREAD_X;  //divide by shader's numthreads.x
            int dispatchThreadGroupYCount = GetRTHeight() / SHADER_NUMTHREAD_Y; //divide by shader's numthreads.y
            int dispatchThreadGroupZCount = 1;                                  //divide by shader's numthreads.z

            if (settings.ShouldRenderSSPR)
            {
                cb.SetComputeVectorParam(cs, Shader.PropertyToID("_RTSize"), new Vector2(GetRTWidth(), GetRTHeight()));
                cb.SetComputeFloatParam(cs, Shader.PropertyToID("_HorizontalPlaneHeightWS"), settings.HorizontalReflectionPlaneHeightWS);

                cb.SetComputeFloatParam(cs, Shader.PropertyToID("_FadeOutScreenBorderWidthVerticle"), settings.FadeOutScreenBorderWidthVerticle);
                cb.SetComputeFloatParam(cs, Shader.PropertyToID("_FadeOutScreenBorderWidthHorizontal"), settings.FadeOutScreenBorderWidthHorizontal);
                cb.SetComputeVectorParam(cs, Shader.PropertyToID("_CameraDirection"), renderingData.cameraData.camera.transform.forward);
                cb.SetComputeFloatParam(cs, Shader.PropertyToID("_ScreenLRStretchIntensity"), settings.ScreenLRStretchIntensity);
                cb.SetComputeFloatParam(cs, Shader.PropertyToID("_ScreenLRStretchThreshold"), settings.ScreenLRStretchThreshold);
                cb.SetComputeVectorParam(cs, Shader.PropertyToID("_FinalTintColor"), settings.TintColor);


                if (ShouldUseSinglePassUnsafeAllowFlickeringDirectResolve())
                {
                    ////////////////////////////////////////////////
                    //Android Path
                    ////////////////////////////////////////////////

                    //kernel MobilePathsinglePassColorRTDirectResolve
                    int kernel_MobilePathSinglePassColorRTDirectResolve = cs.FindKernel("MobilePathSinglePassColorRTDirectResolve");
                    cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "ColorRT", _SSPR_ColorRT_rti);
                    cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "PosWSyRT", _SSPR_PosWSyRT_rti);
                    cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "_CameraOpaqueTexture", new RenderTargetIdentifier("_CameraOpaqueTexture"));
                    cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "_CameraDepthTexture", new RenderTargetIdentifier("_CameraDepthTexture"));
                    cb.DispatchCompute(cs, kernel_MobilePathSinglePassColorRTDirectResolve, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount);
                }
                else
                {
                    ////////////////////////////////////////////////
                    //Non-Android Path (PC/console..)
                    ////////////////////////////////////////////////

                    //kernel NonMobilePathClear
                    int kernel_NonMobilePathClear = cs.FindKernel("NonMobilePathClear");
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathClear, "HashRT", _SSPR_PackedDataRT_rti);
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathClear, "ColorRT", _SSPR_ColorRT_rti);
                    cb.DispatchCompute(cs, kernel_NonMobilePathClear, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount);

                    //kernel NonMobilePathRenderHashRT
                    int kernel_NonMobilePathRenderHashRT = cs.FindKernel("NonMobilePathRenderHashRT");
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathRenderHashRT, "HashRT", _SSPR_PackedDataRT_rti);
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathRenderHashRT, "_CameraDepthTexture", new RenderTargetIdentifier("_CameraDepthTexture"));

                    cb.DispatchCompute(cs, kernel_NonMobilePathRenderHashRT, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount);

                    //resolve to ColorRT
                    int kernel_NonMobilePathResolveColorRT = cs.FindKernel("NonMobilePathResolveColorRT");
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathResolveColorRT, "_CameraOpaqueTexture", new RenderTargetIdentifier("_CameraOpaqueTexture"));
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathResolveColorRT, "ColorRT", _SSPR_ColorRT_rti);
                    cb.SetComputeTextureParam(cs, kernel_NonMobilePathResolveColorRT, "HashRT", _SSPR_PackedDataRT_rti);
                    cb.DispatchCompute(cs, kernel_NonMobilePathResolveColorRT, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount);
                }

                //optional shared pass to improve result only: fill RT hole
                if (settings.ApplyFillHoleFix)
                {
                    int kernel_FillHoles = cs.FindKernel("FillHoles");
                    cb.SetComputeTextureParam(cs, kernel_FillHoles, "ColorRT", _SSPR_ColorRT_rti);
                    cb.SetComputeTextureParam(cs, kernel_FillHoles, "PackedDataRT", _SSPR_PackedDataRT_rti);
                    cb.DispatchCompute(cs, kernel_FillHoles, Mathf.CeilToInt(dispatchThreadGroupXCount / 2f), Mathf.CeilToInt(dispatchThreadGroupYCount / 2f), dispatchThreadGroupZCount);
                }

                //send out to global, for user's shader to sample reflection result RT (_MobileSSPR_ColorRT)
                //where _MobileSSPR_ColorRT's rgb is reflection color, a is reflection usage 0~1 for user's shader to lerp with fallback reflection probe's rgb
                cb.SetGlobalTexture(_SSPR_ColorRT_pid, _SSPR_ColorRT_rti);
                cb.EnableShaderKeyword("_MobileSSPR");
            }
            else
            {
                //allow user to skip SSPR related code if disabled
                cb.DisableShaderKeyword("_MobileSSPR");
            }

            context.ExecuteCommandBuffer(cb);
            CommandBufferPool.Release(cb);

            //======================================================================
            //draw objects(e.g. reflective wet ground plane) with lightmode "MobileSSPR", which will sample _MobileSSPR_ColorRT
            DrawingSettings   drawingSettings   = CreateDrawingSettings(lightMode_SSPR_sti, ref renderingData, SortingCriteria.CommonOpaque);
            FilteringSettings filteringSettings = new FilteringSettings(RenderQueueRange.all);

            context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings);
        }
    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);
            camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;

            //Setup sort, filter, draw settings
            var sortingSettings = new SortingSettings(camera);

            var drawSettings = new DrawingSettings(m_StochasticColorPassName, sortingSettings);
            drawSettings.perObjectData |= PerObjectData.MotionVectors;

            var filterSettings = new FilteringSettings(RenderQueueRange.all);
            filterSettings.excludeMotionVectorObjects = false;

            InitializeFrameSettings();

            // Render background
            DrawSkybox(camera, context);

            // Push constants
            PushShadingConstants(camera, context, 0);

            //------------------------------------------------------------------------------------
            // STOCHASTIC TRANSPARENCY IMPLEMENTATION
            //------------------------------------------------------------------------------------
            {
                //1.) Transmission Pass
                RenderTransmission(sortingSettings, drawSettings, filterSettings, cull, context);

                //2.) Stochastic Depths
                RenderStochasticDepths(sortingSettings, drawSettings, filterSettings, cull, context);

                //3.) Stochastic Colors
                RenderStochasticColors(sortingSettings, drawSettings, filterSettings, cull, context);

                //4.) Final Pass
                RenderFinalPass(context, 0, camera);
            }
            //------------------------------------------------------------------------------------

            CommandBuffer cmd = CommandBufferPool.Get("PostProcessing");

            // Post Process
            var postProcessLayer = camera.GetComponent <PostProcessLayer>();
            if (postProcessLayer != null)
            {
                RenderPostProcess(postProcessLayer, cmd, camera);
            }

            // Flip to back buffer
            cmd.Blit(m_ColorBuffer, BuiltinRenderTextureType.CameraTarget);
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);

            context.Submit();
        }
    }