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(renderer): a lost device ends a mesh's realization, not its identity
esengine9165d2a1658d
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 9c7fcf30e..d9f7d7df9 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -31,7 +31,7 @@ env:test_compressed_format test_batch_builder test_boundary_span test_webgpu_devicetest_clip_depth test_shadow_atlas test_particle_shapes test_lod_selection test_hdr_formattest_text_edit test_render_graph test_device_loss test_physics_interpolation- test_bitmap_font test_texture_cache test_aot_host test_aot_conformance+ test_bitmap_font test_texture_cache test_mesh_recovery test_aot_host test_aot_conformancetest_frame_lifecyclejobs:diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 6f945b7c4..553380e95 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -92,6 +92,18 @@ export interface CppResourceManager {* behind. Optional: absent on an older wasm build.*/adoptTextureContent?(target: number, source: number): boolean;+ /**+ * The meshes whose GPU realization died with the device, as comma-separated+ * handle ids. No path travels with them: the engine never knew one, and the+ * asset layer holds the provenance. Optional: absent on an older wasm build.+ */+ meshesAwaitingRemat?(): string;+ /**+ * Meshes the loss ended for good — host-only geometry no source can replay.+ * Reported rather than skipped, so recovery cannot count them as recovered.+ * Optional: absent on an older wasm build.+ */+ meshesLostNonRecoverable?(): number;getTextureGLId(handle: number): number;getTextureDimensions(handle: number): { width: number; height: number } | null;releaseTexture(handle: number): void;diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 7d52cd0be..286d3c517 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -301,6 +301,7 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexSConstSpan<u32>(indices, indexCount),ConstSpan<GfxVertexAttribute>(channels, channelCount), vertexStride,glm::vec3(minX, minY, minZ), glm::vec3(maxX, maxY, maxZ),+ MeshRecovery::SourceReplayable,bind ? ConstSpan<f32>(bind, bindFloats) : ConstSpan<f32>());return handle.id();}@@ -351,11 +352,14 @@ u32 freezeMeshGeometry(ecs::MeshRenderer* mesh) {verts[i] = { in.position.x, in.position.y, 0.0f, in.uv.x, in.uv.y, in.color };}+ // HostOnly: the payload below is cleared on the way out, so this geometry+ // exists in no file and a device generation ends it for good.auto handle = rm->createMesh(ConstSpan<u8>(reinterpret_cast<const u8*>(verts.data()), verts.size() * sizeof(MeshVertex)),ConstSpan<u32>(mesh->indices.data(), mesh->indices.size()),ConstSpan<GfxVertexAttribute>(kStandardMeshChannels, 3), sizeof(MeshVertex),- glm::vec3(mesh->localMin, 0.0f), glm::vec3(mesh->localMax, 0.0f));+ glm::vec3(mesh->localMin, 0.0f), glm::vec3(mesh->localMax, 0.0f),+ MeshRecovery::HostOnly);if (!handle.isValid()) return 0;mesh->mesh = handle;diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cppindex caca39c76..f87544668 100644--- a/src/esengine/bindings/ResourceManagerBindings.cpp+++ b/src/esengine/bindings/ResourceManagerBindings.cpp@@ -149,6 +149,19 @@ std::string rm_texturesAwaitingReupload(resource::ResourceManager& rm) {return out;}+std::string rm_meshesAwaitingRemat(resource::ResourceManager& rm) {+ std::string out;+ for (resource::MeshHandle handle : rm.meshesAwaitingRematerialization()) {+ if (!out.empty()) out += ',';+ out += std::to_string(handle.id());+ }+ return out;+}++u32 rm_meshesLostNonRecoverable(resource::ResourceManager& rm) {+ return rm.meshesLostNonRecoverable();+}+u32 rm_registerExternalTextureSized(resource::ResourceManager& rm, u32 glTextureId,u32 width, u32 height, u32 bytes) {auto handle = rm.registerExternalTexture(glTextureId, width, height,diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hppindex 08744e1f3..83fde28aa 100644--- a/src/esengine/bindings/ResourceManagerBindings.hpp+++ b/src/esengine/bindings/ResourceManagerBindings.hpp@@ -44,6 +44,14 @@ std::string rm_texturesAwaitingReupload(resource::ResourceManager& rm);/** @brief Moves a freshly loaded texture's GPU object onto an existing handle. */bool rm_adoptTextureContent(resource::ResourceManager& rm, u32 target, u32 source);+/** @brief Meshes whose realization is gone, as comma-separated handle ids. No+ * path: the engine never knew one, and the asset layer holds it. */+std::string rm_meshesAwaitingRemat(resource::ResourceManager& rm);++/** @brief Meshes the last loss ended for good — host-only geometry no source+ * can replay. Reported so recovery cannot call them recovered. */+u32 rm_meshesLostNonRecoverable(resource::ResourceManager& rm);+u32 rm_registerExternalTextureSized(resource::ResourceManager& rm, u32 glTextureId,u32 width, u32 height, u32 bytes);void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 462774828..8dc437cc1 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -492,6 +492,8 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {.function("registerExternalTextureSized", &esengine::rm_registerExternalTextureSized).function("retargetExternalTexture", &esengine::rm_retargetExternalTexture).function("texturesAwaitingReupload", &esengine::rm_texturesAwaitingReupload)+ .function("meshesAwaitingRemat", &esengine::rm_meshesAwaitingRemat)+ .function("meshesLostNonRecoverable", &esengine::rm_meshesLostNonRecoverable).function("adoptTextureContent", &esengine::rm_adoptTextureContent).function("releaseTexture", &esengine::rm_releaseTexture).function("getTextureRefCount", &esengine::rm_getTextureRefCount)diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cppindex 25125a571..82002638f 100644--- a/src/esengine/core/EstellaContext.cpp+++ b/src/esengine/core/EstellaContext.cpp@@ -139,13 +139,20 @@ bool EstellaContext::recoverDevice() {// Last: the placeholder now exists to park them on. Their CONTENT is still// missing, which is why this leaves the device Recovering, not Live.resources->invalidateGpuTextures(renderContext->getWhiteTexture());+ // Meshes have no placeholder to park on — geometry cannot be stood in for —+ // so they lose their realization outright and the draw path skips them until+ // a source replaces it.+ resources->invalidateGpuMeshes();return true;}u32 EstellaContext::finishDeviceRecovery() {auto* resources = services_.getService<resource::ResourceManager>();+ // Both debts, not just the textures: a device declared Live with geometry+ // still missing is a screen with holes in it reporting that it recovered.const u32 pending = resources- ? static_cast<u32>(resources->texturesAwaitingReupload().size())+ ? static_cast<u32>(resources->texturesAwaitingReupload().size()+ + resources->meshesAwaitingRematerialization().size()): 0;if (pending > 0) return pending;if (auto* device = services_.getService<GfxDevice>()) device->markDeviceRestored();diff --git a/src/esengine/renderer/rhi/Buffer.hpp b/src/esengine/renderer/rhi/Buffer.hppindex 53a8c5e7e..d62063442 100644--- a/src/esengine/renderer/rhi/Buffer.hpp+++ b/src/esengine/renderer/rhi/Buffer.hpp@@ -298,6 +298,14 @@ public:/** @brief Gets the device buffer handle */BufferHandle handle() const { return handle_; }+ /**+ * @brief Forgets the GPU buffer, which died with its device.+ * @details Not a delete: the object is already gone, and asking a dead device+ * to free an id it no longer has is at best a no-op. Forgetting it+ * is what keeps the destructor from doing exactly that later.+ */+ void abandonGpuBuffer() { handle_ = BufferHandle::Invalid; }+// =========================================================================// Raw API for internal use only// =========================================================================@@ -402,6 +410,14 @@ public:/** @brief Gets the device buffer handle */BufferHandle handle() const { return handle_; }+ /**+ * @brief Forgets the GPU buffer, which died with its device.+ * @details Not a delete: the object is already gone, and asking a dead device+ * to free an id it no longer has is at best a no-op. Forgetting it+ * is what keeps the destructor from doing exactly that later.+ */+ void abandonGpuBuffer() { handle_ = BufferHandle::Invalid; }+/** @brief Returns true if using 16-bit indices */bool is16Bit() const { return is16Bit_; }diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex 258b6054c..4708e973d 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -106,6 +106,14 @@ public:device_status_ == GfxDeviceStatus::Recovering;}+ /**+ * @brief Which generation of the device the live GPU objects belong to.+ * @details Bumped by every successful rebuild. A resource can record the+ * generation it was realized on, so a diagnostic can say whether it+ * truly came back — a non-zero handle only looks like it did.+ */+ u64 deviceGeneration() const { return device_generation_; }+/** @brief The loss report, or null while the device is Live. */const GfxDeviceLostInfo* deviceLostInfo() const {return device_status_ == GfxDeviceStatus::Live ? nullptr : &device_info_;@@ -157,6 +165,7 @@ public:device_status_ = GfxDeviceStatus::Lost;return false;}+ ++device_generation_;return true;}@@ -701,6 +710,7 @@ private:GfxDeviceIdentity identity_;GfxDeviceLostInfo device_info_;u64 device_frame_ = 0;+ u64 device_generation_ = 0;std::function<void(const GfxDeviceLostInfo&)> device_lost_handler_;};diff --git a/src/esengine/resource/Mesh.hpp b/src/esengine/resource/Mesh.hppindex b90b6c9a7..6dc20aad2 100644--- a/src/esengine/resource/Mesh.hpp+++ b/src/esengine/resource/Mesh.hpp@@ -15,6 +15,19 @@namespace esengine {+/**+ * @brief How a mesh's geometry comes back after a device generation ends.+ *+ * @details Declared by the producer that mints the handle, because nothing+ * downstream can work it out — by the time recovery runs, all that is+ * left of a mesh is a number. tools/meshProducers.mjs is the census+ * that keeps every producer's answer here and its declaration in step.+ */+enum class MeshRecovery : u8 {+ SourceReplayable, ///< Replayable from an asset the loader can load again.+ HostOnly, ///< Built in this process from bytes kept nowhere else.+};+/*** @brief Buffers, the layout that describes them, and the bounds culling reads.*@@ -39,6 +52,16 @@ public:u32 indexCount = 0;+ /** Set at mint by the producer that created this mesh; never inferred later.+ * Defaulted to the answer that promises nothing, so a mesh reaching the pool+ * without one is never mistaken for recoverable. */+ MeshRecovery recovery = MeshRecovery::HostOnly;++ /** The device generation the three handles above belong to. A diagnostic:+ * it answers whether a mesh was really rebuilt, where a non-zero handle+ * only looks like it. */+ u64 realizationGeneration = 0;+/** Whether the vertices carry normals — decides the per-object record's shape* and which shader variant draws it. */bool hasNormals = false;@@ -53,12 +76,16 @@ public:bool isSkinned() const { return !inverseBind.empty(); }- bool isDrawable() const {+ /** Whether a live GPU realization stands behind this identity. False from a+ * device loss until the rematerialization that replaces it, which is what+ * stops the draw path consuming buffers that died with their device. */+ bool hasRealization() const {return vertexBuffer != BufferHandle::Invalid&& indexBuffer != BufferHandle::Invalid- && layout != VertexLayoutHandle::Invalid- && indexCount > 0;+ && layout != VertexLayoutHandle::Invalid;}++ bool isDrawable() const { return hasRealization() && indexCount > 0; }};} // namespace esenginediff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex 2f762a76d..caee611b6 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -488,7 +488,7 @@ void ResourceManager::releaseVertexBuffer(VertexBufferHandle handle) {MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,const glm::vec3& localMin, const glm::vec3& localMax,- ConstSpan<f32> inverseBind) {+ MeshRecovery recovery, ConstSpan<f32> inverseBind) {if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty()) return MeshHandle();// The mesh describes its own vertices; the per-object transform is the@@ -550,6 +550,8 @@ MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32>mesh->indexBuffer = ib ? ib->handle() : BufferHandle::Invalid;mesh->layout = device_->createVertexLayout(layout);mesh->indexCount = static_cast<u32>(indices.size());+ mesh->recovery = recovery;+ mesh->realizationGeneration = device_->deviceGeneration();mesh->hasNormals = hasNormals;mesh->localMin = localMin;mesh->localMax = localMax;@@ -569,6 +571,34 @@ const Mesh* ResourceManager::getMesh(MeshHandle handle) const {return meshes_.get(handle);}+u32 ResourceManager::invalidateGpuMeshes() {+ awaitingRematerialization_.clear();+ meshes_lost_non_recoverable_ = 0;+ meshes_.forEachAlive([&](MeshHandle handle, Mesh& mesh) {+ // Abandoned, never deleted: the GPU objects went with the device, so the+ // records are told to forget them rather than ask a dead device to free+ // ids it no longer has.+ if (auto* vb = vertexBuffers_.get(mesh.vertices)) vb->abandonGpuBuffer();+ if (auto* ib = indexBuffers_.get(mesh.indices)) ib->abandonGpuBuffer();+ mesh.vertexBuffer = BufferHandle::Invalid;+ mesh.indexBuffer = BufferHandle::Invalid;+ mesh.layout = VertexLayoutHandle::Invalid;++ if (mesh.recovery == MeshRecovery::SourceReplayable) {+ awaitingRematerialization_.push_back(handle);+ } else {+ ++meshes_lost_non_recoverable_;+ }+ });+ ES_LOG_INFO("Device loss: {} mesh(es) awaiting rematerialization, {} host-only mesh(es) gone"+ " for good", awaitingRematerialization_.size(), meshes_lost_non_recoverable_);+ return static_cast<u32>(awaitingRematerialization_.size());+}++std::vector<MeshHandle> ResourceManager::meshesAwaitingRematerialization() const {+ return awaitingRematerialization_;+}+void ResourceManager::releaseMesh(MeshHandle handle) {Mesh* mesh = meshes_.get(handle);if (!mesh) return;@@ -577,6 +607,16 @@ void ResourceManager::releaseMesh(MeshHandle handle) {releaseVertexBuffer(mesh->vertices);releaseIndexBuffer(mesh->indices);meshes_.release(handle.id());++ // A released mesh cannot be owed: the identity the debt named is gone, and a+ // rematerialization aimed at it would land on whatever reuses the slot.+ for (usize i = 0; i < awaitingRematerialization_.size(); ++i) {+ if (awaitingRematerialization_[i] == handle) {+ awaitingRematerialization_[i] = awaitingRematerialization_.back();+ awaitingRematerialization_.pop_back();+ break;+ }+ }}// =============================================================================diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 3d73778f3..2bcc2a701 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -466,7 +466,7 @@ public:MeshHandle createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,const glm::vec3& localMin, const glm::vec3& localMax,- ConstSpan<f32> inverseBind = {});+ MeshRecovery recovery, ConstSpan<f32> inverseBind = {});/** @brief The mesh a handle names, or null. */Mesh* getMesh(MeshHandle handle);@@ -475,6 +475,30 @@ public:/** @brief Releases a mesh and the buffers it owns. */void releaseMesh(MeshHandle handle);+ /**+ * @brief Ends every mesh's GPU realization, keeping every MeshHandle valid.+ *+ * @details The realization died with the device; the handles did not, so it+ * is dropped and the identity stands. A SourceReplayable mesh is+ * enqueued; a HostOnly one is COUNTED, since silence there reports+ * success over content nothing can bring back.+ *+ * @return How many meshes are awaiting rematerialization.+ */+ u32 invalidateGpuMeshes();++ /**+ * @brief Meshes whose realization is gone and whose source has not replaced it.+ * @details A copy, and only ever emptied by a rematerialization that+ * SUCCEEDED: a debt drained by the act of reading it is a debt the+ * engine forgets the moment its holder fails to pay.+ */+ std::vector<MeshHandle> meshesAwaitingRematerialization() const;++ /** @brief Meshes the last loss ended for good, because no source can replay+ * them. Never part of the awaiting list, never silently skipped. */+ u32 meshesLostNonRecoverable() const { return meshes_lost_non_recoverable_; }+// =========================================================================// Environment Resources// =========================================================================@@ -641,6 +665,8 @@ private:/// Handles whose GPU texture died with the device, still showing the/// placeholder. Empty means the content is whole again.std::vector<TextureHandle> awaitingReupload_;+ std::vector<MeshHandle> awaitingRematerialization_;+ u32 meshes_lost_non_recoverable_ = 0;std::unordered_map<std::string, TextureHandle> guidToTexture_;std::unordered_map<TextureHandle::IdType, TextureMetadata> textureMetadata_;LoaderRegistry loaderRegistry_;diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex e6100c450..d89022bec 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -245,6 +245,27 @@ target_include_directories(test_texture_cache PRIVATE)add_test(NAME test_texture_cache COMMAND test_texture_cache)+# Persistent mesh identity across a device generation. Same shape as the texture+# cache harness: the REAL ResourceManager.cpp against MockGfxDevice, so what it+# asserts is the engine's invalidation and not a model of it.+add_executable(test_mesh_recovery+ resource/test_mesh_recovery.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/resource/ResourceManager.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/resource/ShaderParser.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/text/BitmapFont.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Shader.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Texture.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Buffer.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/draw/DrawParams.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_mesh_recovery PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/tests+ ${CMAKE_SOURCE_DIR}/third_party/glm+ ${CMAKE_SOURCE_DIR}/third_party/stb+)+add_test(NAME test_mesh_recovery COMMAND test_mesh_recovery)# Shader variant (feature-permutation) system (RC7-6). Compiles ShaderParser.cpp# directly — no GL/engine link — and checks #pragma feature parsing + #define injection.diff --git a/tests/resource/test_mesh_recovery.cpp b/tests/resource/test_mesh_recovery.cppnew file mode 100644index 000000000..45fda4723--- /dev/null+++ b/tests/resource/test_mesh_recovery.cpp@@ -0,0 +1,172 @@+// Persistent mesh identity across a device generation.+//+// The REAL ResourceManager.cpp against MockGfxDevice: at the loss the handle+// survives, the realization does not, and every mesh is owed or gone for good.++#include "../renderer/MockGfxDevice.hpp"+#include "esengine/resource/ResourceManager.hpp"++#include <algorithm>+#include <cstdio>+#include <vector>++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)++namespace {++struct Vertex { f32 x, y, z, u, v; };++const GfxVertexAttribute kChannels[2] = {+ {0, 3, GfxDataType::Float, false, 0, 0},+ {1, 2, GfxDataType::Float, false, 12, 0},+};++resource::MeshHandle makeMesh(resource::ResourceManager& rm, MeshRecovery recovery) {+ const Vertex verts[3] = {{0, 0, 0, 0, 0}, {1, 0, 0, 1, 0}, {0, 1, 0, 0, 1}};+ const u32 indices[3] = {0, 1, 2};+ return rm.createMesh(+ ConstSpan<u8>(reinterpret_cast<const u8*>(verts), sizeof(verts)),+ ConstSpan<u32>(indices, 3),+ ConstSpan<GfxVertexAttribute>(kChannels, 2), sizeof(Vertex),+ glm::vec3(0.0f), glm::vec3(1.0f), recovery);+}++bool owes(const std::vector<resource::MeshHandle>& awaiting, resource::MeshHandle h) {+ return std::find(awaiting.begin(), awaiting.end(), h) != awaiting.end();+}++} // namespace++int main() {+ // --- The identity survives; the realization does not ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ CHECK(h.isValid(), "a mesh mints a handle");+ const Mesh* before = rm.getMesh(h);+ CHECK(before != nullptr, "and the handle resolves");+ CHECK(before->hasRealization(), "a fresh mesh has a GPU realization");+ CHECK(before->isDrawable(), "and is drawable");+ CHECK(before->indexCount == 3, "with its index count");++ rm.invalidateGpuMeshes();++ const Mesh* after = rm.getMesh(h);+ CHECK(after != nullptr, "the SAME handle still resolves after the loss");+ CHECK(after == before, "naming the same record — identity was never re-minted");+ CHECK(!after->hasRealization(), "whose realization is gone");+ CHECK(!after->isDrawable(), "so the draw path skips it instead of binding a dead buffer");+ CHECK(after->vertexBuffer == BufferHandle::Invalid, "the VBO is unavailable");+ CHECK(after->indexBuffer == BufferHandle::Invalid, "the EBO is unavailable");+ CHECK(after->layout == VertexLayoutHandle::Invalid, "the vertex layout is unavailable");+ // Bounds and index count are the identity's, not the realization's: they+ // are what culling reads while the geometry is on its way back.+ CHECK(after->indexCount == 3, "the index count survives the loss");+ CHECK(after->localMax == glm::vec3(1.0f), "and so do the bounds");+ }++ // --- The debt is declared, and declared once ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto a = makeMesh(rm, MeshRecovery::SourceReplayable);+ const auto b = makeMesh(rm, MeshRecovery::SourceReplayable);+ CHECK(rm.meshesAwaitingRematerialization().empty(), "a live device owes nothing");++ const u32 owed = rm.invalidateGpuMeshes();+ const auto awaiting = rm.meshesAwaitingRematerialization();+ CHECK(owed == 2, "the loss reports what it enqueued");+ CHECK(awaiting.size() == 2, "both meshes are owed");+ CHECK(owes(awaiting, a) && owes(awaiting, b), "by handle, and by the right ones");++ // One loss, one debt: a second sweep of the same event must not double it.+ rm.invalidateGpuMeshes();+ const auto again = rm.meshesAwaitingRematerialization();+ CHECK(again.size() == 2, "a second invalidate does not double the debt");+ CHECK(std::count(again.begin(), again.end(), a) == 1, "each handle is owed exactly once");+ }++ // --- Host-only geometry is counted, never quietly skipped ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto asset = makeMesh(rm, MeshRecovery::SourceReplayable);+ const auto hostOnly = makeMesh(rm, MeshRecovery::HostOnly);++ rm.invalidateGpuMeshes();+ const auto awaiting = rm.meshesAwaitingRematerialization();+ CHECK(awaiting.size() == 1, "only the replayable mesh is owed");+ CHECK(owes(awaiting, asset), "and it is the asset-backed one");+ CHECK(!owes(awaiting, hostOnly), "host-only geometry is not queued for a source it has not got");+ CHECK(rm.meshesLostNonRecoverable() == 1, "it is REPORTED as permanently gone");+ CHECK(rm.getMesh(hostOnly) != nullptr, "its handle still resolves");+ CHECK(!rm.getMesh(hostOnly)->isDrawable(), "and it is undrawable rather than drawing garbage");+ }++ // --- A dead device is not asked to free what it already lost ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);+ makeMesh(rm, MeshRecovery::SourceReplayable);++ const int deletesBefore = d.deleteBufferCalls;+ rm.invalidateGpuMeshes();+ CHECK(d.deleteBufferCalls == deletesBefore,+ "invalidation deletes no buffer — the objects went with the device");+ }++ // --- The generation a realization belongs to is on the record ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ CHECK(rm.getMesh(h)->realizationGeneration == d.deviceGeneration(),+ "a mesh records the device generation it was realized on");++ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();+ CHECK(d.deviceGeneration() == 1, "a rebuilt device is a new generation");+ rm.invalidateGpuMeshes();+ CHECK(rm.getMesh(h)->realizationGeneration == 0,+ "and a mesh not yet rebuilt still carries the OLD one, so nothing can"+ " mistake a stale realization for a current one");+ }++ // --- A released mesh is not owed ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto keep = makeMesh(rm, MeshRecovery::SourceReplayable);+ const auto drop = makeMesh(rm, MeshRecovery::SourceReplayable);+ rm.invalidateGpuMeshes();+ CHECK(rm.meshesAwaitingRematerialization().size() == 2, "both are owed to begin with");++ rm.releaseMesh(drop);+ const auto awaiting = rm.meshesAwaitingRematerialization();+ CHECK(awaiting.size() == 1, "releasing a mesh cancels its debt");+ CHECK(owes(awaiting, keep), "leaving the one that is still there");+ CHECK(!owes(awaiting, drop), "and not an identity nothing holds any more");+ }++ std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);+ return g_failures ? 1 : 0;+}diff --git a/tools/check-mesh-provenance.mjs b/tools/check-mesh-provenance.mjsindex 8857cd51c..3ffee8cb3 100644--- a/tools/check-mesh-provenance.mjs+++ b/tools/check-mesh-provenance.mjs@@ -18,6 +18,10 @@* producer is gone is worse than no table: it reads as an answered question. A* one-way census becomes a graveyard, and a graveyard is what a reader trusts.*+ * The third question is whether the table and the code agree: a producer's class+ * here and the MeshRecovery it hands createMesh are the same answer written+ * twice, and recovery acts on the one no person reads.+ ** What this gate deliberately does NOT do is let recovery infer the answer at* runtime. Missing provenance for a mesh declared recoverable is a defect to be* reported, not evidence that the mesh was host-only all along.@@ -113,7 +117,7 @@ function bodyName(head) {return m ? m[1].replace(/\s+/g, '') : null;}-const NEEDLES = ['createMesh(', `${MINT.pool}.add(`];+const NEEDLES = ['createMesh(', `${MINT.pool}.add(`, 'MeshRecovery::'];/** Each needle occurrence with the function it sits in. */function occurrences(code) {@@ -130,6 +134,7 @@ function occurrences(code) {found.push({index: i,needle,+ enumName: (/^\w+/.exec(code.slice(i + needle.length)) ?? [])[0] ?? null,fn: stack.find((s) => s.fn)?.fn ?? null,qualifier: (/([A-Za-z_]\w*)\s*::\s*$/.exec(code.slice(Math.max(0, i - 96), i))?? [])[1] ?? null,@@ -162,6 +167,8 @@ if (files.length === 0) problems.push(`no engine sources under ${ROOTS.join(', 'const declared = new Map(MESH_PRODUCERS.map((p) => [p.id, p]));/** Producers this run actually found in the sources, for the backwards half. */const discovered = new Map();+/** The MeshRecovery each function hands createMesh, for the table-vs-code half. */+const policies = new Map();let mints = 0;for (const file of files) {@@ -169,6 +176,13 @@ for (const file of files) {const code = blank(readFileSync(file, 'utf8'));for (const hit of occurrences(code)) {const where = `${rel}:${lineOf(code, hit.index)}`;+ if (hit.needle === 'MeshRecovery::') {+ if (hit.fn && hit.enumName) {+ if (!policies.has(hit.fn)) policies.set(hit.fn, []);+ policies.get(hit.fn).push(hit.enumName);+ }+ continue;+ }if (hit.needle !== 'createMesh(') {mints++;if (rel !== MINT.file || hit.fn !== MINT.fn) {@@ -203,10 +217,24 @@ if (mints === 0) {}for (const p of MESH_PRODUCERS) {- if (discovered.has(p.id)) continue;- problems.push(`${p.id} is declared ${p.class} in tools/meshProducers.mjs and no longer mints`- + ` a mesh in ${p.file}. A declaration outliving its producer reads as an answered`- + ' question; drop the row.');+ if (!discovered.has(p.id)) {+ problems.push(`${p.id} is declared ${p.class} in tools/meshProducers.mjs and no longer`+ + ` mints a mesh in ${p.file}. A declaration outliving its producer reads as an`+ + ' answered question; drop the row.');+ continue;+ }+ // The table says one thing and the code hands the engine another: recovery+ // would act on the second, and only the first is ever read by a person.+ const want = CLASSES[p.class]?.policy;+ const said = policies.get(p.id) ?? [];+ if (said.length === 0) {+ problems.push(`${p.id} is declared ${p.class} and names no MeshRecovery where it mints.`+ + ` Hand createMesh MeshRecovery::${want}, so the engine holds the same answer the`+ + ' table does.');+ } else if (said.length > 1 || said[0] !== want) {+ problems.push(`${p.id} is declared ${p.class} (MeshRecovery::${want}) and hands`+ + ` createMesh ${said.map((n) => `MeshRecovery::${n}`).join(', ')}`);+ }}if (problems.length > 0) {diff --git a/tools/meshProducers.mjs b/tools/meshProducers.mjsindex a3c00187a..9a019481c 100644--- a/tools/meshProducers.mjs+++ b/tools/meshProducers.mjs@@ -37,15 +37,21 @@ export const MINT = {* `source` (recoverable) and `why` (non-recoverable) are each owed: a class on* its own is a label, and the sentence beside it is what a later reader checks* the class against.+ *+ * `policy` is the same answer in the engine's own words — the MeshRecovery a+ * producer hands createMesh. Naming it here is what stops the table and the code+ * drifting into two different answers, one of which recovery would act on.*/export const CLASSES = {'asset-backed-recoverable': {owes: 'source',+ policy: 'SourceReplayable',means: 'the geometry is replayable from an asset the loader can load again;'+ ' a handle of this class with no recorded source is a contract violation',},'host-only-non-recoverable': {owes: 'why',+ policy: 'HostOnly',means: 'the geometry exists only in the process that built it, by design;'+ ' a device generation ends it, and no source can bring it back',},