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.

fix(ecs): the native registry answers every entity op the web one does, from one generated table

yhha36098ed3885
diff --git a/native/host/bindings/EcsBindings.cpp b/native/host/bindings/EcsBindings.cpp
index 53979a417..3d1969de4 100644
--- a/native/host/bindings/EcsBindings.cpp
+++ b/native/host/bindings/EcsBindings.cpp
@@ -2,15 +2,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file EcsBindings.cpp
- * @brief Entity + hierarchy — the base Registry surface the SDK's World drives.
+ * @brief Hierarchy reads and the transform composition — the entity-level
+ * entry points that are not Registry methods on the web.
* @details Entity ids cross as the native Entity's raw u32 (round-tripped via
* Entity::fromRaw), so a hierarchy query returns ids the SDK recognises.
*
- * Hand-written because there is nothing to generate from: the web build
- * reaches the registry as an embind CLASS, not as free binding entry
- * points, so no binding header declares this surface. Everything
- * per-component — es_set_<C>, es_<C>_buffer, _has, _remove — IS generated,
- * from the same reflection the web's embind bindings come from.
+ * The Registry's own entity ops (create, destroy, valid, activity,
+ * destruction ownership, setParent) are NOT here: they are generated as
+ * es_registry_<op> from tools/eht/registry_ops.py, the table the embind
+ * Registry is generated from, so the two hosts cannot bind different
+ * sets. What stays is what embind answers through the Parent/Children
+ * components or module free functions, which have no native surface.
*
* @author ESEngine Team
* @date 2026
@@ -31,9 +33,6 @@ using namespace esengine;
namespace eshost {
namespace {
-esjs::Val js_createEntity(const esjs::Args& a) {
- return esjs::uint32(host().registry->create().id());
-}
/**
* Every pool's version in one number — `Registry::layoutEpoch`, which the web
* build reaches as an embind free function. A holder of raw addresses asks this
@@ -43,38 +42,6 @@ esjs::Val js_createEntity(const esjs::Args& a) {
esjs::Val js_layoutEpoch(const esjs::Args& a) {
return esjs::number(host().registry->layoutEpoch());
}
-esjs::Val js_destroyEntity(const esjs::Args& a) {
- host().registry->destroy(esn_entity(a[0]));
- return esjs::undefined();
-}
-esjs::Val js_setParent(const esjs::Args& a) {
- return esjs::boolean(ecs::setParent(*host().registry, esn_entity(a[0]), esn_entity(a[1])));
-}
-esjs::Val js_reserveDestruction(const esjs::Args& a) {
- return esjs::boolean(host().registry->reserveDestruction(esn_entity(a[0])));
-}
-esjs::Val js_releaseDestruction(const esjs::Args& a) {
- host().registry->releaseDestruction(esn_entity(a[0]));
- return esjs::undefined();
-}
-esjs::Val js_destructionPending(const esjs::Args& a) {
- return esjs::boolean(host().registry->destructionPending(esn_entity(a[0])));
-}
-esjs::Val js_setEntityEnabled(const esjs::Args& a) {
- return esjs::boolean(host().registry->setEntityEnabled(esn_entity(a[0]), esjs::toBool(a[1])));
-}
-esjs::Val js_isEntityActive(const esjs::Args& a) {
- return esjs::boolean(host().registry->isEntityActive(esn_entity(a[0])));
-}
-esjs::Val js_isEntityEnabled(const esjs::Args& a) {
- return esjs::boolean(host().registry->isEntityEnabled(esn_entity(a[0])));
-}
-esjs::Val js_hasInactiveEntities(const esjs::Args& a) {
- return esjs::boolean(host().registry->hasInactiveEntities());
-}
-esjs::Val js_activityEpoch(const esjs::Args& a) {
- return esjs::uint32(host().registry->activityEpoch());
-}
esjs::Val js_hasParent(const esjs::Args& a) {
return esjs::boolean(host().registry->has<ecs::Parent>(esn_entity(a[0])));
}
@@ -186,17 +153,6 @@ esjs::Val js_transformEnsureComposed(const esjs::Args& a) {
} // namespace
void registerEcsBindings(HostState& h, esjs::Val global) {
- bindGlobal(global, "es_createEntity", js_createEntity, 0);
- bindGlobal(global, "es_destroyEntity", js_destroyEntity, 1);
- bindGlobal(global, "es_setParent", js_setParent, 2);
- bindGlobal(global, "es_reserveDestruction", js_reserveDestruction, 1);
- bindGlobal(global, "es_releaseDestruction", js_releaseDestruction, 1);
- bindGlobal(global, "es_destructionPending", js_destructionPending, 1);
- bindGlobal(global, "es_setEntityEnabled", js_setEntityEnabled, 2);
- bindGlobal(global, "es_isEntityActive", js_isEntityActive, 1);
- bindGlobal(global, "es_isEntityEnabled", js_isEntityEnabled, 1);
- bindGlobal(global, "es_hasInactiveEntities", js_hasInactiveEntities, 0);
- bindGlobal(global, "es_activityEpoch", js_activityEpoch, 0);
bindGlobal(global, "es_hasParent", js_hasParent, 1);
bindGlobal(global, "es_getParent", js_getParent, 1);
bindGlobal(global, "es_removeParent", js_removeParent, 1);
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 079a0e890..864bfa7e9 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -13,7 +13,7 @@ shutdown: () => void
## CppRegistry — interface @experimental
```
-activityEpoch: (() => number) | undefined
+activityEpoch: () => number
addBillboard: (entity: Entity, component: Billboard) => void
addBitmapText: (entity: Entity, component: BitmapText) => void
addBoxCollider2D: (entity: Entity, component: BoxCollider2D) => void
@@ -74,7 +74,7 @@ componentTypeId: ((name: string) => number) | undefined
create: () => Entity
delete: () => void
destroy: (entity: Entity) => void
-destructionPending: ((entity: Entity) => boolean) | undefined
+destructionPending: (entity: Entity) => boolean
entityCount: () => number
getBillboard: (entity: Entity) => Billboard
getBitmapText: (entity: Entity) => BitmapText
@@ -151,7 +151,7 @@ hasDragonBonesAnimation: (entity: Entity) => boolean
hasFlexContainer: (entity: Entity) => boolean
hasGroupOpacity: (entity: Entity) => boolean
hasImpostor: (entity: Entity) => boolean
-hasInactiveEntities: (() => boolean) | undefined
+hasInactiveEntities: () => boolean
hasInteractable: (entity: Entity) => boolean
hasLODGroup: (entity: Entity) => boolean
hasLight: (entity: Entity) => boolean
@@ -190,10 +190,10 @@ hasUINode: (entity: Entity) => boolean
hasUIScroll: (entity: Entity) => boolean
hasUIVisual: (entity: Entity) => boolean
hasVelocity: (entity: Entity) => boolean
-isEntityActive: ((entity: Entity) => boolean) | undefined
-isEntityEnabled: ((entity: Entity) => boolean) | undefined
+isEntityActive: (entity: Entity) => boolean
+isEntityEnabled: (entity: Entity) => boolean
layoutEpoch: (() => number) | undefined
-releaseDestruction: ((entity: Entity) => void) | undefined
+releaseDestruction: (entity: Entity) => void
removeBillboard: (entity: Entity) => void
removeBitmapText: (entity: Entity) => void
removeBoxCollider2D: (entity: Entity) => void
@@ -250,9 +250,9 @@ removeUINode: (entity: Entity) => void
removeUIScroll: (entity: Entity) => void
removeUIVisual: (entity: Entity) => void
removeVelocity: (entity: Entity) => void
-reserveDestruction: ((entity: Entity) => boolean) | undefined
-setEntityEnabled: ((entity: Entity, enabled: boolean) => boolean) | undefined
-setParent: (child: Entity, parent: Entity) => boolean | void
+reserveDestruction: (entity: Entity) => boolean
+setEntityEnabled: (entity: Entity, enabled: boolean) => boolean
+setParent: (child: Entity, parent: Entity) => boolean
valid: (entity: Entity) => boolean
```
diff --git a/sdk/src/ecs/bridge/nativeBindings.ts b/sdk/src/ecs/bridge/nativeBindings.ts
index 527102bf0..9c1aad04b 100644
--- a/sdk/src/ecs/bridge/nativeBindings.ts
+++ b/sdk/src/ecs/bridge/nativeBindings.ts
@@ -23,11 +23,20 @@
* those, are hand-written in `native/host/bindings/`.
*/
-/** Entity + hierarchy — the base Registry surface the SDK's World drives. */
+import { REGISTRY_OPS } from './registryOps.generated';
+
+export { REGISTRY_OPS, type RegistryOp } from './registryOps.generated';
+
+/**
+ * The hierarchy reads and the other entity-level entry points that are not
+ * Registry methods on the web. The Registry's own entity ops (create, destroy,
+ * valid, activity, destruction ownership, setParent) are {@link REGISTRY_OPS},
+ * generated from the one table embind is generated from, so a host cannot bind
+ * fewer of them than the web has.
+ */
export const REGISTRY_BINDINGS = {
- createEntity: 'es_createEntity',
- destroyEntity: 'es_destroyEntity',
- setParent: 'es_setParent',
+ // Embind answers these through the Parent/Children component methods; a
+ // native host has no such component surface, so they are entity ops here.
hasParent: 'es_hasParent',
getParent: 'es_getParent',
removeParent: 'es_removeParent',
@@ -47,22 +56,6 @@ export const REGISTRY_BINDINGS = {
ensureComposed: 'es_transformEnsureComposed',
} as const;
-/** Optional shared destruction ownership for current native hosts. */
-export const DESTRUCTION_BINDINGS = {
- reserveDestruction: 'es_reserveDestruction',
- releaseDestruction: 'es_releaseDestruction',
- destructionPending: 'es_destructionPending',
-} as const;
-
-/** Effective entity activity, available on hosts implementing the shared core. */
-export const ACTIVITY_BINDINGS = {
- setEntityEnabled: 'es_setEntityEnabled',
- isEntityActive: 'es_isEntityActive',
- isEntityEnabled: 'es_isEntityEnabled',
- hasInactiveEntities: 'es_hasInactiveEntities',
- activityEpoch: 'es_activityEpoch',
-} as const;
-
/**
* The composition's change REPORT, which not every host has to answer: a core
* that does not leaves consumers rebuilding rather than updating, so these are
@@ -300,6 +293,7 @@ export function assertNativeBindings(
scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
): void {
const missing = [
+ ...Object.values(REGISTRY_OPS),
...Object.values(REGISTRY_BINDINGS),
...Object.values(RESOURCE_BINDINGS),
...Object.values(PLATFORM_BINDINGS),
diff --git a/sdk/src/ecs/bridge/nativeRegistry.ts b/sdk/src/ecs/bridge/nativeRegistry.ts
index 583ddc8d0..489e605e9 100644
--- a/sdk/src/ecs/bridge/nativeRegistry.ts
+++ b/sdk/src/ecs/bridge/nativeRegistry.ts
@@ -17,7 +17,7 @@
import type { CppRegistry } from '../../wasm';
import type { Entity } from '../../types';
import { PTR_ACCESSORS } from './ptrAccessors.generated';
-import { REGISTRY_BINDINGS, SCENE_QUERY_BINDINGS, ACTIVITY_BINDINGS, DESTRUCTION_BINDINGS, INSPECTION_BINDINGS } from './nativeBindings';
+import { REGISTRY_BINDINGS, REGISTRY_OPS, SCENE_QUERY_BINDINGS, INSPECTION_BINDINGS } from './nativeBindings';
import { COMPONENT_META } from '../component.generated';
import { convertForWasm, convertFromWasm } from './BuiltinBridge';
@@ -78,7 +78,7 @@ function vectorEntity(
/**
* Build the full CppRegistry over the host's native bindings — entity lifecycle +
- * hierarchy (es_createEntity / es_destroyEntity / es_setParent / …) plus, per
+ * hierarchy (the generated REGISTRY_OPS, es_getChildren / …) plus, per
* component, the generated es_<Component>_buffer / _has / _remove. `scope` holds
* those globals (the QuickJS global object on a device; a plain object in tests).
* Only components whose three bindings are present get component methods, so a host
@@ -91,28 +91,21 @@ export function createNativeRegistry(
for (const [method, binding] of Object.entries(INSPECTION_BINDINGS)) {
if (typeof scope[binding] === 'function') reg[method] = (...args: unknown[]) => hostCall(scope, binding, args);
}
- for (const [method, binding] of Object.entries(ACTIVITY_BINDINGS)) {
- if (typeof scope[binding] === 'function') reg[method] = (...args: unknown[]) => hostCall(scope, binding, args);
- }
- if (Object.values(DESTRUCTION_BINDINGS).every(binding => typeof scope[binding] === 'function')) {
- for (const [method, binding] of Object.entries(DESTRUCTION_BINDINGS)) {
- reg[method] = (entity: Entity) => hostCall(scope, binding, [entity]);
- }
+ // The Registry's entity ops, every one the web has: the list is generated
+ // from the table embind is generated from, and `assertNativeBindings`
+ // requires each at boot, so a missing op is a boot error rather than a
+ // TypeError in whichever system first calls it (#114 was `valid`).
+ for (const [method, binding] of Object.entries(REGISTRY_OPS)) {
+ reg[method] = (...args: unknown[]) => hostCall(scope, binding, args);
}
- // Entity lifecycle + hierarchy — the base Registry surface World drives (spawn,
- // despawn, parent/child). These are not per-component; the host binds them by
- // hand (the native siblings of the embind Registry's entity ops).
- reg.create = (): Entity => hostCall(scope, REGISTRY_BINDINGS.createEntity, []) as Entity;
- reg.destroy = (e: Entity): void => { hostCall(scope, REGISTRY_BINDINGS.destroyEntity, [e]); };
+ // Entity hierarchy reads and the module-level epochs — the native siblings of
+ // what embind answers through the Parent/Children components and free functions.
// Required like the rest of the set, and `assertNativeBindings` says so at
// boot: a host that cannot date its world makes every holder of an address
// re-resolve it every frame, silently.
reg.layoutEpoch = (): number => hostCall(scope, REGISTRY_BINDINGS.layoutEpoch, []) as number;
reg.hasParent = (e: Entity): boolean => !!hostCall(scope, REGISTRY_BINDINGS.hasParent, [e]);
- reg.setParent = (child: Entity, parent: Entity): boolean | void => {
- return hostCall(scope, REGISTRY_BINDINGS.setParent, [child, parent]) as boolean | void;
- };
reg.removeParent = (e: Entity): void => { hostCall(scope, REGISTRY_BINDINGS.removeParent, [e]); };
reg.hasChildren = (e: Entity): boolean => !!hostCall(scope, REGISTRY_BINDINGS.hasChildren, [e]);
reg.getChildren = (e: Entity) => ({
@@ -128,14 +121,14 @@ export function createNativeRegistry(
entity: (hostCall(scope, REGISTRY_BINDINGS.getParent, [e]) as Entity),
});
reg.addParent = (child: Entity, data: { entity: Entity }): void => {
- hostCall(scope, REGISTRY_BINDINGS.setParent, [child, data.entity]);
+ hostCall(scope, REGISTRY_OPS.setParent, [child, data.entity]);
};
// Children is the reverse index of Parent; write it by re-parenting each listed
// child. Rarely called (scenes rebuild the tree with setParent), but a complete
// surface keeps the two registries interchangeable.
reg.addChildren = (parent: Entity, data: { entities: Iterable<Entity> }): void => {
for (const child of data.entities ?? []) {
- hostCall(scope, REGISTRY_BINDINGS.setParent, [child, parent]);
+ hostCall(scope, REGISTRY_OPS.setParent, [child, parent]);
}
};
reg.removeChildren = (parent: Entity): void => {
diff --git a/sdk/src/ecs/bridge/registryOps.generated.ts b/sdk/src/ecs/bridge/registryOps.generated.ts
new file mode 100644
index 000000000..7dfe1ac51
--- /dev/null
+++ b/sdk/src/ecs/bridge/registryOps.generated.ts
@@ -0,0 +1,25 @@
+/**
+ * @file registryOps.generated.ts
+ * @brief The Registry entity ops and their native host globals.
+ * @details Generated by EHT from tools/eht/registry_ops.py - DO NOT EDIT
+ */
+
+import type { Registry } from '../../wasm/wasm.generated';
+
+export const REGISTRY_OPS = {
+ create: 'es_registry_create',
+ destroy: 'es_registry_destroy',
+ valid: 'es_registry_valid',
+ entityCount: 'es_registry_entityCount',
+ reserveDestruction: 'es_registry_reserveDestruction',
+ releaseDestruction: 'es_registry_releaseDestruction',
+ destructionPending: 'es_registry_destructionPending',
+ setEntityEnabled: 'es_registry_setEntityEnabled',
+ isEntityActive: 'es_registry_isEntityActive',
+ isEntityEnabled: 'es_registry_isEntityEnabled',
+ hasInactiveEntities: 'es_registry_hasInactiveEntities',
+ activityEpoch: 'es_registry_activityEpoch',
+ setParent: 'es_registry_setParent',
+} as const satisfies { readonly [K in keyof Registry]?: string };
+
+export type RegistryOp = keyof typeof REGISTRY_OPS;
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index ba57f0651..638274646 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -401,14 +401,14 @@ export class World {
// Detach before taking native ownership: setParent also rejects
// reserved entities. The same core guard then protects raw registry
// calls and native teardown invoked from an SDK callback.
- if (cppRegistry?.reserveDestruction && cppRegistry.releaseDestruction) {
+ if (cppRegistry) {
for (const current of owned) {
if (cppRegistry.reserveDestruction(current)) nativeOwned.push(current);
}
}
for (const current of postorder) if (this.valid(current)) this.despawnOne_(current, cppRegistry);
} finally {
- for (const current of nativeOwned) cppRegistry!.releaseDestruction!(current);
+ for (const current of nativeOwned) cppRegistry!.releaseDestruction(current);
for (const current of owned) reserved.delete(current);
if (reserved.size === 0) this.despawning_ = null;
}
diff --git a/sdk/src/index.native.ts b/sdk/src/index.native.ts
index fbfb3ad4b..d9554ba77 100644
--- a/sdk/src/index.native.ts
+++ b/sdk/src/index.native.ts
@@ -61,7 +61,7 @@ export type { MemoryProvider, ComponentHeap, NativeComponentBufferFn } from './e
export { createNativeRegistry } from './ecs/bridge/nativeRegistry';
// The es_* names a host binds, declared once and checked at boot.
-export { REGISTRY_BINDINGS, RESOURCE_BINDINGS, PLATFORM_BINDINGS, assertNativeBindings } from './ecs/bridge/nativeBindings';
+export { REGISTRY_BINDINGS, REGISTRY_OPS, RESOURCE_BINDINGS, PLATFORM_BINDINGS, assertNativeBindings } from './ecs/bridge/nativeBindings';
// The native ResourceManager — the embind-ResourceManager sibling the SDK's asset
// pipeline drives (createTexture / releaseTexture / dims). Built over the host's
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 660aee613..0cb2485ff 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -35,10 +35,6 @@ export interface CppRegistry extends GeneratedRegistry {
* registry itself. The web module answers the same question as a free
* function; absent on a core built before either existed. */
layoutEpoch?(): number;
- /** Shared subtree teardown ownership; optional for older hosts. */
- reserveDestruction?(entity: Entity): boolean;
- releaseDestruction?(entity: Entity): void;
- destructionPending?(entity: Entity): boolean;
[key: string]: Function | undefined;
}
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index c069e950d..bf81ca591 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -1134,10 +1134,32 @@ export interface Velocity {
// Registry
export interface Registry {
+ /** A new entity. */
create(): Entity;
+ /** Destroys the entity and its components. */
destroy(entity: Entity): void;
+ /** Whether the id names a live entity. */
valid(entity: Entity): boolean;
+ /** Live entities. */
entityCount(): number;
+ /** Claims the subtree teardown; false when another owner already has it. */
+ reserveDestruction(entity: Entity): boolean;
+ /** Gives back a claim from reserveDestruction. */
+ releaseDestruction(entity: Entity): void;
+ /** Whether a teardown has claimed the entity. */
+ destructionPending(entity: Entity): boolean;
+ /** Sets the entity's own enabled flag; activity follows the hierarchy. */
+ setEntityEnabled(entity: Entity, enabled: boolean): boolean;
+ /** Enabled itself and under enabled ancestors. */
+ isEntityActive(entity: Entity): boolean;
+ /** The entity's own flag, ignoring ancestors. */
+ isEntityEnabled(entity: Entity): boolean;
+ /** Whether any entity is inactive (lets a query skip the activity check). */
+ hasInactiveEntities(): boolean;
+ /** Bumped by every activity change. */
+ activityEpoch(): number;
+ /** Re-parents child; false when refused (a cycle, an invalid entity). */
+ setParent(child: Entity, parent: Entity): boolean;
/** All generated builtin names, separated by |; absent on older cores. */
getBuiltinComponentNames?(entity: Entity): string;
/** Host-local component ID; -1 for an unknown name. */
@@ -1367,14 +1389,6 @@ export interface Registry {
getVelocity(entity: Entity): Velocity;
addVelocity(entity: Entity, component: Velocity): void;
removeVelocity(entity: Entity): void;
-
- // Hierarchy Utilities
- setEntityEnabled?(entity: Entity, enabled: boolean): boolean;
- isEntityActive?(entity: Entity): boolean;
- isEntityEnabled?(entity: Entity): boolean;
- hasInactiveEntities?(): boolean;
- activityEpoch?(): number;
- setParent(child: Entity, parent: Entity): boolean | void;
}
// Module
diff --git a/sdk/tests/helpers/fakeEngine.ts b/sdk/tests/helpers/fakeEngine.ts
index 32fa4d8f4..85b9dd5a7 100644
--- a/sdk/tests/helpers/fakeEngine.ts
+++ b/sdk/tests/helpers/fakeEngine.ts
@@ -42,7 +42,17 @@ export function connectFakeCpp(world: World): void {
}
// AFTER the generic pass: Parent and Children are not rows, they are two
// halves of one link, and the accessors named for them answer from it.
+ // Teardown ownership as Registry::reserveDestruction keeps it: one owner at a
+ // time. Every core binds it, so World takes it without asking.
+ const pendingTeardown = new Set<number>();
Object.assign(registry, {
+ reserveDestruction: (e: number) => {
+ if (pendingTeardown.has(e)) return false;
+ pendingTeardown.add(e);
+ return true;
+ },
+ releaseDestruction: (e: number) => { pendingTeardown.delete(e); },
+ destructionPending: (e: number) => pendingTeardown.has(e),
create: () => nextEntity++,
destroy: (e: number) => {
unlink(e);
diff --git a/sdk/tests/helpers/nativeRegistryOps.ts b/sdk/tests/helpers/nativeRegistryOps.ts
new file mode 100644
index 000000000..abfaf2bd5
--- /dev/null
+++ b/sdk/tests/helpers/nativeRegistryOps.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The REGISTRY_OPS a mock native host leaves to defaults. Every op is required
+ * (a real host binds all of them, generated), so a mock that only cares about
+ * spawning still answers valid/activity/destruction like a host with nothing
+ * disabled and no teardown in flight. Ops the mock already binds are kept.
+ */
+import { REGISTRY_OPS } from '../../src/ecs/bridge/nativeBindings';
+
+export function installRegistryOpDefaults(scope: Record<string, unknown>, alive?: ReadonlySet<number>): void {
+ const pending = new Set<number>();
+ const enabled = new Map<number, boolean>();
+ let epoch = 0;
+ const defaults: Record<keyof typeof REGISTRY_OPS, (...args: never[]) => unknown> = {
+ create: () => { throw new Error('mock host: bind es_registry_create'); },
+ destroy: () => undefined,
+ valid: (e: number) => alive ? alive.has(e) : e > 0,
+ entityCount: () => alive?.size ?? 0,
+ reserveDestruction: (e: number) => { if (pending.has(e)) return false; pending.add(e); return true; },
+ releaseDestruction: (e: number) => { pending.delete(e); },
+ destructionPending: (e: number) => pending.has(e),
+ setEntityEnabled: (e: number, value: boolean) => { enabled.set(e, value); ++epoch; return true; },
+ isEntityActive: (e: number) => enabled.get(e) ?? true,
+ isEntityEnabled: (e: number) => enabled.get(e) ?? true,
+ hasInactiveEntities: () => [...enabled.values()].some((v) => !v),
+ activityEpoch: () => epoch,
+ setParent: () => true,
+ };
+ for (const [op, binding] of Object.entries(REGISTRY_OPS) as [keyof typeof REGISTRY_OPS, string][]) {
+ if (typeof scope[binding] !== 'function') scope[binding] = defaults[op];
+ }
+}
+
+/** `scope` with the op defaults installed, for a call site that builds it inline. */
+export function withRegistryOps<T extends Record<string, unknown>>(scope: T): T {
+ installRegistryOpDefaults(scope);
+ return scope;
+}
+
+/** A host scope that binds only the registry ops — for tests of a native app
+ * whose subject (input, say) needs no other host surface. */
+export function hostWithRegistryOps(): Record<string, unknown> {
+ return withRegistryOps({});
+}
diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.ts
index cb9259bd4..54bb24b79 100644
--- a/sdk/tests/mocks/wasm.ts
+++ b/sdk/tests/mocks/wasm.ts
@@ -18,6 +18,7 @@ export interface MockModule extends ESEngineModule {
export function createMockModule(): MockModule {
const entities = new Set<Entity>();
const components = new Map<Entity, Map<string, any>>();
+ const destructionPending = new Set<Entity>();
let nextEntity = 1;
const baseRegistry = {
@@ -39,6 +40,17 @@ export function createMockModule(): MockModule {
entityCount: () => entities.size,
+ // Shared subtree teardown ownership, as Registry::reserveDestruction has
+ // it: one owner at a time, and only over a live entity. Every core binds
+ // these, so World takes ownership without asking whether it may.
+ reserveDestruction: (entity: Entity) => {
+ if (!entities.has(entity) || destructionPending.has(entity)) return false;
+ destructionPending.add(entity);
+ return true;
+ },
+ releaseDestruction: (entity: Entity) => { destructionPending.delete(entity); },
+ destructionPending: (entity: Entity) => destructionPending.has(entity),
+
/**
* Every engine pool's version. A constant, and the TRUTH rather than a
* stub: this registry keeps components in JS maps, so nothing here has
diff --git a/sdk/tests/native-app-input.test.ts b/sdk/tests/native-app-input.test.ts
index c8ef4a680..3e662ba71 100644
--- a/sdk/tests/native-app-input.test.ts
+++ b/sdk/tests/native-app-input.test.ts
@@ -11,6 +11,7 @@ import { describe, expect, it } from 'vitest';
import { createNativeApp } from '../src/ecs/bridge/nativeRuntime';
import { Input } from '../src/input/input';
import type { NativeBridge, NativeInputListener } from '../src/platform/native/bridge';
+import { hostWithRegistryOps } from './helpers/nativeRegistryOps';
/** A NativeBridge whose registerInput captures the engine's listener; everything
* else is a stub (input needs none of it). */
@@ -34,7 +35,7 @@ function makeBridge() {
describe('createNativeApp', () => {
it('routes host touch through the real input plugin to the Input resource', async () => {
const { bridge, listener } = makeBridge();
- const app = createNativeApp(bridge, {});
+ const app = createNativeApp(bridge, hostWithRegistryOps());
// First tick finishes plugin builds: inputPlugin.build calls
// getPlatform().bindInputEvents, which registers with the host bridge.
@@ -56,7 +57,7 @@ describe('createNativeApp', () => {
it('gives the game the real World over the native core', async () => {
const { bridge } = makeBridge();
- const app = createNativeApp(bridge, {});
+ const app = createNativeApp(bridge, hostWithRegistryOps());
await app.tick(0);
expect(app.world).toBeDefined();
expect(app.world.hasCpp).toBe(true); // connected to the native registry
diff --git a/sdk/tests/native-assets.test.ts b/sdk/tests/native-assets.test.ts
index 46f5ad316..6c0fd6d6a 100644
--- a/sdk/tests/native-assets.test.ts
+++ b/sdk/tests/native-assets.test.ts
@@ -20,6 +20,7 @@ import { shutdownResourceManager } from '../src/wasm/resourceManager';
import { TextureContent } from '../src/wasm';
import { setPlatform } from '../src/platform/base';
import type { NativeBridge } from '../src/platform/native/bridge';
+import { withRegistryOps } from './helpers/nativeRegistryOps';
/** A mock native ResourceManager scope: a Map-backed texture pool addressed by
* handle, exposed through the es_* host globals the SDK's native RM binds to. */
@@ -131,7 +132,7 @@ describe('native Assets.loadTexture', () => {
it('decodes through the bridge and uploads via the native ResourceManager', async () => {
const { scope, createSpy, releaseSpy } = makeTextureScope();
const bridge = makeBridge({ 'logo.png': solidImage(4, 2) });
- const app = createNativeApp(bridge, scope);
+ const app = createNativeApp(bridge, withRegistryOps(scope));
await app.tick(0); // finish plugin builds + install platform
const assets = app.getResource(Assets);
@@ -196,7 +197,7 @@ describe('native Assets mesh loading', () => {
mesh_createFromChannels: scope.es_mesh_createFromChannels as never,
});
try {
- const app = createNativeApp(makeBridge({}), scope);
+ const app = createNativeApp(makeBridge({}), withRegistryOps(scope));
await app.tick(0);
const assets = app.getResource(Assets);
diff --git a/sdk/tests/native-audio.test.ts b/sdk/tests/native-audio.test.ts
index ae31dc60a..fe1ac9d43 100644
--- a/sdk/tests/native-audio.test.ts
+++ b/sdk/tests/native-audio.test.ts
@@ -13,7 +13,7 @@ import type { NativeBridge } from '../src/platform/native';
import { NativeAudioBackend } from '../src/audio/NativeAudioBackend';
import {
AUDIO_BINDINGS, hasAudioBindings,
- REGISTRY_BINDINGS, RESOURCE_BINDINGS, PLATFORM_BINDINGS,
+ REGISTRY_BINDINGS, REGISTRY_OPS, RESOURCE_BINDINGS, PLATFORM_BINDINGS,
} from '../src/ecs/bridge/nativeBindings';
function hostGlobals(): Record<string, unknown> {
@@ -302,6 +302,7 @@ describe('assertNativeHost — audio stays optional', () => {
it('passes on a host with no audio engine', () => {
const scope = hostGlobals();
for (const name of [
+ ...Object.values(REGISTRY_OPS),
...Object.values(REGISTRY_BINDINGS),
...Object.values(RESOURCE_BINDINGS),
...Object.values(PLATFORM_BINDINGS),
diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.ts
index 2c476d455..271b29404 100644
--- a/sdk/tests/native-host-bridge.test.ts
+++ b/sdk/tests/native-host-bridge.test.ts
@@ -9,7 +9,7 @@
import { describe, it, expect, vi } from 'vitest';
import { createHostBridge, assertHostEnvironment, assertNativeHost, NativePlatformAdapter } from '../src/platform/native';
import { cacheEntryName } from '../src/platform/cacheEntryName';
-import { REGISTRY_BINDINGS, RESOURCE_BINDINGS, PLATFORM_BINDINGS } from '../src/ecs/bridge/nativeBindings';
+import { REGISTRY_BINDINGS, REGISTRY_OPS, RESOURCE_BINDINGS, PLATFORM_BINDINGS } from '../src/ecs/bridge/nativeBindings';
/** The globals a real host installs (console, timers, clock, decoder). */
function hostGlobals(): Record<string, unknown> {
@@ -261,6 +261,7 @@ describe('assertNativeHost', () => {
function fullHost(): Record<string, unknown> {
const scope = hostGlobals();
for (const name of [
+ ...Object.values(REGISTRY_OPS),
...Object.values(REGISTRY_BINDINGS),
...Object.values(RESOURCE_BINDINGS),
...Object.values(PLATFORM_BINDINGS),
@@ -274,9 +275,9 @@ describe('assertNativeHost', () => {
it('lists every missing binding at once, not just the first', () => {
const scope = fullHost();
- delete scope[REGISTRY_BINDINGS.setParent];
+ delete scope[REGISTRY_OPS.setParent];
delete scope[RESOURCE_BINDINGS.createTexture];
- expect(() => assertNativeHost(scope)).toThrow(/es_setParent/);
+ expect(() => assertNativeHost(scope)).toThrow(/es_registry_setParent/);
expect(() => assertNativeHost(scope)).toThrow(new RegExp(RESOURCE_BINDINGS.createTexture));
});
diff --git a/sdk/tests/native-registry.test.ts b/sdk/tests/native-registry.test.ts
index 40c21833b..1fe65ee3a 100644
--- a/sdk/tests/native-registry.test.ts
+++ b/sdk/tests/native-registry.test.ts
@@ -14,6 +14,10 @@ import { createNativeRegistry } from '../src/ecs/bridge/nativeRegistry';
import { NativeMemoryProvider } from '../src/ecs/bridge/memoryProvider';
import { PTR_ACCESSORS } from '../src/ecs/bridge/ptrAccessors.generated';
import { Sprite } from '../src/ecs/component';
+import { COMPONENT_META } from '../src/ecs/component.generated';
+import { INSPECTION_BINDINGS, REGISTRY_BINDINGS, REGISTRY_OPS } from '../src/ecs/bridge/nativeBindings';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
/**
* A fake native host: each component's storage is an entity->ArrayBuffer map, with
@@ -103,39 +107,66 @@ describe('createNativeRegistry', () => {
expect(reg.getShadowCaster2D(1)).toEqual({ size: { x: 32, y: 48 }, enabled: false,
path: [{ x: 1, y: 2 }, { x: 3, y: 4 }] });
});
- it('forwards shared destruction ownership only when the complete host contract exists', () => {
+ it('forwards shared destruction ownership to the host', () => {
const pending = new Set<number>();
const reg = createNativeRegistry({
- es_reserveDestruction: (e: number) => { if (pending.has(e)) return false; pending.add(e); return true; },
- es_releaseDestruction: (e: number) => { pending.delete(e); },
- es_destructionPending: (e: number) => pending.has(e),
+ es_registry_reserveDestruction: (e: number) => { if (pending.has(e)) return false; pending.add(e); return true; },
+ es_registry_releaseDestruction: (e: number) => { pending.delete(e); },
+ es_registry_destructionPending: (e: number) => pending.has(e),
});
- expect(reg.reserveDestruction!(1 as never)).toBe(true);
- expect(reg.reserveDestruction!(1 as never)).toBe(false);
- expect(reg.destructionPending!(1 as never)).toBe(true);
- reg.releaseDestruction!(1 as never);
- expect(reg.destructionPending!(1 as never)).toBe(false);
- expect(createNativeRegistry({}).reserveDestruction).toBeUndefined();
- expect(createNativeRegistry({ es_reserveDestruction: () => true }).reserveDestruction).toBeUndefined();
+ expect(reg.reserveDestruction(1 as never)).toBe(true);
+ expect(reg.reserveDestruction(1 as never)).toBe(false);
+ expect(reg.destructionPending(1 as never)).toBe(true);
+ reg.releaseDestruction(1 as never);
+ expect(reg.destructionPending(1 as never)).toBe(false);
});
- it('forwards the optional shared activity contract and preserves legacy hosts', () => {
+ it('forwards entity activity to the host', () => {
let enabled = true;
const reg = createNativeRegistry({
- es_setEntityEnabled: (_e: number, value: boolean) => { enabled = value; return true; },
- es_isEntityEnabled: () => enabled,
- es_isEntityActive: () => enabled,
- es_hasInactiveEntities: () => !enabled,
- es_activityEpoch: () => 7,
+ es_registry_setEntityEnabled: (_e: number, value: boolean) => { enabled = value; return true; },
+ es_registry_isEntityEnabled: () => enabled,
+ es_registry_isEntityActive: () => enabled,
+ es_registry_hasInactiveEntities: () => !enabled,
+ es_registry_activityEpoch: () => 7,
});
- expect(reg.setEntityEnabled!(1 as never, false)).toBe(true);
- expect(reg.isEntityEnabled!(1 as never)).toBe(false);
- expect(reg.isEntityActive!(1 as never)).toBe(false);
- expect(reg.hasInactiveEntities!()).toBe(true);
- expect(reg.activityEpoch!()).toBe(7);
- expect(createNativeRegistry({}).isEntityActive).toBeUndefined();
+ expect(reg.setEntityEnabled(1 as never, false)).toBe(true);
+ expect(reg.isEntityEnabled(1 as never)).toBe(false);
+ expect(reg.isEntityActive(1 as never)).toBe(false);
+ expect(reg.hasInactiveEntities()).toBe(true);
+ expect(reg.activityEpoch()).toBe(7);
+ });
+ // #114: `valid` was the one op the native registry lacked, and the mutation
+ // reader's subtree walk called it, so PhysicsStepSystem threw every frame.
+ it('asks the host whether an entity is alive, destroyed ones included', () => {
+ const alive = new Set([42]);
+ const reg = createNativeRegistry({ es_registry_valid: (e: number) => alive.has(e) });
+ expect(reg.valid(42 as never)).toBe(true);
+ expect(reg.valid(43 as never)).toBe(false);
+ alive.delete(42);
+ expect(reg.valid(42 as never)).toBe(false);
+ });
+ it('names the binding when a host left an op unbound', () => {
+ expect(() => createNativeRegistry({}).valid(1 as never)).toThrow(/es_registry_valid/);
+ });
+ // The class of #114, not the instance: every non-component method the web's
+ // embind Registry has, the native registry has too. Read from the generated
+ // bindings, so a method added to embind without a native route fails here.
+ it('has every entity-level method the embind Registry has', () => {
+ const cpp = readFileSync(resolve(__dirname, '../../src/esengine/bindings/WebBindings.generated.cpp'), 'utf8');
+ const block = cpp.slice(cpp.indexOf('EMSCRIPTEN_BINDINGS(esengine_registry)'));
+ const perComponent = new Set(Object.keys(COMPONENT_META).flatMap(
+ (c) => ['has', 'get', 'add', 'remove'].map((verb) => `${verb}${c}`)));
+ const web = [...block.slice(0, block.indexOf('\n}')).matchAll(/\.function\("(\w+)"/g)]
+ .map((m) => m[1]).filter((name) => !perComponent.has(name));
+ expect(web).toContain('valid');
+ const scope: Record<string, unknown> = {};
+ for (const name of [...Object.values(REGISTRY_OPS), ...Object.values(REGISTRY_BINDINGS),
+ ...Object.values(INSPECTION_BINDINGS)]) scope[name] = () => undefined;
+ const reg = createNativeRegistry(scope) as unknown as Record<string, unknown>;
+ expect(web.filter((name) => typeof reg[name] !== 'function')).toEqual([]);
});
it.each([true, false])('forwards native hierarchy acceptance %s', (accepted) => {
- const reg = createNativeRegistry({ es_setParent: () => accepted });
+ const reg = createNativeRegistry({ es_registry_setParent: () => accepted });
expect(reg.setParent(1 as never, 2 as never)).toBe(accepted);
});
it('round-trips a component through add / has / get / remove (embind shape)', () => {
@@ -231,7 +262,7 @@ describe('createNativeRegistry', () => {
const parents = new Map<number, number>();
const children = new Map<number, number[]>();
const scope: Record<string, unknown> = {
- es_setParent: (c: number, p: number) => {
+ es_registry_setParent: (c: number, p: number) => {
parents.set(c, p);
(children.get(p) ?? children.set(p, []).get(p)!).push(c);
},
diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.ts
index b8cfc7e16..195c2a00a 100644
--- a/sdk/tests/native-text.test.ts
+++ b/sdk/tests/native-text.test.ts
@@ -24,6 +24,7 @@ import { SdfTextRenderer } from '../src/ui/text/text-renderer';
import { Text, TextRenderMode } from '../src/ui/core/text';
import { UICameraInfo } from '../src/ui/core/ui-camera-info';
import { PTR_ACCESSORS } from '../src/ecs/bridge/ptrAccessors.generated';
+import { installRegistryOpDefaults } from './helpers/nativeRegistryOps';
import type { PlatformGlyphRequest } from '../src/platform/types';
import type { NativeBridge } from '../src/platform/native/bridge';
@@ -37,13 +38,14 @@ function installMockEcs(scope: Record<string, unknown>): void {
if (!m) { m = new Map(); comps.set(cpp, m); }
return m;
};
- scope.es_createEntity = () => nextId++;
- scope.es_destroyEntity = (e: number) => { for (const m of comps.values()) m.delete(e); };
+ scope.es_registry_create = () => nextId++;
+ scope.es_registry_destroy = (e: number) => { for (const m of comps.values()) m.delete(e); };
scope.es_hasParent = () => false;
- scope.es_setParent = () => {};
+ scope.es_registry_setParent = () => {};
scope.es_removeParent = () => {};
scope.es_hasChildren = () => false;
scope.es_getChildren = () => [];
+ installRegistryOpDefaults(scope);
for (const cppName of Object.keys(PTR_ACCESSORS)) {
scope[`es_${cppName}_buffer`] = (e: number) => {
const m = store(cppName);
diff --git a/sdk/tests/native-world.test.ts b/sdk/tests/native-world.test.ts
index ed8afb7f7..16c102beb 100644
--- a/sdk/tests/native-world.test.ts
+++ b/sdk/tests/native-world.test.ts
@@ -11,6 +11,7 @@
import { describe, expect, it } from 'vitest';
import { createNativeWorld } from '../src/ecs/bridge/nativeRuntime';
import { PTR_ACCESSORS } from '../src/ecs/bridge/ptrAccessors.generated';
+import { installRegistryOpDefaults } from './helpers/nativeRegistryOps';
import { Sprite, Transform } from '../src/ecs/component';
/** A self-contained fake native ECS + the host bindings createNativeWorld expects. */
@@ -27,8 +28,8 @@ function mockNativeEcs() {
};
const scope: Record<string, unknown> = {
- es_createEntity: () => { const e = nextId++; alive.add(e); return e; },
- es_destroyEntity: (e: number) => {
+ es_registry_create: () => { const e = nextId++; alive.add(e); return e; },
+ es_registry_destroy: (e: number) => {
alive.delete(e);
for (const m of comps.values()) m.delete(e);
const p = parents.get(e);
@@ -37,7 +38,7 @@ function mockNativeEcs() {
children.delete(e);
},
es_hasParent: (e: number) => parents.has(e),
- es_setParent: (c: number, p: number) => {
+ es_registry_setParent: (c: number, p: number) => {
parents.set(c, p);
let s = children.get(p);
if (!s) { s = new Set(); children.set(p, s); }
@@ -51,6 +52,7 @@ function mockNativeEcs() {
es_hasChildren: (e: number) => (children.get(e)?.size ?? 0) > 0,
es_getChildren: (e: number) => [...(children.get(e) ?? [])],
};
+ installRegistryOpDefaults(scope, alive);
for (const cppName of Object.keys(PTR_ACCESSORS)) {
scope[`es_${cppName}_buffer`] = (e: number) => {
const m = store(cppName);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index f63c1e8fb..769894de3 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -2465,25 +2465,19 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
EMSCRIPTEN_BINDINGS(esengine_registry) {
class_<Registry>("Registry")
.constructor<>()
- .function("create", optional_override([](Registry& r) {
- return static_cast<u32>(r.create());
- }))
- .function("destroy", optional_override([](Registry& r, u32 e) {
- r.destroy(static_cast<Entity>(e));
- }))
- .function("valid", optional_override([](Registry& r, u32 e) {
- return r.valid(static_cast<Entity>(e));
- }))
- .function("reserveDestruction", optional_override([](Registry& r, u32 e) {
- return r.reserveDestruction(static_cast<Entity>(e));
- }))
- .function("releaseDestruction", optional_override([](Registry& r, u32 e) {
- r.releaseDestruction(static_cast<Entity>(e));
- }))
- .function("destructionPending", optional_override([](Registry& r, u32 e) {
- return r.destructionPending(static_cast<Entity>(e));
- }))
- .function("entityCount", &Registry::entityCount)
+ .function("create", optional_override([](Registry& r) { return static_cast<u32>(r.create()); }))
+ .function("destroy", optional_override([](Registry& r, u32 entity) { r.destroy(static_cast<Entity>(entity)); }))
+ .function("valid", optional_override([](Registry& r, u32 entity) { return r.valid(static_cast<Entity>(entity)); }))
+ .function("entityCount", optional_override([](Registry& r) { return r.entityCount(); }))
+ .function("reserveDestruction", optional_override([](Registry& r, u32 entity) { return r.reserveDestruction(static_cast<Entity>(entity)); }))
+ .function("releaseDestruction", optional_override([](Registry& r, u32 entity) { r.releaseDestruction(static_cast<Entity>(entity)); }))
+ .function("destructionPending", optional_override([](Registry& r, u32 entity) { return r.destructionPending(static_cast<Entity>(entity)); }))
+ .function("setEntityEnabled", optional_override([](Registry& r, u32 entity, bool enabled) { return r.setEntityEnabled(static_cast<Entity>(entity), enabled); }))
+ .function("isEntityActive", optional_override([](Registry& r, u32 entity) { return r.isEntityActive(static_cast<Entity>(entity)); }))
+ .function("isEntityEnabled", optional_override([](Registry& r, u32 entity) { return r.isEntityEnabled(static_cast<Entity>(entity)); }))
+ .function("hasInactiveEntities", optional_override([](Registry& r) { return r.hasInactiveEntities(); }))
+ .function("activityEpoch", optional_override([](Registry& r) { return r.activityEpoch(); }))
+ .function("setParent", optional_override([](Registry& r, u32 child, u32 parent) { return esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent)); }))
.function("getBuiltinComponentNames", optional_override([](Registry& r, u32 e) {
const auto entity = static_cast<Entity>(e);
@@ -3872,16 +3866,6 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Velocity>(entity);
}))
- // Hierarchy Utilities
- .function("setEntityEnabled", optional_override([](Registry& r, u32 e, bool enabled) { return r.setEntityEnabled(static_cast<Entity>(e), enabled); }))
- .function("isEntityActive", optional_override([](Registry& r, u32 e) { return r.isEntityActive(static_cast<Entity>(e)); }))
- .function("isEntityEnabled", optional_override([](Registry& r, u32 e) { return r.isEntityEnabled(static_cast<Entity>(e)); }))
- .function("hasInactiveEntities", &Registry::hasInactiveEntities)
- .function("activityEpoch", &Registry::activityEpoch)
- .function("setParent", optional_override([](Registry& r, u32 child, u32 parent) {
- return esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent));
- }))
-
;
}
diff --git a/tools/eht/__main__.py b/tools/eht/__main__.py
index 12bf53d73..e55570031 100644
--- a/tools/eht/__main__.py
+++ b/tools/eht/__main__.py
@@ -298,6 +298,7 @@ def main() -> int:
ts_gen = TypeScriptGenerator(cpp_parser.components, cpp_parser.enums)
ts_content = ts_gen.generate()
write_ts('wasm/wasm.generated.ts', ts_content)
+ write_ts('ecs/bridge/registryOps.generated.ts', ts_gen.generate_registry_ops())
# ── Component Metadata ──
meta_gen = MetadataGenerator(cpp_parser.components, cpp_parser.enums, abi_hash=abi_hash)
diff --git a/tools/eht/generators/embind.py b/tools/eht/generators/embind.py
index 457845656..b5a297f3e 100644
--- a/tools/eht/generators/embind.py
+++ b/tools/eht/generators/embind.py
@@ -1,6 +1,7 @@
"""Emscripten embind C++ bindings generator."""
from typing import List, Set
+from ..registry_ops import REGISTRY_OPS
from ..data import Component, Enum, HIERARCHY_COMPONENTS, READ_HOOKS
from ..type_system import TypeSystem
@@ -352,6 +353,19 @@ class EmbindGenerator:
' }))',
]
+ def _gen_registry_ops(self) -> List[str]:
+ """The entity ops, from the one table every backend reads (registry_ops)."""
+ lines = []
+ for op in REGISTRY_OPS:
+ params = ''.join(f', {"bool" if k == "bool" else "u32"} {n}' for n, k in op.params)
+ args = [f'static_cast<Entity>({n})' if k == 'entity' else n for n, k in op.params]
+ call = op.call.format(*args)
+ body = (f'{call};' if op.returns == 'void'
+ else f'return static_cast<u32>({call});' if op.returns == 'entity'
+ else f'return {call};')
+ lines.append(f' .function("{op.name}", optional_override([](Registry& r{params}) {{ {body} }}))')
+ return lines
+
def _gen_registry(self) -> List[str]:
lines = [
'// =============================================================================',
@@ -361,27 +375,9 @@ class EmbindGenerator:
'EMSCRIPTEN_BINDINGS(esengine_registry) {',
' class_<Registry>("Registry")',
' .constructor<>()',
- ' .function("create", optional_override([](Registry& r) {',
- ' return static_cast<u32>(r.create());',
- ' }))',
- ' .function("destroy", optional_override([](Registry& r, u32 e) {',
- ' r.destroy(static_cast<Entity>(e));',
- ' }))',
- ' .function("valid", optional_override([](Registry& r, u32 e) {',
- ' return r.valid(static_cast<Entity>(e));',
- ' }))',
- ' .function("reserveDestruction", optional_override([](Registry& r, u32 e) {',
- ' return r.reserveDestruction(static_cast<Entity>(e));',
- ' }))',
- ' .function("releaseDestruction", optional_override([](Registry& r, u32 e) {',
- ' r.releaseDestruction(static_cast<Entity>(e));',
- ' }))',
- ' .function("destructionPending", optional_override([](Registry& r, u32 e) {',
- ' return r.destructionPending(static_cast<Entity>(e));',
- ' }))',
- ' .function("entityCount", &Registry::entityCount)',
- '',
]
+ lines.extend(self._gen_registry_ops())
+ lines.append('')
lines.extend([
' .function("getBuiltinComponentNames", optional_override([](Registry& r, u32 e) {',
@@ -468,18 +464,6 @@ class EmbindGenerator:
lines.append(' }))')
lines.append('')
- lines.extend([
- ' // Hierarchy Utilities',
- ' .function("setEntityEnabled", optional_override([](Registry& r, u32 e, bool enabled) { return r.setEntityEnabled(static_cast<Entity>(e), enabled); }))',
- ' .function("isEntityActive", optional_override([](Registry& r, u32 e) { return r.isEntityActive(static_cast<Entity>(e)); }))',
- ' .function("isEntityEnabled", optional_override([](Registry& r, u32 e) { return r.isEntityEnabled(static_cast<Entity>(e)); }))',
- ' .function("hasInactiveEntities", &Registry::hasInactiveEntities)',
- ' .function("activityEpoch", &Registry::activityEpoch)',
- ' .function("setParent", optional_override([](Registry& r, u32 child, u32 parent) {',
- ' return esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent));',
- ' }))',
- '',
- ])
lines.append(' ;')
lines.append('}')
return lines
diff --git a/tools/eht/generators/native_bindings.py b/tools/eht/generators/native_bindings.py
index 8d15e9d12..03d21a6b2 100644
--- a/tools/eht/generators/native_bindings.py
+++ b/tools/eht/generators/native_bindings.py
@@ -15,6 +15,7 @@ for the ``esn_*`` readers, the entity lookup, and the component includes.
"""
from typing import List
+from ..registry_ops import REGISTRY_OPS
from ..data import Component, Enum, READ_HOOKS, WRITE_HOOKS
from ..type_system import TypeSystem
from .ptr_layout import PtrLayoutGenerator
@@ -233,6 +234,31 @@ class NativeBindingsGenerator:
out.append('')
return out
+ def _registry_ops(self) -> List[str]:
+ """The entity ops as es_registry_<name>, from the table embind reads too."""
+ out = []
+ for op in REGISTRY_OPS:
+ args = [f'esn_entity(a[{i}])' if k == 'entity' else f'esjs::toBool(a[{i}])'
+ for i, (_n, k) in enumerate(op.params)]
+ call = op.call.replace('r.', 'esn_reg().', 1) if op.call.startswith('r.') else op.call.replace('(r,', '(esn_reg(),', 1)
+ call = call.format(*args)
+ out.append(f'static esjs::Val {op.native_name}(const esjs::Args& a) {{')
+ if op.params:
+ out.append(f' if (a.size() < {len(op.params)}) return esjs::undefined();')
+ else:
+ out.append(' (void)a;')
+ if op.returns == 'void':
+ out += [f' {call};', ' return esjs::undefined();']
+ elif op.returns == 'entity':
+ out.append(f' return esjs::uint32(({call}).id());')
+ elif op.returns == 'bool':
+ out.append(f' return esjs::boolean({call});')
+ else:
+ out.append(f' return esjs::number(static_cast<double>({call}));')
+ out.append('}')
+ out.append('')
+ return out
+
def generate(self) -> str:
lines = [
'// Auto-generated by EHT (native_bindings) — DO NOT EDIT.',
@@ -244,8 +270,8 @@ class NativeBindingsGenerator:
'',
]
components = sorted(self.components, key=lambda c: c.name)
- if any(c.name in WRITE_HOOKS for c in components):
- lines.append('#include "esengine/ecs/TransformSystem.hpp"')
+ # ecs::setParent, which the setParent op and the write hooks call.
+ lines.append('#include "esengine/ecs/TransformSystem.hpp"')
# Self-include each bound component's header (relative to src/), so the TU
# needs only the shim for the esn_* plumbing — deduped (some components
# share a header, e.g. the collider family).
@@ -259,6 +285,7 @@ class NativeBindingsGenerator:
lines.append(f'#include "{hp}"')
if seen:
lines.append('')
+ lines.extend(self._registry_ops())
for comp in components:
lines.extend(self._component(comp))
lines.extend([
@@ -284,6 +311,8 @@ class NativeBindingsGenerator:
lines.append(f' if (name == "{comp.name}") return esjs::int64(esengine::componentTypeId<{full}>());')
lines.extend([' return esjs::int32(-1);', '}', ''])
lines.append('void esn_register(esjs::Val global) {')
+ for op in REGISTRY_OPS:
+ lines.append(f' esjs::setFunction(global, "{op.native_name}", {op.native_name}, {len(op.params)});')
lines.append(' esjs::setFunction(global, "es_componentTypeId", es_componentTypeId, 1);')
lines.append(' esjs::setFunction(global, "es_getBuiltinComponentNames", es_getBuiltinComponentNames, 1);')
for comp in components:
diff --git a/tools/eht/generators/typescript.py b/tools/eht/generators/typescript.py
index cd61ff2c9..7d5012fcb 100644
--- a/tools/eht/generators/typescript.py
+++ b/tools/eht/generators/typescript.py
@@ -1,6 +1,7 @@
"""TypeScript type definitions generator."""
from typing import List
+from ..registry_ops import REGISTRY_OPS
from ..data import Component, Enum
from ..type_system import TypeSystem
@@ -92,10 +93,10 @@ class TypeScriptGenerator:
lines = [
'// Registry',
'export interface Registry {',
- ' create(): Entity;',
- ' destroy(entity: Entity): void;',
- ' valid(entity: Entity): boolean;',
- ' entityCount(): number;',
+ ]
+ for op in REGISTRY_OPS:
+ lines.extend([f' /** {op.doc} */', f' {op.ts_signature()}'])
+ lines += [
' /** All generated builtin names, separated by |; absent on older cores. */',
' getBuiltinComponentNames?(entity: Entity): string;',
' /** Host-local component ID; -1 for an unknown name. */',
@@ -110,20 +111,34 @@ class TypeScriptGenerator:
f' add{n}(entity: Entity, component: {n}): void;',
f' remove{n}(entity: Entity): void;',
])
- lines.extend([
- '',
- ' // Hierarchy Utilities',
- ' setEntityEnabled?(entity: Entity, enabled: boolean): boolean;',
- ' isEntityActive?(entity: Entity): boolean;',
- ' isEntityEnabled?(entity: Entity): boolean;',
- ' hasInactiveEntities?(): boolean;',
- ' activityEpoch?(): number;',
- ' setParent(child: Entity, parent: Entity): boolean | void;',
- ])
lines.append('}')
lines.append('')
return lines
+ def generate_registry_ops(self) -> str:
+ """REGISTRY_OPS: each entity op and the global a native host binds it as.
+ The SDK's native registry installs these in a loop and the boot check
+ requires every one, so a host cannot ship without an op the web has."""
+ lines = [
+ '/**',
+ ' * @file registryOps.generated.ts',
+ ' * @brief The Registry entity ops and their native host globals.',
+ ' * @details Generated by EHT from tools/eht/registry_ops.py - DO NOT EDIT',
+ ' */',
+ '',
+ "import type { Registry } from '../../wasm/wasm.generated';",
+ '',
+ 'export const REGISTRY_OPS = {',
+ ]
+ lines += [f" {op.name}: '{op.native_name}'," for op in REGISTRY_OPS]
+ lines += [
+ '} as const satisfies { readonly [K in keyof Registry]?: string };',
+ '',
+ 'export type RegistryOp = keyof typeof REGISTRY_OPS;',
+ '',
+ ]
+ return '\n'.join(lines)
+
def _gen_module(self) -> List[str]:
lines = [
'// Module',
diff --git a/tools/eht/registry_ops.py b/tools/eht/registry_ops.py
new file mode 100644
index 000000000..0fb2f6e3c
--- /dev/null
+++ b/tools/eht/registry_ops.py
@@ -0,0 +1,74 @@
+"""The Registry's entity operations, declared once.
+
+Every backend reaches the C++ Registry's entity-level surface (create, destroy,
+valid, activity, hierarchy) through a binding, and each binding used to be
+written by hand: an embind ``.function`` here, an ``es_*`` global in the native
+host, a TS signature, and a name in the SDK's native bridge. Four spellings of
+one list, and only the web one was complete — the native host never bound
+``valid``, which nothing noticed until a reader called it (issue #114).
+
+This table is the list. The embind generator emits it as Registry methods, the
+native generator as ``es_registry_<name>`` globals, the TS generator as the
+``Registry`` interface and as ``REGISTRY_OPS`` (method -> native global), which
+the SDK's native registry installs in a loop. A new op is one row here.
+
+Per-component methods (has/get/add/remove<Name>) are not here: they come from
+the component reflection. Nor are the hierarchy READS (hasParent, getChildren):
+embind answers those through the Parent/Children component methods, so only the
+native bridge needs them as entity ops.
+"""
+
+from dataclasses import dataclass
+from typing import Tuple
+
+# Argument and result kinds that cross. 'entity' is the raw u32 id.
+_TS = {'entity': 'Entity', 'bool': 'boolean', 'number': 'number', 'void': 'void'}
+
+
+@dataclass(frozen=True)
+class RegistryOp:
+ name: str
+ params: Tuple[Tuple[str, str], ...]
+ returns: str
+ # C++ expression over `r` (the Registry) and `{0}`, `{1}`… (the arguments,
+ # already converted to their C++ types by whichever backend emits it).
+ call: str
+ doc: str
+
+ @property
+ def native_name(self) -> str:
+ return f'es_registry_{self.name}'
+
+ def ts_signature(self) -> str:
+ args = ', '.join(f'{n}: {_TS[k]}' for n, k in self.params)
+ return f'{self.name}({args}): {_TS[self.returns]};'
+
+
+def _e(name: str = 'entity') -> Tuple[str, str]:
+ return (name, 'entity')
+
+
+REGISTRY_OPS: Tuple[RegistryOp, ...] = (
+ RegistryOp('create', (), 'entity', 'r.create()', 'A new entity.'),
+ RegistryOp('destroy', (_e(),), 'void', 'r.destroy({0})', 'Destroys the entity and its components.'),
+ RegistryOp('valid', (_e(),), 'bool', 'r.valid({0})', 'Whether the id names a live entity.'),
+ RegistryOp('entityCount', (), 'number', 'r.entityCount()', 'Live entities.'),
+ RegistryOp('reserveDestruction', (_e(),), 'bool', 'r.reserveDestruction({0})',
+ 'Claims the subtree teardown; false when another owner already has it.'),
+ RegistryOp('releaseDestruction', (_e(),), 'void', 'r.releaseDestruction({0})',
+ 'Gives back a claim from reserveDestruction.'),
+ RegistryOp('destructionPending', (_e(),), 'bool', 'r.destructionPending({0})',
+ 'Whether a teardown has claimed the entity.'),
+ RegistryOp('setEntityEnabled', (_e(), ('enabled', 'bool')), 'bool', 'r.setEntityEnabled({0}, {1})',
+ "Sets the entity's own enabled flag; activity follows the hierarchy."),
+ RegistryOp('isEntityActive', (_e(),), 'bool', 'r.isEntityActive({0})',
+ 'Enabled itself and under enabled ancestors.'),
+ RegistryOp('isEntityEnabled', (_e(),), 'bool', 'r.isEntityEnabled({0})',
+ "The entity's own flag, ignoring ancestors."),
+ RegistryOp('hasInactiveEntities', (), 'bool', 'r.hasInactiveEntities()',
+ 'Whether any entity is inactive (lets a query skip the activity check).'),
+ RegistryOp('activityEpoch', (), 'number', 'r.activityEpoch()', 'Bumped by every activity change.'),
+ RegistryOp('setParent', (_e('child'), _e('parent')), 'bool',
+ 'esengine::ecs::setParent(r, {0}, {1})',
+ 'Re-parents child; false when refused (a cycle, an invalid entity).'),
+)