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(native): Spine on the device — the last subsystem a device could not render
yhh3aca89078cb4
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex 927eb8d9f..09dd0e1cd 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -59,6 +59,7 @@ export const ENGINE_BINDING_HEADERS = [export const MODULE_BINDING_HEADERS = ['PhysicsBindings.hpp','VideoBindings.hpp',+ 'SpineBindings.hpp',];export const NATIVE_BINDING_HEADERS = [...ENGINE_BINDING_HEADERS, ...MODULE_BINDING_HEADERS];diff --git a/desktop/src/project/targetSupport.ts b/desktop/src/project/targetSupport.tsindex 650a0e69f..f48c77dfa 100644--- a/desktop/src/project/targetSupport.ts+++ b/desktop/src/project/targetSupport.ts@@ -3,13 +3,16 @@/*** @file What a build target can render — and what it cannot.*- * The editor authors every subsystem the engine has; a target does not- * necessarily compile all of them. The native app builds a subset: the flags- * `native/CMakeLists.txt` sets decide what `cmake/ESEngineSources.cmake` compiles- * in, and of the optional emscripten side modules Box2D and the video decoder are- * compiled into the host binary (there is no dynamic-linking story on a device) while- * the Spine runtime is not there yet. iOS and Android build from that same- * CMakeLists, so their gaps are one list.+ * The editor authors every subsystem the engine has; a target does not necessarily+ * compile all of them, and this is where that is declared.+ *+ * The native app has no gap left: the flags `native/CMakeLists.txt` sets bring in the+ * whole engine source list, and the three optional runtimes that ship as emscripten+ * side modules on the web (Box2D, the Spine runtime, the video decoder) are compiled+ * into the host binary instead — a device has no dynamic-linking story to have. The+ * table stays because that can change: turn a flag off, or add a subsystem that only+ * one platform can host, and the entry belongs here so the export can name it rather+ * than writing a package that is quietly missing half a scene.** Without this, an export writes a package that is quietly missing half a* scene. This is the one declaration of that gap, so the export can name it@@ -74,11 +77,11 @@ export interface SubsystemGap {why: string;}-/** What the native app cannot render. ONE list: iOS and Android compile the same- * `native/CMakeLists.txt`, so a flag flipped there closes the gap on both. */-const NATIVE_GAPS: readonly SubsystemGap[] = [- { subsystem: 'spine', why: 'the Spine runtime ships as an emscripten side module; the native host has no counterpart yet' },-];+/** What the native app cannot render — currently nothing. ONE list: iOS and Android+ * compile the same `native/CMakeLists.txt`, so a flag flipped there opens or closes+ * the gap on both. `desktop/tests/target-support.test.ts` reads that file and fails+ * when the two disagree. */+const NATIVE_GAPS: readonly SubsystemGap[] = [];/*** Per-target gaps. A platform absent from this table has none *known*: only the@@ -130,9 +133,12 @@ const MAX_NAMED_FILES = 3;export function subsystemGapWarnings(platform: ExportPlatform,usage: ReadonlyMap<Subsystem, readonly string[]>,+ /** The gaps to report; defaults to this platform's declared ones. Overridable so+ * the reporting can be exercised while no target actually has a gap. */+ gaps: readonly SubsystemGap[] = targetGaps(platform),): string[] {const warnings: string[] = [];- for (const gap of targetGaps(platform)) {+ for (const gap of gaps) {const files = usage.get(gap.subsystem);if (!files || files.length === 0) continue;const named = [...files].sort();diff --git a/desktop/tests/target-support.test.ts b/desktop/tests/target-support.test.tsindex e2beede11..4e9523150 100644--- a/desktop/tests/target-support.test.ts+++ b/desktop/tests/target-support.test.ts@@ -56,23 +56,29 @@ describe('subsystemGapWarnings', () => {const usage = new Map<Subsystem, string[]>([['spine', ['scenes/b.esscene', 'scenes/a.esscene']]]);it('names the subsystem, the reason and the files', () => {- const [warning, ...rest] = subsystemGapWarnings('android', usage);+ // Driven through a declared gap rather than a real one: every subsystem is+ // supported on every target today, and the reporting still has to work for the+ // day one is not (a flag turned off, a new platform-bound feature).+ const declared = [{ subsystem: 'spine' as Subsystem, why: 'a made-up gap, for this test' }];+ const [warning, ...rest] = subsystemGapWarnings('android', usage, declared);expect(rest).toEqual([]);expect(warning).toContain('Spine animation will not render');+ expect(warning).toContain('a made-up gap, for this test');expect(warning).toContain('scenes/a.esscene, scenes/b.esscene');});- it('is silent for a target with no known gaps', () => {- expect(subsystemGapWarnings('web', usage)).toEqual([]);+ it('is silent about a gap the content does not use', () => {+ const declared = [{ subsystem: 'spine' as Subsystem, why: 'a made-up gap' }];+ expect(subsystemGapWarnings('android', new Map(), declared)).toEqual([]);});- it('is silent about a gap the content does not use', () => {- expect(subsystemGapWarnings('ios', new Map())).toEqual([]);+ it('says nothing at all now that every target compiles every subsystem', () => {+ expect(subsystemGapWarnings('android', usage)).toEqual([]);+ expect(subsystemGapWarnings('web', usage)).toEqual([]);});it('reports the same gaps for both native targets — they compile one CMakeLists', () => {expect(targetGaps('ios')).toEqual(targetGaps('android'));- expect(targetGaps('ios').length).toBeGreaterThan(0);});});@@ -132,22 +138,16 @@ describe('exportGame warns about content the target cannot render', () => {outDir, platform, title: 'Game',});- it('names every unsupported subsystem the scene uses — and ships anyway', async () => {+ it('warns about nothing: the native build renders everything this scene uses', async () => {+ // The scene deliberately authors every optional subsystem — text, particles,+ // tilemaps, physics and spine — and the native app compiles all of them now, so+ // any warning here would be false. The reporting mechanism itself is covered+ // above, against a declared gap.const res = await run('android', path.join(root, 'dist-android'));expect(res.errors).toEqual([]);expect(res.ok).toBe(true);const gaps = res.warnings.filter((w) => w.startsWith('android:'));- expect(gaps).toHaveLength(1);- expect(gaps.join('\n')).toContain('Spine animation will not render');- expect(gaps.join('\n')).toContain('scenes/main.esscene');- // What the native build DOES have is not warned about: text (the host- // rasterizes glyphs for the same atlas), tilemaps, particles,- // post-processing, and physics (Box2D compiles into the host binary). The- // gaps are what the build really cannot do, not everything optional.- expect(gaps.join('\n')).not.toContain('Text will not render');- expect(gaps.join('\n')).not.toContain('Tilemaps will not render');- expect(gaps.join('\n')).not.toContain('Particles will not render');- expect(gaps.join('\n')).not.toContain('Physics (Box2D) will not render');+ expect(gaps).toEqual([]);}, 60_000);it('stays quiet for a target that renders all of it', async () => {diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex c424f4f2a..8b10f74c4 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -71,6 +71,31 @@ set(BOX2D_UNIT_TESTS OFF CACHE BOOL "" FORCE)set(BOX2D_VALIDATE OFF CACHE BOOL "" FORCE) # release: no heavy internal assertionsadd_subdirectory("${TP}/box2d" "${CMAKE_BINARY_DIR}/box2d" EXCLUDE_FROM_ALL)+# The Spine runtime: spine-c plus the module's entry points, compiled into the host.+# The three vendored runtimes (3.8 / 4.1 / 4.2) export the same symbol names, so a+# binary carries exactly ONE — which is why the web ships a module per version and a+# native app picks at build time. `spine_runtimeVersion()` reports the choice, and the+# SDK's acquirer answers only that version's id.+set(ESTELLA_SPINE_VERSION "4.2" CACHE STRING "Spine runtime to link (4.2 / 4.1 / 3.8)")+set(SPINE_DIR "${TP}/spine-runtimes-${ESTELLA_SPINE_VERSION}/spine-c/spine-c")+if(NOT EXISTS "${SPINE_DIR}/include")+ message(FATAL_ERROR "Spine runtime ${ESTELLA_SPINE_VERSION} not vendored at ${SPINE_DIR}. "+ "Pass -DESTELLA_SPINE_VERSION=<4.2|4.1|3.8>.")+endif()+file(GLOB SPINE_SOURCES "${SPINE_DIR}/src/spine/*.c")+add_library(spine_c STATIC ${SPINE_SOURCES})+target_include_directories(spine_c PUBLIC "${SPINE_DIR}/include")+target_compile_options(spine_c PRIVATE -w) # vendored C, not ours to lint++add_library(estella_spine STATIC "${SRC}/esengine/bindings/SpineModuleEntry.cpp")+target_include_directories(estella_spine PUBLIC "${SRC}")+target_link_libraries(estella_spine PUBLIC spine_c)+if(ESTELLA_SPINE_VERSION STREQUAL "4.1")+ target_compile_definitions(estella_spine PRIVATE ES_SPINE_41)+elseif(ESTELLA_SPINE_VERSION STREQUAL "3.8")+ target_compile_definitions(estella_spine PRIVATE ES_SPINE_38)+endif()+# The engine's own MPEG-1 decoder (pl_mpeg), the same TU the web links as the# "videodec" side module. Header-only dependency, so nothing to fetch.add_library(estella_video STATIC "${SRC}/esengine/bindings/VideoModuleEntry.cpp")@@ -113,6 +138,9 @@ set(ES_ENABLE_BITMAP_TEXT ON)set(ES_ENABLE_TILEMAP ON)set(ES_ENABLE_PARTICLES ON)set(ES_ENABLE_POSTPROCESS ON)+# Spine: the runtime itself is a separate library (above); this only gates the+# renderer's spine RenderItem plumbing inside the engine's own TUs.+set(ES_ENABLE_SPINE ON)include(ESEngineSources)add_library(esengine STATIC ${ESENGINE_SOURCES})@@ -123,7 +151,7 @@ target_include_directories(esengine PUBLIC"${ESTELLA_DAWN_BUILD}/gen/include") # generated <dawn/webgpu.h>target_compile_definitions(esengine PUBLIC # NOT ES_PLATFORM_WEBES_ENABLE_WEBGPU ES_ENABLE_BITMAP_TEXT- ES_ENABLE_TILEMAP ES_ENABLE_PARTICLES ES_ENABLE_POSTPROCESS)+ ES_ENABLE_TILEMAP ES_ENABLE_PARTICLES ES_ENABLE_POSTPROCESS ES_ENABLE_SPINE)target_link_libraries(esengine PUBLIC glm yogacore webgpu_dawn)# The host (opt-in): a QuickJS runtime drives the engine through the EHT-generated@@ -193,7 +221,7 @@ if(ESTELLA_QUICKJS_DIR)# archive, so these also live in native/ios/project.yml).set_source_files_properties(host/media/native_audio.cpp PROPERTIESCOMPILE_OPTIONS "-x;objective-c++")- target_link_libraries(estella_js_host esengine estella_physics estella_video qjs+ target_link_libraries(estella_js_host esengine estella_physics estella_video estella_spine qjs"-framework UIKit" "-framework QuartzCore" "-framework Foundation""-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox""-framework CoreText" "-framework CoreGraphics")@@ -204,13 +232,15 @@ if(ESTELLA_QUICKJS_DIR)$<TARGET_FILE:estella_js_host> $<TARGET_FILE:esengine>$<TARGET_FILE:estella_physics> $<TARGET_FILE:box2d>$<TARGET_FILE:estella_video>+ $<TARGET_FILE:estella_spine> $<TARGET_FILE:spine_c>$<TARGET_FILE:qjs> $<TARGET_FILE:yogacore> "${ESTELLA_DAWN_LIB}"COMMENT "Merging the iOS host, engine and Dawn into libestella_ios.a")else()# Android: plain C++; miniaudio dlopens AAudio/OpenSL at runtime (no extra# link libs). native_audio.cpp's Obj-C paths are __APPLE__-guarded out.add_library(estella_js_host SHARED ${HOST_SOURCES} host/platform/android.cpp)- target_link_libraries(estella_js_host esengine estella_physics estella_video qjs native_app_glue android log)+ target_link_libraries(estella_js_host esengine estella_physics estella_video estella_spine+ qjs native_app_glue android log)set_target_properties(estella_js_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")endif()# host/ is the include root: every host TU spells its siblings from therediff --git a/native/README.md b/native/README.mdindex 090204b30..436e9a640 100644--- a/native/README.md+++ b/native/README.md@@ -41,6 +41,22 @@ Dawn and QuickJS are **not vendored** (multi-GB / separate project); the recipefetches them, the way Dawn fetches its own deps. Nothing here is compiled by theweb/emscripten build or CI — it is inert until you run the native build below.+### The optional runtimes are compiled IN, not side-loaded++On the web, Box2D, the Spine runtime and the MPEG-1 decoder ship as standalone wasm+side modules a realm fetches. A device has no dynamic-linking story and no reason for+one, so the **same C sources** link straight into the host binary — all three are+vendored — and the SDK reaches them through the QuickJS wrappers EHT generates from+their binding headers. `app.sideModules` still answers them, so the runtime's own+gating installs physics or spine exactly as it does in a browser (see+`sdk/src/ecs/nativeSideModules.ts`).++Spine is the one build-time choice: the three vendored runtimes (3.8 / 4.1 / 4.2)+export the same symbol names, so a binary carries exactly one.+`-DESTELLA_SPINE_VERSION=4.1` picks another; `spine_runtimeVersion()` reports what+was linked, and content authored against a different release is told so by name+instead of being decoded by the wrong parser.+## Why this works (the architecture, proven on device)The engine is portable by construction; the native seams are small and already indiff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex 42e6a717e..363df1135 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -16,7 +16,7 @@ collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]controller: SpineModuleControllerenableEvents: (entity: Entity) => voidentityCount: number-extractAndSubmitMeshes: (coreModule: ESEngineModule, registry: CppRegistry) => void+extractAndSubmitMeshes: (core: NonNullable<EngineApi>, registry: CppRegistry) => voidgetAnimations: (entity: Entity) => string[]getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | nullgetPathConstraintMix: (entity: Entity, name: string) => PathMixData | null@@ -131,7 +131,7 @@ submitMeshes: (registry: CppRegistry) => voidupdateAnimations: (dt: number) => voidstatic detectVersion: (data: Uint8Array) => SpineVersion | nullstatic detectVersionJson: (json: string) => SpineVersion | null-static new (coreModule: ESEngineModule, moduleFactories: Map<SpineVersion, SpineModuleFactory>): SpineManager+static new (coreModule: NonNullable<EngineApi>, moduleFactories: Map<SpineVersion, SpineModuleFactory>): SpineManagerstatic prototype: SpineManager```@@ -216,12 +216,12 @@ mixY: number## loadSpineAssets — function```-(module: ESEngineModule, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider): Promise<Map<string, SpineAssetInfo>>+(module: ESEngineModule | null, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider): Promise<Map<string, SpineAssetInfo>>```## loadSpineSceneEntities — function```-(opts: { module: ESEngineModule; source: RuntimeAssetSource; spineManager: SpineManager; sceneData: SceneData; entityMap: Map<number, Entity>; registry: CppRegistry; transcoderProvider?: TranscoderProvider; }): Promise<void>+(opts: { module: ESEngineModule | null; source: RuntimeAssetSource; spineManager: SpineManager; sceneData: SceneData; entityMap: Map<number, Entity>; registry: CppRegistry; transcoderProvider?: TranscoderProvider; }): Promise<void>```## spineEntityProps — functiondiff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.tsindex 6b76f55bc..a8a5d6727 100644--- a/sdk/src/ecs/nativeRuntime.ts+++ b/sdk/src/ecs/nativeRuntime.ts@@ -36,6 +36,7 @@ import { cameraPlugin } from '../camera/CameraPlugin';import { UICameraInfo } from '../ui/core/ui-camera-info';import { DEFAULT_UI_CAMERA_INFO } from '../corePlugin';import { uiPlugin } from '../ui/ui-plugin';+import { SpinePlugin } from '../spine';import { setNativeTextSubmit } from '../ui/text/submit';import { initResourceManager } from '../resourceManager';import { Assets as AssetsClass } from '../asset/Assets';@@ -113,6 +114,10 @@ export function createNativeApp(// each one reports a core that compiles its subsystem out.installNativePostProcess(app);app.addPlugins(presentationBasePlugins());+ // Spine, like on the web, is a fresh plugin instance per App (it holds a+ // SpineManager keyed to this app's core) and builds its runtime backends from+ // `app.sideModules` — which on a device is the runtime compiled into the binary.+ app.addPlugin(new SpinePlugin());return app;}diff --git a/sdk/src/ecs/nativeSideModules.ts b/sdk/src/ecs/nativeSideModules.tsindex 39642b6b5..4450d6039 100644--- a/sdk/src/ecs/nativeSideModules.ts+++ b/sdk/src/ecs/nativeSideModules.ts@@ -22,7 +22,7 @@*/import { createSideModuleHost, type SideModuleHost, type SideModule } from '../sideModules/host';-import type { SideModuleId } from '../sideModules/registry';+import { SPINE_VERSIONS, spineModuleId, type SideModuleId } from '../sideModules/registry';import { log } from '../logger';import { createNativeHeap, type NativeHeap } from './nativeHeap';@@ -34,8 +34,45 @@ import { createNativeHeap, type NativeHeap } from './nativeHeap';export const NATIVE_SIDE_MODULE_PROBES: Partial<Record<SideModuleId, string>> = {physics: 'es_physics_init',videodec: 'es_video_open',+ // One entry per Spine version the SDK can ask for; which one this host actually+ // linked is a second question (see SPINE_VERSION_BINDING), because the three+ // vendored runtimes export the same symbols and a binary carries exactly one.+ 'spine:4.2': 'es_spine_loadSkeleton',+ 'spine:4.1': 'es_spine_loadSkeleton',+ 'spine:3.8': 'es_spine_loadSkeleton',};+/** The host global that reports the linked Spine runtime (38 / 41 / 42). */+export const SPINE_VERSION_BINDING = 'es_spine_runtimeVersion';++/** The id the host's own Spine runtime answers to, or null if it linked none. */+function nativeSpineId(scope: Record<string, unknown>): SideModuleId | null {+ const report = scope[SPINE_VERSION_BINDING];+ if (typeof report !== 'function') return null;+ const version = (report as () => number)();+ const id = SPINE_VERSIONS.find((v) => v.replace('.', '') === String(version));+ return id ? spineModuleId(id) : null;+}++/** A NUL-terminated UTF-8 string at `ptr` in the heap; empty for a null pointer,+ * which is what emscripten's UTF8ToString(0) answers. */+function readUtf8(heap: NativeHeap, ptr: number): string {+ if (!ptr) return '';+ let end = ptr;+ while (end < heap.HEAPU8.length && heap.HEAPU8[end] !== 0) end++;+ return new TextDecoder().decode(heap.HEAPU8.subarray(ptr, end));+}++/** Copy `str` into the heap as NUL-terminated UTF-8; the caller frees it. */+function writeUtf8(heap: NativeHeap, str: string): number {+ const bytes = new TextEncoder().encode(str);+ const ptr = heap._malloc(bytes.length + 1);+ if (!ptr) return 0;+ heap.HEAPU8.set(bytes, ptr);+ heap.HEAPU8[ptr + bytes.length] = 0;+ return ptr;+}+/*** The host global behind an emscripten C-export name: `_physics_step` →* `es_physics_step`. `es_` marks the boundary surface, so a C name that already@@ -53,7 +90,20 @@ function hostGlobal(exportName: string): string {* before passing an offset.*/function nativeCModule(scope: Record<string, unknown>, heap: NativeHeap): SideModule {- const resolved: Record<string, unknown> = { ...heap };+ const resolved: Record<string, unknown> = {+ ...heap,+ /**+ * emscripten's `cwrap`, as a passthrough. It exists to convert JS strings to+ * C strings and back around a raw export; the generated wrapper already takes+ * and returns JS strings where the declaration says `const char*`, so there is+ * nothing left to convert — the argument types are the caller's statement about+ * a surface that already agrees with them.+ */+ cwrap: (ident: string): unknown => scope[hostGlobal(`_${ident}`)],+ /** The heap's string helpers, in the same terms emscripten states them. */+ UTF8ToString: (ptr: number): string => readUtf8(heap, ptr),+ stringToNewUTF8: (str: string): number => writeUtf8(heap, str),+ };return new Proxy(resolved, {get(target, prop): unknown {if (prop in target) return Reflect.get(target, prop);@@ -93,6 +143,19 @@ export function createNativeSideModules(+ 'rebuild it with that subsystem enabled',);}+ // A Spine binary is one runtime. Answering the wrong version would load a+ // skeleton with a decoder that cannot read its format, so a project authored+ // against another release is told which one this app carries instead.+ if (id.startsWith('spine:')) {+ const linked = nativeSpineId(scope);+ if (linked !== id) {+ throw new Error(+ `[native] this app links Spine ${linked ? linked.slice(6) : 'none'}, and the `+ + `content asks for ${id.slice(6)} — rebuild with `+ + `-DESTELLA_SPINE_VERSION=${id.slice(6)} (a binary carries one runtime)`,+ );+ }+ }if (!heap) {throw new Error(`[native] "${id}" needs the host heap to marshal buffers, and es_heap is not bound`,diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 40be83db9..382175ab8 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -260,12 +260,16 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): PromisapplyTextureMetadata(sceneData, assetResult.textureHandles, source.resolveRef ?? ((ref) => ref));// KTX2 atlas pages transcode through the realm's basis module, acquired the- // same lazy way the TextureLoader's provider does (AssetPlugin).- // Spine rides the wasm side-module host, which a native host does not have.- if (!module && discovered.spines.length > 0) {- log.warn('scene', `${discovered.spines.length} spine asset(s) skipped — this realm has no wasm module`);+ // same lazy way the TextureLoader's provider does (AssetPlugin). Spine itself+ // rides `app.sideModules` — a fetched wasm module on the web, the runtime+ // compiled into the binary on a device — so what decides here is whether the+ // realm has an acquirer at all, not whether it has a wasm engine module (the+ // atlas upload takes bytes without one).+ if (!app.sideModules && discovered.spines.length > 0) {+ log.warn('scene', `${discovered.spines.length} spine asset(s) skipped — `+ + 'this realm has no optional-module host to load a Spine runtime from');}- const spineAssetInfo = module+ const spineAssetInfo = app.sideModules? await loadSpineAssets(module, source, spineManager, discovered.spines, async () => {const host = app.sideModules;if (!host) return null;diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.tsindex 1c8f4c5b5..a2cfde8a2 100644--- a/sdk/src/spine/ModuleBackend.ts+++ b/sdk/src/spine/ModuleBackend.ts@@ -1,7 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Entity } from '../types';-import type { ESEngineModule, CppRegistry } from '../wasm';+import type { CppRegistry } from '../wasm';+import type { EngineApi } from '../ecs/engineApi';import type { SpineModuleController } from './SpineController';import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';import { log } from '../logger';@@ -230,23 +231,28 @@ export class ModuleBackend {}}- extractAndSubmitMeshes(coreModule: ESEngineModule, registry: CppRegistry): void {- const submitFn = coreModule.renderer_submitSpineBatchByEntity;- if (!submitFn) return;+ /** @param core whichever engine core is present (see ecs/engineApi.ts) — the+ * batches cross through its heap, which is wasm linear memory on the web and the+ * host arena on a device. */+ extractAndSubmitMeshes(core: NonNullable<EngineApi>, registry: CppRegistry): void {+ const submitFn = core.renderer_submitSpineBatchByEntity;+ const heap = core.HEAPU8;+ if (!submitFn || !heap || !core._malloc || !core._free) return;+ const allocator = { _malloc: core._malloc, _free: core._free };for (const [entity, info] of this.entities_) {if (this.disabledEntities_.has(entity)) continue;// One engine-side scratch arena per entity; each batch's spine-heap// bytes are copied straight into it and submitted while the spine view// is still live. No intermediate JS arrays, no per-frame cache (C7).- withScratch(coreModule, alloc => {+ withScratch(allocator, alloc => {this.controller_.forEachMeshBatch(info.instanceId,(vertBytes, idxBytes, vertexCount, indexCount, textureId, blendMode) => {const dstVert = alloc(vertBytes.byteLength);const dstIdx = alloc(idxBytes.byteLength);- coreModule.HEAPU8.set(vertBytes, dstVert);- coreModule.HEAPU8.set(idxBytes, dstIdx);- submitFn.call(coreModule, registry,+ heap.set(vertBytes, dstVert);+ heap.set(idxBytes, dstIdx);+ submitFn.call(core, registry,dstVert, vertexCount, dstIdx, indexCount,textureId, blendMode, entity as number,info.skeletonScale, info.flipX, info.flipY, info.layer, 0);diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex a0246113d..0c6726c5b 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { EngineApi } from '../ecs/engineApi';import type { ESEngineModule, CppRegistry } from '../wasm';import type { Entity } from '../types';import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';@@ -12,14 +13,15 @@ import { log } from '../logger';export type SpineVersion = '3.8' | '4.1' | '4.2';export class SpineManager {- private coreModule_: ESEngineModule;+ private coreModule_: NonNullable<EngineApi>;private factories_: Map<SpineVersion, SpineModuleFactory>;private backends_: Map<SpineVersion, ModuleBackend> = new Map();private loadingBackends_: Map<SpineVersion, Promise<ModuleBackend | null>> = new Map();private entityVersions_: Map<Entity, SpineVersion> = new Map();constructor(- coreModule: ESEngineModule,+ /** Whichever engine core is present (see ecs/engineApi.ts). */+ coreModule: NonNullable<EngineApi>,moduleFactories: Map<SpineVersion, SpineModuleFactory>,) {this.coreModule_ = coreModule;diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.tsindex 626d10684..02f9ada7a 100644--- a/sdk/src/spine/SpinePlugin.ts+++ b/sdk/src/spine/SpinePlugin.ts@@ -9,6 +9,7 @@ import type { Entity } from '../types';import { SpineManager, type SpineVersion } from './SpineManager';import type { SpineModuleFactory, SpineWasmModule } from './SpineModuleLoader';import { SPINE_VERSIONS, spineModuleId } from '../sideModules';+import { engineApi } from '../ecs/engineApi';import { AnimatorController } from '../animation/Animator';export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'event';@@ -91,9 +92,11 @@ export class SpinePlugin implements Plugin {build(app: App): void {this.app_ = app;- const coreModule = app.wasmModule!;+ // The core the mesh batches are submitted through: the wasm module on the+ // web, the native host's bindings on a device.+ const coreModule = engineApi(app);- if (!this.spineManager_ && app.sideModules) {+ if (!this.spineManager_ && app.sideModules && coreModule) {const host = app.sideModules;const factories = new Map<SpineVersion, SpineModuleFactory>();for (const version of SPINE_VERSIONS) {diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.tsindex 29b8b00cb..9d847e81a 100644--- a/sdk/src/spine/loadSpineScene.ts+++ b/sdk/src/spine/loadSpineScene.ts@@ -74,7 +74,9 @@ export interface SpineAssetInfo {* its runtime version. Keyed by `skeletonRef:atlasRef` for {@link applySpineEntities}.*/export async function loadSpineAssets(- module: ESEngineModule,+ /** The wasm engine module, or null on a core with no heap — the atlas page upload+ * goes through the ResourceManager's byte path there. */+ module: ESEngineModule | null,source: RuntimeAssetSource,spineManager: SpineManager | null | undefined,spinePairs: ReadonlyArray<{ skeleton: string; atlas: string }>,@@ -202,7 +204,7 @@ export async function applySpineEntities(opts: {* JS runtimes, where the native virtual-FS ordering doesn't apply.*/export async function loadSpineSceneEntities(opts: {- module: ESEngineModule;+ module: ESEngineModule | null;source: RuntimeAssetSource;spineManager: SpineManager;sceneData: SceneData;diff --git a/sdk/tests/binding-surface.test.ts b/sdk/tests/binding-surface.test.tsindex 85d9423ed..0417ebf7b 100644--- a/sdk/tests/binding-surface.test.ts+++ b/sdk/tests/binding-surface.test.ts@@ -94,6 +94,11 @@ function parseKeepaliveSigs(cppSource: string): Map<string, number> {const out = new Map<string, number>();const re = /EMSCRIPTEN_KEEPALIVE\b/g;for (let m = re.exec(src); m; m = re.exec(src)) {+ // Not the portability fallback (`#define EMSCRIPTEN_KEEPALIVE` for a native+ // build, where the attribute has no meaning) — that is not an export, and+ // reading past it would attribute the next function in the file to it.+ const lineStart = src.lastIndexOf('\n', m.index) + 1;+ if (src.slice(lineStart, m.index).trimStart().startsWith('#define')) continue;const paren = src.indexOf('(', m.index);if (paren < 0) continue;const tokens = src.slice(m.index + m[0].length, paren).match(/\w+/g);@@ -351,8 +356,17 @@ describe('WASM binding surface: side modules (C exports)', () => {.toEqual([]);});+ // Exported for the NATIVE side only, so no SDK caller names them: which spine+ // runtime a host linked (the web names the artifact instead — spine38 / 41 / 42)+ // and how much the event buffer published, which a native wrapper needs to copy+ // the readback into the caller's heap. See SpineBindings.hpp.+ const SPINE_NATIVE_ONLY = new Set(['spine_runtimeVersion', 'spine_eventBufferBytes']);+it('SpineWasmModule + its cwrap table mirror the spine module exports exactly', () => {- const cpp = parseKeepaliveExports(read(resolve(CPP, 'bindings/SpineModuleEntry.cpp')));+ const cpp = new Set(+ [...parseKeepaliveExports(read(resolve(CPP, 'bindings/SpineModuleEntry.cpp')))]+ .filter((n) => !SPINE_NATIVE_ONLY.has(n)),+ );const loaderTs = read(resolve(SDK, 'spine/SpineModuleLoader.ts'));const declared = new Set([...parseInterfaceMethods(loaderTs, 'SpineWasmModule'),@@ -361,6 +375,25 @@ describe('WASM binding surface: side modules (C exports)', () => {expectMirrored('spine', declared, cpp);});+ // The native half, as for physics: a device reaches spine through wrappers EHT+ // generates from SpineBindings.hpp, so a declaration missing there is an entry+ // point the device does not answer, and one with no definition is a wrapper that+ // will not link.+ it('SpineBindings.hpp declares exactly what the module exports', () => {+ const header = stripComments(read(resolve(CPP, 'bindings/SpineBindings.hpp')));+ const declared = new Set([...header.matchAll(/\b(spine_\w+)\s*\(/g)].map((m) => m[1]!));+ const exported = new Set(+ [...parseKeepaliveExports(read(resolve(CPP, 'bindings/SpineModuleEntry.cpp')))]+ .filter((n) => n.startsWith('spine_')),+ );+ const undeclared = [...exported].filter((n) => !declared.has(n)).sort();+ const phantom = [...declared].filter((n) => !exported.has(n)).sort();+ expect(undeclared, `exported but not declared in SpineBindings.hpp: ${undeclared.join(', ')}`)+ .toEqual([]);+ expect(phantom, `declared in SpineBindings.hpp but defined nowhere: ${phantom.join(', ')}`)+ .toEqual([]);+ });+it('BasisWasmModule mirrors the basis EXPORTED_FUNCTIONS list exactly', () => {const cmake = read(resolve(CPP, '../../cmake/Emscripten.cmake'));const exported = parseExportedFunctions(cmake, 'es_basis');diff --git a/sdk/tests/native-side-modules.test.ts b/sdk/tests/native-side-modules.test.tsindex 48a4d5a43..8b849cb8e 100644--- a/sdk/tests/native-side-modules.test.ts+++ b/sdk/tests/native-side-modules.test.ts@@ -9,13 +9,15 @@//// Driven against a mock host scope — the marshalling is what these check, not Box2D.import { describe, it, expect, vi } from 'vitest';-import { createNativeSideModules, NATIVE_SIDE_MODULE_PROBES } from '../src/ecs/nativeSideModules';+import {+ createNativeSideModules, NATIVE_SIDE_MODULE_PROBES, SPINE_VERSION_BINDING,+} from '../src/ecs/nativeSideModules';import { HEAP_BINDINGS } from '../src/ecs/nativeHeap';import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';/** A host that compiled physics in: the heap plus a few es_physics_* globals. */-function mockNativeHost(options: { physics?: boolean; heap?: boolean } = {}) {- const { physics = true, heap = true } = options;+function mockNativeHost(options: { physics?: boolean; heap?: boolean; spine?: number } = {}) {+ const { physics = true, heap = true, spine } = options;const buffer = new ArrayBuffer(4096);let next = 8;const calls: { name: string; args: unknown[] }[] = [];@@ -37,6 +39,15 @@ function mockNativeHost(options: { physics?: boolean; heap?: boolean } = {}) {// the module's bytes there), exactly like a wasm pointer.scope['es_physics_getDynamicBodyTransforms'] = () => 64;}+ if (spine !== undefined) {+ // A host links ONE spine runtime and says which (spine_runtimeVersion).+ scope[SPINE_VERSION_BINDING] = () => spine;+ scope['es_spine_loadSkeleton'] = (...args: unknown[]) => { calls.push({ name: 'loadSkeleton', args }); return 1; };+ scope['es_spine_playAnimation'] = (...args: unknown[]) => { calls.push({ name: 'playAnimation', args }); return 1; };+ // A C string crosses as a JS string, in and out — the generated wrapper reads+ // and writes them, so nothing here needs the heap.+ scope['es_spine_getAnimations'] = () => 'idle,walk,run';+ }return { scope, buffer, calls };}@@ -57,10 +68,12 @@ describe('createNativeSideModules', () => {expect(await createNativeSideModules(scope).acquire('physics')).toBeNull();});- it('answers null for a subsystem no native host compiles yet', async () => {+ it('answers null for a subsystem this host did not compile in', async () => {+ // The KTX2 transcoder is the one no native host needs a module for — it+ // transcodes in C++ behind the texture path (host/media/ktx2_decode.cpp).const { scope } = mockNativeHost();- expect(await createNativeSideModules(scope).acquire('spine:4.2')).toBeNull();- expect(NATIVE_SIDE_MODULE_PROBES['spine:4.2']).toBeUndefined();+ expect(await createNativeSideModules(scope).acquire('basis')).toBeNull();+ expect(NATIVE_SIDE_MODULE_PROBES.basis).toBeUndefined();});it('caches, so two consumers share one view', async () => {@@ -131,3 +144,50 @@ describe('the runtime installs physics from a native host', () => {expect(acquire).toHaveBeenCalledWith('physics');});});++describe('spine on a native host', () => {+ it('answers the version the host actually linked', async () => {+ const host = createNativeSideModules(mockNativeHost({ spine: 42 }).scope);+ expect(await host.acquire('spine:4.2')).not.toBeNull();+ });++ it('refuses a version it did not link, rather than mis-decoding a skeleton', async () => {+ // The three vendored runtimes export the same symbols, so the entry points+ // being present says nothing about the format they can read.+ const host = createNativeSideModules(mockNativeHost({ spine: 42 }).scope);+ expect(await host.acquire('spine:3.8')).toBeNull();+ expect(await host.acquire('spine:4.1')).toBeNull();+ });++ it('answers nothing when no spine runtime is linked at all', async () => {+ const host = createNativeSideModules(mockNativeHost().scope);+ expect(await host.acquire('spine:4.2')).toBeNull();+ });++ it('cwrap is a passthrough — the wrapper already speaks JS strings', async () => {+ const { scope, calls } = mockNativeHost({ spine: 42 });+ const mod = (await createNativeSideModules(scope).acquire('spine:4.2')) as unknown as {+ cwrap(ident: string, ret: string | null, args: string[]): (...a: unknown[]) => unknown;+ };+ const play = mod.cwrap('spine_playAnimation', 'number', ['number', 'string', 'number', 'number']);+ expect(play(1, 'walk', 1, 0)).toBe(1);+ expect(calls.at(-1)).toEqual({ name: 'playAnimation', args: [1, 'walk', 1, 0] });++ const list = mod.cwrap('spine_getAnimations', 'string', ['number']);+ expect(list(1)).toBe('idle,walk,run');+ });++ it('reads and writes heap strings the way emscripten states them', async () => {+ const { scope } = mockNativeHost({ spine: 42 });+ const mod = (await createNativeSideModules(scope).acquire('spine:4.2')) as unknown as {+ UTF8ToString(ptr: number): string;+ stringToNewUTF8(str: string): number;+ _free(ptr: number): void;+ };+ const ptr = mod.stringToNewUTF8('走る');+ expect(ptr).toBeGreaterThan(0);+ expect(mod.UTF8ToString(ptr)).toBe('走る');+ expect(mod.UTF8ToString(0)).toBe(''); // what UTF8ToString(0) answers on the web+ mod._free(ptr);+ });+});diff --git a/src/esengine/bindings/SpineBindings.hpp b/src/esengine/bindings/SpineBindings.hppnew file mode 100644index 000000000..edf196d7b--- /dev/null+++ b/src/esengine/bindings/SpineBindings.hpp@@ -0,0 +1,84 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SpineBindings.hpp+ * @brief The Spine runtime's entry points, declared once for both platforms.+ * @details Spine is plain C over spine-c: load a skeleton + atlas, drive animation+ * state, and hand back mesh batches the engine's renderer submits. On the web+ * it links as a per-version wasm side module (spine38 / spine41 / spine42,+ * which is how one editor opens projects authored against different Spine+ * releases); a native app compiles ONE of those runtimes into the host binary+ * and reaches it through the QuickJS wrappers EHT generates from here — the+ * three vendored runtimes export the same symbol names, so only one can link.+ * `spine_runtimeVersion` is how the SDK asks which one it got.+ *+ * Names (animations, skins, slots, constraints) cross as strings; vertex,+ * index and event data cross as offsets into the caller's heap — wasm linear+ * memory on the web, the host arena on a device.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include <cstddef>+#include <cstdint>++extern "C" {++int spine_loadSkeleton(uintptr_t skelDataPtr, int skelDataLen, const char* atlasText, int atlasLen, int isBinary);+const char* spine_getLastError();+void spine_unloadSkeleton(int handle);+int spine_getAtlasPageCount(int handle);+const char* spine_getAtlasPageTextureName(int handle, int pageIndex);+void spine_setAtlasPageTexture(int handle, int pageIndex, uint32_t textureId, int width, int height);+int spine_createInstance(int skeletonHandle);+void spine_destroyInstance(int instanceId);+int spine_playAnimation(int instanceId, const char* name, int loop, int track);+int spine_addAnimation(int instanceId, const char* name, int loop, float delay, int track);+void spine_setSkin(int instanceId, const char* name);+void spine_update(int instanceId, float dt);+const char* spine_getAnimations(int instanceId);+const char* spine_getSkins(int instanceId);+int spine_getBonePosition(int instanceId, const char* bone, uintptr_t outXPtr, uintptr_t outYPtr);+float spine_getBoneRotation(int instanceId, const char* bone);+void spine_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr, uintptr_t outWPtr, uintptr_t outHPtr);+int spine_getMeshBatchCount(int instanceId);+int spine_getMeshBatchVertexCount(int instanceId, int batchIndex);+int spine_getMeshBatchIndexCount(int instanceId, int batchIndex);+void spine_getMeshBatchData(int instanceId, int batchIndex, uintptr_t outVerticesPtr, uintptr_t outIndicesPtr, uintptr_t outTextureIdPtr, uintptr_t outBlendModePtr);+void spine_setClippingEnabled(int enabled);+void spine_setDefaultMix(int skeletonHandle, float duration);+void spine_setMixDuration(int skeletonHandle, const char* fromAnim, const char* toAnim, float duration);+void spine_setTrackAlpha(int instanceId, int track, float alpha);+void spine_enableEvents(int instanceId);+int spine_getEventCount(int instanceId);+// @heapreturn spine_eventBufferBytes()+uintptr_t spine_getEventBuffer();+void spine_clearEvents();+const char* spine_getEventAnimationName(int index);+const char* spine_getEventName(int index);+const char* spine_getEventStringValue(int index);+int spine_setAttachment(int instanceId, const char* slotName, const char* attachmentName);+int spine_setIKTarget(int instanceId, const char* constraintName, float targetX, float targetY, float mix);+const char* spine_listConstraints(int instanceId);+const char* spine_getTransformConstraintMix(int instanceId, const char* name);+int spine_setTransformConstraintMix(int instanceId, const char* name, float rotate, float x, float y, float scaleX, float scaleY, float shearY);+const char* spine_getPathConstraintMix(int instanceId, const char* name);+int spine_setPathConstraintMix(int instanceId, const char* name, float position, float spacing, float rotate, float x, float y);+int spine_setSlotColor(int instanceId, const char* slotName, float r, float g, float b, float a);+int spine_setSkeletonColor(int instanceId, float r, float g, float b, float a);++// Which Spine runtime this build linked (38 / 41 / 42). The web ships one module per+// version and names the artifact; a native host has room for one, so it says which —+// and the SDK's acquirer answers that version's id only.+int spine_runtimeVersion();++// How many bytes the last event collection published, for the readback above. The+// buffer is the module's own vector, so only the module can say how much is live.+size_t spine_eventBufferBytes();++} // extern "C"diff --git a/src/esengine/bindings/SpineModuleEntry.cpp b/src/esengine/bindings/SpineModuleEntry.cppindex 742931cda..3598338f9 100644--- a/src/esengine/bindings/SpineModuleEntry.cpp+++ b/src/esengine/bindings/SpineModuleEntry.cpp@@ -9,9 +9,21 @@* Core WASM handles all rendering via renderer_submitTriangles.** Uses spine-c (pure C runtime) for minimal WASM size.+ *+ * The same TU compiles into the native host binary, where there is no side-module+ * story: the entry points are declared in SpineBindings.hpp and reached through the+ * QuickJS wrappers EHT generates from them.*/+// KEEPALIVE keeps these exported through the emscripten link; natively the attribute+// has no meaning and the header does not exist.+#ifdef __EMSCRIPTEN__#include <emscripten.h>+#else+#define EMSCRIPTEN_KEEPALIVE+#endif++#include "SpineBindings.hpp"#include <spine/spine.h>#include <spine/extension.h>@@ -1124,8 +1136,34 @@ int spine_setSkeletonColor(int instanceId, float r, float g, float b, float a) {return 1;}+// Which spine-c runtime this build linked. The three vendored runtimes export the+// same symbols, so a binary carries exactly one and the caller has to be able to ask+// (the web names the artifact instead — spine38.wasm / spine41 / spine42).+EMSCRIPTEN_KEEPALIVE+int spine_runtimeVersion() {+#if defined(ES_SPINE_38)+ return 38;+#elif defined(ES_SPINE_41)+ return 41;+#else+ return 42;+#endif+}++// The live extent of the event buffer, for the readback getter above: it is this+// module's own vector, so a caller cannot infer it from a count and a stride without+// assuming the stride — see `@heapreturn` in SpineBindings.hpp.+EMSCRIPTEN_KEEPALIVE+size_t spine_eventBufferBytes() {+ return g_ctx.eventBuffer.size() * sizeof(float);+}+} // extern "C"+#ifdef __EMSCRIPTEN__+// The module is linked as an executable, so it needs an entry point; a native build+// links it into a host that has its own.int main() {return 0;}+#endifdiff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.pyindex f19f199d3..eb300101b 100644--- a/tools/eht/generators/native_functions.py+++ b/tools/eht/generators/native_functions.py@@ -25,11 +25,14 @@ The mapping is small because the declarations are:native/host/heap.hpp). A JS buffer handed straight across isstill accepted and copied in. Either way the binding's ownBoundarySpan validation runs, now against a real region.- returns void / integer / float / bool--Anything else — ``emscripten::val`` results, ``std::string``, typed pointers — is-SKIPPED and reported, never silently dropped: the skip list is what tells you-which entry points still need a hand-written binding.+ strings ``const std::string&`` / ``const char*`` in, and either out:+ a JS string, copied for the call. Not bulk data, so no heap+ returns void / integer / float / bool / string, or a pointer WITH an+ ``@heapreturn`` byte count++Anything else — ``emscripten::val`` results, a typed pointer, a pointer return with+no ``@heapreturn`` — is SKIPPED and reported, never silently dropped: the skip list+is what tells you which entry points still need a hand-written binding."""import re@@ -41,6 +44,10 @@ _INT_TYPES = {'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64',_FLOAT_TYPES = {'f32', 'f64', 'float', 'double'}_BOOL_TYPES = {'bool'}_STRING = 'std::string'+# A C string, in or out. The module surfaces written as plain C use these where the+# C++ ones use std::string; both cross the boundary as a JS string, and neither needs+# the heap — a name or an animation id is not bulk data.+_CSTR = 'char*'_VOID = 'void'# A pointer-returning entry point hands back memory the MODULE owns (a static@@ -71,9 +78,12 @@ _IMPLICIT_SUFFIXES = {'ResourceManager': 'resource::ResourceManager&',}-# `void name(args);` on one or more lines, inside the header's namespace.+# `void name(args);` on one or more lines, inside the header's namespace. The return+# type may be const-qualified and may be a pointer (`const char* spine_getLastError()`)+# — without both, such a declaration matched nothing at all and was dropped without+# even reaching the skip list, which is the one thing this generator must never do._DECL = re.compile(- r'^(?P<ret>[A-Za-z_][\w:]*(?:\s*\*)?)\s+(?P<name>[A-Za-z_]\w*)\s*\((?P<args>[^;{]*)\)\s*;',+ r'^(?P<ret>(?:const\s+)?[A-Za-z_][\w:]*(?:\s*\*)?)\s+(?P<name>[A-Za-z_]\w*)\s*\((?P<args>[^;{]*)\)\s*;',re.MULTILINE | re.DOTALL,)@@ -224,6 +234,10 @@ def _parse_params(args: str) -> Tuple[List[Param], Optional[str]]:if parts[0] == _STRING:params.append(Param(_STRING, parts[-1]))continue+ # `const char*` — the same, handed over as a pointer.+ if decl.replace(' ', '').startswith('char*'):+ params.append(Param(_CSTR, parts[-1]))+ continueif '&' in decl or '*' in decl:return params, f'takes {decl}'cpp_type = ' '.join(parts[:-1]) if len(parts) > 1 else parts[0]@@ -239,7 +253,8 @@ def _returnable(ret: str, heap_return: Optional[str] = None) -> bool:if ret == 'uintptr_t':# Only with an annotation saying how much memory it covers.return heap_return is not None- return ret == _VOID or ret == _STRING or ret in _INT_TYPES | _FLOAT_TYPES | _BOOL_TYPES+ return (ret in (_VOID, _STRING, _CSTR)+ or ret in _INT_TYPES | _FLOAT_TYPES | _BOOL_TYPES)# The engine's short scalar aliases live in namespace esengine; the plain C++@@ -285,6 +300,8 @@ class NativeFunctionsGenerator:# (local, js argument index) per buffer argument, so a copied-in buffer is# released after the call — see esn_argRelease.ptr_releases: List[Tuple[str, int]] = []+ # C-string arguments, freed after the call for the same reason.+ cstr_frees: List[str] = []js_index = 0for param in fn.params:if param.cpp_type in _IMPLICIT_REFS:@@ -300,6 +317,12 @@ class NativeFunctionsGenerator:out.append(f' const uint32_t {local}_off = esn_argOffset(ctx, argv[{js_index}]);')out.append(f' const uintptr_t {local} = esn_heapAddr({local}_off);')ptr_releases.append((local, js_index))+ elif param.cpp_type == _CSTR:+ # Owned by the wrapper for the duration of the call. A missing or+ # non-string argument reads as empty, matching how cwrap coerces one.+ out.append(f' const char* {local}_c = JS_ToCString(ctx, argv[{js_index}]);')+ out.append(f' const char* {local} = {local}_c ? {local}_c : "";')+ cstr_frees.append(local)elif param.cpp_type == _STRING:# A JS string, owned by the wrapper for the call. An absent or# non-string argument reads as empty rather than aborting the call,@@ -324,6 +347,7 @@ class NativeFunctionsGenerator:call = f'{scope}{fn.name}({", ".join(call_args)})'releases = [f' esn_argRelease(ctx, argv[{index}], {local}_off);'for local, index in ptr_releases]+ releases += [f' if ({local}_c) JS_FreeCString(ctx, {local}_c);' for local in cstr_frees]if fn.ret == _VOID:out.append(f' {call};')out.extend(releases)@@ -343,6 +367,13 @@ class NativeFunctionsGenerator:out.append(f' const std::string result = {call};')out.extend(releases)out.append(' return JS_NewStringLen(ctx, result.data(), result.size());')+ elif fn.ret == _CSTR:+ # The module owns the storage (a static scratch string), so the value+ # is copied into a JS string here rather than published to the heap.+ # A null answers as empty, which is what UTF8ToString(0) reads as.+ out.append(f' const char* result = {call};')+ out.extend(releases)+ out.append(' return JS_NewString(ctx, result ? result : "");')elif fn.ret == 'uintptr_t':# Module-owned memory: copy `@heapreturn` bytes into this entry# point's own heap slot and answer the offset, so the SDK reads the@@ -367,13 +398,13 @@ class NativeFunctionsGenerator:# The same declarations, as the object a native host answers them through.# The SDK's plugins call these by the module's own names, so a plugin reaches# whichever core is present without knowing which (see ecs/engineApi.ts).- _TS_RETURN = {'void': 'void', 'bool': 'boolean', _STRING: 'string'}+ _TS_RETURN = {'void': 'void', 'bool': 'boolean', _STRING: 'string', _CSTR: 'string'}@staticmethoddef _ts_type(cpp: str) -> str:if cpp in _BOOL_TYPES:return 'boolean'- if cpp == _STRING:+ if cpp in (_STRING, _CSTR):return 'string'if cpp in _IMPLICIT_REFS:return 'unknown'