花了我两天的时间才解决这个问题,记录下问题经过
起因
项目需要改渲染管线,在后处理之前插入一个后处理,然后特效再单独处理
过程
这里特效需要做深度测试,然后我用URP PostprocessPass抄来的代码发现depthbuffer丢失,如图:
一片黑啊,绘制代码如下
var colorLoadAction = RenderBufferLoadAction.DontCare;
if (m_Destination == RenderTargetHandle.CameraTarget && !cameraData.isDefaultViewport)
colorLoadAction = RenderBufferLoadAction.Load;
// Note: We rendering to "camera target" we need to get the cameraData.targetTexture as this will get the targetTexture of the camera stack.
// Overlay cameras need to output to the target described in the base camera while doing camera stack.
RenderTargetIdentifier cameraTarget = new RenderTargetIdentifier(cameraData.targetTexture);
cameraTarget = (m_Destination == RenderTargetHandle.CameraTarget) ? cameraTarget : m_Destination.Identifier();
cmd.SetRenderTarget(cameraTarget,
colorLoadAction, RenderBufferStoreAction.Store,
RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare);
cmd.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, m_Materials.uber);
所以根本就没绘制深度貌似,然后我也不知道怎么去绘制,搞了好久,后来发现用Blit就好了
Blit(cmd, GetSource(), GetDestination(), m_Materials.uber);
Blit(cmd, GetDestination(), GetSource());
分析
打开ScriptableRendererPass,查看Blit的调用
public void Blit(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, Material material = null, int passIndex = 0)
{
ScriptableRenderer.SetRenderTarget(cmd, destination, BuiltinRenderTextureType.CameraTarget, clearFlag, clearColor);
cmd.Blit(source, destination, material, passIndex);
}
发现有个这个东西
BuiltinRenderTextureType.CameraTarget
原来是没传这个,不过cmd.setRenderTarget和 ScriptableRenderer.SetRenderTarget这个去设置肯定不一样,所以还是用后者吧
参考
顺便可以参考下这个https://github.com/Thousandyearsofwar/CommandBufferDemo/tree/main/Assets/Scripts/RenderFeatures/SetRenderTarget