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(profiler): an agent can ask where the frame went, and the tree stops lying about waits
yhha473f554905c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 345e57ccf..1778f52ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -69,6 +69,31 @@ published separately; it ships inside the editor.what makes the frame tree's claim to add up true on any frame the accumulatorhad a backlog for.+- **An agent can read the profiler.** `profile_frames` samples the running frame+ for a window and answers where the time went: fps and percentiles, the frame as+ `cpu + wait + idle` with GPU alongside, what each cost domain came to, and the+ costliest systems — each with its scopes and what its queries walked. So "why+ does the boss fight drop to 40fps" is answerable with the system, the number,+ and the reason, rather than with a screenshot.++ It is ranked and truncated, and says how much it left out: the tree behind it+ is hundreds of rows and the caller has a context window, and a silently short+ list reads as the whole list. It registers an engine consumer for the duration+ of its window, because the profiler skips the cross-boundary engine read+ entirely while nothing is mounted to display it — a caller that just read the+ ring with the panel closed would get frames with no engine costs in them and+ no sign that was why. A window in which no frame ran reports `stalled` rather+ than a set of zeroes that reads like a fast frame.++- **A wait is not a row in the tree.** Blocked time was being subtracted from the+ system that absorbed it while the scope beneath kept its full wall-clock, so a+ `render.submit` of 0.36ms sat under a `RenderSystem` of 0.22ms — a child larger+ than its parent, in the tree whose whole claim is that it adds up. The tree is+ work: the wait leaves it and survives as the profile's `waitMs`, which the+ frame identity already carries. The assertion that missed it — children summing+ was only ever checked below the scope, never across a system holding one — now+ runs over every node of a frame that has a wait in it.+- **One derivation, three readers.** `buildFrameProfile` is a pure function overplain per-frame data, so the live view, a pinned frame and a recorded sessioncannot each round their own way to a different answer. The editor's owndiff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjsindex 88000b6e4..07bd01e6e 100644--- a/desktop/shared/toolCatalog.mjs+++ b/desktop/shared/toolCatalog.mjs@@ -212,6 +212,19 @@ export const TOOLS = [+ 'Take one before a Play/Stop (or a hot reload, or a scene load) and one after: every counter tagged `conserved` must come back to the same number. '+ 'This is the door for "the editor got slower after an hour" — the question no screenshot answers.',schema: obj({}), method: 'census', args: () => [], root: 'editor' },+ { name: 'profile_frames',+ description: 'Watch the running frame for a while, then answer WHERE THE TIME WENT — the door for "why is this scene 40fps". '+ + 'Samples for `ms` (default 1000, clamped 100..5000) and returns, per frame: fps/p50/p95/p99 and long-frame count; '+ + 'the frame split into `cpuMs + waitMs + idleMs` (plus `gpuMs` as a parallel track — the three CPU figures are what add up to the frame); '+ + 'per cost domain (scripts / render / physics / ui / …) how much it cost; and the costliest systems, each with its domain, '+ + 'the scopes measured inside it, and — the point — what its QUERIES walked: `scanned` entities over `calls`, of which `filtered` '+ + 'were discarded by an Added/Changed filter. A system whose `filtered` is nearly its `scanned` is walking the whole world every '+ + 'frame to throw it away, which is the fix, not the symptom. `waitMs` is CPU blocked on the display or an await — NOT a hotspot, '+ + 'do not report it as one. `stalled: true` means no frame ran at all (nothing animating, or the window is in the background) — '+ + 'say so rather than reading the zeroes as a fast frame. `omittedSystems` counts what ranked below the cut. '+ + 'Works in both realms: it profiles the running game while playing, the editor scene otherwise (see `realm`).',+ schema: obj({ ms: { type: 'number' }, topSystems: { type: 'number' } }),+ method: 'profileFrames', args: (i) => [i.ms ?? 1000, i.topSystems ?? 12] },{ name: 'get_subsystems',description: 'Lifecycle + liveness of every engine subsystem (physics, audio, …): phase and activity.',schema: obj({}), method: 'getSubsystems', args: () => [] },diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex 1603c5fe3..061a2565c 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -30,6 +30,7 @@ import { EngineHost } from './EngineHost';import { isRequiredEmpty, componentByName, userSchema, coerceEnumInput, componentAuthorability, inspectorFields, modelAddableComponentEntries } from './schema';import { ViewportController } from './ViewportController';import { PerfMonitor, type PerfSnapshot, type FrameSample, type SessionCapture } from './PerfMonitor';+import type { ProfileReport } from './profileReport';import type { SceneCommandsImpl, EditorTransaction } from './SceneCommands';import type { SceneQueryImpl, EntityInfo } from './SceneQuery';import type { SceneModelImpl } from './SceneModel';@@ -37,6 +38,8 @@ import type { EditorHistoryImpl, HistoryMark } from './EditorHistory';import type { ReconcilerImpl } from './Reconciler';import type { SelectionStore } from '@/store/selectionStore';+const r2 = (n: number): number => Math.round(n * 100) / 100;+/** A captured viewport frame: raw RGBA pixels (GL order: bottom-up rows). */export interface ViewportCapture {rgba: Uint8Array;@@ -926,6 +929,61 @@ export class EditorControlSurfaceImpl {};}+ /**+ * Sample the running frame for `ms` and answer with where the time went.+ *+ * Ranked and truncated rather than complete: the tree behind this is hundreds+ * of rows and the caller has a context window. What was left out is counted in+ * the reply, because a silently short list reads as "that is all of it".+ */+ async profileFrames(ms = 1000, topSystems = 12): Promise<ProfileReport> {+ const w = await PerfMonitor.captureWindow(Math.min(5000, Math.max(100, ms)));+ const systems = w.mean.domains+ .flatMap((d) => d.children.map((s) => ({ domain: d.id, node: s })))+ .sort((a, b) => b.node.ms - a.node.ms);+ const shown = systems.slice(0, topSystems);+ return {+ realm: w.realm,+ windowMs: w.windowMs,+ frames: w.frames,+ stalled: w.stalled,+ budgetMs: w.budgetMs,+ fps: w.fps,+ p50: w.p50, p95: w.p95, p99: w.p99,+ longFrames: w.longFrames,+ worstFrameMs: w.worstFrameMs,+ frame: {+ totalMs: r2(w.mean.frameMs),+ cpuMs: r2(w.mean.cpuMs),+ waitMs: r2(w.mean.waitMs),+ idleMs: r2(w.mean.idleMs),+ gpuMs: w.mean.gpuMs >= 0 ? r2(w.mean.gpuMs) : -1,+ },+ // A plugin that is installed and costs nothing is not an answer to "where+ // did the time go", and there are two dozen of them. Counted, not hidden.+ domains: w.mean.domains.filter((d) => r2(d.ms) > 0).map((d) => ({ domain: d.id, ms: r2(d.ms) })),+ freeDomains: w.mean.domains.filter((d) => r2(d.ms) === 0).length,+ systems: shown.map(({ domain, node }) => ({+ name: node.label,+ domain,+ ms: r2(node.ms),+ ...(node.query+ ? {+ query: {+ calls: r2(node.query.calls),+ scanned: Math.round(node.query.scanned),+ filtered: Math.round(node.query.filtered),+ },+ }+ : {}),+ scopes: node.children+ .filter((c) => c.ms >= 0.05)+ .map((c) => ({ name: c.label, ms: r2(c.ms), kind: c.kind })),+ })),+ omittedSystems: systems.length - shown.length,+ };+ }+/** The current profiler snapshot: frame timing, stat-unit segments, per-system* timings, counters, memory, and GPU — the full per-frame telemetry. */getFrameStats(): PerfSnapshot {diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.tsindex df32b5e7d..df5626305 100644--- a/desktop/src/engine/PerfMonitor.ts+++ b/desktop/src/engine/PerfMonitor.ts@@ -4,7 +4,7 @@* @file PerfMonitor.ts — the editor's per-frame instrumentation hub.*/import { createStore } from 'zustand/vanilla';-import { buildFrameProfile, type FrameCosts, type FrameProfile, type ScopeCost } from 'esengine';+import { buildFrameProfile, meanFrameProfile, type FrameCosts, type FrameProfile, type ScopeCost } from 'esengine';/** p-th percentile (0..100) of an unsorted sample; 0 for an empty set. */export function percentile(values: readonly number[], p: number): number {@@ -165,6 +165,25 @@ export interface PerfSnapshot {recordedFrames: number;}+/** What a sampling window saw — the answer to "why is it slow right now". */+export interface ProfileWindow {+ realm: 'edit' | 'play';+ windowMs: number;+ frames: number;+ /** No frame ran in the window: nothing is animating, or the window is hidden. */+ stalled: boolean;+ budgetMs: number;+ fps: number;+ p50: number;+ p95: number;+ p99: number;+ longFrames: number;+ worstFrameMs: number;+ worstFrameProfile: FrameProfile | null;+ /** The window's cost, per frame. */+ mean: FrameProfile;+}+/** A recorded profiling session, serialized to JSON for offline analysis. */export interface SessionCapture {version: number;@@ -337,6 +356,46 @@ class PerfMonitorImpl {/** The capture ring (oldest→newest). Aligned 1:1 with the snapshot's `frames`. */getSamples(): readonly FrameSample[] { return this.samples; }+ /**+ * Watch for `ms`, then answer with the window's frames folded into one profile.+ * Registers an engine consumer for the duration: the loop skips the engine read+ * entirely while nothing is mounted to display it, so reading the ring with the+ * panel closed yields frames with no engine costs and no sign of why.+ */+ async captureWindow(ms: number): Promise<ProfileWindow> {+ const release = this.addEngineConsumer();+ const wasFrozen = this.frozen;+ if (wasFrozen) this.resumeLive();+ const firstId = this.sampleSeq;+ try {+ await new Promise((resolve) => setTimeout(resolve, ms));+ } finally {+ release();+ if (wasFrozen) this.freezeLatest();+ }+ const frames = this.samples.filter((s) => s.id >= firstId);+ const profiles = frames.map(profileOf);+ const dts = frames.map((s) => s.dt);+ const worst = frames.reduce<FrameSample | null>((w, s) => (!w || s.dt > w.dt ? s : w), null);+ return {+ realm: this.realm,+ windowMs: ms,+ frames: frames.length,+ // A window with no frames means the loop never ran (nothing is animating,+ // or the editor is in the background). Said, not implied by zeroes.+ stalled: frames.length === 0,+ budgetMs: r1(1000 / 60),+ fps: frames.length ? Math.round(1000 / (percentile(dts, 50) || 1)) : 0,+ p50: r1(percentile(dts, 50)),+ p95: r1(percentile(dts, 95)),+ p99: r1(percentile(dts, 99)),+ longFrames: dts.filter((d) => d >= LONG_FRAME_MS).length,+ worstFrameMs: worst ? worst.dt : 0,+ worstFrameProfile: worst ? profileOf(worst) : null,+ mean: meanFrameProfile(profiles),+ };+ }+/** The pinned/queried frame's full breakdown, or null if it scrolled out. */getSample(id: number): FrameSample | null {for (let i = this.samples.length - 1; i >= 0; i--) if (this.samples[i].id === id) return this.samples[i];diff --git a/desktop/src/engine/profileReport.ts b/desktop/src/engine/profileReport.tsnew file mode 100644index 000000000..66af5ca12--- /dev/null+++ b/desktop/src/engine/profileReport.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file profileReport.ts — the profile as an agent reads it: ranked, and honest+ * about what it left out.+ */++export interface ProfileReportQuery {+ calls: number;+ scanned: number;+ filtered: number;+}++export interface ProfileReportSystem {+ name: string;+ domain: string;+ ms: number;+ /** Absent when the system runs no query. */+ query?: ProfileReportQuery;+ scopes: Array<{ name: string; ms: number; kind: string }>;+}++export interface ProfileReport {+ realm: 'edit' | 'play';+ windowMs: number;+ frames: number;+ /** No frame ran: nothing is animating, or the editor window is in the background. */+ stalled: boolean;+ budgetMs: number;+ fps: number;+ p50: number;+ p95: number;+ p99: number;+ longFrames: number;+ worstFrameMs: number;+ /** Per frame over the window. `totalMs = cpuMs + waitMs + idleMs`; gpu is parallel. */+ frame: { totalMs: number; cpuMs: number; waitMs: number; idleMs: number; gpuMs: number };+ domains: Array<{ domain: string; ms: number }>;+ /** Domains that cost nothing this window — installed and idle. */+ freeDomains: number;+ /** Costliest systems over the window, per frame. */+ systems: ProfileReportSystem[];+ /** Systems ranked below the cut. Zero means the list above is all of them. */+ omittedSystems: number;+}diff --git a/desktop/src/theme/profiler.css b/desktop/src/theme/profiler.cssindex 5907e94d9..2120b9db1 100644--- a/desktop/src/theme/profiler.css+++ b/desktop/src/theme/profiler.css@@ -137,9 +137,6 @@.prof-tree-system .prof-fill { background: var(--run); }.prof-tree-scope .prof-tree-name { color: var(--text-dim); }.prof-tree-scope .prof-fill { background: var(--text-mute); }-.prof-tree-wait .prof-tree-name,-.prof-tree-wait .prof-tree-ms { color: var(--warn); }-.prof-tree-wait .prof-fill { background: var(--warn); }.prof-tree-rest .prof-tree-name,.prof-tree-rest .prof-tree-ms { color: var(--text-faint); }.prof-tree-rest .prof-fill { background: var(--text-faint); }diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 2c4009948..b36da2fdc 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 112,"beta": 60,- "experimental": 1470,+ "experimental": 1472,"deprecated": 3},- "total": 1642,+ "total": 1644,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 471d372df..bebc5b149 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1355 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1357 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5401,7 +5401,7 @@ query: QueryCost | undefined## ProfileNodeKind — type @experimental```-'domain' | 'system' | 'scope' | 'wait' | 'rest'+'domain' | 'system' | 'scope' | 'rest'```## ProgressHandle — interface @experimental@@ -5485,6 +5485,13 @@ with: (...components: AnyComponentDef[]) => QueryBuilder<C>without: (...components: AnyComponentDef[]) => QueryBuilder<C>```+## QueryCost — interface @experimental+```+calls: number+filtered: number+scanned: number+```+## QueryDescriptor — interface @public```@internal _addedFilters: { index: number; component: AnyComponentDef; }[]@@ -10042,6 +10049,11 @@ Logger(type: BtNodeType): number```+## meanFrameProfile — function @experimental+```+(profiles: readonly FrameProfile[]): FrameProfile+```+## measureText — function @experimental```(text: string, opts: MeasureTextOptions): TextMetricsdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 480a87594..430c6d318 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 58 beta · 1374 experimental · 3 deprecated+Symbols: 112 public · 58 beta · 1376 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5584,7 +5584,7 @@ query: QueryCost | undefined## ProfileNodeKind — type @experimental```-'domain' | 'system' | 'scope' | 'wait' | 'rest'+'domain' | 'system' | 'scope' | 'rest'```## ProgressHandle — interface @experimental@@ -5668,6 +5668,13 @@ with: (...components: AnyComponentDef[]) => QueryBuilder<C>without: (...components: AnyComponentDef[]) => QueryBuilder<C>```+## QueryCost — interface @experimental+```+calls: number+filtered: number+scanned: number+```+## QueryDescriptor — interface @public```@internal _addedFilters: { index: number; component: AnyComponentDef; }[]@@ -10285,6 +10292,11 @@ Logger(type: BtNodeType): number```+## meanFrameProfile — function @experimental+```+(profiles: readonly FrameProfile[]): FrameProfile+```+## measureText — function @experimental```(text: string, opts: MeasureTextOptions): TextMetricsdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex dcd30f2d9..578370a23 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 55 beta · 1354 experimental · 3 deprecated+Symbols: 112 public · 55 beta · 1356 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5396,7 +5396,7 @@ query: QueryCost | undefined## ProfileNodeKind — type @experimental```-'domain' | 'system' | 'scope' | 'wait' | 'rest'+'domain' | 'system' | 'scope' | 'rest'```## ProgressHandle — interface @experimental@@ -5480,6 +5480,13 @@ with: (...components: AnyComponentDef[]) => QueryBuilder<C>without: (...components: AnyComponentDef[]) => QueryBuilder<C>```+## QueryCost — interface @experimental+```+calls: number+filtered: number+scanned: number+```+## QueryDescriptor — interface @public```@internal _addedFilters: { index: number; component: AnyComponentDef; }[]@@ -10042,6 +10049,11 @@ Logger(type: BtNodeType): number```+## meanFrameProfile — function @experimental+```+(profiles: readonly FrameProfile[]): FrameProfile+```+## measureText — function @experimental```(text: string, opts: MeasureTextOptions): TextMetricsdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 981218bc1..a45927f9d 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1375 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1377 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5641,7 +5641,7 @@ query: QueryCost | undefined## ProfileNodeKind — type @experimental```-'domain' | 'system' | 'scope' | 'wait' | 'rest'+'domain' | 'system' | 'scope' | 'rest'```## ProgressHandle — interface @experimental@@ -5725,6 +5725,13 @@ with: (...components: AnyComponentDef[]) => QueryBuilder<C>without: (...components: AnyComponentDef[]) => QueryBuilder<C>```+## QueryCost — interface @experimental+```+calls: number+filtered: number+scanned: number+```+## QueryDescriptor — interface @public```@internal _addedFilters: { index: number; component: AnyComponentDef; }[]@@ -10297,6 +10304,11 @@ Logger(type: BtNodeType): number```+## meanFrameProfile — function @experimental+```+(profiles: readonly FrameProfile[]): FrameProfile+```+## measureText — function @experimental```(text: string, opts: MeasureTextOptions): TextMetricsdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex e2f1357fe..dc55d6aa1 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1365 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1367 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5403,7 +5403,7 @@ query: QueryCost | undefined## ProfileNodeKind — type @experimental```-'domain' | 'system' | 'scope' | 'wait' | 'rest'+'domain' | 'system' | 'scope' | 'rest'```## ProgressHandle — interface @experimental@@ -5487,6 +5487,13 @@ with: (...components: AnyComponentDef[]) => QueryBuilder<C>without: (...components: AnyComponentDef[]) => QueryBuilder<C>```+## QueryCost — interface @experimental+```+calls: number+filtered: number+scanned: number+```+## QueryDescriptor — interface @public```@internal _addedFilters: { index: number; component: AnyComponentDef; }[]@@ -10069,6 +10076,11 @@ Logger(type: BtNodeType): number```+## meanFrameProfile — function @experimental+```+(profiles: readonly FrameProfile[]): FrameProfile+```+## measureText — function @experimental```(text: string, opts: MeasureTextOptions): TextMetricsdiff --git a/sdk/src/app/frameProfile.ts b/sdk/src/app/frameProfile.tsindex cd611b4fc..d316b6248 100644--- a/sdk/src/app/frameProfile.ts+++ b/sdk/src/app/frameProfile.ts@@ -41,7 +41,7 @@ export interface FrameProfileInput {readonly gpuMs?: number;}-export type ProfileNodeKind = 'domain' | 'system' | 'scope' | 'wait' | 'rest';+export type ProfileNodeKind = 'domain' | 'system' | 'scope' | 'rest';export interface ProfileNode {readonly id: string;@@ -69,6 +69,78 @@ export interface FrameProfile {/** Below this a row is noise, and a `rest` row for it would be rounding dust. */const EPS_MS = 0.05;+/**+ * Average a window of frames into one profile, per frame. A node is divided by+ * the whole window, not by the frames it appeared in: dividing by its own+ * appearances would report an every-fourth-frame system four times too dear.+ * Obeys the same sums a single frame does.+ */+export function meanFrameProfile(profiles: readonly FrameProfile[]): FrameProfile {+ if (profiles.length === 0) {+ return { frameMs: 0, cpuMs: 0, waitMs: 0, idleMs: 0, gpuMs: -1, domains: [] };+ }+ const n = profiles.length;+ const withGpu = profiles.filter((p) => p.gpuMs >= 0);+ return {+ frameMs: profiles.reduce((a, p) => a + p.frameMs, 0) / n,+ cpuMs: profiles.reduce((a, p) => a + p.cpuMs, 0) / n,+ waitMs: profiles.reduce((a, p) => a + p.waitMs, 0) / n,+ idleMs: profiles.reduce((a, p) => a + p.idleMs, 0) / n,+ gpuMs: withGpu.length > 0 ? withGpu.reduce((a, p) => a + p.gpuMs, 0) / withGpu.length : -1,+ domains: meanNodes(profiles.map((p) => p.domains), n),+ };+}++function meanNodes(perFrame: ReadonlyArray<readonly ProfileNode[]>, frames: number): ProfileNode[] {+ const acc = new Map<string, { node: ProfileNode; ms: number; kids: ProfileNode[][]; query: QueryCost | null }>();+ for (const nodes of perFrame) {+ for (const node of nodes) {+ const prev = acc.get(node.id);+ if (prev) {+ prev.ms += node.ms;+ prev.kids.push([...node.children]);+ if (node.query) {+ prev.query = prev.query+ ? {+ calls: prev.query.calls + node.query.calls,+ scanned: prev.query.scanned + node.query.scanned,+ filtered: prev.query.filtered + node.query.filtered,+ }+ : { ...node.query };+ }+ } else {+ acc.set(node.id, {+ node,+ ms: node.ms,+ kids: [[...node.children]],+ query: node.query ? { ...node.query } : null,+ });+ }+ }+ }+ const out: ProfileNode[] = [];+ for (const e of acc.values()) {+ out.push({+ id: e.node.id,+ label: e.node.label,+ ms: e.ms / frames,+ kind: e.node.kind,+ children: meanNodes(e.kids, frames),+ ...(e.query+ ? {+ query: {+ calls: e.query.calls / frames,+ scanned: e.query.scanned / frames,+ filtered: e.query.filtered / frames,+ },+ }+ : {}),+ });+ }+ out.sort(byMsDesc);+ return out;+}+/** The part of a dotted scope name that names its domain. */export function scopeDomain(name: string): string {const dot = name.indexOf('.');@@ -123,30 +195,34 @@ export function buildFrameProfile(input: FrameProfileInput): FrameProfile {kind: 'scope',children: [],}));- const rest = Math.max(0, scope.ms - sumMs(grandChildren));- if (rest >= EPS_MS) {+ const unclaimed = Math.max(0, scope.ms - sumMs(grandChildren));+ // A wait leaves the tree entirely rather than becoming a row in it:+ // the tree is work, and time blocked on a swapchain is not work. It+ // survives as the profile's waitMs, which the frame identity carries.+ if (scope.remainder === 'wait') {+ systemWait += unclaimed;+ } else if (unclaimed >= EPS_MS && grandChildren.length > 0) {grandChildren.push({id: `${sys.name}/${scope.name}/~`,- label: scope.remainder === 'wait' ? 'wait' : 'rest',- ms: rest,- kind: scope.remainder === 'wait' ? 'wait' : 'rest',+ label: 'rest',+ ms: unclaimed,+ kind: 'rest',children: [],});- if (scope.remainder === 'wait') systemWait += rest;}grandChildren.sort(byMsDesc);+ const scopeWork = scope.remainder === 'wait' ? scope.ms - unclaimed : scope.ms;children.push({id: `${sys.name}/${scope.name}`,label: scope.name,- ms: scope.ms,+ ms: scopeWork,kind: 'scope',children: grandChildren,});}const work = Math.max(0, sys.ms - systemWait);- const measured = sumMs(children) - systemWait;- const rest = Math.max(0, work - measured);+ const rest = Math.max(0, work - sumMs(children));if (children.length > 0 && rest >= EPS_MS) {children.push({ id: `${sys.name}/~`, label: 'rest', ms: rest, kind: 'rest', children: [] });}diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex bc37f4e80..4bf8c6ac2 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -203,6 +203,7 @@ export { StatsOverlay, type StatsPosition } from './stats-overlay';export {buildFrameProfile,+ meanFrameProfile,scopeDomain,DOMAIN_SCRIPTS,DOMAIN_UNATTRIBUTED,@@ -210,6 +211,7 @@ export {type FrameProfileInput,type ProfileNode,type ProfileNodeKind,+ type QueryCost,type ScopeCost,type ScopeRemainder,type SystemCost,diff --git a/sdk/tests/frame-profile.test.ts b/sdk/tests/frame-profile.test.tsindex 8c25ddc96..fe88bc750 100644--- a/sdk/tests/frame-profile.test.ts+++ b/sdk/tests/frame-profile.test.ts@@ -3,6 +3,7 @@import { describe, it, expect } from 'vitest';import {buildFrameProfile,+ meanFrameProfile,scopeDomain,DOMAIN_SCRIPTS,type FrameProfileInput,@@ -163,8 +164,21 @@ describe('buildFrameProfile', () => {const profile = buildFrameProfile(emptyScene);const scope = findNode(profile.domains, 'RenderSystem/render.submit');- expect(scope?.children.map((c) => c.label)).toEqual(['wait', 'render.collect', 'render.finalize']);- assertChildrenSum(scope!);+ expect(scope?.children.map((c) => c.label)).toEqual(['render.collect', 'render.finalize']);+ expect(scope?.ms).toBeCloseTo(0.03, 4);+ });++ // The wait leaves the tree rather than becoming a row in it, so a scope+ // can never come out larger than the system that contains it.+ it('keeps every node the sum of its children, wait and all', () => {+ const profile = buildFrameProfile(emptyScene);+ for (const domain of profile.domains) assertChildrenSum(domain);+ });++ it('does not let a blocked scope outgrow its system', () => {+ const profile = buildFrameProfile(emptyScene);+ const sys = findNode(profile.domains, 'RenderSystem')!;+ for (const child of sys.children) expect(child.ms).toBeLessThanOrEqual(sys.ms + 1e-9);});it('does not hand the same native scope to a work scope', () => {@@ -174,8 +188,55 @@ describe('buildFrameProfile', () => {});expect(profile.waitMs).toBe(0);- expect(findNode(profile.domains, 'RenderSystem/render.submit')?.children.map((c) => c.label))- .toEqual(['rest']);+ expect(findNode(profile.domains, 'RenderSystem/render.submit')?.children).toEqual([]);});});});++describe('meanFrameProfile', () => {+ const frameOf = (renderMs: number, scanned = 0): FrameProfileInput => ({+ frameMs: 16.7,+ systems: [{+ name: 'RenderSystem',+ ms: renderMs,+ domain: 'render',+ ...(scanned ? { query: { calls: 1, scanned, filtered: 0 } } : {}),+ }],+ scopes: [],+ });++ it('is an empty profile for an empty window', () => {+ const p = meanFrameProfile([]);+ expect(p.domains).toEqual([]);+ expect(p.frameMs).toBe(0);+ expect(p.gpuMs).toBe(-1);+ });++ it('averages a node over the window', () => {+ const p = meanFrameProfile([frameOf(2), frameOf(4)].map(buildFrameProfile));+ expect(findNode(p.domains, 'RenderSystem')?.ms).toBeCloseTo(3, 4);+ });++ it('divides a sometimes-absent system by the whole window, not its appearances', () => {+ const idle = buildFrameProfile({ frameMs: 16.7, systems: [], scopes: [] });+ const p = meanFrameProfile([buildFrameProfile(frameOf(4)), idle, idle, idle]);+ expect(findNode(p.domains, 'RenderSystem')?.ms).toBeCloseTo(1, 4);+ });++ it('keeps the frame identity every single frame has', () => {+ const p = meanFrameProfile([frameOf(2), frameOf(4)].map(buildFrameProfile));+ expect(p.cpuMs + p.waitMs + p.idleMs).toBeCloseTo(p.frameMs, 4);+ });++ it('averages query cost per frame, so it reads as what a frame walks', () => {+ const p = meanFrameProfile([frameOf(2, 100), frameOf(2, 300)].map(buildFrameProfile));+ expect(findNode(p.domains, 'RenderSystem')?.query?.scanned).toBeCloseTo(200, 4);+ });++ it('reports gpu unavailable only when no frame had a timer', () => {+ const noTimer = buildFrameProfile({ frameMs: 16.7, systems: [], scopes: [] });+ const timed = buildFrameProfile({ frameMs: 16.7, systems: [], scopes: [], gpuMs: 4 });+ expect(meanFrameProfile([noTimer, noTimer]).gpuMs).toBe(-1);+ expect(meanFrameProfile([noTimer, timed]).gpuMs).toBeCloseTo(4, 4);+ });+});