11#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
29WGPUStringView sv(
const char*
text) {
30 WGPUStringView view{};
32 view.length =
text ? std::strlen(
text) : 0;
36std::string fromSv(
const WGPUStringView& view) {
37 if (!view.data)
return {};
38 return std::string(view.data,
39 view.length == WGPU_STRLEN ? std::strlen(view.data) : view.length);
42bool isDepthFormat(WGPUTextureFormat format) {
43 return format == WGPUTextureFormat_Depth24Plus ||
44 format == WGPUTextureFormat_Depth24PlusStencil8;
47u32 dsVariantOf(WGPUTextureFormat format) {
58 (
static_cast<u32>(wrapS) << 2) |
59 (
static_cast<u32>(wrapT) << 4));
64 : device_(device), adapter_(adapter) {
66 queue_ = wgpuDeviceGetQueue(device_);
69 owns_instance_ =
false;
71 instance_ = wgpuCreateInstance(
nullptr);
72 owns_instance_ =
true;
88#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
97 std::string vendor =
"WebGPU";
101 WGPUAdapterInfo info = {};
102 if (wgpuAdapterGetInfo(adapter_, &info) == WGPUStatus_Success) {
103 vendor = fromSv(info.vendor);
104 renderer = fromSv(info.device) +
" (" + fromSv(info.architecture) +
")";
105 version = fromSv(info.description);
106 wgpuAdapterInfoFreeMembers(info);
109 setDeviceIdentity(
"WebGPU", std::move(vendor), std::move(renderer), std::move(version));
113 switch (
static_cast<WGPUDeviceLostReason
>(wgpuReason)) {
125 if (instance_) wgpuInstanceProcessEvents(instance_);
134 const auto type =
static_cast<WGPUErrorType
>(wgpuErrorType);
135 if (type == WGPUErrorType_OutOfMemory) {
138 }
else if (type == WGPUErrorType_Internal) {
145 ES_LOG_WARN(
"WebGPU validation error: {}", message ? message :
"(no message)");
149bool WebGPUDevice::adoptDevice(WGPUDevice device) {
150 if (!device)
return false;
155 releaseDeviceObjects();
157 mailbox_ = std::make_shared<Mailbox>();
159 queue_ = wgpuDeviceGetQueue(device_);
162#if defined(__EMSCRIPTEN__)
163 if (surface_selector_.empty())
return true;
164 return configureSurface(surface_selector_.c_str(), surface_width_, surface_height_);
166 if (!surface_window_)
return true;
167 NativeSurface window{};
168 window.handle = surface_window_;
177 if (!pending_device_)
return false;
178 WGPUDevice next = pending_device_;
179 pending_device_ =
nullptr;
180 return adoptDevice(next);
184 releaseDeviceObjects();
185 if (owns_device_ && pending_device_) wgpuDeviceRelease(pending_device_);
186 pending_device_ =
nullptr;
187 if (instance_ && owns_instance_) { wgpuInstanceRelease(instance_); }
191void WebGPUDevice::releaseDeviceObjects() {
193 frames_done_ = frames_ended_;
194#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
196 metal_compute_.reset();
197 metal_compute_attempted_ =
false;
199 if (pass_) { wgpuRenderPassEncoderRelease(pass_); pass_ =
nullptr; }
200 pass_pipeline_ =
nullptr;
201 if (encoder_) { wgpuCommandEncoderRelease(encoder_); encoder_ =
nullptr; }
202 if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ =
nullptr; }
203 if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ =
nullptr; }
205 capture_copied_ =
false;
206 pass_is_surface_ =
false;
209 span_closing_ =
false;
210 span_slot_ = kGpuTimeRing;
214 for (
auto& bucket : bind_group_cache_)
for (
auto& e : bucket.second)
if (e.bg) wgpuBindGroupRelease(e.bg);
215 bind_group_cache_.clear();
216 bind_group_count_ = 0;
217 bind_group_ =
nullptr;
218 texture_group_ =
nullptr;
219 bind_group_dirty_ =
true;
222 for (
auto& [
id, rec] : buffers_) {
223 if (rec.buffer) wgpuBufferRelease(rec.buffer);
226 for (
auto& [
id, rec] : textures_) releaseTexture(rec);
228 for (
auto& [
id, rec] : programs_) {
229 if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
230 if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
233 for (
auto& [
id, rec] : computes_) {
234 for (
auto& [key, pipeline] : rec.pipelines) {
235 if (pipeline) wgpuComputePipelineRelease(pipeline);
237 if (rec.module) wgpuShaderModuleRelease(rec.module);
240 for (
auto& [key, layout] : compute_pipeline_layouts_) {
241 if (layout) wgpuPipelineLayoutRelease(layout);
243 compute_pipeline_layouts_.clear();
244 for (
auto& [key, layout] : compute_layouts_) {
245 if (layout) wgpuBindGroupLayoutRelease(layout);
247 compute_layouts_.clear();
248 for (
auto& [
id, rec] : pipelines_) {
249 for (WGPURenderPipeline variant : rec.variants) {
250 if (variant) wgpuRenderPipelineRelease(variant);
255 if (dummy_ubo_.buffer) wgpuBufferRelease(dummy_ubo_.buffer);
256 dummy_ubo_ = BufferRec{};
257 releaseTexture(dummy_texture_);
258 releaseTexture(dummy_depth_texture_);
259 releaseTexture(dummy_array_texture_);
260 releaseTexture(dummy_volume_texture_);
263 parallel_span_ =
false;
264 if (clock_pipeline_) { wgpuComputePipelineRelease(clock_pipeline_); clock_pipeline_ =
nullptr; }
265 if (timestamp_qset_) { wgpuQuerySetRelease(timestamp_qset_); timestamp_qset_ =
nullptr; }
266 if (timestamp_resolve_) { wgpuBufferRelease(timestamp_resolve_); timestamp_resolve_ =
nullptr; }
267 for (
auto& s : gpu_time_ring_) {
if (s.buf) wgpuBufferRelease(s.buf); s.buf =
nullptr; s.pending =
false; }
268 gpu_time_results_.clear();
269 for (
auto& ps : pass_time_pool_) {
if (ps.buf) wgpuBufferRelease(ps.buf); }
270 pass_time_pool_.clear();
271 pass_time_results_.clear();
272 pass_time_slot_ = kNoPassSlot;
274 timestamp_supported_ =
false;
275 timestamp_init_done_ =
false;
276 if (clear_bind_group_) { wgpuBindGroupRelease(clear_bind_group_); clear_bind_group_ =
nullptr; }
277 if (clear_color_buffer_) { wgpuBufferRelease(clear_color_buffer_); clear_color_buffer_ =
nullptr; }
278 for (
auto& [key, pipeline] : clear_pipelines_) {
279 if (pipeline) wgpuRenderPipelineRelease(pipeline);
281 clear_pipelines_.clear();
282 if (clear_layout_) { wgpuPipelineLayoutRelease(clear_layout_); clear_layout_ =
nullptr; }
283 if (clear_bgl_) { wgpuBindGroupLayoutRelease(clear_bgl_); clear_bgl_ =
nullptr; }
284 for (
auto& [key, pipeline] : flip_pipelines_) {
285 if (pipeline) wgpuRenderPipelineRelease(pipeline);
287 flip_pipelines_.clear();
288 if (surface_copy_view_) { wgpuTextureViewRelease(surface_copy_view_); surface_copy_view_ =
nullptr; }
289 if (surface_copy_) { wgpuTextureRelease(surface_copy_); surface_copy_ =
nullptr; }
290 surface_copy_width_ = surface_copy_height_ = 0;
291 if (flip_layout_) { wgpuPipelineLayoutRelease(flip_layout_); flip_layout_ =
nullptr; }
292 if (flip_bgl_) { wgpuBindGroupLayoutRelease(flip_bgl_); flip_bgl_ =
nullptr; }
295 for (
auto& [key, pipeline] : depth_resolve_pipelines_) {
296 if (pipeline) wgpuRenderPipelineRelease(pipeline);
298 depth_resolve_pipelines_.clear();
299 if (depth_resolve_layout_) { wgpuPipelineLayoutRelease(depth_resolve_layout_); depth_resolve_layout_ =
nullptr; }
300 if (depth_resolve_bgl_) { wgpuBindGroupLayoutRelease(depth_resolve_bgl_); depth_resolve_bgl_ =
nullptr; }
301 if (depth_resolve_vs_) { wgpuShaderModuleRelease(depth_resolve_vs_); depth_resolve_vs_ =
nullptr; }
302 if (depth_resolve_fs_) { wgpuShaderModuleRelease(depth_resolve_fs_); depth_resolve_fs_ =
nullptr; }
303 for (
auto& [key, pipeline] : mip_pipelines_) {
304 if (pipeline) wgpuRenderPipelineRelease(pipeline);
306 mip_pipelines_.clear();
307 if (mip_layout_) { wgpuPipelineLayoutRelease(mip_layout_); mip_layout_ =
nullptr; }
308 if (mip_bgl_) { wgpuBindGroupLayoutRelease(mip_bgl_); mip_bgl_ =
nullptr; }
309 if (mip_module_) { wgpuShaderModuleRelease(mip_module_); mip_module_ =
nullptr; }
310 if (mip_sampler_) { wgpuSamplerRelease(mip_sampler_); mip_sampler_ =
nullptr; }
311 for (
auto& [key, layout] : pipeline_layouts_) {
312 if (layout) wgpuPipelineLayoutRelease(layout);
314 pipeline_layouts_.clear();
315 for (
auto& [key, layout] : group_layouts_) {
316 if (layout) wgpuBindGroupLayoutRelease(layout);
318 group_layouts_.clear();
321 while (!readbacks_.empty()) releaseReadback(readbacks_.begin()->first);
322 for (
auto& [key, sampler] : samplers_) {
323 if (sampler) wgpuSamplerRelease(sampler);
326 if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ =
nullptr; }
327 if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ =
nullptr; }
328 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ =
nullptr; }
329 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ =
nullptr; }
330 surface_msaa_width_ = surface_msaa_height_ = 0;
331 surface_msaa_samples_ = 0;
332 releaseSurfaceProxy();
333 if (surface_) { wgpuSurfaceRelease(surface_); surface_ =
nullptr; }
336 surface_depth_width_ = 0;
337 surface_depth_height_ = 0;
338 if (queue_) { wgpuQueueRelease(queue_); queue_ =
nullptr; }
339 if (owns_device_ && device_) { wgpuDeviceRelease(device_); device_ =
nullptr; }
346#if defined(__EMSCRIPTEN__)
348 if (!device_ || !instance_) {
349 ES_LOG_ERROR(
"WebGPUDevice::configureSurface: no device/instance");
353 WGPUEmscriptenSurfaceSourceCanvasHTMLSelector canvas{};
354 canvas.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
355 canvas.selector = sv(selector);
357 WGPUSurfaceDescriptor sd{};
358 sd.nextInChain = &canvas.chain;
361 surface_selector_ = selector;
362 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
364 ES_LOG_ERROR(
"WebGPUDevice::configureSurface: surface creation failed for '{}'", selector);
368 return configureSwapchain(width, height);
372#if !defined(__EMSCRIPTEN__)
379 if (!device_ || !instance_) {
380 ES_LOG_ERROR(
"WebGPUDevice::configureSurface(native): no device/instance");
384 ES_LOG_ERROR(
"WebGPUDevice::configureSurface(native): null window handle");
393 if (surface_ && surface_window_ == window.
handle) {
395 return configureSwapchain(width, height);
402 wgpuSurfaceUnconfigure(surface_);
403 wgpuSurfaceRelease(surface_);
406 if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ =
nullptr; }
407 if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ =
nullptr; }
408 surface_depth_width_ = surface_depth_height_ = 0;
409 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ =
nullptr; }
410 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ =
nullptr; }
411 surface_msaa_width_ = surface_msaa_height_ = 0;
412 surface_msaa_samples_ = 0;
415 WGPUSurfaceDescriptor sd{};
416 switch (window.
kind) {
418 WGPUSurfaceSourceMetalLayer metal{};
419 metal.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
420 metal.layer = window.
handle;
421 sd.nextInChain = &metal.chain;
422 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
426 WGPUSurfaceSourceAndroidNativeWindow android{};
427 android.chain.sType = WGPUSType_SurfaceSourceAndroidNativeWindow;
428 android.window = window.
handle;
429 sd.nextInChain = &android.chain;
430 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
435 WGPUSurfaceSourceWindowsHWND win32{};
436 win32.chain.sType = WGPUSType_SurfaceSourceWindowsHWND;
438 win32.hwnd = window.
handle;
439 sd.nextInChain = &win32.chain;
440 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
445#if defined(__linux__)
446 WGPUSurfaceSourceWaylandSurface wayland{};
447 wayland.chain.sType = WGPUSType_SurfaceSourceWaylandSurface;
449 wayland.surface = window.
handle;
450 sd.nextInChain = &wayland.chain;
451 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
456#if defined(__linux__)
457 WGPUSurfaceSourceXlibWindow xlib{};
458 xlib.chain.sType = WGPUSType_SurfaceSourceXlibWindow;
463 xlib.window =
static_cast<uint64_t
>(
reinterpret_cast<uintptr_t
>(window.
handle));
464 sd.nextInChain = &xlib.chain;
465 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
471 ES_LOG_ERROR(
"WebGPUDevice::configureSurface(native): surface creation failed");
474 surface_window_ = window.
handle;
476 return configureSwapchain(width, height);
481 return f == WGPUTextureFormat_BGRA8UnormSrgb || f == WGPUTextureFormat_RGBA8UnormSrgb;
485 if (!surface_)
return;
486 presentSurfaceProxy();
487 wgpuSurfacePresent(surface_);
498 return surface_format_ == WGPUTextureFormat_BGRA8Unorm
499 || surface_format_ == WGPUTextureFormat_BGRA8UnormSrgb;
510WGPUPresentMode WebGPUDevice::pickUncappedPresentMode()
const {
511#if !defined(__EMSCRIPTEN__)
512 if (surface_ && adapter_) {
513 WGPUSurfaceCapabilities caps{};
514 if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success) {
515 WGPUPresentMode chosen = WGPUPresentMode_Fifo;
516 for (
size_t i = 0; i < caps.presentModeCount; ++i) {
517 if (caps.presentModes[i] == WGPUPresentMode_Immediate) {
518 chosen = WGPUPresentMode_Immediate;
521 if (caps.presentModes[i] == WGPUPresentMode_Mailbox) chosen = WGPUPresentMode_Mailbox;
523 wgpuSurfaceCapabilitiesFreeMembers(caps);
528 return WGPUPresentMode_Fifo;
531bool WebGPUDevice::configureSwapchain(
u32 width,
u32 height) {
535 surface_format_ = prefer_surface_bgra_ ? WGPUTextureFormat_BGRA8Unorm
536 : WGPUTextureFormat_RGBA8Unorm;
537#if !defined(__EMSCRIPTEN__)
547 WGPUSurfaceCapabilities caps{};
548 if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success
549 && caps.formatCount > 0) {
550 surface_format_ = caps.formats[0];
551 for (
size_t i = 0; i < caps.formatCount; ++i) {
553 surface_format_ = caps.formats[i];
557 wgpuSurfaceCapabilitiesFreeMembers(caps);
561 WGPUSurfaceConfiguration cfg{};
562 cfg.device = device_;
563 cfg.format = surface_format_;
564 cfg.usage = WGPUTextureUsage_RenderAttachment;
566 if (surface_readback_) cfg.usage |= WGPUTextureUsage_CopySrc;
573 cfg.alphaMode = WGPUCompositeAlphaMode_Auto;
577 cfg.presentMode = present_uncapped_ ? pickUncappedPresentMode() : WGPUPresentMode_Fifo;
581 if (present_uncapped_) {
582 ES_LOG_WARN(
"WebGPUDevice: uncapped present asked for, surface gave {}",
583 cfg.presentMode == WGPUPresentMode_Immediate ?
"Immediate"
584 : cfg.presentMode == WGPUPresentMode_Mailbox ?
"Mailbox — the compositor still shows one frame per vsync"
585 :
"Fifo — the frame IS the refresh interval");
587 wgpuSurfaceConfigure(surface_, &cfg);
588 surface_width_ = width;
589 surface_height_ = height;
591 return ensureSurfaceDepth(width, height);
601bool WebGPUDevice::ensureSurfaceDepth(
u32 width,
u32 height) {
602 if (surface_depth_view_ && width == surface_depth_width_ && height == surface_depth_height_
603 && surface_depth_samples_ == surface_samples_) {
606 if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ =
nullptr; }
607 if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ =
nullptr; }
608 WGPUTextureDescriptor dd{};
609 dd.dimension = WGPUTextureDimension_2D;
610 dd.format = WGPUTextureFormat_Depth24PlusStencil8;
611 dd.size = WGPUExtent3D{width, height, 1};
612 dd.mipLevelCount = 1;
615 dd.sampleCount = surface_samples_;
616 dd.usage = WGPUTextureUsage_RenderAttachment;
617 surface_depth_texture_ = wgpuDeviceCreateTexture(device_, &dd);
618 if (surface_depth_texture_) {
619 surface_depth_view_ = wgpuTextureCreateView(surface_depth_texture_,
nullptr);
620 surface_depth_width_ = width;
621 surface_depth_height_ = height;
622 surface_depth_samples_ = surface_samples_;
624 return surface_depth_view_ !=
nullptr;
633bool WebGPUDevice::ensureSurfaceMsaa(
u32 width,
u32 height) {
634 if (surface_samples_ <= 1) {
635 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ =
nullptr; }
636 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ =
nullptr; }
637 surface_msaa_samples_ = 0;
640 if (surface_msaa_view_ && width == surface_msaa_width_ && height == surface_msaa_height_
641 && surface_samples_ == surface_msaa_samples_) {
644 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ =
nullptr; }
645 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ =
nullptr; }
646 WGPUTextureDescriptor cd{};
647 cd.dimension = WGPUTextureDimension_2D;
648 cd.format = surface_format_;
649 cd.size = WGPUExtent3D{width, height, 1};
650 cd.mipLevelCount = 1;
651 cd.sampleCount = surface_samples_;
652 cd.usage = WGPUTextureUsage_RenderAttachment;
653 surface_msaa_texture_ = wgpuDeviceCreateTexture(device_, &cd);
654 if (surface_msaa_texture_) {
655 surface_msaa_view_ = wgpuTextureCreateView(surface_msaa_texture_,
nullptr);
656 surface_msaa_width_ = width;
657 surface_msaa_height_ = height;
658 surface_msaa_samples_ = surface_samples_;
660 return surface_msaa_view_ !=
nullptr;
663void WebGPUDevice::releaseSurfaceProxy() {
664 if (surface_proxy_view_) { wgpuTextureViewRelease(surface_proxy_view_); surface_proxy_view_ =
nullptr; }
665 if (surface_proxy_) { wgpuTextureRelease(surface_proxy_); surface_proxy_ =
nullptr; }
666 surface_proxy_width_ = surface_proxy_height_ = 0;
667 surface_proxy_format_ = WGPUTextureFormat_Undefined;
668 surface_proxy_drawn_ =
false;
671bool WebGPUDevice::ensureSurfaceProxy(
u32 width,
u32 height) {
672 if (surface_proxy_view_ && width == surface_proxy_width_ && height == surface_proxy_height_
673 && surface_format_ == surface_proxy_format_) {
676 releaseSurfaceProxy();
677 WGPUTextureDescriptor td{};
678 td.dimension = WGPUTextureDimension_2D;
679 td.format = surface_format_;
680 td.size = WGPUExtent3D{width, height, 1};
681 td.mipLevelCount = 1;
683 td.usage = WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopySrc;
684 surface_proxy_ = wgpuDeviceCreateTexture(device_, &td);
685 if (!surface_proxy_)
return false;
686 surface_proxy_view_ = wgpuTextureCreateView(surface_proxy_,
nullptr);
687 surface_proxy_width_ = width;
688 surface_proxy_height_ = height;
689 surface_proxy_format_ = surface_format_;
690 return surface_proxy_view_ !=
nullptr;
693bool WebGPUDevice::acquireFrameView() {
694 if (frame_view_)
return true;
695 if (surface_reconfigure_) {
696 surface_reconfigure_ =
false;
697 configureSwapchain(surface_width_, surface_height_);
699 WGPUSurfaceTexture st{};
700 wgpuSurfaceGetCurrentTexture(surface_, &st);
701 if (st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal &&
702 st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) {
703 ES_LOG_ERROR(
"WebGPUDevice: surface texture unavailable ({})",
704 static_cast<u32>(st.status));
705 if (st.texture) wgpuTextureRelease(st.texture);
708 frame_texture_ = st.texture;
709 frame_view_ = wgpuTextureCreateView(frame_texture_,
nullptr);
715 const u32 texW = wgpuTextureGetWidth(frame_texture_);
716 const u32 texH = wgpuTextureGetHeight(frame_texture_);
717 if (texW > 0 && texH > 0) {
718 surface_width_ = texW;
719 surface_height_ = texH;
720 ensureSurfaceDepth(texW, texH);
722 return frame_view_ !=
nullptr;
725void WebGPUDevice::presentSurfaceProxy() {
726 if (!surface_proxy_drawn_)
return;
727 surface_proxy_drawn_ =
false;
728 if (!device_ || !surface_proxy_view_ || !
isDeviceUsable() || !acquireFrameView())
return;
730 WGPURenderPipeline pipeline = ensureFlipPipeline(surface_format_,
true);
731 if (!pipeline)
return;
732 WGPUBindGroupEntry entry{};
734 entry.textureView = surface_proxy_view_;
735 WGPUBindGroupDescriptor bgd{};
736 bgd.layout = flip_bgl_;
738 bgd.entries = &entry;
739 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
740 WGPURenderPassColorAttachment color{};
741 color.view = frame_view_;
742 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
743 color.loadOp = WGPULoadOp_Clear;
744 color.storeOp = WGPUStoreOp_Store;
745 WGPURenderPassDescriptor rp{};
746 rp.colorAttachmentCount = 1;
747 rp.colorAttachments = &color;
748 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
749 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
750 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
751 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0,
nullptr);
752 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
753 wgpuRenderPassEncoderEnd(pass);
754 wgpuRenderPassEncoderRelease(pass);
755 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder,
nullptr);
756 wgpuQueueSubmit(queue_, 1, &commands);
757 wgpuCommandBufferRelease(commands);
758 wgpuCommandEncoderRelease(encoder);
759 wgpuBindGroupRelease(group);
763 if (!surface_ || !device_ || width == 0 || height == 0)
return;
764 if (width == surface_width_ && height == surface_height_)
return;
766 ES_LOG_WARN(
"WebGPUDevice::resizeBackbuffer: ignored inside a render pass");
769 configureSwapchain(width, height);
772void WebGPUDevice::stubOnce(
const char* what) {
773 for (
const auto& logged : stub_logged_) {
774 if (logged == what)
return;
776 stub_logged_.emplace_back(what);
777 ES_LOG_WARN(
"WebGPUDevice: {} not implemented yet (REARCH_WGSL Phase 2 slice 2)", what);
790 wgpuRenderPassEncoderSetViewport(pass_,
static_cast<f32>(x),
static_cast<f32>(y),
791 static_cast<f32>(w),
static_cast<f32>(h), 0.0f, 1.0f);
800 ES_LOG_WARN(
"WebGPUDevice::clearStencil: no active pass");
804 ES_LOG_WARN(
"WebGPUDevice::clearStencil: pass target has no stencil planes");
807 drawInternalClear(
false,
false,
true,
nullptr, value,
nullptr);
812 if (pass_ && !enabled) {
813 wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
818 if (!pass_ || w <= 0 || h <= 0)
return;
821 const i32 x0 = std::clamp(x, 0,
static_cast<i32>(pass_width_));
822 const i32 y0 = std::clamp(y, 0,
static_cast<i32>(pass_height_));
823 const i32 x1 = std::clamp(x + w, 0,
static_cast<i32>(pass_width_));
824 const i32 y1 = std::clamp(y + h, 0,
static_cast<i32>(pass_height_));
825 wgpuRenderPassEncoderSetScissorRect(pass_,
static_cast<u32>(x0),
static_cast<u32>(y0),
826 static_cast<u32>(std::max(0, x1 - x0)),
827 static_cast<u32>(std::max(0, y1 - y0)));
837 const auto bufferBytes = [](WGPUBuffer buffer) ->
u64 {
return buffer ? wgpuBufferGetSize(buffer) : 0; };
838 for (
const auto& [
id, buffer] : buffers_) bytes += bufferBytes(buffer.buffer);
839 bytes += bufferBytes(dummy_ubo_.buffer) + bufferBytes(clear_color_buffer_) + bufferBytes(timestamp_resolve_);
840 for (
const auto& slot : gpu_time_ring_) bytes += bufferBytes(slot.buf);
841 for (
const auto& [
id, readback] : readbacks_) bytes += bufferBytes(readback.buffer);
842 const auto textureBytes = [](WGPUTexture texture) ->
u64 {
843 if (!texture)
return 0;
844 u32 width = wgpuTextureGetWidth(texture), height = wgpuTextureGetHeight(texture);
845 const auto format = wgpuTextureGetFormat(texture);
846 const u32 pixelBytes = format == WGPUTextureFormat_RGBA32Float ? 16 : format == WGPUTextureFormat_RGBA16Float ? 8 : 4;
855 for (
u32 level = 0; level < wgpuTextureGetMipLevelCount(texture); ++level) {
858 * wgpuTextureGetSampleCount(texture);
859 width = std::max(1u, width / 2); height = std::max(1u, height / 2);
861 return size * wgpuTextureGetDepthOrArrayLayers(texture);
863 for (
const auto& [
id, texture] : textures_) bytes += textureBytes(texture.texture);
864 bytes += textureBytes(dummy_texture_.texture) + textureBytes(dummy_depth_texture_.texture)
865 + textureBytes(dummy_array_texture_.texture) + textureBytes(dummy_volume_texture_.texture);
866 bytes += textureBytes(surface_depth_texture_) + textureBytes(surface_msaa_texture_);
870WGPUBuffer WebGPUDevice::makeBuffer(
GfxBufferUsage usage,
u32 size,
const void* data) {
872 ES_LOG_ERROR(
"WebGPUDevice: no device to create a buffer on");
875 WGPUBufferDescriptor bd{};
879 WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
881 ES_LOG_ERROR(
"WebGPUDevice: buffer creation failed ({} bytes)", size);
884 if (data && size > 0) writeBufferPadded(buffer, 0, data, size);
889 WGPUBuffer buffer = makeBuffer(desc.
usage, desc.
size, data);
890 if (!buffer)
return false;
891 buffers_[id] = BufferRec{buffer, desc.
size, desc.
usage};
895void WebGPUDevice::writeBufferPadded(WGPUBuffer buffer,
u32 offset,
const void* data,
u32 size) {
897 wgpuQueueWriteBuffer(queue_, buffer, offset, data, size);
901 std::memcpy(padded.data(), data, size);
902 wgpuQueueWriteBuffer(queue_, buffer, offset, padded.data(), padded.size());
906#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
907 if (metal_compute_) metal_compute_->forgetBuffer(
id);
909 auto it = buffers_.find(
id);
910 if (it == buffers_.end())
return;
911 if (it->second.buffer) {
912 evictBindGroups(
static_cast<u64>(
reinterpret_cast<uintptr_t
>(it->second.buffer)));
913 wgpuBufferRelease(it->second.buffer);
918void WebGPUDevice::evictBindGroups(
u64 id) {
919 for (
auto it = bind_group_cache_.begin(); it != bind_group_cache_.end();) {
920 auto& bucket = it->second;
921 for (
usize i = bucket.size(); i-- > 0;) {
924 for (
u64 v : e.ids) {
925 if (v ==
id) { hit =
true;
break; }
928 if (e.bg == bind_group_) bind_group_ =
nullptr;
929 if (e.bg == texture_group_) texture_group_ =
nullptr;
930 if (e.bg) wgpuBindGroupRelease(e.bg);
931 bucket.erase(bucket.begin() +
static_cast<std::ptrdiff_t
>(i));
933 bind_group_dirty_ =
true;
935 it = bucket.empty() ? bind_group_cache_.erase(it) : std::next(it);
940 auto it = buffers_.find(
id);
941 if (it == buffers_.end() || !it->second.buffer || !data || sizeBytes == 0)
return;
943 ES_LOG_ERROR(
"WebGPUDevice::updateBuffer: range {}+{} exceeds buffer size {}",
944 offsetBytes, sizeBytes, it->second.size);
948 if ((offsetBytes & 3u) != 0) {
949 ES_LOG_ERROR(
"WebGPUDevice::updateBuffer: offset {} is not 4-byte aligned", offsetBytes);
955 ES_LOG_ERROR(
"WebGPUDevice::updateBuffer: unaligned partial write {}+{} of {}",
956 offsetBytes, sizeBytes, it->second.size);
959 writeBufferPadded(it->second.buffer, offsetBytes, data, sizeBytes);
963#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
964 if (metal_compute_) metal_compute_->forgetBuffer(
id);
966 auto it = buffers_.find(
id);
967 if (it == buffers_.end())
return;
972 if (it->second.buffer) {
973 evictBindGroups(
static_cast<u64>(
reinterpret_cast<uintptr_t
>(it->second.buffer)));
974 wgpuBufferRelease(it->second.buffer);
976 bind_group_dirty_ =
true;
977 it->second.buffer = makeBuffer(desc.
usage, desc.
size, data);
978 it->second.size = desc.
size;
982 if (slot >= kUniformSlots)
return;
983 const u32 id =
static_cast<u32>(buffer);
984 if (uniform_slots_[slot] !=
id || uniform_offsets_[slot] != offsetBytes ||
985 uniform_sizes_[slot] != sizeBytes) {
986 uniform_slots_[slot] = id;
987 uniform_offsets_[slot] = offsetBytes;
988 uniform_sizes_[slot] = sizeBytes;
989 bind_group_dirty_ =
true;
1003 ES_LOG_ERROR(
"WebGPUDevice::createVertexLayout: attribute {} ({} x type {}) has no WGPU format",
1004 i, a.components,
static_cast<u32>(a.type));
1012 auto it = buffers_.find(
static_cast<u32>(buffer));
1013 if (!pass_ || it == buffers_.end())
return;
1014 wgpuRenderPassEncoderSetVertexBuffer(pass_, slot, it->second.buffer, offsetBytes,
1015 it->second.size - offsetBytes);
1021 bound_index_buffer_ =
static_cast<u32>(buffer);
1030 case WGPUTextureFormat_RGBA8UnormSrgb:
return kColorSrgb8;
1033 case WGPUTextureFormat_BGRA8Unorm:
return kColorBgra8;
1038bool WebGPUDevice::makeTexture(
const TextureDesc& desc,
const void* pixels, TextureRec& out) {
1040 ES_LOG_ERROR(
"WebGPUDevice: no device to create a texture on");
1045 WGPUTextureDescriptor td{};
1046 td.dimension = desc.
volume ? WGPUTextureDimension_3D : WGPUTextureDimension_2D;
1048 td.size = WGPUExtent3D{desc.
width, desc.
height, layers};
1050 td.mipLevelCount = 1;
1051 if (desc.
mipmaps && !desc.
volume && td.sampleCount == 1 && !isDepthFormat(td.format)) {
1052 for (
u32 side = std::max(desc.
width, desc.
height); side > 1; side >>= 1) ++td.mipLevelCount;
1057 td.usage = isDepthFormat(td.format)
1058 ? (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_RenderAttachment)
1060 ? (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst)
1061 : (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst |
1062 WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment);
1065 const bool storage = desc.
storage && !desc.
volume && td.sampleCount == 1 &&
1066 (td.format == WGPUTextureFormat_RGBA8Unorm || td.format == WGPUTextureFormat_RGBA16Float ||
1067 td.format == WGPUTextureFormat_RGBA32Float);
1068 if (storage) td.usage |= WGPUTextureUsage_StorageBinding;
1072 if (td.sampleCount > 1) {
1073 td.usage = isDepthFormat(td.format)
1074 ? (WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_TextureBinding)
1075 : WGPUTextureUsage_RenderAttachment;
1078 WGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);
1084 WGPUTextureView view =
nullptr;
1087 WGPUTextureViewDescriptor vd{};
1088 vd.format = td.format;
1089 vd.dimension = WGPUTextureViewDimension_3D;
1090 vd.mipLevelCount = 1;
1091 vd.arrayLayerCount = 1;
1092 vd.aspect = WGPUTextureAspect_All;
1093 view = wgpuTextureCreateView(texture, &vd);
1094 }
else if (layers > 1) {
1096 WGPUTextureViewDescriptor vd{};
1097 vd.format = td.format;
1098 vd.dimension = WGPUTextureViewDimension_2DArray;
1099 vd.mipLevelCount = td.mipLevelCount;
1100 vd.arrayLayerCount = layers;
1101 vd.aspect = WGPUTextureAspect_All;
1102 view = wgpuTextureCreateView(texture, &vd);
1103 }
else if (td.mipLevelCount > 1) {
1104 WGPUTextureViewDescriptor vd{};
1105 vd.format = td.format;
1106 vd.dimension = WGPUTextureViewDimension_2D;
1107 vd.mipLevelCount = 1;
1108 vd.arrayLayerCount = 1;
1109 vd.aspect = WGPUTextureAspect_All;
1110 view = wgpuTextureCreateView(texture, &vd);
1112 view = wgpuTextureCreateView(texture,
nullptr);
1117 WGPUTextureView sampleView = view;
1118 if (isDepthFormat(td.format)) {
1119 WGPUTextureViewDescriptor vd{};
1123 vd.format = td.format == WGPUTextureFormat_Depth24PlusStencil8
1124 ? WGPUTextureFormat_Depth24Plus
1126 vd.dimension = WGPUTextureViewDimension_2D;
1127 vd.mipLevelCount = 1;
1128 vd.arrayLayerCount = 1;
1129 vd.aspect = WGPUTextureAspect_DepthOnly;
1130 sampleView = wgpuTextureCreateView(texture, &vd);
1131 }
else if (td.mipLevelCount > 1 && layers == 1) {
1132 sampleView = wgpuTextureCreateView(texture, nullptr);
1135 out = TextureRec{texture, view, sampleView,
1136 desc.width, desc.height, td.format, desc.format,
1137 packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT),
1138 td.sampleCount, td.mipLevelCount};
1139 out.storage = storage;
1140 out.layers = layers;
1141 out.volume = desc.
volume;
1143 if (pixels && !isDepthFormat(td.format) && (layers > 1 || desc.
volume)) {
1146 const usize layerBytes = static_cast<usize>(desc.width) * desc.height * gfxBytesPerPixel(desc.format);
1147 for (u32 layer = 0; layer < layers; ++layer) {
1148 writeTexture(out, 0, 0, desc.width, desc.height,
1149 static_cast<const u8*>(pixels) + layerBytes * layer, false, layer);
1151 if (out.mipLevels > 1) buildMipChain(out);
1152 }
else if (pixels && !isDepthFormat(td.format)) {
1155 writeTexture(out, 0, 0, desc.width, desc.height, pixels, desc.flipY);
1156 if (out.mipLevels > 1) buildMipChain(out);
1163 if (!makeTexture(desc, pixels, rec))
return false;
1164 textures_[id] = rec;
1169 const void* data,
u32 byteLength,
u32 mipLevels) {
1170 if (!device_ || !queue_) {
1171 ES_LOG_ERROR(
"WebGPUDevice::createCompressedTexture: no device");
1175 if (wgpuFmt == WGPUTextureFormat_Undefined) {
1176 ES_LOG_ERROR(
"WebGPUDevice::createCompressedTexture: unmapped format");
1179 const u32 levels = mipLevels ? mipLevels : 1;
1181 WGPUTextureDescriptor td{};
1182 td.dimension = WGPUTextureDimension_2D;
1183 td.format = wgpuFmt;
1184 td.size = WGPUExtent3D{desc.
width, desc.
height, 1};
1185 td.mipLevelCount = levels;
1187 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst;
1189 WGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);
1198 const u8* ptr =
static_cast<const u8*
>(data);
1199 const u8* end = ptr + byteLength;
1200 for (
u32 level = 0; ptr && level < levels; ++level) {
1201 const u32 lw = (desc.
width >> level) ? (desc.
width >> level) : 1u;
1206 if (levelBytes >
static_cast<usize>(end - ptr))
break;
1207 WGPUTexelCopyTextureInfo dst{};
1208 dst.texture = texture;
1209 dst.mipLevel = level;
1210 dst.origin = WGPUOrigin3D{0, 0, 0};
1211 WGPUTexelCopyBufferLayout layout{};
1213 layout.rowsPerImage = blocksY;
1217 wgpuQueueWriteTexture(queue_, &dst, ptr, levelBytes, &layout, &extent);
1223 WGPUTextureView view = wgpuTextureCreateView(texture,
nullptr);
1224 textures_[id] = TextureRec{texture, view, view,
1231void WebGPUDevice::releaseTexture(TextureRec& rec) {
1232#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
1233 if (metal_compute_ && rec.texture) metal_compute_->forgetTexture(rec.texture);
1237 if (rec.sampleView && rec.sampleView != rec.view) {
1238 evictBindGroups(
static_cast<u64>(
reinterpret_cast<uintptr_t
>(rec.sampleView)));
1239 wgpuTextureViewRelease(rec.sampleView);
1242 evictBindGroups(
static_cast<u64
>(
reinterpret_cast<uintptr_t
>(rec.view)));
1243 wgpuTextureViewRelease(rec.view);
1245 if (rec.texture) wgpuTextureRelease(rec.texture);
1250 auto it = textures_.find(
id);
1251 if (it == textures_.end())
return;
1252 releaseTexture(it->second);
1253 textures_.erase(it);
1257 auto it = textures_.find(from);
1258 if (it == textures_.end())
return;
1259 textures_[into] = it->second;
1260 textures_.erase(from);
1261 for (
u32 slot = 0; slot < kTextureSlots; ++slot) {
1262 if (texture_slots_[slot] == into || texture_slots_[slot] == from) bind_group_dirty_ =
true;
1267 const void* pixels,
bool flipY) {
1268 auto it = textures_.find(
id);
1269 if (it == textures_.end())
return;
1270 writeTexture(it->second, x, y, width, height, pixels, flipY);
1273void WebGPUDevice::writeTexture(
const TextureRec& rec,
i32 x,
i32 y,
u32 width,
u32 height,
1274 const void* pixels,
bool flipY,
u32 layer) {
1275 if (!pixels || !queue_ || !rec.texture)
return;
1276 if (isDepthFormat(rec.format)) {
1277 ES_LOG_ERROR(
"WebGPUDevice::updateTexture: depth-stencil textures are attachment-only");
1280 WGPUTexelCopyTextureInfo dst{};
1281 dst.texture = rec.texture;
1282 dst.origin = WGPUOrigin3D{
static_cast<u32>(x),
static_cast<u32>(y), layer};
1289 const usize dstRow =
static_cast<usize>(width) * dstBpp;
1291 WGPUTexelCopyBufferLayout layout{};
1292 layout.bytesPerRow =
static_cast<u32>(dstRow);
1293 layout.rowsPerImage = height;
1298 const bool reverseRows = flipY && height > 1;
1299 std::vector<u8> staged;
1300 const void* src = pixels;
1301 if (reverseRows || srcBpp != dstBpp) {
1302 staged.resize(dstRow * height);
1304 width, height, srcBpp, dstBpp, reverseRows);
1305 src = staged.data();
1308 WGPUExtent3D extent{width, height, 1};
1309 wgpuQueueWriteTexture(queue_, &dst, src, dstRow * height, &layout, &extent);
1315 auto it = textures_.find(
id);
1316 if (it == textures_.end())
return;
1318 if (it->second.samplerKey == key)
return;
1319 it->second.samplerKey = key;
1320 for (
u32 slot = 0; slot < kTextureSlots; ++slot) {
1321 if (texture_slots_[slot] ==
id) {
1322 bind_group_dirty_ =
true;
1329 auto it = textures_.find(
id);
1330 if (it != textures_.end() && it->second.mipLevels > 1) buildMipChain(it->second);
1334 if (slot >= kTextureSlots)
return;
1335 const u32 id =
static_cast<u32>(texture);
1336 if (texture_slots_[slot] !=
id) {
1337 texture_slots_[slot] = id;
1338 bind_group_dirty_ =
true;
1344 if (!device_)
return false;
1359 if (outLog) *outLog =
"WebGPUDevice compiles WGSL only";
1361 ES_LOG_ERROR(
"WebGPUDevice::createProgram: unsupported shader language");
1365 if (outLog) *outLog =
"no WGPUDevice";
1366 ES_LOG_ERROR(
"WebGPUDevice::createProgram: no device");
1373 const auto undeclared = [&](
const char* src,
const char* stage) ->
bool {
1378 for (
u32 unit = 0; unit < 16; ++unit) {
1379 const bool tex = (reachedTex & (1u << unit)) != 0
1381 const bool sam = (reachedSam & (1u << unit)) != 0
1383 if (!tex && !sam)
continue;
1385 *outLog = std::string(
"the ") + stage +
" stage reaches "
1386 + (tex ?
"t" :
"s") + std::to_string(unit) +
" and declares no binding for it";
1388 ES_LOG_ERROR(
"WebGPUDevice::createProgram: the {} stage reaches {}{} and declares "
1389 "no binding for it", stage, tex ?
"t" :
"s", unit);
1394 if (undeclared(source.
vertexSrc,
"vertex")) {
1403 auto makeModule = [&](
const char* code) -> WGPUShaderModule {
1404 WGPUShaderSourceWGSL wgsl{};
1405 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1406 wgsl.code = sv(code);
1407 WGPUShaderModuleDescriptor md{};
1408 md.nextInChain = &wgsl.chain;
1409 return wgpuDeviceCreateShaderModule(device_, &md);
1413 rec.vertex = makeModule(source.
vertexSrc);
1433 if (!rec.vertex || !rec.fragment) {
1434 if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
1435 if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
1436 if (outLog) *outLog =
"shader module creation failed";
1441 programs_[id] = rec;
1446 auto it = programs_.find(
id);
1447 if (it == programs_.end())
return;
1448 if (it->second.vertex) wgpuShaderModuleRelease(it->second.vertex);
1449 if (it->second.fragment) wgpuShaderModuleRelease(it->second.fragment);
1450 programs_.erase(it);
1458WGPURenderPipeline WebGPUDevice::ensurePipeline(
u32 id) {
1460 if (!described || !device_)
return nullptr;
1461 PipelineRec& built = pipelines_[id];
1462 const u32 dsVariant = dsVariantOf(pass_ds_format_);
1463 const PipelineDesc& desc = *described;
1464 const bool writesAlbedo = pass_albedo_ && desc.
gbuffer && desc.albedo;
1465 const u32 gbufferVariant = !pass_gbuffer_ ? kGBufferNone
1466 : writesAlbedo ? kGBufferWritesAlbedo
1467 : desc.gbuffer ? kGBufferWrites : kGBufferSkips;
1468 const u32 variant = ((dsVariant * kColorVariantCount + colorVariantOf(pass_color_format_))
1469 * kSampleVariantCount + (pass_samples_ > 1 ? kMultiSample : kSingleSample))
1470 * kGBufferVariantCount + gbufferVariant;
1471 if (built.variants[variant])
return built.variants[variant];
1473 auto progIt = programs_.find(
static_cast<u32
>(desc.program));
1474 const VertexLayoutDesc* layout = vertexLayoutDesc(desc.vertexLayout);
1475 if (progIt == programs_.end() || !layout) {
1476 ES_LOG_ERROR(
"WebGPUDevice::ensurePipeline: missing program or layout");
1479 const VertexLayoutDesc& vl = *layout;
1482 WGPUVertexAttribute attrs[MAX_VERTEX_ATTRIBUTES] = {};
1483 WGPUVertexBufferLayout slots[MAX_VERTEX_BUFFER_SLOTS] = {};
1486 for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
1487 const u32 first = attrCursor;
1488 for (u32 i = 0; i < vl.attributeCount; ++i) {
1489 const auto& a = vl.attributes[i];
1490 if (a.bufferSlot != slot)
continue;
1492 attrs[attrCursor].offset = a.offset;
1493 attrs[attrCursor].shaderLocation = a.location;
1496 if (attrCursor == first)
continue;
1497 slots[slotCount].stepMode = vl.instanceStep[slot] ? WGPUVertexStepMode_Instance
1498 : WGPUVertexStepMode_Vertex;
1499 slots[slotCount].arrayStride = vl.strides[slot];
1500 slots[slotCount].attributeCount = attrCursor - first;
1501 slots[slotCount].attributes = &attrs[first];
1505 const BlendStateWGPU blend =
toWGPUBlend(desc.blend, desc.layerAlpha);
1506 WGPUBlendState blendState{};
1507 blendState.color = blend.color;
1508 blendState.alpha = blend.alpha;
1510 WGPUColorTargetState targets[3]{};
1511 targets[0].format = pass_color_format_;
1512 targets[0].blend = desc.blendEnabled ? &blendState :
nullptr;
1513 targets[0].writeMask = (
writesStencil(desc.stencil) || !desc.colorWrite) ? WGPUColorWriteMask_None
1514 : WGPUColorWriteMask_All;
1519 targets[1].format = WGPUTextureFormat_RGBA8Unorm;
1520 targets[1].writeMask = (desc.gbuffer && desc.colorWrite && !
writesStencil(desc.stencil)) ? WGPUColorWriteMask_All
1521 : WGPUColorWriteMask_None;
1523 targets[2].format = WGPUTextureFormat_RGBA8Unorm;
1524 targets[2].writeMask = (writesAlbedo && desc.colorWrite && !
writesStencil(desc.stencil)) ? WGPUColorWriteMask_All
1525 : WGPUColorWriteMask_None;
1527 WGPUFragmentState fragment{};
1528 fragment.module = progIt->second.fragment;
1529 fragment.entryPoint = sv(
"fs_main");
1530 fragment.targetCount = !pass_gbuffer_ ? 1 : pass_albedo_ ? 3 : 2;
1531 fragment.targets = targets;
1533 WGPURenderPipelineDescriptor pd{};
1538 pd.layout = pipelineLayoutFor(progIt->second.group0Mask, progIt->second.group1Mask,
1539 progIt->second.group1DepthMask,
1540 progIt->second.group1VertexMask,
1541 progIt->second.group1ArrayMask,
1542 progIt->second.group1VolumeMask, progIt->second.group1FragmentMask);
1543 pd.vertex.module = progIt->second.vertex;
1544 pd.vertex.entryPoint = sv(
"vs_main");
1545 pd.vertex.bufferCount = slotCount;
1546 pd.vertex.buffers = slots;
1547 pd.primitive.topology = desc.topology == GfxTopology::Lines ? WGPUPrimitiveTopology_LineList
1548 : WGPUPrimitiveTopology_TriangleList;
1551 pd.primitive.frontFace = WGPUFrontFace_CW;
1552 pd.primitive.cullMode =
toWGPUCullMode(desc.cullEnabled, desc.cullFront);
1555 pd.multisample.count = pass_samples_;
1556 pd.multisample.mask = 0xFFFFFFFFu;
1558 pd.multisample.alphaToCoverageEnabled = desc.alphaToCoverage && pass_samples_ > 1;
1559 pd.fragment = &fragment;
1560 WGPUDepthStencilState ds{};
1561 if (dsVariant != kDsNone) {
1563 pd.depthStencil = &ds;
1564 }
else if (desc.depthTest || desc.stencil != GfxStencilMode::Off) {
1565 ES_LOG_WARN(
"WebGPUDevice::ensurePipeline: depth/stencil requested but the "
1566 "pass target has no depth-stencil attachment");
1569 built.variants[variant] = wgpuDeviceCreateRenderPipeline(device_, &pd);
1570 if (!built.variants[variant]) {
1571 ES_LOG_ERROR(
"WebGPUDevice::ensurePipeline: creation failed");
1573 return built.variants[variant];
1577 bound_pipeline_ = id;
1579 if (WGPURenderPipeline p = ensurePipeline(
id)) {
1580 if (p == pass_pipeline_)
return;
1581 wgpuRenderPassEncoderSetPipeline(pass_, p);
1583 bind_group_dirty_ =
true;
1588 stencil_ref_ = reference;
1589 if (pass_) wgpuRenderPassEncoderSetStencilReference(pass_,
static_cast<u32>(reference));
1592WGPUSampler WebGPUDevice::samplerFor(
u8 key) {
1593 auto it = samplers_.find(key);
1594 if (it != samplers_.end())
return it->second;
1595 if (!device_)
return nullptr;
1597 WGPUSamplerDescriptor sd{};
1598 sd.minFilter = (key & 1u) ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;
1599 sd.magFilter = (key & 2u) ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;
1600 sd.addressModeU = toWGPUAddressMode(
static_cast<TextureWrap
>((key >> 2) & 3u));
1601 sd.addressModeV = toWGPUAddressMode(
static_cast<TextureWrap
>((key >> 4) & 3u));
1602 sd.addressModeW = WGPUAddressMode_ClampToEdge;
1606 sd.mipmapFilter = WGPUMipmapFilterMode_Linear;
1607 sd.lodMinClamp = 0.0f;
1608 sd.lodMaxClamp = 32.0f;
1611 sd.maxAnisotropy = (key & 3u) == 0u ? 16 : 1;
1612 WGPUSampler sampler = wgpuDeviceCreateSampler(device_, &sd);
1613 samplers_[key] = sampler;
1623WGPURenderPipeline WebGPUDevice::ensureDepthResolvePipeline(WGPUTextureFormat format) {
1624 const u32 key =
static_cast<u32>(format);
1625 auto it = depth_resolve_pipelines_.find(key);
1626 if (it != depth_resolve_pipelines_.end())
return it->second;
1627 if (!device_)
return nullptr;
1629 static const char* kVS = R
"(
1630@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
1631 var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
1632 return vec4f(p[i], 0.0, 1.0);
1635 static const char* kFS = R
"(
1636@group(0) @binding(0) var src : texture_depth_multisampled_2d;
1637@fragment fn fs_main(@builtin(position) pos : vec4f) -> @builtin(frag_depth) f32 {
1638 return textureLoad(src, vec2i(i32(pos.x), i32(pos.y)), 0);
1641 auto makeModule = [&](
const char* code) {
1642 WGPUShaderSourceWGSL wgsl{};
1643 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1644 wgsl.code = sv(code);
1645 WGPUShaderModuleDescriptor md{};
1646 md.nextInChain = &wgsl.chain;
1647 return wgpuDeviceCreateShaderModule(device_, &md);
1649 if (!depth_resolve_vs_) depth_resolve_vs_ = makeModule(kVS);
1650 if (!depth_resolve_fs_) depth_resolve_fs_ = makeModule(kFS);
1651 if (!depth_resolve_bgl_) {
1652 WGPUBindGroupLayoutEntry ble{};
1654 ble.visibility = WGPUShaderStage_Fragment;
1655 ble.texture.sampleType = WGPUTextureSampleType_Depth;
1656 ble.texture.viewDimension = WGPUTextureViewDimension_2D;
1657 ble.texture.multisampled =
true;
1658 WGPUBindGroupLayoutDescriptor bld{};
1661 depth_resolve_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
1662 WGPUPipelineLayoutDescriptor pld{};
1663 pld.bindGroupLayoutCount = 1;
1664 pld.bindGroupLayouts = &depth_resolve_bgl_;
1665 depth_resolve_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
1668 WGPURenderPipelineDescriptor pd{};
1669 pd.layout = depth_resolve_layout_;
1670 pd.vertex.module = depth_resolve_vs_;
1671 pd.vertex.entryPoint = sv(
"vs_main");
1672 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
1673 pd.primitive.frontFace = WGPUFrontFace_CCW;
1674 pd.primitive.cullMode = WGPUCullMode_None;
1675 pd.multisample.count = 1;
1676 pd.multisample.mask = 0xFFFFFFFFu;
1678 WGPUFragmentState fragment{};
1679 fragment.module = depth_resolve_fs_;
1680 fragment.entryPoint = sv(
"fs_main");
1681 fragment.targetCount = 0;
1682 pd.fragment = &fragment;
1683 WGPUDepthStencilState ds{};
1685 ds.depthWriteEnabled = WGPUOptionalBool_True;
1686 ds.depthCompare = WGPUCompareFunction_Always;
1687 WGPUStencilFaceState face{};
1688 face.compare = WGPUCompareFunction_Always;
1689 face.failOp = WGPUStencilOperation_Keep;
1690 face.depthFailOp = WGPUStencilOperation_Keep;
1691 face.passOp = WGPUStencilOperation_Keep;
1692 ds.stencilFront = face;
1693 ds.stencilBack = face;
1694 ds.stencilReadMask = 0xFFFFFFFFu;
1695 ds.stencilWriteMask = 0u;
1696 pd.depthStencil = &ds;
1698 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
1699 if (!pipeline)
ES_LOG_ERROR(
"WebGPUDevice: depth resolve pipeline creation failed");
1700 depth_resolve_pipelines_[key] = pipeline;
1704WGPURenderPipeline WebGPUDevice::ensureMipPipeline(WGPUTextureFormat format) {
1705 const u32 key =
static_cast<u32>(format);
1706 auto it = mip_pipelines_.find(key);
1707 if (it != mip_pipelines_.end())
return it->second;
1708 if (!device_)
return nullptr;
1712 static const char* kWGSL = R
"(
1713struct VSOut { @builtin(position) pos : vec4f, @location(0) uv : vec2f };
1714@vertex fn vs_main(@builtin(vertex_index) i : u32) -> VSOut {
1715 var p = array<vec2f, 3>(vec2f(-1.0, 1.0), vec2f(3.0, 1.0), vec2f(-1.0, -3.0));
1717 out.pos = vec4f(p[i], 0.0, 1.0);
1718 out.uv = vec2f(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
1721@group(0) @binding(0) var src : texture_2d<f32>;
1722@group(0) @binding(1) var smp : sampler;
1723@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
1724 return textureSampleLevel(src, smp, v.uv, 0.0);
1728 WGPUShaderSourceWGSL wgsl{};
1729 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1730 wgsl.code = sv(kWGSL);
1731 WGPUShaderModuleDescriptor md{};
1732 md.nextInChain = &wgsl.chain;
1733 mip_module_ = wgpuDeviceCreateShaderModule(device_, &md);
1736 WGPUBindGroupLayoutEntry entries[2]{};
1737 entries[0].binding = 0;
1738 entries[0].visibility = WGPUShaderStage_Fragment;
1739 entries[0].texture.sampleType = WGPUTextureSampleType_Float;
1740 entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
1741 entries[1].binding = 1;
1742 entries[1].visibility = WGPUShaderStage_Fragment;
1743 entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
1744 WGPUBindGroupLayoutDescriptor bld{};
1746 bld.entries = entries;
1747 mip_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
1748 WGPUPipelineLayoutDescriptor pld{};
1749 pld.bindGroupLayoutCount = 1;
1750 pld.bindGroupLayouts = &mip_bgl_;
1751 mip_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
1752 WGPUSamplerDescriptor sd{};
1753 sd.minFilter = WGPUFilterMode_Linear;
1754 sd.magFilter = WGPUFilterMode_Linear;
1755 sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
1756 sd.addressModeU = WGPUAddressMode_ClampToEdge;
1757 sd.addressModeV = WGPUAddressMode_ClampToEdge;
1758 sd.addressModeW = WGPUAddressMode_ClampToEdge;
1759 sd.lodMaxClamp = 32.0f;
1760 sd.maxAnisotropy = 1;
1761 mip_sampler_ = wgpuDeviceCreateSampler(device_, &sd);
1764 WGPURenderPipelineDescriptor pd{};
1765 pd.layout = mip_layout_;
1766 pd.vertex.module = mip_module_;
1767 pd.vertex.entryPoint = sv(
"vs_main");
1768 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
1769 pd.primitive.frontFace = WGPUFrontFace_CCW;
1770 pd.primitive.cullMode = WGPUCullMode_None;
1771 pd.multisample.count = 1;
1772 pd.multisample.mask = 0xFFFFFFFFu;
1773 WGPUColorTargetState target{};
1774 target.format = format;
1775 target.writeMask = WGPUColorWriteMask_All;
1776 WGPUFragmentState fragment{};
1777 fragment.module = mip_module_;
1778 fragment.entryPoint = sv(
"fs_main");
1779 fragment.targetCount = 1;
1780 fragment.targets = ⌖
1781 pd.fragment = &fragment;
1783 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
1784 if (!pipeline)
ES_LOG_ERROR(
"WebGPUDevice: mip pipeline creation failed");
1785 mip_pipelines_[key] = pipeline;
1789void WebGPUDevice::buildMipChain(
const TextureRec& rec) {
1790 if (!device_ || !queue_ || rec.mipLevels < 2)
return;
1791 WGPURenderPipeline pipeline = ensureMipPipeline(rec.format);
1792 if (!pipeline)
return;
1796 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
1797 if (!encoder)
return;
1799 std::vector<WGPUTextureView> views;
1800 std::vector<WGPUBindGroup> groups;
1801 for (u32 layer = 0; layer < rec.layers; ++layer) {
1802 for (u32 level = 0; level < rec.mipLevels; ++level) {
1803 WGPUTextureViewDescriptor vd{};
1804 vd.format = rec.format;
1805 vd.dimension = WGPUTextureViewDimension_2D;
1806 vd.baseMipLevel = level;
1807 vd.mipLevelCount = 1;
1808 vd.baseArrayLayer = layer;
1809 vd.arrayLayerCount = 1;
1810 vd.aspect = WGPUTextureAspect_All;
1811 views.push_back(wgpuTextureCreateView(rec.texture, &vd));
1814 for (u32 step = 0;
step < rec.layers * rec.mipLevels; ++
step) {
1815 const u32 level =
step % rec.mipLevels;
1816 if (level == 0)
continue;
1817 WGPUBindGroupEntry entries[2]{};
1818 entries[0].binding = 0;
1819 entries[0].textureView = views[
step - 1];
1820 entries[1].binding = 1;
1821 entries[1].sampler = mip_sampler_;
1822 WGPUBindGroupDescriptor bgd{};
1823 bgd.layout = mip_bgl_;
1825 bgd.entries = entries;
1826 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
1828 groups.push_back(group);
1830 WGPURenderPassColorAttachment color{};
1831 color.view = views[
step];
1832 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
1833 color.loadOp = WGPULoadOp_Clear;
1834 color.storeOp = WGPUStoreOp_Store;
1835 WGPURenderPassDescriptor rp{};
1836 rp.colorAttachmentCount = 1;
1837 rp.colorAttachments = &color;
1838 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
1840 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
1841 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0,
nullptr);
1842 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
1843 wgpuRenderPassEncoderEnd(pass);
1844 wgpuRenderPassEncoderRelease(pass);
1846 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder,
nullptr);
1848 wgpuQueueSubmit(queue_, 1, &commands);
1849 wgpuCommandBufferRelease(commands);
1851 wgpuCommandEncoderRelease(encoder);
1852 for (WGPUBindGroup group : groups) wgpuBindGroupRelease(group);
1853 for (WGPUTextureView view : views) wgpuTextureViewRelease(view);
1856void WebGPUDevice::resolveDepthAttachment(u32 msaaDepth, u32 resolveDepth) {
1857 if (!device_ || !encoder_)
return;
1858 auto srcIt = textures_.find(msaaDepth);
1859 auto dstIt = textures_.find(resolveDepth);
1860 if (srcIt == textures_.end() || dstIt == textures_.end())
return;
1861 WGPURenderPipeline pipeline = ensureDepthResolvePipeline(dstIt->second.format);
1862 if (!pipeline)
return;
1867 WGPUBindGroupEntry entry{};
1869 entry.textureView = srcIt->second.sampleView;
1870 WGPUBindGroupDescriptor bgd{};
1871 bgd.layout = depth_resolve_bgl_;
1873 bgd.entries = &entry;
1874 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
1877 WGPURenderPassDepthStencilAttachment ds{};
1878 ds.view = dstIt->second.view;
1879 ds.depthLoadOp = WGPULoadOp_Clear;
1880 ds.depthStoreOp = WGPUStoreOp_Store;
1881 ds.depthClearValue = 1.0f;
1883 ds.stencilLoadOp = WGPULoadOp_Clear;
1884 ds.stencilStoreOp = WGPUStoreOp_Store;
1886 WGPURenderPassDescriptor rp{};
1887 rp.colorAttachmentCount = 0;
1888 rp.depthStencilAttachment = &ds;
1890 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder_, &rp);
1892 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
1893 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0,
nullptr);
1894 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
1895 wgpuRenderPassEncoderEnd(pass);
1896 wgpuRenderPassEncoderRelease(pass);
1898 wgpuBindGroupRelease(group);
1909WGPURenderPipeline WebGPUDevice::ensureClearPipeline(
bool color,
bool depth,
bool stencil) {
1912 const u32 key = (pass_gbuffer_ ? 1u << 12 : 0u) | (pass_albedo_ ? 1u << 13 : 0u) |
1913 colorVariantOf(pass_color_format_) << 6 |
1914 dsVariantOf(pass_ds_format_) << 4 |
1915 (pass_samples_ > 1 ? 8u : 0u) |
1916 (color ? 1u : 0u) | (depth ? 2u : 0u) | (stencil ? 4u : 0u);
1917 auto it = clear_pipelines_.find(key);
1918 if (it != clear_pipelines_.end())
return it->second;
1920 static const char* kClearVS = R
"(
1921@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
1922 var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
1923 return vec4f(p[i], 1.0, 1.0);
1926 static const char* kClearFS = R
"(
1927struct ClearColor { value : vec4f };
1928@group(0) @binding(0) var<uniform> clearColor : ClearColor;
1929@fragment fn fs_main() -> @location(0) vec4f { return clearColor.value; }
1931 auto makeModule = [&](
const char* code) {
1932 WGPUShaderSourceWGSL wgsl{};
1933 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1934 wgsl.code = sv(code);
1935 WGPUShaderModuleDescriptor md{};
1936 md.nextInChain = &wgsl.chain;
1937 return wgpuDeviceCreateShaderModule(device_, &md);
1943 WGPUBindGroupLayoutEntry ble{};
1945 ble.visibility = WGPUShaderStage_Fragment;
1946 ble.buffer.type = WGPUBufferBindingType_Uniform;
1947 ble.buffer.minBindingSize = 16;
1948 WGPUBindGroupLayoutDescriptor bld{};
1951 clear_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
1953 WGPUPipelineLayoutDescriptor pld{};
1954 pld.bindGroupLayoutCount = 1;
1955 pld.bindGroupLayouts = &clear_bgl_;
1956 clear_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
1958 clear_color_buffer_ = makeBuffer(GfxBufferUsage::Uniform, 16,
nullptr);
1959 WGPUBindGroupEntry entry{};
1961 entry.buffer = clear_color_buffer_;
1964 WGPUBindGroupDescriptor bgd{};
1965 bgd.layout = clear_bgl_;
1967 bgd.entries = &entry;
1968 clear_bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
1971 WGPUShaderModule vs = makeModule(kClearVS);
1972 WGPUShaderModule fs = makeModule(kClearFS);
1974 WGPUColorTargetState clearTargets[3]{};
1975 clearTargets[0].format = pass_color_format_;
1976 clearTargets[0].writeMask = color ? WGPUColorWriteMask_All : WGPUColorWriteMask_None;
1978 clearTargets[1].format = WGPUTextureFormat_RGBA8Unorm;
1979 clearTargets[1].writeMask = WGPUColorWriteMask_None;
1980 clearTargets[2].format = WGPUTextureFormat_RGBA8Unorm;
1981 clearTargets[2].writeMask = WGPUColorWriteMask_None;
1983 WGPUFragmentState fragment{};
1984 fragment.module = fs;
1985 fragment.entryPoint = sv(
"fs_main");
1986 fragment.targetCount = !pass_gbuffer_ ? 1 : pass_albedo_ ? 3 : 2;
1987 fragment.targets = clearTargets;
1989 WGPURenderPipelineDescriptor pd{};
1990 pd.layout = clear_layout_;
1991 pd.vertex.module = vs;
1992 pd.vertex.entryPoint = sv(
"vs_main");
1993 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
1994 pd.primitive.frontFace = WGPUFrontFace_CCW;
1995 pd.primitive.cullMode = WGPUCullMode_None;
1996 pd.multisample.count = pass_samples_;
1997 pd.multisample.mask = 0xFFFFFFFFu;
1998 pd.fragment = &fragment;
2000 WGPUDepthStencilState ds{};
2001 if (pass_ds_format_ != WGPUTextureFormat_Undefined) {
2002 ds.format = pass_ds_format_;
2003 ds.depthCompare = WGPUCompareFunction_Always;
2004 ds.depthWriteEnabled = depth ? WGPUOptionalBool_True : WGPUOptionalBool_False;
2005 WGPUStencilFaceState face{};
2006 face.compare = WGPUCompareFunction_Always;
2007 face.failOp = stencil ? WGPUStencilOperation_Replace : WGPUStencilOperation_Keep;
2008 face.depthFailOp = face.failOp;
2009 face.passOp = face.failOp;
2010 ds.stencilFront = face;
2011 ds.stencilBack = face;
2012 ds.stencilReadMask = 0xFFu;
2013 ds.stencilWriteMask = stencil ? 0xFFu : 0x00u;
2014 pd.depthStencil = &ds;
2017 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
2018 wgpuShaderModuleRelease(vs);
2019 wgpuShaderModuleRelease(fs);
2020 clear_pipelines_[key] = pipeline;
2024void WebGPUDevice::drawInternalClear(
bool color,
bool depth,
bool stencil,
2025 const f32 rgba[4], i32 stencilValue,
2026 const RenderPassDesc* region) {
2027 if (!pass_ || !device_)
return;
2028 WGPURenderPipeline pipeline = ensureClearPipeline(color, depth, stencil);
2029 if (!pipeline || !clear_bind_group_)
return;
2031 const f32 black[4] = {0.0f, 0.0f, 0.0f, 0.0f};
2032 writeBufferPadded(clear_color_buffer_, 0, rgba ? rgba : black, 16);
2038 setScissor(region->clearX, region->clearY,
2039 static_cast<i32>(region->clearW),
static_cast<i32>(region->clearH));
2041 wgpuRenderPassEncoderSetPipeline(pass_, pipeline);
2042 wgpuRenderPassEncoderSetBindGroup(pass_, 0, clear_bind_group_, 0,
nullptr);
2044 wgpuRenderPassEncoderSetStencilReference(pass_,
static_cast<u32>(stencilValue));
2046 wgpuRenderPassEncoderDraw(pass_, 3, 1, 0, 0);
2048 wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
2051 wgpuRenderPassEncoderSetStencilReference(pass_,
static_cast<u32>(stencil_ref_));
2054 bound_pipeline_ = 0;
2055 pass_pipeline_ =
nullptr;
2056 bind_group_dirty_ =
true;
2059WGPURenderPipeline WebGPUDevice::ensureFlipPipeline(WGPUTextureFormat format,
bool flip) {
2060 const u32 key =
static_cast<u32>(format) | (flip ? 0u : 0x80000000u);
2061 if (
auto it = flip_pipelines_.find(key); it != flip_pipelines_.end())
return it->second;
2062 static const char* kFlipVS = R
"(
2063@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
2064 var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
2065 return vec4f(p[i], 0.0, 1.0);
2068 static const char* kFlipFS = R
"(
2069@group(0) @binding(0) var source : texture_2d<f32>;
2070@fragment fn fs_main(@builtin(position) at : vec4f) -> @location(0) vec4f {
2071 let size = vec2i(textureDimensions(source));
2072 return textureLoad(source, vec2i(i32(at.x), size.y - 1 - i32(at.y)), 0);
2075 static const char* kCopyFS = R
"(
2076@group(0) @binding(0) var source : texture_2d<f32>;
2077@fragment fn fs_main(@builtin(position) at : vec4f) -> @location(0) vec4f {
2078 return textureLoad(source, vec2i(i32(at.x), i32(at.y)), 0);
2081 auto makeModule = [&](
const char* code) {
2082 WGPUShaderSourceWGSL wgsl{};
2083 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
2084 wgsl.code = sv(code);
2085 WGPUShaderModuleDescriptor md{};
2086 md.nextInChain = &wgsl.chain;
2087 return wgpuDeviceCreateShaderModule(device_, &md);
2090 WGPUBindGroupLayoutEntry entry{};
2092 entry.visibility = WGPUShaderStage_Fragment;
2093 entry.texture.sampleType = WGPUTextureSampleType_UnfilterableFloat;
2094 entry.texture.viewDimension = WGPUTextureViewDimension_2D;
2095 WGPUBindGroupLayoutDescriptor bld{};
2097 bld.entries = &entry;
2098 flip_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
2099 WGPUPipelineLayoutDescriptor pld{};
2100 pld.bindGroupLayoutCount = 1;
2101 pld.bindGroupLayouts = &flip_bgl_;
2102 flip_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
2104 WGPUShaderModule vs = makeModule(kFlipVS);
2105 WGPUShaderModule fs = makeModule(flip ? kFlipFS : kCopyFS);
2106 WGPUColorTargetState target{};
2107 target.format = format;
2108 target.writeMask = WGPUColorWriteMask_All;
2109 WGPUFragmentState fragment{};
2110 fragment.module = fs;
2111 fragment.entryPoint = sv(
"fs_main");
2112 fragment.targetCount = 1;
2113 fragment.targets = ⌖
2114 WGPURenderPipelineDescriptor pd{};
2115 pd.layout = flip_layout_;
2116 pd.vertex.module = vs;
2117 pd.vertex.entryPoint = sv(
"vs_main");
2118 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
2119 pd.primitive.frontFace = WGPUFrontFace_CCW;
2120 pd.primitive.cullMode = WGPUCullMode_None;
2121 pd.multisample.count = 1;
2122 pd.multisample.mask = 0xFFFFFFFFu;
2123 pd.fragment = &fragment;
2124 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
2125 wgpuShaderModuleRelease(vs);
2126 wgpuShaderModuleRelease(fs);
2127 flip_pipelines_[key] = pipeline;
2131bool WebGPUDevice::surfaceAllowsCopy()
const {
2132#if !defined(__EMSCRIPTEN__)
2133 if (surface_ && adapter_) {
2134 WGPUSurfaceCapabilities caps{};
2135 if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success) {
2136 const bool allowed = (caps.usages & WGPUTextureUsage_CopySrc) != 0;
2137 wgpuSurfaceCapabilitiesFreeMembers(caps);
2145bool WebGPUDevice::copyFramebufferColor(FramebufferHandle source, TextureHandle dst) {
2146 if (!device_ || !isDeviceUsable())
return false;
2147 const auto to = textures_.find(
static_cast<u32>(dst));
2148 if (to == textures_.end() || to->second.samples > 1 || to->second.layers > 1 || to->second.volume)
return false;
2149 if (pass_) endRenderPass();
2151 WGPUTexture from =
nullptr;
2152 WGPUTextureFormat fromFormat = WGPUTextureFormat_Undefined;
2155 if (source == FramebufferHandle::Default) {
2156 if (!surface_readback_) {
2157 if (!surfaceAllowsCopy())
return false;
2158 surface_readback_ =
true;
2159 surface_reconfigure_ =
true;
2162 if (surface_reconfigure_ || (!frame_texture_ && !surface_proxy_drawn_) || !surface_proxy_)
return false;
2163 from = surface_proxy_;
2164 fromFormat = surface_format_;
2165 width = surface_width_;
2166 height = surface_height_;
2168 const FramebufferDesc* fb = framebufferDesc(source);
2169 if (!fb)
return false;
2170 auto color = textures_.find(
static_cast<u32>(fb->color0));
2171 if (color != textures_.end() && color->second.samples > 1) color = textures_.find(
static_cast<u32>(fb->resolveColor0));
2172 if (color == textures_.end() || color->second.samples > 1)
return false;
2173 from = color->second.texture;
2174 fromFormat = color->second.format;
2175 width = color->second.width;
2176 height = color->second.height;
2178 if (!from || width != to->second.width || height != to->second.height)
return false;
2180 const bool direct = fromFormat == to->second.format;
2181 WGPUTexture target = to->second.texture;
2183 if (!surface_copy_ || surface_copy_format_ != fromFormat || surface_copy_width_ != width || surface_copy_height_ != height) {
2184 if (surface_copy_view_) { wgpuTextureViewRelease(surface_copy_view_); surface_copy_view_ =
nullptr; }
2185 if (surface_copy_) { wgpuTextureRelease(surface_copy_); surface_copy_ =
nullptr; }
2186 WGPUTextureDescriptor td{};
2187 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst;
2188 td.dimension = WGPUTextureDimension_2D;
2189 td.size = {width, height, 1};
2190 td.format = fromFormat;
2191 td.mipLevelCount = 1;
2193 surface_copy_ = wgpuDeviceCreateTexture(device_, &td);
2194 if (!surface_copy_)
return false;
2195 surface_copy_view_ = wgpuTextureCreateView(surface_copy_,
nullptr);
2196 surface_copy_format_ = fromFormat;
2197 surface_copy_width_ = width;
2198 surface_copy_height_ = height;
2200 target = surface_copy_;
2203 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
2204 WGPUTexelCopyTextureInfo src{};
2206 src.aspect = WGPUTextureAspect_All;
2207 WGPUTexelCopyTextureInfo dest{};
2208 dest.texture = target;
2209 dest.aspect = WGPUTextureAspect_All;
2210 const WGPUExtent3D extent{width, height, 1};
2211 wgpuCommandEncoderCopyTextureToTexture(encoder, &src, &dest, &extent);
2213 WGPURenderPipeline pipeline = ensureFlipPipeline(to->second.format,
false);
2215 wgpuCommandEncoderRelease(encoder);
2218 WGPUBindGroupEntry entry{};
2220 entry.textureView = surface_copy_view_;
2221 WGPUBindGroupDescriptor bgd{};
2222 bgd.layout = flip_bgl_;
2224 bgd.entries = &entry;
2225 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
2226 WGPURenderPassColorAttachment color{};
2227 color.view = to->second.view;
2228 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2229 color.loadOp = WGPULoadOp_Clear;
2230 color.storeOp = WGPUStoreOp_Store;
2231 WGPURenderPassDescriptor rp{};
2232 rp.colorAttachmentCount = 1;
2233 rp.colorAttachments = &color;
2234 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
2235 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
2236 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0,
nullptr);
2237 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
2238 wgpuRenderPassEncoderEnd(pass);
2239 wgpuRenderPassEncoderRelease(pass);
2240 wgpuBindGroupRelease(group);
2242 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder,
nullptr);
2243 wgpuQueueSubmit(queue_, 1, &commands);
2244 wgpuCommandBufferRelease(commands);
2245 wgpuCommandEncoderRelease(encoder);
2249WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u64 mask, u64 depthMask,
2250 u64 vertexMask, u64 arrayMask, u64 volumeMask, u64 fragmentMask) {
2253 const std::array<u64, 7> key{group, mask, depthMask, vertexMask, arrayMask, volumeMask, fragmentMask};
2254 auto cached = group_layouts_.find(key);
2255 if (cached != group_layouts_.end())
return cached->second;
2256 if (!device_)
return nullptr;
2258 WGPUBindGroupLayoutEntry entries[kTextureSlots * 2];
2263 for (u32 slot = 0; slot < kUniformSlots; ++slot) {
2264 if ((mask & (1u << slot)) == 0)
continue;
2265 WGPUBindGroupLayoutEntry e{};
2267 e.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
2268 e.buffer.type = WGPUBufferBindingType_Uniform;
2269 entries[count++] = e;
2274 "device texture slots mirror the group-1 convention");
2275 for (u32 unit = 0; unit < kTextureSlots; ++unit) {
2278 const auto stages = [&](
u32 binding) {
2279 const u64 bit =
u64{1} << binding;
2280 return ((vertexMask & bit) ? WGPUShaderStage_Vertex : 0) |
2281 ((fragmentMask & bit) ? WGPUShaderStage_Fragment : 0);
2283 if (mask & (u64{1} << tb)) {
2284 WGPUBindGroupLayoutEntry e{};
2286 e.visibility = stages(tb);
2290 e.texture.sampleType =
2291 (depthMask & (
u64{1} << tb)) ? WGPUTextureSampleType_Depth
2292 : (mask & (
u64{1} << sb)) ? WGPUTextureSampleType_Float
2293 : WGPUTextureSampleType_UnfilterableFloat;
2294 e.texture.viewDimension = (arrayMask & (
u64{1} << tb)) ? WGPUTextureViewDimension_2DArray
2295 : (volumeMask & (
u64{1} << tb)) ? WGPUTextureViewDimension_3D
2296 : WGPUTextureViewDimension_2D;
2297 entries[count++] = e;
2299 if (mask & (u64{1} << sb)) {
2300 WGPUBindGroupLayoutEntry e{};
2302 e.visibility = stages(sb);
2303 e.sampler.type = WGPUSamplerBindingType_Filtering;
2304 entries[count++] = e;
2309 WGPUBindGroupLayoutDescriptor bld{};
2310 bld.entryCount = count;
2311 bld.entries = entries;
2312 WGPUBindGroupLayout layout = wgpuDeviceCreateBindGroupLayout(device_, &bld);
2313 group_layouts_[key] = layout;
2317WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u64 group1Mask,
2318 u64 group1DepthMask, u64 group1VertexMask,
2319 u64 group1ArrayMask, u64 group1VolumeMask, u64 group1FragmentMask) {
2322 const std::array<u64, 7> key{group0Mask, group1Mask, group1DepthMask, group1VertexMask, group1ArrayMask,
2323 group1VolumeMask, group1FragmentMask};
2324 auto cached = pipeline_layouts_.find(key);
2325 if (cached != pipeline_layouts_.end())
return cached->second;
2326 if (!device_)
return nullptr;
2330 WGPUBindGroupLayout bgls[2];
2332 if (group0Mask != 0 || group1Mask != 0) bgls[count++] = groupLayoutFor(0, group0Mask);
2333 if (group1Mask != 0) {
2334 bgls[count++] = groupLayoutFor(1, group1Mask, group1DepthMask, group1VertexMask, group1ArrayMask,
2335 group1VolumeMask, group1FragmentMask);
2338 WGPUPipelineLayoutDescriptor pld{};
2339 pld.bindGroupLayoutCount = count;
2340 pld.bindGroupLayouts = bgls;
2341 WGPUPipelineLayout layout = wgpuDeviceCreatePipelineLayout(device_, &pld);
2342 pipeline_layouts_[key] = layout;
2346void WebGPUDevice::ensureDummies() {
2347 if (!dummy_ubo_.buffer) {
2350 const std::vector<u8> zeros(16384, 0);
2351 dummy_ubo_ = BufferRec{makeBuffer(GfxBufferUsage::Uniform, 16384, zeros.data()), 16384,
2352 GfxBufferUsage::Uniform};
2354 if (!dummy_texture_.texture) {
2355 const u8 white[4] = {255, 255, 255, 255};
2356 makeTexture(TextureDesc{}, white, dummy_texture_);
2358 if (!dummy_depth_texture_.texture) {
2362 td.format = GfxPixelFormat::Depth24Stencil8;
2363 makeTexture(td,
nullptr, dummy_depth_texture_);
2365 if (!dummy_array_texture_.texture) {
2366 const u8 white[8] = {255, 255, 255, 255, 255, 255, 255, 255};
2369 makeTexture(td, white, dummy_array_texture_);
2371 if (!dummy_volume_texture_.texture) {
2372 const u8 white[4] = {255, 255, 255, 255};
2375 makeTexture(td, white, dummy_volume_texture_);
2379WGPUBindGroup WebGPUDevice::cachedBindGroup(
const u64* ids, u32 idCount,
2380 const WGPUBindGroupDescriptor& desc) {
2383 auto found = bind_group_cache_.find(hash);
2384 if (found != bind_group_cache_.end()) {
2385 for (
auto& e : found->second) {
2386 if (e.layout != desc.layout || e.ids.size() != idCount)
continue;
2388 for (u32 i = 0; i < idCount; ++i) {
2389 if (e.ids[i] != ids[i]) { same =
false;
break; }
2391 if (same) { e.used = bind_group_frame_;
return e.bg; }
2396 if (bind_group_count_ >= kBindGroupCacheCap) {
2397 for (
auto it = bind_group_cache_.begin(); it != bind_group_cache_.end();) {
2398 auto& bucket = it->second;
2399 for (usize i = bucket.size(); i-- > 0;) {
2400 if (bucket[i].used + 1 >= bind_group_frame_)
continue;
2401 if (bucket[i].bg) wgpuBindGroupRelease(bucket[i].bg);
2402 bucket.erase(bucket.begin() +
static_cast<std::ptrdiff_t
>(i));
2403 --bind_group_count_;
2405 it = bucket.empty() ? bind_group_cache_.erase(it) : std::next(it);
2408 WGPUBindGroup bg = wgpuDeviceCreateBindGroup(device_, &desc);
2410 bind_group_cache_[hash].push_back({desc.layout, std::vector<u64>(ids, ids + idCount), bg, bind_group_frame_});
2411 ++bind_group_count_;
2416void WebGPUDevice::flushBindGroup() {
2417 if (!bind_group_dirty_ || !pass_ || !device_)
return;
2419 WGPURenderPipeline p = ensurePipeline(bound_pipeline_);
2422 const ProgramRec* prog =
nullptr;
2423 if (
const PipelineDesc* desc = pipelineDesc(PipelineHandle{bound_pipeline_})) {
2424 auto progIt = programs_.find(
static_cast<u32>(desc->program));
2425 if (progIt != programs_.end()) prog = &progIt->second;
2428 if (prog->group0Mask == 0 && prog->group1Mask == 0) {
2429 bind_group_dirty_ =
false;
2441 WGPUBindGroupEntry entries[kUniformSlots];
2443 for (u32 slot = 0; slot < kUniformSlots; ++slot) {
2444 if ((prog->group0Mask & (1u << slot)) == 0)
continue;
2445 auto it = buffers_.find(uniform_slots_[slot]);
2446 const bool armed = it != buffers_.end() && it->second.buffer;
2447 const BufferRec& bound = armed ? it->second : dummy_ubo_;
2448 if (!bound.buffer)
continue;
2449 WGPUBindGroupEntry e{};
2451 e.buffer = bound.buffer;
2452 e.offset = armed ? uniform_offsets_[slot] : 0;
2453 e.size = armed && uniform_sizes_[slot] ? uniform_sizes_[slot] : bound.size;
2454 entries[count++] = e;
2457 WGPUBindGroupDescriptor bgd{};
2458 bgd.layout = groupLayoutFor(0, prog->group0Mask);
2459 bgd.entryCount = count;
2460 bgd.entries = entries;
2463 u64 ids[kUniformSlots * 2];
2464 for (u32 i = 0; i < count; ++i) {
2465 ids[i * 2] =
static_cast<u64>(
reinterpret_cast<uintptr_t
>(entries[i].buffer));
2466 ids[i * 2 + 1] = (
u64{1} << 63) | (entries[i].offset << 20) | entries[i].size;
2468 bind_group_ = cachedBindGroup(ids, count * 2, bgd);
2469 if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0,
nullptr);
2478 if (prog->group1Mask != 0) {
2479 const TextureRec* dummy = dummy_texture_.texture ? &dummy_texture_ :
nullptr;
2480 const TextureRec* depthDummy = dummy_depth_texture_.texture ? &dummy_depth_texture_ :
nullptr;
2481 const TextureRec* arrayDummy = dummy_array_texture_.texture ? &dummy_array_texture_ :
nullptr;
2482 const TextureRec* volumeDummy = dummy_volume_texture_.texture ? &dummy_volume_texture_ :
nullptr;
2484 WGPUBindGroupEntry texEntries[kTextureSlots * 2];
2486 for (u32 unit = 0; unit < kTextureSlots; ++unit) {
2490 const u32 bound = texture_slots_[unit];
2491 const bool feedback = bound != 0 && (bound == pass_color_texture_ ||
2492 bound == pass_depth_texture_);
2493 auto it = feedback ? textures_.end() : textures_.find(bound);
2494 const TextureRec* rec = (it != textures_.end()) ? &it->second : dummy;
2498 if (prog->group1Mask & (u64{1} << tb)) {
2502 const bool wantsDepth = (prog->group1DepthMask & (
u64{1} << tb)) != 0;
2505 const bool wantsArray = (prog->group1ArrayMask & (
u64{1} << tb)) != 0;
2506 const bool wantsVolume = (prog->group1VolumeMask & (
u64{1} << tb)) != 0;
2507 const bool isArray = !rec->volume && rec->layers > 1;
2508 const TextureRec* src = rec;
2509 if (wantsDepth && !isDepthFormat(src->format)) src = depthDummy;
2514 else if (!wantsDepth && isDepthFormat(src->format)) src = dummy;
2515 else if (wantsVolume) src = rec->volume ? rec : volumeDummy;
2516 else if (wantsArray && !isArray) src = arrayDummy;
2517 else if (!wantsArray && (isArray || rec->volume)) src = dummy;
2519 WGPUBindGroupEntry e{};
2521 e.textureView = src->sampleView;
2522 texEntries[texCount++] = e;
2524 if (prog->group1Mask & (
u64{1} << sb)) {
2525 WGPUBindGroupEntry e{};
2527 e.sampler = samplerFor(rec->samplerKey);
2528 texEntries[texCount++] = e;
2532 WGPUBindGroupDescriptor tgd{};
2533 tgd.layout = groupLayoutFor(1, prog->group1Mask, prog->group1DepthMask,
2534 prog->group1VertexMask, prog->group1ArrayMask, prog->group1VolumeMask, prog->group1FragmentMask);
2535 tgd.entryCount = texCount;
2536 tgd.entries = texEntries;
2537 u64 tids[kTextureSlots * 2];
2538 for (
u32 i = 0; i < texCount; ++i) {
2539 const uintptr_t p = texEntries[i].textureView
2540 ?
reinterpret_cast<uintptr_t
>(texEntries[i].textureView)
2541 :
reinterpret_cast<uintptr_t
>(texEntries[i].sampler);
2542 tids[i] =
static_cast<u64>(p);
2544 texture_group_ = cachedBindGroup(tids, texCount, tgd);
2545 if (texture_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 1, texture_group_, 0,
nullptr);
2547 bind_group_dirty_ =
false;
2555 if (!isDeviceUsable() || !pass_)
return;
2556 auto it = buffers_.find(bound_index_buffer_);
2557 if (it == buffers_.end())
return;
2559 wgpuRenderPassEncoderSetIndexBuffer(pass_, it->second.buffer,
toWGPUIndexFormat(indexType),
2560 0, it->second.size);
2563 wgpuRenderPassEncoderDrawIndexed(pass_, indexCount, 1, indexByteOffset / indexSize, 0, 0);
2566void WebGPUDevice::drawArrays(u32 firstVertex, u32 vertexCount) {
2567 if (!isDeviceUsable() || !pass_)
return;
2570 wgpuRenderPassEncoderDraw(pass_, vertexCount, 1, firstVertex, 0);
2573void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,
2574 u32 instanceCount) {
2575 if (!isDeviceUsable() || !pass_)
return;
2576 auto it = buffers_.find(bound_index_buffer_);
2577 if (it == buffers_.end())
return;
2579 wgpuRenderPassEncoderSetIndexBuffer(pass_, it->second.buffer,
toWGPUIndexFormat(indexType),
2580 0, it->second.size);
2581 const u32 indexSize = (indexType == GfxDataType::UnsignedShort) ? 2 : 4;
2583 wgpuRenderPassEncoderDrawIndexed(pass_, indexCount, instanceCount,
2584 indexByteOffset / indexSize, 0, 0);
2587bool WebGPUDevice::backendCreateFramebuffer(u32,
const FramebufferDesc& desc) {
2588 const u32 depthStencil =
static_cast<u32>(desc.depthStencil);
2589 if (depthStencil != 0 && !textures_.count(depthStencil)) {
2590 ES_LOG_ERROR(
"WebGPUDevice::createFramebuffer: unknown depth-stencil texture");
2596void WebGPUDevice::beginRenderPass(
const RenderPassDesc& desc) {
2597 if (computeJobOpen()) {
2598 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: a compute job is open");
2601 if (!isDeviceUsable())
return;
2602 if (!device_)
return;
2603 if (pass_) endRenderPass();
2605 WGPUTextureView targetView =
nullptr;
2606 WGPUTextureView resolveView =
nullptr;
2607 WGPUTextureView dsView =
nullptr;
2608 pass_ds_format_ = WGPUTextureFormat_Undefined;
2609 pass_color_format_ = surface_format_;
2610 pass_color_texture_ = 0;
2611 pass_depth_texture_ = 0;
2612 pass_is_surface_ = desc.target == FramebufferHandle::Default;
2614 pass_gbuffer_ =
false;
2615 pass_albedo_ =
false;
2616 WGPUTextureView gbufferView =
nullptr;
2617 WGPUTextureView gbufferResolveView =
nullptr;
2618 WGPUTextureView albedoView =
nullptr;
2619 WGPUTextureView albedoResolveView =
nullptr;
2620 pass_depth_msaa_ = 0;
2621 pass_depth_resolve_ = 0;
2622 if (desc.target != FramebufferHandle::Default) {
2623 const FramebufferDesc* fb = framebufferDesc(desc.target);
2625 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: unknown framebuffer");
2628 const u32 color0 =
static_cast<u32>(fb->color0);
2629 const u32 depthStencil =
static_cast<u32>(fb->depthStencil);
2630 auto texIt = textures_.find(color0);
2631 if (texIt == textures_.end()) {
2632 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: framebuffer color texture missing");
2635 targetView = texIt->second.view;
2636 pass_color_format_ = texIt->second.format;
2637 pass_color_texture_ = color0;
2638 pass_samples_ = texIt->second.samples;
2639 pass_width_ = texIt->second.width;
2640 pass_height_ = texIt->second.height;
2644 if (pass_samples_ > 1) {
2645 const u32 resolve =
static_cast<u32>(fb->resolveColor0);
2646 auto resolveIt = textures_.find(resolve);
2647 if (resolveIt == textures_.end()) {
2648 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: a multisampled target with no resolve twin");
2651 resolveView = resolveIt->second.view;
2652 pass_color_texture_ = resolve;
2654 if (fb->color1 != TextureHandle::Invalid) {
2655 auto gIt = textures_.find(
static_cast<u32>(fb->color1));
2656 if (gIt != textures_.end()) {
2657 gbufferView = gIt->second.view;
2658 pass_gbuffer_ =
true;
2659 if (gIt->second.samples > 1) {
2660 auto gResolve = textures_.find(
static_cast<u32>(fb->resolveColor1));
2661 if (gResolve == textures_.end()) {
2662 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: a multisampled surface record with no resolve twin");
2665 gbufferResolveView = gResolve->second.view;
2669 if (pass_gbuffer_ && fb->color2 != TextureHandle::Invalid) {
2670 auto aIt = textures_.find(
static_cast<u32>(fb->color2));
2671 if (aIt != textures_.end()) {
2672 albedoView = aIt->second.view;
2673 pass_albedo_ =
true;
2674 if (aIt->second.samples > 1) {
2675 auto aResolve = textures_.find(
static_cast<u32>(fb->resolveColor2));
2676 if (aResolve == textures_.end()) {
2677 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: a multisampled albedo with no resolve twin");
2680 albedoResolveView = aResolve->second.view;
2684 if (depthStencil != 0) {
2685 auto dsIt = textures_.find(depthStencil);
2686 if (dsIt != textures_.end()) {
2687 dsView = dsIt->second.view;
2688 pass_ds_format_ = dsIt->second.format;
2689 pass_depth_texture_ = depthStencil;
2693 const u32 resolveDepth =
static_cast<u32>(fb->resolveDepthStencil);
2694 if (dsIt->second.samples > 1 && resolveDepth != 0) {
2695 pass_depth_msaa_ = depthStencil;
2696 pass_depth_resolve_ = resolveDepth;
2697 pass_depth_texture_ = resolveDepth;
2703 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: no surface configured");
2708 if (!late_surface_acquire_ && !acquireFrameView())
return;
2709 pass_width_ = surface_width_;
2710 pass_height_ = surface_height_;
2713 if (!ensureSurfaceProxy(surface_width_, surface_height_)) {
2714 ES_LOG_ERROR(
"WebGPUDevice::beginRenderPass: no backbuffer texture");
2717 if (!ensureSurfaceDepth(surface_width_, surface_height_))
return;
2718 const bool multisampled = ensureSurfaceMsaa(surface_width_, surface_height_);
2719 if (surface_samples_ > 1 && !multisampled)
return;
2720 surface_proxy_drawn_ =
true;
2722 targetView = surface_msaa_view_;
2723 resolveView = surface_proxy_view_;
2724 pass_samples_ = surface_msaa_samples_;
2726 targetView = surface_proxy_view_;
2728 dsView = surface_depth_view_;
2729 pass_ds_format_ = WGPUTextureFormat_Depth24PlusStencil8;
2732 encoder_ = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
2736 pass_time_slot_ = takePassTimeSlot();
2737 pass_timed_ = pass_time_slot_ == kNoPassSlot && spanTakesPass();
2739 const bool scoped = desc.clearW != 0;
2740 WGPURenderPassColorAttachment color{};
2741 color.view = targetView;
2742 color.resolveTarget = resolveView;
2743 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2746 color.storeOp = (desc.discardMultisampled && resolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2750 WGPURenderPassColorAttachment colors[3]{};
2752 if (pass_gbuffer_) {
2753 colors[1].view = gbufferView;
2754 colors[1].resolveTarget = gbufferResolveView;
2755 colors[1].depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2756 colors[1].loadOp =
toWGPULoadOp(desc.clearColor, scoped);
2757 colors[1].storeOp = (desc.discardMultisampled && gbufferResolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2758 colors[1].clearValue = {0.0, 0.0, 0.0, 0.0};
2761 colors[2].view = albedoView;
2762 colors[2].resolveTarget = albedoResolveView;
2763 colors[2].depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2764 colors[2].loadOp =
toWGPULoadOp(desc.clearColor, scoped);
2765 colors[2].storeOp = (desc.discardMultisampled && albedoResolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2766 colors[2].clearValue = {0.0, 0.0, 0.0, 0.0};
2769 WGPURenderPassDescriptor rp{};
2770 rp.colorAttachmentCount = !pass_gbuffer_ ? 1 : pass_albedo_ ? 3 : 2;
2771 rp.colorAttachments = colors;
2773 WGPURenderPassDepthStencilAttachment ds{};
2776 ds.depthLoadOp =
toWGPULoadOp(desc.clearDepth, scoped);
2778 ds.depthStoreOp = (desc.discardDepth && pass_depth_msaa_ == 0) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2779 ds.depthClearValue = 1.0f;
2781 ds.stencilLoadOp =
toWGPULoadOp(desc.clearStencil, scoped);
2782 ds.stencilStoreOp = WGPUStoreOp_Store;
2783 ds.stencilClearValue =
static_cast<u32>(desc.clearStencilValue);
2785 rp.depthStencilAttachment = &ds;
2787 WGPUPassTimestampWrites tw{};
2788 if (pass_timed_ || pass_time_slot_ != kNoPassSlot) {
2789 tw.querySet = timestamp_qset_;
2790 tw.beginningOfPassWriteIndex = 0;
2791 tw.endOfPassWriteIndex = 1;
2792 rp.timestampWrites = &tw;
2794 pass_ = wgpuCommandEncoderBeginRenderPass(encoder_, &rp);
2795 pass_pipeline_ =
nullptr;
2796 bind_group_dirty_ =
true;
2801 if (scoped && (desc.clearColor || desc.clearDepth || desc.clearStencil)) {
2802 drawInternalClear(desc.clearColor, desc.clearDepth && dsView,
2804 desc.clearColorValue, desc.clearStencilValue, &desc);
2810 wgpuRenderPassEncoderEnd(pass_);
2811 wgpuRenderPassEncoderRelease(pass_);
2813 pass_pipeline_ =
nullptr;
2817 if (pass_depth_msaa_ && pass_depth_resolve_) {
2818 resolveDepthAttachment(pass_depth_msaa_, pass_depth_resolve_);
2819 pass_depth_msaa_ = 0;
2820 pass_depth_resolve_ = 0;
2825 const u32 passSlot = encoder_ ? pass_time_slot_ : kNoPassSlot;
2826 pass_time_slot_ = kNoPassSlot;
2827 if (passSlot != kNoPassSlot) resolvePassTime(encoder_, passSlot);
2828 if (pass_timed_ && encoder_) resolveSpanPass(encoder_);
2829 pass_timed_ =
false;
2834 if (capture_id_ && pass_is_surface_ && surface_proxy_ && encoder_) {
2835 encodeReadbackCopy(encoder_, capture_id_, surface_proxy_);
2836 capture_copied_ =
true;
2838 pass_is_surface_ =
false;
2840 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder_,
nullptr);
2841 wgpuCommandEncoderRelease(encoder_);
2843 wgpuQueueSubmit(queue_, 1, &commands);
2844 wgpuCommandBufferRelease(commands);
2846 if (passSlot != kNoPassSlot) mapPassTime(passSlot);
2848 if (span_closing_) {
2849 span_closing_ =
false;
2856bool WebGPUDevice::framePending() {
2857 if (frames_done_ >= frames_ended_)
return false;
2858 if (instance_) wgpuInstanceProcessEvents(instance_);
2860 return frames_done_ < frames_ended_;
2863void WebGPUDevice::endFrame() {
2865 ++bind_group_frame_;
2866 presentSurfaceProxy();
2869 const u64 frame = ++frames_ended_;
2870 WGPUQueueWorkDoneCallbackInfo done = WGPU_QUEUE_WORK_DONE_CALLBACK_INFO_INIT;
2871 done.mode = WGPUCallbackMode_AllowSpontaneous;
2872 done.callback = [](WGPUQueueWorkDoneStatus, WGPUStringView,
void* ticket,
void*) {
2873 publishCompletion(ticket);
2875 done.userdata1 =
new Ticket{mailbox_, {CompletionKind::Frame, frame}};
2876 wgpuQueueOnSubmittedWorkDone(queue_, done);
2882 const u32 id = capture_id_;
2884 if (capture_copied_) {
2885 capture_copied_ =
false;
2887 }
else if (frame_texture_ && surface_proxy_) {
2888 submitReadbackCopy(
id, surface_proxy_);
2892 auto it = readbacks_.find(
id);
2893 if (it != readbacks_.end()) it->second.status = GfxReadbackStatus::Failed;
2896 if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ =
nullptr; }
2897 if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ =
nullptr; }
2901 if (!isDeviceUsable() || !device_ || w == 0 || h == 0)
return ReadbackHandle::Invalid;
2902 if (!surface_readback_) {
2903 ES_LOG_ERROR(
"WebGPUDevice::captureNextFrame: the surface was configured without CopySrc "
2904 "(setSurfaceReadback must be on before configureSurface)");
2905 return ReadbackHandle::Invalid;
2907 if (capture_id_)
return ReadbackHandle::Invalid;
2908 capture_id_ = allocReadback(w, h);
2916void WebGPUDevice::publishCompletion(
void* userdata, WGPUMapAsyncStatus status) {
2917 std::unique_ptr<Ticket> ticket(
static_cast<Ticket*
>(userdata));
2918 ticket->result.status = status;
2919 std::lock_guard lock(ticket->mailbox->mutex);
2920 ticket->mailbox->ready.push_back(ticket->result);
2923WGPUBufferMapCallbackInfo WebGPUDevice::mapCallback(CompletionKind kind,
u32 id) {
2924 WGPUBufferMapCallbackInfo cb = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT;
2925 cb.mode = WGPUCallbackMode_AllowSpontaneous;
2926 cb.callback = [](WGPUMapAsyncStatus status, WGPUStringView,
void* data,
void*) {
2927 publishCompletion(data, status);
2929 cb.userdata1 =
new Ticket{mailbox_, {kind,
id}};
2933void WebGPUDevice::drainCompletions() {
2934 if (!mailbox_)
return;
2935 std::vector<Completion> ready;
2937 std::lock_guard lock(mailbox_->mutex);
2938 ready.swap(mailbox_->ready);
2940 for (
const auto& result : ready) {
2941 const u32 id =
static_cast<u32>(result.id);
2942 switch (result.kind) {
2943 case CompletionKind::Frame: frames_done_ = std::max(frames_done_, result.id);
break;
2944 case CompletionKind::Readback: onReadbackMapped(result.status,
id);
break;
2945 case CompletionKind::PassTime: onPassTimeMapped(result.status,
id);
break;
2946 case CompletionKind::GpuTime: onGpuTimeMapped(result.status,
id);
break;
2951void WebGPUDevice::onReadbackMapped(WGPUMapAsyncStatus status, u32
id) {
2952 auto it = readbacks_.find(
id);
2953 if (it == readbacks_.end())
return;
2954 it->second.status = (status == WGPUMapAsyncStatus_Success) ? GfxReadbackStatus::Ready
2958void WebGPUDevice::releaseReadback(u32
id) {
2959 auto it = readbacks_.find(
id);
2960 if (it == readbacks_.end())
return;
2961 WGPUBuffer buffer = it->second.buffer;
2964 readbacks_.erase(it);
2965 if (buffer) wgpuBufferRelease(buffer);
2968ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u32 h) {
2969 if (!isDeviceUsable())
return ReadbackHandle::Invalid;
2970 if (!device_ || w == 0 || h == 0)
return ReadbackHandle::Invalid;
2972 ES_LOG_ERROR(
"WebGPUDevice::requestReadback: must be called outside a render pass");
2973 return ReadbackHandle::Invalid;
2975 if (target == FramebufferHandle::Default) {
2979 stubOnce(
"requestReadback(default framebuffer) — use captureNextFrame");
2980 return ReadbackHandle::Invalid;
2982 const FramebufferDesc* fb = framebufferDesc(target);
2983 if (!fb)
return ReadbackHandle::Invalid;
2984 auto tit = textures_.find(
static_cast<u32>(fb->color0));
2985 if (tit == textures_.end() || !tit->second.texture)
return ReadbackHandle::Invalid;
2987 const u32 id = allocReadback(w, h);
2988 if (!
id)
return ReadbackHandle::Invalid;
2989 submitReadbackCopy(
id, tit->second.texture);
2996u32 WebGPUDevice::allocReadback(u32 w, u32 h) {
2999 const u32 padded = (w * 4u + 255u) & ~255u;
3000 WGPUBufferDescriptor bd{};
3001 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
3002 bd.size =
static_cast<u64>(padded) * h;
3003 WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
3004 if (!buffer)
return 0;
3005 const u32 id = next_readback_id_++;
3010void WebGPUDevice::encodeReadbackCopy(WGPUCommandEncoder encoder, u32
id, WGPUTexture source) {
3011 auto it = readbacks_.find(
id);
3012 if (it == readbacks_.end() || !source || !encoder)
return;
3013 ReadbackRec& rec = it->second;
3015 WGPUTexelCopyTextureInfo src = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT;
3016 src.texture = source;
3017 WGPUTexelCopyBufferInfo dst = WGPU_TEXEL_COPY_BUFFER_INFO_INIT;
3018 dst.buffer = rec.buffer;
3019 dst.layout.offset = 0;
3020 dst.layout.bytesPerRow = rec.paddedBytesPerRow;
3021 dst.layout.rowsPerImage = rec.height;
3022 WGPUExtent3D size{rec.width, rec.height, 1};
3023 wgpuCommandEncoderCopyTextureToBuffer(encoder, &src, &dst, &size);
3026void WebGPUDevice::mapReadback(u32
id) {
3027 auto it = readbacks_.find(
id);
3028 if (it == readbacks_.end())
return;
3029 ReadbackRec& rec = it->second;
3030 auto cb = mapCallback(CompletionKind::Readback,
id);
3031 wgpuBufferMapAsync(rec.buffer, WGPUMapMode_Read, 0,
3032 static_cast<u64
>(rec.paddedBytesPerRow) * rec.height, cb);
3035void WebGPUDevice::submitReadbackCopy(u32
id, WGPUTexture source) {
3036 if (readbacks_.find(
id) == readbacks_.end() || !source)
return;
3037 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
3038 encodeReadbackCopy(encoder,
id, source);
3039 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder,
nullptr);
3040 wgpuCommandEncoderRelease(encoder);
3041 wgpuQueueSubmit(queue_, 1, &commands);
3042 wgpuCommandBufferRelease(commands);
3049 if (instance_) wgpuInstanceProcessEvents(instance_);
3051 auto it = readbacks_.find(
static_cast<u32>(handle));
3052 if (it == readbacks_.end())
return GfxReadbackStatus::Failed;
3053 if (it->second.status == GfxReadbackStatus::Failed) {
3054 releaseReadback(
static_cast<u32>(handle));
3057 return it->second.status;
3060bool WebGPUDevice::takeReadback(ReadbackHandle handle,
void* dest, usize destSize) {
3062 auto it = readbacks_.find(
static_cast<u32
>(handle));
3063 if (it == readbacks_.end() || it->second.status != GfxReadbackStatus::Ready)
return false;
3064 ReadbackRec& rec = it->second;
3067 if (destSize < rec.tightBytes)
return false;
3068 const auto* mapped =
static_cast<const u8*
>(
3069 wgpuBufferGetConstMappedRange(rec.buffer, 0,
static_cast<u64
>(rec.paddedBytesPerRow) * rec.height));
3071 releaseReadback(
static_cast<u32
>(handle));
3074 auto* out =
static_cast<u8*
>(dest);
3075 const u32 rowBytes = rec.width * rec.bytesPerTexel;
3076 for (u32 row = 0; row < rec.height; ++row) {
3077 std::memcpy(out +
static_cast<usize>(row) * rowBytes, mapped +
static_cast<usize>(row) * rec.paddedBytesPerRow, rowBytes);
3079 wgpuBufferUnmap(rec.buffer);
3080 releaseReadback(
static_cast<u32>(handle));
3083 const usize tight =
static_cast<usize>(rec.width) * rec.height * 4;
3084 if (destSize < tight)
return false;
3085 const auto* mapped =
static_cast<const u8*
>(
3086 wgpuBufferGetConstMappedRange(rec.buffer, 0,
static_cast<u64>(rec.paddedBytesPerRow) * rec.height));
3088 releaseReadback(
static_cast<u32>(handle));
3092 auto* out =
static_cast<u8*
>(dest);
3093 const u32 rowBytes = rec.width * 4u;
3094 for (
u32 row = 0; row < rec.height; ++row) {
3095 std::memcpy(out +
static_cast<usize>(row) * rowBytes,
3096 mapped +
static_cast<usize>(row) * rec.paddedBytesPerRow, rowBytes);
3098 wgpuBufferUnmap(rec.buffer);
3099 releaseReadback(
static_cast<u32>(handle));
3103void WebGPUDevice::discardReadback(ReadbackHandle handle) {
3104 releaseReadback(
static_cast<u32
>(handle));
3111void WebGPUDevice::ensureTimestamps() {
3112 if (timestamp_init_done_)
return;
3113 timestamp_init_done_ =
true;
3114 if (!device_ || !wgpuDeviceHasFeature(device_, WGPUFeatureName_TimestampQuery))
return;
3116 WGPUQuerySetDescriptor qd{};
3117 qd.type = WGPUQueryType_Timestamp;
3119 timestamp_qset_ = wgpuDeviceCreateQuerySet(device_, &qd);
3120 if (!timestamp_qset_)
return;
3122 WGPUBufferDescriptor rd{};
3123 rd.usage = WGPUBufferUsage_QueryResolve | WGPUBufferUsage_CopySrc;
3125 timestamp_resolve_ = wgpuDeviceCreateBuffer(device_, &rd);
3126 for (u32 i = 0; i < kGpuTimeRing; ++i) {
3127 WGPUBufferDescriptor bd{};
3128 bd.usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst;
3129 bd.size = 16 * kSpanPasses;
3130 gpu_time_ring_[i].buf = wgpuDeviceCreateBuffer(device_, &bd);
3132 timestamp_supported_ = timestamp_resolve_ && gpu_time_ring_[0].buf;
3137bool WebGPUDevice::backendCreateTimerQuery(u32) {
3139 return timestamp_supported_;
3144void WebGPUDevice::beginTimerQuery(u32) {
3145 if (!timestamp_supported_)
return;
3146 span_closing_ =
false;
3147 span_slot_ = kGpuTimeRing;
3149 for (u32 i = 0; i < kGpuTimeRing; ++i) {
3150 const u32 s = (gpu_time_next_ + i) % kGpuTimeRing;
3151 if (!gpu_time_ring_[s].pending) {
3153 gpu_time_next_ = (s + 1) % kGpuTimeRing;
3160 parallel_span_ = asyncComputeEnabled() && supportsAsyncCompute();
3161 if (parallel_span_ && span_slot_ < kGpuTimeRing) stampParallelSpan(
false);
3164void WebGPUDevice::stampParallelSpan(
bool end) {
3165 if (!clock_pipeline_) {
3166 WGPUShaderSourceWGSL code{};
3167 code.chain.sType = WGPUSType_ShaderSourceWGSL;
3168 code.code = sv(
"@compute @workgroup_size(1) fn main() {}");
3169 WGPUShaderModuleDescriptor md{};
3170 md.nextInChain = &code.chain;
3171 auto module = wgpuDeviceCreateShaderModule(device_, &md);
3172 WGPUComputePipelineDescriptor pd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT;
3173 pd.compute.module =
module;
3174 pd.compute.entryPoint = sv(
"main");
3175 clock_pipeline_ = wgpuDeviceCreateComputePipeline(device_, &pd);
3176 wgpuShaderModuleRelease(module);
3178 if (!clock_pipeline_)
return;
3179 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
3180 WGPUPassTimestampWrites time{};
3181 time.querySet = timestamp_qset_;
3182 time.beginningOfPassWriteIndex = 0;
3183 time.endOfPassWriteIndex = 1;
3184 WGPUComputePassDescriptor pd{};
3185 pd.timestampWrites = &time;
3186 auto pass = wgpuCommandEncoderBeginComputePass(encoder, &pd);
3187 wgpuComputePassEncoderSetPipeline(pass, clock_pipeline_);
3188 wgpuComputePassEncoderDispatchWorkgroups(pass, 1, 1, 1);
3189 wgpuComputePassEncoderEnd(pass);
3190 wgpuComputePassEncoderRelease(pass);
3191 wgpuCommandEncoderResolveQuerySet(encoder, timestamp_qset_, 0, 2, timestamp_resolve_, 0);
3192 const u64 offset = end ?
sizeof(
u64) : 0;
3193 wgpuCommandEncoderCopyBufferToBuffer(encoder, timestamp_resolve_, offset, gpu_time_ring_[span_slot_].buf, offset,
sizeof(
u64));
3194 if (end) span_passes_ = 1;
3195 auto commands = wgpuCommandEncoderFinish(encoder,
nullptr);
3196 wgpuCommandEncoderRelease(encoder);
3197 wgpuQueueSubmit(queue_, 1, &commands);
3198 wgpuCommandBufferRelease(commands);
3202 if (!span_open_)
return;
3205 if (pass_) span_closing_ =
true;
3209bool WebGPUDevice::spanTakesPass()
const {
3210 return timestamp_supported_ && span_open_ && !parallel_span_ && span_slot_ < kGpuTimeRing && span_passes_ < kSpanPasses;
3213void WebGPUDevice::resolveSpanPass(WGPUCommandEncoder encoder) {
3214 wgpuCommandEncoderResolveQuerySet(encoder, timestamp_qset_, 0, 2, timestamp_resolve_, 0);
3215 wgpuCommandEncoderCopyBufferToBuffer(encoder, timestamp_resolve_, 0,
3216 gpu_time_ring_[span_slot_].buf, 16ull * span_passes_, 16);
3220void WebGPUDevice::finishSpan() {
3222 if (parallel_span_) {
3223 parallel_span_ =
false;
3224 manualComputeBarrier();
3225 if (span_slot_ < kGpuTimeRing && isDeviceUsable()) stampParallelSpan(
true);
3227 const u32 slot = span_slot_;
3228 const u32 passes = span_passes_;
3229 span_slot_ = kGpuTimeRing;
3231 if (!timestamp_supported_)
return;
3232 if (slot >= kGpuTimeRing || passes == 0) {
3233 if (gpu_time_results_.size() < 16) gpu_time_results_.push_back(0);
3237 gpu_time_ring_[slot].pending =
true;
3238 gpu_time_ring_[slot].passes = passes;
3239 auto cb = mapCallback(CompletionKind::GpuTime, slot);
3240 wgpuBufferMapAsync(gpu_time_ring_[slot].buf, WGPUMapMode_Read, 0, 16ull * passes, cb);
3242bool WebGPUDevice::timerDisjoint() {
return false; }
3244bool WebGPUDevice::getTimerQueryNs(u32 query, u64* outNs) {
3246 if (pass_time_tags_.count(query)) {
3247 const auto it = pass_time_results_.find(query);
3248 if (it == pass_time_results_.end())
return false;
3249 if (outNs) *outNs = it->second;
3250 pass_time_results_.erase(it);
3253 if (gpu_time_results_.empty())
return false;
3254 if (outNs) *outNs = gpu_time_results_.front();
3255 gpu_time_results_.erase(gpu_time_results_.begin());
3259void WebGPUDevice::armPassTimer(u32 query) {
3260 armed_pass_tag_ = timestamp_supported_ ? query : 0;
3261 if (armed_pass_tag_) pass_time_tags_.insert(armed_pass_tag_);
3264u32 WebGPUDevice::takePassTimeSlot() {
3265 const u32 tag = armed_pass_tag_;
3266 armed_pass_tag_ = 0;
3267 if (!tag || !timestamp_supported_)
return kNoPassSlot;
3268 u32 slot = kNoPassSlot;
3269 for (u32 i = 0; i < pass_time_pool_.size(); ++i) {
3270 if (!pass_time_pool_[i].pending) { slot = i;
break; }
3272 if (slot == kNoPassSlot) {
3273 if (pass_time_pool_.size() >= kPassTimePool)
return kNoPassSlot;
3274 WGPUBufferDescriptor bd{};
3275 bd.usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst;
3278 fresh.buf = wgpuDeviceCreateBuffer(device_, &bd);
3279 if (!fresh.buf)
return kNoPassSlot;
3280 pass_time_pool_.push_back(fresh);
3281 slot =
static_cast<u32>(pass_time_pool_.size() - 1);
3283 pass_time_pool_[slot].tag = tag;
3287void WebGPUDevice::resolvePassTime(WGPUCommandEncoder encoder, u32 slot) {
3288 wgpuCommandEncoderResolveQuerySet(encoder, timestamp_qset_, 0, 2, timestamp_resolve_, 0);
3289 wgpuCommandEncoderCopyBufferToBuffer(encoder, timestamp_resolve_, 0, pass_time_pool_[slot].buf, 0, 16);
3292void WebGPUDevice::mapPassTime(
u32 slot) {
3293 pass_time_pool_[slot].pending =
true;
3294 auto cb = mapCallback(CompletionKind::PassTime, slot);
3295 wgpuBufferMapAsync(pass_time_pool_[slot].buf, WGPUMapMode_Read, 0, 16, cb);
3298void WebGPUDevice::onPassTimeMapped(WGPUMapAsyncStatus status,
u32 slot) {
3299 if (slot >= pass_time_pool_.size())
return;
3300 PassTimeSlot& ps = pass_time_pool_[slot];
3301 if (status == WGPUMapAsyncStatus_Success && ps.buf) {
3302 const auto* ts =
static_cast<const u64*
>(wgpuBufferGetConstMappedRange(ps.buf, 0, 16));
3303 if (ts && ts[1] >= ts[0]) pass_time_results_[ps.tag] = ts[1] - ts[0];
3304 wgpuBufferUnmap(ps.buf);
3309void WebGPUDevice::onGpuTimeMapped(WGPUMapAsyncStatus status, u32 slot) {
3310 if (slot >= kGpuTimeRing)
return;
3311 WGPUBuffer buf = gpu_time_ring_[slot].buf;
3312 const u32 passes = gpu_time_ring_[slot].passes;
3313 if (status == WGPUMapAsyncStatus_Success && buf) {
3314 const auto* ts =
static_cast<const u64*
>(wgpuBufferGetConstMappedRange(buf, 0, 16ull * passes));
3317 for (u32 i = 0; ts && i < passes; ++i) {
3318 if (ts[2 * i + 1] >= ts[2 * i]) total += ts[2 * i + 1] - ts[2 * i];
3321 if (ts && gpu_time_results_.size() < 16) gpu_time_results_.push_back(total);
3322 wgpuBufferUnmap(buf);
3324 gpu_time_ring_[slot].pending =
false;
3327void WebGPUDevice::setWireframe(
bool) {}
3328u32 WebGPUDevice::getError() {
return 0; }
3330std::string WebGPUDevice::getString(GfxStringName name) {
3332 case GfxStringName::Renderer:
return "WebGPU (Dawn/emdawnwebgpu)";
3333 case GfxStringName::Vendor:
return "WebGPU";
3334 case GfxStringName::Version:
return "WebGPU 1.0";
3335 case GfxStringName::ShadingLanguageVersion:
return "WGSL";
3340i32 WebGPUDevice::getInt(GfxIntParam param) {
3342 case GfxIntParam::MaxTextureSize:
return 8192;
3343 case GfxIntParam::MaxTextureImageUnits:
return 16;
3344 case GfxIntParam::MaxVertexAttribs:
return 16;
3356u32 storageTexelBytes(WGPUTextureFormat format) {
3358 case WGPUTextureFormat_RGBA8Unorm:
3359 case WGPUTextureFormat_BGRA8Unorm:
3360 case WGPUTextureFormat_RGBA8UnormSrgb:
return 4;
3361 case WGPUTextureFormat_RGBA16Float:
return 8;
3362 case WGPUTextureFormat_RGBA32Float:
return 16;
3369bool WebGPUDevice::backendCreateCompute(u32
id,
const GfxComputeSource& source, std::string* outLog) {
3370 if (source.language != GfxShaderLanguage::WGSL || !source.source) {
3371 if (outLog) *outLog =
"WebGPUDevice compiles WGSL only";
3375 if (outLog) *outLog =
"no WGPUDevice";
3378 WGPUShaderSourceWGSL wgsl{};
3379 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
3380 wgsl.code = sv(source.source);
3381 WGPUShaderModuleDescriptor md{};
3382 md.nextInChain = &wgsl.chain;
3383 WGPUShaderModule module = wgpuDeviceCreateShaderModule(device_, &md);
3385 if (outLog) *outLog =
"shader module creation failed";
3389 rec.module =
module;
3390 rec.entry = source.entry && *source.entry ? source.entry :
"main";
3391 computes_[id] = std::move(rec);
3395void WebGPUDevice::backendDeleteCompute(u32
id) {
3396#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
3397 if (metal_compute_) metal_compute_->forgetProgram(
id);
3399 auto it = computes_.find(
id);
3400 if (it == computes_.end())
return;
3401 for (
auto& [key, pipeline] : it->second.pipelines) {
3402 if (pipeline) wgpuComputePipelineRelease(pipeline);
3404 if (it->second.module) wgpuShaderModuleRelease(it->second.module);
3405 computes_.erase(it);
3408bool WebGPUDevice::backendDispatchCompute(u32
id,
const GfxComputeBinding* bindings, u32 bindingCount,
3409 u32 groupsX, u32 groupsY, u32 groupsZ) {
3411 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: must be called outside a render pass");
3414 auto program = computes_.find(
id);
3415 if (program == computes_.end() || !program->second.module)
return false;
3416 if (groupsX > kMaxWorkgroupsPerDimension || groupsY > kMaxWorkgroupsPerDimension ||
3417 groupsZ > kMaxWorkgroupsPerDimension || bindingCount > kMaxComputeBindings) {
3418 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: {}x{}x{} groups with {} bindings is over the limit",
3419 groupsX, groupsY, groupsZ, bindingCount);
3423 WGPUBindGroupLayoutEntry layoutEntries[kMaxComputeBindings] = {};
3424 WGPUBindGroupEntry groupEntries[kMaxComputeBindings] = {};
3426 for (u32 i = 0; i < bindingCount; ++i) {
3427 const GfxComputeBinding& b = bindings[i];
3428 WGPUBindGroupLayoutEntry& le = layoutEntries[i];
3429 WGPUBindGroupEntry& ge = groupEntries[i];
3430 le.binding = ge.binding = b.binding;
3431 le.visibility = WGPUShaderStage_Compute;
3432 key += std::to_string(b.binding) +
"." + std::to_string(
static_cast<u32>(b.kind));
3434 case GfxComputeBinding::Kind::Uniform:
3435 case GfxComputeBinding::Kind::StorageRead:
3436 case GfxComputeBinding::Kind::Storage: {
3437 auto it = buffers_.find(
static_cast<u32>(b.buffer));
3438 if (it == buffers_.end() || !it->second.buffer) {
3439 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: binding {} names a buffer that is gone", b.binding);
3442 const bool uniform = b.kind == GfxComputeBinding::Kind::Uniform;
3443 if ((uniform && it->second.usage != GfxBufferUsage::Uniform) ||
3444 (!uniform && it->second.usage != GfxBufferUsage::Storage)) {
3445 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: binding {} is bound as {} but the buffer was not made for it",
3446 b.binding, uniform ?
"a uniform" :
"storage");
3449 le.buffer.type = uniform ? WGPUBufferBindingType_Uniform
3450 : b.kind == GfxComputeBinding::Kind::StorageRead ? WGPUBufferBindingType_ReadOnlyStorage
3451 : WGPUBufferBindingType_Storage;
3452 ge.buffer = it->second.buffer;
3453 ge.offset = b.offset;
3454 const u32 whole = webgpu::alignedWriteSize(it->second.size);
3455 ge.size = b.size ? b.size : (whole > b.offset ? whole - b.offset : 0);
3458 case GfxComputeBinding::Kind::Texture: {
3459 auto it = textures_.find(
static_cast<u32>(b.texture));
3460 if (it == textures_.end() || !it->second.texture) {
3461 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: binding {} names a texture that is gone", b.binding);
3464 const WGPUTextureFormat f = it->second.format;
3465 le.texture.sampleType = isDepthFormat(f) ? WGPUTextureSampleType_Depth
3466 : f == WGPUTextureFormat_RGBA32Float ? WGPUTextureSampleType_UnfilterableFloat
3467 : WGPUTextureSampleType_Float;
3468 le.texture.viewDimension = WGPUTextureViewDimension_2D;
3469 ge.textureView = it->second.sampleView;
3470 key +=
"." + std::to_string(
static_cast<u32>(le.texture.sampleType));
3473 case GfxComputeBinding::Kind::DepthTexture: {
3474 auto it = textures_.find(
static_cast<u32>(b.texture));
3475 const TextureRec* rec = (it != textures_.end() && it->second.texture && isDepthFormat(it->second.format)) ? &it->second :
nullptr;
3478 rec = &dummy_depth_texture_;
3480 le.texture.sampleType = WGPUTextureSampleType_Depth;
3481 le.texture.viewDimension = WGPUTextureViewDimension_2D;
3482 ge.textureView = rec->sampleView;
3485 case GfxComputeBinding::Kind::StorageTexture: {
3486 auto it = textures_.find(
static_cast<u32>(b.texture));
3487 if (it == textures_.end() || !it->second.texture) {
3488 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: binding {} names a texture that is gone", b.binding);
3491 if (!it->second.storage) {
3492 ES_LOG_ERROR(
"WebGPUDevice::dispatchCompute: binding {} is a storage texture but the texture was not made with storage", b.binding);
3495 le.storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
3496 le.storageTexture.format = it->second.format;
3497 le.storageTexture.viewDimension = WGPUTextureViewDimension_2D;
3498 ge.textureView = it->second.view;
3499 key +=
"." + std::to_string(
static_cast<u32>(it->second.format));
3502 case GfxComputeBinding::Kind::Sampler:
3503 le.sampler.type = WGPUSamplerBindingType_Filtering;
3504 ge.sampler = samplerFor(packSamplerKey(b.filter, b.filter, TextureWrap::ClampToEdge, TextureWrap::ClampToEdge));
3510 WGPUBindGroupLayout layout =
nullptr;
3511 auto cachedLayout = compute_layouts_.find(key);
3512 if (cachedLayout != compute_layouts_.end()) {
3513 layout = cachedLayout->second;
3515 WGPUBindGroupLayoutDescriptor bld{};
3516 bld.entryCount = bindingCount;
3517 bld.entries = layoutEntries;
3518 layout = wgpuDeviceCreateBindGroupLayout(device_, &bld);
3519 compute_layouts_[key] = layout;
3521 if (!layout)
return false;
3523 WGPUPipelineLayout pipelineLayout =
nullptr;
3524 auto cachedPipelineLayout = compute_pipeline_layouts_.find(key);
3525 if (cachedPipelineLayout != compute_pipeline_layouts_.end()) {
3526 pipelineLayout = cachedPipelineLayout->second;
3528 WGPUPipelineLayoutDescriptor pld{};
3529 pld.bindGroupLayoutCount = 1;
3530 pld.bindGroupLayouts = &layout;
3531 pipelineLayout = wgpuDeviceCreatePipelineLayout(device_, &pld);
3532 compute_pipeline_layouts_[key] = pipelineLayout;
3534 if (!pipelineLayout)
return false;
3536 WGPUComputePipeline pipeline =
nullptr;
3537 auto cachedPipeline = program->second.pipelines.find(key);
3538 if (cachedPipeline != program->second.pipelines.end()) {
3539 pipeline = cachedPipeline->second;
3541 WGPUComputePipelineDescriptor cpd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT;
3542 cpd.layout = pipelineLayout;
3543 cpd.compute.module = program->second.module;
3544 cpd.compute.entryPoint = sv(program->second.entry.c_str());
3545 pipeline = wgpuDeviceCreateComputePipeline(device_, &cpd);
3546 program->second.pipelines[key] = pipeline;
3548 if (!pipeline)
return false;
3550 WGPUBindGroupDescriptor bgd{};
3551 bgd.layout = layout;
3552 bgd.entryCount = bindingCount;
3553 bgd.entries = groupEntries;
3554 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
3555 if (!group)
return false;
3557 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
3558 WGPUComputePassDescriptor pd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT;
3559 const u32 passSlot = takePassTimeSlot();
3562 const bool inSpan = passSlot == kNoPassSlot && spanTakesPass();
3563 WGPUPassTimestampWrites tw{};
3564 if (passSlot != kNoPassSlot || inSpan) {
3565 tw.querySet = timestamp_qset_;
3566 tw.beginningOfPassWriteIndex = 0;
3567 tw.endOfPassWriteIndex = 1;
3568 pd.timestampWrites = &tw;
3570 WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(encoder, &pd);
3571 wgpuComputePassEncoderSetPipeline(pass, pipeline);
3572 wgpuComputePassEncoderSetBindGroup(pass, 0, group, 0,
nullptr);
3573 wgpuComputePassEncoderDispatchWorkgroups(pass, groupsX, groupsY, groupsZ);
3574 wgpuComputePassEncoderEnd(pass);
3575 wgpuComputePassEncoderRelease(pass);
3576 if (passSlot != kNoPassSlot) resolvePassTime(encoder, passSlot);
3577 if (inSpan) resolveSpanPass(encoder);
3578 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder,
nullptr);
3579 wgpuCommandEncoderRelease(encoder);
3580 wgpuQueueSubmit(queue_, 1, &commands);
3581 wgpuCommandBufferRelease(commands);
3582 if (passSlot != kNoPassSlot) mapPassTime(passSlot);
3583 wgpuBindGroupRelease(group);
3587u32 WebGPUDevice::allocRawReadback(
u32 w,
u32 h,
u32 bytesPerTexel,
u32 tightBytes) {
3589 const u32 padded = (h > 1 || bytesPerTexel != 1) ? ((w * bytesPerTexel + 255u) & ~255u) : tightBytes;
3590 WGPUBufferDescriptor bd{};
3591 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
3592 bd.size =
static_cast<u64
>(padded) * h;
3593 WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
3594 if (!buffer)
return 0;
3595 const u32
id = next_readback_id_++;
3596 ReadbackRec rec{buffer, w, h, padded, GfxReadbackStatus::Pending};
3598 rec.bytesPerTexel = bytesPerTexel;
3599 rec.tightBytes = tightBytes;
3600 readbacks_[id] = rec;
3604ReadbackHandle WebGPUDevice::requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
3605 if (!isDeviceUsable() || !device_ || sizeBytes == 0 || (offsetBytes & 3u) || (sizeBytes & 3u)) {
3606 return ReadbackHandle::Invalid;
3609 ES_LOG_ERROR(
"WebGPUDevice::requestBufferReadback: must be called outside a render pass");
3610 return ReadbackHandle::Invalid;
3612 auto it = buffers_.find(
static_cast<u32>(buffer));
3613 if (it == buffers_.end() || !it->second.buffer || it->second.usage != GfxBufferUsage::Storage ||
3614 static_cast<u64>(offsetBytes) + sizeBytes > webgpu::alignedWriteSize(it->second.size)) {
3615 return ReadbackHandle::Invalid;
3618 const u32 id = allocRawReadback(sizeBytes, 1, 1, sizeBytes);
3619 if (!
id)
return ReadbackHandle::Invalid;
3620 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_,
nullptr);
3621 wgpuCommandEncoderCopyBufferToBuffer(encoder, it->second.buffer, offsetBytes, readbacks_[
id].buffer, 0, sizeBytes);
3622 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder,
nullptr);
3623 wgpuCommandEncoderRelease(encoder);
3624 wgpuQueueSubmit(queue_, 1, &commands);
3625 wgpuCommandBufferRelease(commands);
3630ReadbackHandle WebGPUDevice::requestTextureReadback(TextureHandle texture) {
3631 if (!isDeviceUsable() || !device_)
return ReadbackHandle::Invalid;
3633 ES_LOG_ERROR(
"WebGPUDevice::requestTextureReadback: must be called outside a render pass");
3634 return ReadbackHandle::Invalid;
3636 auto it = textures_.find(
static_cast<u32>(texture));
3637 if (it == textures_.end() || !it->second.texture || it->second.samples > 1)
return ReadbackHandle::Invalid;
3638 const u32 bpt = storageTexelBytes(it->second.format);
3639 if (bpt == 0)
return ReadbackHandle::Invalid;
3640 const u32 w = it->second.width, h = it->second.height;
3641 const u32 id = allocRawReadback(w, h, bpt, w * h * bpt);
3642 if (!
id)
return ReadbackHandle::Invalid;
3643 submitReadbackCopy(
id, it->second.texture);
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
#define ES_LOG_ERROR(...)
Logs an error message.
Row arithmetic shared by the backends' texture uploads.
WebGPU (Dawn / emdawnwebgpu) backend for GfxDevice (REARCH_WGSL Phase 2).
Pure RHI-enum → WebGPU translations (REARCH_WGSL Phase 2).
bool markDeviceLost(GfxDeviceLostReason reason, std::string message={}, std::string context={})
The single transition into Lost. Backends call this on detection.
Viewport viewport_
Backends record what they were last handed; see viewport.
virtual void backendSetAsyncComputeEnabled(bool)
bool asyncComputeEnabled() const
bool isDeviceUsable() const
Whether work may be submitted — the one check the guards make.
void manualComputeBarrier()
Order dispatches across queues. Each inline dispatch is already a complete compute pass.
void setDeviceIdentity(std::string backend, std::string vendor, std::string renderer, std::string version)
Records the backend identity; see captureDeviceIdentity.
void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override
Binds a vertex buffer to a layout slot for subsequent draws.
void bindTexture(u32 slot, TextureHandle texture) override
Activates a texture slot and binds a 2D texture.
void setIndexBuffer(BufferHandle buffer) override
Binds the index buffer for subsequent indexed draws.
void clearStencil(i32 value) override
Mid-pass stencil reset (the one clear that isn't a pass load-op).
void endFrame() override
The frame is over — everything drawn for it has been submitted.
static u32 colorVariantOf(WGPUTextureFormat format)
Which variant slot a pass's colour format uses. Beside the enum because the two are one decision: a f...
void setScissorTest(bool enabled) override
Enables or disables scissor test.
WebGPUDevice(WGPUDevice device=nullptr, WGPUInstance instance=nullptr, WGPUAdapter adapter=nullptr)
device may be null for bookkeeping-only use (tests, bring-up).
void backendDeleteTexture(u32 id) override
void captureDeviceIdentity() override
Records who this backend is, so a later loss report can name it.
void endRenderPass() override
Ends the current pass, restoring the default framebuffer.
void setViewport(i32 x, i32 y, u32 w, u32 h) override
Sets the rendering viewport.
void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY) override
void backendSetPipeline(u32 id, const PipelineDesc &desc) override
bool configureSurface(const NativeSurface &window, u32 width, u32 height)
Binds a native window as the render target; shares configureSwapchain with the web path....
void init() override
Initializes the graphics device.
void endTimerQuery() override
Stops the active timer query.
void backendResizeBuffer(u32 id, const BufferDesc &desc, const void *data) override
static constexpr u32 kMsaaSamples
The multisampled count this backend offers. WebGPU guarantees 1 and 4 for every renderable format; no...
static GfxDeviceLostReason reasonFromWgpu(u32 wgpuReason)
Maps a WGPUDeviceLostReason to the backend-neutral reason.
void backendDeleteProgram(u32 id) override
u64 estimatedGpuBytes() const override
bool backendCreateTexture(u32 id, const TextureDesc &desc, const void *pixels) override
void reportUncapturedError(u32 wgpuErrorType, const char *message)
Routes the device's uncaptured-error callback; only fatal kinds become losses.
bool backendCreateBuffer(u32 id, const BufferDesc &desc, const void *data) override
bool recreateDevice() override
Backend half of recoverDevice: a working device again, with every id-to-native map and derived cache ...
bool surfaceBytesAreBGRA() const
Whether bytes read back from the DEFAULT framebuffer are BGRA rather than RGBA.
void backendDeleteBuffer(u32 id) override
void backendUpdateBuffer(u32 id, u32 offsetBytes, const void *data, u32 sizeBytes) override
u32 maxSamples() override
Most samples an offscreen colour attachment may carry; 1 = none.
void backendMoveTexture(u32 into, u32 from) override
Re-keys from's native texture under into; into holds none on entry.
void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override
bool backendCreateProgram(u32 id, const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage) override
std::string getString(GfxStringName name) override
Queries a backend identification string (diagnostics).
void present()
Flips the swapchain to the display. The web path relies on the browser presenting the canvas after th...
void backendGenerateMipmaps(u32 id) override
void setScissor(i32 x, i32 y, i32 w, i32 h) override
Sets the scissor rectangle.
void resizeBackbuffer(u32 width, u32 height) override
Resizes the default backbuffer to the viewport size.
bool backendAcceptsVertexLayout(const VertexLayoutDesc &desc) override
False for a layout this backend has no way to express.
bool backendCreateCompressedTexture(u32 id, const TextureDesc &desc, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels) override
void setStencilReference(i32 reference) override
WebGPU stores a texture from the top down.
u32 validation_errors_logged_
Validation errors said so far (reportUncapturedError says the first few).
bool supportsCompressedFormat(GfxCompressedFormat format) override
Reports whether the backend can sample the given compressed format.
void backendSetTextureParams(u32 id, const TextureDesc &desc) override
bool pollDeviceLost() override
Pumps backend-native loss detection.
void drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) override
Draws indexed triangles.
void shutdown() override
Shuts down the graphics device.
constexpr u64 fnv1aWord(u64 h, u64 word)
constexpr u64 kFnv64Offset
bool writeFitsInBuffer(u32 offset, u32 size, u32 capacity)
WGPUVertexFormat toWGPUVertexFormat(u8 components, GfxDataType type, bool normalized)
Maps one RHI attribute (components × type × normalized) to a WGPUVertexFormat, or kInvalidVertexForma...
u64 scanWGSLVolumeTextureMask(const char *source, u32 group)
Bit mask of the group's bindings a WGSL source declares as texture_3d.
WGPUDepthStencilState toWGPUDepthStencil(const PipelineDesc &desc, WGPUTextureFormat format)
A pipeline's full depth-stencil state against a pass attachment format.
u32 wgpuBytesPerPixel(GfxPixelFormat fmt)
WGPUIndexFormat toWGPUIndexFormat(GfxDataType type)
Index type for drawElements' GfxDataType.
bool hasStencilPlanes(WGPUTextureFormat format)
True when a depth-stencil format carries stencil planes (drives whether a pass may set stencil load/s...
bool needsWriteStaging(u32 size)
BlendStateWGPU toWGPUBlend(BlendMode mode, bool layerAlpha=false)
Maps BlendMode to its WebGPU blend components — mirrors GLDevice's setBlendMode table (Overlay render...
WGPUFeatureName compressionFeatureFor(GfxCompressedFormat fmt)
constexpr WGPUVertexFormat kInvalidVertexFormat
Sentinel for "no WGPU spelling": the header defines no Undefined vertex format, so the enum's non-val...
u64 scanWGSLArrayTextureMask(const char *source, u32 group)
Bit mask of the group's bindings a WGSL source declares as texture_2d_array.
constexpr u32 kGroup1TextureUnits
Texture units the group-1 convention spans — see WGSL_MAX_TEXTURE_UNITS.
WGPUCullMode toWGPUCullMode(bool enabled, bool front)
Cull state (PipelineDesc.cullEnabled/cullFront). Front face is CCW, matching the GL backend's default...
WGPUColor toWGPUClearColor(const RenderPassDesc &desc)
WGPUBufferUsage toWGPUBufferUsage(GfxBufferUsage usage)
WGPUTextureFormat toWGPUTextureFormat(GfxPixelFormat fmt)
WGPULoadOp toWGPULoadOp(bool clearRequested, bool scoped)
WGPUTextureFormat toWGPUCompressedFormat(GfxCompressedFormat fmt)
u64 scanWGSLDepthTextureMask(const char *source, u32 group)
Bit mask of the group's bindings a WGSL source declares as DEPTH textures.
u32 alignedWriteSize(u32 size)
std::int32_t i32
Signed 32-bit integer.
u64 scanWGSLBindingMask(const char *source, u32 group)
Bit mask of the @group(N) @binding(i) indices a WGSL source declares.
bool writesStencil(GfxStencilMode mode)
constexpr u32 samplerBindingForUnit(u32 unit)
Group-1 binding of a texture unit's sampler (see textureBindingForUnit).
std::uint64_t u64
Unsigned 64-bit integer.
constexpr u32 textureBindingForUnit(u32 unit)
Group-1 binding of a texture unit. Units 0-7 are the batch stream and take bindings 0-7; a material's...
void scanWGSLReachedUnits(const char *source, u32 &textures, u32 &samplers)
The tN / sN names a WGSL source REACHES, by unit.
GfxDeviceLostReason
Why the device was lost. The report leads with this.
@ Destroyed
We destroyed it. A loss report that is not a failure.
@ Internal
The backend failed inside itself and said no more than that.
@ OutOfMemory
An allocation the backend could not satisfy.
std::size_t usize
Size type for indexing and sizes.
void stageTextureRows(u8 *dst, const u8 *src, u32 width, u32 height, u32 srcBpp, u32 dstBpp, bool reverseRows)
@ Nearest
No interpolation (pixelated look).
GfxShaderStage
Which pipeline stage rejected a program during createProgram().
PipelineHandle
Opaque handle to a cached pipeline; PipelineHandle{0} is the null/invalid handle.
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
@ ETC2_RGBA8_SRGB
GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC (core).
@ S3TC_DXT5
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT (extension).
@ ETC2_RGB8
GL_COMPRESSED_RGB8_ETC2 (core).
@ S3TC_DXT5_SRGB
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT (extension).
@ ASTC_8x8
GL_COMPRESSED_RGBA_ASTC_8x8_KHR (extension).
@ S3TC_DXT1
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT (extension).
@ ASTC_4x4_SRGB
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR (extension).
@ ETC2_RGBA8
GL_COMPRESSED_RGBA8_ETC2_EAC (core).
@ ASTC_4x4
GL_COMPRESSED_RGBA_ASTC_4x4_KHR (extension).
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
std::uint32_t u32
Unsigned 32-bit integer.
std::uint8_t u8
Unsigned 8-bit integer.
static bool isSrgbFormat(WGPUTextureFormat f)
u32 gfxBytesPerPixel(GfxPixelFormat fmt)
Bytes one pixel occupies in the CALLER's upload buffer — the single source both backends size a read ...
GfxBlockInfo gfxCompressedBlockInfo(GfxCompressedFormat fmt)
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
float f32
32-bit floating point
Immutable creation parameters of a GPU buffer.
Vertex attribute location binding applied before a program is linked.
Block footprint of a compressed format, the single source both backends use to size each mip level's ...
A program's source pair, tagged with the language it is written in.
GfxShaderLanguage language
Immutable description of a draw pipeline. Equality keys the pipeline cache, so two draws with the sam...
Immutable creation parameters of a 2D texture or 2D texture array.
Describes how vertex-buffer bytes map to shader attributes.
GfxVertexAttribute attributes[MAX_VERTEX_ATTRIBUTES]