Skip to content

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

perf(profiler): attribute the render system's present/vsync wait, not phantom CPU

yhh329f109ecdfe
diff --git a/desktop/src/components/PerfRealmBridge.tsx b/desktop/src/components/PerfRealmBridge.tsx
index 175b0d55e..a3225a275 100644
--- a/desktop/src/components/PerfRealmBridge.tsx
+++ b/desktop/src/components/PerfRealmBridge.tsx
@@ -25,7 +25,7 @@ export function PerfRealmBridge() {
const s = await PlayRealm.stats();
if (!alive) return;
cache = s
- ? { phaseMs: s.phases, systemMs: s.systems, drawCalls: s.drawCalls, triangles: s.triangles, sprites: s.sprites, entities: s.entities, gpuMs: s.gpuMs, cppScopes: s.cppScopes, cppCounters: s.cppCounters, gpuScopes: s.gpuScopes, wasmBytes: s.wasmBytes, vramBytes: s.vramBytes }
+ ? { phaseMs: s.phases, systemMs: s.systems, drawCalls: s.drawCalls, triangles: s.triangles, sprites: s.sprites, entities: s.entities, gpuMs: s.gpuMs, cppScopes: s.cppScopes, cppCounters: s.cppCounters, gpuScopes: s.gpuScopes, jsScopes: s.jsScopes, wasmBytes: s.wasmBytes, vramBytes: s.vramBytes }
: null;
};
void poll();
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index 129c0c572..752652187 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -138,6 +138,7 @@ class EngineHostImpl {
cppScopes: Record<string, number>;
cppCounters: Record<string, number>;
gpuScopes: Record<string, number>;
+ jsScopes: Record<string, number>;
wasmBytes: number;
vramBytes: number;
} | null {
@@ -146,6 +147,7 @@ class EngineHostImpl {
const m = this.module_;
const phases = app.getPhaseTimings();
const systems = app.getSystemTimings();
+ const jsScopes = app.getFrameScopes();
let cppScopes: Record<string, number> = {};
const scopesJson = m?.engine_getCpuScopes?.();
if (scopesJson) {
@@ -172,6 +174,7 @@ class EngineHostImpl {
cppScopes,
cppCounters,
gpuScopes,
+ jsScopes: jsScopes ? Object.fromEntries(jsScopes) : {},
wasmBytes: m?.HEAPU8?.byteLength ?? 0,
vramBytes: m?.renderer_getTextureBytes?.() ?? 0,
};
diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.ts
index 0a331bfa0..88bba495e 100644
--- a/desktop/src/engine/PerfMonitor.ts
+++ b/desktop/src/engine/PerfMonitor.ts
@@ -53,6 +53,9 @@ export interface EngineFrame {
cppCounters: Record<string, number>;
/** Per-frame per-pass GPU times (submit, postprocess), name → ms. */
gpuScopes: Record<string, number>;
+ /** Per-frame JS-side sub-system CPU scopes (render.resolveCameras etc.) — the
+ * `js.*` rows; the JS sibling of cppScopes. */
+ jsScopes: Record<string, number>;
/** Total wasm linear memory (bytes) — the engine's heap. */
wasmBytes: number;
/** Resident texture VRAM (bytes, estimate). */
@@ -69,10 +72,15 @@ export interface FrameSample {
engineMs: number;
editorMs: number;
gpuMs: number;
+ /** CPU blocked on the GPU swapchain/vsync (present wait), separated out of
+ * engineMs so the render system isn't misread as a hotspot. Derived from
+ * the render submit scope's wall-clock minus the C++ render CPU inside it. */
+ presentWaitMs: number;
editorPhases: Record<string, number>;
enginePhases: Record<string, number>;
cppScopes: Record<string, number>;
gpuScopes: Record<string, number>;
+ jsScopes: Record<string, number>;
counters: Record<string, number>;
systems: Array<{ name: string; ms: number }>;
drawCalls: number;
@@ -100,6 +108,9 @@ export interface PerfSnapshot {
enabled: boolean;
engineMs: number;
editorMs: number;
+ /** Windowed present/vsync wait (ms) — CPU blocked on the swapchain, split out
+ * of engineMs. See FrameSample.presentWaitMs. */
+ presentWaitMs: number;
drawCalls: number;
triangles: number;
entities: number;
@@ -143,6 +154,23 @@ export interface SessionCapture {
longTasks?: Array<{ start: number; ms: number; name: string }>;
}
+// The render system's JS scope that wraps the GPU submit + implicit present. Its
+// wall-clock minus the C++ render CPU inside it is the swapchain/vsync wait the
+// last GPU-submitting system absorbs — reclassified out of engine CPU (see loop).
+const RENDER_SUBMIT_SCOPE = 'render.submit';
+
+/**
+ * Present/vsync wait absorbed by the render system: the render submit scope's
+ * JS wall-clock minus the C++ render CPU dispatched inside it (`cppScopes`).
+ * What's left is the CPU blocked on the swapchain — not work. Returns 0 when the
+ * submit scope is absent (an SDK without the render.submit instrumentation), so
+ * the profiler degrades to the old lumped view rather than inventing a number.
+ */
+export function presentWait(jsScopes: Record<string, number>, cppScopes: Record<string, number>): number {
+ const submitWall = jsScopes[RENDER_SUBMIT_SCOPE] ?? 0;
+ return submitWall > 0 ? Math.max(0, submitWall - sumMs(cppScopes)) : 0;
+}
+
const LONG_FRAME_MS = 24; // missed a 60Hz frame
const HITCH_MS = 50; // auto-freeze threshold — a real hitch (below 20fps)
const WINDOW_MS = 500;
@@ -153,7 +181,7 @@ const r1 = (n: number) => Math.round(n * 10) / 10;
class PerfMonitorImpl {
private readonly store = createStore<PerfSnapshot>(() => ({
fps: 0, p50: 0, p95: 0, p99: 0, longFrames: 0, worstMs: 0, worstPhase: null, longTaskMs: 0, visible: false, enabled: true,
- engineMs: 0, editorMs: 0, drawCalls: 0, triangles: 0, entities: 0, systemsTop: [], realm: 'edit', gpuMs: -1, frames: [],
+ engineMs: 0, editorMs: 0, presentWaitMs: 0, drawCalls: 0, triangles: 0, entities: 0, systemsTop: [], realm: 'edit', gpuMs: -1, frames: [],
frozen: false, pinnedId: null, autoHitch: false, longTaskRev: 0,
wasmMB: 0, jsHeapMB: 0, jsHeapLimitMB: 0, vramMB: 0, memHist: [], counters: {},
recording: false, recordedFrames: 0,
@@ -176,6 +204,7 @@ class PerfMonitorImpl {
private engineConsumers_ = 0;
private engineSum = 0;
private editorSum = 0;
+ private presentWaitSum = 0;
private winFrames = 0;
private systemMax: Record<string, number> = {};
private counters = { drawCalls: 0, triangles: 0, entities: 0, gpuMs: -1 };
@@ -399,15 +428,22 @@ class PerfMonitorImpl {
let enginePhases: Record<string, number> = {};
let cppScopes: Record<string, number> = {};
let gpuScopes: Record<string, number> = {};
+ let jsScopes: Record<string, number> = {};
let engineCounters: Record<string, number> = {};
let systemsFrame: Array<{ name: string; ms: number }> = [];
+ let presentWaitMs = 0;
if (ef) {
enginePhases = ef.phaseMs;
cppScopes = ef.cppScopes;
gpuScopes = ef.gpuScopes;
+ jsScopes = ef.jsScopes;
engineCounters = ef.cppCounters;
engineFrameMs = sumMs(enginePhases);
this.engineSum += engineFrameMs;
+ // Split the swapchain/vsync block out of engine CPU (see presentWait): the
+ // render system reads as ~0, not a phantom multi-ms hotspot.
+ presentWaitMs = presentWait(jsScopes, cppScopes);
+ this.presentWaitSum += presentWaitMs;
for (const k in ef.systemMs) {
if (ef.systemMs[k] > (this.systemMax[k] ?? 0)) this.systemMax[k] = ef.systemMs[k];
}
@@ -425,11 +461,13 @@ class PerfMonitorImpl {
t1: now,
engineMs: r1(engineFrameMs),
editorMs: r1(editorFrameMs),
+ presentWaitMs: r1(presentWaitMs),
gpuMs: this.counters.gpuMs >= 0 ? r1(this.counters.gpuMs) : -1,
editorPhases: { ...editorPhases },
enginePhases: { ...enginePhases },
cppScopes: { ...cppScopes },
gpuScopes: { ...gpuScopes },
+ jsScopes: { ...jsScopes },
counters: { ...engineCounters, ...editorCounters },
systems: systemsFrame,
drawCalls: this.counters.drawCalls,
@@ -467,7 +505,7 @@ class PerfMonitorImpl {
fps: p50 > 0 ? Math.round(1000 / p50) : 0,
p50: r1(p50), p95: r1(percentile(this.frames, 95)), p99: r1(percentile(this.frames, 99)),
longFrames: this.longFrames, worstMs: r1(this.worstMs), worstPhase: this.worstPhase, longTaskMs: r1(this.longTaskMs),
- engineMs: r1(this.engineSum / wf), editorMs: r1(this.editorSum / wf),
+ engineMs: r1(this.engineSum / wf), editorMs: r1(this.editorSum / wf), presentWaitMs: r1(this.presentWaitSum / wf),
drawCalls: this.counters.drawCalls, triangles: this.counters.triangles, entities: this.counters.entities,
systemsTop: topSystems(this.systemMax, 5).map((s) => ({ name: s.name, ms: r1(s.ms) })),
realm: this.realm,
@@ -479,7 +517,7 @@ class PerfMonitorImpl {
});
this.windowStart = now;
this.longFrames = 0; this.worstMs = 0; this.worstPhase = null; this.longTaskMs = 0;
- this.engineSum = 0; this.editorSum = 0; this.winFrames = 0; this.systemMax = {};
+ this.engineSum = 0; this.editorSum = 0; this.presentWaitSum = 0; this.winFrames = 0; this.systemMax = {};
}
};
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index 2bf72672d..6d9e351d5 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -92,6 +92,7 @@ export interface PlayStatsReply {
cppScopes: Record<string, number>;
cppCounters: Record<string, number>;
gpuScopes: Record<string, number>;
+ jsScopes: Record<string, number>;
wasmBytes: number;
vramBytes: number;
}
diff --git a/desktop/src/i18n/messages/logs.ts b/desktop/src/i18n/messages/logs.ts
index c18b844ad..9a5b0d1b3 100644
--- a/desktop/src/i18n/messages/logs.ts
+++ b/desktop/src/i18n/messages/logs.ts
@@ -80,6 +80,11 @@ export const logsMessages = defineMessages({
'prof.editor': { en: 'editor', zh: '编辑器' },
'prof.present': { en: 'present', zh: '呈现' },
'prof.idle': { en: 'idle', zh: '空闲' },
+ 'prof.presentWait': { en: 'present · vsync', zh: '呈现 · 垂直同步' },
+ 'prof.presentWaitHint': {
+ en: 'CPU blocked waiting for the display swapchain (vsync), absorbed by the last system that submits to the GPU. This is idle wait, not a hotspot — it does not steal frame budget.',
+ zh: 'CPU 阻塞等待显示交换链(垂直同步),被最后一个向 GPU 提交的系统吸收。这是空闲等待、不是热点——不占帧预算。',
+ },
'prof.na': { en: 'n/a', zh: '不可用' },
// — Profiler: Render / Memory sections —
diff --git a/desktop/src/panels/ProfilerPanel.tsx b/desktop/src/panels/ProfilerPanel.tsx
index 2031f910e..60ba54c5b 100644
--- a/desktop/src/panels/ProfilerPanel.tsx
+++ b/desktop/src/panels/ProfilerPanel.tsx
@@ -174,10 +174,10 @@ function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number |
}
/** One "Frame = a + b + …" bar segment, width ∝ its share of the frame. */
-function Seg({ label, ms, frame, color }: { label: string; ms: number; frame: number; color: string }) {
+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;
return (
- <div className="prof-row">
+ <div className="prof-row" title={title}>
<span className="prof-key" style={{ color }}>{label}</span>
<span className="prof-val">{ms.toFixed(1)}<span className="prof-unit">ms</span></span>
<span className="prof-bar"><span className="prof-fill" style={{ width: `${pct}%`, background: color }} /></span>
@@ -196,21 +196,31 @@ export function ProfilerPanel() {
// Sections read the pinned frame when one is inspected, else the live window.
const v = pinned
? {
- frameMs: pinned.dt, engineMs: pinned.engineMs, editorMs: pinned.editorMs, gpuMs: pinned.gpuMs,
+ frameMs: pinned.dt, engineMs: pinned.engineMs, editorMs: pinned.editorMs, presentWaitMs: pinned.presentWaitMs, gpuMs: pinned.gpuMs,
drawCalls: pinned.drawCalls, triangles: pinned.triangles, entities: pinned.entities, systems: pinned.systems, counters: pinned.counters,
}
: {
- frameMs: s.p50, engineMs: s.engineMs, editorMs: s.editorMs, gpuMs: s.gpuMs,
+ frameMs: s.p50, engineMs: s.engineMs, editorMs: s.editorMs, presentWaitMs: s.presentWaitMs, gpuMs: s.gpuMs,
drawCalls: s.drawCalls, triangles: s.triangles, entities: s.entities, systems: s.systemsTop, counters: s.counters,
};
const counterRows = Object.entries(v.counters).sort((a, b) => a[0].localeCompare(b[0]));
- const frame = Math.max(v.frameMs, v.engineMs + v.editorMs);
- const other = Math.max(0, frame - v.engineMs - v.editorMs);
+ // Split the swap/vsync wait out of engine CPU: performance.now() around the render
+ // system absorbs the present block, so its raw engineMs reads as work it never did.
+ // engine → real CPU busy; presentWait → the blocked wait; idle → the rAF gap.
+ const presentWait = v.presentWaitMs;
+ const engineBusy = Math.max(0, v.engineMs - presentWait);
+ const frame = Math.max(v.frameMs, engineBusy + v.editorMs + presentWait);
+ const idle = Math.max(0, frame - engineBusy - v.editorMs - presentWait);
const p99Bad = s.p99 >= BUDGET_MS * 1.5;
- // A near-budget frame's leftover is just the browser idle-waiting for vsync — not
- // a hot spot. Only on a spike is the leftover genuinely unattributed work.
- const isIdle = v.frameMs <= BUDGET_MS * 1.25;
- const presentLabel = isIdle ? t('prof.idle') : t('prof.present');
+ // RenderSystem's raw timing includes the present wait; show its real CPU and list
+ // the wait as its own dimmed row so the table ranks by work, not by vsync blocking.
+ const r1 = (n: number) => Math.round(n * 10) / 10;
+ const sysRows: Array<{ name: string; ms: number; wait: boolean }> = v.systems
+ .map((sys) => sys.name === 'RenderSystem'
+ ? { name: sys.name, ms: Math.max(0, r1(sys.ms - presentWait)), wait: false }
+ : { name: sys.name, ms: sys.ms, wait: false });
+ if (presentWait >= 0.05) sysRows.push({ name: t('prof.presentWait'), ms: r1(presentWait), wait: true });
+ sysRows.sort((a, b) => b.ms - a.ms);
// The long tasks that hit the pinned frame + its measured phases, ranked.
const longTasks = pinned ? PerfMonitor.getFrameLongTasks(pinned.id) : [];
@@ -220,6 +230,7 @@ export function ProfilerPanel() {
? [
...Object.entries(pinned.editorPhases),
...Object.entries(pinned.enginePhases).map(([n, m]) => [`engine.${n}`, m] as [string, number]),
+ ...Object.entries(pinned.jsScopes).map(([n, m]) => [`js.${n}`, m] as [string, number]),
...Object.entries(pinned.cppScopes).map(([n, m]) => [`cpp.${n}`, m] as [string, number]),
...Object.entries(pinned.gpuScopes).map(([n, m]) => [`gpu.${n}`, m] as [string, number]),
]
@@ -308,9 +319,12 @@ export function ProfilerPanel() {
{show('unit') && (
<section className="prof-sec">
<h4>{t('prof.unitHeader')} <span className="prof-realm">· {s.realm}</span></h4>
- <Seg label={t('prof.engine')} ms={v.engineMs} frame={frame} color="var(--run, #46a04a)" />
+ <Seg label={t('prof.engine')} ms={engineBusy} frame={frame} color="var(--run, #46a04a)" />
<Seg label={t('prof.editor')} ms={v.editorMs} frame={frame} color="var(--star, #2f88d6)" />
- <Seg label={presentLabel} ms={other} frame={frame} color="var(--text-mute, #696a71)" />
+ {presentWait >= 0.05 ? (
+ <Seg label={t('prof.presentWait')} ms={presentWait} frame={frame} color="var(--warn, #d3a23c)" title={t('prof.presentWaitHint')} />
+ ) : null}
+ <Seg label={t('prof.idle')} ms={idle} frame={frame} color="var(--text-mute, #696a71)" />
{v.gpuMs >= 0 ? (
<Seg label="gpu" ms={v.gpuMs} frame={frame} color={GPU_COLOR} />
) : (
@@ -395,11 +409,15 @@ export function ProfilerPanel() {
{show('systems') && (
<section className="prof-sec">
<h4>{t('prof.groupSystems')}{pinned ? ` · ${t('prof.thisFrame')}` : ''}</h4>
- {v.systems.length ? (
+ {sysRows.length ? (
<table className="prof-sys">
<tbody>
- {v.systems.map((sys) => (
- <tr key={sys.name}>
+ {sysRows.map((sys) => (
+ <tr
+ key={sys.name}
+ style={sys.wait ? { opacity: 0.6 } : undefined}
+ title={sys.wait ? t('prof.presentWaitHint') : undefined}
+ >
<td>{sys.name}</td>
<td className="prof-sys-ms">{sys.ms}<i>ms</i></td>
</tr>
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index cda1e8498..afa15e364 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -470,6 +470,7 @@ window.addEventListener('message', (e: MessageEvent) => {
// engine segment for the editor profiler (PerfMonitor, realm 'play').
const phases = app ? Object.fromEntries(app.getPhaseTimings() ?? []) : {};
const systems = app ? Object.fromEntries(app.getSystemTimings() ?? []) : {};
+ const jsScopes = app ? Object.fromEntries(app.getFrameScopes() ?? []) : {};
const m = engineModule;
post({
type: 'estella:play:reply',
@@ -485,6 +486,7 @@ window.addEventListener('message', (e: MessageEvent) => {
cppScopes: jsonMap(m?.engine_getCpuScopes?.()),
cppCounters: jsonMap(m?.engine_getCounters?.()),
gpuScopes: jsonMap(m?.engine_getGpuScopes?.()),
+ jsScopes,
wasmBytes: m?.HEAPU8?.byteLength ?? 0,
vramBytes: m?.renderer_getTextureBytes?.() ?? 0,
},
diff --git a/desktop/tests/perf-monitor.test.ts b/desktop/tests/perf-monitor.test.ts
index 80874f85b..3d2852735 100644
--- a/desktop/tests/perf-monitor.test.ts
+++ b/desktop/tests/perf-monitor.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { percentile, dominantPhase, sumMs, topSystems } from '@/engine/PerfMonitor';
+import { percentile, dominantPhase, sumMs, topSystems, presentWait } from '@/engine/PerfMonitor';
describe('percentile', () => {
const v = Array.from({ length: 100 }, (_, i) => i + 1); // 1..100
@@ -41,3 +41,22 @@ describe('topSystems', () => {
expect(topSystems({ a: 1 }, 5)).toEqual([{ name: 'a', ms: 1 }]);
});
});
+
+describe('presentWait', () => {
+ it('is the submit wall-clock minus the C++ render CPU inside it', () => {
+ // Real numbers from an empty-scene capture: 2.1ms submit, ~0.02ms C++ work.
+ const js = { 'render.submit': 2.1, 'render.resolveCameras': 0.007 };
+ const cpp = { 'render.collect': 0.013, 'render.submit': 0.006, 'render.finalize': 0.002 };
+ expect(presentWait(js, cpp)).toBeCloseTo(2.079, 3);
+ });
+ it('is 0 when the submit scope is absent (old SDK, no instrumentation)', () => {
+ expect(presentWait({}, { 'render.submit': 0.5 })).toBe(0);
+ expect(presentWait({ 'render.resolveCameras': 0.1 }, {})).toBe(0);
+ });
+ it('never goes negative when C++ work exceeds the (tiny) submit wall', () => {
+ expect(presentWait({ 'render.submit': 0.1 }, { 'render.submit': 0.5 })).toBe(0);
+ });
+ it('equals the full submit wall when no C++ scopes are reported', () => {
+ expect(presentWait({ 'render.submit': 1.8 }, {})).toBe(1.8);
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index f1ecc2575..f6a7215d1 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -369,6 +369,7 @@ connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: Bridge
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
+getFrameScopes: () => ReadonlyMap<string, number> | null
getPhaseTimings: () => ReadonlyMap<string, number> | null
getPlaySpeed: () => number
getPlugin: <T extends Plugin>(ctor: new (...args: any[]) => T) => T | undefined
@@ -383,6 +384,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
isPaused: () => boolean
isPhysicsReady: boolean
+measureFrameScope: <T>(name: string, fn: () => T) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ba6c8b76e..cb415095e 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -364,6 +364,7 @@ connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: Bridge
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
+getFrameScopes: () => ReadonlyMap<string, number> | null
getPhaseTimings: () => ReadonlyMap<string, number> | null
getPlaySpeed: () => number
getPlugin: <T extends Plugin>(ctor: new (...args: any[]) => T) => T | undefined
@@ -378,6 +379,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;
insertResource: <T>(resource: ResourceDef<T>, value: T) => App
isPaused: () => boolean
isPhysicsReady: boolean
+measureFrameScope: <T>(name: string, fn: () => T) => T
onError: (handler: (error: unknown, systemName: string) => void) => App
onSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => App
onWasmError: (handler: (error: unknown, context: string) => void) => App
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index d0bdb7582..fd8f43fc4 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -112,6 +112,11 @@ export class App {
private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;
private statsEnabled_ = false;
private phaseTimings_: Map<string, number> | null = null;
+ // Sub-frame CPU scopes inside a single system (e.g. the render system's
+ // resolveCameras / submit split) — the JS-side sibling of the engine's C++
+ // ES_PROFILE_SCOPE. Null unless stats are on; same per-frame lifecycle as
+ // phaseTimings_ (cleared at tick start, read after the tick).
+ private frameScopes_: Map<string, number> | null = null;
private frame_paused_ = false;
private user_paused_ = false;
private step_pending_ = false;
@@ -515,6 +520,7 @@ export class App {
enableStats(): this {
this.statsEnabled_ = true;
this.phaseTimings_ = new Map();
+ this.frameScopes_ = new Map();
this.runner_?.setTimingEnabled(true);
return this;
}
@@ -527,6 +533,32 @@ export class App {
return this.phaseTimings_;
}
+ /**
+ * Sub-frame CPU scopes recorded this frame via {@link measureFrameScope} —
+ * the finer breakdown within a single system, keyed by scope name. Null when
+ * stats aren't enabled. Sibling of {@link getSystemTimings} /
+ * {@link getPhaseTimings}; surfaces as the profiler's `js.*` rows.
+ */
+ getFrameScopes(): ReadonlyMap<string, number> | null {
+ return this.frameScopes_;
+ }
+
+ /**
+ * Time `fn` as a named sub-frame scope (accumulated if the name repeats in a
+ * frame). A no-op passthrough when stats are off, so shipped games pay only a
+ * single branch. Use it to split a heavy system into attributable pieces.
+ */
+ measureFrameScope<T>(name: string, fn: () => T): T {
+ const scopes = this.frameScopes_;
+ if (!scopes) return fn();
+ const t0 = performance.now();
+ try {
+ return fn();
+ } finally {
+ scopes.set(name, (scopes.get(name) ?? 0) + (performance.now() - t0));
+ }
+ }
+
getEntityCount(): number {
return this.world_.entityCount();
}
@@ -689,6 +721,7 @@ export class App {
private async runFrame_(delta: number): Promise<void> {
this.runner_?.clearTimings();
this.phaseTimings_?.clear();
+ this.frameScopes_?.clear();
this.eventRegistry_.swapAll();
this.world_.advanceTick();
this.updateTime(delta);
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index bf47ee0cc..717708913 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -431,6 +431,11 @@ export function cameraPlugin(
// Per-App scratch pool for collectCameras — one per plugin instance,
// so two Apps running at once never clobber each other's CameraInfo.
const cameraInfoPool: CameraInfo[] = [];
+ // Last size pushed to the renderer — resize only when it actually
+ // changes (the C++ viewport state persists across frames), so a stable
+ // viewport pays no per-frame WASM crossing. Mirrors RenderPipeline.render.
+ let lastResizeW = 0;
+ let lastResizeH = 0;
// The editor view is inactive by default — shipped games never touch
// it; the editor activates it in edit mode (see desktop EngineHost).
@@ -477,7 +482,11 @@ export function cameraPlugin(
}
const elapsed = (platformNow() - startTime) / 1000;
- Renderer.resize(width, height);
+ if (width !== lastResizeW || height !== lastResizeH) {
+ app.measureFrameScope('render.resize', () => Renderer.resize(width, height));
+ lastResizeW = width;
+ lastResizeH = height;
+ }
let activeScenes: Set<string> | undefined;
if (app.hasResource(SceneManager)) {
@@ -490,39 +499,46 @@ export function cameraPlugin(
pipeline.setActiveScenes(activeScenes ?? null);
// Authoritative tick (advance=true): ticks the director's blend.
- const cameras = resolveCameras(app, module, cppRegistry, width, height, app.world, activeScenes, cameraInfoPool, elapsed, true);
-
- syncUICameraInfo(app, module, cppRegistry, width, height, cameras);
-
- if (cameras.length === 0) {
- pipeline.render({
- registry: { _cpp: cppRegistry },
- viewProjection: IDENTITY,
- width, height, elapsed,
- clearColor,
- });
- } else {
- pipeline.beginFrame(elapsed);
- pipeline.beginScreenCapture();
- for (const cam of cameras) {
- const vp = cam.viewportRect;
- const px = Math.round(vp.x * width);
- const py = Math.round((1 - vp.y - vp.h) * height);
- const pw = Math.round(vp.w * width);
- const ph = Math.round(vp.h * height);
- pipeline.renderCamera({
+ const cameras = app.measureFrameScope('render.resolveCameras', () =>
+ resolveCameras(app, module, cppRegistry, width, height, app.world, activeScenes, cameraInfoPool, elapsed, true));
+
+ app.measureFrameScope('render.uiCameraSync', () =>
+ syncUICameraInfo(app, module, cppRegistry, width, height, cameras));
+
+ // The JS-side dispatch of the frame — pairs with the engine's
+ // cpp.render.* scopes (submit/finalize) and gpu.* to separate the
+ // orchestration cost from the actual draw-list + GPU cost.
+ app.measureFrameScope('render.submit', () => {
+ if (cameras.length === 0) {
+ pipeline.render({
registry: { _cpp: cppRegistry },
- viewProjection: cam.viewProjection,
- viewportPixels: { x: px, y: py, w: pw, h: ph },
- clearFlags: cam.clearFlags,
- elapsed,
- cameraEntity: cam.entity,
+ viewProjection: IDENTITY,
+ width, height, elapsed,
clearColor,
});
+ } else {
+ pipeline.beginFrame(elapsed);
+ pipeline.beginScreenCapture();
+ for (const cam of cameras) {
+ const vp = cam.viewportRect;
+ const px = Math.round(vp.x * width);
+ const py = Math.round((1 - vp.y - vp.h) * height);
+ const pw = Math.round(vp.w * width);
+ const ph = Math.round(vp.h * height);
+ pipeline.renderCamera({
+ registry: { _cpp: cppRegistry },
+ viewProjection: cam.viewProjection,
+ viewportPixels: { x: px, y: py, w: pw, h: ph },
+ clearFlags: cam.clearFlags,
+ elapsed,
+ cameraEntity: cam.entity,
+ clearColor,
+ });
+ }
+ pipeline.endScreenCapture();
+ Renderer.setViewport(0, 0, width, height);
}
- pipeline.endScreenCapture();
- Renderer.setViewport(0, 0, width, height);
- }
+ });
},
};
diff --git a/sdk/tests/stats.test.ts b/sdk/tests/stats.test.ts
index c31a953fd..3aadb3702 100644
--- a/sdk/tests/stats.test.ts
+++ b/sdk/tests/stats.test.ts
@@ -202,6 +202,52 @@ describe('App stats API', () => {
expect(typeof timings.get('MySystem')).toBe('number');
});
+ it('getFrameScopes is null before enableStats; measureFrameScope is a passthrough', () => {
+ const app = App.new();
+ expect(app.getFrameScopes()).toBeNull();
+ // Off = no map, so the scope runs but records nothing and returns the value.
+ expect(app.measureFrameScope('x', () => 42)).toBe(42);
+ expect(app.getFrameScopes()).toBeNull();
+ });
+
+ it('measureFrameScope records a named scope after enableStats', () => {
+ const app = App.new();
+ app.enableStats();
+ const out = app.measureFrameScope('render.resolveCameras', () => 'ok');
+ expect(out).toBe('ok');
+ const scopes = app.getFrameScopes()!;
+ expect(scopes).toBeInstanceOf(Map);
+ expect(typeof scopes.get('render.resolveCameras')).toBe('number');
+ expect(scopes.get('render.resolveCameras')).toBeGreaterThanOrEqual(0);
+ });
+
+ it('measureFrameScope accumulates repeats of the same name within a frame', () => {
+ const app = App.new();
+ app.enableStats();
+ app.measureFrameScope('dup', () => {});
+ const first = app.getFrameScopes()!.get('dup')!;
+ app.measureFrameScope('dup', () => {});
+ expect(app.getFrameScopes()!.get('dup')!).toBeGreaterThanOrEqual(first);
+ // Still a single accumulated entry, not two.
+ expect([...app.getFrameScopes()!.keys()].filter((k) => k === 'dup')).toHaveLength(1);
+ });
+
+ it('frame scopes reset at tick start', async () => {
+ const app = App.new();
+ app.enableStats();
+ app.measureFrameScope('stale', () => {});
+ expect(app.getFrameScopes()!.has('stale')).toBe(true);
+ await app.tick(1 / 60); // no system records 'stale' this frame
+ expect(app.getFrameScopes()!.has('stale')).toBe(false);
+ });
+
+ it('measureFrameScope still records when the body throws', () => {
+ const app = App.new();
+ app.enableStats();
+ expect(() => app.measureFrameScope('boom', () => { throw new Error('x'); })).toThrow('x');
+ expect(app.getFrameScopes()!.has('boom')).toBe(true);
+ });
+
it('should return entity count', () => {
const app = App.new();
expect(app.getEntityCount()).toBe(0);