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(aot): native must not take a system it cannot hand events to

esengined65fcc94dbc6
diff --git a/compiler/tests/codegen.test.ts b/compiler/tests/codegen.test.ts
index c48c237cb..f0ad0c2e3 100644
--- a/compiler/tests/codegen.test.ts
+++ b/compiler/tests/codegen.test.ts
@@ -655,3 +655,29 @@ describe.skipIf(!CC)('the emitted C says what the interpreter says', () => {
expect(source).not.toMatch(/\bes_abi_\w+\(/);
});
});
+
+/**
+ * What a road has to hand a compiled system before it does anything. A host
+ * that passes 0 in `events` faults on a frame where the system would have done
+ * nothing, which is why `installNativeAot` leaves event systems interpreted.
+ * Narrow this and that rule can be narrowed with it.
+ */
+describe('what the emitted C reaches for before it does anything', () => {
+ it('a writer dereferences the event block at entry, not at the send', () => {
+ const layout = packLayout(fixtures.module.comps);
+ const ping = systemOf(fixtures, 'FixturePing');
+ const { source } = emitC(fixtures.module, layout, [ping], 8);
+ const body = source.slice(source.indexOf(cSymbol('FixturePing')));
+ const prologue = body.slice(0, body.indexOf('for ('));
+ expect(prologue).toContain('ES_PTR(es_c->events)');
+ expect(prologue).toMatch(/es_ev_buf = \(double \*\)ES_PTR\(es_ev->buf\)/);
+ });
+
+ /** A reader asks for its payloads through a query slot that names the EVENT,
+ * which is what the artifact's declaration table tells a host as well. */
+ it('a reader names its event where a host reads a component name', () => {
+ const layout = packLayout(fixtures.module.comps);
+ const { decls } = emitC(fixtures.module, layout, [systemOf(fixtures, 'FixturePong')], 8);
+ expect(decls).toContain('"FixturePinged"');
+ });
+});
diff --git a/sdk/src/ecs/aot/installNativeAot.ts b/sdk/src/ecs/aot/installNativeAot.ts
index 9bb2f6e47..d9dabefce 100644
--- a/sdk/src/ecs/aot/installNativeAot.ts
+++ b/sdk/src/ecs/aot/installNativeAot.ts
@@ -24,7 +24,7 @@ import type { World } from '../world';
import type { SystemRunner } from '../system';
import { ENTITY_INDEX_MASK, type Entity } from '../../types';
import { WasmPoolMemory, type WasmHeap } from '../WasmPoolMemory';
-import { AotSystems, type AotManifest, type AotTwin } from './AotSystems';
+import { AotSystems, type AotManifest, type AotSystemDecl, type AotTwin } from './AotSystems';
import { AotResources, type ResourceReader } from './AotResources';
import type { AotDispatcher, AotRuntime } from './AotRuntime';
@@ -77,6 +77,16 @@ function declaredResourceLayouts(manifest: AotManifest): Map<string, readonly st
*/
const SPARSE_INDEX_MASK = ENTITY_INDEX_MASK;
+/**
+ * Whether a native host can hand this system what it compiled against. Not
+ * events: the ctx carries `events = 0` (AotHost.hpp) and the emitted C
+ * dereferences it in the PROLOGUE, so a writer's twin faults on a frame where
+ * it would have done nothing. A capability this road lacks is a FALLBACK.
+ */
+function nativeCanHost(decl: AotSystemDecl): boolean {
+ return !decl.readers?.length && !decl.writers?.length;
+}
+
/** Read the `es_aot_*` globals a native host bound, or null where it bound none. */
export function nativeAotBindings(
scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
@@ -123,6 +133,11 @@ export function installNativeAot(opts: InstallNativeAotOptions): AotRuntime | nu
// that component, and until then the interpreter keeps the system.
const byName = new Map<string, number>();
for (const decl of opts.manifest.systems) {
+ if (!nativeCanHost(decl)) {
+ log.info('runtime', `AOT: ${decl.name} reads or writes events, which a loading host `
+ + 'cannot hand compiled code — the interpreter keeps it');
+ continue;
+ }
const at = bindings.index(decl.name);
if (at >= 0) byName.set(decl.name, at);
}
diff --git a/sdk/tests/aot-native-install.test.ts b/sdk/tests/aot-native-install.test.ts
index 9dd18618d..4aaa13146 100644
--- a/sdk/tests/aot-native-install.test.ts
+++ b/sdk/tests/aot-native-install.test.ts
@@ -23,6 +23,7 @@ import { describe, it, expect } from 'vitest';
import { World } from '../src/ecs/world';
import { defineComponent } from '../src/ecs/component';
import { defineSystem, SystemRunner } from '../src/ecs/system';
+import { defineEvent, EventReader, EventWriter, EventRegistry } from '../src/ecs/event';
import { Query, Mut, Changed } from '../src/ecs/query';
import { ResourceStorage } from '../src/ecs/resource';
import { engineAbiDigest, projectShapeDigest } from '../src/ecs/aot/abiDigest';
@@ -94,6 +95,59 @@ function fixture(boundNames: readonly string[]) {
return { world, runner, runtime, Drift, ...host };
}
+/**
+ * The same two systems, plus one that writes an event and one that reads one.
+ * A reader's payloads come through a QUERY slot naming the event, which is what
+ * the compiled artifact tells a host as well.
+ */
+const EVENT_MANIFEST: AotManifest = {
+ engineAbi: engineAbiDigest(8),
+ projectShapes: projectShapeDigest([{ name: 'Drift', fields: ['x'] }]),
+ systems: [
+ {
+ name: 'SendSystem', symbol: 'es_sys_Send', resources: [],
+ queries: [[{ comp: 'Drift', mut: true }]],
+ writers: [{ slot: 0, event: 'Hit', fields: ['amount'] }],
+ },
+ {
+ name: 'ReadSystem', symbol: 'es_sys_Read', resources: [],
+ queries: [[{ comp: 'Hit', mut: false }], [{ comp: 'Drift', mut: true }]],
+ readers: [{ slot: 0, event: 'Hit', fields: ['amount'] }],
+ },
+ {
+ name: 'PlainSystem', symbol: 'es_sys_Plain', resources: [],
+ queries: [[{ comp: 'Drift', mut: true }]],
+ },
+ ],
+};
+
+function eventFixture() {
+ const Drift = declareDrift();
+ const Hit = defineEvent<{ amount: number }>('Hit');
+ const events = new EventRegistry();
+ const world = new World();
+ const runner = new SystemRunner(world, new ResourceStorage(), events);
+ const order = EVENT_MANIFEST.systems.map((s) => s.name);
+ const calls: string[] = [];
+ // A host that can name and run EVERY system in the module — so what keeps
+ // its hands off the two event systems is this side's decision, not its
+ // inability, which is the thing under test.
+ const bindings: NativeAotBindings = {
+ install: () => order.length,
+ index: (name) => order.indexOf(name),
+ bound: () => true,
+ scriptRows: () => true,
+ resource: () => true,
+ run: (i) => { calls.push(order[i] ?? `#${i}`); return 0; },
+ reset: () => {},
+ };
+ const runtime = installNativeAot({
+ world, runner, modulePath: 'systems.dll', manifest: EVENT_MANIFEST,
+ heap: fakeHeap(), bindings,
+ });
+ return { world, runner, runtime, Drift, Hit, events, calls };
+}
+
describe('installing compiled systems on a host that loads a library', () => {
it('a system the host cannot run is interpreted that frame, not skipped', () => {
const f = fixture(['DriftSystem']);
@@ -210,3 +264,64 @@ describe('installing compiled systems on a host that loads a library', () => {
expect(watched.at(-1)).toBe(1);
});
});
+
+
+/**
+ * A native host's ctx carries `events = 0` (AotHost.hpp) and the emitted C
+ * dereferences it before it looks at a row: probed against a real artifact, a
+ * writer-only system with ZERO rows segfaults on entry. Nothing stopped it —
+ * the takeover question was "did the library export this symbol".
+ */
+describe('a capability a loading host cannot hand compiled code', () => {
+ it('leaves an event WRITER to the interpreter, and the event still arrives', () => {
+ const f = eventFixture();
+ expect(f.runtime).not.toBeNull();
+
+ let sent = 0;
+ const send = defineSystem([Query(Mut(f.Drift)), EventWriter(f.Hit)], (_q, out) => {
+ sent++;
+ out.send({ amount: 7 });
+ }, { name: 'SendSystem' });
+ const seen: number[] = [];
+ const watch = defineSystem([EventReader(f.Hit)], (hits) => {
+ for (const h of hits) seen.push(h.amount);
+ }, { name: 'WatchSystem' });
+
+ const entity = f.world.spawn();
+ f.world.insert(entity, f.Drift, { x: 0 });
+ f.runner.run(send);
+ f.events.swapAll();
+ f.runner.run(watch);
+
+ expect(f.calls).not.toContain('SendSystem');
+ expect(sent).toBe(1);
+ expect(seen).toEqual([7]);
+ });
+
+ it('leaves an event READER to the interpreter, which is the half that would go quiet', () => {
+ const f = eventFixture();
+ f.events.getBus(f.Hit).send({ amount: 3 });
+ f.events.swapAll();
+
+ const seen: number[] = [];
+ const read = defineSystem([EventReader(f.Hit), Query(Mut(f.Drift))], (hits) => {
+ for (const h of hits) seen.push(h.amount);
+ }, { name: 'ReadSystem' });
+ f.runner.run(read);
+
+ expect(f.calls).not.toContain('ReadSystem');
+ expect(seen).toEqual([3]);
+ });
+
+ it('and takes the system that needs none of it', () => {
+ const f = eventFixture();
+ const plain = defineSystem([Query(Mut(f.Drift))], () => {
+ throw new Error('the closure must not run when the host took this one');
+ }, { name: 'PlainSystem' });
+ const entity = f.world.spawn();
+ f.world.insert(entity, f.Drift, { x: 0 });
+ f.runner.run(plain);
+
+ expect(f.calls).toEqual(['PlainSystem']);
+ });
+});