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(editor): boot-phase profiler — measure open→engine-ready timing
yhh94bbfb6bfe19
diff --git a/desktop/electron/assetDb.ts b/desktop/electron/assetDb.tsindex f42abdf0f..100235943 100644--- a/desktop/electron/assetDb.ts+++ b/desktop/electron/assetDb.ts@@ -61,6 +61,10 @@ export interface ScanAssetsResult {warnings: string[];/** Orphan content files the scan adopted (minted a `.meta` for) this pass. */adopted: string[];+ /** Per-sub-phase wall time (ms) — surfaced in the renderer boot profile so the+ * cost of this O(files) scan is visible and attributable (adopt vs meta-walk+ * vs dependency graph vs write-back). */+ timingMs?: { adopt: number; walk: number; deps: number; write: number; total: number; files: number };}/** Recursively yield every `<file>.meta` path (project-relative, forward-slashed). */@@ -184,10 +188,18 @@ export async function scanAssetDatabase(const entries: AssetEntry[] = [];const warnings: string[] = [];+ // Sub-phase timing: this scan is O(files) and runs on every project open, so+ // make each phase's cost visible (returned as timingMs, folded into the boot+ // profile). performance.now() is a Node global.+ const t = { adopt: 0, walk: 0, deps: 0, write: 0 };+ const tStart = performance.now();+// Adopt-before-index: orphans minted here are picked up by the meta walk below,// so a single scan both registers and indexes them (no second pass needed).const adopted = opts?.adopt === false ? [] : await adoptOrphans(root);+ t.adopt = performance.now() - tStart;+ const tWalk = performance.now();for await (const metaRel of walkMeta(root)) {let meta: { uuid?: unknown; type?: unknown; importer?: unknown };try {@@ -209,7 +221,9 @@ export async function scanAssetDatabase(}entries.sort((a, b) => a.path.localeCompare(b.path));+ t.walk = performance.now() - tWalk;+ const tDeps = performance.now();// Dependency graph: any JSON asset can reference others — by uuid or by path// (project-relative like a scene's "assets/materials/x.esmaterial", or// relative to the referencing document's own directory like a material's@@ -256,8 +270,10 @@ export async function scanAssetDatabase(}}+ t.deps = performance.now() - tDeps;const index: AssetIndex = { version: '1.0', entries, deps };+ const tWrite = performance.now();let outputPath: string | null = null;if (opts?.write !== false) {outputPath = path.join(root, CACHE_DIR, OUTPUT);@@ -277,5 +293,16 @@ export async function scanAssetDatabase(}}- return { ok: true, outputPath, index, warnings, adopted };+ t.write = performance.now() - tWrite;+ const round1 = (n: number): number => Math.round(n * 10) / 10;+ const timingMs = {+ adopt: round1(t.adopt), walk: round1(t.walk), deps: round1(t.deps), write: round1(t.write),+ total: round1(performance.now() - tStart), files: entries.length,+ };+ console.info(+ `[boot] scanAssetDatabase: ${timingMs.total}ms (${timingMs.files} assets) — ` ++ `adopt ${timingMs.adopt} / walk ${timingMs.walk} / deps ${timingMs.deps} / write ${timingMs.write}`,+ );++ return { ok: true, outputPath, index, warnings, adopted, timingMs };}diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.tsindex c1c3a9923..129c0c572 100644--- a/desktop/src/engine/EngineHost.ts+++ b/desktop/src/engine/EngineHost.ts@@ -22,6 +22,7 @@ import { SceneLoader } from './SceneLoader';import { useSettings } from '@/store/settingsStore';import { loadEditorSpine } from './spineLoad';import { checkEngineBuild } from './EngineGuard';+import { bootProfiler } from './bootProfiler';import { PROJECT_MANIFEST_FILE } from '@/project/format';import type { ReadonlyWorldT, WorldT } from './schema';@@ -476,11 +477,12 @@ class EngineHostImpl {this.activeBackend = backend;this.activeColorSpace = opts.colorSpace ?? 'gamma';console.info(`[engine] backend: ${backend}, colorSpace: ${this.activeColorSpace}`);+ bootProfiler.begin(`engine boot (${backend})`);// Early build-consistency check: compare the wasm's stamped manifest// (variant / ABI / provenance) against this SDK before the heavy// instantiate. Advisory only — the runtime bridge handshake is the// authoritative fatal layout check (reads the real binary).- const guard = await checkEngineBuild();+ const guard = await bootProfiler.phase('checkBuild', () => checkEngineBuild());if (guard.level === 'warn') console.warn('[engine]', guard.message);else console.info('[engine]', guard.message);@@ -491,7 +493,7 @@ class EngineHostImpl {// NOTE: works in dev (http origin); production packaging will need a// custom protocol or relative base since file:// roots differently.const glueUrl = `${location.origin}/wasm/esengine.js`;- const { default: createModule } = (await import(/* @vite-ignore */ glueUrl)) as {+ const { default: createModule } = await bootProfiler.phase('importGlue', () => import(/* @vite-ignore */ glueUrl)) as {default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;};@@ -547,7 +549,7 @@ class EngineHostImpl {document.body.appendChild(canvas);}}- const module = await createModule(moduleArg);+ const module = await bootProfiler.phase('createModule (wasm instantiate)', () => createModule(moduleArg));this.module_ = module;// WebGL2: bind the renderer to a context WE create on this canvas (rather@@ -573,7 +575,7 @@ class EngineHostImpl {});}- const app = createWebApp(module, {+ const app = await bootProfiler.phase('createWebApp', () => createWebApp(module, {backend,colorSpace: opts.colorSpace,canvasSelector: `#${canvas.id}`,@@ -583,7 +585,7 @@ class EngineHostImpl {// (same /wasm/ dir as locateFile above), so the web spine provider can// load 3.8/4.1 assets in the viewport, not just the engine-linked 4.2.wasmBaseUrl: '/wasm',- });+ }));this.app_ = app;if (this.targetFps_ > 0) app.setTargetFrameRate(this.targetFps_);@@ -638,6 +640,9 @@ class EngineHostImpl {// Report ready before run() (the DOM path) in case the loop never resolves.this.setStatus('ready');+ // Emit the boot timing table now that the overlay is about to clear — the+ // sceneBootstrap above recorded its own sub-phases (asset scan, preload, …).+ bootProfiler.report();if (opts.runLoop) {void Promise.resolve(app.run()).catch((err) => this.swallowUnwind(err));}diff --git a/desktop/src/engine/bootProfiler.ts b/desktop/src/engine/bootProfiler.tsnew file mode 100644index 000000000..2583f7983--- /dev/null+++ b/desktop/src/engine/bootProfiler.ts@@ -0,0 +1,115 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A boot-phase profiler for the "open project → engine ready" path. The+ * editor shows a "Booting esengine…" overlay until EngineHost flips to+ * 'ready', and that flip only happens after the wasm instantiates AND the+ * scene bootstrap (which runs a full project-wide asset scan) completes.+ * Nothing measured where the seconds actually go — this does.+ *+ * Renderer-side aggregator: it times renderer phases directly and folds in+ * main-process costs as they are experienced (IPC round-trips) plus any+ * sub-phase breakdown a handler chooses to return (see `detail`). One+ * console.table per open, and `window.__estellaBootProfile` for tooling.+ */++const now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());+const round1 = (n: number): number => Math.round(n * 10) / 10;++export interface BootPhase {+ name: string;+ ms: number;+ /** Optional sub-phase breakdown, e.g. a main-process scan's adopt/walk/deps split. */+ detail?: Record<string, number>;+}++export interface BootProfile {+ label: string;+ total: number;+ phases: BootPhase[];+}++class BootProfiler {+ private active = false;+ private t0 = 0;+ private label = '';+ private phases: BootPhase[] = [];+ // Detail can be reported from INSIDE a phase's fn — before phase() has recorded+ // the phase — so buffer it by name and attach when the phase lands.+ private pendingDetails = new Map<string, Record<string, number>>();++ /** Open a fresh profile. A second begin() before report() discards the first. */+ begin(label: string): void {+ this.active = true;+ this.label = label;+ this.t0 = now();+ this.phases = [];+ this.pendingDetails.clear();+ }++ get isActive(): boolean {+ return this.active;+ }++ /**+ * Time one async phase and record it. A no-op wrapper (just awaits `fn`) when+ * no profile is open, so instrumented functions on the shared open→ready path+ * are safe to call outside a boot (e.g. re-opening a scene while running).+ */+ async phase<T>(name: string, fn: () => Promise<T> | T): Promise<T> {+ if (!this.active) return fn();+ const start = now();+ try {+ return await fn();+ } finally {+ const phase: BootPhase = { name, ms: round1(now() - start) };+ const pending = this.pendingDetails.get(name);+ if (pending) { phase.detail = pending; this.pendingDetails.delete(name); }+ this.phases.push(phase);+ }+ }++ /**+ * Attach a sub-phase breakdown to the phase named `name` — usable from inside+ * that phase's fn (buffered until the phase lands) or after it (attached to the+ * already-recorded phase).+ */+ detail(name: string, detail: Record<string, number>): void {+ if (!this.active) return;+ for (let i = this.phases.length - 1; i >= 0; i--) {+ if (this.phases[i].name === name) { this.phases[i].detail = detail; return; }+ }+ this.pendingDetails.set(name, detail);+ }++ /** Close the profile: emit one table + a summary line, and publish the data. */+ report(): BootProfile | null {+ if (!this.active) return null;+ this.active = false;+ const total = round1(now() - this.t0);+ const measured = this.phases.reduce((s, p) => s + p.ms, 0);+ const other = round1(total - measured);++ const rows = this.phases+ .slice()+ .sort((a, b) => b.ms - a.ms)+ .map((p) => ({ phase: p.name, ms: p.ms, '%': total > 0 ? Math.round((p.ms / total) * 100) : 0 }));+ if (other > 0.5) rows.push({ phase: '(other/setup)', ms: other, '%': total > 0 ? Math.round((other / total) * 100) : 0 });++ const profile: BootProfile = { label: this.label, total, phases: this.phases.slice() };+ // One compact table + a one-liner. The table is the "直观数据统计"; the+ // window handle lets automation/SHOT scripts read the profile programmatically.+ /* eslint-disable no-console */+ console.info(`[boot] ${this.label}: ${total}ms total (slowest: ${rows[0]?.phase} ${rows[0]?.ms}ms)`);+ console.table(rows);+ for (const p of this.phases) {+ if (p.detail) console.info(`[boot] ${p.name} breakdown:`, p.detail);+ }+ /* eslint-enable no-console */+ (window as unknown as { __estellaBootProfile?: BootProfile }).__estellaBootProfile = profile;+ return profile;+ }+}++/** Shared singleton — the open→ready path is a single sequence, so one profile at a time. */+export const bootProfiler = new BootProfiler();diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 08026af60..e766acecf 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -5,6 +5,7 @@ import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab,import { readTextureImportSettings } from './assetImporter';import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData } from 'esengine';import { EngineHost } from '@/engine/EngineHost';+import { bootProfiler } from '@/engine/bootProfiler';import { SceneModel } from '@/engine/SceneModel';import { Reconciler } from '@/engine/Reconciler';import { blankInputMap } from './inputMapDoc';@@ -347,24 +348,26 @@ class ProjectStoreImpl {);}// Build the uuid→path registry first (prefab + texture refs resolve through it).- await this.buildAssetRegistry();+ // This runs the full project-wide asset scan (O(files)) on every open — the+ // usual boot-time hot spot on asset-heavy projects, so it gets its own phase.+ await bootProfiler.phase('scanAssets', () => this.buildAssetRegistry());// Expand prefab-instance entries into ordinary tagged entities (the model is// always expanded; the file stores deltas). Internal// entities get fresh ids above the file's max so they don't collide.let nextId = raw.entities.reduce((m, e) => Math.max(m, (e as { id?: number }).id ?? 0), 0) + 1;- const { scene: expandedRaw, tags } = await expandScenePrefabs(+ const { scene: expandedRaw, tags } = await bootProfiler.phase('expandPrefabs', () => expandScenePrefabs(raw,(ref) => this.loadPrefabAsset(ref),() => nextId++,- );+ ));// Preload EVERY referenced asset type through the engine's own system, and// resolve a COPY of the (expanded) scene (refs → handles) for the World.const assets = EngineHost.getResource(Assets);let resolved: SceneData = expandedRaw;if (assets) {- const result = await assets.preloadSceneAssets(expandedRaw);+ const result = await bootProfiler.phase('preloadSceneAssets', () => assets.preloadSceneAssets(expandedRaw));resolved = JSON.parse(JSON.stringify(expandedRaw)) as SceneData; // resolveSceneAssetPaths mutatesassets.resolveSceneAssetPaths(resolved, result);this.lastAssetResult = result; // narrowed to the handle maps the resolver reads@@ -390,7 +393,7 @@ class ProjectStoreImpl {// of the model, driven by model events: adopt's `reset` performs the initial// bind, and later ref/field edits keep the viewport true (see spineSync).installSpineSync(this.spineTransport());- Reconciler.adopt(expandedRaw, resolved);+ await bootProfiler.phase('reconcile (build world)', () => Reconciler.adopt(expandedRaw, resolved));// Re-apply prefab-instance tags (adopt cleared them) so save can collapse.for (const { id, tag } of tags) SceneModel.setPrefabTag(id, tag);@@ -481,6 +484,8 @@ class ProjectStoreImpl {const scan = await window.estella.project.scanAssets();({ entries } = scan.index);adopted = scan.adopted ?? [];+ // Fold the main-process scan's sub-phase split into the 'scanAssets' boot phase.+ if (scan.timingMs) bootProfiler.detail('scanAssets', scan.timingMs);} catch (err) {console.warn('[project] asset scan failed', err);return;