CullingResults Cull(ScriptableRenderContext context, Camera camera) { camera.TryGetCullingParameters(out var cullingParameters); return(context.Cull(ref cullingParameters)); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { foreach (var camera in cameras) { context.SetupCameraProperties(camera); // Очищаем буфер экрана clearBuffer.Clear(); CameraClearFlags clearFlags = camera.clearFlags; clearBuffer.ClearRenderTarget( clearDepth: (clearFlags & CameraClearFlags.Depth) != 0, clearColor: (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); context.ExecuteCommandBuffer(clearBuffer); // Рисуем объекты редактора #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif // Отсекаем невидимые объекты ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { continue; } CullingResults cullingResults = context.Cull(ref cullingParameters); // Рисуем непрозрачные объекты var opaqueSortingSettings = new SortingSettings(camera); opaqueSortingSettings.criteria = SortingCriteria.CommonOpaque; var opaqueDrawingSettings = new DrawingSettings(ForwardBase, opaqueSortingSettings); var opaqueFilteringSettings = new FilteringSettings(RenderQueueRange.opaque); context.DrawRenderers(cullingResults, ref opaqueDrawingSettings, ref opaqueFilteringSettings); // Рисуем небо if (camera.clearFlags == CameraClearFlags.Skybox && RenderSettings.skybox != null) { context.DrawSkybox(camera); } // Рисуем прозрачные объекты var transparentSortingSettings = new SortingSettings(camera); transparentSortingSettings.criteria = SortingCriteria.CommonTransparent; var transparentDrawingSettings = new DrawingSettings(ForwardBase, transparentSortingSettings); var transparentFilteringSettings = new FilteringSettings(RenderQueueRange.transparent); context.DrawRenderers(cullingResults, ref transparentDrawingSettings, ref transparentFilteringSettings); // Отправляем на отрисовку 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 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) { 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(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 Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { return; } // shadow distance cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); cull = context.Cull(ref cullingParameters); if (cull.visibleLights.Length > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } // camera setup context.SetupCameraProperties(camera); // post-processing var customPipelineCamera = camera.GetComponent <CustomPipelineCamera>(); CustomPostProcessingStack activeStack = customPipelineCamera ? customPipelineCamera.PostProcessingStack : defaultStack; bool scaledRendering = renderScale != 1f && camera.cameraType == CameraType.Game; int renderWidth = camera.pixelWidth; int renderHeight = camera.pixelHeight; if (scaledRendering) { renderWidth = (int)(renderWidth * renderScale); renderHeight = (int)(renderHeight * renderScale); } int renderSamples = camera.allowMSAA ? msaaSamples : 1; bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack; bool needsDepth = activeStack && activeStack.NeedsDepth; bool needsDirectDepth = needsDepth && renderSamples == 1; // post && no msaa bool needsDepthOnlyPass = needsDepth && renderSamples > 1; // post && 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); } if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); } } // clear CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); // global constants cameraBuffer.BeginSample("Render Camera"); 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(); // render mesh opaque var sortingSettings = new SortingSettings(camera); sortingSettings.criteria = SortingCriteria.CommonOpaque; var drawSettings = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), sortingSettings); drawSettings.enableDynamicBatching = true; drawSettings.enableInstancing = true; if (cull.visibleLights.Length > 0) { drawSettings.perObjectData = PerObjectData.LightIndices; } drawSettings.perObjectData |= PerObjectData.ReflectionProbes; drawSettings.perObjectData |= PerObjectData.Lightmaps; drawSettings.perObjectData |= PerObjectData.LightProbe; drawSettings.perObjectData |= PerObjectData.LightProbeProxyVolume; drawSettings.perObjectData |= PerObjectData.ShadowMask; // shadow for static drawSettings.perObjectData |= PerObjectData.OcclusionProbe; // shadow for dynamic drawSettings.perObjectData |= PerObjectData.OcclusionProbeProxyVolume; // shadow for dynamic var filterSettings = new FilteringSettings(RenderQueueRange.opaque); filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // render skybox context.DrawSkybox(camera); // post-processing if (activeStack) { if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawingSettings(new ShaderTagId("DepthOnly"), sortingSettings); cameraBuffer.SetRenderTarget(cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); cameraBuffer.ClearRenderTarget(true, false, Color.clear); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.DrawRenderers(cull, ref drawSettings, ref filterSettings); } activeStack.RenderAfterOpaque(postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, msaaSamples, format); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); } context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } // render mesh transparent sortingSettings.criteria = SortingCriteria.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //DrawDefaultPipeline(context, camera); // post-processing if (renderToTexture) { if (activeStack) { activeStack.RenderAfterTransparent(postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, msaaSamples, format); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); } else { cameraBuffer.Blit(cameraColorTextureId, BuiltinRenderTextureType.CameraTarget); } cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId); if (needsDepth) { cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId); } } cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // sumbit context.Submit(); // release if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
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; } }
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; //Texture Descriptor - Color RenderTextureDescriptor rtDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); rtDesc.graphicsFormat = m_ColorFormat; rtDesc.depthBufferBits = 0; rtDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); rtDesc.msaaSamples = 1; rtDesc.enableRandomWrite = false; RenderTextureDescriptor rtDesc2 = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); rtDesc2.graphicsFormat = m_ColorFormat; rtDesc2.depthBufferBits = 0; rtDesc2.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); rtDesc2.msaaSamples = 1; rtDesc2.enableRandomWrite = false; //Texture Descriptor - Depth RenderTextureDescriptor rtDescDepth = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); rtDescDepth.colorFormat = RenderTextureFormat.Depth; rtDescDepth.depthBufferBits = 24; rtDescDepth.msaaSamples = 1; rtDescDepth.enableRandomWrite = false; //Get Temp Texture for Color Texture CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT!!!!!!!!!!!!!!!!!!!!!!!!"; cmdTempId.GetTemporaryRT(m_AlbedoRTid, rtDesc, FilterMode.Point); cmdTempId.GetTemporaryRT(m_EmissionRTid, rtDesc, FilterMode.Point); cmdTempId.GetTemporaryRT(m_DepthRTid, rtDescDepth, FilterMode.Point); context.ExecuteCommandBuffer(cmdTempId); //MyDebug(camera, context, m_DepthRTid, rtDesc, null); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Pass 1========================================================= //SetUp Multi-RenderTargets For the 1st pass & clear CommandBuffer cmdPass1 = new CommandBuffer(); mRTIDs[0] = m_AlbedoRTid; mRTIDs[1] = m_EmissionRTid; cmdPass1.SetRenderTarget(mRTIDs, m_DepthRT); cmdPass1.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdPass1); cmdPass1.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); //Final blit==================================================== //debug CommandBuffer debugCMD = new CommandBuffer(); debugCMD.name = "DEBUGCMD"; debugCMD.GetTemporaryRT(m_EmissionRTid2, rtDesc2, FilterMode.Point); // MyDebug(camera, context, m_EmissionRT2, rtDesc2, debugCMD); context.ExecuteCommandBuffer(debugCMD); debugCMD.Release(); //Blit to CameraTarget, to combine the previous 2 texture results with a blit material CommandBuffer cmd = new CommandBuffer(); cmd.name = "Cam:" + camera.name + " BlitToCamera"; cmd.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget, copyColorMaterial); MyDebug(camera, context, m_EmissionRTid2, rtDesc, null); context.ExecuteCommandBuffer(cmd); cmd.Release(); //CleanUp Texture CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_AlbedoRTid); cmdclean.ReleaseTemporaryRT(m_EmissionRTid); cmdclean.ReleaseTemporaryRT(m_DepthRTid); cmdclean.ReleaseTemporaryRT(m_EmissionRTid2); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Define positions positions.Clear(); Vector4 pos = Vector4.zero; int splitRow = 5; for (int i = 0; i < m_PipelineAsset.count; i++) { pos.x = i % splitRow; pos.y = Mathf.FloorToInt(i / splitRow); pos.z = 0; pos.w = 1; positions.Add(pos); } //SetUp Position Computebuffers Data positionBuffer = new ComputeBuffer(m_PipelineAsset.count, 16); //4*4 bytes for Vector4 positionBuffer.SetData(positions); //vector4 16 m_MaterialPropertyBlock.SetBuffer("positionBuffer", positionBuffer); //SetUp Args Computebuffers Data argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments); args[0] = (uint)m_PipelineAsset.mesh.GetIndexCount(0); args[1] = (uint)m_PipelineAsset.count; args[2] = (uint)m_PipelineAsset.mesh.GetIndexStart(0); args[3] = (uint)m_PipelineAsset.mesh.GetBaseVertex(0); argsBuffer.SetData(args); //Draw Commands CommandBuffer cmdDraw = new CommandBuffer(); cmdDraw.DrawMeshInstancedIndirect(m_PipelineAsset.mesh, 0, m_PipelineAsset.mat, 0, argsBuffer, 0, m_MaterialPropertyBlock); context.ExecuteCommandBuffer(cmdDraw); cmdDraw.Release(); sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); context.Submit(); //CleanUp after rendering this cam if (positionBuffer != null) { positionBuffer.Release(); positionBuffer = null; } if (argsBuffer != null) { argsBuffer.Release(); argsBuffer = null; } EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
private 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 _cull = context.Cull(ref cullingParameters); context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; _commandBuffer.ClearRenderTarget( clearFlags == CameraClearFlags.Depth || clearFlags == CameraClearFlags.Skybox, clearFlags == CameraClearFlags.Color || clearFlags == CameraClearFlags.Skybox, camera.backgroundColor); ConfigureLights(); _commandBuffer.BeginSample("Render Camera"); _commandBuffer.SetGlobalVectorArray(_visibleLightColorsID, _visibleLightColors); _commandBuffer.SetGlobalVectorArray(_visibleLightDirectionsOrPositionsID, _visibleLightDirectionsOrPositions); _commandBuffer.SetGlobalVectorArray(_visibleLightAttenuationsID, _visibleLightAttenuations); context.ExecuteCommandBuffer(_commandBuffer); _commandBuffer.Clear(); var sortingSettings = new SortingSettings(camera) { criteria = SortingCriteria.CommonOpaque }; var drawSettings = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), sortingSettings); drawSettings.enableDynamicBatching = _dynamicBatching; drawSettings.enableInstancing = _instancing; var filterSettings = new FilteringSettings(RenderQueueRange.opaque); context.DrawRenderers(_cull, ref drawSettings, ref filterSettings); context.DrawSkybox(camera); sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(_cull, ref drawSettings, ref filterSettings); DrawDefaultPipeline(context, camera); _commandBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(_commandBuffer); _commandBuffer.Clear(); context.Submit(); }
private void RenderCurrentCamera() { _pixelWidth = _camera.pixelWidth; _pixelHeight = _camera.pixelHeight; var clearFlags = _camera.clearFlags; _mainBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, _camera.backgroundColor); _context.SetupCameraProperties(_camera); var farClipPlane = _camera.farClipPlane; var nearClipPlane = _camera.nearClipPlane; var clipDistance = farClipPlane - nearClipPlane; var zBufferParams = new Vector4(clipDistance / nearClipPlane, 1, clipDistance / (farClipPlane * nearClipPlane), 1 / farClipPlane); _mainBuffer.SetGlobalFloat(ShaderManager.ALPHA_TEST_DEPTH_CUTOFF, @params.alphaTestDepthCutoff); _mainBuffer.SetGlobalVector(ShaderManager.Z_BUFFER_PARAMS, zBufferParams); ExecuteMainBuffer(); #if UNITY_EDITOR if (_camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(_camera); } #endif // todo add gpu culling (cs based AABB/OBB tests) if (!_camera.TryGetCullingParameters(out var cullingParameters)) { return; } var cull = _context.Cull(ref cullingParameters); GenerateRTs(); var dirLightCount = 0u; var pointLightCount = 0u; var spotLightCount = 0u; var shadowDirLightCount = 0u; var shadowPointLightCount = 0u; var shadowSpotLightCount = 0u; var dirLightMax = @params.directionalLightParams.enabled ? @params.directionalLightParams.maxPerFrame : 0; var pointLightMax = @params.pointLightParams.enabled ? @params.pointLightParams.maxPerFrame : 0; var spotLightMax = @params.spotLightParams.enabled ? @params.spotLightParams.maxPerFrame : 0; var shadowDirLightMax = @params.directionalLightParams.enabled ? @params.directionalLightParams.maxShadowCount : 0; var shadowPointLightMax = @params.pointLightParams.enabled ? @params.pointLightParams.maxShadowCount : 0; var shadowSpotLightMax = @params.spotLightParams.enabled ? @params.spotLightParams.maxShadowCount : 0; if (_dirLights.Length < dirLightMax) { _dirLights = new DirectionalLight[dirLightMax]; } if (_pointLights.Length < pointLightMax) { _pointLights = new PointLight[pointLightMax]; } if (_spotLights.Length < spotLightMax) { _spotLights = new SpotLight[spotLightMax]; } if (_shadowDirLights.Length < shadowDirLightMax) { _shadowDirLights = new int[shadowDirLightMax]; } if (_shadowPointLights.Length < shadowPointLightMax) { _shadowPointLights = new int[shadowPointLightMax]; } if (_shadowSpotLights.Length < shadowSpotLightMax) { _shadowSpotLights = new int[shadowSpotLightMax]; } var visibleLights = cull.visibleLights; for (int i = 0; i < visibleLights.Length; i++) { var visibleLight = visibleLights[i]; var originalLight = visibleLight.light; switch (visibleLight.lightType) { case LightType.Directional: if (dirLightCount >= dirLightMax) { continue; } DirectionalLight dirLight = new DirectionalLight { direction = new float4(visibleLight.localToWorldMatrix.GetDirectionFromLocalTransform()), color = new float4(visibleLight.finalColor.ToFloat3(), originalLight.shadowStrength) }; if (originalLight.shadows != LightShadows.None && shadowDirLightCount < shadowDirLightMax) { _shadowDirLights[shadowDirLightCount] = i; shadowDirLightCount++; dirLight.shadowIndex = shadowDirLightCount; } else { dirLight.shadowIndex = 0; } _dirLights[dirLightCount] = dirLight; dirLightCount++; break; case LightType.Point: if (pointLightCount >= pointLightMax) { continue; } PointLight pointLight = new PointLight { sphere = new float4(originalLight.transform.position, originalLight.range), color = new float4(visibleLight.finalColor.ToFloat3(), originalLight.shadowStrength) }; if (originalLight.shadows != LightShadows.None && shadowPointLightCount < shadowPointLightMax) { _shadowPointLights[shadowPointLightCount] = i; shadowPointLightCount++; pointLight.shadowIndex = shadowPointLightCount; } else { pointLight.shadowIndex = 0; } _pointLights[pointLightCount] = pointLight; pointLightCount++; break; case LightType.Spot: if (spotLightCount >= spotLightMax) { continue; } SpotLight spotLight = new SpotLight { cone = new Cone(visibleLight.localToWorldMatrix.GetPositionFromLocalTransform(), Mathf.Deg2Rad * visibleLight.spotAngle * .5f, visibleLight.range, visibleLight.localToWorldMatrix.GetDirectionFromLocalTransform().ToFloat3()), color = new float4(visibleLight.finalColor.ToFloat3(), originalLight.shadowStrength) }; if (originalLight.shadows != LightShadows.None && shadowSpotLightCount < shadowSpotLightMax) { _shadowSpotLights[shadowSpotLightCount] = i; shadowSpotLightCount++; spotLight.shadowIndex = shadowSpotLightCount; } else { spotLight.shadowIndex = 0; } _spotLights[spotLightCount] = spotLight; spotLightCount++; break; } } // Cluster Cull var clusterCullFence = ClusterCull(); // Depth Prepass var opaqueSortSettings = new SortingSettings(_camera) { criteria = SortingCriteria.QuantizedFrontToBack | SortingCriteria.OptimizeStateChanges }; var depthDrawSettings = new DrawingSettings(ShaderTagManager.DEPTH, opaqueSortSettings) { enableDynamicBatching = @params.enableDynamicBatching, enableInstancing = @params.enableInstancing }; var filterSettings = FilteringSettings.defaultValue; filterSettings.layerMask = _camera.cullingMask; filterSettings.renderQueueRange = ShaderManager.OPAQUE_RENDER_QUEUE_RANGE; ResetRenderTarget(ColorBufferId, DepthId, false, true, 1, Color.black); ExecuteMainBuffer(); _context.DrawRenderers(cull, ref depthDrawSettings, ref filterSettings); // Stencil Prepass var stencilDrawSettings = new DrawingSettings(ShaderTagManager.STENCIL, opaqueSortSettings) { enableDynamicBatching = @params.enableDynamicBatching, enableInstancing = @params.enableInstancing }; filterSettings.renderQueueRange = RenderQueueRange.all; ResetRenderTarget(ColorBufferId, DepthId, false, false, 1, Color.black); ExecuteMainBuffer(); _context.DrawRenderers(cull, ref stencilDrawSettings, ref filterSettings); // Editor Pass #if UNITY_EDITOR if (@params.gizmosOn) { _context.DrawGizmos(_camera, GizmoSubset.PostImageEffects); } #endif ReleaseRTs(); ExecuteMainBuffer(); _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 TempRT ************************************ CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; //Color m_ColorFormatActive = camera.allowHDR ? m_ColorFormatHDR : m_ColorFormat; RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.graphicsFormat = m_ColorFormatActive; colorRTDesc.depthBufferBits = depthBufferBits; //colorRTDesc.sRGB = ; colorRTDesc.msaaSamples = camera.allowMSAA ? QualitySettings.antiAliasing : 1; colorRTDesc.enableRandomWrite = false; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); //Depth RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); depthRTDesc.colorFormat = RenderTextureFormat.Depth; depthRTDesc.depthBufferBits = depthBufferBits; cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear); //MotionVector RenderTextureDescriptor motionvectorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); motionvectorRTDesc.graphicsFormat = UnityEngine.Experimental.Rendering.GraphicsFormat.R16G16_SFloat; motionvectorRTDesc.depthBufferBits = depthBufferBits; //colorRTDesc.sRGB = ; motionvectorRTDesc.msaaSamples = 1; motionvectorRTDesc.enableRandomWrite = false; cmdTempId.GetTemporaryRT(m_MotionVectorRTid, motionvectorRTDesc, FilterMode.Bilinear); context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //************************** Setup DrawSettings and FilterSettings ************************************ camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth; var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); DrawingSettings drawSettingsMotionVector = new DrawingSettings(m_PassName, sortingSettings) { perObjectData = PerObjectData.MotionVectors, overrideMaterial = motionVectorMaterial, overrideMaterialPassIndex = 0 }; FilteringSettings filterSettingsMotionVector = new FilteringSettings(RenderQueueRange.all) { excludeMotionVectorObjects = false }; DrawingSettings drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings) { //perObjectData = PerObjectData.None, overrideMaterial = depthOnlyMaterial, overrideMaterialPassIndex = 0, }; FilteringSettings filterSettingsDepth = new FilteringSettings(RenderQueueRange.all); //************************** Rendering depth ************************************ //Set RenderTarget & Camera clear flag 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(); //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsDepth.sortingSettings = sortingSettings; filterSettingsDepth.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettingsDepth); //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(); //************************** Rendering motion vectors ************************************ //Camera clear flag CommandBuffer cmdMotionvector = new CommandBuffer(); cmdMotionvector.SetRenderTarget(m_MotionVectorRT); //Set CameraTarget to the motion vector texture cmdMotionvector.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdMotionvector); cmdMotionvector.Release(); //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsMotionVector.sortingSettings = sortingSettings; filterSettingsMotionVector.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsMotionVector, ref filterSettingsMotionVector); //Camera motion vector CommandBuffer cmdCameraMotionVector = new CommandBuffer(); cmdCameraMotionVector.name = "(" + camera.name + ")" + "Camera MotionVector"; _NonJitteredVP = camera.nonJitteredProjectionMatrix * camera.worldToCameraMatrix; cmdCameraMotionVector.SetGlobalMatrix("_CamPrevViewProjMatrix", _PreviousVP); cmdCameraMotionVector.SetGlobalMatrix("_CamNonJitteredViewProjMatrix", _NonJitteredVP); cmdCameraMotionVector.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity); cmdCameraMotionVector.DrawMesh(fullscreenMesh, Matrix4x4.identity, motionVectorMaterial, 0, 1, null); // draw full screen quad to make Camera motion cmdCameraMotionVector.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix); context.ExecuteCommandBuffer(cmdCameraMotionVector); cmdCameraMotionVector.Release(); //To let shader has MotionVectorTexture CommandBuffer cmdMotionVectorTexture = new CommandBuffer(); cmdMotionVectorTexture.name = "(" + camera.name + ")" + "MotionVector Texture"; cmdMotionVectorTexture.SetGlobalTexture(m_MotionVectorRTid, m_MotionVectorRT); context.ExecuteCommandBuffer(cmdMotionVectorTexture); cmdMotionVectorTexture.Release(); //************************** Rendering color ************************************ //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(m_ColorRT); //Set CameraTarget to the color texture cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //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); //************************** SetUp Post-processing ************************************ PostProcessLayer m_CameraPostProcessLayer = camera.GetComponent <PostProcessLayer>(); bool hasPostProcessing = m_CameraPostProcessLayer != null; bool usePostProcessing = false; //bool hasOpaqueOnlyEffects = false; PostProcessRenderContext m_PostProcessRenderContext = null; if (hasPostProcessing) { m_PostProcessRenderContext = new PostProcessRenderContext(); usePostProcessing = m_CameraPostProcessLayer.enabled; //hasOpaqueOnlyEffects = m_CameraPostProcessLayer.HasOpaqueOnlyEffects(m_PostProcessRenderContext); } //************************** Opaque Post-processing ************************************ //Ambient Occlusion, Screen-spaced reflection are generally not supported for SRP //So this part is only for custom opaque post-processing // if(usePostProcessing) // { // CommandBuffer cmdpp = new CommandBuffer(); // cmdpp.name = "("+camera.name+")"+ "Post-processing Opaque"; // m_PostProcessRenderContext.Reset(); // m_PostProcessRenderContext.camera = camera; // m_PostProcessRenderContext.source = m_ColorRT; // m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive); // m_PostProcessRenderContext.destination = m_ColorRT; // m_PostProcessRenderContext.command = cmdpp; // m_PostProcessRenderContext.flip = camera.targetTexture == null; // m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext); // context.ExecuteCommandBuffer(cmdpp); // cmdpp.Release(); // } //************************** Rendering Transparent Objects ************************************ sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //************************** Transparent Post-processing ************************************ //Bloom, Vignette, Grain, ColorGrading, LensDistortion, Chromatic Aberration, Auto Exposure, Motion Blur if (usePostProcessing) { CommandBuffer cmdpp = new CommandBuffer(); cmdpp.name = "(" + camera.name + ")" + "Post-processing Transparent"; m_PostProcessRenderContext.Reset(); m_PostProcessRenderContext.camera = camera; m_PostProcessRenderContext.source = m_ColorRT; m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive); m_PostProcessRenderContext.destination = BuiltinRenderTextureType.CameraTarget; m_PostProcessRenderContext.command = cmdpp; m_PostProcessRenderContext.flip = camera.targetTexture == null; m_CameraPostProcessLayer.Render(m_PostProcessRenderContext); context.ExecuteCommandBuffer(cmdpp); cmdpp.Release(); } else { //Make sure screen has the thing when Postprocessing is off CommandBuffer cmdBlitToCam = new CommandBuffer(); cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera"; cmdBlitToCam.Blit(m_ColorRTid, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmdBlitToCam); cmdBlitToCam.Release(); } //************************** Debug ************************************ if (_motionVectorDebug) { CommandBuffer cmdDebug = new CommandBuffer(); cmdDebug.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget, motionVectorDebugMaterial); context.ExecuteCommandBuffer(cmdDebug); cmdDebug.Release(); } //************************** Clean Up ************************************ CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); cmdclean.ReleaseTemporaryRT(m_DepthRTid); cmdclean.ReleaseTemporaryRT(m_MotionVectorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); //For camera motion vector _PreviousVP = _NonJitteredVP; } }
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(); }
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 = false; //Set Temp RT & set render target to the RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); DrawingSettings drawSettingsDistortion = new DrawingSettings(m_PassNameDistortion, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Camera clear flag CommandBuffer cmd = new CommandBuffer(); 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); //Blit to color texture CommandBuffer cmdBlitToTex = new CommandBuffer(); cmdBlitToTex.name = "(" + camera.name + ")" + "Blit to Color Texture"; cmdBlitToTex.Blit(BuiltinRenderTextureType.CameraTarget, m_ColorRT); cmdBlitToTex.SetGlobalTexture(m_ColorRTid, m_ColorRT); cmdBlitToTex.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); //Blit will change target, so make sure to reset it context.ExecuteCommandBuffer(cmdBlitToTex); cmdBlitToTex.Release(); //Distortion object sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDistortion, ref filterSettings); //Clean Up CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
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(); }
protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { //渲染开始后,创建CommandBuffer; if (_commandBuffer == null) { _commandBuffer = new CommandBuffer() { name = "SRP Study CB" } } ; //将shader中需要的属性参数映射为ID,加速传参 var _LightDir0 = Shader.PropertyToID("_DLightDir"); var _LightColor0 = Shader.PropertyToID("_DLightColor"); //同上一节,所有相机开始逐次渲染 foreach (var camera in cameras) { //设置渲染相关相机参数,包含相机的各个矩阵和剪裁平面等 renderContext.SetupCameraProperties(camera); //清理myCommandBuffer,设置渲染目标的颜色为灰色。 _commandBuffer.ClearRenderTarget(true, true, Color.gray); //同上一节的剪裁 ScriptableCullingParameters cullParam = new ScriptableCullingParameters(); camera.TryGetCullingParameters(out cullParam); cullParam.isOrthographic = false; CullingResults cullResults = renderContext.Cull(ref cullParam); //在剪裁结果中获取灯光并进行参数获取 var lights = cullResults.visibleLights; _commandBuffer.name = "Render Lights"; foreach (var light in lights) { //判断灯光类型 if (light.lightType != LightType.Directional) { continue; } //获取灯光参数,平行光朝向即为灯光Z轴方向。矩阵第一到三列分别为xyz轴项,第四列为位置。 Vector4 lightpos = light.localToWorldMatrix.GetColumn(2); //灯光方向反向。默认管线中,unity提供的平行光方向也是灯光反向。光照计算决定 Vector4 lightDir = -lightpos; //方向的第四个值(W值)为0,点为1. lightDir.w = 0; //这边获取的灯光的finalColor是灯光颜色乘上强度之后的值,也正好是shader需要的值 Color lightColor = light.finalColor; Debug.LogError("lightColor = " + lightColor.ToString()); //利用CommandBuffer进行参数传递。 _commandBuffer.SetGlobalVector(_LightDir0, lightDir); _commandBuffer.SetGlobalColor(_LightColor0, Color.blue); break; } //执行CommandBuffer中的指令 renderContext.ExecuteCommandBuffer(_commandBuffer); _commandBuffer.Clear(); //同上节,过滤 FilteringSettings filtSet = new FilteringSettings(RenderQueueRange.opaque, -1); //filtSet.renderQueueRange = RenderQueueRange.opaque; //filtSet.layerMask = -1; //同上节,设置Renderer Settings //注意在构造的时候就需要传入Lightmode参数,对应shader的pass的tag中的LightMode SortingSettings sortSet = new SortingSettings(camera) { criteria = SortingCriteria.CommonOpaque }; DrawingSettings drawSet = new DrawingSettings(new ShaderTagId("BaseLit"), sortSet); //绘制物体 renderContext.DrawRenderers(cullResults, ref drawSet, ref filtSet); //绘制天空球 renderContext.DrawSkybox(camera); //开始执行渲染内容 renderContext.Submit(); } } }
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); }
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 = false; //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //cmd.BeginSample("xxx"); //cmd.EndSample("xxx"); //UnityEngine.Profiling.Profiler.BeginSample("xxx"); //UnityEngine.Profiling.Profiler.EndSample(); //Camera clear flag { CommandBuffer cmd = CommandBufferPool.Get(sampler_ClearRenderTarget.name); using (new ProfilingScope(cmd, sampler_ClearRenderTarget)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // cmd.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); cmd.SetRenderTarget(m_ColorRT); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } // Skybox { CommandBuffer cmd = CommandBufferPool.Get(sampler_DrawSkyBox.name); using (new ProfilingScope(cmd, sampler_DrawSkyBox)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // if (drawSkyBox) { context.DrawSkybox(camera); } // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Opaque objects { CommandBuffer cmd = CommandBufferPool.Get(sampler_DrawOpaqueObjects.name); using (new ProfilingScope(cmd, sampler_DrawOpaqueObjects)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Transparent objects { CommandBuffer cmd = CommandBufferPool.Get(sampler_DrawTransparentObjects.name); using (new ProfilingScope(cmd, sampler_DrawTransparentObjects)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Blit to screen { CommandBuffer cmd = CommandBufferPool.Get(sampler_BlitToScreen.name); using (new ProfilingScope(cmd, sampler_BlitToScreen)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // cmd.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Clean Up { CommandBuffer cmd = CommandBufferPool.Get(sampler_CleanUp.name); using (new ProfilingScope(cmd, sampler_CleanUp)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // cmd.ReleaseTemporaryRT(m_ColorRTid); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
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(); }
protected virtual void RenderCamera(ScriptableRenderContext context, Camera camera) { camera.TryGetCullingParameters(out var cullingParameters); var cmd = CommandBufferPool.Get(camera.name); cmd.Clear(); #if UNITY_EDITOR //Emit UI if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif 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.y * 2 - 1) / camera.pixelHeight; var renderingData = new MyRenderingData() { camera = camera, cullResults = cullResults, colorTarget = BuiltinRenderTextureType.CameraTarget, depthTarget = BuiltinRenderTextureType.CameraTarget, colorBufferFormat = RenderTextureFormat.Default, shadowMapData = new Dictionary <Light, MyShadowMapData>(), frameID = frameID, discardFrameBuffer = true, viewMatrix = camera.worldToCameraMatrix, projectionMatrix = projectionMat, jitteredProjectionMatrix = jitteredProjectionMat, projectionJitter = projectionJitter.Current, nextProjectionJitter = new Vector2(0.5f, 0.5f), resolutionScale = settings.ResolutionScale }; Setup(context, ref renderingData); context.SetupCameraProperties(camera, false); InitRenderQueue(camera); SetupLight(ref renderingData); cmd.SetRenderTarget(colorTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, depthTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); cmd.ClearRenderTarget(true, true, Color.black, 1); context.ExecuteCommandBuffer(cmd); cmd.Clear(); context.DrawSkybox(camera); foreach (var pass in renderPassQueue) { pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } foreach (var pass in globalUserPasses) { pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } var userPasses = camera.GetComponents <MyUserPass>(); foreach (var pass in userPasses) { if (pass.global) { continue; } pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } cmd.SetViewProjectionMatrices(renderingData.viewMatrix, renderingData.projectionMatrix); cmd.Blit(renderingData.colorTarget, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); if (camera.cameraType == CameraType.SceneView) { //draw Gizmos 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); } Cleanup(context, ref renderingData); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); projectionJitter.Next = renderingData.nextProjectionJitter; }
public static void RenderSingleCamera(LightweightRenderPipeline pipelineInstance, ScriptableRenderContext context, Camera camera, 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 (!camera.TryGetCullingParameters(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 var cullResults = context.Cull(ref cullingParameters); 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 static void Render(ScriptableRenderContext context, Camera camera, ClearFlag clearFlag, RenderTargetIdentifier targetColor, RenderTargetIdentifier targetDepth) { #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif ScriptableCullingParameters cullingParameters; CullingResults cullingResults; if (camera.TryGetCullingParameters(false, out cullingParameters)) { cullingResults = context.Cull(ref cullingParameters); } else { return; } CommandBuffer buffer = new CommandBuffer() { name = camera.name }; NativeArray <VisibleLight> visibleLights = cullingResults.visibleLights; Lighting.SetupLights(buffer, visibleLights, cullingResults); context.ExecuteCommandBuffer(buffer); buffer.Clear(); context.SetupCameraProperties(camera); SortingSettings sortingSettings = new SortingSettings(camera) { criteria = SortingCriteria.CommonOpaque }; DrawingSettings drawingSettings = new DrawingSettings(unlitShaderTagId, sortingSettings) { perObjectData = PerObjectData.LightData | PerObjectData.LightIndices }; FilteringSettings filteringSettings = new FilteringSettings(RenderQueueRange.all); buffer.SetRenderTarget( targetColor, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, targetDepth, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); if (clearFlag != ClearFlag.None) { buffer.ClearRenderTarget( (clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, (clearFlag & ClearFlag.Color) != 0 ? camera.backgroundColor : Color.clear, 1.0f ); } context.ExecuteCommandBuffer(buffer); buffer.Clear(); context.DrawRenderers(cullingResults, ref drawingSettings, ref filteringSettings); context.DrawSkybox(camera); #if UNITY_EDITOR if (Handles.ShouldRenderGizmos()) { context.DrawGizmos(camera, GizmoSubset.PreImageEffects); } #endif // if (postProcessingSettings != null) // { // CommandBuffer postProcessingBuffer = new CommandBuffer() { name = "Post-processing" }; // postProcessingBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); // PostProcessing.Render(postProcessingBuffer, camera, postProcessingSettings); // context.ExecuteCommandBuffer(postProcessingBuffer); // postProcessingBuffer.Release(); // } #if UNITY_EDITOR if (Handles.ShouldRenderGizmos()) { context.DrawGizmos(camera, GizmoSubset.PostImageEffects); } #endif buffer.Release(); context.Submit(); // TODO: necessary? }
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(); } }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { if (cameras.Length == 0) { return; } UnityEngine.Rendering.RenderPipeline.BeginFrameRendering(context, cameras); // Loop over all active cameras in the scene and render them. foreach (var camera in cameras) { if (camera == null) { continue; } // S E T U P UnityEngine.Rendering.RenderPipeline.BeginCameraRendering(context, camera); // TODO: Should we move this after we set the rasterization render target so that scene view UI is also pixelated? DrawSceneViewUI(camera); ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(camera.stereoEnabled, out cullingParameters)) { continue; } // Need to update the volume manager for the current camera before querying any volume parameter results. // This triggers the volume manager to blend volume parameters spatially, based on the camera position. VolumeManager.instance.Update(camera.transform, camera.cullingMask); // Compute the list of visible render meshes and light sources that are inside the camera's view. CullingResults cullingResults = context.Cull(ref cullingParameters); // Setup camera for rendering (sets render target, view/projection matrices and other per-camera built-in shader variables). context.SetupCameraProperties(camera); // R E N D E R S C E N E var cmd = CommandBufferPool.Get(GameheadsStringConstants.s_CommandBufferRenderForwardStr); int renderTargetWidth = camera.pixelWidth; int renderTargetHeight = camera.pixelHeight; RenderTexture rasterizationRT = RenderTexture.GetTemporary(renderTargetWidth, renderTargetHeight, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default, 1, RenderTextureMemoryless.None, VRTextureUsage.None, false); cmd.SetRenderTarget(rasterizationRT); { PushGlobalRasterizationParameters(camera, cmd, renderTargetWidth, renderTargetHeight); PushFogParameters(camera, cmd); context.ExecuteCommandBuffer(cmd); cmd.Release(); DrawOpaque(context, camera, ref cullingResults); // DrawTransparent(context, camera, ref cullingResults); // TODO: DrawSkybox(context, camera); DrawLegacyCanvasUI(context, camera, ref cullingResults); DrawGizmos(context, camera, GizmoSubset.PreImageEffects); DrawGizmos(context, camera, GizmoSubset.PostImageEffects); } // R E N D E R P O S T P R O C E S S I N G cmd = CommandBufferPool.Get(GameheadsStringConstants.s_CommandBufferRenderPostProcessStr); cmd.SetRenderTarget(camera.targetTexture); { PushGlobalPostProcessingParameters(camera, cmd, m_Asset, rasterizationRT, renderTargetWidth, renderTargetHeight); PushTonemapperParameters(camera, cmd); GameheadsRenderPipeline.DrawFullScreenQuad(cmd, postProcessingMaterial); } // C L E A N U P context.ExecuteCommandBuffer(cmd); cmd.Release(); context.Submit(); RenderTexture.ReleaseTemporary(rasterizationRT); UnityEngine.Rendering.RenderPipeline.EndCameraRendering(context, camera); } UnityEngine.Rendering.RenderPipeline.EndFrameRendering(context, cameras); }
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); } }
protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { //渲染开始后,创建CommandBuffer; if (myCommandBuffer == null) { myCommandBuffer = new CommandBuffer() { name = "T SRP CB" } } ; //将shader中需要的属性参数映射为ID,加速传参 var _DLightDir = Shader.PropertyToID("_DLightDir"); var _DLightColor = Shader.PropertyToID("_DLightColor"); var _PLightPos = Shader.PropertyToID("_PLightPos"); var _PLightColor = Shader.PropertyToID("_PLightColor"); var _SLightPos = Shader.PropertyToID("_SLightPos"); var _SLightColor = Shader.PropertyToID("_SLightColor"); var _SLightDir = Shader.PropertyToID("_SLightDir"); var _CameraPos = Shader.PropertyToID("_CameraPos"); //全部相机逐次渲染 foreach (var camera in cameras) { //清理myCommandBuffer,设置渲染目标的颜色为灰色。 myCommandBuffer.ClearRenderTarget(true, true, Color.black); //设置渲染相关相机参数,包含相机的各个矩阵和剪裁平面等 renderContext.SetupCameraProperties(camera); //绘制天空球 renderContext.DrawSkybox(camera); //剪裁,这边应该是相机的视锥剪裁相关。 //自定义一个剪裁参数,cullParam类里有很多可以设置的东西。我们先简单采用相机的默认剪裁参数。 ScriptableCullingParameters cullParam = new ScriptableCullingParameters(); //直接使用相机默认剪裁参数 camera.TryGetCullingParameters(out cullParam); //非正交相机 cullParam.isOrthographic = false; //获取剪裁之后的全部结果(其中不仅有渲染物体,还有相关的其他渲染要素) CullingResults cullResults = renderContext.Cull(ref cullParam); //传入相机参数。注意是世界空间位置。 Vector4 cameraPos = camera.transform.position; myCommandBuffer.SetGlobalVector(_CameraPos, cameraPos); //在剪裁结果中获取灯光并进行参数获取 var lights = cullResults.visibleLights; myCommandBuffer.name = "Render Lights"; int indexDirectionalLight = 0; int indexPointLight = 0; int indexSpotLight = 0; foreach (var light in lights) { //判断灯光类型 if (light.lightType == LightType.Directional) { if (indexDirectionalLight < maxDirectionalLights) { //获取灯光参数,平行光朝向即为灯光Z轴方向。矩阵第一到三列分别为xyz轴项,第四列为位置。 Vector4 lightpos = light.localToWorldMatrix.GetColumn(2); DLightColors[indexDirectionalLight] = light.finalColor; DLightDirections[indexDirectionalLight] = -lightpos; DLightDirections[indexDirectionalLight].w = 0; //if (i == 2) Debug.Log("color:"+ DLightColors[i]); indexDirectionalLight++; } } else if (light.lightType == LightType.Point) { if (indexPointLight < maxPointLights) { PLightColors[indexPointLight] = light.finalColor; //将点光源的距离设置塞到颜色的A通道 PLightColors[indexPointLight].w = light.range; //矩阵第4列为位置 PLightPos[indexPointLight] = light.localToWorldMatrix.GetColumn(3); indexPointLight++; } } else if (light.lightType == LightType.Spot) { if (indexSpotLight < maxSpotLights) { SLightColors[indexSpotLight] = light.finalColor; //将聚光灯的距离设置塞到颜色的A通道 SLightColors[indexSpotLight].w = light.range; //矩阵第三列为朝向,第四列为位置 Vector4 lightpos = light.localToWorldMatrix.GetColumn(2); SLightDir[indexSpotLight] = -lightpos; //外角弧度-unity中设置的角度为外角全角,我们之取半角进行计算 float outerRad = Mathf.Deg2Rad * 0.5f * light.spotAngle; //外角弧度cos值和tan值 float outerCos = Mathf.Cos(outerRad); float outerTan = Mathf.Tan(outerRad); //内角弧度计算-设定内角tan值为外角tan值的46/64 float innerRad = Mathf.Atan(((46f / 64f) * outerTan)); //内角弧度cos值 float innerCos = Mathf.Cos(innerRad); SLightPos[indexSpotLight] = light.localToWorldMatrix.GetColumn(3); //角度计算用的cos(ro)与cos(ri) - cos(ro)分别存入方向与位置的w分量 SLightDir[indexSpotLight].w = outerCos; SLightPos[indexSpotLight].w = innerCos - outerCos; indexSpotLight++; } } else { continue; } } //将灯光参数组传入Shader myCommandBuffer.SetGlobalVectorArray(_DLightColor, DLightColors); myCommandBuffer.SetGlobalVectorArray(_DLightDir, DLightDirections); myCommandBuffer.SetGlobalVectorArray(_PLightColor, PLightColors); myCommandBuffer.SetGlobalVectorArray(_PLightPos, PLightPos); myCommandBuffer.SetGlobalVectorArray(_SLightColor, SLightColors); myCommandBuffer.SetGlobalVectorArray(_SLightPos, SLightPos); myCommandBuffer.SetGlobalVectorArray(_SLightDir, SLightDir); //执行CommandBuffer中的指令 renderContext.ExecuteCommandBuffer(myCommandBuffer); myCommandBuffer.Clear(); //渲染时,会牵扯到渲染排序,所以先要进行一个相机的排序设置,这里Unity内置了一些默认的排序可以调用 SortingSettings sortSet = new SortingSettings(camera) { criteria = SortingCriteria.CommonOpaque }; //这边进行渲染的相关设置,需要指定渲染的shader的光照模式(就是这里,如果shader中没有标注LightMode的 //话,使用该shader的物体就没法进行渲染了)和上面的排序设置两个参数 DrawingSettings drawSet = new DrawingSettings(new ShaderTagId("Always"), sortSet); //这边是指定渲染的种类(对应shader中的Rendertype)和相关Layer的设置(-1表示全部layer) FilteringSettings filtSet = new FilteringSettings(RenderQueueRange.opaque, -1); //绘制物体 renderContext.DrawRenderers(cullResults, ref drawSet, ref filtSet); //绘制天空球 //renderContext.DrawSkybox(camera); //开始执行上下文 renderContext.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; //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(); } }
private bool StartCullingIfVisible(ScriptableRenderContext context, Camera cam) { if (m_frustumVertices == null) { return(false); } ScriptableCullingParameters cullingParameters = new ScriptableCullingParameters(); if (!cam.TryGetCullingParameters(out cullingParameters)) { return(false); } if (m_temporaryData == null) { m_temporaryData = new TemporaryData(); } uint flags = 0; System.UInt64 flags64 = 0; for (int i = 0; i < 8; ++i) { Vector3 v = m_temporaryData.m_vertices[i] = transform.TransformPoint(m_frustumVertices[i]); uint f = 0; for (int j = 0; j < cullingParameters.cullingPlaneCount; ++j) { Plane plane = cullingParameters.GetCullingPlane(j); if (plane.GetDistanceToPoint(v) < 0) { f |= (1U << j); } } flags &= f; flags64 |= (f << (8 * i)); } if (flags != 0) { // projector is not visible from the camera return(false); } uint cameraPlanes = 0; int planeCount = 0; // -x flags = (uint)((flags64 >> 0) & (flags64 >> 8) & (flags64 >> 32) & (flags64 >> 40)); if (flags == 0) { m_temporaryData.m_clipPlanes[planeCount++] = new Plane(m_temporaryData.m_vertices[0], m_temporaryData.m_vertices[1], m_temporaryData.m_vertices[4]); } else { cameraPlanes |= flags; } // +x flags = (uint)((flags64 >> 16) & (flags64 >> 24) & (flags64 >> 48) & (flags64 >> 56)); if (flags == 0) { m_temporaryData.m_clipPlanes[planeCount++] = new Plane(m_temporaryData.m_vertices[3], m_temporaryData.m_vertices[2], m_temporaryData.m_vertices[7]); } else { cameraPlanes |= flags; } // -y flags = (uint)((flags64 >> 0) & (flags64 >> 16) & (flags64 >> 32) & (flags64 >> 48)); if (flags == 0) { m_temporaryData.m_clipPlanes[planeCount++] = new Plane(m_temporaryData.m_vertices[2], m_temporaryData.m_vertices[0], m_temporaryData.m_vertices[6]); } else { cameraPlanes |= flags; } // +y flags = (uint)((flags64 >> 8) & (flags64 >> 24) & (flags64 >> 40) & (flags64 >> 56)); if (flags == 0) { m_temporaryData.m_clipPlanes[planeCount++] = new Plane(m_temporaryData.m_vertices[1], m_temporaryData.m_vertices[3], m_temporaryData.m_vertices[5]); } else { cameraPlanes |= flags; } // near flags = (uint)((flags64 >> 0) & (flags64 >> 8) & (flags64 >> 16) & (flags64 >> 24)); if (flags == 0) { m_temporaryData.m_clipPlanes[planeCount++] = new Plane(m_temporaryData.m_vertices[0], m_temporaryData.m_vertices[2], m_temporaryData.m_vertices[1]); } else { cameraPlanes |= flags; } // far flags = (uint)((flags64 >> 32) & (flags64 >> 40) & (flags64 >> 48) & (flags64 >> 56)); if (flags == 0) { m_temporaryData.m_clipPlanes[planeCount++] = new Plane(m_temporaryData.m_vertices[4], m_temporaryData.m_vertices[5], m_temporaryData.m_vertices[6]); } else { cameraPlanes |= flags; } int maxPlaneCount = ScriptableCullingParameters.maximumCullingPlaneCount; for (int i = 0; i < cullingParameters.cullingPlaneCount && planeCount < maxPlaneCount; ++i) { if ((cameraPlanes & (1U << i)) != 0) { m_temporaryData.m_clipPlanes[planeCount++] = cullingParameters.GetCullingPlane(i); } } cullingParameters.cullingPlaneCount = planeCount; for (int i = 0; i < planeCount; ++i) { cullingParameters.SetCullingPlane(i, m_temporaryData.m_clipPlanes[i]); } #if DEBUG // To avoid the error: Assertion failed on expression: 'params.cullingPlaneCount == kPlaneFrustumNum' cullingParameters.cullingPlaneCount = 6; #endif CullingResults cullingResults = context.Cull(ref cullingParameters); m_cullingResults.Add(cam, cullingResults); return(true); }