在Unity URP中实现Hi-Z(Hierarchical Z-Buffer)技术涉及构建深度纹理的Mipmap金字塔,用于高效遮挡剔除或屏幕空间效果。以下是完整实现步骤:
对惹,这里有一个游戏开发交流小组,希望大家可以点击进来一起交流一下开发经验呀!
1. 创建必要资源
计算着色器 (HiZ.compute):
#pragma kernel CSMain_HiZ
Texture2D<float> _DepthTexture;
RWTexture2D<float> _HiZTexture;
float2 _TexelSize;
groupshared float depthCache[64]; // 8x8线程组共享内存
[numthreads(8, 8, 1)]
void CSMain_HiZ(uint3 id : SV_DispatchThreadID, uint localIdx : SV_GroupIndex)
{
// 读取当前深度(取最大值)
float depth = _DepthTexture.Load(uint3(id.xy, 0));
depthCache[localIdx] = depth;
GroupMemoryBarrierWithGroupSync();
// 并行归约求深度最大值
[unroll]
for (int stride = 32; stride > 0; stride >>= 1) {
if (localIdx < stride) {
depthCache[localIdx] = max(depthCache[localIdx], depthCache[localIdx + stride]);
}
GroupMemoryBarrierWithGroupSync();
}
// 第一个线程写入结果
if (localIdx == 0) {
_HiZTexture[id.xy / 8] = depthCache[0]; // 下采样8x8区域
}
}
2. 创建C#脚本管理Hi-Z流程
using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; public class HiZFeature : ScriptableRendererFeature { class HiZPass : ScriptableRenderPass { const string ProfilerTag = "HiZ Generation"; readonly ComputeShader _hizShader; RenderTexture _hizPyramid; int _kernel; Vector2Int _textureSize; public HiZPass(ComputeShader shader) { _hizShader = shader; _kernel = _hizShader.FindKernel("CSMain_HiZ"); renderPassEvent = RenderPassEvent.AfterRenderingOpaques; } public override void Configure(CommandBuffer cmd, RenderTextureDescriptor desc) { _textureSize = new Vector2Int(desc.width, desc.height); // 创建Hi-Z金字塔纹理(带Mipmaps) if (_hizPyramid == null || _hizPyramid.width != _textureSize.x) { if (_hizPyramid != null) _hizPyramid.Release(); _hizPyramid = new RenderTexture(_textureSize.x, _textureSize.y, 0, RenderTextureFormat.RFloat) { enableRandomWrite = true, autoGenerateMips = false, useMipMap = true, filterMode = FilterMode.Point }; _hizPyramid.Create(); } } public override void Execute(ScriptableRenderContext context, ref RenderingData data) { CommandBuffer cmd = CommandBufferPool.Get(ProfilerTag); // 获取相机深度纹理 var depthId = new RenderTargetIdentifier("_CameraDepthTexture"); cmd.SetComputeTextureParam(_hizShader, _kernel, "_DepthTexture", depthId); // 生成Mipmap金字塔 int width = _textureSize.x; int height = _textureSize.y; int mipLevel = 0; while (width > 8 || height > 8) // 最小8x8 { cmd.SetComputeVectorParam(_hizShader, "_TexelSize", new Vector4(1f / width, 1f / height, width, height)); cmd.SetComputeTextureParam(_hizShader, _kernel, "_HiZTexture", _hizPyramid, mipLevel); cmd.DispatchCompute(_hizShader, _kernel, Mathf.CeilToInt(width / 8f), Mathf.CeilToInt(height / 8f), 1); width = Mathf.Max(1, width >> 1); height = Mathf.Max(1, height >> 1); mipLevel++; } // 传递到Shader全局变量 cmd.SetGlobalTexture("_HiZPyramid", _hizPyramid); cmd.SetGlobalFloat("_HiZMaxLevel", mipLevel - 1); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } public void Release() { if (_hizPyramid != null) _hizPyramid.Release(); } } [SerializeField] ComputeShader _hizComputeShader; HiZPass _pass; public override void Create() { if (_hizComputeShader == null) { Debug.LogError("HiZ Compute Shader missing!"); return; } _pass = new HiZPass(_hizComputeShader); } public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData data) { if (data.cameraData.cameraType == CameraType.Game) renderer.EnqueuePass(_pass); } protected override void Dispose(bool disposing) { _pass?.Release(); _pass = null; } }
3. 在URP Renderer中配置
4. 在Shader中使用Hi-Z数据
Texture2D _HiZPyramid; float _HiZMaxLevel; // 层级深度遮挡测试 bool HiZOcclusionTest(float3 worldPos) { // 转换到屏幕空间 float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1)); float3 ndc = clipPos.xyz / clipPos.w; float2 uv = ndc.xy * 0.5 + 0.5; // 计算最佳Mip层级 float mip = min(_HiZMaxLevel, log2(max(abs(ddx(uv.x)), abs(ddy(uv.y))) * 2); // 从Hi-Z金字塔采样 float hizDepth = _HiZPyramid.SampleLevel(sampler_point_clamp, uv, mip).r; // 比较当前深度和Hi-Z深度 return ndc.z > hizDepth; // 如果当前深度更大,说明被遮挡 } // 在片段着色器中 void frag() { if (HiZOcclusionTest(worldPosition)) discard; // 或被遮挡物体执行其他逻辑 }
5. 优化技巧
cmd.SetExecutionFlags(CommandBufferExecutionFlags.AsyncCompute);
动态分辨率:根据性能需求动态调整Hi-Z金字塔尺寸
_textureSize = new Vector2Int( Mathf.ClosestPowerOfTwo(desc.width / 2), Mathf.ClosestPowerOfTwo(desc.height / 2) );
部分更新:仅当相机移动时更新高层级Mips
if (cameraMoved) UpdateFullPyramid(); else UpdateTopMipsOnly();
注意事项
此实现提供了完整的Hi-Z金字塔生成流程,可用于:
使用时根据具体需求调整金字塔更新频率和分辨率,在复杂场景中可提升性能30%以上(视遮挡情况而定)。
更多教学视频
Unity3D
www.bycwedu.com/promotion_channels/2146264125
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删