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(aot): a service becomes memory, and a row loop gains its exits

esengine37f0a693f1e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c6c3070c..f444de0a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,16 @@ published separately; it ships inside the editor.
anything is registered, and the message says which one moved: rebuild the
module, or rebuild the project.
+ A system may also declare `ResMut(X)` to write a resource, and may ask a
+ SERVICE a question with a compile-time key: `input.isKeyDown('KeyW')` compiles
+ to a load and a mask, because the runtime mirrors the answer the method would
+ have given into one bit. That is what makes input-reading systems compilable
+ at all — 117 of the 120 such calls in the examples pass a literal. A key the
+ table does not declare, or one computed at run time, is refused and the system
+ keeps interpreting. `Input` and `UICameraInfo` gained the layout that needs;
+ `UICameraInfo.viewProjection` is deliberately not in it, since a member has to
+ have a fixed width.
+
Hosts embedding the runtime themselves can do the same through
`App.useCompiledSystems`, and `App.compiledSystems` reports which systems are
running compiled and how many twin calls have happened (both
diff --git a/compiler/src/abi.ts b/compiler/src/abi.ts
index 572f2d61e..e9b169eb4 100644
--- a/compiler/src/abi.ts
+++ b/compiler/src/abi.ts
@@ -24,6 +24,7 @@ import {
engineAbiDigest, projectShapeDigest, type ShapeDigestInput,
} from '../../sdk/src/ecs/aot/abiDigest';
import { resourceNames } from './builtins';
+import { resourceBlockBytes, resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';
import { encBytes, type CompShape, type EirSystem, type EirType, type LeafEnc, type QueryArg } from './eir';
import { runSystemOn, type EirHost, type Fns } from './interp';
@@ -137,6 +138,19 @@ export class AbiMemory {
return base;
}
+ /**
+ * Set one bit of a service's mirror, as a host would after asking it. The
+ * bit is chosen the same way the compiled code chooses it, which is the
+ * point: a test placing it by hand would be a third answer.
+ */
+ setResourceBit(name: string, method: string, key: string | number, on: boolean): void {
+ const at = resourceMethodBit(name, method, key);
+ if (!at) throw new Error(`ABI: '${name}.${method}' is not a declared service question`);
+ const byte = this.resourceBase(name) + at.offset;
+ if (on) this.u8[byte] = (this.u8[byte]! | (1 << at.bit));
+ else this.u8[byte] = (this.u8[byte]! & ~(1 << at.bit));
+ }
+
private writeLeaf(shape: FieldOffsets, base: number, path: string, v: number | boolean): void {
const leaf = shape.leaves.get(path);
if (!leaf) throw new Error(`ABI: no field '${path}'`);
@@ -322,6 +336,17 @@ export function abiHost(mem: AbiMemory, layout: AbiLayout, plan: SysPlan, call:
const leaf = leafAt(owner, path);
store(mem, (base as number) + leaf.byteOffset, leaf.enc, v);
},
+ service(name, method, key) {
+ // The mirrored answer, read as one bit — which is exactly what the
+ // compiled code does, and the reason the interpreter over live
+ // objects has to agree with it.
+ const at = resourceMethodBit(name, method, key);
+ if (!at) throw new Error(`ABI: '${name}.${method}' is not a declared service question`);
+ const k = plan.resources.findIndex((r) => r.name === name);
+ if (k < 0) throw new Error(`ABI: '${plan.system}' asks a resource it did not declare`);
+ const base = mem.u32[(resTable >> 2) + k]!;
+ return ((mem.u8[base + at.offset]! >> at.bit) & 1) !== 0;
+ },
resource(name) {
const k = plan.resources.findIndex((r) => r.name === name);
if (k < 0) throw new Error(`ABI: '${plan.system}' reads a resource it did not declare`);
@@ -441,10 +466,16 @@ export function packLayout(shapes: ReadonlyMap<string, CompShape>): AbiLayout {
leaves.set(path, { byteOffset: at, enc: spec.enc, type: spec.type });
end = Math.max(end, at + width);
}
- const packed: FieldOffsets = { leaves, stride: Math.max(8, (end + 7) & ~7) };
// A resource is addressed by field exactly as a component is, so the two
- // tables differ only in which one a `Res(...)` parameter looks in.
- (shape.storage === 'host' && RESOURCES.has(name) ? resources : comps).set(name, packed);
+ // tables differ only in which one a `Res(...)` parameter looks in. Its
+ // SIZE is not derived here though: a service's bit sets are members no
+ // field walk sees, and a block sized to the last scalar is too small.
+ const isResource = shape.storage === 'host' && RESOURCES.has(name);
+ const packed: FieldOffsets = {
+ leaves,
+ stride: isResource ? resourceBlockBytes(name) : Math.max(8, (end + 7) & ~7),
+ };
+ (isResource ? resources : comps).set(name, packed);
}
return { comps, resources };
}
diff --git a/compiler/src/builtins.ts b/compiler/src/builtins.ts
index cfe8323e1..5e175d2de 100644
--- a/compiler/src/builtins.ts
+++ b/compiler/src/builtins.ts
@@ -14,7 +14,7 @@
* file exists to avoid.
*/
import { PTR_LAYOUTS } from '../../sdk/src/wasm/ptrLayouts.generated';
-import { RESOURCE_NAMES, RESOURCE_SHAPES } from '../../sdk/src/ecs/resourceShapes';
+import { RESOURCE_NAMES, RESOURCE_SHAPES, resourceLayout } from '../../sdk/src/ecs/resourceShapes';
import { BOOL, F64, HOST_ENC, type CompShape, type FieldSpec, type LeafEnc } from './eir';
/** Leaf member names per composite field, in memory order. Every one is f32. */
@@ -63,8 +63,8 @@ export function builtinShapes(): Map<string, CompShape> {
// engine-stored. Nothing downstream has to ask by name.
out.set(name, { name, storage: 'engine', fields });
}
- for (const [name, shape] of Object.entries(RESOURCE_SHAPES)) {
- out.set(name, resourceShape(name, shape));
+ for (const name of Object.keys(RESOURCE_SHAPES)) {
+ out.set(name, resourceShape(name));
}
return out;
}
@@ -74,13 +74,18 @@ export function builtinShapes(): Map<string, CompShape> {
* throughout and laid out by the ABI rather than by EHT. The field ORDER is the
* declaration order, and it IS the layout.
*/
-function resourceShape(name: string, shape: Readonly<Record<string, number | boolean>>): CompShape {
+function resourceShape(name: string): CompShape {
+ const declared = RESOURCE_SHAPES[name]!.fields;
const fields = new Map<string, FieldSpec>();
- for (const [field, value] of Object.entries(shape)) {
- fields.set(field, {
- type: typeof value === 'boolean' ? BOOL : F64,
+ // Offsets come from the shared layout rather than being repacked here: the
+ // runtime mirrors a resource at those exact offsets, and a second answer to
+ // where a field is would be read as a different field.
+ for (const member of resourceLayout(name) ?? []) {
+ if (member.kind !== 'scalar') continue;
+ fields.set(member.name, {
+ type: typeof declared[member.name] === 'boolean' ? BOOL : F64,
enc: HOST_ENC,
- offset: null,
+ offset: member.offset,
});
}
return { name, storage: 'host', fields };
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.ts
index 291c7430b..f8220f521 100644
--- a/compiler/src/codegen.ts
+++ b/compiler/src/codegen.ts
@@ -27,6 +27,7 @@
* `-ffp-contract=off` in CFLAGS — a fused multiply-add is more accurate
* than what JS computes, and more accurate is still different.
*/
+import { resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';
import {
CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS, CMD_DESPAWN, CMD_REMOVE,
abiHandshake, planFor,
@@ -205,6 +206,8 @@ static inline void es_set_f64(unsigned char *p, double v) { memcpy(p, &v, 8); }
/* A bool in the C++ structs is ONE byte. Reading it as a float would read three
bytes of whatever follows it, which is a value rather than an error. */
static inline int es_bool(const unsigned char *p) { return *p != 0; }
+/* One question of a service, as the host mirrored it: a byte and a mask. */
+static inline int es_bit(const unsigned char *p, unsigned bit) { return (*p >> bit) & 1u; }
static inline void es_set_bool(unsigned char *p, int v) { *p = (unsigned char)(v ? 1 : 0); }
/* ---------------------------------------------------------------------------
@@ -363,12 +366,16 @@ function readsOf(stmts: readonly Stmt[], out: Set<number>): void {
case 'neg': case 'not': expr(e.v); break;
case 'bin': case 'logic': expr(e.l); expr(e.r); break;
case 'select': expr(e.cond); expr(e.then); expr(e.otherwise); break;
+ // The receiver IS read: the bit is at an offset from its base.
+ case 'svc': place(e.base); break;
case 'call': for (const a of e.args) expr(a); break;
}
};
for (const s of stmts) {
switch (s.s) {
- case 'let': case 'return': expr(s.value); break;
+ case 'let': expr(s.value); break;
+ case 'return': if (s.value) expr(s.value); break;
+ case 'continue': case 'break': break;
// A field target READS its base to compute the address; a local
// target does not, which is exactly the distinction that decides
// whether a bound row local is dead.
@@ -479,6 +486,13 @@ class Emitter {
return typeof e.value === 'boolean' ? (e.value ? '1' : '0') : num(e.value);
case 'read':
return this.read(e.place, e.type);
+ case 'svc': {
+ const at = e.base.p === 'local'
+ ? resourceMethodBit(this.owners.get(e.base.id) ?? '', e.method, e.key) : null;
+ if (!at) throw new Error(`codegen: '${e.method}' is not a declared service question`);
+ if (e.base.p !== 'local') throw new Error('codegen: a service receiver must be a local');
+ return `es_bit(${cName(this.local(e.base.id))} + ${at.offset}u, ${at.bit}u)`;
+ }
case 'neg':
return `(-${coerce(this.expr(e.v), e.v.type, F64)})`;
case 'not':
@@ -517,8 +531,11 @@ class Emitter {
break;
}
case 'return':
- this.line(indent, `return ${this.expr(s.value)};`);
+ this.line(indent, s.value ? `return ${this.expr(s.value)};` : 'return;');
break;
+ // A row loop IS the C for-loop, so these need no translation.
+ case 'continue': this.line(indent, 'continue;'); break;
+ case 'break': this.line(indent, 'break;'); break;
case 'assign': {
if (s.target.p === 'local') {
const l = this.local(s.target.id);
@@ -826,7 +843,8 @@ function calledFns(module: EirModule, systems: readonly EirSystem[]): string[] {
const visit = (stmts: readonly Stmt[]): void => {
for (const s of stmts) {
switch (s.s) {
- case 'let': case 'return': case 'assign': visitExpr(s.value); break;
+ case 'let': case 'assign': visitExpr(s.value); break;
+ case 'return': if (s.value) visitExpr(s.value); break;
case 'emit': for (const a of s.args) visitExpr(a); break;
case 'if': visitExpr(s.cond); visit(s.then); visit(s.otherwise); break;
case 'rowLoop': visit(s.body); break;
diff --git a/compiler/src/eir.ts b/compiler/src/eir.ts
index 08c1626e3..5fce76a46 100644
--- a/compiler/src/eir.ts
+++ b/compiler/src/eir.ts
@@ -72,6 +72,13 @@ export type Expr =
readonly otherwise: Expr;
readonly type: EirType;
}
+ /**
+ * `resource.method(key)` with a compile-time key: a SERVICE asked one
+ * question. Kept as itself rather than lowered here, because the backends
+ * answer it differently — an interpreter over live objects calls the method,
+ * and compiled code reads the bit a host mirrored the answer into.
+ */
+ | { readonly e: 'svc'; readonly base: Place; readonly method: string; readonly key: string | number; readonly type: EirType }
/** A call. One node, parameterised by target — as `emit` is by record. */
| { readonly e: 'call'; readonly target: CallTarget; readonly args: readonly Expr[]; readonly type: EirType };
@@ -105,7 +112,11 @@ export type Stmt =
readonly body: readonly Stmt[];
}
| { readonly s: 'assign'; readonly target: Place; readonly value: Expr }
- | { readonly s: 'return'; readonly value: Expr }
+ /** `value` is null for a SYSTEM's early exit; a module function returns one. */
+ | { readonly s: 'return'; readonly value: Expr | null }
+ /** Only inside a row loop, where they mean the next row and no more rows. */
+ | { readonly s: 'continue' }
+ | { readonly s: 'break' }
| { readonly s: 'let'; readonly id: number; readonly value: Expr }
/**
* Append one record to a channel. Commands are a QUEUE the runner flushes at
@@ -231,6 +242,8 @@ function exprText(e: Expr, locals: ReadonlyMap<number, Local>): string {
case 'not': return `!${exprText(e.v, locals)}`;
case 'select':
return `(${exprText(e.cond, locals)} ? ${exprText(e.then, locals)} : ${exprText(e.otherwise, locals)})`;
+ case 'svc':
+ return `${placeName(e.base, locals)}.${e.method}(${JSON.stringify(e.key)})`;
case 'call': {
const name = e.target.k === 'math' ? e.target.fn : e.target.name;
return `${name}(${e.args.map((a) => exprText(a, locals)).join(', ')})`;
@@ -252,7 +265,9 @@ function stmtText(s: Stmt, locals: ReadonlyMap<number, Local>, indent: string):
case 'let':
return [`${indent}let ${locals.get(s.id)?.name ?? `%${s.id}`} = ${exprText(s.value, locals)}`];
case 'return':
- return [`${indent}return ${exprText(s.value, locals)}`];
+ return [s.value ? `${indent}return ${exprText(s.value, locals)}` : `${indent}return`];
+ case 'continue': return [`${indent}continue`];
+ case 'break': return [`${indent}break`];
case 'emit':
return [`${indent}emit ${placeName(s.channel, locals)}.${s.record}(`
+ `${s.args.map((a) => exprText(a, locals)).join(', ')})`];
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.ts
index 0595e0b4c..905fa3695 100644
--- a/compiler/src/frontend.ts
+++ b/compiler/src/frontend.ts
@@ -26,6 +26,7 @@
*/
import { sep } from 'node:path';
import ts from 'typescript';
+import { resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';
import {
BOOL, ENTITY, F64, HOST_ENC,
type CompShape, type EirModule, type EirSystem, type EirType,
@@ -177,6 +178,14 @@ function annotatedType(node: ts.TypeNode): EirType | null {
return null;
}
+/** A string or integer literal argument, or null when it is neither. */
+function literalKey(node: ts.Expression | undefined): string | number | null {
+ if (!node) return null;
+ if (ts.isStringLiteral(node)) return node.text;
+ if (ts.isNumericLiteral(node)) return Number(node.text);
+ return null;
+}
+
/**
* `permanent` = the contract has no place for it, not a
* todo. `pending` = the contract admits it, nobody lowered it yet. Default is
@@ -367,6 +376,20 @@ class SystemLowerer {
if (ts.isBlock(node)) return this.scoped(() => node.statements.flatMap((s) => this.stmt(s)));
if (ts.isVariableStatement(node)) return this.declarations(node);
if (ts.isIfStatement(node)) return [this.ifStmt(node)];
+ // A bare `return` leaves the SYSTEM; one with a value belongs to a
+ // module function, which `fn()` lowers on its own.
+ if (ts.isReturnStatement(node)) {
+ if (node.expression) throw new NotInSubset(node, 'a system returns no value');
+ return [{ s: 'return', value: null }];
+ }
+ if (ts.isContinueStatement(node)) {
+ if (node.label) throw new NotInSubset(node, 'a labelled continue is not lowered');
+ return [{ s: 'continue' }];
+ }
+ if (ts.isBreakStatement(node)) {
+ if (node.label) throw new NotInSubset(node, 'a labelled break is not lowered');
+ return [{ s: 'break' }];
+ }
throw new NotInSubset(node, `${ts.SyntaxKind[node.kind]} is not a statement this subset lowers`);
}
@@ -598,9 +621,19 @@ class SystemLowerer {
? this.tryLookup(callee.expression.text)
: null;
if (recv && recv.type.k === 'res') {
- throw new NotInSubset(node,
- `${recv.name}.${(callee as ts.PropertyAccessExpression).name.text}(…) is a resource method`
- + ' — the contract wants it read as memory, and nothing lowers it yet');
+ const method = (callee as ts.PropertyAccessExpression).name.text;
+ const key = literalKey(node.arguments[0]);
+ // A service question the shape declares: the host mirrors the
+ // answer into a bit, so this is a load and a mask. The KEY has
+ // to be a literal — a bit index is chosen at compile time.
+ if (node.arguments.length === 1 && key !== null
+ && resourceMethodBit(recv.type.name, method, key)) {
+ return { e: 'svc', base: { p: 'local', id: recv.id }, method, key, type: BOOL };
+ }
+ throw new NotInSubset(node, resourceMethodBit(recv.type.name, method, '') !== null
+ ? `${recv.name}.${method}(…) needs a literal key the shape declares`
+ : `${recv.name}.${method}(…) is a resource method`
+ + ' — the contract wants it read as memory, and nothing lowers it yet');
}
throw new NotInSubset(node, 'CallExpression is not an expression this subset lowers', 'permanent');
}
diff --git a/compiler/src/inline.ts b/compiler/src/inline.ts
index 3d1f36f83..5f97956a2 100644
--- a/compiler/src/inline.ts
+++ b/compiler/src/inline.ts
@@ -50,7 +50,8 @@ function walkExprs(stmts: readonly Stmt[], visit: (e: Expr) => void): void {
};
for (const s of stmts) {
switch (s.s) {
- case 'let': case 'return': expr(s.value); break;
+ case 'let': expr(s.value); break;
+ case 'return': if (s.value) expr(s.value); break;
case 'assign': expr(s.value); break;
case 'emit': for (const a of s.args) expr(a); break;
case 'if': expr(s.cond); walkExprs(s.then, visit); walkExprs(s.otherwise, visit); break;
@@ -93,7 +94,8 @@ class Inliner {
private stmt(s: Stmt): Stmt {
switch (s.s) {
case 'let': return { ...s, value: this.expr(s.value) };
- case 'return': return { ...s, value: this.expr(s.value) };
+ case 'return': return s.value ? { ...s, value: this.expr(s.value) } : s;
+ case 'continue': case 'break': return s;
case 'assign': return { ...s, value: this.expr(s.value) };
case 'emit': return { ...s, args: s.args.map((a) => this.expr(a)) };
case 'if': return {
@@ -110,7 +112,7 @@ class Inliner {
private expr(e: Expr): Expr {
switch (e.e) {
- case 'const': case 'read': return e;
+ case 'const': case 'read': case 'svc': return e;
case 'neg': return { ...e, v: this.expr(e.v) };
case 'not': return { ...e, v: this.expr(e.v) };
case 'bin': return { ...e, l: this.expr(e.l), r: this.expr(e.r) };
@@ -129,7 +131,7 @@ class Inliner {
subst.set(p.id, { e: 'read', place: { p: 'local', id: tmp.id }, type: p.type });
});
const only = def.body[0];
- if (!only || only.s !== 'return') return { ...e, args };
+ if (!only || only.s !== 'return' || !only.value) return { ...e, args };
// The body is one `return <expr>`, so inlining is substitution.
return this.expr(substitute(only.value, subst));
}
@@ -143,6 +145,9 @@ function substitute(e: Expr, subst: ReadonlyMap<number, Expr>): Expr {
case 'const': return e;
case 'read':
return e.place.p === 'local' ? (subst.get(e.place.id) ?? e) : e;
+ // A service question is asked of a PARAMETER, which inlining never
+ // rebinds — a module function cannot take one.
+ case 'svc': return e;
case 'neg': return { ...e, v: substitute(e.v, subst) };
case 'not': return { ...e, v: substitute(e.v, subst) };
case 'bin': return { ...e, l: substitute(e.l, subst), r: substitute(e.r, subst) };
diff --git a/compiler/src/interp.ts b/compiler/src/interp.ts
index e5f841dd9..3f15f268f 100644
--- a/compiler/src/interp.ts
+++ b/compiler/src/interp.ts
@@ -34,6 +34,12 @@ export interface EirHost {
writeField(base: unknown, comp: string, path: readonly string[], v: number | boolean): void;
/** An opaque base for a resource, addressed by field like a component. */
resource(name: string): unknown;
+ /**
+ * `resource.method(key)`. The two hosts answer it differently and that is
+ * the point: one calls the live object, the other reads the bit a host
+ * mirrored the answer into. Agreeing is what the differential proves.
+ */
+ service(resource: string, method: string, key: string | number): boolean;
emit(record: string, args: readonly (number | boolean)[]): void;
/** Called once after the body, where the SDK's runner flushes. */
flush(): void;
@@ -100,6 +106,11 @@ function evalExpr(e: Expr, frame: Frame, fns: Fns, host: EirHost, owners: Owners
case 'not': return !(evalExpr(e.v, frame, fns, host, owners) as boolean);
case 'select':
return evalExpr(e.cond, frame, fns, host, owners) ? evalExpr(e.then, frame, fns, host, owners) : evalExpr(e.otherwise, frame, fns, host, owners);
+ case 'svc': {
+ const owner = owners.get((e.base as { id: number }).id);
+ if (!owner) throw new Error(`EIR: '${e.method}' called on an unbound receiver`);
+ return host.service(owner, e.method, e.key);
+ }
case 'call': {
const a = e.args.map((x) => evalExpr(x, frame, fns, host, owners));
if (e.target.k === 'math') {
@@ -113,7 +124,11 @@ function evalExpr(e: Expr, frame: Frame, fns: Fns, host: EirHost, owners: Owners
const inner = new Frame();
def.params.forEach((p, i) => inner.set(p.id, a[i]));
const out = exec(def.body, inner, fns, host, owners);
- if (out === undefined) throw new Error(`EIR: '${def.name}' returned nothing`);
+ // A module function's body is one `return <expr>`; the control-flow
+ // exits belong to a system and cannot reach here.
+ if (typeof out !== 'number' && typeof out !== 'boolean') {
+ throw new Error(`EIR: '${def.name}' returned nothing`);
+ }
return out;
}
case 'logic': {
@@ -145,13 +160,26 @@ function evalExpr(e: Expr, frame: Frame, fns: Fns, host: EirHost, owners: Owners
/** Entities carrying every component the query names, in world order. */
/** Rows the query matches, from the host. */
+/**
+ * How a block ended. A value is a module function returning one; the three
+ * symbols are control flow, and only a row loop consumes two of them — anything
+ * else passes them up, which is what makes `continue` inside an `if` work.
+ */
+const LEFT = Symbol('return');
+const NEXT_ROW = Symbol('continue');
+const NO_MORE_ROWS = Symbol('break');
+
+type Exit = number | boolean | undefined | typeof LEFT | typeof NEXT_ROW | typeof NO_MORE_ROWS;
+
function exec(
stmts: readonly Stmt[], frame: Frame, fns: Fns, host: EirHost, owners: Owners,
-): number | boolean | undefined {
+): Exit {
for (const s of stmts) {
switch (s.s) {
case 'return':
- return evalExpr(s.value, frame, fns, host, owners);
+ return s.value === null ? LEFT : evalExpr(s.value, frame, fns, host, owners);
+ case 'continue': return NEXT_ROW;
+ case 'break': return NO_MORE_ROWS;
case 'let':
frame.set(s.id, evalExpr(s.value, frame, fns, host, owners));
break;
@@ -174,7 +202,9 @@ function exec(
if (s.entity !== null) frame.set(s.entity, row.entity);
s.binds.forEach((id, i) => frame.set(id, row.binds[i]));
const out = exec(s.body, frame, fns, host, owners);
- if (out !== undefined) return out;
+ if (out === NEXT_ROW || out === undefined) continue;
+ if (out === NO_MORE_ROWS) break;
+ return out;
}
break;
}
@@ -237,6 +267,13 @@ export function jsHost(world: EirWorld): EirHost {
if (!row) throw new Error(`EIR: no resource '${name}' in the world`);
return row;
},
+ service(name, method, key) {
+ // Over live objects there is nothing to mirror: ask the service.
+ const row = world.resources.get(name) as Record<string, unknown> | undefined;
+ const fn = row?.[method];
+ if (typeof fn !== 'function') throw new Error(`EIR: resource '${name}' has no method '${method}'`);
+ return (fn as (k: unknown) => unknown).call(row, key) === true;
+ },
emit(record, args) {
queued.push({ record, args });
},
diff --git a/compiler/src/verify.ts b/compiler/src/verify.ts
index ad6701028..6380b456c 100644
--- a/compiler/src/verify.ts
+++ b/compiler/src/verify.ts
@@ -13,6 +13,7 @@
* and the failure this catches is a frontend that lowered something
* wrong, not a source file that was outside the subset.
*/
+import { resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';
import {
MATH_FNS,
type CompShape, type EirFn, type EirSystem, type EirType, type Expr, type Local, type Place, type Stmt,
@@ -26,6 +27,8 @@ export interface VerifyError {
class Verifier {
private readonly byId = new Map<number, Local>();
+ /** Row loops entered, so a `continue` can be asked whether it has a target. */
+ private loopDepth = 0;
readonly errors: VerifyError[] = [];
constructor(
@@ -84,6 +87,21 @@ class Verifier {
}
return t;
}
+ case 'svc': {
+ const base = this.placeType(e.base);
+ if (base && base.k !== 'res') {
+ this.fail(`'${e.method}(…)' called on a ${typeName(base)}`);
+ return null;
+ }
+ // Re-asked of the shape rather than trusted from the frontend:
+ // an undeclared method has no bit, and reading a bit that was
+ // never mirrored answers zero instead of failing.
+ if (base && !resourceMethodBit(base.name, e.method, e.key)) {
+ this.fail(`'${base.name}.${e.method}(${JSON.stringify(e.key)})' is not a declared service question`);
+ }
+ if (e.type.k !== 'bool') this.fail(`'${e.method}(…)' is declared ${typeName(e.type)}, not bool`);
+ return e.type;
+ }
case 'neg': {
const t = this.exprType(e.v);
if (t && t.k !== 'f64') this.fail(`negation of a ${typeName(t)}`);
@@ -147,6 +165,14 @@ class Verifier {
stmt(s: Stmt): void {
switch (s.s) {
+ // A jump out of a row loop that is not in one has no target: C would
+ // take it to whatever encloses the emitted code instead.
+ case 'continue': case 'break':
+ if (this.loopDepth === 0) this.fail(`'${s.s}' outside a row loop`);
+ break;
+ case 'return':
+ if (s.value !== null) this.fail('a system statement returns a value');
+ break;
case 'let': {
const declared = this.local(s.id)?.type;
const actual = this.exprType(s.value);
@@ -213,7 +239,9 @@ class Verifier {
const l = this.local(s.entity);
if (l && l.type.k !== 'entity') this.fail(`row entity bound as ${typeName(l.type)}`);
}
+ this.loopDepth++;
for (const b of s.body) this.stmt(b);
+ this.loopDepth--;
break;
}
}
diff --git a/compiler/tests/codegen.test.ts b/compiler/tests/codegen.test.ts
index d14bd48fa..353b3a11c 100644
--- a/compiler/tests/codegen.test.ts
+++ b/compiler/tests/codegen.test.ts
@@ -45,7 +45,7 @@ import { F64, type EirSystem } from '../src/eir';
import type { Row } from '../src/interp';
import { moveSystem } from '../../examples/ecs-basics/src/systems/move';
-import { driftSystem } from './fixtures/in-subset';
+import { driftSystem, gateSystem } from './fixtures/in-subset';
import { PROBE } from './probe';
import { builtinShapes as shapesForPins } from '../src/builtins';
import type { StubSystem } from './stubs/esengine';
@@ -295,6 +295,11 @@ function movedWorld(layout: AbiLayout): AbiMemory {
function fixtureWorld(layout: AbiLayout): AbiMemory {
const mem = new AbiMemory(layout, IMAGE);
mem.addResource('Time', { delta: 1 / 30, elapsed: 0 });
+ // A service, mirrored: the same two answers the interpreter's fake object
+ // gives, placed the way a host places them.
+ mem.addResource('Input', {});
+ mem.setResourceBit('Input', 'isKeyDown', 'KeyW', true);
+ mem.setResourceBit('Input', 'isKeyPressed', 'Space', true);
for (let i = 1; i <= N; i++) {
const s = seed(i);
mem.addComponent('Transform', i, { 'position.x': s['tx']!, 'position.y': s['ty']! });
@@ -380,7 +385,7 @@ describe('the emitted C says what the interpreter says', () => {
// ternaries, folded module constants with a shadowing local, an inlined
// helper, and the Math arguments where libm and ECMAScript disagree.
for (const name of ['FixtureDrift', 'FixtureClampSys', 'FixtureTuned', 'FixtureHelpers',
- 'FixtureMathOps', 'FixtureCamera']) {
+ 'FixtureMathOps', 'FixtureCamera', 'FixtureGate']) {
it(`${name}: the whole image agrees with the interpreter`, () => {
const sys = systemOf(fixtures, name);
const layout = packLayout(fixtures.module.comps);
@@ -397,6 +402,42 @@ describe('the emitted C says what the interpreter says', () => {
});
}
+ /**
+ * The one comparison that judges the MIRROR. Everything else has both sides
+ * reading bits; here the C reads a bit and node calls the method, so they
+ * agree only if the host placed the answer where the compiler expects it.
+ */
+ it('FixtureGate: a bit the host set answers what the method answers', () => {
+ const gate = systemOf(fixtures, 'FixtureGate');
+ const layout = packLayout(fixtures.module.comps);
+ const exe = build(join(tmp, 'gate-node'), emitC(fixtures.module, layout, [gate]), cSymbol('FixtureGate'));
+
+ const mem = fixtureWorld(layout);
+ const drifts = new Map<number, Row>();
+ const entities: number[] = [];
+ for (let i = 1; i <= N; i++) {
+ entities.push(i);
+ drifts.set(i, { rate: seed(i)['rate']!, wrap: 100, enabled: i % 4 !== 0 });
+ }
+ // The object the bits were mirrored FROM, answering by method.
+ const input = { isKeyDown: (k: string) => k === 'KeyW', isKeyPressed: (k: string) => k === 'Space' };
+ const stub = (gateSystem as unknown as StubSystem).fn as unknown as (q: unknown, i: unknown) => void;
+
+ for (let f = 0; f < FRAMES; f++) {
+ frameOfC(exe, mem, gate);
+ stub({
+ *[Symbol.iterator]() { for (const e of entities) yield [e, drifts.get(e)!]; },
+ }, input);
+ }
+ for (const e of entities) {
+ expect([e, mem.read('FixtureDrift', e, 'rate')])
+ .toEqual([e, (drifts.get(e)! as { rate: number }).rate]);
+ }
+ // With the key up neither side moves, which is the `return` arriving in
+ // both — and it is a different assertion from "they agree".
+ expect(entities.some((e) => (drifts.get(e)! as { rate: number }).rate !== seed(e)['rate']!)).toBe(true);
+ });
+
it('FixtureDrift also agrees with node, not only with the interpreter', () => {
const drift = systemOf(fixtures, 'FixtureDrift');
const layout = packLayout(fixtures.module.comps);
diff --git a/compiler/tests/conformance.test.ts b/compiler/tests/conformance.test.ts
index 782d6826a..09ee4e637 100644
--- a/compiler/tests/conformance.test.ts
+++ b/compiler/tests/conformance.test.ts
@@ -22,13 +22,21 @@ import { inlineSystem } from '../src/inline';
import { builtinShapes } from '../src/builtins';
import { printSystem } from '../src/eir';
-import { driftSystem, clampSystem, tunedSystem, helperSystem, mathSystem } from './fixtures/in-subset';
+import { driftSystem, clampSystem, tunedSystem, helperSystem, mathSystem, gateSystem } from './fixtures/in-subset';
import { PROBE, probeRow } from './probe';
import type { StubSystem } from './stubs/esengine';
const FIXTURE = resolve(fileURLToPath(new URL('./fixtures/in-subset.ts', import.meta.url)));
const ENTITIES = 48;
+/** Two keys held and one not, so both answers are exercised every frame. */
+function fakeInput(): { isKeyDown(k: string): boolean; isKeyPressed(k: string): boolean } {
+ return {
+ isKeyDown: (k) => k === 'KeyW',
+ isKeyPressed: (k) => k === 'Space',
+ };
+}
+
function makeWorld(): EirWorld {
let a = 0x51ed270b >>> 0;
const rand = (): number => {
@@ -55,7 +63,12 @@ function makeWorld(): EirWorld {
return {
entities,
comps: new Map([['Transform', transforms], ['FixtureDrift', drifts]]),
- resources: new Map<string, Row>([['Time', { delta: 1 / 30, elapsed: 0 }]]),
+ resources: new Map<string, Row>([
+ ['Time', { delta: 1 / 30, elapsed: 0 }],
+ // A service, not a record: the interpreter asks it, and a compiled
+ // build reads what a host mirrored the same answers into.
+ ['Input', fakeInput() as unknown as Row],
+ ]),
};
}
@@ -77,6 +90,7 @@ const { module, diagnostics } = lowerProgram([FIXTURE], builtinShapes());
const drift = module.systems.find((s) => s.name === 'FixtureDrift');
const clamp = module.systems.find((s) => s.name === 'FixtureClampSys');
const tuned = module.systems.find((s) => s.name === 'FixtureTuned');
+const gate = module.systems.find((s) => s.name === 'FixtureGate');
describe('conformance — locals, branches, logic', () => {
it('compiles', () => {
@@ -141,6 +155,72 @@ describe('conformance — locals, branches, logic', () => {
});
});
+describe('conformance — a service question, and the ways out of a row loop', () => {
+ /** The author's own system, over the same world the interpreter walks. */
+ const runGateNative = (world: EirWorld): void => {
+ const drifts = world.comps.get('FixtureDrift')!;
+ const query = {
+ *[Symbol.iterator]() {
+ for (const e of world.entities) if (drifts.has(e)) yield [e, drifts.get(e)!];
+ },
+ };
+ (gateSystem as unknown as StubSystem).fn(query, world.resources.get('Input'));
+ };
+
+ it('compiles, and verifies', () => {
+ expect(diagnostics.filter((d) => d.system === 'FixtureGate')).toEqual([]);
+ expect(gate).toBeDefined();
+ expect(verifySystem(gate!, module.comps, module.fns)).toEqual([]);
+ });
+
+ it('reads back as the question and the jumps, not as calls', () => {
+ expect(printSystem(gate!)).toMatchInlineSnapshot(`
+ "system FixtureGate(query: query<mut FixtureDrift>, input: res<Input>) {
+ if !input.isKeyDown("KeyW") {
+ return
+ }
+ rowLoop query -> (_, d) {
+ if !d.enabled {
+ continue
+ }
+ if (d.rate > 110) {
+ break
+ }
+ d.rate = (d.rate + (input.isKeyPressed("Space") ? 2 : 1))
+ }
+ }"
+ `);
+ });
+
+ it('agrees with node over 40 frames', () => {
+ const byNode = makeWorld();
+ const byEir = makeWorld();
+ for (let f = 0; f < 40; f++) {
+ runGateNative(byNode);
+ runSystem(gate!, byEir);
+ }
+ expect(byEir.comps.get('FixtureDrift')).toEqual(byNode.comps.get('FixtureDrift'));
+ });
+
+ it('took each exit — an agreement over an untaken jump proves nothing', () => {
+ const world = makeWorld();
+ const rows = [...world.comps.get('FixtureDrift')!.values()] as { rate: number; enabled: boolean }[];
+ // `continue`: rows with enabled false, which must never move.
+ const skipped = rows.filter((r) => !r.enabled).map((r) => r.rate);
+ // `break`: a row over the limit exists, so the loop ends early and the
+ // rows after it are untouched this frame.
+ expect(rows.some((r) => r.rate > 110)).toBe(true);
+ for (let f = 0; f < 40; f++) runSystem(gate!, world);
+ expect(rows.filter((r) => !r.enabled).map((r) => r.rate)).toEqual(skipped);
+ // `return`: with the key up, nothing at all moves.
+ const quiet = makeWorld();
+ quiet.resources.set('Input', { isKeyDown: () => false, isKeyPressed: () => false } as never);
+ const before = JSON.stringify([...quiet.comps.get('FixtureDrift')!.values()]);
+ for (let f = 0; f < 4; f++) runSystem(gate!, quiet);
+ expect(JSON.stringify([...quiet.comps.get('FixtureDrift')!.values()])).toBe(before);
+ });
+});
+
describe('conformance — ternaries and exact Math', () => {
function clampWorld(): EirWorld {
let a = 0x9e3779b1 >>> 0;
diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.ts
index 27d9b36c2..a284340cf 100644
--- a/compiler/tests/coverage.test.ts
+++ b/compiler/tests/coverage.test.ts
@@ -24,6 +24,13 @@
* the top line usually reveals the next one rather than raising the
* number.
*
+ * Which is also why the CEILING falls as pending work lands. It counts
+ * a system reachable when every refusal against it is pending, and it
+ * can only see the first — so it is an optimistic estimate that gets
+ * less optimistic as systems get further and meet what is permanent.
+ * A drop there is the number becoming true, not the corpus losing
+ * ground; the floor below it moves with a reason in the commit.
+ *
* It also reports the CEILING: how much of the corpus the contract could
* ever take, counting a system as reachable when every refusal against
* it is `pending` rather than `permanent`. That number is what says the
@@ -43,9 +50,9 @@ import { builtinShapes } from '../src/builtins';
const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));
/** Per-frame systems only. See the file header before lowering these. */
-const FRAME_FLOOR = 9;
+const FRAME_FLOOR = 12;
/** Per-frame systems the contract could take once the pending work is done. */
-const CEILING_FLOOR = 88;
+const CEILING_FLOOR = 75;
function walk(dir: string, out: string[] = []): string[] {
for (const name of readdirSync(dir)) {
diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.ts
index 85d6fc00a..2d5ce9783 100644
--- a/compiler/tests/fixtures/in-subset.ts
+++ b/compiler/tests/fixtures/in-subset.ts
@@ -8,7 +8,7 @@
* by conformance.test.ts — a feature the frontend lowers but nobody
* runs both ways is a feature nobody has checked.
*/
-import { defineComponent, defineSystem, Query, Mut, Res, Camera, Time, Transform } from 'esengine';
+import { defineComponent, defineSystem, Query, Mut, Res, Camera, Input, Time, Transform } from 'esengine';
export const Drift = defineComponent('FixtureDrift', { rate: 40, wrap: 100, enabled: true });
@@ -137,3 +137,22 @@ export const cameraSystem = defineSystem(
},
{ name: 'FixtureCamera' },
);
+
+/**
+ * A SERVICE question, and the three ways out of a row loop. The two sides
+ * answer `isKeyDown` differently by construction — the interpreter over live
+ * objects calls the method, compiled code reads the bit a host mirrored it
+ * into — so agreement here is the only thing that says the mirror is right.
+ */
+export const gateSystem = defineSystem(
+ [Query(Mut(Drift)), Res(Input)],
+ (query, input) => {
+ if (!input.isKeyDown('KeyW')) return;
+ for (const [, d] of query) {
+ if (!d.enabled) continue;
+ if (d.rate > 110) break;
+ d.rate = d.rate + (input.isKeyPressed('Space') ? 2 : 1);
+ }
+ },
+ { name: 'FixtureGate' },
+);
diff --git a/compiler/tests/stubs/esengine.ts b/compiler/tests/stubs/esengine.ts
index c24961b90..43d51c13c 100644
--- a/compiler/tests/stubs/esengine.ts
+++ b/compiler/tests/stubs/esengine.ts
@@ -34,6 +34,10 @@ export function Res(resource: unknown): unknown {
export function Commands(): unknown {
return { kind: 'commands' };
}
+export function ResMut(resource: unknown): unknown {
+ return { kind: 'resmut', resource };
+}
+export const Input = { _name: 'Input' };
export const Sprite = { _name: 'Sprite' };
export const Camera = { _name: 'Camera' };
export function defineSystem(
diff --git a/compiler/tsconfig.json b/compiler/tsconfig.json
index 70474cfe8..3f2e8713d 100644
--- a/compiler/tsconfig.json
+++ b/compiler/tsconfig.json
@@ -8,7 +8,6 @@
"exactOptionalPropertyTypes": true,
"noEmit": true,
"skipLibCheck": true,
- "baseUrl": ".",
"paths": { "esengine": ["./tests/stubs/esengine.ts"] },
"types": []
},
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index 7c3d97086..deaf19ee0 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -7,7 +7,7 @@
import { World } from '../ecs/world';
import { Schedule, SystemDef, SystemRunner, SystemSet, mergeOrderingEdges, rescopeSystem, type RunCondition } from '../ecs/system';
-import { BUILTIN_RESOURCES, ResourceStorage, Time, TimeData, type ResourceDef } from '../ecs/resource';
+import { builtinResource, ResourceStorage, Time, TimeData, type ResourceDef } from '../ecs/resource';
import { prepareAot, type AotHost } from '../ecs/aot/installAot';
import type { AotManifest } from '../ecs/aot/AotSystems';
import type { AotRuntime } from '../ecs/aot/AotRuntime';
@@ -631,11 +631,15 @@ export class App {
host: opts.host,
manifest: opts.manifest,
wasm: opts.wasm,
+ knowsResource: (name) => builtinResource(name) !== undefined,
resources: (name) => {
- const def = BUILTIN_RESOURCES[name];
- return def !== undefined && this.resources_.has(def)
- ? this.resources_.get(def) as Readonly<Record<string, unknown>>
- : undefined;
+ const def = builtinResource(name);
+ // `get`, not `has` then `get`: a slot holding a materialised
+ // default is what an INTERPRETED system reads, and a twin has to
+ // see the same world or the two stop being the same program.
+ return def === undefined
+ ? undefined
+ : this.resources_.get(def) as Readonly<Record<string, unknown>>;
},
});
this.runner_?.useAot(this.aot_);
diff --git a/sdk/src/ecs/aot/AotResources.ts b/sdk/src/ecs/aot/AotResources.ts
index 9ca544c87..7c73e1889 100644
--- a/sdk/src/ecs/aot/AotResources.ts
+++ b/sdk/src/ecs/aot/AotResources.ts
@@ -20,7 +20,7 @@
*/
import { POOL_SLOT_BYTES, type PoolBlock, type PoolMemory } from '../ScriptPool';
-import { resourceFields } from '../resourceShapes';
+import { resourceBitSource, resourceBlockBytes, resourceLayout } from '../resourceShapes';
/** Reads the live value of a named resource, or undefined if the world has none. */
export type ResourceReader = (name: string) => Readonly<Record<string, unknown>> | undefined;
@@ -32,7 +32,7 @@ export type ResourceReader = (name: string) => Readonly<Record<string, unknown>>
*/
export class AotResources {
private readonly blocks = new Map<string, PoolBlock>();
- private readonly views = new Map<string, Float64Array>();
+ private readonly views = new Map<string, Uint8Array>();
constructor(private readonly memory: PoolMemory, private readonly read: ResourceReader) {}
@@ -41,14 +41,14 @@ export class AotResources {
* undefined when the resource has no layout or the world has no value.
*/
addressOf(name: string): number | undefined {
- const fields = resourceFields(name);
- if (!fields) return undefined;
+ const layout = resourceLayout(name);
+ if (!layout) return undefined;
const value = this.read(name);
if (!value) return undefined;
let block = this.blocks.get(name);
if (!block) {
- block = this.memory.alloc(fields.length * POOL_SLOT_BYTES);
+ block = this.memory.alloc(resourceBlockBytes(name));
this.blocks.set(name, block);
}
// Re-viewed rather than held: allocating anything may have grown the
@@ -56,16 +56,44 @@ export class AotResources {
const buffer = this.memory.current?.(block) ?? block.buffer;
let view = this.views.get(name);
if (!view || view.buffer !== buffer) {
- view = new Float64Array(buffer, block.byteOffset, fields.length);
+ view = new Uint8Array(buffer, block.byteOffset, resourceBlockBytes(name));
this.views.set(name, view);
}
- fields.forEach((field, i) => {
- const v = value[field];
- view![i] = typeof v === 'boolean' ? (v ? 1 : 0) : (typeof v === 'number' ? v : 0);
- });
+ const f64 = new Float64Array(view.buffer, view.byteOffset, view.byteLength / POOL_SLOT_BYTES);
+ for (const member of layout) {
+ if (member.kind === 'scalar') {
+ const v = value[member.name];
+ f64[member.offset / POOL_SLOT_BYTES] =
+ typeof v === 'boolean' ? (v ? 1 : 0) : (typeof v === 'number' ? v : 0);
+ continue;
+ }
+ this.fillBits(name, member.name, member.offset, member.bits, view, value);
+ }
return block.byteOffset;
}
+ /**
+ * One bit per key, from the resource's OWN method. That is a call per key
+ * per system call — bounded by the declared table, and paid only by a system
+ * that named the resource. Reading the state behind the method instead would
+ * be cheaper and would answer a different question inside a fixed step.
+ */
+ private fillBits(
+ resource: string, set: string, offset: number, bits: number,
+ view: Uint8Array, value: Readonly<Record<string, unknown>>,
+ ): void {
+ const bytes = Math.ceil(bits / 8);
+ view.fill(0, offset, offset + bytes);
+ const source = resourceBitSource(resource, set);
+ const ask = source && value[source.method];
+ if (!source || typeof ask !== 'function') return;
+ source.keys.forEach((key, i) => {
+ if ((ask as (k: unknown) => unknown).call(value, key) === true) {
+ view[offset + (i >> 3)]! |= 1 << (i & 7);
+ }
+ });
+ }
+
/**
* Copy `name`'s block back onto the live resource, for a system that
* declared `ResMut`: a mirror nobody reads back is a write that did not
@@ -73,15 +101,20 @@ export class AotResources {
* skipped, because the block never carried it.
*/
writeBack(name: string): void {
- const fields = resourceFields(name);
+ const layout = resourceLayout(name);
const view = this.views.get(name);
const value = this.read(name) as Record<string, unknown> | undefined;
- if (!fields || !view || !value) return;
- fields.forEach((field, i) => {
- const was = value[field];
- if (typeof was === 'boolean') value[field] = view[i] !== 0;
- else if (typeof was === 'number') value[field] = view[i]!;
- });
+ if (!layout || !view || !value) return;
+ const f64 = new Float64Array(view.buffer, view.byteOffset, view.byteLength / POOL_SLOT_BYTES);
+ for (const member of layout) {
+ // Bit sets are a service's answers, not its state: there is nothing
+ // on the other side to assign back to.
+ if (member.kind !== 'scalar') continue;
+ const was = value[member.name];
+ const now = f64[member.offset / POOL_SLOT_BYTES]!;
+ if (typeof was === 'boolean') value[member.name] = now !== 0;
+ else if (typeof was === 'number') value[member.name] = now;
+ }
}
dispose(): void {
diff --git a/sdk/src/ecs/aot/AotSystems.ts b/sdk/src/ecs/aot/AotSystems.ts
index 337e02040..da057d908 100644
--- a/sdk/src/ecs/aot/AotSystems.ts
+++ b/sdk/src/ecs/aot/AotSystems.ts
@@ -90,6 +90,7 @@ export class AotSystems {
manifest: AotManifest,
exports: Readonly<Record<string, unknown>>,
resolve: (name: string) => AnyComponentDef | undefined,
+ hasResource: (name: string) => boolean = () => true,
): void {
// Two questions with two fixes, so two answers rather than one that can
// only say "something moved".
@@ -107,6 +108,14 @@ export class AotSystems {
+ `has ${shapes}. Rebuild the project — a component's fields moved under it.`);
}
for (const decl of manifest.systems) {
+ for (const r of decl.resources) {
+ // A resource with no address is not a slow path: the ctx would
+ // carry 0 and the compiled code would read whatever is there.
+ if (!hasResource(r.name)) {
+ throw new Error(`AOT module refused: '${decl.name}' reads resource `
+ + `'${r.name}', which this runtime does not have`);
+ }
+ }
const call = exports[decl.symbol];
if (typeof call !== 'function') {
throw new Error(`AOT module refused: it declares '${decl.name}' but exports no `
diff --git a/sdk/src/ecs/aot/abiDigest.ts b/sdk/src/ecs/aot/abiDigest.ts
index 5eb8db462..bcf15f96f 100644
--- a/sdk/src/ecs/aot/abiDigest.ts
+++ b/sdk/src/ecs/aot/abiDigest.ts
@@ -28,7 +28,7 @@
*/
import { PTR_LAYOUTS } from '../../wasm/ptrLayouts.generated';
-import { RESOURCE_SHAPES } from '../resourceShapes';
+import { RESOURCE_NAMES, RESOURCE_SHAPES, resourceLayout } from '../resourceShapes';
/** Sizes of the three ABI structs, in address-wide words. */
export const SYSCTX_WORDS = 6;
@@ -54,6 +54,16 @@ export interface ShapeDigestInput {
* what it ships, which is what makes this the check that can actually run.
*/
export function engineAbiDigest(addressBytes: AddressBytes): string {
+ return fnv1a64(engineAbiParts(addressBytes).join('\n'));
+}
+
+/**
+ * What the digest is taken OF, so a test can ask whether something is covered.
+ * A digest can only say two things differ; this says what it was looking at.
+ *
+ * @internal
+ */
+export function engineAbiParts(addressBytes: AddressBytes): readonly string[] {
const parts: string[] = [
`addr=${addressBytes}`,
`sysctx=${SYSCTX_WORDS} rows=${QUERYROWS_WORDS} cmd=${CMD_WORDS}`,
@@ -70,10 +80,21 @@ export function engineAbiDigest(addressBytes: AddressBytes): string {
});
parts.push(`comp ${name}=${fields.join(',')}`);
}
- for (const [name, shape] of Object.entries(RESOURCE_SHAPES)) {
- parts.push(`res ${name}=${Object.keys(shape).join(',')}`);
+ // The whole layout, not the spec's own keys: a member's OFFSET is what a
+ // compiled system reads at, and for a bit set the KEY ORDER is what picks
+ // the bit. Either moving under a built module is a read of something else.
+ for (const name of RESOURCE_NAMES) {
+ const spec = RESOURCE_SHAPES[name]!;
+ const members = (resourceLayout(name) ?? []).map((m) => {
+ if (m.kind === 'scalar') return `${m.name}@${m.offset}`;
+ const how = spec.bits?.[m.name];
+ const domain = how?.keys ? how.keys.join('/') : `0..${(how?.count ?? 0) - 1}`;
+ return `${m.name}@${m.offset}[${domain}]`;
+ });
+ const methods = Object.entries(spec.methods ?? {}).map(([m, set]) => `${m}->${set}`);
+ parts.push(`res ${name}=${members.join(',')}|${methods.join(',')}`);
}
- return fnv1a64(parts.join('\n'));
+ return parts;
}
/**
diff --git a/sdk/src/ecs/aot/installAot.ts b/sdk/src/ecs/aot/installAot.ts
index 4a285b4ce..24e32c2f0 100644
--- a/sdk/src/ecs/aot/installAot.ts
+++ b/sdk/src/ecs/aot/installAot.ts
@@ -51,6 +51,12 @@ export interface InstallAotOptions {
readonly wasm: string | BufferSource;
/** The live value of a named resource, for the mirror to copy in. */
readonly resources: ResourceReader;
+ /**
+ * Whether this runtime HAS such a resource, asked once at install. Distinct
+ * from `resources`, which asks for a value: a resource the engine creates on
+ * its first frame has no value yet and is not missing.
+ */
+ readonly knowsResource?: (name: string) => boolean;
}
/**
@@ -83,7 +89,8 @@ export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): Promi
(exports['_initialize'] as (() => void) | undefined)?.();
const systems = new AotSystems();
- systems.install(opts.manifest, exports, componentNamed);
+ systems.install(opts.manifest, exports, componentNamed,
+ opts.knowsResource ?? ((name) => opts.resources(name) !== undefined));
return {
systems,
diff --git a/sdk/src/ecs/resource.ts b/sdk/src/ecs/resource.ts
index 3141e721b..d9a2ba624 100644
--- a/sdk/src/ecs/resource.ts
+++ b/sdk/src/ecs/resource.ts
@@ -39,11 +39,31 @@ let resourceCounter = 0;
*/
export function defineResource<T>(defaultValue: T, name?: string): ResourceDef<T> {
const id = ++resourceCounter;
- return {
+ const def: ResourceDef<T> = {
_id: Symbol(`Resource_${id}_${name ?? ''}`),
_name: name ?? `Resource_${id}`,
_default: defaultValue
};
+ // The engine's own resources answer to their NAME too, because a compiled
+ // module's manifest carries names. Only the DECLARED ones: a project's
+ // resource is identified by reference, and two may share a name.
+ if (name && RESOURCE_SHAPES[name]) builtinByName.set(name, def as ResourceDef<unknown>);
+ return def;
+}
+
+/** Registered by `defineResource` for the names `resourceShapes.ts` declares. */
+const builtinByName = new Map<string, ResourceDef<unknown>>();
+
+/**
+ * The engine resource a manifest's NAME refers to, or undefined when the module
+ * that declared it was never loaded — a trimmed build without the input plugin
+ * would be one, and a twin reading a resource with no address is not something
+ * to discover at the first row.
+ *
+ * @internal
+ */
+export function builtinResource(name: string): ResourceDef<unknown> | undefined {
+ return builtinByName.get(name);
}
// =============================================================================
@@ -277,17 +297,7 @@ export interface TimeData {
*
* @public
*/
-export const Time = defineResource<TimeData>({ ...RESOURCE_SHAPES.Time }, 'Time');
+export const Time = defineResource<TimeData>(
+ { ...RESOURCE_SHAPES['Time']!.fields } as unknown as TimeData, 'Time');
-/**
- * The engine's own resources, by the name a compiled system names them with.
- * Not a general registry: `defineResource` identifies by REFERENCE, so a name
- * answers a resource only for the ones the engine itself declares — which is
- * exactly the set that has a layout to read at an address.
- *
- * @internal
- */
-export const BUILTIN_RESOURCES: Readonly<Record<string, ResourceDef<unknown>>> = {
- Time: Time as ResourceDef<unknown>,
-};
diff --git a/sdk/src/ecs/resourceShapes.ts b/sdk/src/ecs/resourceShapes.ts
index 16ad3b392..e9d99ae14 100644
--- a/sdk/src/ecs/resourceShapes.ts
+++ b/sdk/src/ecs/resourceShapes.ts
@@ -2,44 +2,215 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file resourceShapes.ts
- * @brief The built-in resources a compiled system can read, and their fields.
+ * @brief The built-in resources a compiled system can read, and their layout.
*
- * @details A compiled system reaches a resource by ADDRESS, so its fields need a
+ * @details A compiled system reaches a resource by ADDRESS, so it needs a
* layout, and a layout needs exactly one author. This is that author:
- * `resource.ts` builds the resource from it, and the AOT compiler reads
- * it for the offsets.
+ * `resource.ts` builds `Time` from it, the AOT compiler derives offsets
+ * from it, and the runtime mirrors a resource into a block shaped by it.
*
- * A resource belongs here when every field is a number or a boolean —
- * the same bar `defineComponent` shapes meet, and for the same reason:
- * anything else has no fixed width. `Input` is deliberately absent; it
- * is a class with methods, so there is nothing to lay out.
+ * A member is a SCALAR or a BIT SET. Scalars are the fields a system
+ * reads by name. A bit set is how a SERVICE becomes memory: a method
+ * whose argument is a compile-time key is one bit, so `isKeyDown('KeyW')`
+ * is a load and a mask rather than a call the contract has no way to
+ * make. `methods` is that mapping, and it is the only thing that makes
+ * such a call lowerable.
*
- * Order is the layout. Adding a field in the middle moves every field
- * after it, which is why this list is the thing that changes and not a
- * copy of it somewhere else.
+ * Order is the layout, in both directions: adding a member moves every
+ * member after it, and adding a key renumbers every key after it.
+ *
+ * `fields` carries a value per scalar. For `Time` that value IS the
+ * default the resource is built with; for a service the resource builds
+ * itself, and the value only says which of the two scalar types the
+ * field is. `resource-shape.test.ts` holds the declaration against the
+ * real object either way.
*
* NO IMPORTS. A build tool reads this without pulling in the engine.
*/
-/** Field defaults per resource, in declaration order. */
-export const RESOURCE_SHAPES = {
+/**
+ * The keys a compiled system may name, and the bit each one is. `KeyboardEvent.
+ * code` values: physical keys, so they do not move with the layout the player
+ * types in. A key outside this list is not a lowering failure to work around —
+ * the system falls back to its closure and runs interpreted.
+ */
+export const KEY_CODES: readonly string[] = [
+ 'KeyA', 'KeyB', 'KeyC', 'KeyD', 'KeyE', 'KeyF', 'KeyG', 'KeyH', 'KeyI',
+ 'KeyJ', 'KeyK', 'KeyL', 'KeyM', 'KeyN', 'KeyO', 'KeyP', 'KeyQ', 'KeyR',
+ 'KeyS', 'KeyT', 'KeyU', 'KeyV', 'KeyW', 'KeyX', 'KeyY', 'KeyZ',
+ 'Digit0', 'Digit1', 'Digit2', 'Digit3', 'Digit4',
+ 'Digit5', 'Digit6', 'Digit7', 'Digit8', 'Digit9',
+ 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
+ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
+ 'ShiftLeft', 'ShiftRight', 'ControlLeft', 'ControlRight',
+ 'AltLeft', 'AltRight', 'MetaLeft', 'MetaRight',
+ 'Space', 'Enter', 'Escape', 'Tab', 'Backspace', 'Delete', 'Insert',
+ 'Home', 'End', 'PageUp', 'PageDown',
+ 'Minus', 'Equal', 'BracketLeft', 'BracketRight', 'Backslash',
+ 'Semicolon', 'Quote', 'Backquote', 'Comma', 'Period', 'Slash',
+ 'Numpad0', 'Numpad1', 'Numpad2', 'Numpad3', 'Numpad4',
+ 'Numpad5', 'Numpad6', 'Numpad7', 'Numpad8', 'Numpad9',
+ 'NumpadAdd', 'NumpadSubtract', 'NumpadMultiply', 'NumpadDivide',
+ 'NumpadDecimal', 'NumpadEnter',
+ 'CapsLock', 'NumLock', 'ScrollLock', 'PrintScreen', 'Pause', 'ContextMenu',
+];
+
+/** Mouse buttons, where the button NUMBER is the bit: 0 left, 1 middle, 2 right. */
+const MOUSE_BUTTON_BITS = 8;
+
+/** A bit set: either a table of names, or a count where the index is the key. */
+export interface BitSetSpec {
+ readonly keys?: readonly string[];
+ readonly count?: number;
+}
+
+export interface ResourceSpec {
+ /** Scalars, in layout order. The value is the default, and its type. */
+ readonly fields: Readonly<Record<string, number | boolean>>;
+ /** Bit sets, in layout order after the scalars. */
+ readonly bits?: Readonly<Record<string, BitSetSpec>>;
+ /** `method(key)` -> which bit set answers it. */
+ readonly methods?: Readonly<Record<string, string>>;
+}
+
+export const RESOURCE_SHAPES: Readonly<Record<string, ResourceSpec>> = {
Time: {
- delta: 0,
- elapsed: 0,
- frameCount: 0,
- fixedDelta: 1 / 60,
- fixedAlpha: 0,
- fixedTick: 0,
- scale: 1,
- unscaledDelta: 0,
+ fields: {
+ delta: 0,
+ elapsed: 0,
+ frameCount: 0,
+ fixedDelta: 1 / 60,
+ fixedAlpha: 0,
+ fixedTick: 0,
+ scale: 1,
+ unscaledDelta: 0,
+ },
+ },
+ /**
+ * The edge sets are the ones a call would have RESOLVED, not the raw state:
+ * `isKeyPressed` reads a different set inside a fixed step, and the host
+ * mirrors whichever one applies. Compiled code reads one bit either way.
+ */
+ Input: {
+ fields: {
+ mouseX: 0,
+ mouseY: 0,
+ scrollDeltaX: 0,
+ scrollDeltaY: 0,
+ touchAvailable: false,
+ },
+ bits: {
+ keyDown: { keys: KEY_CODES },
+ keyPressed: { keys: KEY_CODES },
+ keyReleased: { keys: KEY_CODES },
+ mouseDown: { count: MOUSE_BUTTON_BITS },
+ mousePressed: { count: MOUSE_BUTTON_BITS },
+ mouseReleased: { count: MOUSE_BUTTON_BITS },
+ },
+ methods: {
+ isKeyDown: 'keyDown',
+ isKeyPressed: 'keyPressed',
+ isKeyReleased: 'keyReleased',
+ isMouseButtonDown: 'mouseDown',
+ isMouseButtonPressed: 'mousePressed',
+ isMouseButtonReleased: 'mouseReleased',
+ },
},
-} as const satisfies Record<string, Readonly<Record<string, number | boolean>>>;
+ /**
+ * The UI surface. `viewProjection` is a Float32Array and is deliberately
+ * absent: a member has to have a fixed width, and a system reading it is
+ * refused by name rather than handed something else at that offset.
+ */
+ UICameraInfo: {
+ fields: {
+ vpX: 0, vpY: 0, vpW: 0, vpH: 0,
+ screenW: 0, screenH: 0,
+ worldLeft: 0, worldBottom: 0, worldRight: 0, worldTop: 0,
+ worldMouseX: 0, worldMouseY: 0,
+ valid: false,
+ },
+ },
+};
/** Names of the resources with a layout — what tells a host shape from a component. */
export const RESOURCE_NAMES: readonly string[] = Object.keys(RESOURCE_SHAPES);
-/** The fields of `name`, in layout order, or null if it has no layout. */
+/** One member of a resource's block, in layout order. */
+export type ResourceMember =
+ | { readonly kind: 'scalar'; readonly name: string; readonly offset: number }
+ | { readonly kind: 'bits'; readonly name: string; readonly offset: number; readonly bits: number };
+
+/** A scalar is one f64, so a bit set is padded to the same step. */
+const SLOT = 8;
+
+/**
+ * `name`'s block, member by member, or null if it has no layout. Scalars first
+ * in declaration order, then bit sets: two groups so that adding a key to a set
+ * cannot move a scalar, which is the field an offset is most often read at.
+ */
+export function resourceLayout(name: string): readonly ResourceMember[] | null {
+ const spec = RESOURCE_SHAPES[name];
+ if (!spec) return null;
+ const out: ResourceMember[] = [];
+ let at = 0;
+ for (const field of Object.keys(spec.fields)) {
+ out.push({ kind: 'scalar', name: field, offset: at });
+ at += SLOT;
+ }
+ for (const [set, how] of Object.entries(spec.bits ?? {})) {
+ const bits = how.keys ? how.keys.length : (how.count ?? 0);
+ out.push({ kind: 'bits', name: set, offset: at, bits });
+ at += Math.ceil(bits / 8 / SLOT) * SLOT;
+ }
+ return out;
+}
+
+/** How many bytes `name`'s block takes. */
+export function resourceBlockBytes(name: string): number {
+ const layout = resourceLayout(name);
+ if (!layout) return 0;
+ const last = layout[layout.length - 1];
+ if (!last) return 0;
+ return last.kind === 'scalar' ? last.offset + SLOT
+ : last.offset + Math.ceil(last.bits / 8 / SLOT) * SLOT;
+}
+
+/** The scalar fields of `name`, in layout order, or null if it has no layout. */
export function resourceFields(name: string): readonly string[] | null {
- const shape = (RESOURCE_SHAPES as Record<string, Record<string, unknown>>)[name];
- return shape ? Object.keys(shape) : null;
+ const spec = RESOURCE_SHAPES[name];
+ return spec ? Object.keys(spec.fields) : null;
+}
+
+/**
+ * How a host FILLS a bit set: the method to ask, and every key to ask it about.
+ * Asking the method rather than reading the state behind it is what keeps the
+ * mirror honest — `isKeyPressed` answers from a different set inside a fixed
+ * step, and that decision lives in the method.
+ */
+export function resourceBitSource(
+ resource: string, set: string,
+): { readonly method: string; readonly keys: readonly (string | number)[] } | null {
+ const spec = RESOURCE_SHAPES[resource];
+ const method = Object.entries(spec?.methods ?? {}).find(([, s]) => s === set)?.[0];
+ const how = spec?.bits?.[set];
+ if (!method || !how) return null;
+ const keys = how.keys ?? Array.from({ length: how.count ?? 0 }, (_, i) => i);
+ return { method, keys };
+}
+
+/** Where `resource.method(key)` reads: a byte offset and a bit, or null. */
+export function resourceMethodBit(
+ resource: string, method: string, key: string | number,
+): { readonly offset: number; readonly bit: number } | null {
+ const spec = RESOURCE_SHAPES[resource];
+ const set = spec?.methods?.[method];
+ if (!spec || !set) return null;
+ const how = spec.bits?.[set];
+ const member = resourceLayout(resource)?.find((m) => m.kind === 'bits' && m.name === set);
+ if (!how || !member) return null;
+ const index = how.keys
+ ? (typeof key === 'string' ? how.keys.indexOf(key) : -1)
+ : (typeof key === 'number' && Number.isInteger(key) && key >= 0 && key < (how.count ?? 0) ? key : -1);
+ if (index < 0) return null;
+ return { offset: member.offset + (index >> 3), bit: index & 7 };
}
diff --git a/sdk/tests/aot-app.test.ts b/sdk/tests/aot-app.test.ts
index faeaee984..93f6951fc 100644
--- a/sdk/tests/aot-app.test.ts
+++ b/sdk/tests/aot-app.test.ts
@@ -12,13 +12,14 @@
import { describe, it, expect } from 'vitest';
import { bootMockApp } from './helpers/mockApp';
import {
- buildAotModule, buildFadeModule, fadeManifest, timeScaleManifest,
+ buildAotModule, buildFadeModule, fadeManifest, keyProbeC, keyProbeManifest, timeScaleManifest,
FADE_PROBE_ALPHA, FADE_PROBE_C, TIME_SCALE_C,
} from './helpers/aotFade';
import { FakeEngine } from './fakeEngine';
import { emccPath } from '../../build-tools/utils/emscripten.js';
import { defineComponent } from '../src/ecs/component';
import { Time } from '../src/ecs/resource';
+import { Input } from '../src/input/input';
import { defineSystem, Schedule } from '../src/ecs/system';
import { Query, Mut } from '../src/ecs/query';
import type { AnyComponentDef } from '../src/ecs/component';
@@ -137,6 +138,34 @@ describe('an App told to run its compiled twins', () => {
expect(await scaleAfter(false)).toBe(1);
});
+ it.skipIf(!EMCC)('mirrors a service question into the bit the twin reads', async () => {
+ const wasm = buildAotModule(EMCC!, keyProbeC(), 'es_sys_KeyProbe');
+ // Named for the twin: dispatch is by system name, so a mismatch here
+ // would quietly run the closure and prove nothing.
+ const { app } = bootMockApp();
+ const Fade = defineComponent('Fade', { alpha: 1, step: 0.1 }) as AnyComponentDef;
+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Fade))], () => {
+ /* the twin is the point */
+ }, { name: 'KeyProbe' }));
+ // The engine's own Input, answering by method — the mirror is what has
+ // to turn that into the bit, and nothing else in the suite asks it to.
+ const input = app.getResource(Input);
+ await app.useCompiledSystems({ host: new FakeEngine(), manifest: keyProbeManifest(), wasm });
+ const entities = seed(app, Fade);
+
+ await app.tick(1 / 60);
+ expect(alphas(app, Fade, entities).every((a) => a === 0)).toBe(true);
+
+ input.noteKeyDown('KeyW');
+ await app.tick(1 / 60);
+ expect(alphas(app, Fade, entities).every((a) => a === 1)).toBe(true);
+
+ // And back: a mirror that only ever sets bits would pass the line above.
+ input.noteKeyUp('KeyW');
+ await app.tick(1 / 60);
+ expect(alphas(app, Fade, entities).every((a) => a === 0)).toBe(true);
+ });
+
it.skipIf(!EMCC)('refuses a module built for other shapes, and the App keeps interpreting', async () => {
const { app, Fade } = fadeApp();
await expect(app.useCompiledSystems({
diff --git a/sdk/tests/helpers/aotFade.ts b/sdk/tests/helpers/aotFade.ts
index b74a622ac..75c2e478b 100644
--- a/sdk/tests/helpers/aotFade.ts
+++ b/sdk/tests/helpers/aotFade.ts
@@ -15,6 +15,7 @@ import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { WASM_LINK_FLAGS } from '../../../compiler/src/codegen';
import { engineAbiDigest, projectShapeDigest } from '../../src/ecs/aot/abiDigest';
+import { resourceMethodBit } from '../../src/ecs/resourceShapes';
import type { AotManifest } from '../../src/ecs/aot/AotSystems';
/** `Fade`: alpha -= step, addressed the way the ABI lays a call out. */
@@ -90,6 +91,48 @@ void es_sys_Speed(es_addr_t ctx) {
}
`;
+/**
+ * A system that asks a SERVICE: `alpha = input.isKeyDown('KeyW') ? 1 : 0`. The
+ * bit offsets come from the shared layout rather than being written down here,
+ * because a third opinion about where the bit is would pass while the runtime
+ * and the compiler disagreed.
+ */
+export function keyProbeC(): string {
+ const at = resourceMethodBit('Input', 'isKeyDown', 'KeyW');
+ if (!at) throw new Error('Input.isKeyDown(KeyW) is not a declared service question');
+ return `#include <stdint.h>
+#include <string.h>
+typedef uint32_t es_addr_t;
+#define ES_PTR(a) ((unsigned char *)(a))
+typedef struct { es_addr_t rows, count; } EsQueryRows;
+typedef struct { es_addr_t queries, resources, cmdBuf, cmdCap, cmdCount, events; } EsSysCtx;
+static void st(unsigned char *p, double v) { memcpy(p, &v, 8); }
+
+void es_sys_KeyProbe(es_addr_t ctx) {
+ const EsSysCtx *c = (const EsSysCtx *)ES_PTR(ctx);
+ const EsQueryRows *q = (const EsQueryRows *)ES_PTR(c->queries);
+ const es_addr_t *rows = (const es_addr_t *)ES_PTR(q[0].rows);
+ const es_addr_t *res = (const es_addr_t *)ES_PTR(c->resources);
+ const int down = (ES_PTR(res[0])[${at.offset}u] >> ${at.bit}u) & 1u;
+ for (es_addr_t i = 0; i < q[0].count; ++i) {
+ st(ES_PTR(rows[i * 2u + 1u]), down ? 1.0 : 0.0);
+ }
+}
+`;
+}
+
+/** What a build writes for the probe above. */
+export function keyProbeManifest(): AotManifest {
+ return {
+ engineAbi: engineAbiDigest(4),
+ projectShapes: projectShapeDigest([{ name: 'Fade', fields: FADE_FIELDS }]),
+ systems: [{
+ name: 'KeyProbe', symbol: 'es_sys_KeyProbe',
+ queries: [[{ comp: 'Fade', mut: true }]], resources: [{ name: 'Input', mut: false }],
+ }],
+ };
+}
+
/** What a build writes for that one, with Time declared writable or not. */
export function timeScaleManifest(mut: boolean): AotManifest {
return {
diff --git a/sdk/tests/resource-shape.test.ts b/sdk/tests/resource-shape.test.ts
new file mode 100644
index 000000000..8ec787647
--- /dev/null
+++ b/sdk/tests/resource-shape.test.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file resource-shape.test.ts
+ * @brief The declared layout against the resource it claims to describe.
+ *
+ * @details `resourceShapes.ts` is a leaf with no imports, so it cannot check
+ * itself: it says `Input` has a `mouseX` and an `isKeyDown`, and only
+ * something that can see the real object knows whether it does. A
+ * field that is not there mirrors as 0 and a method that is not there
+ * mirrors as all-zero bits — both answer, and both answer wrongly.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ RESOURCE_NAMES, RESOURCE_SHAPES, KEY_CODES, resourceBlockBytes, resourceLayout,
+ resourceMethodBit,
+} from '../src/ecs/resourceShapes';
+import { builtinResource, Time } from '../src/ecs/resource';
+import { engineAbiParts } from '../src/ecs/aot/abiDigest';
+import '../src/input/input';
+import '../src/ui/core/ui-camera-info';
+
+describe('a declared resource layout', () => {
+ it('names a resource the runtime actually registered', () => {
+ // Registration happens in `defineResource`, so a name here with no
+ // module importing it would leave a compiled system reading nothing.
+ for (const name of RESOURCE_NAMES) {
+ expect([name, builtinResource(name) !== undefined]).toEqual([name, true]);
+ }
+ });
+
+ for (const name of RESOURCE_NAMES) {
+ it(`${name}: every declared scalar is a field of that type on the resource`, () => {
+ const value = builtinResource(name)!._default as Record<string, unknown>;
+ for (const [field, declared] of Object.entries(RESOURCE_SHAPES[name]!.fields)) {
+ expect([field, typeof value[field]]).toEqual([field, typeof declared]);
+ }
+ });
+
+ it(`${name}: every declared method is a method on the resource`, () => {
+ const value = builtinResource(name)!._default as Record<string, unknown>;
+ for (const method of Object.keys(RESOURCE_SHAPES[name]!.methods ?? {})) {
+ expect([method, typeof value[method]]).toEqual([method, 'function']);
+ }
+ });
+ }
+
+ it('Time is built FROM the declaration, so the two cannot drift', () => {
+ expect(Time._default).toEqual(RESOURCE_SHAPES['Time']!.fields);
+ });
+
+ it('lays bit sets out after the scalars, and sizes the block for both', () => {
+ const layout = resourceLayout('Input')!;
+ const scalars = layout.filter((m) => m.kind === 'scalar').length;
+ expect(layout.slice(0, scalars).every((m) => m.kind === 'scalar')).toBe(true);
+ // Room for the last member, not just the last scalar: a block sized to
+ // the scalars would have the first mirrored bit land outside it.
+ const last = layout[layout.length - 1]!;
+ expect(resourceBlockBytes('Input')).toBeGreaterThanOrEqual(
+ last.offset + (last.kind === 'bits' ? Math.ceil(last.bits / 8) : 8));
+ });
+
+ it('gives every declared key its own bit, and refuses one it does not declare', () => {
+ const seen = new Set<string>();
+ for (const key of KEY_CODES) {
+ const at = resourceMethodBit('Input', 'isKeyDown', key)!;
+ expect([key, at !== null]).toEqual([key, true]);
+ const slot = `${at.offset}:${at.bit}`;
+ expect([key, seen.has(slot)]).toEqual([key, false]);
+ seen.add(slot);
+ }
+ expect(resourceMethodBit('Input', 'isKeyDown', 'KeyNotOnAnyKeyboard')).toBeNull();
+ expect(resourceMethodBit('Input', 'isPointerOverUI', 0)).toBeNull();
+ });
+});
+
+describe('what the engine handshake is taken of', () => {
+ const parts = engineAbiParts(4).join('\n');
+
+ it('covers a member offset, so moving one invalidates a built module', () => {
+ const valid = resourceLayout('UICameraInfo')!.find((m) => m.name === 'valid')!;
+ expect(parts).toContain(`valid@${valid.offset}`);
+ });
+
+ it('covers the KEY ORDER, because that is what picks the bit', () => {
+ // Swapping two keys moves no member and changes no count; without the
+ // table itself in here, a module built before the swap would keep
+ // loading and read the wrong key's bit.
+ expect(parts).toContain(KEY_CODES.join('/'));
+ });
+
+ it('covers which method reads which set', () => {
+ expect(parts).toContain('isKeyPressed->keyPressed');
+ });
+});
diff --git a/src/esengine/aot/estella_abi.h b/src/esengine/aot/estella_abi.h
index 81277bbd2..35fc0c71c 100644
--- a/src/esengine/aot/estella_abi.h
+++ b/src/esengine/aot/estella_abi.h
@@ -100,6 +100,8 @@ static inline void es_set_f64(unsigned char *p, double v) { memcpy(p, &v, 8); }
/* A bool in the C++ structs is ONE byte. Reading it as a float would read three
bytes of whatever follows it, which is a value rather than an error. */
static inline int es_bool(const unsigned char *p) { return *p != 0; }
+/* One question of a service, as the host mirrored it: a byte and a mask. */
+static inline int es_bit(const unsigned char *p, unsigned bit) { return (*p >> bit) & 1u; }
static inline void es_set_bool(unsigned char *p, int v) { *p = (unsigned char)(v ? 1 : 0); }
/* ---------------------------------------------------------------------------
diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.c
index 27442f09c..d0b31b465 100644
--- a/tests/aot/generated/move_system_decl.c
+++ b/tests/aot/generated/move_system_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x36cbaec9128499cdULL
+#define ES_ABI_ENGINE_DIGEST 0xe83b13ad2f96720cULL
const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.h
index 6f5a2d0fc..51cead3ff 100644
--- a/tests/aot/generated/move_system_hash.h
+++ b/tests/aot/generated/move_system_hash.h
@@ -1,3 +1,3 @@
/* GENERATED by @estella/compiler — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_EXPECTED_CONTRACT_HASH 0x36cbaec9128499cdULL
+#define ES_EXPECTED_CONTRACT_HASH 0xe83b13ad2f96720cULL