A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a lost WebGPU device is replaced, and the frame comes back
esenginef82881c4a57d
diff --git a/desktop/src/headless.ts b/desktop/src/headless.tsindex 275547b53..528c6d1b1 100644--- a/desktop/src/headless.ts+++ b/desktop/src/headless.ts@@ -120,8 +120,21 @@ window.__estellaHeadless = {},lose: () => {const ext = loseContextExtension();- if (!ext) return false;- ext.loseContext();+ if (ext) {+ ext.loseContext();+ return true;+ }+ // WebGPU has no lose-context extension. Destroying the device is the one+ // loss a page can cause, and it reaches the engine as any other would.+ const m = EngineHost.module as unknown as {+ currentWebGPUDevice?: { destroy?(): void };+ preinitializedWebGPUDevice?: { destroy?(): void };+ } | null;+ // The device in use, not the one booted with: after a recovery those differ,+ // and destroying the dead one again is not a loss.+ const gpu = m?.currentWebGPUDevice ?? m?.preinitializedWebGPUDevice;+ if (!gpu?.destroy) return false;+ gpu.destroy();return true;},restore: () => {diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 80821d27b..772b51f07 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -293,6 +293,7 @@ postprocess_setScreenUniformVec4: (passName: string, uniform: string, x: number,postprocess_setUniformFloat: (passName: string, uniform: string, value: number) => voidpostprocess_setUniformVec4: (passName: string, uniform: string, x: number, y: number, z: number, w: number) => voidpostprocess_shutdown: () => void+provideReplacementDevice: (() => boolean) | undefinedrecoverDevice: (() => boolean) | undefinedregistry_batchSyncPhysicsTransforms: (registry: CppRegistry, bufferPtr: number, count: number, ppu: number) => voidregistry_getCameraEntities: (registry: CppRegistry) => number[]diff --git a/sdk/src/render/renderer.ts b/sdk/src/render/renderer.tsindex 5bcb88fa6..b93740198 100644--- a/sdk/src/render/renderer.ts+++ b/sdk/src/render/renderer.ts@@ -7,6 +7,7 @@ import { requireResourceManager } from '../wasm/resourceManager';import { platformOnContextLost } from '../platform';import { findWebGL2Context } from '../asset/loaders/TextureLoader';import { decodeFrameCapture, replayToDrawCall as replayToDrawCallImpl, getSnapshotImageData as getSnapshotImpl, type FrameCaptureData } from './frameCapture';+import { acquireWebGPUDevice } from './webgpuBoot';export enum RenderStage {Background = 0,@@ -228,15 +229,40 @@ export function finishDeviceRecovery(): number {* the module lets ONE subscription cover every host, instead of each wiring its own.*/export function watchWebGPUDeviceLoss(wasmModule: ESEngineModule): void {- const device = (wasmModule as unknown as {- preinitializedWebGPUDevice?: { lost?: Promise<{ reason?: string; message?: string }> };- }).preinitializedWebGPUDevice;- void device?.lost?.then((info) => {- // `destroyed` is us tearing the device down, not a failure.+ watchOneWebGPUDevice(wasmModule, (wasmModule as unknown as {+ preinitializedWebGPUDevice?: WatchableGPUDevice;+ }).preinitializedWebGPUDevice);+}++interface WatchableGPUDevice { lost?: Promise<{ reason?: string; message?: string }> }++/**+ * Reports the loss, then acquires the replacement only the page can make.+ *+ * The engine cannot create a GPUDevice, so a lost one is fatal until something+ * hands over another — and left to each host, the second device's feature+ * negotiation stops matching the first's. Re-armed on the replacement.+ */+function watchOneWebGPUDevice(wasmModule: ESEngineModule, device?: WatchableGPUDevice): void {+ // Which device is live NOW, since the one the page booted with may be several+ // losses ago and nothing else records the succession.+ (wasmModule as unknown as { currentWebGPUDevice?: unknown }).currentWebGPUDevice = device;+ void device?.lost?.then(async (info) => {const reason = info?.reason === 'destroyed'? DeviceLostReason.Destroyed: DeviceLostReason.Unknown;reportDeviceLost(reason, info?.message ?? 'The GPUDevice reported itself lost');+ // Our own teardown resolves this promise too, and replacing a device+ // nobody is going to draw with would resurrect a renderer being closed.+ if (!module) return;++ const { device: next } = await acquireWebGPUDevice('webgpu');+ if (!next || !module) return;+ (wasmModule as unknown as { pendingWebGPUDevice?: unknown }).pendingWebGPUDevice = next;+ // Handed over, not adopted here: the recovery attempt takes it up, so+ // both backends rebuild through the same one order of operations.+ wasmModule.provideReplacementDevice?.();+ watchOneWebGPUDevice(wasmModule, next as WatchableGPUDevice);});}diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex c742c6dba..689dafae4 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -225,6 +225,12 @@ export interface ESEngineModule {* On success the device is Recovering: drawing, with placeholder textures.*/recoverDevice?(): boolean;+ /**+ * Take up the replacement device left on `Module.pendingWebGPUDevice`. A+ * WebGPU device belongs to whoever created it, so the page has to supply+ * one; the next {@link recoverDevice} adopts it. WebGL2 answers false.+ */+ provideReplacementDevice?(): boolean;/*** End recovery — the engine decides whether it actually ended. Returns how* many textures are still on the placeholder; 0 means the device is Live.diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex ff80a7ac2..1f4693f1e 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -296,6 +296,38 @@ std::string deviceIdentity() {return id.backend + "|" + id.vendor + "|" + id.renderer + "|" + id.version;}+#ifdef ES_ENABLE_WEBGPU+EM_JS_DEPS(estella_webgpu_replacement, "$WebGPU");++// The page's replacement GPUDevice, as a WGPUDevice. Imported rather than read+// through emscripten_webgpu_get_device, which caches the FIRST device and would+// hand back the dead one forever.+EM_JS(uintptr_t, es_takePendingWebGPUDevice, (), {+ var device = Module['pendingWebGPUDevice'];+ if (!device) return 0;+ Module['pendingWebGPUDevice'] = null;+ return WebGPU.importJsDevice(device);+});+#endif++/**+ * @brief Hands the backend a replacement device the page acquired.+ * @details WebGPU only: a device belongs to whoever created it, so a lost one+ * can only be replaced from the page. Taken up by the next recovery+ * attempt, which keeps one order of operations for both backends.+ */+bool provideReplacementDevice() {+#ifdef ES_ENABLE_WEBGPU+ GfxDevice* device = activeGfxDevice();+ if (!device) return false;+ const uintptr_t raw = es_takePendingWebGPUDevice();+ if (!raw) return false;+ return device->provideReplacementDevice(reinterpret_cast<void*>(raw));+#else+ return false;+#endif+}+/*** @brief Rebuilds the renderer after a loss; see EstellaContext::recoverDevice.* @details Leaves the device Recovering — drawable, but its textures are@@ -446,6 +478,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("deviceIdentity", &esengine::deviceIdentity);emscripten::function("notifyDeviceLost", &esengine::notifyDeviceLost);emscripten::function("recoverDevice", &esengine::recoverDevice);+ emscripten::function("provideReplacementDevice", &esengine::provideReplacementDevice);emscripten::function("markDeviceRestored", &esengine::markDeviceRestored);emscripten::class_<esengine::resource::ResourceManager>("ResourceManager")diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex 829b4532f..adaffd1c4 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -175,6 +175,18 @@ public:device_status_ = GfxDeviceStatus::Dead;}+ /**+ * @brief Takes a replacement device from the host, for backends that cannot+ * make their own.+ * @details A WebGPU device is created by the page, so only the page can+ * replace a lost one; GL rebuilds itself and has no use for this.+ * The next recovery attempt picks up whatever was handed over.+ */+ virtual bool provideReplacementDevice(void* nativeDevice) {+ (void)nativeDevice;+ return false;+ }+/*** @brief Pumps backend-native loss detection.* @details Backends whose loss arrives as a callback (WebGPU) or a statusdiff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex 8c9c845cb..dd78bcd3c 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -133,7 +133,46 @@ void WebGPUDevice::reportUncapturedError(u32 wgpuErrorType, const char* message)}}+bool WebGPUDevice::adoptDevice(WGPUDevice device) {+ if (!device) return false;++ // Everything below the device goes: a WebGPU object belongs to the device+ // that made it, so none of these caches can be carried over. The instance+ // stays — it outlives devices, and on native the surface must match it.+ releaseDeviceObjects();++ device_ = device;+ queue_ = wgpuDeviceGetQueue(device_);+ init();++#if defined(__EMSCRIPTEN__)+ if (surface_selector_.empty()) return true;+ return configureSurface(surface_selector_.c_str(), surface_width_, surface_height_);+#else+ if (!surface_window_) return true;+ NativeSurface window{};+ window.handle = surface_window_;+ return configureSurface(window, surface_width_, surface_height_);+#endif+}++bool WebGPUDevice::recreateDevice() {+ // "Not yet", not "never": only whoever created the device can replace it, so+ // this waits for a host to hand one over rather than claiming a recovery it+ // cannot perform. The GL path waits on the browser the same way.+ if (!pending_device_) return false;+ WGPUDevice next = pending_device_;+ pending_device_ = nullptr;+ return adoptDevice(next);+}+void WebGPUDevice::shutdown() {+ releaseDeviceObjects();+ if (instance_ && owns_instance_) { wgpuInstanceRelease(instance_); }+ instance_ = nullptr;+}++void WebGPUDevice::releaseDeviceObjects() {for (auto& [id, rec] : buffers_) {if (rec.buffer) wgpuBufferRelease(rec.buffer);}@@ -196,8 +235,10 @@ void WebGPUDevice::shutdown() {if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ = nullptr; }if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ = nullptr; }if (surface_) { wgpuSurfaceRelease(surface_); surface_ = nullptr; }- if (instance_ && owns_instance_) { wgpuInstanceRelease(instance_); }- instance_ = nullptr;+ // Sizes are kept: a re-configured surface has to come back the same shape,+ // and the depth companion is rebuilt against them.+ surface_depth_width_ = 0;+ surface_depth_height_ = 0;}// =============================================================================@@ -217,6 +258,9 @@ bool WebGPUDevice::configureSurface(const char* selector, u32 width, u32 height)WGPUSurfaceDescriptor sd{};sd.nextInChain = &canvas.chain;+ // Kept so a replacement device can re-make the surface: the old one belonged+ // to the device that died, and nothing else records which canvas it was.+ surface_selector_ = selector;surface_ = wgpuInstanceCreateSurface(instance_, &sd);if (!surface_) {ES_LOG_ERROR("WebGPUDevice::configureSurface: surface creation failed for '{}'", selector);diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hppindex 6466618f7..1dd70bfef 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp@@ -79,11 +79,24 @@ public:bool pollDeviceLost() override;+ /**+ * @brief Takes over a replacement device, rebuilding everything under it.+ * @details Only whoever created a WebGPU device can replace it, so recovery+ * arrives from outside rather than being something this class can+ * perform. Every cached object belonged to the dead device and is+ * released; the surface is re-created against the new one.+ */+ bool adoptDevice(WGPUDevice device);++ /** @brief Hands a replacement in for the next recovery attempt to take up. */+ bool provideReplacementDevice(void* nativeDevice) override {+ pending_device_ = static_cast<WGPUDevice>(nativeDevice);+ return pending_device_ != nullptr;+ }+protected:void captureDeviceIdentity() override;- // recreateDevice is deliberately NOT overridden: only whoever created the- // device can replace it, and claiming otherwise would report a recovery that- // did not happen. A WebGPU loss stays fatal until that host hands one over.+ bool recreateDevice() override;public:@@ -389,6 +402,7 @@ private:WGPUDevice device_ = nullptr;WGPUQueue queue_ = nullptr;+ WGPUDevice pending_device_ = nullptr; ///< Replacement a host handed over, not yet adopted.WGPUInstance instance_ = nullptr;WGPUAdapter adapter_ = nullptr; ///< Native only, host-owned: surface capability queries.bool owns_instance_ = true; ///< False when a native host injected its instance (don't release it).@@ -410,6 +424,8 @@ private:u32 capture_id_ = 0;u32 surface_width_ = 0;u32 surface_height_ = 0;+ /** The canvas the surface was made for, so a replacement device can re-make it. */+ std::string surface_selector_;WGPUTexture surface_depth_texture_ = nullptr;WGPUTextureView surface_depth_view_ = nullptr;@@ -427,6 +443,9 @@ private:void* userdata1, void* userdata2);/** @brief Erases + releases a readback record (aborts a still-pending map). */void releaseReadback(u32 id);++ /** Frees everything the device owns, keeping the instance and surface shape. */+ void releaseDeviceObjects();/** A staging buffer + record with no copy submitted yet; 0 on failure. */u32 allocReadback(u32 w, u32 h);void submitReadbackCopy(u32 id, WGPUTexture source);diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex c1e64c8a2..2075392ca 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -27,7 +27,7 @@ export const TIERS = ['pr', 'nightly'];* Dawn adapter, so nothing here runs it. Where an adapter exists every scene* passes — both backends read the frame the same way, off the engine's buffer.*/-export const WEBGPU_GAP = 'no adapter on a CI runner; with one, all 52 pass (`--backend webgpu`)';+export const WEBGPU_GAP = 'no adapter on a CI runner; with one, all 53 pass (`--backend webgpu`)';/*** Every pixel gate. `env` is handed to desktop/scripts/headless-verify.mjs@@ -120,7 +120,10 @@ export const SCENES = [// happens FOUR times — backgrounding a tab is not a one-off, a recovery that// works once and never again passes any single-round check, and it takes// three rounds to measure whether the host's object tables are growing.- { id: "device-loss-auto", tier: "pr", env: { ESTELLA_VERIFY_LOSS_ROUNDS: "4", ESTELLA_VERIFY_DEVICE_LOSS: "auto", ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },+ // Three on WebGPU, where a loss is a destroyed device and the replacement can+ // only come from the page: the rounds check that the engine adopts a NEW one+ // each time. Object tables are a GL notion there and read zero.+ { id: "device-loss-auto", tier: "pr", webgpu: { ESTELLA_VERIFY_LOSS_ROUNDS: "3" }, env: { ESTELLA_VERIFY_LOSS_ROUNDS: "4", ESTELLA_VERIFY_DEVICE_LOSS: "auto", ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },];const rank = (tier) => TIERS.indexOf(tier);