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): a profile is a document, and the panel is its viewer
yhh44fa158344ea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d71b7040d..9af0df9b4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -110,6 +110,25 @@ published separately; it ships inside the editor.rule, because every member is a branch of the rule. `FlushReason` is gone; thenames that replace it are the ones the merge actually uses.+- **A profile is a document, and the panel is its viewer.** The profiler only+ existed where the editor was attached, which is the wrong place: what drops to+ 40fps drops on someone's phone. Recorded frames are now a portable `.esprof`+ the panel opens — the same rows, the same tree, the same sums, with where it+ came from stated on the page rather than assumed.++ The format lives beside the cost model rather than in the editor, because it is+ the same vocabulary: a capture is a list of frames in exactly the terms a live+ frame is measured in, so reading one needs no translation and no second+ implementation to drift. `summarizeFrames` is what the live window an agent+ asks for, an imported file and (next) a report from a shipped build all go+ through, so none of them can compute a different fps from the same frames. The+ editor's per-frame cost rides along in a field a shipped game simply omits.++ A file picked by hand is the one input guaranteed to sometimes be the wrong+ file, so the reader returns a refusal with the reason — not JSON, no version,+ frames that are not frames, a version newer than this editor reads — instead of+ throwing where a panel cannot say why.+- **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/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex ea2b1c843..43dcd4cbe 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -29,7 +29,8 @@ import { Material, Sprite, Renderer } from 'esengine';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 { PerfMonitor, type PerfSnapshot, type FrameSample } from './PerfMonitor';+import type { ProfileCapture } from 'esengine';import type { ProfileReport } from './profileReport';import type { SceneCommandsImpl, EditorTransaction } from './SceneCommands';import type { SceneQueryImpl, EntityInfo } from './SceneQuery';@@ -1024,7 +1025,7 @@ export class EditorControlSurfaceImpl {stopProfileRecording(): void {PerfMonitor.stopRecording();}- exportProfileSession(): SessionCapture {+ exportProfileSession(): ProfileCapture {return PerfMonitor.exportSession();}diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.tsindex 5b8ed6377..b6d6ef511 100644--- a/desktop/src/engine/PerfMonitor.ts+++ b/desktop/src/engine/PerfMonitor.ts@@ -4,15 +4,21 @@* @file PerfMonitor.ts — the editor's per-frame instrumentation hub.*/import { createStore } from 'zustand/vanilla';-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 {- if (values.length === 0) return 0;- const s = [...values].sort((a, b) => a - b);- const i = Math.min(s.length - 1, Math.max(0, Math.round((p / 100) * (s.length - 1))));- return s[i];-}+import {+ buildFrameProfile,+ frameProfileOf,+ percentile,+ summarizeFrames,+ PROFILE_CAPTURE_VERSION,+ type CapturedFrame,+ type CaptureSummary,+ type FrameCosts,+ type FrameProfile,+ type ProfileCapture,+ type ScopeCost,+} from 'esengine';++export { percentile };/** The phase with the most accumulated time in a frame, or null. */export function dominantPhase(phases: Record<string, number>): { phase: string; ms: number } | null {@@ -166,48 +172,31 @@ export interface PerfSnapshot {}/** What a sampling window saw — the answer to "why is it slow right now". */-export interface ProfileWindow {+export interface ProfileWindow extends CaptureSummary {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;- drawCalls: number;- triangles: number;- entities: number;- /** Engine + editor named counters, averaged per frame. */- counters: Record<string, number>;-}--function meanCounters(frames: readonly FrameSample[]): Record<string, number> {- const total: Record<string, number> = {};- for (const f of frames) {- for (const k in f.counters) total[k] = (total[k] ?? 0) + f.counters[k];- }- for (const k in total) total[k] /= frames.length;- return total;}-/** A recorded profiling session, serialized to JSON for offline analysis. */-export interface SessionCapture {- version: number;- generatedAt: string;- realm: 'edit' | 'play';- budgetMs: number;- frameCount: number;- frames: FrameSample[];- /** Recent main-thread long tasks — correlate `start` with frame t0/t1. */- longTasks?: Array<{ start: number; ms: number; name: string }>;+/** One captured frame in the portable vocabulary — what a `.esprof` holds. */+export function capturedFrameOf(s: FrameSample): CapturedFrame {+ return {+ id: s.id,+ dtMs: s.dt,+ systems: s.costs?.systems ?? [],+ scopes: s.costs?.scopes ?? [],+ nativeScopes: nativeScopesOf(s.cppScopes),+ gpuMs: s.gpuMs,+ counters: s.counters,+ drawCalls: s.drawCalls,+ triangles: s.triangles,+ entities: s.entities,+ // Absent from anything a shipped game records; kept here because profiling+ // the editor is a real thing the editor's own profiler is asked to do.+ editor: { ms: s.editorMs, phases: s.editorPhases },+ };}const LONG_FRAME_MS = 24; // missed a 60Hz frame@@ -354,16 +343,15 @@ class PerfMonitorImpl {}/** The recorded session (or the live ring if nothing was recorded), for export. */- exportSession(): SessionCapture {- const frames = this.recordBuffer.length ? this.recordBuffer.slice() : this.samples.slice();+ exportSession(): ProfileCapture {+ const frames = this.recordBuffer.length ? this.recordBuffer : this.samples;return {- version: 1,+ version: PROFILE_CAPTURE_VERSION,generatedAt: new Date().toISOString(),- realm: this.realm,+ source: { realm: this.realm },budgetMs: 1000 / 60,- frameCount: frames.length,- frames,- longTasks: this.longTasks.slice(),+ frames: frames.map(capturedFrameOf),+ longTasks: this.longTasks.map((t) => ({ startMs: t.start, ms: t.ms, name: t.name })),};}@@ -387,30 +375,17 @@ class PerfMonitorImpl {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);+ const frames = this.samples.filter((s) => s.id >= firstId).map(capturedFrameOf);+ const worstId = summarizeFrames(frames).worstFrameId;+ const worst = frames.find((f) => f.id === worstId) ?? null;return {+ ...summarizeFrames(frames),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),- drawCalls: frames.length ? frames.reduce((a, s) => a + s.drawCalls, 0) / frames.length : 0,- triangles: frames.length ? frames.reduce((a, s) => a + s.triangles, 0) / frames.length : 0,- entities: frames.length ? frames.reduce((a, s) => a + s.entities, 0) / frames.length : 0,- counters: frames.length ? meanCounters(frames) : {},+ worstFrameProfile: worst ? frameProfileOf(worst) : null,};}diff --git a/desktop/src/i18n/messages/logs.ts b/desktop/src/i18n/messages/logs.tsindex 6fcfc63e8..0c3218d70 100644--- a/desktop/src/i18n/messages/logs.ts+++ b/desktop/src/i18n/messages/logs.ts@@ -103,6 +103,20 @@ export const logsMessages = defineMessages({'prof.unattributed': { en: '{ms}ms unattributed', zh: '{ms}ms 未归因' },'prof.browserPaintGc': { en: 'browser paint / GC', zh: '浏览器绘制 / GC' },+ // — Profiler: imported capture —+ 'prof.open': { en: 'Open…', zh: '打开…' },+ 'prof.openTitle': { en: 'Open a recorded .esprof capture', zh: '打开一份录制的 .esprof 捕获' },+ 'prof.importedCapture': { en: 'Imported capture', zh: '导入的捕获' },+ 'prof.closeCapture': { en: '← Live', zh: '← 实时' },+ 'prof.wholeCapture': { en: 'Whole capture', zh: '整份捕获' },+ 'prof.captureMean': { en: 'per frame', zh: '每帧平均' },+ 'prof.frameN': { en: 'frame #{id}', zh: '帧 #{id}' },+ 'prof.unknownOrigin': { en: 'origin not recorded', zh: '未记录来源' },+ 'prof.captureOrigin': {+ en: '{frames} frames · {when} · {origin}',+ zh: '{frames} 帧 · {when} · {origin}',+ },+// — Profiler: cost tree —'prof.lastFrame': { en: 'last frame', zh: '最近一帧' },'prof.queryScanned': { en: 'query walked {n} entities in {calls}', zh: '查询遍历 {n} 个实体,{calls} 次' },diff --git a/desktop/src/panels/ProfilerPanel.tsx b/desktop/src/panels/ProfilerPanel.tsxindex add2d84ee..0f9bca578 100644--- a/desktop/src/panels/ProfilerPanel.tsx+++ b/desktop/src/panels/ProfilerPanel.tsx@@ -6,7 +6,8 @@import { useSyncExternalStore, useRef, useEffect, useCallback, useState } from 'react';import type { MouseEvent as ReactMouseEvent } from 'react';import { PerfMonitor, profileOf } from '@/engine/PerfMonitor';-import type { ProfileNode } from 'esengine';+import { parseProfileCapture, summarizeCapture, frameProfileOf } from 'esengine';+import type { ProfileNode, ProfileCapture, CaptureSummary, CapturedFrame } from 'esengine';import { t } from '@/i18n';const BUDGET_MS = 1000 / 60; // 60 Hz frame budget (16.6ms)@@ -30,11 +31,33 @@ function downloadSession(): void {const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;- a.download = `profile-${cap.generatedAt.replace(/[:.]/g, '-')}.json`;+ a.download = `profile-${cap.generatedAt.replace(/[:.]/g, '-')}.esprof`;a.click();URL.revokeObjectURL(url);}+/** A capture read off disk, and what it came to. Null while looking at the live realm. */+interface LoadedCapture {+ name: string;+ capture: ProfileCapture;+ summary: CaptureSummary;+}++async function pickCapture(): Promise<LoadedCapture | string> {+ const input = document.createElement('input');+ input.type = 'file';+ input.accept = '.esprof,.json';+ const file = await new Promise<File | null>((resolve) => {+ input.onchange = () => resolve(input.files?.[0] ?? null);+ input.click();+ });+ if (!file) return '';+ const parsed = parseProfileCapture(await file.text());+ if ('error' in parsed) return `${file.name}: ${parsed.error}`;+ if (parsed.capture.frames.length === 0) return `${file.name}: the capture has no frames`;+ return { name: file.name, capture: parsed.capture, summary: summarizeCapture(parsed.capture) };+}+const GROUPS = [{ id: 'frame', label: t('prof.groupFrame') },{ id: 'unit', label: t('prof.groupUnit') },@@ -102,8 +125,15 @@ function MemGraph({ hist }: { hist: Array<{ wasm: number; js: number; vram: numb/** Frame-time history: each recent frame as a bar with 60/30 Hz budget lines,* hitches amber→red, the pinned frame marked. Click a bar to pin it. */-function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number | null }) {+function FrameGraph({ frames, pinnedIdx, budgetMs, onPick }: {+ frames: number[];+ /** Index into `frames`, or -1 for none. */+ pinnedIdx: number;+ budgetMs: number;+ onPick: (index: number) => void;+}) {const ref = useRef<HTMLCanvasElement>(null);+ const budget30 = budgetMs * 2;useEffect(() => {const cv = ref.current;@@ -127,29 +157,24 @@ function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number |let maxObserved = 0;for (const f of frames) if (f > maxObserved) maxObserved = f;- const maxMs = Math.max(BUDGET_30 * 1.2, maxObserved * 1.1);+ const maxMs = Math.max(budget30 * 1.2, maxObserved * 1.1);const yOf = (ms: number) => h - (Math.min(ms, maxMs) / maxMs) * h;ctx.strokeStyle = grid;ctx.globalAlpha = 0.5;- ctx.beginPath(); ctx.moveTo(0, yOf(BUDGET_MS)); ctx.lineTo(w, yOf(BUDGET_MS)); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(0, yOf(budgetMs)); ctx.lineTo(w, yOf(budgetMs)); ctx.stroke();ctx.setLineDash([3, 3]);- ctx.beginPath(); ctx.moveTo(0, yOf(BUDGET_30)); ctx.lineTo(w, yOf(BUDGET_30)); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(0, yOf(budget30)); ctx.lineTo(w, yOf(budget30)); ctx.stroke();ctx.setLineDash([]);ctx.globalAlpha = 1;const n = frames.length;if (!n) return;const bw = w / n;- // Index of the pinned frame within the (lockstep) capture ring, for the marker.- const samples = PerfMonitor.getSamples();- let pinnedIdx = -1;- if (pinnedId != null) for (let i = 0; i < samples.length; i++) if (samples[i].id === pinnedId) { pinnedIdx = i; break; }-for (let i = 0; i < n; i++) {const ms = frames[i];const y = yOf(ms);- ctx.fillStyle = ms >= BUDGET_30 ? err : ms >= BUDGET_MS * 1.05 ? warn : accent;+ ctx.fillStyle = ms >= budget30 ? err : ms >= budgetMs * 1.05 ? warn : accent;ctx.fillRect(i * bw, y, Math.max(1, bw - 0.4), h - y);}if (pinnedIdx >= 0) {@@ -159,18 +184,15 @@ function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number |ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke();ctx.globalAlpha = 1;}- }, [frames, pinnedId]);+ }, [frames, pinnedIdx, budgetMs, budget30]);const onClick = useCallback((e: ReactMouseEvent<HTMLCanvasElement>) => {const cv = ref.current;- if (!cv) return;+ if (!cv || frames.length === 0) return;const rect = cv.getBoundingClientRect();- const samples = PerfMonitor.getSamples();- const n = samples.length;- if (!n) return;- const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - rect.left) / rect.width) * n)));- PerfMonitor.pin(samples[i].id);- }, []);+ const n = frames.length;+ onPick(Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - rect.left) / rect.width) * n))));+ }, [frames, onPick]);return <canvas ref={ref} className="prof-graph" title={t('prof.clickToInspect')} onClick={onClick} />;}@@ -225,6 +247,104 @@ function TreeRow({ node, frameMs, depth }: { node: ProfileNode; frameMs: number;);}+/**+ * A capture off disk, rendered by the same rows the live realm uses. Where it+ * came from is stated rather than implied: a file recorded on someone's phone+ * and the editor's own last second look identical once they are both a tree.+ */+function CaptureView({ loaded, frame, onPick, onClose }: {+ loaded: LoadedCapture;+ frame: CapturedFrame | null;+ onPick: (i: number | null) => void;+ onClose: () => void;+}) {+ const { capture, summary } = loaded;+ const profile = frame ? frameProfileOf(frame) : summary.mean;+ const src = capture.source;+ const origin = [src.label, src.platform, src.realm, src.gpu].filter(Boolean).join(' · ');+ return (+ <>+ <div className="prof-controls">+ <button type="button" className="prof-btn" onClick={onClose}>{t('prof.closeCapture')}</button>+ {frame ? (+ <button type="button" className="prof-btn" onClick={() => onPick(null)}>{t('prof.wholeCapture')}</button>+ ) : null}+ <span className="prof-spacer" />+ <span className="prof-pinned">{loaded.name}</span>+ </div>++ <section className="prof-sec">+ <h4>{t('prof.importedCapture')}</h4>+ <div className="prof-budget">+ {t('prof.captureOrigin', {+ frames: summary.frames,+ when: capture.generatedAt ? capture.generatedAt.slice(0, 19).replace('T', ' ') : '—',+ origin: origin || t('prof.unknownOrigin'),+ })}+ </div>+ <FrameGraph+ frames={capture.frames.map((f) => f.dtMs)}+ pinnedIdx={frame ? capture.frames.indexOf(frame) : -1}+ budgetMs={capture.budgetMs}+ onPick={onPick}+ />+ <div className="prof-stat-grid">+ <div><span>fps</span><b>{summary.fps}</b></div>+ <div><span>p50</span><b>{summary.p50.toFixed(1)}<i>ms</i></b></div>+ <div><span>p95</span><b>{summary.p95.toFixed(1)}<i>ms</i></b></div>+ <div><span>p99</span><b>{summary.p99.toFixed(1)}<i>ms</i></b></div>+ </div>+ <div className="prof-budget">+ {t('prof.budget', { ms: capture.budgetMs.toFixed(1) })}+ {' · '}{t('prof.longFrames', { count: summary.longFrames })}+ {' · '}{t('prof.worst', { ms: summary.worstFrameMs.toFixed(1) })}+ </div>+ </section>++ <section className="prof-sec">+ <h4>+ {t('prof.groupTree')}+ <span className="prof-realm"> · {frame ? t('prof.frameN', { id: frame.id }) : t('prof.captureMean')}</span>+ </h4>+ <div className="prof-tree">+ {profile.domains.map((d) => (+ <TreeRow key={d.id} node={d} frameMs={profile.frameMs} depth={0} />+ ))}+ </div>+ <div className="prof-budget">+ {t('prof.treeTotals', {+ frame: profile.frameMs.toFixed(1),+ cpu: profile.cpuMs.toFixed(1),+ wait: profile.waitMs.toFixed(1),+ idle: profile.idleMs.toFixed(1),+ })}+ </div>+ </section>++ <section className="prof-sec">+ <h4>{t('prof.groupRender')}</h4>+ <div className="prof-stat-grid">+ <div><span>{t('prof.drawCalls')}</span><b>{Math.round(frame?.drawCalls ?? summary.drawCalls)}</b></div>+ <div><span>{t('prof.triangles')}</span><b>{kfmt(Math.round(frame?.triangles ?? summary.triangles))}</b></div>+ <div><span>{t('prof.entities')}</span><b>{Math.round(frame?.entities ?? summary.entities)}</b></div>+ </div>+ </section>++ <section className="prof-sec">+ <h4>{t('prof.groupCounters')}</h4>+ {Object.entries<number>(frame?.counters ?? summary.counters)+ .sort((a, b) => a[0].localeCompare(b[0]))+ .map(([name, val]) => (+ <div className="prof-brk" key={name}>+ <span className="prof-brk-name" title={name}>{name}</span>+ <span className="prof-brk-val">{kfmt(Math.round(val))}</span>+ </div>+ ))}+ </section>+ </>+ );+}+/** One "Frame = a + b + …" bar segment, width ∝ its share of the frame. */function Seg({ label, ms, frame, color, title }: { label: string; ms: number; frame: number; color: string; title?: string }) {const pct = frame > 0 ? Math.min(100, (ms / frame) * 100) : 0;@@ -241,10 +361,37 @@ export function ProfilerPanel() {const s = useSyncExternalStore(PerfMonitor.subscribe, PerfMonitor.getSnapshot);// Only while this panel is mounted does the loop pay for the engine-frame read.useEffect(() => PerfMonitor.addEngineConsumer(), []);+ const [loaded, setLoaded] = useState<LoadedCapture | null>(null);+ const [loadError, setLoadError] = useState('');+ const [loadedFrameIdx, setLoadedFrameIdx] = useState<number | null>(null);const pinned = s.pinnedId != null ? PerfMonitor.getSample(s.pinnedId) : null;const [hidden, toggleGroup] = useHiddenGroups();const show = (id: string) => !hidden.has(id);+ const openCapture = useCallback(async () => {+ const r = await pickCapture();+ if (typeof r === 'string') { if (r) setLoadError(r); return; }+ setLoadError('');+ setLoadedFrameIdx(null);+ setLoaded(r);+ }, []);++ // A loaded capture answers every section, so the panel is a viewer of one+ // whether it came off disk or off the running realm.+ const loadedFrame = loaded && loadedFrameIdx != null ? loaded.capture.frames[loadedFrameIdx] ?? null : null;+ if (loaded) {+ return (+ <div className="prof">+ <CaptureView+ loaded={loaded}+ frame={loadedFrame}+ onPick={setLoadedFrameIdx}+ onClose={() => { setLoaded(null); setLoadedFrameIdx(null); }}+ />+ </div>+ );+ }+// Sections read the pinned frame when one is inspected, else the live window.const profile = pinned ? profileOf(pinned) : s.profile;const v = pinned@@ -319,6 +466,9 @@ export function ProfilerPanel() {<button type="button" className="prof-btn" onClick={downloadSession} title={t('prof.exportTitle')}>{t('prof.export')}</button>+ <button type="button" className="prof-btn" onClick={() => void openCapture()} title={t('prof.openTitle')}>+ {t('prof.open')}+ </button><span className="prof-spacer" />{pinned ? (<span className="prof-pinned">{t('prof.pinnedFrame', { id: pinned.id, ms: pinned.dt })}</span>@@ -327,6 +477,8 @@ export function ProfilerPanel() {)}</div>+ {loadError ? <div className="prof-budget prof-warn">{loadError}</div> : null}+<div className="prof-groups">{GROUPS.map((g) => (<button@@ -344,7 +496,15 @@ export function ProfilerPanel() {{show('frame') && (<section className="prof-sec"><h4>{t('prof.groupFrame')}</h4>- <FrameGraph frames={s.frames} pinnedId={s.pinnedId} />+ <FrameGraph+ frames={s.frames}+ pinnedIdx={s.pinnedId != null ? PerfMonitor.getSamples().findIndex((x) => x.id === s.pinnedId) : -1}+ budgetMs={BUDGET_MS}+ onPick={(i) => {+ const sample = PerfMonitor.getSamples()[i];+ if (sample) PerfMonitor.pin(sample.id);+ }}+ />{pinned ? (<div className="prof-budget">{t('prof.inspectingFrame', { id: pinned.id, ms: pinned.dt })}diff --git a/desktop/tests/profile-capture-roundtrip.test.ts b/desktop/tests/profile-capture-roundtrip.test.tsnew file mode 100644index 000000000..057149bad--- /dev/null+++ b/desktop/tests/profile-capture-roundtrip.test.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file profile-capture-roundtrip.test.ts — a captured frame survives being+ * written, read back and summarized, so the panel showing a file and the+ * panel showing the live realm are showing the same numbers.+ */+import { describe, it, expect } from 'vitest';+import { parseProfileCapture, summarizeCapture, frameProfileOf, PROFILE_CAPTURE_VERSION } from 'esengine';+import type { ProfileCapture } from 'esengine';+import { capturedFrameOf, profileOf, type FrameSample } from '@/engine/PerfMonitor';++const sample = (over: Partial<FrameSample> = {}): FrameSample => ({+ id: 7,+ dt: 20,+ t0: 0,+ t1: 20,+ engineMs: 4,+ editorMs: 1.5,+ presentWaitMs: 0,+ gpuMs: 3.2,+ editorPhases: { 'react.Details': 1.5 },+ enginePhases: { Update: 4 },+ cppScopes: { 'render.collect': 0.4 },+ gpuScopes: { 'gpu.submit': 3.2 },+ costs: {+ systems: [+ { name: 'RenderSystem', ms: 3, domain: 'render' },+ { name: 'EnemyAI', ms: 1, domain: 'scripts', query: { calls: 2, scanned: 400, filtered: 380 } },+ ],+ scopes: [{ name: 'render.submit', ms: 2, system: 'RenderSystem', remainder: 'wait' }],+ },+ counters: { 'batch.draws': 6, 'batch.break.shader': 2 },+ drawCalls: 6,+ triangles: 120,+ entities: 50,+ ...over,+});++const captureOf = (samples: FrameSample[]): ProfileCapture => ({+ version: PROFILE_CAPTURE_VERSION,+ generatedAt: '2026-08-12T00:00:00.000Z',+ source: { realm: 'play' },+ budgetMs: 1000 / 60,+ frames: samples.map(capturedFrameOf),+});++/** Through JSON, as a real file would be. */+function roundTrip(capture: ProfileCapture): ProfileCapture {+ const parsed = parseProfileCapture(JSON.stringify(capture));+ if ('error' in parsed) throw new Error(parsed.error);+ return parsed.capture;+}++describe('a live frame written as a capture and read back', () => {+ it('folds into the same tree it did live', () => {+ const s = sample();+ const live = profileOf(s);+ const read = frameProfileOf(roundTrip(captureOf([s])).frames[0]);++ expect(read.cpuMs).toBeCloseTo(live.cpuMs, 6);+ expect(read.waitMs).toBeCloseTo(live.waitMs, 6);+ expect(read.idleMs).toBeCloseTo(live.idleMs, 6);+ expect(read.domains.map((d) => `${d.id}:${d.ms}`)).toEqual(live.domains.map((d) => `${d.id}:${d.ms}`));+ });++ it('keeps the wait out of the tree on the way through', () => {+ const read = frameProfileOf(roundTrip(captureOf([sample()])).frames[0]);+ expect(read.waitMs).toBeCloseTo(1.6, 6);+ expect(read.cpuMs + read.waitMs + read.idleMs).toBeCloseTo(read.frameMs, 6);+ });++ it('carries the query cost that explains a system', () => {+ const read = roundTrip(captureOf([sample()]));+ const enemy = read.frames[0].systems.find((x) => x.name === 'EnemyAI');+ expect(enemy?.query).toEqual({ calls: 2, scanned: 400, filtered: 380 });+ });++ it('carries the counters a draw-call count is made of', () => {+ const s = summarizeCapture(roundTrip(captureOf([sample(), sample({ id: 8 })])));+ expect(s.counters['batch.break.shader']).toBeCloseTo(2, 6);+ expect(s.drawCalls).toBeCloseTo(6, 6);+ });++ it('summarizes the file the same way the live window summarizes its frames', () => {+ const frames = [sample({ id: 1, dt: 16 }), sample({ id: 2, dt: 40 }), sample({ id: 3, dt: 16 })];+ const s = summarizeCapture(roundTrip(captureOf(frames)));++ expect(s.frames).toBe(3);+ expect(s.worstFrameId).toBe(2);+ expect(s.longFrames).toBe(1);+ expect(s.mean.cpuMs + s.mean.waitMs + s.mean.idleMs).toBeCloseTo(s.mean.frameMs, 6);+ });++ it('keeps the editor own cost, which a shipped game will not have', () => {+ const read = roundTrip(captureOf([sample()]));+ expect(read.frames[0].editor).toEqual({ ms: 1.5, phases: { 'react.Details': 1.5 } });+ });++ it('reads a frame with no editor block at all', () => {+ const capture = captureOf([sample()]);+ delete capture.frames[0].editor;+ const read = roundTrip(capture);+ expect(read.frames[0].editor).toBeUndefined();+ expect(frameProfileOf(read.frames[0]).cpuMs).toBeGreaterThan(0);+ });+});diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex b36da2fdc..3f5a0b114 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": 1472,+ "experimental": 1482,"deprecated": 3},- "total": 1644,+ "total": 1654,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex acf545d4e..be68e4467 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 · 1357 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1367 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1590,6 +1590,49 @@ radius: numberrestitution: number```+## CaptureSource — interface @experimental+```+engineVersion: string | undefined+gpu: string | undefined+label: string | undefined+platform: string | undefined+realm: string | undefined+```++## CaptureSummary — interface @experimental+```+budgetMs: number+counters: Record<string, number>+drawCalls: number+entities: number+fps: number+frames: number+longFrames: number+mean: FrameProfile+p50: number+p95: number+p99: number+triangles: number+worstFrameId: number | null+worstFrameMs: number+```++## CapturedFrame — interface @experimental+```+counters: Record<string, number> | undefined+drawCalls: number | undefined+dtMs: number+editor: { ms: number; phases: Record<string, number>; } | undefined+entities: number | undefined+gpuMs: number | undefined+id: number+memory: { wasmBytes?: number; jsHeapBytes?: number; vramBytes?: number; } | undefined+nativeScopes: ScopeCost[] | undefined+scopes: ScopeCost[]+systems: SystemCost[]+triangles: number | undefined+```+## Catalog — class @experimental```getAllLabels: () => string[]@@ -4450,6 +4493,11 @@ width: number | undefined"2"```+## PROFILE_CAPTURE_VERSION — const @experimental+```+1+```+## PTR_LAYOUTS — const @experimental```Record<string, PtrLayout>@@ -5398,6 +5446,16 @@ prefabEntityId: stringvisible: boolean```+## ProfileCapture — interface @experimental+```+budgetMs: number+frames: CapturedFrame[]+generatedAt: string+longTasks: { startMs: number; ms: number; name: string; }[] | undefined+source: CaptureSource+version: number+```+## ProfileNode — interface @experimental```children: readonly ProfileNode[]@@ -9535,6 +9593,11 @@ FocusPlugin(report: CensusReport): string```+## frameProfileOf — function @experimental+```+(frame: CapturedFrame): FrameProfile+```+## fsmEdges — function @experimental```(def: FsmDefinition): FsmEdge[]@@ -10230,6 +10293,11 @@ NavPlugin(text: string, path: string): LocaleTableAsset```+## parseProfileCapture — function @experimental+```+(text: string): { capture: ProfileCapture; } | { error: string; }+```+## parseRichText — function @experimental```(input: string): RichTextRun[]@@ -10275,6 +10343,11 @@ ParticlePlugin(n: number) => Dimension```+## percentile — function @experimental+```+(values: readonly number[], p: number): number+```+## perceptionPlugin — const @experimental```PerceptionPlugin@@ -10960,6 +11033,16 @@ StatsPlugin(world: World, entity: Entity): void```+## summarizeCapture — function @experimental+```+(capture: ProfileCapture): CaptureSummary+```++## summarizeFrames — function @experimental+```+(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary+```+## switchTheme — function @experimental```(world: World, tokens: ThemeTokens): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex bdda5c498..04111d28f 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 · 1376 experimental · 3 deprecated+Symbols: 112 public · 58 beta · 1386 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1590,6 +1590,49 @@ radius: numberrestitution: number```+## CaptureSource — interface @experimental+```+engineVersion: string | undefined+gpu: string | undefined+label: string | undefined+platform: string | undefined+realm: string | undefined+```++## CaptureSummary — interface @experimental+```+budgetMs: number+counters: Record<string, number>+drawCalls: number+entities: number+fps: number+frames: number+longFrames: number+mean: FrameProfile+p50: number+p95: number+p99: number+triangles: number+worstFrameId: number | null+worstFrameMs: number+```++## CapturedFrame — interface @experimental+```+counters: Record<string, number> | undefined+drawCalls: number | undefined+dtMs: number+editor: { ms: number; phases: Record<string, number>; } | undefined+entities: number | undefined+gpuMs: number | undefined+id: number+memory: { wasmBytes?: number; jsHeapBytes?: number; vramBytes?: number; } | undefined+nativeScopes: ScopeCost[] | undefined+scopes: ScopeCost[]+systems: SystemCost[]+triangles: number | undefined+```+## Catalog — class @experimental```getAllLabels: () => string[]@@ -4633,6 +4676,11 @@ width: number | undefined"2"```+## PROFILE_CAPTURE_VERSION — const @experimental+```+1+```+## PTR_LAYOUTS — const @experimental```Record<string, PtrLayout>@@ -5581,6 +5629,16 @@ prefabEntityId: stringvisible: boolean```+## ProfileCapture — interface @experimental+```+budgetMs: number+frames: CapturedFrame[]+generatedAt: string+longTasks: { startMs: number; ms: number; name: string; }[] | undefined+source: CaptureSource+version: number+```+## ProfileNode — interface @experimental```children: readonly ProfileNode[]@@ -9768,6 +9826,11 @@ FocusPlugin(report: CensusReport): string```+## frameProfileOf — function @experimental+```+(frame: CapturedFrame): FrameProfile+```+## fsmEdges — function @experimental```(def: FsmDefinition): FsmEdge[]@@ -10473,6 +10536,11 @@ NavPlugin(text: string, path: string): LocaleTableAsset```+## parseProfileCapture — function @experimental+```+(text: string): { capture: ProfileCapture; } | { error: string; }+```+## parseRichText — function @experimental```(input: string): RichTextRun[]@@ -10518,6 +10586,11 @@ ParticlePlugin(n: number) => Dimension```+## percentile — function @experimental+```+(values: readonly number[], p: number): number+```+## perceptionPlugin — const @experimental```PerceptionPlugin@@ -11203,6 +11276,16 @@ StatsPlugin(world: World, entity: Entity): void```+## summarizeCapture — function @experimental+```+(capture: ProfileCapture): CaptureSummary+```++## summarizeFrames — function @experimental+```+(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary+```+## switchTheme — function @experimental```(world: World, tokens: ThemeTokens): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e6d551d30..e60451c2b 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 · 1356 experimental · 3 deprecated+Symbols: 112 public · 55 beta · 1366 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1585,6 +1585,49 @@ radius: numberrestitution: number```+## CaptureSource — interface @experimental+```+engineVersion: string | undefined+gpu: string | undefined+label: string | undefined+platform: string | undefined+realm: string | undefined+```++## CaptureSummary — interface @experimental+```+budgetMs: number+counters: Record<string, number>+drawCalls: number+entities: number+fps: number+frames: number+longFrames: number+mean: FrameProfile+p50: number+p95: number+p99: number+triangles: number+worstFrameId: number | null+worstFrameMs: number+```++## CapturedFrame — interface @experimental+```+counters: Record<string, number> | undefined+drawCalls: number | undefined+dtMs: number+editor: { ms: number; phases: Record<string, number>; } | undefined+entities: number | undefined+gpuMs: number | undefined+id: number+memory: { wasmBytes?: number; jsHeapBytes?: number; vramBytes?: number; } | undefined+nativeScopes: ScopeCost[] | undefined+scopes: ScopeCost[]+systems: SystemCost[]+triangles: number | undefined+```+## Catalog — class @experimental```getAllLabels: () => string[]@@ -4445,6 +4488,11 @@ width: number | undefined"2"```+## PROFILE_CAPTURE_VERSION — const @experimental+```+1+```+## PTR_LAYOUTS — const @experimental```Record<string, PtrLayout>@@ -5393,6 +5441,16 @@ prefabEntityId: stringvisible: boolean```+## ProfileCapture — interface @experimental+```+budgetMs: number+frames: CapturedFrame[]+generatedAt: string+longTasks: { startMs: number; ms: number; name: string; }[] | undefined+source: CaptureSource+version: number+```+## ProfileNode — interface @experimental```children: readonly ProfileNode[]@@ -9530,6 +9588,11 @@ FocusPlugin(report: CensusReport): string```+## frameProfileOf — function @experimental+```+(frame: CapturedFrame): FrameProfile+```+## fsmEdges — function @experimental```(def: FsmDefinition): FsmEdge[]@@ -10235,6 +10298,11 @@ NodePlatformAdapter(text: string, path: string): LocaleTableAsset```+## parseProfileCapture — function @experimental+```+(text: string): { capture: ProfileCapture; } | { error: string; }+```+## parseRichText — function @experimental```(input: string): RichTextRun[]@@ -10280,6 +10348,11 @@ ParticlePlugin(n: number) => Dimension```+## percentile — function @experimental+```+(values: readonly number[], p: number): number+```+## perceptionPlugin — const @experimental```PerceptionPlugin@@ -10965,6 +11038,16 @@ StatsPlugin(world: World, entity: Entity): void```+## summarizeCapture — function @experimental+```+(capture: ProfileCapture): CaptureSummary+```++## summarizeFrames — function @experimental+```+(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary+```+## switchTheme — function @experimental```(world: World, tokens: ThemeTokens): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 62231a716..f57f52b26 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 · 1377 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1387 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1585,6 +1585,49 @@ radius: numberrestitution: number```+## CaptureSource — interface @experimental+```+engineVersion: string | undefined+gpu: string | undefined+label: string | undefined+platform: string | undefined+realm: string | undefined+```++## CaptureSummary — interface @experimental+```+budgetMs: number+counters: Record<string, number>+drawCalls: number+entities: number+fps: number+frames: number+longFrames: number+mean: FrameProfile+p50: number+p95: number+p99: number+triangles: number+worstFrameId: number | null+worstFrameMs: number+```++## CapturedFrame — interface @experimental+```+counters: Record<string, number> | undefined+drawCalls: number | undefined+dtMs: number+editor: { ms: number; phases: Record<string, number>; } | undefined+entities: number | undefined+gpuMs: number | undefined+id: number+memory: { wasmBytes?: number; jsHeapBytes?: number; vramBytes?: number; } | undefined+nativeScopes: ScopeCost[] | undefined+scopes: ScopeCost[]+systems: SystemCost[]+triangles: number | undefined+```+## Catalog — class @experimental```getAllLabels: () => string[]@@ -4690,6 +4733,11 @@ width: number | undefined"2"```+## PROFILE_CAPTURE_VERSION — const @experimental+```+1+```+## PTR_LAYOUTS — const @experimental```Record<string, PtrLayout>@@ -5638,6 +5686,16 @@ prefabEntityId: stringvisible: boolean```+## ProfileCapture — interface @experimental+```+budgetMs: number+frames: CapturedFrame[]+generatedAt: string+longTasks: { startMs: number; ms: number; name: string; }[] | undefined+source: CaptureSource+version: number+```+## ProfileNode — interface @experimental```children: readonly ProfileNode[]@@ -9780,6 +9838,11 @@ FocusPlugin(report: CensusReport): string```+## frameProfileOf — function @experimental+```+(frame: CapturedFrame): FrameProfile+```+## fsmEdges — function @experimental```(def: FsmDefinition): FsmEdge[]@@ -10485,6 +10548,11 @@ NavPlugin(text: string, path: string): LocaleTableAsset```+## parseProfileCapture — function @experimental+```+(text: string): { capture: ProfileCapture; } | { error: string; }+```+## parseRichText — function @experimental```(input: string): RichTextRun[]@@ -10530,6 +10598,11 @@ ParticlePlugin(n: number) => Dimension```+## percentile — function @experimental+```+(values: readonly number[], p: number): number+```+## perceptionPlugin — const @experimental```PerceptionPlugin@@ -11215,6 +11288,16 @@ StatsPlugin(world: World, entity: Entity): void```+## summarizeCapture — function @experimental+```+(capture: ProfileCapture): CaptureSummary+```++## summarizeFrames — function @experimental+```+(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary+```+## switchTheme — function @experimental```(world: World, tokens: ThemeTokens): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 1d64332e3..45a71f2f9 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 · 1367 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1377 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1585,6 +1585,49 @@ radius: numberrestitution: number```+## CaptureSource — interface @experimental+```+engineVersion: string | undefined+gpu: string | undefined+label: string | undefined+platform: string | undefined+realm: string | undefined+```++## CaptureSummary — interface @experimental+```+budgetMs: number+counters: Record<string, number>+drawCalls: number+entities: number+fps: number+frames: number+longFrames: number+mean: FrameProfile+p50: number+p95: number+p99: number+triangles: number+worstFrameId: number | null+worstFrameMs: number+```++## CapturedFrame — interface @experimental+```+counters: Record<string, number> | undefined+drawCalls: number | undefined+dtMs: number+editor: { ms: number; phases: Record<string, number>; } | undefined+entities: number | undefined+gpuMs: number | undefined+id: number+memory: { wasmBytes?: number; jsHeapBytes?: number; vramBytes?: number; } | undefined+nativeScopes: ScopeCost[] | undefined+scopes: ScopeCost[]+systems: SystemCost[]+triangles: number | undefined+```+## Catalog — class @experimental```getAllLabels: () => string[]@@ -4452,6 +4495,11 @@ width: number | undefined"2"```+## PROFILE_CAPTURE_VERSION — const @experimental+```+1+```+## PTR_LAYOUTS — const @experimental```Record<string, PtrLayout>@@ -5400,6 +5448,16 @@ prefabEntityId: stringvisible: boolean```+## ProfileCapture — interface @experimental+```+budgetMs: number+frames: CapturedFrame[]+generatedAt: string+longTasks: { startMs: number; ms: number; name: string; }[] | undefined+source: CaptureSource+version: number+```+## ProfileNode — interface @experimental```children: readonly ProfileNode[]@@ -9557,6 +9615,11 @@ FocusPlugin(report: CensusReport): string```+## frameProfileOf — function @experimental+```+(frame: CapturedFrame): FrameProfile+```+## fsmEdges — function @experimental```(def: FsmDefinition): FsmEdge[]@@ -10257,6 +10320,11 @@ NavPlugin(text: string, path: string): LocaleTableAsset```+## parseProfileCapture — function @experimental+```+(text: string): { capture: ProfileCapture; } | { error: string; }+```+## parseRichText — function @experimental```(input: string): RichTextRun[]@@ -10302,6 +10370,11 @@ ParticlePlugin(n: number) => Dimension```+## percentile — function @experimental+```+(values: readonly number[], p: number): number+```+## perceptionPlugin — const @experimental```PerceptionPlugin@@ -10987,6 +11060,16 @@ StatsPlugin(world: World, entity: Entity): void```+## summarizeCapture — function @experimental+```+(capture: ProfileCapture): CaptureSummary+```++## summarizeFrames — function @experimental+```+(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary+```+## switchTheme — function @experimental```(world: World, tokens: ThemeTokens): voiddiff --git a/sdk/src/app/profileCapture.ts b/sdk/src/app/profileCapture.tsnew file mode 100644index 000000000..9a1f8b0b9--- /dev/null+++ b/sdk/src/app/profileCapture.ts@@ -0,0 +1,182 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file profileCapture.ts — recorded frames as a portable document.+ */+import {+ buildFrameProfile,+ meanFrameProfile,+ type FrameProfile,+ type ScopeCost,+ type SystemCost,+} from './frameProfile';++/** Bumped when a reader can no longer make sense of an older file. */+export const PROFILE_CAPTURE_VERSION = 1;++/** Where a capture came from. Every field optional: a bare App knows none of it. */+export interface CaptureSource {+ /** 'edit' / 'play' in the editor; a shipped build names its platform. */+ realm?: string;+ engineVersion?: string;+ platform?: string;+ gpu?: string;+ /** Free-form: device model, build id, the scene under test. */+ label?: string;+}++/**+ * One frame, in the terms the profile model reads. Deliberately the same+ * vocabulary a live frame is measured in, so a capture needs no translation+ * and no reader can drift from what the panel shows.+ */+export interface CapturedFrame {+ id: number;+ dtMs: number;+ systems: SystemCost[];+ scopes: ScopeCost[];+ /** Scopes measured inside wasm. */+ nativeScopes?: ScopeCost[];+ /** -1 when no GPU timer answered. */+ gpuMs?: number;+ counters?: Record<string, number>;+ drawCalls?: number;+ triangles?: number;+ entities?: number;+ memory?: { wasmBytes?: number; jsHeapBytes?: number; vramBytes?: number };+ /** Editor-only. Absent from anything a shipped game records. */+ editor?: { ms: number; phases: Record<string, number> };+}++export interface ProfileCapture {+ version: number;+ generatedAt: string;+ source: CaptureSource;+ /** The frame budget the capture was judged against (ms). */+ budgetMs: number;+ frames: CapturedFrame[];+ /** Main-thread long tasks, for correlating a spike the frames cannot explain. */+ longTasks?: Array<{ startMs: number; ms: number; name: string }>;+}++/** What a set of frames came to. The one summary every reader shows. */+export interface CaptureSummary {+ frames: number;+ budgetMs: number;+ fps: number;+ p50: number;+ p95: number;+ p99: number;+ /** Frames over the budget by half again — a visible stutter. */+ longFrames: number;+ worstFrameMs: number;+ worstFrameId: number | null;+ /** The window's cost, per frame. */+ mean: FrameProfile;+ drawCalls: number;+ triangles: number;+ entities: number;+ /** Named counters, averaged per frame. */+ counters: Record<string, number>;+}++/** p-th percentile (0..100) of an unsorted sample; 0 for an empty set. */+export function percentile(values: readonly number[], p: number): number {+ if (values.length === 0) return 0;+ const s = [...values].sort((a, b) => a - b);+ const i = Math.min(s.length - 1, Math.max(0, Math.round((p / 100) * (s.length - 1))));+ return s[i];+}++/** Fold one captured frame into its cost tree. */+export function frameProfileOf(frame: CapturedFrame): FrameProfile {+ return buildFrameProfile({+ frameMs: frame.dtMs,+ systems: frame.systems,+ scopes: frame.scopes,+ nativeScopes: frame.nativeScopes,+ gpuMs: frame.gpuMs,+ });+}++function meanOf(frames: readonly CapturedFrame[], pick: (f: CapturedFrame) => number): number {+ if (frames.length === 0) return 0;+ let total = 0;+ for (const f of frames) total += pick(f);+ return total / frames.length;+}++/**+ * Summarize frames the way every reader wants them: the live window an agent+ * asks for, an imported file, and a report a shipped build hands back all go+ * through here, so none of them can compute a different fps from the same frames.+ */+export function summarizeFrames(frames: readonly CapturedFrame[], budgetMs = 1000 / 60): CaptureSummary {+ const dts = frames.map((f) => f.dtMs);+ const p50 = percentile(dts, 50);+ let worst: CapturedFrame | null = null;+ for (const f of frames) if (!worst || f.dtMs > worst.dtMs) worst = f;++ const counters: Record<string, number> = {};+ for (const f of frames) {+ for (const k in f.counters) counters[k] = (counters[k] ?? 0) + f.counters[k];+ }+ if (frames.length > 0) for (const k in counters) counters[k] /= frames.length;++ return {+ frames: frames.length,+ budgetMs,+ fps: p50 > 0 ? Math.round(1000 / p50) : 0,+ p50,+ p95: percentile(dts, 95),+ p99: percentile(dts, 99),+ longFrames: dts.filter((d) => d >= budgetMs * 1.5).length,+ worstFrameMs: worst ? worst.dtMs : 0,+ worstFrameId: worst ? worst.id : null,+ mean: meanFrameProfile(frames.map(frameProfileOf)),+ drawCalls: meanOf(frames, (f) => f.drawCalls ?? 0),+ triangles: meanOf(frames, (f) => f.triangles ?? 0),+ entities: meanOf(frames, (f) => f.entities ?? 0),+ counters,+ };+}++export function summarizeCapture(capture: ProfileCapture): CaptureSummary {+ return summarizeFrames(capture.frames, capture.budgetMs);+}++/**+ * Read a capture from JSON, or say what is wrong with it. Returns a refusal+ * rather than throwing so a UI can show the reason: a file picked by hand is+ * the one input guaranteed to sometimes be the wrong file.+ */+export function parseProfileCapture(text: string): { capture: ProfileCapture } | { error: string } {+ let raw: unknown;+ try {+ raw = JSON.parse(text);+ } catch (e) {+ return { error: `not JSON: ${e instanceof Error ? e.message : String(e)}` };+ }+ if (typeof raw !== 'object' || raw === null) return { error: 'not a capture (expected an object)' };+ const c = raw as Partial<ProfileCapture>;+ if (typeof c.version !== 'number') return { error: 'not a capture (no version)' };+ if (c.version > PROFILE_CAPTURE_VERSION) {+ return { error: `capture version ${c.version} is newer than this editor reads (${PROFILE_CAPTURE_VERSION})` };+ }+ if (!Array.isArray(c.frames)) return { error: 'not a capture (no frames)' };+ for (const f of c.frames) {+ if (typeof f?.dtMs !== 'number' || !Array.isArray(f?.systems) || !Array.isArray(f?.scopes)) {+ return { error: 'frames are not in the capture format (need dtMs, systems, scopes)' };+ }+ }+ return {+ capture: {+ version: c.version,+ generatedAt: typeof c.generatedAt === 'string' ? c.generatedAt : '',+ source: (c.source ?? {}) as CaptureSource,+ budgetMs: typeof c.budgetMs === 'number' && c.budgetMs > 0 ? c.budgetMs : 1000 / 60,+ frames: c.frames,+ longTasks: Array.isArray(c.longTasks) ? c.longTasks : undefined,+ },+ };+}diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex 4bf8c6ac2..c69b61600 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -201,6 +201,19 @@ export {export { StatsOverlay, type StatsPosition } from './stats-overlay';+export {+ PROFILE_CAPTURE_VERSION,+ parseProfileCapture,+ summarizeCapture,+ summarizeFrames,+ frameProfileOf,+ percentile,+ type CaptureSource,+ type CaptureSummary,+ type CapturedFrame,+ type ProfileCapture,+} from './app/profileCapture';+export {buildFrameProfile,meanFrameProfile,diff --git a/sdk/tests/profile-capture.test.ts b/sdk/tests/profile-capture.test.tsnew file mode 100644index 000000000..9cbc43e8b--- /dev/null+++ b/sdk/tests/profile-capture.test.ts@@ -0,0 +1,129 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ PROFILE_CAPTURE_VERSION,+ parseProfileCapture,+ summarizeFrames,+ summarizeCapture,+ percentile,+ frameProfileOf,+ type CapturedFrame,+ type ProfileCapture,+} from '../src/app/profileCapture';++const frame = (id: number, dtMs: number, over: Partial<CapturedFrame> = {}): CapturedFrame => ({+ id,+ dtMs,+ systems: [{ name: 'RenderSystem', ms: 2, domain: 'render' }],+ scopes: [],+ ...over,+});++const capture = (frames: CapturedFrame[]): ProfileCapture => ({+ version: PROFILE_CAPTURE_VERSION,+ generatedAt: '2026-08-12T00:00:00.000Z',+ source: { realm: 'play' },+ budgetMs: 1000 / 60,+ frames,+});++describe('percentile', () => {+ it('is 0 for an empty sample', () => expect(percentile([], 50)).toBe(0));+ it('pins the ends', () => {+ const v = Array.from({ length: 100 }, (_, i) => i + 1);+ expect(percentile(v, 0)).toBe(1);+ expect(percentile(v, 100)).toBe(100);+ });+});++describe('summarizeFrames', () => {+ it('answers an empty set without inventing a frame rate', () => {+ const s = summarizeFrames([]);+ expect(s.frames).toBe(0);+ expect(s.fps).toBe(0);+ expect(s.worstFrameId).toBeNull();+ expect(s.mean.domains).toEqual([]);+ });++ it('reads fps from the median frame', () => {+ expect(summarizeFrames([frame(0, 16.7), frame(1, 16.7), frame(2, 16.7)]).fps).toBe(60);+ });++ it('names the worst frame so a reader can go to it', () => {+ const s = summarizeFrames([frame(0, 16), frame(1, 90), frame(2, 16)]);+ expect(s.worstFrameId).toBe(1);+ expect(s.worstFrameMs).toBe(90);+ });++ it('counts a stutter, not every frame a hair over budget', () => {+ const s = summarizeFrames([frame(0, 17), frame(1, 40), frame(2, 16.7)]);+ expect(s.longFrames).toBe(1);+ });++ it('averages counters per frame', () => {+ const s = summarizeFrames([+ frame(0, 16, { counters: { 'batch.draws': 4 } }),+ frame(1, 16, { counters: { 'batch.draws': 8 } }),+ ]);+ expect(s.counters['batch.draws']).toBeCloseTo(6, 4);+ });++ it('averages a counter over the whole window even when a frame lacked it', () => {+ const s = summarizeFrames([frame(0, 16, { counters: { 'batch.draws': 4 } }), frame(1, 16)]);+ expect(s.counters['batch.draws']).toBeCloseTo(2, 4);+ });++ it('keeps the mean profile summing like a frame', () => {+ const s = summarizeFrames([frame(0, 16.7), frame(1, 16.7)]);+ expect(s.mean.cpuMs + s.mean.waitMs + s.mean.idleMs).toBeCloseTo(s.mean.frameMs, 4);+ });++ it('takes the budget from the capture rather than assuming 60Hz', () => {+ const c = { ...capture([frame(0, 34), frame(1, 34)]), budgetMs: 1000 / 30 };+ expect(summarizeCapture(c).longFrames).toBe(0);+ expect(summarizeFrames(c.frames).longFrames).toBe(2);+ });+});++describe('frameProfileOf', () => {+ it('folds a captured frame with its native scopes', () => {+ const p = frameProfileOf(frame(0, 16.7, {+ scopes: [{ name: 'render.submit', ms: 2, system: 'RenderSystem', remainder: 'wait' }],+ nativeScopes: [{ name: 'render.collect', ms: 0.5, system: '', remainder: 'work' }],+ }));+ expect(p.waitMs).toBeCloseTo(1.5, 4);+ expect(p.cpuMs + p.waitMs + p.idleMs).toBeCloseTo(p.frameMs, 4);+ });+});++describe('parseProfileCapture', () => {+ it('reads a capture it wrote', () => {+ const r = parseProfileCapture(JSON.stringify(capture([frame(0, 16.7)])));+ expect('capture' in r && r.capture.frames).toHaveLength(1);+ });++ it('refuses rather than throwing on a file that is not JSON', () => {+ expect(parseProfileCapture('<html>')).toHaveProperty('error');+ });++ it('says so when the JSON is some other document', () => {+ const r = parseProfileCapture('{"hello":1}');+ expect('error' in r && r.error).toMatch(/no version/);+ });++ it('refuses a capture from a newer writer instead of half-reading it', () => {+ const r = parseProfileCapture(JSON.stringify({ ...capture([]), version: PROFILE_CAPTURE_VERSION + 1 }));+ expect('error' in r && r.error).toMatch(/newer than this editor reads/);+ });++ it('refuses frames that are not frames', () => {+ const r = parseProfileCapture(JSON.stringify({ ...capture([]), frames: [{ id: 0 }] }));+ expect('error' in r && r.error).toMatch(/not in the capture format/);+ });++ it('fills a missing budget rather than dividing by zero later', () => {+ const r = parseProfileCapture(JSON.stringify({ ...capture([frame(0, 16.7)]), budgetMs: 0 }));+ expect('capture' in r && r.capture.budgetMs).toBeCloseTo(1000 / 60, 4);+ });+});