public void Render(ScriptableRenderContext renderContext, Camera camera) { #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif // UNITY_EDITOR renderContext.SetupCameraProperties(camera, camera.stereoEnabled); if (camera.TryGetCullingParameters(true, out ScriptableCullingParameters cullingParameters) == false) { return; } CullResults = renderContext.Cull(ref cullingParameters); CommandBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, 0, CubemapFace.Unknown, -1); if (camera.stereoEnabled) { CommandBuffer.SetSinglePassStereo(SinglePassStereoMode.Instancing); renderContext.StartMultiEye(camera); } else { CommandBuffer.SetSinglePassStereo(SinglePassStereoMode.None); } CommandBuffer.ClearRenderTarget(true, true, camera.backgroundColor, 1.0f); renderContext.ExecuteCommandBuffer(CommandBuffer); CommandBuffer.Clear(); SortingSettings sortingSettings = new SortingSettings(camera); sortingSettings.criteria = SortingCriteria.CommonOpaque; DrawingSettings drawSettings = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), sortingSettings); drawSettings.enableDynamicBatching = false; drawSettings.enableInstancing = true; drawSettings.sortingSettings = sortingSettings; drawSettings.perObjectData = 0; FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.opaque); renderContext.DrawRenderers(CullResults, ref drawSettings, ref filterSettings); if (camera.stereoEnabled) { renderContext.StopMultiEye(camera); } #if UNITY_EDITOR if (UnityEditor.Handles.ShouldRenderGizmos()) { renderContext.DrawGizmos(camera, GizmoSubset.PreImageEffects); renderContext.DrawGizmos(camera, GizmoSubset.PostImageEffects); } #endif // UNITY_EDITOR if (camera.stereoEnabled) { renderContext.StereoEndRender(camera); } renderContext.Submit(); }
void Submit() { _buffer.EndSample(sampleName); ExecuteBuffer(); _context.Submit(); }
private void RenderCamera(ref ScriptableRenderContext context, Camera camera) { if (m_ShadowMap == null) { m_ShadowMap = new RenderTexture(1024, 1024, 24, RenderTextureFormat.Shadowmap); m_ShadowMap.name = "Shadow Map"; m_ShadowMap.Create(); } if (camera.TryGetCullingParameters(out ScriptableCullingParameters cullingParameters)) { // Start camera render RenderPipeline.BeginCameraRendering(context, camera); cullingParameters.shadowDistance = 30; // Perform culling operations CullingResults cullingResults = context.Cull(ref cullingParameters); // Shadow map rendering Matrix4x4 worldToShadowMatrix = Matrix4x4.identity; bool didRenderShadowMap = RenderShadowMaps(ref context, ref cullingResults, ref worldToShadowMatrix); // Setup camera for rendering context.SetupCameraProperties(camera); // Clear camera CommandBuffer cb_ClearCamera = new CommandBuffer(); cb_ClearCamera.name = "ClearCamera"; cb_ClearCamera.SetRenderTarget(camera.targetTexture); cb_ClearCamera.ClearRenderTarget(true, true, camera.backgroundColor); context.ExecuteCommandBuffer(cb_ClearCamera); // Draw opaque objects SortingSettings sortSettings = new SortingSettings(camera); sortSettings.criteria = SortingCriteria.CommonOpaque; FilteringSettings filterSettings = FilteringSettings.defaultValue; filterSettings.renderQueueRange = RenderQueueRange.opaque; if (didRenderShadowMap) { CommandBuffer cb = new CommandBuffer(); cb.name = "Set up shadow shader properties"; cb.SetGlobalTexture("_ShadowMapTexture", m_ShadowMap); cb.SetGlobalMatrix("_WorldToShadowMatrix", worldToShadowMatrix); cb.SetGlobalVector("_LightDirection", -cullingResults.visibleLights[0].light.transform.forward); // Direction towards the light context.ExecuteCommandBuffer(cb); } DrawingSettings opaqueDrawSettings = new DrawingSettings(s_OpaquePassTag, sortSettings); context.DrawRenderers(cullingResults, ref opaqueDrawSettings, ref filterSettings); // Draw skybox context.DrawSkybox(camera); // Final submission context.Submit(); // End camera render RenderPipeline.EndCameraRendering(context, camera); } }
void Submit() { buffer.EndSample(bufferName); ExecuteBuffer(); context.Submit(); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { context.DrawSkybox(cameras[0]); context.Submit(); }
protected virtual void RenderCamera(ScriptableRenderContext context, Camera camera) { var p = Matrix4x4.Perspective(30, 16.0f / 9, .3f, 1000); var v = new Vector4(.5f, .5f, 10, 1); camera.TryGetCullingParameters(out var cullingParameters); var cmd = CommandBufferPool.Get(camera.name); cmd.Clear(); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } var cullResults = context.Cull(ref cullingParameters); var projectionMat = camera.projectionMatrix; var jitteredProjectionMat = projectionMat; jitteredProjectionMat.m02 += (projectionJitter.Current.x * 2 - 1) / camera.pixelWidth; jitteredProjectionMat.m12 += (projectionJitter.Current.x * 2 - 1) / camera.pixelHeight; var renderingData = new RenderingData() { camera = camera, cullResults = cullResults, ColorTarget = BuiltinRenderTextureType.CameraTarget, DepthTarget = BuiltinRenderTextureType.CameraTarget, ColorBufferFormat = RenderTextureFormat.Default, shadowMapData = new Dictionary <Light, ShadowMapData>(), FrameID = frameID, DiscardFrameBuffer = true, ViewMatrix = camera.worldToCameraMatrix, ProjectionMatrix = projectionMat, JitteredProjectionMatrix = jitteredProjectionMat, ProjectionJitter = new Vector2(.5f, .5f), NextProjectionJitter = new Vector2(.5f, .5f), }; this.Setup(context, ref renderingData); context.SetupCameraProperties(camera, false); InitRenderQueue(camera); SetupLight(ref renderingData); /*RenderTargetBinding binding = new RenderTargetBinding(); * binding.colorRenderTargets = new RenderTargetIdentifier[] { ColorTarget }; * binding.colorLoadActions = new RenderBufferLoadAction[] { RenderBufferLoadAction.Clear }; * binding.depthRenderTarget = DepthTarget; * binding.depthLoadAction = RenderBufferLoadAction.Clear; * binding.colorStoreActions = new RenderBufferStoreAction[] { RenderBufferStoreAction.Store }; * binding.depthStoreAction = RenderBufferStoreAction.Store;*/ cmd.SetRenderTarget(ColorTarget, DepthTarget); cmd.ClearRenderTarget(true, true, Color.black, 1); cmd.SetRenderTarget(DepthTarget, DepthTarget); cmd.ClearRenderTarget(true, true, Color.black, 1); cmd.SetRenderTarget(ColorTarget, DepthTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); context.DrawSkybox(camera); foreach (var pass in RenderPassQueue) { pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } // Draw global user passes foreach (var pass in globalUserPasses) { pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } // Draw user passes var userPasses = camera.GetComponents <UserPass>(); foreach (var pass in userPasses) { if (pass.Global) { continue; } pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } cmd.Blit(renderingData.ColorTarget, BuiltinRenderTextureType.CameraTarget); //cmd.CopyTexture(renderingData.DepthTarget, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); if (camera.cameraType == CameraType.SceneView) { context.DrawGizmos(camera, GizmoSubset.PreImageEffects); context.DrawGizmos(camera, GizmoSubset.PostImageEffects); } foreach (var pass in RenderPassQueue) { pass.Cleanup(context, ref renderingData); } foreach (var pass in globalUserPasses) { pass.Cleanup(context, ref renderingData); } foreach (var pass in userPasses) { pass.Cleanup(context, ref renderingData); } this.Cleanup(context, ref renderingData); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); projectionJitter.Next = renderingData.NextProjectionJitter; }
protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length]; UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length); GraphicsSettings.useScriptableRenderPipelineBatching = resources.useSRPBatcher; SceneController.SetState(); #if UNITY_EDITOR int tempID = Shader.PropertyToID("_TempRT"); foreach (var pair in bakeList) { PipelineCamera pipelineCam = pair.pipelineCamera; for (int i = 0; i < pair.worldToCamera.Length; ++i) { pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i]; pipelineCam.cam.projectionMatrix = pair.projection[i]; pipelineCam.cameraTarget = tempID; data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear); Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags); data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0); data.buffer.ReleaseTemporaryRT(tempID); data.ExecuteCommandBuffer(); renderContext.Submit(); } pair.worldToCamera.Dispose(); pair.projection.Dispose(); renderContext.ExecuteCommandBuffer(pair.buffer); pair.buffer.Clear(); renderContext.Submit(); } bakeList.Clear(); #endif if (PipelineCamera.allCamera.isCreated) { foreach (var cam in cameras) { PipelineCamera pipelineCam; UIntPtr pipelineCamPtr; if (!PipelineCamera.allCamera.Get(cam.gameObject.GetInstanceID(), out pipelineCamPtr)) { #if UNITY_EDITOR renderingEditor = true; var pos = cam.transform.eulerAngles; pos.z = 0; cam.transform.eulerAngles = pos; if (!PipelineCamera.allCamera.Get(Camera.main.gameObject.GetInstanceID(), out pipelineCamPtr)) { continue; } #else continue; #endif } else { renderingEditor = false; } pipelineCam = MUnsafeUtility.GetObject <PipelineCamera>(pipelineCamPtr.ToPointer()); Render(pipelineCam, ref renderContext, cam, propertyCheckedFlags); data.ExecuteCommandBuffer(); renderContext.Submit(); } if (bufferAfterFrame.Count > 0) { foreach (var i in bufferAfterFrame) { i(data.buffer); } data.ExecuteCommandBuffer(); bufferAfterFrame.Clear(); renderContext.Submit(); } } else { if (bufferAfterFrame.Count > 0) { foreach (var i in bufferAfterFrame) { i(data.buffer); } Graphics.ExecuteCommandBuffer(data.buffer); bufferAfterFrame.Clear(); } } }
protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length]; bool needSubmit = false; CustomDrawRequest.Initialize(); UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length); GraphicsSettings.useScriptableRenderPipelineBatching = resources.useSRPBatcher; SceneController.SetState(); data.context = renderContext; data.resources = resources; if (motionVectorMatricesBuffer == null || !motionVectorMatricesBuffer.IsValid()) { motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4)); } else if (motionVectorMatricesBuffer.count < MotionVectorDrawer.Capacity) { motionVectorMatricesBuffer.Dispose(); motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4)); } MotionVectorDrawer.ExecuteBeforeFrame(motionVectorMatricesBuffer); data.buffer.SetGlobalBuffer(ShaderIDs._LastFrameModel, motionVectorMatricesBuffer); #if UNITY_EDITOR int tempID = Shader.PropertyToID("_TempRT"); foreach (var pair in bakeList) { PipelineCamera pipelineCam = pair.pipelineCamera; for (int i = 0; i < pair.worldToCamera.Length; ++i) { pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i]; pipelineCam.cam.projectionMatrix = pair.projection[i]; pipelineCam.cameraTarget = tempID; data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear); Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags); data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0); data.buffer.ReleaseTemporaryRT(tempID); data.ExecuteCommandBuffer(); renderContext.Submit(); needSubmit = false; } pair.worldToCamera.Dispose(); pair.projection.Dispose(); renderContext.ExecuteCommandBuffer(pair.buffer); pair.buffer.Clear(); renderContext.Submit(); needSubmit = false; } bakeList.Clear(); #endif foreach (var cam in preFrameRenderCamera) { Render(cam, ref renderContext, cam.cam, propertyCheckedFlags); data.ExecuteCommandBuffer(); renderContext.Submit(); needSubmit = false; } preFrameRenderCamera.Clear(); if (CustomDrawRequest.allEvents.Count > 0 || JobProcessEvent.allEvents.Count > 0) { foreach (var i in CustomDrawRequest.allEvents) { i.PrepareJob(resources); } foreach (var i in JobProcessEvent.allEvents) { i.PrepareJob(); } JobHandle.ScheduleBatchedJobs(); foreach (var i in CustomDrawRequest.allEvents) { i.FinishJob(); } } if (useBeforeFrameBuffer) { renderContext.ExecuteCommandBuffer(m_beforeFrameBuffer); m_beforeFrameBuffer.Clear(); needSubmit = true; useBeforeFrameBuffer = false; } foreach (var cam in cameras) { PipelineCamera pipelineCam = cam.GetComponent <PipelineCamera>(); if (!pipelineCam) { #if UNITY_EDITOR if (cam.cameraType == CameraType.SceneView) { renderingEditor = true; var pos = cam.transform.eulerAngles; pos.z = 0; cam.transform.eulerAngles = pos; if (!Camera.main || !(pipelineCam = Camera.main.GetComponent <PipelineCamera>())) { continue; } } else if (cam.cameraType == CameraType.Game) { renderingEditor = false; pipelineCam = cam.gameObject.AddComponent <PipelineCamera>(); } else { continue; } #else renderingEditor = false; pipelineCam = cam.gameObject.AddComponent <PipelineCamera>(); #endif } else { renderingEditor = false; } Render(pipelineCam, ref renderContext, cam, propertyCheckedFlags); data.ExecuteCommandBuffer(); #if UNITY_EDITOR if (renderingEditor) { renderContext.DrawGizmos(cam, GizmoSubset.PostImageEffects); } #endif renderContext.Submit(); needSubmit = false; } if (useAfterFrameBuffer) { renderContext.ExecuteCommandBuffer(m_afterFrameBuffer); m_afterFrameBuffer.Clear(); needSubmit = true; useAfterFrameBuffer = false; } if (needSubmit) { renderContext.Submit(); } MotionVectorDrawer.ExecuteAfterFrame(); foreach (var i in JobProcessEvent.allEvents) { i.FinishJob(); } }
void Submit() { context.Submit(); }
private void Submit() { buffer.EndSample(SampleName); ExecuteBuffer(); context.Submit(); }
// Main entry point for our scriptable render loop public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras) { bool stereoEnabled = XRSettings.isDeviceActive; foreach (Camera camera in cameras) { // Culling ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets context.SetupCameraProperties(camera, stereoEnabled); // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine if (stereoEnabled) { context.StartMultiEye(camera); } // clear depth buffer CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw skybox context.DrawSkybox(camera); // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); //************************************************************* // Block RenderStateBlock rsb = new RenderStateBlock(RenderStateMask.Depth | RenderStateMask.Blend | RenderStateMask.Raster | RenderStateMask.Stencil); DepthState ds = rsb.depthState;// ds.writeEnabled = true; ds.compareFunction = CompareFunction.LessEqual; rsb.depthState = ds; // BlendState bs = rsb.blendState; // RenderTargetBlendState rs0 = bs.blendState0; // bs.alphaToMask = false; rs0.sourceColorBlendMode = BlendMode.SrcAlpha; rs0.destinationColorBlendMode = BlendMode.One; rs0.colorBlendOperation = BlendOp.Add; rs0.sourceAlphaBlendMode = BlendMode.Zero; rs0.destinationAlphaBlendMode = BlendMode.One; rs0.alphaBlendOperation = BlendOp.Add; rs0.writeMask = ColorWriteMask.All; bs.blendState0 = rs0; // rsb.blendState = bs; // RasterState rs = rsb.rasterState; // rs.cullingMode = CullMode.Off; rs.depthClip = false; rs.offsetFactor = 0; rs.offsetUnits = 0; rsb.rasterState = rs;// StencilState ss = rsb.stencilState;// rsb.stencilReference = 0; ss.compareFunction = CompareFunction.Disabled; ss.compareFunctionBack = CompareFunction.Disabled; ss.compareFunctionFront = CompareFunction.Disabled; ss.failOperation = StencilOp.Keep; ss.failOperationBack = StencilOp.Keep; ss.failOperationFront = StencilOp.Keep; ss.passOperation = StencilOp.Keep; ss.passOperationBack = StencilOp.Keep; ss.passOperationFront = StencilOp.Keep; ss.zFailOperation = StencilOp.Keep; ss.zFailOperationBack = StencilOp.Keep; ss.zFailOperationFront = StencilOp.Keep; ss.readMask = 255; ss.writeMask = 255; ss.enabled = true; rsb.stencilState = ss;// //************************************************************** //mapping RenderStateBlock rsb_opaque = new RenderStateBlock(RenderStateMask.Raster | RenderStateMask.Stencil); rsb_opaque.rasterState = rsb.rasterState; rsb_opaque.stencilState = rsb.stencilState; rsb_opaque.stencilReference = rsb.stencilReference; RenderStateBlock rsb_trans = new RenderStateBlock(RenderStateMask.Blend); rsb_trans.blendState = rsb.blendState; RenderStateBlock rsb_over = new RenderStateBlock(RenderStateMask.Raster | RenderStateMask.Depth | RenderStateMask.Stencil); rsb_over.depthState = rsb.depthState; rsb_over.rasterState = rsb.rasterState; rsb_over.stencilState = rsb.stencilState; rsb_over.stencilReference = rsb.stencilReference; List <RenderStateMapping> rsm = new List <RenderStateMapping> { new RenderStateMapping("Opaque", rsb_opaque), new RenderStateMapping("Transparent", rsb_trans), new RenderStateMapping("Overlay", rsb_over) }; //************************************************************** // Draw opaque objects using BasicPass shader pass filterSettings.layerMask = LayerMask.GetMask("Default"); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // WITH RENDERSTATEBLOCK OPAQUE filterSettings.layerMask = LayerMask.GetMask("TransparentFX"); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsb); // WITH RENDERSTATEMAPPING OPAQUE filterSettings.layerMask = LayerMask.GetMask("Ignore Raycast"); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsm); //************************************************************** // Draw transparent objects using BasicPass shader pass filterSettings.layerMask = LayerMask.GetMask("Default"); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // WITH RENDERSTATEBLOCK TRANSPARENT filterSettings.layerMask = LayerMask.GetMask("TransparentFX"); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsb); // WITH RENDERSTATEMAPPING TRANSPARENT filterSettings.layerMask = LayerMask.GetMask("Ignore Raycast"); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsm); //************************************************************** if (stereoEnabled) { context.StopMultiEye(camera); // StereoEndRender will reset state on the camera to pre-Stereo settings, // and invoke XR based events/callbacks. context.StereoEndRender(camera); } context.Submit(); } }
void Render(ScriptableRenderContext context, Camera camera) { // 剔除参数 ScriptableCullingParameters cullingParameters; // 获取剔除参数 if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { // 如果相机设定非法,直接返回 return; } // 设置阴影参数 cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); // 仅在编辑模式下 #if UNITY_EDITOR // 仅在渲染场景视图时。否则游戏视图中的UI元素会被渲染两次 if (camera.cameraType == CameraType.SceneView) { // 当canvas的渲染被设置在世界空间时,UI元素不会出现在场景视图中 // 需要手动指定以使其正确显示 ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif // 剔除 CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { // 由于该值会被保留为上一个物体使用的值,因此需要手动设置 cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } // 设置unity_MatrixVP,以及一些其他属性 context.SetupCameraProperties(camera); // 获取摄像机的定制后处理栈 var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; // 只影响游戏摄像机 bool scaledRendering = (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game; int renderWidth = camera.pixelWidth; int renderHeight = camera.pixelHeight; if (scaledRendering) { renderWidth = (int)(renderWidth * renderScale); renderHeight = (int)(renderHeight * renderScale); } // 摄像机是否开启MSAA int renderSamples = camera.allowMSAA ? msaaSamples : 1; // 开启渲染到纹理 bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack; // 是否需要深度纹理(深度纹理不支持MSAA) bool needsDepth = activeStack && activeStack.NeedsDepth; bool needsDirectDepth = needsDepth && renderSamples == 1; // 不使用MSAA bool needsDepthOnlyPass = needsDepth && renderSamples > 1; // 使用MSAA、 // 纹理格式 RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; // 获取并设置渲染目标,用于后处理 if (renderToTexture) { cameraBuffer.GetTemporaryRT( cameraColorTextureId, renderWidth, renderHeight, needsDirectDepth ? 0 : 24, FilterMode.Bilinear, format, RenderTextureReadWrite.Default, renderSamples ); if (needsDepth) { cameraBuffer.GetTemporaryRT( cameraDepthTextureId, renderWidth, renderHeight, 24, FilterMode.Point, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear, 1 // 1表示不使用MSAA ); } if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } } // 清空 CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); // 设置采样标志,用于在Frame Debugger中组织结构 cameraBuffer.BeginSample("HY Render Camera"); // 设置光数据 cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visibleLightAttenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsId, visibleLightSpotDirections); // 执行指令缓冲。这并不会立即执行指令,只是将指令拷贝到上下文的内部缓冲中 context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // 绘制设定 // camera参数设定排序和剔除层,pass参数指定使用哪一个shader pass var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags }; // 仅在有可见光时设置,否则Unity会崩溃 if (cull.visibleLights.Count > 0) { // 指定Unity为每个物体传输光索引数据 drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } // 指定使用反射探针,如果场景中没有反射探针,则使用天空球的立方体贴图 drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps; // 指定排序,从前往后 drawSettings.sorting.flags = SortFlags.CommonOpaque; // 过滤设定 // true表示包括所有物体 var filterSettings = new FilterRenderersSettings(true) { // 绘制不透明物体,渲染队列为[0,2500] renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // 绘制天空盒 // camera参数仅用来判断是否绘制天空盒(根据camera的清空标志位) context.DrawSkybox(camera); // 后处理 if (activeStack) { // depth-only pass if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawRendererSettings( camera, new ShaderPassName("DepthOnly") ) { flags = drawFlags }; depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque; cameraBuffer.SetRenderTarget( cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); cameraBuffer.ClearRenderTarget(true, false, Color.clear); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.DrawRenderers( cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings ); } activeStack.RenderAfterOpaque( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } // 指定排序,从后往前 drawSettings.sorting.flags = SortFlags.CommonTransparent; // 绘制透明物体,渲染队列为[2501,5000] filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); DrawDefaultPipeline(context, camera); // 后处理 if (renderToTexture) { if (activeStack) { activeStack.RenderAfterTransparent( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); } else { cameraBuffer.Blit( cameraColorTextureId, BuiltinRenderTextureType.CameraTarget ); } cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId); if (needsDepth) { cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId); } } cameraBuffer.EndSample("HY Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // 提交指令 context.Submit(); // 释放阴影纹理 if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } // 释放层级阴影纹理 if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Color Texture Descriptor RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.graphicsFormat = m_ColorFormat; colorRTDesc.depthBufferBits = depthBufferBits; colorRTDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); colorRTDesc.msaaSamples = 1; colorRTDesc.enableRandomWrite = true; //For compute //Depth Texture Descriptor RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); depthRTDesc.colorFormat = RenderTextureFormat.Depth; depthRTDesc.depthBufferBits = depthBufferBits; //Set texture temp RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear); context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); DrawingSettings drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings) { perObjectData = PerObjectData.None, overrideMaterial = depthOnlyMaterial, overrideMaterialPassIndex = 0 }; //Clear Depth Texture CommandBuffer cmdDepth = new CommandBuffer(); cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag"; cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture cmdDepth.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdDepth); cmdDepth.Release(); //Draw Depth with Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsDepth.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings); //Draw Depth with Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettingsDepth.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings); //To let shader has _CameraDepthTexture CommandBuffer cmdDepthTexture = new CommandBuffer(); cmdDepthTexture.name = "(" + camera.name + ")" + "Depth Texture"; cmdDepthTexture.SetGlobalTexture(m_DepthRTid, m_DepthRT); context.ExecuteCommandBuffer(cmdDepthTexture); cmdDepthTexture.Release(); //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(m_ColorRT); //Remember to set target cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Run Compute shader if (m_PipelineAsset.computeShader != null) { CommandBuffer cmdCompute = new CommandBuffer(); cmdCompute.name = "(" + camera.name + ")" + "Compute"; cmdCompute.SetComputeIntParam(m_PipelineAsset.computeShader, "range", m_PipelineAsset.detectRange); cmdCompute.SetComputeFloatParam(m_PipelineAsset.computeShader, "detect", m_PipelineAsset.edgeDetect); cmdCompute.SetComputeTextureParam(m_PipelineAsset.computeShader, _kernel, m_ColorRTid, m_ColorRT); cmdCompute.SetComputeTextureParam(m_PipelineAsset.computeShader, _kernel, m_DepthRTid, m_DepthRT); cmdCompute.DispatchCompute(m_PipelineAsset.computeShader, _kernel, camera.pixelWidth / 8 + 1, camera.pixelHeight / 8 + 1, 1); context.ExecuteCommandBuffer(cmdCompute); cmdCompute.Release(); } //Blit the content back to screen CommandBuffer cmdBlitToCam = new CommandBuffer(); cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera"; cmdBlitToCam.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmdBlitToCam); cmdBlitToCam.Release(); //Clean Up CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_DepthRTid); cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { return; } #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif BeginCameraRendering(context, camera); _cullingResults = context.Cull(ref cullingParameters); if (_cullingResults.visibleLights.Length > 0) { ConfigureLights(); if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountId, Vector4.zero); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visibleLightAttenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsId, visibleLightSpotDirections); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); SortingSettings sortingSettings = new SortingSettings(camera); sortingSettings.criteria = SortingCriteria.CommonOpaque; DrawingSettings drawingSettings = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), sortingSettings); drawingSettings.enableInstancing = _instancing; drawingSettings.enableDynamicBatching = _dynamicBatching; if (_cullingResults.visibleLights.Length > 0) { drawingSettings.perObjectData = PerObjectData.LightIndices; } FilteringSettings filteringSettings = FilteringSettings.defaultValue; filteringSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(_cullingResults, ref drawingSettings, ref filteringSettings); context.DrawSkybox(camera); sortingSettings.criteria = SortingCriteria.CommonTransparent; filteringSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(_cullingResults, ref drawingSettings, ref filteringSettings); DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); EndCameraRendering(context, camera); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } }
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; } ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, IsStereoEnabled(camera), out cullingParameters)) { 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); 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 }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Color Texture Descriptor RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.colorFormat = m_ColorFormat; colorRTDesc.depthBufferBits = depthBufferBits; colorRTDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); colorRTDesc.msaaSamples = 1; colorRTDesc.enableRandomWrite = false; //Get Temp Texture for Color Texture CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); cmdTempId.SetRenderTarget(m_ColorRT); //so that result won't flip context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings1 = new DrawingSettings(m_PassName1, sortingSettings); DrawingSettings drawSettings2 = new DrawingSettings(m_PassName2, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Native Arrays for Attachaments NativeArray <AttachmentDescriptor> renderPassAttachments = new NativeArray <AttachmentDescriptor>(4, Allocator.Temp); renderPassAttachments[0] = m_Albedo; renderPassAttachments[1] = m_Emission; renderPassAttachments[2] = m_Output; renderPassAttachments[3] = m_Depth; NativeArray <int> renderPassColorAttachments = new NativeArray <int>(2, Allocator.Temp); renderPassColorAttachments[0] = 0; renderPassColorAttachments[1] = 1; NativeArray <int> renderPassOutputAttachments = new NativeArray <int>(1, Allocator.Temp); renderPassOutputAttachments[0] = 2; //Clear Attachements m_Output.ConfigureTarget(m_ColorRT, false, true); m_Output.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1, 0); m_Albedo.ConfigureClear(camera.backgroundColor, 1, 0); m_Emission.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1, 0); m_Depth.ConfigureClear(new Color(), 1, 0); //More clean to use ScopedRenderPass instead of BeginRenderPass+EndRenderPass using (context.BeginScopedRenderPass(camera.pixelWidth, camera.pixelHeight, 1, renderPassAttachments, 3)) { //Output to Albedo & Emission using (context.BeginScopedSubPass(renderPassColorAttachments, false)) { //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings1.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings1, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings1.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings1, ref filterSettings); } //Read from Albedo & Emission, then output to Output using (context.BeginScopedSubPass(renderPassOutputAttachments, renderPassColorAttachments)) { //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings2.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings2, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings2.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings2, ref filterSettings); } } //Blit To Camera so that the CameraTarget has content and make sceneview works CommandBuffer cmd = new CommandBuffer(); cmd.name = "Cam:" + camera.name + " BlitToCamera"; cmd.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Release(); //CleanUp Texture CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); //Submit the CommandBuffers context.Submit(); //CleanUp NativeArrays renderPassAttachments.Dispose(); renderPassColorAttachments.Dispose(); renderPassOutputAttachments.Dispose(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(cameras); foreach (Camera camera in cameras) { BeginCameraRendering(camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects if (m_PipelineAsset.drawOpaqueObjects) //Use the settings on the asset { sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); } //Transparent objects if (m_PipelineAsset.drawTransparentObjects) //Use the settings on the asset { sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); } context.Submit(); } }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { cameraBuffer.SetGlobalVector( lightIndicesOffsetAndCountID, Vector4.zero ); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ) { flags = drawFlags }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightProbeProxyVolume; drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
/// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { CameraData cameraData = renderingData.cameraData; Camera camera = cameraData.camera; var activeDebugHandler = GetActiveDebugHandler(renderingData); if (activeDebugHandler != null) { // 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 (activeDebugHandler.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); } }
void Submit(ScriptableRenderContext context, Camera camera) { buffer.EndSample("Render"); ExecuteBuffer(context, camera); context.Submit(); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(cameras); foreach (Camera camera in cameras) { BeginCameraRendering(camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Set Depth texture temp RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); depthRTDesc.colorFormat = RenderTextureFormat.Depth; depthRTDesc.depthBufferBits = depthBufferBits; cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear); context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); DrawingSettings drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings) { perObjectData = PerObjectData.None, overrideMaterial = depthOnlyMaterial, overrideMaterialPassIndex = 0 }; //Clear Depth Texture CommandBuffer cmdDepth = new CommandBuffer(); cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag"; cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture cmdDepth.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdDepth); cmdDepth.Release(); //Draw Depth with Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsDepth.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings); //To let shader has _CameraDepthTexture CommandBuffer cmdDepthTexture = new CommandBuffer(); cmdDepthTexture.name = "(" + camera.name + ")" + "Depth Texture"; cmdDepthTexture.SetGlobalTexture(m_DepthRTid, m_DepthRT); context.ExecuteCommandBuffer(cmdDepthTexture); cmdDepthTexture.Release(); //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); //Rember to reset target cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Clean Up CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_DepthRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); } }
private void RenderScene(Camera camera) { // Clear the screen var clearFlags = camera.clearFlags; _currentBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); // Set up view port, view matrix and projection matrix // context.SetupCameraProperties(camera); var cameraTransform = camera.transform; var cameraForward = cameraTransform.forward; var cameraPosition = cameraTransform.position; var viewPort = camera.pixelRect; var viewMatrix = camera.worldToCameraMatrix; var projectionMatrix = camera.projectionMatrix; _currentBuffer.SetViewport(viewPort); _currentBuffer.SetViewProjectionMatrices(viewMatrix, projectionMatrix); var farClipPlane = camera.farClipPlane; var nearClipPlane = camera.nearClipPlane; var clipDistance = farClipPlane - nearClipPlane; var zBufferParams = new Vector4(clipDistance / nearClipPlane, 1, clipDistance / (farClipPlane * nearClipPlane), 1 / farClipPlane); _currentBuffer.SetGlobalFloat(ShaderManager.ALPHA_TEST_DEPTH_CUTOFF, @params.alphaTestDepthCutoff); _currentBuffer.SetGlobalVector(ShaderManager.Z_BUFFER_PARAMS, zBufferParams); _currentBuffer.SetComputeVectorParam(@params.tbrComputeShader, ShaderManager.Z_BUFFER_PARAMS, zBufferParams); _currentBuffer.SetComputeMatrixParam(@params.tbrComputeShader, ShaderManager.UNITY_MATRIX_V, viewMatrix); _currentBuffer.SetComputeMatrixParam(@params.tbrComputeShader, ShaderManager.UNITY_INVERSE_P, projectionMatrix.inverse); ExecuteCurrentBuffer(); // Only need to construct UI meshes under Editor mode #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); #endif // Object culling // todo maybe add gpu culling pipeline in the future (compute shader based, AABB/OBB intersection tests) if (!camera.TryGetCullingParameters(out var cullingParameters)) return; cullingParameters.shadowDistance = Mathf.Min(@params.sunlightParams.shadowDistance, farClipPlane); var cull = _context.Cull(ref cullingParameters); var sortingSettings = new SortingSettings(camera) { criteria = SortingCriteria.QuantizedFrontToBack | SortingCriteria.OptimizeStateChanges }; // Render depth and normal textures var drawSettings = new DrawingSettings(ShaderTagManager.SRP_DEFAULT_UNLIT, sortingSettings) { enableDynamicBatching = @params.enableDynamicBatching, enableInstancing = @params.enableInstancing }; var filterSettings = FilteringSettings.defaultValue; filterSettings.layerMask = camera.cullingMask; filterSettings.renderQueueRange = RenderQueueRange.transparent; var pixelWidth = camera.pixelWidth; var pixelHeight = camera.pixelHeight; GenerateRTs(pixelWidth, pixelHeight); ResetRenderTarget(OpaqueNormalId, DepthId, true, true, 1, Color.black); ExecuteCurrentBuffer(); // Depth prepass (with opaque normal rendered) var depthNormalDrawSettings = new DrawingSettings(ShaderTagManager.DEPTH_NORMAL, sortingSettings) { enableDynamicBatching = @params.enableDynamicBatching, enableInstancing = @params.enableInstancing }; filterSettings.renderQueueRange = ShaderManager.OPAQUE_RENDER_QUEUE_RANGE; _context.DrawRenderers(cull, ref depthNormalDrawSettings, ref filterSettings); sortingSettings.criteria = SortingCriteria.OptimizeStateChanges; depthNormalDrawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = ShaderManager.ALPHA_TEST_QUEUE_RANGE; _context.DrawRenderers(cull, ref depthNormalDrawSettings, ref filterSettings); var screenThreadGroupsX = pixelWidth / 8; var screenThreadGroupsY = pixelHeight / 8; if (pixelWidth % 8 != 0) screenThreadGroupsX++; if (pixelHeight % 8 != 0) screenThreadGroupsY++; var depthCopyKernel = @params.generalComputeShader.FindKernel("CopyDepth"); _currentBuffer.SetComputeTextureParam(@params.generalComputeShader, depthCopyKernel, ShaderManager.DEPTH_TEXTURE, DepthId); _currentBuffer.SetComputeTextureParam(@params.generalComputeShader, depthCopyKernel, ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId); _currentBuffer.DispatchCompute(@params.generalComputeShader, depthCopyKernel, screenThreadGroupsX, screenThreadGroupsY, 1); _currentBuffer.SetGlobalTexture(ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId); // Stencil prepass ResetRenderTarget(OpaqueNormalId, DepthId, false, false, 1, Color.black); ExecuteCurrentBuffer(); var stencilDrawSettings = new DrawingSettings(ShaderTagManager.STENCIL, sortingSettings) { enableDynamicBatching = @params.enableDynamicBatching, enableInstancing = @params.enableInstancing }; filterSettings.renderQueueRange = RenderQueueRange.all; _context.DrawRenderers(cull, ref stencilDrawSettings, ref filterSettings); var transparentDepthDrawSettings = new DrawingSettings(ShaderTagManager.DEPTH, sortingSettings) { enableDynamicBatching = @params.enableDynamicBatching, enableInstancing = @params.enableInstancing }; filterSettings.renderQueueRange = RenderQueueRange.transparent; _context.DrawRenderers(cull, ref transparentDepthDrawSettings, ref filterSettings); // Tile-based light culling var depthBoundTextureWidth = pixelWidth / @params.depthTileResolution; var depthBoundTextureHeight = pixelHeight / @params.depthTileResolution; if (pixelWidth % @params.depthTileResolution != 0) depthBoundTextureWidth++; if (pixelHeight % @params.depthTileResolution != 0) depthBoundTextureHeight++; var tileThreadGroupsX = depthBoundTextureWidth / 16; var tileThreadGroupsY = depthBoundTextureHeight / 9; if (depthBoundTextureWidth % 16 != 0) tileThreadGroupsX++; if (depthBoundTextureHeight % 9 != 0) tileThreadGroupsY++; // Debug.Log(pixelWidth + ", " + pixelHeight); var depthBoundKernel = @params.tbrComputeShader.FindKernel("GenerateDepthBound"); _currentBuffer.SetComputeFloatParams(@params.tbrComputeShader, ShaderManager.TILE_NUMBER, (float) depthBoundTextureWidth, (float) depthBoundTextureHeight); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthBoundKernel, ShaderManager.DEPTH_TEXTURE, DepthId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthBoundKernel, ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthBoundKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId); _currentBuffer.DispatchCompute(@params.tbrComputeShader, depthBoundKernel, tileThreadGroupsX, tileThreadGroupsY, 1); ExecuteCurrentBuffer(); var depthMaskKernel = @params.tbrComputeShader.FindKernel("GenerateDepthMask"); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.DEPTH_TEXTURE, DepthId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.OPAQUE_DEPTH_TEXTURE, OpaqueDepthId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthMaskKernel, ShaderManager.DEPTH_MASK_TEXTURE, DepthMaskId); _currentBuffer.DispatchCompute(@params.tbrComputeShader, depthMaskKernel, tileThreadGroupsX, tileThreadGroupsY, 1); ExecuteCurrentBuffer(); var depthFrustumKernel = @params.tbrComputeShader.FindKernel("GenerateDepthFrustum"); _currentBuffer.SetComputeFloatParams(@params.tbrComputeShader, ShaderManager.CAMERA_FORWARD, cameraForward.x, cameraForward.y, cameraForward.z); _currentBuffer.SetComputeFloatParams(@params.tbrComputeShader, ShaderManager.CAMERA_POSITION, cameraPosition.x, cameraPosition.y, cameraPosition.z); // _currentBuffer.SetComputeVectorParam(@params.tbrComputeShader, ShaderManager.Z_BUFFER_PARAMS, zBufferParams); _currentBuffer.SetComputeMatrixParam(@params.tbrComputeShader, ShaderManager.UNITY_INVERSE_VP, (camera.projectionMatrix * camera.worldToCameraMatrix).inverse); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthFrustumKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, depthFrustumKernel, ShaderManager.DEPTH_FRUSTUM_TEXTURE, DepthFrustumId); _currentBuffer.DispatchCompute(@params.tbrComputeShader, depthFrustumKernel, tileThreadGroupsX, tileThreadGroupsY, 1); ExecuteCurrentBuffer(); var allLights = cull.visibleLights; var lightIndexMap = cull.GetLightIndexMap(Allocator.Temp); var sunlightColor = new Vector4(0, 0, 0); var sunlightDirection = new Vector4(0, 0, 0); if (sunlight.Exists()) { sunlightDirection = sunlight.transform.localToWorldMatrix.GetDirectionFromLocalTransform(); sunlightColor = sunlight.color * sunlight.intensity; } _currentBuffer.SetGlobalVector(ShaderManager.SUNLIGHT_COLOR, sunlightColor); _currentBuffer.SetGlobalVector(ShaderManager.SUNLIGHT_DIRECTION, sunlightDirection); var pointLightCountMax = @params.pointLightParams.enabled ? @params.pointLightParams.maxPerFrame : 0; var spotLightCountMax = @params.spotLightParams.enabled ? @params.spotLightParams.maxPerFrame : 0; var pointLightShadowMax = @params.pointLightParams.enabled ? @params.pointLightParams.maxShadowCount : 0; var spotLightShadowMax = @params.spotLightParams.enabled ? @params.spotLightParams.maxShadowCount : 0; var sunlightIndex = 0; var pointLightIndices = new int[pointLightShadowMax]; var spotLightIndices = new int[spotLightShadowMax]; var shadowPointLights = new Light[pointLightShadowMax]; var shadowSpotLights = new Light[spotLightShadowMax]; var pointLightIndex = 0; var spotLightIndex = 0; var pointLightShadowIndex = 0u; var spotLightShadowIndex = 0u; for (int i = 0, l = allLights.Length; i < l; i++) { var visibleLight = allLights[i]; var lightType = allLights[i].lightType; switch (lightType) { case LightType.Point: if (pointLightIndex >= pointLightCountMax) continue; var originalPointLight = visibleLight.light; var pointLightColor = visibleLight.finalColor; var pointLight = new PointLight { // color = new float3(pointLightColor.r, pointLightColor.g, pointLightColor.b), sphere = new float4(visibleLight.light.transform.position, visibleLight.range) }; if (originalPointLight.shadows != LightShadows.None && pointLightShadowIndex < pointLightShadowMax) { // pointLight.shadowStrength = originalPointLight.shadowStrength; pointLight.shadowIndex = pointLightShadowIndex + 1; pointLightIndices[pointLightShadowIndex] = lightIndexMap[i]; shadowPointLights[pointLightShadowIndex] = originalPointLight; pointLightShadowIndex++; } else pointLight.shadowIndex = 0; _pointLights[pointLightIndex] = pointLight; pointLightIndex++; break; case LightType.Spot: if (spotLightIndex >= spotLightCountMax) continue; var originalSpotLight = visibleLight.light; var spotLightColor = visibleLight.finalColor; var spotLightDirection = visibleLight.localToWorldMatrix.GetDirectionFromLocalTransform(); var spotLightAngle = Mathf.Deg2Rad * visibleLight.spotAngle * .5f; var spotLight = new SpotLight { // color = new float3(spotLightColor.r, spotLightColor.g, spotLightColor.b), cone = new Cone(visibleLight.localToWorldMatrix.GetPositionFromLocalTransform(), spotLightAngle, visibleLight.range, new float3(spotLightDirection.x, spotLightDirection.y, spotLightDirection.z)), // innerAngle = Mathf.Deg2Rad * originalSpotLight.innerSpotAngle * .5f, // nearClip = originalSpotLight.shadowNearPlane }; if (originalSpotLight.shadows != LightShadows.None && spotLightShadowIndex < spotLightShadowMax) { // spotLight.shadowStrength = originalSpotLight.shadowStrength; spotLight.shadowIndex = spotLightShadowIndex + 1; spotLightIndices[spotLightShadowIndex] = lightIndexMap[i]; shadowSpotLights[spotLightShadowIndex] = originalSpotLight; spotLightShadowIndex++; } else spotLight.shadowIndex = 0; _spotLights[spotLightIndex] = spotLight; spotLightIndex++; break; case LightType.Directional: if (allLights[i].light == sunlight) sunlightIndex = lightIndexMap[i]; break; } } if (@params.sunlightParams.shadowOn && sunlight.Exists() && sunlight.shadows != LightShadows.None) { _currentBuffer.EnableShaderKeyword(ShaderManager.SUNLIGHT_SHADOWS); RenderCascadedDirectionalShadow(cull, sunlightIndex, sunlight, cullingParameters.shadowDistance); } else _currentBuffer.DisableShaderKeyword(ShaderManager.SUNLIGHT_SHADOWS); if (@params.pointLightParams.shadowOn) { _currentBuffer.EnableShaderKeyword(ShaderManager.POINT_LIGHT_SHADOWS); RenderPointLightShadow(cull, (int) pointLightShadowIndex, shadowPointLights, pointLightIndices); // if (pointLightShadowCount > 0) RenderPointLightShadow(context, cull, shadowPointLights[0], pointLightIndices[0]); } else _currentBuffer.DisableShaderKeyword(ShaderManager.POINT_LIGHT_SHADOWS); if (@params.spotLightParams.shadowOn) { _currentBuffer.EnableShaderKeyword(ShaderManager.SPOT_LIGHT_SHADOWS); RenderSpotLightShadow(cull, (int) spotLightShadowIndex, shadowSpotLights, spotLightIndices); } else _currentBuffer.DisableShaderKeyword(ShaderManager.SPOT_LIGHT_SHADOWS); Extensions.Resize(ref _pointLightBuffer, pointLightIndex); Extensions.Resize(ref _spotLightBuffer, spotLightIndex); _pointLightBuffer.SetData(_pointLights, 0, 0, pointLightIndex); _spotLightBuffer.SetData(_spotLights, 0, 0, spotLightIndex); var pointLightKernel = @params.tbrComputeShader.FindKernel("CullPointLight"); _currentBuffer.SetComputeIntParam(@params.tbrComputeShader, ShaderManager.POINT_LIGHT_COUNT, pointLightIndex); _currentBuffer.SetComputeBufferParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.POINT_LIGHT_BUFFER, _pointLightBuffer); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.DEPTH_BOUND_TEXTURE, DepthBoundId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.DEPTH_MASK_TEXTURE, DepthMaskId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.DEPTH_FRUSTUM_TEXTURE, DepthFrustumId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, pointLightKernel, ShaderManager.CULLED_POINT_LIGHT_TEXTURE, CulledPointLightId); _currentBuffer.DispatchCompute(@params.tbrComputeShader, pointLightKernel, tileThreadGroupsX, tileThreadGroupsY, 1); var spotLightKernel = @params.tbrComputeShader.FindKernel("CullSpotLight"); _currentBuffer.SetComputeIntParam(@params.tbrComputeShader, ShaderManager.SPOT_LIGHT_COUNT, spotLightIndex); _currentBuffer.SetComputeBufferParam(@params.tbrComputeShader, spotLightKernel, ShaderManager.SPOT_LIGHT_BUFFER, _spotLightBuffer); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, spotLightKernel, ShaderManager.DEPTH_FRUSTUM_TEXTURE, DepthFrustumId); _currentBuffer.SetComputeTextureParam(@params.tbrComputeShader, spotLightKernel, ShaderManager.CULLED_SPOT_LIGHT_TEXTURE, CulledSpotLightId); _currentBuffer.DispatchCompute(@params.tbrComputeShader, spotLightKernel, tileThreadGroupsX, tileThreadGroupsY, 1); ExecuteCurrentBuffer(); _currentBuffer.SetGlobalTexture(ShaderManager.CULLED_POINT_LIGHT_TEXTURE, CulledPointLightId); _currentBuffer.SetGlobalTexture(ShaderManager.CULLED_SPOT_LIGHT_TEXTURE, CulledSpotLightId); _currentBuffer.SetGlobalBuffer(ShaderManager.POINT_LIGHT_BUFFER, _pointLightBuffer); _currentBuffer.SetGlobalBuffer(ShaderManager.SPOT_LIGHT_BUFFER, _spotLightBuffer); ExecuteCurrentBuffer(); _context.SetupCameraProperties(camera); ResetRenderTarget(ColorBufferId, OpaqueDepthId, false, true, 0, Color.black); ExecuteCurrentBuffer(); // Opaque pass sortingSettings.criteria = SortingCriteria.OptimizeStateChanges; drawSettings.overrideMaterial = null; filterSettings.renderQueueRange = ShaderManager.OPAQUE_RENDER_QUEUE_RANGE; _context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // Alpha test pass sortingSettings.criteria = SortingCriteria.OptimizeStateChanges; filterSettings.renderQueueRange = ShaderManager.ALPHA_TEST_QUEUE_RANGE; _context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // Skybox Pass if ((camera.clearFlags & CameraClearFlags.Skybox) != 0) _context.DrawSkybox(camera); ResetRenderTarget(ColorBufferId, DepthId, false, false, 1, Color.black); ExecuteCurrentBuffer(); // Transparent Pass filterSettings.renderQueueRange = RenderQueueRange.transparent; _context.DrawRenderers(cull, ref drawSettings, ref filterSettings); if (@params.ditherTransparentParams.blurOn && @params.ditherTransparentParams.blurMaterial != null) DitherTransparentBlur(pixelWidth >> @params.ditherTransparentParams.downSamples, pixelHeight >> @params.ditherTransparentParams.downSamples); // Blit color buffer to camera target (normally screen) _currentBuffer.Blit(ColorBufferId, BuiltinRenderTextureType.CameraTarget); #if UNITY_EDITOR if (@params.testMaterialOn) { @params.testMaterial.SetInt("_TestInt", @params.testInt); _currentBuffer.Blit(BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CurrentActive, @params.testMaterial); // _currentBuffer.Blit(PointLightShadowmapId, BuiltinRenderTextureType.CurrentActive); if (@params.depthBoundOn) _currentBuffer.Blit(DepthBoundId, BuiltinRenderTextureType.CurrentActive); } #endif ExecuteCurrentBuffer(); #if UNITY_EDITOR if (@params.gizmosOn) _context.DrawGizmos(camera, GizmoSubset.PostImageEffects); #endif // Release temporary render textures ReleaseRTs(); // Release unmanaged objects // DisposeComputeBuffers(); ExecuteCurrentBuffer(); _context.Submit(); // allLights.Dispose(); lightIndexMap.Dispose(); }
public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, SRP07CustomParameter SRP07CP) { string tx = ""; foreach (Camera camera in cameras) { ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). context.SetupCameraProperties(camera); // clear depth buffer CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(true, !SRP07CP.DrawSkybox, SRP07CP.ClearColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); if (SRP07CP.DrawSkybox) { // Draw skybox context.DrawSkybox(camera); } // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); // //////////////////////////////////////////////////////////// VisibleLight[] ls = cull.visibleLights.ToArray(); DrawShadowsSettings[] shadowsSettings = new DrawShadowsSettings[ls.Length]; for (int i = 0; i < shadowsSettings.Length; i++) { shadowsSettings[i] = new DrawShadowsSettings(cull, i); } /* * if(camera == Camera.main) //Only generate result from main cam * { * tx += "DrawShadowsSettings" + "\n"+ "\n"; * * for (int i=0; i<ls.Length; i++) * { * tx += "lightIndex = " + shadowsSettings[i].lightIndex + " (" + ls[i].light.name + ") " + "\n"; * tx += "splitData.cullingPlaneCount = " + shadowsSettings[i].splitData.cullingPlaneCount + "\n"; * tx += "splitData.cullingSphere = " + shadowsSettings[i].splitData.cullingSphere + "\n"+ "\n"; * } * * // Output to text * if (textMesh != null) * { * textMesh.text = tx; * Debug.Log("<color=#0F0>TextMesh is updated</color>"); * } * else * { * tx = "<color=#F00>TextMesh is null</color> Please hit play if you hasn't"; * Debug.Log(tx); * } * } */ // //////////////////////////////////////////////////////////// if (SRP07CP.DrawOpaque) { // Draw opaque objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); for (int i = 0; i < shadowsSettings.Length; i++) { //if(ls[i].light.shadows != LightShadows.None) //context.DrawShadows(ref shadowsSettings[i]); } } if (SRP07CP.DrawTransparent) { // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); } context.Submit(); } }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR //ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); //cameraBuffer.DisableShaderKeyword(clippingKeyword); } } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); //cameraBuffer.DisableShaderKeyword(clippingKeyword); } context.SetupCameraProperties(camera); var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; bool scaledRendering = (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game; int renderWidth = camera.pixelWidth; int renderHeight = camera.pixelHeight; if (scaledRendering) { renderWidth = (int)(renderWidth * renderScale); renderHeight = (int)(renderHeight * renderScale); } int renderSamples = camera.allowMSAA ? msaaSamples : 1; bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack; bool needsDepth = activeStack && activeStack.NeedsDepth; bool needsDirectDepth = needsDepth && renderSamples == 1; bool needsDepthOnlyPass = needsDepth && renderSamples > 1; RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; if (renderToTexture) { cameraBuffer.GetTemporaryRT( cameraColorTextureId, renderWidth, renderHeight, needsDirectDepth ? 0 : 24, FilterMode.Bilinear, format, RenderTextureReadWrite.Default, renderSamples ); if (needsDepth) { cameraBuffer.GetTemporaryRT( cameraDepthTextureId, renderWidth, renderHeight, 24, FilterMode.Point, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear, 1 ); } if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } } CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); cameraBuffer.SetGlobalVectorArray( visibleLightOcclusionMasksId, visibleLightOcclusionMasks ); globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y; cameraBuffer.SetGlobalVector(globalShadowDataId, globalShadowData); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags //, //rendererConfiguration = RendererConfiguration.PerObjectLightIndices8 }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightProbeProxyVolume | RendererConfiguration.PerObjectShadowMask | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume; drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); if (activeStack) { if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawRendererSettings( camera, new ShaderPassName("DepthOnly") ) { flags = drawFlags }; depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque; cameraBuffer.SetRenderTarget( cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); cameraBuffer.ClearRenderTarget(true, false, Color.clear); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.DrawRenderers( cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings ); } activeStack.RenderAfterOpaque( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); //cameraBuffer.SetRenderTarget( // cameraColorTextureId, // RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, // cameraDepthTextureId, // RenderBufferLoadAction.Load, RenderBufferStoreAction.Store //); if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); if (renderToTexture) { if (activeStack) { activeStack.RenderAfterTransparent( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); } else { cameraBuffer.Blit( cameraColorTextureId, BuiltinRenderTextureType.CameraTarget ); } cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId); if (needsDepth) { cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId); } } //cameraBuffer.EndSample("Render Camera33"); //CoreUtils.SetKeyword(cameraBuffer, clippingKeyword, true); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
// Main entry point for our scriptable render loop public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, bool useIntermediateBlitPath) { bool stereoEnabled = XRSettings.isDeviceActive; foreach (var camera in cameras) { // Culling ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets context.SetupCameraProperties(camera, stereoEnabled); // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine if (stereoEnabled) { context.StartMultiEye(camera); } RenderTargetIdentifier intermediateRTID = new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive); bool isIntermediateRTTexArray = false; if (useIntermediateBlitPath) { ConfigureAndBindIntermediateRenderTarget(context, camera, stereoEnabled, out intermediateRTID, out isIntermediateRTTexArray); } // clear depth buffer var cmd = CommandBufferPool.Get(); cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw opaque objects using BasicPass shader pass var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("BasicPass")) { sorting = { flags = SortFlags.CommonOpaque } }; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Draw skybox context.DrawSkybox(camera); // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); if (useIntermediateBlitPath) { BlitFromIntermediateToCameraTarget(context, intermediateRTID, isIntermediateRTTexArray); } if (stereoEnabled) { context.StopMultiEye(camera); // StereoEndRender will reset state on the camera to pre-Stereo settings, // and invoke XR based events/callbacks. context.StereoEndRender(camera); } context.Submit(); } }
private void Submit() { commandBuffer.EndSample(sampleName); ExecuteBuffer(); renderContext.Submit(); }
protected void RenderCamera(ScriptableRenderContext context, Camera camera) { m_CameraRender.Render(context, camera); return; BeginCameraRendering(context, camera); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } //setup camera //culling ScriptableCullingParameters cullingParams; camera.TryGetCullingParameters(out cullingParams); //setup shadow cullingParams.shadowDistance = Mathf.Min(m_PipelineConfig.ShadowSetting.maxDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullingResults cullResult = context.Cull(ref cullingParams); SetupRenderContext(ref context, ref cullResult, camera); #if UNITY_EDITOR RenderGizmo(context, camera, GizmoSubset.PreImageEffects); #endif RenderShadow(ref m_RenderContext); context.SetupCameraProperties(camera); cmd.Clear(); cmd.ClearRenderTarget(true, true, Color.clear); context.ExecuteCommandBuffer(cmd); context.Submit(); RenderObject(context, camera, ref cullResult); //draw skybox context.DrawSkybox(camera); #if UNITY_EDITOR RenderGizmo(context, camera, GizmoSubset.PostImageEffects); #endif Cleanup(ref m_RenderContext); context.Submit(); EndCameraRendering(context, camera); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { #if UNITY_EDITOR bool isSceneViewCam = camera.cameraType == CameraType.SceneView; if (isSceneViewCam) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); //This makes the UI Canvas geometry appear on scene view } #endif BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); DrawingSettings drawSettingsDefault = new DrawingSettings(m_PassNameDefault, sortingSettings); //This will let you draw shader passes without the LightMode, //thus it draws the default UGUI materials drawSettingsDefault.SetShaderPassName(1, m_PassNameDefault); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Opaque default context.DrawRenderers(cull, ref drawSettingsDefault, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Transparent default context.DrawRenderers(cull, ref drawSettingsDefault, ref filterSettings); //SceneView fix, so that it draws the gizmos on scene view #if UNITY_EDITOR if (isSceneViewCam) { // context.DrawGizmos(camera, GizmoSubset.PostImageEffects); } #endif context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
void Submit() { buffer.EndSample(SampleName); ExecuteBuffer(); ctx.Submit(); }
private void Render(ScriptableRenderContext context, Camera camera) { // Culling ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { return; } _cull = context.Cull(ref cullingParameters); //CullResults.Cull(, context, ref cull); ConfigureLights(); RenderShadows(context); context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; _buffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif _buffer.BeginSample("Render Camera"); _buffer.SetGlobalTexture(ShadowTexId, _shadowMapFinalTexture); _buffer.SetGlobalVectorArray(VisibleLightColorsId, _visibleLightColors); _buffer.SetGlobalVectorArray(VisibleLightDirectionsOrPositionsId, _visibleLightDirectionsOrPositions); _buffer.SetGlobalVectorArray(VisibleLightSpotDirectionsId, _visibleLightSpotDirections); _buffer.SetGlobalVectorArray(VisibleLightAttenuationsId, _visibleLightAttenuations); _buffer.SetGlobalVectorArray(WorldToShadowMapMatrixId, _worldToShadowMatrices); context.ExecuteCommandBuffer(_buffer); _buffer.Clear(); var drawingSettings = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), new SortingSettings(camera) { criteria = SortingCriteria.SortingLayer }); drawingSettings.SetShaderPassName(1, new ShaderTagId("")); drawingSettings.enableDynamicBatching = true; drawingSettings.enableInstancing = true; drawingSettings.overrideMaterial = _litSprite; drawingSettings.overrideMaterialPassIndex = -1; // if (cull.visibleLights.Length > 0) drawingSettings.perObjectData = PerObjectData.LightData | PerObjectData.LightIndices; // opaque var filterSettings = new FilteringSettings(RenderQueueRange.opaque); context.DrawRenderers(_cull, ref drawingSettings, ref filterSettings); context.DrawSkybox(camera); // transparent filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(_cull, ref drawingSettings, ref filterSettings); DrawDefaultPipeline(context, camera); _buffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(_buffer); _buffer.Clear(); context.Submit(); }