WebGPU Cubemaps(立方体贴图)

原作者: webgpufundamentals Contributors


这篇是“给着色器喂数据的几种方式”系列里的一篇。每篇都接着上一篇讲,按顺序读更顺。读之前最好先看过纹理文章、导入图像到纹理的文章,还有方向光照文章里的概念。

在之前的文章里,我们聊过怎么用纹理、怎么拿 0 到 1 的纹理坐标去引用纹理,还有怎么用 mip 做可选过滤。

另一种纹理类型是立方体贴图(cubemap)。它由 6 个面拼成,正好对应立方体的 6 个面。跟传统的二维纹理坐标不一样,立方体贴图用的是法线,或者说一个 3D 方向。看这个方向指向哪,就从 6 个面里挑一个,再在那个面里采样,取到颜色。

先做个简单例子:用 2D canvas 给 6 个面各生成一张图。

这段代码会填满 canvas,再把一行文字居中画上去:

function generateFace(size, { faceColor, textColor, text }) {
  const canvas = document.createElement("canvas");
  canvas.width = size;
  canvas.height = size;
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = faceColor;
  ctx.fillRect(0, 0, size, size);
  ctx.font = `${size * 0.7}px sans-serif`;
  ctx.fillStyle = textColor;
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  const m = ctx.measureText(text);
  ctx.fillText(
    text,
    (size - m.actualBoundingBoxRight + m.actualBoundingBoxLeft) / 2,
    (size - m.actualBoundingBoxDescent + m.actualBoundingBoxAscent) / 2,
  );
  return canvas;
}

调它生成 6 张图:

const faceSize = 128;
const faceCanvases = [
  { faceColor: "#F00", textColor: "#0FF", text: "+X" },
  { faceColor: "#FF0", textColor: "#00F", text: "-X" },
  { faceColor: "#0F0", textColor: "#F0F", text: "+Y" },
  { faceColor: "#0FF", textColor: "#F00", text: "-Y" },
  { faceColor: "#00F", textColor: "#FF0", text: "+Z" },
  { faceColor: "#F0F", textColor: "#0F0", text: "-Z" },
].map((faceInfo) => generateFace(faceSize, faceInfo));

// 显示结果
for (const canvas of faceCanvases) {
  document.body.appendChild(canvas);
}

(想看生成的面图,可以点原链接)

现在用立方体贴图把这 6 张图贴到立方体上。代码从导入纹理文章里的纹理图集示例起步。

先改着色器,让它用立方体贴图:

struct Uniforms {
  matrix: mat4x4f,
};

struct Vertex {
  @location(0) position: vec4f,
-  @location(1) texcoord: vec2f,
};

struct VSOutput {
  @builtin(position) position: vec4f,
-  @location(0) texcoord: vec2f,
+  @location(0) normal: vec3f,
};

...

@vertex fn vs(vert: Vertex) -> VSOutput {
  var vsOut: VSOutput;
  vsOut.position = uni.matrix * vert.position;
-  vsOut.texcoord = vert.texcoord;
+  vsOut.normal = normalize(vert.position.xyz);
  return vsOut;
}

纹理坐标删掉了,改成把法线当阶段间变量传给片段着色器。立方体的顶点位置正好以原点为中心,所以直接拿来当法线就行。

回想一下光照文章:法线是个方向,一般用来表示某个顶点表面的朝向。这里拿归一化后的位置当法线,所以给这个立方体打光,出来的是平滑的光照效果。

(原文这里有张对比图:标准立方体法线 vs 本立方体法线)

纹理坐标不用了,跟它有关的设置代码都可以删掉:

  const vertexData = new Float32Array([
-     // front face     select the top left image
-    -1,  1,  1,        0   , 0  ,
-    -1, -1,  1,        0   , 0.5,
-     1,  1,  1,        0.25, 0  ,
-     1, -1,  1,        0.25, 0.5,
-     // right face     select the top middle image
-     1,  1, -1,        0.25, 0  ,
-     1,  1,  1,        0.5 , 0  ,
-     1, -1, -1,        0.25, 0.5,
-     1, -1,  1,        0.5 , 0.5,
-     // back face      select to top right image
-     1,  1, -1,        0.5 , 0  ,
-     1, -1, -1,        0.5 , 0.5,
-    -1,  1, -1,        0.75, 0  ,
-    -1, -1, -1,        0.75, 0.5,
-    // left face       select the bottom left image
-    -1,  1,  1,        0   , 0.5,
-    -1,  1, -1,        0.25, 0.5,
-    -1, -1,  1,        0   , 1  ,
-    -1, -1, -1,        0.25, 1  ,
-    // bottom face     select the bottom middle image
-     1, -1,  1,        0.25, 0.5,
-    -1, -1,  1,        0.5 , 0.5,
-     1, -1, -1,        0.25, 1  ,
-    -1, -1, -1,        0.5 , 1  ,
-    // top face        select the bottom right image
-    -1,  1,  1,        0.5 , 0.5,
-     1,  1,  1,        0.75, 0.5,
-    -1,  1, -1,        0.5 , 1  ,
-     1,  1, -1,        0.75, 1  ,
+     // front face
+    -1,  1,  1,
+    -1, -1,  1,
+     1,  1,  1,
+     1, -1,  1,
+     // right face
+     1,  1, -1,
+     1,  1,  1,
+     1, -1, -1,
+     1, -1,  1,
+     // back face
+     1,  1, -1,
+     1, -1, -1,
+    -1,  1, -1,
+    -1, -1, -1,
+    // left face
+    -1,  1,  1,
+    -1,  1, -1,
+    -1, -1,  1,
+    -1, -1, -1,
+    // bottom face
+     1, -1,  1,
+    -1, -1,  1,
+     1, -1, -1,
+    -1, -1, -1,
+    // top face
+    -1,  1,  1,
+     1,  1,  1,
+    -1,  1, -1,
+     1,  1, -1,
  ]);

  ...

  const pipeline = device.createRenderPipeline({
    label: '2 attributes',
    layout: 'auto',
    vertex: {
      module,
      buffers: [
        {
-          arrayStride: (3 + 2) * 4, // (3+2) floats 4 bytes each
+          arrayStride: (3) * 4, // (3) floats 4 bytes each
          attributes: [
            {shaderLocation: 0, offset: 0, format: 'float32x3'},  // position
-            {shaderLocation: 1, offset: 12, format: 'float32x2'},  // texcoord
          ],
        },
      ],
    },
    fragment: {
      module,
      targets: [{ format: presentationFormat }],
    },
    primitive: {
      cullMode: 'back',
    },
    depthStencil: {
      depthWriteEnabled: true,
      depthCompare: 'less',
      format: 'depth24plus',
    },
  });

片段着色器里得用 texture_cube,不能再用 texture_2d。textureSample 配 texture_cube 用时收的是一个 vec3f 方向,所以这里传法线。法线是阶段间变量,会被插值,所以还得归一化一下:

@group(0) @binding(0) `var<uniform>` uni: Uniforms;
@group(0) @binding(1) var ourSampler: sampler;
-@group(0) @binding(2) var ourTexture: `texture_2d<f32>`;
+@group(0) @binding(2) var ourTexture: `texture_cube<f32>`;

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
-  return textureSample(ourTexture, ourSampler, vsOut.texcoord);
+  return textureSample(ourTexture, ourSampler, normalize(vsOut.normal));
}

要建立方体贴图,其实就是建一个 6 层的 2D 纹理。接下来把几个辅助函数都改成能处理多个来源。

让纹理辅助函数处理多个层

先把 createTextureFromSource 改成 createTextureFromSources,收一个来源数组:

-  function createTextureFromSource(device, source, options = {}) {
+  function createTextureFromSources(device, sources, options = {}) {
+    // 假设所有来源尺寸相同,仅用第一个来源的宽高
+    const source = sources[0];
    const texture = device.createTexture({
      format: 'rgba8unorm',
      mipLevelCount: options.mips ? numMipLevels(source.width, source.height) : 1,
-      size: [source.width, source.height],
+      size: [source.width, source.height, sources.length],
      usage: GPUTextureUsage.TEXTURE_BINDING |
             GPUTextureUsage.COPY_DST |
             GPUTextureUsage.RENDER_ATTACHMENT,
    });
-    copySourceToTexture(device, texture, source, options);
+    copySourcesToTexture(device, texture, sources, options);
    return texture;
  }

这段代码建了一个多层纹理,一层对应一个来源。同时假定所有来源尺寸一样——这也说得通,同一个纹理的各层尺寸不同,本来就少见。

再把 copySourceToTexture 改成能处理多个来源:

-  function copySourceToTexture(device, texture, source, {flipY} = {}) {
+  function copySourcesToTexture(device, texture, sources, {flipY} = {}) {
+    sources.forEach((source, layer) => {
*      device.queue.copyExternalImageToTexture(
*        { source, flipY, },
-        { texture },
+        { texture, origin: [0, 0, layer] },
*        { width: source.width, height: source.height },
*      );
+  });

    if (texture.mipLevelCount > 1) {
      generateMips(device, texture);
    }
  }

主要差别是多了一个循环,遍历所有来源,并设好 origin,把每个来源拷到对应的层。

接着把 generateMips 改成能处理多个层:

  const generateMips = (() => {
    let sampler;
    let module;
    const pipelineByFormat = {};

    return function generateMips(device, texture) {
      if (!module) {
        module = device.createShaderModule({
          label: 'textured quad shaders for mip level generation',
          code: /* wgsl */ `
            struct VSOutput {
              @builtin(position) position: vec4f,
              @location(0) texcoord: vec2f,
            };

            @vertex fn vs(
              @builtin(vertex_index) vertexIndex : u32
            ) -> VSOutput {
              let pos = array(
                // 1st triangle
                vec2f( 0.0,  0.0),  // center
                vec2f( 1.0,  0.0),  // right, center
                vec2f( 0.0,  1.0),  // center, top

                // 2nd triangle
                vec2f( 0.0,  1.0),  // center, top
                vec2f( 1.0,  0.0),  // right, center
                vec2f( 1.0,  1.0),  // right, top
              );

              var vsOutput: VSOutput;
              let xy = pos[vertexIndex];
              vsOutput.position = vec4f(xy * 2.0 - 1.0, 0.0, 1.0);
              vsOutput.texcoord = vec2f(xy.x, 1.0 - xy.y);
              return vsOutput;
            }

            @group(0) @binding(0) var ourSampler: sampler;
            @group(0) @binding(1) var ourTexture: `texture_2d<f32>`;

            @fragment fn fs(fsInput: VSOutput) -> @location(0) vec4f {
              return textureSample(ourTexture, ourSampler, fsInput.texcoord);
            }
          `,
        });

        sampler = device.createSampler({
          minFilter: 'linear',
          magFilter: 'linear',
        });
      }

      if (!pipelineByFormat[texture.format]) {
        pipelineByFormat[texture.format] = device.createRenderPipeline({
          label: 'mip level generator pipeline',
          layout: 'auto',
          vertex: {
            module,
          },
          fragment: {
            module,
            targets: [{ format: texture.format }],
          },
        });
      }
      const pipeline = pipelineByFormat[texture.format];

      const encoder = device.createCommandEncoder({
        label: 'mip gen encoder',
      });

      for (let baseMipLevel = 1; baseMipLevel < texture.mipLevelCount; ++baseMipLevel) {
+        for (let layer = 0; layer < texture.depthOrArrayLayers; ++layer) {
*          const bindGroup = device.createBindGroup({
*            layout: pipeline.getBindGroupLayout(0),
*            entries: [
*              { binding: 0, resource: sampler },
-              { binding: 1, resource: texture.createView({baseMipLevel, mipLevelCount: 1}) },
+              {
+                binding: 1,
+                resource: texture.createView({
+                  dimension: '2d',
+                  baseMipLevel: baseMipLevel - 1,
+                  mipLevelCount: 1,
+                  baseArrayLayer: layer,
+                  arrayLayerCount: 1,
+                }),
*              },
*            ],
*          });
*
*          const renderPassDescriptor = {
*            label: 'our basic canvas renderPass',
*            colorAttachments: [
*              {
-                view: texture.createView({baseMipLevel, mipLevelCount: 1}),
+                view: texture.createView({
+                  dimension: '2d',
+                  baseMipLevel: baseMipLevel,
+                  mipLevelCount: 1,
+                  baseArrayLayer: layer,
+                  arrayLayerCount: 1,
+                }),
*                loadOp: 'clear',
*                storeOp: 'store',
*              },
*            ],
*          };
*
*          const pass = encoder.beginRenderPass(renderPassDescriptor);
*          pass.setPipeline(pipeline);
*          pass.setBindGroup(0, bindGroup);
*          pass.draw(6);  // call our vertex shader 6 times
*          pass.end();
+        }
+      }

      const commandBuffer = encoder.finish();
      device.queue.submit([commandBuffer]);
    };
  })();

这里加了个循环,逐层处理纹理。视图也改了,专门挑单个层,并显式写上 dimension: '2d'。因为默认情况下,多层 2D 纹理的视图会变成 dimension: '2d-array',生成 mipmap 时这不是我们要的。

提一句:兼容模式文章里有个能在兼容模式下跑的 generateMips 版本。

这里虽然用不上,但原来的 createTextureFromSource 和 copySourceToTexture 可以顺手改成:

function copySourceToTexture(device, texture, source, options = {}) {
  copySourcesToTexture(device, texture, [source], options);
}

function createTextureFromSource(device, source, options = {}) {
  return createTextureFromSources(device, [source], options);
}

现在可以用文章开头生成的那几个面了:

const texture = await createTextureFromSources(device, faceCanvases, {
  mips: true,
  flipY: false,
});

最后在绑定组里改一下纹理视图:

const bindGroup = device.createBindGroup({
  label: "bind group for object",
  layout: pipeline.getBindGroupLayout(0),
  entries: [
    { binding: 0, resource: uniformBuffer },
    { binding: 1, resource: sampler },
    -{ binding: 2, resource: texture },
    +{ binding: 2, resource: texture.createView({ dimension: "cube" }) },
  ],
});

搞定。

(原链接里有实时示例,能看到旋转的立方体贴图)

注意各个面当纹理层时的顺序:

  • 层 0 = 正 X
  • 层 1 = 负 X
  • 层 2 = 正 Y
  • 层 3 = 负 Y
  • 层 4 = 正 Z
  • 层 5 = 负 Z

换个角度想:调 textureSample 时传对应的方向,返回的就是那个纹理层中心像素的颜色:

  • textureSample(tex, sampler, vec3f( 1, 0, 0)) → 层 0 的中心
  • textureSample(tex, sampler, vec3f(-1, 0, 0)) → 层 1 的中心
  • textureSample(tex, sampler, vec3f( 0, 1, 0)) → 层 2 的中心
  • textureSample(tex, sampler, vec3f( 0,-1, 0)) → 层 3 的中心
  • textureSample(tex, sampler, vec3f( 0, 0, 1)) → 层 4 的中心
  • textureSample(tex, sampler, vec3f( 0, 0,-1)) → 层 5 的中心

拿立方体贴图给立方体贴图,其实不是它的常规用途。正规做法是用纹理图集。这篇主要是讲清立方体贴图的概念,演示怎么传方向(法线)、再取回这个方向上的颜色。

立方体贴图是什么、怎么配,都清楚了,那它真正用来干嘛?最常见的用法大概是当环境贴图。


关键的三点

  1. 用 mipmap 兼顾采样质量和性能。
    建立方体贴图时打开 mips: true,再调 generateMips。这样每个面都会生成一条多级 mip 链,远处或斜着看时锯齿和摩尔纹会少很多,纹理缓存效率也更高。

  2. mipmap 要逐层生成,还得显式写上 dimension: '2d'。
    立方体贴图本质是个 6 层的纹理数组,所以生成 mipmap 时必须一层一层循环,每层单独建一个 2D 视图(dimension: '2d'、baseArrayLayer、arrayLayerCount: 1)。默认的多层视图会变成 '2d-array',mipmap 就生成错了。显式写 dimension: '2d',才能保证每层都当成独立的 2D 纹理处理。

  3. 用立方体贴图视图(dimension: 'cube')把采样简化掉。
    调 texture.createView({dimension: 'cube'}) 建出立方体贴图视图,WGSL 里就能直接声明 texture_cube,调 textureSample 时传个 3D 方向向量。这样不用自己选面、算 UV,面选择和过滤全交给 GPU 硬件。


术语对照

这篇涉及 WebGPU 和 WGSL 的术语(有些概念跟 WebGL/GLSL 像,但也不完全一样)。下面把关键术语和中文译法列一下:

英文术语中文翻译说明
Cubemap立方体贴图由 6 个面组成的纹理类型,通过 3D 方向采样
Texture纹理GPU 中存储图像数据的对象
Sampler采样器定义纹理过滤、寻址模式等采样参数
Mipmap / Mip levelMipmap / Mip 级别纹理的预缩放链,远距离采样用
Inter-stage variable阶段间变量顶点着色器输出、片段着色器输入的可插值变量
Fragment shader片段着色器处理像素着色的可编程阶段
Vertex shader顶点着色器处理顶点变换的可编程阶段
Render pipeline渲染管线包含着色器、混合、深度等状态的管线对象
Bind group绑定组一组绑定资源(缓冲、纹理、采样器)的集合
texture_cube<f32>WGSL 立方体贴图纹理类型等价于 GLSL 中的 samplerCube
texture_2d<f32>WGSL 2D 纹理类型等价于 GLSL 中的 sampler2D
textureSampleWGSL 纹理采样函数等价于 GLSL 中的 texture 函数
GPUTextureUsage.TEXTURE_BINDING纹理绑定用法标志允许纹理被绑定为着色器资源
GPUTextureUsage.COPY_DST纹理复制目标用法标志允许纹理作为复制操作的目标
GPUTextureUsage.RENDER_ATTACHMENT纹理渲染附件用法标志允许纹理作为渲染目标
copyExternalImageToTexture将外部图像复制到纹理WebGPU API,类似 WebGL 的 texImage2D
createView({dimension: 'cube'})创建立方体贴图视图将多层 2D 纹理视为立方体贴图
dimension: '2d' vs '2d-array'纹理视图维度显式指定单个 2D 层视图,避免默认的数组视图
depthOrArrayLayers深度或数组层数纹理的深度或层数(立方体贴图为 6)
baseArrayLayer / arrayLayerCount基础数组层 / 数组层数量创建视图时选择特定的层范围
cullMode: 'back'背面剔除剔除背对相机的三角形
depthStencil深度模板深度和模板测试状态

这些术语在 WebGPU 和 WebGL/GLSL 里概念是通的,但 API 名字和语法不一样。本文代码是 WebGPU 加 WGSL,注意跟 GLSL 的区别(比如 WGSL 用 @location,不用 layout(location);textureSample 对应 texture 函数)。具体用法建议对着 WebGPU 规范看。