A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ecs): an engine component has an address too, and it is the backend's
yhh59abab604a26
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex b79b2db58..5898bda80 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -9251,7 +9251,7 @@ tabIndex: number | undefined## World — class @public```-@internal addressOfScriptComponent: (component: AnyComponentDef, entity: Entity) => number | undefined+@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal advanceTick: () => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 03218d1d6..425c2a9a3 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -9444,7 +9444,7 @@ tabIndex: number | undefined## World — class @public```-@internal addressOfScriptComponent: (component: AnyComponentDef, entity: Entity) => number | undefined+@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal advanceTick: () => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex ba913dacf..628fd4ebd 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -9246,7 +9246,7 @@ tabIndex: number | undefined## World — class @public```-@internal addressOfScriptComponent: (component: AnyComponentDef, entity: Entity) => number | undefined+@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal advanceTick: () => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex e68c81f7f..55883686d 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -9497,7 +9497,7 @@ tabIndex: number | undefined## World — class @public```-@internal addressOfScriptComponent: (component: AnyComponentDef, entity: Entity) => number | undefined+@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal advanceTick: () => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex a3f2320a3..3ee4c366f 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -9273,7 +9273,7 @@ tabIndex: number | undefined## World — class @public```-@internal addressOfScriptComponent: (component: AnyComponentDef, entity: Entity) => number | undefined+@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal advanceTick: () => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => voiddiff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.tsindex efacdba91..b8b248c79 100644--- a/sdk/src/ecs/bridge/BuiltinBridge.ts+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts@@ -667,6 +667,19 @@ export class BuiltinBridge {this.builtinEntitySets_.get(component._cppName)?.delete(entity);}+ /**+ * Where `cppName`'s bytes are for an entity: what compiled code adds an EHT+ * offset to (§2.4). Through the {@link MemoryProvider}, the seam the fast+ * accessors already use — an address resolved a second way can disagree.+ * Null where this backend serves no flat memory.+ */+ resolveComponentAddress(cppName: string): ((entity: Entity) => number | undefined) | null {+ const resolveHeap = this.memory_?.resolveComponentHeap(cppName);+ if (!resolveHeap) return null;+ const heap: ComponentHeap = SCRATCH_HEAP();+ return (e: Entity) => (resolveHeap(e, heap) ? heap.ptr : undefined);+ }+/*** The wasm-exported pointer function for `cppName` — `(entity) => byte offset* of that entity's component in the wasm heap`. Web/emscripten only (there isdiff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex ccc4a1938..ca848d272 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -158,11 +158,13 @@ export class World {module?: ESEngineModule,options?: BridgeConnectOptions,): void {+ this.addressOf_.clear();this.builtin_.connect(cppRegistry, module, options);}/** @internal */disconnectCpp(): void {+ this.addressOf_.clear();this.builtin_.disconnect();}@@ -1173,12 +1175,26 @@ export class World {}/**- * @internal `component`'s bytes for `entity`, in the memory the pool was- * allocated from — what a compiled system is handed. Undefined for a- * component with no flat rows, which is a component no system compiles- * against.+ * @internal `component`'s bytes for `entity`, in the memory compiled code+ * reads: an engine component through the bridge, a script one through its+ * pool. Undefined where there are no flat bytes. The resolver is cached per+ * component — finding it walks a generated table, and this is asked once per+ * entity per frame.*/- addressOfScriptComponent(component: AnyComponentDef, entity: Entity): number | undefined {- return this.scripts_.poolFor(component._id as symbol)?.address(entity);+ addressOfComponent(component: AnyComponentDef, entity: Entity): number | undefined {+ let at = this.addressOf_.get(component._id as symbol);+ if (at === undefined) {+ at = isBuiltinComponent(component)+ ? (this.builtin_.resolveComponentAddress(component._cppName) ?? NO_ADDRESS)+ : (e: Entity) => this.scripts_.poolFor(component._id as symbol)?.address(e);+ this.addressOf_.set(component._id as symbol, at);+ }+ return at(entity);}++ /** Cleared with the bridge, because a reconnect may serve other memory. */+ private readonly addressOf_ = new Map<symbol, (entity: Entity) => number | undefined>();}++/** A component whose backend serves no flat memory: never has an address. */+const NO_ADDRESS = (): undefined => undefined;diff --git a/sdk/tests/aot-dispatch.test.ts b/sdk/tests/aot-dispatch.test.tsindex 7f44135b1..0143183a0 100644--- a/sdk/tests/aot-dispatch.test.ts+++ b/sdk/tests/aot-dispatch.test.ts@@ -192,7 +192,7 @@ describe('the scheduler and its compiled twin', () => {const addresses: AotAddresses = {componentNamed: (name) => (name === 'Decay' ? b.Decay : undefined),- componentAt: (comp, entity) => b.world.addressOfScriptComponent(comp, entity),+ componentAt: (comp, entity) => b.world.addressOfComponent(comp, entity),resourceAt: () => undefined,};const runtime: AotRuntime = { systems, addresses, ctx: new AotContext(memory) };@@ -244,7 +244,7 @@ describe('the scheduler and its compiled twin', () => {systems,addresses: {componentNamed: (name) => (name === 'Decay' ? w.Decay : undefined),- componentAt: (c, e) => w.world.addressOfScriptComponent(c, e),+ componentAt: (c, e) => w.world.addressOfComponent(c, e),resourceAt: () => undefined,},ctx: new AotContext(memory),diff --git a/sdk/tests/aot-engine-component-address.test.ts b/sdk/tests/aot-engine-component-address.test.tsnew file mode 100644index 000000000..a2957f313--- /dev/null+++ b/sdk/tests/aot-engine-component-address.test.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file aot-engine-component-address.test.ts+ * @brief Where an ENGINE component's bytes are, for compiled code.+ *+ * @details A `defineComponent` component is a row in a pool this SDK owns, and+ * that path is tested by the dispatch differential. An engine component+ * is in the C++ pools, and the only thing that knows where is the+ * backend's {@link MemoryProvider} — the same seam the fast accessors+ * go through, because an address resolved a second way is an address+ * that can disagree.+ *+ * The provider is injectable, so this asks the real question without a+ * built engine: given a backend that serves flat memory, does the world+ * hand out the address that backend reports?+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/ecs/world';+import { defineComponent, Transform } from '../src/ecs/component';+import type { AnyComponentDef } from '../src/ecs/component';+import type { ComponentHeap, MemoryProvider } from '../src/ecs/bridge/memoryProvider';+import type { CppRegistry } from '../src/wasm';+import type { Entity } from '../src/types';++/** A backend that serves one component out of one flat block. */+function providerFor(cppName: string, base: number, stride: number, live: Set<number>): MemoryProvider {+ const bytes = new ArrayBuffer(1 << 16);+ return {+ resolveComponentHeap: (name: string) => (name === cppName+ ? (entity: Entity, out: ComponentHeap): boolean => {+ const id = entity as unknown as number;+ if (!live.has(id)) return false;+ out.f32 = new Float32Array(bytes);+ out.u32 = new Uint32Array(bytes);+ out.u8 = new Uint8Array(bytes);+ out.ptr = base + id * stride;+ return true;+ }+ : null),+ };+}++/** Enough of a CppRegistry for `connect` to accept it; nothing here calls it. */+const REGISTRY = {} as unknown as CppRegistry;++describe('an engine component has an address too', () => {+ it('is the one the backend reports, not one this SDK computed', () => {+ const live = new Set([3, 7]);+ const world = new World();+ world.connectCpp(REGISTRY, undefined, {+ memory: providerFor('Transform', 4096, 64, live),+ });++ const at = (id: number): number | undefined =>+ world.addressOfComponent(Transform as unknown as AnyComponentDef, id as unknown as Entity);+ expect(at(3)).toBe(4096 + 3 * 64);+ expect(at(7)).toBe(4096 + 7 * 64);+ // Not live: a compiled system must skip the row rather than read zero,+ // which is a real address and would be somebody else's bytes.+ expect(at(4)).toBeUndefined();+ });++ it('a backend with no flat memory has no address, and says so', () => {+ const world = new World();+ // No module and no override: the native fast path is absent, and this is+ // exactly the case where a project cannot compile against Transform.+ world.connectCpp(REGISTRY);+ expect(world.addressOfComponent(Transform as unknown as AnyComponentDef, 1 as unknown as Entity))+ .toBeUndefined();+ });++ it('the resolver is not re-found per entity, and not kept across a reconnect', () => {+ let asked = 0;+ const live = new Set([1, 2]);+ const base = providerFor('Transform', 512, 32, live);+ const counting: MemoryProvider = {+ resolveComponentHeap: (name) => { asked++; return base.resolveComponentHeap(name); },+ };+ const world = new World();+ world.connectCpp(REGISTRY, undefined, { memory: counting });++ const comp = Transform as unknown as AnyComponentDef;+ for (let i = 0; i < 10; i++) world.addressOfComponent(comp, 1 as unknown as Entity);+ expect(asked, 'the generated table was walked once, not ten times').toBe(1);++ // A reconnect may serve different memory, so the cached answer must go.+ world.connectCpp(REGISTRY, undefined, { memory: counting });+ world.addressOfComponent(comp, 1 as unknown as Entity);+ expect(asked).toBe(2);+ });++ it('a script component still answers from its pool', () => {+ const world = new World();+ const Decay = defineComponent('Decay', { remaining: 1 }) as AnyComponentDef;+ const entity = world.spawn();+ world.insert(entity, Decay, { remaining: 0.5 });+ // One question, two kinds of storage: the runner asks the world, not the+ // storage, which is what lets a system name both in one query.+ expect(world.addressOfComponent(Decay, entity)).toBeTypeOf('number');+ });+});