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(assets): a mesh comes back from its source, into the handle it left
esengine589677940bbd
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 60883b021..9a0243017 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -27,7 +27,7 @@ import { DependencyRecorder, isInvalidatable, rebuildPlan, type AssetIdentity,import { SpineAssetLoader } from './loaders/SpineAssetLoader';import { spinePairKey } from '../spine/prepareSpine';import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';-import { MeshAssetLoader } from './loaders/MeshAssetLoader';+import { MeshAssetLoader, type MeshResult } from './loaders/MeshAssetLoader';import { nativeEngineApi, type EngineApi } from '../ecs/bridge/engineApi';import { isBuiltinMeshRef } from './builtinMeshes';import { EnvironmentAssetLoader } from './loaders/EnvironmentAssetLoader';@@ -487,6 +487,49 @@ export class Assets {return restored;}+ /**+ * The meshes the engine says lost their geometry, by handle. No path travels+ * with them: the engine never knew one, and this layer does — which is the+ * division the whole recovery rests on. The engine says WHICH identity is+ * owed; only the asset layer can say what it was made from.+ */+ meshesAwaitingRematerialization(): number[] {+ const raw = requireResourceManager().meshesAwaitingRemat?.() ?? '';+ return raw ? raw.split(',').map(Number).filter((h) => h > 0) : [];+ }++ /**+ * Replays each owed mesh from its source, into the handle it already has.+ *+ * A missing provenance is a CONTRACT VIOLATION, not a mesh that turns out to+ * be unrecoverable: the engine only enqueues what a producer declared+ * replayable, so an absent path means this layer lost the record.+ *+ * @return How many came back. The rest stay owed, so recovery cannot finish.+ */+ async rematerializeMeshesAfterDeviceLoss(): Promise<number> {+ const loader = this.getLoader<MeshResult>('mesh');+ if (!(loader instanceof MeshAssetLoader)) return 0;++ let restored = 0;+ for (const handle of this.meshesAwaitingRematerialization()) {+ const path = this.pathForHandle('mesh', handle);+ if (!path) {+ log.error('assets', `Device recovery: mesh ${handle} is declared replayable and`+ + ' has no recorded source — its provenance was lost, so it cannot come back');+ continue;+ }+ try {+ if (await loader.rematerialize(handle, path, this.getLoadContext_())) restored++;+ else log.error('assets', `Device recovery: the engine refused geometry for ${path}`);+ } catch (e) {+ log.error('assets', `Device recovery: replaying ${path} failed`, e);+ }+ }+ log.info('assets', `Device recovery: ${restored} mesh(es) rematerialized`);+ return restored;+ }+/*** The whole recovery, in the order it has to happen: rebuild what the engine* can, put the content back, then declare the device whole. Returns false@@ -496,12 +539,20 @@ export class Assets {async recoverFromDeviceLoss(): Promise<boolean> {if (!recoverDevice()) return false;await this.reuploadTexturesAfterDeviceLoss();+ await this.rematerializeMeshesAfterDeviceLoss();const pending = finishDeviceRecovery();if (pending > 0) {log.warn('assets',- `Device recovery: ${pending} texture(s) are still the placeholder`);+ `Device recovery: ${pending} texture(s)/mesh(es) have not come back`);return false;}+ // Host-only geometry cannot come back, and a recovery that says nothing+ // about it reads as one where everything did.+ const lost = requireResourceManager().meshesLostNonRecoverable?.() ?? 0;+ if (lost > 0) {+ log.warn('assets', `Device recovery: ${lost} host-only mesh(es) ended with the`+ + ' device — no source can replay them');+ }return true;}diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.tsindex 108fdaed4..654aec1e2 100644--- a/sdk/src/asset/loaders/MeshAssetLoader.ts+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts@@ -4,7 +4,7 @@ import type { AssetLoader, LoadContext } from '../AssetLoader';import type { EngineApi } from '../../ecs/bridge/engineApi';import { marshallingCore } from './engineCore';import { withScratch } from '../../wasm/wasmScratch';-import { decodeMesh, encodeChannelTable } from '../meshFormat';+import { decodeMesh, encodeChannelTable, type MeshData } from '../meshFormat';import { builtinMeshTemplate, isBuiltinMeshRef } from '../builtinMeshes';import { extractPositions, registerMeshCollision, releaseMeshCollision } from '../meshCollision';@@ -31,17 +31,47 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {constructor(private readonly core_: () => EngineApi | null) {}async load(path: string, ctx: LoadContext): Promise<MeshResult> {+ const mesh = await this.decode_(path, ctx);+ const handle = this.upload_(mesh, 0);+ if (!handle) throw new Error(`the engine rejected the geometry in ${path}`);+ // The triangles the decode already produced, kept for whoever needs shape+ // rather than pixels — a collider cannot ask the GPU what it uploaded.+ const positions = extractPositions(mesh.vertices, mesh.vertexCount,+ mesh.vertexStride, mesh.channels);+ if (positions) registerMeshCollision(handle, { positions, indices: mesh.indices });+ return { handle };+ }++ /**+ * Puts the source back behind a handle a device loss emptied.+ *+ * The same decode and upload as {@link load}, aimed at an existing handle: a+ * second `load` would mint a new one that nothing in the world points at. The+ * collision data is CPU-side and survived the loss, so it is not rebuilt.+ */+ async rematerialize(handle: number, path: string, ctx: LoadContext): Promise<boolean> {+ return this.upload_(await this.decode_(path, ctx), handle) !== 0;+ }++ private async decode_(path: string, ctx: LoadContext): Promise<MeshData> {const builtin = isBuiltinMeshRef(path) ? builtinMeshTemplate(path) : undefined;- const mesh = builtin+ return builtin? builtin.build(): decodeMesh(new Uint8Array(await ctx.loadBinary(ctx.catalog.getBuildPath(path))));+ }++ /** Uploads decoded geometry; `target` 0 mints a handle, otherwise the+ * existing one is re-realized. Returns the handle, or 0 on refusal. */+ private upload_(mesh: MeshData, target: number): number {const table = encodeChannelTable(mesh.channels);const m = marshallingCore(this.core_());- if (!m?.mesh_createFromChannels) {- throw new Error('this engine build carries no mesh_createFromChannels');+ const mint = target === 0;+ if (mint ? !m?.mesh_createFromChannels : !m?.mesh_rematerializeFromChannels) {+ throw new Error(`this engine build carries no ${+ mint ? 'mesh_createFromChannels' : 'mesh_rematerializeFromChannels'}`);}- const handle = withScratch(m, (alloc) => {+ return withScratch(m!, (alloc) => {const tablePtr = alloc(table.byteLength);const vertexPtr = alloc(mesh.vertices.byteLength);const indexPtr = alloc(mesh.indices.byteLength);@@ -50,29 +80,31 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {// guess what a vertex is bound to.const bind = mesh.inverseBindMatrices;const bindPtr = bind ? alloc(bind.byteLength) : 0;- m.HEAPU8.set(table, tablePtr);- m.HEAPU8.set(mesh.vertices, vertexPtr);- m.HEAPU8.set(new Uint8Array(mesh.indices.buffer, mesh.indices.byteOffset,- mesh.indices.byteLength), indexPtr);+ m!.HEAPU8.set(table, tablePtr);+ m!.HEAPU8.set(mesh.vertices, vertexPtr);+ m!.HEAPU8.set(new Uint8Array(mesh.indices.buffer, mesh.indices.byteOffset,+ mesh.indices.byteLength), indexPtr);if (bind) {- m.HEAPU8.set(new Uint8Array(bind.buffer, bind.byteOffset, bind.byteLength), bindPtr);+ m!.HEAPU8.set(new Uint8Array(bind.buffer, bind.byteOffset, bind.byteLength),+ bindPtr);}- return m.mesh_createFromChannels!(- tablePtr, mesh.channels.length, mesh.vertexStride,- vertexPtr, mesh.vertices.byteLength,- indexPtr, mesh.indices.length,- mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],- mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2],- bindPtr, bind?.length ?? 0);+ return mint+ ? m!.mesh_createFromChannels!(+ tablePtr, mesh.channels.length, mesh.vertexStride,+ vertexPtr, mesh.vertices.byteLength,+ indexPtr, mesh.indices.length,+ mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],+ mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2],+ bindPtr, bind?.length ?? 0)+ : m!.mesh_rematerializeFromChannels!(+ target,+ tablePtr, mesh.channels.length, mesh.vertexStride,+ vertexPtr, mesh.vertices.byteLength,+ indexPtr, mesh.indices.length,+ mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],+ mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2],+ bindPtr, bind?.length ?? 0);});-- if (!handle) throw new Error(`the engine rejected the geometry in ${path}`);- // The triangles the decode already produced, kept for whoever needs shape- // rather than pixels — a collider cannot ask the GPU what it uploaded.- const positions = extractPositions(mesh.vertices, mesh.vertexCount,- mesh.vertexStride, mesh.channels);- if (positions) registerMeshCollision(handle, { positions, indices: mesh.indices });- return { handle };}unload(asset: MeshResult): void {diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 4b9a57e24..9a7aa2953 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -73,6 +73,7 @@ export interface NativeEngineApi {meshRenderer_setMeshAll?(registry: unknown, meshHandle: number): number;mesh_createFromChannels?(channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number): number;mesh_release?(meshHandle: number): void;+ mesh_rematerializeFromChannels?(targetHandle: number, channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number): number;particle_getAliveCount?(entity: number): number;particle_play?(registry: unknown, entity: number): void;particle_reset?(registry: unknown, entity: number): void;@@ -195,6 +196,8 @@ export interface NativeEngineApi {rm_getTextureRefCount?(rm: unknown, handleId: number): number;rm_invalidateTexturePath?(rm: unknown, path: string): boolean;rm_loadBitmapFont?(rm: unknown, fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;+ rm_meshesAwaitingRemat?(rm: unknown): string;+ rm_meshesLostNonRecoverable?(rm: unknown): number;rm_registerExternalTexture?(rm: unknown, glTextureId: number, width: number, height: number): number;rm_registerExternalTextureSized?(rm: unknown, glTextureId: number, width: number, height: number, bytes: number): number;rm_registerTextureWithPath?(rm: unknown, handleId: number, path: string): void;@@ -327,6 +330,7 @@ export function createNativeEngineApi(bind('meshRenderer_setMeshAll', 'es_meshRenderer_setMeshAll', true);bind('mesh_createFromChannels', 'es_mesh_createFromChannels', false);bind('mesh_release', 'es_mesh_release', false);+ bind('mesh_rematerializeFromChannels', 'es_mesh_rematerializeFromChannels', false);bind('particle_getAliveCount', 'es_particle_getAliveCount', false);bind('particle_play', 'es_particle_play', true);bind('particle_reset', 'es_particle_reset', true);@@ -449,6 +453,8 @@ export function createNativeEngineApi(bind('rm_getTextureRefCount', 'es_rm_getTextureRefCount', true);bind('rm_invalidateTexturePath', 'es_rm_invalidateTexturePath', true);bind('rm_loadBitmapFont', 'es_rm_loadBitmapFont', true);+ bind('rm_meshesAwaitingRemat', 'es_rm_meshesAwaitingRemat', true);+ bind('rm_meshesLostNonRecoverable', 'es_rm_meshesLostNonRecoverable', true);bind('rm_registerExternalTexture', 'es_rm_registerExternalTexture', true);bind('rm_registerExternalTextureSized', 'es_rm_registerExternalTextureSized', true);bind('rm_registerTextureWithPath', 'es_rm_registerTextureWithPath', true);diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 553380e95..d7e186e9a 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -251,6 +251,20 @@ export interface ESEngineModule {minX: number, minY: number, minZ: number,maxX: number, maxY: number, maxZ: number,bindPtr: number, bindFloats: number): number;+ /**+ * Put replayed geometry behind an EXISTING mesh handle after a device loss.+ * Returns the handle it was given, or 0 if the engine refused — never a new+ * handle, which is why this is not a second mesh_createFromChannels: every+ * component in the world still names the mesh by the handle it already has.+ */+ mesh_rematerializeFromChannels?(targetHandle: number,+ channelsPtr: number, channelCount: number,+ vertexStride: number,+ vertexPtr: number, vertexBytes: number,+ indexPtr: number, indexCount: number,+ minX: number, minY: number, minZ: number,+ maxX: number, maxY: number, maxZ: number,+ bindPtr: number, bindFloats: number): number;/** Release a mesh and the buffers it owns. */mesh_release?(meshHandle: number): void;/**diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 286d3c517..6346a4bf6 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -240,31 +240,58 @@ void meshRenderer_setGeometry(ecs::Registry& registry, u32 entity,// Geometry from an .esmesh. The channel table arrives in the file's own layout// (8 bytes each), so the asset layer owns the FORMAT and the engine owns the// vertex layout it becomes. A channel's semantic is its attribute location.-u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,- uintptr_t vertexPtr, u32 vertexBytes,- uintptr_t indexPtr, u32 indexCount,- f32 minX, f32 minY, f32 minZ,- f32 maxX, f32 maxY, f32 maxZ,- uintptr_t bindPtr, u32 bindFloats) {- auto* rm = ctx().tryGet<resource::ResourceManager>();- if (!rm || channelCount == 0 || vertexStride == 0 || vertexBytes == 0 || indexCount == 0) return 0;+namespace {++/** One .esmesh's geometry, marshalled out of wasm memory and validated. */+struct MeshUpload {+ GfxVertexAttribute channels[MAX_VERTEX_ATTRIBUTES];+ u32 channelCount = 0;+ u32 vertexStride = 0;+ const u8* verts = nullptr;+ u32 vertexBytes = 0;+ const u32* indices = nullptr;+ u32 indexCount = 0;+ const f32* bind = nullptr;+ u32 bindFloats = 0;+ glm::vec3 localMin{0.0f};+ glm::vec3 localMax{0.0f};++ ConstSpan<u8> vertexSpan() const { return ConstSpan<u8>(verts, vertexBytes); }+ ConstSpan<u32> indexSpan() const { return ConstSpan<u32>(indices, indexCount); }+ ConstSpan<GfxVertexAttribute> channelSpan() const {+ return ConstSpan<GfxVertexAttribute>(channels, channelCount);+ }+ ConstSpan<f32> bindSpan() const {+ return bind ? ConstSpan<f32>(bind, bindFloats) : ConstSpan<f32>();+ }+};++// Shared by the mint and the rebuild so a mesh cannot be validated one way when+// it arrives and another way when it comes back.+bool marshalMeshChannels(MeshUpload& out, const char* who,+ uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,+ uintptr_t vertexPtr, u32 vertexBytes,+ uintptr_t indexPtr, u32 indexCount,+ f32 minX, f32 minY, f32 minZ,+ f32 maxX, f32 maxY, f32 maxZ,+ uintptr_t bindPtr, u32 bindFloats) {+ if (channelCount == 0 || channelCount > MAX_VERTEX_ATTRIBUTES) return false;+ if (vertexStride == 0 || vertexBytes == 0 || indexCount == 0) return false;if (indexCount % 3 != 0) {- ES_LOG_WARN("mesh_createFromChannels: indexCount {} is not a triangle list", indexCount);- return 0;+ ES_LOG_WARN("{}: indexCount {} is not a triangle list", who, indexCount);+ return false;}- const u8* table = boundarySpan<u8>(channelsPtr, static_cast<u64>(channelCount) * 8,- "mesh_createFromChannels.channels");- const u8* verts = boundarySpan<u8>(vertexPtr, vertexBytes, "mesh_createFromChannels.vertices");- const u32* indices = boundarySpan<u32>(indexPtr, indexCount, "mesh_createFromChannels.indices");- if (!table || !verts || !indices) return 0;+ const u8* table = boundarySpan<u8>(channelsPtr, static_cast<u64>(channelCount) * 8, who);+ const u8* verts = boundarySpan<u8>(vertexPtr, vertexBytes, who);+ const u32* indices = boundarySpan<u32>(indexPtr, indexCount, who);+ if (!table || !verts || !indices) return false;const u32 vertexCount = vertexBytes / vertexStride;for (u32 i = 0; i < indexCount; ++i) {if (indices[i] >= vertexCount) {- ES_LOG_WARN("mesh_createFromChannels: index {} out of range ({} vertices)",- indices[i], vertexCount);- return 0;+ ES_LOG_WARN("{}: index {} out of range ({} vertices)", who, indices[i], vertexCount);+ return false;}}@@ -277,12 +304,9 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexSdefault: return GfxDataType::Float;}};-- GfxVertexAttribute channels[MAX_VERTEX_ATTRIBUTES];- if (channelCount > MAX_VERTEX_ATTRIBUTES) return 0;for (u32 i = 0; i < channelCount; ++i) {const u8* c = table + i * 8;- channels[i] = GfxVertexAttribute{+ out.channels[i] = GfxVertexAttribute{.location = c[0],.components = c[1],.type = channelType(c[2]),@@ -295,17 +319,69 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS// The bind pose rides beside the vertices because the Joints channel indexes// it; a mesh with joints and no matrices is drawn static rather than wrong.- const f32* bind = bindFloats > 0- ? boundarySpan<f32>(bindPtr, bindFloats, "mesh_createFromChannels.inverseBind") : nullptr;- auto handle = rm->createMesh(ConstSpan<u8>(verts, vertexBytes),- ConstSpan<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>());+ out.bind = bindFloats > 0 ? boundarySpan<f32>(bindPtr, bindFloats, who) : nullptr;+ out.bindFloats = bindFloats;+ out.channelCount = channelCount;+ out.vertexStride = vertexStride;+ out.verts = verts;+ out.vertexBytes = vertexBytes;+ out.indices = indices;+ out.indexCount = indexCount;+ out.localMin = glm::vec3(minX, minY, minZ);+ out.localMax = glm::vec3(maxX, maxY, maxZ);+ return true;+}++} // namespace++// Geometry from an .esmesh. The channel table arrives in the file's own layout+// (8 bytes each), so the asset layer owns the FORMAT and the engine owns the+// vertex layout it becomes. A channel's semantic is its attribute location.+u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,+ uintptr_t vertexPtr, u32 vertexBytes,+ uintptr_t indexPtr, u32 indexCount,+ f32 minX, f32 minY, f32 minZ,+ f32 maxX, f32 maxY, f32 maxZ,+ uintptr_t bindPtr, u32 bindFloats) {+ auto* rm = ctx().tryGet<resource::ResourceManager>();+ MeshUpload up;+ if (!rm || !marshalMeshChannels(up, "mesh_createFromChannels",+ channelsPtr, channelCount, vertexStride,+ vertexPtr, vertexBytes, indexPtr, indexCount,+ minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats)) {+ return 0;+ }+ auto handle = rm->createMesh(up.vertexSpan(), up.indexSpan(), up.channelSpan(), up.vertexStride,+ up.localMin, up.localMax,+ MeshRecovery::SourceReplayable, up.bindSpan());return handle.id();}+// The same geometry arriving for a SECOND time, behind a handle that already+// exists: a device generation ended and the asset layer is replaying the source.+// Minting here instead would leave every component pointing at the dead mesh.+u32 mesh_rematerializeFromChannels(u32 targetHandle,+ uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,+ uintptr_t vertexPtr, u32 vertexBytes,+ uintptr_t indexPtr, u32 indexCount,+ f32 minX, f32 minY, f32 minZ,+ f32 maxX, f32 maxY, f32 maxZ,+ uintptr_t bindPtr, u32 bindFloats) {+ auto* rm = ctx().tryGet<resource::ResourceManager>();+ MeshUpload up;+ if (!rm || targetHandle == 0+ || !marshalMeshChannels(up, "mesh_rematerializeFromChannels",+ channelsPtr, channelCount, vertexStride,+ vertexPtr, vertexBytes, indexPtr, indexCount,+ minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats)) {+ return 0;+ }+ return rm->rematerializeMesh(resource::MeshHandle(targetHandle),+ up.vertexSpan(), up.indexSpan(), up.channelSpan(),+ up.vertexStride, up.localMin, up.localMax, up.bindSpan())+ ? targetHandle : 0;+}+/** @brief Releases a mesh and the buffers it owns. */void mesh_release(u32 meshHandle) {if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 7504efb3a..6cca81ae2 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -78,6 +78,17 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexSf32 maxX, f32 maxY, f32 maxZ,uintptr_t bindPtr, u32 bindFloats);/** @brief Releases a mesh and the buffers it owns. */+/** @brief Puts replayed geometry behind an EXISTING mesh handle after a device+ * loss. Returns @p targetHandle on success, 0 on failure — never a new+ * handle, which is the whole reason this is not mesh_createFromChannels. */+u32 mesh_rematerializeFromChannels(u32 targetHandle,+ uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,+ uintptr_t vertexPtr, u32 vertexBytes,+ uintptr_t indexPtr, u32 indexCount,+ f32 minX, f32 minY, f32 minZ,+ f32 maxX, f32 maxY, f32 maxZ,+ uintptr_t bindPtr, u32 bindFloats);+void mesh_release(u32 meshHandle);/** @brief Registers a baked environment (27 irradiance floats + a reflection atlas). */diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 8dc437cc1..dbae11762 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -525,6 +525,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("renderer_submitTextBatch", &esengine::renderer_submitTextBatch);emscripten::function("meshRenderer_setGeometry", &esengine::meshRenderer_setGeometry);emscripten::function("mesh_createFromChannels", &esengine::mesh_createFromChannels);+ emscripten::function("mesh_rematerializeFromChannels", &esengine::mesh_rematerializeFromChannels);emscripten::function("mesh_release", &esengine::mesh_release);emscripten::function("environment_create", &esengine::environment_create);emscripten::function("environment_release", &esengine::environment_release);diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex caee611b6..49fd407d4 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -485,19 +485,19 @@ void ResourceManager::releaseVertexBuffer(VertexBufferHandle handle) {// Mesh Resources// =============================================================================-MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,- ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,- const glm::vec3& localMin, const glm::vec3& localMax,- MeshRecovery recovery, ConstSpan<f32> inverseBind) {- if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty()) return MeshHandle();+bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,+ ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,+ const glm::vec3& localMin, const glm::vec3& localMax,+ ConstSpan<f32> inverseBind) {+ if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty()) return false;// The mesh describes its own vertices; the per-object transform is the// engine's and is appended here, so no caller has to know how a transform// reaches the shader — the reason a mesh is drawn without touching its bytes.VertexLayoutDesc layout;if (channels.size() + MESH_INSTANCE_ATTRIBUTES > MAX_VERTEX_ATTRIBUTES) {- ES_LOG_ERROR("createMesh: {} channels exceeds the layout budget", channels.size());- return MeshHandle();+ ES_LOG_ERROR("realizeMesh: {} channels exceeds the layout budget", channels.size());+ return false;}for (usize i = 0; i < channels.size(); ++i) {layout.attributes[i] = channels[i];@@ -535,34 +535,98 @@ MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32>}layout.attributeCount = next;+ // The old records go only once the new ones stand: a rematerialization that+ // fails half-way must leave the mesh as it found it, not stripped of the+ // realization it still had.+ const VertexBufferHandle previousVertices = mesh.vertices;+ const IndexBufferHandle previousIndices = mesh.indices;++ const VertexBufferHandle vertices = createVertexBuffer(vertexBytes);+ const IndexBufferHandle indices_handle = createIndexBuffer(indices);+ const VertexBuffer* vb = getVertexBuffer(vertices);+ const IndexBuffer* ib = getIndexBuffer(indices_handle);+ const VertexLayoutHandle layoutHandle = device_->createVertexLayout(layout);+ // A pool record is not a GPU object. An allocation the device refused still+ // lands in the pool, so its handle reads as valid while naming nothing — the+ // shape in which a failure becomes a mesh that silently draws no triangles.+ if (!vb || !ib || vb->handle() == BufferHandle::Invalid+ || ib->handle() == BufferHandle::Invalid || layoutHandle == VertexLayoutHandle::Invalid) {+ releaseVertexBuffer(vertices);+ releaseIndexBuffer(indices_handle);+ return false;+ }++ releaseVertexBuffer(previousVertices);+ releaseIndexBuffer(previousIndices);++ mesh.vertices = vertices;+ mesh.indices = indices_handle;+ mesh.vertexBuffer = vb->handle();+ mesh.indexBuffer = ib->handle();+ mesh.layout = layoutHandle;+ mesh.indexCount = static_cast<u32>(indices.size());+ mesh.realizationGeneration = device_->deviceGeneration();+ mesh.hasNormals = hasNormals;+ mesh.localMin = localMin;+ mesh.localMax = localMax;+ mesh.inverseBind.clear();+ if (skinned) {+ const usize joints = inverseBind.size() / 16;+ mesh.inverseBind.resize(joints);+ std::memcpy(mesh.inverseBind.data(), inverseBind.data(), joints * sizeof(glm::mat4));+ }+ return true;+}++MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,+ ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,+ const glm::vec3& localMin, const glm::vec3& localMax,+ MeshRecovery recovery, ConstSpan<f32> inverseBind) {auto mesh = makeUnique<Mesh>();- mesh->vertices = createVertexBuffer(vertexBytes);- mesh->indices = createIndexBuffer(indices);- if (!mesh->vertices.isValid() || !mesh->indices.isValid()) {- releaseVertexBuffer(mesh->vertices);- releaseIndexBuffer(mesh->indices);+ if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,+ localMin, localMax, inverseBind)) {return MeshHandle();}-- const VertexBuffer* vb = getVertexBuffer(mesh->vertices);- const IndexBuffer* ib = getIndexBuffer(mesh->indices);- mesh->vertexBuffer = vb ? vb->handle() : BufferHandle::Invalid;- 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;- if (skinned) {- const usize joints = inverseBind.size() / 16;- mesh->inverseBind.resize(joints);- std::memcpy(mesh->inverseBind.data(), inverseBind.data(), joints * sizeof(glm::mat4));- }return meshes_.add(std::move(mesh));}+bool ResourceManager::rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexBytes,+ ConstSpan<u32> indices,+ ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,+ const glm::vec3& localMin, const glm::vec3& localMax,+ ConstSpan<f32> inverseBind) {+ Mesh* mesh = meshes_.get(target);+ if (!mesh) {+ ES_LOG_ERROR("rematerializeMesh: handle {} names no live mesh", target.id());+ return false;+ }+ // A producer's answer is given once, at mint. Recovery replaces geometry; it+ // never gets to decide that geometry is recoverable.+ if (mesh->recovery != MeshRecovery::SourceReplayable) {+ ES_LOG_ERROR("rematerializeMesh: mesh {} is host-only and has no source to replay",+ target.id());+ return false;+ }+ if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,+ localMin, localMax, inverseBind)) {+ ES_LOG_ERROR("rematerializeMesh: mesh {} could not be rebuilt; it stays owed",+ target.id());+ return false;+ }++ // Acknowledged only now. The debt is cleared by a rebuild that WORKED, never+ // by the attempt — a handle dropped on failure is a hole nothing reports.+ for (usize i = 0; i < awaitingRematerialization_.size(); ++i) {+ if (awaitingRematerialization_[i] == target) {+ awaitingRematerialization_[i] = awaitingRematerialization_.back();+ awaitingRematerialization_.pop_back();+ break;+ }+ }+ return true;+}+Mesh* ResourceManager::getMesh(MeshHandle handle) {return meshes_.get(handle);}diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 2bcc2a701..6d71d3a88 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -468,6 +468,20 @@ public:const glm::vec3& localMin, const glm::vec3& localMax,MeshRecovery recovery, ConstSpan<f32> inverseBind = {});+ /**+ * @brief Puts new geometry behind an EXISTING mesh handle.+ *+ * @details Same identity, a fresh realization. Re-uploading through createMesh+ * would mint a SECOND handle and leave every component on the dead+ * one. Refuses a host-only mesh; clears the debt only on success.+ * @return False if the handle names no live mesh, is not replayable, or the+ * geometry could not be rebuilt.+ */+ bool rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,+ ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,+ const glm::vec3& localMin, const glm::vec3& localMax,+ ConstSpan<f32> inverseBind = {});+/** @brief The mesh a handle names, or null. */Mesh* getMesh(MeshHandle handle);const Mesh* getMesh(MeshHandle handle) const;@@ -665,6 +679,14 @@ private:/// Handles whose GPU texture died with the device, still showing the/// placeholder. Empty means the content is whole again.std::vector<TextureHandle> awaitingReupload_;+ /** Builds the buffers and layout one mesh is drawn from, replacing whatever+ * it had. Shared by the mint and the rebuild so the two cannot describe the+ * same geometry differently. Leaves the mesh untouched when it fails. */+ bool realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,+ ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,+ const glm::vec3& localMin, const glm::vec3& localMax,+ ConstSpan<f32> inverseBind);+std::vector<MeshHandle> awaitingRematerialization_;u32 meshes_lost_non_recoverable_ = 0;std::unordered_map<std::string, TextureHandle> guidToTexture_;diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hppindex 52666b0fd..025d1357d 100644--- a/tests/renderer/MockGfxDevice.hpp+++ b/tests/renderer/MockGfxDevice.hpp@@ -129,10 +129,15 @@ struct MockGfxDevice final : GfxDevice {void setScissorTest(bool) override {}void setScissor(i32, i32, i32, i32) override {}+ /** Set false to make allocation fail, the way a GPU out of memory does — the+ * path a caller's "leaves it as it found it" promise is only true along. */+ bool createBufferSucceeds = true;+BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override {++createBufferCalls;lastBufferDesc = desc;lastCreateBufferHadData = initialData != nullptr;+ if (!createBufferSucceeds) return BufferHandle::Invalid;return BufferHandle{nextBufferId++};}void deleteBuffer(BufferHandle) override { ++deleteBufferCalls; }diff --git a/tests/resource/test_mesh_recovery.cpp b/tests/resource/test_mesh_recovery.cppindex 45fda4723..1f92176f2 100644--- a/tests/resource/test_mesh_recovery.cpp+++ b/tests/resource/test_mesh_recovery.cpp@@ -167,6 +167,147 @@ int main() {CHECK(!owes(awaiting, drop), "and not an identity nothing holds any more");}+ // --- A mint the GPU refuses hands back nothing, not a mesh that draws nothing ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);+ d.createBufferSucceeds = false;++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ CHECK(!h.isValid(),+ "a mesh whose buffers the device refused is not minted at all — a pool record"+ " reads as valid while naming no GPU object, and would draw nothing forever");+ }++ // --- The source comes back INTO the handle it left ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ const Mesh* record = rm.getMesh(h);+ rm.invalidateGpuMeshes();+ CHECK(!record->hasRealization(), "the mesh starts owed and unrealized");++ const Vertex verts[3] = {{0, 0, 0, 0, 0}, {2, 0, 0, 1, 0}, {0, 2, 0, 0, 1}};+ const u32 indices[3] = {0, 1, 2};+ const bool ok = rm.rematerializeMesh(+ h, 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(2.0f));++ CHECK(ok, "a replayed source rematerializes");+ CHECK(rm.getMesh(h) == record, "into the SAME record — no second handle was minted");+ CHECK(record->hasRealization(), "which has a realization again");+ CHECK(record->isDrawable(), "and is drawable again");+ CHECK(record->vertexBuffer != BufferHandle::Invalid, "on a new VBO");+ CHECK(record->indexBuffer != BufferHandle::Invalid, "a new EBO");+ CHECK(record->layout != VertexLayoutHandle::Invalid, "and a new vertex layout");+ CHECK(record->localMax == glm::vec3(2.0f), "carrying the geometry that was replayed");+ CHECK(rm.meshesAwaitingRematerialization().empty(),+ "and the debt is acknowledged, because the rebuild worked");+ }++ // --- A rebuild that fails leaves the debt standing ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ rm.invalidateGpuMeshes();++ // Empty geometry: the decode produced nothing usable.+ const bool ok = rm.rematerializeMesh(+ h, ConstSpan<u8>(), ConstSpan<u32>(), ConstSpan<GfxVertexAttribute>(kChannels, 2),+ sizeof(Vertex), glm::vec3(0.0f), glm::vec3(1.0f));++ CHECK(!ok, "a rebuild that cannot happen reports failure");+ CHECK(owes(rm.meshesAwaitingRematerialization(), h),+ "and the handle is STILL owed — a debt dropped on failure is a hole nothing reports");+ CHECK(!rm.getMesh(h)->hasRealization(), "the mesh stays unrealized rather than half-built");+ }++ // --- A failed rebuild leaves a LIVE mesh exactly as it found it ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ const Mesh* record = rm.getMesh(h);+ const BufferHandle vbo = record->vertexBuffer;+ const BufferHandle ebo = record->indexBuffer;+ CHECK(record->hasRealization(), "the mesh is realized to begin with");++ const bool empty = rm.rematerializeMesh(h, ConstSpan<u8>(), ConstSpan<u32>(),+ ConstSpan<GfxVertexAttribute>(kChannels, 2),+ sizeof(Vertex), glm::vec3(0.0f), glm::vec3(1.0f));+ CHECK(!empty, "a rebuild with nothing to build from fails");+ CHECK(record->hasRealization(), "and the mesh keeps what it had");++ // The other way it fails, and the one the promise is actually about: the+ // geometry is fine and the GPU cannot allocate for it.+ d.createBufferSucceeds = false;+ 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};+ const bool oom = rm.rematerializeMesh(+ h, 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));+ CHECK(!oom, "a rebuild the GPU cannot allocate for fails");+ CHECK(record->hasRealization(),+ "and the mesh KEEPS the realization it had — a rebuild that cannot finish must"+ " not take away the geometry that was already drawing");+ CHECK(record->vertexBuffer == vbo, "the same VBO");+ CHECK(record->indexBuffer == ebo, "and the same EBO");+ }++ // --- Host-only geometry cannot be rematerialized into ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::HostOnly);+ rm.invalidateGpuMeshes();++ 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};+ const bool ok = rm.rematerializeMesh(+ h, 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));+ CHECK(!ok, "a host-only mesh refuses geometry it never had a source for");+ CHECK(!rm.getMesh(h)->hasRealization(), "and stays gone, as its producer declared");+ }++ // --- A rematerialized mesh belongs to the CURRENT generation ---+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);++ const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);+ CHECK(rm.getMesh(h)->realizationGeneration == 0, "minted on generation 0");++ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();+ rm.invalidateGpuMeshes();++ 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};+ rm.rematerializeMesh(+ h, 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));+ CHECK(rm.getMesh(h)->realizationGeneration == 1,+ "a rebuilt mesh records the generation it was rebuilt ON, so a stale realization"+ " cannot pass for a current one");+ }+std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);return g_failures ? 1 : 0;}