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
refactor: simplify review fixes
esengine6f32d782a3ec
diff --git a/desktop/src-tauri/src/compiler.rs b/desktop/src-tauri/src/compiler.rsindex 5295e8a7b..68fed6b7f 100644--- a/desktop/src-tauri/src/compiler.rs+++ b/desktop/src-tauri/src/compiler.rs@@ -742,6 +742,7 @@ pub async fn compile_wasm(std::fs::create_dir_all(&build_dir).map_err(|e| e.to_string())?;// Check cache — validate both output existence AND source hash+ let source_hash = compute_source_hash(&engine_src);if !options.clean_build {let wasm_output = if options.target == "playable" {build_dir.join("sdk/esengine.single.js")@@ -750,11 +751,10 @@ pub async fn compile_wasm(};if wasm_output.exists() {- let current_hash = compute_source_hash(&engine_src);let hash_file = build_dir.join(".source_hash");let cached_hash = std::fs::read_to_string(&hash_file).unwrap_or_default();- if current_hash == cached_hash {+ if source_hash == cached_hash {emit_progress(&app, "complete", "Using cached build", 1.0);return Ok(make_result(true, &build_dir, &cache_key, &options));}@@ -902,7 +902,9 @@ pub async fn compile_wasm(// Save source hash for cache invalidationlet hash_file = build_dir.join(".source_hash");- let _ = std::fs::write(&hash_file, compute_source_hash(&engine_src));+ if let Err(e) = std::fs::write(&hash_file, &source_hash) {+ eprintln!("[compiler] Failed to write source hash: {}", e);+ }emit_progress(&app, "complete", "Build complete!", 1.0);diff --git a/editor/src/builder/EmitterUtils.ts b/editor/src/builder/EmitterUtils.tsindex 41ac6c16b..d86c32af1 100644--- a/editor/src/builder/EmitterUtils.ts+++ b/editor/src/builder/EmitterUtils.ts@@ -100,8 +100,7 @@ export async function compileUserScripts(context: BuildContext,options: CompileOptions,): Promise<string> {- const compiler = new ScriptCompiler();- return compiler.compile(fs, projectDir, options.entryContent, {+ return ScriptCompiler.compile(fs, projectDir, options.entryContent, {format: 'iife',sdk: { type: 'loader', load: options.sdkResolver, preferEsmEntry: options.preferEsmEntry ?? true },minify: options.minify,@@ -165,13 +164,12 @@ export async function collectUserScriptImports(fs: NativeFS,projectDir: string,): Promise<{ imports: string; hasSrcDir: boolean }> {- const compiler = new ScriptCompiler();const scriptsPath = joinPath(projectDir, 'src');const hasSrcDir = await fs.exists(scriptsPath);- const plugins = await compiler.discoverPlugins(fs, projectDir, 'main');- const scripts = hasSrcDir ? await compiler.discoverScripts(fs, projectDir) : [];- const imports = compiler.buildEntry(plugins, scripts);+ const plugins = await ScriptCompiler.discoverPlugins(fs, projectDir, 'main');+ const scripts = hasSrcDir ? await ScriptCompiler.discoverScripts(fs, projectDir) : [];+ const imports = ScriptCompiler.buildEntry(plugins, scripts);return { imports, hasSrcDir: hasSrcDir || plugins.length > 0 };}diff --git a/editor/src/scripting/ScriptCompiler.ts b/editor/src/scripting/ScriptCompiler.tsindex 8bf274a65..330679b7e 100644--- a/editor/src/scripting/ScriptCompiler.ts+++ b/editor/src/scripting/ScriptCompiler.ts@@ -17,14 +17,13 @@ import { initializeEsbuild } from '../builder/ArtifactBuilder';export class ScriptCompiler {private ctx_: esbuild.BuildContext | null = null;- private lastEntry_: string | null = null;- private lastTargetKey_: string | null = null;+ private lastOptionsKey_: string | null = null;// =========================================================================- // Script & Plugin Discovery+ // Script & Plugin Discovery (stateless)// =========================================================================- async discoverScripts(fs: NativeFS, projectDir: string): Promise<string[]> {+ static async discoverScripts(fs: NativeFS, projectDir: string): Promise<string[]> {const srcPath = joinPath(projectDir, 'src');try {if (!await fs.exists(srcPath)) return [];@@ -35,7 +34,7 @@ export class ScriptCompiler {}}- async discoverPlugins(+ static async discoverPlugins(fs: NativeFS,projectDir: string,entry: 'main' | 'editor',@@ -48,7 +47,7 @@ export class ScriptCompiler {}}- buildEntry(+ static buildEntry(plugins: DiscoveredPlugin[],scriptPaths: string[],preamble?: string,@@ -68,7 +67,7 @@ export class ScriptCompiler {// One-shot Compilation (Build export path)// =========================================================================- async compile(+ static async compile(fs: NativeFS,projectDir: string,entryContent: string,@@ -76,9 +75,9 @@ export class ScriptCompiler {): Promise<string> {await initializeEsbuild();- const result = await esbuild.build({- ...this.buildOptions_(fs, projectDir, entryContent, target),- });+ const result = await esbuild.build(+ buildOptions(fs, projectDir, entryContent, target),+ );const output = result.outputFiles?.[0]?.text;if (!output) {@@ -99,29 +98,31 @@ export class ScriptCompiler {): Promise<esbuild.BuildResult> {await initializeEsbuild();- const targetKey = this.targetKey_(target);- const entryChanged = entryContent !== this.lastEntry_;- const targetChanged = targetKey !== this.lastTargetKey_;+ const opts = buildOptions(fs, projectDir, entryContent, target);+ const optionsKey = JSON.stringify({+ entry: entryContent,+ format: target.format,+ sdkType: target.sdk.type,+ minify: target.minify,+ sourcemap: target.sourcemap,+ defines: target.defines,+ });- if (this.ctx_ && (entryChanged || targetChanged)) {+ if (this.ctx_ && optionsKey !== this.lastOptionsKey_) {await this.ctx_.dispose();this.ctx_ = null;}if (!this.ctx_) {- this.ctx_ = await esbuild.context({- ...this.buildOptions_(fs, projectDir, entryContent, target),- });- this.lastEntry_ = entryContent;- this.lastTargetKey_ = targetKey;+ this.ctx_ = await esbuild.context(opts);+ this.lastOptionsKey_ = optionsKey;}return this.ctx_.rebuild();}invalidateIncremental(): void {- // Force context recreation on next compileIncremental call- this.lastEntry_ = null;+ this.lastOptionsKey_ = null;}async dispose(): Promise<void> {@@ -129,49 +130,42 @@ export class ScriptCompiler {await this.ctx_.dispose();this.ctx_ = null;}- this.lastEntry_ = null;- this.lastTargetKey_ = null;+ this.lastOptionsKey_ = null;}+}- // =========================================================================- // Private- // =========================================================================-- private buildOptions_(- fs: NativeFS,- projectDir: string,- entryContent: string,- target: CompileTarget,- ): esbuild.BuildOptions {- const preferEsm = target.sdk.type === 'loader'- ? (target.sdk.preferEsmEntry ?? true)- : true;+// =============================================================================+// Private Helper+// =============================================================================- const plugins: esbuild.Plugin[] = [+function buildOptions(+ fs: NativeFS,+ projectDir: string,+ entryContent: string,+ target: CompileTarget,+): esbuild.BuildOptions {+ const preferEsm = target.sdk.type === 'loader'+ ? (target.sdk.preferEsmEntry ?? true)+ : true;++ return {+ stdin: {+ contents: entryContent,+ loader: 'ts',+ resolveDir: joinPath(projectDir, 'src'),+ },+ bundle: true,+ format: target.format,+ write: false,+ platform: 'browser',+ target: 'es2020',+ treeShaking: true,+ sourcemap: target.sourcemap,+ minify: target.minify,+ define: target.defines,+ plugins: [sdkResolvePlugin(target.sdk),virtualFsPlugin({ fs, projectDir, preferEsmEntry: preferEsm }),- ];-- return {- stdin: {- contents: entryContent,- loader: 'ts',- resolveDir: joinPath(projectDir, 'src'),- },- bundle: true,- format: target.format,- write: false,- platform: 'browser',- target: 'es2020',- treeShaking: true,- sourcemap: target.sourcemap,- minify: target.minify,- define: target.defines,- plugins,- };- }-- private targetKey_(target: CompileTarget): string {- return `${target.format}|${target.sdk.type}|${target.minify ?? false}|${target.sourcemap ?? false}`;- }+ ],+ };}diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.tsindex 21bad657d..883cfbc0c 100644--- a/editor/src/scripting/ScriptLoader.ts+++ b/editor/src/scripting/ScriptLoader.ts@@ -72,7 +72,7 @@ export class ScriptLoader {console.warn('ScriptLoader: NativeFS not available');return [];}- return this.compiler_.discoverScripts(fs, this.projectDir_);+ return ScriptCompiler.discoverScripts(fs, this.projectDir_);}async compile(): Promise<boolean> {@@ -101,8 +101,8 @@ export class ScriptLoader {return false;}- const scripts = await this.compiler_.discoverScripts(fs, this.projectDir_);- const plugins = await this.compiler_.discoverPlugins(fs, this.projectDir_, 'main');+ const scripts = await ScriptCompiler.discoverScripts(fs, this.projectDir_);+ const plugins = await ScriptCompiler.discoverPlugins(fs, this.projectDir_, 'main');if (scripts.length === 0 && plugins.length === 0) {this.swapper_.prepare([]);@@ -113,7 +113,7 @@ export class ScriptLoader {}try {- const entryContent = this.compiler_.buildEntry(plugins, scripts);+ const entryContent = ScriptCompiler.buildEntry(plugins, scripts);const result = await this.compiler_.compileIncremental(fs,diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.tsindex 761fad00a..b1f1cc3d3 100644--- a/editor/src/scripting/esbuildPlugins.ts+++ b/editor/src/scripting/esbuildPlugins.ts@@ -161,10 +161,6 @@ export function sdkResolvePlugin(strategy: SdkResolveStrategy): esbuild.Plugin {build.onLoad({ filter: /.*/, namespace: 'esengine-sdk' }, async (args) => {return load(args.path);});-- if (preferEsmEntry !== undefined) {- (build as any).__sdkPreferEsm = preferEsmEntry;- }},};}@@ -187,7 +183,7 @@ export function virtualFsPlugin(options: VirtualFsOptions): esbuild.Plugin {return {name: 'virtual-fs',setup(build) {- const esmPref = (build as any).__sdkPreferEsm ?? preferEsmEntry;+ const esmPref = preferEsmEntry;// -----------------------------------------------------------------// Absolute path resolution (Unix + Windows)@@ -323,18 +319,14 @@ async function resolveExtension(fs: { exists(path: string): Promise<boolean> },basePath: string,): Promise<string> {- const tsPath = basePath + '.ts';- if (await fs.exists(tsPath)) return tsPath;-- const jsPath = basePath + '.js';- if (await fs.exists(jsPath)) return jsPath;-- const indexTsPath = joinPath(basePath, 'index.ts');- if (await fs.exists(indexTsPath)) return indexTsPath;-- const indexJsPath = joinPath(basePath, 'index.js');- if (await fs.exists(indexJsPath)) return indexJsPath;-- return tsPath;+ const candidates = [+ basePath + '.ts',+ basePath + '.js',+ joinPath(basePath, 'index.ts'),+ joinPath(basePath, 'index.js'),+ ];+ const results = await Promise.all(candidates.map(c => fs.exists(c)));+ const idx = results.indexOf(true);+ return idx >= 0 ? candidates[idx] : candidates[0];}