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
fix(engine): a system that fails to start says why, every frame, not once
yhhfe72fe2714aa
diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex f069b1508..33dc28c7f 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -284,16 +284,20 @@ export class SystemRunner {this.currentLastRunTick_ = this.systemTicks_.get(system._id) ?? -1;- let queries = this.queryCache_.get(system._id);- let removeds = this.removedCache_.get(system._id);- const firstRun = !queries;-- if (firstRun) {- queries = [];- removeds = [];- this.queryCache_.set(system._id, queries);- this.removedCache_.set(system._id, removeds);- }+ // Published only once every param resolved. Building a system's first set+ // of query instances can throw — an unregistered component reaches+ // resolveGetter, and that is exactly when it says so — and a cache+ // published up front kept whatever had been built before the throw. The+ // next frame then read `firstRun === false` against a SHORT array, found+ // `undefined` where a later query belonged, and reported+ // "cannot read properties of undefined (reading 'resetTick')" forever:+ // the true error scrolls away and every frame after it names the runner.+ // Commit at the end instead, so a failed setup is simply not cached and+ // the following frame re-raises the real one.+ const cachedQueries = this.queryCache_.get(system._id);+ const firstRun = !cachedQueries;+ const queries = cachedQueries ?? [];+ const removeds = this.removedCache_.get(system._id) ?? [];let qi = 0, ri = 0;for (let i = 0; i < system._params.length; i++) {@@ -301,10 +305,10 @@ export class SystemRunner {if (param._type === 'query') {if (firstRun) {const inst = new QueryInstance(this.world_, param, this.currentLastRunTick_);- queries!.push(inst);+ queries.push(inst);args[i] = inst;} else {- const inst = queries![qi];+ const inst = queries[qi];inst.resetTick(this.currentLastRunTick_);args[i] = inst;}@@ -313,10 +317,10 @@ export class SystemRunner {if (firstRun) {const desc = param as RemovedQueryDescriptor<AnyComponentDef>;const inst = new RemovedQueryInstance(this.world_, desc._component, this.currentLastRunTick_);- removeds!.push(inst);+ removeds.push(inst);args[i] = inst;} else {- const inst = removeds![ri];+ const inst = removeds[ri];inst.resetTick(this.currentLastRunTick_);args[i] = inst;}@@ -325,6 +329,10 @@ export class SystemRunner {args[i] = this.resolveParam(param);}}+ if (firstRun) {+ this.queryCache_.set(system._id, queries);+ this.removedCache_.set(system._id, removeds);+ }const t0 = this.timings_ ? performance.now() : 0;let result: void | Promise<void>;diff --git a/sdk/tests/query-mixed-mut.test.ts b/sdk/tests/query-mixed-mut.test.tsnew file mode 100644index 000000000..aee7768d8--- /dev/null+++ b/sdk/tests/query-mixed-mut.test.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file query-mixed-mut.test.ts+ * @brief One query asking for a BUILTIN component and a SCRIPT component in the+ * same tuple, both Mut, plus a plain script component to narrow it.+ *+ * The two are fetched by different machinery — a builtin reads through+ * the wasm registry, a script one through per-context storage — and+ * write-back takes a different branch for each. A game that positions+ * entities (builtin Transform) and labels them (script Text) writes+ * exactly this query, so "every argument arrives, and every write lands"+ * is the claim.+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/ecs/world';+import { Query, QueryInstance, Mut } from '../src/ecs/query';+import { Transform, defineComponent, type TransformData } from '../src/ecs/component';+import { createMockModule } from './mocks/wasm';+import type { Entity } from '../src/types';++const Label = defineComponent('MixTestLabel', { text: '' });+const Piece = defineComponent('MixTestPiece', { kind: 'pawn', col: 0 });++function defaultTransform(): TransformData {+ return {+ position: { x: 0, y: 0, z: 0 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 },+ worldPosition: { x: 0, y: 0, z: 0 },+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },+ worldScale: { x: 1, y: 1, z: 1 },+ } as TransformData;+}++function connectedWorld(): World {+ const mod = createMockModule();+ const world = new World();+ world.connectCpp(mod.getRegistry(), mod);+ return world;+}++function seed(world: World, col: number): Entity {+ const e = world.spawn();+ world.insert(e, Transform, defaultTransform());+ world.insert(e, Label, { text: '' });+ world.insert(e, Piece, { kind: 'rook', col });+ return e;+}++describe('a query mixing a builtin and a script component', () => {+ it('hands every component of the tuple to the callback, none undefined', () => {+ const world = connectedWorld();+ const a = seed(world, 3);++ const seen: Array<[Entity, unknown, unknown, unknown]> = [];+ new QueryInstance(world, Query(Mut(Transform), Mut(Label), Piece), -1)+ .forEach((entity, transform, label, piece) => {+ seen.push([entity, transform, label, piece]);+ });++ expect(seen).toHaveLength(1);+ const [entity, transform, label, piece] = seen[0];+ expect(entity).toBe(a);+ expect(transform).toBeDefined();+ expect(label).toBeDefined();+ // The one that was reported as undefined in a real game: the narrowing+ // script component, third in a tuple whose first is builtin.+ expect(piece).toBeDefined();+ expect((piece as { col: number }).col).toBe(3);+ });++ it('writes back through both kinds in the same iteration', () => {+ const world = connectedWorld();+ const e = seed(world, 1);++ for (const [, transform, label] of new QueryInstance(world, Query(Mut(Transform), Mut(Label), Piece), -1)) {+ (transform as TransformData).position.x = 42;+ (label as { text: string }).text = 'rook';+ }++ expect(world.get(e, Transform).position.x).toBe(42);+ expect(world.get(e, Label).text).toBe('rook');+ });++ it('skips an entity missing the narrowing component rather than passing undefined', () => {+ const world = connectedWorld();+ const withPiece = seed(world, 5);+ const withoutPiece = world.spawn();+ world.insert(withoutPiece, Transform, defaultTransform());+ world.insert(withoutPiece, Label, { text: 'hud' });++ const visited: Entity[] = [];+ new QueryInstance(world, Query(Mut(Transform), Mut(Label), Piece), -1)+ .forEach((entity, _t, _l, piece) => {+ visited.push(entity);+ expect(piece).toBeDefined();+ });++ expect(visited).toEqual([withPiece]);+ });+});diff --git a/sdk/tests/system.test.ts b/sdk/tests/system.test.tsindex 8bc4ec446..e506d2e36 100644--- a/sdk/tests/system.test.ts+++ b/sdk/tests/system.test.ts@@ -201,6 +201,45 @@ describe('SystemRunner', () => {});});+ describe('a first run that throws while building its params', () => {+ /**+ * The real shape of this: a system queries a component the world does not+ * know, so building that query instance throws — naming the component,+ * which is the useful error. The runner used to publish its query cache+ * before filling it, so the next frame found a short array, read+ * `undefined` where the failing query belonged, and reported+ * "cannot read properties of undefined (reading 'resetTick')" from then+ * on. Every frame after the first blamed the runner and the true cause+ * scrolled out of the log.+ */+ it('re-raises the real error next frame instead of a resetTick TypeError', () => {+ const Broken = defineComponent('SysTestBroken', { v: 0 });+ (world.resolveGetter as ReturnType<typeof vi.fn>).mockImplementation(+ (comp: { _name: string }) => {+ if (comp._name === 'SysTestBroken') throw new Error('component SysTestBroken is not registered');+ return null;+ },+ );+ const fn = vi.fn();+ const sys = defineSystem([Query(Position), Query(Broken)], fn);++ expect(() => runner.run(sys)).toThrow(/SysTestBroken is not registered/);+ expect(() => runner.run(sys)).toThrow(/SysTestBroken is not registered/);+ expect(() => runner.run(sys)).not.toThrow(/resetTick/);+ expect(fn).not.toHaveBeenCalled();+ });++ it('still caches query instances across runs when setup succeeds', () => {+ const seen: unknown[] = [];+ const sys = defineSystem([Query(Position), Query(Velocity)], (a, b) => { seen.push(a, b); });+ runner.run(sys);+ runner.run(sys);+ expect(seen).toHaveLength(4);+ expect(seen[0]).toBe(seen[2]);+ expect(seen[1]).toBe(seen[3]);+ });+ });+describe('parameter resolution', () => {it('should resolve Query parameter', () => {let received: unknown = null;