Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(residency): the generation contract is held where it lives, not where it happens to show

esengine706c59b4e240
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2bb514b6..dfe9ae50e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,49 @@ published separately; it ships inside the editor.
### Added
+- **World streaming: a place exists because something is near it, and stops
+ existing when nothing is.** A scene loads whole, which is right until the world
+ is bigger than a machine wants resident at once — and then the question stops
+ being what is DRAWN and becomes what EXISTS. The cook cuts an authored world
+ into square cells on the XZ plane; at runtime `WorldStreamingSource` asks for
+ the places near it, and `WorldStreamer` is the one thing that decides.
+
+ Three authored declarations and no policy: `StreamedWorld` says a scene is cut
+ and how big the cells are, `WorldPersistent` keeps a subtree out of the
+ cutting, and `WorldStreamingSource` states one need. Several sources are
+ UNIONED rather than folded — a fold lets the last one written decide, and the
+ frame after a second camera exists it deletes the world the first is standing
+ in — which makes split screen, a spectator, a cinematic camera and an editor
+ preview one kind of thing. Distance is measured to a cell's box, not its
+ centre, because a centre answers the same for a source on a diagonal corner as
+ for one a whole cell away. A cell comes in at `loadRadius` and leaves only past
+ `unloadRadius`, so a source breathing on a boundary does not rebuild a place
+ every frame.
+
+ **Unloading is a real destroy.** A cell is an additively-loaded scene, so it
+ leaves through the scene lifecycle transaction that already exists: its
+ entities, its physics bodies, its navigating agents and its asset receipts all
+ go. A place that is merely hidden still costs memory, still collides, and still
+ lets an enemy nobody can see attack the player.
+
+ **A subtree is the unit of residency.** Only top-level entities are placed, so
+ a door cannot be sorted away from its house even when its own world position
+ falls in the next cell — the version that places each entity separately strands
+ children when their parent unloads. Hard entity references may not cross a
+ residency boundary: same cell is fine, and so is a cell naming the persistent
+ world, but one cell naming another's entity fails the build rather than
+ shipping a handle that dangles the first time a player walks away.
+
+ Residency owns existence and not continuity: a reloaded cell is rebuilt from
+ what was authored, so an enemy you walked away from comes back at full health.
+ What survives is the authored identity, which a save system can be built on.
+ `worldResidencyReport(app)` publishes counts of things that ARE, per cell,
+ because a cell that is not drawn and a cell that is not there look the same
+ from a camera. See the guide: **World → World Streaming**.
+
+ Not in this version: HLOD, streaming priority or prefetch, an asset memory
+ budget, navmesh or texture streaming, and world origin rebasing.
+
- **Level of detail: an object can hand over to a cheaper mesh once it is small
on screen.** A rock a hundred units away and a rock two thousand units away
were drawn with the same number of triangles, and at two thousand almost all of
diff --git a/bench/residency/run.mjs b/bench/residency/run.mjs
new file mode 100755
index 000000000..be0d5c2c2
--- /dev/null
+++ b/bench/residency/run.mjs
@@ -0,0 +1,217 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file bench/residency/run.mjs — what a streamed world costs to hold.
+ *
+ * Generates a 10x10 world of cells, packages it, and drives the real thing:
+ * cells arrive over the network into the same scene lifecycle a game uses, so
+ * every number here includes what a player would actually wait through.
+ *
+ * Three residencies from one source, chosen by radius: its own cell, its 3x3
+ * neighbourhood, its 5x5. And the scan itself, isolated — the same world cut
+ * into 100 cells and into 4, with NOTHING resident in either, so the difference
+ * over 96 cells is the per-frame cost of deciding.
+ *
+ * node bench/residency/run.mjs
+ * node bench/residency/run.mjs --props 40 denser cells
+ */
+import { spawnSync } from 'node:child_process';
+import { rmSync, mkdirSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { randomUUID } from 'node:crypto';
+import { runElectron } from '../../tools/lib/electronRun.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+const WORK = path.join(ROOT, '.golden', 'bench-residency');
+const LAUNCHER = path.join(ROOT, 'tools', 'launchers', 'residency-run.mjs');
+
+const flag = (name, fallback) => {
+ const at = process.argv.indexOf(`--${name}`);
+ return at >= 0 && process.argv[at + 1] ? process.argv[at + 1] : fallback;
+};
+
+const CELL = 600;
+const PROPS = Number(flag('props', '20'));
+const FRAMES = Number(flag('frames', '300'));
+
+/**
+ * Radii that select exactly 1, 9 and 25 cells for a source standing at a cell's
+ * centre. The gaps are wide: a 3x3 needs to reach a diagonal box corner at 424
+ * and must not reach the next ring at 900.
+ */
+const LEVELS = [
+ { key: 'Digit1', cells: 1, radius: 100 },
+ { key: 'Digit2', cells: 9, radius: 500 },
+ { key: 'Digit3', cells: 25, radius: 1300 },
+];
+
+function project(dir, columns) {
+ rmSync(dir, { recursive: true, force: true });
+ mkdirSync(path.join(dir, 'assets', 'scenes'), { recursive: true });
+ mkdirSync(path.join(dir, 'src'), { recursive: true });
+
+ const entities = [];
+ const transform = (x, y, z, s = 1) => ({
+ type: 'Transform',
+ data: { position: { x, y, z }, scale: { x: s, y: s, z: s } },
+ });
+ const box = (r, g, b) => ({
+ type: 'MeshRenderer',
+ data: { mesh: 'builtin:cube', lit: true, opaque: true, cullBackfaces: true,
+ color: { r, g, b, a: 1 } },
+ });
+ const push = (id, name, components, parent = null) =>
+ entities.push({ id, name, parent, children: [], visible: true, components });
+
+ // The source stands at the centre of the middle cell, so every radius below
+ // measures from one place.
+ const middle = Math.floor(columns / 2);
+ push(0, 'World', [transform(0, 0, 0),
+ { type: 'StreamedWorld', data: { cellSize: CELL, enabled: true } }]);
+ push(1, 'Camera', [transform(middle * CELL + 300, 900, middle * CELL + 1200),
+ { type: 'Camera', data: { projectionType: 0, fov: 55, nearPlane: 10, farPlane: 20000,
+ isActive: true, priority: 0 } },
+ { type: 'WorldPersistent', data: {} }]);
+ push(2, 'Sun', [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 0.834, x: -0.521, y: 0.182, z: 0 } } },
+ { type: 'Light', data: { type: 1, intensity: 1.05, enabled: true,
+ color: { r: 1, g: 0.96, b: 0.9, a: 1 } } },
+ { type: 'WorldPersistent', data: {} }]);
+ push(3, 'Source', [transform(middle * CELL + 300, 60, middle * CELL + 300),
+ { type: 'WorldStreamingSource', data: { loadRadius: 0, unloadRadius: 0, enabled: false } },
+ { type: 'WorldPersistent', data: {} }]);
+
+ let id = 100;
+ for (let cx = 0; cx < columns; cx++) {
+ for (let cz = 0; cz < columns; cz++) {
+ for (let n = 0; n < PROPS; n++) {
+ const x = cx * CELL + 40 + (n % 5) * 120;
+ const z = cz * CELL + 40 + Math.floor(n / 5) * 120;
+ push(id++, `P_${cx}_${cz}_${n}`, [transform(x, 30, z, 0.5), box(0.6, 0.55, 0.45)]);
+ }
+ }
+ }
+
+ writeFileSync(path.join(dir, 'assets', 'scenes', 'main.esscene'),
+ JSON.stringify({ version: 4, name: 'main', entities }, null, 1) + '\n');
+ writeFileSync(path.join(dir, 'assets', 'scenes', 'main.esscene.meta'),
+ JSON.stringify({ uuid: randomUUID(), version: '2.0', type: 'scene', importer: {} }) + '\n');
+ writeFileSync(path.join(dir, 'project.esproject'), JSON.stringify({
+ formatVersion: '1', name: 'Residency Bench', description: 'A generated world of cells.',
+ tag: '3D', version: '0.1.0', defaultScene: 'assets/scenes/main.esscene',
+ designResolution: { width: 640, height: 360 }, spineVersion: 'none',
+ }, null, 2) + '\n');
+ // The radius is the knob, and only the game may turn it: a driver that could
+ // set residency directly would be measuring itself.
+ writeFileSync(path.join(dir, 'src', 'main.ts'), `
+import { addSystemToSchedule, Schedule, defineSystem, GetWorld, Res, Input, WorldStreamingSource } from 'esengine';
+import type { World, InputState } from 'esengine';
+
+const RADII: Record<string, number> = ${JSON.stringify(
+ Object.fromEntries([['Digit0', 0], ...LEVELS.map((l) => [l.key, l.radius])]))};
+
+const radiusSystem = defineSystem(
+ [Res(Input), GetWorld()],
+ (input: InputState, world: World) => {
+ for (const key of Object.keys(RADII)) {
+ if (!input.isKeyPressed(key)) continue;
+ const source = world.findEntityByName('Source');
+ if (source === null) continue;
+ world.update(source, WorldStreamingSource, (s) => {
+ s.loadRadius = RADII[key];
+ s.unloadRadius = RADII[key] * 1.05;
+ s.enabled = RADII[key] > 0;
+ });
+ }
+ },
+ { name: 'RadiusSystem' },
+);
+addSystemToSchedule(Schedule.Update, radiusSystem);
+`);
+ writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
+ compilerOptions: {
+ target: 'ES2020', module: 'ESNext', moduleResolution: 'bundler', strict: true,
+ esModuleInterop: true, skipLibCheck: true, noEmit: true,
+ paths: { esengine: ['./.esengine/sdk/index.d.ts'] },
+ },
+ include: ['src/**/*'],
+ }, null, 2) + '\n');
+ return dir;
+}
+
+function packageProject(dir, out) {
+ const r = spawnSync(process.execPath, [
+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', dir,
+ '--platform', 'web', '--out', out,
+ ], { encoding: 'utf8', cwd: ROOT });
+ if (r.status !== 0) {
+ console.error(`✗ the bench world did not package:\n${(r.stderr || r.stdout || '').slice(-800)}`);
+ process.exit(1);
+ }
+ return out;
+}
+
+function drive(dir, name, steps) {
+ const script = path.join(WORK, `${name}.json`);
+ writeFileSync(script, JSON.stringify(steps, null, 2));
+ const r = runElectron([LAUNCHER, '--dir', dir, '--script', script, '--w', '640', '--h', '360'],
+ { encoding: 'utf8', cwd: ROOT });
+ const out = {};
+ for (const line of (r.stdout || '').split('\n')) {
+ const at = Math.max(line.indexOf('timing '), line.indexOf('reading '));
+ if (at < 0) continue;
+ const label = line.slice(line.indexOf(' ', at) + 1, line.indexOf(':', at));
+ try { out[label] = JSON.parse(line.slice(line.indexOf('{', at))); } catch { /* partial line */ }
+ }
+ if (Object.keys(out).length === 0) {
+ console.error(`✗ ${name}: nothing was measured — ${(r.stdout || r.stderr || '').slice(-400)}`);
+ process.exit(1);
+ }
+ return out;
+}
+
+const ms = (v) => `${v.toFixed(2)} ms`;
+
+function main() {
+ rmSync(WORK, { recursive: true, force: true });
+ mkdirSync(WORK, { recursive: true });
+
+ const wide = packageProject(project(path.join(WORK, 'src-100'), 10), path.join(WORK, 'web-100'));
+ const narrow = packageProject(project(path.join(WORK, 'src-4'), 2), path.join(WORK, 'web-4'));
+
+ const steps = [{ do: 'step', frames: 30 }, { do: 'time', as: 'idle', frames: FRAMES }];
+ for (const level of LEVELS) {
+ steps.push({ do: 'arrive', as: `arrive${level.cells}`, key: level.key });
+ steps.push({ do: 'time', as: `hold${level.cells}`, frames: FRAMES });
+ steps.push({ do: 'arrive', as: `leave${level.cells}`, key: 'Digit0' });
+ }
+ const held = drive(wide, 'held', steps);
+ const scan = drive(narrow, 'scan', [{ do: 'step', frames: 30 },
+ { do: 'time', as: 'idle', frames: FRAMES }]);
+
+ console.log(`\nresidency — ${100} cells authored, ${PROPS} props each, cell ${CELL} wu\n`);
+ console.log(' level cells entities renderers bodies refs hold/frame arrive leave');
+ for (const level of LEVELS) {
+ const hold = held[`hold${level.cells}`];
+ const s = hold.streaming;
+ const entities = Object.values(s.cellEntityCounts).reduce((a, b) => a + b, 0);
+ const renderers = Object.values(s.cellRenderCounts).reduce((a, b) => a + b, 0);
+ const refs = Object.values(s.assetRefsByCell).reduce((a, b) => a + b, 0);
+ console.log(` ${String(level.cells).padStart(5)} ${String(s.residentCells.length).padStart(5)}`
+ + ` ${String(entities).padStart(8)} ${String(renderers).padStart(9)}`
+ + ` ${String(s.physicsBodies).padStart(6)} ${String(refs).padStart(4)}`
+ + ` ${ms(hold.msPerFrame).padStart(11)}`
+ + ` ${ms(held[`arrive${level.cells}`].ms).padStart(7)}`
+ + ` ${ms(held[`leave${level.cells}`].ms).padStart(6)}`);
+ }
+ // Nothing resident in either, so what differs is 96 cells' worth of deciding.
+ const wideIdle = held.idle.msPerFrame;
+ const narrowIdle = scan.idle.msPerFrame;
+ console.log(`\n deciding: ${ms(wideIdle)}/frame over 100 cells vs ${ms(narrowIdle)} over 4`
+ + ` → ${((wideIdle - narrowIdle) / 96 * 1000).toFixed(1)} µs per 100 cells scanned`);
+ console.log(` (nothing is resident in either, so the difference is the scan and not the content)\n`);
+}
+
+main();
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 3cad5086c..a4c87682d 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -287,6 +287,7 @@ export default defineConfig({
{ label: 'Prefabs', translations: { 'zh-CN': '预制体' }, slug: 'world/prefabs' },
{ label: 'Tilemaps', translations: { 'zh-CN': '瓦片地图' }, slug: 'world/tilemaps' },
{ label: 'Particles', translations: { 'zh-CN': '粒子' }, slug: 'world/particles' },
+ { label: 'World Streaming', translations: { 'zh-CN': '世界流送' }, slug: 'world/streaming' },
],
},
{
diff --git a/docs/astro/src/content/docs/world/streaming.mdx b/docs/astro/src/content/docs/world/streaming.mdx
new file mode 100644
index 000000000..dc92183eb
--- /dev/null
+++ b/docs/astro/src/content/docs/world/streaming.mdx
@@ -0,0 +1,130 @@
+---
+title: World Streaming
+description: Cut a large world into cells at cook time and let residency decide which of them exist — streaming sources, load and unload radii, what a persistent world holds, and the rules a cell has to obey.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+A scene loads whole. That is the right answer until the world is bigger than a
+machine wants resident at once — and then the question stops being "what is
+drawn" and becomes **"what exists"**. World streaming answers the second one: the
+cook cuts an authored world into square cells, and at runtime a cell exists
+because something is near it, and stops existing when nothing is.
+
+Nothing about this is a visibility trick. A cell that leaves is destroyed: its
+entities, its physics bodies, its navigating agents and its asset references all
+go. That is the point — a place that is merely hidden still costs memory, still
+collides, and still lets an enemy nobody can see attack the player.
+
+## Declaring a streamed world
+
+Two components, both authored in the scene:
+
+```typescript
+// On the world's settings entity: this scene is cut into 1000-unit cells.
+world.insert(settings, StreamedWorld, { cellSize: 1000 });
+
+// On everything that must never be streamed away.
+world.insert(player, WorldPersistent, {});
+world.insert(camera, WorldPersistent, {});
+world.insert(sun, WorldPersistent, {});
+```
+
+Everything else is placed into a cell by **where its top-level entity stands**.
+A scene with no `StreamedWorld` in it is not a streamed world and loads exactly
+as it always did.
+
+<Aside type="note">
+`WorldPersistent` is not scene persistence. `SceneContext.setPersistent` decides
+whether an entity survives a scene *switch*; `WorldPersistent` decides which
+cooked scene an entity is written into, and therefore whether residency can
+remove it at all.
+</Aside>
+
+## Asking for places: streaming sources
+
+A cell exists because a **source** is near it:
+
+```typescript
+world.insert(player, WorldStreamingSource, {
+ loadRadius: 2000, // cells this close are brought in
+ unloadRadius: 3000, // resident cells are kept until past this
+});
+```
+
+Several sources may exist, and what they ask for is **unioned** — a cell any one
+of them needs stays resident. That is what makes split screen, a spectator
+camera, a cinematic camera and an editor preview the same kind of thing rather
+than four special cases. Nothing folds them into a single focus, because a fold
+lets the last one written decide, and the frame after a second camera exists it
+deletes the world the first is standing in.
+
+Distance is measured to the cell's **box**, not its centre: to a centre, a source
+standing on a diagonal corner reads the same as one a whole cell away, which is
+where holes open along the diagonals of a grid.
+
+### The band between the two radii
+
+A cell comes in at `loadRadius` and only leaves once it is past `unloadRadius`.
+The gap between them is the whole reason both exist: a source standing on a
+boundary would otherwise spend every frame instantiating and destroying a place.
+Set `unloadRadius` comfortably larger than `loadRadius` — half again is a good
+starting point.
+
+## What the cook produces
+
+Partitioning happens at **cook time**, not at boot:
+
+```
+main.esscene ──cook──▶ main.esscene the persistent world
+ world/main.world.json the manifest
+ world/main.cell_0_0.json
+ world/main.cell_1_0.json ...
+```
+
+The entry scene the package boots is what is left after the cells are taken out
+of it — the things residency never removes. Cells are **not** switchable scenes:
+they are content residency brings in, and a game never names one.
+
+Cells are cut on the XZ plane only. A cell is a vertical column, so a tower's
+floors are one place.
+
+## The rules a streamed world has to obey
+
+**A subtree is the unit of residency.** Only top-level entities are placed, so a
+door cannot be sorted away from its house even if the door's world position falls
+in the next cell. A cell's box grows to cover its content, so a prop hanging over
+the edge does not pop in at the boundary.
+
+**Hard entity references may not cross a residency boundary.** Two entities in
+one cell may reference each other; so may anything in the persistent world; and a
+cell may reference the persistent world, which outlives it. A reference from one
+cell into another — or from the persistent world into a cell — fails the build,
+because either one points at something residency is entitled to delete.
+
+**Residency owns existence; it does not own continuity.** A cell that unloads
+loses its runtime state, and reloading rebuilds it from what was authored. An
+enemy at 25 health that you walk away from comes back at full health. What does
+survive is the entity's authored identity, which is what a save system will be
+built on later.
+
+## Reading what is resident
+
+```typescript
+const report = worldResidencyReport(app);
+report.residentCells; // ['main.cell_1_0', 'main.cell_2_0']
+report.cellEntityCounts; // live entities each resident cell owns
+report.loadCount; // places brought in since boot
+```
+
+Counts rather than a picture, because a cell that is not drawn and a cell that
+does not exist look the same from a camera.
+
+## What this version does not do
+
+Cells load asynchronously through the same scene loading a game already uses, but
+there is no priority, no prefetch and no budget yet: a large cell arriving is a
+hitch. There is no HLOD, so a place that is not resident is not represented at
+all in the distance. Navigation meshes are not streamed — a world-sized navmesh
+stays resident. Neither is texture streaming, and the world origin is never
+rebased.
diff --git a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx b/docs/astro/src/content/docs/zh-cn/world/streaming.mdx
new file mode 100644
index 000000000..10fc4a1e0
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/world/streaming.mdx
@@ -0,0 +1,111 @@
+---
+title: 世界流送
+description: cook 时把大世界切成格子,由 residency 决定哪些格子此刻应该存在——流送源、加载/卸载半径、持久世界的边界,以及一个格子必须遵守的规则。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+场景是整体加载的。在世界大到一台机器不愿意一次性常驻之前,这都是对的答案;越过那条线
+之后,问题就不再是"什么被画出来",而是**"什么存在"**。世界流送回答后者:cook 把作者
+编排的世界切成方形格子,运行时一个格子之所以存在,是因为有东西靠近它;没有任何东西需要
+它时,它就不再存在。
+
+这里没有任何"隐藏"的把戏。离开的格子是被**销毁**的:它的实体、刚体、导航代理、资源引用
+全部交回。这正是重点——只是被隐藏的地方仍然占内存、仍然会碰撞,也仍然允许一个谁都看不见
+的敌人攻击玩家。
+
+## 声明一个流送世界
+
+两个组件,都在场景里编排:
+
+```typescript
+// 挂在世界设置实体上:这个场景按 1000 单位的格子切分。
+world.insert(settings, StreamedWorld, { cellSize: 1000 });
+
+// 挂在任何绝不允许被流送掉的东西上。
+world.insert(player, WorldPersistent, {});
+world.insert(camera, WorldPersistent, {});
+world.insert(sun, WorldPersistent, {});
+```
+
+其余一切按**它所在顶层实体的位置**落入某个格子。没有 `StreamedWorld` 的场景不是流送
+世界,加载方式和以前完全一样。
+
+<Aside type="note">
+`WorldPersistent` 不是场景持久化。`SceneContext.setPersistent` 决定一个实体能否活过
+一次场景**切换**;`WorldPersistent` 决定这个实体被写进哪一份 cooked 场景,也就决定了
+residency 到底能不能移除它。
+</Aside>
+
+## 请求"地方存在":流送源
+
+一个格子之所以存在,是因为有**源**靠近它:
+
+```typescript
+world.insert(player, WorldStreamingSource, {
+ loadRadius: 2000, // 距离在此以内的格子被带进来
+ unloadRadius: 3000, // 已常驻的格子在越过这个距离前一直保留
+});
+```
+
+可以同时存在多个源,它们的请求是**并集**——只要任意一个源需要,格子就继续常驻。这正是
+分屏、观战相机、过场相机和编辑器预览可以是同一类东西、而不是四个特例的原因。这里不会把
+多个源折叠成一个焦点:折叠意味着最后写入的那个说了算,于是第二个相机出现的下一帧,它就
+把第一个相机正站着的那片世界删掉了。
+
+距离量到格子的**包围盒**,而不是中心点:按中心量,站在对角角落的源和隔了整整一格的源
+读数相同,而网格的对角线正是"洞"出现的地方。
+
+### 两个半径之间的带
+
+格子在 `loadRadius` 处进来,直到越过 `unloadRadius` 才离开。两者之间的空隙就是它们都
+必须存在的全部理由:否则一个站在边界上的源会每一帧都在实例化和销毁同一个地方。把
+`unloadRadius` 设得比 `loadRadius` 明显更大——多出一半是个不错的起点。
+
+## cook 产出什么
+
+切分发生在 **cook 时**,不在启动时:
+
+```
+main.esscene ──cook──▶ main.esscene 持久世界
+ world/main.world.json 清单
+ world/main.cell_0_0.json
+ world/main.cell_1_0.json ...
+```
+
+包体启动的入口场景,是把格子取走之后剩下的东西——residency 永远不会移除的那部分。格子
+**不是**可切换的场景:它们是 residency 带进来的内容,游戏永远不会点名其中任何一个。
+
+格子只在 XZ 平面上切。一个格子是一根垂直柱体,所以一座塔的各层是同一个地方。
+
+## 一个流送世界必须遵守的规则
+
+**子树是 residency 的最小单位。** 只有顶层实体会被定位,所以即使一扇门的世界坐标落在
+隔壁格子里,它也不会被从自己的房子里分出去。格子的包围盒会扩张到覆盖它的内容,因此悬在
+边缘外的道具不会在边界处突然弹出。
+
+**硬实体引用不允许跨越 residency 边界。** 同一个格子里的两个实体可以互相引用;持久世界
+内部也可以;格子引用持久世界也可以,因为持久世界比每一个格子都活得久。而从一个格子指向
+另一个格子、或者从持久世界指向格子内部——都会让构建失败,因为它们指向的东西 residency
+有权删除。
+
+**Residency 拥有"存在",不拥有"延续"。** 卸载的格子会丢掉运行时状态,重新加载会按编排
+内容重建。你走开时只剩 25 点血的敌人,回来时是满血的。真正留下来的是实体的编排身份,
+以后的存档系统会建在它上面。
+
+## 读取当前常驻状态
+
+```typescript
+const report = worldResidencyReport(app);
+report.residentCells; // ['main.cell_1_0', 'main.cell_2_0']
+report.cellEntityCounts; // 每个常驻格子当前拥有的实体数
+report.loadCount; // 启动以来带进来过多少个地方
+```
+
+给的是计数而不是画面,因为"没有被画出来的格子"和"根本不存在的格子",从相机看是一样的。
+
+## 这一版不做什么
+
+格子通过游戏本来就在用的场景加载路径异步到达,但还没有优先级、预取和预算:一个大格子
+到达时就是一次卡顿。没有 HLOD,所以不常驻的地方在远处根本没有任何表示。导航网格不流送
+——世界尺寸的 navmesh 一直常驻。纹理流送同样没有,世界原点也从不重定基准。
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index d98645441..cae5deb7a 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -75,6 +75,9 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
PostProcessVolume: { category: 'graphics', summary: 'A stack of full-screen effects (bloom, vignette, colour grading) applied after the scene is drawn.', doc: 'graphics/post-processing', anchor: 'using-a-postprocessvolume', anchorZh: '使用-postprocessvolume' },
MeshRenderer: { category: 'graphics', summary: 'Geometry drawn as an entity — your own vertices or an imported mesh, with a material and a sorting layer.', doc: 'graphics/drawing', anchor: 'custom-meshes-meshrenderer', anchorZh: '自定义网格meshrenderer' },
MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a MeshRenderer — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
+ StreamedWorld: { category: 'world', summary: 'Declares the scene a streamed world and how big the cook cuts its cells.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
+ WorldPersistent: { category: 'world', summary: 'Keeps an entity\'s whole subtree out of the partition — it belongs to the persistent world.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
+ WorldStreamingSource: { category: 'world', summary: 'Asks for the places near it to exist; several sources are unioned.', doc: 'world/streaming', anchor: 'asking-for-places-streaming-sources', anchorZh: '请求地方存在流送源' },
LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
Video: { category: 'graphics', summary: 'Plays a video stream onto a surface in the world or the UI.', doc: 'graphics/video', anchor: 'the-video-component', anchorZh: 'video-组件' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 76d098b53..80aace373 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -4014,6 +4014,22 @@
}
]
},
+ {
+ "name": "StreamedWorld",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "cellSize",
+ "type": "number",
+ "default": "1000",
+ "doc": "Edge of one cell on the XZ plane.",
+ "range": "≥ 1"
+ }
+ ],
+ "animatable": [
+ "cellSize"
+ ]
+ },
{
"name": "Text",
"source": "ts",
@@ -5463,6 +5479,41 @@
"maxMotorTorque",
"motorSpeed"
]
+ },
+ {
+ "name": "WorldPersistent",
+ "source": "ts",
+ "fields": [],
+ "tag": true
+ },
+ {
+ "name": "WorldStreamingSource",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "loadRadius",
+ "type": "number",
+ "default": "2000",
+ "doc": "Cells this close are brought in.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "unloadRadius",
+ "type": "number",
+ "default": "3000",
+ "doc": "Resident cells are kept until past this.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "loadRadius",
+ "unloadRadius"
+ ]
}
]
}
diff --git a/examples/world-streaming-3d/README.md b/examples/world-streaming-3d/README.md
new file mode 100644
index 000000000..cd26f79ca
--- /dev/null
+++ b/examples/world-streaming-3d/README.md
@@ -0,0 +1,29 @@
+# World Streaming 3D
+
+A world cut into cells at cook time. Places exist because a source is near them,
+and stop existing — really stop, not stop being drawn — when none is.
+
+- **WASD / arrows** — walk. Walking is what makes places arrive and leave.
+- **K** — switch the player's streaming source off and on. With nobody asking,
+ every cell leaves.
+- **L** — switch on a second source parked in the far cell. Two sources are
+ unioned, so it brings its own place in without taking the first away.
+- **M** — set a third source oscillating across a cell boundary. It crosses the
+ load threshold repeatedly and never the unload one, so the place comes in once.
+- **J** — aim a blow at the enemy this project *remembered* before its cell
+ unloaded, and at a canary that never leaves.
+
+| In the scene | What it is there for |
+|---|---|
+| `StreamedWorld` on `World` | Declares the scene streamed and the cells 600 units across. |
+| `WorldPersistent` | The player, the camera, the sun, the ground, the sources. Never streamed. |
+| `WorldStreamingSource` on `Player` | Asks for the places near it: in at 250, out past 450. |
+| `Arch` with a child at +400 | A subtree whose child stands in another cell — it still arrives and leaves whole. |
+| `Wall` in the middle cell | Something a player can walk into, so "the cell unloaded" can be told from "the cell stopped drawing". |
+| `Enemy` in the middle cell | Hunts, navigates and collides — all of which must be gone when its cell is. |
+
+This is a **fixture**. Its cell size, radii and coordinates answer to
+`tools/verify-world-residency.mjs` and to nothing else, which is also why the
+ground is persistent (so a walk can be repeated with a cell absent rather than
+ending in a fall) and why every cell entity carries `Health` (so a blow that
+landed on a recycled handle is visible whichever entity inherited it).
diff --git a/examples/world-streaming-3d/assets/scenes/main.esscene b/examples/world-streaming-3d/assets/scenes/main.esscene
index 7353a02ed..3ce332d3a 100644
--- a/examples/world-streaming-3d/assets/scenes/main.esscene
+++ b/examples/world-streaming-3d/assets/scenes/main.esscene
@@ -64,8 +64,7 @@
{
"type": "StreamedWorld",
"data": {
- "cellSize": 600,
- "enabled": true
+ "cellSize": 600
}
}
]
@@ -436,6 +435,13 @@
"a": 1
}
}
+ },
+ {
+ "type": "Health",
+ "data": {
+ "current": 100,
+ "max": 100
+ }
}
]
},
@@ -492,6 +498,13 @@
"a": 1
}
}
+ },
+ {
+ "type": "Health",
+ "data": {
+ "current": 100,
+ "max": 100
+ }
}
]
},
@@ -633,6 +646,13 @@
"a": 1
}
}
+ },
+ {
+ "type": "Health",
+ "data": {
+ "current": 100,
+ "max": 100
+ }
}
]
},
@@ -672,6 +692,13 @@
"a": 1
}
}
+ },
+ {
+ "type": "Health",
+ "data": {
+ "current": 100,
+ "max": 100
+ }
}
]
},
@@ -711,6 +738,13 @@
"a": 1
}
}
+ },
+ {
+ "type": "Health",
+ "data": {
+ "current": 100,
+ "max": 100
+ }
}
]
}
diff --git a/examples/world-streaming-3d/src/main.ts b/examples/world-streaming-3d/src/main.ts
index 6065f831a..f5e79f9a8 100644
--- a/examples/world-streaming-3d/src/main.ts
+++ b/examples/world-streaming-3d/src/main.ts
@@ -50,24 +50,26 @@ const bobberSystem = defineSystem(
* The pair is the point: the canary proves the gesture reached the damage bus,
* so the enemy being untouched is a handle refused, not a key that did nothing.
*/
-let remembered = 0;
+const remembered: Record<string, number> = { Enemy: 0, Beacon: 0 };
const staleBlowSystem = defineSystem(
[Res(Input), GetWorld(), EventWriter(Damage)],
(input: InputState, world: World, damage: EventWriterInstance<DamagePayload>) => {
- // Remembered ONCE. Refreshing it every frame is how a test for a stale
- // handle quietly becomes a test for a live one: after the cell comes back
- // the name resolves again, to a different entity.
- if (remembered === 0) {
- const enemy = world.findEntityByName('Enemy');
- if (enemy !== null) remembered = enemy;
+ // Remembered ONCE each. Refreshing them is how a test for a stale handle
+ // quietly becomes a test for a live one: after the cell comes back the
+ // name resolves again, to a different entity.
+ for (const name of Object.keys(remembered)) {
+ if (remembered[name] !== 0) continue;
+ const entity = world.findEntityByName(name);
+ if (entity !== null) remembered[name] = entity;
}
- if (!input.isKeyPressed('KeyJ') || remembered === 0) return;
+ if (!input.isKeyPressed('KeyJ')) return;
const player = world.findEntityByName('Player') ?? 0;
- const canary = world.findEntityByName('Canary');
- damage.send({ target: remembered, source: player, amount: 25, x: 0, y: 0, z: 0 });
- if (canary !== null) {
- damage.send({ target: canary, source: player, amount: 25, x: 0, y: 0, z: 0 });
- }
+ const blow = (target: number): void => {
+ if (target !== 0) damage.send({ target, source: player, amount: 25, x: 0, y: 0, z: 0 });
+ };
+ blow(remembered.Enemy);
+ blow(remembered.Beacon);
+ blow(world.findEntityByName('Canary') ?? 0);
},
{ name: 'StaleBlowSystem' },
);
diff --git a/pipeline/src/world/partitionWorld.ts b/pipeline/src/world/partitionWorld.ts
index 23e033320..ce5879e20 100644
--- a/pipeline/src/world/partitionWorld.ts
+++ b/pipeline/src/world/partitionWorld.ts
@@ -199,7 +199,6 @@ export function partitionWorld(
for (const entry of entries) {
if (!hasComponent(entry, 'StreamedWorld')) continue;
const declaration = componentData(entry, 'StreamedWorld');
- if (declaration && declaration.enabled === false) return null;
cellSize = typeof declaration?.cellSize === 'number' ? declaration.cellSize : 0;
break;
}
diff --git a/pipeline/tests/partition-world.test.ts b/pipeline/tests/partition-world.test.ts
index 5697d1ea9..9ebe6e54a 100644
--- a/pipeline/tests/partition-world.test.ts
+++ b/pipeline/tests/partition-world.test.ts
@@ -28,7 +28,7 @@ function entity(
return { id, name, parent: extra.parent ?? null, children: [], visible: true, components };
}
-const declaration: Component = { type: 'StreamedWorld', data: { cellSize: SIZE, enabled: true } };
+const declaration: Component = { type: 'StreamedWorld', data: { cellSize: SIZE } };
function scene(...entities: Array<Record<string, unknown>>): SceneData {
return { version: 4, name: 'main', entities } as unknown as SceneData;
@@ -185,11 +185,4 @@ describe('partitionWorld', () => {
))!;
expect(partition.errors.join('\n')).toContain('no positive cellSize');
});
-
- it('answers null for a world whose streaming is switched off', () => {
- expect(cut(scene(
- entity(0, 'World', null, { components: [{ type: 'StreamedWorld', data: { cellSize: SIZE, enabled: false } }] }),
- entity(1, 'RockA', [500, 0, 500]),
- ))).toBeNull();
- });
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 206bf62e3..a350c35b9 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -8141,7 +8141,6 @@ ComponentDef<StreamedWorldData>
## StreamedWorldData — interface @experimental
```
cellSize: number
-enabled: boolean
```
## SubEmitterTrigger — enum @beta
@@ -10096,9 +10095,8 @@ assetRefsByCell: Record<string, number>
authoredCellEntityCounts: Record<string, number>
cellCount: number
cellEntityCounts: Record<string, number>
-cellHandles: Record<string, number[]>
cellRenderCounts: Record<string, number>
-cellStableIds: Record<string, number[]>
+cellRows: Record<string, { id: number; entity: number; }[]>
desiredCells: string[]
loadCount: number
loadingCells: string[]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6d180509d..6f2ec0ba3 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -8334,7 +8334,6 @@ ComponentDef<StreamedWorldData>
## StreamedWorldData — interface @experimental
```
cellSize: number
-enabled: boolean
```
## SubEmitterTrigger — enum @beta
@@ -10289,9 +10288,8 @@ assetRefsByCell: Record<string, number>
authoredCellEntityCounts: Record<string, number>
cellCount: number
cellEntityCounts: Record<string, number>
-cellHandles: Record<string, number[]>
cellRenderCounts: Record<string, number>
-cellStableIds: Record<string, number[]>
+cellRows: Record<string, { id: number; entity: number; }[]>
desiredCells: string[]
loadCount: number
loadingCells: string[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fa392e98f..8e41c41e1 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -8136,7 +8136,6 @@ ComponentDef<StreamedWorldData>
## StreamedWorldData — interface @experimental
```
cellSize: number
-enabled: boolean
```
## SubEmitterTrigger — enum @beta
@@ -10091,9 +10090,8 @@ assetRefsByCell: Record<string, number>
authoredCellEntityCounts: Record<string, number>
cellCount: number
cellEntityCounts: Record<string, number>
-cellHandles: Record<string, number[]>
cellRenderCounts: Record<string, number>
-cellStableIds: Record<string, number[]>
+cellRows: Record<string, { id: number; entity: number; }[]>
desiredCells: string[]
loadCount: number
loadingCells: string[]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index abe8bf734..9ea73ef22 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -8382,7 +8382,6 @@ ComponentDef<StreamedWorldData>
## StreamedWorldData — interface @experimental
```
cellSize: number
-enabled: boolean
```
## SubEmitterTrigger — enum @beta
@@ -10343,9 +10342,8 @@ assetRefsByCell: Record<string, number>
authoredCellEntityCounts: Record<string, number>
cellCount: number
cellEntityCounts: Record<string, number>
-cellHandles: Record<string, number[]>
cellRenderCounts: Record<string, number>
-cellStableIds: Record<string, number[]>
+cellRows: Record<string, { id: number; entity: number; }[]>
desiredCells: string[]
loadCount: number
loadingCells: string[]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 84b85633a..a12905068 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -8143,7 +8143,6 @@ ComponentDef<StreamedWorldData>
## StreamedWorldData — interface @experimental
```
cellSize: number
-enabled: boolean
```
## SubEmitterTrigger — enum @beta
@@ -10119,9 +10118,8 @@ assetRefsByCell: Record<string, number>
authoredCellEntityCounts: Record<string, number>
cellCount: number
cellEntityCounts: Record<string, number>
-cellHandles: Record<string, number[]>
cellRenderCounts: Record<string, number>
-cellStableIds: Record<string, number[]>
+cellRows: Record<string, { id: number; entity: number; }[]>
desiredCells: string[]
loadCount: number
loadingCells: string[]
diff --git a/sdk/src/residency/components.ts b/sdk/src/residency/components.ts
index 39f91af5b..48198c764 100644
--- a/sdk/src/residency/components.ts
+++ b/sdk/src/residency/components.ts
@@ -22,20 +22,20 @@ export interface StreamedWorldData {
* partition: a cell is a vertical column, so a tower's floors are one place.
*/
cellSize: number;
- enabled: boolean;
}
/**
* Declares the scene carrying it a streamed world, and how the cook cuts it.
*
* Its entity is persistent by construction — it is what says the world streams.
- * Without this component a scene loads whole, which is what a small one should.
+ * Presence is the switch: remove it and the scene loads whole, which is what a
+ * small one should do and what every scene did before.
*
* @experimental
*/
export const StreamedWorld: ComponentDef<StreamedWorldData> = defineComponent<StreamedWorldData>(
'StreamedWorld',
- { cellSize: 1000, enabled: true },
+ { cellSize: 1000 },
{
fields: {
cellSize: { min: 1, unit: 'wu', tooltip: 'Edge of one cell on the XZ plane.' },
diff --git a/sdk/src/residency/report.ts b/sdk/src/residency/report.ts
index 65cae31d6..8ecbb2f4a 100644
--- a/sdk/src/residency/report.ts
+++ b/sdk/src/residency/report.ts
@@ -40,10 +40,12 @@ export interface WorldResidencyReport {
assetRefsByCell: Record<string, number>;
/** What the cook put in each cell — the number a live count is checked against. */
authoredCellEntityCounts: Record<string, number>;
- /** The authored rows each resident cell instantiated; unchanged by a reload. */
- cellStableIds: Record<string, number[]>;
- /** The runtime handles those rows currently have; a reload mints new ones. */
- cellHandles: Record<string, number[]>;
+ /**
+ * Each resident cell's authored rows and the handle each one currently has.
+ * The row survives a reload and the handle does not, which is the difference
+ * between an identity and a way to reach something that exists.
+ */
+ cellRows: Record<string, Array<{ id: number; entity: number }>>;
/** Live entities the persistent world owns; residency never touches these. */
persistentEntities: number;
/** Their handles. Unchanged for the life of the world — that is the claim. */
@@ -55,7 +57,7 @@ const EMPTY: WorldResidencyReport = {
desiredCells: [], residentCells: [], loadingCells: [], unloadingCells: [],
loadCount: 0, unloadCount: 0,
cellEntityCounts: {}, cellRenderCounts: {}, assetRefsByCell: {},
- authoredCellEntityCounts: {}, cellStableIds: {}, cellHandles: {},
+ authoredCellEntityCounts: {}, cellRows: {},
persistentEntities: 0, persistentHandles: [],
};
@@ -76,8 +78,7 @@ export function worldResidencyReport(app: App): WorldResidencyReport {
const cellRenderCounts: Record<string, number> = {};
const assetRefsByCell: Record<string, number> = {};
const authoredCellEntityCounts: Record<string, number> = {};
- const cellStableIds: Record<string, number[]> = {};
- const cellHandles: Record<string, number[]> = {};
+ const cellRows: Record<string, Array<{ id: number; entity: number }>> = {};
const drawing = renderableComponents();
for (const cell of manifest.cells) {
authoredCellEntityCounts[cell.name] = cell.entityCount;
@@ -86,18 +87,15 @@ export function worldResidencyReport(app: App): WorldResidencyReport {
// between "not here" and "here and empty" that a zero would hide.
if (context === null) continue;
let drawn = 0;
- const stable: number[] = [];
- const handles: number[] = [];
+ const rows: Array<{ id: number; entity: number }> = [];
for (const entity of context.entities) {
if (drawing.some((component) => app.world.has(entity, component))) drawn++;
const authored = stableEntityId(app, entity);
- if (authored !== undefined) stable.push(authored);
- handles.push(entity);
+ if (authored !== undefined) rows.push({ id: authored, entity });
}
cellEntityCounts[cell.name] = context.entities.size;
cellRenderCounts[cell.name] = drawn;
- cellStableIds[cell.name] = stable.sort((a, b) => a - b);
- cellHandles[cell.name] = handles.sort((a, b) => a - b);
+ cellRows[cell.name] = rows.sort((a, b) => a.id - b.id);
assetRefsByCell[cell.name] = scenes.assetScopeFor(cell.name)?.size ?? 0;
}
@@ -113,7 +111,7 @@ export function worldResidencyReport(app: App): WorldResidencyReport {
loadCount: status.loadCount,
unloadCount: status.unloadCount,
cellEntityCounts, cellRenderCounts, assetRefsByCell, authoredCellEntityCounts,
- cellStableIds, cellHandles,
+ cellRows,
persistentEntities: persistent.length,
persistentHandles: persistent,
};
diff --git a/sdk/tests/world-residency.test.ts b/sdk/tests/world-residency.test.ts
index 35f082a7b..6cd3e4a25 100644
--- a/sdk/tests/world-residency.test.ts
+++ b/sdk/tests/world-residency.test.ts
@@ -11,6 +11,9 @@ import {
} from '../src/residency/cells';
import { WorldStreamer, type WorldStreamHost } from '../src/residency/WorldStreamer';
import type { WorldManifest } from '../src/residency/cells';
+import { World } from '../src/ecs/world';
+import { Health, applyDamage } from '../src/gameplay/Health';
+import { makeEntity, entityIndex, entityGeneration } from '../src/types';
const flush = async () => { await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); };
@@ -193,3 +196,27 @@ describe('WorldStreamer', () => {
expect(streamer.residencyOf('c_0_0')).toBe('unloaded');
});
});
+
+describe('a handle that no longer names its entity', () => {
+ it('does not reach the entity holding its slot', () => {
+ // What residency makes ordinary: an event in flight carries a handle
+ // whose index is live and whose generation is not, and anything keying by
+ // index lands the blow on a stranger.
+ const world = new World();
+ const live = world.spawn();
+ world.insert(live, Health, { current: 25, max: 25 });
+
+ const stale = makeEntity(entityIndex(live), entityGeneration(live) + 1);
+ expect(entityIndex(stale)).toBe(entityIndex(live));
+ expect(stale).not.toBe(live);
+ expect(world.valid(stale)).toBe(false);
+
+ applyDamage(world, [{ target: stale, source: live, amount: 25, x: 0, y: 0, z: 0 }]);
+ expect(world.get(live, Health).current).toBe(25);
+
+ // …and the live handle still works, so the refusal above is about the
+ // generation and not about damage being broken.
+ applyDamage(world, [{ target: live, source: live, amount: 10, x: 0, y: 0, z: 0 }]);
+ expect(world.get(live, Health).current).toBe(15);
+ });
+});
diff --git a/tools/check-component-fields.mjs b/tools/check-component-fields.mjs
index d858bde95..c2263127e 100644
--- a/tools/check-component-fields.mjs
+++ b/tools/check-component-fields.mjs
@@ -47,7 +47,12 @@ const components = JSON.parse(
// `examples` is in the list because some fields exist to be read by a GAME:
// Perception writes what it saw and the engine never looks at it again, so
// judging that one by engine sources alone would call an output a dead knob.
-const { files, missing } = listTrackedSources(['src', 'sdk/src', 'desktop/src', 'native', 'plugins', 'examples']);
+//
+// `pipeline/src` because some are read by the COOK and by nothing at runtime:
+// `StreamedWorld.cellSize` decides how a world is cut. A reader still has to
+// name the component, so this widens nothing else.
+const { files, missing } = listTrackedSources(
+ ['src', 'sdk/src', 'desktop/src', 'native', 'plugins', 'examples', 'pipeline/src']);
// A reader this gate cannot see is a field it will call dead. Naming the gap
// beats judging a smaller corpus and printing the same green either way.
if (missing.length) {
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index 4491822a4..9c960eb0f 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -251,6 +251,10 @@ export const GOLDEN = [
// Walking is what makes a place exist here, so the frame after 60 frames of
// it differs by more than a character moving — a cell came in.
interact: { keys: ['KeyD'], frames: 60 },
+ // Cutting the world is a COOK step, so the editor plays the authored scene
+ // whole and the two frames hold different amounts of world on purpose. What
+ // the package does is held to by tools/verify-world-residency.mjs.
+ parityGap: 'the package streams its world and the editor plays it whole; the frames differ by design',
},
{
id: 'ui-controls',
diff --git a/tools/launchers/residency-run.mjs b/tools/launchers/residency-run.mjs
index bae62eb81..58bda5d0d 100644
--- a/tools/launchers/residency-run.mjs
+++ b/tools/launchers/residency-run.mjs
@@ -172,7 +172,7 @@ async function main() {
const read = async () => ({
streaming: await exec('window.__estellaCooked.streaming()'),
at: (await exec(`window.__estellaCooked.probe(${JSON.stringify(NAMES)})`)).at,
- combat: await exec(`window.__estellaCooked.combat("Player", ${JSON.stringify(['Enemy', 'Canary', 'Player'])})`),
+ combat: await exec(`window.__estellaCooked.combat("Player", ${JSON.stringify(['Enemy', 'Canary', 'Player', 'Wall', 'RockA', 'Arch', 'ArchTop', 'Beacon'])})`),
ai: await exec('window.__estellaCooked.ai("Enemy")'),
});
@@ -233,6 +233,31 @@ async function main() {
continue;
}
if (step.do === 'tap') { await exec(tapScript(step.key, step.frames ?? 10)); continue; }
+ if (step.do === 'time') {
+ // Wall time for a batch of engine frames, with the clock already handed
+ // over: what a held world costs per frame, rather than what the runner had
+ // spare. Settled first, so an arrival is not charged to the steady state.
+ await settle();
+ const began = performance.now();
+ await exec(holdScript([], step.frames ?? 300));
+ const ms = performance.now() - began;
+ const streaming = await exec('window.__estellaCooked.streaming()');
+ console.log(`timing ${step.as}: ${JSON.stringify({
+ frames: step.frames ?? 300, ms, msPerFrame: ms / (step.frames ?? 300), streaming,
+ })}`);
+ continue;
+ }
+ if (step.do === 'arrive') {
+ // How long a gesture's worth of residency takes to finish — the load or the
+ // unload it asked for, IO included, which is what a player waits through.
+ const began = performance.now();
+ if (step.key) await exec(tapScript(step.key, 1));
+ const settled = await settle();
+ const ms = performance.now() - began;
+ const streaming = await exec('window.__estellaCooked.streaming()');
+ console.log(`timing ${step.as}: ${JSON.stringify({ ms, settled, streaming })}`);
+ continue;
+ }
if (step.do === 'hold') { await exec(holdScript(step.keys ?? [], step.frames ?? 30)); continue; }
if (step.do === 'walkTo') {
if (!(await calibrate())) { stop(); server.close(); return fail('holding a key moved the character nowhere', 1); }
diff --git a/tools/verify-world-residency.mjs b/tools/verify-world-residency.mjs
index e4a201c4a..4c82dd08f 100644
--- a/tools/verify-world-residency.mjs
+++ b/tools/verify-world-residency.mjs
@@ -31,6 +31,8 @@ const A = 'main.cell_0_0';
const B = 'main.cell_1_0';
const C = 'main.cell_2_0';
const D = 'main.cell_0_5';
+/** The enemy's authored row in the fixture — what its handle is looked up by. */
+const ENEMY_ROW = 31;
function packageGame() {
rmSync(WORK, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
@@ -98,6 +100,16 @@ function main() {
{ do: 'read', as: 'scoutOff' },
{ do: 'tap', key: 'KeyM', frames: 20 },
{ do: 'watch', as: 'bobbed', name: 'Bobber', axis: 'z', frames: 400, every: 20 },
+ // One cell, alone: nothing else loads between its unload and its reload,
+ // so the handle slot it gives up is the one it gets back — which is the
+ // arrangement a stale handle is actually dangerous in.
+ { do: 'read', as: 'beaconFirst' },
+ { do: 'tap', key: 'KeyM', frames: 30 },
+ { do: 'read', as: 'beaconGone' },
+ { do: 'tap', key: 'KeyM', frames: 30 },
+ { do: 'read', as: 'beaconBack' },
+ { do: 'tap', key: 'KeyJ', frames: 30 },
+ { do: 'read', as: 'beaconBlown' },
]);
const initial = start.initial;
@@ -137,6 +149,24 @@ function main() {
'and a boundary it breathes across loads the place once and keeps it',
`${loads} load(s), ${unloads} unload(s) over 400 frames`);
+ // ---- 10a. A blow held across ONE cell's whole lifetime ---------------
+ const wasBeacon = (start.beaconFirst.streaming.cellRows[D] ?? [])[0];
+ const isBeacon = (start.beaconBack.streaming.cellRows[D] ?? [])[0];
+ claim(start.beaconGone.at.Beacon === undefined && isBeacon !== undefined
+ && wasBeacon !== undefined && wasBeacon.entity !== isBeacon.entity,
+ 'a place that leaves and comes back mints a new handle for the same row',
+ `row ${wasBeacon?.id}: ${wasBeacon?.entity} then ${isBeacon?.entity}`);
+ // Which slot comes back is the allocator's business, not a contract, so it is
+ // reported rather than claimed. The generation's guarantee is held to where it
+ // lives — sdk/tests/world-residency.test.ts fabricates a handle to test it.
+ console.log(` slot ${slot(wasBeacon?.entity ?? 0)} gave way to slot ${slot(isBeacon?.entity ?? 0)}`);
+ claim(start.beaconBlown.combat.targets.Beacon.health
+ === start.beaconBlown.combat.targets.Beacon.max
+ && start.beaconBlown.combat.targets.Canary.health < 100,
+ 'and the blow held over that lifetime lands on nobody while the live one lands',
+ `beacon at ${start.beaconBlown.combat.targets.Beacon.health}, `
+ + `canary at ${start.beaconBlown.combat.targets.Canary.health}`);
+
// ---- 2/3/4/7/8. The journey ------------------------------------------
const trip = drive(dir, 'journey', [
{ do: 'step', frames: 30 },
@@ -187,13 +217,12 @@ function main() {
&& back.streaming.hunters === 1 && back.streaming.navAgents === 1,
'coming back builds the place once, not twice',
`${entities(back, B)}/${authored(back, B)} entities, ${back.streaming.hunters} hunter(s)`);
- const sameRows = JSON.stringify(back.streaming.cellStableIds[B])
- === JSON.stringify(atB.streaming.cellStableIds[B]);
- const newHandles = JSON.stringify(back.streaming.cellHandles[B])
- !== JSON.stringify(atB.streaming.cellHandles[B]);
- claim(sameRows && newHandles,
+ const rowsOf = (r) => (r.streaming.cellRows[B] ?? []).map((row) => row.id);
+ const handlesOf = (r) => (r.streaming.cellRows[B] ?? []).map((row) => row.entity);
+ claim(JSON.stringify(rowsOf(back)) === JSON.stringify(rowsOf(atB))
+ && JSON.stringify(handlesOf(back)) !== JSON.stringify(handlesOf(atB)),
'with the same authored rows and different runtime handles',
- `rows ${JSON.stringify(back.streaming.cellStableIds[B])}`);
+ `rows ${JSON.stringify(rowsOf(back))}`);
// ---- 7. The persistent world is not rebuilt --------------------------
const persistent = JSON.stringify(trip.atA.streaming.persistentHandles);
@@ -237,21 +266,32 @@ function main() {
{ do: 'tap', key: 'KeyJ', frames: 30 },
{ do: 'read', as: 'blown' },
]);
- const before = stale.met.streaming.cellHandles[B] ?? [];
- const after = stale.back.streaming.cellHandles[B] ?? [];
- const reused = before.some((h) => after.some((n) => slot(n) === slot(h) && n !== h));
+ const before = stale.met.streaming.cellRows[B] ?? [];
+ const after = stale.back.streaming.cellRows[B] ?? [];
+ const remembered = before.find((row) => row.id === ENEMY_ROW);
+ // Whoever holds that slot NOW — anywhere, since a freed one goes to whichever
+ // place loads next. Every cell entity carries Health on purpose, so a blow
+ // that landed is visible whichever of them inherited it.
+ const everywhere = Object.values(stale.blown.streaming.cellRows).flat();
+ const current = after.find((row) => row.id === ENEMY_ROW);
+ const inherited = everywhere.find((row) => slot(row.entity) === slot(remembered?.entity ?? -1));
claim(stale.gone.at.Enemy === undefined && after.length === before.length,
'the enemy a blow was aimed at really did stop existing');
+ claim(remembered !== undefined && current !== undefined && remembered.entity !== current.entity,
+ 'and the handle it was aimed at no longer names it',
+ `row ${remembered?.id}: ${remembered?.entity} then ${current?.entity}`
+ + (inherited ? `; its slot is now row ${inherited.id}` : '; its slot is unheld'));
claim(stale.blown.combat.targets.Canary.health < 100,
'the gesture reached the damage bus',
`canary at ${stale.blown.combat.targets.Canary.health}`);
- claim(stale.blown.combat.targets.Enemy.health === stale.blown.combat.targets.Enemy.max,
+ const hurt = Object.entries(stale.blown.combat.targets)
+ .filter(([name, t]) => name !== 'Canary' && name !== 'Player' && t.health !== t.max)
+ .map(([name, t]) => `${name} at ${t.health}`);
+ claim(hurt.length === 0,
'and the blow held for the entity that left landed on nobody',
- `enemy at ${stale.blown.combat.targets.Enemy.health}, slot reused: ${reused}`);
- // Without a reused slot the claim above is true for a duller reason, so say so.
- if (!reused) {
- console.log(' note: no handle slot was recycled in this run — the claim is weaker than it reads');
- }
+ hurt.length === 0
+ ? `${Object.keys(stale.blown.combat.targets).length} targets, all whole`
+ : hurt.join(', '));
const failed = results.filter((r) => !r.ok).length;
console.log(`\nworld-residency: ${results.length - failed}/${results.length}`);