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(debug): a development build's log, frame stats and controls reach the editor
esenginebc45a3475219
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ca192e80..4cc76a90c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,10 +16,12 @@ published separately; it ships inside the editor.### Added+- A development build connected to the editor shows its log in the Output Log (from before the editor connected, too), can be profiled in the Profiler on its own frame clock, and can be paused, stepped and frame-capped from there; the log says which project and content version connected.- The Frame Debugger can capture and replay a frame of a development build running outside the editor — a browser or a mini-game host, on this machine or another on the network: export with the Development configuration and "Frame debugger connection", then pick the device in the panel. Native apps cannot connect yet.### Fixed+- A frame-rate cap now holds: `setTargetFrameRate(30)` on a 60 Hz display runs at 30, not 24.- A hot update reports how far it got — verified, applied, stored for the next launch, cached for offline — instead of one `ok`; two updates at once no longer both commit or lose the newer one; and an update stored by an older build no longer covers a newer one the player installed.- A hot update on a mini-game is stored for the next launch and its assets are cached on the device, so the updated game starts offline; before, a mini-game went back to what shipped.- A Douyin recording the host ends on its own keeps its video, and an interruption is not counted as recorded time.diff --git a/desktop b/desktopindex 0edacd351..a5dcf56e6 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 0edacd351714c5cadb7a8447059e5a7dfa1b41c0+Subproject commit a5dcf56e6648327732d0ae9649cc93d43c667c6ddiff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex ad1092529..600dc28bb 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 103,- "experimental": 2113,+ "experimental": 2119,"deprecated": 3},- "total": 2331,+ "total": 2337,"subsystems": [{"id": "ecs",diff --git a/pipeline/src/export/debugChannel.ts b/pipeline/src/export/debugChannel.tsindex 848877135..a9c2d93da 100644--- a/pipeline/src/export/debugChannel.ts+++ b/pipeline/src/export/debugChannel.ts@@ -11,11 +11,12 @@ import type { DebugChannelConfig } from 'esengine';* that dials an editor must never reach a player.*/export function packagedDebugChannel(- opts: { debugChannel?: DebugChannelConfig | null; minify?: boolean },+ opts: { debugChannel?: DebugChannelConfig | null; minify?: boolean; title?: string },): DebugChannelConfig | undefined {if (!opts.debugChannel) return undefined;if (opts.minify) {throw new Error('a shipping build never carries a debug channel — export the Development config to debug on a device');}- return { url: opts.debugChannel.url };+ const project = opts.debugChannel.project ?? opts.title;+ return { url: opts.debugChannel.url, ...(project ? { project } : {}) };}diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 459c37588..1d432d1f1 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -21,6 +21,7 @@ import {AnimatorRootMotion, Playthrough, Name,worldResidencyReport, PostProcess, Renderer, Audio, Camera,getComponentRegistry,+ startDebugChannel,} from 'esengine';/**@@ -123,6 +124,8 @@ async function boot(): Promise<void> {const cfg = (await (await fetch('./game.config.json')).json()) as PackagedGameConfig;splash?.reach('config');+ // Before the engine boots, so a boot that fails is still heard by the editor.+ if (cfg.debugChannel) startDebugChannel(cfg.debugChannel);// The project's own components and systems. The config SAYS whether this build// has any, so a load failure is a failure rather than a build that turned outdiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 88b86da88..5726b54cb 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: 115 public · 91 beta · 1499 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1505 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2463,6 +2463,11 @@ thresholdDb: number | undefinedtype: "compressor"```+## ConsoleLevel — type @experimental+```+'info' | 'warn' | 'error'+```+## ControllerState — interface @experimental```current: string@@ -2714,20 +2719,31 @@ Int4 = 8## DebugChannelConfig — interface @experimental```+project: string | undefinedurl: string```## DebugChannelMessage — type @experimental```-| { t: 'hello'; v: number; platform: string; title: string }+| { t: 'hello'; v: number; platform: string; title: string; project: string | null; revision: string | null }| { t: 'reply'; reqId: number; data: unknown; pixels?: boolean }| { t: 'reply'; reqId: number; error: string }+ | { t: 'log'; level: ConsoleLevel; line: string }```## DebugChannelQuery — type @experimental```| { t: 'query'; reqId: number; kind: 'frameCapture' }| { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number }+ | { t: 'query'; reqId: number; kind: 'stats' }+ | ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)+```++## DebugControl — interface @experimental+```+fps: number | undefined+paused: boolean | undefined+step: number | undefined```## DecalBakeOptions — interface @experimental@@ -3797,6 +3813,22 @@ text: numbertriangles: number```+## FrameStatsReport — interface @experimental+```+costs: FrameCosts | null+cppCounters: Record<string, number>+cppScopes: Record<string, number>+drawCalls: number+entities: number+gpuMs: number+gpuScopes: Record<string, number>+phases: Record<string, number>+sprites: number+triangles: number+vramBytes: number+wasmBytes: number+```+## GLDebug — const @experimental```{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }@@ -10832,6 +10864,11 @@ FocusPlugin(report: CensusReport): string```+## forwardConsole — function @experimental+```+(send: (level: ConsoleLevel, line: string) => void): () => void+```+## frameDebugReport — function @experimental```(data: FrameCaptureData, nameOf: (entity: number) => string | null, assets?: FrameAssetNames): FrameDebugReport@@ -10842,6 +10879,11 @@ FocusPlugin(frame: CapturedFrame): FrameProfile```+## frameStatsReport — function @experimental+```+(app: App): FrameStatsReport+```+## fxPreviewOrPlayMode — function @experimental```(): boolean@@ -12382,6 +12424,11 @@ MotionDriver<AnimatorClipMotion>(error: unknown): string | undefined```+## startDebugChannel — function @experimental+```+(config: DebugChannelConfig): void+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex c27b65967..e8da18b6e 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: 115 public · 96 beta · 1518 experimental · 3 deprecated+Symbols: 115 public · 96 beta · 1524 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2471,6 +2471,11 @@ thresholdDb: number | undefinedtype: "compressor"```+## ConsoleLevel — type @experimental+```+'info' | 'warn' | 'error'+```+## ControllerState — interface @experimental```current: string@@ -2722,20 +2727,31 @@ Int4 = 8## DebugChannelConfig — interface @experimental```+project: string | undefinedurl: string```## DebugChannelMessage — type @experimental```-| { t: 'hello'; v: number; platform: string; title: string }+| { t: 'hello'; v: number; platform: string; title: string; project: string | null; revision: string | null }| { t: 'reply'; reqId: number; data: unknown; pixels?: boolean }| { t: 'reply'; reqId: number; error: string }+ | { t: 'log'; level: ConsoleLevel; line: string }```## DebugChannelQuery — type @experimental```| { t: 'query'; reqId: number; kind: 'frameCapture' }| { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number }+ | { t: 'query'; reqId: number; kind: 'stats' }+ | ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)+```++## DebugControl — interface @experimental+```+fps: number | undefined+paused: boolean | undefined+step: number | undefined```## DecalBakeOptions — interface @experimental@@ -3805,6 +3821,22 @@ text: numbertriangles: number```+## FrameStatsReport — interface @experimental+```+costs: FrameCosts | null+cppCounters: Record<string, number>+cppScopes: Record<string, number>+drawCalls: number+entities: number+gpuMs: number+gpuScopes: Record<string, number>+phases: Record<string, number>+sprites: number+triangles: number+vramBytes: number+wasmBytes: number+```+## GLDebug — const @experimental```{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }@@ -11065,6 +11097,11 @@ FocusPlugin(report: CensusReport): string```+## forwardConsole — function @experimental+```+(send: (level: ConsoleLevel, line: string) => void): () => void+```+## frameDebugReport — function @experimental```(data: FrameCaptureData, nameOf: (entity: number) => string | null, assets?: FrameAssetNames): FrameDebugReport@@ -11075,6 +11112,11 @@ FocusPlugin(frame: CapturedFrame): FrameProfile```+## frameStatsReport — function @experimental+```+(app: App): FrameStatsReport+```+## fxPreviewOrPlayMode — function @experimental```(): boolean@@ -12625,6 +12667,11 @@ MotionDriver<AnimatorClipMotion>(error: unknown): string | undefined```+## startDebugChannel — function @experimental+```+(config: DebugChannelConfig): void+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex aa0f7643b..ee31abb43 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: 115 public · 93 beta · 1498 experimental · 3 deprecated+Symbols: 115 public · 93 beta · 1504 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2458,6 +2458,11 @@ thresholdDb: number | undefinedtype: "compressor"```+## ConsoleLevel — type @experimental+```+'info' | 'warn' | 'error'+```+## ControllerState — interface @experimental```current: string@@ -2709,20 +2714,31 @@ Int4 = 8## DebugChannelConfig — interface @experimental```+project: string | undefinedurl: string```## DebugChannelMessage — type @experimental```-| { t: 'hello'; v: number; platform: string; title: string }+| { t: 'hello'; v: number; platform: string; title: string; project: string | null; revision: string | null }| { t: 'reply'; reqId: number; data: unknown; pixels?: boolean }| { t: 'reply'; reqId: number; error: string }+ | { t: 'log'; level: ConsoleLevel; line: string }```## DebugChannelQuery — type @experimental```| { t: 'query'; reqId: number; kind: 'frameCapture' }| { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number }+ | { t: 'query'; reqId: number; kind: 'stats' }+ | ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)+```++## DebugControl — interface @experimental+```+fps: number | undefined+paused: boolean | undefined+step: number | undefined```## DecalBakeOptions — interface @experimental@@ -3792,6 +3808,22 @@ text: numbertriangles: number```+## FrameStatsReport — interface @experimental+```+costs: FrameCosts | null+cppCounters: Record<string, number>+cppScopes: Record<string, number>+drawCalls: number+entities: number+gpuMs: number+gpuScopes: Record<string, number>+phases: Record<string, number>+sprites: number+triangles: number+vramBytes: number+wasmBytes: number+```+## GLDebug — const @experimental```{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }@@ -10827,6 +10859,11 @@ FocusPlugin(report: CensusReport): string```+## forwardConsole — function @experimental+```+(send: (level: ConsoleLevel, line: string) => void): () => void+```+## frameDebugReport — function @experimental```(data: FrameCaptureData, nameOf: (entity: number) => string | null, assets?: FrameAssetNames): FrameDebugReport@@ -10837,6 +10874,11 @@ FocusPlugin(frame: CapturedFrame): FrameProfile```+## frameStatsReport — function @experimental+```+(app: App): FrameStatsReport+```+## fxPreviewOrPlayMode — function @experimental```(): boolean@@ -12387,6 +12429,11 @@ MotionDriver<AnimatorClipMotion>(error: unknown): string | undefined```+## startDebugChannel — function @experimental+```+(config: DebugChannelConfig): void+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex bc746e636..bf7144e57 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: 115 public · 91 beta · 1520 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1526 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2458,6 +2458,11 @@ thresholdDb: number | undefinedtype: "compressor"```+## ConsoleLevel — type @experimental+```+'info' | 'warn' | 'error'+```+## ControllerState — interface @experimental```current: string@@ -2709,20 +2714,31 @@ Int4 = 8## DebugChannelConfig — interface @experimental```+project: string | undefinedurl: string```## DebugChannelMessage — type @experimental```-| { t: 'hello'; v: number; platform: string; title: string }+| { t: 'hello'; v: number; platform: string; title: string; project: string | null; revision: string | null }| { t: 'reply'; reqId: number; data: unknown; pixels?: boolean }| { t: 'reply'; reqId: number; error: string }+ | { t: 'log'; level: ConsoleLevel; line: string }```## DebugChannelQuery — type @experimental```| { t: 'query'; reqId: number; kind: 'frameCapture' }| { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number }+ | { t: 'query'; reqId: number; kind: 'stats' }+ | ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)+```++## DebugControl — interface @experimental+```+fps: number | undefined+paused: boolean | undefined+step: number | undefined```## DecalBakeOptions — interface @experimental@@ -3792,6 +3808,22 @@ text: numbertriangles: number```+## FrameStatsReport — interface @experimental+```+costs: FrameCosts | null+cppCounters: Record<string, number>+cppScopes: Record<string, number>+drawCalls: number+entities: number+gpuMs: number+gpuScopes: Record<string, number>+phases: Record<string, number>+sprites: number+triangles: number+vramBytes: number+wasmBytes: number+```+## GLDebug — const @experimental```{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }@@ -11106,6 +11138,11 @@ FocusPlugin(report: CensusReport): string```+## forwardConsole — function @experimental+```+(send: (level: ConsoleLevel, line: string) => void): () => void+```+## frameDebugReport — function @experimental```(data: FrameCaptureData, nameOf: (entity: number) => string | null, assets?: FrameAssetNames): FrameDebugReport@@ -11116,6 +11153,11 @@ FocusPlugin(frame: CapturedFrame): FrameProfile```+## frameStatsReport — function @experimental+```+(app: App): FrameStatsReport+```+## fxPreviewOrPlayMode — function @experimental```(): boolean@@ -12666,6 +12708,11 @@ MotionDriver<AnimatorClipMotion>(error: unknown): string | undefined```+## startDebugChannel — function @experimental+```+(config: DebugChannelConfig): void+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0a2e48be9..65435b662 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: 115 public · 91 beta · 1511 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1517 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2458,6 +2458,11 @@ thresholdDb: number | undefinedtype: "compressor"```+## ConsoleLevel — type @experimental+```+'info' | 'warn' | 'error'+```+## ControllerState — interface @experimental```current: string@@ -2709,20 +2714,31 @@ Int4 = 8## DebugChannelConfig — interface @experimental```+project: string | undefinedurl: string```## DebugChannelMessage — type @experimental```-| { t: 'hello'; v: number; platform: string; title: string }+| { t: 'hello'; v: number; platform: string; title: string; project: string | null; revision: string | null }| { t: 'reply'; reqId: number; data: unknown; pixels?: boolean }| { t: 'reply'; reqId: number; error: string }+ | { t: 'log'; level: ConsoleLevel; line: string }```## DebugChannelQuery — type @experimental```| { t: 'query'; reqId: number; kind: 'frameCapture' }| { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number }+ | { t: 'query'; reqId: number; kind: 'stats' }+ | ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)+```++## DebugControl — interface @experimental+```+fps: number | undefined+paused: boolean | undefined+step: number | undefined```## DecalBakeOptions — interface @experimental@@ -3792,6 +3808,22 @@ text: numbertriangles: number```+## FrameStatsReport — interface @experimental+```+costs: FrameCosts | null+cppCounters: Record<string, number>+cppScopes: Record<string, number>+drawCalls: number+entities: number+gpuMs: number+gpuScopes: Record<string, number>+phases: Record<string, number>+sprites: number+triangles: number+vramBytes: number+wasmBytes: number+```+## GLDebug — const @experimental```{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }@@ -10858,6 +10890,11 @@ FocusPlugin(report: CensusReport): string```+## forwardConsole — function @experimental+```+(send: (level: ConsoleLevel, line: string) => void): () => void+```+## frameDebugReport — function @experimental```(data: FrameCaptureData, nameOf: (entity: number) => string | null, assets?: FrameAssetNames): FrameDebugReport@@ -10868,6 +10905,11 @@ FocusPlugin(frame: CapturedFrame): FrameProfile```+## frameStatsReport — function @experimental+```+(app: App): FrameStatsReport+```+## fxPreviewOrPlayMode — function @experimental```(): boolean@@ -12418,6 +12460,11 @@ MotionDriver<AnimatorClipMotion>(error: unknown): string | undefined```+## startDebugChannel — function @experimental+```+(config: DebugChannelConfig): void+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 8e4d35d04..aab06c581 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -447,8 +447,10 @@ export {type PackagedGameConfig,} from './runtime/packagedRuntime';export {+ startDebugChannel,DEBUG_CHANNEL_PROTOCOL,type DebugChannelConfig,+ type DebugControl,type DebugChannelMessage,type DebugChannelQuery,} from './runtime/debugChannel';diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex cd383c5ce..8db3e16df 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -506,6 +506,8 @@ export {type WebAppOptions,type RenderSurfaceSource,} from './app/app';+export { frameStatsReport, type FrameStatsReport } from './runtime/frameStats';+export { forwardConsole, type ConsoleLevel } from './runtime/consoleForward';// =============================================================================// Subsystem observabilitydiff --git a/sdk/src/runtime/consoleForward.ts b/sdk/src/runtime/consoleForward.tsnew file mode 100644index 000000000..843235ac0--- /dev/null+++ b/sdk/src/runtime/consoleForward.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file consoleForward.ts+ * @brief Everything a game prints, handed to a listener as well as the console.+ *+ * wasm print/printErr and the SDK logger both route through console, so wrapping+ * it catches the whole stream — the editor's Play realm and a development build+ * talking to the editor forward the same lines.+ */+export type ConsoleLevel = 'info' | 'warn' | 'error';++const LEVELS = { log: 'info', info: 'info', debug: 'info', warn: 'warn', error: 'error' } as const;++export function formatConsoleArg(a: unknown): string {+ if (typeof a === 'string') return a;+ if (a instanceof Error) return a.stack ?? a.message;+ try {+ return typeof a === 'object' ? JSON.stringify(a) : String(a);+ } catch {+ return String(a);+ }+}++/** Wrap console so @p send hears every line; returns the unwrap. A throwing+ * listener never stops the original console from printing. */+export function forwardConsole(send: (level: ConsoleLevel, line: string) => void): () => void {+ const originals = new Map<keyof typeof LEVELS, (...args: unknown[]) => void>();+ for (const m of Object.keys(LEVELS) as Array<keyof typeof LEVELS>) {+ const orig = console[m].bind(console);+ originals.set(m, console[m]);+ console[m] = (...args: unknown[]) => {+ orig(...args);+ try {+ send(LEVELS[m], args.map(formatConsoleArg).join(' '));+ } catch {+ // The listener is gone (a realm tearing down); the console still printed.+ }+ };+ }+ return () => { for (const [m, fn] of originals) console[m] = fn; };+}diff --git a/sdk/src/runtime/debugChannel.ts b/sdk/src/runtime/debugChannel.tsindex 15eee7afe..29a4e8bf4 100644--- a/sdk/src/runtime/debugChannel.ts+++ b/sdk/src/runtime/debugChannel.ts@@ -16,6 +16,9 @@ import type { PlatformSocket } from '../platform/types';import type { NextFrame } from '../render/frameCapture';import { captureFrameReport, replayFrameDraw } from '../render/frameDebugReport';import { log } from '../util/logger';+import { Assets } from '../asset/AssetPlugin';+import { frameStatsReport } from './frameStats';+import { forwardConsole, type ConsoleLevel } from './consoleForward';export const DEBUG_CHANNEL_PROTOCOL = 1;@@ -23,11 +26,25 @@ export const DEBUG_CHANNEL_PROTOCOL = 1;export interface DebugChannelConfig {/** `ws://<editor host>:<port>/?token=<token>` */url: string;+ /** The project the build was made from, so the editor can tell a build of+ * another project from one of the project it has open. */+ project?: string;+}++/** What `control` changes; each field absent leaves that setting alone. */+export interface DebugControl {+ paused?: boolean;+ /** Advance this many frames — a paused game included. */+ step?: number;+ /** A cap on the frame rate; 0 lifts it. */+ fps?: number;}export type DebugChannelQuery =| { t: 'query'; reqId: number; kind: 'frameCapture' }- | { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number };+ | { t: 'query'; reqId: number; kind: 'frameReplay'; drawIndex: number }+ | { t: 'query'; reqId: number; kind: 'stats' }+ | ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl);/*** What a device sends. A replay's pixels follow their `reply` as the very next@@ -35,11 +52,14 @@ export type DebugChannelQuery =* would add a third to every byte of it.*/export type DebugChannelMessage =- | { t: 'hello'; v: number; platform: string; title: string }+ | { t: 'hello'; v: number; platform: string; title: string; project: string | null; revision: string | null }| { t: 'reply'; reqId: number; data: unknown; pixels?: boolean }- | { t: 'reply'; reqId: number; error: string };+ | { t: 'reply'; reqId: number; error: string }+ | { t: 'log'; level: ConsoleLevel; line: string };const RECONNECT_MS = 3000;+/** Lines kept while no editor listens; the oldest go first, and how many is said. */+const LOG_BACKLOG = 200;/** Resolves once @p app has finished a frame and the task that drew it has run. */function appFrame(app: App): NextFrame {@@ -51,37 +71,93 @@ function appFrame(app: App): NextFrame {});}+let active: { attach(app: App): void } | null = null;+/**- * Keep a channel to the editor open for as long as @p app runs, dialling again- * when it drops — the editor restarts far more often than a debug session ends.- * Returns the disposer.+ * Dial the editor and forward everything printed from now on — called as soon as+ * a host has read its config, so an engine that fails to boot is still heard.+ * Redials when the connection drops: the editor restarts far more often than a+ * debug session ends. Once per page; later calls keep the first channel.*/-export function openDebugChannel(app: App, config: DebugChannelConfig, title = ''): () => void {+export function startDebugChannel(config: DebugChannelConfig): void {+ if (active) return;const platform = getPlatform();if (!platform.createSocket) {log.warn('debug', `this platform has no socket, so the editor cannot reach this build (${platform.name})`);- return () => {};+ return;}- const nextFrame = appFrame(app);+ let app: App | null = null;+ let nextFrame: NextFrame | null = null;let socket: PlatformSocket | null = null;let retry: ReturnType<typeof setTimeout> | null = null;- let closed = false;+ let statsOn = false;+ let frameSum = 0, frames = 0, worstMs = 0;++ const backlog: Array<{ level: ConsoleLevel; line: string }> = [];+ let dropped = 0;+ const send = (m: DebugChannelMessage): void => {+ if (socket?.readyState === 'open') socket.send(JSON.stringify(m));+ };+ forwardConsole((level, line) => {+ if (socket?.readyState === 'open') {+ send({ t: 'log', level, line });+ return;+ }+ if (backlog.length >= LOG_BACKLOG) { backlog.shift(); dropped++; }+ backlog.push({ level, line });+ });+ const flushBacklog = (): void => {+ if (dropped > 0) send({ t: 'log', level: 'warn', line: `[debug] ${dropped} earlier line(s) are not shown: the editor was not listening yet` });+ for (const e of backlog) send({ t: 'log', ...e });+ backlog.length = 0;+ dropped = 0;+ };+ const hello = (): void => {+ const assets = app?.hasResource(Assets) ? app.getResource(Assets) : null;+ send({+ t: 'hello', v: DEBUG_CHANNEL_PROTOCOL, platform: platform.name, title: '',+ project: config.project ?? null, revision: assets?.getManifest()?.revision() ?? null,+ });+ };- const answer = async (s: PlatformSocket, q: DebugChannelQuery): Promise<void> => {- const reply = (m: DebugChannelMessage): void => s.send(JSON.stringify(m));+ const answer = async (q: DebugChannelQuery): Promise<void> => {+ const reply = (m: DebugChannelMessage): void => send(m);try {+ if (!app || !nextFrame) throw new Error('the game has not started yet');+ const game = app;if (q.kind === 'frameCapture') {- reply({ t: 'reply', reqId: q.reqId, data: await captureFrameReport(app, nextFrame) });+ reply({ t: 'reply', reqId: q.reqId, data: await captureFrameReport(game, nextFrame) });+ return;+ }+ if (q.kind === 'stats') {+ // Timings cost a little every frame, so they start when first asked for.+ if (!statsOn) {+ game.enableStats();+ game.onFrameEnd((dt) => { frameSum += dt; frames++; worstMs = Math.max(worstMs, dt); });+ statsOn = true;+ }+ // The device's own frame time since the last ask: the editor's clock+ // runs on another machine and says nothing about this one.+ const span = { frames, frameMs: frames > 0 ? frameSum / frames : 0, worstMs };+ frameSum = 0; frames = 0; worstMs = 0;+ reply({ t: 'reply', reqId: q.reqId, data: { ...frameStatsReport(game), ...span } });return;}- const image = await replayFrameDraw(app, q.drawIndex, nextFrame);+ if (q.kind === 'control') {+ if (q.fps !== undefined) game.setTargetFrameRate(q.fps);+ if (q.paused !== undefined) game.setPaused(q.paused);+ if (q.step && q.step > 0) await game.stepFrames(q.step);+ reply({ t: 'reply', reqId: q.reqId, data: { paused: game.isPaused(), fps: Math.round(game.getTargetFrameRate()) } });+ return;+ }+ const image = await replayFrameDraw(game, q.drawIndex, nextFrame);if (!image) {reply({ t: 'reply', reqId: q.reqId, data: null });return;}const { pixels, ...rest } = image;reply({ t: 'reply', reqId: q.reqId, data: rest, pixels: true });- s.send(pixels.buffer.byteLength === pixels.byteLength+ socket?.send(pixels.buffer.byteLength === pixels.byteLength? pixels.buffer as ArrayBuffer: pixels.slice().buffer as ArrayBuffer);} catch (e) {@@ -91,33 +167,38 @@ export function openDebugChannel(app: App, config: DebugChannelConfig, title = 'const dial = (): void => {retry = null;- if (closed) return;const s = platform.createSocket!({ url: config.url });socket = s;s.on('open', () => {- const hello: DebugChannelMessage = { t: 'hello', v: DEBUG_CHANNEL_PROTOCOL, platform: platform.name, title };- s.send(JSON.stringify(hello));- log.info('debug', 'connected to the editor');+ hello();+ flushBacklog();});s.on('message', (data) => {if (typeof data !== 'string') return;let q: DebugChannelQuery;try { q = JSON.parse(data) as DebugChannelQuery; } catch { return; }- if (q.t === 'query') void answer(s, q);+ if (q.t === 'query') void answer(q);});s.on('close', () => {if (socket === s) socket = null;- if (!closed && retry === null) retry = setTimeout(dial, RECONNECT_MS);+ if (retry === null) retry = setTimeout(dial, RECONNECT_MS);});s.on('error', () => { /* a close follows, and it redials */ });s.connect();};dial();- return () => {- closed = true;- if (retry !== null) clearTimeout(retry);- socket?.close();- socket = null;+ active = {+ attach(game) {+ app = game;+ nextFrame = appFrame(game);+ hello();+ },};}++/** Hand the running game to the channel {@link startDebugChannel} opened, so the+ * editor can capture, profile and control it. */+export function attachDebugChannel(app: App): void {+ active?.attach(app);+}diff --git a/sdk/src/runtime/frameStats.ts b/sdk/src/runtime/frameStats.tsnew file mode 100644index 000000000..46765e3aa--- /dev/null+++ b/sdk/src/runtime/frameStats.ts@@ -0,0 +1,48 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file frameStats.ts+ * @brief The last frame's cost and counters, as the editor's profiler reads+ * them — the same answer from its Play realm and from a device.+ */+import type { App, FrameCosts } from '../app/app';++export interface FrameStatsReport {+ phases: Record<string, number>;+ /** Per-system and per-scope cost with the domain/system attribution the+ * profile tree is folded from. Null while the app has stats off. */+ costs: FrameCosts | null;+ drawCalls: number;+ triangles: number;+ sprites: number;+ entities: number;+ gpuMs: number;+ cppScopes: Record<string, number>;+ cppCounters: Record<string, number>;+ gpuScopes: Record<string, number>;+ wasmBytes: number;+ vramBytes: number;+}++function jsonMap(json: string | undefined): Record<string, number> {+ if (!json) return {};+ try { return JSON.parse(json) as Record<string, number>; } catch { return {}; }+}++export function frameStatsReport(app: App): FrameStatsReport {+ const m = app.wasmModule;+ return {+ phases: Object.fromEntries(app.getPhaseTimings() ?? []),+ costs: app.getFrameCosts(),+ drawCalls: m?.renderer_getDrawCalls?.() ?? 0,+ triangles: m?.renderer_getTriangles?.() ?? 0,+ sprites: m?.renderer_getSprites?.() ?? 0,+ entities: app.world.getAllEntities().length,+ gpuMs: m?.renderer_getGpuTimeMs?.() ?? -1,+ cppScopes: jsonMap(m?.engine_getCpuScopes?.()),+ cppCounters: jsonMap(m?.engine_getCounters?.()),+ gpuScopes: jsonMap(m?.engine_getGpuScopes?.()),+ wasmBytes: m?.HEAPU8?.byteLength ?? 0,+ vramBytes: m?.renderer_getTextureBytes?.() ?? 0,+ };+}diff --git a/sdk/src/runtime/miniGameRuntime.ts b/sdk/src/runtime/miniGameRuntime.tsindex 8bb2608ca..ada1f91f4 100644--- a/sdk/src/runtime/miniGameRuntime.ts+++ b/sdk/src/runtime/miniGameRuntime.ts@@ -31,7 +31,7 @@ import { createMiniGameSideModuleHost, type MiniGameSideModuleFactories } from 'import type { Physics2DPluginConfig } from '../physics/PhysicsTypes';import type { SceneData } from '../scene/scene';import type { AotManifest } from '../ecs/aot/AotSystems';-import type { DebugChannelConfig } from './debugChannel';+import { startDebugChannel, type DebugChannelConfig } from './debugChannel';import type { PackagedGameConfig } from './packagedRuntime';import { log } from '../util/logger';import { Schedule, defineSystem } from '../ecs/system';@@ -197,6 +197,8 @@ function hostProgress(global: { showLoading?: (o: { title: string; mask?: boolea}export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promise<void> {+ // Before the engine boots, so a boot that fails is still heard by the editor.+ if (config.debugChannel) startDebugChannel(config.debugChannel);// Before the app exists, so a plugin that acquires during build finds them.registerPackagedSideModules({ sideModules: config.sideModules });// The family adapter owns the host global; boot refuses to guess at one.diff --git a/sdk/src/runtime/nativeGameRuntime.ts b/sdk/src/runtime/nativeGameRuntime.tsindex ba86ddf33..924d5d51e 100644--- a/sdk/src/runtime/nativeGameRuntime.ts+++ b/sdk/src/runtime/nativeGameRuntime.ts@@ -15,6 +15,7 @@* before the async boot settles).*/+import { startDebugChannel } from './debugChannel';import type { App } from '../app/app';import { initRuntime } from './runtimeLoader';import { createNativeApp } from '../ecs/bridge/nativeRuntime';@@ -52,6 +53,7 @@ export async function initNativeGame(options: NativeGameOptions): Promise<Nativeconst config = JSON.parse(await platformReadTextFile(options.configPath ?? 'game.config.json'),) as PackagedGameConfig;+ if (config.debugChannel) startDebugChannel(config.debugChannel);const index = await loadPackagedAssetIndex();const source = createPackagedAssetSource(index);diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex a779da24a..ece2aa59a 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -44,7 +44,7 @@ import { flushPendingRegistrations } from '../app/app';import { installHotUpdateRebind } from '../hotUpdateRebind';import { requireResourceManager } from '../wasm/resourceManager';import { log } from '../util/logger';-import { openDebugChannel, type DebugChannelConfig } from './debugChannel';+import { startDebugChannel, attachDebugChannel, type DebugChannelConfig } from './debugChannel';import type { AotManifest } from '../ecs/aot/AotSystems';import { type RuntimeAssetSource, type TextureParams } from './runtimeAssets';import type { SpineAssetInfo } from '../spine/loadSpineScene';@@ -816,7 +816,7 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {log.info('runtime', `AOT: ${installed} compiled system(s) installed`);}- if (config.debugChannel) openDebugChannel(app, config.debugChannel);+ if (config.debugChannel) startDebugChannel(config.debugChannel);// Install the per-App runtime Assets up front (scene loads reuse it) and// hand it the manifest so on-demand loadGroup works from the first frame.@@ -828,6 +828,8 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {// A persisted update (from a prior applyUpdate) supersedes the shipped manifest// + root, so a returning player boots straight onto the already-updated content.if (config.persistUpdateKey) assets.restorePersistedUpdate(config.persistUpdateKey);+ // Once the content it runs is known, so the editor is told which revision it is.+ attachDebugChannel(app);// Built-in rebinder: on a hot update, swap the changed texture into live// sprites/meshes automatically — a scene @uuid ref updates with no game code.installHotUpdateRebind(app, assets);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 0b77e8d2d..fb12b5512 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -1064,4 +1064,10 @@ export const NOTED = {{ note: 'A hot update reports how far it got — verified, applied, stored for the next launch, cached for offline — instead of one `ok`; two updates at once no longer both commit or lose the newer one; and an update stored by an older build no longer covers a newer one the player installed.' },'fix(minigame): a hot update reaches a mini-game, and survives its next launch offline':{ note: 'A hot update on a mini-game is stored for the next launch and its assets are cached on the device, so the updated game starts offline; before, a mini-game went back to what shipped.' },+ 'feat(debug): a development build\'s log, frame stats and controls reach the editor':+ { note: 'A development build connected to the editor shows its log in the Output Log (from before the editor connected, too), can be profiled in the Profiler on its own frame clock, and can be paused, stepped and frame-capped from there; the log says which project and content version connected.' },+ 'feat(profiler): a development build\'s frames, log and clock, read and driven from the editor':+ { note: 'A development build connected to the editor shows its log in the Output Log (from before the editor connected, too), can be profiled in the Profiler on its own frame clock, and can be paused, stepped and frame-capped from there; the log says which project and content version connected.' },+ 'fix(app): a frame-rate cap keeps a cadence, so 30 on a 60 Hz display is 30':+ { note: 'A frame-rate cap now holds: `setTargetFrameRate(30)` on a 60 Hz display runs at 30, not 24.' },};diff --git a/tools/verify-remote-capture.mjs b/tools/verify-remote-capture.mjsindex 14a59c9e9..74319804d 100644--- a/tools/verify-remote-capture.mjs+++ b/tools/verify-remote-capture.mjs@@ -48,7 +48,10 @@ const exportPackage = (out, extra) => spawnSync(process.execPath, ['--platform', PLATFORM, '--out', out, ...extra,], { encoding: 'utf8', cwd: ROOT });-const server = await createDebugChannelServer({ WebSocketServer, host: '127.0.0.1' });+const lines = [];+const server = await createDebugChannelServer({+ WebSocketServer, host: '127.0.0.1', onLog: (_id, level, line) => lines.push({ level, line }),+});let child = null;try {const refused = await new Promise((resolve) => {@@ -115,6 +118,24 @@ try {if (image.pixels[i + 3] > 0 && (image.pixels[i] | image.pixels[i + 1] | image.pixels[i + 2]) > 8) lit++;}check(lit > 0, `the replayed pass has drawn pixels (${lit})`);++ const now = server.targets().find((t) => t.id === target.id);+ check(now?.project === 'Input Actions' && typeof now?.revision === 'string',+ `the build said which project and content it is (${now?.project}, ${now?.revision})`);+ check(lines.some((l) => /EstellaContext initialized/.test(l.line)),+ `what the device printed before it connected reached the editor (${lines.length} line(s))`);++ await server.query(target.id, 'stats');+ await new Promise((r) => setTimeout(r, 500));+ const stats = await server.query(target.id, 'stats');+ check(stats?.entities > 0 && Object.keys(stats?.phases ?? {}).length > 0 && stats?.wasmBytes > 0,+ `the device reported its frame: ${stats?.entities} entities, ${Object.keys(stats?.phases ?? {}).length} phase(s), ${stats?.wasmBytes} wasm bytes`);++ const paused = await server.query(target.id, 'control', { paused: true, fps: 30 });+ const stepped = await server.query(target.id, 'control', { step: 2 });+ const resumed = await server.query(target.id, 'control', { paused: false, fps: 0 });+ check(paused.paused && paused.fps === 30 && stepped.paused && !resumed.paused && resumed.fps === 0,+ `the device paused, stepped while paused, capped and resumed (${JSON.stringify([paused, stepped, resumed])})`);} catch (e) {problems.push(e.message);console.error(`✗ ${e.message}`);