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.

feat: profiler panel with real-time stats, pause/resume and frame inspection

esenginebe779d65474e
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index b4aa15b65..16992257e 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -875,6 +875,7 @@ declare class App {
private error_handler_;
private system_error_handler_;
private statsEnabled_;
+ private phaseTimings_;
private frame_paused_;
private user_paused_;
private step_pending_;
@@ -915,6 +916,7 @@ declare class App {
getPlaySpeed(): number;
enableStats(): this;
getSystemTimings(): ReadonlyMap<string, number> | null;
+ getPhaseTimings(): ReadonlyMap<string, number> | null;
getEntityCount(): number;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 6939b5de4..ec260637f 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -947,6 +947,7 @@ declare class App {
private error_handler_;
private system_error_handler_;
private statsEnabled_;
+ private phaseTimings_;
private frame_paused_;
private user_paused_;
private step_pending_;
@@ -987,6 +988,7 @@ declare class App {
getPlaySpeed(): number;
enableStats(): this;
getSystemTimings(): ReadonlyMap<string, number> | null;
+ getPhaseTimings(): ReadonlyMap<string, number> | null;
getEntityCount(): number;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index a188be7e9..16c37b948 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -501,6 +501,9 @@
if (physicsPlugin) {
app.addPlugin(physicsPlugin);
}
+ if (config.showStats) {
+ app.addPlugin(new sdk.StatsPlugin({ position: 'top-left' }));
+ }
app.addPlugin(previewPlugin);
step = 'waitForReady (scene load)';
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 5a4957b96..8075f0ba9 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -30,6 +30,7 @@ import { ScriptLoader } from './scripting';
import { showBuildSettingsDialog, BuildService } from './builder';
import { AddressablePanel } from './panels/AddressablePanel';
import { getGlobalPathResolver } from './asset';
+import { getSharedRenderContext } from './renderer/SharedRenderContext';
import type { EditorAssetServer } from './asset/EditorAssetServer';
import { getAssetLibrary } from './asset/AssetLibrary';
import { setEditorInstance, getEditorContext, getEditorInstance } from './context/EditorContext';
@@ -79,6 +80,8 @@ import {
} from './panels/PanelRegistry';
import { MainWindowBridge } from './multiwindow/MainWindowBridge';
import { WindowManager } from './multiwindow/WindowManager';
+import { emit } from '@tauri-apps/api/event';
+import { CHANNEL_PROFILER_STATS } from './multiwindow/protocol';
export interface EditorOptions {
projectPath?: string;
@@ -107,6 +110,7 @@ export class Editor {
private scriptsReady_: Promise<void> = Promise.resolve();
private clipboard_: EntityData[] | null = null;
private addressableWindow_: { element: HTMLElement; panel: AddressablePanel; keyHandler: (e: KeyboardEvent) => void } | null = null;
+ private profilerActive_ = false;
private previewUrl_: string | null = null;
private escapeHandler_: ((e: KeyboardEvent) => void) | null = null;
private closeUnlisten_: (() => void) | null = null;
@@ -563,6 +567,49 @@ export class Editor {
this.addressableWindow_ = { element: win, panel, keyHandler };
}
+ async showProfilerWindow(): Promise<void> {
+ if (!this.windowManager_) return;
+
+ await this.windowManager_.detachPanel('profiler', 'Profiler');
+ this.startProfilerStats();
+ }
+
+ startProfilerStats(): void {
+ if (this.profilerActive_) return;
+ this.profilerActive_ = true;
+
+ const ctx = getSharedRenderContext();
+ ctx.setPostTickCallback(() => this.emitProfilerStats());
+ }
+
+ stopProfilerStats(): void {
+ if (!this.profilerActive_) return;
+ this.profilerActive_ = false;
+
+ const ctx = getSharedRenderContext();
+ ctx.setPostTickCallback(null);
+ }
+
+ private emitProfilerStats(): void {
+ const ctx = getSharedRenderContext();
+ const app = ctx.app_;
+
+ const frameTimeMs = app?.getPhaseTimings()
+ ? [...(app.getPhaseTimings() as Map<string, number>).values()].reduce((a: number, b: number) => a + b, 0)
+ : 0;
+
+ const phaseTimings: [string, number][] = app?.getPhaseTimings()
+ ? [...(app.getPhaseTimings() as Map<string, number>).entries()]
+ : [];
+
+ const systemTimings: [string, number][] = app?.getSystemTimings()
+ ? [...(app.getSystemTimings() as ReadonlyMap<string, number>).entries()]
+ : [];
+
+ const msg = { frameTimeMs, phaseTimings, systemTimings };
+ emit(CHANNEL_PROFILER_STATS, msg);
+ }
+
private async syncProjectSettings(): Promise<void> {
if (!this.projectPath_) return;
const config = await loadProjectConfig(this.projectPath_);
@@ -884,6 +931,19 @@ export class Editor {
this.updatePreviewUrl();
}
+ togglePreviewStats(enabled: boolean): void {
+ this.previewManager_.setShowStats(enabled);
+ if (this.previewUrl_) {
+ this.previewManager_.refreshFiles(
+ this.store_.scene, this.scriptLoader_, this.spineVersion_,
+ );
+ }
+ }
+
+ get previewStatsEnabled(): boolean {
+ return this.previewManager_.showStats;
+ }
+
private updatePreviewUrl(): void {
const urlEl = this.container_.querySelector('.es-preview-url') as HTMLElement;
if (!urlEl) return;
@@ -1011,6 +1071,10 @@ export class Editor {
<span class="es-menubar-scene-name"></span>
</div>
<span class="es-preview-url" style="display:none" title="Click to copy"></span>
+ <label class="es-preview-stats-toggle" title="Show stats overlay in preview">
+ <input type="checkbox" class="es-preview-stats-cb" />
+ <span>Stats</span>
+ </label>
<button class="es-btn es-btn-preview" data-action="preview">${icons.play(14)} Preview</button>
</div>
<div class="es-editor-dock"></div>
@@ -1050,6 +1114,11 @@ export class Editor {
}
});
+ const statsCb = this.container_.querySelector('.es-preview-stats-cb') as HTMLInputElement;
+ statsCb?.addEventListener('change', () => {
+ this.togglePreviewStats(statsCb.checked);
+ });
+
this.menuManager_.setupToolbarEvents(this.container_, () => this.startPreview());
this.setupEscapeHandler();
this.store_.subscribe(() => this.menuManager_.updateToolbarState(this.container_));
@@ -1193,6 +1262,7 @@ export class Editor {
document.removeEventListener('keydown', this.addressableWindow_.keyHandler);
this.addressableWindow_ = null;
}
+ this.stopProfilerStats();
if (this.escapeHandler_) {
document.removeEventListener('keydown', this.escapeHandler_);
this.escapeHandler_ = null;
diff --git a/editor/src/PreviewManager.ts b/editor/src/PreviewManager.ts
index a5235f8c8..3efdee351 100644
--- a/editor/src/PreviewManager.ts
+++ b/editor/src/PreviewManager.ts
@@ -73,6 +73,16 @@ export class PreviewManager {
this.previewService_.updatePreviewFiles(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig, runtimeConfig);
}
+ private showStats_ = false;
+
+ setShowStats(enabled: boolean): void {
+ this.showStats_ = enabled;
+ }
+
+ get showStats(): boolean {
+ return this.showStats_;
+ }
+
private collectPreviewConfig(spineVersion: string) {
const enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;
const physicsConfig = enablePhysics ? {
@@ -91,6 +101,7 @@ export class PreviewManager {
maxDeltaTime: getSettingsValue<number>('runtime.maxDeltaTime') ?? 0.25,
maxFixedSteps: getSettingsValue<number>('runtime.maxFixedSteps') ?? 8,
textCanvasSize: parseInt(getSettingsValue<string>('runtime.textCanvasSize') ?? '512', 10),
+ showStats: this.showStats_,
};
return { enablePhysics, physicsConfig, previewSpineVersion, runtimeConfig };
}
diff --git a/editor/src/index.ts b/editor/src/index.ts
index 061929e93..5aac466f1 100644
--- a/editor/src/index.ts
+++ b/editor/src/index.ts
@@ -439,6 +439,7 @@ export {
CHANNEL_PANEL_OPENED,
CHANNEL_PANEL_CLOSED,
CHANNEL_OUTPUT,
+ CHANNEL_PROFILER_STATS,
type SerializedEditorState,
type ActionType,
type ActionMessage,
@@ -447,4 +448,5 @@ export {
type PanelClosedMessage,
type OutputType,
type OutputMessage,
+ type ProfilerStatsMessage,
} from './multiwindow';
diff --git a/editor/src/menus/builtinMenus.ts b/editor/src/menus/builtinMenus.ts
index cd6e53799..fec225cd7 100644
--- a/editor/src/menus/builtinMenus.ts
+++ b/editor/src/menus/builtinMenus.ts
@@ -152,8 +152,13 @@ export function registerBuiltinMenus(editor: Editor): void {
action: () => editor.showPanel('game'),
});
registerMenuItem({
- id: 'view.addressable', menu: 'view', label: 'Addressable Groups',
+ id: 'view.profiler', menu: 'view', label: 'Profiler',
order: 5, separator: true,
+ action: () => editor.showProfilerWindow(),
+ });
+ registerMenuItem({
+ id: 'view.addressable', menu: 'view', label: 'Addressable Groups',
+ order: 6,
action: () => editor.showAddressableWindow(),
});
registerMenuItem({
diff --git a/editor/src/multiwindow/WindowManager.ts b/editor/src/multiwindow/WindowManager.ts
index 3a8e50e4b..72ee7782c 100644
--- a/editor/src/multiwindow/WindowManager.ts
+++ b/editor/src/multiwindow/WindowManager.ts
@@ -29,13 +29,14 @@ export class WindowManager {
}
const windowLabel = `panel-${panelId}-${Date.now()}`;
+ const isProfiler = panelId === 'profiler';
const webviewWindow = new WebviewWindow(windowLabel, {
url,
title,
- width: 400,
- height: 600,
- minWidth: 300,
- minHeight: 200,
+ width: isProfiler ? 780 : 400,
+ height: isProfiler ? 540 : 600,
+ minWidth: isProfiler ? 500 : 300,
+ minHeight: isProfiler ? 360 : 200,
center: true,
decorations: true,
resizable: true,
diff --git a/editor/src/multiwindow/index.ts b/editor/src/multiwindow/index.ts
index 7f213652c..16df332da 100644
--- a/editor/src/multiwindow/index.ts
+++ b/editor/src/multiwindow/index.ts
@@ -9,6 +9,7 @@ export {
CHANNEL_PANEL_OPENED,
CHANNEL_PANEL_CLOSED,
CHANNEL_OUTPUT,
+ CHANNEL_PROFILER_STATS,
type SerializedEditorState,
type ActionType,
type ActionMessage,
@@ -17,6 +18,7 @@ export {
type PanelClosedMessage,
type OutputType,
type OutputMessage,
+ type ProfilerStatsMessage,
} from './protocol';
export { serializeEditorState } from './stateSerializer';
diff --git a/editor/src/multiwindow/protocol.ts b/editor/src/multiwindow/protocol.ts
index 692550d2b..65b5a0581 100644
--- a/editor/src/multiwindow/protocol.ts
+++ b/editor/src/multiwindow/protocol.ts
@@ -11,6 +11,7 @@ export const CHANNEL_ACTION_RESULT = 'editor:action-result';
export const CHANNEL_PANEL_OPENED = 'editor:panel-opened';
export const CHANNEL_PANEL_CLOSED = 'editor:panel-closed';
export const CHANNEL_OUTPUT = 'editor:output';
+export const CHANNEL_PROFILER_STATS = 'editor:profiler-stats';
// =============================================================================
// State Snapshot
@@ -89,3 +90,13 @@ export interface OutputMessage {
text: string;
type: OutputType;
}
+
+// =============================================================================
+// Profiler Stats Messages
+// =============================================================================
+
+export interface ProfilerStatsMessage {
+ frameTimeMs: number;
+ phaseTimings: [string, number][];
+ systemTimings: [string, number][];
+}
diff --git a/editor/src/panels/PanelRegistry.ts b/editor/src/panels/PanelRegistry.ts
index 998b12a7a..8ba1ba783 100644
--- a/editor/src/panels/PanelRegistry.ts
+++ b/editor/src/panels/PanelRegistry.ts
@@ -11,6 +11,7 @@ export interface PanelDescriptor {
icon?: string;
position: PanelPosition;
defaultVisible?: boolean;
+ detachOnly?: boolean;
order?: number;
factory: PanelFactory;
}
@@ -119,5 +120,5 @@ export function getAllPanels(): PanelDescriptor[] {
}
export function getPanelsByPosition(position: PanelPosition): PanelDescriptor[] {
- return getAllPanels().filter(p => p.position === position);
+ return getAllPanels().filter(p => p.position === position && !p.detachOnly);
}
diff --git a/editor/src/panels/builtinPanels.ts b/editor/src/panels/builtinPanels.ts
index b4bc50ef9..0adc5ed70 100644
--- a/editor/src/panels/builtinPanels.ts
+++ b/editor/src/panels/builtinPanels.ts
@@ -5,7 +5,7 @@ import { SceneViewPanel } from './scene-view/SceneViewPanel';
import { GameViewPanel } from './game-view/GameViewPanel';
import { ContentBrowserPanel } from './content-browser/ContentBrowserPanel';
import { OutputPanel } from './OutputPanel';
-
+import { ProfilerPanel } from './profiler/ProfilerPanel';
import { icons } from '../utils/icons';
export interface BuiltinPanelOptions {
@@ -76,4 +76,14 @@ export function registerBuiltinPanels(options: BuiltinPanelOptions): void {
factory: (c) => new OutputPanel(c),
});
+ registerPanel({
+ id: 'profiler',
+ title: 'Profiler',
+ icon: icons.gauge(14),
+ position: 'bottom',
+ detachOnly: true,
+ order: 99,
+ factory: (c) => new ProfilerPanel(c),
+ });
+
}
diff --git a/editor/src/panels/profiler/FrameTimeline.ts b/editor/src/panels/profiler/FrameTimeline.ts
new file mode 100644
index 000000000..3e9d37523
--- /dev/null
+++ b/editor/src/panels/profiler/FrameTimeline.ts
@@ -0,0 +1,207 @@
+import type { FrameSnapshot } from 'esengine';
+
+const BUDGET_60FPS_MS = 16.67;
+const BAR_WIDTH = 2;
+const BAR_GAP = 1;
+const PADDING_TOP = 20;
+const PADDING_BOTTOM = 16;
+const PADDING_LEFT = 36;
+const PADDING_RIGHT = 8;
+
+const COLOR_NORMAL = '#4ec9b0';
+const COLOR_OVER_BUDGET = '#e06c75';
+const COLOR_BUDGET_LINE = 'rgba(209, 154, 102, 0.7)';
+const COLOR_GRID = 'rgba(60, 60, 60, 0.6)';
+const COLOR_TEXT = '#8c8c8c';
+const COLOR_SELECTED_BORDER = '#61afef';
+const COLOR_HOVER_BORDER = 'rgba(97, 175, 239, 0.5)';
+
+export type FrameSelectCallback = (index: number) => void;
+
+export class FrameTimeline {
+ private canvas_: HTMLCanvasElement;
+ private ctx_: CanvasRenderingContext2D;
+ private tooltip_: HTMLElement;
+ private onFrameSelect_: FrameSelectCallback | null = null;
+ private lastSnapshots_: FrameSnapshot[] = [];
+ private lastVisibleStart_ = 0;
+ private selectedIndex_ = -1;
+ private hoveredIndex_ = -1;
+
+ constructor(container: HTMLElement) {
+ this.canvas_ = document.createElement('canvas');
+ this.canvas_.className = 'es-profiler-timeline-canvas';
+ this.canvas_.style.cssText = 'width:100%;height:100%;display:block;';
+ container.appendChild(this.canvas_);
+ this.ctx_ = this.canvas_.getContext('2d')!;
+
+ this.tooltip_ = document.createElement('div');
+ this.tooltip_.className = 'es-profiler-tooltip';
+ container.appendChild(this.tooltip_);
+
+ this.canvas_.addEventListener('click', this.onClick_);
+ this.canvas_.addEventListener('mousemove', this.onMouseMove_);
+ this.canvas_.addEventListener('mouseleave', this.onMouseLeave_);
+ }
+
+ set onFrameSelect(cb: FrameSelectCallback | null) {
+ this.onFrameSelect_ = cb;
+ }
+
+ set selectedIndex(idx: number) {
+ this.selectedIndex_ = idx;
+ }
+
+ render(snapshots: FrameSnapshot[]): void {
+ this.lastSnapshots_ = snapshots;
+
+ const dpr = window.devicePixelRatio || 1;
+ const rect = this.canvas_.getBoundingClientRect();
+ const w = rect.width;
+ const h = rect.height;
+ this.canvas_.width = w * dpr;
+ this.canvas_.height = h * dpr;
+
+ const ctx = this.ctx_;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+
+ if (snapshots.length === 0) {
+ ctx.fillStyle = COLOR_TEXT;
+ ctx.font = '11px monospace';
+ ctx.textAlign = 'center';
+ ctx.fillText('No frame data', w / 2, h / 2);
+ this.lastVisibleStart_ = 0;
+ return;
+ }
+
+ const plotW = w - PADDING_LEFT - PADDING_RIGHT;
+ const plotH = h - PADDING_TOP - PADDING_BOTTOM;
+ const maxBars = Math.floor(plotW / (BAR_WIDTH + BAR_GAP));
+ const visibleStart = snapshots.length > maxBars ? snapshots.length - maxBars : 0;
+ const visibleSnapshots = snapshots.slice(visibleStart);
+ this.lastVisibleStart_ = visibleStart;
+
+ let maxMs = BUDGET_60FPS_MS * 2;
+ for (const snap of visibleSnapshots) {
+ if (snap.frameTimeMs > maxMs) maxMs = snap.frameTimeMs;
+ }
+ maxMs = Math.ceil(maxMs / 5) * 5;
+
+ this.drawGrid(ctx, plotW, plotH, maxMs, w, h);
+
+ for (let i = 0; i < visibleSnapshots.length; i++) {
+ const absIndex = visibleStart + i;
+ const ms = visibleSnapshots[i].frameTimeMs;
+ const barH = Math.max(1, (ms / maxMs) * plotH);
+ const x = PADDING_LEFT + i * (BAR_WIDTH + BAR_GAP);
+ const y = PADDING_TOP + plotH - barH;
+
+ ctx.fillStyle = ms > BUDGET_60FPS_MS ? COLOR_OVER_BUDGET : COLOR_NORMAL;
+ ctx.fillRect(x, y, BAR_WIDTH, barH);
+
+ if (absIndex === this.selectedIndex_) {
+ ctx.strokeStyle = COLOR_SELECTED_BORDER;
+ ctx.lineWidth = 1.5;
+ ctx.strokeRect(x - 1, y - 1, BAR_WIDTH + 2, barH + 2);
+ } else if (absIndex === this.hoveredIndex_) {
+ ctx.strokeStyle = COLOR_HOVER_BORDER;
+ ctx.lineWidth = 1;
+ ctx.strokeRect(x - 1, y - 1, BAR_WIDTH + 2, barH + 2);
+ }
+ }
+ }
+
+ private drawGrid(
+ ctx: CanvasRenderingContext2D,
+ plotW: number,
+ plotH: number,
+ maxMs: number,
+ w: number,
+ _h: number,
+ ): void {
+ ctx.font = '10px monospace';
+ ctx.textAlign = 'right';
+ ctx.textBaseline = 'middle';
+
+ const gridLines = [0, BUDGET_60FPS_MS, maxMs / 2, maxMs];
+ for (const ms of gridLines) {
+ const y = PADDING_TOP + plotH - (ms / maxMs) * plotH;
+ ctx.strokeStyle = ms === BUDGET_60FPS_MS ? COLOR_BUDGET_LINE : COLOR_GRID;
+ ctx.lineWidth = ms === BUDGET_60FPS_MS ? 1.5 : 0.5;
+ ctx.setLineDash(ms === BUDGET_60FPS_MS ? [4, 2] : []);
+ ctx.beginPath();
+ ctx.moveTo(PADDING_LEFT, y);
+ ctx.lineTo(PADDING_LEFT + plotW, y);
+ ctx.stroke();
+
+ ctx.fillStyle = ms === BUDGET_60FPS_MS ? COLOR_BUDGET_LINE : COLOR_TEXT;
+ ctx.fillText(`${ms.toFixed(0)}ms`, PADDING_LEFT - 4, y);
+ }
+ ctx.setLineDash([]);
+
+ ctx.fillStyle = COLOR_TEXT;
+ ctx.font = '10px monospace';
+ ctx.textAlign = 'center';
+ ctx.fillText('Frame Timeline', w / 2, 12);
+ }
+
+ private hitTest_(clientX: number, clientY: number): number {
+ const rect = this.canvas_.getBoundingClientRect();
+ const x = clientX - rect.left;
+ const _y = clientY - rect.top;
+
+ const barStep = BAR_WIDTH + BAR_GAP;
+ const localX = x - PADDING_LEFT;
+ if (localX < 0) return -1;
+
+ const barIndex = Math.floor(localX / barStep);
+ const absIndex = this.lastVisibleStart_ + barIndex;
+ if (absIndex >= this.lastSnapshots_.length) return -1;
+
+ return absIndex;
+ }
+
+ private onClick_ = (e: MouseEvent): void => {
+ const idx = this.hitTest_(e.clientX, e.clientY);
+ if (idx >= 0 && this.onFrameSelect_) {
+ this.onFrameSelect_(idx);
+ }
+ };
+
+ private onMouseMove_ = (e: MouseEvent): void => {
+ const idx = this.hitTest_(e.clientX, e.clientY);
+ if (idx === this.hoveredIndex_) return;
+ this.hoveredIndex_ = idx;
+
+ if (idx >= 0) {
+ const snap = this.lastSnapshots_[idx];
+ this.tooltip_.textContent = `Frame #${idx} ${snap.frameTimeMs.toFixed(2)}ms`;
+ this.tooltip_.style.display = 'block';
+
+ const rect = this.canvas_.getBoundingClientRect();
+ const localX = e.clientX - rect.left;
+ const localY = e.clientY - rect.top;
+ this.tooltip_.style.left = `${localX + 12}px`;
+ this.tooltip_.style.top = `${localY - 8}px`;
+ } else {
+ this.tooltip_.style.display = 'none';
+ }
+
+ this.render(this.lastSnapshots_);
+ };
+
+ private onMouseLeave_ = (): void => {
+ this.hoveredIndex_ = -1;
+ this.tooltip_.style.display = 'none';
+ this.render(this.lastSnapshots_);
+ };
+
+ dispose(): void {
+ this.canvas_.removeEventListener('click', this.onClick_);
+ this.canvas_.removeEventListener('mousemove', this.onMouseMove_);
+ this.canvas_.removeEventListener('mouseleave', this.onMouseLeave_);
+ this.canvas_.remove();
+ this.tooltip_.remove();
+ }
+}
diff --git a/editor/src/panels/profiler/PhaseWaterfall.ts b/editor/src/panels/profiler/PhaseWaterfall.ts
new file mode 100644
index 000000000..eaeafaf82
--- /dev/null
+++ b/editor/src/panels/profiler/PhaseWaterfall.ts
@@ -0,0 +1,107 @@
+const PADDING_TOP = 20;
+const PADDING_BOTTOM = 8;
+const PADDING_LEFT = 8;
+const PADDING_RIGHT = 8;
+const BAR_HEIGHT = 18;
+const BAR_GAP = 3;
+
+const PHASE_COLORS: Record<string, string> = {
+ First: '#61afef',
+ FixedPreUpdate: '#56b6c2',
+ FixedUpdate: '#56b6c2',
+ FixedPostUpdate: '#56b6c2',
+ PreUpdate: '#c678dd',
+ Update: '#98c379',
+ PostUpdate: '#d19a66',
+ Last: '#e5c07b',
+};
+
+const PHASE_ORDER = [
+ 'First',
+ 'FixedPreUpdate', 'FixedUpdate', 'FixedPostUpdate',
+ 'PreUpdate', 'Update', 'PostUpdate',
+ 'Last',
+];
+
+const COLOR_TEXT = '#cccccc';
+const COLOR_TEXT_DIM = '#8c8c8c';
+const COLOR_DEFAULT_BAR = '#abb2bf';
+
+export class PhaseWaterfall {
+ private canvas_: HTMLCanvasElement;
+ private ctx_: CanvasRenderingContext2D;
+
+ constructor(container: HTMLElement) {
+ this.canvas_ = document.createElement('canvas');
+ this.canvas_.className = 'es-profiler-waterfall-canvas';
+ this.canvas_.style.cssText = 'width:100%;height:100%;display:block;';
+ container.appendChild(this.canvas_);
+ this.ctx_ = this.canvas_.getContext('2d')!;
+ }
+
+ render(phaseTimings: Map<string, number>): void {
+ const dpr = window.devicePixelRatio || 1;
+ const rect = this.canvas_.getBoundingClientRect();
+ const w = rect.width;
+ const h = rect.height;
+ this.canvas_.width = w * dpr;
+ this.canvas_.height = h * dpr;
+
+ const ctx = this.ctx_;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+
+ ctx.fillStyle = COLOR_TEXT_DIM;
+ ctx.font = '10px monospace';
+ ctx.textAlign = 'center';
+ ctx.fillText('Phase Breakdown', w / 2, 12);
+
+ if (phaseTimings.size === 0) {
+ ctx.fillStyle = COLOR_TEXT_DIM;
+ ctx.textAlign = 'center';
+ ctx.fillText('No phase data', w / 2, h / 2);
+ return;
+ }
+
+ const phases = PHASE_ORDER.filter(p => phaseTimings.has(p));
+ let maxMs = 0;
+ for (const p of phases) {
+ const v = phaseTimings.get(p)!;
+ if (v > maxMs) maxMs = v;
+ }
+ if (maxMs <= 0) maxMs = 1;
+
+ const labelWidth = 100;
+ const barAreaLeft = PADDING_LEFT + labelWidth;
+ const barAreaWidth = w - barAreaLeft - PADDING_RIGHT - 50;
+
+ for (let i = 0; i < phases.length; i++) {
+ const name = phases[i];
+ const ms = phaseTimings.get(name)!;
+ const y = PADDING_TOP + i * (BAR_HEIGHT + BAR_GAP);
+ const barW = Math.max(1, (ms / maxMs) * barAreaWidth);
+
+ ctx.fillStyle = COLOR_TEXT;
+ ctx.font = '11px monospace';
+ ctx.textAlign = 'right';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(name, PADDING_LEFT + labelWidth - 8, y + BAR_HEIGHT / 2);
+
+ ctx.fillStyle = PHASE_COLORS[name] ?? COLOR_DEFAULT_BAR;
+ ctx.fillRect(barAreaLeft, y, barW, BAR_HEIGHT);
+
+ ctx.fillStyle = COLOR_TEXT;
+ ctx.font = '10px monospace';
+ ctx.textAlign = 'left';
+ ctx.fillText(
+ ms < 0.01 ? '<0.01ms' : `${ms.toFixed(2)}ms`,
+ barAreaLeft + barW + 6,
+ y + BAR_HEIGHT / 2,
+ );
+ }
+ }
+
+ dispose(): void {
+ this.canvas_.remove();
+ }
+}
diff --git a/editor/src/panels/profiler/ProfilerPanel.ts b/editor/src/panels/profiler/ProfilerPanel.ts
new file mode 100644
index 000000000..adbef1b15
--- /dev/null
+++ b/editor/src/panels/profiler/ProfilerPanel.ts
@@ -0,0 +1,235 @@
+import { FrameHistory, type FrameSnapshot } from 'esengine';
+import { listen, type UnlistenFn } from '@tauri-apps/api/event';
+import { CHANNEL_PROFILER_STATS, type ProfilerStatsMessage } from '../../multiwindow/protocol';
+import { getEditorInstance } from '../../context/EditorContext';
+import type { PanelInstance } from '../PanelRegistry';
+import { FrameTimeline } from './FrameTimeline';
+import { PhaseWaterfall } from './PhaseWaterfall';
+import { SystemTable } from './SystemTable';
+
+const enum Mode {
+ Live,
+ Paused,
+}
+
+export class ProfilerPanel implements PanelInstance {
+ private container_: HTMLElement;
+ private frameHistory_ = new FrameHistory();
+ private timeline_: FrameTimeline | null = null;
+ private waterfall_: PhaseWaterfall | null = null;
+ private systemTable_: SystemTable | null = null;
+ private disposed_ = false;
+ private unlisten_: UnlistenFn | null = null;
+
+ private mode_ = Mode.Live;
+ private selectedIndex_ = -1;
+ private rafId_ = 0;
+ private dirty_ = false;
+ private frozenSnapshots_: FrameSnapshot[] = [];
+
+ private btnPause_!: HTMLButtonElement;
+ private btnClear_!: HTMLButtonElement;
+ private btnPrev_!: HTMLButtonElement;
+ private btnNext_!: HTMLButtonElement;
+ private fpsDisplay_!: HTMLElement;
+ private frameDisplay_!: HTMLElement;
+
+ constructor(container: HTMLElement) {
+ this.container_ = container;
+ this.buildUI();
+ this.startListening();
+ getEditorInstance()?.startProfilerStats();
+ }
+
+ dispose(): void {
+ this.disposed_ = true;
+ this.unlisten_?.();
+ this.unlisten_ = null;
+ if (this.rafId_) cancelAnimationFrame(this.rafId_);
+ this.timeline_?.dispose();
+ this.waterfall_?.dispose();
+ this.systemTable_?.dispose();
+ this.container_.innerHTML = '';
+ getEditorInstance()?.stopProfilerStats();
+ }
+
+ private buildUI(): void {
+ this.container_.innerHTML = `
+ <div class="es-profiler-panel">
+ <div class="es-profiler-toolbar">
+ <button class="es-profiler-btn es-profiler-btn-pause" title="Pause/Resume">▮▮</button>
+ <button class="es-profiler-btn es-profiler-btn-clear" title="Clear">Clear</button>
+ <span class="es-profiler-fps-display">-- FPS / --ms</span>
+ <span class="es-profiler-toolbar-sep"></span>
+ <button class="es-profiler-btn es-profiler-btn-prev" title="Previous frame" disabled>◀</button>
+ <span class="es-profiler-frame-display">--</span>
+ <button class="es-profiler-btn es-profiler-btn-next" title="Next frame" disabled>▶</button>
+ </div>
+ <div class="es-profiler-top">
+ <div class="es-profiler-timeline-wrap"></div>
+ <div class="es-profiler-waterfall-wrap"></div>
+ </div>
+ <div class="es-profiler-bottom">
+ <div class="es-profiler-table-wrap"></div>
+ </div>
+ </div>
+ `;
+
+ this.btnPause_ = this.container_.querySelector('.es-profiler-btn-pause') as HTMLButtonElement;
+ this.btnClear_ = this.container_.querySelector('.es-profiler-btn-clear') as HTMLButtonElement;
+ this.btnPrev_ = this.container_.querySelector('.es-profiler-btn-prev') as HTMLButtonElement;
+ this.btnNext_ = this.container_.querySelector('.es-profiler-btn-next') as HTMLButtonElement;
+ this.fpsDisplay_ = this.container_.querySelector('.es-profiler-fps-display') as HTMLElement;
+ this.frameDisplay_ = this.container_.querySelector('.es-profiler-frame-display') as HTMLElement;
+
+ this.btnPause_.addEventListener('click', this.onTogglePause_);
+ this.btnClear_.addEventListener('click', this.onClear_);
+ this.btnPrev_.addEventListener('click', this.onPrev_);
+ this.btnNext_.addEventListener('click', this.onNext_);
+
+ const timelineWrap = this.container_.querySelector('.es-profiler-timeline-wrap') as HTMLElement;
+ const waterfallWrap = this.container_.querySelector('.es-profiler-waterfall-wrap') as HTMLElement;
+ const tableWrap = this.container_.querySelector('.es-profiler-table-wrap') as HTMLElement;
+
+ this.timeline_ = new FrameTimeline(timelineWrap);
+ this.timeline_.onFrameSelect = this.onFrameSelect_;
+ this.waterfall_ = new PhaseWaterfall(waterfallWrap);
+ this.systemTable_ = new SystemTable(tableWrap);
+ }
+
+ private async startListening(): Promise<void> {
+ this.unlisten_ = await listen<ProfilerStatsMessage>(CHANNEL_PROFILER_STATS, (event) => {
+ if (this.disposed_) return;
+ this.onStatsReceived(event.payload);
+ });
+ }
+
+ private onStatsReceived(msg: ProfilerStatsMessage): void {
+ if (this.mode_ === Mode.Paused) return;
+
+ const phaseTimings = new Map(msg.phaseTimings);
+ const systemTimings = new Map(msg.systemTimings);
+
+ this.frameHistory_.push(msg.frameTimeMs, phaseTimings, systemTimings);
+ this.scheduleRender();
+ }
+
+ private scheduleRender(): void {
+ if (this.dirty_) return;
+ this.dirty_ = true;
+ this.rafId_ = requestAnimationFrame(() => {
+ this.dirty_ = false;
+ this.renderOnce();
+ });
+ }
+
+ private renderOnce(): void {
+ if (!this.timeline_ || !this.waterfall_ || !this.systemTable_) return;
+
+ if (this.mode_ === Mode.Live) {
+ const all = this.frameHistory_.getAll();
+ this.timeline_.selectedIndex = -1;
+ this.timeline_.render(all);
+
+ const latest = this.frameHistory_.getLatest();
+ if (latest) {
+ this.waterfall_.render(latest.phaseTimings);
+ if (latest.systemTimings.size > 0) {
+ this.systemTable_.update(latest.systemTimings);
+ }
+ }
+ this.updateFpsDisplay(all);
+ this.frameDisplay_.textContent = all.length > 0 ? `Frame #${all.length - 1}` : '--';
+ } else {
+ this.timeline_.selectedIndex = this.selectedIndex_;
+ this.timeline_.render(this.frozenSnapshots_);
+
+ if (this.selectedIndex_ >= 0 && this.selectedIndex_ < this.frozenSnapshots_.length) {
+ const snap = this.frozenSnapshots_[this.selectedIndex_];
+ this.waterfall_.render(snap.phaseTimings);
+ if (snap.systemTimings.size > 0) {
+ this.systemTable_.update(snap.systemTimings);
+ }
+ this.frameDisplay_.textContent = `Frame #${this.selectedIndex_}`;
+ }
+ }
+
+ this.updateNavButtons();
+ }
+
+ private updateFpsDisplay(snapshots: FrameSnapshot[]): void {
+ if (snapshots.length === 0) {
+ this.fpsDisplay_.textContent = '-- FPS / --ms';
+ return;
+ }
+ const latest = snapshots[snapshots.length - 1];
+ const fps = latest.frameTimeMs > 0 ? (1000 / latest.frameTimeMs) : 0;
+ this.fpsDisplay_.textContent = `${fps.toFixed(0)} FPS / ${latest.frameTimeMs.toFixed(1)}ms`;
+ }
+
+ private updateNavButtons(): void {
+ const isPaused = this.mode_ === Mode.Paused;
+ this.btnPrev_.disabled = !isPaused || this.selectedIndex_ <= 0;
+ this.btnNext_.disabled = !isPaused || this.selectedIndex_ >= this.frozenSnapshots_.length - 1;
+ }
+
+ private enterPaused(selectIndex: number): void {
+ this.frozenSnapshots_ = this.frameHistory_.getAll();
+ this.selectedIndex_ = Math.min(selectIndex, this.frozenSnapshots_.length - 1);
+ this.mode_ = Mode.Paused;
+ this.btnPause_.textContent = '▶';
+ this.btnPause_.classList.add('es-profiler-btn-active');
+ this.scheduleRender();
+ }
+
+ private enterLive(): void {
+ this.mode_ = Mode.Live;
+ this.selectedIndex_ = -1;
+ this.frozenSnapshots_ = [];
+ this.btnPause_.textContent = '▮▮';
+ this.btnPause_.classList.remove('es-profiler-btn-active');
+ this.scheduleRender();
+ }
+
+ private onTogglePause_ = (): void => {
+ if (this.mode_ === Mode.Live) {
+ this.enterPaused(this.frameHistory_.count - 1);
+ } else {
+ this.enterLive();
+ }
+ };
+
+ private onClear_ = (): void => {
+ this.frameHistory_.reset();
+ this.systemTable_?.reset();
+ this.frozenSnapshots_ = [];
+ this.selectedIndex_ = -1;
+ this.mode_ = Mode.Live;
+ this.btnPause_.textContent = '▮▮';
+ this.btnPause_.classList.remove('es-profiler-btn-active');
+ this.fpsDisplay_.textContent = '-- FPS / --ms';
+ this.frameDisplay_.textContent = '--';
+ this.scheduleRender();
+ };
+
+ private onPrev_ = (): void => {
+ if (this.mode_ !== Mode.Paused || this.selectedIndex_ <= 0) return;
+ this.selectedIndex_--;
+ this.scheduleRender();
+ };
+
+ private onNext_ = (): void => {
+ if (this.mode_ !== Mode.Paused || this.selectedIndex_ >= this.frozenSnapshots_.length - 1) return;
+ this.selectedIndex_++;
+ this.scheduleRender();
+ };
+
+ private onFrameSelect_ = (index: number): void => {
+ if (this.mode_ === Mode.Live) {
+ this.enterPaused(index);
+ } else {
+ this.selectedIndex_ = Math.min(index, this.frozenSnapshots_.length - 1);
+ this.scheduleRender();
+ }
+ };
+}
diff --git a/editor/src/panels/profiler/SystemTable.ts b/editor/src/panels/profiler/SystemTable.ts
new file mode 100644
index 000000000..3f8c7f110
--- /dev/null
+++ b/editor/src/panels/profiler/SystemTable.ts
@@ -0,0 +1,90 @@
+import { escapeHtml } from '../../utils/html';
+
+const MAX_HISTORY = 60;
+
+const COLOR_BAR = '#4ec9b0';
+const COLOR_BAR_HOT = '#e06c75';
+const HOT_THRESHOLD_MS = 2.0;
+
+interface SystemRecord {
+ history: number[];
+}
+
+export class SystemTable {
+ private container_: HTMLElement;
+ private el_: HTMLElement;
+ private records_ = new Map<string, SystemRecord>();
+
+ constructor(container: HTMLElement) {
+ this.container_ = container;
+ this.el_ = document.createElement('div');
+ this.el_.className = 'es-profiler-system-table';
+ this.container_.appendChild(this.el_);
+ }
+
+ update(systemTimings: Map<string, number>): void {
+ for (const [name, ms] of systemTimings) {
+ let rec = this.records_.get(name);
+ if (!rec) {
+ rec = { history: [] };
+ this.records_.set(name, rec);
+ }
+ rec.history.push(ms);
+ if (rec.history.length > MAX_HISTORY) {
+ rec.history.shift();
+ }
+ }
+
+ const sorted = [...systemTimings.entries()].sort((a, b) => b[1] - a[1]);
+
+ let maxMs = 0;
+ for (const [, ms] of sorted) {
+ if (ms > maxMs) maxMs = ms;
+ }
+ if (maxMs <= 0) maxMs = 1;
+
+ let html = `<div class="es-profiler-table-header">
+ <span class="es-profiler-col-name">System</span>
+ <span class="es-profiler-col-time">Time</span>
+ <span class="es-profiler-col-bar">%</span>
+ <span class="es-profiler-col-avg">Avg</span>
+ <span class="es-profiler-col-max">Max</span>
+ </div>`;
+
+ for (const [name, ms] of sorted) {
+ const rec = this.records_.get(name)!;
+ const avg = rec.history.reduce((s, v) => s + v, 0) / rec.history.length;
+ const max = Math.max(...rec.history);
+ const pct = (ms / maxMs) * 100;
+ const isHot = ms >= HOT_THRESHOLD_MS;
+ const barColor = isHot ? COLOR_BAR_HOT : COLOR_BAR;
+ const displayName = escapeHtml(name.length > 28 ? name.slice(0, 28) + '...' : name);
+ const timeStr = ms < 0.01 ? '<0.01' : ms.toFixed(2);
+ const avgStr = avg < 0.01 ? '<0.01' : avg.toFixed(2);
+ const maxStr = max < 0.01 ? '<0.01' : max.toFixed(2);
+
+ html += `<div class="es-profiler-table-row${isHot ? ' es-profiler-hot' : ''}">
+ <span class="es-profiler-col-name" title="${escapeHtml(name)}">${displayName}</span>
+ <span class="es-profiler-col-time">${timeStr}ms</span>
+ <span class="es-profiler-col-bar">
+ <span class="es-profiler-bar-bg">
+ <span class="es-profiler-bar-fill" style="width:${pct.toFixed(1)}%;background:${barColor}"></span>
+ </span>
+ </span>
+ <span class="es-profiler-col-avg">${avgStr}</span>
+ <span class="es-profiler-col-max">${maxStr}</span>
+ </div>`;
+ }
+
+ this.el_.innerHTML = html;
+ }
+
+ reset(): void {
+ this.records_.clear();
+ this.el_.innerHTML = '';
+ }
+
+ dispose(): void {
+ this.el_.remove();
+ }
+}
diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.ts
index 0ee2a83d0..da2684e6e 100644
--- a/editor/src/renderer/SharedRenderContext.ts
+++ b/editor/src/renderer/SharedRenderContext.ts
@@ -62,6 +62,7 @@ export class SharedRenderContext {
private gameViewportH_ = 0;
private renderCallback_: (() => void) | null = null;
private onInitCallbacks_: (() => void)[] = [];
+ private postTickCallback_: (() => void) | null = null;
constructor() {
this.pathResolver_ = new AssetPathResolver();
@@ -151,6 +152,7 @@ export class SharedRenderContext {
}, { name: 'EditorInputClearSystem' }));
setEditorMode(true);
+ app.enableStats();
app.addPlugin(assetPlugin);
app.addPlugin(prefabsPlugin);
app.addPlugin(animationPlugin);
@@ -279,6 +281,10 @@ export class SharedRenderContext {
}
}
+ setPostTickCallback(cb: (() => void) | null): void {
+ this.postTickCallback_ = cb;
+ }
+
tickApp(): void {
if (!this.app_) return;
if (this.playMode_ && !this.paused_) {
@@ -290,6 +296,7 @@ export class SharedRenderContext {
} else {
this.app_.tick(1 / 60);
}
+ this.postTickCallback_?.();
}
enterPlayMode(): void {
diff --git a/editor/src/styles/index.css b/editor/src/styles/index.css
index 86ee3d91b..4a7b1e6e8 100644
--- a/editor/src/styles/index.css
+++ b/editor/src/styles/index.css
@@ -9,3 +9,4 @@
@import './dialogs.css';
@import './output.css';
@import './builder.css';
+@import './profiler.css';
diff --git a/editor/src/styles/menus.css b/editor/src/styles/menus.css
index 7a4d339a1..be98bef41 100644
--- a/editor/src/styles/menus.css
+++ b/editor/src/styles/menus.css
@@ -160,6 +160,21 @@
background: #c9302c;
}
+.es-preview-stats-toggle {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 11px;
+ color: var(--es-text-secondary);
+ cursor: pointer;
+ user-select: none;
+ margin-right: 4px;
+}
+
+.es-preview-stats-toggle input {
+ margin: 0;
+}
+
.es-preview-url {
font-size: 11px;
color: var(--es-accent);
diff --git a/editor/src/styles/profiler.css b/editor/src/styles/profiler.css
new file mode 100644
index 000000000..f9e655a35
--- /dev/null
+++ b/editor/src/styles/profiler.css
@@ -0,0 +1,205 @@
+.es-profiler-window {
+ width: 720px;
+ height: 520px;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ resize: both;
+ min-width: 500px;
+ min-height: 360px;
+}
+
+.es-profiler-window .es-floating-body {
+ overflow: hidden;
+}
+
+.es-profiler-panel {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+ font: 11px monospace;
+ color: #cccccc;
+ position: relative;
+}
+
+/* Toolbar */
+.es-profiler-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ background: var(--es-bg-secondary, rgba(30, 30, 30, 0.5));
+ border-bottom: 1px solid var(--es-border);
+ flex-shrink: 0;
+}
+
+.es-profiler-btn {
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: #cccccc;
+ font: 10px monospace;
+ padding: 2px 8px;
+ border-radius: 3px;
+ cursor: pointer;
+ line-height: 1.4;
+}
+
+.es-profiler-btn:hover {
+ background: rgba(255, 255, 255, 0.12);
+}
+
+.es-profiler-btn:disabled {
+ opacity: 0.35;
+ cursor: default;
+}
+
+.es-profiler-btn-active {
+ background: rgba(97, 175, 239, 0.2);
+ border-color: rgba(97, 175, 239, 0.4);
+ color: #61afef;
+}
+
+.es-profiler-fps-display {
+ color: #4ec9b0;
+ font-size: 11px;
+ margin-left: 4px;
+}
+
+.es-profiler-toolbar-sep {
+ flex: 1;
+}
+
+.es-profiler-frame-display {
+ color: #8c8c8c;
+ font-size: 10px;
+ min-width: 70px;
+ text-align: center;
+}
+
+/* Tooltip */
+.es-profiler-tooltip {
+ display: none;
+ position: absolute;
+ background: rgba(30, 30, 30, 0.95);
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ color: #cccccc;
+ font: 10px monospace;
+ padding: 3px 8px;
+ border-radius: 3px;
+ pointer-events: none;
+ white-space: nowrap;
+ z-index: 10;
+}
+
+.es-profiler-timeline-wrap {
+ position: relative;
+}
+
+.es-profiler-top {
+ display: flex;
+ flex: 0 0 auto;
+ height: 180px;
+ min-height: 120px;
+ border-bottom: 1px solid var(--es-border);
+}
+
+.es-profiler-timeline-wrap {
+ flex: 1 1 60%;
+ min-width: 0;
+ overflow: hidden;
+}
+
+.es-profiler-waterfall-wrap {
+ flex: 0 0 280px;
+ min-width: 200px;
+ border-left: 1px solid var(--es-border);
+ overflow: hidden;
+}
+
+.es-profiler-bottom {
+ flex: 1 1 auto;
+ overflow: auto;
+ min-height: 0;
+}
+
+.es-profiler-table-wrap {
+ padding: 0;
+}
+
+/* System Table */
+.es-profiler-system-table {
+ width: 100%;
+}
+
+.es-profiler-table-header {
+ display: flex;
+ align-items: center;
+ padding: 4px 8px;
+ font-size: 10px;
+ color: #8c8c8c;
+ border-bottom: 1px solid var(--es-border);
+ background: var(--es-bg-secondary, rgba(30, 30, 30, 0.5));
+ position: sticky;
+ top: 0;
+ z-index: 1;
+}
+
+.es-profiler-table-row {
+ display: flex;
+ align-items: center;
+ padding: 2px 8px;
+ border-bottom: 1px solid rgba(60, 60, 60, 0.3);
+}
+
+.es-profiler-table-row:hover {
+ background: rgba(255, 255, 255, 0.03);
+}
+
+.es-profiler-table-row.es-profiler-hot .es-profiler-col-time {
+ color: #e06c75;
+}
+
+.es-profiler-col-name {
+ flex: 0 0 200px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-profiler-col-time {
+ flex: 0 0 70px;
+ text-align: right;
+ color: #d19a66;
+ padding-right: 8px;
+}
+
+.es-profiler-col-bar {
+ flex: 1 1 auto;
+ min-width: 60px;
+ padding: 0 8px;
+}
+
+.es-profiler-col-avg,
+.es-profiler-col-max {
+ flex: 0 0 55px;
+ text-align: right;
+ color: #8c8c8c;
+ font-size: 10px;
+}
+
+.es-profiler-bar-bg {
+ display: block;
+ height: 10px;
+ background: rgba(60, 60, 60, 0.5);
+ border-radius: 2px;
+ overflow: hidden;
+}
+
+.es-profiler-bar-fill {
+ display: block;
+ height: 100%;
+ border-radius: 2px;
+ transition: width 0.1s ease-out;
+}
+
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index f96c97323..1b58a1573 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -85,6 +85,7 @@ export class App {
private error_handler_: ((error: unknown, systemName: string) => void) | null = null;
private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;
private statsEnabled_ = false;
+ private phaseTimings_: Map<string, number> | null = null;
private frame_paused_ = false;
private user_paused_ = false;
private step_pending_ = false;
@@ -303,6 +304,7 @@ export class App {
enableStats(): this {
this.statsEnabled_ = true;
+ this.phaseTimings_ = new Map();
this.runner_?.setTimingEnabled(true);
return this;
}
@@ -311,6 +313,10 @@ export class App {
return this.runner_?.getTimings() ?? null;
}
+ getPhaseTimings(): ReadonlyMap<string, number> | null {
+ return this.phaseTimings_;
+ }
+
getEntityCount(): number {
return this.world_.entityCount();
}
@@ -602,6 +608,8 @@ export class App {
this.sortedSystemsCache_.set(schedule, systems);
}
+ const t0 = this.phaseTimings_ ? performance.now() : 0;
+
for (const entry of systems) {
try {
this.runner_.run(entry.system);
@@ -621,6 +629,10 @@ export class App {
}
}
}
+
+ if (this.phaseTimings_) {
+ this.phaseTimings_.set(Schedule[schedule], performance.now() - t0);
+ }
}
private updateTime(delta: number): void {
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 2c512dd52..b150419a8 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -692,8 +692,10 @@ export {
StatsPlugin,
statsPlugin,
StatsCollector,
+ FrameHistory,
defaultFrameStats,
type FrameStats,
+ type FrameSnapshot,
type StatsPluginOptions,
} from './stats';
diff --git a/sdk/src/stats.ts b/sdk/src/stats.ts
index 2f52a2e68..d16245eb2 100644
--- a/sdk/src/stats.ts
+++ b/sdk/src/stats.ts
@@ -9,6 +9,7 @@ export interface FrameStats {
frameTimeMs: number;
entityCount: number;
systemTimings: Map<string, number>;
+ phaseTimings: Map<string, number>;
drawCalls: number;
triangles: number;
sprites: number;
@@ -24,6 +25,7 @@ export function defaultFrameStats(): FrameStats {
frameTimeMs: 0,
entityCount: 0,
systemTimings: new Map(),
+ phaseTimings: new Map(),
drawCalls: 0,
triangles: 0,
sprites: 0,
@@ -36,6 +38,72 @@ export function defaultFrameStats(): FrameStats {
export const Stats = defineResource<FrameStats>(defaultFrameStats(), 'Stats');
+// =============================================================================
+// Frame History
+// =============================================================================
+
+const DEFAULT_HISTORY_CAPACITY = 300;
+
+export interface FrameSnapshot {
+ frameTimeMs: number;
+ phaseTimings: Map<string, number>;
+ systemTimings: Map<string, number>;
+}
+
+export class FrameHistory {
+ private readonly capacity_: number;
+ private buffer_: FrameSnapshot[] = [];
+ private cursor_ = 0;
+ private count_ = 0;
+
+ constructor(capacity = DEFAULT_HISTORY_CAPACITY) {
+ this.capacity_ = capacity;
+ }
+
+ get count(): number {
+ return this.count_;
+ }
+
+ push(frameTimeMs: number, phaseTimings: Map<string, number>, systemTimings?: Map<string, number>): void {
+ const snapshot: FrameSnapshot = {
+ frameTimeMs,
+ phaseTimings: new Map(phaseTimings),
+ systemTimings: systemTimings ? new Map(systemTimings) : new Map(),
+ };
+
+ if (this.count_ < this.capacity_) {
+ this.buffer_.push(snapshot);
+ this.count_++;
+ } else {
+ this.buffer_[this.cursor_] = snapshot;
+ }
+ this.cursor_ = (this.cursor_ + 1) % this.capacity_;
+ }
+
+ getLatest(): FrameSnapshot | null {
+ if (this.count_ === 0) return null;
+ const idx = (this.cursor_ - 1 + this.capacity_) % this.capacity_;
+ return this.buffer_[idx];
+ }
+
+ getAll(): FrameSnapshot[] {
+ if (this.count_ === 0) return [];
+ if (this.count_ < this.capacity_) {
+ return this.buffer_.slice();
+ }
+ return [
+ ...this.buffer_.slice(this.cursor_),
+ ...this.buffer_.slice(0, this.cursor_),
+ ];
+ }
+
+ reset(): void {
+ this.buffer_.length = 0;
+ this.cursor_ = 0;
+ this.count_ = 0;
+ }
+}
+
const SLIDING_WINDOW_SIZE = 60;
const STATS_COLLECT_SYSTEM_NAME = 'StatsCollect';
@@ -128,6 +196,9 @@ export class StatsPlugin implements Plugin {
stats.systemTimings = new Map();
}
+ const pt = app.getPhaseTimings();
+ stats.phaseTimings = pt ? new Map(pt) : new Map();
+
const renderStats = Renderer.getStats();
stats.drawCalls = renderStats.drawCalls;
stats.triangles = renderStats.triangles;
diff --git a/sdk/tests/stats.test.ts b/sdk/tests/stats.test.ts
index 006b47408..c0d05ff85 100644
--- a/sdk/tests/stats.test.ts
+++ b/sdk/tests/stats.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
-import { StatsCollector, defaultFrameStats, Stats, StatsPlugin, statsPlugin, type FrameStats } from '../src/stats';
+import { StatsCollector, defaultFrameStats, Stats, StatsPlugin, statsPlugin, FrameHistory, type FrameStats } from '../src/stats';
import { StatsOverlay } from '../src/stats-overlay';
import { App } from '../src/app';
import { Schedule, defineSystem, SystemRunner } from '../src/system';
@@ -648,6 +648,7 @@ describe('StatsOverlay', () => {
return {
fps: 0, frameTimeMs: 0, entityCount: 0,
systemTimings: new Map(),
+ phaseTimings: new Map(),
drawCalls: 0, triangles: 0, sprites: 0,
text: 0, spine: 0, meshes: 0, culled: 0,
...overrides,
@@ -847,3 +848,180 @@ describe('StatsOverlay', () => {
expect(() => overlay.update(makeStats({ fps: 60 }))).not.toThrow();
});
});
+
+// ============================================================================
+// FrameHistory
+// ============================================================================
+
+describe('FrameHistory', () => {
+ it('should start empty', () => {
+ const history = new FrameHistory();
+ expect(history.count).toBe(0);
+ expect(history.getAll()).toEqual([]);
+ });
+
+ it('should store pushed snapshots', () => {
+ const history = new FrameHistory();
+ history.push(16.7, new Map([['Update', 5.0]]));
+ expect(history.count).toBe(1);
+ const all = history.getAll();
+ expect(all[0].frameTimeMs).toBeCloseTo(16.7);
+ expect(all[0].phaseTimings.get('Update')).toBe(5.0);
+ expect(all[0].systemTimings).toBeInstanceOf(Map);
+ expect(all[0].systemTimings.size).toBe(0);
+ });
+
+ it('should store systemTimings when provided', () => {
+ const history = new FrameHistory();
+ const sysTimes = new Map([['PhysicsSystem', 1.5], ['RenderSystem', 3.2]]);
+ history.push(16.7, new Map(), sysTimes);
+ const snap = history.getLatest()!;
+ expect(snap.systemTimings.get('PhysicsSystem')).toBe(1.5);
+ expect(snap.systemTimings.get('RenderSystem')).toBe(3.2);
+ });
+
+ it('should deep copy systemTimings on push', () => {
+ const history = new FrameHistory();
+ const sysTimes = new Map([['Sys', 2.0]]);
+ history.push(16.0, new Map(), sysTimes);
+ sysTimes.set('Sys', 99.0);
+ expect(history.getLatest()!.systemTimings.get('Sys')).toBe(2.0);
+ });
+
+ it('should preserve insertion order', () => {
+ const history = new FrameHistory();
+ history.push(10.0, new Map());
+ history.push(20.0, new Map());
+ history.push(30.0, new Map());
+ const all = history.getAll();
+ expect(all.map(s => s.frameTimeMs)).toEqual([10.0, 20.0, 30.0]);
+ });
+
+ it('should evict oldest when exceeding capacity', () => {
+ const capacity = 300;
+ const history = new FrameHistory(capacity);
+ for (let i = 0; i < capacity + 10; i++) {
+ history.push(i, new Map());
+ }
+ expect(history.count).toBe(capacity);
+ const all = history.getAll();
+ expect(all[0].frameTimeMs).toBe(10);
+ expect(all[all.length - 1].frameTimeMs).toBe(capacity + 9);
+ });
+
+ it('should return latest snapshot', () => {
+ const history = new FrameHistory();
+ history.push(10.0, new Map());
+ history.push(20.0, new Map());
+ expect(history.getLatest()!.frameTimeMs).toBe(20.0);
+ });
+
+ it('should return null for latest when empty', () => {
+ const history = new FrameHistory();
+ expect(history.getLatest()).toBeNull();
+ });
+
+ it('should use default capacity of 300', () => {
+ const history = new FrameHistory();
+ for (let i = 0; i < 400; i++) {
+ history.push(i, new Map());
+ }
+ expect(history.count).toBe(300);
+ });
+
+ it('should deep copy phase timings on push', () => {
+ const history = new FrameHistory();
+ const timings = new Map([['Update', 5.0]]);
+ history.push(16.0, timings);
+ timings.set('Update', 99.0);
+ expect(history.getLatest()!.phaseTimings.get('Update')).toBe(5.0);
+ });
+
+ it('should reset to empty', () => {
+ const history = new FrameHistory();
+ for (let i = 0; i < 10; i++) history.push(i, new Map());
+ expect(history.count).toBe(10);
+ history.reset();
+ expect(history.count).toBe(0);
+ expect(history.getAll()).toEqual([]);
+ });
+});
+
+// ============================================================================
+// Phase Timings
+// ============================================================================
+
+describe('App phase timings', () => {
+ it('should return null before enableStats', () => {
+ const app = App.new();
+ expect(app.getPhaseTimings()).toBeNull();
+ });
+
+ it('should return a Map after enableStats + tick', () => {
+ const app = App.new();
+ app.enableStats();
+ app.tick(1 / 60);
+ const pt = app.getPhaseTimings();
+ expect(pt).toBeInstanceOf(Map);
+ });
+
+ it('should contain schedule phase names after tick', () => {
+ const app = App.new();
+ app.enableStats();
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [], () => {}, { name: 'Dummy' }
+ ));
+ app.tick(1 / 60);
+ const pt = app.getPhaseTimings()!;
+ expect(pt.has('First')).toBe(true);
+ expect(pt.has('PreUpdate')).toBe(true);
+ expect(pt.has('Update')).toBe(true);
+ expect(pt.has('PostUpdate')).toBe(true);
+ expect(pt.has('Last')).toBe(true);
+ });
+
+ it('should have numeric values for each phase', () => {
+ const app = App.new();
+ app.enableStats();
+ app.tick(1 / 60);
+ const pt = app.getPhaseTimings()!;
+ for (const [, v] of pt) {
+ expect(typeof v).toBe('number');
+ expect(v).toBeGreaterThanOrEqual(0);
+ }
+ });
+
+ it('should work when enableStats called after first tick', () => {
+ const app = App.new();
+ app.tick(1 / 60);
+ expect(app.getPhaseTimings()).toBeNull();
+
+ app.enableStats();
+ app.tick(1 / 60);
+ expect(app.getPhaseTimings()).toBeInstanceOf(Map);
+ });
+});
+
+// ============================================================================
+// FrameStats phaseTimings field
+// ============================================================================
+
+describe('FrameStats phaseTimings', () => {
+ it('should default to empty Map', () => {
+ const stats = defaultFrameStats();
+ expect(stats.phaseTimings).toBeInstanceOf(Map);
+ expect(stats.phaseTimings.size).toBe(0);
+ });
+
+ it('should be populated by StatsPlugin', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin({ overlay: false }));
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [], () => {}, { name: 'TestSys' }
+ ));
+ app.tick(1 / 60);
+ const stats = app.getResource(Stats);
+ expect(stats.phaseTimings).toBeInstanceOf(Map);
+ expect(stats.phaseTimings.size).toBeGreaterThan(0);
+ });
+});