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
fix: address memory leaks, type safety, performance, and reliability issues
esengine45d64578a003
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 4b8fbbe81..11a0fe3f8 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -130,6 +130,12 @@ jobs:- name: Install dependenciesrun: pnpm install+ - name: Type-check SDK+ run: npx tsc --noEmit -p sdk/tsconfig.json++ - name: Type-check Editor+ run: npx tsc --noEmit -p editor/tsconfig.json+- name: Run SDK tests with coveragerun: pnpm --filter esengine vitest run --coverage --coverage.thresholds.lines=60 --coverage.thresholds.functions=60 --coverage.thresholds.branches=60 --coverage.thresholds.statements=60diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 8568a8b1e..f5e8b7bc2 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -25,7 +25,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@v4with:- node-version: '20'+ node-version: '22'- name: Install Doxygenrun: sudo apt-get update && sudo apt-get install -y doxygen graphvizdiff --git a/.github/workflows/publish-sdk.yml b/.github/workflows/publish-sdk.ymlindex 04ec038e5..5a122e236 100644--- a/.github/workflows/publish-sdk.yml+++ b/.github/workflows/publish-sdk.yml@@ -21,13 +21,13 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@v4with:- node-version: '20'+ node-version: '22'registry-url: 'https://registry.npmjs.org'- name: Setup pnpm- uses: pnpm/action-setup@v2+ uses: pnpm/action-setup@v4with:- version: 8+ version: 9- name: Install dependenciesworking-directory: sdkdiff --git a/build-tools/release.js b/build-tools/release.jsindex 36dc45c4f..5df755b69 100644--- a/build-tools/release.js+++ b/build-tools/release.js@@ -8,7 +8,11 @@ const TAURI_CONF = 'desktop/src-tauri/tauri.conf.json';function run(cmd) {console.log(chalk.gray(` $ ${cmd}`));- execSync(cmd, { stdio: 'inherit' });+ try {+ execSync(cmd, { stdio: 'inherit' });+ } catch (e) {+ die(`Command failed: ${cmd}`);+ }}function die(msg) {diff --git a/build-tools/tasks/sdk.js b/build-tools/tasks/sdk.jsindex b3487999e..89ca9a77f 100644--- a/build-tools/tasks/sdk.js+++ b/build-tools/tasks/sdk.js@@ -19,66 +19,51 @@ export async function buildSdk(options = {}) {const sdkDir = config.paths.sdk;const outputDir = path.join(config.paths.output, 'sdk');+ const sdkOutputs = [+ 'esm/esengine.js',+ 'esm/esengine.d.ts',+ 'esm/wasm.js',+ 'esm/wasm.d.ts',+ 'esm/spine/index.js',+ 'esm/spine/index.d.ts',+ 'esm/physics/index.js',+ 'esm/physics/index.d.ts',+ 'cjs/esengine.wechat.js',+ 'cjs/index.wechat.js',+ ];++ let cache = null;+ let currentHash = null;+if (!noCache) {- const cache = new HashCache(config.paths.cache);+ cache = new HashCache(config.paths.cache);await cache.load();const sdkSrcDir = path.join(sdkDir, 'src');- const currentHash = await hashDirectory(sdkSrcDir, /\.ts$/);+ currentHash = await hashDirectory(sdkSrcDir, /\.ts$/);if (!await cache.isChanged('sdk', currentHash)) {logger.success('SDK: No changes detected (cached)');- const result = {- outputDir,- outputs: [- 'esm/esengine.js',- 'esm/esengine.d.ts',- 'esm/wasm.js',- 'esm/wasm.d.ts',- 'esm/spine/index.js',- 'esm/spine/index.d.ts',- 'esm/physics/index.js',- 'esm/physics/index.d.ts',- 'cjs/esengine.wechat.js',- 'cjs/index.wechat.js',- ],- skipped: true,- };+ const result = { outputDir, outputs: sdkOutputs, skipped: true };if (manifest) {await manifest.endTarget('sdk', result);}return result;}+ }- await mkdir(outputDir, { recursive: true });- await runCommand('npm', ['run', 'build'], { cwd: sdkDir });- await copyDistOutputs(sdkDir, outputDir);+ await mkdir(outputDir, { recursive: true });+ await runCommand('npm', ['run', 'build'], { cwd: sdkDir });+ await copyDistOutputs(sdkDir, outputDir);+ if (cache) {cache.set('sdk', currentHash);await cache.save();- } else {- await mkdir(outputDir, { recursive: true });- await runCommand('npm', ['run', 'build'], { cwd: sdkDir });- await copyDistOutputs(sdkDir, outputDir);}logger.success('SDK: Build complete');- const result = {- outputDir,- outputs: [- 'esm/esengine.js',- 'esm/esengine.d.ts',- 'esm/wasm.js',- 'esm/wasm.d.ts',- 'esm/spine/index.js',- 'esm/spine/index.d.ts',- 'esm/physics/index.js',- 'esm/physics/index.d.ts',- 'cjs/esengine.wechat.js',- 'cjs/index.wechat.js',- ],- };+ const result = { outputDir, outputs: sdkOutputs };if (manifest) {await manifest.endTarget('sdk', result);diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.jsindex 48aaf3d77..1d4c78f1c 100644--- a/build-tools/tasks/wasm.js+++ b/build-tools/tasks/wasm.js@@ -143,6 +143,7 @@ async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2') {const wasmFiles = Object.keys(outputs).filter(src => src.endsWith('.wasm'));if (wasmFiles.length === 0) return;+ const warnings = [];for (const src of wasmFiles) {const wasmPath = path.join(buildDir, src);if (!existsSync(wasmPath)) continue;@@ -154,19 +155,30 @@ async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2') {const reduction = ((1 - after / before) * 100).toFixed(1);logger.debug(`wasm-opt ${optLevel}: ${src} ${(before / 1024).toFixed(0)}KB → ${(after / 1024).toFixed(0)}KB (-${reduction}%)`);} catch {- logger.warn('wasm-opt not found or failed, skipping WASM optimization');- return;+ const msg = `wasm-opt failed for ${src}, skipping optimization`;+ logger.warn(msg);+ warnings.push(msg);}}++ if (warnings.length > 0) {+ logger.warn(`wasm-opt completed with ${warnings.length} warning(s)`);+ }}async function copyOutputs(buildDir, outputDir, outputs) {+ const missing = [];+for (const [src, dest] of Object.entries(outputs)) {const srcPath = path.join(buildDir, src);const destPath = path.join(outputDir, dest);if (!existsSync(srcPath)) {- logger.warn(`Output file not found: ${srcPath}`);+ if (src.endsWith('.wasm') || src.endsWith('.js')) {+ missing.push(src);+ } else {+ logger.warn(`Output file not found: ${srcPath}`);+ }continue;}@@ -174,6 +186,10 @@ async function copyOutputs(buildDir, outputDir, outputs) {await cp(srcPath, destPath);logger.debug(`Copied ${src} → ${dest}`);}++ if (missing.length > 0) {+ throw new Error(`Critical output files missing after build: ${missing.join(', ')}`);+ }}export async function buildWasmParallel(targets, options = {}) {diff --git a/build-tools/tasks/watch.js b/build-tools/tasks/watch.jsindex 289f9ed6b..838e46015 100644--- a/build-tools/tasks/watch.js+++ b/build-tools/tasks/watch.js@@ -17,8 +17,11 @@ export async function startWatch(options = {}) {const rootDir = config.paths.root;+ const RETRY_DELAY_MS = 1000;+let isBuilding = false;let pendingTypes = new Set();+ let lastBuildFailed = false;async function rebuild(type, file) {if (isBuilding) {@@ -33,13 +36,18 @@ export async function startWatch(options = {}) {try {await executeBuild(type);logger.success('Rebuild complete');+ lastBuildFailed = false;} catch (err) {logger.error(`Build failed: ${err.message}`);+ lastBuildFailed = true;} finally {isBuilding = false;}if (pendingTypes.size > 0) {+ if (lastBuildFailed) {+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));+ }const types = pendingTypes;pendingTypes = new Set();await executePendingBuild(types);@@ -78,13 +86,18 @@ export async function startWatch(options = {}) {}await syncToDesktop();logger.success('Rebuild complete');+ lastBuildFailed = false;} catch (err) {logger.error(`Build failed: ${err.message}`);+ lastBuildFailed = true;} finally {isBuilding = false;}if (pendingTypes.size > 0) {+ if (lastBuildFailed) {+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));+ }const nextTypes = pendingTypes;pendingTypes = new Set();await executePendingBuild(nextTypes);diff --git a/build-tools/utils/hash.js b/build-tools/utils/hash.jsindex 5898c32b3..67c46a18c 100644--- a/build-tools/utils/hash.js+++ b/build-tools/utils/hash.js@@ -1,5 +1,5 @@import { createHash } from 'crypto';-import { readFile, writeFile, mkdir, readdir, stat } from 'fs/promises';+import { readFile, writeFile, mkdir, readdir, stat, rename } from 'fs/promises';import path from 'path';import * as logger from './logger.js';@@ -98,7 +98,9 @@ export class HashCache {async save() {try {await mkdir(this.cacheDir, { recursive: true });- await writeFile(this.cacheFile, JSON.stringify(this.cache, null, 2));+ const tmpFile = this.cacheFile + '.tmp';+ await writeFile(tmpFile, JSON.stringify(this.cache, null, 2));+ await rename(tmpFile, this.cacheFile);logger.debug('Cache saved');} catch (err) {logger.warn(`Failed to save cache: ${err.message}`);diff --git a/editor/src/MenuManager.ts b/editor/src/MenuManager.tsindex ebd94cd2e..6cfcbf07f 100644--- a/editor/src/MenuManager.ts+++ b/editor/src/MenuManager.ts@@ -6,6 +6,7 @@ import { icons } from './utils/icons';export class MenuManager {private statusbarInstances_: Array<{ dispose(): void; update?(): void }> = [];private shortcutManager_: ShortcutManager;+ private documentClickHandler_: ((e: MouseEvent) => void) | null = null;constructor() {this.shortcutManager_ = new ShortcutManager();@@ -135,35 +136,12 @@ export class MenuManager {const menubar = container.querySelector('.es-editor-menubar');if (!menubar) return;- let activeMenu: HTMLElement | null = null;+ this.attachMenuTriggers(container);const closeAllMenus = () => {menubar.querySelectorAll('.es-menu').forEach(m => m.classList.remove('es-open'));- activeMenu = null;};- menubar.querySelectorAll('.es-menu-trigger').forEach(trigger => {- trigger.addEventListener('click', (e) => {- e.stopPropagation();- const menu = (trigger as HTMLElement).parentElement!;- const isOpen = menu.classList.contains('es-open');- closeAllMenus();- if (!isOpen) {- menu.classList.add('es-open');- activeMenu = menu;- }- });-- trigger.addEventListener('mouseenter', () => {- if (activeMenu && activeMenu !== trigger.parentElement) {- closeAllMenus();- const menu = (trigger as HTMLElement).parentElement!;- menu.classList.add('es-open');- activeMenu = menu;- }- });- });-menubar.addEventListener('click', (e) => {const target = e.target as HTMLElement;const menuItem = target.closest('.es-menu-item') as HTMLElement;@@ -190,11 +168,20 @@ export class MenuManager {const previewBtn = menubar.querySelector('[data-action="preview"]');previewBtn?.addEventListener('click', () => onPreview());- document.addEventListener('click', (e) => {+ this.removeDocumentClickHandler();+ this.documentClickHandler_ = (e: MouseEvent) => {if (!menubar.contains(e.target as Node)) {closeAllMenus();}- });+ };+ document.addEventListener('click', this.documentClickHandler_);+ }++ removeDocumentClickHandler(): void {+ if (this.documentClickHandler_) {+ document.removeEventListener('click', this.documentClickHandler_);+ this.documentClickHandler_ = null;+ }}updateToolbarState(container: HTMLElement): void {@@ -263,6 +250,7 @@ export class MenuManager {dispose(): void {this.shortcutManager_.detach();+ this.removeDocumentClickHandler();for (const instance of this.statusbarInstances_) {instance.dispose();}diff --git a/editor/src/PanelManager.ts b/editor/src/PanelManager.tsindex dabdf745b..07f41344b 100644--- a/editor/src/PanelManager.ts+++ b/editor/src/PanelManager.ts@@ -76,13 +76,7 @@ export class PanelManager {}parentEl.appendChild(panelContainer);- this.createPanelWithErrorBoundary(desc, panelContainer, store);-- const instance = this.panelInstances_.get(desc.id);- if (instance) {- if (bridge && isBridgeAware(instance)) instance.setBridge(bridge);- if (app && isAppAware(instance)) instance.setApp(app);- }+ this.createPanelWithErrorBoundary(desc, panelContainer, store, bridge, app);}}@@ -90,9 +84,13 @@ export class PanelManager {desc: PanelDescriptor,container: HTMLElement,store: EditorStore,+ bridge?: EditorBridge | null,+ app?: App | null,): void {try {const instance = desc.factory(container, store);+ if (bridge && isBridgeAware(instance)) instance.setBridge(bridge);+ if (app && isAppAware(instance)) instance.setApp(app);this.panelInstances_.set(desc.id, instance);} catch (err) {console.error(`Panel "${desc.id}" failed to initialize:`, err);diff --git a/editor/src/asset/AssetDatabase.ts b/editor/src/asset/AssetDatabase.tsindex 269384461..7ceb7a04f 100644--- a/editor/src/asset/AssetDatabase.ts+++ b/editor/src/asset/AssetDatabase.ts@@ -82,11 +82,7 @@ export class AssetDatabase {// =========================================================================getPath(uuid: string): string | undefined {- const path = this.uuidToEntry_.get(uuid)?.path;- if (!path) {- console.warn(`[AssetDatabase] getPath: UUID "${uuid}" not found (${this.uuidToEntry_.size} entries registered)`);- }- return path;+ return this.uuidToEntry_.get(uuid)?.path;}getUuid(path: string): string | undefined {diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsindex 76f38a2ef..ec5bf20e2 100644--- a/editor/src/builder/ArtifactBuilder.ts+++ b/editor/src/builder/ArtifactBuilder.ts@@ -42,11 +42,21 @@ export async function buildArtifact(progress.setPhase('processing_assets');progress.setCurrentTask('Packing texture atlas...', 0);- const imagePaths = [...assetPaths].filter(p => {+ const imagePathCandidates = [...assetPaths].filter(p => {const ext = p.split('.').pop()?.toLowerCase() ?? '';return ext === 'png' || ext === 'jpg' || ext === 'jpeg';});+ const imagePaths: string[] = [];+ for (const p of imagePathCandidates) {+ const fullPath = isAbsolutePath(p) ? normalizePath(p) : joinPath(projectDir, p);+ if (await fs.exists(fullPath)) {+ imagePaths.push(p);+ } else {+ progress.log('warn', `Image not found, skipping: ${p}`);+ }+ }+const sceneDataList: Array<{ name: string; data: Record<string, unknown> }> = [];for (const scenePath of config.scenes) {const fullPath = isAbsolutePath(scenePath)diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex 591336f98..02b26a008 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -77,6 +77,7 @@ export class SceneViewPanel {private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;+ private static readonly MAX_CACHE_SIZE = 100;private textureCache_: Map<string, HTMLImageElement | null> = new Map();private metadataCache_: Map<string, SliceBorder | null> = new Map();private loadingTextures_: Set<string> = new Set();@@ -368,12 +369,14 @@ export class SceneViewPanel {img.onload = () => {this.loadingTextures_.delete(resolved);+ this.evictCache(this.textureCache_);this.textureCache_.set(resolved, img);this.requestRender();};img.onerror = () => {this.loadingTextures_.delete(resolved);+ this.evictCache(this.textureCache_);this.textureCache_.set(resolved, null);console.warn(`Failed to load texture: ${fullPath}`);};@@ -383,6 +386,15 @@ export class SceneViewPanel {return null;}+ private evictCache<T>(cache: Map<string, T>): void {+ if (cache.size >= SceneViewPanel.MAX_CACHE_SIZE) {+ const firstKey = cache.keys().next().value;+ if (firstKey !== undefined) {+ cache.delete(firstKey);+ }+ }+ }+get canvas(): HTMLCanvasElement {return this.canvas_;}diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex c8b58fa65..5f22967f1 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -129,6 +129,7 @@ export class EditorStore {private worldTransforms_ = new WorldTransformCache();private entityMap_ = new Map<number, EntityData>();+ private prefabLock_: Promise<void> | null = null;private prefabEditingPath_: string | null = null;private savedSceneState_: {scene: SceneData;@@ -673,6 +674,25 @@ export class EditorStore {async instantiatePrefab(prefabPath: string,parentEntity: Entity | null = null+ ): Promise<Entity | null> {+ if (this.prefabLock_) {+ await this.prefabLock_;+ }++ let resolve: () => void;+ this.prefabLock_ = new Promise<void>(r => { resolve = r; });++ try {+ return await this.instantiatePrefabInner(prefabPath, parentEntity);+ } finally {+ this.prefabLock_ = null;+ resolve!();+ }+ }++ private async instantiatePrefabInner(+ prefabPath: string,+ parentEntity: Entity | null): Promise<Entity | null> {const hasNested = await this.prefabHasNested(prefabPath);diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 4cc8e7ea3..d9552d5dd 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -12,6 +12,7 @@ import { inputPlugin } from './input';import { assetPlugin } from './asset';import { prefabsPlugin } from './prefabServer';import { initDrawAPI, shutdownDrawAPI } from './draw';+import { clearDrawCallbacks } from './customDraw';import { initMaterialAPI, shutdownMaterialAPI } from './material';import { initGeometryAPI, shutdownGeometryAPI } from './geometry';import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';@@ -300,6 +301,7 @@ export class App {quit(): void {this.running_ = false;+ clearDrawCallbacks();const shutdowns = [shutdownGLDebugAPI,diff --git a/sdk/src/asset/AsyncCache.ts b/sdk/src/asset/AsyncCache.tsindex a0f42769c..f3f58ecf6 100644--- a/sdk/src/asset/AsyncCache.ts+++ b/sdk/src/asset/AsyncCache.ts@@ -16,7 +16,7 @@ export class AsyncCache<T> {}const existing = this.pending_.get(key);- if (existing) {+ if (existing && !existing.aborted) {return existing.promise;}diff --git a/sdk/src/commands.ts b/sdk/src/commands.tsindex 2490a0c6a..aafd9d3ab 100644--- a/sdk/src/commands.ts+++ b/sdk/src/commands.ts@@ -26,7 +26,7 @@ export function Commands(): CommandsDescriptor {interface SpawnComponentEntry {component: AnyComponentDef;- data: any;+ data: unknown;}interface SpawnCommand {@@ -44,7 +44,7 @@ interface InsertCommand {type: 'insert';entity: Entity;component: AnyComponentDef;- data: any;+ data: unknown;}interface RemoveCommand {@@ -180,7 +180,7 @@ export class CommandsInstance {entityRef.entity = entity;for (const entry of components) {- this.world_.insert(entity, entry.component, entry.data);+ this.world_.insert(entity, entry.component, entry.data as Record<string, unknown>);}}@@ -202,7 +202,7 @@ export class CommandsInstance {const entity = this.world_.spawn();cmd.entityRef.entity = entity;for (const entry of cmd.components) {- this.world_.insert(entity, entry.component, entry.data);+ this.world_.insert(entity, entry.component, entry.data as Record<string, unknown>);}break;}@@ -220,7 +220,7 @@ export class CommandsInstance {console.warn(`[Commands] insert skipped: entity ${cmd.entity} is invalid`);break;}- this.world_.insert(cmd.entity, cmd.component, cmd.data);+ this.world_.insert(cmd.entity, cmd.component, cmd.data as Record<string, unknown>);break;case 'remove':diff --git a/sdk/src/material.ts b/sdk/src/material.tsindex ec50b3c2e..304bc400d 100644--- a/sdk/src/material.ts+++ b/sdk/src/material.ts@@ -82,6 +82,8 @@ export function shutdownMaterialAPI(): void {materials.clear();nextMaterialId = 1;materialCallbackRegistered = false;+ encodedNameCache.clear();+ encoder = null;resourceManager = null;module = null;}diff --git a/sdk/src/prefab.ts b/sdk/src/prefab.tsindex 6fd951098..de8f7050a 100644--- a/sdk/src/prefab.ts+++ b/sdk/src/prefab.ts@@ -112,13 +112,22 @@ export async function instantiatePrefab(// Flatten Nested Prefabs// =============================================================================+const MAX_PREFAB_NESTING_DEPTH = 10;+async function flattenPrefab(prefab: PrefabData,overrides: PrefabOverride[],options: InstantiatePrefabOptions | undefined,startId?: number,visited?: Set<string>,+ depth: number = 0,): Promise<FlattenResult> {+ if (depth > MAX_PREFAB_NESTING_DEPTH) {+ throw new Error(+ `Prefab nesting depth exceeded ${MAX_PREFAB_NESTING_DEPTH}. ` ++ `Check for deep or circular nesting in: ${prefab.name}`,+ );+ }const idMapping = new Map<number, number>();let nextId: number;@@ -166,6 +175,7 @@ async function flattenPrefab(options,nextId,visited,+ depth + 1,);idMapping.set(pe.prefabEntityId, nested.rootId);diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex b010e02ac..b8594f1be 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -24,6 +24,8 @@ export class PreviewPlugin implements Plugin {private app_: App | null = null;private loadPromise_: Promise<void> | null = null;private eventSource_: EventSource | null = null;+ private onMessage_: ((event: MessageEvent) => void) | null = null;+ private onError_: ((event: Event) => void) | null = null;constructor(sceneUrl: string, baseUrl?: string) {this.sceneUrl_ = sceneUrl;@@ -144,22 +146,41 @@ export class PreviewPlugin implements Plugin {}}+ cleanup(): void {+ if (this.eventSource_) {+ if (this.onMessage_) {+ this.eventSource_.removeEventListener('message', this.onMessage_ as EventListener);+ }+ if (this.onError_) {+ this.eventSource_.removeEventListener('error', this.onError_);+ }+ this.eventSource_.close();+ this.eventSource_ = null;+ }+ this.onMessage_ = null;+ this.onError_ = null;+ this.app_ = null;+ }+private setupHotReload(): void {const url = new URL(this.sceneUrl_, window.location.href);const eventsUrl = `${url.protocol}//${url.host}/sse-reload`;this.eventSource_ = new EventSource(eventsUrl);- this.eventSource_.addEventListener('message', async (event) => {+ this.onMessage_ = async (event: MessageEvent) => {if (event.data === 'reload') {console.log('[PreviewPlugin] Reload event received, updating scene...');await this.reloadScene();}- });+ };- this.eventSource_.addEventListener('error', (err) => {+ this.onError_ = (err: Event) => {console.error('[PreviewPlugin] EventSource error:', err);- });+ };++ this.eventSource_.addEventListener('message', this.onMessage_ as EventListener);+ this.eventSource_.addEventListener('error', this.onError_);}private async reloadScene(): Promise<void> {diff --git a/sdk/src/query.ts b/sdk/src/query.tsindex be037cc46..3008471da 100644--- a/sdk/src/query.ts+++ b/sdk/src/query.ts@@ -89,7 +89,7 @@ export type QueryResult<C extends readonly QueryArg[]> = [interface PendingMutation {entity: Entity;component: AnyComponentDef;- data: any;+ data: Record<string, unknown>;}export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<QueryResult<C>> {@@ -97,8 +97,8 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quprivate readonly descriptor_: QueryDescriptor<C>;private readonly actualComponents_: AnyComponentDef[];private readonly allRequired_: AnyComponentDef[];- private readonly result_: any[];- private readonly mutData_: Array<{ component: AnyComponentDef; data: any }>;+ private readonly result_: unknown[];+ private readonly mutData_: Array<{ component: AnyComponentDef; data: Record<string, unknown> }>;constructor(world: World, descriptor: QueryDescriptor<C>) {this.world_ = world;@@ -110,7 +110,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quthis.result_ = new Array(this.actualComponents_.length + 1);this.mutData_ = descriptor._mutIndices.map(idx => ({component: this.actualComponents_[idx],- data: null as any+ data: null as unknown as Record<string, unknown>}));}@@ -159,12 +159,12 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quif (hasMut) {for (let i = 0; i < mutCount; i++) {- mutData[i].data = result[_mutIndices[i] + 1];+ mutData[i].data = result[_mutIndices[i] + 1] as Record<string, unknown>;}prevEntity = entity;}- yield result.slice() as QueryResult<C>;+ yield result as QueryResult<C>;}} finally {this.world_.endIteration();diff --git a/sdk/src/resource.ts b/sdk/src/resource.tsindex e17601107..5962b96a2 100644--- a/sdk/src/resource.ts+++ b/sdk/src/resource.ts@@ -72,6 +72,11 @@ export class ResMutInstance<T> {fn(this.value_);this.setter_(this.value_);}++ /** @internal */+ updateValue(value: T): void {+ this.value_ = value;+ }}// =============================================================================@@ -109,7 +114,7 @@ export class ResourceStorage {getResMut<T>(resource: ResourceDef<T>): ResMutInstance<T> {let instance = this.resMutPool_.get(resource._id) as ResMutInstance<T> | undefined;if (instance) {- (instance as any).value_ = this.get(resource);+ instance.updateValue(this.get(resource));return instance;}instance = new ResMutInstance(diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex 8afae8942..e60c21818 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -130,7 +130,7 @@ export function loadSceneData(world: World, sceneData: SceneData): Map<number, Eif (entityData.visible !== false) {for (const compData of entityData.components) {- loadComponent(world, entity, compData);+ loadComponent(world, entity, compData, entityData.name);}}}@@ -171,7 +171,7 @@ export async function loadSceneWithAssets(if (entityData.visible === false) continue;for (const compData of entityData.components) {- loadComponent(world, entity, compData);+ loadComponent(world, entity, compData, entityData.name);}}@@ -333,7 +333,7 @@ async function preloadSceneAssets(}}-export function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void {+export function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void {if (compData.type === 'UIRect') {const rectData = compData.data as Record<string, unknown>;if (rectData.anchor && !rectData.anchorMin) {@@ -346,7 +346,8 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompoif (comp) {world.insert(entity, comp, compData.data);} else {- console.warn(`Unknown component type: ${compData.type}`);+ const context = entityName ? ` on entity "${entityName}"` : '';+ console.warn(`Unknown component type: ${compData.type}${context}`);}}diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.tsindex 3cb5a19e1..b14ef2746 100644--- a/sdk/src/ui/TextInputPlugin.ts+++ b/sdk/src/ui/TextInputPlugin.ts@@ -13,6 +13,15 @@ import { Res } from '../resource';import { platformCreateCanvas } from '../platform';export class TextInputPlugin implements Plugin {+ private cleanupListeners_: (() => void) | null = null;++ cleanup(): void {+ if (this.cleanupListeners_) {+ this.cleanupListeners_();+ this.cleanupListeners_ = null;+ }+ }+build(app: App): void {registerComponent('TextInput', TextInput);@@ -40,21 +49,21 @@ export class TextInputPlugin implements Plugin {}const textarea = textareaOrNull;- textarea.addEventListener('input', () => {+ const onInput = () => {if (composing || focusedEntity === null) return;syncFromTextarea();- });+ };- textarea.addEventListener('compositionstart', () => {+ const onCompositionStart = () => {composing = true;- });+ };- textarea.addEventListener('compositionend', () => {+ const onCompositionEnd = () => {composing = false;syncFromTextarea();- });+ };- textarea.addEventListener('keydown', (e: KeyboardEvent) => {+ const onKeyDown = (e: KeyboardEvent) => {if (focusedEntity === null) return;if (e.key === 'Escape') {@@ -89,16 +98,31 @@ export class TextInputPlugin implements Plugin {ti.dirty = true;resetCursorBlink();}- });+ };- textarea.addEventListener('blur', () => {+ const onBlur = () => {if (focusedEntity !== null && world.valid(focusedEntity) && world.has(focusedEntity, TextInput)) {const ti = world.get(focusedEntity, TextInput) as TextInputData;ti.focused = false;ti.dirty = true;}focusedEntity = null;- });+ };++ textarea.addEventListener('input', onInput);+ textarea.addEventListener('compositionstart', onCompositionStart);+ textarea.addEventListener('compositionend', onCompositionEnd);+ textarea.addEventListener('keydown', onKeyDown);+ textarea.addEventListener('blur', onBlur);++ this.cleanupListeners_ = () => {+ textarea.removeEventListener('input', onInput);+ textarea.removeEventListener('compositionstart', onCompositionStart);+ textarea.removeEventListener('compositionend', onCompositionEnd);+ textarea.removeEventListener('keydown', onKeyDown);+ textarea.removeEventListener('blur', onBlur);+ textarea.remove();+ };function syncFromTextarea(): void {if (focusedEntity === null || !world.valid(focusedEntity)) return;diff --git a/src/esengine/ESEngine.hpp b/src/esengine/ESEngine.hppindex 8c988e935..c20ff05b4 100644--- a/src/esengine/ESEngine.hpp+++ b/src/esengine/ESEngine.hpp@@ -86,10 +86,9 @@#include <emscripten.h>#define ES_MAIN(AppClass) \extern "C" { \- static AppClass* g_app = nullptr; \EMSCRIPTEN_KEEPALIVE void es_app_init() { \- g_app = new AppClass(); \- g_app->run(); \+ static AppClass app; \+ app.run(); \} \}#elsediff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex a8fe0b94c..5cfd36dcb 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -38,6 +38,8 @@#include <glm/glm.hpp>#include <cstring>+static_assert(sizeof(void*) == 4, "EM_JS pointer passing assumes wasm32 (4-byte pointers)");+namespace esengine {static EngineContext& ctx() { return EngineContext::instance(); }@@ -68,11 +70,12 @@ bool getMaterialData(u32 materialId, u32& shaderId, u32& blendMode) {}u32 uniformBufferPtr = 0;u32 uniformCount = 0;+ auto toPtr = [](auto* p) { return static_cast<int>(reinterpret_cast<uintptr_t>(p)); };callMaterialProvider(materialId,- (int)(uintptr_t)&shaderId,- (int)(uintptr_t)&blendMode,- (int)(uintptr_t)&uniformBufferPtr,- (int)(uintptr_t)&uniformCount);+ toPtr(&shaderId),+ toPtr(&blendMode),+ toPtr(&uniformBufferPtr),+ toPtr(&uniformCount));return shaderId != 0;}@@ -90,11 +93,12 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,u32 uniformBufferPtr = 0;u32 uniformCount = 0;+ auto toPtr = [](auto* p) { return static_cast<int>(reinterpret_cast<uintptr_t>(p)); };callMaterialProvider(materialId,- (int)(uintptr_t)&shaderId,- (int)(uintptr_t)&blendMode,- (int)(uintptr_t)&uniformBufferPtr,- (int)(uintptr_t)&uniformCount);+ toPtr(&shaderId),+ toPtr(&blendMode),+ toPtr(&uniformBufferPtr),+ toPtr(&uniformCount));if (shaderId == 0) return false;