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 tag is a component with no fields, and a query may filter on one

esengine04b64f103dc3
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.ts
index 905fa3695..83cd5dae7 100644
--- a/compiler/src/frontend.ts
+++ b/compiler/src/frontend.ts
@@ -719,10 +719,15 @@ class SystemLowerer {
}
}
-/** `defineComponent('Mover', { speed: 100 })` -> a shape, or null if not literal. */
-function componentShape(call: ts.CallExpression): CompShape | null {
+/**
+ * `defineComponent('Mover', { speed: 100 })` or `defineTag('Player')` -> a
+ * shape, or null when a default is not a literal scalar. A TAG is a shape with
+ * no fields, which is a thing a query can filter on and nothing can read.
+ */
+function componentShape(call: ts.CallExpression, tag: boolean): CompShape | null {
const [nameArg, defaults] = call.arguments;
if (!nameArg || !ts.isStringLiteral(nameArg)) return null;
+ if (tag) return { name: nameArg.text, storage: 'host', fields: new Map() };
if (!defaults || !ts.isObjectLiteralExpression(defaults)) return null;
const fields = new Map<string, FieldSpec>();
for (const prop of defaults.properties) {
@@ -836,13 +841,18 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str
for (const sf of sources) {
walkTop(sf, (node, binding) => {
if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) return;
- if (node.expression.text !== 'defineComponent') return;
- const shape = componentShape(node);
+ const tag = node.expression.text === 'defineTag';
+ if (!tag && node.expression.text !== 'defineComponent') return;
+ const shape = componentShape(node, tag);
if (!shape) {
+ // Which is nearly always a FIELD, not the call: a default that
+ // is an object, an array or a computed value has no fixed width,
+ // and the pool that would hold the rows admits the same set.
diagnostics.push({
file: sf.fileName, line: lineOf(sf, node),
kind: 'permanent', severity: 'note',
- message: 'defineComponent needs a string literal name and an object literal of literal defaults',
+ message: `defineComponent('${ts.isStringLiteral(node.arguments[0] ?? node) ? (node.arguments[0] as ts.StringLiteral).text : '…'}') `
+ + 'has a default that is not a literal number or boolean',
});
return;
}
diff --git a/compiler/tests/conformance.test.ts b/compiler/tests/conformance.test.ts
index 09ee4e637..7598fa515 100644
--- a/compiler/tests/conformance.test.ts
+++ b/compiler/tests/conformance.test.ts
@@ -214,7 +214,8 @@ describe('conformance — a service question, and the ways out of a row loop', (
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);
+ (quiet.resources as Map<string, Row>).set('Input',
+ { isKeyDown: () => false, isKeyPressed: () => false } as unknown as Row);
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);
diff --git a/compiler/tests/subset.test.ts b/compiler/tests/subset.test.ts
index 9b3ec0047..dc80ad893 100644
--- a/compiler/tests/subset.test.ts
+++ b/compiler/tests/subset.test.ts
@@ -66,7 +66,11 @@ describe('the subset refuses, and says why', () => {
const dyn = lowerProgram([DYNAMIC], builtinShapes());
expect(dyn.module.comps.has('FixtureDynamic')).toBe(false);
expect(dyn.diagnostics).toHaveLength(1);
- expect(dyn.diagnostics[0]!.message).toMatch(/object literal of literal defaults/);
+ // The message names the COMPONENT and what is wrong with it: the call
+ // shape was almost never the problem, and "needs an object literal"
+ // sent readers looking at a line that already had one.
+ expect(dyn.diagnostics[0]!.message)
+ .toMatch(/defineComponent\('FixtureDynamic'\) has a default that is not a literal/);
});
});
diff --git a/sdk/src/ecs/aot/AotDispatch.ts b/sdk/src/ecs/aot/AotDispatch.ts
index 3bf05cfd3..163aa8b89 100644
--- a/sdk/src/ecs/aot/AotDispatch.ts
+++ b/sdk/src/ecs/aot/AotDispatch.ts
@@ -92,6 +92,21 @@ interface Plan {
* One per installed runtime, holding one plan per twin — a system's shape is
* fixed by the build that produced it, so nothing here is recomputed per frame.
*/
+/** A component with no fields: a query filters on it and nothing reads it. */
+function isTagDef(def: AnyComponentDef): boolean {
+ const shape = (def as { _default?: unknown })._default;
+ return typeof shape === 'object' && shape !== null && Object.keys(shape).length === 0;
+}
+
+/**
+ * A TAG has no fields, so no bytes and no address — and a resolver answering
+ * `undefined` would drop the whole row. Its slot is never read (the verifier
+ * refuses a field read against a shape with none), so zero is a filler.
+ */
+function resolverFor(world: World, def: AnyComponentDef): (entity: Entity) => number | undefined {
+ return isTagDef(def) ? () => 0 : world.addressResolver(def);
+}
+
export class AotDispatch {
private readonly plans = new Map<AotTwin, Plan>();
@@ -215,7 +230,7 @@ export class AotDispatch {
const resolved = comps.length === args.length;
return {
comps,
- resolvers: comps.map((c) => this.world.addressResolver(c)),
+ resolvers: comps.map((c) => resolverFor(this.world, c)),
mutated: [...(twin.mutated[k] ?? [])],
key: computeQueryCacheKey(comps),
depIds: comps.map((c) => c._id as symbol),
diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.ts
index 181ff281a..71a48193c 100644
--- a/sdk/src/ecs/system.ts
+++ b/sdk/src/ecs/system.ts
@@ -393,6 +393,12 @@ export function addSystemSetToSchedule(schedule: Schedule, set: SystemSet): void
// System Runner
// =============================================================================
+/** A component with no fields: a query filters on it and nothing reads it. */
+function isTagDef(def: AnyComponentDef): boolean {
+ const shape = (def as { _default?: unknown })._default;
+ return typeof shape === 'object' && shape !== null && Object.keys(shape).length === 0;
+}
+
export class SystemRunner {
private readonly world_: World;
private readonly resources_: ResourceStorage;
diff --git a/sdk/tests/aot-app.test.ts b/sdk/tests/aot-app.test.ts
index 93f6951fc..0952b7beb 100644
--- a/sdk/tests/aot-app.test.ts
+++ b/sdk/tests/aot-app.test.ts
@@ -12,12 +12,13 @@
import { describe, it, expect } from 'vitest';
import { bootMockApp } from './helpers/mockApp';
import {
- buildAotModule, buildFadeModule, fadeManifest, keyProbeC, keyProbeManifest, timeScaleManifest,
+ buildAotModule, buildFadeModule, fadeManifest, fadeTaggedManifest, keyProbeC, keyProbeManifest,
+ timeScaleManifest, FADE_TAGGED_C,
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 { defineComponent, defineTag } from '../src/ecs/component';
import { Time } from '../src/ecs/resource';
import { Input } from '../src/input/input';
import { defineSystem, Schedule } from '../src/ecs/system';
@@ -166,6 +167,34 @@ describe('an App told to run its compiled twins', () => {
expect(alphas(app, Fade, entities).every((a) => a === 0)).toBe(true);
});
+ it.skipIf(!EMCC)('reaches its rows when the query also filters on a tag', async () => {
+ const { app } = bootMockApp();
+ const Fade = defineComponent('Fade', { alpha: 1, step: 0.1 }) as AnyComponentDef;
+ const Lit = defineTag('Lit') as AnyComponentDef;
+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Fade), Lit)], () => {
+ /* the twin is the point */
+ }, { name: 'FadeTagged' }));
+ await app.useCompiledSystems({
+ host: new FakeEngine(), manifest: fadeTaggedManifest(),
+ wasm: buildAotModule(EMCC!, FADE_TAGGED_C, 'es_sys_FadeTagged'),
+ });
+
+ const lit: Entity[] = [];
+ const unlit: Entity[] = [];
+ for (let i = 1; i <= 4; i++) {
+ const e = app.world.spawn();
+ app.world.insert(e, Fade, { alpha: 1, step: 0.25 });
+ if (i % 2 === 0) { app.world.insert(e, Lit, {}); lit.push(e); } else unlit.push(e);
+ }
+ await app.tick(1 / 60);
+
+ // A tag carries no address, and a host that read that as "no row" would
+ // leave these untouched — which is the same thing an uninstalled twin
+ // looks like, so the untagged half is what tells them apart.
+ expect(alphas(app, Fade, lit)).toEqual(lit.map(() => 0.75));
+ expect(alphas(app, Fade, unlit)).toEqual(unlit.map(() => 1));
+ });
+
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 75c2e478b..32aaeea29 100644
--- a/sdk/tests/helpers/aotFade.ts
+++ b/sdk/tests/helpers/aotFade.ts
@@ -121,6 +121,26 @@ void es_sys_KeyProbe(es_addr_t ctx) {
`;
}
+/**
+ * The same fade, but the query also filters on a TAG. A tag has no bytes, so
+ * its row slot carries a filler the code never reads — and a host that treated
+ * a missing address as a missing row would drop every row instead.
+ */
+export const FADE_TAGGED_C = FADE_C
+ .replace('void es_sys_Fade', 'void es_sys_FadeTagged')
+ .replace('rows[i * 2u + 1u]', 'rows[i * 3u + 1u]');
+
+export function fadeTaggedManifest(): AotManifest {
+ return {
+ engineAbi: engineAbiDigest(4),
+ projectShapes: projectShapeDigest([{ name: 'Fade', fields: FADE_FIELDS }, { name: 'Lit', fields: [] }]),
+ systems: [{
+ name: 'FadeTagged', symbol: 'es_sys_FadeTagged',
+ queries: [[{ comp: 'Fade', mut: true }, { comp: 'Lit', mut: false }]], resources: [],
+ }],
+ };
+}
+
/** What a build writes for the probe above. */
export function keyProbeManifest(): AotManifest {
return {