A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ecs): the switched-off subtree is derived, not written down
esenginec35d9fac3341
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76dd0dc92..a6c56ad63 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,14 @@ published separately; it ships inside the editor.### Added+- **The outliner switches an entity off.** Right-click → Disable writes the+ engine's `Disabled` tag onto that entity, and the row is struck through — the+ eye beside it means something else, and always did: hiding stops the drawing+ and leaves the entity in the world. Only the entity the author picked carries+ the tag; which of its descendants that takes out of the game is derived while+ it runs, so switching a boss back on cannot un-switch a prop that was switched+ off on its own. `set_entity_active` is the same door for automation.+- **A disabled entity is actually skipped.** `Disabled`'s doc promised that "theengine's systems skip it" and nothing read the tag: `setEntityActive` returned,every query went on answering with the entity, and the only record of this wasdiff --git a/desktop b/desktopindex e22b89ac0..5f097c473 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit e22b89ac05572759f6509d164a611df9ffce7e79+Subproject commit 5f097c473ddbbdb53a1b03904de5b16377b738d8diff --git a/sdk/src/ecs/QueryCache.ts b/sdk/src/ecs/QueryCache.tsindex 51d437480..096c7f99b 100644--- a/sdk/src/ecs/QueryCache.ts+++ b/sdk/src/ecs/QueryCache.ts@@ -45,6 +45,12 @@ export class QueryCache {this.structuralVersion_++;}+ /** A component's current version — for a derived set that has to recompute+ * when it moves, without standing up a second invalidation scheme. */+ componentVersion(componentId: symbol): number {+ return this.componentVersions_.get(componentId) ?? 0;+ }+markComponentDirty(componentId: symbol): void {const cur = this.componentVersions_.get(componentId) ?? 0;this.componentVersions_.set(componentId, cur + 1);diff --git a/sdk/src/ecs/entityUtils.ts b/sdk/src/ecs/entityUtils.tsindex 8fa5320ff..79085e216 100644--- a/sdk/src/ecs/entityUtils.ts+++ b/sdk/src/ecs/entityUtils.ts@@ -16,7 +16,7 @@*/import type { Entity } from '../types';import type { World } from './world';-import { Children, Disabled, renderableComponents, Transform, type ChildrenData } from './component';+import { Disabled, renderableComponents, Transform } from './component';import { UINode, UIDisplay, type UINodeData } from '../ui/core/ui-node';/**@@ -66,27 +66,22 @@ export function isEntityVisible(world: World, entity: Entity): boolean {}/**- * Switch `entity` and everything under it off, or back on — a character switched- * off with its sword still swinging is not switched off.- *- * Tagged per entity rather than derived from an ancestor, so a query costs one- * lookup: a subtree RE-PARENTED under a disabled entity needs this called again.+ * Switch `entity` off, or back on. Everything under it goes with it — a+ * character switched off with its sword still swinging is not switched off —+ * and the subtree is DERIVED, so switching the character back on does not+ * un-switch a sword the author had switched off on its own.*/export function setEntityActive(world: World, entity: Entity, active: boolean): void {- const apply = (e: Entity): void => {- if (!world.valid(e)) return;- if (active) {- if (world.has(e, Disabled)) world.remove(e, Disabled);- } else if (!world.has(e, Disabled)) {- world.insert(e, Disabled, {});- }- if (!world.has(e, Children)) return;- for (const child of (world.get(e, Children) as ChildrenData).entities) apply(child as Entity);- };- apply(entity);+ if (!world.valid(entity)) return;+ if (active) {+ if (world.has(entity, Disabled)) world.remove(entity, Disabled);+ } else if (!world.has(entity, Disabled)) {+ world.insert(entity, Disabled, {});+ }}-/** Whether this entity itself is switched on — see {@link setEntityActive}. */+/** Whether this entity ITSELF is switched on. An ancestor's switch takes it out+ * of every query without changing this — see {@link setEntityActive}. */export function isEntityActive(world: World, entity: Entity): boolean {return !world.has(entity, Disabled);}diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex bd2513fff..a75d3e274 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -131,7 +131,7 @@ export function queryDepIds(withoutFilters: readonly AnyComponentDef[],filterDeps: readonly AnyComponentDef[] = [],): symbol[] {- const ids: symbol[] = [Disabled._id];+ const ids: symbol[] = [Disabled._id, Children._id];for (const c of components) ids.push(c._id);for (const c of withFilters) ids.push(c._id);for (const c of withoutFilters) ids.push(c._id);@@ -156,6 +156,9 @@ export class World {readonly changes_ = new ChangeTracker();/** @internal */readonly queries_ = new QueryCache();+ /** @see inactiveEntities_ */+ private inactive_: { set: Set<Entity> } | null = null;+ private inactiveVersion_ = -1;private entities_ = new Map<Entity, number>();private indexGeneration_ = new Map<number, number>(); // index -> current generation (for isStale detection)private iterationDepth_ = 0;@@ -1009,6 +1012,36 @@ export class World {return Array.from(types);}++ /**+ * Every entity switched off, ITSELF or by an ancestor.+ *+ * Derived, not tagged down the tree: a scene that wrote the tag on each+ * descendant would lose which of them the author switched off. Recomputed+ * when the tag or the hierarchy moves; free when nothing is switched off.+ */+ private inactiveEntities_(): { has(entity: Entity): boolean } | null {+ const storage = this.scripts_.getStorageById(Disabled._id);+ if (!storage || storage.size === 0) return null;+ const version = this.queries_.componentVersion(Disabled._id)+ + this.queries_.componentVersion(Children._id);+ if (this.inactive_ && this.inactiveVersion_ === version) return this.inactive_.set;++ const set = new Set<Entity>();+ const walk = (entity: Entity): void => {+ if (set.has(entity)) return;+ set.add(entity);+ if (!this.has(entity, Children)) return;+ for (const child of (this.get(entity, Children) as ChildrenData).entities) {+ walk(child as Entity);+ }+ };+ for (const entity of storage.keys()) walk(entity as Entity);+ this.inactive_ = { set };+ this.inactiveVersion_ = version;+ return set;+ }+private resolveStorages_(comps: AnyComponentDef[],scriptOut: Map<Entity, unknown>[],@@ -1093,7 +1126,7 @@ export class World {return this.queries_.getOrCompute(cacheKey, depIds, () => {const entities: Entity[] = [];- const off = namesDisabled ? null : this.scripts_.getStorageById(Disabled._id);+ const off = namesDisabled ? null : this.inactiveEntities_();const reqScript: Map<Entity, unknown>[] = [];const reqBuiltin: BuiltinMethods[] = [];diff --git a/sdk/tests/disabled-entities.test.ts b/sdk/tests/disabled-entities.test.tsindex 943e9be0b..0e2a004e8 100644--- a/sdk/tests/disabled-entities.test.ts+++ b/sdk/tests/disabled-entities.test.ts@@ -51,30 +51,15 @@ describe('a disabled entity', () => {expect(world.getEntitiesWithComponents([Health, Disabled])).toEqual([entities[0]]);});- it('takes its subtree with it', () => {- // `Children` is written by the engine's hierarchy, which a unit test has- // no wasm for — so the TREE is modelled and the walk over it is what runs.- // That a real setParent produces this shape is the engine's own contract.- const tags = new Map<Entity, Set<symbol>>();- const kids = new Map<Entity, Entity[]>([[1 as Entity, [2 as Entity]], [2 as Entity, [3 as Entity]]]);- const tree = {- valid: () => true,- has: (e: Entity, c: { _id: symbol }) =>- c === Children ? kids.has(e) : (tags.get(e)?.has(c._id) ?? false),- get: (e: Entity) => ({ entities: kids.get(e) ?? [] }),- insert: (e: Entity, c: { _id: symbol }) => {- if (!tags.has(e)) tags.set(e, new Set());- tags.get(e)!.add(c._id);- },- remove: (e: Entity, c: { _id: symbol }) => { tags.get(e)?.delete(c._id); },- } as unknown as World;-- setEntityActive(tree, 1 as Entity, false);- // A character switched off with its sword still swinging is not off.- for (const e of [1, 2, 3]) expect(isEntityActive(tree, e as Entity), `entity ${e}`).toBe(false);-- setEntityActive(tree, 1 as Entity, true);- for (const e of [1, 2, 3]) expect(isEntityActive(tree, e as Entity), `entity ${e}`).toBe(true);+ it('marks itself and nothing else — the subtree is derived', () => {+ const { world, entities } = worldWith(2);+ setEntityActive(world, entities[0]!, false);+ // The tag says what the AUTHOR switched off; which entities that takes+ // out of a query is a walk down the tree, driven by the play-realm check+ // (a real hierarchy is the one thing a unit test has no engine for).+ expect(isEntityActive(world, entities[0]!)).toBe(false);+ expect(isEntityActive(world, entities[1]!)).toBe(true);+ expect(world.getEntitiesWithComponents([Health, Disabled])).toEqual([entities[0]]);});it('leaves the cached answer behind when it is switched', () => {diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex c2833f4da..2494eebae 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -125,7 +125,7 @@ const DISPOSITION = {ParticleForceField: ['owed', 'particle-demo adds force fields from code, and the field has a radius gizmo the Inspector already draws'],NavArea: ['owed', 'cost-modifying nav regions (mud, road) never appear; enemy-ai-3d authors NavVolume, NavLink and NavObstacle but no area'],Marker: ['owed', 'Create > Marker and Create > Trigger Area are one click each, and not one project places either — the converged target for .tmj object groups has no hand-authored instance'],- Disabled: ['owed', 'queries skip it now, but the editor still has no switch for it — the Outliner eye toggles visibility, which is a different thing — so no scene ships one'],+ Disabled: ['owed', 'queries skip it and the outliner switches it now; what is missing is a scene that ships something switched off — a boss gate, a tutorial-only prop'],Velocity: ['owed', 'motion without a physics body — the cheapest thing in the engine, authored nowhere'],};