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(native): the registry answers small components and the whole hierarchy surface

esenginec985f4de4a27
diff --git a/native/host/bindings/EcsBindings.cpp b/native/host/bindings/EcsBindings.cpp
index 737ac16fb..16ddf16eb 100644
--- a/native/host/bindings/EcsBindings.cpp
+++ b/native/host/bindings/EcsBindings.cpp
@@ -44,6 +44,10 @@ JSValue js_setParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
JSValue js_hasParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
return JS_NewBool(ctx, host().registry->has<ecs::Parent>(esn_entity(ctx, argv[0])));
}
+JSValue js_getParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
+ auto* p = host().registry->tryGet<ecs::Parent>(esn_entity(ctx, argv[0]));
+ return JS_NewUint32(ctx, (p ? p->entity : INVALID_ENTITY).id());
+}
JSValue js_removeParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), INVALID_ENTITY);
return JS_UNDEFINED;
@@ -70,6 +74,7 @@ void registerEcsBindings(HostState& h, JSValue global) {
bindGlobal(h, global, "es_destroyEntity", js_destroyEntity, 1);
bindGlobal(h, global, "es_setParent", js_setParent, 2);
bindGlobal(h, global, "es_hasParent", js_hasParent, 1);
+ bindGlobal(h, global, "es_getParent", js_getParent, 1);
bindGlobal(h, global, "es_removeParent", js_removeParent, 1);
bindGlobal(h, global, "es_hasChildren", js_hasChildren, 1);
bindGlobal(h, global, "es_getChildren", js_getChildren, 1);
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index e1874afac..5e654a18c 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5347,7 +5347,7 @@ static prototype: QueryInstance<any>
## REGISTRY_BINDINGS — const
```
-{ readonly createEntity: "es_createEntity"; readonly destroyEntity: "es_destroyEntity"; readonly setParent: "es_setParent"; readonly hasParent: "es_hasParent"; readonly removeParent: "es_removeParent"; readonly hasChildren: "es_hasChildren"; readonly getChildren: "es_getChildren"; }
+{ readonly createEntity: "es_createEntity"; readonly destroyEntity: "es_destroyEntity"; readonly setParent: "es_setParent"; readonly hasParent: "es_hasParent"; readonly getParent: "es_getParent"; readonly removeParent: "es_removeParent"; readonly hasChildren: "es_hasChildren"; readonly getChildren: "es_getChildren"; }
```
## REPLICATION_CHANNEL — const
diff --git a/sdk/src/ecs/nativeBindings.ts b/sdk/src/ecs/nativeBindings.ts
index 2c7843779..d712b4217 100644
--- a/sdk/src/ecs/nativeBindings.ts
+++ b/sdk/src/ecs/nativeBindings.ts
@@ -29,6 +29,7 @@ export const REGISTRY_BINDINGS = {
destroyEntity: 'es_destroyEntity',
setParent: 'es_setParent',
hasParent: 'es_hasParent',
+ getParent: 'es_getParent',
removeParent: 'es_removeParent',
hasChildren: 'es_hasChildren',
getChildren: 'es_getChildren',
diff --git a/sdk/src/ecs/nativeRegistry.ts b/sdk/src/ecs/nativeRegistry.ts
index 7087b8d7e..ef1bf523c 100644
--- a/sdk/src/ecs/nativeRegistry.ts
+++ b/sdk/src/ecs/nativeRegistry.ts
@@ -27,7 +27,12 @@ type HasFn = (entity: number) => boolean;
type RemoveFn = (entity: number) => void;
function views(buf: ArrayBuffer): [Float32Array, Uint32Array, Uint8Array] {
- return [new Float32Array(buf), new Uint32Array(buf), new Uint8Array(buf)];
+ // Float32Array/Uint32Array require a byteLength that is a multiple of 4, but a
+ // component's native struct can be any size (Interactable is 3 bytes, UIMask 2).
+ // Cover the 4-aligned prefix for the word views — every f32/u32 field is
+ // naturally aligned and fits within it — and the whole buffer for the byte view.
+ const words = Math.floor(buf.byteLength / 4);
+ return [new Float32Array(buf, 0, words), new Uint32Array(buf, 0, words), new Uint8Array(buf)];
}
/** Invoke a host-provided global by name (throws a clear error if the host did not
@@ -50,9 +55,19 @@ function hostCallOpt(scope: Record<string, unknown>, name: string, args: unknown
/** Present a JS array as the embind VectorEntity interface World.getChildren
* returns (size()/get(i)/delete()), so despawn iterates it the same on both
- * backends. Native memory is JS-owned here, so delete() is a no-op. */
-function vectorEntity(arr: readonly Entity[]): { size(): number; get(i: number): Entity; delete(): void } {
- return { size: () => arr.length, get: (i: number) => arr[i], delete: () => { /* nothing to free */ } };
+ * backends. Native memory is JS-owned here, so delete() is a no-op. Also iterable
+ * (`for...of`): consumers like the timeline/animator child-path resolver walk the
+ * children with a for-of and type the field as `Entity[]`, so the shim must
+ * answer Symbol.iterator too, not only the vector methods. */
+function vectorEntity(
+ arr: readonly Entity[],
+): { size(): number; get(i: number): Entity; delete(): void; [Symbol.iterator](): Iterator<Entity> } {
+ return {
+ size: () => arr.length,
+ get: (i: number) => arr[i],
+ delete: () => { /* nothing to free */ },
+ [Symbol.iterator]: () => arr[Symbol.iterator](),
+ };
}
/**
@@ -82,6 +97,30 @@ export function createNativeRegistry(
reg.getChildren = (e: Entity) => ({
entities: vectorEntity((hostCall(scope, REGISTRY_BINDINGS.getChildren, [e]) as Entity[] | undefined) ?? []),
});
+
+ // Parent/Children are hierarchy components, not POD ptr components, so they are
+ // not in PTR_ACCESSORS. The embind Registry still exposes them the component way
+ // (add/get/has/remove), and readers like the physics and hierarchy systems reach
+ // them through BuiltinBridge.getBuiltinMethods, which needs all four to exist.
+ // Present that surface here over the native entity-ops so both backends match.
+ reg.getParent = (e: Entity): { entity: Entity } => ({
+ 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]);
+ };
+ // 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]);
+ }
+ };
+ reg.removeChildren = (parent: Entity): void => {
+ const kids = (hostCall(scope, REGISTRY_BINDINGS.getChildren, [parent]) as Entity[] | undefined) ?? [];
+ for (const child of kids) hostCall(scope, REGISTRY_BINDINGS.removeParent, [child]);
+ };
reg.delete = (): void => {};
// The scene queries the wasm module answers as module-level functions. There is
diff --git a/sdk/tests/native-registry.test.ts b/sdk/tests/native-registry.test.ts
index c3b1e6495..65b8eee77 100644
--- a/sdk/tests/native-registry.test.ts
+++ b/sdk/tests/native-registry.test.ts
@@ -97,6 +97,75 @@ describe('createNativeRegistry', () => {
expect(reg.hasSprite(9)).toBe(false); // must not have emplaced it
});
+ it('adds a component whose native struct is not 4-byte aligned (Interactable is 3 bytes)', () => {
+ // The host returns a buffer the exact size of the component. Interactable is
+ // three bools = 3 bytes, not a multiple of 4, so building a Float32Array over
+ // the whole buffer throws "invalid length" on QuickJS. views() must cover only
+ // the 4-aligned prefix for the word views and the whole buffer for the byte view.
+ const store = new Map<number, ArrayBuffer>();
+ const scope: Record<string, unknown> = {
+ es_Interactable_buffer: (e: number) => {
+ let b = store.get(e);
+ if (!b) { b = new ArrayBuffer(3); store.set(e, b); }
+ return b;
+ },
+ es_Interactable_has: (e: number) => store.has(e),
+ es_Interactable_remove: (e: number) => { store.delete(e); },
+ };
+ const reg = createNativeRegistry(scope) as unknown as Record<string, Function>;
+ const data = PTR_ACCESSORS.Interactable.create() as Record<string, unknown>;
+ data.enabled = true; data.blockRaycast = false; data.raycastTarget = true;
+ expect(() => reg.addInteractable(1, data)).not.toThrow();
+ const got = reg.getInteractable(1) as Record<string, boolean>;
+ expect(got.enabled).toBe(true);
+ expect(got.blockRaycast).toBe(false);
+ expect(got.raycastTarget).toBe(true);
+ });
+
+ it('exposes Parent/Children the component way over the native entity-ops', () => {
+ // BuiltinBridge.getBuiltinMethods requires add/get/has/remove for the hierarchy
+ // components — the physics and hierarchy systems read them that way. The host
+ // binds only entity-ops (setParent/getParent/getChildren); the registry adapts.
+ const parents = new Map<number, number>();
+ const children = new Map<number, number[]>();
+ const scope: Record<string, unknown> = {
+ es_setParent: (c: number, p: number) => {
+ parents.set(c, p);
+ (children.get(p) ?? children.set(p, []).get(p)!).push(c);
+ },
+ es_getParent: (c: number) => parents.get(c) ?? 0,
+ es_hasParent: (c: number) => parents.has(c),
+ es_removeParent: (c: number) => { parents.delete(c); },
+ es_hasChildren: (p: number) => (children.get(p)?.length ?? 0) > 0,
+ es_getChildren: (p: number) => children.get(p) ?? [],
+ };
+ const reg = createNativeRegistry(scope) as unknown as Record<string, Function>;
+ for (const m of ['addParent', 'getParent', 'hasParent', 'removeParent',
+ 'addChildren', 'getChildren', 'hasChildren', 'removeChildren']) {
+ expect(typeof reg[m]).toBe('function');
+ }
+ reg.addParent(2, { entity: 1 });
+ expect(reg.hasParent(2)).toBe(true);
+ expect((reg.getParent(2) as { entity: number }).entity).toBe(1);
+ expect(reg.hasChildren(1)).toBe(true);
+ });
+
+ it('getChildren.entities is iterable (for...of) as well as vector-shaped', () => {
+ // The timeline/animator child-path resolver walks children with a for-of and
+ // types the field `Entity[]`; the VectorEntity shim must answer Symbol.iterator
+ // too, or that for-of throws "value is not iterable" on the native backend.
+ const scope: Record<string, unknown> = {
+ es_getChildren: (_p: number) => [10, 11, 12],
+ es_hasChildren: (_p: number) => true,
+ };
+ const reg = createNativeRegistry(scope) as unknown as Record<string, Function>;
+ const kids = (reg.getChildren(1) as { entities: Iterable<number> }).entities;
+ expect([...kids]).toEqual([10, 11, 12]);
+ const seen: number[] = [];
+ for (const c of kids) seen.push(c);
+ expect(seen).toEqual([10, 11, 12]);
+ });
+
it('skips components whose host bindings are absent', () => {
// Only Sprite is bound; other components must not get registry methods.
const scope: Record<string, unknown> = {