Skip to content

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

feat(rhi): a lost GPU device is a state, not a black screen

esengine633637d56610
diff --git a/native/host/Host.cpp b/native/host/Host.cpp
index 39d399a40..4f240fe74 100644
--- a/native/host/Host.cpp
+++ b/native/host/Host.cpp
@@ -36,6 +36,12 @@ using namespace esengine;
namespace eshost {
namespace {
+/** Dawn returns strings as pointer+length, with WGPU_STRLEN meaning "null-terminated". */
+std::string svText(const WGPUStringView& v) {
+ return v.data ? std::string(v.data, v.length == WGPU_STRLEN ? strlen(v.data) : v.length)
+ : std::string();
+}
+
/** Has the SDK's render pipeline taken over the frame? It declares itself through
* `es_jsOwnsFrame` (see HOST_FLAGS in the SDK's nativeBindings) once installed. */
bool jsOwnsFrame(HostState& h) {
@@ -113,10 +119,28 @@ bool createDevice(HostState& h) {
// Without this, a validation failure is silent: WebGPU does not throw, the
// offending call is dropped, and all that reaches anyone is a black frame.
dd.uncapturedErrorCallbackInfo.callback =
- [](WGPUDevice const*, WGPUErrorType, WGPUStringView message, void*, void*) {
- ESHOST_LOGE("WebGPU: %.*s", (int)(message.length == WGPU_STRLEN
- ? strlen(message.data) : message.length),
- message.data ? message.data : "");
+ [](WGPUDevice const*, WGPUErrorType type, WGPUStringView message, void*, void*) {
+ const std::string text = svText(message);
+ ESHOST_LOGE("WebGPU: %s", text.c_str());
+ // An out-of-memory or internal error is the device telling us it is
+ // finished; the backend decides which kinds end it.
+ if (hostAlive() && host().gfx) {
+ host().gfx->reportUncapturedError(static_cast<uint32_t>(type), text.c_str());
+ }
+ };
+ // Device loss can only be subscribed to HERE — WebGPU takes the callback in
+ // the descriptor that creates the device, and there is no way to attach one
+ // afterwards. A device created without it loses itself in silence.
+ dd.deviceLostCallbackInfo.mode = WGPUCallbackMode_AllowSpontaneous;
+ dd.deviceLostCallbackInfo.callback =
+ [](WGPUDevice const*, WGPUDeviceLostReason reason, WGPUStringView message, void*, void*) {
+ const std::string text = svText(message);
+ ESHOST_LOGE("WebGPU device lost (%d): %s", (int)reason, text.c_str());
+ if (hostAlive() && host().gfx) {
+ host().gfx->notifyDeviceLost(
+ WebGPUDevice::reasonFromWgpu(static_cast<uint32_t>(reason)),
+ text, "Dawn device-lost callback");
+ }
};
WGPURequestDeviceCallbackInfo dci = {};
dci.mode = WGPUCallbackMode_WaitAnyOnly; dci.callback = onDevice; dci.userdata1 = &h.device;
@@ -137,12 +161,8 @@ void logAdapter(HostState& h) {
if (!h.adapter) return;
WGPUAdapterInfo info = {};
if (wgpuAdapterGetInfo(h.adapter, &info) != WGPUStatus_Success) return;
- auto str = [](const WGPUStringView& v) {
- return v.data ? std::string(v.data, v.length == WGPU_STRLEN ? strlen(v.data) : v.length)
- : std::string();
- };
- bootNote("gpu: %s %s (%s) — %s", str(info.vendor).c_str(), str(info.device).c_str(),
- str(info.architecture).c_str(), str(info.description).c_str());
+ bootNote("gpu: %s %s (%s) — %s", svText(info.vendor).c_str(), svText(info.device).c_str(),
+ svText(info.architecture).c_str(), svText(info.description).c_str());
wgpuAdapterInfoFreeMembers(info);
}
diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cpp
index d93cf039d..adc862b07 100644
--- a/src/esengine/core/EstellaContext.cpp
+++ b/src/esengine/core/EstellaContext.cpp
@@ -118,6 +118,14 @@ void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {
// every other renderer subsystem borrow this single device. Which backend
// it is was decided at the platform edge (init overloads).
auto* gfxDevicePtr = gfxDevice.get();
+
+ // The one place a device loss becomes visible. Logged whether or not
+ // anything above the engine is listening: a loss nobody recorded is the
+ // black screen with no explanation.
+ gfxDevicePtr->setDeviceLostHandler([](const GfxDeviceLostInfo& info) {
+ ES_LOG_ERROR("{}", gfxFormatDeviceLost(info));
+ });
+
services_.registerOwned<GfxDevice>(std::move(gfxDevice));
auto resourceManager = makeUnique<resource::ResourceManager>();
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 0f85e1d78..44ca64d30 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -195,6 +195,14 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::H
void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::Handle target,
const PassClear& clear) {
+ // A lost device makes the whole frame meaningless, so it is refused here
+ // rather than discovered by each pass and readback failing separately.
+ // in_frame_ stays false, which makes end() a no-op too: no half-frame.
+ if (!device_.beginDeviceFrame()) {
+ in_frame_ = false;
+ return;
+ }
+
view_projection_ = view_projection;
frustum_.extractFromMatrix(view_projection);
current_target_ = target;
@@ -278,6 +286,11 @@ void RenderFrame::flush() {
flushed_ = true;
+ // The device can still die between begin() and here — a GL error check, a
+ // spontaneous WebGPU callback. Marked flushed above first, so end() does not
+ // come back for a second attempt at a frame that has nowhere to go.
+ if (!device_.isDeviceLive()) return;
+
// Drop any pipeline a prior phase left bound, so the first draw re-applies its state.
device_.invalidatePipelineCache();
@@ -435,6 +448,7 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
void RenderFrame::renderToTarget(ecs::Registry& registry, const glm::mat4& viewProjection, u32 w, u32 h) {
if (w == 0 || h == 0) return;
+ if (!device_.isDeviceLive()) return;
if (preview_rt_ == 0) {
preview_rt_ = target_manager_.create(w, h, /*depth=*/false, /*linearFilter=*/false);
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index 58be42cb1..94b46038a 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -252,6 +252,10 @@ void GLDevice::init() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ // Ask who we are while the answer still exists: glGetString returns null on a
+ // lost context, so a report assembled after the loss would name no driver.
+ setDeviceIdentity("WebGL2", getString(GfxStringName::Vendor),
+ getString(GfxStringName::Renderer), getString(GfxStringName::Version));
ES_LOG_DEBUG("GLDevice initialized");
}
@@ -259,6 +263,21 @@ void GLDevice::shutdown() {
ES_LOG_INFO("GLDevice shutdown");
}
+bool GLDevice::pollDeviceLost() {
+ if (!isDeviceLive()) return false;
+#ifdef __EMSCRIPTEN__
+ // Asked directly rather than waited for: a `webglcontextlost` listener
+ // attached after the loss never fires, and a renderer that missed the event
+ // would submit into a dead context forever.
+ if (emscripten_is_webgl_context_lost(0)) {
+ markDeviceLost(GfxDeviceLostReason::ContextLost,
+ "WebGL reports the context is lost", "pollDeviceLost");
+ return true;
+ }
+#endif
+ return false;
+}
+
// =============================================================================
// Viewport & Clear
// =============================================================================
@@ -420,6 +439,10 @@ void GLDevice::setCullFace(bool front) {
ShaderHandle GLDevice::createProgram(const GfxShaderSource& source,
const GfxAttribBinding* bindings, u32 bindingCount,
std::string* outLog, GfxShaderStage* outFailedStage) {
+ if (!isDeviceLive()) {
+ if (outLog) *outLog = "device lost";
+ return ShaderHandle::Invalid;
+ }
if (source.language != GfxShaderLanguage::GLSL_ES300) {
if (outLog) *outLog = "GLDevice compiles GLSL ES 300 only (got another language)";
if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;
@@ -632,7 +655,12 @@ void GLDevice::uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const voi
}
}
+// A lost GL context accepts every call silently, so the danger is not a crash:
+// creation appears to succeed and returns an id naming nothing. Guarded are the
+// calls whose RESULT the caller acts on; state setters are no-ops already.
+
BufferHandle GLDevice::createBuffer(const BufferDesc& desc, const void* initialData) {
+ if (!isDeviceLive()) return BufferHandle::Invalid;
GLuint id = 0;
glGenBuffers(1, &id);
buffer_meta_[id] = BufferMeta{desc.usage, desc.dynamic};
@@ -663,6 +691,7 @@ void GLDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
// =============================================================================
VertexLayoutHandle GLDevice::createVertexLayout(const VertexLayoutDesc& desc) {
+ if (!isDeviceLive()) return VertexLayoutHandle::Invalid;
LayoutRecord rec;
rec.desc = desc;
rec.alive = true;
@@ -758,6 +787,7 @@ void GLDevice::uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bin
// =============================================================================
PipelineHandle GLDevice::createPipeline(const PipelineDesc& desc) {
+ if (!isDeviceLive()) return PipelineHandle::Invalid;
for (u32 i = 0; i < pipelines_.size(); ++i) {
if (pipelines_[i] == desc) {
return static_cast<PipelineHandle>(i + 1);
@@ -837,17 +867,20 @@ void GLDevice::invalidatePipelineCache() {
// =============================================================================
void GLDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) {
+ if (!isDeviceLive()) return;
prepareVertexState();
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexCount), toGLDataType(indexType),
reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)));
}
void GLDevice::drawArrays(u32 first, u32 vertexCount) {
+ if (!isDeviceLive()) return;
prepareVertexState();
glDrawArrays(GL_TRIANGLES, static_cast<GLint>(first), static_cast<GLsizei>(vertexCount));
}
void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) {
+ if (!isDeviceLive()) return;
prepareVertexState();
glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(indexCount), toGLDataType(indexType),
reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)),
@@ -893,6 +926,7 @@ void GLDevice::evictSamplerBinding(u32 textureId) {
}
TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixels) {
+ if (!isDeviceLive()) return TextureHandle::Invalid;
GLuint id = 0;
glGenTextures(1, &id);
texture_formats_[id] = desc.format;
@@ -919,6 +953,7 @@ TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixel
TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
const void* data, u32 byteLength, u32 mipLevels) {
+ if (!isDeviceLive()) return TextureHandle::Invalid;
GLuint id = 0;
glGenTextures(1, &id);
texture_formats_[id] = desc.format;
@@ -953,6 +988,7 @@ TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxComp
}
TextureHandle GLDevice::importExternalTexture(u32 nativeId, const TextureDesc& desc) {
+ if (!isDeviceLive()) return TextureHandle::Invalid;
texture_formats_[nativeId] = desc.format;
return TextureHandle{nativeId};
}
@@ -996,6 +1032,7 @@ void GLDevice::generateMipmaps(TextureHandle texture) {
// =============================================================================
FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {
+ if (!isDeviceLive()) return FramebufferHandle::Default;
GLuint id = 0;
glGenFramebuffers(1, &id);
glBindFramebuffer(GL_FRAMEBUFFER, id);
@@ -1088,6 +1125,7 @@ void GLDevice::endRenderPass() {
// =============================================================================
ReadbackHandle GLDevice::requestReadback(FramebufferHandle target, u32 w, u32 h) {
+ if (!isDeviceLive()) return ReadbackHandle::Invalid;
if (w == 0 || h == 0) return ReadbackHandle::Invalid;
std::vector<u8> pixels(static_cast<usize>(w) * h * 4);
// Called outside a pass (framebuffer 0 bound); bind the source, read, restore.
@@ -1174,7 +1212,15 @@ void GLDevice::setWireframe(bool enabled) {
}
u32 GLDevice::getError() {
- return static_cast<u32>(glGetError());
+ const GLenum err = glGetError();
+ // GL_CONTEXT_LOST is not an error to handle but the context announcing it is
+ // gone; the two enums for it differ by header origin. Reporting it here lets
+ // a build with error checking on notice in the same frame.
+ if (err == GL_CONTEXT_LOST || err == GL_CONTEXT_LOST_WEBGL) {
+ markDeviceLost(GfxDeviceLostReason::ContextLost,
+ "glGetError returned GL_CONTEXT_LOST", "getError");
+ }
+ return static_cast<u32>(err);
}
std::string GLDevice::getString(GfxStringName name) {
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index fc4b8e5f9..b8dc98f23 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -39,6 +39,8 @@ public:
void init() override;
void shutdown() override;
+ bool pollDeviceLost() override;
+
void setViewport(i32 x, i32 y, u32 w, u32 h) override;
void clearStencil(i32 value) override;
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index e1244511e..6d2738c1a 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -26,7 +26,9 @@
#include "./GfxEnums.hpp"
#include "./PipelineState.hpp"
+#include <functional>
#include <string>
+#include <utility>
#include <vector>
namespace esengine {
@@ -78,6 +80,86 @@ public:
/** @brief Shuts down the graphics device */
virtual void shutdown() = 0;
+ // =========================================================================
+ // Device Loss
+ // =========================================================================
+
+ // The state machine lives here, not in each backend: a backend only has to
+ // DETECT its own kind of loss and call markDeviceLost. What "lost" then MEANS
+ // — one report, one transition, submission stopped — stays identical.
+
+ /** @brief Whether the device can be drawn to (see {@link GfxDeviceStatus}). */
+ GfxDeviceStatus deviceStatus() const { return device_status_; }
+
+ /** @brief True while the device is usable — the one check submission paths make. */
+ bool isDeviceLive() const { return device_status_ == GfxDeviceStatus::Live; }
+
+ /** @brief The loss report, or null while the device is Live. */
+ const GfxDeviceLostInfo* deviceLostInfo() const {
+ return device_status_ == GfxDeviceStatus::Live ? nullptr : &device_info_;
+ }
+
+ /**
+ * @brief Declares the device lost from outside the backend.
+ * @details The host observes losses the backend cannot: a browser firing
+ * `webglcontextlost`, a shell told by the OS that the adapter is
+ * gone. Idempotent — the FIRST reason wins, because it is the one
+ * that explains the rest.
+ */
+ void notifyDeviceLost(GfxDeviceLostReason reason, std::string message = {},
+ std::string context = {}) {
+ markDeviceLost(reason, std::move(message), std::move(context));
+ }
+
+ /**
+ * @brief Gives up on the device: no further recovery will be attempted.
+ * @details The clean end of a loss that could not be recovered from. The
+ * report is kept; what changes is that the renderer stops waiting.
+ */
+ void markDeviceDead() {
+ if (device_status_ == GfxDeviceStatus::Dead) return;
+ if (device_status_ == GfxDeviceStatus::Live) {
+ markDeviceLost(GfxDeviceLostReason::Unknown, {}, {});
+ }
+ device_status_ = GfxDeviceStatus::Dead;
+ }
+
+ /**
+ * @brief Pumps backend-native loss detection.
+ * @details Backends whose loss arrives as a callback (WebGPU) or a status
+ * query (GL robustness) surface it here. Default: the backend
+ * cannot detect loss itself and depends entirely on
+ * notifyDeviceLost.
+ * @return True when THIS call is the one that observed the loss.
+ */
+ virtual bool pollDeviceLost() { return false; }
+
+ /**
+ * @brief Opens a frame: polls for loss, and numbers the frame a report is stamped with.
+ * @details The one place the renderer asks "may I draw at all". Everything a
+ * frame does afterwards — passes, post-process, readbacks — is
+ * predicated on this having returned true, which is why it is a
+ * single question at the top rather than a check per submission.
+ * @return True when the device is live and the frame may proceed.
+ */
+ bool beginDeviceFrame() {
+ ++device_frame_;
+ if (device_status_ == GfxDeviceStatus::Live) pollDeviceLost();
+ return device_status_ == GfxDeviceStatus::Live;
+ }
+
+ /**
+ * @brief Called once per loss, with the completed report.
+ * @details One observer, not a list: the renderer owns the device and fans
+ * the report out to whoever else needs it.
+ */
+ void setDeviceLostHandler(std::function<void(const GfxDeviceLostInfo&)> handler) {
+ device_lost_handler_ = std::move(handler);
+ }
+
+ /** @brief Backend identity captured at init (see {@link GfxDeviceLostInfo}). */
+ const GfxDeviceLostInfo& deviceIdentity() const { return device_info_; }
+
// =========================================================================
// Viewport & Clear
// =========================================================================
@@ -453,6 +535,44 @@ public:
* different claim than "nothing is allocated" — see censusProbes.ts.
*/
virtual GfxLiveObjects liveObjects() const { return {}; }
+
+protected:
+ /**
+ * @brief Records who this backend is, so a later loss report can name it.
+ * @details Call from init(), while the backend still answers. Doing it at
+ * loss time is too late — see {@link GfxDeviceLostInfo}.
+ */
+ void setDeviceIdentity(std::string backend, std::string vendor,
+ std::string renderer, std::string version) {
+ device_info_.backend = std::move(backend);
+ device_info_.vendor = std::move(vendor);
+ device_info_.renderer = std::move(renderer);
+ device_info_.version = std::move(version);
+ }
+
+ /**
+ * @brief The single transition into Lost. Backends call this on detection.
+ * @details Idempotent: a lost device usually produces a burst of secondary
+ * failures, and the first reason is the one that explains them.
+ * @return True when this call performed the transition.
+ */
+ bool markDeviceLost(GfxDeviceLostReason reason, std::string message = {},
+ std::string context = {}) {
+ if (device_status_ != GfxDeviceStatus::Live) return false;
+ device_status_ = GfxDeviceStatus::Lost;
+ device_info_.reason = reason;
+ device_info_.message = std::move(message);
+ device_info_.context = std::move(context);
+ device_info_.frame = device_frame_;
+ if (device_lost_handler_) device_lost_handler_(device_info_);
+ return true;
+ }
+
+private:
+ GfxDeviceStatus device_status_ = GfxDeviceStatus::Live;
+ GfxDeviceLostInfo device_info_;
+ u64 device_frame_ = 0;
+ std::function<void(const GfxDeviceLostInfo&)> device_lost_handler_;
};
} // namespace esengine
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index df241199f..4775f71d6 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -337,6 +337,104 @@ enum class GfxIntParam : u8 {
MaxVertexAttribs,
};
+// =============================================================================
+// Device Loss
+// =============================================================================
+
+/**
+ * @brief Whether the device can still be drawn to.
+ *
+ * @details Every backend can lose its device: WebGL fires `webglcontextlost`,
+ * WebGPU resolves its lost future, a native driver resets under us. The
+ * states make "lost" a value the renderer branches on, not a condition
+ * it discovers by drawing into a dead device.
+ */
+enum class GfxDeviceStatus : u8 {
+ Live, ///< Normal operation.
+ Lost, ///< Every handle issued before is dead; submission has stopped.
+ Recovering, ///< A replacement device is being built; old handles stay dead.
+ Dead, ///< Unrecoverable — the renderer will not draw again this run.
+};
+
+/** @brief Why the device was lost. The report leads with this. */
+enum class GfxDeviceLostReason : u8 {
+ Unknown,
+ ContextLost, ///< The host took the context away (web `webglcontextlost`, surface teardown).
+ OutOfMemory, ///< An allocation the backend could not satisfy.
+ Reset, ///< Driver/GPU reset — a hang watchdog (TDR) or a peer process's fault.
+ Removed, ///< The adapter itself is gone: driver update, eGPU unplugged.
+ Destroyed, ///< We destroyed it. A loss report that is not a failure.
+ Validation, ///< The backend rejected our commands fatally.
+ Internal, ///< The backend failed inside itself and said no more than that.
+};
+
+/**
+ * @brief Everything a human needs to know about one device loss.
+ *
+ * @details Assembled once, at the moment of loss, and then immutable — a report
+ * that says only "the context was lost" is what this type exists to
+ * replace.
+ */
+struct GfxDeviceLostInfo {
+ GfxDeviceLostReason reason = GfxDeviceLostReason::Unknown;
+
+ /**
+ * Backend identity, captured at init() rather than at loss.
+ *
+ * A lost backend cannot be asked who it was — GL returns null from
+ * glGetString once the context is gone — so a report assembled at loss time
+ * would name no vendor, no driver and no GPU.
+ */
+ std::string backend; ///< "WebGL2", "WebGPU".
+ std::string vendor;
+ std::string renderer;
+ std::string version;
+
+ /** Driver-supplied text; empty when the backend offered no detail. */
+ std::string message;
+
+ /** What the device was doing when it died, when the site knows (e.g. "createTexture 4096x4096"). */
+ std::string context;
+
+ /** The frame the loss was observed on. */
+ u64 frame = 0;
+};
+
+/**
+ * @brief The whole report as one line, for a log or a crash report.
+ * @details Single formatter so the C++ log, the JS diagnostics record and a
+ * user-facing error all name the failure identically.
+ */
+inline std::string gfxFormatDeviceLost(const GfxDeviceLostInfo& info);
+
+/** @brief Human-readable reason, for logs and diagnostics reports. */
+inline const char* gfxDeviceLostReasonName(GfxDeviceLostReason reason) {
+ switch (reason) {
+ case GfxDeviceLostReason::ContextLost: return "context-lost";
+ case GfxDeviceLostReason::OutOfMemory: return "out-of-memory";
+ case GfxDeviceLostReason::Reset: return "device-reset";
+ case GfxDeviceLostReason::Removed: return "device-removed";
+ case GfxDeviceLostReason::Destroyed: return "destroyed";
+ case GfxDeviceLostReason::Validation: return "validation";
+ case GfxDeviceLostReason::Internal: return "internal-error";
+ case GfxDeviceLostReason::Unknown: break;
+ }
+ return "unknown";
+}
+
+inline std::string gfxFormatDeviceLost(const GfxDeviceLostInfo& info) {
+ std::string out = "GPU device lost: ";
+ out += gfxDeviceLostReasonName(info.reason);
+ out += " [backend=" + (info.backend.empty() ? std::string("unknown") : info.backend);
+ if (!info.vendor.empty()) out += ", vendor=" + info.vendor;
+ if (!info.renderer.empty()) out += ", gpu=" + info.renderer;
+ if (!info.version.empty()) out += ", driver=" + info.version;
+ out += ", frame=" + std::to_string(info.frame) + "]";
+ if (!info.context.empty()) out += " during " + info.context;
+ if (!info.message.empty()) out += " — " + info.message;
+ return out;
+}
+
// =============================================================================
// Shader Program Creation
// =============================================================================
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 11cc5d192..1663d42c8 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -28,6 +28,12 @@ WGPUStringView sv(const char* text) {
return view;
}
+std::string fromSv(const WGPUStringView& view) {
+ if (!view.data) return {};
+ return std::string(view.data,
+ view.length == WGPU_STRLEN ? std::strlen(view.data) : view.length);
+}
+
bool isDepthFormat(WGPUTextureFormat format) {
return format == WGPUTextureFormat_Depth24Plus ||
format == WGPUTextureFormat_Depth24PlusStencil8;
@@ -73,7 +79,55 @@ WebGPUDevice::~WebGPUDevice() {
shutdown();
}
-void WebGPUDevice::init() {}
+void WebGPUDevice::init() {
+ // Ask the adapter who this GPU is. getString() below answers with constants
+ // true of every WebGPU build, and so useless in a loss report; the adapter
+ // knows the vendor, the chip and the driver build.
+ std::string vendor = "WebGPU";
+ std::string renderer = getString(GfxStringName::Renderer);
+ std::string version = getString(GfxStringName::Version);
+ if (adapter_) {
+ WGPUAdapterInfo info = {};
+ if (wgpuAdapterGetInfo(adapter_, &info) == WGPUStatus_Success) {
+ vendor = fromSv(info.vendor);
+ renderer = fromSv(info.device) + " (" + fromSv(info.architecture) + ")";
+ version = fromSv(info.description);
+ wgpuAdapterInfoFreeMembers(info);
+ }
+ }
+ setDeviceIdentity("WebGPU", std::move(vendor), std::move(renderer), std::move(version));
+}
+
+GfxDeviceLostReason WebGPUDevice::reasonFromWgpu(u32 wgpuReason) {
+ switch (static_cast<WGPUDeviceLostReason>(wgpuReason)) {
+ // Not a failure: this is the device we destroyed reporting that it is gone.
+ case WGPUDeviceLostReason_Destroyed: return GfxDeviceLostReason::Destroyed;
+ case WGPUDeviceLostReason_FailedCreation: return GfxDeviceLostReason::Internal;
+ default: return GfxDeviceLostReason::Unknown;
+ }
+}
+
+bool WebGPUDevice::pollDeviceLost() {
+ // The device-lost callback is registered AllowSpontaneous and so fires on
+ // its own, but pumping here gives it a guaranteed point in the frame — and
+ // keeps the loss detectable if the mode ever tightens to ProcessEvents.
+ if (instance_) wgpuInstanceProcessEvents(instance_);
+ return false;
+}
+
+void WebGPUDevice::reportUncapturedError(u32 wgpuErrorType, const char* message) {
+ // Only errors that mean the device is finished become losses. A validation
+ // error is a bug in the frame we just built — WebGPU drops the call and keeps
+ // the device — so promoting it would end the game over one bad draw.
+ const auto type = static_cast<WGPUErrorType>(wgpuErrorType);
+ if (type == WGPUErrorType_OutOfMemory) {
+ markDeviceLost(GfxDeviceLostReason::OutOfMemory, message ? message : "",
+ "uncaptured error");
+ } else if (type == WGPUErrorType_Internal) {
+ markDeviceLost(GfxDeviceLostReason::Internal, message ? message : "",
+ "uncaptured error");
+ }
+}
void WebGPUDevice::shutdown() {
for (auto& [id, rec] : buffers_) {
@@ -389,7 +443,12 @@ void WebGPUDevice::setScissor(i32 x, i32 y, i32 w, i32 h) {
// Buffers
// =============================================================================
+// Unlike GL — where a lost context turns every call into a silent no-op — calling
+// into a lost WebGPU device is not defined to be harmless. The guards below are
+// the backend's half of the contract; the frame loop stops submitting above them.
+
BufferHandle WebGPUDevice::createBuffer(const BufferDesc& desc, const void* initialData) {
+ if (!isDeviceLive()) return BufferHandle::Invalid;
if (!device_) {
ES_LOG_ERROR("WebGPUDevice::createBuffer: no device");
return BufferHandle::Invalid;
@@ -511,6 +570,7 @@ void WebGPUDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
// =============================================================================
VertexLayoutHandle WebGPUDevice::createVertexLayout(const VertexLayoutDesc& desc) {
+ if (!isDeviceLive()) return VertexLayoutHandle::Invalid;
// Validate every attribute has a WebGPU spelling up front — a mismatch is an
// engine bug, not a runtime condition.
for (u32 i = 0; i < desc.attributeCount; ++i) {
@@ -558,6 +618,7 @@ const PipelineDesc* WebGPUDevice::pipelineDesc(PipelineHandle handle) const {
// =============================================================================
TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* pixels) {
+ if (!isDeviceLive()) return TextureHandle::Invalid;
if (!device_) {
ES_LOG_ERROR("WebGPUDevice::createTexture: no device");
return TextureHandle::Invalid;
@@ -599,6 +660,7 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* p
TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
const void* data, u32 byteLength, u32 mipLevels) {
+ if (!isDeviceLive()) return TextureHandle::Invalid;
if (!device_ || !queue_) {
ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: no device");
return TextureHandle::Invalid;
@@ -759,6 +821,10 @@ bool WebGPUDevice::supportsCompressedFormat(GfxCompressedFormat format) {
ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,
const GfxAttribBinding*, u32,
std::string* outLog, GfxShaderStage* outFailedStage) {
+ if (!isDeviceLive()) {
+ if (outLog) *outLog = "device lost";
+ return ShaderHandle::Invalid;
+ }
if (source.language != GfxShaderLanguage::WGSL) {
if (outLog) *outLog = "WebGPUDevice compiles WGSL only";
if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;
@@ -840,6 +906,7 @@ void WebGPUDevice::uniformBlockBinding(ShaderHandle, u32, u32) {}
// =============================================================================
PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {
+ if (!isDeviceLive()) return PipelineHandle::Invalid;
// Dedup on the descriptor like GLDevice's pipeline cache.
for (const auto& [id, rec] : pipelines_) {
if (rec.desc == desc) return static_cast<PipelineHandle>(id);
@@ -1344,7 +1411,7 @@ void WebGPUDevice::flushBindGroup() {
// =============================================================================
void WebGPUDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) {
- if (!pass_) return;
+ if (!isDeviceLive() || !pass_) return;
auto it = buffers_.find(bound_index_buffer_);
if (it == buffers_.end()) return;
flushBindGroup();
@@ -1355,14 +1422,14 @@ void WebGPUDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 index
}
void WebGPUDevice::drawArrays(u32 firstVertex, u32 vertexCount) {
- if (!pass_) return;
+ if (!isDeviceLive() || !pass_) return;
flushBindGroup();
wgpuRenderPassEncoderDraw(pass_, vertexCount, 1, firstVertex, 0);
}
void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,
u32 instanceCount) {
- if (!pass_) return;
+ if (!isDeviceLive() || !pass_) return;
auto it = buffers_.find(bound_index_buffer_);
if (it == buffers_.end()) return;
flushBindGroup();
@@ -1374,6 +1441,7 @@ void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType,
}
FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc& desc) {
+ if (!isDeviceLive()) return FramebufferHandle::Default;
FramebufferRec rec{};
rec.color0 = static_cast<u32>(desc.color0);
rec.depthStencil = static_cast<u32>(desc.depthStencil);
@@ -1393,6 +1461,7 @@ void WebGPUDevice::deleteFramebuffer(FramebufferHandle framebuffer) {
}
void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
+ if (!isDeviceLive()) return;
if (!device_) return;
if (pass_) endRenderPass(); // defensive: a dangling pass would deadlock the queue
@@ -1595,6 +1664,7 @@ void WebGPUDevice::releaseReadback(u32 id) {
}
ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u32 h) {
+ if (!isDeviceLive()) return ReadbackHandle::Invalid;
if (!device_ || w == 0 || h == 0) return ReadbackHandle::Invalid;
if (inPass()) {
ES_LOG_ERROR("WebGPUDevice::requestReadback: must be called outside a render pass");
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 4f8f38acb..5af15d2ec 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -67,6 +67,18 @@ public:
void init() override;
void shutdown() override;
+ // Device loss reaches this class from OUTSIDE it: WebGPU accepts a
+ // device-lost callback only in the descriptor that creates the device, and
+ // both hosts create theirs before handing it over. Hence these entry points.
+
+ /** @brief Maps a WGPUDeviceLostReason to the backend-neutral reason. */
+ static GfxDeviceLostReason reasonFromWgpu(u32 wgpuReason);
+
+ /** @brief Routes the device's uncaptured-error callback; only fatal kinds become losses. */
+ void reportUncapturedError(u32 wgpuErrorType, const char* message);
+
+ bool pollDeviceLost() override;
+
void setViewport(i32 x, i32 y, u32 w, u32 h) override;
void clearStencil(i32 value) override;
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index ac0048558..6684e0b52 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -118,6 +118,15 @@ add_executable(test_buffer_device
target_include_directories(test_buffer_device PRIVATE ${CMAKE_SOURCE_DIR}/src)
add_test(NAME test_buffer_device COMMAND test_buffer_device)
+# Device loss: the shared state machine (GfxDevice), driven through MockGfxDevice.
+# Header-only, so nothing but Log.cpp is needed to link.
+add_executable(test_device_loss
+ renderer/test_device_loss.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_device_loss PRIVATE ${CMAKE_SOURCE_DIR}/src)
+add_test(NAME test_device_loss COMMAND test_device_loss)
+
# WebGPU backend slice 1 (REARCH_WGSL Phase 2): the enum→WGPU mapping layer +
# the null-device-safe WebGPUDevice skeleton, compiled against the REAL Dawn C
# headers via the emdawnwebgpu port (emscripten-only; the port supplies
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 4b611d9d5..11ecc638e 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -13,6 +13,11 @@
namespace esengine {
struct MockGfxDevice final : GfxDevice {
+ // Device-loss entry points a backend calls on itself. Protected on GfxDevice,
+ // so a harness driving the state machine needs them republished here.
+ using GfxDevice::markDeviceLost;
+ using GfxDevice::setDeviceIdentity;
+
// call counters
// The render state a draw resolved to, as the pipeline saw it.
PipelineDesc lastPipelineDesc{};
diff --git a/tests/renderer/test_device_loss.cpp b/tests/renderer/test_device_loss.cpp
new file mode 100644
index 000000000..96713449b
--- /dev/null
+++ b/tests/renderer/test_device_loss.cpp
@@ -0,0 +1,98 @@
+// Device loss: the state machine every backend shares.
+//
+// Under test is that a lost device cannot be half-alive: the frame stops opening
+// and the report names the GPU. Per-backend guards: test_webgpu_device.cpp.
+
+#include "MockGfxDevice.hpp"
+#include "esengine/renderer/rhi/GfxEnums.hpp"
+
+#include <cstdio>
+#include <string>
+
+using namespace esengine;
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+int main() {
+ // --- A live device reports nothing ---
+ {
+ MockGfxDevice d;
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "a new device is Live");
+ CHECK(d.isDeviceLive(), "isDeviceLive agrees");
+ CHECK(d.deviceLostInfo() == nullptr, "a live device has no loss report");
+ CHECK(d.beginDeviceFrame(), "a live device opens a frame");
+ }
+
+ // --- The transition, and its report ---
+ {
+ MockGfxDevice d;
+ d.setDeviceIdentity("WebGL2", "Acme", "Acme GPU 9000", "4.2-driver");
+
+ int handlerCalls = 0;
+ GfxDeviceLostInfo seen{};
+ d.setDeviceLostHandler([&](const GfxDeviceLostInfo& info) {
+ ++handlerCalls;
+ seen = info;
+ });
+
+ d.beginDeviceFrame();
+ d.beginDeviceFrame();
+ d.notifyDeviceLost(GfxDeviceLostReason::OutOfMemory, "allocation failed", "createTexture");
+
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Lost, "notifyDeviceLost moves it to Lost");
+ CHECK(!d.isDeviceLive(), "a lost device is not live");
+ CHECK(handlerCalls == 1, "the handler fires once");
+ CHECK(seen.reason == GfxDeviceLostReason::OutOfMemory, "the reason is carried through");
+ CHECK(seen.message == "allocation failed", "the driver message is carried through");
+ CHECK(seen.context == "createTexture", "what it was doing is carried through");
+ CHECK(seen.frame == 2, "the loss is stamped with the frame it happened on");
+
+ // The identity was captured at init, when the backend could still answer.
+ const std::string report = gfxFormatDeviceLost(seen);
+ CHECK(report.find("out-of-memory") != std::string::npos, "the report names the reason");
+ CHECK(report.find("WebGL2") != std::string::npos, "the report names the backend");
+ CHECK(report.find("Acme GPU 9000") != std::string::npos, "the report names the GPU");
+ CHECK(report.find("4.2-driver") != std::string::npos, "the report names the driver");
+ CHECK(report.find("createTexture") != std::string::npos, "the report says what was running");
+ }
+
+ // --- A lost device stays lost, with its FIRST explanation ---
+ {
+ MockGfxDevice d;
+ int handlerCalls = 0;
+ d.setDeviceLostHandler([&](const GfxDeviceLostInfo&) { ++handlerCalls; });
+
+ d.notifyDeviceLost(GfxDeviceLostReason::Reset, "gpu hang");
+ d.notifyDeviceLost(GfxDeviceLostReason::Validation, "a later, derived failure");
+
+ CHECK(handlerCalls == 1, "a second loss does not re-report");
+ CHECK(d.deviceLostInfo() != nullptr, "the report survives");
+ CHECK(d.deviceLostInfo()->reason == GfxDeviceLostReason::Reset,
+ "the first reason wins — it is the one that explains the rest");
+ CHECK(!d.beginDeviceFrame(), "a lost device refuses to open a frame");
+ }
+
+ // --- Giving up is a state, not a silence ---
+ {
+ MockGfxDevice d;
+ d.markDeviceDead();
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Dead, "markDeviceDead on a live device ends it");
+ CHECK(d.deviceLostInfo() != nullptr, "a dead device still carries a report");
+ CHECK(!d.beginDeviceFrame(), "a dead device refuses to open a frame");
+
+ MockGfxDevice d2;
+ d2.notifyDeviceLost(GfxDeviceLostReason::Removed, "adapter gone");
+ d2.markDeviceDead();
+ CHECK(d2.deviceStatus() == GfxDeviceStatus::Dead, "a lost device can be given up on");
+ CHECK(d2.deviceLostInfo()->reason == GfxDeviceLostReason::Removed,
+ "giving up does not overwrite why it was lost");
+ }
+
+ std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);
+ return g_failures ? 1 : 0;
+}
diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cpp
index 0b15f18ef..372de4e4e 100644
--- a/tests/renderer/test_webgpu_device.cpp
+++ b/tests/renderer/test_webgpu_device.cpp
@@ -10,6 +10,8 @@
#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
#include "esengine/renderer/webgpu/WebGPUMappings.hpp"
+#include <string>
+
using namespace esengine;
using namespace esengine::webgpu;
@@ -169,6 +171,30 @@ TEST_CASE("pass load-ops: full-target clear is a real load-op, a scoped clear is
CHECK(color.a == doctest::Approx(0.5));
}
+TEST_CASE("a lost device issues no more handles") {
+ WebGPUDevice device;
+ device.init();
+
+ VertexLayoutDesc layout{};
+ layout.attributeCount = 1;
+ layout.strides[0] = 8;
+ layout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
+ REQUIRE(device.createVertexLayout(layout) != VertexLayoutHandle::Invalid);
+
+ device.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "the host took the context");
+
+ CHECK(device.deviceStatus() == GfxDeviceStatus::Lost);
+ // Registering a layout is descriptor-only bookkeeping — it succeeds with no
+ // GPU device at all, as the case below asserts. So this refusal is the loss
+ // guard and nothing else.
+ CHECK(device.createVertexLayout(layout) == VertexLayoutHandle::Invalid);
+
+ REQUIRE(device.deviceLostInfo() != nullptr);
+ const std::string report = gfxFormatDeviceLost(*device.deviceLostInfo());
+ CHECK(report.find("context-lost") != std::string::npos);
+ CHECK(report.find("WebGPU") != std::string::npos);
+}
+
TEST_CASE("null-device skeleton: language gate + graceful degradation + bookkeeping") {
WebGPUDevice device; // no WGPUDevice — bookkeeping-only mode
CHECK(!device.hasDevice());