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(residency): a prefetch hit is what demand FINDS, not what it ends up with
esenginefd00891a584f
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 80d632a6e..b4c83718d 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -10124,7 +10124,7 @@ cellCount: numbercellEntityCounts: Record<string, number>cellRenderCounts: Record<string, number>cellRows: Record<string, { id: number; entity: number; }[]>-delivery: Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: Record<string, CellDelivery>desiredCells: string[]lastDemandToResidentMs: numberloadCount: number@@ -10134,6 +10134,7 @@ persistentHandles: number[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]@@ -10156,7 +10157,7 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```clear: () => void-delivery: () => Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void@@ -10179,6 +10180,7 @@ loadingCells: string[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 1e5603e9d..97bde0c8b 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -10317,7 +10317,7 @@ cellCount: numbercellEntityCounts: Record<string, number>cellRenderCounts: Record<string, number>cellRows: Record<string, { id: number; entity: number; }[]>-delivery: Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: Record<string, CellDelivery>desiredCells: string[]lastDemandToResidentMs: numberloadCount: number@@ -10327,6 +10327,7 @@ persistentHandles: number[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]@@ -10349,7 +10350,7 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```clear: () => void-delivery: () => Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void@@ -10372,6 +10373,7 @@ loadingCells: string[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 900c34f47..42bb2aaeb 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -10119,7 +10119,7 @@ cellCount: numbercellEntityCounts: Record<string, number>cellRenderCounts: Record<string, number>cellRows: Record<string, { id: number; entity: number; }[]>-delivery: Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: Record<string, CellDelivery>desiredCells: string[]lastDemandToResidentMs: numberloadCount: number@@ -10129,6 +10129,7 @@ persistentHandles: number[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]@@ -10151,7 +10152,7 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```clear: () => void-delivery: () => Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void@@ -10174,6 +10175,7 @@ loadingCells: string[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 9bc45fa6a..67bd4e1db 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -10371,7 +10371,7 @@ cellCount: numbercellEntityCounts: Record<string, number>cellRenderCounts: Record<string, number>cellRows: Record<string, { id: number; entity: number; }[]>-delivery: Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: Record<string, CellDelivery>desiredCells: string[]lastDemandToResidentMs: numberloadCount: number@@ -10381,6 +10381,7 @@ persistentHandles: number[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]@@ -10403,7 +10404,7 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```clear: () => void-delivery: () => Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void@@ -10426,6 +10427,7 @@ loadingCells: string[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex c1efbee81..74c6eb422 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -10147,7 +10147,7 @@ cellCount: numbercellEntityCounts: Record<string, number>cellRenderCounts: Record<string, number>cellRows: Record<string, { id: number; entity: number; }[]>-delivery: Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: Record<string, CellDelivery>desiredCells: string[]lastDemandToResidentMs: numberloadCount: number@@ -10157,6 +10157,7 @@ persistentHandles: number[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]@@ -10179,7 +10180,7 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```clear: () => void-delivery: () => Record<string, { phases: Record<string, number>; deliveryMs: number; }>+delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void@@ -10202,6 +10203,7 @@ loadingCells: string[]prefetchCells: string[]prefetchHits: numberprefetchMisses: number+prefetchRequests: numberprepareCount: numberpreparedCells: string[]residentCells: string[]diff --git a/sdk/src/residency/WorldStreamer.ts b/sdk/src/residency/WorldStreamer.tsindex 3ebc65f3c..e9978967a 100644--- a/sdk/src/residency/WorldStreamer.ts+++ b/sdk/src/residency/WorldStreamer.ts@@ -68,11 +68,15 @@ export interface WorldStreamerStatus {/** Preparations begun, and preparations thrown away unpublished. */prepareCount: number;cancelCount: number;+ /** Of those preparations, the ones begun for a cell nobody had asked for yet. */+ prefetchRequests: number;/** Acquisitions given back by discarding readiness — not by unloading. */cancelledRefs: number;/**- * Publications that had a prepared cell waiting, and publications that had to- * do the preparing themselves. The second is a player arriving early.+ * Decided the instant a cell is first DEMANDED, by what demand finds there:+ * readiness that already exists is a hit, and anything else — nothing, or a+ * preparation still in flight — is a miss. A preparation that was on its way+ * is not a hit: the player waited for it either way.*/prefetchHits: number;prefetchMisses: number;@@ -95,8 +99,35 @@ interface CellState {delivery: number;/** When it became demanded, so the latency a player feels can be measured. */demandedAt: number;- /** Whether the preparation now running was begun because it was ALREADY wanted. */- preparedUnderDemand: boolean;+ /** When readiness arrived, so how long it then sat unused is measurable. */+ preparedAt: number;+ /** When publication began, so the wait BEFORE it is not charged to it. */+ publishedAt: number;+ /** Issue to prepared: what a hit takes off the latency a player feels. */+ prepareMs: number;+ /** Publish to resident: what a hit still costs, whatever prefetch does. */+ publishMs: number;+ /** Demanded to resident — the whole of what a player waits through. */+ demandToResidentMs: number;+ /** Prepared to demanded. Only a hit has one; a miss had nothing waiting. */+ dwellMs: number;+ /** What the last demand for this cell found. */+ outcome: 'hit' | 'miss' | '';+}++/** Where one cell's last delivery spent its time. @experimental */+export interface CellDelivery {+ /** Phases of the preparation, which runs between frames and on no system timer. */+ phases: Record<string, number>;+ /** Issue to resident. For a hit this contains the dwell, so it is not a latency. */+ deliveryMs: number;+ prepareMs: number;+ publishMs: number;+ /** The latency a player feels: from wanting the place to standing in it. */+ demandToResidentMs: number;+ /** How long readiness waited to be wanted. Zero on a miss — nothing waited. */+ dwellMs: number;+ outcome: 'hit' | 'miss' | '';}export class WorldStreamer {@@ -110,6 +141,7 @@ export class WorldStreamer {private prepareCount_ = 0;private cancelCount_ = 0;private cancelledRefs_ = 0;+ private prefetchRequests_ = 0;private prefetchHits_ = 0;private prefetchMisses_ = 0;private lastDemandToResident_ = 0;@@ -133,7 +165,8 @@ export class WorldStreamer {this.cells_.set(cell.name, {cell, residency: 'unloaded', desired: false, speculated: false,phases: {}, issuedAt: 0, delivery: 0,- demandedAt: 0, preparedUnderDemand: false,+ demandedAt: 0, preparedAt: 0, publishedAt: 0,+ prepareMs: 0, publishMs: 0, demandToResidentMs: 0, dwellMs: 0, outcome: '',});}}@@ -157,12 +190,26 @@ export class WorldStreamer {if (state) state.phases[phase] = (state.phases[phase] ?? 0) + ms;}- /** Per cell: the phases of its last load, and issue-to-resident wall time. */- delivery(): Record<string, { phases: Record<string, number>; deliveryMs: number }> {- const out: Record<string, { phases: Record<string, number>; deliveryMs: number }> = {};+ /**+ * Per cell: where its last delivery spent its time.+ *+ * Per CELL and not a running average, because the question prefetch answers+ * is asked one arrival at a time: a mean over hits and misses together+ * describes no arrival that happened.+ */+ delivery(): Record<string, CellDelivery> {+ const out: Record<string, CellDelivery> = {};for (const [name, state] of this.cells_) {if (state.delivery === 0 && Object.keys(state.phases).length === 0) continue;- out[name] = { phases: { ...state.phases }, deliveryMs: state.delivery };+ out[name] = {+ phases: { ...state.phases },+ deliveryMs: state.delivery,+ prepareMs: state.prepareMs,+ publishMs: state.publishMs,+ demandToResidentMs: state.demandToResidentMs,+ dwellMs: state.dwellMs,+ outcome: state.outcome,+ };}return out;}@@ -192,9 +239,7 @@ export class WorldStreamer {const now = performance.now();for (const [name, state] of this.cells_) {const wanted = target.has(name);- // The moment demand begins, so what a prefetch hit is worth can be- // measured rather than asserted.- if (wanted && !state.desired) state.demandedAt = now;+ if (wanted && !state.desired) this.demand_(state, now);state.desired = wanted;state.speculated = speculated.has(name);}@@ -241,12 +286,36 @@ export class WorldStreamer {loadingCells, unloadingCells,loadCount: this.loadCount_, unloadCount: this.unloadCount_,prepareCount: this.prepareCount_, cancelCount: this.cancelCount_,+ prefetchRequests: this.prefetchRequests_,cancelledRefs: this.cancelledRefs_,prefetchHits: this.prefetchHits_, prefetchMisses: this.prefetchMisses_,lastDemandToResidentMs: this.lastDemandToResident_,};}+ /**+ * A cell has just been asked for, and what the ask FINDS is the hit.+ *+ * Not judged at publication: "prepared by the time we published it" is true+ * of every cell that ever loads. Only readiness that already existed when+ * the ask arrived took anything off the wait.+ */+ private demand_(state: CellState, now: number): void {+ state.demandedAt = now;+ // Already here, or already on its way in: this ask owes no publication,+ // so there is nothing for speculation to have been early for.+ if (state.residency === 'resident' || state.residency === 'publishing') return;+ if (state.residency === 'prepared') {+ this.prefetchHits_++;+ state.outcome = 'hit';+ state.dwellMs = now - state.preparedAt;+ } else {+ this.prefetchMisses_++;+ state.outcome = 'miss';+ state.dwellMs = 0;+ }+ }+/*** Move one cell toward what it should be, or leave it alone while an earlier* move is still in flight. Re-entered when that move finishes, which is what@@ -278,11 +347,23 @@ export class WorldStreamer {state.residency = 'preparing';state.phases = {};state.issuedAt = performance.now();- state.preparedUnderDemand = state.desired;+ state.prepareMs = 0;+ state.publishMs = 0;+ state.demandToResidentMs = 0;this.prepareCount_++;+ if (!state.desired) {+ // Speculating afresh about a cell whose last delivery is over. Its+ // verdict belonged to THAT delivery, and carrying it forward would+ // report a hit for an ask nobody has made yet.+ this.prefetchRequests_++;+ state.outcome = '';+ state.dwellMs = 0;+ }Promise.resolve(this.host_.prepare(name)).then(() => {state.residency = 'prepared';+ state.preparedAt = performance.now();+ state.prepareMs = state.preparedAt - state.issuedAt;// What finished was begun against a world that has moved. Whether// this cell is still wanted — or wanted now when it was not — is// asked again here rather than assumed from when it started.@@ -297,15 +378,17 @@ export class WorldStreamer {private beginLoad_(name: string, state: CellState): void {state.residency = 'publishing';- if (state.preparedUnderDemand) this.prefetchMisses_++;- else this.prefetchHits_++;+ state.publishedAt = performance.now();this.loadCount_++;Promise.resolve(this.host_.loadAdditive(name)).then(() => {+ const now = performance.now();state.residency = 'resident';- state.delivery = performance.now() - state.issuedAt;+ state.delivery = now - state.issuedAt;+ state.publishMs = now - state.publishedAt;if (state.demandedAt > 0) {- this.lastDemandToResident_ = performance.now() - state.demandedAt;+ state.demandToResidentMs = now - state.demandedAt;+ this.lastDemandToResident_ = state.demandToResidentMs;}this.step_(name);},diff --git a/sdk/src/residency/index.ts b/sdk/src/residency/index.tsindex 1b0cecbf9..d2599486b 100644--- a/sdk/src/residency/index.ts+++ b/sdk/src/residency/index.ts@@ -15,7 +15,7 @@ export {} from './cells';export {WorldStreamer, WorldStreaming,- type CellResidency, type WorldStreamHost, type WorldStreamerStatus,+ type CellResidency, type WorldStreamHost, type WorldStreamerStatus, type CellDelivery,} from './WorldStreamer';export { worldResidencyPlugin, worldResidencySystem } from './residencyPlugin';export { worldResidencyReport, type WorldResidencyReport } from './report';diff --git a/sdk/src/residency/report.ts b/sdk/src/residency/report.tsindex 79a763632..f3a410c10 100644--- a/sdk/src/residency/report.ts+++ b/sdk/src/residency/report.ts@@ -16,7 +16,7 @@import type { App } from '../app/app';import { SceneManager } from '../scene/sceneManager';-import { WorldStreaming } from './WorldStreamer';+import { WorldStreaming, type CellDelivery } from './WorldStreamer';import { stableEntityId } from './identity';import { renderableComponents } from '../ecs/component';@@ -38,8 +38,11 @@ export interface WorldResidencyReport {unloadCount: number;prepareCount: number;cancelCount: number;+ /** Of those preparations, the ones begun before anything asked for the cell. */+ prefetchRequests: number;/** Acquisitions given back by discarding readiness — not by unloading. */cancelledRefs: number;+ /** What demand FOUND, counted the instant it arrived. See `WorldStreamerStatus`. */prefetchHits: number;prefetchMisses: number;lastDemandToResidentMs: number;@@ -62,18 +65,19 @@ export interface WorldResidencyReport {/** Their handles. Unchanged for the life of the world — that is the claim. */persistentHandles: number[];/**- * Per cell: where its last load spent its time, and issue-to-resident wall- * time. The phases run between frames, which is why no frame profiler holds- * them and why a total is not a hitch.+ * Per cell: where its last delivery spent its time, and whether the ask for+ * it found readiness waiting. The phases run between frames, which is why no+ * frame profiler holds them and why a total is not a hitch.*/- delivery: Record<string, { phases: Record<string, number>; deliveryMs: number }>;+ delivery: Record<string, CellDelivery>;}const EMPTY: WorldResidencyReport = {streamed: false, cellCount: 0, sourceCount: 0,desiredCells: [], prefetchCells: [], residentCells: [], preparedCells: [],loadingCells: [], unloadingCells: [],- loadCount: 0, unloadCount: 0, prepareCount: 0, cancelCount: 0, cancelledRefs: 0,+ loadCount: 0, unloadCount: 0, prepareCount: 0, cancelCount: 0,+ prefetchRequests: 0, cancelledRefs: 0,prefetchHits: 0, prefetchMisses: 0, lastDemandToResidentMs: 0,cellEntityCounts: {}, cellRenderCounts: {}, assetRefsByCell: {},authoredCellEntityCounts: {}, cellRows: {},@@ -133,6 +137,7 @@ export function worldResidencyReport(app: App): WorldResidencyReport {unloadCount: status.unloadCount,prepareCount: status.prepareCount,cancelCount: status.cancelCount,+ prefetchRequests: status.prefetchRequests,cancelledRefs: status.cancelledRefs,prefetchHits: status.prefetchHits,prefetchMisses: status.prefetchMisses,diff --git a/sdk/tests/world-residency.test.ts b/sdk/tests/world-residency.test.tsindex 29de0cc0a..a5f5c2a71 100644--- a/sdk/tests/world-residency.test.ts+++ b/sdk/tests/world-residency.test.ts@@ -284,6 +284,96 @@ describe('WorldStreamer', () => {expect(streamer.status().prefetchHits).toBe(0);});+ it('calls a preparation still in flight a miss, however it ends', async () => {+ // Rules out reading a hit as "prepared by the time we published it",+ // which is true of every cell that loads. This speculation had not+ // landed when the place was wanted, so it bought nothing.+ const { host, settle, defer } = recordingHost();+ defer(true);+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(3, 0)));+ streamer.update([source(0, 50, 100, 150, 400)]);+ expect(streamer.residencyOf('c_3_0')).toBe('preparing');++ streamer.update([source(280, 50, 100, 150, 400)]);+ expect(streamer.status().prefetchMisses).toBe(1);+ expect(streamer.status().prefetchHits).toBe(0);++ // It goes on to publish from that preparation — the move is right and+ // only the CREDIT is refused.+ settle();+ await flush();+ settle();+ await flush();+ expect(streamer.residencyOf('c_3_0')).toBe('resident');+ expect(streamer.status().prefetchHits).toBe(0);+ expect(streamer.delivery()['c_3_0'].outcome).toBe('miss');+ });++ it('counts a preparation as speculative only when nothing had asked yet', async () => {+ const { host } = recordingHost();+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(0, 0), cell(3, 0)));+ // c_0_0 is demanded outright; c_3_0 is only speculated about.+ streamer.update([source(50, 50, 100, 150, 400)]);+ await flush();+ expect(streamer.status().prepareCount).toBe(2);+ expect(streamer.status().prefetchRequests).toBe(1);+ });++ it('reports a dwell only where readiness actually waited', async () => {+ const { host } = recordingHost();+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(0, 0), cell(3, 0)));+ // The band is as wide as the speculation, so walking on does not give+ // c_0_0 up and re-speculate about it — which would clear the very+ // verdict this is reading.+ streamer.update([source(50, 50, 100, 400, 400)]);+ await flush();+ streamer.update([source(280, 50, 100, 400, 400)]);+ await flush();+ const delivery = streamer.delivery();+ // c_0_0 was wanted the instant it was heard of; c_3_0 sat ready first.+ expect(delivery['c_0_0'].outcome).toBe('miss');+ expect(delivery['c_0_0'].dwellMs).toBe(0);+ expect(delivery['c_3_0'].outcome).toBe('hit');+ expect(delivery['c_3_0'].dwellMs).toBeGreaterThanOrEqual(0);+ expect(delivery['c_3_0'].publishMs).toBeGreaterThanOrEqual(0);+ });++ it('readies again, at once, a cell it gave up while still speculating about it', async () => {+ // The shape of speculation without a heading: the streamer knows how far+ // a source is, never which way it is going. Hence the authoring rule —+ // keep prefetchRadius inside unloadRadius, or leaving refetches.+ const { host } = recordingHost();+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20, 400)]);+ await flush();+ expect(streamer.residencyOf('c_0_0')).toBe('resident');++ // 25 out: past unloadRadius 20, and far inside prefetchRadius 400.+ streamer.update([source(125, 50, 10, 20, 400)]);+ await flush();+ expect(streamer.status().unloadCount).toBe(1);+ expect(streamer.residencyOf('c_0_0')).toBe('prepared');+ expect(streamer.status().prepareCount).toBe(2);+ // And the delivery that ended does not lend its verdict to the one that+ // has not been asked for: a report reading this row would otherwise+ // count a hit for a cell nobody has demanded since.+ expect(streamer.delivery()['c_0_0'].outcome).toBe('');++ // With the band wider than the speculation, the same departure is final.+ const second = recordingHost();+ const kept = new WorldStreamer(second.host);+ kept.loadManifest(manifest(cell(0, 0)));+ kept.update([source(50, 50, 10, 400, 400)]);+ await flush();+ kept.update([source(125, 50, 10, 400, 400)]);+ await flush();+ expect(kept.residencyOf('c_0_0')).toBe('resident');+ });+it('throws away what a source turned away from, rather than publishing it', async () => {const { host, calls, loaded } = recordingHost();const streamer = new WorldStreamer(host);