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: critical build pipeline, WeChat runtime, and engine stability issues
esenginec1b0b24f75d2
diff --git a/desktop/src/native-fs.ts b/desktop/src/native-fs.tsindex 1113c7614..dc2553d8d 100644--- a/desktop/src/native-fs.ts+++ b/desktop/src/native-fs.ts@@ -14,6 +14,7 @@ import {readDir,stat,copyFile,+ remove,watch as tauriWatch,} from '@tauri-apps/plugin-fs';import { invoke, convertFileSrc } from '@tauri-apps/api/core';@@ -46,6 +47,7 @@ export interface NativeFS {loadFile(): Promise<{ path: string; content: string } | null>;selectDirectory(): Promise<string | null>;createDirectory(path: string): Promise<boolean>;+ removeDirectory(path: string): Promise<boolean>;exists(path: string): Promise<boolean>;writeFile(path: string, content: string): Promise<boolean>;writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;@@ -140,6 +142,15 @@ export const nativeFS: NativeFS = {}},+ async removeDirectory(path: string) {+ try {+ await remove(path, { recursive: true });+ return true;+ } catch {+ return false;+ }+ },+async exists(path: string) {try {return await exists(path);diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsindex 6a1aef001..47a85a5c2 100644--- a/editor/src/builder/ArtifactBuilder.ts+++ b/editor/src/builder/ArtifactBuilder.ts@@ -10,7 +10,7 @@ import type { NativeFS } from '../types/NativeFS';import { BuildProgressReporter } from './BuildProgress';import { AssetExportConfigService, BuildAssetCollector } from './AssetCollector';import { TextureAtlasPacker } from './TextureAtlas';-import { AssetLibrary, isUUID } from '../asset/AssetLibrary';+import { AssetLibrary, isUUID, getComponentRefFields } from '../asset/AssetLibrary';import { getAssetType, toAddressableType } from '../asset/AssetTypes';import { compileMaterials } from './MaterialCompiler';import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';@@ -66,22 +66,15 @@ export async function buildArtifact(}progress.setCurrentTask('Compiling materials...', 20);- const compiledMaterials = await compileMaterials(fs, projectDir, assetLibrary, config, exportConfig);+ const compiledMaterials = await compileMaterials(fs, projectDir, assetLibrary, assetPaths);progress.log('info', `Compiled ${compiledMaterials.length} material(s)`);progress.setCurrentTask('Processing scenes...', 40);const scenes = new Map<string, Record<string, unknown>>();- for (const scenePath of config.scenes) {- const fullPath = isAbsolutePath(scenePath)- ? normalizePath(scenePath)- : joinPath(projectDir, scenePath);- const content = await fs.readFile(fullPath);- if (content) {- const name = scenePath.replace(/.*\//, '').replace('.esscene', '');- const sceneData = JSON.parse(content);- packer.rewriteSceneData(sceneData, atlasResult, '');- scenes.set(name, sceneData);- }+ for (const { name, data } of sceneDataList) {+ packer.rewriteSceneData(data, atlasResult, '');+ resolveSceneUUIDs(data, assetLibrary);+ scenes.set(name, data);}return {@@ -94,6 +87,52 @@ export async function buildArtifact(};}+function resolveSceneUUIDs(sceneData: Record<string, unknown>, assetLibrary: AssetLibrary): void {+ const entities = sceneData.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ prefab?: { prefabPath?: string };+ }> | undefined;++ if (!entities) return;++ for (const entity of entities) {+ for (const comp of entity.components || []) {+ if (!comp.data) continue;+ const refFields = getComponentRefFields(comp.type);+ if (!refFields) continue;+ for (const field of refFields) {+ const value = comp.data[field];+ if (typeof value === 'string' && isUUID(value)) {+ const path = assetLibrary.getPath(value);+ if (path) {+ comp.data[field] = path;+ }+ }+ }+ }+ if (entity.prefab?.prefabPath && isUUID(entity.prefab.prefabPath)) {+ const path = assetLibrary.getPath(entity.prefab.prefabPath);+ if (path) {+ entity.prefab.prefabPath = path;+ }+ }+ }++ const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;+ if (textureMetadata) {+ const resolved: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(textureMetadata)) {+ if (isUUID(key)) {+ const path = assetLibrary.getPath(key);+ resolved[path ?? key] = value;+ } else {+ resolved[key] = value;+ }+ }+ sceneData.textureMetadata = resolved;+ }+}+// =============================================================================// Shared esbuild utilities// =============================================================================@@ -106,7 +145,10 @@ export async function initializeEsbuild(): Promise<void> {if (esbuildInitialized) return;try {await esbuild.initialize({ wasmURL: getEsbuildWasmURL() });- } catch {+ } catch (e) {+ if (!String(e).includes('already')) {+ throw e;+ }}esbuildInitialized = true;}diff --git a/editor/src/builder/AssetCollector.ts b/editor/src/builder/AssetCollector.tsindex 8aaf90075..e152e529d 100644--- a/editor/src/builder/AssetCollector.ts+++ b/editor/src/builder/AssetCollector.ts@@ -128,11 +128,18 @@ export class AssetReferenceCollector {): Promise<void> {const entities = scene.entities as Array<{components: Array<{ type: string; data: Record<string, unknown> }>;+ prefab?: { prefabPath: string };}> | undefined;if (!entities) return;for (const entity of entities) {+ if (entity.prefab?.prefabPath) {+ const resolved = this.resolveRef(entity.prefab.prefabPath);+ refs.add(resolved);+ await this.collectPrefabRefs(resolved, refs, visited);+ }+for (const comp of entity.components || []) {if (!comp.data) continue;@@ -143,15 +150,7 @@ export class AssetReferenceCollector {if (typeof value !== 'string') continue;const resolved = this.resolveRef(value);-- if (resolved.endsWith('.esmaterial')) {- await this.collectMaterialRefs(resolved, refs, visited);- } else if (resolved.endsWith('.atlas')) {- refs.add(resolved);- await this.collectAtlasTextures(resolved, refs);- } else {- refs.add(resolved);- }+ await this.collectAssetRef(resolved, refs, visited);}}}@@ -165,6 +164,105 @@ export class AssetReferenceCollector {}}+ private async collectAssetRef(+ resolved: string,+ refs: Set<string>,+ visited: Set<string>+ ): Promise<void> {+ if (resolved.endsWith('.esmaterial')) {+ await this.collectMaterialRefs(resolved, refs, visited);+ } else if (resolved.endsWith('.atlas')) {+ refs.add(resolved);+ await this.collectAtlasTextures(resolved, refs);+ } else if (resolved.endsWith('.bmfont') || resolved.endsWith('.fnt')) {+ refs.add(resolved);+ await this.collectFontRefs(resolved, refs);+ } else if (resolved.endsWith('.esprefab')) {+ refs.add(resolved);+ await this.collectPrefabRefs(resolved, refs, visited);+ } else {+ refs.add(resolved);+ }+ }++ private async collectPrefabRefs(+ prefabPath: string,+ refs: Set<string>,+ visited: Set<string>+ ): Promise<void> {+ if (visited.has(prefabPath)) return;+ visited.add(prefabPath);++ const fullPath = isAbsolutePath(prefabPath)+ ? prefabPath+ : joinPath(this.projectDir_, prefabPath);++ const content = await this.fs_.readFile(fullPath);+ if (!content) return;++ try {+ const prefab = JSON.parse(content);+ const entities = prefab.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ nestedPrefab?: { prefabPath: string };+ }> | undefined;++ if (!entities) return;++ for (const entity of entities) {+ if (entity.nestedPrefab?.prefabPath) {+ const resolved = this.resolveRef(entity.nestedPrefab.prefabPath);+ refs.add(resolved);+ await this.collectPrefabRefs(resolved, refs, visited);+ }++ for (const comp of entity.components || []) {+ if (!comp.data) continue;+ const refFields = getComponentRefFields(comp.type);+ if (!refFields) continue;+ for (const field of refFields) {+ const value = comp.data[field];+ if (typeof value !== 'string') continue;+ const resolved = this.resolveRef(value);+ await this.collectAssetRef(resolved, refs, visited);+ }+ }+ }+ } catch {+ // Ignore parse errors+ }+ }++ private async collectFontRefs(fontPath: string, refs: Set<string>): Promise<void> {+ const fullPath = isAbsolutePath(fontPath)+ ? fontPath+ : joinPath(this.projectDir_, fontPath);++ const content = await this.fs_.readFile(fullPath);+ if (!content) return;++ const dir = getDirName(fontPath);++ if (fontPath.endsWith('.bmfont')) {+ try {+ const json = JSON.parse(content);+ if (json.fntFile) {+ const fntPath = dir ? `${dir}/${json.fntFile}` : json.fntFile;+ refs.add(fntPath);+ await this.collectFontRefs(fntPath, refs);+ }+ } catch {+ // Ignore parse errors+ }+ } else {+ const pageMatch = content.match(/file="([^"]+)"/);+ if (pageMatch) {+ const texPath = dir ? `${dir}/${pageMatch[1]}` : pageMatch[1];+ refs.add(texPath);+ }+ }+ }+private async collectMaterialRefs(materialPath: string,refs: Set<string>,diff --git a/editor/src/builder/MaterialCompiler.ts b/editor/src/builder/MaterialCompiler.tsindex 4ea1bac21..67477e731 100644--- a/editor/src/builder/MaterialCompiler.ts+++ b/editor/src/builder/MaterialCompiler.ts@@ -1,8 +1,5 @@import type { NativeFS } from '../types/NativeFS';import type { AssetLibrary } from '../asset/AssetLibrary';-import type { BuildConfig } from '../types/BuildTypes';-import type { AssetExportConfig } from './AssetCollector';-import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';import { joinPath } from '../utils/path';import { parseEsShader, resolveShaderPath } from '../utils/shader';@@ -16,12 +13,9 @@ export async function compileMaterials(fs: NativeFS,projectDir: string,assetLibrary: AssetLibrary,- config: BuildConfig,- exportConfig: AssetExportConfig+ assetPaths: Set<string>): Promise<CompiledMaterial[]> {const results: CompiledMaterial[] = [];- const collector = new BuildAssetCollector(fs, projectDir, assetLibrary);- const assetPaths = await collector.collect(config, exportConfig);for (const relativePath of assetPaths) {if (!relativePath.endsWith('.esmaterial')) continue;diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.tsindex 4a40954f9..d8dad7397 100644--- a/editor/src/builder/PlayableEmitter.ts+++ b/editor/src/builder/PlayableEmitter.ts@@ -284,10 +284,6 @@ ${imports}const compiledMaterialPaths = new Set(artifact.compiledMaterials.map(m => m.relativePath));const allFiles = new Set(artifact.assetPaths);- const assetsDir = joinPath(projectDir, 'assets');- if (await fs.exists(assetsDir)) {- await this.walkDirectory(fs, assetsDir, 'assets', allFiles);- }const pending: Array<Promise<void>> = [];@@ -334,24 +330,6 @@ ${imports}return assets;}- private async walkDirectory(- fs: NativeFS,- absolutePath: string,- relativePath: string,- result: Set<string>- ): Promise<void> {- const entries = await fs.listDirectoryDetailed(absolutePath);- for (const entry of entries) {- const childAbsolute = joinPath(absolutePath, entry.name);- const childRelative = `${relativePath}/${entry.name}`;- if (entry.isDirectory) {- await this.walkDirectory(fs, childAbsolute, childRelative, result);- } else {- result.add(childRelative);- }- }- }-private assembleHTML(wasmSdk: string, gameCode: string, sceneData: string,assets: Map<string, string>,diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.tsindex 8e1fba1ee..4a5217423 100644--- a/editor/src/builder/WeChatEmitter.ts+++ b/editor/src/builder/WeChatEmitter.ts@@ -36,6 +36,9 @@ export class WeChatEmitter implements PlatformEmitter {const outputDir = joinPath(projectDir, settings.outputDir);try {+ if (await fs.exists(outputDir)) {+ await fs.removeDirectory(outputDir);+ }await fs.createDirectory(outputDir);// 1. Generate project.config.jsondiff --git a/editor/src/builder/templates.ts b/editor/src/builder/templates.tsindex ff5da4128..f8d16df48 100644--- a/editor/src/builder/templates.ts+++ b/editor/src/builder/templates.ts@@ -242,6 +242,7 @@ ${physicsInit}}function resolvePath(ref) {var entry = assetIndex[ref];+ if (!entry) console.warn('[ESEngine] Asset not found in manifest:', ref);return entry ? entry.path : ref;}diff --git a/editor/src/types/NativeFS.ts b/editor/src/types/NativeFS.tsindex e84d3d6fb..907bdac74 100644--- a/editor/src/types/NativeFS.ts+++ b/editor/src/types/NativeFS.ts@@ -15,6 +15,7 @@ export interface NativeFS {loadFile(): Promise<{ path: string; content: string } | null>;selectDirectory(): Promise<string | null>;createDirectory(path: string): Promise<boolean>;+ removeDirectory(path: string): Promise<boolean>;exists(path: string): Promise<boolean>;writeFile(path: string, content: string): Promise<boolean>;writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 2703e4908..4d8b9083c 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -234,7 +234,7 @@ export class App {const deltaMs = currentTime - this.lastTime_;this.lastTime_ = currentTime;- const delta = deltaMs / 1000;+ const delta = Math.min(deltaMs / 1000, 0.25);this.updateTime(delta);this.world_.resetQueryPool();@@ -242,11 +242,16 @@ export class App {this.runSchedule(Schedule.First);this.fixedAccumulator_ += delta;- while (this.fixedAccumulator_ >= this.fixedTimestep_) {+ let fixedSteps = 0;+ while (this.fixedAccumulator_ >= this.fixedTimestep_ && fixedSteps < 8) {this.fixedAccumulator_ -= this.fixedTimestep_;this.runSchedule(Schedule.FixedPreUpdate);this.runSchedule(Schedule.FixedUpdate);this.runSchedule(Schedule.FixedPostUpdate);+ fixedSteps++;+ }+ if (fixedSteps >= 8) {+ this.fixedAccumulator_ = 0;}this.runSchedule(Schedule.PreUpdate);@@ -259,12 +264,29 @@ export class App {quit(): void {this.running_ = false;- shutdownGLDebugAPI();- shutdownRendererAPI();- shutdownPostProcessAPI();- shutdownGeometryAPI();- shutdownMaterialAPI();- shutdownDrawAPI();++ const shutdowns = [+ shutdownGLDebugAPI,+ shutdownRendererAPI,+ shutdownPostProcessAPI,+ shutdownGeometryAPI,+ shutdownMaterialAPI,+ shutdownDrawAPI,+ ];+ for (const fn of shutdowns) {+ try { fn(); } catch (e) {+ console.error('[ESEngine] Shutdown error:', e);+ }+ }++ for (const entity of this.world_.getAllEntities()) {+ try { this.world_.despawn(entity); } catch (_) { /* ignore */ }+ }+ this.world_.disconnectCpp();++ this.pipeline_ = null;+ this.runner_ = null;+ this.module_ = null;}// =========================================================================diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex c97523f86..29e7fe8d9 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -206,12 +206,15 @@ export class AssetServer {for (const handle of this.fontCache_.values()) {rm.releaseBitmapFont(handle);}- this.textureCache_.clear();- this.fontCache_.clear();- this.prefabCache_.clear();- this.jsonCache_.clear();- this.textCache_.clear();- this.binaryCache_.clear();+ this.materialLoader_.releaseAll();+ Material.releaseAll();+ this.textureCache_.clearAll();+ this.shaderCache_.clearAll();+ this.fontCache_.clearAll();+ this.prefabCache_.clearAll();+ this.jsonCache_.clearAll();+ this.textCache_.clearAll();+ this.binaryCache_.clearAll();this.loadedSpines_.clear();if (this.spineController_) {for (const handle of this.spineSkeletons_.values()) {diff --git a/sdk/src/asset/AsyncCache.ts b/sdk/src/asset/AsyncCache.tsindex eee6e4e12..a0f42769c 100644--- a/sdk/src/asset/AsyncCache.ts+++ b/sdk/src/asset/AsyncCache.ts@@ -1,8 +1,13 @@const DEFAULT_TIMEOUT = 30000;+interface PendingEntry<T> {+ promise: Promise<T>;+ aborted: boolean;+}+export class AsyncCache<T> {private cache_ = new Map<string, T>();- private pending_ = new Map<string, Promise<T>>();+ private pending_ = new Map<string, PendingEntry<T>>();async getOrLoad(key: string, loader: () => Promise<T>, timeout = DEFAULT_TIMEOUT): Promise<T> {const cached = this.cache_.get(key);@@ -10,33 +15,45 @@ export class AsyncCache<T> {return cached;}- const pending = this.pending_.get(key);- if (pending) {- return pending;+ const existing = this.pending_.get(key);+ if (existing) {+ return existing.promise;}- const promise = loader();- this.pending_.set(key, promise);+ const entry: PendingEntry<T> = { promise: null!, aborted: false };++ entry.promise = (async () => {+ const loaderPromise = loader();- try {const result = await (timeout > 0? Promise.race([- promise,+ loaderPromise,new Promise<never>((_, reject) =>- setTimeout(() => reject(new Error(`AsyncCache timeout: ${key} (${timeout}ms)`)), timeout)+ setTimeout(() => {+ entry.aborted = true;+ reject(new Error(`AsyncCache timeout: ${key} (${timeout}ms)`));+ }, timeout)),])- : promise);- this.cache_.set(key, result);+ : loaderPromise);++ if (!entry.aborted) {+ this.cache_.set(key, result);+ }+ this.pending_.delete(key);return result;+ })();++ this.pending_.set(key, entry);++ try {+ return await entry.promise;} catch (err) {this.pending_.delete(key);if (err instanceof Error && err.message.startsWith('AsyncCache timeout:')) {console.warn(`[AsyncCache] ${err.message}`);}throw err;- } finally {- this.pending_.delete(key);}}@@ -56,6 +73,14 @@ export class AsyncCache<T> {this.cache_.clear();}+ clearAll(): void {+ this.cache_.clear();+ for (const entry of this.pending_.values()) {+ entry.aborted = true;+ }+ this.pending_.clear();+ }+values(): IterableIterator<T> {return this.cache_.values();}diff --git a/sdk/src/material.ts b/sdk/src/material.tsindex d6d662732..ec50b3c2e 100644--- a/sdk/src/material.ts+++ b/sdk/src/material.ts@@ -240,6 +240,10 @@ export const Material = {return materials.has(material);},+ releaseAll(): void {+ materials.clear();+ },+/*** Creates a material from asset data.* @param data Material asset data (properties object)diff --git a/sdk/src/query.ts b/sdk/src/query.tsindex e9e0f5442..eda7741ec 100644--- a/sdk/src/query.ts+++ b/sdk/src/query.ts@@ -159,7 +159,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<QuprevEntity = entity;}- yield result as QueryResult<C>;+ yield result.slice() as QueryResult<C>;}} finally {if (prevEntity !== null && hasMut) {diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex b4fd3277c..8735265d2 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -22,8 +22,8 @@ import { Assets } from './asset/AssetPlugin';export interface RuntimeAssetProvider {loadPixels(ref: string): Promise<{ width: number; height: number; pixels: Uint8Array }>;loadPixelsRaw?(ref: string): Promise<{ width: number; height: number; pixels: Uint8Array }>;- readText(ref: string): string;- readBinary(ref: string): Uint8Array;+ readText(ref: string): string | Promise<string>;+ readBinary(ref: string): Uint8Array | Promise<Uint8Array>;resolvePath(ref: string): string;}@@ -140,18 +140,18 @@ async function loadSpineAssets(const atlasPath = provider.resolvePath(atlasRef);try {- const atlasContent = provider.readText(atlasRef);+ const atlasContent = await provider.readText(atlasRef);const isBinary = skelPath.endsWith('.skel');let skelDataPtr: number;let skelDataLen: number;if (isBinary) {- const bytes = provider.readBinary(skelRef);+ const bytes = await provider.readBinary(skelRef);skelDataLen = bytes.length;skelDataPtr = spineModule._malloc(skelDataLen);spineModule.HEAPU8.set(bytes, skelDataPtr);} else {- const text = provider.readText(skelRef);+ const text = await provider.readText(skelRef);const encoder = new TextEncoder();const bytes = encoder.encode(text);skelDataLen = bytes.length;@@ -344,15 +344,15 @@ async function loadBitmapFonts(let fntDir: string;if (ref.endsWith('.bmfont')) {- const json = JSON.parse(provider.readText(ref));+ const json = JSON.parse(await provider.readText(ref));const fntFile = json.type === 'label-atlas' ? json.generatedFnt : json.fntFile;if (!fntFile) { cache[ref] = 0; continue; }const dir = ref.substring(0, ref.lastIndexOf('/'));const fntRef = dir ? `${dir}/${fntFile}` : fntFile;- fntContent = provider.readText(fntRef);+ fntContent = await provider.readText(fntRef);fntDir = fntRef.substring(0, fntRef.lastIndexOf('/'));} else {- fntContent = provider.readText(ref);+ fntContent = await provider.readText(ref);fntDir = ref.substring(0, ref.lastIndexOf('/'));}@@ -401,10 +401,10 @@ function updateBitmapTextFonts(// Material Helpers// =============================================================================-function loadMaterials(+async function loadMaterials(sceneData: SceneData,provider: RuntimeAssetProvider,-): Record<string, number> {+): Promise<Record<string, number>> {const materialCache: Record<string, number> = {};const shaderCache: Record<string, number> = {};for (const entity of sceneData.entities) {@@ -414,7 +414,7 @@ function loadMaterials(const matRef = comp.data.material as string;if (materialCache[matRef] !== undefined) continue;try {- const matData = JSON.parse(provider.readText(matRef));+ const matData = JSON.parse(await provider.readText(matRef));if (!matData.vertexSource || !matData.fragmentSource) {materialCache[matRef] = 0;continue;@@ -499,7 +499,7 @@ export async function loadRuntimeScene(}const fontCache = await loadBitmapFonts(module, sceneData, provider);- const materialCache = loadMaterials(sceneData, provider);+ const materialCache = await loadMaterials(sceneData, provider);const entityMap = loadSceneData(app.world, sceneData);updateSpriteTextures(app.world, sceneData, textureCache, entityMap);diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex 9de014900..5847e5a39 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -186,6 +186,8 @@ async function preloadSceneAssets(baseUrl: string | undefined,texturePathToUrl: Map<string, string>,): Promise<void> {+ sceneData = JSON.parse(JSON.stringify(sceneData));+const textures = new Set<string>();const materials = new Set<string>();const fonts = new Set<string>();