Skip to content

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

feat(native): the presentation stack runs on the device, not just the simulation

yhh51039691ece6
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 957380af3..aedf00ab4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -264,6 +264,7 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
src/esengine/bindings/UIBindings.cpp
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
+ src/esengine/bindings/AnimationBindings.cpp
${GENERATED_WEB_BINDINGS}
${GENERATED_EDITOR_API}
)
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index d1138a806..a77323df6 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -34,6 +34,21 @@ async function generateNativeBindings(rootDir, genDir, python) {
return out;
}
+// The binding headers whose entry points a native host gets, and the ONE list of
+// them: the QuickJS wrappers and the TS surface the SDK calls
+// (sdk/src/ecs/nativeEngineApi.generated.ts) are both generated from these, so
+// adding a subsystem to a device is adding its header here.
+export const NATIVE_BINDING_HEADERS = [
+ 'RendererBindings.hpp',
+ 'UIBindings.hpp',
+ 'ResourceManagerBindings.hpp',
+ 'TilemapBindings.hpp',
+ 'PostProcessBindings.hpp',
+ 'GeometryBindings.hpp',
+ 'ImmediateDrawBindings.hpp',
+ 'AnimationBindings.hpp',
+];
+
// Generate the QuickJS wrappers for the engine's binding ENTRY POINTS — the same
// declarations embind registers on the web, so the SDK reaches the engine by the
// same names on both platforms and nothing is bound twice by hand. The bodies are
@@ -42,13 +57,20 @@ async function generateNativeFunctionBindings(rootDir, genDir, python) {
const out = path.join(genDir, 'NativeFunctionBindings.generated.cpp');
// Every binding TU the native build compiles (see cmake/ESEngineSources.cmake).
// ResourceManagerBindings is the texture surface the asset pipeline uploads
- // through: the host used to hand-write a second copy of it.
- const headers = ['RendererBindings.hpp', 'UIBindings.hpp', 'ResourceManagerBindings.hpp'].map(
+ // through: the host used to hand-write a second copy of it. Tilemap and
+ // post-process declarations sit behind their ES_ENABLE_* gates, which the
+ // generator carries into the wrapper, so a build without them still compiles.
+ const headers = NATIVE_BINDING_HEADERS.map(
(h) => path.join(rootDir, 'src', 'esengine', 'bindings', h));
await runCommand(python, [
path.join(rootDir, 'tools', 'eht.py'),
'--native-functions', ...headers,
'--native-functions-output', out,
+ // The TS half is committed (the SDK compiles without running EHT), so it is
+ // refreshed here rather than left to be updated by hand: after a native
+ // build, a surface that moved shows up as a diff instead of as a call the
+ // device silently does not answer.
+ '--native-functions-ts', path.join(rootDir, 'sdk', 'src', 'ecs', 'nativeEngineApi.generated.ts'),
'--native-shim', 'esn_shim.hpp',
], { cwd: rootDir });
return out;
diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmake
index 60cba7f9c..a70d54afc 100644
--- a/cmake/ESEngineSources.cmake
+++ b/cmake/ESEngineSources.cmake
@@ -63,10 +63,25 @@ if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
# hand-written copy of these for a while, drifting from the web's; it now
# compiles the same TU and registers the same rm_* entry points.
${ESENGINE_ROOT}/src/esengine/bindings/ResourceManagerBindings.cpp
+ # Custom geometry (Mesh2D) and the immediate-draw surface: portable C++ the
+ # web build compiles into its SDK target, so a device gets them too.
+ ${ESENGINE_ROOT}/src/esengine/bindings/GeometryBindings.cpp
+ ${ESENGINE_ROOT}/src/esengine/bindings/ImmediateDrawBindings.cpp
+ # Tweens: portable C++ that used to live in the emscripten entry TU.
+ ${ESENGINE_ROOT}/src/esengine/bindings/AnimationBindings.cpp
# activeCtx()'s unset fallback. A host that installs its own context (the
# native one does, at boot) never reaches it, but the inline accessor
# references it, so the definition has to link.
${ESENGINE_ROOT}/src/esengine/bindings/EngineContext.cpp)
+ # The subsystem entry points, under the same flags that compile the subsystem.
+ # On the web these are part of the SDK target instead (SDK_BINDING_SOURCES),
+ # because that is where embind registers them; the implementation is the same TU.
+ if(ES_ENABLE_TILEMAP)
+ list(APPEND ESENGINE_SOURCES ${ESENGINE_ROOT}/src/esengine/bindings/TilemapBindings.cpp)
+ endif()
+ if(ES_ENABLE_POSTPROCESS)
+ list(APPEND ESENGINE_SOURCES ${ESENGINE_ROOT}/src/esengine/bindings/PostProcessBindings.cpp)
+ endif()
endif()
if(ES_ENABLE_WEBGPU)
diff --git a/desktop/scripts/export-project.mjs b/desktop/scripts/export-project.mjs
new file mode 100644
index 000000000..b01cb383a
--- /dev/null
+++ b/desktop/scripts/export-project.mjs
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Package a project the way the editor's "Package Project" does, without the
+// editor: `exportGame` is plain node + esbuild (no electron), so a headless run is
+// just a matter of bundling the TypeScript and calling it.
+//
+// This exists because the native app's content comes from an export, and verifying
+// a platform means packaging real projects for it repeatedly — one example after
+// another. Doing that through the editor UI is not repeatable, and a second export
+// path written by hand would drift from the one every game takes.
+//
+// node desktop/scripts/export-project.mjs <projectDir> [options]
+// --platform <id> web | desktop | wechat | playable | android | ios (default android)
+// --out <dir> output dir (default <projectDir>/dist-<platform>)
+// --scene <path> entry scene, project-relative (default: the project's own)
+// --title <name> app title (default: the project's name)
+// --scripts <path> scripts entry, project-relative (default src/main.ts if present)
+//
+// Prints the export result as JSON — errors and warnings included, so a caller can
+// tell a clean package from one that silently dropped half a scene.
+import path from 'node:path';
+import { existsSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DESKTOP = path.join(HERE, '..');
+const REPO = path.join(DESKTOP, '..');
+
+function parseArgs(argv) {
+ const [projectDir, ...rest] = argv;
+ if (!projectDir) {
+ console.error('usage: node desktop/scripts/export-project.mjs <projectDir> [--platform android] [--out dir]');
+ process.exit(2);
+ }
+ const opts = { projectDir: path.resolve(projectDir), platform: 'android' };
+ for (let i = 0; i < rest.length; i += 2) {
+ const key = rest[i]?.replace(/^--/, '');
+ const value = rest[i + 1];
+ if (!key || value === undefined) break;
+ opts[key] = value;
+ }
+ return opts;
+}
+
+const fileUrl = (p) => `file:///${p.replace(/\\/g, '/')}`;
+
+// Bundle exportGame.ts to a temp module and import it. ESM, because the cook reads
+// `import.meta.url` (the basis encoder locates its binary that way) — and with a
+// `require` shim bound to desktop/, because some of its dependencies are CommonJS
+// (pngjs). esbuild itself stays external: the module resolves it at runtime the
+// same way the electron main process does.
+async function loadExportGame() {
+ const require = createRequire(path.join(DESKTOP, 'package.json'));
+ const esbuild = require('esbuild');
+ // Inside desktop/, so the bundle's own `import 'esbuild'` resolves through
+ // desktop/node_modules the way it does for the electron main process.
+ const dir = mkdtempSync(path.join(DESKTOP, '.export-'));
+ const outfile = path.join(dir, 'exportGame.mjs');
+ await esbuild.build({
+ entryPoints: [path.join(DESKTOP, 'electron', 'exportGame.ts')],
+ outfile, bundle: true, format: 'esm', platform: 'node', target: 'node20',
+ external: ['esbuild', 'electron', 'sharp'], logLevel: 'error',
+ banner: {
+ js: "import { createRequire as __esCreateRequire } from 'node:module';\n"
+ + `const require = __esCreateRequire('${fileUrl(path.join(DESKTOP, 'package.json'))}');\n`,
+ },
+ });
+ const mod = await import(fileUrl(outfile));
+ return { exportGame: mod.exportGame, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
+}
+
+/** The project's own settings, so a headless export matches what the editor would do. */
+function projectSettings(projectDir) {
+ for (const name of ['project.esproject', 'project.esproj', 'project.json']) {
+ const file = path.join(projectDir, name);
+ if (existsSync(file)) {
+ try {
+ return JSON.parse(readFileSync(file, 'utf8'));
+ } catch {
+ return {};
+ }
+ }
+ }
+ return {};
+}
+
+function firstExisting(candidates) {
+ return candidates.find((c) => existsSync(c));
+}
+
+const opts = parseArgs(process.argv.slice(2));
+const project = projectSettings(opts.projectDir);
+const platform = opts.platform;
+
+const entryScene = opts.scene ?? project.defaultScene ?? (
+ firstExisting([
+ path.join(opts.projectDir, 'assets', 'scenes', 'main.esscene'),
+ path.join(opts.projectDir, 'scenes', 'main.esscene'),
+ ])?.slice(opts.projectDir.length + 1).replace(/\\/g, '/')
+);
+if (!entryScene) {
+ console.error(`No entry scene found in ${opts.projectDir} (pass --scene <project-relative path>).`);
+ process.exit(2);
+}
+
+const scriptsEntry = opts.scripts ?? (existsSync(path.join(opts.projectDir, 'src', 'main.ts'))
+ ? 'src/main.ts' : undefined);
+
+const outDir = path.resolve(opts.out ?? path.join(opts.projectDir, `dist-${platform}`));
+const { exportGame, cleanup } = await loadExportGame();
+let code = 1;
+try {
+ const result = await exportGame({
+ root: opts.projectDir,
+ entryScene,
+ scriptsEntry,
+ gameHostEntry: path.join(DESKTOP, 'src', 'gameHost.ts'),
+ sdkDistDir: path.join(REPO, 'sdk', 'dist'),
+ wasmDir: path.join(DESKTOP, 'public', 'wasm'),
+ outDir,
+ platform,
+ title: opts.title ?? project.name ?? path.basename(opts.projectDir),
+ orientation: project.orientation ?? 'landscape',
+ });
+ console.log(JSON.stringify({ ...result, outDir }, null, 2));
+ code = result.ok ? 0 : 1;
+} finally {
+ // Before the exit, not after: process.exit() in the try block would skip this
+ // and leave the bundle dir behind.
+ cleanup();
+}
+process.exit(code);
diff --git a/desktop/src/project/targetSupport.ts b/desktop/src/project/targetSupport.ts
index 509e4c171..05e9ee874 100644
--- a/desktop/src/project/targetSupport.ts
+++ b/desktop/src/project/targetSupport.ts
@@ -76,9 +76,6 @@ export interface SubsystemGap {
/** 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: 'tilemap', why: 'the native build leaves out the tilemap sources (ES_ENABLE_TILEMAP)' },
- { subsystem: 'particles', why: 'the native build leaves out the particle sources (ES_ENABLE_PARTICLES)' },
- { subsystem: 'postprocess', why: 'the native build leaves out the post-process pipeline (ES_ENABLE_POSTPROCESS)' },
{ subsystem: 'physics', why: 'Box2D ships as an emscripten side module; the native host has no counterpart yet' },
{ subsystem: 'spine', why: 'the Spine runtime ships as an emscripten side module; the native host has no counterpart yet' },
{ subsystem: 'video', why: 'the video decoder ships as an emscripten side module; the native host has no counterpart yet' },
diff --git a/desktop/tests/target-support.test.ts b/desktop/tests/target-support.test.ts
index be275fe6e..9b538f189 100644
--- a/desktop/tests/target-support.test.ts
+++ b/desktop/tests/target-support.test.ts
@@ -53,12 +53,12 @@ describe('collectSubsystems', () => {
});
describe('subsystemGapWarnings', () => {
- const usage = new Map<Subsystem, string[]>([['tilemap', ['scenes/b.esscene', 'scenes/a.esscene']]]);
+ const usage = new Map<Subsystem, string[]>([['physics', ['scenes/b.esscene', 'scenes/a.esscene']]]);
it('names the subsystem, the reason and the files', () => {
const [warning, ...rest] = subsystemGapWarnings('android', usage);
expect(rest).toEqual([]);
- expect(warning).toContain('Tilemaps will not render');
+ expect(warning).toContain('Physics (Box2D) will not render');
expect(warning).toContain('scenes/a.esscene, scenes/b.esscene');
});
@@ -113,6 +113,8 @@ describe('exportGame warns about content the target cannot render', () => {
{ id: 1, components: [{ type: 'Text', data: { text: 'score' } }] },
{ id: 2, components: [{ type: 'ParticleEmitter', data: {} }] },
{ id: 3, components: [{ type: 'TilemapLayer', data: {} }] },
+ { id: 4, components: [{ type: 'RigidBody', data: {} }] },
+ { id: 5, components: [{ type: 'SpineAnimation', data: {} }] },
],
}));
writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
@@ -136,12 +138,16 @@ describe('exportGame warns about content the target cannot render', () => {
expect(res.ok).toBe(true);
const gaps = res.warnings.filter((w) => w.startsWith('android:'));
expect(gaps).toHaveLength(2);
- expect(gaps.join('\n')).toContain('Particles will not render');
- expect(gaps.join('\n')).toContain('Tilemaps will not render');
+ expect(gaps.join('\n')).toContain('Physics (Box2D) will not render');
+ expect(gaps.join('\n')).toContain('Spine animation will not render');
expect(gaps.join('\n')).toContain('scenes/main.esscene');
- // Text renders on the native core (the host rasterizes glyphs), so the scene's
- // label is not warned about — the gaps are what the build really cannot do.
+ // What the native core DOES compile is not warned about: text (the host
+ // rasterizes glyphs for the same atlas), tilemaps, particles and
+ // post-processing. The gaps are what the build really cannot do, not
+ // everything that happens to be 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');
}, 60_000);
it('stays quiet for a target that renders all of it', async () => {
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 39a40f5a4..3e6d625db 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -68,9 +68,9 @@ endif()
# The engine core, native arm64. The source list is the SAME single-source file the
# web build uses (cmake/ESEngineSources.cmake) — selecting the WebGPU backend and
-# dropping GL / particles / tilemap / post-process for this build. It also brings in
-# the portable binding entry points (RendererBindings.cpp), whose QuickJS wrappers
-# are generated from the same declarations embind registers.
+# dropping GL for this build. It also brings in the portable binding entry points
+# (RendererBindings.cpp and friends), whose QuickJS wrappers are generated from the
+# same declarations embind registers.
set(ESENGINE_ROOT "${REPO}")
list(APPEND CMAKE_MODULE_PATH "${REPO}/cmake")
set(ES_ENABLE_WEBGPU ON)
@@ -79,6 +79,12 @@ set(ES_ENABLE_WEBGPU ON)
# SdfGenerator so both platforms encode the field identically), and the C++
# BitmapText path comes along with it. Neither needs freetype/msdfgen.
set(ES_ENABLE_BITMAP_TEXT ON)
+# Tilemaps, particles and post-processing: pure engine C++ with no emscripten
+# dependency, driven from the SDK through entry points that marshal buffers. What
+# kept them off a device was the marshalling, not the code — see host/heap.hpp.
+set(ES_ENABLE_TILEMAP ON)
+set(ES_ENABLE_PARTICLES ON)
+set(ES_ENABLE_POSTPROCESS ON)
include(ESEngineSources)
add_library(esengine STATIC ${ESENGINE_SOURCES})
@@ -87,7 +93,9 @@ target_include_directories(esengine PUBLIC
"${SRC}" "${TP}/stb"
"${ESTELLA_DAWN_DIR}/include" # <webgpu/webgpu.h> forwarder
"${ESTELLA_DAWN_BUILD}/gen/include") # generated <dawn/webgpu.h>
-target_compile_definitions(esengine PUBLIC ES_ENABLE_WEBGPU ES_ENABLE_BITMAP_TEXT) # NOT ES_PLATFORM_WEB
+target_compile_definitions(esengine PUBLIC # NOT ES_PLATFORM_WEB
+ ES_ENABLE_WEBGPU ES_ENABLE_BITMAP_TEXT
+ ES_ENABLE_TILEMAP ES_ENABLE_PARTICLES ES_ENABLE_POSTPROCESS)
target_link_libraries(esengine PUBLIC glm yogacore webgpu_dawn)
# The host (opt-in): a QuickJS runtime drives the engine through the EHT-generated
@@ -136,6 +144,7 @@ if(ESTELLA_QUICKJS_DIR)
host/Host.cpp
host/Runtime.cpp
host/EsnShim.cpp
+ host/bindings/HeapBindings.cpp
host/bindings/EcsBindings.cpp
host/bindings/RenderBindings.cpp
host/bindings/AssetBindings.cpp
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index 5fc228e25..758b3bf2a 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -10,7 +10,10 @@ import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import type { Entity } from '../types';
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import { engineApi } from '../ecs/engineApi';
+import { log } from '../logger';
+import type { AnimCore } from './Tween';
import { Tween, TweenAPI } from './Tween';
import { SpriteAnimation, SpriteAnimationAPI } from './SpriteAnimator';
import { AnimatorController, AnimatorControllerAPI } from './Animator';
@@ -24,9 +27,15 @@ export class AnimationPlugin implements Plugin {
private offDespawn_: (() => void) | null = null;
build(app: App): void {
- const module = app.wasmModule as ESEngineModule;
+ // Whichever core is present (see ecs/engineApi.ts). Sprite animation and the
+ // animator graph are pure TypeScript, but tweens live in the engine, so a core
+ // that compiles no tween system gets the rest of the plugin and says so.
+ const engine = engineApi(app);
const registry = app.world.getCppRegistry() as CppRegistry;
- const tween = new TweenAPI(module, registry);
+ if (engine && typeof engine.anim_createTween !== 'function') {
+ log.warn('animation', 'this engine core has no tween system — Tween.to() will not animate');
+ }
+ const tween = new TweenAPI(engine ?? {}, registry);
app.insertResource(Tween, tween);
const anim = new SpriteAnimationAPI();
app.insertResource(SpriteAnimation, anim);
diff --git a/sdk/src/animation/Tween.ts b/sdk/src/animation/Tween.ts
index 66551b08c..53017b529 100644
--- a/sdk/src/animation/Tween.ts
+++ b/sdk/src/animation/Tween.ts
@@ -10,7 +10,8 @@
*/
import type { Entity } from '../types';
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import type { EngineApi } from '../ecs/engineApi';
import { defineResource } from '../resource';
import { EasingType } from './Easing';
import { LoopMode, TweenState, type TweenOptions } from './TweenTypes';
@@ -42,7 +43,7 @@ export { ValueTweenHandle } from './ValueTween';
* it composes smaller setters on top of `AnimApplicator`. TweenTarget
* is intentionally narrower — just the common property tweens that
* have a fast C++ fast-path. Unifying the two would require
- * `_anim_createTween` on the WASM boundary to accept AnimTargetField
+ * `anim_createTween` on the WASM boundary to accept AnimTargetField
* values directly and an extended TWEEN_TO_ANIM_FIELD map in
* TweenSystem.cpp. That's a larger cross-layer change tracked
* separately; for now TweenTarget is the stable subset.
@@ -73,14 +74,22 @@ export type TweenTarget = (typeof TweenTarget)[keyof typeof TweenTarget];
// Tween Handle (fluent builder)
// =============================================================================
+/**
+ * Whichever engine core drives the tweens: the wasm module on the web, the native
+ * host's bindings on a device (see ecs/engineApi.ts). Every call is optional-chained
+ * — a core built without the tween system leaves a tween inert rather than throwing,
+ * the same way particles and trails already treat an absent entry point.
+ */
+export type AnimCore = NonNullable<EngineApi>;
+
export class TweenHandle {
- private readonly module_: ESEngineModule;
+ private readonly module_: AnimCore;
private readonly registry_: CppRegistry;
private readonly valueManager_: ValueTweenManager;
readonly entity: Entity;
constructor(
- module: ESEngineModule,
+ module: AnimCore,
registry: CppRegistry,
valueManager: ValueTweenManager,
entity: Entity,
@@ -92,11 +101,12 @@ export class TweenHandle {
}
get state(): TweenState {
- return this.module_._anim_getTweenState(this.registry_, this.entity) as TweenState;
+ return (this.module_.anim_getTweenState?.(this.registry_, this.entity)
+ ?? TweenState.Completed) as TweenState;
}
bezier(p1x: number, p1y: number, p2x: number, p2y: number): this {
- this.module_._anim_setTweenBezier(this.registry_, this.entity, p1x, p1y, p2x, p2y);
+ this.module_.anim_setTweenBezier?.(this.registry_, this.entity, p1x, p1y, p2x, p2y);
return this;
}
@@ -105,20 +115,20 @@ export class TweenHandle {
this.valueManager_.registerCppSequence(this.entity, next.id);
return this;
}
- this.module_._anim_setSequenceNext(this.registry_, this.entity, next.entity);
+ this.module_.anim_setSequenceNext?.(this.registry_, this.entity, next.entity);
return this;
}
pause(): void {
- this.module_._anim_pauseTween(this.registry_, this.entity);
+ this.module_.anim_pauseTween?.(this.registry_, this.entity);
}
resume(): void {
- this.module_._anim_resumeTween(this.registry_, this.entity);
+ this.module_.anim_resumeTween?.(this.registry_, this.entity);
}
cancel(): void {
- this.module_._anim_cancelTween(this.registry_, this.entity);
+ this.module_.anim_cancelTween?.(this.registry_, this.entity);
}
}
@@ -127,12 +137,12 @@ export class TweenHandle {
// =============================================================================
export class TweenAPI {
- private readonly module_: ESEngineModule;
+ private readonly module_: AnimCore;
private readonly registry_: CppRegistry;
private readonly valueManager_: ValueTweenManager;
private readonly compositionManager_: TweenCompositionManager;
- constructor(module: ESEngineModule, registry: CppRegistry) {
+ constructor(module: AnimCore, registry: CppRegistry) {
this.module_ = module;
this.registry_ = registry;
this.valueManager_ = new ValueTweenManager(module, registry);
@@ -152,10 +162,11 @@ export class TweenAPI {
const loop = options?.loop ?? LoopMode.None;
const loopCount = options?.loopCount ?? 0;
- const tweenEntity = this.module_._anim_createTween(
+ // No tween system in this core → an inert handle (its state reads Completed).
+ const tweenEntity = (this.module_.anim_createTween?.(
this.registry_, entity, target, from, to, duration,
easing, delay, loop, loopCount,
- ) as Entity;
+ ) ?? 0) as Entity;
return new TweenHandle(this.module_, this.registry_, this.valueManager_, tweenEntity);
}
@@ -172,15 +183,15 @@ export class TweenAPI {
}
cancel(tweenHandle: TweenHandle): void {
- this.module_._anim_cancelTween(this.registry_, tweenHandle.entity);
+ this.module_.anim_cancelTween?.(this.registry_, tweenHandle.entity);
}
cancelAll(entity: Entity): void {
- this.module_._anim_cancelAllTweens(this.registry_, entity);
+ this.module_.anim_cancelAllTweens?.(this.registry_, entity);
}
update(deltaTime: number): void {
- this.module_._anim_updateTweens(this.registry_, deltaTime);
+ this.module_.anim_updateTweens?.(this.registry_, deltaTime);
this.valueManager_.update(deltaTime);
this.compositionManager_.update();
}
diff --git a/sdk/src/animation/ValueTween.ts b/sdk/src/animation/ValueTween.ts
index b9b859737..1ce252bca 100644
--- a/sdk/src/animation/ValueTween.ts
+++ b/sdk/src/animation/ValueTween.ts
@@ -9,7 +9,8 @@
* `handle.state` / `handle.cancel()` etc. route to the right app.
*/
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import type { AnimCore } from './Tween';
import type { Entity } from '../types';
import { applyEasing, EasingType, type BezierPoints } from './Easing';
import { LoopMode, TweenState, type TweenOptions } from './TweenTypes';
@@ -44,10 +45,10 @@ export class ValueTweenManager {
private entries_ = new Map<number, ValueTweenEntry>();
private nextId_ = 1;
private cppSequences_ = new Map<number, number>();
- private readonly module_: ESEngineModule;
+ private readonly module_: AnimCore;
private readonly registry_: CppRegistry;
- constructor(module: ESEngineModule, registry: CppRegistry) {
+ constructor(module: AnimCore, registry: CppRegistry) {
this.module_ = module;
this.registry_ = registry;
}
@@ -82,7 +83,7 @@ export class ValueTweenManager {
update(dt: number): void {
for (const [cppEntity, jsTweenId] of this.cppSequences_) {
- const cppState = this.module_._anim_getTweenState(
+ const cppState = this.module_.anim_getTweenState?.(
this.registry_, cppEntity as Entity,
);
if (cppState === TweenState.Completed) {
diff --git a/sdk/src/corePlugin.ts b/sdk/src/corePlugin.ts
index 5784311e7..c4d7c290c 100644
--- a/sdk/src/corePlugin.ts
+++ b/sdk/src/corePlugin.ts
@@ -33,7 +33,7 @@ export const corePlugin: Plugin = {
initDrawAPI(module);
initGeometryAPI(module);
initMaterialAPI(module);
- initPostProcessAPI(module);
+ initPostProcessAPI(module); // the module IS the core here (see engineApi)
initRendererAPI(module);
initGLDebugAPI(module);
app.insertResource(CameraView, new CameraViewAPI(app));
diff --git a/sdk/src/ecs/nativeEngineApi.generated.ts b/sdk/src/ecs/nativeEngineApi.generated.ts
index 83cf146bb..b0cbeae52 100644
--- a/sdk/src/ecs/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/nativeEngineApi.generated.ts
@@ -8,24 +8,95 @@
// and reaches whichever core is present. Generated from the SAME bindings
// headers embind registers from, so the two surfaces cannot drift.
//
-// Every member is optional: a core answers what it compiles. Entry points that
-// take a heap pointer are NOT here — those need a real backend that decides how
-// bytes cross (see RendererBackend), not a name forwarded.
+// Every member is optional: a core answers what it compiles. A `…Ptr`
+// argument is an offset into the heap the core marshals through — wasm linear
+// memory on the web, the host arena on a device — so a caller writes it the
+// same way on both (see ecs/nativeHeap.ts).
export interface NativeEngineApi {
+ anim_cancelAllTweens?(registry: unknown, targetEntity: number): void;
+ anim_cancelTween?(registry: unknown, tweenEntity: number): void;
+ anim_createTween?(registry: unknown, entity: number, targetProp: number, from: number, to: number, duration: number, easing: number, delay: number, loopMode: number, loopCount: number): number;
+ anim_getTweenState?(registry: unknown, tweenEntity: number): number;
+ anim_pauseTween?(registry: unknown, tweenEntity: number): void;
+ anim_resumeTween?(registry: unknown, tweenEntity: number): void;
+ anim_setSequenceNext?(registry: unknown, tweenEntity: number, nextEntity: number): void;
+ anim_setTweenBezier?(registry: unknown, tweenEntity: number, p1x: number, p1y: number, p2x: number, p2y: number): void;
+ anim_updateTweens?(registry: unknown, deltaTime: number): void;
+ draw_begin?(matrixPtr: number): void;
+ draw_circle?(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
+ draw_circleOutline?(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
+ draw_end?(): void;
+ draw_getDrawCallCount?(): number;
+ draw_getPrimitiveCount?(): number;
+ draw_line?(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
+ draw_mesh?(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
+ draw_meshWithMaterial?(geometryHandle: number, materialId: number): boolean;
+ draw_meshWithUniforms?(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
+ draw_rect?(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
+ draw_rectOutline?(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
+ draw_setBlendMode?(mode: number): void;
+ draw_setDepth?(depth: number): void;
+ draw_setDepthTest?(enabled: boolean): void;
+ draw_setLayer?(layer: number): void;
+ draw_texture?(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
+ draw_textureRotated?(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
+ engine_getCounters?(): string;
+ engine_getCpuScopes?(): string;
+ engine_getGpuScopes?(): string;
engine_setCpuProfiling?(on: boolean): void;
+ geometry_create?(): number;
+ geometry_init?(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
+ geometry_isValid?(handle: number): boolean;
+ geometry_release?(handle: number): void;
+ geometry_setIndices16?(handle: number, indicesPtr: number, indexCount: number): void;
+ geometry_setIndices32?(handle: number, indicesPtr: number, indexCount: number): void;
+ geometry_updateVertices?(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
getUINodeComputedHeight?(registry: unknown, entity: number): number;
getUINodeComputedWidth?(registry: unknown, entity: number): number;
getUINodeHiddenInTree?(registry: unknown, entity: number): boolean;
+ gl_checkErrors?(context: string): number;
gl_enableErrorCheck?(enabled: boolean): void;
+ mesh2d_setGeometry?(registry: unknown, entity: number, posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number): void;
particle_getAliveCount?(entity: number): number;
particle_play?(registry: unknown, entity: number): void;
particle_reset?(registry: unknown, entity: number): void;
+ particle_set_color_lut?(entity: number, ptr: number, count: number): void;
+ particle_set_size_lut?(entity: number, ptr: number, count: number): void;
particle_stop?(registry: unknown, entity: number): void;
particle_update?(registry: unknown, dt: number): void;
+ postprocess_addPass?(name: string, shaderHandle: number): number;
+ postprocess_addScreenPass?(name: string, shaderHandle: number): number;
+ postprocess_begin?(): void;
+ postprocess_beginScreenCapture?(): void;
+ postprocess_clearPasses?(): void;
+ postprocess_clearScreenPasses?(): void;
+ postprocess_end?(): void;
+ postprocess_endScreenCapture?(): void;
+ postprocess_executeScreenPasses?(): void;
+ postprocess_getPassCount?(): number;
+ postprocess_init?(width: number, height: number): boolean;
+ postprocess_isBypassed?(): boolean;
+ postprocess_isInitialized?(): boolean;
+ postprocess_isPassEnabled?(name: string): boolean;
+ postprocess_removePass?(name: string): void;
+ postprocess_resize?(width: number, height: number): void;
+ postprocess_setBypass?(bypass: boolean): void;
+ postprocess_setOutputTarget?(fboId: number): void;
+ postprocess_setOutputViewport?(x: number, y: number, w: number, h: number): void;
+ postprocess_setPassEnabled?(name: string, enabled: boolean): void;
+ postprocess_setPassTexture?(passName: string, uniform: string, textureHandle: number): void;
+ postprocess_setScreenUniformFloat?(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4?(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
+ postprocess_setUniformFloat?(passName: string, uniform: string, value: number): void;
+ postprocess_setUniformVec4?(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
+ postprocess_shutdown?(): void;
+ registry_batchSyncPhysicsTransforms?(registry: unknown, bufferPtr: number, count: number, ppu: number): void;
registry_getCanvasEntity?(registry: unknown): number;
registry_getGeneration?(registry: unknown, entity: number): number;
renderFrame?(registry: unknown, viewportWidth: number, viewportHeight: number): void;
+ renderFrameWithMatrix?(registry: unknown, viewportWidth: number, viewportHeight: number, matrixPtr: number): void;
+ renderer_begin?(matrixPtr: number, targetHandle: number, clearFlags: number, r: number, g: number, b: number, a: number, clearX: number, clearY: number, clearW: number, clearH: number): void;
renderer_beginFrame?(elapsedSec: number): void;
renderer_captureNextFrame?(): void;
renderer_clearAllClipRects?(): void;
@@ -78,9 +149,61 @@ export interface NativeEngineApi {
renderer_submitParticles?(registry: unknown): void;
renderer_submitShapes?(registry: unknown): void;
renderer_submitSpine?(registry: unknown): void;
+ renderer_submitSpineBatch?(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, entity: number, layer: number, depth: number): void;
+ renderer_submitSpineBatchByEntity?(registry: unknown, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number): void;
renderer_submitSprites?(registry: unknown): void;
+ renderer_submitTextBatch?(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number): void;
renderer_submitUIElements?(registry: unknown): void;
renderer_updateTransforms?(registry: unknown): void;
+ rm_acquireTextureByPath?(rm: unknown, path: string): number;
+ rm_createLabelAtlasFont?(rm: unknown, textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ rm_createShader?(rm: unknown, vertSrc: string, fragSrc: string): number;
+ rm_createTexture?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean): number;
+ rm_createTextureEx?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
+ rm_getBitmapFontRefCount?(rm: unknown, handleId: number): number;
+ rm_getShaderRefCount?(rm: unknown, handleId: number): number;
+ rm_getTextureGLId?(rm: unknown, handleId: number): number;
+ 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_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;
+ rm_releaseBitmapFont?(rm: unknown, handleId: number): void;
+ rm_releaseShader?(rm: unknown, handleId: number): void;
+ rm_releaseTexture?(rm: unknown, handleId: number): void;
+ rm_setTextureBudget?(rm: unknown, bytes: number): void;
+ rm_setTextureMetadata?(rm: unknown, handleId: number, left: number, right: number, top: number, bottom: number): void;
+ rm_trimTextureCache?(rm: unknown): number;
+ rm_updateTextureSubregion?(rm: unknown, handleId: number, x: number, y: number, width: number, height: number, pixelsPtr: number, pixelsLen: number): void;
+ tilemap_advanceAnimations?(entity: number, dtMs: number): void;
+ tilemap_clearTileAnimations?(entity: number): void;
+ tilemap_destroyLayer?(entity: number): void;
+ tilemap_exportChunks?(entity: number): string;
+ tilemap_fillRect?(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
+ tilemap_flipTile?(entity: number, x: number, y: number, flipH: boolean, flipV: boolean, flipD: boolean): void;
+ tilemap_getTile?(entity: number, x: number, y: number): number;
+ tilemap_getTileProperty?(entity: number, x: number, y: number, key: string): string;
+ tilemap_hasLayer?(entity: number): boolean;
+ tilemap_importChunks?(entity: number, encoded: string): boolean;
+ tilemap_initInfinite?(entity: number, tileWidth: number, tileHeight: number): void;
+ tilemap_initInfiniteLayer?(entity: number, tileWidth: number, tileHeight: number): void;
+ tilemap_initLayer?(entity: number, width: number, height: number, tileWidth: number, tileHeight: number): void;
+ tilemap_rotateTile?(entity: number, x: number, y: number, degrees: number): void;
+ tilemap_setChunkTiles?(entity: number, chunkX: number, chunkY: number, tilesPtr: number, width: number, height: number): void;
+ tilemap_setGridType?(entity: number, type: number): void;
+ tilemap_setHexParams?(entity: number, sideLength: number, staggerAxisX: number, staggerIndexEven: number): void;
+ tilemap_setOriginEntity?(layerKey: number, originEntity: number): void;
+ tilemap_setRenderProps?(entity: number, textureHandle: number, tilesetColumns: number, uvTileW: number, uvTileH: number, sortLayer: number, depth: number, parallaxX: number, parallaxY: number): void;
+ tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
+ tilemap_setTileAnimation?(entity: number, tileId: number, framesPtr: number, frameCount: number): void;
+ tilemap_setTileProperty?(entity: number, tileId: number, key: string, value: string): void;
+ tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
+ tilemap_setTilesets?(entity: number, dataPtr: number, count: number): void;
+ tilemap_setTint?(entity: number, r: number, g: number, b: number, a: number, opacity: number): void;
+ tilemap_setVisible?(entity: number, visible: boolean): void;
+ tilemap_tileToWorld?(entity: number, tx: number, ty: number, originX: number, originY: number): number;
+ tilemap_worldToTile?(entity: number, wx: number, wy: number, originX: number, originY: number): number;
trail_clear?(registry: unknown, entity: number): void;
trail_update?(registry: unknown, dt: number): void;
transform_patchPosition?(registry: unknown, entity: number, x: number, y: number, z: number): void;
@@ -102,8 +225,6 @@ export interface NativeEngineApi {
ui_getRenderOrder?(registry: unknown, entity: number): number;
}
-// Not forwarded (they take a heap pointer): mesh2d_setGeometry, particle_set_color_lut, particle_set_size_lut, registry_batchSyncPhysicsTransforms, renderFrameWithMatrix, renderer_begin, renderer_submitSpineBatch, renderer_submitSpineBatchByEntity, renderer_submitTextBatch.
-
/** Build the API over a host scope (the QuickJS global object; a plain object
* in tests). A name the host did not bind simply stays absent. */
export function createNativeEngineApi(
@@ -115,22 +236,92 @@ export function createNativeEngineApi(
if (typeof fn !== 'function') return;
const call = fn as (...a: unknown[]) => unknown;
api[name] = dropFirst
- ? (_registry: unknown, ...args: unknown[]) => call(...args)
+ ? (_implicit: unknown, ...args: unknown[]) => call(...args)
: (...args: unknown[]) => call(...args);
};
+ bind('anim_cancelAllTweens', 'es_anim_cancelAllTweens', true);
+ bind('anim_cancelTween', 'es_anim_cancelTween', true);
+ bind('anim_createTween', 'es_anim_createTween', true);
+ bind('anim_getTweenState', 'es_anim_getTweenState', true);
+ bind('anim_pauseTween', 'es_anim_pauseTween', true);
+ bind('anim_resumeTween', 'es_anim_resumeTween', true);
+ bind('anim_setSequenceNext', 'es_anim_setSequenceNext', true);
+ bind('anim_setTweenBezier', 'es_anim_setTweenBezier', true);
+ bind('anim_updateTweens', 'es_anim_updateTweens', true);
+ bind('draw_begin', 'es_draw_begin', false);
+ bind('draw_circle', 'es_draw_circle', false);
+ bind('draw_circleOutline', 'es_draw_circleOutline', false);
+ bind('draw_end', 'es_draw_end', false);
+ bind('draw_getDrawCallCount', 'es_draw_getDrawCallCount', false);
+ bind('draw_getPrimitiveCount', 'es_draw_getPrimitiveCount', false);
+ bind('draw_line', 'es_draw_line', false);
+ bind('draw_mesh', 'es_draw_mesh', false);
+ bind('draw_meshWithMaterial', 'es_draw_meshWithMaterial', false);
+ bind('draw_meshWithUniforms', 'es_draw_meshWithUniforms', false);
+ bind('draw_rect', 'es_draw_rect', false);
+ bind('draw_rectOutline', 'es_draw_rectOutline', false);
+ bind('draw_setBlendMode', 'es_draw_setBlendMode', false);
+ bind('draw_setDepth', 'es_draw_setDepth', false);
+ bind('draw_setDepthTest', 'es_draw_setDepthTest', false);
+ bind('draw_setLayer', 'es_draw_setLayer', false);
+ bind('draw_texture', 'es_draw_texture', false);
+ bind('draw_textureRotated', 'es_draw_textureRotated', false);
+ bind('engine_getCounters', 'es_engine_getCounters', false);
+ bind('engine_getCpuScopes', 'es_engine_getCpuScopes', false);
+ bind('engine_getGpuScopes', 'es_engine_getGpuScopes', false);
bind('engine_setCpuProfiling', 'es_engine_setCpuProfiling', false);
+ bind('geometry_create', 'es_geometry_create', false);
+ bind('geometry_init', 'es_geometry_init', false);
+ bind('geometry_isValid', 'es_geometry_isValid', false);
+ bind('geometry_release', 'es_geometry_release', false);
+ bind('geometry_setIndices16', 'es_geometry_setIndices16', false);
+ bind('geometry_setIndices32', 'es_geometry_setIndices32', false);
+ bind('geometry_updateVertices', 'es_geometry_updateVertices', false);
bind('getUINodeComputedHeight', 'es_getUINodeComputedHeight', true);
bind('getUINodeComputedWidth', 'es_getUINodeComputedWidth', true);
bind('getUINodeHiddenInTree', 'es_getUINodeHiddenInTree', true);
+ bind('gl_checkErrors', 'es_gl_checkErrors', false);
bind('gl_enableErrorCheck', 'es_gl_enableErrorCheck', false);
+ bind('mesh2d_setGeometry', 'es_mesh2d_setGeometry', true);
bind('particle_getAliveCount', 'es_particle_getAliveCount', false);
bind('particle_play', 'es_particle_play', true);
bind('particle_reset', 'es_particle_reset', true);
+ bind('particle_set_color_lut', 'es_particle_set_color_lut', false);
+ bind('particle_set_size_lut', 'es_particle_set_size_lut', false);
bind('particle_stop', 'es_particle_stop', true);
bind('particle_update', 'es_particle_update', true);
+ bind('postprocess_addPass', 'es_postprocess_addPass', false);
+ bind('postprocess_addScreenPass', 'es_postprocess_addScreenPass', false);
+ bind('postprocess_begin', 'es_postprocess_begin', false);
+ bind('postprocess_beginScreenCapture', 'es_postprocess_beginScreenCapture', false);
+ bind('postprocess_clearPasses', 'es_postprocess_clearPasses', false);
+ bind('postprocess_clearScreenPasses', 'es_postprocess_clearScreenPasses', false);
+ bind('postprocess_end', 'es_postprocess_end', false);
+ bind('postprocess_endScreenCapture', 'es_postprocess_endScreenCapture', false);
+ bind('postprocess_executeScreenPasses', 'es_postprocess_executeScreenPasses', false);
+ bind('postprocess_getPassCount', 'es_postprocess_getPassCount', false);
+ bind('postprocess_init', 'es_postprocess_init', false);
+ bind('postprocess_isBypassed', 'es_postprocess_isBypassed', false);
+ bind('postprocess_isInitialized', 'es_postprocess_isInitialized', false);
+ bind('postprocess_isPassEnabled', 'es_postprocess_isPassEnabled', false);
+ bind('postprocess_removePass', 'es_postprocess_removePass', false);
+ bind('postprocess_resize', 'es_postprocess_resize', false);
+ bind('postprocess_setBypass', 'es_postprocess_setBypass', false);
+ bind('postprocess_setOutputTarget', 'es_postprocess_setOutputTarget', false);
+ bind('postprocess_setOutputViewport', 'es_postprocess_setOutputViewport', false);
+ bind('postprocess_setPassEnabled', 'es_postprocess_setPassEnabled', false);
+ bind('postprocess_setPassTexture', 'es_postprocess_setPassTexture', false);
+ bind('postprocess_setScreenUniformFloat', 'es_postprocess_setScreenUniformFloat', false);
+ bind('postprocess_setScreenUniformVec4', 'es_postprocess_setScreenUniformVec4', false);
+ bind('postprocess_setUniformFloat', 'es_postprocess_setUniformFloat', false);
+ bind('postprocess_setUniformVec4', 'es_postprocess_setUniformVec4', false);
+ bind('postprocess_shutdown', 'es_postprocess_shutdown', false);
+ bind('registry_batchSyncPhysicsTransforms', 'es_registry_batchSyncPhysicsTransforms', true);
bind('registry_getCanvasEntity', 'es_registry_getCanvasEntity', true);
bind('registry_getGeneration', 'es_registry_getGeneration', true);
bind('renderFrame', 'es_renderFrame', true);
+ bind('renderFrameWithMatrix', 'es_renderFrameWithMatrix', true);
+ bind('renderer_begin', 'es_renderer_begin', false);
bind('renderer_beginFrame', 'es_renderer_beginFrame', false);
bind('renderer_captureNextFrame', 'es_renderer_captureNextFrame', false);
bind('renderer_clearAllClipRects', 'es_renderer_clearAllClipRects', false);
@@ -183,9 +374,61 @@ export function createNativeEngineApi(
bind('renderer_submitParticles', 'es_renderer_submitParticles', true);
bind('renderer_submitShapes', 'es_renderer_submitShapes', true);
bind('renderer_submitSpine', 'es_renderer_submitSpine', true);
+ bind('renderer_submitSpineBatch', 'es_renderer_submitSpineBatch', false);
+ bind('renderer_submitSpineBatchByEntity', 'es_renderer_submitSpineBatchByEntity', true);
bind('renderer_submitSprites', 'es_renderer_submitSprites', true);
+ bind('renderer_submitTextBatch', 'es_renderer_submitTextBatch', false);
bind('renderer_submitUIElements', 'es_renderer_submitUIElements', true);
bind('renderer_updateTransforms', 'es_renderer_updateTransforms', true);
+ bind('rm_acquireTextureByPath', 'es_rm_acquireTextureByPath', true);
+ bind('rm_createLabelAtlasFont', 'es_rm_createLabelAtlasFont', true);
+ bind('rm_createShader', 'es_rm_createShader', true);
+ bind('rm_createTexture', 'es_rm_createTexture', true);
+ bind('rm_createTextureEx', 'es_rm_createTextureEx', true);
+ bind('rm_getBitmapFontRefCount', 'es_rm_getBitmapFontRefCount', true);
+ bind('rm_getShaderRefCount', 'es_rm_getShaderRefCount', true);
+ bind('rm_getTextureGLId', 'es_rm_getTextureGLId', true);
+ bind('rm_getTextureRefCount', 'es_rm_getTextureRefCount', true);
+ bind('rm_invalidateTexturePath', 'es_rm_invalidateTexturePath', true);
+ bind('rm_loadBitmapFont', 'es_rm_loadBitmapFont', true);
+ bind('rm_registerExternalTexture', 'es_rm_registerExternalTexture', true);
+ bind('rm_registerExternalTextureSized', 'es_rm_registerExternalTextureSized', true);
+ bind('rm_registerTextureWithPath', 'es_rm_registerTextureWithPath', true);
+ bind('rm_releaseBitmapFont', 'es_rm_releaseBitmapFont', true);
+ bind('rm_releaseShader', 'es_rm_releaseShader', true);
+ bind('rm_releaseTexture', 'es_rm_releaseTexture', true);
+ bind('rm_setTextureBudget', 'es_rm_setTextureBudget', true);
+ bind('rm_setTextureMetadata', 'es_rm_setTextureMetadata', true);
+ bind('rm_trimTextureCache', 'es_rm_trimTextureCache', true);
+ bind('rm_updateTextureSubregion', 'es_rm_updateTextureSubregion', true);
+ bind('tilemap_advanceAnimations', 'es_tilemap_advanceAnimations', false);
+ bind('tilemap_clearTileAnimations', 'es_tilemap_clearTileAnimations', false);
+ bind('tilemap_destroyLayer', 'es_tilemap_destroyLayer', false);
+ bind('tilemap_exportChunks', 'es_tilemap_exportChunks', false);
+ bind('tilemap_fillRect', 'es_tilemap_fillRect', false);
+ bind('tilemap_flipTile', 'es_tilemap_flipTile', false);
+ bind('tilemap_getTile', 'es_tilemap_getTile', false);
+ bind('tilemap_getTileProperty', 'es_tilemap_getTileProperty', false);
+ bind('tilemap_hasLayer', 'es_tilemap_hasLayer', false);
+ bind('tilemap_importChunks', 'es_tilemap_importChunks', false);
+ bind('tilemap_initInfinite', 'es_tilemap_initInfinite', false);
+ bind('tilemap_initInfiniteLayer', 'es_tilemap_initInfiniteLayer', false);
+ bind('tilemap_initLayer', 'es_tilemap_initLayer', false);
+ bind('tilemap_rotateTile', 'es_tilemap_rotateTile', false);
+ bind('tilemap_setChunkTiles', 'es_tilemap_setChunkTiles', false);
+ bind('tilemap_setGridType', 'es_tilemap_setGridType', false);
+ bind('tilemap_setHexParams', 'es_tilemap_setHexParams', false);
+ bind('tilemap_setOriginEntity', 'es_tilemap_setOriginEntity', false);
+ bind('tilemap_setRenderProps', 'es_tilemap_setRenderProps', false);
+ bind('tilemap_setTile', 'es_tilemap_setTile', false);
+ bind('tilemap_setTileAnimation', 'es_tilemap_setTileAnimation', false);
+ bind('tilemap_setTileProperty', 'es_tilemap_setTileProperty', false);
+ bind('tilemap_setTiles', 'es_tilemap_setTiles', false);
+ bind('tilemap_setTilesets', 'es_tilemap_setTilesets', false);
+ bind('tilemap_setTint', 'es_tilemap_setTint', false);
+ bind('tilemap_setVisible', 'es_tilemap_setVisible', false);
+ bind('tilemap_tileToWorld', 'es_tilemap_tileToWorld', false);
+ bind('tilemap_worldToTile', 'es_tilemap_worldToTile', false);
bind('trail_clear', 'es_trail_clear', true);
bind('trail_update', 'es_trail_update', true);
bind('transform_patchPosition', 'es_transform_patchPosition', true);
diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.ts
index bbb290e53..476f6c785 100644
--- a/sdk/src/ecs/nativeRuntime.ts
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -16,6 +16,7 @@ import { inputPlugin } from '../input';
import { prefabsPlugin } from '../prefabServer';
import { sceneManagerPlugin } from '../scenePlugin';
import { headlessBasePlugins } from '../webAppFactory';
+import { presentationBasePlugins } from '../pluginSets';
import { ensureBuiltinComponentsRegistered } from '../component';
import { installNativePlatform, type NativeBridge } from '../platform/native';
import { createNativeRegistry } from './nativeRegistry';
@@ -24,7 +25,10 @@ import { createNativeResourceManager } from './nativeResourceManager';
import { HOST_FLAGS, TEXT_BINDINGS, hasTextBindings, hasRendererBindings } from './nativeBindings';
import { createNativeRendererBackend, nativeSurfaceSize } from './nativeRenderer';
import { createNativeEngineApi } from './nativeEngineApi.generated';
-import { setNativeEngineApi } from './engineApi';
+import { setNativeEngineApi, engineApi } from './engineApi';
+import { createNativeHeap } from './nativeHeap';
+import { initPostProcessAPI } from '../postprocess';
+import { log } from '../logger';
import { setRendererBackend } from '../renderer';
import { RenderPipeline } from '../renderPipeline';
import { cameraPlugin } from '../camera/CameraPlugin';
@@ -96,9 +100,32 @@ export function createNativeApp(
app.addPlugin(prefabsPlugin);
app.addPlugin(sceneManagerPlugin);
app.addPlugins(headlessBasePlugins());
+ // The presentation stack — the same list the web factory installs. These used to
+ // be absent on a device, which is why a scene's tilemaps, particles, trails,
+ // meshes and post-process volumes did nothing there: not because the engine
+ // cannot draw them (it is the same C++) but because the plugins that drive them
+ // reached the core as `app.wasmModule`. They go through `engineApi(app)` now, and
+ // each one reports a core that compiles its subsystem out.
+ installNativePostProcess(app);
+ app.addPlugins(presentationBasePlugins());
return app;
}
+/**
+ * Post-processing needs one thing the other presentation plugins do not: the API
+ * bound to the core before the plugin builds (on the web `corePlugin` does this,
+ * and a native app does not run it). The engine's own passes then execute inside
+ * the render pipeline exactly as they do on the web.
+ */
+function installNativePostProcess(app: App): void {
+ const engine = engineApi(app);
+ if (!engine || typeof engine.postprocess_init !== 'function') {
+ log.info('postprocess', 'not available — this engine core was built without it');
+ return;
+ }
+ initPostProcessAPI(engine);
+}
+
/**
* Install the native asset channel — the same `Assets` class the web build uses,
* over the native core. The native analog of the AssetPlugin / runtimeLoader
@@ -132,7 +159,12 @@ function installNativeEngine(scope: Record<string, unknown>): void {
// the same C++ declarations embind registers (nativeEngineApi.generated.ts).
// With this installed, a plugin that calls uiLayout_update / uiHitTest_* /
// uiRenderOrder_update reaches the native core without knowing it is native.
- setNativeEngineApi(createNativeEngineApi(scope));
+ //
+ // The heap rides along: an entry point that takes a `…Ptr` needs somewhere for
+ // the caller to write the bytes, and on this core that is the host's arena
+ // (nativeHeap.ts). Together they make the two cores interchangeable for the
+ // subsystems that marshal buffers — tilemaps, particles, post-processing.
+ setNativeEngineApi({ ...createNativeEngineApi(scope), ...(createNativeHeap(scope) ?? {}) });
}
function installNativeRenderer(app: App, scope: Record<string, unknown>): void {
diff --git a/sdk/src/mesh2d.ts b/sdk/src/mesh2d.ts
index dda8fa640..25f985857 100644
--- a/sdk/src/mesh2d.ts
+++ b/sdk/src/mesh2d.ts
@@ -7,7 +7,9 @@
*/
import type { App, Plugin } from './app';
import type { Entity } from './types';
-import type { ESEngineModule, CppRegistry } from './wasm';
+import type { CppRegistry } from './wasm';
+import type { EngineApi } from './ecs/engineApi';
+import { engineApi } from './ecs/engineApi';
import type { Mesh2DGeometry } from './component';
import { defineResource } from './resource';
import { registerSceneComponentCodec } from './scene';
@@ -26,7 +28,8 @@ export class Mesh2DAPI {
private readonly authored_ = new Map<number, Mesh2DGeometry>();
constructor(
- private readonly module_: ESEngineModule,
+ /** Whichever engine core is present (see ecs/engineApi.ts). */
+ private readonly module_: NonNullable<EngineApi>,
private readonly registry_: CppRegistry,
) {}
@@ -37,7 +40,13 @@ export class Mesh2DAPI {
*/
setGeometry(entity: Entity, geometry: Mesh2DGeometry): void {
const m = this.module_;
- if (!m.mesh2d_setGeometry) return;
+ const upload = m.mesh2d_setGeometry;
+ // A core that compiles no mesh2d, or marshals no buffers, uploads nothing.
+ // The heap is wasm linear memory on the web and the host's arena on a
+ // device — the writes below are identical either way.
+ if (!upload || !m._malloc || !m._free || !m.HEAPU8) return;
+ const heap = m.HEAPU8;
+ const allocator = { _malloc: m._malloc, _free: m._free };
const vertexCount = Math.floor(geometry.positions.length / 2);
const indexCount = geometry.indices.length;
if (vertexCount === 0 || indexCount === 0) {
@@ -45,9 +54,9 @@ export class Mesh2DAPI {
return;
}
- withScratch(m, alloc => {
+ withScratch(allocator, alloc => {
const posUvPtr = alloc(vertexCount * 4 * 4);
- const posUv = new Float32Array(m.HEAPU8.buffer, posUvPtr, vertexCount * 4);
+ const posUv = new Float32Array(heap.buffer, posUvPtr, vertexCount * 4);
const uvs = geometry.uvs;
for (let v = 0; v < vertexCount; v++) {
posUv[v * 4 + 0] = geometry.positions[v * 2 + 0] ?? 0;
@@ -60,15 +69,15 @@ export class Mesh2DAPI {
const colors = geometry.colors;
if (colors && colors.length > 0) {
colorsPtr = alloc(vertexCount * 4);
- const packed = new Uint32Array(m.HEAPU8.buffer, colorsPtr, vertexCount);
+ const packed = new Uint32Array(heap.buffer, colorsPtr, vertexCount);
for (let v = 0; v < vertexCount; v++) packed[v] = packRgba(colors, v);
}
const indicesPtr = alloc(indexCount * 4);
- new Uint32Array(m.HEAPU8.buffer, indicesPtr, indexCount).set(geometry.indices);
+ new Uint32Array(heap.buffer, indicesPtr, indexCount).set(geometry.indices);
- m.mesh2d_setGeometry!(this.registry_, entity, posUvPtr, vertexCount,
- colorsPtr, indicesPtr, indexCount);
+ upload(this.registry_, entity, posUvPtr, vertexCount,
+ colorsPtr, indicesPtr, indexCount);
});
this.authored_.set(entity, geometry);
}
@@ -92,9 +101,11 @@ export class Mesh2DPlugin implements Plugin {
private offDespawn_: (() => void) | null = null;
build(app: App): void {
- const module = app.wasmModule as ESEngineModule;
+ // `?? {}`: an app with no engine core (a test, a pure-logic host) still gets
+ // the resource, and every call through it no-ops.
+ const engine = engineApi(app) ?? {};
const registry = app.world.getCppRegistry() as CppRegistry;
- const api = new Mesh2DAPI(module, registry);
+ const api = new Mesh2DAPI(engine, registry);
app.insertResource(Meshes2D, api);
this.offDespawn_ = app.world.onDespawn((entity: Entity) => {
diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.ts
index 381615172..fdce807d6 100644
--- a/sdk/src/particle/ParticleAPI.ts
+++ b/sdk/src/particle/ParticleAPI.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import type { EngineApi } from '../ecs/engineApi';
import type { Entity } from '../types';
import { defineResource } from '../resource';
@@ -13,10 +14,12 @@ import { defineResource } from '../resource';
* grab it with `app.getResource(Particle)` outside ECS code.
*/
export class ParticleAPI {
- private readonly module_: ESEngineModule;
+ private readonly module_: NonNullable<EngineApi>;
private readonly registry_: CppRegistry;
- constructor(module: ESEngineModule, registry: CppRegistry) {
+ /** @param module whichever engine core is present — the wasm module on the web,
+ * the native host's bindings on a device (see ecs/engineApi.ts). */
+ constructor(module: NonNullable<EngineApi>, registry: CppRegistry) {
this.module_ = module;
this.registry_ = registry;
}
@@ -56,8 +59,10 @@ export class ParticleAPI {
this.uploadLut(this.module_.particle_set_size_lut, entity, lut, 1);
}
- // Copy a Float32Array into the wasm heap and hand its pointer + element count
- // (length / `stride`) to the C++ setter, then free; null/empty clears.
+ // Copy a Float32Array into the core's heap and hand its offset + element count
+ // (length / `stride`) to the C++ setter, then free; null/empty clears. The heap
+ // is wasm linear memory on the web and the host's arena on a device — the same
+ // call either way (see ecs/nativeHeap.ts).
private uploadLut(
fn: ((entity: number, ptr: number, count: number) => void) | undefined,
entity: Entity,
@@ -69,12 +74,14 @@ export class ParticleAPI {
fn(entity as number, 0, 0);
return;
}
- const ptr = this.module_._malloc(lut.length * 4);
+ const { _malloc: malloc, _free: free, HEAPF32: heap } = this.module_;
+ if (!malloc || !free || !heap) return; // a core with no heap marshals nothing
+ const ptr = malloc(lut.length * 4);
try {
- this.module_.HEAPF32.set(lut, ptr / 4);
+ heap.set(lut, ptr / 4);
fn(entity as number, ptr, lut.length / stride);
} finally {
- this.module_._free(ptr);
+ free(ptr);
}
}
}
diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.ts
index 3d570684f..653b5aa39 100644
--- a/sdk/src/particle/ParticlePlugin.ts
+++ b/sdk/src/particle/ParticlePlugin.ts
@@ -5,7 +5,8 @@ import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import { fxPreviewOrPlayMode } from '../env';
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import { engineApi } from '../ecs/engineApi';
import { registerSceneComponentCodec } from '../scene';
import { Particle, ParticleAPI } from './ParticleAPI';
import { bakeGradient, type Gradient } from './gradient';
@@ -21,9 +22,13 @@ export class ParticlePlugin implements Plugin {
private offDespawn_: (() => void) | null = null;
build(app: App): void {
- const module = app.wasmModule as ESEngineModule;
+ // Whichever core is present; a core built without ES_ENABLE_PARTICLES simply
+ // answers no particle_* entry point, which the API already tolerates.
+ // `?? {}`: an app with no engine core (a test, a pure-logic host) still gets
+ // the resource, and every call through it no-ops.
+ const engine = engineApi(app) ?? {};
const registry = app.world.getCppRegistry() as CppRegistry;
- const api = new ParticleAPI(module, registry);
+ const api = new ParticleAPI(engine, registry);
app.insertResource(Particle, api);
// The color gradient is authored as stops in the component data but isn't a
diff --git a/sdk/src/pluginSets.ts b/sdk/src/pluginSets.ts
new file mode 100644
index 000000000..1167f0105
--- /dev/null
+++ b/sdk/src/pluginSets.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pluginSets.ts
+ * @brief Which plugins make up a runtime, in one place.
+ *
+ * @details There are three shapes: the web app (everything), a headless one (the
+ * simulation, nothing to be seen) and a native one (everything, over the
+ * native core). They used to keep three separate lists, and a plugin added
+ * to the web stack quietly skipped the other two — which is how a device
+ * ended up running a game's logic but none of its tilemaps, particles,
+ * trails, meshes or post-process volumes.
+ *
+ * So the web stack is defined here as simulation + presentation, and every
+ * factory takes the part it wants. `sdk/tests/plugin-sets.test.ts` pins the
+ * three against each other.
+ *
+ * Presentation plugins reach the engine through `engineApi(app)`, so they
+ * are core-agnostic: each one runs against the wasm module or the native
+ * host's bindings, and says so when the core it got compiled its subsystem
+ * out. Internal: the factories are the public surface, not the lists.
+ */
+import type { Plugin } from './app';
+import { animationPlugin } from './animation';
+import { audioPlugin } from './audio';
+import { videoPlugin } from './video';
+import { particlePlugin } from './particle';
+import { trailPlugin } from './trail';
+import { mesh2dPlugin } from './mesh2d';
+import { tilemapPlugin } from './tilemap';
+import { postProcessPlugin } from './postprocess';
+import { timelinePlugin } from './timeline';
+import { timerPlugin } from './timer';
+import { velocityPlugin } from './velocity';
+import { lifecyclePlugin } from './lifecycle';
+import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from './ai';
+import { eventBindingPlugin } from './eventBinding';
+import { replicationPlugin } from './net/replication';
+
+/**
+ * The simulation: timers/lifecycle, gameplay AI, audio (silent on a host with no
+ * device) and replication. What an authoritative server runs.
+ */
+export const simulationBasePlugins = (): Plugin[] => [
+ timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,
+ perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
+];
+
+/** What exists to be seen. Every entry drives the engine through `engineApi`. */
+export const presentationBasePlugins = (): Plugin[] => [
+ animationPlugin, videoPlugin, particlePlugin, trailPlugin, mesh2dPlugin,
+ tilemapPlugin, postProcessPlugin, timelinePlugin,
+];
+
+/**
+ * The full stack, in the order the web factory has always built it (build order
+ * decides resource insertion and per-schedule system order, so it is preserved
+ * exactly rather than derived by concatenation).
+ */
+export const webBasePlugins = (): Plugin[] => [
+ timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,
+ particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin,
+ perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
+];
diff --git a/sdk/src/postprocess/PostProcessAPI.ts b/sdk/src/postprocess/PostProcessAPI.ts
index 65da0b2e2..98127d30b 100644
--- a/sdk/src/postprocess/PostProcessAPI.ts
+++ b/sdk/src/postprocess/PostProcessAPI.ts
@@ -1,20 +1,47 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { ESEngineModule } from '../wasm';
import type { Entity } from '../types';
import type { ShaderHandle } from '../material';
+import type { EngineApi } from '../ecs/engineApi';
import { defineResource } from '../resource';
import { handleWasmError } from '../wasmError';
-import { CoreApiBridge } from '../CoreApiBridge';
+import { WasmBridge } from '../WasmBridge';
import { PostProcessStack, PostProcessState } from './PostProcessStack';
-const bridge = new CoreApiBridge('postprocess');
-let module: ESEngineModule | null = null;
+/**
+ * The post-process entry points as a core that HAS them answers them. Named, not
+ * re-declared: the signatures come from the generated engine surface, so this
+ * cannot drift from the C++ (PostProcessBindings.hpp) that produced it.
+ */
+type PostProcessCore = Required<Pick<NonNullable<EngineApi>,
+ 'postprocess_init' | 'postprocess_shutdown' | 'postprocess_resize'
+ | 'postprocess_isInitialized' | 'postprocess_begin' | 'postprocess_end'
+ | 'postprocess_clearPasses' | 'postprocess_addPass' | 'postprocess_setPassTexture'
+ | 'postprocess_setUniformFloat' | 'postprocess_setUniformVec4'
+ | 'postprocess_setBypass' | 'postprocess_setOutputViewport'
+ | 'postprocess_beginScreenCapture' | 'postprocess_endScreenCapture'
+ | 'postprocess_executeScreenPasses' | 'postprocess_addScreenPass'
+ | 'postprocess_clearScreenPasses' | 'postprocess_setScreenUniformFloat'
+ | 'postprocess_setScreenUniformVec4'>>;
+
+/** Guarded view of the core: after a wasm abort a call throws instead of reaching
+ * a dead module; a native host's bindings never abort. */
+class PostProcessBridge extends WasmBridge<NonNullable<EngineApi>> {
+ protected readonly label = 'postprocess';
+}
-/** @internal Wired by the engine plugins — not part of the public API. */
-export function initPostProcessAPI(wasmModule: ESEngineModule): void {
- bridge.connect(wasmModule);
- module = bridge.module;
+const bridge = new PostProcessBridge();
+let module: PostProcessCore | null = null;
+
+/**
+ * @internal Wired by the engine plugins — not part of the public API.
+ * Takes whichever core is present (see ecs/engineApi.ts). A core built without
+ * ES_ENABLE_POSTPROCESS answers none of these entry points; the plugin checks that
+ * before calling, which is what makes the narrowing here sound.
+ */
+export function initPostProcessAPI(engine: NonNullable<EngineApi>): void {
+ bridge.connect(engine);
+ module = bridge.module as PostProcessCore;
}
/** @internal Wired by the engine plugins — not part of the public API. */
@@ -31,7 +58,7 @@ export function shutdownPostProcessAPI(): void {
module = null;
}
-function getModule(): ESEngineModule {
+function getModule(): PostProcessCore {
if (!module) {
throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');
}
diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.ts
index 8a1c242f4..dc82cd2ed 100644
--- a/sdk/src/tilemap/tilemapAPI.ts
+++ b/sdk/src/tilemap/tilemapAPI.ts
@@ -1,10 +1,16 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { ESEngineModule } from '../wasm';
import { withMalloc } from '../wasmScratch';
-import { CoreApiBridge } from '../CoreApiBridge';
+import { WasmBridge } from '../WasmBridge';
+import type { EngineApi } from '../ecs/engineApi';
import { defineResource } from '../resource';
+/**
+ * The tilemap entry points as a core that HAS tilemaps answers them — the shape
+ * this file drives, spelled once. Both cores answer these names (embind on the
+ * web, EHT-generated QuickJS wrappers on a device), and both carry the heap the
+ * tile arrays cross through, so the toolkit below is core-agnostic.
+ */
interface TilemapModule {
tilemap_initLayer(entity: number, width: number, height: number,
tileWidth: number, tileHeight: number): void;
@@ -57,12 +63,22 @@ interface TilemapModule {
_free(ptr: number): void;
}
-const bridge = new CoreApiBridge('tilemap');
+/** Guarded view of the core: after a wasm abort a call throws instead of reaching
+ * a dead module. A native host's bindings pass through the same channel and
+ * simply never abort. */
+class TilemapBridge extends WasmBridge<NonNullable<EngineApi>> {
+ protected readonly label = 'tilemap';
+}
+
+const bridge = new TilemapBridge();
let module_: TilemapModule | null = null;
-/** @internal Wired by the engine plugins — not part of the public API. */
-export function initTilemapAPI(m: ESEngineModule): void {
- bridge.connect(m);
+/** @internal Wired by the engine plugins — not part of the public API.
+ * Takes whichever core is present (see ecs/engineApi.ts); the plugin only calls
+ * this once it has checked that the core compiles tilemaps, which is what makes
+ * the narrowing below sound. */
+export function initTilemapAPI(engine: NonNullable<EngineApi>): void {
+ bridge.connect(engine);
module_ = bridge.module as unknown as TilemapModule;
}
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index b69fd156d..d8f9bcc26 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { App, Plugin } from '../app';
-import type { ESEngineModule } from '../wasm';
+import { engineApi } from '../ecs/engineApi';
import { Transform, TilemapLayer, Sprite, Canvas, RuntimeOnly, Marker, type TilemapLayerData } from '../component';
import { Schedule } from '../system';
import type { SystemDef } from '../system';
@@ -83,8 +83,15 @@ export class TilemapPlugin implements Plugin {
}>();
build(app: App): void {
- const module = app.wasmModule as ESEngineModule;
- initTilemapAPI(module);
+ // Whichever core is present (the wasm module on the web, the native host's
+ // bindings on a device). A core built without ES_ENABLE_TILEMAP answers
+ // none of these, and says so once instead of throwing on the first tile.
+ const engine = engineApi(app);
+ if (!engine || typeof engine.tilemap_initLayer !== 'function') {
+ log.warn('tilemap', 'this engine core has no tilemap support — layers will not render');
+ return;
+ }
+ initTilemapAPI(engine);
// Tile chunks live in a C++ blob, not the component's field record, so
// teach the scene (de)serializer to carry them out-of-band instead of
diff --git a/sdk/src/trail/TrailAPI.ts b/sdk/src/trail/TrailAPI.ts
index b659741fe..722d7568b 100644
--- a/sdk/src/trail/TrailAPI.ts
+++ b/sdk/src/trail/TrailAPI.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import type { EngineApi } from '../ecs/engineApi';
import type { Entity } from '../types';
import { defineResource } from '../resource';
@@ -12,10 +13,11 @@ import { defineResource } from '../resource';
* `app.getResource(Trail)` outside ECS code.
*/
export class TrailAPI {
- private readonly module_: ESEngineModule;
+ private readonly module_: NonNullable<EngineApi>;
private readonly registry_: CppRegistry;
- constructor(module: ESEngineModule, registry: CppRegistry) {
+ /** @param module whichever engine core is present (see ecs/engineApi.ts). */
+ constructor(module: NonNullable<EngineApi>, registry: CppRegistry) {
this.module_ = module;
this.registry_ = registry;
}
diff --git a/sdk/src/trail/TrailPlugin.ts b/sdk/src/trail/TrailPlugin.ts
index 4c642545a..21d20db58 100644
--- a/sdk/src/trail/TrailPlugin.ts
+++ b/sdk/src/trail/TrailPlugin.ts
@@ -5,7 +5,8 @@ import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import { fxPreviewOrPlayMode } from '../env';
-import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import { engineApi } from '../ecs/engineApi';
import { TrailRenderer } from '../component';
import { Trail, TrailAPI } from './TrailAPI';
@@ -14,9 +15,11 @@ export class TrailPlugin implements Plugin {
private offDespawn_: (() => void) | null = null;
build(app: App): void {
- const module = app.wasmModule as ESEngineModule;
+ // `?? {}`: an app with no engine core (a test, a pure-logic host) still gets
+ // the resource, and every call through it no-ops.
+ const engine = engineApi(app) ?? {};
const registry = app.world.getCppRegistry() as CppRegistry;
- const api = new TrailAPI(module, registry);
+ const api = new TrailAPI(engine, registry);
app.insertResource(Trail, api);
// Trail history lives in a C++ side table keyed by entity, not in the
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index 106cfe0e9..234d5bc8f 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -58,7 +58,13 @@ export class TextInputPlugin implements Plugin {
const moduleOrNull = app.wasmModule;
if (!moduleOrNull) {
- log.warn('ui', 'TextInputPlugin: No WASM module available');
+ // Editing needs two things this realm does not have: the module's glyph
+ // measurement and a DOM text field to take keystrokes and IME composition
+ // (a native app has neither — the OS supplies its own editing surface, and
+ // wiring that is its own piece of work). The component still renders through
+ // the shared SDF atlas, so a field shows its value; it just cannot be typed
+ // into. Stated as a fact about the realm, not as a missing dependency.
+ log.info('ui', 'TextInput: this realm has no text-editing surface — fields render, typing is off');
return;
}
const module = moduleOrNull;
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index b356c1802..60c5d0d74 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -440,19 +440,19 @@ export interface ESEngineModule {
transform_patchPosition(registry: CppRegistry, entity: number, x: number, y: number, z: number): void;
// Animation (Tween) API
- _anim_createTween(registry: CppRegistry, entity: number, targetProp: number,
+ anim_createTween(registry: CppRegistry, entity: number, targetProp: number,
from: number, to: number, duration: number,
easing: number, delay: number,
loopMode: number, loopCount: number): number;
- _anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
- _anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_setTweenBezier(registry: CppRegistry, tweenEntity: number,
+ anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
+ anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
+ anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
+ anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
+ anim_setTweenBezier(registry: CppRegistry, tweenEntity: number,
p1x: number, p1y: number, p2x: number, p2y: number): void;
- _anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
- _anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
- _anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
+ anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
+ anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
+ anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
// Pointer-based component access
getTransformPtr(registry: CppRegistry, entity: number): number;
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index 3f266d2c2..3d200da67 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -7,21 +7,7 @@ import { prefabsPlugin } from './prefabServer';
import { sceneManagerPlugin } from './scenePlugin';
import { seedEngineComponents } from './component';
import { uiPlugins } from './uiPlugins';
-import { animationPlugin } from './animation';
-import { audioPlugin } from './audio';
-import { videoPlugin } from './video';
-import { particlePlugin } from './particle';
-import { trailPlugin } from './trail';
-import { mesh2dPlugin } from './mesh2d';
-import { tilemapPlugin } from './tilemap';
-import { postProcessPlugin } from './postprocess';
-import { timelinePlugin } from './timeline';
-import { timerPlugin } from './timer';
-import { velocityPlugin } from './velocity';
-import { lifecyclePlugin } from './lifecycle';
-import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from './ai';
-import { eventBindingPlugin } from './eventBinding';
-import { replicationPlugin } from './net/replication';
+import { simulationBasePlugins, webBasePlugins } from './pluginSets';
import { SpinePlugin } from './spine';
import { createFetchSideModuleHost, type SideModuleHost } from './sideModules';
@@ -37,7 +23,9 @@ export interface CreateWebAppOptions extends WebAppOptions {
wasmBaseUrl?: string;
}
-const basePlugins = [timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin, particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin];
+// Simulation + presentation, in build order (see pluginSets.ts — one definition,
+// so the headless and native factories cannot drift from this one).
+const basePlugins = webBasePlugins();
export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {
const sideModules: SideModuleHost | undefined = options?.sideModules
@@ -54,16 +42,10 @@ export interface HeadlessAppOptions {
sideModules?: SideModuleHost;
}
-// The simulation-relevant plugin set: timers/lifecycle, gameplay AI, audio
-// (silent on hosts without a device) and replication. Presentation plugins
-// (particles, tilemap render, post-process, timeline, UI, spine) stay out —
-// they exist to be seen.
-/** The simulation stack with no presentation — shared by the headless and
- * native factories, so neither drifts into its own plugin list. */
-export const headlessBasePlugins = (): Plugin[] => [
- timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,
- perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
-];
+/** The simulation stack with no presentation: timers/lifecycle, gameplay AI, audio
+ * (silent on a host with no device) and replication. Presentation plugins exist to
+ * be seen, so a headless app leaves them out — see pluginSets.ts. */
+export const headlessBasePlugins = (): Plugin[] => simulationBasePlugins();
/**
* An App with the full simulation stack and no presentation: no renderer, no
diff --git a/sdk/tests/binding-surface.test.ts b/sdk/tests/binding-surface.test.ts
index ad6869332..91492bad8 100644
--- a/sdk/tests/binding-surface.test.ts
+++ b/sdk/tests/binding-surface.test.ts
@@ -402,6 +402,9 @@ const pooledModuleCpp = [
'bindings/ImmediateDrawBindings.cpp',
'bindings/PostProcessBindings.hpp',
'bindings/PostProcessBindings.cpp',
+ 'bindings/TilemapBindings.hpp',
+ 'bindings/AnimationBindings.hpp',
+ 'bindings/AnimationBindings.cpp',
].map((f) => stripComments(read(resolve(CPP, f)))).join('\n');
function expectArities(label: string, tsSigs: Map<string, number>, cppSigs: Map<string, number>): void {
diff --git a/sdk/tests/cpp-contract.test.ts b/sdk/tests/cpp-contract.test.ts
index c0336c4b7..eaa897bf9 100644
--- a/sdk/tests/cpp-contract.test.ts
+++ b/sdk/tests/cpp-contract.test.ts
@@ -106,7 +106,7 @@ describe('C++ contract: animation tween enums (animation/TweenData.hpp)', () =>
it('EasingType matches (same names + values, minus COUNT sentinel)', () => {
// The TS easing dispatcher switches on these values; they are the wire
- // protocol for _anim_createTween's easing byte.
+ // protocol for anim_createTween's easing byte.
expect(sortedEntries(new Map(Object.entries(EasingType))))
.toEqual(sortedEntries(byName(parseEnum(src, 'EasingType'))));
});
diff --git a/sdk/tests/plugin-sets.test.ts b/sdk/tests/plugin-sets.test.ts
new file mode 100644
index 000000000..48c099eec
--- /dev/null
+++ b/sdk/tests/plugin-sets.test.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The web, headless and native runtimes are three slices of ONE plugin list.
+// Before that, each factory kept its own: the presentation plugins were listed in
+// the web factory only, so a device ran a game's logic and none of its tilemaps,
+// particles, trails, meshes or post-process volumes — and nothing said so.
+//
+// These pin the slices against each other, so adding a plugin to the web stack
+// forces a decision about the other two instead of silently skipping them.
+import { describe, it, expect } from 'vitest';
+import {
+ simulationBasePlugins, presentationBasePlugins, webBasePlugins,
+} from '../src/pluginSets';
+
+const names = (plugins: { name: string }[]): string[] => plugins.map((p) => p.name).sort();
+
+describe('plugin sets', () => {
+ it('the web stack is exactly simulation + presentation', () => {
+ expect(names(webBasePlugins()))
+ .toEqual(names([...simulationBasePlugins(), ...presentationBasePlugins()]));
+ });
+
+ it('nothing is in both halves', () => {
+ const sim = new Set(names(simulationBasePlugins()));
+ const both = names(presentationBasePlugins()).filter((n) => sim.has(n));
+ expect(both).toEqual([]);
+ });
+
+ it('each half is free of duplicates', () => {
+ for (const set of [simulationBasePlugins(), presentationBasePlugins()]) {
+ expect(names(set)).toEqual([...new Set(names(set))]);
+ }
+ });
+
+ it('the lists hand out the same plugin instances every call', () => {
+ // They are module singletons holding per-app state keyed by App, so two
+ // factories in one process must not build two copies.
+ expect(webBasePlugins()[0]).toBe(webBasePlugins()[0]);
+ });
+});
diff --git a/sdk/tests/tween.test.ts b/sdk/tests/tween.test.ts
index 812f1e520..df4a57f5d 100644
--- a/sdk/tests/tween.test.ts
+++ b/sdk/tests/tween.test.ts
@@ -23,19 +23,19 @@ function createMockAnimModule() {
const registry = {} as CppRegistry;
const module = {
- _anim_createTween: vi.fn((_reg: CppRegistry, entity: number, targetProp: number,
+ anim_createTween: vi.fn((_reg: CppRegistry, entity: number, targetProp: number,
from: number, to: number, duration: number,
easing: number, delay: number, loopMode: number, loopCount: number) => {
return nextTweenEntity++;
}),
- _anim_cancelTween: vi.fn(),
- _anim_cancelAllTweens: vi.fn(),
- _anim_pauseTween: vi.fn(),
- _anim_resumeTween: vi.fn(),
- _anim_setTweenBezier: vi.fn(),
- _anim_setSequenceNext: vi.fn(),
- _anim_updateTweens: vi.fn(),
- _anim_getTweenState: vi.fn(() => TweenState.Running),
+ anim_cancelTween: vi.fn(),
+ anim_cancelAllTweens: vi.fn(),
+ anim_pauseTween: vi.fn(),
+ anim_resumeTween: vi.fn(),
+ anim_setTweenBezier: vi.fn(),
+ anim_setSequenceNext: vi.fn(),
+ anim_updateTweens: vi.fn(),
+ anim_getTweenState: vi.fn(() => TweenState.Running),
} as unknown as ESEngineModule;
return { module, registry, calls };
@@ -97,7 +97,7 @@ describe('Tween API', () => {
const entity = 42 as Entity;
tween.to(entity, TweenTarget.PositionX, 0, 100, 1.5);
- expect(module._anim_createTween).toHaveBeenCalledWith(
+ expect(module.anim_createTween).toHaveBeenCalledWith(
registry, 42, TweenTarget.PositionX,
0, 100, 1.5,
EasingType.Linear, 0, LoopMode.None, 0,
@@ -109,7 +109,7 @@ describe('Tween API', () => {
easing: EasingType.EaseOutQuad,
});
- expect(module._anim_createTween).toHaveBeenCalledWith(
+ expect(module.anim_createTween).toHaveBeenCalledWith(
registry, 1, TweenTarget.ColorA,
1, 0, 0.5,
EasingType.EaseOutQuad, 0, LoopMode.None, 0,
@@ -121,7 +121,7 @@ describe('Tween API', () => {
delay: 0.5,
});
- expect(module._anim_createTween).toHaveBeenCalledWith(
+ expect(module.anim_createTween).toHaveBeenCalledWith(
registry, 1, TweenTarget.ScaleX,
1, 2, 1,
EasingType.Linear, 0.5, LoopMode.None, 0,
@@ -134,7 +134,7 @@ describe('Tween API', () => {
loopCount: 3,
});
- expect(module._anim_createTween).toHaveBeenCalledWith(
+ expect(module.anim_createTween).toHaveBeenCalledWith(
registry, 1, TweenTarget.PositionY,
0, 50, 2,
EasingType.Linear, 0, LoopMode.PingPong, 3,
@@ -153,7 +153,7 @@ describe('Tween API', () => {
describe('TweenHandle', () => {
it('should report state from WASM', () => {
- (module._anim_getTweenState as ReturnType<typeof vi.fn>)
+ (module.anim_getTweenState as ReturnType<typeof vi.fn>)
.mockReturnValueOnce(TweenState.Paused);
const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
@@ -164,7 +164,7 @@ describe('Tween API', () => {
const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.bezier(0.25, 0.1, 0.25, 1.0);
- expect(module._anim_setTweenBezier).toHaveBeenCalledWith(
+ expect(module.anim_setTweenBezier).toHaveBeenCalledWith(
registry, handle.entity, 0.25, 0.1, 0.25, 1.0,
);
});
@@ -180,7 +180,7 @@ describe('Tween API', () => {
const h2 = tween.to(1 as Entity, TweenTarget.PositionY, 0, 20, 1);
h1.then(h2);
- expect(module._anim_setSequenceNext).toHaveBeenCalledWith(
+ expect(module.anim_setSequenceNext).toHaveBeenCalledWith(
registry, h1.entity, h2.entity,
);
});
@@ -196,21 +196,21 @@ describe('Tween API', () => {
const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.pause();
- expect(module._anim_pauseTween).toHaveBeenCalledWith(registry, handle.entity);
+ expect(module.anim_pauseTween).toHaveBeenCalledWith(registry, handle.entity);
});
it('should resume a tween', () => {
const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.resume();
- expect(module._anim_resumeTween).toHaveBeenCalledWith(registry, handle.entity);
+ expect(module.anim_resumeTween).toHaveBeenCalledWith(registry, handle.entity);
});
it('should cancel a tween via handle', () => {
const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.cancel();
- expect(module._anim_cancelTween).toHaveBeenCalledWith(registry, handle.entity);
+ expect(module.anim_cancelTween).toHaveBeenCalledWith(registry, handle.entity);
});
});
@@ -223,20 +223,20 @@ describe('Tween API', () => {
const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
tween.cancel(handle);
- expect(module._anim_cancelTween).toHaveBeenCalledWith(registry, handle.entity);
+ expect(module.anim_cancelTween).toHaveBeenCalledWith(registry, handle.entity);
});
it('tween.cancelAll() should delegate to WASM', () => {
const entity = 5 as Entity;
tween.cancelAll(entity);
- expect(module._anim_cancelAllTweens).toHaveBeenCalledWith(registry, 5);
+ expect(module.anim_cancelAllTweens).toHaveBeenCalledWith(registry, 5);
});
it('tween.update() should delegate to WASM', () => {
tween.update(0.016);
- expect(module._anim_updateTweens).toHaveBeenCalledWith(registry, 0.016);
+ expect(module.anim_updateTweens).toHaveBeenCalledWith(registry, 0.016);
});
});
@@ -252,14 +252,14 @@ describe('Tween API', () => {
tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
tween2.to(2 as Entity, TweenTarget.PositionY, 0, 20, 1);
- expect(module._anim_createTween).toHaveBeenCalledTimes(1);
- expect(module2._anim_createTween).toHaveBeenCalledTimes(1);
- expect(module._anim_createTween).toHaveBeenCalledWith(
+ expect(module.anim_createTween).toHaveBeenCalledTimes(1);
+ expect(module2.anim_createTween).toHaveBeenCalledTimes(1);
+ expect(module.anim_createTween).toHaveBeenCalledWith(
registry, 1, TweenTarget.PositionX,
0, 10, 1,
EasingType.Linear, 0, LoopMode.None, 0,
);
- expect(module2._anim_createTween).toHaveBeenCalledWith(
+ expect(module2.anim_createTween).toHaveBeenCalledWith(
registry2, 2, TweenTarget.PositionY,
0, 20, 1,
EasingType.Linear, 0, LoopMode.None, 0,
diff --git a/sdk/tests/value-tween.test.ts b/sdk/tests/value-tween.test.ts
index fd62294fd..a744185d6 100644
--- a/sdk/tests/value-tween.test.ts
+++ b/sdk/tests/value-tween.test.ts
@@ -12,12 +12,13 @@ import { describe, it, expect, vi } from 'vitest';
import { ValueTweenManager, ValueTweenHandle } from '../src/animation/ValueTween';
import { TweenGroup } from '../src/animation/TweenGroup';
import { TweenState, LoopMode } from '../src/animation/TweenTypes';
-import type { ESEngineModule, CppRegistry } from '../src/wasm';
+import type { CppRegistry } from '../src/wasm';
+import type { AnimCore } from '../src/animation/Tween';
-// The manager only ever calls module._anim_getTweenState (for C++ sequences);
+// The manager only ever calls module.anim_getTweenState (for C++ sequences);
// everything else is pure JS. A closure-controlled stub covers that one seam.
function makeManager(cppState: () => number = () => TweenState.Running) {
- const module = { _anim_getTweenState: vi.fn(() => cppState()) } as unknown as ESEngineModule;
+ const module = { anim_getTweenState: vi.fn(() => cppState()) } as unknown as AnimCore;
const registry = {} as CppRegistry;
return new ValueTweenManager(module, registry);
}
diff --git a/src/esengine/bindings/AnimationBindings.cpp b/src/esengine/bindings/AnimationBindings.cpp
new file mode 100644
index 000000000..de946757a
--- /dev/null
+++ b/src/esengine/bindings/AnimationBindings.cpp
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AnimationBindings.cpp
+ * @brief The tween entry points the SDK's Tween API drives.
+ * @details Moved out of WebSDKEntry.cpp — the emscripten entry TU — which is the
+ * only reason they were web-only: the bodies just reach the engine through
+ * activeCtx() and the registry, both portable. A device now compiles this
+ * TU and registers the same functions from generated QuickJS wrappers, so
+ * tweens run there on the same implementation.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "AnimationBindings.hpp"
+
+#include "ActiveContext.hpp"
+#include "../animation/TweenSystem.hpp"
+
+namespace esengine {
+
+// The active context, spelled as every other binding TU spells it.
+static EstellaContext& ctx() { return activeCtx(); }
+
+u32 anim_createTween(ecs::Registry& registry, u32 entity, u32 targetProp,
+ f32 from, f32 to, f32 duration,
+ u32 easing, f32 delay,
+ u32 loopMode, i32 loopCount) {
+ auto* sys = ctx().tryGet<animation::TweenSystem>();
+ if (!sys) {
+ return INVALID_ENTITY.id();
+ }
+ auto tweenEntity = sys->createTween(
+ registry, Entity::fromRaw(entity),
+ static_cast<animation::TweenTarget>(targetProp),
+ from, to, duration,
+ static_cast<animation::EasingType>(easing));
+
+ auto& tween = registry.get<animation::TweenData>(tweenEntity);
+ tween.delay = delay;
+ tween.loop_mode = static_cast<animation::LoopMode>(loopMode);
+ tween.loop_count = loopCount;
+ tween.loops_remaining = loopCount;
+ return tweenEntity.id();
+}
+
+void anim_cancelTween(ecs::Registry& registry, u32 tweenEntity) {
+ if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
+ sys->cancelTween(registry, Entity::fromRaw(tweenEntity));
+ }
+}
+
+void anim_cancelAllTweens(ecs::Registry& registry, u32 targetEntity) {
+ if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
+ sys->cancelAllTweens(registry, Entity::fromRaw(targetEntity));
+ }
+}
+
+void anim_pauseTween(ecs::Registry& registry, u32 tweenEntity) {
+ if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
+ sys->pauseTween(registry, Entity::fromRaw(tweenEntity));
+ }
+}
+
+void anim_resumeTween(ecs::Registry& registry, u32 tweenEntity) {
+ if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
+ sys->resumeTween(registry, Entity::fromRaw(tweenEntity));
+ }
+}
+
+void anim_setTweenBezier(ecs::Registry& registry, u32 tweenEntity,
+ f32 p1x, f32 p1y, f32 p2x, f32 p2y) {
+ if (auto* tween = registry.tryGet<animation::TweenData>(Entity::fromRaw(tweenEntity))) {
+ tween->easing = animation::EasingType::CubicBezier;
+ tween->bezier_p1x = p1x;
+ tween->bezier_p1y = p1y;
+ tween->bezier_p2x = p2x;
+ tween->bezier_p2y = p2y;
+ }
+}
+
+void anim_setSequenceNext(ecs::Registry& registry, u32 tweenEntity, u32 nextEntity) {
+ if (auto* tween = registry.tryGet<animation::TweenData>(Entity::fromRaw(tweenEntity))) {
+ tween->sequence_next = Entity::fromRaw(nextEntity);
+ }
+}
+
+void anim_updateTweens(ecs::Registry& registry, f32 deltaTime) {
+ if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
+ sys->update(registry, deltaTime);
+ }
+}
+
+i32 anim_getTweenState(ecs::Registry& registry, u32 tweenEntity) {
+ if (auto* tween = registry.tryGet<animation::TweenData>(Entity::fromRaw(tweenEntity))) {
+ return static_cast<i32>(tween->state);
+ }
+ return static_cast<i32>(animation::TweenState::Completed);
+}
+
+} // namespace esengine
diff --git a/src/esengine/bindings/AnimationBindings.hpp b/src/esengine/bindings/AnimationBindings.hpp
new file mode 100644
index 000000000..84849e0ed
--- /dev/null
+++ b/src/esengine/bindings/AnimationBindings.hpp
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AnimationBindings.hpp
+ * @brief The tween entry points, declared once for both registration layers.
+ * @details The SDK's `Tween` API creates and drives tweens as ECS entities through
+ * these. They were defined inside the emscripten entry TU, which made them
+ * web-only by construction even though the bodies are portable; declaring
+ * them here is what lets embind register them for the web and EHT generate
+ * the QuickJS wrappers for a device, from one source.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../core/Types.hpp"
+#include "../ecs/Registry.hpp"
+
+namespace esengine {
+
+/** Create a tween entity animating @p targetProp of @p entity. Returns the tween
+ * entity's raw id (the invalid id when no tween system is installed). */
+u32 anim_createTween(ecs::Registry& registry, u32 entity, u32 targetProp,
+ f32 from, f32 to, f32 duration,
+ u32 easing, f32 delay,
+ u32 loopMode, i32 loopCount);
+void anim_cancelTween(ecs::Registry& registry, u32 tweenEntity);
+void anim_cancelAllTweens(ecs::Registry& registry, u32 targetEntity);
+void anim_pauseTween(ecs::Registry& registry, u32 tweenEntity);
+void anim_resumeTween(ecs::Registry& registry, u32 tweenEntity);
+void anim_setTweenBezier(ecs::Registry& registry, u32 tweenEntity,
+ f32 p1x, f32 p1y, f32 p2x, f32 p2y);
+/** Chain @p nextEntity to run when @p tweenEntity completes. */
+void anim_setSequenceNext(ecs::Registry& registry, u32 tweenEntity, u32 nextEntity);
+void anim_updateTweens(ecs::Registry& registry, f32 deltaTime);
+/** The tween's `animation::TweenState`, or Completed when it no longer exists. */
+i32 anim_getTweenState(ecs::Registry& registry, u32 tweenEntity);
+
+} // namespace esengine
diff --git a/src/esengine/bindings/TilemapBindings.cpp b/src/esengine/bindings/TilemapBindings.cpp
index b0cf89b24..efcea6731 100644
--- a/src/esengine/bindings/TilemapBindings.cpp
+++ b/src/esengine/bindings/TilemapBindings.cpp
@@ -2,6 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#ifdef ES_ENABLE_TILEMAP
+#include "TilemapBindings.hpp"
+
#include "ActiveContext.hpp"
#include "BoundarySpan.hpp"
#include "../tilemap/TilemapSystem.hpp"
@@ -13,7 +15,6 @@
#include "../resource/ResourceManager.hpp"
#include "../ecs/TransformSystem.hpp"
-#include <emscripten/bind.h>
#include <cstring>
#include <string>
#include <utility>
@@ -395,38 +396,4 @@ uintptr_t tilemap_worldToTile(u32 entity, f32 wx, f32 wy,
} // namespace esengine
-EMSCRIPTEN_BINDINGS(esengine_tilemap) {
- emscripten::function("tilemap_initLayer", &esengine::tilemap_initLayer);
- emscripten::function("tilemap_initInfinite", &esengine::tilemap_initInfinite);
- emscripten::function("tilemap_destroyLayer", &esengine::tilemap_destroyLayer);
- emscripten::function("tilemap_setTile", &esengine::tilemap_setTile);
- emscripten::function("tilemap_getTile", &esengine::tilemap_getTile);
- emscripten::function("tilemap_fillRect", &esengine::tilemap_fillRect);
- emscripten::function("tilemap_setTiles", &esengine::tilemap_setTiles);
- emscripten::function("tilemap_setTilesets", &esengine::tilemap_setTilesets);
- emscripten::function("tilemap_hasLayer", &esengine::tilemap_hasLayer);
- emscripten::function("tilemap_setRenderProps", &esengine::tilemap_setRenderProps);
- emscripten::function("tilemap_setTint", &esengine::tilemap_setTint);
- emscripten::function("tilemap_setVisible", &esengine::tilemap_setVisible);
- emscripten::function("tilemap_setOriginEntity", &esengine::tilemap_setOriginEntity);
- emscripten::function("tilemap_exportChunks", &esengine::tilemap_exportChunks);
- emscripten::function("tilemap_importChunks", &esengine::tilemap_importChunks);
-
-
- emscripten::function("tilemap_initInfiniteLayer", &esengine::tilemap_initInfiniteLayer);
- emscripten::function("tilemap_setChunkTiles", &esengine::tilemap_setChunkTiles);
-
- emscripten::function("tilemap_setTileAnimation", &esengine::tilemap_setTileAnimation);
- emscripten::function("tilemap_clearTileAnimations", &esengine::tilemap_clearTileAnimations);
- emscripten::function("tilemap_advanceAnimations", &esengine::tilemap_advanceAnimations);
- emscripten::function("tilemap_setTileProperty", &esengine::tilemap_setTileProperty);
- emscripten::function("tilemap_getTileProperty", &esengine::tilemap_getTileProperty);
- emscripten::function("tilemap_flipTile", &esengine::tilemap_flipTile);
- emscripten::function("tilemap_rotateTile", &esengine::tilemap_rotateTile);
- emscripten::function("tilemap_setGridType", &esengine::tilemap_setGridType);
- emscripten::function("tilemap_setHexParams", &esengine::tilemap_setHexParams);
- emscripten::function("tilemap_tileToWorld", &esengine::tilemap_tileToWorld);
- emscripten::function("tilemap_worldToTile", &esengine::tilemap_worldToTile);
-}
-
#endif // ES_ENABLE_TILEMAP
diff --git a/src/esengine/bindings/TilemapBindings.hpp b/src/esengine/bindings/TilemapBindings.hpp
new file mode 100644
index 000000000..e034ab668
--- /dev/null
+++ b/src/esengine/bindings/TilemapBindings.hpp
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TilemapBindings.hpp
+ * @brief The tilemap entry points the SDK drives layers through.
+ * @details Declared here rather than only defined in the .cpp for the reason every
+ * other binding header exists: the declaration is the single source both
+ * registration layers are generated from — embind for the web
+ * (WebSDKEntry.cpp) and QuickJS wrappers for a native host
+ * (`eht --native-functions`). While these lived only in the .cpp, a device
+ * build had no tilemaps at all.
+ *
+ * Addressing: a "layer" is an entity. Tile arrays cross as an offset into
+ * the heap the caller marshals through (wasm linear memory on the web, the
+ * host arena on a device) plus a count, validated by `BoundarySpan`.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#ifdef ES_ENABLE_TILEMAP
+
+#include "../core/Types.hpp"
+
+#include <cstdint>
+#include <string>
+
+namespace esengine {
+
+// — Layer lifecycle —
+
+void tilemap_initLayer(u32 entity, u32 width, u32 height, f32 tileWidth, f32 tileHeight);
+void tilemap_initInfinite(u32 entity, f32 tileWidth, f32 tileHeight);
+void tilemap_initInfiniteLayer(u32 entity, f32 tileWidth, f32 tileHeight);
+void tilemap_destroyLayer(u32 entity);
+bool tilemap_hasLayer(u32 entity);
+
+// — Tiles —
+
+void tilemap_setTile(u32 entity, i32 x, i32 y, u32 tileId);
+u32 tilemap_getTile(u32 entity, i32 x, i32 y);
+void tilemap_fillRect(u32 entity, i32 x, i32 y, u32 w, u32 h, u32 tileId);
+void tilemap_setTiles(u32 entity, uintptr_t tilesPtr, u32 count);
+void tilemap_setChunkTiles(u32 entity, i32 chunkX, i32 chunkY,
+ uintptr_t tilesPtr, u32 width, u32 height);
+void tilemap_flipTile(u32 entity, i32 x, i32 y, bool flipH, bool flipV, bool flipD);
+void tilemap_rotateTile(u32 entity, i32 x, i32 y, i32 degrees);
+
+// — Rendering —
+
+void tilemap_setTilesets(u32 entity, uintptr_t dataPtr, u32 count);
+void tilemap_setRenderProps(u32 entity, u32 textureHandle, u32 tilesetColumns,
+ f32 uvTileW, f32 uvTileH,
+ i32 sortLayer, f32 depth,
+ f32 parallaxX, f32 parallaxY);
+void tilemap_setTint(u32 entity, f32 r, f32 g, f32 b, f32 a, f32 opacity);
+void tilemap_setVisible(u32 entity, bool visible);
+void tilemap_setOriginEntity(u32 layerKey, u32 originEntity);
+
+// — Grid shape (orthogonal / isometric / staggered / hexagonal) —
+
+void tilemap_setGridType(u32 entity, u32 type);
+void tilemap_setHexParams(u32 entity, f32 sideLength, u32 staggerAxisX, u32 staggerIndexEven);
+
+// Both answer a pair of floats in a shared static buffer, so the offset is stable
+// and the byte count is fixed.
+// @heapreturn 2 * sizeof(float)
+uintptr_t tilemap_tileToWorld(u32 entity, i32 tx, i32 ty, f32 originX, f32 originY);
+// @heapreturn 2 * sizeof(float)
+uintptr_t tilemap_worldToTile(u32 entity, f32 wx, f32 wy, f32 originX, f32 originY);
+
+// — Animated tiles —
+
+void tilemap_setTileAnimation(u32 entity, u32 tileId, uintptr_t framesPtr, u32 frameCount);
+void tilemap_clearTileAnimations(u32 entity);
+void tilemap_advanceAnimations(u32 entity, f32 dtMs);
+
+// — Tile properties + chunk serialization (the editor's tools and .estileset) —
+
+void tilemap_setTileProperty(u32 entity, u32 tileId,
+ const std::string& key, const std::string& value);
+std::string tilemap_getTileProperty(u32 entity, i32 x, i32 y, const std::string& key);
+std::string tilemap_exportChunks(u32 entity);
+bool tilemap_importChunks(u32 entity, const std::string& encoded);
+
+} // namespace esengine
+
+#endif // ES_ENABLE_TILEMAP
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 7b2acf315..ceef0ffcd 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -24,9 +24,13 @@
#include "BoundarySpan.hpp"
#include "ImmediateDrawBindings.hpp"
#include "GeometryBindings.hpp"
+#include "AnimationBindings.hpp"
#ifdef ES_ENABLE_POSTPROCESS
#include "PostProcessBindings.hpp"
#endif
+#ifdef ES_ENABLE_TILEMAP
+#include "TilemapBindings.hpp"
+#endif
#include "../ecs/UILayoutSystem.hpp"
#include "../ecs/UIHitTestSystem.hpp"
@@ -600,6 +604,39 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("postprocess_setScreenUniformVec4", &esengine::postprocess_setScreenUniformVec4);
#endif
+#ifdef ES_ENABLE_TILEMAP
+ // Tilemaps registered here with every other binding, from the same
+ // TilemapBindings.hpp declarations the native wrappers are generated from.
+ emscripten::function("tilemap_initLayer", &esengine::tilemap_initLayer);
+ emscripten::function("tilemap_initInfinite", &esengine::tilemap_initInfinite);
+ emscripten::function("tilemap_destroyLayer", &esengine::tilemap_destroyLayer);
+ emscripten::function("tilemap_setTile", &esengine::tilemap_setTile);
+ emscripten::function("tilemap_getTile", &esengine::tilemap_getTile);
+ emscripten::function("tilemap_fillRect", &esengine::tilemap_fillRect);
+ emscripten::function("tilemap_setTiles", &esengine::tilemap_setTiles);
+ emscripten::function("tilemap_setTilesets", &esengine::tilemap_setTilesets);
+ emscripten::function("tilemap_hasLayer", &esengine::tilemap_hasLayer);
+ emscripten::function("tilemap_setRenderProps", &esengine::tilemap_setRenderProps);
+ emscripten::function("tilemap_setTint", &esengine::tilemap_setTint);
+ emscripten::function("tilemap_setVisible", &esengine::tilemap_setVisible);
+ emscripten::function("tilemap_setOriginEntity", &esengine::tilemap_setOriginEntity);
+ emscripten::function("tilemap_exportChunks", &esengine::tilemap_exportChunks);
+ emscripten::function("tilemap_importChunks", &esengine::tilemap_importChunks);
+ emscripten::function("tilemap_initInfiniteLayer", &esengine::tilemap_initInfiniteLayer);
+ emscripten::function("tilemap_setChunkTiles", &esengine::tilemap_setChunkTiles);
+ emscripten::function("tilemap_setTileAnimation", &esengine::tilemap_setTileAnimation);
+ emscripten::function("tilemap_clearTileAnimations", &esengine::tilemap_clearTileAnimations);
+ emscripten::function("tilemap_advanceAnimations", &esengine::tilemap_advanceAnimations);
+ emscripten::function("tilemap_setTileProperty", &esengine::tilemap_setTileProperty);
+ emscripten::function("tilemap_getTileProperty", &esengine::tilemap_getTileProperty);
+ emscripten::function("tilemap_flipTile", &esengine::tilemap_flipTile);
+ emscripten::function("tilemap_rotateTile", &esengine::tilemap_rotateTile);
+ emscripten::function("tilemap_setGridType", &esengine::tilemap_setGridType);
+ emscripten::function("tilemap_setHexParams", &esengine::tilemap_setHexParams);
+ emscripten::function("tilemap_tileToWorld", &esengine::tilemap_tileToWorld);
+ emscripten::function("tilemap_worldToTile", &esengine::tilemap_worldToTile);
+#endif
+
emscripten::function("renderer_init", &esengine::renderer_init);
emscripten::function("renderer_resize", &esengine::renderer_resize);
emscripten::function("renderer_beginFrame", &esengine::renderer_beginFrame);
@@ -717,103 +754,20 @@ EMSCRIPTEN_BINDINGS(esengine_ui_systems) {
emscripten::function("uiTree_markAllDirty", &esengine::uiTree_markAllDirty);
emscripten::function("transform_update", &esengine::transform_update);
emscripten::function("transform_patchPosition", &esengine::transform_patchPosition);
-}
-
-// =============================================================================
-// Animation Bindings
-// =============================================================================
-namespace esengine {
-
-u32 anim_createTween(ecs::Registry& registry, u32 entity, u32 targetProp,
- f32 from, f32 to, f32 duration,
- u32 easing, f32 delay,
- u32 loopMode, i32 loopCount) {
- auto* sys = ctx().tryGet<animation::TweenSystem>();
- if (!sys) {
- return INVALID_ENTITY.id();
- }
- auto tweenEntity = sys->createTween(
- registry, Entity::fromRaw(entity),
- static_cast<animation::TweenTarget>(targetProp),
- from, to, duration,
- static_cast<animation::EasingType>(easing));
-
- auto& tween = registry.get<animation::TweenData>(tweenEntity);
- tween.delay = delay;
- tween.loop_mode = static_cast<animation::LoopMode>(loopMode);
- tween.loop_count = loopCount;
- tween.loops_remaining = loopCount;
- return tweenEntity.id();
-}
-
-void anim_cancelTween(ecs::Registry& registry, u32 tweenEntity) {
- if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
- sys->cancelTween(registry, Entity::fromRaw(tweenEntity));
- }
-}
-
-void anim_cancelAllTweens(ecs::Registry& registry, u32 targetEntity) {
- if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
- sys->cancelAllTweens(registry, Entity::fromRaw(targetEntity));
- }
-}
-
-void anim_pauseTween(ecs::Registry& registry, u32 tweenEntity) {
- if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
- sys->pauseTween(registry, Entity::fromRaw(tweenEntity));
- }
+ // Tweens (AnimationBindings.hpp) — the same declarations the native
+ // wrappers are generated from.
+ emscripten::function("anim_createTween", &esengine::anim_createTween);
+ emscripten::function("anim_cancelTween", &esengine::anim_cancelTween);
+ emscripten::function("anim_cancelAllTweens", &esengine::anim_cancelAllTweens);
+ emscripten::function("anim_pauseTween", &esengine::anim_pauseTween);
+ emscripten::function("anim_resumeTween", &esengine::anim_resumeTween);
+ emscripten::function("anim_setTweenBezier", &esengine::anim_setTweenBezier);
+ emscripten::function("anim_setSequenceNext", &esengine::anim_setSequenceNext);
+ emscripten::function("anim_updateTweens", &esengine::anim_updateTweens);
+ emscripten::function("anim_getTweenState", &esengine::anim_getTweenState);
}
-void anim_resumeTween(ecs::Registry& registry, u32 tweenEntity) {
- if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
- sys->resumeTween(registry, Entity::fromRaw(tweenEntity));
- }
-}
-
-void anim_setTweenBezier(ecs::Registry& registry, u32 tweenEntity,
- f32 p1x, f32 p1y, f32 p2x, f32 p2y) {
- if (auto* tween = registry.tryGet<animation::TweenData>(Entity::fromRaw(tweenEntity))) {
- tween->easing = animation::EasingType::CubicBezier;
- tween->bezier_p1x = p1x;
- tween->bezier_p1y = p1y;
- tween->bezier_p2x = p2x;
- tween->bezier_p2y = p2y;
- }
-}
-
-void anim_setSequenceNext(ecs::Registry& registry, u32 tweenEntity, u32 nextEntity) {
- if (auto* tween = registry.tryGet<animation::TweenData>(Entity::fromRaw(tweenEntity))) {
- tween->sequence_next = Entity::fromRaw(nextEntity);
- }
-}
-
-void anim_updateTweens(ecs::Registry& registry, f32 deltaTime) {
- if (auto* sys = ctx().tryGet<animation::TweenSystem>()) {
- sys->update(registry, deltaTime);
- }
-}
-
-i32 anim_getTweenState(ecs::Registry& registry, u32 tweenEntity) {
- if (auto* tween = registry.tryGet<animation::TweenData>(Entity::fromRaw(tweenEntity))) {
- return static_cast<i32>(tween->state);
- }
- return static_cast<i32>(animation::TweenState::Completed);
-}
-
-} // namespace esengine
-
-EMSCRIPTEN_BINDINGS(esengine_animation) {
- emscripten::function("_anim_createTween", &esengine::anim_createTween);
- emscripten::function("_anim_cancelTween", &esengine::anim_cancelTween);
- emscripten::function("_anim_cancelAllTweens", &esengine::anim_cancelAllTweens);
- emscripten::function("_anim_pauseTween", &esengine::anim_pauseTween);
- emscripten::function("_anim_resumeTween", &esengine::anim_resumeTween);
- emscripten::function("_anim_setTweenBezier", &esengine::anim_setTweenBezier);
- emscripten::function("_anim_setSequenceNext", &esengine::anim_setSequenceNext);
- emscripten::function("_anim_updateTweens", &esengine::anim_updateTweens);
- emscripten::function("_anim_getTweenState", &esengine::anim_getTweenState);
-}
int main() {
return 0;