Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): the WebGPU device runs compute shaders, and the render graph has compute passes

yhh8a511e02d375
diff --git a/desktop b/desktop
index 269475ad4..7a4114229 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 269475ad4412ee970ef63258598f94ac35c26b08
+Subproject commit 7a4114229c64e56045d2bd31e1e5b4b83d6a0903
diff --git a/src/esengine/renderer/graph/RenderGraph.cpp b/src/esengine/renderer/graph/RenderGraph.cpp
index 74af866d4..db3e46f17 100644
--- a/src/esengine/renderer/graph/RenderGraph.cpp
+++ b/src/esengine/renderer/graph/RenderGraph.cpp
@@ -144,6 +144,7 @@ TargetHandle RenderGraph::acquire(const Resource& res) {
shape.depthStencil = res.desc.depthStencil;
shape.samples = res.desc.samples;
shape.gbuffer = res.desc.gbuffer;
+ shape.storage = res.desc.storage;
const TargetHandle handle = pool_.acquire(shape);
if (handle != kNoTarget) borrowed_.push_back(handle);
return handle;
@@ -195,6 +196,25 @@ void RenderGraph::execute() {
fbo = target.target;
}
+ if (pass.compute) {
+ // A dispatch is not a draw: it runs between render passes, with nothing bound for it by the graph.
+ inputScratch_.clear();
+ for (const ResourceId id : pass.reads) inputScratch_.push_back(textureOf(id));
+ if (pass.execute) {
+ PassContext ctx;
+ ctx.width = target.width;
+ ctx.height = target.height;
+ ctx.inputs = &inputScratch_;
+ ctx.output = target.texture;
+ pass.execute(ctx);
+ }
+ ++executed_;
+ for (auto& res : resources_) {
+ if (res.kind == Kind::Transient && res.lastRead == static_cast<i32>(i)) release(res);
+ }
+ continue;
+ }
+
RenderPassDesc rp{};
rp.target = fbo;
rp.clearColor = pass.clear;
diff --git a/src/esengine/renderer/graph/RenderGraph.hpp b/src/esengine/renderer/graph/RenderGraph.hpp
index 9a617499b..f53df23b6 100644
--- a/src/esengine/renderer/graph/RenderGraph.hpp
+++ b/src/esengine/renderer/graph/RenderGraph.hpp
@@ -66,6 +66,8 @@ struct TargetDesc {
u32 samples = 1;
/// A second colour attachment for the surface's material, drawn beside the first.
bool gbuffer = false;
+ /// Written by a compute shader (a pass with `compute` set), then sampled like any target.
+ bool storage = false;
};
/** What a pass's execute() is told: where it is drawing and what it may read. */
@@ -74,6 +76,8 @@ struct PassContext {
u32 height = 0;
/// The pass's declared reads, already bound to units 0..n-1, in order.
const std::vector<TextureHandle>* inputs = nullptr;
+ /// The texture this pass writes: the storage texture of a compute pass (a render pass draws into its framebuffer instead).
+ TextureHandle output = TextureHandle::Invalid;
TextureHandle input(u32 i) const {
return (inputs && i < inputs->size()) ? (*inputs)[i] : TextureHandle::Invalid;
@@ -100,6 +104,11 @@ struct PassDesc {
*/
std::vector<ResourceId> dependencies;
ResourceId write = kNoResource;
+ /**
+ * @brief A compute pass: no render pass is opened and no unit is bound — `execute` dispatches, reading `ctx.input(i)` and
+ * writing `ctx.output`, which has to be a target declared with `storage`. Ordered, culled and recycled like any pass.
+ */
+ bool compute = false;
bool clear = false;
/// Clears the depth attachment with the colour, for a target that has one.
/// A geometry pass writes depth, so the frame before it is not what it
diff --git a/src/esengine/renderer/graph/TargetPool.cpp b/src/esengine/renderer/graph/TargetPool.cpp
index 102b6c22b..941b65584 100644
--- a/src/esengine/renderer/graph/TargetPool.cpp
+++ b/src/esengine/renderer/graph/TargetPool.cpp
@@ -32,7 +32,7 @@ u64 texelBytes(const TargetShape& shape) {
bool sameShape(const TargetShape& a, const TargetShape& b) {
return a.width == b.width && a.height == b.height && a.format == b.format
&& a.linearFilter == b.linearFilter && a.depthStencil == b.depthStencil
- && a.samples == b.samples && a.gbuffer == b.gbuffer;
+ && a.samples == b.samples && a.gbuffer == b.gbuffer && a.storage == b.storage;
}
} // namespace
@@ -75,6 +75,7 @@ TargetHandle TargetPool::acquire(const TargetShape& shape) {
spec.colorFormat = shape.format;
spec.samples = shape.samples;
spec.gbuffer = shape.gbuffer;
+ spec.storage = shape.storage;
auto fbo = Framebuffer::create(device_, spec);
if (!fbo) {
ES_LOG_ERROR("TargetPool: failed to create a {}x{} target", shape.width, shape.height);
diff --git a/src/esengine/renderer/graph/TargetPool.hpp b/src/esengine/renderer/graph/TargetPool.hpp
index 815e3a902..daae346dc 100644
--- a/src/esengine/renderer/graph/TargetPool.hpp
+++ b/src/esengine/renderer/graph/TargetPool.hpp
@@ -57,6 +57,8 @@ struct TargetShape {
u32 samples = 1;
/// A second colour attachment for the surface's material (see FramebufferSpec::gbuffer).
bool gbuffer = false;
+ /// Written by a compute shader as a storage texture, and sampled after.
+ bool storage = false;
};
class TargetPool {
diff --git a/src/esengine/renderer/rhi/Framebuffer.cpp b/src/esengine/renderer/rhi/Framebuffer.cpp
index 3ffddd8a9..a6d4d1e36 100644
--- a/src/esengine/renderer/rhi/Framebuffer.cpp
+++ b/src/esengine/renderer/rhi/Framebuffer.cpp
@@ -132,6 +132,7 @@ bool Framebuffer::initialize() {
colorDesc.minFilter = filter;
colorDesc.magFilter = filter;
colorDesc.samples = samples;
+ colorDesc.storage = spec_.storage && samples == 1 && device_->supportsCompute();
colorAttachment_ = device_->createTexture(colorDesc, GfxContent::transient(), nullptr);
// The surface's own record: 8 bits a channel is what an octahedral normal, a roughness and a metalness
diff --git a/src/esengine/renderer/rhi/Framebuffer.hpp b/src/esengine/renderer/rhi/Framebuffer.hpp
index 53149a8e4..8a9d2ca30 100644
--- a/src/esengine/renderer/rhi/Framebuffer.hpp
+++ b/src/esengine/renderer/rhi/Framebuffer.hpp
@@ -58,6 +58,8 @@ struct FramebufferSpec {
GfxPixelFormat colorFormat = GfxPixelFormat::RGBA8;
/** @brief A second colour attachment (RGBA8) drawn in the same pass: the surface's material, for effects that need to know what they are looking at. */
bool gbuffer = false;
+ /** @brief The colour attachment can also be written by a compute shader (GfxDevice::supportsCompute). */
+ bool storage = false;
};
// =============================================================================
diff --git a/src/esengine/renderer/rhi/GfxDevice.cpp b/src/esengine/renderer/rhi/GfxDevice.cpp
index 252c20136..d1a4fe75a 100644
--- a/src/esengine/renderer/rhi/GfxDevice.cpp
+++ b/src/esengine/renderer/rhi/GfxDevice.cpp
@@ -71,6 +71,7 @@ bool GfxDevice::markDeviceLost(GfxDeviceLostReason reason, std::string message,
for (auto& [id, record] : registry_.buffers.all()) { record.realized = false; record.owed = false; }
for (auto& [id, record] : registry_.textures.all()) { record.realized = false; record.owed = false; }
for (auto& [id, record] : registry_.programs.all()) record.realized = false;
+ for (auto& [id, record] : registry_.computes.all()) record.realized = false;
for (auto& [id, record] : registry_.framebuffers.all()) record.realized = false;
for (auto& [id, record] : registry_.timerQueries.all()) record.realized = false;
owed_count_ = 0;
@@ -116,6 +117,13 @@ void GfxDevice::realizeRegistry() {
}
}
+ for (auto& [id, record] : registry_.computes.all()) {
+ const GfxComputeSource source{GfxShaderLanguage::WGSL, record.source.c_str(), record.entry.c_str()};
+ std::string log;
+ record.realized = backendCreateCompute(id, source, &log);
+ if (!record.realized) ES_LOG_ERROR("Device recovery: compute program {} did not rebuild: {}", id, log);
+ }
+
for (auto& [id, record] : registry_.buffers.all()) {
const bool hasBytes = !record.bytes.empty();
record.realized = backendCreateBuffer(id, record.desc, hasBytes ? record.bytes.data() : nullptr);
@@ -603,6 +611,51 @@ void GfxDevice::deleteProgram(ShaderHandle program) {
if (current_program_ == program) current_program_ = ShaderHandle::Invalid;
}
+ComputeHandle GfxDevice::createCompute(const GfxComputeSource& source, std::string* outLog) {
+ if (device_status_ == GfxDeviceStatus::Dead) {
+ if (outLog) *outLog = "device dead";
+ return ComputeHandle::Invalid;
+ }
+ if (!supportsCompute()) {
+ if (outLog) *outLog = "this device has no compute stage";
+ return ComputeHandle::Invalid;
+ }
+ if (source.language != GfxShaderLanguage::WGSL || !source.source) {
+ if (outLog) *outLog = "compute is WGSL only";
+ return ComputeHandle::Invalid;
+ }
+ GfxComputeRecord record;
+ record.source = source.source;
+ record.entry = source.entry ? source.entry : "main";
+ const u32 id = registry_.computes.insert(std::move(record));
+ if (!isDeviceUsable()) return ComputeHandle{id};
+ if (!backendCreateCompute(id, source, outLog)) {
+ registry_.computes.erase(id);
+ return ComputeHandle::Invalid;
+ }
+ registry_.computes.find(id)->realized = true;
+ return ComputeHandle{id};
+}
+
+void GfxDevice::deleteCompute(ComputeHandle program) {
+ const u32 id = static_cast<u32>(program);
+ auto* record = registry_.computes.find(id);
+ if (!record) return;
+ if (record->realized) backendDeleteCompute(id);
+ registry_.computes.erase(id);
+}
+
+bool GfxDevice::dispatchCompute(ComputeHandle program, const GfxComputeBinding* bindings, u32 bindingCount,
+ u32 groupsX, u32 groupsY, u32 groupsZ) {
+ if (!supportsCompute() || !isDeviceUsable()) return false;
+ const u32 id = static_cast<u32>(program);
+ const auto* record = registry_.computes.find(id);
+ if (!record || !record->realized) return false;
+ if (groupsX == 0 || groupsY == 0 || groupsZ == 0) return false;
+ if (bindingCount > 0 && !bindings) return false;
+ return backendDispatchCompute(id, bindings, bindingCount, groupsX, groupsY, groupsZ);
+}
+
void GfxDevice::useProgram(ShaderHandle program) {
const u32 id = static_cast<u32>(program);
current_program_ = program;
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index 4c7f16ebc..9261a24bf 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -497,6 +497,59 @@ public:
/** @brief Deletes a shader program */
void deleteProgram(ShaderHandle program);
+ // =========================================================================
+ // Compute
+ // =========================================================================
+
+ /**
+ * @brief Whether this device runs compute shaders.
+ * @details WebGPU does; WebGL2 has no compute stage, so a caller asks first and keeps a fallback. The calls below
+ * are harmless on a device that does not: they refuse (Invalid, false) and draw nothing.
+ */
+ virtual bool supportsCompute() const { return false; }
+
+ /**
+ * @brief Compiles a compute program.
+ * @return The program, or Invalid with @p outLog saying why (no compute, wrong language, a WGSL error).
+ */
+ ComputeHandle createCompute(const GfxComputeSource& source, std::string* outLog = nullptr);
+
+ /** @brief Deletes a compute program. */
+ void deleteCompute(ComputeHandle program);
+
+ /**
+ * @brief Runs @p program over @p groupsX x @p groupsY x @p groupsZ workgroups, with these resources bound.
+ *
+ * @details Outside a render pass, in submission order with every pass before and after it, so what an earlier
+ * pass drew is there to read and what this writes is there for the next to sample. A storage buffer
+ * or texture is bound for write only by the bindings listed; the rest of the device's state is
+ * untouched.
+ * @return false when nothing ran: the device does not compute, a resource named is gone, a render pass is
+ * open, or a count is zero or over the device's limit.
+ */
+ bool dispatchCompute(ComputeHandle program, const GfxComputeBinding* bindings, u32 bindingCount,
+ u32 groupsX, u32 groupsY = 1, u32 groupsZ = 1);
+
+ /**
+ * @brief Copies bytes of a storage buffer out, to be taken with pollReadback / takeReadback.
+ * @details takeReadback hands the bytes back as they are in the buffer; @p size and @p offsetBytes are
+ * multiples of 4. Invalid on a device that does not compute.
+ */
+ virtual ReadbackHandle requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
+ (void)buffer; (void)offsetBytes; (void)sizeBytes;
+ return ReadbackHandle::Invalid;
+ }
+
+ /**
+ * @brief Copies a storage texture's pixels out, tightly packed in the texture's own format (rows top-down).
+ * @details Unlike requestReadback it names the texture, not a framebuffer, since a compute target has none.
+ * RGBA8, RGBA16F and RGBA32F: four, eight and sixteen bytes a texel.
+ */
+ virtual ReadbackHandle requestTextureReadback(TextureHandle texture) {
+ (void)texture;
+ return ReadbackHandle::Invalid;
+ }
+
/**
* @brief Binds a program directly, for setup-time uniform seeding.
* @details Per-frame rendering binds programs through setPipeline.
@@ -760,6 +813,17 @@ protected:
virtual void backendSetTextureParams(u32 id, const TextureDesc& desc) = 0;
virtual void backendGenerateMipmaps(u32 id) = 0;
+ virtual bool backendCreateCompute(u32 id, const GfxComputeSource& source, std::string* outLog) {
+ (void)id; (void)source;
+ if (outLog) *outLog = "this device has no compute stage";
+ return false;
+ }
+ virtual void backendDeleteCompute(u32 id) { (void)id; }
+ virtual bool backendDispatchCompute(u32 id, const GfxComputeBinding* bindings, u32 bindingCount,
+ u32 groupsX, u32 groupsY, u32 groupsZ) {
+ (void)id; (void)bindings; (void)bindingCount; (void)groupsX; (void)groupsY; (void)groupsZ;
+ return false;
+ }
virtual bool backendCreateProgram(u32 id, const GfxShaderSource& source,
const GfxAttribBinding* bindings, u32 bindingCount,
std::string* outLog, GfxShaderStage* outFailedStage) = 0;
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index 8cfe843e9..b75194e5e 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -31,6 +31,8 @@ namespace esengine {
enum class BufferHandle : u32 { Invalid = 0 };
enum class TextureHandle : u32 { Invalid = 0 };
enum class ShaderHandle : u32 { Invalid = 0 };
+/** @brief A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one. */
+enum class ComputeHandle : u32 { Invalid = 0 };
/** @brief Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted. */
enum class FramebufferHandle : u32 { Default = 0 };
/** @brief An in-flight framebuffer readback (GfxDevice::requestReadback). */
@@ -67,6 +69,8 @@ enum class GfxBufferUsage : u8 {
Vertex,
Index,
Uniform,
+ /// Read and written by compute shaders (`var<storage, read_write>`), and readable back. Needs a device that supportsCompute().
+ Storage,
};
// =============================================================================
@@ -414,6 +418,9 @@ struct TextureDesc {
TextureWrap wrapT = TextureWrap::ClampToEdge;
bool mipmaps = false;
bool flipY = false;
+ /// Writable from a compute shader as a storage texture. RGBA8, RGBA16F and RGBA32F only, and only on a device
+ /// that supportsCompute(); a texture asked for this elsewhere is created without it.
+ bool storage = false;
};
/**
@@ -623,6 +630,55 @@ struct GfxShaderSource {
const char* fragmentSrc = nullptr;
};
+/** @brief A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage. */
+struct GfxComputeSource {
+ GfxShaderLanguage language = GfxShaderLanguage::WGSL;
+ const char* source = nullptr;
+ /// The `@compute` entry point.
+ const char* entry = "main";
+};
+
+/**
+ * @brief One resource a compute dispatch binds, at `@group(0) @binding(binding)`.
+ *
+ * @details The bind-group layout is built from the list itself, so the shader's declarations have to say the
+ * same thing: `Uniform` is `var<uniform>`, `StorageRead` is `var<storage, read>`, `Storage` is
+ * `var<storage, read_write>`, `Texture` is a `texture_2d<f32>` (or `texture_depth_2d` for a depth
+ * texture) read with `textureLoad`, `StorageTexture` is a `texture_storage_2d<FORMAT, write>` whose
+ * format is the texture's, and `Sampler` is a `sampler`.
+ */
+struct GfxComputeBinding {
+ enum class Kind : u8 { Uniform, StorageRead, Storage, Texture, StorageTexture, Sampler };
+ Kind kind = Kind::Uniform;
+ u32 binding = 0;
+ BufferHandle buffer = BufferHandle::Invalid;
+ /// Bytes into the buffer (a multiple of 256 for a uniform, 4 for storage) and how many; 0 = the rest.
+ u32 offset = 0;
+ u32 size = 0;
+ TextureHandle texture = TextureHandle::Invalid;
+ /// A Sampler's filter.
+ TextureFilter filter = TextureFilter::Linear;
+
+ static GfxComputeBinding uniform(u32 binding, BufferHandle buffer, u32 offset = 0, u32 size = 0) {
+ GfxComputeBinding b; b.kind = Kind::Uniform; b.binding = binding; b.buffer = buffer; b.offset = offset; b.size = size; return b;
+ }
+ static GfxComputeBinding storageRead(u32 binding, BufferHandle buffer, u32 offset = 0, u32 size = 0) {
+ GfxComputeBinding b; b.kind = Kind::StorageRead; b.binding = binding; b.buffer = buffer; b.offset = offset; b.size = size; return b;
+ }
+ static GfxComputeBinding storage(u32 binding, BufferHandle buffer, u32 offset = 0, u32 size = 0) {
+ GfxComputeBinding b; b.kind = Kind::Storage; b.binding = binding; b.buffer = buffer; b.offset = offset; b.size = size; return b;
+ }
+ static GfxComputeBinding sampled(u32 binding, TextureHandle texture) {
+ GfxComputeBinding b; b.kind = Kind::Texture; b.binding = binding; b.texture = texture; return b;
+ }
+ static GfxComputeBinding storageTexture(u32 binding, TextureHandle texture) {
+ GfxComputeBinding b; b.kind = Kind::StorageTexture; b.binding = binding; b.texture = texture; return b;
+ }
+ static GfxComputeBinding sampler(u32 binding, TextureFilter filter) {
+ GfxComputeBinding b; b.kind = Kind::Sampler; b.binding = binding; b.filter = filter; return b;
+ }
+};
+
/**
* @brief Vertex attribute location binding applied before a program is linked.
* @note `name` is borrowed for the duration of the createProgram() call only.
diff --git a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp b/src/esengine/renderer/rhi/GfxResourceRegistry.hpp
index 5a9d185e1..6e9587db6 100644
--- a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp
+++ b/src/esengine/renderer/rhi/GfxResourceRegistry.hpp
@@ -73,6 +73,12 @@ struct GfxProgramRecord {
inline constexpr u32 GFX_UNBOUND_BLOCK = 0xFFFFFFFFu;
+struct GfxComputeRecord {
+ std::string source;
+ std::string entry;
+ bool realized = false;
+};
+
struct GfxFramebufferRecord {
FramebufferDesc desc;
bool realized = false;
@@ -136,6 +142,7 @@ public:
GfxRecordTable<GfxBufferRecord> buffers;
GfxRecordTable<GfxTextureRecord> textures;
GfxRecordTable<GfxProgramRecord> programs;
+ GfxRecordTable<GfxComputeRecord> computes;
GfxRecordTable<GfxFramebufferRecord> framebuffers;
GfxRecordTable<GfxLayoutRecord> layouts;
GfxRecordTable<GfxPipelineRecord> pipelines;
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 1873f34e3..bb7ed9eb2 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -201,6 +201,21 @@ void WebGPUDevice::releaseDeviceObjects() {
if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
}
programs_.clear();
+ for (auto& [id, rec] : computes_) {
+ for (auto& [key, pipeline] : rec.pipelines) {
+ if (pipeline) wgpuComputePipelineRelease(pipeline);
+ }
+ if (rec.module) wgpuShaderModuleRelease(rec.module);
+ }
+ computes_.clear();
+ for (auto& [key, layout] : compute_pipeline_layouts_) {
+ if (layout) wgpuPipelineLayoutRelease(layout);
+ }
+ compute_pipeline_layouts_.clear();
+ for (auto& [key, layout] : compute_layouts_) {
+ if (layout) wgpuBindGroupLayoutRelease(layout);
+ }
+ compute_layouts_.clear();
for (auto& [id, rec] : pipelines_) {
for (WGPURenderPipeline variant : rec.variants) {
if (variant) wgpuRenderPipelineRelease(variant);
@@ -888,6 +903,12 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
? (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_RenderAttachment)
: (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst |
WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment);
+ // A compute target is also written by shaders. Only these formats have the capability in core WebGPU,
+ // and one that does not is created plain rather than refused: the record says what it got.
+ const bool storage = desc.storage && td.sampleCount == 1 &&
+ (td.format == WGPUTextureFormat_RGBA8Unorm || td.format == WGPUTextureFormat_RGBA16Float ||
+ td.format == WGPUTextureFormat_RGBA32Float);
+ if (storage) td.usage |= WGPUTextureUsage_StorageBinding;
// No copies: invalid on a multisampled texture. Depth keeps TextureBinding
// because resolveDepthAttachment samples it; colour is read through the
// single-sample twin the pass resolves into.
@@ -940,6 +961,7 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
desc.width, desc.height, td.format, desc.format,
packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT),
td.sampleCount, td.mipLevelCount};
+ out.storage = storage;
if (pixels && !isDepthFormat(td.format)) {
// desc.flipY, not false: the caller's orientation request has to reach the
@@ -2547,6 +2569,24 @@ bool WebGPUDevice::takeReadback(ReadbackHandle handle, void* dest, usize destSiz
auto it = readbacks_.find(static_cast<u32>(handle));
if (it == readbacks_.end() || it->second.status != GfxReadbackStatus::Ready) return false;
ReadbackRec& rec = it->second;
+ if (rec.raw) {
+ // A compute readback: the source's own bytes, rows top-down with the padding taken out.
+ if (destSize < rec.tightBytes) return false;
+ const auto* mapped = static_cast<const u8*>(
+ wgpuBufferGetConstMappedRange(rec.buffer, 0, static_cast<u64>(rec.paddedBytesPerRow) * rec.height));
+ if (!mapped) {
+ releaseReadback(static_cast<u32>(handle));
+ return false;
+ }
+ auto* out = static_cast<u8*>(dest);
+ const u32 rowBytes = rec.width * rec.bytesPerTexel;
+ for (u32 row = 0; row < rec.height; ++row) {
+ std::memcpy(out + static_cast<usize>(row) * rowBytes, mapped + static_cast<usize>(row) * rec.paddedBytesPerRow, rowBytes);
+ }
+ wgpuBufferUnmap(rec.buffer);
+ releaseReadback(static_cast<u32>(handle));
+ return true;
+ }
const usize tight = static_cast<usize>(rec.width) * rec.height * 4;
if (destSize < tight) return false;
const auto* mapped = static_cast<const u8*>(
@@ -2655,4 +2695,275 @@ i32 WebGPUDevice::getInt(GfxIntParam param) {
}
}
+
+// =============================================================================
+// Compute
+// =============================================================================
+
+namespace {
+/// Bytes a texel takes in the formats a compute shader can write, 0 for the rest.
+u32 storageTexelBytes(WGPUTextureFormat format) {
+ switch (format) {
+ case WGPUTextureFormat_RGBA8Unorm:
+ case WGPUTextureFormat_BGRA8Unorm:
+ case WGPUTextureFormat_RGBA8UnormSrgb: return 4;
+ case WGPUTextureFormat_RGBA16Float: return 8;
+ case WGPUTextureFormat_RGBA32Float: return 16;
+ default: return 0;
+ }
+}
+
+constexpr u32 kMaxComputeBindings = 16;
+constexpr u32 kMaxWorkgroupsPerDimension = 65535;
+} // namespace
+
+bool WebGPUDevice::backendCreateCompute(u32 id, const GfxComputeSource& source, std::string* outLog) {
+ if (source.language != GfxShaderLanguage::WGSL || !source.source) {
+ if (outLog) *outLog = "WebGPUDevice compiles WGSL only";
+ return false;
+ }
+ if (!device_) {
+ if (outLog) *outLog = "no WGPUDevice";
+ return false;
+ }
+ WGPUShaderSourceWGSL wgsl{};
+ wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
+ wgsl.code = sv(source.source);
+ WGPUShaderModuleDescriptor md{};
+ md.nextInChain = &wgsl.chain;
+ WGPUShaderModule module = wgpuDeviceCreateShaderModule(device_, &md);
+ if (!module) {
+ if (outLog) *outLog = "shader module creation failed";
+ return false;
+ }
+ ComputeRec rec;
+ rec.module = module;
+ rec.entry = source.entry && *source.entry ? source.entry : "main";
+ computes_[id] = std::move(rec);
+ return true;
+}
+
+void WebGPUDevice::backendDeleteCompute(u32 id) {
+ auto it = computes_.find(id);
+ if (it == computes_.end()) return;
+ for (auto& [key, pipeline] : it->second.pipelines) {
+ if (pipeline) wgpuComputePipelineRelease(pipeline);
+ }
+ if (it->second.module) wgpuShaderModuleRelease(it->second.module);
+ computes_.erase(it);
+}
+
+bool WebGPUDevice::backendDispatchCompute(u32 id, const GfxComputeBinding* bindings, u32 bindingCount,
+ u32 groupsX, u32 groupsY, u32 groupsZ) {
+ if (inPass()) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: must be called outside a render pass");
+ return false;
+ }
+ auto program = computes_.find(id);
+ if (program == computes_.end() || !program->second.module) return false;
+ if (groupsX > kMaxWorkgroupsPerDimension || groupsY > kMaxWorkgroupsPerDimension ||
+ groupsZ > kMaxWorkgroupsPerDimension || bindingCount > kMaxComputeBindings) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: {}x{}x{} groups with {} bindings is over the limit",
+ groupsX, groupsY, groupsZ, bindingCount);
+ return false;
+ }
+
+ WGPUBindGroupLayoutEntry layoutEntries[kMaxComputeBindings] = {};
+ WGPUBindGroupEntry groupEntries[kMaxComputeBindings] = {};
+ std::string key;
+ for (u32 i = 0; i < bindingCount; ++i) {
+ const GfxComputeBinding& b = bindings[i];
+ WGPUBindGroupLayoutEntry& le = layoutEntries[i];
+ WGPUBindGroupEntry& ge = groupEntries[i];
+ le.binding = ge.binding = b.binding;
+ le.visibility = WGPUShaderStage_Compute;
+ key += std::to_string(b.binding) + "." + std::to_string(static_cast<u32>(b.kind));
+ switch (b.kind) {
+ case GfxComputeBinding::Kind::Uniform:
+ case GfxComputeBinding::Kind::StorageRead:
+ case GfxComputeBinding::Kind::Storage: {
+ auto it = buffers_.find(static_cast<u32>(b.buffer));
+ if (it == buffers_.end() || !it->second.buffer) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} names a buffer that is gone", b.binding);
+ return false;
+ }
+ const bool uniform = b.kind == GfxComputeBinding::Kind::Uniform;
+ if ((uniform && it->second.usage != GfxBufferUsage::Uniform) ||
+ (!uniform && it->second.usage != GfxBufferUsage::Storage)) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} is bound as {} but the buffer was not made for it",
+ b.binding, uniform ? "a uniform" : "storage");
+ return false;
+ }
+ le.buffer.type = uniform ? WGPUBufferBindingType_Uniform
+ : b.kind == GfxComputeBinding::Kind::StorageRead ? WGPUBufferBindingType_ReadOnlyStorage
+ : WGPUBufferBindingType_Storage;
+ ge.buffer = it->second.buffer;
+ ge.offset = b.offset;
+ const u32 whole = webgpu::alignedWriteSize(it->second.size);
+ ge.size = b.size ? b.size : (whole > b.offset ? whole - b.offset : 0);
+ break;
+ }
+ case GfxComputeBinding::Kind::Texture: {
+ auto it = textures_.find(static_cast<u32>(b.texture));
+ if (it == textures_.end() || !it->second.texture) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} names a texture that is gone", b.binding);
+ return false;
+ }
+ const WGPUTextureFormat f = it->second.format;
+ le.texture.sampleType = isDepthFormat(f) ? WGPUTextureSampleType_Depth
+ : f == WGPUTextureFormat_RGBA32Float ? WGPUTextureSampleType_UnfilterableFloat
+ : WGPUTextureSampleType_Float;
+ le.texture.viewDimension = WGPUTextureViewDimension_2D;
+ ge.textureView = it->second.sampleView;
+ key += "." + std::to_string(static_cast<u32>(le.texture.sampleType));
+ break;
+ }
+ case GfxComputeBinding::Kind::StorageTexture: {
+ auto it = textures_.find(static_cast<u32>(b.texture));
+ if (it == textures_.end() || !it->second.texture) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} names a texture that is gone", b.binding);
+ return false;
+ }
+ if (!it->second.storage) {
+ ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} is a storage texture but the texture was not made with storage", b.binding);
+ return false;
+ }
+ le.storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
+ le.storageTexture.format = it->second.format;
+ le.storageTexture.viewDimension = WGPUTextureViewDimension_2D;
+ ge.textureView = it->second.view;
+ key += "." + std::to_string(static_cast<u32>(it->second.format));
+ break;
+ }
+ case GfxComputeBinding::Kind::Sampler:
+ le.sampler.type = WGPUSamplerBindingType_Filtering;
+ ge.sampler = samplerFor(packSamplerKey(b.filter, b.filter, TextureWrap::ClampToEdge, TextureWrap::ClampToEdge));
+ break;
+ }
+ key += "/";
+ }
+
+ WGPUBindGroupLayout layout = nullptr;
+ auto cachedLayout = compute_layouts_.find(key);
+ if (cachedLayout != compute_layouts_.end()) {
+ layout = cachedLayout->second;
+ } else {
+ WGPUBindGroupLayoutDescriptor bld{};
+ bld.entryCount = bindingCount;
+ bld.entries = layoutEntries;
+ layout = wgpuDeviceCreateBindGroupLayout(device_, &bld);
+ compute_layouts_[key] = layout;
+ }
+ if (!layout) return false;
+
+ WGPUPipelineLayout pipelineLayout = nullptr;
+ auto cachedPipelineLayout = compute_pipeline_layouts_.find(key);
+ if (cachedPipelineLayout != compute_pipeline_layouts_.end()) {
+ pipelineLayout = cachedPipelineLayout->second;
+ } else {
+ WGPUPipelineLayoutDescriptor pld{};
+ pld.bindGroupLayoutCount = 1;
+ pld.bindGroupLayouts = &layout;
+ pipelineLayout = wgpuDeviceCreatePipelineLayout(device_, &pld);
+ compute_pipeline_layouts_[key] = pipelineLayout;
+ }
+ if (!pipelineLayout) return false;
+
+ WGPUComputePipeline pipeline = nullptr;
+ auto cachedPipeline = program->second.pipelines.find(key);
+ if (cachedPipeline != program->second.pipelines.end()) {
+ pipeline = cachedPipeline->second;
+ } else {
+ WGPUComputePipelineDescriptor cpd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT;
+ cpd.layout = pipelineLayout;
+ cpd.compute.module = program->second.module;
+ cpd.compute.entryPoint = sv(program->second.entry.c_str());
+ pipeline = wgpuDeviceCreateComputePipeline(device_, &cpd);
+ program->second.pipelines[key] = pipeline;
+ }
+ if (!pipeline) return false;
+
+ WGPUBindGroupDescriptor bgd{};
+ bgd.layout = layout;
+ bgd.entryCount = bindingCount;
+ bgd.entries = groupEntries;
+ WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
+ if (!group) return false;
+
+ WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
+ WGPUComputePassDescriptor pd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT;
+ WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(encoder, &pd);
+ wgpuComputePassEncoderSetPipeline(pass, pipeline);
+ wgpuComputePassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
+ wgpuComputePassEncoderDispatchWorkgroups(pass, groupsX, groupsY, groupsZ);
+ wgpuComputePassEncoderEnd(pass);
+ wgpuComputePassEncoderRelease(pass);
+ WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
+ wgpuCommandEncoderRelease(encoder);
+ wgpuQueueSubmit(queue_, 1, &commands);
+ wgpuCommandBufferRelease(commands);
+ wgpuBindGroupRelease(group);
+ return true;
+}
+
+u32 WebGPUDevice::allocRawReadback(u32 w, u32 h, u32 bytesPerTexel, u32 tightBytes) {
+ // A texture copy wants 256-byte rows; a buffer copy is one row of any multiple of four.
+ const u32 padded = (h > 1 || bytesPerTexel != 1) ? ((w * bytesPerTexel + 255u) & ~255u) : tightBytes;
+ WGPUBufferDescriptor bd{};
+ bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
+ bd.size = static_cast<u64>(padded) * h;
+ WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
+ if (!buffer) return 0;
+ const u32 id = next_readback_id_++;
+ ReadbackRec rec{buffer, w, h, padded, GfxReadbackStatus::Pending};
+ rec.raw = true;
+ rec.bytesPerTexel = bytesPerTexel;
+ rec.tightBytes = tightBytes;
+ readbacks_[id] = rec;
+ return id;
+}
+
+ReadbackHandle WebGPUDevice::requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
+ if (!isDeviceUsable() || !device_ || sizeBytes == 0 || (offsetBytes & 3u) || (sizeBytes & 3u)) {
+ return ReadbackHandle::Invalid;
+ }
+ if (inPass()) {
+ ES_LOG_ERROR("WebGPUDevice::requestBufferReadback: must be called outside a render pass");
+ return ReadbackHandle::Invalid;
+ }
+ auto it = buffers_.find(static_cast<u32>(buffer));
+ if (it == buffers_.end() || !it->second.buffer || it->second.usage != GfxBufferUsage::Storage ||
+ static_cast<u64>(offsetBytes) + sizeBytes > webgpu::alignedWriteSize(it->second.size)) {
+ return ReadbackHandle::Invalid;
+ }
+ // One row of sizeBytes bytes: width counts bytes, a texel is one.
+ const u32 id = allocRawReadback(sizeBytes, 1, 1, sizeBytes);
+ if (!id) return ReadbackHandle::Invalid;
+ WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
+ wgpuCommandEncoderCopyBufferToBuffer(encoder, it->second.buffer, offsetBytes, readbacks_[id].buffer, 0, sizeBytes);
+ WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
+ wgpuCommandEncoderRelease(encoder);
+ wgpuQueueSubmit(queue_, 1, &commands);
+ wgpuCommandBufferRelease(commands);
+ mapReadback(id);
+ return static_cast<ReadbackHandle>(id);
+}
+
+ReadbackHandle WebGPUDevice::requestTextureReadback(TextureHandle texture) {
+ if (!isDeviceUsable() || !device_) return ReadbackHandle::Invalid;
+ if (inPass()) {
+ ES_LOG_ERROR("WebGPUDevice::requestTextureReadback: must be called outside a render pass");
+ return ReadbackHandle::Invalid;
+ }
+ auto it = textures_.find(static_cast<u32>(texture));
+ if (it == textures_.end() || !it->second.texture || it->second.samples > 1) return ReadbackHandle::Invalid;
+ const u32 bpt = storageTexelBytes(it->second.format);
+ if (bpt == 0) return ReadbackHandle::Invalid;
+ const u32 w = it->second.width, h = it->second.height;
+ const u32 id = allocRawReadback(w, h, bpt, w * h * bpt);
+ if (!id) return ReadbackHandle::Invalid;
+ submitReadbackCopy(id, it->second.texture);
+ return static_cast<ReadbackHandle>(id);
+}
+
} // namespace esengine
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index e62b25c0b..f144a9876 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -136,6 +136,11 @@ public:
surface_samples_ = samples > 1 ? kMsaaSamples : 1;
}
+ /// WebGPU is the backend with a compute stage; a device-less instance (bookkeeping only) has none to offer.
+ bool supportsCompute() const override { return device_ != nullptr; }
+ ReadbackHandle requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override;
+ ReadbackHandle requestTextureReadback(TextureHandle texture) override;
+
bool supportsShaderLanguage(GfxShaderLanguage language) const override {
return language == GfxShaderLanguage::WGSL;
}
@@ -191,6 +196,11 @@ protected:
void backendSetTextureParams(u32 id, const TextureDesc& desc) override;
void backendGenerateMipmaps(u32 id) override;
+ bool backendCreateCompute(u32 id, const GfxComputeSource& source, std::string* outLog) override;
+ void backendDeleteCompute(u32 id) override;
+ bool backendDispatchCompute(u32 id, const GfxComputeBinding* bindings, u32 bindingCount,
+ u32 groupsX, u32 groupsY, u32 groupsZ) override;
+
bool backendCreateProgram(u32 id, const GfxShaderSource& source,
const GfxAttribBinding* bindings, u32 bindingCount,
std::string* outLog, GfxShaderStage* outFailedStage) override;
@@ -358,6 +368,8 @@ private:
/// 1, or the whole chain for a texture that declared mipmaps. `view` is
/// then level 0 alone (an attachment is one level) and `sampleView` all.
u32 mipLevels = 1;
+ /// Created with StorageBinding: a compute shader may write it.
+ bool storage = false;
};
struct ProgramRec {
WGPUShaderModule vertex = nullptr;
@@ -387,12 +399,22 @@ private:
* static_cast<u32>(kSampleVariantCount)
* static_cast<u32>(kGBufferVariantCount)] = {};
};
+ struct ComputeRec {
+ WGPUShaderModule module = nullptr;
+ std::string entry;
+ /// One pipeline per bind-group layout the program has been dispatched with.
+ std::unordered_map<std::string, WGPUComputePipeline> pipelines;
+ };
struct ReadbackRec {
WGPUBuffer buffer = nullptr; ///< CopyDst|MapRead staging buffer.
u32 width = 0;
u32 height = 0;
u32 paddedBytesPerRow = 0; ///< Row stride in the buffer (256-aligned).
GfxReadbackStatus status = GfxReadbackStatus::Pending;
+ /// A compute readback: tight rows in the source's own bytes, top-down, never flipped to GL's order.
+ bool raw = false;
+ u32 bytesPerTexel = 4;
+ u32 tightBytes = 0; ///< What takeReadback hands back for a raw readback.
};
/** @brief Logs a not-yet-implemented path once per entry point. */
@@ -500,6 +522,8 @@ private:
void releaseDeviceObjects();
/** A staging buffer + record with no copy submitted yet; 0 on failure. */
u32 allocReadback(u32 w, u32 h);
+ /// The same for a compute readback: @p bytes of a buffer, or a w x h texture of @p bytesPerTexel.
+ u32 allocRawReadback(u32 w, u32 h, u32 bytesPerTexel, u32 tightBytes);
void submitReadbackCopy(u32 id, WGPUTexture source);
void encodeReadbackCopy(WGPUCommandEncoder encoder, u32 id, WGPUTexture source);
void mapReadback(u32 id);
@@ -658,6 +682,10 @@ private:
std::unordered_map<u32, BufferRec> buffers_;
std::unordered_map<u32, TextureRec> textures_;
std::unordered_map<u32, ProgramRec> programs_;
+ std::unordered_map<u32, ComputeRec> computes_;
+ /// Bind-group layouts of compute dispatches, by what they bind (see computeLayoutKey).
+ std::unordered_map<std::string, WGPUBindGroupLayout> compute_layouts_;
+ std::unordered_map<std::string, WGPUPipelineLayout> compute_pipeline_layouts_;
std::unordered_map<u32, PipelineRec> pipelines_;
std::vector<std::string> stub_logged_;
};
diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
index 2c429dcbc..04226d716 100644
--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
@@ -227,6 +227,8 @@ inline WGPUBufferUsage toWGPUBufferUsage(GfxBufferUsage usage) {
case GfxBufferUsage::Vertex: return WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst;
case GfxBufferUsage::Index: return WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst;
case GfxBufferUsage::Uniform: return WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst;
+ // Copy both ways: a compute buffer is filled from the CPU and read back to it.
+ case GfxBufferUsage::Storage: return WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc;
default: return WGPUBufferUsage_CopyDst;
}
}
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 277d94026..cbf1c5277 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -565,6 +565,24 @@ if(EMSCRIPTEN)
target_link_options(webgpu_bringup PRIVATE --use-port=emdawnwebgpu)
endif()
+# WebGPU compute bring-up: a browser-run wasm that drives the compute half of the RHI through the real WebGPUDevice
+# (storage buffers and textures, dispatch, readback) and prints what the GPU computed. Driven by
+# desktop/scripts/webgpu-compute-bringup.mjs, which asserts it.
+if(EMSCRIPTEN)
+ add_executable(webgpu_compute_bringup
+ renderer/webgpu_compute_bringup.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+ )
+ target_include_directories(webgpu_compute_bringup PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+ )
+ target_compile_options(webgpu_compute_bringup PRIVATE --use-port=emdawnwebgpu)
+ target_link_options(webgpu_compute_bringup PRIVATE --use-port=emdawnwebgpu)
+endif()
+
# Engine-level backend parity harness (REARCH_WGSL Phase 2): the FULL engine —
# EstellaContext with every subsystem — booted on an injected backend (WebGPU
# via emdawnwebgpu, or the stock WebGL2 path, chosen by URL) rendering one ECS
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 40928da87..3a22c42bc 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -41,6 +41,15 @@ struct MockGfxDevice final : GfxDevice {
int beginRenderPassCalls = 0;
int endRenderPassCalls = 0;
int createProgramCalls = 0;
+ // A stand-in for a backend with (or without) a compute stage.
+ bool computeSupported = false;
+ int createComputeCalls = 0;
+ int deleteComputeCalls = 0;
+ int dispatchComputeCalls = 0;
+ bool supportsCompute() const override { return computeSupported; }
+ bool backendCreateCompute(u32, const GfxComputeSource&, std::string*) override { ++createComputeCalls; return true; }
+ void backendDeleteCompute(u32) override { ++deleteComputeCalls; }
+ bool backendDispatchCompute(u32, const GfxComputeBinding*, u32, u32, u32, u32) override { ++dispatchComputeCalls; return true; }
int deleteProgramCalls = 0;
int setUniform1iCalls = 0;
int setUniform1fCalls = 0;
diff --git a/tests/renderer/test_device_loss.cpp b/tests/renderer/test_device_loss.cpp
index 20cc35e83..b537af021 100644
--- a/tests/renderer/test_device_loss.cpp
+++ b/tests/renderer/test_device_loss.cpp
@@ -378,6 +378,33 @@ int main() {
CHECK(dead.deviceStatus() == GfxDeviceStatus::Dead, "it stays Dead");
}
+ // --- compute programs: refused where there is no compute, rebuilt after a loss where there is ---
+ {
+ MockGfxDevice none;
+ std::string log;
+ const ComputeHandle refused = none.createCompute({GfxShaderLanguage::WGSL, "src", "main"}, &log);
+ CHECK(refused == ComputeHandle::Invalid && !log.empty(), "a device with no compute stage refuses a compute program and says why");
+ CHECK(!none.dispatchCompute(ComputeHandle{1}, nullptr, 0, 1), "and a dispatch on it runs nothing");
+
+ MockGfxDevice d;
+ d.computeSupported = true;
+ const ComputeHandle glsl = d.createCompute({GfxShaderLanguage::GLSL_ES300, "src", "main"}, &log);
+ CHECK(glsl == ComputeHandle::Invalid, "compute is WGSL only");
+ const ComputeHandle program = d.createCompute({GfxShaderLanguage::WGSL, "src", "main"}, &log);
+ CHECK(program != ComputeHandle::Invalid && d.createComputeCalls == 1, "a compute program is built on a device that computes");
+ CHECK(d.dispatchCompute(program, nullptr, 0, 4, 2, 1) && d.dispatchComputeCalls == 1, "and dispatched");
+ CHECK(!d.dispatchCompute(program, nullptr, 0, 0, 1, 1) && d.dispatchComputeCalls == 1, "a dispatch of no groups runs nothing");
+
+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");
+ CHECK(!d.dispatchCompute(program, nullptr, 0, 1), "nothing is dispatched on a lost device");
+ d.recoverDevice();
+ CHECK(d.createComputeCalls == 2, "the program is built once more on the new device");
+ CHECK(d.dispatchCompute(program, nullptr, 0, 1) && d.dispatchComputeCalls == 2, "and the same handle dispatches again");
+
+ d.deleteCompute(program);
+ CHECK(d.deleteComputeCalls == 1 && !d.dispatchCompute(program, nullptr, 0, 1), "a deleted program names nothing");
+ }
+
std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);
return g_failures ? 1 : 0;
}
diff --git a/tests/renderer/test_render_graph.cpp b/tests/renderer/test_render_graph.cpp
index ff1ce55b5..9037b1c40 100644
--- a/tests/renderer/test_render_graph.cpp
+++ b/tests/renderer/test_render_graph.cpp
@@ -435,6 +435,61 @@ int main() {
"so the newcomer is reachable and the ghost still is not");
}
+ // --- a compute pass opens no render pass, writes a storage target, and feeds the pass after it ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ std::vector<std::string> ran;
+ graph.begin(256, 128);
+ const auto screen = graph.importTarget(FramebufferHandle{9}, 256, 128);
+ const auto scene = graph.importTexture(TextureHandle{5}, 256, 128);
+ rg::TargetDesc storage;
+ storage.storage = true;
+ const auto computed = graph.createTarget(storage);
+
+ TextureHandle seenInput = TextureHandle::Invalid;
+ TextureHandle seenOutput = TextureHandle::Invalid;
+ rg::PassDesc compute;
+ compute.name = "compute";
+ compute.reads = {scene};
+ compute.write = computed;
+ compute.compute = true;
+ compute.execute = [&](const rg::PassContext& ctx) {
+ ran.push_back("compute");
+ seenInput = ctx.input(0);
+ seenOutput = ctx.output;
+ };
+ graph.addPass(std::move(compute));
+ graph.addPass(fullscreen("draw", {computed}, screen, &ran));
+ graph.execute();
+
+ CHECK((ran == std::vector<std::string>{"compute", "draw"}), "a compute pass runs in order with the draws around it");
+ CHECK(d.beginRenderPassCalls == 1, "and opens no render pass of its own");
+ CHECK(seenInput == TextureHandle{5}, "it is told the texture it reads");
+ CHECK(seenOutput != TextureHandle::Invalid, "and the storage texture it writes");
+ }
+
+ // --- a compute pass nothing reads is culled like any other ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ std::vector<std::string> ran;
+ graph.begin(64, 64);
+ const auto screen = graph.importTarget(FramebufferHandle{9}, 64, 64);
+ rg::TargetDesc storage;
+ storage.storage = true;
+ const auto unused = graph.createTarget(storage);
+ rg::PassDesc compute;
+ compute.name = "compute";
+ compute.write = unused;
+ compute.compute = true;
+ compute.execute = [&](const rg::PassContext&) { ran.push_back("compute"); };
+ graph.addPass(std::move(compute));
+ graph.addPass(fullscreen("draw", {}, screen, &ran));
+ graph.execute();
+ CHECK((ran == std::vector<std::string>{"draw"}), "a compute pass whose output nothing reaches is dropped");
+ }
+
std::printf(g_failures == 0 ? "\nALL PASS\n" : "\n%d FAILURE(S)\n", g_failures);
return g_failures == 0 ? 0 : 1;
}
diff --git a/tests/renderer/webgpu_compute_bringup.cpp b/tests/renderer/webgpu_compute_bringup.cpp
new file mode 100644
index 000000000..89dd18450
--- /dev/null
+++ b/tests/renderer/webgpu_compute_bringup.cpp
@@ -0,0 +1,369 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WebGPU compute bring-up — NOT a doctest harness.
+ *
+ * A browser-run program: the host page acquires a GPUDevice (navigator.gpu) and hands it over via
+ * Module.preinitializedWebGPUDevice; this program then drives the REAL WebGPUDevice through the compute half of the RHI —
+ * createCompute / dispatchCompute and the readbacks that bring a storage buffer or texture back — and checks the numbers
+ * the GPU computed:
+ * buffers a uniform, a read-only and a read-write storage buffer in one dispatch; a second dispatch with other
+ * parameters through the cached pipeline
+ * texture a compute-written RGBA8 and RGBA32F storage texture, read back whole
+ * sampling a sampled texture read with textureLoad, and with a linear sampler between texels
+ * refusals a dispatch inside a render pass runs nothing; a buffer not made for the binding is refused
+ * It prints `COMPUTE_CHECK <name> ok|FAIL …` per case and `COMPUTE_DONE failures=N`; the runner
+ * (desktop/scripts/webgpu-compute-bringup.mjs) asserts them and surfaces device validation errors.
+ */
+#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
+
+#include <emscripten.h>
+#include <emscripten/html5.h>
+
+#include <cmath>
+#include <cstdlib>
+#include <cstdio>
+#include <cstring>
+#include <functional>
+#include <string>
+#include <vector>
+
+using namespace esengine;
+
+namespace {
+
+WebGPUDevice* g_device = nullptr;
+int g_failures = 0;
+
+struct Pending {
+ std::string name;
+ ReadbackHandle handle;
+ u32 bytes;
+ std::function<std::string(const u8*)> verify; // empty = ok, else why not
+};
+std::vector<Pending> g_pending;
+
+void report(const std::string& name, const std::string& why) {
+ if (why.empty()) {
+ std::printf("COMPUTE_CHECK %s ok\n", name.c_str());
+ } else {
+ ++g_failures;
+ std::printf("COMPUTE_CHECK %s FAIL %s\n", name.c_str(), why.c_str());
+ }
+}
+
+void expect(const std::string& name, bool cond, const std::string& why) { report(name, cond ? "" : why); }
+
+void later(const std::string& name, ReadbackHandle handle, u32 bytes, std::function<std::string(const u8*)> verify) {
+ if (handle == ReadbackHandle::Invalid) {
+ report(name, "the readback was refused");
+ return;
+ }
+ g_pending.push_back({name, handle, bytes, std::move(verify)});
+}
+
+void pump() {
+ for (usize i = 0; i < g_pending.size();) {
+ Pending& p = g_pending[i];
+ const GfxReadbackStatus status = g_device->pollReadback(p.handle);
+ if (status == GfxReadbackStatus::Pending) { ++i; continue; }
+ if (status == GfxReadbackStatus::Failed) {
+ report(p.name, "the readback failed");
+ } else {
+ std::vector<u8> bytes(p.bytes);
+ if (!g_device->takeReadback(p.handle, bytes.data(), bytes.size())) {
+ report(p.name, "takeReadback refused");
+ } else {
+ report(p.name, p.verify(bytes.data()));
+ }
+ }
+ g_pending.erase(g_pending.begin() + static_cast<long>(i));
+ }
+ if (g_pending.empty()) {
+ std::printf("COMPUTE_DONE failures=%d\n", g_failures);
+ emscripten_cancel_main_loop();
+ }
+}
+
+const char* kBufferShader = R"(
+struct Params { add : u32, n : u32, pad0 : u32, pad1 : u32 };
+@group(0) @binding(0) var<uniform> params : Params;
+@group(0) @binding(1) var<storage, read> src : array<u32>;
+@group(0) @binding(2) var<storage, read_write> dst : array<u32>;
+@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id : vec3u) {
+ if (id.x >= params.n) { return; }
+ dst[id.x] = src[id.x] * 2u + params.add;
+}
+)";
+
+const char* kTextureShader = R"(
+@group(0) @binding(0) var out : texture_storage_2d<rgba8unorm, write>;
+@compute @workgroup_size(8, 8) fn main(@builtin(global_invocation_id) id : vec3u) {
+ textureStore(out, vec2i(id.xy), vec4f(f32(id.x) / 7.0, f32(id.y) / 7.0, 0.5, 1.0));
+}
+)";
+
+const char* kFloatShader = R"(
+@group(0) @binding(0) var out : texture_storage_2d<rgba32float, write>;
+@compute @workgroup_size(4, 4) fn main(@builtin(global_invocation_id) id : vec3u) {
+ textureStore(out, vec2i(id.xy), vec4f(f32(id.x), f32(id.y), f32(id.x * id.y), 1.0));
+}
+)";
+
+const char* kLoadShader = R"(
+@group(0) @binding(0) var src : texture_2d<f32>;
+@group(0) @binding(1) var<storage, read_write> dst : array<u32>;
+@compute @workgroup_size(4, 2) fn main(@builtin(global_invocation_id) id : vec3u) {
+ let c = textureLoad(src, vec2i(id.xy), 0);
+ dst[id.y * 4u + id.x] = pack4x8unorm(c);
+}
+)";
+
+const char* kSampleShader = R"(
+@group(0) @binding(0) var src : texture_2d<f32>;
+@group(0) @binding(1) var samp : sampler;
+@group(0) @binding(2) var<storage, read_write> dst : array<f32>;
+@compute @workgroup_size(1) fn main() {
+ // The centre of a 2x2 texture is half way between all four texels.
+ let c = textureSampleLevel(src, samp, vec2f(0.5, 0.5), 0.0);
+ dst[0] = c.r;
+ dst[1] = c.g;
+ dst[2] = c.b;
+ dst[3] = c.a;
+}
+)";
+
+ComputeHandle compile(const char* source, const char* name) {
+ std::string log;
+ ComputeHandle h = g_device->createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, source, "main"}, &log);
+ if (h == ComputeHandle::Invalid) {
+ ++g_failures;
+ std::printf("COMPUTE_CHECK %s FAIL could not create the program: %s\n", name, log.c_str());
+ }
+ return h;
+}
+
+std::string diff(const char* what, i64 got, i64 want) {
+ return std::string(what) + " is " + std::to_string(got) + ", expected " + std::to_string(want);
+}
+
+void runBuffers() {
+ constexpr u32 N = 1000;
+ ComputeHandle program = compile(kBufferShader, "buffers");
+ if (program == ComputeHandle::Invalid) return;
+
+ std::vector<u32> src(N);
+ for (u32 i = 0; i < N; ++i) src[i] = i * 3;
+ struct Params { u32 add, n, pad0, pad1; };
+ BufferHandle srcBuf = g_device->createBuffer({GfxBufferUsage::Storage, N * 4, false}, GfxContent::retained(), src.data());
+ BufferHandle dstBuf = g_device->createBuffer({GfxBufferUsage::Storage, N * 4, false}, GfxContent::transient(), nullptr);
+ Params params{7, N, 0, 0};
+ BufferHandle paramBuf = g_device->createBuffer({GfxBufferUsage::Uniform, sizeof(Params), false}, GfxContent::retained(), &params);
+
+ const GfxComputeBinding bindings[3] = {
+ GfxComputeBinding::uniform(0, paramBuf),
+ GfxComputeBinding::storageRead(1, srcBuf),
+ GfxComputeBinding::storage(2, dstBuf),
+ };
+ expect("buffers dispatch", g_device->dispatchCompute(program, bindings, 3, (N + 63) / 64), "dispatchCompute returned false");
+ later("buffers result", g_device->requestBufferReadback(dstBuf, 0, N * 4), N * 4, [](const u8* bytes) -> std::string {
+ const u32* out = reinterpret_cast<const u32*>(bytes);
+ for (u32 i = 0; i < N; ++i) {
+ if (out[i] != i * 3 * 2 + 7) return diff(("dst[" + std::to_string(i) + "]").c_str(), out[i], i * 3 * 2 + 7);
+ }
+ return "";
+ });
+
+ // The same program again, other parameters and a slice of the buffer: the layout and pipeline come from the cache.
+ params.add = 100;
+ g_device->updateBuffer(paramBuf, 0, &params, sizeof(params));
+ expect("buffers second dispatch", g_device->dispatchCompute(program, bindings, 3, (N + 63) / 64), "dispatchCompute returned false");
+ later("buffers second result", g_device->requestBufferReadback(dstBuf, 40, 16), 16, [](const u8* bytes) -> std::string {
+ const u32* out = reinterpret_cast<const u32*>(bytes);
+ for (u32 i = 0; i < 4; ++i) {
+ const u32 index = 10 + i;
+ if (out[i] != index * 3 * 2 + 100) return diff(("dst[" + std::to_string(index) + "]").c_str(), out[i], index * 3 * 2 + 100);
+ }
+ return "";
+ });
+
+ // Refusals: a zero group count, and a uniform bound where a storage buffer is declared.
+ expect("zero groups refused", !g_device->dispatchCompute(program, bindings, 3, 0), "a dispatch of no groups ran");
+ const GfxComputeBinding wrong[3] = {
+ GfxComputeBinding::uniform(0, paramBuf),
+ GfxComputeBinding::storageRead(1, paramBuf), // a uniform buffer where storage is bound
+ GfxComputeBinding::storage(2, dstBuf),
+ };
+ expect("wrong buffer refused", !g_device->dispatchCompute(program, wrong, 3, 1), "a buffer not made for storage was bound as storage");
+}
+
+void runTextures() {
+ ComputeHandle program = compile(kTextureShader, "texture");
+ if (program != ComputeHandle::Invalid) {
+ TextureDesc td{};
+ td.width = 8;
+ td.height = 8;
+ td.format = GfxPixelFormat::RGBA8;
+ td.storage = true;
+ td.minFilter = td.magFilter = TextureFilter::Nearest;
+ TextureHandle tex = g_device->createTexture(td, GfxContent::transient(), nullptr);
+ const GfxComputeBinding bindings[1] = {GfxComputeBinding::storageTexture(0, tex)};
+ expect("texture dispatch", g_device->dispatchCompute(program, bindings, 1, 1, 1), "dispatchCompute returned false");
+ later("texture result", g_device->requestTextureReadback(tex), 8 * 8 * 4, [](const u8* bytes) -> std::string {
+ for (u32 y = 0; y < 8; ++y) {
+ for (u32 x = 0; x < 8; ++x) {
+ const u8* p = bytes + (y * 8 + x) * 4;
+ const int wantR = static_cast<int>(std::lround(x / 7.0 * 255.0));
+ const int wantG = static_cast<int>(std::lround(y / 7.0 * 255.0));
+ if (std::abs(p[0] - wantR) > 1 || std::abs(p[1] - wantG) > 1 || std::abs(p[2] - 128) > 1 || p[3] != 255) {
+ return "texel (" + std::to_string(x) + "," + std::to_string(y) + ") is " + std::to_string(p[0]) + "," +
+ std::to_string(p[1]) + "," + std::to_string(p[2]) + "," + std::to_string(p[3]);
+ }
+ }
+ }
+ return "";
+ });
+
+ // A texture made without storage cannot be bound as one.
+ TextureDesc plain = td;
+ plain.storage = false;
+ TextureHandle plainTex = g_device->createTexture(plain, GfxContent::transient(), nullptr);
+ const GfxComputeBinding refused[1] = {GfxComputeBinding::storageTexture(0, plainTex)};
+ expect("plain texture refused", !g_device->dispatchCompute(program, refused, 1, 1, 1), "a texture without storage was bound as storage");
+ }
+
+ ComputeHandle floats = compile(kFloatShader, "float texture");
+ if (floats != ComputeHandle::Invalid) {
+ TextureDesc td{};
+ td.width = 4;
+ td.height = 4;
+ td.format = GfxPixelFormat::RGBA32F;
+ td.storage = true;
+ td.minFilter = td.magFilter = TextureFilter::Nearest;
+ TextureHandle tex = g_device->createTexture(td, GfxContent::transient(), nullptr);
+ const GfxComputeBinding bindings[1] = {GfxComputeBinding::storageTexture(0, tex)};
+ expect("float dispatch", g_device->dispatchCompute(floats, bindings, 1, 1, 1), "dispatchCompute returned false");
+ later("float result", g_device->requestTextureReadback(tex), 4 * 4 * 16, [](const u8* bytes) -> std::string {
+ const f32* f = reinterpret_cast<const f32*>(bytes);
+ for (u32 y = 0; y < 4; ++y) {
+ for (u32 x = 0; x < 4; ++x) {
+ const f32* p = f + (y * 4 + x) * 4;
+ if (p[0] != static_cast<f32>(x) || p[1] != static_cast<f32>(y) || p[2] != static_cast<f32>(x * y) || p[3] != 1.0f) {
+ return "texel (" + std::to_string(x) + "," + std::to_string(y) + ") is " + std::to_string(p[0]) + "," +
+ std::to_string(p[1]) + "," + std::to_string(p[2]) + "," + std::to_string(p[3]);
+ }
+ }
+ }
+ return "";
+ });
+ }
+}
+
+void runSampling() {
+ // 4x2 RGBA8 with a distinct value in every channel of every texel.
+ u8 pixels[4 * 2 * 4];
+ for (u32 i = 0; i < 8; ++i) {
+ pixels[i * 4 + 0] = static_cast<u8>(10 + i * 20);
+ pixels[i * 4 + 1] = static_cast<u8>(250 - i * 20);
+ pixels[i * 4 + 2] = static_cast<u8>(i * 30);
+ pixels[i * 4 + 3] = static_cast<u8>(255 - i * 5);
+ }
+ TextureDesc td{};
+ td.width = 4;
+ td.height = 2;
+ td.format = GfxPixelFormat::RGBA8;
+ td.minFilter = td.magFilter = TextureFilter::Nearest;
+ TextureHandle tex = g_device->createTexture(td, GfxContent::retained(), pixels);
+
+ ComputeHandle load = compile(kLoadShader, "textureLoad");
+ if (load != ComputeHandle::Invalid) {
+ BufferHandle dst = g_device->createBuffer({GfxBufferUsage::Storage, 8 * 4, false}, GfxContent::transient(), nullptr);
+ const GfxComputeBinding bindings[2] = {GfxComputeBinding::sampled(0, tex), GfxComputeBinding::storage(1, dst)};
+ expect("textureLoad dispatch", g_device->dispatchCompute(load, bindings, 2, 1, 1), "dispatchCompute returned false");
+ std::vector<u8> expected(pixels, pixels + sizeof(pixels));
+ later("textureLoad result", g_device->requestBufferReadback(dst, 0, 8 * 4), 8 * 4, [expected](const u8* bytes) -> std::string {
+ for (u32 i = 0; i < 32; ++i) {
+ if (bytes[i] != expected[i]) return diff(("byte " + std::to_string(i)).c_str(), bytes[i], expected[i]);
+ }
+ return "";
+ });
+ }
+
+ // Linear sampling at the centre of a 2x2: the mean of the four.
+ const u8 corners[2 * 2 * 4] = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255};
+ TextureDesc linear{};
+ linear.width = 2;
+ linear.height = 2;
+ linear.format = GfxPixelFormat::RGBA8;
+ linear.minFilter = linear.magFilter = TextureFilter::Linear;
+ TextureHandle small = g_device->createTexture(linear, GfxContent::retained(), corners);
+ ComputeHandle sample = compile(kSampleShader, "textureSampleLevel");
+ if (sample != ComputeHandle::Invalid) {
+ BufferHandle dst = g_device->createBuffer({GfxBufferUsage::Storage, 16, false}, GfxContent::transient(), nullptr);
+ const GfxComputeBinding bindings[3] = {
+ GfxComputeBinding::sampled(0, small), GfxComputeBinding::sampler(1, TextureFilter::Linear), GfxComputeBinding::storage(2, dst),
+ };
+ expect("sampler dispatch", g_device->dispatchCompute(sample, bindings, 3, 1, 1), "dispatchCompute returned false");
+ later("sampler result", g_device->requestBufferReadback(dst, 0, 16), 16, [](const u8* bytes) -> std::string {
+ const f32* f = reinterpret_cast<const f32*>(bytes);
+ const f32 want[4] = {0.5f, 0.5f, 0.5f, 1.0f};
+ for (int i = 0; i < 4; ++i) {
+ if (std::fabs(f[i] - want[i]) > 0.01f) return "channel " + std::to_string(i) + " is " + std::to_string(f[i]) + ", expected " + std::to_string(want[i]);
+ }
+ return "";
+ });
+ }
+}
+
+void runInsideRenderPass() {
+ ComputeHandle program = compile(kTextureShader, "inside a pass");
+ if (program == ComputeHandle::Invalid) return;
+ TextureDesc td{};
+ td.width = 8;
+ td.height = 8;
+ td.format = GfxPixelFormat::RGBA8;
+ td.storage = true;
+ TextureHandle storageTex = g_device->createTexture(td, GfxContent::transient(), nullptr);
+ TextureDesc target{};
+ target.width = 4;
+ target.height = 4;
+ target.format = GfxPixelFormat::RGBA8;
+ TextureHandle color = g_device->createTexture(target, GfxContent::transient(), nullptr);
+ FramebufferDesc fb{};
+ fb.color0 = color;
+ FramebufferHandle fbo = g_device->createFramebuffer(fb);
+ RenderPassDesc pass{};
+ pass.target = fbo;
+ pass.clearColor = true;
+ g_device->beginRenderPass(pass);
+ const GfxComputeBinding bindings[1] = {GfxComputeBinding::storageTexture(0, storageTex)};
+ const bool ran = g_device->dispatchCompute(program, bindings, 1, 1, 1);
+ g_device->endRenderPass();
+ expect("no dispatch inside a render pass", !ran, "a dispatch ran inside a render pass");
+ // And once the pass is over it runs again.
+ expect("dispatch after the pass", g_device->dispatchCompute(program, bindings, 1, 1, 1), "dispatchCompute returned false after the pass");
+}
+
+} // namespace
+
+int main() {
+ WGPUDevice raw = emscripten_webgpu_get_device();
+ if (!raw) {
+ std::printf("COMPUTE_FAIL no preinitialized device\n");
+ return 1;
+ }
+ static WebGPUDevice device(raw);
+ g_device = &device;
+ if (!device.supportsCompute()) {
+ std::printf("COMPUTE_FAIL the device reports no compute\n");
+ return 1;
+ }
+ std::printf("COMPUTE_INIT_OK\n");
+
+ runBuffers();
+ runTextures();
+ runSampling();
+ runInsideRenderPass();
+ emscripten_set_main_loop(pump, 0, /*simulate_infinite_loop=*/false);
+ return 0;
+}
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 47f12e518..15e613ecb 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2493,6 +2493,8 @@ export const NOTED = {
{"note":"Skinned meshes are followed by their bones, from the palette they were last drawn with."},
"feat(render): fog follows the scene's sun and can walk the air against its shadow map":
{"note":"Height Fog and Light Shafts follow the scene's own sun, and Height Fog can carry the sun's shadows as volumetric light."},
+ "feat(render): the WebGPU device runs compute shaders, and the render graph has compute passes":
+ {"internal":"Renderer plumbing with no creator-facing surface yet: no effect or component asks for compute until the first consumer lands."},
"feat(render): the sky scatters light like an atmosphere and carries volumetric clouds the sun lights":
{"note":"The Sky Atmosphere effect scatters the sun's light through an atmosphere and draws volumetric clouds that the sun lights and the wind moves."},
"feat(runtime): a TimeOfDay component moves the sun and the moon across the sky and draws the day, the dusk and the night":