WebGPU 阴影映射:从光源视角渲染深度图

说明:抓到的原文片段只有页面导航、样式和侧边栏,<div className="lesson-main"> 里的正文内容是缺的。所以下面不是逐句翻译,而是按该教程公开版本的核心知识整理的解读,代码也是简化示例,不是原文逐字代码。


阴影映射核心原理

阴影映射(Shadow Mapping)是实时渲染里最常用的阴影技术。流程就两步:

  1. 从光源视角渲染场景:把场景深度写进一张深度纹理(Depth Texture)。
  2. 主渲染阶段比深度:把片段变换到光源的投影空间,采样深度纹理,拿片段的实际深度和存下来的深度比一比,看这个片段是不是在阴影里。

WebGPU 做阴影映射,要建一个只有深度附件的渲染通道,主渲染时再用深度比较采样器采样。


核心代码示例

创建深度纹理

const depthTexture = device.createTexture({
  size: [1024, 1024], // 阴影贴图分辨率
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
  format: "depth32float", // 深度格式
});

const shadowSampler = device.createSampler({
  compare: "less", // 深度比较函数
  magFilter: "linear",
  minFilter: "linear",
});

渲染深度通道(光源视角)

const depthEncoder = device.createCommandEncoder();
const depthPass = depthEncoder.beginRenderPass({
  colorAttachments: [], // 没有颜色附件
  depthStencilAttachment: {
    view: depthTexture.createView(),
    depthClearValue: 1.0, // 远平面深度为 1.0
    depthLoadOp: "clear",
    depthStoreOp: "store",
  },
});
depthPass.setPipeline(depthPipeline);
// ... 绑定光源视角的 VP 矩阵并绘制场景 ...
depthPass.end();

主渲染着色器(WGSL)

struct Uniforms {
  cameraViewProjectionMatrix: mat4x4f,
  lightViewProjectionMatrix: mat4x4f,
  lightDirection: vec3f,
};

@group(0) @binding(0) `var<uniform>` uni: Uniforms;
@group(1) @binding(0) var shadowMap: texture_depth_2d;
@group(1) @binding(1) var shadowSampler: sampler_comparison;

struct FragmentInput {
  @builtin(position) position: vec4f,
  @location(0) normal: vec3f,
  @location(1) shadowPosition: vec4f,
};

@vertex
fn vsMain(@location(0) position: vec3f,
          @location(1) normal: vec3f) -> FragmentInput {
  var out: FragmentInput;
  out.position = uni.cameraViewProjectionMatrix * vec4f(position, 1.0);
  out.normal = normal;
  out.shadowPosition = uni.lightViewProjectionMatrix * vec4f(position, 1.0);
  return out;
}

@fragment
fn fsMain(frag: FragmentInput) -> @location(0) vec4f {
  // 将阴影坐标从裁剪空间转换到 NDC,再映射到 [0,1] 纹理坐标
  let shadowPos = frag.shadowPosition.xyz / frag.shadowPosition.w;
  let uv = shadowPos.xy * 0.5 + 0.5;

  // 深度比较采样,返回 0 或 1
  let inShadow = textureSampleCompare(
    shadowMap,
    shadowSampler,
    uv,
    shadowPos.z - 0.0005   // bias 防止阴影痤疮
  );

  let lightAngleDot = dot(normalize(uni.lightDirection), normalize(frag.normal));
  let light = saturate(lightAngleDot);
  let shadowFactor = select(0.0, 1.0, inShadow);

  let baseColor = vec3f(0.8, 0.8, 0.8);
  return vec4f(baseColor * light * shadowFactor, 1.0);
}

关键的三点

用硬件深度比较采样器(sampler_comparison + textureSampleCompare)。WebGPU 能建带 compare 参数的采样器,配上 texture_depth_2d 纹理直接做深度比较。手写比较的代码省了,还能吃到硬件加速的 PCF(Percentage Closer Filtering):采样的时候顺手把比较和线性过滤做完,阴影边缘的锯齿能压下去不少。

加深度偏移(Depth Bias)。深度纹理分辨率有限,直接比深度很容易出阴影痤疮(shadow acne)。比较时减掉一个很小的偏移量 bias(比如 0.0005),问题能轻很多。偏移量得按场景尺度调,给太大就会出现“阴影悬浮”(peter panning)。

阴影贴图渲染路径也能省。- 只渲深度:阴影 pass 里不绑颜色附件,只写深度,带宽省下来。- 投影矩阵收紧凑点:光源视锥尽量贴着场景包围盒,别浪费深度范围。- 分辨率挑合适的:阴影贴图分辨率直接影响阴影质量和性能,按光源影响范围权衡。- 复用阴影贴图:光照方向固定的话,只更新需要动的对象。


术语对照

GLSL / WebGL 术语WGSL / WebGPU 对应说明
sampler2DShadowtexture_depth_2d + sampler_comparisonWebGPU 把深度纹理和比较采样器拆开了
texture(sampler2DShadow, vec3)textureSampleCompare(t, s, coord, ref)深度比较采样
gl.createTexture() + gl.texImage2D()device.createTexture()创建纹理
gl.RENDER_ATTACHMENTGPUTextureUsage.RENDER_ATTACHMENT渲染附件用途
gl.TEXTURE_2Dtexture_2d<f32> / texture_depth_2d纹理类型,深度纹理得显式声明
gl_FragDepth@builtin(frag_depth)片元深度输出
gl.clearDepth(1.0)depthClearValue: 1.0深度清除值

最后提一句:WebGPU 的着色语言是 WGSL,不是 GLSL。概念上接近,API 和语法都有差别。把 WebGL 的阴影实现搬到 WebGPU 时,记得用 texture_depth_2d、sampler_comparison 和 textureSampleCompare,深度附件的 depthLoadOp / depthStoreOp 也要显式设。