载入中...
搜索中...
未找到
Graphics.cpp
浏览该文件的文档.
4#include "graphics/Batcher.h"
7#include "graphics/GBuffer.h"
9#include "graphics/Light.h"
10#include "graphics/Mesh.h"
15#include "graphics/Shader.h"
16#include "graphics/Shadow.h"
17#include "graphics/Texture.h"
25
26#include "common/Exception.h"
27#include "common/Resource.h"
28#include "common/config.h"
29#include "filesystem/FileData.h"
31#include "image/Image.h"
32#include "image/ImageData.h"
33
34// Header-only Assimp mesh types for newMeshFromAssimp. The Assimp library is
35// not linked on Emscripten; only these POD headers are required here.
36#include <assimp/matrix3x3.h>
37#include <assimp/matrix4x4.h>
38#include <assimp/mesh.h>
39#include <assimp/vector3.h>
40
41#include <algorithm>
42#include <bit>
43#include <cmath>
44#include <cstdio>
45#include <cstring>
46#include <fstream>
47#include <limits>
48#include <map>
49#include <memory>
50#include <mutex>
51#include <vector>
52
53#include <glm/gtc/constants.hpp>
54
55#include <SDL2/SDL.h>
56#include <SDL2/SDL_syswm.h>
57// SDL's native X11 declarations define Success, which collides with WebGPU enums.
58#ifdef Success
59#undef Success
60#endif
61#if defined(__APPLE__) && !defined(__EMSCRIPTEN__)
62#include <objc/message.h>
63#include <objc/runtime.h>
64#endif
65
66#if defined(_WIN32)
67#include <windows.h>
68#endif
69
70#if defined(__EMSCRIPTEN__)
71#include <emscripten/emscripten.h>
72#endif
73
75
76namespace eve::graphics::webgpu {
77using namespace detail;
78
81 caps.backend = "webgpu";
82 frameCaptures().configure(std::move(caps));
83 for (uint32_t i = 0; i < kFramesInFlight; ++i) {
84 uboArenas.emplace_back();
85 vertexArenas.emplace_back();
86 }
87}
88
90 destroyDeferredLightingResources();
93}
94
95// ---------------------------------------------------------------------------
96// Init
97// ---------------------------------------------------------------------------
98
100 if (deviceInitDone) {
101 if (headless_) {
103 return;
104 }
105 throw Exception("Graphics::initHeadless: already initialized with a window");
106 }
107 if (width <= 0 || height <= 0) throw Exception("Graphics::initHeadless: invalid size");
108
109 auto inst = InitFlow::createInstance();
110 auto adp = InitFlow::requestAdapter(std::move(inst), surface);
111 auto dev = InitFlow::requestDevice(std::move(adp));
112 initHeadlessFromDevice(width, height, std::move(dev));
113}
114
116 if (deviceInitDone || width <= 0 || height <= 0 || !dev.instance || !dev.adapter || !dev.device || !dev.queue)
117 throw Exception("Graphics::initHeadlessFromDevice: invalid size, device stage, or initialization state");
118 dev.caps.capture(dev.adapter, dev.device);
119
120 instance = std::move(dev.instance);
121 adapter = std::move(dev.adapter);
122 device = std::move(dev.device);
123 queue = std::move(dev.queue);
124 caps = std::move(dev.caps);
125 surfaceFormat = WGPUTextureFormat_BGRA8Unorm;
126
127 createPipelineResources();
128 createShadowResources();
129 createDefaultTextures();
131 createSceneColorResources(width, height);
132 headless_ = true;
133 initialized = true;
134 deviceInitDone = true;
135}
136
137void Graphics::initWithWindow(void* nativeWindow) {
138 sdlWindow = nativeWindow;
139 if (deviceInitDone) return;
140
141 auto inst = InitFlow::createInstance();
142
143 // ---- Surface ----
144 WGPUSurfaceDescriptor surfDesc{};
145 surfDesc.label = sv("eve_surface");
146#if defined(__EMSCRIPTEN__)
147 WGPUEmscriptenSurfaceSourceCanvasHTMLSelector canvasSel{};
148 canvasSel.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
149 canvasSel.selector = sv("#canvas");
150 surfDesc.nextInChain = &canvasSel.chain;
151 surface = inst.instance.CreateSurface(reinterpret_cast<const wgpu::SurfaceDescriptor*>(&surfDesc));
152 surfaceFormat = WGPUTextureFormat_BGRA8Unorm;
153#else
154 wgpu::SurfaceDescriptor nativeSurfDesc{};
155 nativeSurfDesc.label = "eve_surface";
156 SDL_SysWMinfo wminfo;
157 SDL_VERSION(&wminfo.version);
158 if (!SDL_GetWindowWMInfo(static_cast<SDL_Window*>(sdlWindow), &wminfo))
159 throw Exception("WebGPU: SDL_GetWindowWMInfo failed: %s", SDL_GetError());
160#if defined(_WIN32)
161 wgpu::SurfaceSourceWindowsHWND winChain{};
162 winChain.hwnd = wminfo.info.win.window;
163 winChain.hinstance = GetModuleHandle(nullptr);
164 nativeSurfDesc.nextInChain = &winChain;
165 surface = inst.instance.CreateSurface(&nativeSurfDesc);
166#elif defined(__linux__)
167 if (wminfo.subsystem == SDL_SYSWM_X11) {
168 wgpu::SurfaceSourceXlibWindow x11Chain{};
169 x11Chain.display = wminfo.info.x11.display;
170 x11Chain.window = wminfo.info.x11.window;
171 nativeSurfDesc.nextInChain = &x11Chain;
172 surface = inst.instance.CreateSurface(&nativeSurfDesc);
173#if defined(SDL_VIDEO_DRIVER_WAYLAND)
174 } else if (wminfo.subsystem == SDL_SYSWM_WAYLAND) {
175 wgpu::SurfaceSourceWaylandSurface wlChain{};
176 wlChain.display = wminfo.info.wl.display;
177 wlChain.surface = wminfo.info.wl.surface;
178 nativeSurfDesc.nextInChain = &wlChain;
179 surface = inst.instance.CreateSurface(&nativeSurfDesc);
180#endif
181 } else {
182 throw Exception("WebGPU: unsupported SDL window subsystem on Linux");
183 }
184#elif defined(__APPLE__)
185 // SDL exposes an NSWindow, while Dawn requires its content view's
186 // CAMetalLayer. Runtime messaging keeps this source portable C++.
187 using SendId = id (*)(id, SEL);
188 using SendVoidId = void (*)(id, SEL, id);
189 using SendVoidBool = void (*)(id, SEL, BOOL);
190 using SendIsKind = BOOL (*)(id, SEL, Class);
191 const auto sendId = reinterpret_cast<SendId>(objc_msgSend);
192 const auto sendVoidId = reinterpret_cast<SendVoidId>(objc_msgSend);
193 const auto sendVoidBool = reinterpret_cast<SendVoidBool>(objc_msgSend);
194 const auto sendIsKind = reinterpret_cast<SendIsKind>(objc_msgSend);
195 id window = reinterpret_cast<id>(wminfo.info.cocoa.window);
196 id view = sendId(window, sel_registerName("contentView"));
197 if (view == nil) throw Exception("WebGPU: SDL Cocoa window has no content view");
198 sendVoidBool(view, sel_registerName("setWantsLayer:"), YES);
199 id layer = sendId(view, sel_registerName("layer"));
200 Class metalLayerClass = objc_getClass("CAMetalLayer");
201 if (metalLayerClass == Nil) throw Exception("WebGPU: CAMetalLayer class unavailable");
202 if (layer == nil || !sendIsKind(layer, sel_registerName("isKindOfClass:"), metalLayerClass)) {
203 layer = sendId(reinterpret_cast<id>(metalLayerClass), sel_registerName("layer"));
204 sendVoidId(view, sel_registerName("setLayer:"), layer);
205 }
206 if (layer == nil) throw Exception("WebGPU: failed to create CAMetalLayer");
207 WGPUSurfaceSourceMetalLayer metalChain{};
208 metalChain.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
209 metalChain.layer = layer;
210 surfDesc.nextInChain = &metalChain.chain;
211 surface = inst.instance.CreateSurface(reinterpret_cast<const wgpu::SurfaceDescriptor*>(&surfDesc));
212#else
213 throw Exception("WebGPU: unsupported native platform for surface creation");
214#endif
215#endif
216 if (!surface) throw Exception("WebGPU: surface creation failed");
217 auto adp = InitFlow::requestAdapter(std::move(inst), surface);
218 auto dev = InitFlow::requestDevice(std::move(adp));
219
220 instance = std::move(dev.instance);
221 adapter = std::move(dev.adapter);
222 device = std::move(dev.device);
223 queue = std::move(dev.queue);
224 caps = std::move(dev.caps);
225 // Preferred surface format comes from wgpuSurfaceGetCapabilities in the
226 // current ABI (Surface::GetPreferredFormat was removed).
227 WGPUSurfaceCapabilities caps{};
228 if (wgpuSurfaceGetCapabilities(surface.Get(), adapter.Get(), &caps) == WGPUStatus_Success && caps.formatCount > 0) {
229 // Match Vulkan's display-space convention: the scene tone-map pass
230 // writes sRGB-encoded values to UNORM, then UI is composited without
231 // an additional hardware transfer function. Fall back only when the
232 // platform does not expose either common UNORM surface format.
233 surfaceFormat = caps.formats[0];
234#if !defined(__EMSCRIPTEN__)
235 for (size_t i = 0; i < caps.formatCount; ++i) {
236 if (caps.formats[i] == WGPUTextureFormat_BGRA8Unorm) {
237 surfaceFormat = caps.formats[i];
238 break;
239 }
240 if (caps.formats[i] == WGPUTextureFormat_RGBA8Unorm) {
241 surfaceFormat = caps.formats[i];
242 }
243 }
244#endif
245 }
246 wgpuSurfaceCapabilitiesFreeMembers(caps);
247
248 swapchainConfigured = false;
249 // Bind group layouts / pipelines must exist before the default textures
250 // (texture bind groups reference the 2D / mesh3d layouts), and the shadow
251 // depth array must exist before mesh bind groups are built at flush time.
252 createPipelineResources();
253 createShadowResources();
254 createDefaultTextures();
255 initialized = true;
256 deviceInitDone = true;
257}
258
260 if (vsyncEnabled == enabled) return;
262 markSwapchainDirty();
263}
264
265void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight) {
266 // Mirror the Vulkan backend: keep the base-class viewport members in sync
267 // so getWidth()/getPixelWidth() (used by RenderSystem3D for the GBuffer
268 // size) return the real dimensions instead of 0.
269 this->width = width;
270 this->height = height;
271 this->pixelWidth = pixelwidth;
272 this->pixelHeight = pixelheight;
273 logicalW = width;
274 logicalH = height;
275 pixelW = pixelwidth;
276 pixelH = pixelheight;
277 if (width <= 0 || height <= 0) return;
278 if (initialized) configureSurface(width, height);
279}
280
281void Graphics::configureSurface(int width, int height) {
282 if (!surface || !device || width <= 0 || height <= 0) return;
283 WGPUSurfaceConfiguration cfg{};
284 cfg.nextInChain = nullptr;
285 cfg.device = device.Get();
286 cfg.width = static_cast<uint32_t>(width);
287 cfg.height = static_cast<uint32_t>(height);
288 cfg.format = surfaceFormat;
289#if defined(__EMSCRIPTEN__)
290 // GPUCanvasConfiguration accepts COPY_SRC for canvas textures. Unlike native
291 // surfaces, the browser API has no surface-usage capability query; the C API
292 // adapter's synthesized capabilities need not populate the usages member.
293 surfaceCanCopySrc = true;
294#else
295 WGPUSurfaceCapabilities caps{};
296 surfaceCanCopySrc = wgpuSurfaceGetCapabilities(surface.Get(), adapter.Get(), &caps) == WGPUStatus_Success &&
297 (caps.usages & WGPUTextureUsage_CopySrc) != 0;
298 wgpuSurfaceCapabilitiesFreeMembers(caps);
299#endif
300 cfg.usage = WGPUTextureUsage_RenderAttachment | (surfaceCanCopySrc ? WGPUTextureUsage_CopySrc : 0);
301 cfg.viewFormatCount = 0;
302 cfg.viewFormats = nullptr;
303 // emdawnwebgpu only accepts Fifo / Undefined present modes.
304 cfg.presentMode = WGPUPresentMode_Fifo;
305 // Auto (0) maps to an empty slot in emdawnwebgpu's JS CompositeAlphaMode
306 // table �?`alphaMode: undefined`, which some browsers reject. Use Opaque,
307 // which maps to the JS value 'opaque' used by the working replica.
308 cfg.alphaMode = WGPUCompositeAlphaMode_Opaque;
309 surface.Configure(reinterpret_cast<const wgpu::SurfaceConfiguration*>(&cfg));
310 swapchainConfigured = true;
311 // Recreate the offscreen targets at the new size.
312 int w = pixelW > 0 ? pixelW : width;
313 int h = pixelH > 0 ? pixelH : height;
314 if (w > 0 && h > 0) {
315 createSceneColorResources(w, h);
316 createShadowResources();
317 }
318}
319
320void Graphics::rebuildSwapchainIfNeeded() {
321 if (!swapchainConfigured && surface && logicalW > 0 && logicalH > 0) {
322 configureSurface(logicalW, logicalH);
323 }
324}
325
326// ---------------------------------------------------------------------------
327// Default / placeholder resources
328// ---------------------------------------------------------------------------
329
330void Graphics::createDefaultTextures() {
331 uint8_t white[4] = {255, 255, 255, 255};
332 whiteTexture = static_cast<GpuTexture*>(newTexture(1, 1, white, false, false)->gpuHandle);
333
334 // Flat normal (0.5,0.5,1) in RGBA8 �?sampled as (0,0,1) normal.
335 uint8_t flatNrm[4] = {128, 128, 255, 255};
336 flatNormalTexture = static_cast<GpuTexture*>(newTexture(1, 1, flatNrm, false, false)->gpuHandle);
337 flatNormalTexture3D = flatNormalTexture;
338
339 uint8_t flatH[4] = {0, 0, 0, 255};
340 flatHeightTexture3D = static_cast<GpuTexture*>(newTexture(1, 1, flatH, false, false)->gpuHandle);
341
342 // 1x1 depth placeholder for the mesh3d scene-depth binding (9). Only X-ray
343 // shaders sample it; every other mesh draw binds this unused depth view.
344 {
345 auto* gpu = new GpuTexture();
346 WGPUTextureDescriptor td{};
347 td.label = sv("eve_flat_depth");
348 td.dimension = WGPUTextureDimension_2D;
349 td.size = {1, 1, 1};
350 td.sampleCount = 1;
351 td.format = WGPUTextureFormat_Depth32Float;
352 td.mipLevelCount = 1;
353 td.usage = WGPUTextureUsage_TextureBinding;
354 gpu->texture = device.CreateTexture(reinterpret_cast<const wgpu::TextureDescriptor*>(&td));
355 WGPUTextureViewDescriptor vd{};
356 vd.format = WGPUTextureFormat_Depth32Float;
357 vd.dimension = WGPUTextureViewDimension_2D;
358 vd.baseMipLevel = 0;
359 vd.mipLevelCount = 1;
360 vd.baseArrayLayer = 0;
361 vd.arrayLayerCount = 1;
362 gpu->view = gpu->texture.CreateView(reinterpret_cast<const wgpu::TextureViewDescriptor*>(&vd));
363 gpu->width = 1;
364 gpu->height = 1;
365 flatDepthTexture3D = gpu;
366 }
367
368 // 1x1xN depth-array placeholder for the mesh3d shadow bindings (5/8).
369 // sampleShadowPCF() early-outs (bias.y < 0.5) when shadows are disabled,
370 // so the texture is never actually sampled.
371 {
372 auto* gpu = new GpuTexture();
373 WGPUTextureDescriptor td{};
374 td.label = sv("eve_default_shadow_depth");
375 td.dimension = WGPUTextureDimension_2D;
376 td.size = {1, 1, static_cast<uint32_t>(ShadowConfig::kTotalLayers)};
377 td.sampleCount = 1;
378 td.format = WGPUTextureFormat_Depth32Float;
379 td.mipLevelCount = 1;
380 td.usage = WGPUTextureUsage_TextureBinding;
381 gpu->texture = device.CreateTexture(reinterpret_cast<const wgpu::TextureDescriptor*>(&td));
382 WGPUTextureViewDescriptor vd{};
383 vd.format = WGPUTextureFormat_Depth32Float;
384 vd.dimension = WGPUTextureViewDimension_2DArray;
385 vd.baseMipLevel = 0;
386 vd.mipLevelCount = 1;
387 vd.baseArrayLayer = 0;
388 vd.arrayLayerCount = static_cast<uint32_t>(ShadowConfig::kTotalLayers);
389 gpu->view = gpu->texture.CreateView(reinterpret_cast<const wgpu::TextureViewDescriptor*>(&vd));
390 WGPUSamplerDescriptor sd{};
391 sd.label = sv("eve_default_shadow_sampler");
392 sd.addressModeU = WGPUAddressMode_ClampToEdge;
393 sd.addressModeV = WGPUAddressMode_ClampToEdge;
394 sd.addressModeW = WGPUAddressMode_ClampToEdge;
395 sd.magFilter = WGPUFilterMode_Linear;
396 sd.minFilter = WGPUFilterMode_Linear;
397 sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
398 sd.compare = WGPUCompareFunction_LessEqual;
399 sd.maxAnisotropy = 1;
400 gpu->sampler = device.CreateSampler(reinterpret_cast<const wgpu::SamplerDescriptor*>(&sd));
401 defaultShadowTex = gpu;
402 }
403
404 // Default env cubemap is black so an unset environment (RenderSystem3D
405 // still passes envIntensity=1.0 by default) does not wash the scene
406 // toward white. Only an explicitly set envMap contributes IBL.
407 uint8_t cubeFace[4] = {0, 0, 0, 0};
408 uint8_t cubeData[24];
409 for (int f = 0; f < 6; ++f) std::memcpy(cubeData + f * 4, cubeFace, 4);
410 defaultEnvCubemap = static_cast<GpuTexture*>(newCubemap(1, cubeData)->gpuHandle);
411
412 // Shared filtering sampler for WGSL bindings declared as plain `sampler`.
413 TextureSampler def;
414 mainSampler = makeSampler(def, 1);
415
416 const uint8_t transparent[4] = {0, 0, 0, 0};
417 const uint8_t decalNormal[4] = {128, 128, 255, 0};
418 const uint8_t decalParams[4] = {0, 0, 0, 0};
419 decalFlatAlbedo = newTexture(1, 1, transparent);
420 decalFlatNormal = newTexture(1, 1, decalNormal);
421 decalFlatParams = newTexture(1, 1, decalParams);
422}
423
424// ---------------------------------------------------------------------------
425// Pipeline resource creation
426// ---------------------------------------------------------------------------
427
428bool Graphics::acquireSurfaceTexture(wgpu::TextureView& view, wgpu::Texture& texture) {
429 if (!surface || !device || !swapchainConfigured) return false;
430 wgpu::SurfaceTexture surfTex{};
431 surface.GetCurrentTexture(&surfTex);
432 if (!surfTex.texture) return false;
433 texture = surfTex.texture;
434 view = texture.CreateView();
435 return bool(view);
436}
437
439 // Browser validation is reported by the device uncaptured-error callback.
440 // Emdawnwebgpu scope callbacks can report a dropped instance every frame.
441#if defined(EVENGINE_WEBGPU) && !defined(__EMSCRIPTEN__)
442 if (device) device.PushErrorScope(wgpu::ErrorFilter::Validation);
443#endif
444}
445
447#if defined(EVENGINE_WEBGPU) && !defined(__EMSCRIPTEN__)
448 if (!device) return;
449 device.PopErrorScope(wgpu::CallbackMode::AllowProcessEvents,
450 [](wgpu::PopErrorScopeStatus status, wgpu::ErrorType type, wgpu::StringView message) {
451 (void)status;
452 if (message.data && type != wgpu::ErrorType::NoError) {
453 std::fprintf(stderr, "[webgpu] validation error type=%d: %.*s\n", int(type),
454 static_cast<int>(message.length), message.data);
455 }
456 });
457#endif
458}
459
460
463 applyPendingResourceChanges();
464 if (headless_) return;
465 if (!isActive()) return;
466 if (isCanvasActive()) throw Exception("present: cannot present while a Canvas is active");
467 if (!device || !surface || !swapchainConfigured) return;
468 pumpReadback();
469 rebuildSwapchainIfNeeded();
470 if (!swapchainConfigured) return;
471 // RenderControl can toggle MSAA without resizing the window. Re-evaluate
472 // the offscreen sample count every frame, matching the Vulkan backend.
473 if (sceneColorWidth > 0 && sceneColorHeight > 0) createSceneColorResources(sceneColorWidth, sceneColorHeight);
474 const bool aoActive = renderControl_ && renderControl_->isEnabled("ao");
475
476 wgpu::TextureView surfaceView;
477 wgpu::Texture surfaceTex;
478 if (!acquireSurfaceTexture(surfaceView, surfaceTex)) {
479 return;
480 }
481
482 auto& uboArena = currentUboArena();
483 uboArena.reset();
484 auto& vtxArena = currentVertexArena();
485 vtxArena.reset();
486 voxelInstanceArena.used = 0;
487 voxelAoArena.used = 0;
488 ensureUboArena(uboArena, 4096);
489 ensureVertexArena(vtxArena, 4096);
490 // Match the desktop (Vulkan) flow: the 3D/swapchain pass clears with the
491 // background set by setBackgroundColor unless the script called clear().
492 if (!hasPendingClear) clearColor = backgroundColor;
493 hasPendingClear = false;
494
495 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
496 // Compute compaction writes the visible-model table and indexed-indirect
497 // commands consumed by the scene render pass below. Ending the compute
498 // pass establishes the required WebGPU storage-to-indirect dependency.
499 recordGpuDrivenCompute(encoder);
500
501 recordDirectionalShadowPasses(encoder);
502
503 // Stage-3 visibility pass consumes the compute-compacted instance table
504 // before the scene pass resolves material shading.
505 recordGpuDrivenVisibility(encoder);
506
507 // Hybrid: GBuffer must be written before deferred lighting samples it into
508 // scene color. Forward+ keeps the historical order (GBuffer after scene).
509 const bool wantDeferredLighting = deferredLightingPending_;
510 if (wantDeferredLighting) flushGBufferPassInto(encoder, aoActive);
511
512 // 2. Scene color pass (3D) into the offscreen target.
513 wgpu::TextureView sceneView;
514 wgpu::Texture sceneTex;
515 if (frameHad3DThisFrame) {
516 if (active3DCanvas) {
517 // 3D into an offscreen canvas: render the mesh pass into the
518 // canvas color/depth (RGBA8Unorm, matches the mesh3d pipelines).
519 OffscreenCanvas* oc = active3DCanvas;
520 WGPURenderPassColorAttachment colorAtt{};
521 colorAtt.view = oc->colorView.Get();
522 colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
523 colorAtt.loadOp = WGPULoadOp_Clear;
524 colorAtt.storeOp = WGPUStoreOp_Store;
525 colorAtt.clearValue = {clearColor.r, clearColor.g, clearColor.b, 1.f};
526 WGPURenderPassDepthStencilAttachment ds{};
527 ds.view = oc->depthView.Get();
528 ds.depthClearValue = 1.f;
529 ds.depthLoadOp = WGPULoadOp_Clear;
530 ds.depthStoreOp = WGPUStoreOp_Store;
531 ds.stencilClearValue = 0;
532 ds.stencilLoadOp = WGPULoadOp_Undefined;
533 ds.stencilStoreOp = WGPUStoreOp_Undefined;
534 WGPURenderPassDescriptor rp{};
535 rp.colorAttachmentCount = 1;
536 rp.colorAttachments = &colorAtt;
537 rp.depthStencilAttachment = &ds;
538 wgpu::RenderPassEncoder pass =
539 encoder.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&rp));
540 // Voxel draws are not expected on the canvas path (voxel module is
541 // trimmed from the web build), and its pipeline follows the scene
542 // sample count which would mismatch the 1x canvas attachment.
543 flushMesh3D(pass, WGPUTextureFormat_RGBA8Unorm, /*canvasTarget*/ true);
544 flushGpuDrivenDraws(pass, /*canvasTarget*/ true);
545 flushPrimitive3D(pass, WGPUTextureFormat_RGBA8Unorm, 1);
546 pass.End();
547 oc->clearRequested = false;
548 // The script draws the canvas texture explicitly (2D path); it is
549 // not composited into the swapchain.
550 lastReadbackTex = oc->color;
551 lastReadbackW = oc->getWidth();
552 lastReadbackH = oc->getHeight();
553 } else if (!sceneColorSlots.empty()) {
554 SceneColorSlot& slot = sceneColorSlots[currentFrameSlot()];
555 std::vector<Mesh3dDraw> refractiveDraws;
556 const bool splitSceneColor = mesh3dSceneColorCaptureIndex.has_value() &&
557 *mesh3dSceneColorCaptureIndex <= mesh3dDraws.size() &&
558 sceneColorSlots.size() > 1 && slot.sampleCount == 1;
559 if (splitSceneColor) {
560 auto split = mesh3dDraws.begin() + static_cast<std::ptrdiff_t>(*mesh3dSceneColorCaptureIndex);
561 refractiveDraws.assign(std::make_move_iterator(split), std::make_move_iterator(mesh3dDraws.end()));
562 mesh3dDraws.erase(split, mesh3dDraws.end());
563 }
564 WGPURenderPassColorAttachment colorAtt{};
565 colorAtt.view = slot.sampleCount > 1 ? slot.msaaView.Get() : slot.colorView.Get();
566 colorAtt.resolveTarget = slot.sampleCount > 1 ? slot.colorView.Get() : nullptr;
567 colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
568 colorAtt.loadOp = WGPULoadOp_Clear;
569 // When resolving to a single-sample target, the multisampled
570 // attachment must be discarded (WebGPU spec).
571 colorAtt.storeOp = slot.sampleCount > 1 ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
572 colorAtt.clearValue = {clearColor.r, clearColor.g, clearColor.b, 1.f};
573 WGPURenderPassDepthStencilAttachment ds{};
574 ds.view = slot.depthView.Get();
575 ds.depthClearValue = 1.f;
576 ds.depthLoadOp = WGPULoadOp_Clear;
577 ds.depthStoreOp = WGPUStoreOp_Store;
578 ds.stencilClearValue = 0;
579 ds.stencilLoadOp = WGPULoadOp_Undefined;
580 ds.stencilStoreOp = WGPUStoreOp_Undefined;
581 WGPURenderPassDescriptor rp{};
582 rp.colorAttachmentCount = 1;
583 rp.colorAttachments = &colorAtt;
584 rp.depthStencilAttachment = &ds;
585 wgpu::RenderPassEncoder pass =
586 encoder.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&rp));
587 // Phase D Hybrid: clustered deferred lighting fills opaque scene
588 // color + depth before transparent Forward+ mesh draws.
589 if (wantDeferredLighting) flushDeferredLighting(pass);
590 flushVoxelDraws(pass, sceneColorFormat);
591 flushGpuDrivenResolve(pass);
592 flushMesh3D(pass, sceneColorFormat);
593 flushGpuDrivenDraws(pass, /*canvasTarget*/ false);
594 flushPrimitive3D(pass, sceneColorFormat, slot.sampleCount);
595 pass.End();
596 if (splitSceneColor) {
597 const uint32_t snapshotIndex =
598 (currentFrameSlot() + 1u) % static_cast<uint32_t>(sceneColorSlots.size());
599 SceneColorSlot& snapshot = sceneColorSlots[snapshotIndex];
600 WGPUTexelCopyTextureInfo source{};
601 source.texture = slot.color.Get();
602 source.mipLevel = 0;
603 source.origin = {0, 0, 0};
604 source.aspect = WGPUTextureAspect_All;
605 WGPUTexelCopyTextureInfo destination{};
606 destination.texture = snapshot.color.Get();
607 destination.mipLevel = 0;
608 destination.origin = {0, 0, 0};
609 destination.aspect = WGPUTextureAspect_All;
610 WGPUExtent3D extent{static_cast<uint32_t>(sceneColorWidth), static_cast<uint32_t>(sceneColorHeight), 1};
611 encoder.CopyTextureToTexture(reinterpret_cast<const wgpu::TexelCopyTextureInfo*>(&source),
612 reinterpret_cast<const wgpu::TexelCopyTextureInfo*>(&destination),
613 reinterpret_cast<const wgpu::Extent3D*>(&extent));
614
615 lastPresentSlot = snapshotIndex;
616 sceneColorHistoryValid = true;
617 mesh3dDraws = std::move(refractiveDraws);
618 colorAtt.resolveTarget = nullptr;
619 colorAtt.loadOp = WGPULoadOp_Load;
620 colorAtt.storeOp = WGPUStoreOp_Store;
621 ds.depthLoadOp = WGPULoadOp_Load;
622 wgpu::RenderPassEncoder transparentPass =
623 encoder.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&rp));
624 flushMesh3D(transparentPass, sceneColorFormat);
625 transparentPass.End();
626 }
627 mesh3dSceneColorCaptureIndex.reset();
628 lastPresentSlot = currentFrameSlot();
629 sceneColorHistoryValid = true;
630 lastReadbackTex = slot.color;
631 lastReadbackW = sceneColorWidth;
632 lastReadbackH = sceneColorHeight;
633 sceneView = slot.colorView;
634 sceneTex = slot.color;
635 }
636 }
637
638 // 3. GBuffer pass (Forward+ / post-only path). Hybrid already flushed above.
639 if (!wantDeferredLighting) flushGBufferPassInto(encoder, aoActive);
640
641 // 3c. Screen-space decals consume the freshly written GBuffer depth and
642 // world normal, then write three transparent layer attachments.
643 if (decalPassPending && !decalSlots.empty() && !gbufferSlots.empty()) {
644 lastDecalSlot = currentFrameSlot();
645 DecalSlot& slot = decalSlots[lastDecalSlot];
646 WGPURenderPassColorAttachment colorAtts[3]{};
647 for (auto& attachment : colorAtts) {
648 attachment.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
649 attachment.loadOp = WGPULoadOp_Clear;
650 attachment.storeOp = WGPUStoreOp_Store;
651 attachment.clearValue = {0.f, 0.f, 0.f, 0.f};
652 }
653 colorAtts[0].view = slot.albedoView.Get();
654 colorAtts[1].view = slot.normalView.Get();
655 colorAtts[2].view = slot.paramsView.Get();
656 WGPURenderPassDescriptor rp{};
657 rp.colorAttachmentCount = 3;
658 rp.colorAttachments = colorAtts;
659 wgpu::RenderPassEncoder pass =
660 encoder.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&rp));
661 flushDecalPass(pass);
662 pass.End();
663 }
664
665 // 4. Active canvas: flush 2D batches into the offscreen target instead.
666 if (activeCanvas) {
667 auto* oc = static_cast<OffscreenCanvas*>(activeCanvas);
668 flush2DToCanvas(oc);
669 }
670
671 // 5. Swapchain pass: composite scene color, draw 2D, run the overlay.
672 {
673 WGPURenderPassColorAttachment colorAtt{};
674 colorAtt.view = surfaceView.Get();
675 colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
676 colorAtt.loadOp = WGPULoadOp_Clear;
677 colorAtt.storeOp = WGPUStoreOp_Store;
678 colorAtt.clearValue = {clearColor.r, clearColor.g, clearColor.b, 1.f};
679 WGPURenderPassDescriptor rp{};
680 rp.colorAttachmentCount = 1;
681 rp.colorAttachments = &colorAtt;
682 wgpu::RenderPassEncoder pass =
683 encoder.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&rp));
684
685 if (sceneView && !sceneColorComposited) {
686 if (!fullscreenQuadReady) {
687 // Textured vertex: pos(2) + color(4) + uv(2) = 32 bytes.
688 float verts[32] = {
689 -1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 0.f,
690 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 0.f, 1.f,
691 };
692 uint32_t indices[6] = {0, 1, 2, 2, 3, 0};
693 WGPUBufferDescriptor vbd{};
694 vbd.label = sv("eve_fullscreen_vb");
695 vbd.size = sizeof(verts);
696 vbd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex;
697 fullscreenQuadVb = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&vbd));
698 queue.WriteBuffer(fullscreenQuadVb, 0, verts, sizeof(verts));
699 WGPUBufferDescriptor ibd{};
700 ibd.label = sv("eve_fullscreen_ib");
701 ibd.size = sizeof(indices);
702 ibd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index;
703 fullscreenQuadIb = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&ibd));
704 queue.WriteBuffer(fullscreenQuadIb, 0, indices, sizeof(indices));
705 fullscreenQuadReady = true;
706 }
707
708 GpuTexture sceneGpu;
709 sceneGpu.texture = sceneTex;
710 sceneGpu.view = sceneView;
711 sceneGpu.sampler = createLinearSampler(device);
712 wgpu::BindGroup bg = makeTex2DBindGroup(&sceneGpu, nullptr);
713 uint32_t offsets[1] = {0};
714 pass.SetPipeline(get2DTexturedPipeline(BlendMode::Alpha, false));
715 pass.SetBindGroup(0, bg, 1, offsets);
716 pass.SetVertexBuffer(0, fullscreenQuadVb, 0, 4 * 32);
717 pass.SetIndexBuffer(fullscreenQuadIb, wgpu::IndexFormat::Uint32, 0, 24);
718 pass.DrawIndexed(6, 1, 0, 0, 0);
719 }
720
721 if (!activeCanvas) {
722 flush2D(pass, pixelW > 0 ? pixelW : logicalW, pixelH > 0 ? pixelH : logicalH, surfaceFormat);
723 }
724
726 WGPURenderPassEncoder cPass = pass.Get();
728 }
729 pass.End();
730 }
731
732 if (screenReadbackEnabled && surfaceCanCopySrc) recordPresentedReadback(encoder, surfaceTex);
733 wgpu::CommandBuffer cmd = encoder.Finish();
734 queue.Submit(1, &cmd);
735 // emdawnwebgpu implements the GPU on the JS main thread: queued commands
736 // (draws, writes) only execute when ProcessEvents drives the work queue.
737 // Without this, render-pass draws are silently never executed (only the
738 // swapchain clear, handled by the browser present, is visible).
739#ifdef __EMSCRIPTEN__
740 if (instance) instance.ProcessEvents();
741#endif
742 // emdawnwebgpu does not implement wgpuSurfacePresent (it aborts); the
743 // browser presents the canvas automatically once the command buffer is
744 // submitted from within a requestAnimationFrame callback. On Emscripten
745 // the engine frame is driven by emscripten_set_main_loop (rAF), so the
746 // Squirrel main loop no longer blocks and no sleep is needed here.
747#if !defined(__EMSCRIPTEN__)
748 surface.Present();
749#endif
750
751 frameIndex++;
752 frame3DStarted = false;
753 frameHad3DThisFrame = false;
754 frameHad3D = false;
755 sceneColorPassOpen = false;
756 active3DCanvas = nullptr;
757 gbufferPassPending = false;
758 deferredLightingPending_ = false;
759}
760
761// ---------------------------------------------------------------------------
762// Canvas
763// ---------------------------------------------------------------------------
764
765
766} // namespace eve::graphics::webgpu
float w
Definition AnimClip.cpp:738
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
std::string message
wgpu::PopErrorScopeStatus status
std::vector< std::uint32_t > indices
int h
std::uint32_t height
std::uint32_t width
std::string id
Snapshot snapshot
std::shared_ptr< OceanGpuSpectrum > gpu
OceanSprayView view
Texture * texture
TileLayer * layer
float f
int detail
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
std::string_view source
int caps
Definition TreeMesh.cpp:164
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
void configure(FrameCaptureCapabilities capabilities)
Set backend support at provider initialization.
virtual void setVSync(bool enabled)
Prefer uncapped present (IMMEDIATE/MAILBOX) when false, vsync (MAILBOX/FIFO) when true....
Definition Graphics.h:1589
void retireResourceLifetime() const
Retire resource lifetime.
void ensureFileTexturesReady()
Finish CPU decode and GPU upload for outstanding newTextureFromFile results. @thread Game/render thre...
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
bool isActive() const
True when active.
Definition Graphics.h:1616
PresentOverlayFn presentOverlayFn_
Definition Graphics.h:2335
FrameCaptureStore & frameCaptures()
Graphics-owned frame capture authority. @thread Engine main thread only. @lifetime Borrowed until Gra...
Definition Graphics.cpp:202
void pushValidationScope() override
Pushes validation scope.
Definition Graphics.cpp:438
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
void present() override
Present.
Definition Graphics.cpp:461
void flush2DToCanvas(OffscreenCanvas *canvas)
Flush accumulated 2D batches into an offscreen canvas target.
void pumpReadback()
Advances a pending frame readback; called every present().
void popValidationScope() override
Pops validation scope.
Definition Graphics.cpp:446
void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override
Sets the viewport size.
Definition Graphics.cpp:265
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
void initWithWindow(void *nativeWindow) override
Initializes with window.
Definition Graphics.cpp:137
~Graphics() override
Graphics.
Definition Graphics.cpp:89
void initHeadlessFromDevice(int width, int height, DeviceDone &&dev)
Finish headless initialization with a consumed device stage.
Definition Graphics.cpp:115
void setVSync(bool enabled) override
Sets the v sync.
Definition Graphics.cpp:259
bool isCanvasActive() const override
True when canvas active.
void initHeadless(int width, int height) override
Initialize the renderer without a window or swapchain (headless mode). Creates a GPU device and offsc...
Definition Graphics.cpp:99
static InstanceDone createInstance()
Create a wgpu Instance (native requests the TimedWaitAny feature).
Definition InitFlow.cpp:16
static AdapterDone requestAdapter(InstanceDone &&prev, const wgpu::Surface &compatibleSurface)
Blocking adapter request. Drives ProcessEvents until the callback fires; throws eve::graphics::Except...
Definition InitFlow.cpp:33
static DeviceDone requestDevice(AdapterDone &&prev, uint32_t colorAttachmentByteBudget=40)
Blocking device request (plus queue + capability capture). Throws eve::graphics::Exception on failure...
Definition InitFlow.cpp:77
Offscreen render target (RGBA8Unorm color, optional Depth32Float). 2D batches are flushed into the ca...
Definition Canvas.h:17
int getWidth() const override
Returns the width.
Definition Canvas.h:25
int getHeight() const override
Returns the height.
Definition Canvas.h:27
wgpu::Sampler createLinearSampler(wgpu::Device &dev)
Internal WebGPU pipeline/descriptor helper; render-thread only.
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
void detachGraphicsArtifactProvider(Graphics *graphics) noexcept
Detach a Graphics instance before its derived backend is destroyed.
bool enabled
Backend support is explicit; candidates need not be produced in every frame.
static constexpr int kTotalLayers
Definition Shadow.h:27
Instance + adapter + device + queue + capability snapshot.
Definition InitFlow.h:31
Texture resources backed by a wgpu texture + view + sampler + bind groups.
Definition Graphics.h:137