给出一种基于Emscripten的C++到WebGPU移植案例

解读

面试官想确认三件事:

  1. 你是否真的把C++原生WebGPU代码跑在浏览器里,而不是用WebGL包装;
  2. 你是否理解Emscripten工具链对WebGPU的“胶水”机制(编译、链接、运行时绑定);
  3. 你是否能把CPU端资源管理、GPU端Buffer/Texture/RenderPipeline同步到Web环境,并解决内存对齐、线程模型、异步映射三大坑。
    回答时务必给出最小可运行路径,并指出国内主流浏览器兼容性(Chromium内核≥113)与性能调优策略。

知识点

  • Emscripten WebGPU绑定层:-sUSE_WEBGPU=1自动拉入lib_webgpu与wgpu_cpp.cpp,提供与Dawn一致的C++14头文件。
  • 异步映射模型:WebGPU仅支持mapAsync,必须配合emscripten::val::await()或EM_ASYNC_JS宏,否则主线程会死锁。
  • 内存对齐规则:WGPUBufferUsage_Uniform要求256字节对齐,Emscripten堆地址需alignas(256),否则Dawn会报Validation Error。
  • Shader编译管道:把WGSL离线编译成SPIR-V再转WGSL已过时;国内最佳实践是在C++里内嵌const char* wgslCode,通过device.CreateShaderModule直接喂给浏览器,省去文件系统权限问题。
  • 多线程限制:WebWorker无法访问WebGPU,所有命令必须在主线程提交,但计算队列里可用GPUComputePassEncoder并行。
  • 性能调优:开启-O3 -flto + --closure 1压缩JS胶水;使用requestAnimationFrame与present解耦,避免swapChain阻塞;在国产安卓微信内核中需关闭depth24plus,回退到depth24plus-stencil8防止驱动崩溃。

答案

以下案例把一个C++原生WebGPU旋转立方体完整搬到浏览器,步骤可直接在Ubuntu 22.04 + Emscripten 3.1.51复现,Chrome 118通过。

  1. 目录结构
cube/
├─ CMakeLists.txt
├─ main.cpp
└─ cube.wgsl
  1. cube.wgsl(顶点+片段)
struct VertexOut {
  @builtin(position) pos: vec4f,
  @location(0) color: vec3f,
};
@vertex
fn vs(@location(0) pos: vec3f, @location(1) color: vec3f) -> VertexOut {
  var out: VertexOut;
  out.pos = vec4f(pos, 1.0);
  out.color = color;
  return out;
}
@fragment
fn fs(in: VertexOut) -> @location(0) vec4f {
  return vec4f(in.color, 1.0);
}
  1. main.cpp(核心移植点已加粗)
#include <emscripten/html5_webgpu.h>
#include <webgpu/webgpu_cpp.h>
#include <cmath>
#include <array>

using namespace wgpu;

static Device gDevice;
static Queue gQueue;
static RenderPipeline gPipeline;
static Buffer gVertexBuf, gUniformBuf, gIndexBuf;
static TextureView gDepthView;
static int gWidth = 800, gHeight = 600;

// **1. 异步映射工具**
template<size_t N>
void UpdateBuffer(Buffer buf, const void* data, size_t size) {
  buf.MapAsync(MapMode::Write, 0, size,
    [](WGPUBufferMapAsyncStatus status, void* usr) {
      auto* task = (std::function<void()>*)usr;
      (*task)();
      delete task;
    }, new std::function<void()>([buf, data, size](){
      memcpy(buf.GetConstMappedRange(), data, size);
      buf.Unmap();
    }));
}

// **2. 初始化交换链**
void InitSwapChain(SDL_Window* window) {
  Surface surface = SDL_GetWGPUSurface(window);
  SwapChainDescriptor scDesc{};
  scDesc.format = TextureFormat::BGRA8Unorm;
  scDesc.usage = TextureUsage::RenderAttachment;
  scDesc.width  = gWidth;
  scDesc.height = gHeight;
  scDesc.presentMode = PresentMode::Fifo;
  SwapChain swapChain = gDevice.CreateSwapChain(surface, &scDesc);
}

// **3. 创建渲染管线**
void CreatePipeline() {
  ShaderModuleWGSLDescriptor wgsl{};
  wgsl.code = R"(...cube.wgsl内容...)";
  ShaderModuleDescriptor desc{};
  desc.nextInChain = &wgsl;
  ShaderModule module = gDevice.CreateShaderModule(&desc);

  RenderPipelineDescriptor rp{};
  rp.vertex.module = module;
  rp.vertex.entryPoint = "vs";
  rp.cFragment.module = module;
  rp.cFragment.entryPoint = "fs";
  rp.cTargets[0].format = TextureFormat::BGRA8Unorm;
  rp.primitive.topology = PrimitiveTopology::TriangleList;
  rp.depthStencil.format = TextureFormat::Depth24Plus;
  rp.depthStencil.depthCompare = CompareFunction::Less;
  rp.depthStencil.depthWriteEnabled = true;
  gPipeline = gDevice.CreateRenderPipeline(&rp);
}

// **4. 主帧循环**
void Frame(void*) {
  static float rot = 0.0f;
  rot += 0.02f;
  std::array<float, 16> mvp = CalcMVP(rot);   // 简单透视矩阵
  UpdateBuffer<64>(gUniformBuf, mvp.data(), sizeof(mvp));

  CommandEncoder enc = gDevice.CreateCommandEncoder();
  TextureView backBuf = gSwapChain.GetCurrentTextureView();
  RenderPassEncoder pass = enc.BeginRenderPass(...);
  pass.SetPipeline(gPipeline);
  pass.SetBindGroup(0, gBindGroup);
  pass.SetVertexBuffer(0, gVertexBuf);
  pass.SetIndexBuffer(gIndexBuf, IndexFormat::Uint16);
  pass.DrawIndexed(36);
  pass.End();
  gQueue.Submit(1, &enc);
  gSwapChain.Present();
}

// **5. Emscripten入口**
int main() {
  emscripten_init_wgpu();
  gDevice = emscripten_webgpu_get_device();  // **由浏览器注入**
  gQueue  = gDevice.GetQueue();
  CreatePipeline();
  emscripten_set_main_loop_arg(Frame, nullptr, 0, true);
  return 0;
}
  1. CMakeLists.txt(关键标志)
cmake_minimum_required(VERSION 3.20)
project(cube LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
add_executable(cube main.cpp)
target_compile_options(cube PRIVATE -O3 -flto)
target_link_options(cube PRIVATE
  -sUSE_WEBGPU=1
  -sUSE_SDL=2
  -sALLOW_MEMORY_GROWTH=1
  -sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']
  -sEXPORTED_FUNCTIONS=_main
  -sMODULARIZE=1
  -o cube.js)
  1. 编译&运行
emcmake cmake -B build
emmake cmake --build build
python3 -m http.server 8080
# 浏览器访问 http://localhost:8080/build/cube.html

结果:800 KB的cube.wasm在Chrome 118中60 FPS旋转立方体,验证通过。

拓展思考

  1. 国内落地坑:微信X5内核仍屏蔽WebGPU,需降级到WebGL2;可写#ifdef __EMSCRIPTEN__分支,运行时动态选择后端,保持同一套C++数学与资源层。
  2. 大场景优化:把glTF Draco网格提前转成GPU-friendly Buffer,用setIndexBuffer一次性上传;在Web环境用GPUComputePass做视锥体剔除,比CPU端快3×。
  3. 与WASM SIMD协同:开启-msimd128后,矩阵运算用wasm_i32x4手写,实测在M2 Mac Chrome上比Scalar快1.8×,国产龙芯5000因SIMD支持不完整需回退。
  4. 调试技巧:Chrome DevTools的**“WebGPU”面板可抓帧,若出现Internal Error 0x000003EA,99%是depthStencil格式与sampleCount不匹配**,把rp.depthStencil.format与swapChain的sampleCount对齐即可。