public void RenderDeferred(ScriptableRenderContext renderContext, Camera camera, VXGI vxgi) { ScriptableCullingParameters cullingParams; if (!CullResults.GetCullingParameters(camera, out cullingParams)) { return; } CullResults.Cull(ref cullingParams, renderContext, ref _cullResults); _command.BeginSample(_command.name); _command.GetTemporaryRT(_propDepth, camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth); _command.GetTemporaryRT(_propDiffuse, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf); _command.GetTemporaryRT(_propNormal, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBFloat); _command.GetTemporaryRT(_propEmission, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf); _command.GetTemporaryRT(_propOther, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf); _command.GetTemporaryRT(_propIrradiance, (int)(vxgi.diffuseResolutionScale * camera.pixelWidth), (int)(vxgi.diffuseResolutionScale * camera.pixelHeight), 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf ); var binding = new RenderTargetBinding( new RenderTargetIdentifier[] { _propDiffuse, _propNormal, _propEmission, _propOther }, new[] { RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare, RenderBufferLoadAction.DontCare }, new[] { RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare, RenderBufferStoreAction.DontCare }, _propDepth, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare ); _command.SetRenderTarget(binding); _command.ClearRenderTarget(true, true, Color.clear); renderContext.ExecuteCommandBuffer(_command); _command.Clear(); var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("Deferred")); drawSettings.flags = _renderPipeline.drawRendererFlags; drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes; drawSettings.sorting.flags = SortFlags.CommonOpaque; renderContext.DrawRenderers(_cullResults.visibleRenderers, ref drawSettings, _filterSettings); if (vxgi.pass == Pass.ConeTracing) { renderContext.SetupCameraProperties(camera); renderContext.DrawSkybox(camera); } Matrix4x4 clipToWorld = camera.cameraToWorldMatrix * GL.GetGPUProjectionMatrix(camera.projectionMatrix, false).inverse; _command.SetGlobalVector("CameraPosition", camera.transform.position); _command.SetGlobalMatrix("ClipToWorld", clipToWorld); _command.SetGlobalMatrix("ClipToVoxel", vxgi.worldToVoxel * clipToWorld); _command.SetGlobalMatrix("WorldToVoxel", vxgi.worldToVoxel); _command.SetGlobalMatrix("VoxelToWorld", vxgi.voxelToWorld); _command.EndSample(_command.name); renderContext.ExecuteCommandBuffer(_command); _command.Clear(); if (vxgi.pass == Pass.ConeTracing) { _commandDiffuse.BeginSample(_commandDiffuse.name); _commandDiffuse.Blit(_propDiffuse, _propIrradiance, material, (int)Pass.DiffuseConeTracing); _commandDiffuse.EndSample(_commandDiffuse.name); renderContext.ExecuteCommandBuffer(_commandDiffuse); _commandDiffuse.Clear(); } _commandReflection.BeginSample(_commandReflection.name); _commandReflection.Blit(_propDiffuse, BuiltinRenderTextureType.CameraTarget, material, (int)vxgi.pass); _commandReflection.EndSample(_commandReflection.name); renderContext.ExecuteCommandBuffer(_commandReflection); _commandReflection.Clear(); _command.BeginSample(_command.name); _command.ReleaseTemporaryRT(_propDepth); _command.ReleaseTemporaryRT(_propDiffuse); _command.ReleaseTemporaryRT(_propNormal); _command.ReleaseTemporaryRT(_propEmission); _command.ReleaseTemporaryRT(_propOther); _command.ReleaseTemporaryRT(_propIrradiance); _command.EndSample(_command.name); renderContext.ExecuteCommandBuffer(_command); _command.Clear(); }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { base.Render(context, cameras); foreach (Camera camera in cameras) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { continue; } cullingParameters.shadowDistance = m_ShadowSettings.maxShadowDistance; CullResults cullResults = CullResults.Cull(ref cullingParameters, context); VisibleLight[] visibleLights = cullResults.visibleLights; LightData lightData; InitializeLightData(visibleLights, out lightData); // Render Shadow Map bool shadowsRendered = false; InitializeMainShadowLightIndex(visibleLights); if (m_ShadowLightIndex > -1) { shadowsRendered = RenderShadows(ref cullResults, ref visibleLights[m_ShadowLightIndex], ref context); } // Setup camera matrices and RT context.SetupCameraProperties(camera); // Clear RenderTarget to avoid tile initialization on mobile GPUs // https://community.arm.com/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers var cmd = new CommandBuffer() { name = "Clear" }; cmd.ClearRenderTarget(true, true, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Dispose(); // Setup light and shadow shader constants SetupLightShaderVariables(visibleLights, ref cullResults, ref context, ref lightData); if (shadowsRendered) { SetupShadowShaderVariables(ref context, m_ShadowCasterCascadesCount); } RendererConfiguration configuration = RendererConfiguration.PerObjectReflectionProbes; if (m_Asset.EnableLightmap) { configuration |= RendererConfiguration.PerObjectLightmaps; } if (m_Asset.EnableAmbientProbe) { configuration |= RendererConfiguration.PerObjectLightProbe; } if (!lightData.isSingleDirectionalLight) { configuration |= RendererConfiguration.ProvideLightIndices; } // Render Opaques var litSettings = new DrawRendererSettings(cullResults, camera, m_LitPassName); litSettings.sorting.flags = SortFlags.CommonOpaque; litSettings.inputFilter.SetQueuesOpaque(); litSettings.rendererConfiguration = configuration; var unlitSettings = new DrawRendererSettings(cullResults, camera, m_UnlitPassName); unlitSettings.sorting.flags = SortFlags.CommonOpaque; unlitSettings.inputFilter.SetQueuesOpaque(); context.DrawRenderers(ref litSettings); // Release temporary RT var discardRT = new CommandBuffer(); discardRT.ReleaseTemporaryRT(m_ShadowMapProperty); context.ExecuteCommandBuffer(discardRT); discardRT.Dispose(); context.DrawRenderers(ref unlitSettings); // TODO: Check skybox shader context.DrawSkybox(camera); // Render Alpha blended litSettings.sorting.flags = SortFlags.CommonTransparent; litSettings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref litSettings); unlitSettings.sorting.flags = SortFlags.CommonTransparent; unlitSettings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref unlitSettings); } context.Submit(); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR //ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); //cameraBuffer.DisableShaderKeyword(clippingKeyword); } } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); //cameraBuffer.DisableShaderKeyword(clippingKeyword); } context.SetupCameraProperties(camera); var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; bool scaledRendering = (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game; int renderWidth = camera.pixelWidth; int renderHeight = camera.pixelHeight; if (scaledRendering) { renderWidth = (int)(renderWidth * renderScale); renderHeight = (int)(renderHeight * renderScale); } int renderSamples = camera.allowMSAA ? msaaSamples : 1; bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack; bool needsDepth = activeStack && activeStack.NeedsDepth; bool needsDirectDepth = needsDepth && renderSamples == 1; bool needsDepthOnlyPass = needsDepth && renderSamples > 1; RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; if (renderToTexture) { cameraBuffer.GetTemporaryRT( cameraColorTextureId, renderWidth, renderHeight, needsDirectDepth ? 0 : 24, FilterMode.Bilinear, format, RenderTextureReadWrite.Default, renderSamples ); if (needsDepth) { cameraBuffer.GetTemporaryRT( cameraDepthTextureId, renderWidth, renderHeight, 24, FilterMode.Point, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear, 1 ); } if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } } CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); cameraBuffer.SetGlobalVectorArray( visibleLightOcclusionMasksId, visibleLightOcclusionMasks ); globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y; cameraBuffer.SetGlobalVector(globalShadowDataId, globalShadowData); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags //, //rendererConfiguration = RendererConfiguration.PerObjectLightIndices8 }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightProbeProxyVolume | RendererConfiguration.PerObjectShadowMask | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume; drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); if (activeStack) { if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawRendererSettings( camera, new ShaderPassName("DepthOnly") ) { flags = drawFlags }; depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque; cameraBuffer.SetRenderTarget( cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); cameraBuffer.ClearRenderTarget(true, false, Color.clear); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.DrawRenderers( cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings ); } activeStack.RenderAfterOpaque( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); //cameraBuffer.SetRenderTarget( // cameraColorTextureId, // RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, // cameraDepthTextureId, // RenderBufferLoadAction.Load, RenderBufferStoreAction.Store //); if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); if (renderToTexture) { if (activeStack) { activeStack.RenderAfterTransparent( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); } else { cameraBuffer.Blit( cameraColorTextureId, BuiltinRenderTextureType.CameraTarget ); } cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId); if (needsDepth) { cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId); } } //cameraBuffer.EndSample("Render Camera33"); //CoreUtils.SetKeyword(cameraBuffer, clippingKeyword, true); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, SRP07CustomParameter SRP07CP) { string tx = ""; foreach (Camera camera in cameras) { ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). context.SetupCameraProperties(camera); // clear depth buffer CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(true, !SRP07CP.DrawSkybox, SRP07CP.ClearColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); if (SRP07CP.DrawSkybox) { // Draw skybox context.DrawSkybox(camera); } // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); // //////////////////////////////////////////////////////////// VisibleLight[] ls = cull.visibleLights.ToArray(); DrawShadowsSettings[] shadowsSettings = new DrawShadowsSettings[ls.Length]; for (int i = 0; i < shadowsSettings.Length; i++) { shadowsSettings[i] = new DrawShadowsSettings(cull, i); } /* * if(camera == Camera.main) //Only generate result from main cam * { * tx += "DrawShadowsSettings" + "\n"+ "\n"; * * for (int i=0; i<ls.Length; i++) * { * tx += "lightIndex = " + shadowsSettings[i].lightIndex + " (" + ls[i].light.name + ") " + "\n"; * tx += "splitData.cullingPlaneCount = " + shadowsSettings[i].splitData.cullingPlaneCount + "\n"; * tx += "splitData.cullingSphere = " + shadowsSettings[i].splitData.cullingSphere + "\n"+ "\n"; * } * * // Output to text * if (textMesh != null) * { * textMesh.text = tx; * Debug.Log("<color=#0F0>TextMesh is updated</color>"); * } * else * { * tx = "<color=#F00>TextMesh is null</color> Please hit play if you hasn't"; * Debug.Log(tx); * } * } */ // //////////////////////////////////////////////////////////// if (SRP07CP.DrawOpaque) { // Draw opaque objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); for (int i = 0; i < shadowsSettings.Length; i++) { //if(ls[i].light.shadows != LightShadows.None) //context.DrawShadows(ref shadowsSettings[i]); } } if (SRP07CP.DrawTransparent) { // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); } context.Submit(); } }
void Render(ScriptableRenderContext context, Camera camera) { //获取剔除参数 ScriptableCullingParameters cullingParameters; //使用该方法自动填充剔除参数 if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } #if UNITY_EDITOR //手动将UI添加到scene界面,用于使UI在scene界面显示 if (camera.cameraType == CameraType.SceneView) { //这行会在game界面再添加一次UI,导致game界面UI被渲染两次,故外部嵌套条件 ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif //使用剔除参数进行剔除,获取剔除结果 CullResults.Cull(ref cullingParameters, context, ref cull); //使用存起来的cull引用减少gc开销 //CullResults cull = CullResults.Cull(ref cullingParameters, context); 这一行由于每帧要生成一个新的struct,生成了大量新gc //设置摄像机参数,包括vp矩阵 context.SetupCameraProperties(camera); //CameraClearFlags由一系列表示各种状态的二进制位组成 /*CameraClearFlags clearFlags = camera.clearFlags; * cameraBuffer.ClearRenderTarget( * (clearFlags & CameraClearFlags.Depth) != 0,//判断某一位是不是1 * (clearFlags & CameraClearFlags.Color) != 0, * camera.backgroundColor * );*/ ConfigureLights(); //设置帧调试器采样 cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsId, visibleLightDirections ); cameraBuffer.ClearRenderTarget(true, false, Color.clear); //绘制设置 var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") //传入Unity默认Unlit shader的名字 ); //绘制不透明物体前设置物体的渲染次序,按zbuffer从近到远的次序渲染 drawSettings.sorting.flags = SortFlags.CommonOpaque; //由于透明层不会绘制zbuffer,故若绘制次序在skybox之前一定会被skybox遮挡 //过滤器设置,默认为空过滤所有东西,true表示不过滤任何东西全部显示 var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque//在绘制天空盒之前先设置只渲染opaque层以及之前(0-2500) }; //绘制一次(在天空盒前先绘制opaque层及之前) context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); //画天空盒 context.DrawSkybox(camera); //绘制透明物体前再次设置物体的渲染次序,因为透明物体需要blend,渲染次序和不透明物体反向,按zbuffer从远到近的次序渲染 drawSettings.sorting.flags = SortFlags.CommonTransparent; //再将filter设置为transparent(2501-5000)用于绘制透明层 filterSettings.renderQueueRange = RenderQueueRange.transparent; //第二次绘制,绘制透明层次 context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); //帧调试器采样 cameraBuffer.EndSample("Render Camera"); //执行命令缓冲区中的命令 context.ExecuteCommandBuffer(cameraBuffer); //释放命令缓冲区 cameraBuffer.Clear(); //之前只是把命令缓存了,submit函数执行缓存的命令 context.Submit(); }
// Main entry point for our scriptable render loop public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras) { bool stereoEnabled = XRSettings.isDeviceActive; foreach (Camera camera in cameras) { // Culling ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets context.SetupCameraProperties(camera, stereoEnabled); // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine if (stereoEnabled) { context.StartMultiEye(camera); } // clear depth buffer CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw skybox context.DrawSkybox(camera); // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); //************************************************************* // Block RenderStateBlock rsb = new RenderStateBlock(RenderStateMask.Depth | RenderStateMask.Blend | RenderStateMask.Raster | RenderStateMask.Stencil); DepthState ds = rsb.depthState;// ds.writeEnabled = true; ds.compareFunction = CompareFunction.LessEqual; rsb.depthState = ds; // BlendState bs = rsb.blendState; // RenderTargetBlendState rs0 = bs.blendState0; // bs.alphaToMask = false; rs0.sourceColorBlendMode = BlendMode.SrcAlpha; rs0.destinationColorBlendMode = BlendMode.One; rs0.colorBlendOperation = BlendOp.Add; rs0.sourceAlphaBlendMode = BlendMode.Zero; rs0.destinationAlphaBlendMode = BlendMode.One; rs0.alphaBlendOperation = BlendOp.Add; rs0.writeMask = ColorWriteMask.All; bs.blendState0 = rs0; // rsb.blendState = bs; // RasterState rs = rsb.rasterState; // rs.cullingMode = CullMode.Off; rs.depthClip = false; rs.offsetFactor = 0; rs.offsetUnits = 0; rsb.rasterState = rs;// StencilState ss = rsb.stencilState;// rsb.stencilReference = 0; ss.compareFunction = CompareFunction.Disabled; ss.compareFunctionBack = CompareFunction.Disabled; ss.compareFunctionFront = CompareFunction.Disabled; ss.failOperation = StencilOp.Keep; ss.failOperationBack = StencilOp.Keep; ss.failOperationFront = StencilOp.Keep; ss.passOperation = StencilOp.Keep; ss.passOperationBack = StencilOp.Keep; ss.passOperationFront = StencilOp.Keep; ss.zFailOperation = StencilOp.Keep; ss.zFailOperationBack = StencilOp.Keep; ss.zFailOperationFront = StencilOp.Keep; ss.readMask = 255; ss.writeMask = 255; ss.enabled = true; rsb.stencilState = ss;// //************************************************************** //mapping RenderStateBlock rsb_opaque = new RenderStateBlock(RenderStateMask.Raster | RenderStateMask.Stencil); rsb_opaque.rasterState = rsb.rasterState; rsb_opaque.stencilState = rsb.stencilState; rsb_opaque.stencilReference = rsb.stencilReference; RenderStateBlock rsb_trans = new RenderStateBlock(RenderStateMask.Blend); rsb_trans.blendState = rsb.blendState; RenderStateBlock rsb_over = new RenderStateBlock(RenderStateMask.Raster | RenderStateMask.Depth | RenderStateMask.Stencil); rsb_over.depthState = rsb.depthState; rsb_over.rasterState = rsb.rasterState; rsb_over.stencilState = rsb.stencilState; rsb_over.stencilReference = rsb.stencilReference; List <RenderStateMapping> rsm = new List <RenderStateMapping> { new RenderStateMapping("Opaque", rsb_opaque), new RenderStateMapping("Transparent", rsb_trans), new RenderStateMapping("Overlay", rsb_over) }; //************************************************************** // Draw opaque objects using BasicPass shader pass filterSettings.layerMask = LayerMask.GetMask("Default"); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // WITH RENDERSTATEBLOCK OPAQUE filterSettings.layerMask = LayerMask.GetMask("TransparentFX"); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsb); // WITH RENDERSTATEMAPPING OPAQUE filterSettings.layerMask = LayerMask.GetMask("Ignore Raycast"); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsm); //************************************************************** // Draw transparent objects using BasicPass shader pass filterSettings.layerMask = LayerMask.GetMask("Default"); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // WITH RENDERSTATEBLOCK TRANSPARENT filterSettings.layerMask = LayerMask.GetMask("TransparentFX"); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsb); // WITH RENDERSTATEMAPPING TRANSPARENT filterSettings.layerMask = LayerMask.GetMask("Ignore Raycast"); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, rsm); //************************************************************** if (stereoEnabled) { context.StopMultiEye(camera); // StereoEndRender will reset state on the camera to pre-Stereo settings, // and invoke XR based events/callbacks. context.StereoEndRender(camera); } context.Submit(); } }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { base.Render(context, cameras); foreach (Camera camera in cameras) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { continue; } cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance, camera.farClipPlane); CullResults.Cull(ref cullingParameters, context, ref m_CullResults); VisibleLight[] visibleLights = m_CullResults.visibleLights.ToArray(); LightData lightData; InitializeLightData(visibleLights, out lightData); // Render Shadow Map if (lightData.shadowLightIndex > -1) { lightData.shadowsRendered = RenderShadows(ref m_CullResults, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, ref context); } // Setup camera matrices and RT context.SetupCameraProperties(camera); // Setup light and shadow shader constants SetupShaderLightConstants(visibleLights, ref lightData, ref m_CullResults, ref context); if (lightData.shadowsRendered) { SetupShadowShaderConstants(ref context, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, m_ShadowCasterCascadesCount); } SetShaderKeywords(ref lightData, ref context); RendererConfiguration configuration = RendererConfiguration.PerObjectReflectionProbes; if (m_Asset.EnableLightmap) { configuration |= RendererConfiguration.PerObjectLightmaps; } if (m_Asset.EnableAmbientProbe) { configuration |= RendererConfiguration.PerObjectLightProbe; } if (!lightData.isSingleDirectionalLight) { configuration |= RendererConfiguration.PerObjectLightIndices8; } BeginForwardRendering(camera, ref context); // Render Opaques var litSettings = new DrawRendererSettings(m_CullResults, camera, m_LitPassName); litSettings.sorting.flags = SortFlags.CommonOpaque; litSettings.inputFilter.SetQueuesOpaque(); litSettings.rendererConfiguration = configuration; var unlitSettings = new DrawRendererSettings(m_CullResults, camera, m_UnlitPassName); unlitSettings.sorting.flags = SortFlags.CommonTransparent; unlitSettings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref litSettings); // Release temporary RT var discardRT = CommandBufferPool.Get(); discardRT.ReleaseTemporaryRT(m_ShadowMapProperty); discardRT.ReleaseTemporaryRT(m_CameraRTProperty); context.ExecuteCommandBuffer(discardRT); CommandBufferPool.Release(discardRT); // TODO: Check skybox shader context.DrawSkybox(camera); // Render Alpha blended litSettings.sorting.flags = SortFlags.CommonTransparent; litSettings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref litSettings); context.DrawRenderers(ref unlitSettings); EndForwardRendering(camera, ref context); } context.Submit(); }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { if (m_IsCameraRendering) { Debug.LogWarning("Nested camera rendering is forbidden. If you are calling camera.Render inside OnWillRenderObject callback, use BeginCameraRender callback instead."); return; } base.Render(context, cameras); BeginFrameRendering(cameras); GraphicsSettings.lightsUseLinearIntensity = true; SetupPerFrameShaderConstants(); // Sort cameras array by camera depth Array.Sort(cameras, m_CameraComparer); foreach (Camera camera in cameras) { BeginCameraRendering(camera); string renderCameraTag = "Render " + camera.name; CommandBuffer cmd = CommandBufferPool.Get(renderCameraTag); using (new ProfilingSample(cmd, renderCameraTag)) { CameraData cameraData; InitializeCameraData(camera, out cameraData); SetupPerCameraShaderConstants(cameraData); ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, cameraData.isStereoEnabled, out cullingParameters)) { CommandBufferPool.Release(cmd); continue; } cullingParameters.shadowDistance = Mathf.Min(cameraData.maxShadowDistance, camera.farClipPlane); context.ExecuteCommandBuffer(cmd); cmd.Clear(); #if UNITY_EDITOR try #endif { m_IsCameraRendering = true; #if UNITY_EDITOR // Emit scene view UI if (cameraData.isSceneViewCamera) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref m_CullResults); List <VisibleLight> visibleLights = m_CullResults.visibleLights; RenderingData renderingData; InitializeRenderingData(ref cameraData, visibleLights, m_Renderer.maxSupportedLocalLightsPerPass, m_Renderer.maxSupportedVertexLights, out renderingData); m_Renderer.Setup(ref context, ref m_CullResults, ref renderingData); m_Renderer.Execute(ref context, ref m_CullResults, ref renderingData); } #if UNITY_EDITOR catch (Exception) { CommandBufferPool.Release(cmd); throw; } finally #endif { m_IsCameraRendering = false; } } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); } }
void Render(ScriptableRenderContext context, Camera camera) { //取得culling 物件資訊 ScriptableCullingParameters cullingParameters; context.SetupCameraProperties(camera); if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } //在Cull前 Draw UI #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); //Clear Buffer var cameraBuff = new CommandBuffer { name = "Render Camera" }; CameraClearFlags clearFlags = camera.clearFlags; cameraBuff.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); ConfigureLights(); cameraBuff.BeginSample("Render Camera"); //傳遞光線參數到Shaders cameraBuff.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuff.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuff.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuff.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); context.ExecuteCommandBuffer(cameraBuff); cameraBuff.Clear(); //設置drawSettings var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ); drawSettings.sorting.flags = SortFlags.CommonOpaque; drawSettings.flags = drawFlags; //套上 DynamicBatching 設定 //Draw opaque(非透明) var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); //Draw SkyBox context.DrawSkybox(camera); //Draw Transparent(透明) drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); cameraBuff.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuff); cameraBuff.Release(); context.Submit(); }
private void Render(ScriptableRenderContext renderContext, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, renderContext, ref _cullResult); renderContext.SetupCameraProperties(camera); /* #region Orignal Version * // GC优化 * var buffer = new CommandBuffer { * name = "Render Camera" * }; * * ClearRenderTarget(buffer); * ClearRenderTargetPerCamera(buffer, camera); * // this doesn't immediately execute the commands, * // but copies them to the internal buffer of the context. * renderContext.ExecuteCommandBuffer(buffer); * buffer.Release(); #endregion */ #region Optimize Version _cameraBuffer.BeginSample("Render Camera"); _cameraBuffer.SetGlobalVectorArray(_visibleLightColorsId, _visibleLightColors); _cameraBuffer.SetGlobalVectorArray(_visibleLightDirectionId, _visibleLightColors); CameraClearFlags clearFlag = camera.clearFlags; _cameraBuffer.ClearRenderTarget( (clearFlag & CameraClearFlags.Depth) != 0, (clearFlag & CameraClearFlags.Color) != 0, camera.backgroundColor); ConfigureLights(); // this doesn't immediately execute the commands, // but copies them to the internal buffer of the context. renderContext.ExecuteCommandBuffer(_cameraBuffer); _cameraBuffer.Clear(); #endregion #region Draw Opaque Queue var drawRendererSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit")); drawRendererSettings.flags = _drawFlags; // front to back, (over draw) drawRendererSettings.sorting.flags = SortFlags.CommonOpaque; var filterRendererSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; renderContext.DrawRenderers(_cullResult.visibleRenderers, ref drawRendererSettings, filterRendererSettings); #endregion #region Draw Background renderContext.DrawSkybox(camera); #endregion #region Draw Transparent Queue // draw from back to front drawRendererSettings.sorting.flags = SortFlags.CommonTransparent; filterRendererSettings.renderQueueRange = RenderQueueRange.transparent; renderContext.DrawRenderers(_cullResult.visibleRenderers, ref drawRendererSettings, filterRendererSettings); #endregion DrawDefaultPipeline(renderContext, camera); _cameraBuffer.EndSample("Render Camera"); renderContext.ExecuteCommandBuffer(_cameraBuffer); _cameraBuffer.Clear(); renderContext.Submit(); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { cameraBuffer.SetGlobalVector( lightIndicesOffsetAndCountID, Vector4.zero ); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } context.SetupCameraProperties(camera); var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; if (activeStack) { cameraBuffer.GetTemporaryRT( cameraColorTextureId, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Bilinear ); cameraBuffer.GetTemporaryRT( cameraDepthTextureId, camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth ); cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); cameraBuffer.SetGlobalVectorArray( visibleLightOcclusionMasksId, visibleLightOcclusionMasks ); globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y; cameraBuffer.SetGlobalVector(globalShadowDataId, globalShadowData); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ) { flags = drawFlags }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightProbeProxyVolume | RendererConfiguration.PerObjectShadowMask | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume; drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); if (activeStack) { activeStack.RenderAfterOpaque( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, camera.pixelWidth, camera.pixelHeight ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); if (activeStack) { activeStack.RenderAfterTransparent( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, camera.pixelWidth, camera.pixelHeight ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId); cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId); } cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { base.Render(context, cameras); foreach (var camera in cameras) { if (!CullResults.Cull(camera, context, out m_CullResults)) { continue; } context.SetupCameraProperties(camera); { var cmd = CommandBufferPool.Get("Clear"); cmd.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } { var cmd = CommandBufferPool.Get("Set-up Light Buffer"); var lightCount = m_CullResults.visibleLights.Count; // We need to build up the data we want to put into the ComputeBuffer, as we cannot write directly // to it. We use a native array for this, as the allocation will be extremely cheap when using the // temp allocator. // Each light uses 2 x float4 values in the shader, so we allocate 2 x Vector4 per light. You could // also create a C# struct that mirrors the HLSL struct, but be careful wrt. packing rules. var lightArray = new NativeArray <Vector4>(lightCount * 2, Allocator.Temp); // Loop over all the lights and fill up the light buffer. for (var i = 0; i < lightCount; i++) { var light = m_CullResults.visibleLights[i]; // Let's decide what to put in the first float4. Depending on whether it's a point light or a // directional light, we store position or direction in here, respectively. // Note that you can choose your own format if you want to. Just make sure it maches on both the // shader side and the C# side. Vector4 lightData; if (light.lightType == LightType.Directional) { // If it's a directional light we store direction in the xyz components, and a negative // value in the w component. This allows us to identify whether it is a directional light. lightData = light.localToWorld.MultiplyVector(Vector3.back); lightData.w = -1; } else if (light.lightType == LightType.Point) { // If it's a point light we store position in the xyz components, and range in the w // component. lightData = light.localToWorld.GetColumn(3); lightData.w = light.range; } else { // If it's not a point light or a directional light, we ignore the light. continue; } // Finally we put the values into the light buffer. lightArray[i * 2] = lightData; lightArray[i * 2 + 1] = light.finalColor; } // Now that our native array with light data is all filled up, we put it into the light buffer. m_LightBuffer.SetData(lightArray); // We can now now safely dispose of the light array. This is important as we would otherwise leak // memory. lightArray.Dispose(); // Finally, make it available for use in shaders. cmd.SetGlobalBuffer("_LightBuffer", m_LightBuffer); cmd.SetGlobalInt("_LightCount", lightCount); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("Forward")); var filterSettings = new FilterRenderersSettings(true); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(m_CullResults.visibleRenderers, ref drawSettings, filterSettings); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(m_CullResults.visibleRenderers, ref drawSettings, filterSettings); context.Submit(); } }
public void Render(ScriptableRenderContext ctx, Camera camera) { // // CULLING // ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) // fill culling params from our camera { return; // can fail, we wont be able to cull in that case, so, return. } // Add world-space UI elements to the scene view, only in editor mode. // Needs to be done before culling. #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif // Actually cull, using the predefined method. "cull" contains info about what is visible. CullResults.Cull(ref cullingParameters, ctx, ref cull); // // SETUP camera // ctx.SetupCameraProperties(camera); // pass camera matrices to shaders // // CLEAR // //cameraBuffer.BeginSample(""); CameraClearFlags cf = camera.clearFlags; cameraBuffer.ClearRenderTarget( (cf & CameraClearFlags.Depth) != 0, // use the camera flags DEPTH (cf & CameraClearFlags.Color) != 0, // use the camera flags COLOR Color.clear); if (cull.visibleLights.Count > 0) { ConfigureLights(); } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountId, Vector4.zero); } // send the light buffer(s) to the GPU cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visibleLightAttenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsId, visibleLightSpotDirections); //cameraBuffer.EndSample("Render Camera"); ctx.ExecuteCommandBuffer(cameraBuffer); // pushes this buffer commands to the context internal buffer cameraBuffer.Clear(); // Release(); // Clear instead of Release since we reuse the variable. // // DRAW opaque RENDERERS // var drawSettings = new DrawRendererSettings( camera, // used for sorting and layers new ShaderPassName("SRPDefaultUnlit") // used, obviously, as the shader to use to draw. ) { flags = drawFlags, // enable [optional] batching of small objects, and instancing. }; if (cull.visibleLights.Count > 0) // or else Unity crashes... { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; // Forward+, 8 light indices per object } drawSettings.sorting.flags = SortFlags.CommonOpaque; // front-to-back sort for opaque objects var filterSettings = new FilterRenderersSettings(true) // true = include everything { renderQueueRange = RenderQueueRange.opaque // range 0-2500 }; ctx.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // // // ctx.DrawSkybox(camera); // pre-defined function, does not need a command buffer. // // DRAW transparent RENDERERS (after the skybox) // drawSettings.sorting.flags = SortFlags.CommonTransparent; // back-to-front sort for transparent objects filterSettings.renderQueueRange = RenderQueueRange.transparent; // range 2501-5000 ctx.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Draw non-supported materials with the Unity Error Shader DrawDefaultPipeline(ctx, camera); // reuse the cameraBuffer just to push the EndSample command //cameraBuffer.EndSample("Render Camera"); //cameraBuffer.EndSample(""); //ctx.ExecuteCommandBuffer(cameraBuffer); // pushes this buffer commands to the context internal buffer //cameraBuffer.Clear(); // Release(); // Clear instead of Release since we reuse the variable. ctx.Submit(); // commands are buffered in the context. flush. }
void Render(ScriptableRenderContext context, Camera camera) { //Culling ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } #if UNITY_EDITOR //add UI to SceneWindow if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); //shadows if (cull.visibleLights.Count > 0) { ConfigureLights(); if (shadowTileCount > 0) { RenderShadows(context); } else { //no shadows cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else //no lights { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } //Setup Camera parameters context.SetupCameraProperties(camera); //set MVP matrix, etc. //Setup Command Buffer and Execute CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.BeginSample("Render Camera"); //start a sub-level //transfer light properties to buffers in shader cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); //Draw Opaque, Unlit Shader var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags, }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings); //Draw Skybox context.DrawSkybox(camera); //Draw Transparent drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); //Conditions for default pipelines DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); //end the sub-level context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } }//end Render
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { base.Render(renderContext, cameras); ScriptableCullingParameters cullingParams; CullResults cull = new CullResults(); foreach (var item in cameras) { renderContext.SetupCameraProperties(item); // Culling if (!CullResults.GetCullingParameters(item, out cullingParams)) { continue; } // use cull parameters to cull unvisible object, return what is visible CullResults.Cull(ref cullingParams, renderContext, ref cull); CameraClearFlags clearFlags = item.clearFlags; //clear z stencil commandBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, clearColor ); renderContext.ExecuteCommandBuffer(commandBuffer); commandBuffer.Dispose(); //use default pass name,which is include in build-in shader var settings = new DrawRendererSettings( item, new ShaderPassName("BaseShader") ); // Draw opaque objects using BasicPass shader pass // var settings = new DrawRendererSettings(item, new ShaderPassName("BasicPass")); //sort flag definition a sort regulation of render order settings.sorting.flags = SortFlags.CommonOpaque; //draw opaque first var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; //Why FilterRenderersSettings and not FilterRendererSettings? renderContext.DrawRenderers(cull.visibleRenderers, ref settings, filterSettings); renderContext.DrawSkybox(item); //after opaque objects are drawed, command line start darw transparent objects //the render order of visible objets is sorted by unity render command. //On the surface, it seems that the order is sorted by distance between camera and objects, //Is a black box,check the sort model in the source code filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.transparent }; //filterSettings.renderQueueRange = RenderQueueRange.transparent; settings.sorting.flags = SortFlags.CommonTransparent; //Why FilterRenderersSettings and not FilterRendererSettings? renderContext.DrawRenderers(cull.visibleRenderers, ref settings, filterSettings); renderContext.Submit(); } }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { var prevPipe = Shader.globalRenderPipeline; Shader.globalRenderPipeline = "LowEndMobilePipeline"; base.Render(context, cameras); foreach (Camera camera in cameras) { CullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { continue; } cullingParameters.shadowDistance = m_ShadowSettings.maxShadowDistance; CullResults cull = CullResults.Cull(ref cullingParameters, context); VisibleLight[] visibleLights = cull.visibleLights; int pixelLightsCount, vertexLightsCount; GetMaxSupportedLights(visibleLights.Length, out pixelLightsCount, out vertexLightsCount); SortLights(ref visibleLights, pixelLightsCount); // TODO: Add remaining lights to SH // Render Shadow Map bool shadowsRendered = false; if (m_ShadowLightIndex > -1) { shadowsRendered = RenderShadows(cull, visibleLights[m_ShadowLightIndex], context); } // Setup camera matrices and RT context.SetupCameraProperties(camera); // Clear RenderTarget to avoid tile initialization on mobile GPUs // https://community.arm.com/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers var cmd = new CommandBuffer() { name = "Clear" }; cmd.ClearRenderTarget(true, true, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Dispose(); // Setup light and shadow shader constants SetupLightShaderVariables(visibleLights, pixelLightsCount, vertexLightsCount, context); if (shadowsRendered) { SetupShadowShaderVariables(context, m_ShadowCasterCascadesCount); } // Render Opaques var settings = new DrawRendererSettings(cull, camera, m_ForwardBasePassName); settings.sorting.flags = SortFlags.CommonOpaque; settings.inputFilter.SetQueuesOpaque(); settings.rendererConfiguration = RendererConfiguration.PerObjectReflectionProbes; if (m_Asset.EnableLightmap) { settings.rendererConfiguration |= RendererConfiguration.PerObjectLightmaps; } if (m_Asset.EnableAmbientProbe) { settings.rendererConfiguration |= RendererConfiguration.PerObjectLightProbe; } context.DrawRenderers(ref settings); // Release temporary RT var discardRT = new CommandBuffer(); discardRT.ReleaseTemporaryRT(m_ShadowMapProperty); context.ExecuteCommandBuffer(discardRT); discardRT.Dispose(); // TODO: Check skybox shader context.DrawSkybox(camera); // Render Alpha blended settings.sorting.flags = SortFlags.CommonTransparent; settings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref settings); } context.Submit(); Shader.globalRenderPipeline = prevPipe; }
private static readonly ShaderPassName m_UnlitPassName = new ShaderPassName("SRPDefaultUnlit"); //For default shaders public static void Render(ScriptableRenderContext context, Camera[] cameras) { RenderPipeline.BeginFrameRendering(cameras); foreach (Camera camera in cameras) { RenderPipeline.BeginCameraRendering(camera); // Culling ScriptableCullingParameters cullingParams; if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); //============================================== if (camera.name == "MainCamera" || camera.name == "AllCam" || camera.name == "NoneCam") { string tx = ""; tx += "Culling Result of : " + camera.name + " \n"; tx += "\n"; //------------------------------- VisibleLight[] ls = cull.visibleLights.ToArray(); tx += "Lights : Visible : " + ls.Length + "\n"; if (lights != null) { for (int i = 0; i < lights.Length; i++) { int existed = 0; for (int j = 0; j < ls.Length; j++) { if (lights[i] == ls[j].light) { existed++; } } if (existed > 0) { tx += lights[i].gameObject.name + " : <color=#0F0>Visible</color>" + "\n"; } else { tx += lights[i].gameObject.name + " : <color=#F00>Not Visible</color>" + "\n"; } } } else { tx += "Light list is null \n"; } tx += "\n"; //------------------------------- VisibleReflectionProbe[] rs = cull.visibleReflectionProbes.ToArray(); tx += "Reflection Probes : Visible : " + rs.Length + "\n"; if (reflprobes != null) { for (int i = 0; i < reflprobes.Length; i++) { int existed = 0; for (int j = 0; j < rs.Length; j++) { if (reflprobes[i] == rs[j].probe) { existed++; } } if (existed > 0) { tx += reflprobes[i].gameObject.name + " : <color=#0F0>Visible</color>" + "\n"; } else { tx += reflprobes[i].gameObject.name + " : <color=#F00>Not Visible</color>" + "\n"; } } } else { tx += "reflection probe list is null \n"; } tx += "\n"; //------------------------------- tx += "Renderers : \n"; if (rens != null) { for (int i = 0; i < rens.Length; i++) { if (rens[i].isVisible) { tx += rens[i].gameObject.name + " <color=#0F0>Yes</color> \n"; } else { tx += rens[i].gameObject.name + " <color=#F00>No</color> \n"; } } tx += "\n"; } //------------------------------- //Show debug msg on TextMesh //Debug.Log(tx); if (textMesh != null) { textMesh.text = tx; //Debug.Log("<color=#0F0>TextMesh is updated</color>"); } else { tx = "<color=#F00>TextMesh is null</color> Please hit play if you hasn't"; //Debug.Log(tx); } //update = false; } //============================================== context.SetupCameraProperties(camera); // clear depth buffer CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw skybox context.DrawSkybox(camera); // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); //Draw passes that has no light mode (default) ShaderPassName passNameDefault = new ShaderPassName(""); DrawRendererSettings drawSettingsDefault = new DrawRendererSettings(camera, passNameDefault); drawSettingsDefault.SetShaderPassName(1, m_UnlitPassName); // Draw opaque objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Default drawSettingsDefault.sorting.flags = SortFlags.CommonOpaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings); // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Default drawSettingsDefault.sorting.flags = SortFlags.CommonTransparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings); context.Submit(); } }
//### main render methodes ############################################################################################################# //this methode reenders vertexIds and baycentric coordinates in uv space for each object //it's called by the Render(...) at the beginning //Input: renderContext: ScriptableRenderContext // camera: Camera in scene //Output: List<ObjData>, list of all objects with renderer in scene List <ObjData> UVRenderer(ScriptableRenderContext context, Camera camera) //initialize list { List <ObjData> sceneObjects = new List <ObjData>(); //used as return value //object id int id = 0; //iterate objects foreach (MeshFilter mesh in GameObject.FindObjectsOfType <MeshFilter>()) { //setup _______________________________________________________________________________________________________________________________________________ //set camera to only render uv render layer int camCullMask = camera.cullingMask; camera.cullingMask = 1 << 9; context.SetupCameraProperties(camera); //setup struct for object ObjData obj = new ObjData(); obj.obj = mesh.gameObject; obj.obj.GetComponent <Renderer>().material.SetInt("_ID", id++); obj.tileMask = CreateRenderTexture(MAX_TEXTURE_SIZE / TILE_SIZE * 2, MAX_TEXTURE_SIZE / TILE_SIZE, RenderTextureFormat.R8); //move object to uv render layer int objLayer = obj.obj.layer; obj.obj.layer = 9; //Initilize RenderTexture for baycentric coordinate/vertex id RenderTexture bayCent = new RenderTexture(MAX_TEXTURE_SIZE, MAX_TEXTURE_SIZE, 0, RenderTextureFormat.ARGB32); bayCent.filterMode = FilterMode.Point; bayCent.anisoLevel = 0; bayCent.Create(); RenderTexture vertexIds = new RenderTexture(MAX_TEXTURE_SIZE, MAX_TEXTURE_SIZE, 24, RenderTextureFormat.ARGBInt); vertexIds.filterMode = FilterMode.Point; vertexIds.anisoLevel = 0; vertexIds.Create(); obj.obj.GetComponent <Renderer>().material.SetTexture("_TextureAtlas", CreateRenderTexture(MAX_TEXTURE_SIZE * 2, MAX_TEXTURE_SIZE, RenderTextureFormat.ARGB32)); //culling _____________________________________________________________________________________________________________________________________________ ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return(null); } CullResults.Cull(ref cullingParameters, context, ref cull); //set render target ___________________________________________________________________________________________________________________________________ RenderBuffer[] cBuffer = new RenderBuffer[2] { bayCent.colorBuffer, vertexIds.colorBuffer }; camera.SetTargetBuffers(cBuffer, bayCent.depthBuffer); //clearing ____________________________________________________________________________________________________________________________________________ //clearing render target cameraBuffer.ClearRenderTarget(true, true, new Color(0, 0, 0, 0)); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); //drawing _____________________________________________________________________________________________________________________________________________ //setting DrawRendererSettings drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")); drawSettings.sorting.flags = SortFlags.CommonOpaque; FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); drawSettings.SetOverrideMaterial(new Material(Shader.Find("Custom/UVRenderer")), 0); //draw unlit opaque materials context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); context.Submit(); //finish _____________________________________________________________________________________________________________________________________________ //move object and camera back to original layer obj.obj.layer = objLayer; camera.cullingMask = camCullMask; //set object properties obj.obj.GetComponent <Renderer>().material.SetTexture("_BaycentCoords", bayCent); obj.bayCent = bayCent; obj.obj.GetComponent <Renderer>().material.SetTexture("_VertexIDs", vertexIds); //add object to result list sceneObjects.Add(obj); //reset render taget Graphics.SetRenderTarget(null); } //return list return(sceneObjects); }
void Render(ScriptableRenderContext context, Camera camera) { //渲染上下文 context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; //清屏 commandBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); //配置光源 ConfigureLights(); commandBuffer.BeginSample("Render Camera"); //设置光照数据 commandBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); commandBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); commandBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visibleLightAttenuations); context.ExecuteCommandBuffer(commandBuffer); commandBuffer.Clear(); //剔除 ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); //调用Unity默认的pass unlit pass DrawRendererSettings drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")); drawSettings.flags = drawFlags; drawSettings.sorting.flags = SortFlags.CommonOpaque; //渲染过滤器 FilterRenderersSettings filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; //渲染不透明物体 context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); //渲染天空盒 context.DrawSkybox(camera); //渲染透明物体 filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); filterSettings.renderQueueRange = RenderQueueRange.transparent; DrawDefaultPipeline(context, camera); commandBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(commandBuffer); commandBuffer.Clear(); context.Submit(); }
void Render(ScriptableRenderContext context, Camera camera) { // 剔除参数 ScriptableCullingParameters cullingParameters; // 获取剔除参数 if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { // 如果相机设定非法,直接返回 return; } // 设置阴影参数 cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); // 仅在编辑模式下 #if UNITY_EDITOR // 仅在渲染场景视图时。否则游戏视图中的UI元素会被渲染两次 if (camera.cameraType == CameraType.SceneView) { // 当canvas的渲染被设置在世界空间时,UI元素不会出现在场景视图中 // 需要手动指定以使其正确显示 ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif // 剔除 CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { // 由于该值会被保留为上一个物体使用的值,因此需要手动设置 cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } // 设置unity_MatrixVP,以及一些其他属性 context.SetupCameraProperties(camera); // 获取摄像机的定制后处理栈 var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; // 只影响游戏摄像机 bool scaledRendering = (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game; int renderWidth = camera.pixelWidth; int renderHeight = camera.pixelHeight; if (scaledRendering) { renderWidth = (int)(renderWidth * renderScale); renderHeight = (int)(renderHeight * renderScale); } // 摄像机是否开启MSAA int renderSamples = camera.allowMSAA ? msaaSamples : 1; // 开启渲染到纹理 bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack; // 是否需要深度纹理(深度纹理不支持MSAA) bool needsDepth = activeStack && activeStack.NeedsDepth; bool needsDirectDepth = needsDepth && renderSamples == 1; // 不使用MSAA bool needsDepthOnlyPass = needsDepth && renderSamples > 1; // 使用MSAA、 // 纹理格式 RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; // 获取并设置渲染目标,用于后处理 if (renderToTexture) { cameraBuffer.GetTemporaryRT( cameraColorTextureId, renderWidth, renderHeight, needsDirectDepth ? 0 : 24, FilterMode.Bilinear, format, RenderTextureReadWrite.Default, renderSamples ); if (needsDepth) { cameraBuffer.GetTemporaryRT( cameraDepthTextureId, renderWidth, renderHeight, 24, FilterMode.Point, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear, 1 // 1表示不使用MSAA ); } if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); } } // 清空 CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); // 设置采样标志,用于在Frame Debugger中组织结构 cameraBuffer.BeginSample("HY Render Camera"); // 设置光数据 cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visibleLightAttenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsId, visibleLightSpotDirections); // 执行指令缓冲。这并不会立即执行指令,只是将指令拷贝到上下文的内部缓冲中 context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // 绘制设定 // camera参数设定排序和剔除层,pass参数指定使用哪一个shader pass var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags }; // 仅在有可见光时设置,否则Unity会崩溃 if (cull.visibleLights.Count > 0) { // 指定Unity为每个物体传输光索引数据 drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } // 指定使用反射探针,如果场景中没有反射探针,则使用天空球的立方体贴图 drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps; // 指定排序,从前往后 drawSettings.sorting.flags = SortFlags.CommonOpaque; // 过滤设定 // true表示包括所有物体 var filterSettings = new FilterRenderersSettings(true) { // 绘制不透明物体,渲染队列为[0,2500] renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // 绘制天空盒 // camera参数仅用来判断是否绘制天空盒(根据camera的清空标志位) context.DrawSkybox(camera); // 后处理 if (activeStack) { // depth-only pass if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawRendererSettings( camera, new ShaderPassName("DepthOnly") ) { flags = drawFlags }; depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque; cameraBuffer.SetRenderTarget( cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store ); cameraBuffer.ClearRenderTarget(true, false, Color.clear); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.DrawRenderers( cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings ); } activeStack.RenderAfterOpaque( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, cameraDepthTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } else { cameraBuffer.SetRenderTarget( cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store ); } context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } // 指定排序,从后往前 drawSettings.sorting.flags = SortFlags.CommonTransparent; // 绘制透明物体,渲染队列为[2501,5000] filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); DrawDefaultPipeline(context, camera); // 后处理 if (renderToTexture) { if (activeStack) { activeStack.RenderAfterTransparent( postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId, renderWidth, renderHeight, renderSamples, format ); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); } else { cameraBuffer.Blit( cameraColorTextureId, BuiltinRenderTextureType.CameraTarget ); } cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId); if (needsDepth) { cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId); } } cameraBuffer.EndSample("HY Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // 提交指令 context.Submit(); // 释放阴影纹理 if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } // 释放层级阴影纹理 if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
//------------------------------------------------------------------------------ // PRIVATE FUNCTIONS //------------------------------------------------------------------------------ private void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } CullResults.Cull(ref cullingParameters, context, ref cullResults); // render shadow map RenderShadows(context); // pass builtin global camera vars to GPU context.SetupCameraProperties(camera); // clear buffer CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); // prepare light data if (cullResults.visibleLights.Count > 0) { ConfigureLights(); } else { cameraBuffer.SetGlobalVector( lightIndicesOffsetAndCountID, Vector4.zero ); } cameraBuffer.BeginSample("Camera"); // pass custom global shader vars to GPU cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightVectorsId, visibleLightVectors ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // draw opaques var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ) { flags = drawFlags }; if (cullResults.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cullResults.visibleRenderers, ref drawSettings, filterSettings ); // draw skybox context.DrawSkybox(camera); // draw transparents drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cullResults.visibleRenderers, ref drawSettings, filterSettings ); // draw error material DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); // release shadow map mem if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { cameraBuffer.SetGlobalVector( lightIndicesOffsetAndCountID, Vector4.zero ); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ) { flags = drawFlags }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightProbeProxyVolume; drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
public void UpdatePointLights(ref Dictionary <Light, int> light_table, ref ScriptableRenderContext renderContext, List <Light> plights, Camera camera, ref CommandBuffer setup_properties) { //todo: now will update every light for every camera, which is not totally necessary. if (helper_ == null) { return; } if (plights.Count == 0) { return; } Transform helper_trans = helper_.transform; m_PointShadowArray.TestNeedModify((int)m_asset.pointShadowResolution, (int)m_asset.pointShadowResolution, plights.Count); if (m_PointShadowArray.IsValid()) { setup_properties.SetGlobalTexture(shaderPropertyID.pointShadowArray, m_PointShadowArray.data); } m_pointLightMatrix.TestNeedModify(plights.Count); if (m_pointLightMatrix.IsValid()) { setup_properties.SetGlobalBuffer(shaderPropertyID.pointLightMatrixArray, m_pointLightMatrix.data); } helper_trans.up = Vector3.up; helper.aspect = 1f; var cb = CommandBufferPool.Get("Point light shadow map"); ShadowCascadeMatrix[] light_mats = new ShadowCascadeMatrix[plights.Count]; string tes = m_asset.enableTessellation ? "_TES" : ""; for (int i = 0; i < plights.Count; i++) { var light = plights[i]; light_table[light] = i; helper_trans.position = light.transform.position; helper.orthographicSize = light.range * 2; helper.farClipPlane = light.range; cb.SetRenderTarget(m_PointShadowArray.data, 0, CubemapFace.Unknown, i); cb.ClearRenderTarget(true, true, Color.clear); renderContext.ExecuteCommandBuffer(cb); cb.Clear(); helper_trans.forward = Vector3.forward; var mats = new ShadowCascadeMatrix(); mats.a = helper.worldToCameraMatrix; mats.b = GL.GetGPUProjectionMatrix(helper.projectionMatrix, true); cb.SetGlobalMatrix(shaderPropertyID.shadow_mat, mats.a); cb.SetGlobalMatrix(shaderPropertyID.shadow_mat2, mats.b); cb.SetGlobalVector(shaderPropertyID.shadow_Range, new Vector4(helper.farClipPlane, helper.farClipPlane)); renderContext.ExecuteCommandBuffer(cb); cb.Clear(); var cullResults = new CullResults(); CullResults.Cull(helper, renderContext, out cullResults); var filterSetting = new FilterRenderersSettings(true); filterSetting.renderQueueRange = RenderQueueRange.opaque; filterSetting.layerMask = helper.cullingMask; var renderSetting = new DrawRendererSettings(camera, new ShaderPassName("VRP_PS_0" + tes)); renderSetting.sorting.flags = SortFlags.None; renderContext.DrawRenderers(cullResults.visibleRenderers, ref renderSetting, filterSetting); helper_trans.forward = -Vector3.forward; mats.c = helper.worldToCameraMatrix; mats.d = mats.b; cb.ClearRenderTarget(true, false, Color.clear); cb.SetGlobalMatrix("_Shadow_mat", mats.c); renderContext.ExecuteCommandBuffer(cb); cb.Clear(); cullResults = new CullResults(); CullResults.Cull(helper, renderContext, out cullResults); renderSetting = new DrawRendererSettings(camera, new ShaderPassName("VRP_PS_1" + tes)); renderSetting.sorting.flags = SortFlags.None; renderContext.DrawRenderers(cullResults.visibleRenderers, ref renderSetting, filterSetting); light_mats[i] = mats; } CommandBufferPool.Release(cb); m_pointLightMatrix.data.SetData(light_mats); }
public static void RenderSingleCamera(LightweightRenderPipeline pipelineInstance, ScriptableRenderContext context, Camera camera, ref CullResults cullResults, IRendererSetup setup = null) { if (pipelineInstance == null) { Debug.LogError("Trying to render a camera with an invalid render pipeline instance."); return; } ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, IsStereoEnabled(camera), out cullingParameters)) { return; } CommandBuffer cmd = CommandBufferPool.Get(k_RenderCameraTag); using (new ProfilingSample(cmd, k_RenderCameraTag)) { CameraData cameraData; PipelineSettings settings = pipelineInstance.settings; ScriptableRenderer renderer = pipelineInstance.renderer; InitializeCameraData(settings, camera, out cameraData); SetupPerCameraShaderConstants(cameraData); cullingParameters.shadowDistance = Mathf.Min(cameraData.maxShadowDistance, camera.farClipPlane); context.ExecuteCommandBuffer(cmd); cmd.Clear(); #if UNITY_EDITOR // Emit scene view UI if (cameraData.isSceneViewCamera) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cullResults); RenderingData renderingData; InitializeRenderingData(settings, ref cameraData, ref cullResults, renderer.maxVisibleAdditionalLights, renderer.maxPerObjectAdditionalLights, out renderingData); var setupToUse = setup; if (setupToUse == null) { setupToUse = defaultRendererSetup; } renderer.Clear(); setupToUse.Setup(renderer, ref renderingData); renderer.Execute(context, ref renderingData); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); #if UNITY_EDITOR Handles.DrawGizmos(camera); #endif }
public void UpdateDirectionalLights(ref Dictionary <Light, int> light_table, ref ScriptableRenderContext renderContext, List <Light> dirlights, Camera camera, ref CommandBuffer setup_properties) { if (helper_ == null) { return; } light_table.Clear(); //helper.name = camera.name + "_helper"; if (dirlights.Count == 0) { return; } Transform helper_trans = helper_.transform; Matrix4x4 proj_mat = GL.GetGPUProjectionMatrix(camera.projectionMatrix, false) * camera.worldToCameraMatrix; proj_mat = proj_mat.inverse; //spilt the view frustrum CascadeHelper cascadeHelper = new CascadeHelper(proj_mat, camera.transform.position, m_asset.cascadeNum); //setup property setup_properties.SetGlobalVector(shaderPropertyID.dirctionalShadowSplitDistance, cascadeHelper.SplitVolum(m_asset.cascadeDistribution, m_asset.shadowDistance)); setup_properties.SetGlobalInt(shaderPropertyID.maxCascadeNum, m_asset.cascadeNum); setup_properties.SetGlobalVector(shaderPropertyID.dirShadowResolution, new Vector4((int)m_asset.directionalShadowResolution, (int)m_asset.directionalShadowResolution, 1f / (float)m_asset.directionalShadowResolution, 1f / (float)m_asset.directionalShadowResolution)); m_DirShadowArray.TestNeedModify((int)m_asset.directionalShadowResolution, (int)m_asset.directionalShadowResolution, dirlights.Count); if (m_DirShadowArray.IsValid()) { setup_properties.SetGlobalTexture(shaderPropertyID.dirShadowArray, m_DirShadowArray.data); } m_shadowcascade_matrix_vp.TestNeedModify(dirlights.Count); if (m_shadowcascade_matrix_vp.IsValid()) { setup_properties.SetGlobalBuffer(shaderPropertyID.shadowcascade_matrix_vp, m_shadowcascade_matrix_vp.data); } var cb = CommandBufferPool.Get("Directional light shadowmap"); List <ShadowCascadeMatrix> mts = new List <ShadowCascadeMatrix>(); for (int i = 0; i < dirlights.Count; i++) { var light = dirlights[i]; light_table[light] = i; Matrix4x4 l2w = light.transform.localToWorldMatrix; Vector4 dir = new Vector4(l2w.m02, l2w.m12, l2w.m22, 0); cb.SetRenderTarget(m_DirShadowArray.data, 0, CubemapFace.Unknown, i); cb.ClearRenderTarget(false, true, Color.clear); renderContext.ExecuteCommandBuffer(cb); cb.Clear(); Matrix4x4[] mats_per_light = new Matrix4x4[4]; for (int j = 0; j < m_asset.cascadeNum; j++) { //correct the forward of the helper camera to light dir helper_trans.forward = dir; float[] bias = cascadeHelper.GetCascadeVolum(helper_trans.worldToLocalMatrix, j); helper_trans.position = new Vector3(bias[0], bias[1], bias[2]) - helper_trans.forward * m_asset.shadowDistance; helper.orthographicSize = bias[4] / 2; helper.farClipPlane = bias[5] + m_asset.shadowDistance; helper.aspect = bias[3] / bias[4]; cb.ClearRenderTarget(true, false, Color.clear); mats_per_light[j] = GL.GetGPUProjectionMatrix(helper.projectionMatrix, true) * helper.worldToCameraMatrix; cb.SetGlobalMatrix(shaderPropertyID.shadow_mat, mats_per_light[j]); renderContext.ExecuteCommandBuffer(cb); cb.Clear(); var cullResults = new CullResults(); CullResults.Cull(helper, renderContext, out cullResults); var filterSetting = new FilterRenderersSettings(true); filterSetting.renderQueueRange = RenderQueueRange.opaque; filterSetting.layerMask = helper.cullingMask; var renderSetting = new DrawRendererSettings(camera, new ShaderPassName(string.Format("VRP_DS_{0:G}", j))); renderSetting.sorting.flags = SortFlags.None; renderContext.DrawRenderers(cullResults.visibleRenderers, ref renderSetting, filterSetting); } var mt = new ShadowCascadeMatrix(); mt.a = mats_per_light[0]; mt.b = mats_per_light[1]; mt.c = mats_per_light[2]; mt.d = mats_per_light[3]; mts.Add(mt); } CommandBufferPool.Release(cb); m_shadowcascade_matrix_vp.data.SetData(mts); }
// Main entry point for our scriptable render loop public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, bool useIntermediateBlitPath) { bool stereoEnabled = XRSettings.isDeviceActive; foreach (var camera in cameras) { // Culling ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets context.SetupCameraProperties(camera, stereoEnabled); // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine if (stereoEnabled) { context.StartMultiEye(camera); } RenderTargetIdentifier intermediateRTID = new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive); bool isIntermediateRTTexArray = false; if (useIntermediateBlitPath) { ConfigureAndBindIntermediateRenderTarget(context, camera, stereoEnabled, out intermediateRTID, out isIntermediateRTTexArray); } // clear depth buffer var cmd = CommandBufferPool.Get(); cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw opaque objects using BasicPass shader pass var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("BasicPass")) { sorting = { flags = SortFlags.CommonOpaque } }; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Draw skybox context.DrawSkybox(camera); // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); if (useIntermediateBlitPath) { BlitFromIntermediateToCameraTarget(context, intermediateRTID, isIntermediateRTTexArray); } if (stereoEnabled) { context.StopMultiEye(camera); // StereoEndRender will reset state on the camera to pre-Stereo settings, // and invoke XR based events/callbacks. context.StereoEndRender(camera); } context.Submit(); } }
public void Render(ScriptableRenderContext renderContext, CommandBuffer cmd) { if (needRender || isDynamic) { needRender = false; GameObject probeCamObj = new GameObject("Probe Camera"); probeCamObj.hideFlags = HideFlags.HideAndDontSave; Camera probeCamera = probeCamObj.AddComponent <Camera>(); probeCamera.enabled = false; probeCamera.renderingPath = RenderingPath.Forward; probeCamera.nearClipPlane = NearPlane; probeCamera.farClipPlane = FarPlane; probeCamera.depthTextureMode = DepthTextureMode.None; probeCamera.clearFlags = CameraClearFlags.SolidColor | CameraClearFlags.Depth; probeCamera.backgroundColor = Color.black; probeCamera.orthographic = false; probeCamera.hideFlags = HideFlags.HideAndDontSave; probeCamera.allowMSAA = false; probeCamera.stereoTargetEye = StereoTargetEyeMask.None; probeCamera.fieldOfView = 90.0f; probeCamera.aspect = 1; probeCamObj.SetActive(false); for (int i = 0; i < Probes.Count; i++) { probeCamObj.transform.position = Probes[i].position; for (int j = 0; j < 6; j++) { probeCamObj.transform.rotation = rotations[j]; m_ProbeLightManager.NewFrame(); RGCamera rgCam = RGCamera.Get(probeCamera, null, 128, false); ScriptableCullingParameters cullingParams; if (!CullResults.GetCullingParameters(probeCamera, false, out cullingParams)) { continue; } CullResults.Cull(ref cullingParams, renderContext, ref m_cullResults); m_ProbeLightManager.UpdateCullingParameters(ref cullingParams, false); m_ProbeLightManager.PrepareLightsDataForGPU(cmd, m_ShadowSettings, m_cullResults, probeCamera, false); bool enableStaticShadowmap = false; if (m_ShadowSettings.StaticShadowmap) { enableStaticShadowmap = true; cmd.SetGlobalTexture(ClusterShaderIDs._StaticShadowmapExp, m_ShadowSettings.StaticShadowmap); } var clusterShadowSettings = VolumeManager.instance.stack.GetComponent <ClusterShadowSettings>(); if (clusterShadowSettings) { m_ShadowSettings.MaxShadowDistance = clusterShadowSettings.MaxShadowDistance; m_ShadowSettings.MaxShadowCasters = clusterShadowSettings.MaxShadowCasters; m_ShadowSettings.ShadowmapRes = clusterShadowSettings.ShadowMapResolution; m_ShadowSettings.StaticShadowmapRes = clusterShadowSettings.StaticShadowMapResolution; m_ShadowSettings.StaticShadowmap = clusterShadowSettings.staticShadowmap.value; } else { m_ShadowSettings.MaxShadowDistance = 1000.0f; m_ShadowSettings.MaxShadowCasters = 5; m_ShadowSettings.ShadowmapRes = new Vector2Int(m_ShadowInitParams.shadowAtlasWidth, m_ShadowInitParams.shadowAtlasHeight); m_ShadowSettings.StaticShadowmapRes = Vector2Int.one; m_ShadowSettings.StaticShadowmap = null; } m_ProbeLightManager.RenderShadows(renderContext, cmd, m_cullResults); m_ProbeLightManager.PostBlurExpShadows(cmd, 1); m_ProbeLightManager.ClusterLightCompute(rgCam, cmd); rgCam.SetupGlobalParams(cmd, 0, 0); renderContext.ExecuteCommandBuffer(cmd); cmd.Clear(); renderContext.SetupCameraProperties(probeCamera, rgCam.StereoEnabled); // Need to recall SetupCameraProperties after m_ShadowPass.Render //RenderTargetIdentifier[] rendertargets = { Probes[i].RadianceTexture, Probes[i].NormalTexture }; cmd.SetRenderTarget(radianceCubeArray, probeDepth, 0, CubemapFace.Unknown, i * 6 + (int)faces[j]); cmd.ClearRenderTarget(true, true, probeCamera.backgroundColor.linear); RendererConfiguration settings = RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe; RenderRendererList(m_cullResults, rgCam.camera, renderContext, cmd, m_RadiancePassNames, RGRenderQueue.k_RenderQueue_AllOpaque, settings); renderContext.DrawSkybox(probeCamera); //RenderTargetIdentifier[] rendertargets = { Probes[i].RadianceTexture, Probes[i].NormalTexture }; cmd.SetRenderTarget(normalMapArray, probeDepth, 0, CubemapFace.Unknown, i * 6 + (int)faces[j]); cmd.ClearRenderTarget(true, true, new Color(0, 0, 0)); RenderRendererList(m_cullResults, rgCam.camera, renderContext, cmd, m_NormalPassNames, RGRenderQueue.k_RenderQueue_AllOpaque); //RenderTargetIdentifier[] rendertargets = { Probes[i].RadianceTexture, Probes[i].NormalTexture }; cmd.SetRenderTarget(depthMapArray, probeDepth, 0, CubemapFace.Unknown, i * 6 + (int)faces[j]); cmd.ClearRenderTarget(true, true, new Color(1, 1, 1)); RenderRendererList(m_cullResults, rgCam.camera, renderContext, cmd, m_DepthPassNames, RGRenderQueue.k_RenderQueue_AllOpaque); renderContext.Submit(); } } ReprojectCubeToOctan(renderContext, cmd); UnityEngine.Object.DestroyImmediate(probeCamera); UnityEngine.Object.DestroyImmediate(probeCamObj); } }