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: comprehensive architecture improvements across engine, SDK, editor, and infra
esengine1cd2a1924630
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 7e37a72f6..4b8fbbe81 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -130,11 +130,11 @@ jobs:- name: Install dependenciesrun: pnpm install- - name: Run SDK tests- run: pnpm --filter esengine test+ - name: Run SDK tests with coverage+ run: pnpm --filter esengine vitest run --coverage --coverage.thresholds.lines=60 --coverage.thresholds.functions=60 --coverage.thresholds.branches=60 --coverage.thresholds.statements=60- name: Build SDKrun: pnpm --filter esengine build- - name: Run Editor tests- run: pnpm --filter @esengine/editor test+ - name: Run Editor tests with coverage+ run: pnpm --filter @esengine/editor vitest run --coverage --coverage.thresholds.lines=60 --coverage.thresholds.functions=60 --coverage.thresholds.branches=60 --coverage.thresholds.statements=60diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex db2c55cde..da2f28fa9 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -12,6 +12,12 @@ export default {sdk: path.resolve(__dirname, '../sdk'),},+ optimization: {+ web: { cmakeOpt: '-O2', wasmOpt: '-O2' },+ wechat: { cmakeOpt: '-O2', wasmOpt: '-O2' },+ playable: { cmakeOpt: '-Oz', wasmOpt: '-Oz' },+ },+wasm: {web: {buildDir: 'build-web',diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 955273858..28bf1fac8 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -57,18 +57,21 @@ programconst wasmTargets = targets.filter(t => t !== 'sdk');const buildSdkFlag = options.target === 'all' || options.target === 'sdk' || wasmTargets.length > 0;+ const noCache = !options.cache;+if (wasmTargets.length > 0) {- await runEht({ noCache: !options.cache });+ await runEht({ noCache });await buildWasmParallel(wasmTargets, {debug: isDebug,clean: options.clean,manifest,continueOnError: options.continueOnError,+ noCache,});}if (buildSdkFlag) {- await buildSdk({ manifest });+ await buildSdk({ manifest, noCache });}if (options.sync) {diff --git a/build-tools/tasks/sdk.js b/build-tools/tasks/sdk.jsindex a5a00afbe..b3487999e 100644--- a/build-tools/tasks/sdk.js+++ b/build-tools/tasks/sdk.js@@ -4,9 +4,10 @@ import { existsSync } from 'fs';import config from '../build.config.js';import * as logger from '../utils/logger.js';import { runCommand } from '../utils/emscripten.js';+import { hashDirectory, HashCache } from '../utils/hash.js';export async function buildSdk(options = {}) {- const { manifest = null } = options;+ const { manifest = null, noCache = false } = options;if (manifest) {manifest.startTarget('sdk');@@ -18,11 +19,48 @@ export async function buildSdk(options = {}) {const sdkDir = config.paths.sdk;const outputDir = path.join(config.paths.output, 'sdk');- await mkdir(outputDir, { recursive: true });-- await runCommand('npm', ['run', 'build'], { cwd: sdkDir });-- await copyDistOutputs(sdkDir, outputDir);+ if (!noCache) {+ const cache = new HashCache(config.paths.cache);+ await cache.load();++ const sdkSrcDir = path.join(sdkDir, 'src');+ const 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,+ };+ 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);++ 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');diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.jsindex d94ec80f7..48aaf3d77 100644--- a/build-tools/tasks/wasm.js+++ b/build-tools/tasks/wasm.js@@ -4,9 +4,30 @@ import { existsSync } from 'fs';import config from '../build.config.js';import * as logger from '../utils/logger.js';import { runCommand, getCpuCount } from '../utils/emscripten.js';+import { hashFiles, hashDirectory, HashCache } from '../utils/hash.js';++async function computeWasmHash(target, targetConfig, debug) {+ const rootDir = config.paths.root;+ const srcDir = path.join(rootDir, 'src/esengine');+ const cmakeLists = path.join(rootDir, 'CMakeLists.txt');++ const sourceHash = await hashDirectory(srcDir, /\.(hpp|cpp|h)$/);++ const buildType = debug ? 'Debug' : 'Release';+ const flagsKey = [...targetConfig.cmakeFlags, `CMAKE_BUILD_TYPE=${buildType}`].join('|');++ const configHash = await hashFiles([cmakeLists]);++ const { createHash } = await import('crypto');+ return createHash('md5')+ .update(sourceHash)+ .update(configHash)+ .update(flagsKey)+ .digest('hex');+}export async function buildWasm(target, options = {}) {- const { debug = false, clean = false, manifest = null } = options;+ const { debug = false, clean = false, manifest = null, noCache = false } = options;const targetConfig = config.wasm[target];if (!targetConfig) {@@ -24,37 +45,36 @@ export async function buildWasm(target, options = {}) {const buildDir = path.join(rootDir, targetConfig.buildDir);const outputDir = config.paths.output;- if (clean && existsSync(buildDir)) {- logger.debug(`Cleaning ${buildDir}`);- await rm(buildDir, { recursive: true, force: true });- }-- await mkdir(buildDir, { recursive: true });-- const buildType = debug ? 'Debug' : 'Release';- const cmakeArgs = [- 'cmake',- ...targetConfig.cmakeFlags,- `-DCMAKE_BUILD_TYPE=${buildType}`,- rootDir,- ];-- logger.debug(`CMake configure: emcmake ${cmakeArgs.join(' ')}`);- await runCommand('emcmake', cmakeArgs, { cwd: buildDir });+ if (!noCache && !clean) {+ const cache = new HashCache(config.paths.cache);+ await cache.load();++ const currentHash = await computeWasmHash(target, targetConfig, debug);+ const cacheKey = `wasm:${target}`;++ if (!await cache.isChanged(cacheKey, currentHash)) {+ logger.success(`WASM ${target}: No changes detected (cached)`);+ const result = {+ target,+ buildDir,+ outputDir,+ outputs: Object.values(targetConfig.outputs),+ skipped: true,+ };+ if (manifest) {+ await manifest.endTarget(`wasm:${target}`, result);+ }+ return result;+ }- const cpuCount = getCpuCount();- const buildArgs = ['--build', '.', '-j', String(cpuCount)];+ await executeWasmBuild(target, targetConfig, { debug, clean, buildDir, rootDir, outputDir });- if (targetConfig.targets && targetConfig.targets.length > 0) {- buildArgs.push('--target', ...targetConfig.targets);+ cache.set(cacheKey, currentHash);+ await cache.save();+ } else {+ await executeWasmBuild(target, targetConfig, { debug, clean, buildDir, rootDir, outputDir });}- logger.debug(`CMake build: cmake ${buildArgs.join(' ')}`);- await runCommand('cmake', buildArgs, { cwd: buildDir });-- await optimizeWasmFiles(buildDir, targetConfig.outputs);- await copyOutputs(buildDir, outputDir, targetConfig.outputs);-logger.success(`WASM ${target}: Build complete`);const result = {@@ -77,7 +97,49 @@ export async function buildWasm(target, options = {}) {}}-async function optimizeWasmFiles(buildDir, outputs) {+async function executeWasmBuild(target, targetConfig, { debug, clean, buildDir, rootDir, outputDir }) {+ if (clean && existsSync(buildDir)) {+ logger.debug(`Cleaning ${buildDir}`);+ await rm(buildDir, { recursive: true, force: true });+ }++ await mkdir(buildDir, { recursive: true });++ const buildType = debug ? 'Debug' : 'Release';+ const optConfig = config.optimization[target];+ const cmakeArgs = [+ 'cmake',+ ...targetConfig.cmakeFlags,+ `-DCMAKE_BUILD_TYPE=${buildType}`,+ ];++ if (!debug && optConfig?.cmakeOpt) {+ cmakeArgs.push(`-DCMAKE_C_FLAGS=${optConfig.cmakeOpt}`);+ cmakeArgs.push(`-DCMAKE_CXX_FLAGS=${optConfig.cmakeOpt}`);+ cmakeArgs.push('-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON');+ }++ cmakeArgs.push(rootDir);++ logger.debug(`CMake configure: emcmake ${cmakeArgs.join(' ')}`);+ await runCommand('emcmake', cmakeArgs, { cwd: buildDir });++ const cpuCount = getCpuCount();+ const buildArgs = ['--build', '.', '-j', String(cpuCount)];++ if (targetConfig.targets && targetConfig.targets.length > 0) {+ buildArgs.push('--target', ...targetConfig.targets);+ }++ logger.debug(`CMake build: cmake ${buildArgs.join(' ')}`);+ await runCommand('cmake', buildArgs, { cwd: buildDir });++ const wasmOptLevel = config.optimization[target]?.wasmOpt || '-O2';+ await optimizeWasmFiles(buildDir, targetConfig.outputs, wasmOptLevel);+ await copyOutputs(buildDir, outputDir, targetConfig.outputs);+}++async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2') {const wasmFiles = Object.keys(outputs).filter(src => src.endsWith('.wasm'));if (wasmFiles.length === 0) return;@@ -87,10 +149,10 @@ async function optimizeWasmFiles(buildDir, outputs) {try {const before = (await stat(wasmPath)).size;- await runCommand('wasm-opt', ['-Oz', '-o', wasmPath, wasmPath], { silent: true });+ await runCommand('wasm-opt', [optLevel, '-o', wasmPath, wasmPath], { silent: true });const after = (await stat(wasmPath)).size;const reduction = ((1 - after / before) * 100).toFixed(1);- logger.debug(`wasm-opt: ${src} ${(before / 1024).toFixed(0)}KB → ${(after / 1024).toFixed(0)}KB (-${reduction}%)`);+ 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;diff --git a/build-tools/tasks/watch.js b/build-tools/tasks/watch.jsindex 3ebef7aef..289f9ed6b 100644--- a/build-tools/tasks/watch.js+++ b/build-tools/tasks/watch.js@@ -18,11 +18,11 @@ export async function startWatch(options = {}) {const rootDir = config.paths.root;let isBuilding = false;- let pendingBuild = null;+ let pendingTypes = new Set();async function rebuild(type, file) {if (isBuilding) {- pendingBuild = { type, file };+ pendingTypes.add(type);return;}@@ -31,28 +31,63 @@ export async function startWatch(options = {}) {logger.info(`File changed: ${relFile}`);try {- if (type === 'component') {+ await executeBuild(type);+ logger.success('Rebuild complete');+ } catch (err) {+ logger.error(`Build failed: ${err.message}`);+ } finally {+ isBuilding = false;+ }++ if (pendingTypes.size > 0) {+ const types = pendingTypes;+ pendingTypes = new Set();+ await executePendingBuild(types);+ }+ }++ async function executeBuild(type) {+ if (type === 'component') {+ await runEht({ noCache: true });+ await buildWasm(target, { debug: true });+ await buildSdk();+ } else if (type === 'cpp') {+ await buildWasm(target, { debug: true });+ } else if (type === 'ts') {+ await buildSdk();+ }+ await syncToDesktop();+ }++ async function executePendingBuild(types) {+ isBuilding = true;+ logger.info(`Processing pending changes: ${[...types].join(', ')}`);++ try {+ if (types.has('component')) {await runEht({ noCache: true });await buildWasm(target, { debug: true });await buildSdk();- } else if (type === 'cpp') {- await buildWasm(target, { debug: true });- } else if (type === 'ts') {- await buildSdk();+ } else {+ if (types.has('cpp')) {+ await buildWasm(target, { debug: true });+ }+ if (types.has('ts')) {+ await buildSdk();+ }}-await syncToDesktop();logger.success('Rebuild complete');} catch (err) {logger.error(`Build failed: ${err.message}`);+ } finally {+ isBuilding = false;}- isBuilding = false;-- if (pendingBuild) {- const pending = pendingBuild;- pendingBuild = null;- await rebuild(pending.type, pending.file);+ if (pendingTypes.size > 0) {+ const nextTypes = pendingTypes;+ pendingTypes = new Set();+ await executePendingBuild(nextTypes);}}diff --git a/build-tools/track-bundle-size.js b/build-tools/track-bundle-size.jsindex bca0edfce..066beb831 100644--- a/build-tools/track-bundle-size.js+++ b/build-tools/track-bundle-size.js@@ -13,6 +13,8 @@ const THRESHOLDS = {'wasm/web/spine42.wasm': 300 * 1024,'wasm/web/spine38.wasm': 300 * 1024,'wasm/web/spine41.wasm': 300 * 1024,+ 'wasm/wechat/esengine.wxgame.wasm': 4 * 1024 * 1024,+ 'wasm/wechat/esengine.wxgame.js': 512 * 1024,'sdk/esm/esengine.js': 150 * 1024,};diff --git a/build-tools/utils/emscripten.js b/build-tools/utils/emscripten.jsindex 8dab4faa7..ec103fca4 100644--- a/build-tools/utils/emscripten.js+++ b/build-tools/utils/emscripten.js@@ -2,13 +2,37 @@ import { spawn } from 'child_process';import os from 'os';import * as logger from './logger.js';+const MIN_EMSCRIPTEN_VERSION = '3.1.51';++function compareVersions(a, b) {+ const pa = a.split('.').map(Number);+ const pb = b.split('.').map(Number);+ for (let i = 0; i < 3; i++) {+ if (pa[i] > pb[i]) return 1;+ if (pa[i] < pb[i]) return -1;+ }+ return 0;+}+export async function checkEmscripten() {try {const result = await runCommand('emcc', ['--version'], { silent: true });const versionMatch = result.stdout.match(/(\d+\.\d+\.\d+)/);- if (versionMatch) {- logger.debug(`Emscripten version: ${versionMatch[1]}`);+ if (!versionMatch) {+ logger.error('Could not determine Emscripten version.');+ return false;}++ const version = versionMatch[1];+ logger.debug(`Emscripten version: ${version}`);++ if (compareVersions(version, MIN_EMSCRIPTEN_VERSION) < 0) {+ logger.error(`Emscripten ${version} is too old. Minimum required: ${MIN_EMSCRIPTEN_VERSION}`);+ logger.info(` Update: emsdk install ${MIN_EMSCRIPTEN_VERSION} && emsdk activate ${MIN_EMSCRIPTEN_VERSION}`);+ logger.info(' Then: source /path/to/emsdk/emsdk_env.sh');+ return false;+ }+return true;} catch {return false;diff --git a/docs/astro/src/content/docs/en/guides/debugging.mdx b/docs/astro/src/content/docs/en/guides/debugging.mdxnew file mode 100644index 000000000..d7e0393da--- /dev/null+++ b/docs/astro/src/content/docs/en/guides/debugging.mdx@@ -0,0 +1,161 @@+---+title: Debugging+description: Debug ESEngine games with source maps, WASM debugging, and performance profiling+---++import { Aside } from '@astrojs/starlight/components';++This guide covers debugging techniques for ESEngine projects, including source maps, WASM debugging, performance profiling, and solutions to common errors.++## Source Maps++### Editor Preview++When previewing in the editor, source maps are enabled by default. Open the browser DevTools in the preview window to set breakpoints and step through your TypeScript code.++### Build Output++For playable ad builds, enable **Dev Build** in the build configuration to include source maps. Production builds strip source maps for smaller file size.++For WeChat MiniGame builds, source maps are generated alongside the output. Enable **Source Maps** in WeChat DevTools settings to use them.++## WASM Debugging++The engine core runs as WebAssembly. WASM debugging requires a debug build of the engine.++### Debug Build++Build the engine in debug mode:++```bash+node build-tools/cli.js build -t web -d+```++This produces an unoptimized WASM binary with DWARF debug info. The binary is significantly larger than a release build.++### Chrome WASM Debugging++1. Install the [C/C++ DevTools Support](https://chrome.google.com/webstore/detail/cc%2B%2B-devtools-support-dwa/pdcpmagijalfljmkmjngeonclgbbannb) Chrome extension+2. Open Chrome DevTools+3. Navigate to the **Sources** panel+4. WASM source files appear under the `file://` tree+5. Set breakpoints in C++ source files and step through code++<Aside type="note">+ WASM debugging is only available in Chromium-based browsers. Firefox and Safari do not support DWARF-based WASM debugging.+</Aside>++### Debug Logging++The engine provides logging macros at different levels. In debug builds, all log levels are active. In release builds, only warnings and errors are emitted.++From the SDK side, use the browser console. The engine forwards C++ log messages to `console.log` / `console.warn` / `console.error` automatically.++## Performance Profiling++### Frame Time++Use the browser Performance panel to record a trace:++1. Open DevTools and go to the **Performance** tab+2. Click **Record**, interact with your game, then stop+3. Examine the flame chart for long frames++Look for:+- **Long system execution** -- a single system taking too much time per frame+- **Asset loading stalls** -- large textures or Spine data blocking the main thread+- **GC pauses** -- frequent garbage collection from excessive allocations++### Draw Call Count++Use the Draw API to monitor render statistics:++```typescript+import { Draw } from 'esengine';++console.log('Draw calls:', Draw.getDrawCallCount());+console.log('Primitives:', Draw.getPrimitiveCount());+```++### ECS Query Performance++If a system with a broad query runs slowly, narrow the query by adding more specific component filters. Queries with fewer matching entities run faster.++```typescript+const narrowSystem = defineSystem(+ [Query(Mut(LocalTransform), Velocity, Player)],+ (query) => {+ for (const [entity, transform, velocity] of query) {+ transform.position.x += velocity.linear.x;+ }+ }+);+```++### Texture Atlas Efficiency++Large numbers of individual textures cause more draw calls. Use the build panel to verify that textures are packed into atlases. Textures that exceed the atlas page size (default 2048x2048) remain as separate draw calls.++## Common Errors++### "WASM module failed to compile"++**Cause**: The WASM binary is corrupted or incompatible with the current browser.++**Fix**:+- Rebuild the WASM binary: `node build-tools/cli.js build -t web -c`+- Verify the Emscripten version matches what the project expects+- Check that the browser supports WebAssembly++### "Entity not found" / Invalid entity access++**Cause**: Accessing an entity that has been despawned, or using a stale entity ID.++**Fix**:+- Check entity existence before access: `if (world.isAlive(entity)) { ... }`+- Avoid storing entity IDs across frames without validation+- Remember that `Commands` are deferred -- entities are not despawned until the end of the schedule stage++### "Component not registered"++**Cause**: Using a component type that has not been defined or imported.++**Fix**:+- Ensure `defineComponent()` or `defineBuiltin()` is called before using the component+- Check that the component module is imported in your entry file+- For builtin components, verify the SDK version matches the WASM binary version++### "WebGL context lost"++**Cause**: The GPU driver reset the WebGL context, usually due to resource exhaustion.++**Fix**:+- Reduce texture memory usage (smaller atlases, compressed textures)+- Reduce the number of active render targets+- On mobile devices, minimize background GPU usage++### Blank or black screen in preview++**Cause**: Multiple possible causes.++**Checklist**:+1. Check DevTools console for errors+2. Verify the scene file exists and is valid JSON+3. Ensure at least one camera entity exists in the scene+4. Check that textures referenced by sprites are loaded (no 404s in Network tab)+5. Verify the WASM binary loaded successfully++### Build output does not match editor preview++**Cause**: Build-time asset processing (atlas packing, material compilation) can surface issues not visible in preview.++**Fix**:+- Compare the DevTools console output between preview and build+- Verify all assets are included (check `asset-manifest.json`)+- For WeChat builds, check that custom file extensions are in `packOptions.include`++## Next Steps++- [Custom Draw](/microes/en/guides/custom-draw/) -- Debug visualization with the Draw API+- [Building & Exporting](/microes/en/guides/building/) -- Build pipeline and configuration+- [Scenes](/microes/en/guides/scenes/) -- Scene loading and managementdiff --git a/docs/astro/src/content/docs/en/guides/wechat.mdx b/docs/astro/src/content/docs/en/guides/wechat.mdxnew file mode 100644index 000000000..eb7fc911d--- /dev/null+++ b/docs/astro/src/content/docs/en/guides/wechat.mdx@@ -0,0 +1,164 @@+---+title: WeChat MiniGame+description: Build and deploy ESEngine games to the WeChat MiniGame platform+---++import { Aside } from '@astrojs/starlight/components';++ESEngine supports building games as WeChat MiniGames. The editor handles the entire build process, producing a project directory that can be opened directly in WeChat DevTools.++## Prerequisites++Before building for WeChat MiniGame, ensure you have:++1. **WeChat DevTools** installed ([download](https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html))+2. A **WeChat MiniGame AppID** (optional for testing -- you can use `touristappid`)++## Building a WeChat MiniGame++### 1. Open the Build Panel++Open the **Build** panel from the editor toolbar and select or create a WeChat MiniGame configuration.++### 2. Configure Settings++| Setting | Description |+|---------|-------------|+| **AppID** | WeChat MiniGame AppID. Use `touristappid` for testing without a registered app. |+| **Version** | Version string (e.g. `1.0.0`) |+| **Orientation** | `Portrait` or `Landscape` |+| **Pack Mode** | `Subpackage` (recommended for most games), `Single` or `Single File` |+| **Output Directory** | Where to write the build output (e.g. `build/wechat`) |++### 3. Add Scenes++Make sure the scenes you want to include are listed in the scene list. Click **Add Current Scene** to add the scene currently open in the editor.++### 4. Click Build++Click **Build** or press `Cmd/Ctrl + B`. The editor will:++1. Collect all assets referenced by scenes+2. Pack textures into atlas pages+3. Compile materials and user scripts+4. Generate `game.js`, `game.json` and `project.config.json`+5. Copy the engine WASM files and SDK+6. Write the complete project to the output directory++Build progress is displayed in real time.++## Opening in WeChat DevTools++After a successful build:++1. Open **WeChat DevTools**+2. Click **Import Project**+3. Navigate to the build output directory (e.g. `build/wechat`)+4. The AppID will auto-fill from `project.config.json`+5. Click **Import**++Your game should load and run in the simulator.++<Aside type="tip">+ After the build completes, click **Open Folder** in the editor build output panel to quickly navigate to the output directory.+</Aside>++## Build Output++The build produces the following directory structure:++```+build/wechat/+ project.config.json # WeChat DevTools project configuration+ game.json # MiniGame manifest (orientation, subpackages, etc.)+ game.js # Entry point (engine init + user scripts)+ esengine.js # WASM engine loader+ esengine.wasm # Engine WASM binary+ sdk.js # ESEngine SDK runtime+ spine.js / spine.wasm # Spine runtime (if Spine is enabled)+ physics.js / physics.wasm # Physics engine (if physics is enabled)+ asset-manifest.json # Addressable asset manifest+ atlas_0.png, ... # Packed texture atlas pages+ scenes/ # Scene JSON files+ assets/ # Game assets (textures, Spine data, etc.)+```++### What `game.js` Does++The generated `game.js` is the MiniGame entry point. It automatically handles all platform-specific initialization:++- Creates a canvas and sets the correct resolution+- Loads the WASM engine using `WXWebAssembly.instantiate()`+- Registers the WebGL context with the engine+- Loads and runs user scripts+- Loads the startup scene and starts the game loop++You should not need to modify `game.js` under normal usage.++## Platform Differences++WeChat MiniGames run in a custom JavaScript runtime that differs from standard browsers:++- **No DOM**: There is no `document` or HTML elements. The canvas is provided by `wx.createCanvas()`.+- **No dynamic execution**: `eval()` and `new Function()` are disabled. The build handles this limitation automatically.+- **Touch input only**: Input comes from the WeChat touch API. The SDK translates it to standard pointer events.+- **Custom file system**: Files are read via `wx.getFileSystemManager()` rather than HTTP fetch.++These differences are handled transparently by the build output. Your game scripts work the same way regardless of the target platform.++## Custom Extension Files++WeChat blocks access to files with unrecognized extensions by default. The build automatically generates the correct `packOptions.include` entries in `project.config.json` for all ESEngine file types (`.esmaterial`, `.esprefab`, `.atlas`, `.skel`, `.fnt`, `.bmfont`).++<Aside type="caution">+ If you add custom asset types with non-standard extensions, you may need to manually add them to `packOptions.include` in the generated `project.config.json`.+</Aside>++## Troubleshooting++### "Permission denied" when reading files++This occurs when WeChat blocks access to files with unrecognized extensions. The build automatically generates `packOptions.include`, but if you have manually added new asset types, verify the extension is listed:++```json+{+ "packOptions": {+ "include": [+ { "type": "suffix", "value": ".yourextension" }+ ]+ }+}+```++### "File not found"++The asset was not included in the build. Ensure one of the following:+- It is referenced by a scene or prefab (automatically included)+- Its folder has export mode set to `always` in the asset export configuration++### WebGL context errors++If you see `Failed to create WebGL context`, make sure the WeChat base library version supports WebGL 2. The build defaults `libVersion` to `3.0.0`, but verify in WeChat DevTools under **Project Settings > Base Library Version**.++### White screen++- Check the WeChat DevTools console for error messages+- Ensure scenes are listed in the build configuration+- Verify the output directory contains all expected files (especially `esengine.wasm` and `sdk.js`)++## Advanced: Customizing `game.js`++For advanced use cases (adding WeChat-specific APIs, analytics, or ad SDKs), you can modify the generated `game.js` after building. Key extension points:++- **Before scene load**: Add initialization code after `SDK.flushPendingSystems(app)` and before scene loading+- **After scene load**: Add code after `SDK.loadRuntimeScene(...)` and before `app.run()`++<Aside type="caution">+ Each build will overwrite your `game.js` modifications. If you need persistent customizations, keep a copy and merge changes after rebuilding.+</Aside>++## Next Steps++- [Building & Exporting](/microes/en/guides/building/) -- Build pipeline overview+- [Playable Ads](/microes/en/guides/playable-ads/) -- Single-file HTML builds for ad networks+- [Asset Loading](/microes/en/guides/assets/) -- Asset loading APIdiff --git a/docs/astro/src/content/docs/zh/guides/debugging.mdx b/docs/astro/src/content/docs/zh/guides/debugging.mdxnew file mode 100644index 000000000..3767808f5--- /dev/null+++ b/docs/astro/src/content/docs/zh/guides/debugging.mdx@@ -0,0 +1,161 @@+---+title: 调试+description: 使用 source maps、WASM 调试和性能分析调试 ESEngine 游戏+---++import { Aside } from '@astrojs/starlight/components';++本指南介绍 ESEngine 项目的调试技巧,包括 source maps、WASM 调试、性能分析以及常见错误的解决方案。++## Source Maps++### 编辑器预览++在编辑器中预览时,source maps 默认启用。在预览窗口中打开浏览器 DevTools 即可设置断点并逐步执行 TypeScript 代码。++### 构建产物++对于可玩广告构建,在构建配置中启用**开发构建**以包含 source maps。生产构建会移除 source maps 以减小文件体积。++对于微信小游戏构建,source maps 会生成在输出目录中。在微信开发者工具设置中启用 **Source Maps** 即可使用。++## WASM 调试++引擎核心以 WebAssembly 运行。WASM 调试需要引擎的 debug 构建。++### Debug 构建++以 debug 模式构建引擎:++```bash+node build-tools/cli.js build -t web -d+```++这会生成一个包含 DWARF 调试信息的未优化 WASM 二进制文件。该文件会比 release 构建大很多。++### Chrome WASM 调试++1. 安装 [C/C++ DevTools Support](https://chrome.google.com/webstore/detail/cc%2B%2B-devtools-support-dwa/pdcpmagijalfljmkmjngeonclgbbannb) Chrome 扩展+2. 打开 Chrome DevTools+3. 导航到 **Sources** 面板+4. WASM 源文件会出现在 `file://` 树下+5. 在 C++ 源文件中设置断点并逐步执行代码++<Aside type="note">+ WASM 调试仅在基于 Chromium 的浏览器中可用。Firefox 和 Safari 不支持基于 DWARF 的 WASM 调试。+</Aside>++### 调试日志++引擎提供了不同级别的日志宏。在 debug 构建中所有日志级别都会输出。在 release 构建中仅输出警告和错误。++在 SDK 端,使用浏览器控制台。引擎会自动将 C++ 日志消息转发到 `console.log` / `console.warn` / `console.error`。++## 性能分析++### 帧时间++使用浏览器 Performance 面板录制跟踪:++1. 打开 DevTools 并转到 **Performance** 标签+2. 点击 **Record**,与游戏交互,然后停止+3. 检查火焰图中的长帧++重点关注:+- **系统执行时间过长** -- 单个系统每帧耗时过多+- **资源加载阻塞** -- 大纹理或 Spine 数据阻塞主线程+- **GC 暂停** -- 大量分配导致频繁垃圾回收++### Draw Call 计数++使用 Draw API 监控渲染统计:++```typescript+import { Draw } from 'esengine';++console.log('Draw calls:', Draw.getDrawCallCount());+console.log('Primitives:', Draw.getPrimitiveCount());+```++### ECS 查询性能++如果一个查询范围较广的系统运行缓慢,通过添加更具体的组件过滤器来缩小查询范围。匹配实体更少的查询执行更快。++```typescript+const narrowSystem = defineSystem(+ [Query(Mut(LocalTransform), Velocity, Player)],+ (query) => {+ for (const [entity, transform, velocity] of query) {+ transform.position.x += velocity.linear.x;+ }+ }+);+```++### 纹理图集效率++大量独立纹理会导致更多 draw call。使用构建面板验证纹理是否被打包到图集中。超过图集页大小(默认 2048x2048)的纹理会作为单独的 draw call。++## 常见错误++### "WASM module failed to compile"++**原因**: WASM 二进制文件损坏或与当前浏览器不兼容。++**解决**:+- 重新构建 WASM 二进制文件:`node build-tools/cli.js build -t web -c`+- 验证 Emscripten 版本与项目预期一致+- 检查浏览器是否支持 WebAssembly++### "Entity not found" / 无效实体访问++**原因**: 访问已被销毁的实体,或使用了过期的实体 ID。++**解决**:+- 访问前检查实体是否存在:`if (world.isAlive(entity)) { ... }`+- 避免跨帧存储实体 ID 而不进行验证+- 记住 `Commands` 是延迟执行的 -- 实体不会在调度阶段结束前被销毁++### "Component not registered"++**原因**: 使用了未定义或未导入的组件类型。++**解决**:+- 确保在使用组件前调用了 `defineComponent()` 或 `defineBuiltin()`+- 检查组件模块是否在入口文件中导入+- 对于内置组件,验证 SDK 版本与 WASM 二进制版本匹配++### "WebGL context lost"++**原因**: GPU 驱动重置了 WebGL 上下文,通常由资源耗尽引起。++**解决**:+- 减少纹理内存使用(更小的图集、压缩纹理)+- 减少活跃的渲染目标数量+- 在移动设备上,最小化后台 GPU 使用++### 预览中显示空白或黑屏++**原因**: 可能有多种原因。++**排查清单**:+1. 检查 DevTools 控制台的错误信息+2. 验证场景文件存在且是有效的 JSON+3. 确保场景中至少存在一个相机实体+4. 检查精灵引用的纹理是否已加载(Network 标签中无 404)+5. 验证 WASM 二进制文件已成功加载++### 构建产物与编辑器预览不一致++**原因**: 构建时的资源处理(图集打包、材质编译)可能暴露预览中不可见的问题。++**解决**:+- 对比预览和构建的 DevTools 控制台输出+- 验证所有资源都已包含(检查 `asset-manifest.json`)+- 对于微信构建,检查自定义文件扩展名是否在 `packOptions.include` 中++## 下一步++- [自定义绘制](/microes/zh/guides/custom-draw/) -- 使用 Draw API 进行调试可视化+- [构建与导出](/microes/zh/guides/building/) -- 构建流水线和配置+- [场景](/microes/zh/guides/scenes/) -- 场景加载和管理diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex fb9e4af2b..b2bdac84b 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -1,8 +1,3 @@-/**- * @file Editor.ts- * @brief Main editor component- */-import type { App, Entity } from 'esengine';import type { EntityData } from './types/SceneTypes';import * as esengine from 'esengine';@@ -14,24 +9,14 @@ import {} from 'esengine';import { EditorStore } from './store/EditorStore';import { EditorBridge } from './bridge/EditorBridge';-import type { PanelInstance, PanelPosition } from './panels/PanelRegistry';+import { PanelManager } from './PanelManager';+import { MenuManager } from './MenuManager';+import { PreviewManager } from './PreviewManager';import {registerPanel,- getAllPanels,getPanelsByPosition,- isResizable,- isBridgeAware,- isAppAware,- isAssetServerProvider,- isAssetNavigable,- isOutputAppendable,- isSpineControllerAware,- isSpineInfoProvider,- lockBuiltinPanels,- clearExtensionPanels,isBuiltinPanel,} from './panels/PanelRegistry';-import { SpineModuleController, wrapSpineModule, type SpineWasmModule } from 'esengine/spine';import { registerBuiltinPanels } from './panels/builtinPanels';import { registerBuiltinEditors } from './property/editors';import { registerMaterialEditors } from './property/materialEditors';@@ -41,20 +26,21 @@ import { initBoundsProviders, registerBoundsProvider, lockBuiltinBoundsProvidersimport { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from './io/SceneSerializer';import { icons } from './utils/icons';import { ScriptLoader } from './scripting';-import { PreviewService } from './preview';import { showBuildSettingsDialog, BuildService } from './builder';import { AddressablePanel } from './panels/AddressablePanel';import { getGlobalPathResolver } from './asset';import type { EditorAssetServer } from './asset/EditorAssetServer';import { getAssetLibrary } from './asset/AssetLibrary';import { setEditorInstance, getEditorContext, getEditorInstance } from './context/EditorContext';-import { getAllMenus, getMenuItems, getAllStatusbarItems, registerBuiltinMenus } from './menus';-import { ShortcutManager } from './menus/ShortcutManager';+import { registerBuiltinMenus } from './menus';import { registerBuiltinGizmos, registerGizmo, lockBuiltinGizmos, clearExtensionGizmos } from './gizmos';import { registerBuiltinStatusbarItems } from './menus/builtinStatusbar';import { ExtensionLoader } from './extension';import { setEditorAPI, clearEditorAPI } from './extension/editorAPI';-import { registerMenu, registerMenuItem, registerStatusbarItem, lockBuiltinMenus, clearExtensionMenus } from './menus/MenuRegistry';+import {+ registerMenu, registerMenuItem, registerStatusbarItem,+ lockBuiltinMenus, clearExtensionMenus,+} from './menus/MenuRegistry';import { registerPropertyEditor } from './property';import { registerComponentSchema } from './schemas';import { showToast, showSuccessToast, showErrorToast } from './ui/Toast';@@ -85,19 +71,14 @@ import {import { loadProjectConfig, loadEditorLocalSettings, saveEditorLocalSetting } from './launcher/ProjectService';import type { SpineVersion } from './types/ProjectTypes';import { Splitter } from './ui/Splitter';--// =============================================================================-// Types-// =============================================================================+import {+ lockBuiltinPanels, clearExtensionPanels,+} from './panels/PanelRegistry';export interface EditorOptions {projectPath?: string;}-// =============================================================================-// Editor-// =============================================================================-export class Editor {private container_: HTMLElement;private app_: App | null = null;@@ -108,15 +89,14 @@ export class Editor {private bridge_: EditorBridge | null = null;private projectPath_: string | null = null;- private panelInstances_ = new Map<string, PanelInstance>();- private statusbarInstances_: Array<{ dispose(): void; update?(): void }> = [];+ private panelManager_: PanelManager;+ private menuManager_: MenuManager;+ private previewManager_: PreviewManager;+private baseAPI_: Record<string, unknown> | null = null;private scriptLoader_: ScriptLoader | null = null;private extensionLoader_: ExtensionLoader | null = null;private splitters_: Splitter[] = [];- private previewService_: PreviewService | null = null;- private shortcutManager_: ShortcutManager;- private activeBottomPanelId_: string | null = 'content-browser';private assetLibraryReady_: Promise<void> = Promise.resolve();private clipboard_: EntityData[] | null = null;private addressableWindow_: { element: HTMLElement; panel: AddressablePanel; keyHandler: (e: KeyboardEvent) => void } | null = null;@@ -125,7 +105,10 @@ export class Editor {this.container_ = container;this.store_ = new EditorStore();this.projectPath_ = options?.projectPath ?? null;- this.shortcutManager_ = new ShortcutManager();++ this.panelManager_ = new PanelManager();+ this.menuManager_ = new MenuManager();+ this.previewManager_ = new PreviewManager(this.projectPath_);installGlobalErrorHandler();@@ -161,16 +144,15 @@ export class Editor {this.setupLayout();registerBuiltinStatusbarItems(this);- this.instantiateStatusbar();- this.setupMenuShortcuts();- this.shortcutManager_.attach();+ this.menuManager_.instantiateStatusbar(this.container_);+ this.menuManager_.setupMenuShortcuts();+ this.menuManager_.attach();if (this.projectPath_) {this.setupEditorGlobals();this.assetLibraryReady_ = this.initializeAssetLibrary();this.initializeAllScripts();this.syncProjectSettings();- this.previewService_ = new PreviewService({ projectPath: this.projectPath_ });this.restoreLastScene();}}@@ -184,31 +166,19 @@ export class Editor {}get activeBottomPanelId(): string | null {- return this.activeBottomPanelId_;+ return this.panelManager_.activeBottomPanelId;}setApp(app: App): void {this.app_ = app;this.bridge_ = new EditorBridge(app, this.store_);-- for (const panel of this.panelInstances_.values()) {- if (isBridgeAware(panel)) panel.setBridge(this.bridge_);- if (isAppAware(panel)) panel.setApp(app);- }+ this.panelManager_.setApp(app, this.bridge_);}setSpineModule(module: unknown, version: string): void {this.spineModule_ = module;this.spineVersion_ = version;-- const raw = module as SpineWasmModule;- const controller = module ? new SpineModuleController(raw, wrapSpineModule(raw)) : null;- for (const panel of this.panelInstances_.values()) {- if (isSpineControllerAware(panel)) {- panel.setSpineController(controller);- }- }-+ this.panelManager_.setSpineModule(module);this.store_.notifyChange();}@@ -229,28 +199,15 @@ export class Editor {}get assetServer(): EditorAssetServer | null {- for (const panel of this.panelInstances_.values()) {- if (isAssetServerProvider(panel)) return panel.assetServer as EditorAssetServer;- }- return null;+ return this.panelManager_.assetServer;}getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {- for (const panel of this.panelInstances_.values()) {- if (isSpineInfoProvider(panel)) {- return panel.getSpineSkeletonInfo(entityId);- }- }- return null;+ return this.panelManager_.getSpineSkeletonInfo(entityId);}onSpineInstanceReady(listener: (entityId: number) => void): () => void {- for (const panel of this.panelInstances_.values()) {- if (isSpineInfoProvider(panel)) {- return panel.onSpineInstanceReady(listener);- }- }- return () => {};+ return this.panelManager_.onSpineInstanceReady(listener);}// =========================================================================@@ -258,33 +215,20 @@ export class Editor {// =========================================================================showPanel(id: string): void {- this.panelInstances_.get(id)?.onShow?.();+ this.panelManager_.showPanel(id);}hidePanel(id: string): void {- this.panelInstances_.get(id)?.onHide?.();+ this.panelManager_.hidePanel(id);}togglePanel(id: string): void {- const panel = this.panelInstances_.get(id);- if (!panel) return;- panel.onShow?.();+ this.panelManager_.togglePanel(id);}toggleBottomPanel(id: string): void {- const prev = this.activeBottomPanelId_;- if (prev === id) {- this.activeBottomPanelId_ = null;- } else {- this.activeBottomPanelId_ = id;- }- this.updateBottomPanelVisibility();- if (prev && prev !== id) {- this.panelInstances_.get(prev)?.onHide?.();- }- if (this.activeBottomPanelId_) {- this.panelInstances_.get(this.activeBottomPanelId_)?.onShow?.();- }+ this.panelManager_.toggleBottomPanel(id, this.container_);+ this.menuManager_.updateStatusbar();}// =========================================================================@@ -310,7 +254,7 @@ export class Editor {const success = await saveSceneToPath(this.store_.scene, filePath);if (success) {this.store_.markSaved();- this.refreshPreviewFiles();+ this.previewManager_.refreshFiles(this.store_.scene, this.scriptLoader_, this.spineVersion_);return;}}@@ -318,7 +262,7 @@ export class Editor {const savedPath = await saveSceneToFile(this.store_.scene);if (savedPath) {this.store_.markSaved(savedPath);- this.refreshPreviewFiles();+ this.previewManager_.refreshFiles(this.store_.scene, this.scriptLoader_, this.spineVersion_);}}@@ -673,7 +617,7 @@ export class Editor {const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');showErrorToast('Script compile failed', msg);for (const e of errors) {- this.appendOutput(`${e.file}:${e.line}:${e.column} - ${e.message}`, 'error');+ this.panelManager_.appendOutput(`${e.file}:${e.line}:${e.column} - ${e.message}`, 'error');}},onCompileSuccess: () => {@@ -774,12 +718,7 @@ export class Editor {}private cleanupExtensionUI(): void {- for (const [id, instance] of this.panelInstances_) {- if (isBuiltinPanel(id)) continue;- instance.dispose();- this.panelInstances_.delete(id);- this.container_.querySelector(`[data-panel-id="${id}"]`)?.remove();- }+ this.panelManager_.cleanupExtensionPanels(this.container_);this.container_.querySelectorAll('[data-statusbar-id^="toggle-"]').forEach(el => {const panelId = el.getAttribute('data-statusbar-id')?.replace('toggle-', '');@@ -798,125 +737,15 @@ export class Editor {}private applyExtensionUI(): void {- this.instantiateExtensionPanels();- this.addExtensionBottomPanelToggles();- this.rebuildMenuBar();- }-- private addExtensionBottomPanelToggles(): void {- const leftContainer = this.container_.querySelector('.es-statusbar-left');- if (!leftContainer) return;-- for (const panel of getPanelsByPosition('bottom')) {- if (leftContainer.querySelector(`[data-statusbar-id="toggle-${panel.id}"]`)) continue;-- const item = {- id: `toggle-${panel.id}`,- position: 'left' as const,- render: (container: HTMLElement) => {- const btn = document.createElement('button');- btn.className = 'es-statusbar-btn';- btn.dataset.bottomPanel = panel.id;- btn.innerHTML = `${panel.icon ?? ''}<span>${panel.title}</span>`;- btn.addEventListener('click', () => this.toggleBottomPanel(panel.id));- container.appendChild(btn);- return {- dispose() { btn.remove(); },- update: () => {- btn.classList.toggle('es-active', this.activeBottomPanelId_ === panel.id);- },- };- },- };-- const span = document.createElement('span');- span.dataset.statusbarId = item.id;-- const cmdInputItem = leftContainer.querySelector('[data-statusbar-id="cmd-input"]');- if (cmdInputItem) {- leftContainer.insertBefore(span, cmdInputItem);- } else {- leftContainer.appendChild(span);- }-- const instance = item.render(span);- this.statusbarInstances_.push(instance);- }- }-- private instantiateExtensionPanels(): void {- for (const desc of getAllPanels()) {- if (this.panelInstances_.has(desc.id)) continue;-- const position = desc.position ?? 'bottom';- let parentEl: HTMLElement | null = null;-- if (position === 'bottom') {- parentEl = this.container_.querySelector('.es-editor-bottom');- } else {- parentEl = this.container_.querySelector(`.es-editor-${position}`);- }- if (!parentEl) continue;-- const container = document.createElement('div');- container.className = 'es-panel-container';- container.dataset.panelId = desc.id;-- if (position === 'bottom') {- container.style.display = 'none';- }-- parentEl.appendChild(container);- const instance = desc.factory(container, this.store_);- this.panelInstances_.set(desc.id, instance);-- if (this.bridge_ && isBridgeAware(instance)) instance.setBridge(this.bridge_);- if (this.app_ && isAppAware(instance)) instance.setApp(this.app_);- }- }-- private rebuildMenuBar(): void {- const menubar = this.container_.querySelector('.es-editor-menubar');- if (!menubar) return;-- menubar.querySelectorAll('.es-menu').forEach(el => el.remove());-- const spacer = menubar.querySelector('.es-menubar-spacer');- if (!spacer) return;-- const fragment = document.createRange().createContextualFragment(this.buildMenuBarHTML());- menubar.insertBefore(fragment, spacer);-- this.attachMenuTriggers();- }-- private attachMenuTriggers(): void {- const menubar = this.container_.querySelector('.es-editor-menubar');- if (!menubar) return;-- menubar.querySelectorAll('.es-menu-trigger').forEach(trigger => {- if ((trigger as any).__menuBound) return;- (trigger as any).__menuBound = true;-- trigger.addEventListener('click', (e) => {- e.stopPropagation();- const menu = (trigger as HTMLElement).parentElement!;- const isOpen = menu.classList.contains('es-open');- menubar.querySelectorAll('.es-menu').forEach(m => m.classList.remove('es-open'));- if (!isOpen) {- menu.classList.add('es-open');- }- });-- trigger.addEventListener('mouseenter', () => {- const hasOpen = menubar.querySelector('.es-menu.es-open');- if (hasOpen && hasOpen !== trigger.parentElement) {- menubar.querySelectorAll('.es-menu').forEach(m => m.classList.remove('es-open'));- const menu = (trigger as HTMLElement).parentElement!;- menu.classList.add('es-open');- }- });- });+ this.panelManager_.instantiateExtensionPanels(+ this.container_, this.store_, this.bridge_, this.app_,+ );+ this.menuManager_.addExtensionBottomPanelToggles(+ this.container_,+ this.panelManager_.activeBottomPanelId,+ (id) => this.toggleBottomPanel(id),+ );+ this.menuManager_.rebuildMenuBar(this.container_);}async reloadExtensions(): Promise<boolean> {@@ -936,55 +765,17 @@ export class Editor {// =========================================================================async startPreview(): Promise<void> {- if (!this.previewService_) {- console.warn('Preview not available: no project loaded');- return;- }-- try {- if (this.scriptLoader_) {- await this.scriptLoader_.compile();- }- const compiledScript = this.scriptLoader_?.getCompiledCode() ?? undefined;- const enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;- const physicsConfig = enablePhysics ? {- gravityX: getSettingsValue<number>('physics.gravityX') ?? 0,- gravityY: getSettingsValue<number>('physics.gravityY') ?? -9.81,- fixedTimestep: getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60,- subStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,- } : undefined;- const previewSpineVersion = this.spineVersion_ === 'none' ? undefined : this.spineVersion_;- await this.previewService_.startPreview(this.store_.scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig);- } catch (err) {- console.error('Failed to start preview:', err);- }+ await this.previewManager_.startPreview(+ this.store_.scene, this.scriptLoader_, this.spineVersion_,+ );}async stopPreview(): Promise<void> {- await this.previewService_?.stopPreview();- }-- private refreshPreviewFiles(): void {- if (!this.previewService_) return;- const compiledScript = this.scriptLoader_?.getCompiledCode() ?? undefined;- const enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;- const physicsConfig = enablePhysics ? {- gravityX: getSettingsValue<number>('physics.gravityX') ?? 0,- gravityY: getSettingsValue<number>('physics.gravityY') ?? -9.81,- fixedTimestep: getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60,- subStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,- } : undefined;- const spineVersion = this.spineVersion_ === 'none' ? undefined : this.spineVersion_;- this.previewService_.updatePreviewFiles(this.store_.scene, compiledScript, spineVersion, enablePhysics, physicsConfig);+ await this.previewManager_.stopPreview();}async navigateToAsset(assetPath: string): Promise<void> {- for (const panel of this.panelInstances_.values()) {- if (isAssetNavigable(panel)) {- await panel.navigateToAsset(assetPath);- return;- }- }+ await this.panelManager_.navigateToAsset(assetPath);}// =========================================================================@@ -997,39 +788,39 @@ export class Editor {private async executeShellCommand(fullCommand: string): Promise<void> {if (!this.projectPath_) {- this.appendOutput('Error: No project loaded\n', 'error');+ this.panelManager_.appendOutput('Error: No project loaded\n', 'error');return;}const shell = getEditorContext().shell;if (!shell) {- this.appendOutput('Error: Shell not available\n', 'error');+ this.panelManager_.appendOutput('Error: Shell not available\n', 'error');return;}const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');- this.activeBottomPanelId_ = 'output';- this.updateBottomPanelVisibility();+ this.panelManager_.showBottomPanel('output', this.container_);+ this.menuManager_.updateStatusbar();const parts = fullCommand.split(/\s+/);const cmd = parts[0];const args = parts.slice(1);- this.appendOutput(`> ${fullCommand}\n`, 'command');+ this.panelManager_.appendOutput(`> ${fullCommand}\n`, 'command');try {const result = await shell.execute(cmd, args, projectDir, (stream: string, data: string) => {- this.appendOutput(data + '\n', stream === 'stderr' ? 'stderr' : 'stdout');+ this.panelManager_.appendOutput(data + '\n', stream === 'stderr' ? 'stderr' : 'stdout');});if (result.code !== 0) {- this.appendOutput(`Process exited with code ${result.code}\n`, 'error');+ this.panelManager_.appendOutput(`Process exited with code ${result.code}\n`, 'error');} else {- this.appendOutput(`Done.\n`, 'success');+ this.panelManager_.appendOutput(`Done.\n`, 'success');}} catch (err) {- this.appendOutput(`Error: ${err}\n`, 'error');+ this.panelManager_.appendOutput(`Error: ${err}\n`, 'error');}}@@ -1076,7 +867,7 @@ export class Editor {if (stack) {text += '\n' + stack;}- this.appendOutput(text + '\n', type);+ this.panelManager_.appendOutput(text + '\n', type);};console.log = (...args) => { original.log(...args); forward('stdout', args); };@@ -1085,13 +876,6 @@ export class Editor {console.error = (...args) => { original.error(...args); forward('error', args, cleanStack(new Error().stack)); };}- private appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {- const outputPanel = this.panelInstances_.get('output');- if (outputPanel && isOutputAppendable(outputPanel)) {- outputPanel.appendOutput(text, type);- }- }-// =========================================================================// Layout// =========================================================================@@ -1101,26 +885,26 @@ export class Editor {this.container_.innerHTML = `<div class="es-editor-menubar"><div class="es-menubar-logo">${icons.logo(24)}</div>- ${this.buildMenuBarHTML()}+ ${this.menuManager_.buildMenuBarHTML()}<div class="es-menubar-spacer"><span class="es-menubar-scene-name"></span></div><button class="es-btn es-btn-preview" data-action="preview">${icons.play(14)} Preview</button></div><div class="es-editor-tabs">- ${this.buildTabBarHTML()}+ ${this.panelManager_.buildTabBarHTML()}</div><div class="es-editor-body">- ${this.buildMainPanelsHTML()}+ ${this.panelManager_.buildMainPanelsHTML()}<div class="es-editor-bottom">- ${this.buildBottomPanelsHTML()}+ ${this.panelManager_.buildBottomPanelsHTML()}</div></div>- ${this.buildStatusBarHTML()}+ ${this.menuManager_.buildStatusBarHTML()}`;- this.instantiatePanels();- this.updateBottomPanelVisibility();+ this.panelManager_.instantiatePanels(this.container_, this.store_);+ this.panelManager_.updateBottomPanelVisibility(this.container_);this.setupSplitters();setEditorInstance(this);@@ -1134,9 +918,12 @@ export class Editor {e.preventDefault();});- this.setupToolbarEvents();- this.store_.subscribe(() => this.updateToolbarState());- this.store_.subscribe(() => this.updateStatusbar());+ this.menuManager_.setupToolbarEvents(this.container_, () => this.startPreview());+ this.store_.subscribe(() => this.menuManager_.updateToolbarState(this.container_));+ this.store_.subscribe(() => {+ this.menuManager_.updateStatusbar();+ this.updateSceneNameDisplay();+ });this.installConsoleCapture();}@@ -1190,223 +977,6 @@ export class Editor {localStorage.setItem(`esengine.editor.${key}`, String(value));}- private buildTabBarHTML(): string {- const positions: PanelPosition[] = ['left', 'center', 'right'];- return positions.flatMap(pos => getPanelsByPosition(pos))- .filter(p => p.defaultVisible)- .map(p => `- <div class="es-tab es-tab-active" data-panel="${p.id}">- <span class="es-tab-label">${p.title}</span>- <button class="es-tab-close">${icons.x(10)}</button>- </div>- `).join('');- }-- private buildMainPanelsHTML(): string {- const sections = (['left', 'center', 'right'] as const).map(pos => {- const panels = getPanelsByPosition(pos).filter(p => p.defaultVisible);- const containers = panels.map(p =>- `<div class="es-panel-container" data-panel-id="${p.id}"></div>`- ).join('');- return `<div class="es-editor-${pos}">${containers}</div>`;- }).join('');- return `<div class="es-editor-main">${sections}</div>`;- }-- private buildBottomPanelsHTML(): string {- const panels = getPanelsByPosition('bottom');- return panels.map(p =>- `<div class="es-panel-container" data-panel-id="${p.id}" style="display: none;"></div>`- ).join('');- }-- private buildStatusBarHTML(): string {- return `- <div class="es-editor-statusbar">- <div class="es-statusbar-left"></div>- <div class="es-statusbar-right"></div>- </div>- `;- }-- private buildMenuBarHTML(): string {- const menus = getAllMenus();- return menus.map(menu => {- const items = getMenuItems(menu.id);- const itemsHTML = items.map(item => {- const parts: string[] = [];- if (item.separator) {- parts.push('<div class="es-menu-divider"></div>');- }- parts.push(`<div class="es-menu-item" data-action="${item.id}">`);- parts.push(`<span class="es-menu-item-text">${item.label}</span>`);- if (item.shortcut) {- parts.push(`<span class="es-menu-item-shortcut">${item.shortcut}</span>`);- }- parts.push('</div>');- return parts.join('');- }).join('');-- return `- <div class="es-menu" data-menu="${menu.id}">- <div class="es-menu-trigger">${menu.label}</div>- <div class="es-menu-dropdown">${itemsHTML}</div>- </div>- `;- }).join('');- }-- private instantiatePanels(): void {- for (const desc of getAllPanels()) {- if (!desc.defaultVisible && desc.position !== 'bottom') continue;- const el = this.container_.querySelector(`[data-panel-id="${desc.id}"]`) as HTMLElement;- if (!el) continue;- const instance = desc.factory(el, this.store_);- this.panelInstances_.set(desc.id, instance);- }- }-- private instantiateStatusbar(): void {- const items = getAllStatusbarItems();- const leftContainer = this.container_.querySelector('.es-statusbar-left');- const rightContainer = this.container_.querySelector('.es-statusbar-right');-- for (const item of items) {- const container = item.position === 'left' ? leftContainer : rightContainer;- if (!container) continue;- const span = document.createElement('span');- span.dataset.statusbarId = item.id;- container.appendChild(span);- const instance = item.render(span);- this.statusbarInstances_.push(instance);- }- }-- private setupMenuShortcuts(): void {- const menus = getAllMenus();- for (const menu of menus) {- const items = getMenuItems(menu.id);- for (const item of items) {- if (item.shortcut) {- this.shortcutManager_.register(item.shortcut, item.action);- }- }- }- }-- private setupToolbarEvents(): void {- const menubar = this.container_.querySelector('.es-editor-menubar');- if (!menubar) return;-- let activeMenu: HTMLElement | null = null;-- 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;- if (!menuItem) return;-- if (menuItem.classList.contains('es-disabled')) return;-- const actionId = menuItem.dataset.action;- if (!actionId) return;-- closeAllMenus();-- const allMenus = getAllMenus();- for (const menu of allMenus) {- const items = getMenuItems(menu.id);- const found = items.find(i => i.id === actionId);- if (found) {- found.action();- return;- }- }- });-- const previewBtn = menubar.querySelector('[data-action="preview"]');- previewBtn?.addEventListener('click', () => this.startPreview());-- document.addEventListener('click', (e) => {- if (!menubar.contains(e.target as Node)) {- closeAllMenus();- }- });- }-- private updateToolbarState(): void {- const allMenus = getAllMenus();- for (const menu of allMenus) {- const items = getMenuItems(menu.id);- for (const item of items) {- if (item.enabled) {- const el = this.container_.querySelector(`[data-action="${item.id}"]`);- el?.classList.toggle('es-disabled', !item.enabled());- }- }- }- }-- private updateBottomPanelVisibility(): void {- const bottomSection = this.container_.querySelector('.es-editor-bottom') as HTMLElement;- const bottomPanels = getPanelsByPosition('bottom');-- for (const desc of bottomPanels) {- const el = this.container_.querySelector(`[data-panel-id="${desc.id}"]`) as HTMLElement;- if (el) {- el.style.display = desc.id === this.activeBottomPanelId_ ? '' : 'none';- }- }-- if (bottomSection) {- bottomSection.style.display = this.activeBottomPanelId_ ? '' : 'none';- }-- for (const instance of this.statusbarInstances_) {- instance.update?.();- }-- for (const panel of this.panelInstances_.values()) {- if (isResizable(panel)) {- requestAnimationFrame(() => panel.resize());- break;- }- }- }-- private updateStatusbar(): void {- for (const instance of this.statusbarInstances_) {- instance.update?.();- }- this.updateSceneNameDisplay();- }-private updateSceneNameDisplay(): void {const el = this.container_.querySelector('.es-menubar-scene-name');if (!el) return;@@ -1427,25 +997,15 @@ export class Editor {document.removeEventListener('keydown', this.addressableWindow_.keyHandler);this.addressableWindow_ = null;}- this.shortcutManager_.detach();+ this.menuManager_.dispose();this.scriptLoader_?.dispose();this.extensionLoader_?.dispose();- for (const instance of this.statusbarInstances_) {- instance.dispose();- }- this.statusbarInstances_ = [];- for (const panel of this.panelInstances_.values()) {- panel.dispose();- }- this.panelInstances_.clear();+ this.panelManager_.dispose();+ this.previewManager_.dispose();clearEditorAPI();}}-// =============================================================================-// Factory Function-// =============================================================================-export function createEditor(container: HTMLElement, options?: EditorOptions): Editor {return new Editor(container, options);}diff --git a/editor/src/MenuManager.ts b/editor/src/MenuManager.tsnew file mode 100644index 000000000..ebd94cd2e--- /dev/null+++ b/editor/src/MenuManager.ts@@ -0,0 +1,271 @@+import { getAllMenus, getMenuItems, getAllStatusbarItems } from './menus';+import { ShortcutManager } from './menus/ShortcutManager';+import { getPanelsByPosition } from './panels/PanelRegistry';+import { icons } from './utils/icons';++export class MenuManager {+ private statusbarInstances_: Array<{ dispose(): void; update?(): void }> = [];+ private shortcutManager_: ShortcutManager;++ constructor() {+ this.shortcutManager_ = new ShortcutManager();+ }++ get statusbarInstances(): Array<{ dispose(): void; update?(): void }> {+ return this.statusbarInstances_;+ }++ attach(): void {+ this.shortcutManager_.attach();+ }++ detach(): void {+ this.shortcutManager_.detach();+ }++ setupMenuShortcuts(): void {+ const menus = getAllMenus();+ for (const menu of menus) {+ const items = getMenuItems(menu.id);+ for (const item of items) {+ if (item.shortcut) {+ this.shortcutManager_.register(item.shortcut, item.action);+ }+ }+ }+ }++ instantiateStatusbar(container: HTMLElement): void {+ const items = getAllStatusbarItems();+ const leftContainer = container.querySelector('.es-statusbar-left');+ const rightContainer = container.querySelector('.es-statusbar-right');++ for (const item of items) {+ const target = item.position === 'left' ? leftContainer : rightContainer;+ if (!target) continue;+ const span = document.createElement('span');+ span.dataset.statusbarId = item.id;+ target.appendChild(span);+ const instance = item.render(span);+ this.statusbarInstances_.push(instance);+ }+ }++ buildMenuBarHTML(): string {+ const menus = getAllMenus();+ return menus.map(menu => {+ const items = getMenuItems(menu.id);+ const itemsHTML = items.map(item => {+ const parts: string[] = [];+ if (item.separator) {+ parts.push('<div class="es-menu-divider"></div>');+ }+ parts.push(`<div class="es-menu-item" data-action="${item.id}">`);+ parts.push(`<span class="es-menu-item-text">${item.label}</span>`);+ if (item.shortcut) {+ parts.push(`<span class="es-menu-item-shortcut">${item.shortcut}</span>`);+ }+ parts.push('</div>');+ return parts.join('');+ }).join('');++ return `+ <div class="es-menu" data-menu="${menu.id}">+ <div class="es-menu-trigger">${menu.label}</div>+ <div class="es-menu-dropdown">${itemsHTML}</div>+ </div>+ `;+ }).join('');+ }++ buildStatusBarHTML(): string {+ return `+ <div class="es-editor-statusbar">+ <div class="es-statusbar-left"></div>+ <div class="es-statusbar-right"></div>+ </div>+ `;+ }++ rebuildMenuBar(container: HTMLElement): void {+ const menubar = container.querySelector('.es-editor-menubar');+ if (!menubar) return;++ menubar.querySelectorAll('.es-menu').forEach(el => el.remove());++ const spacer = menubar.querySelector('.es-menubar-spacer');+ if (!spacer) return;++ const fragment = document.createRange().createContextualFragment(this.buildMenuBarHTML());+ menubar.insertBefore(fragment, spacer);++ this.attachMenuTriggers(container);+ }++ attachMenuTriggers(container: HTMLElement): void {+ const menubar = container.querySelector('.es-editor-menubar');+ if (!menubar) return;++ menubar.querySelectorAll('.es-menu-trigger').forEach(trigger => {+ if ((trigger as any).__menuBound) return;+ (trigger as any).__menuBound = true;++ trigger.addEventListener('click', (e) => {+ e.stopPropagation();+ const menu = (trigger as HTMLElement).parentElement!;+ const isOpen = menu.classList.contains('es-open');+ menubar.querySelectorAll('.es-menu').forEach(m => m.classList.remove('es-open'));+ if (!isOpen) {+ menu.classList.add('es-open');+ }+ });++ trigger.addEventListener('mouseenter', () => {+ const hasOpen = menubar.querySelector('.es-menu.es-open');+ if (hasOpen && hasOpen !== trigger.parentElement) {+ menubar.querySelectorAll('.es-menu').forEach(m => m.classList.remove('es-open'));+ const menu = (trigger as HTMLElement).parentElement!;+ menu.classList.add('es-open');+ }+ });+ });+ }++ setupToolbarEvents(container: HTMLElement, onPreview: () => void): void {+ const menubar = container.querySelector('.es-editor-menubar');+ if (!menubar) return;++ let activeMenu: HTMLElement | null = null;++ 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;+ if (!menuItem) return;++ if (menuItem.classList.contains('es-disabled')) return;++ const actionId = menuItem.dataset.action;+ if (!actionId) return;++ closeAllMenus();++ const allMenus = getAllMenus();+ for (const menu of allMenus) {+ const items = getMenuItems(menu.id);+ const found = items.find(i => i.id === actionId);+ if (found) {+ found.action();+ return;+ }+ }+ });++ const previewBtn = menubar.querySelector('[data-action="preview"]');+ previewBtn?.addEventListener('click', () => onPreview());++ document.addEventListener('click', (e) => {+ if (!menubar.contains(e.target as Node)) {+ closeAllMenus();+ }+ });+ }++ updateToolbarState(container: HTMLElement): void {+ const allMenus = getAllMenus();+ for (const menu of allMenus) {+ const items = getMenuItems(menu.id);+ for (const item of items) {+ if (item.enabled) {+ const el = container.querySelector(`[data-action="${item.id}"]`);+ el?.classList.toggle('es-disabled', !item.enabled());+ }+ }+ }+ }++ updateStatusbar(): void {+ for (const instance of this.statusbarInstances_) {+ instance.update?.();+ }+ }++ addExtensionBottomPanelToggles(+ container: HTMLElement,+ activeBottomPanelId: string | null,+ onToggle: (id: string) => void,+ ): void {+ const leftContainer = container.querySelector('.es-statusbar-left');+ if (!leftContainer) return;++ for (const panel of getPanelsByPosition('bottom')) {+ if (leftContainer.querySelector(`[data-statusbar-id="toggle-${panel.id}"]`)) continue;++ const item = {+ id: `toggle-${panel.id}`,+ position: 'left' as const,+ render: (renderContainer: HTMLElement) => {+ const btn = document.createElement('button');+ btn.className = 'es-statusbar-btn';+ btn.dataset.bottomPanel = panel.id;+ btn.innerHTML = `${panel.icon ?? ''}<span>${panel.title}</span>`;+ btn.addEventListener('click', () => onToggle(panel.id));+ renderContainer.appendChild(btn);+ return {+ dispose() { btn.remove(); },+ update: () => {+ btn.classList.toggle('es-active', activeBottomPanelId === panel.id);+ },+ };+ },+ };++ const span = document.createElement('span');+ span.dataset.statusbarId = item.id;++ const cmdInputItem = leftContainer.querySelector('[data-statusbar-id="cmd-input"]');+ if (cmdInputItem) {+ leftContainer.insertBefore(span, cmdInputItem);+ } else {+ leftContainer.appendChild(span);+ }++ const instance = item.render(span);+ this.statusbarInstances_.push(instance);+ }+ }++ dispose(): void {+ this.shortcutManager_.detach();+ for (const instance of this.statusbarInstances_) {+ instance.dispose();+ }+ this.statusbarInstances_ = [];+ }+}diff --git a/editor/src/PanelManager.ts b/editor/src/PanelManager.tsnew file mode 100644index 000000000..dabdf745b--- /dev/null+++ b/editor/src/PanelManager.ts@@ -0,0 +1,304 @@+import type { App } from 'esengine';+import type { SpineModuleController, SpineWasmModule } from 'esengine/spine';+import { wrapSpineModule, SpineModuleController as SpineModuleControllerClass } from 'esengine/spine';+import type { EditorStore } from './store/EditorStore';+import type { EditorBridge } from './bridge/EditorBridge';+import type { PanelInstance, PanelPosition, PanelDescriptor } from './panels/PanelRegistry';+import {+ getAllPanels,+ getPanelsByPosition,+ isResizable,+ isBridgeAware,+ isAppAware,+ isAssetServerProvider,+ isAssetNavigable,+ isOutputAppendable,+ isSpineControllerAware,+ isSpineInfoProvider,+ isBuiltinPanel,+} from './panels/PanelRegistry';+import type { EditorAssetServer } from './asset/EditorAssetServer';+import { icons } from './utils/icons';++export class PanelManager {+ private panelInstances_ = new Map<string, PanelInstance>();+ private activeBottomPanelId_: string | null = 'content-browser';++ get activeBottomPanelId(): string | null {+ return this.activeBottomPanelId_;+ }++ get panelInstances(): Map<string, PanelInstance> {+ return this.panelInstances_;+ }++ get assetServer(): EditorAssetServer | null {+ for (const panel of this.panelInstances_.values()) {+ if (isAssetServerProvider(panel)) return panel.assetServer as EditorAssetServer;+ }+ return null;+ }++ instantiatePanels(container: HTMLElement, store: EditorStore): void {+ for (const desc of getAllPanels()) {+ if (!desc.defaultVisible && desc.position !== 'bottom') continue;+ const el = container.querySelector(`[data-panel-id="${desc.id}"]`) as HTMLElement;+ if (!el) continue;+ this.createPanelWithErrorBoundary(desc, el, store);+ }+ }++ instantiateExtensionPanels(+ container: HTMLElement,+ store: EditorStore,+ bridge: EditorBridge | null,+ app: App | null,+ ): void {+ for (const desc of getAllPanels()) {+ if (this.panelInstances_.has(desc.id)) continue;++ const position = desc.position ?? 'bottom';+ let parentEl: HTMLElement | null = null;++ if (position === 'bottom') {+ parentEl = container.querySelector('.es-editor-bottom');+ } else {+ parentEl = container.querySelector(`.es-editor-${position}`);+ }+ if (!parentEl) continue;++ const panelContainer = document.createElement('div');+ panelContainer.className = 'es-panel-container';+ panelContainer.dataset.panelId = desc.id;++ if (position === 'bottom') {+ panelContainer.style.display = 'none';+ }++ 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);+ }+ }+ }++ private createPanelWithErrorBoundary(+ desc: PanelDescriptor,+ container: HTMLElement,+ store: EditorStore,+ ): void {+ try {+ const instance = desc.factory(container, store);+ this.panelInstances_.set(desc.id, instance);+ } catch (err) {+ console.error(`Panel "${desc.id}" failed to initialize:`, err);+ this.showPanelError(desc, container, store, err as Error);+ }+ }++ private showPanelError(+ desc: PanelDescriptor,+ container: HTMLElement,+ store: EditorStore,+ error: Error,+ ): void {+ container.innerHTML = '';+ const overlay = document.createElement('div');+ overlay.className = 'es-panel-error-overlay';+ overlay.innerHTML = `+ <div class="es-panel-error-content">+ <div class="es-panel-error-icon">${icons.x(32)}</div>+ <h4 class="es-panel-error-title">Panel "${escapeHtml(desc.title)}" failed to load</h4>+ <p class="es-panel-error-message">${escapeHtml(error.message)}</p>+ <details class="es-panel-error-details">+ <summary>Details</summary>+ <pre>${escapeHtml(error.stack ?? '')}</pre>+ </details>+ <div class="es-panel-error-actions">+ <button class="es-btn es-btn-primary" data-action="retry">Retry</button>+ <button class="es-btn" data-action="close">Close</button>+ </div>+ </div>+ `;++ overlay.querySelector('[data-action="retry"]')?.addEventListener('click', () => {+ overlay.remove();+ this.createPanelWithErrorBoundary(desc, container, store);+ });++ overlay.querySelector('[data-action="close"]')?.addEventListener('click', () => {+ overlay.remove();+ });++ container.appendChild(overlay);+ }++ setApp(app: App, bridge: EditorBridge): void {+ for (const panel of this.panelInstances_.values()) {+ if (isBridgeAware(panel)) panel.setBridge(bridge);+ if (isAppAware(panel)) panel.setApp(app);+ }+ }++ setSpineModule(module: unknown): void {+ const raw = module as SpineWasmModule;+ const controller = module ? new SpineModuleControllerClass(raw, wrapSpineModule(raw)) : null;+ for (const panel of this.panelInstances_.values()) {+ if (isSpineControllerAware(panel)) {+ panel.setSpineController(controller);+ }+ }+ }++ getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {+ for (const panel of this.panelInstances_.values()) {+ if (isSpineInfoProvider(panel)) {+ return panel.getSpineSkeletonInfo(entityId);+ }+ }+ return null;+ }++ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ for (const panel of this.panelInstances_.values()) {+ if (isSpineInfoProvider(panel)) {+ return panel.onSpineInstanceReady(listener);+ }+ }+ return () => {};+ }++ async navigateToAsset(assetPath: string): Promise<void> {+ for (const panel of this.panelInstances_.values()) {+ if (isAssetNavigable(panel)) {+ await panel.navigateToAsset(assetPath);+ return;+ }+ }+ }++ showPanel(id: string): void {+ this.panelInstances_.get(id)?.onShow?.();+ }++ hidePanel(id: string): void {+ this.panelInstances_.get(id)?.onHide?.();+ }++ togglePanel(id: string): void {+ this.panelInstances_.get(id)?.onShow?.();+ }++ showBottomPanel(id: string, container: HTMLElement): void {+ if (this.activeBottomPanelId_ === id) return;+ const prev = this.activeBottomPanelId_;+ this.activeBottomPanelId_ = id;+ this.updateBottomPanelVisibility(container);+ if (prev) {+ this.panelInstances_.get(prev)?.onHide?.();+ }+ this.panelInstances_.get(id)?.onShow?.();+ }++ toggleBottomPanel(id: string, container: HTMLElement): void {+ const prev = this.activeBottomPanelId_;+ if (prev === id) {+ this.activeBottomPanelId_ = null;+ } else {+ this.activeBottomPanelId_ = id;+ }+ this.updateBottomPanelVisibility(container);+ if (prev && prev !== id) {+ this.panelInstances_.get(prev)?.onHide?.();+ }+ if (this.activeBottomPanelId_) {+ this.panelInstances_.get(this.activeBottomPanelId_)?.onShow?.();+ }+ }++ updateBottomPanelVisibility(container: HTMLElement): void {+ const bottomSection = container.querySelector('.es-editor-bottom') as HTMLElement;+ const bottomPanels = getPanelsByPosition('bottom');++ for (const desc of bottomPanels) {+ const el = container.querySelector(`[data-panel-id="${desc.id}"]`) as HTMLElement;+ if (el) {+ el.style.display = desc.id === this.activeBottomPanelId_ ? '' : 'none';+ }+ }++ if (bottomSection) {+ bottomSection.style.display = this.activeBottomPanelId_ ? '' : 'none';+ }++ for (const panel of this.panelInstances_.values()) {+ if (isResizable(panel)) {+ requestAnimationFrame(() => panel.resize());+ break;+ }+ }+ }++ appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {+ const outputPanel = this.panelInstances_.get('output');+ if (outputPanel && isOutputAppendable(outputPanel)) {+ outputPanel.appendOutput(text, type);+ }+ }++ cleanupExtensionPanels(container: HTMLElement): void {+ for (const [id, instance] of this.panelInstances_) {+ if (isBuiltinPanel(id)) continue;+ instance.dispose();+ this.panelInstances_.delete(id);+ container.querySelector(`[data-panel-id="${id}"]`)?.remove();+ }+ }++ buildMainPanelsHTML(): string {+ const sections = (['left', 'center', 'right'] as const).map(pos => {+ const panels = getPanelsByPosition(pos).filter(p => p.defaultVisible);+ const containers = panels.map(p =>+ `<div class="es-panel-container" data-panel-id="${p.id}"></div>`+ ).join('');+ return `<div class="es-editor-${pos}">${containers}</div>`;+ }).join('');+ return `<div class="es-editor-main">${sections}</div>`;+ }++ buildBottomPanelsHTML(): string {+ const panels = getPanelsByPosition('bottom');+ return panels.map(p =>+ `<div class="es-panel-container" data-panel-id="${p.id}" style="display: none;"></div>`+ ).join('');+ }++ buildTabBarHTML(): string {+ const positions: PanelPosition[] = ['left', 'center', 'right'];+ return positions.flatMap(pos => getPanelsByPosition(pos))+ .filter(p => p.defaultVisible)+ .map(p => `+ <div class="es-tab es-tab-active" data-panel="${p.id}">+ <span class="es-tab-label">${p.title}</span>+ <button class="es-tab-close">${icons.x(10)}</button>+ </div>+ `).join('');+ }++ dispose(): void {+ for (const panel of this.panelInstances_.values()) {+ panel.dispose();+ }+ this.panelInstances_.clear();+ }+}++function escapeHtml(text: string): string {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+}diff --git a/editor/src/PreviewManager.ts b/editor/src/PreviewManager.tsnew file mode 100644index 000000000..ea361993a--- /dev/null+++ b/editor/src/PreviewManager.ts@@ -0,0 +1,67 @@+import type { SceneData } from './types/SceneTypes';+import { PreviewService } from './preview';+import { getSettingsValue } from './settings';+import type { ScriptLoader } from './scripting';++export class PreviewManager {+ private previewService_: PreviewService | null = null;++ constructor(projectPath: string | null) {+ if (projectPath) {+ this.previewService_ = new PreviewService({ projectPath });+ }+ }++ async startPreview(+ scene: SceneData,+ scriptLoader: ScriptLoader | null,+ spineVersion: string,+ ): Promise<void> {+ if (!this.previewService_) {+ console.warn('Preview not available: no project loaded');+ return;+ }++ try {+ if (scriptLoader) {+ await scriptLoader.compile();+ }+ const compiledScript = scriptLoader?.getCompiledCode() ?? undefined;+ const { enablePhysics, physicsConfig, previewSpineVersion } = this.collectPreviewConfig(spineVersion);+ await this.previewService_.startPreview(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig);+ } catch (err) {+ console.error('Failed to start preview:', err);+ }+ }++ async stopPreview(): Promise<void> {+ await this.previewService_?.stopPreview();+ }++ refreshFiles(+ scene: SceneData,+ scriptLoader: ScriptLoader | null,+ spineVersion: string,+ ): void {+ if (!this.previewService_) return;+ const compiledScript = scriptLoader?.getCompiledCode() ?? undefined;+ const { enablePhysics, physicsConfig, previewSpineVersion } = this.collectPreviewConfig(spineVersion);+ this.previewService_.updatePreviewFiles(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig);+ }++ private collectPreviewConfig(spineVersion: string) {+ const enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;+ const physicsConfig = enablePhysics ? {+ gravityX: getSettingsValue<number>('physics.gravityX') ?? 0,+ gravityY: getSettingsValue<number>('physics.gravityY') ?? -9.81,+ fixedTimestep: getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60,+ subStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,+ } : undefined;+ const previewSpineVersion = spineVersion === 'none' ? undefined : spineVersion;+ return { enablePhysics, physicsConfig, previewSpineVersion };+ }++ dispose(): void {+ this.previewService_ = null;+ }+}diff --git a/editor/src/__tests__/asset/AssetDatabase.test.ts b/editor/src/__tests__/asset/AssetDatabase.test.tsindex 4deb7d5f7..6e90da23c 100644--- a/editor/src/__tests__/asset/AssetDatabase.test.ts+++ b/editor/src/__tests__/asset/AssetDatabase.test.ts@@ -1,30 +1,507 @@-import { describe, it, expect } from 'vitest';-import { isUUID } from '../../asset/AssetDatabase';+import { describe, it, expect, beforeEach } from 'vitest';+import { AssetDatabase, isUUID } from '../../asset/AssetDatabase';+import type { NativeFS, FileStats, DirectoryEntry } from '../../types/NativeFS';++function createMockFS(files: Record<string, string> = {}): NativeFS {+ const store = new Map<string, string>(Object.entries(files));+ return {+ readFile: async (path: string) => store.get(path) ?? null,+ writeFile: async (path: string, content: string) => { store.set(path, content); return true; },+ exists: async (path: string) => store.has(path),+ listDirectory: async () => [],+ listDirectoryDetailed: async (): Promise<DirectoryEntry[]> => [],+ createDirectory: async () => true,+ copyFile: async () => true,+ getFileStats: async (): Promise<FileStats | null> => ({ size: 100, modified: new Date(), created: null }),+ } as unknown as NativeFS;+}describe('AssetDatabase utilities', () => {- describe('isUUID', () => {- it('should recognize valid UUIDs', () => {- expect(isUUID('550e8400-e29b-41d4-a716-446655440000')).toBe(true);- expect(isUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')).toBe(true);- expect(isUUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')).toBe(true);+ describe('isUUID', () => {+ it('should recognize valid UUIDs', () => {+ expect(isUUID('550e8400-e29b-41d4-a716-446655440000')).toBe(true);+ expect(isUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')).toBe(true);+ expect(isUUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')).toBe(true);+ });++ it('should recognize uppercase UUIDs', () => {+ expect(isUUID('550E8400-E29B-41D4-A716-446655440000')).toBe(true);+ });++ it('should reject invalid UUIDs', () => {+ expect(isUUID('not-a-uuid')).toBe(false);+ expect(isUUID('550e8400-e29b-41d4-a716')).toBe(false);+ expect(isUUID('550e8400-e29b-41d4-a716-44665544000')).toBe(false);+ expect(isUUID('550e8400-e29b-41d4-a716-4466554400000')).toBe(false);+ expect(isUUID('550e8400e29b41d4a716446655440000')).toBe(false);+ expect(isUUID('')).toBe(false);+ });++ it('should reject UUIDs with invalid characters', () => {+ expect(isUUID('550e8400-e29b-41d4-a716-44665544000g')).toBe(false);+ expect(isUUID('550e8400-e29b-41d4-a716-44665544000 ')).toBe(false);+ });++ it('should reject UUIDs with wrong structure', () => {+ expect(isUUID('550e84000-e29b-41d4-a716-44665544000')).toBe(false);+ expect(isUUID('550e840-e29b-41d4-a716-446655440000')).toBe(false);+ });+ });+});++describe('AssetDatabase', () => {+ let db: AssetDatabase;++ beforeEach(() => {+ db = new AssetDatabase();+ });++ describe('uninitialized state', () => {+ it('returns undefined for unknown UUID', () => {+ expect(db.getPath('nonexistent-uuid')).toBeUndefined();+ });++ it('returns undefined for unknown path', () => {+ expect(db.getUuid('nonexistent/path.png')).toBeUndefined();+ });++ it('has zero entries', () => {+ expect(db.entryCount).toBe(0);+ });++ it('getEntry returns undefined', () => {+ expect(db.getEntry('any-uuid')).toBeUndefined();+ });++ it('getEntryByPath returns undefined', () => {+ expect(db.getEntryByPath('any/path')).toBeUndefined();+ });++ it('returns empty labels', () => {+ expect(db.getAllLabels()).toEqual([]);+ });++ it('returns empty groups', () => {+ expect(db.getAllGroups()).toEqual([]);+ });+ });++ describe('ensureMeta', () => {+ it('throws when not initialized', async () => {+ await expect(db.ensureMeta('assets/test.png')).rejects.toThrow('AssetDatabase not initialized');+ });++ it('creates new meta file for unknown asset', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/test.png');++ expect(isUUID(uuid)).toBe(true);+ expect(db.getPath(uuid)).toBe('assets/test.png');+ expect(db.getUuid('assets/test.png')).toBe(uuid);+ });++ it('returns existing UUID for already registered path', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid1 = await db.ensureMeta('assets/test.png');+ const uuid2 = await db.ensureMeta('assets/test.png');++ expect(uuid1).toBe(uuid2);+ });++ it('reads existing meta file', async () => {+ const meta = JSON.stringify({+ uuid: '550e8400-e29b-41d4-a716-446655440000',+ version: '2.0',+ type: 'texture',+ labels: [],+ address: null,+ importer: {},+ platformOverrides: {},+ });+ const fs = createMockFS({+ '/project/assets/sprite.png.meta': meta,+ });+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/sprite.png');++ expect(uuid).toBe('550e8400-e29b-41d4-a716-446655440000');+ });+ });++ describe('UUID / path bidirectional lookup', () => {+ it('maintains consistent mapping', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid1 = await db.ensureMeta('assets/a.png');+ const uuid2 = await db.ensureMeta('assets/b.png');++ expect(db.getPath(uuid1)).toBe('assets/a.png');+ expect(db.getPath(uuid2)).toBe('assets/b.png');+ expect(db.getUuid('assets/a.png')).toBe(uuid1);+ expect(db.getUuid('assets/b.png')).toBe(uuid2);+ });++ it('entryCount reflects registered assets', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ expect(db.entryCount).toBe(0);++ await db.ensureMeta('assets/a.png');+ expect(db.entryCount).toBe(1);++ await db.ensureMeta('assets/b.png');+ expect(db.entryCount).toBe(2);+ });+ });++ describe('entry access', () => {+ it('getEntry returns full entry data', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/sprite.png');+ const entry = db.getEntry(uuid);++ expect(entry).toBeDefined();+ expect(entry!.uuid).toBe(uuid);+ expect(entry!.path).toBe('assets/sprite.png');+ });++ it('getEntryByPath returns entry', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/sprite.png');+ const entry = db.getEntryByPath('assets/sprite.png');++ expect(entry).toBeDefined();+ expect(entry!.uuid).toBe(uuid);+ });++ it('getAllEntries iterates all entries', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ await db.ensureMeta('assets/a.png');+ await db.ensureMeta('assets/b.png');+ await db.ensureMeta('assets/c.png');++ const entries = [...db.getAllEntries()];+ expect(entries.length).toBe(3);+ });+ });++ describe('address lookup', () => {+ it('sets and retrieves address', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/hero.png');+ await db.updateMeta(uuid, { address: 'hero-sprite' });++ expect(db.getUuidByAddress('hero-sprite')).toBe(uuid);+ });++ it('getEntryByAddress returns entry', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/hero.png');+ await db.updateMeta(uuid, { address: 'hero-sprite' });++ const entry = db.getEntryByAddress('hero-sprite');+ expect(entry).toBeDefined();+ expect(entry!.uuid).toBe(uuid);+ });++ it('changing address removes old mapping', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/hero.png');+ await db.updateMeta(uuid, { address: 'old-address' });+ await db.updateMeta(uuid, { address: 'new-address' });++ expect(db.getUuidByAddress('old-address')).toBeUndefined();+ expect(db.getUuidByAddress('new-address')).toBe(uuid);+ });++ it('setting address to null removes mapping', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/hero.png');+ await db.updateMeta(uuid, { address: 'test-address' });+ await db.updateMeta(uuid, { address: null });++ expect(db.getUuidByAddress('test-address')).toBeUndefined();+ });+ });++ describe('label queries', () => {+ it('assigns and queries labels', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/hero.png');+ await db.updateMeta(uuid, { labels: new Set(['character', 'player']) });++ const characterUuids = db.getUuidsByLabel('character');+ expect(characterUuids.has(uuid)).toBe(true);++ const playerUuids = db.getUuidsByLabel('player');+ expect(playerUuids.has(uuid)).toBe(true);+ });++ it('getAllLabels returns all unique labels', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid1 = await db.ensureMeta('assets/a.png');+ const uuid2 = await db.ensureMeta('assets/b.png');+ await db.updateMeta(uuid1, { labels: new Set(['character', 'sprite']) });+ await db.updateMeta(uuid2, { labels: new Set(['enemy', 'sprite']) });++ const allLabels = db.getAllLabels();+ expect(allLabels).toContain('character');+ expect(allLabels).toContain('enemy');+ expect(allLabels).toContain('sprite');+ });++ it('changing labels removes old label index entries', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { labels: new Set(['old-label']) });++ expect(db.getUuidsByLabel('old-label').has(uuid)).toBe(true);++ await db.updateMeta(uuid, { labels: new Set(['new-label']) });++ expect(db.getUuidsByLabel('old-label').has(uuid)).toBe(false);+ expect(db.getUuidsByLabel('new-label').has(uuid)).toBe(true);+ });++ it('returns empty set for unknown label', () => {+ const result = db.getUuidsByLabel('nonexistent');+ expect(result.size).toBe(0);+ });});- it('should recognize uppercase UUIDs', () => {- expect(isUUID('550E8400-E29B-41D4-A716-446655440000')).toBe(true);+ describe('group queries', () => {+ it('updates group and queries by group', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { group: 'ui' });++ const uiUuids = db.getUuidsByGroup('ui');+ expect(uiUuids.has(uuid)).toBe(true);+ });++ it('changing group removes from old group', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { group: 'old-group' });+ await db.updateMeta(uuid, { group: 'new-group' });++ expect(db.getUuidsByGroup('old-group').has(uuid)).toBe(false);+ expect(db.getUuidsByGroup('new-group').has(uuid)).toBe(true);+ });++ it('returns empty set for unknown group', () => {+ const result = db.getUuidsByGroup('nonexistent');+ expect(result.size).toBe(0);+ });++ it('getAllGroups returns registered groups', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { group: 'ui' });++ expect(db.getAllGroups()).toContain('ui');+ });});- it('should reject invalid UUIDs', () => {- expect(isUUID('not-a-uuid')).toBe(false);- expect(isUUID('550e8400-e29b-41d4-a716')).toBe(false);- expect(isUUID('550e8400-e29b-41d4-a716-44665544000')).toBe(false);- expect(isUUID('550e8400-e29b-41d4-a716-4466554400000')).toBe(false);- expect(isUUID('550e8400e29b41d4a716446655440000')).toBe(false);- expect(isUUID('')).toBe(false);+ describe('unregister', () => {+ it('removes entry by path', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/to-remove.png');+ expect(db.entryCount).toBe(1);++ db.unregister('assets/to-remove.png');++ expect(db.entryCount).toBe(0);+ expect(db.getPath(uuid)).toBeUndefined();+ expect(db.getUuid('assets/to-remove.png')).toBeUndefined();+ });++ it('cleans up address index on unregister', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { address: 'test-addr' });++ db.unregister('assets/a.png');++ expect(db.getUuidByAddress('test-addr')).toBeUndefined();+ });++ it('cleans up label index on unregister', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { labels: new Set(['test-label']) });++ db.unregister('assets/a.png');++ expect(db.getUuidsByLabel('test-label').has(uuid)).toBe(false);+ });++ it('cleans up group index on unregister', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { group: 'test-group' });++ db.unregister('assets/a.png');++ expect(db.getUuidsByGroup('test-group').has(uuid)).toBe(false);+ });++ it('no-op for unknown path', () => {+ db.unregister('nonexistent/path.png');+ expect(db.entryCount).toBe(0);+ });+ });++ describe('updatePath', () => {+ it('updates path while preserving UUID', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/old-name.png');+ db.updatePath('assets/old-name.png', 'assets/new-name.png');++ expect(db.getPath(uuid)).toBe('assets/new-name.png');+ expect(db.getUuid('assets/new-name.png')).toBe(uuid);+ expect(db.getUuid('assets/old-name.png')).toBeUndefined();+ });++ it('no-op for unknown path', () => {+ db.updatePath('nonexistent/old.png', 'nonexistent/new.png');+ expect(db.entryCount).toBe(0);+ });});- it('should reject UUIDs with invalid characters', () => {- expect(isUUID('550e8400-e29b-41d4-a716-44665544000g')).toBe(false);- expect(isUUID('550e8400-e29b-41d4-a716-44665544000 ')).toBe(false);+ describe('importer settings', () => {+ it('updates importer settings', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/sprite.png');+ await db.updateMeta(uuid, {+ importer: { sliceBorder: { left: 10, right: 10, top: 10, bottom: 10 } },+ });++ const entry = db.getEntry(uuid);+ expect(entry!.importer).toEqual({ sliceBorder: { left: 10, right: 10, top: 10, bottom: 10 } });+ });++ it('getSliceBorder returns null for non-texture', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/data.json');+ expect(db.getSliceBorder(uuid)).toBeNull();+ });++ it('getSliceBorder returns null for unknown UUID', () => {+ expect(db.getSliceBorder('nonexistent')).toBeNull();+ });+ });++ describe('platformOverrides', () => {+ it('updates platform overrides', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/sprite.png');+ await db.updateMeta(uuid, {+ platformOverrides: {+ wechat: { maxSize: 512 },+ },+ });++ const entry = db.getEntry(uuid);+ expect(entry!.platformOverrides).toEqual({ wechat: { maxSize: 512 } });+ });+ });++ describe('index consistency', () => {+ it('maintains consistency after multiple operations', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid1 = await db.ensureMeta('assets/a.png');+ const uuid2 = await db.ensureMeta('assets/b.png');+ const uuid3 = await db.ensureMeta('assets/c.png');++ await db.updateMeta(uuid1, { labels: new Set(['shared']), address: 'addr-a', group: 'ui' });+ await db.updateMeta(uuid2, { labels: new Set(['shared']), address: 'addr-b', group: 'ui' });+ await db.updateMeta(uuid3, { labels: new Set(['unique']), address: 'addr-c', group: 'audio' });++ expect(db.getUuidsByLabel('shared').size).toBe(2);+ expect(db.getUuidsByGroup('ui').size).toBe(2);++ db.unregister('assets/a.png');++ expect(db.getUuidsByLabel('shared').size).toBe(1);+ expect(db.getUuidsByGroup('ui').size).toBe(1);+ expect(db.getUuidByAddress('addr-a')).toBeUndefined();+ expect(db.getUuidByAddress('addr-b')).toBe(uuid2);++ db.updatePath('assets/b.png', 'assets/b-renamed.png');++ expect(db.getUuid('assets/b-renamed.png')).toBe(uuid2);+ expect(db.getPath(uuid2)).toBe('assets/b-renamed.png');+ expect(db.getUuidByAddress('addr-b')).toBe(uuid2);+ expect(db.getUuidsByLabel('shared').has(uuid2)).toBe(true);+ });++ it('re-initialization clears all state', async () => {+ const fs = createMockFS();+ await db.initialize('/project', fs);++ const uuid = await db.ensureMeta('assets/a.png');+ await db.updateMeta(uuid, { labels: new Set(['test']), address: 'addr' });++ expect(db.entryCount).toBe(1);++ await db.initialize('/project2', fs);++ expect(db.entryCount).toBe(0);+ expect(db.getPath(uuid)).toBeUndefined();+ expect(db.getUuidByAddress('addr')).toBeUndefined();+ expect(db.getUuidsByLabel('test').size).toBe(0);+ });});- });});diff --git a/editor/src/__tests__/commands/CommandHistory.test.ts b/editor/src/__tests__/commands/CommandHistory.test.tsindex 921f8e6fe..93b97fd7c 100644--- a/editor/src/__tests__/commands/CommandHistory.test.ts+++ b/editor/src/__tests__/commands/CommandHistory.test.ts@@ -1,6 +1,7 @@-import { describe, it, expect, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, vi } from 'vitest';import { CommandHistory } from '../../commands/CommandHistory';import { BaseCommand } from '../../commands/Command';+import { CompoundCommand } from '../../commands/CompoundCommand';import type { Command } from '../../commands/Command';class MockCommand extends BaseCommand {@@ -18,6 +19,22 @@ class MockCommand extends BaseCommand {}}+class StructuralMockCommand extends BaseCommand {+ type = 'structural_mock';+ description = 'Structural mock command';+ readonly structural = true;+ executed = false;+ undone = false;++ execute(): void {+ this.executed = true;+ }++ undo(): void {+ this.undone = true;+ }+}+class MergeableCommand extends BaseCommand {type = 'mergeable';description = 'Mergeable command';@@ -50,11 +67,32 @@ class MergeableCommand extends BaseCommand {}}+class CountingCommand extends BaseCommand {+ type = 'counting';+ description = 'Counting command';+ static executeCount = 0;+ static undoCount = 0;++ execute(): void {+ CountingCommand.executeCount++;+ }++ undo(): void {+ CountingCommand.undoCount++;+ }++ static reset(): void {+ CountingCommand.executeCount = 0;+ CountingCommand.undoCount = 0;+ }+}+describe('CommandHistory', () => {let history: CommandHistory;beforeEach(() => {history = new CommandHistory(10);+ CountingCommand.reset();});describe('execute', () => {@@ -105,6 +143,42 @@ describe('CommandHistory', () => {expect(history.historySize).toBe(2);});++ it('should not merge different command types', () => {+ const cmd1 = new MergeableCommand(10);+ const cmd2 = new MockCommand();++ history.execute(cmd1);+ history.execute(cmd2);++ expect(history.historySize).toBe(2);+ });++ it('should merge multiple consecutive mergeable commands into one', () => {+ const cmd1 = new MergeableCommand(10);+ const cmd2 = new MergeableCommand(20);+ const cmd3 = new MergeableCommand(30);+ const cmd4 = new MergeableCommand(40);++ history.execute(cmd1);+ history.execute(cmd2);+ history.execute(cmd3);+ history.execute(cmd4);++ expect(history.historySize).toBe(1);+ expect((history.peekUndo() as MergeableCommand).value).toBe(40);+ });++ it('should execute all commands even when merging', () => {+ let execCount = 0;+ const cmd1 = new MergeableCommand(10, () => execCount++);+ const cmd2 = new MergeableCommand(20, () => execCount++);++ history.execute(cmd1);+ history.execute(cmd2);++ expect(execCount).toBe(2);+ });});describe('undo', () => {@@ -141,6 +215,27 @@ describe('CommandHistory', () => {expect(history.canUndo()).toBe(true);expect(history.canRedo()).toBe(true);});++ it('should undo all commands to empty state', () => {+ history.execute(new MockCommand());+ history.execute(new MockCommand());+ history.execute(new MockCommand());++ history.undo();+ history.undo();+ history.undo();++ expect(history.canUndo()).toBe(false);+ expect(history.currentIndex).toBe(-1);+ });++ it('should not go below index -1', () => {+ history.undo();+ history.undo();++ expect(history.currentIndex).toBe(-1);+ expect(history.canUndo()).toBe(false);+ });});describe('redo', () => {@@ -180,6 +275,71 @@ describe('CommandHistory', () => {expect(history.currentIndex).toBe(1);expect(history.canRedo()).toBe(false);});++ it('should redo commands in forward order', () => {+ const order: number[] = [];++ history.execute(new CountingCommand());+ history.execute(new CountingCommand());+ history.execute(new CountingCommand());++ history.undo();+ history.undo();+ history.undo();++ CountingCommand.reset();++ history.redo();+ expect(CountingCommand.executeCount).toBe(1);++ history.redo();+ expect(CountingCommand.executeCount).toBe(2);++ history.redo();+ expect(CountingCommand.executeCount).toBe(3);+ });+ });++ describe('undo/redo interleaving', () => {+ it('should handle undo then redo then new command', () => {+ history.execute(new MockCommand());+ history.execute(new MockCommand());+ history.execute(new MockCommand());++ history.undo();+ history.redo();++ expect(history.historySize).toBe(3);+ expect(history.currentIndex).toBe(2);+ });++ it('should discard redo stack when executing after undo', () => {+ history.execute(new MockCommand());+ history.execute(new MockCommand());+ history.execute(new MockCommand());++ history.undo();+ history.undo();++ history.execute(new MockCommand());++ expect(history.historySize).toBe(2);+ expect(history.canRedo()).toBe(false);+ });++ it('should handle undo-redo-undo cycle', () => {+ const cmd = new MockCommand();+ history.execute(cmd);++ history.undo();+ expect(cmd.undone).toBe(true);++ history.redo();+ history.undo();++ expect(history.currentIndex).toBe(-1);+ expect(history.canRedo()).toBe(true);+ });});describe('peek operations', () => {@@ -205,6 +365,21 @@ describe('CommandHistory', () => {it('should return null when nothing to redo', () => {expect(history.peekRedo()).toBeNull();});++ it('should peek correct command after multiple operations', () => {+ const cmd1 = new MockCommand();+ const cmd2 = new MockCommand();+ const cmd3 = new MockCommand();++ history.execute(cmd1);+ history.execute(cmd2);+ history.execute(cmd3);++ history.undo();++ expect(history.peekUndo()).toBe(cmd2);+ expect(history.peekRedo()).toBe(cmd3);+ });});describe('descriptions', () => {@@ -247,6 +422,19 @@ describe('CommandHistory', () => {expect(history.canUndo()).toBe(false);expect(history.canRedo()).toBe(false);});++ it('should clear redo stack too', () => {+ history.execute(new MockCommand());+ history.execute(new MockCommand());+ history.undo();++ expect(history.canRedo()).toBe(true);++ history.clear();++ expect(history.canRedo()).toBe(false);+ expect(history.historySize).toBe(0);+ });});describe('size limit', () => {@@ -274,5 +462,127 @@ describe('CommandHistory', () => {limitedHistory.undo();expect(limitedHistory.canRedo()).toBe(true);});++ it('should discard oldest commands when limit exceeded', () => {+ const maxSize = 3;+ const limitedHistory = new CommandHistory(maxSize);+ const commands: MockCommand[] = [];++ for (let i = 0; i < 5; i++) {+ const cmd = new MockCommand();+ cmd.description = `Command ${i}`;+ commands.push(cmd);+ limitedHistory.execute(cmd);+ }++ limitedHistory.undo();+ limitedHistory.undo();++ expect(limitedHistory.peekUndo()?.description).toBe('Command 2');+ });++ it('should use default max size of 100', () => {+ const defaultHistory = new CommandHistory();++ for (let i = 0; i < 150; i++) {+ defaultHistory.execute(new MockCommand());+ }++ expect(defaultHistory.historySize).toBe(100);+ });+ });++ describe('compound commands', () => {+ it('should execute compound command as single undo unit', () => {+ const cmd1 = new MockCommand();+ const cmd2 = new MockCommand();+ const compound = new CompoundCommand([cmd1, cmd2], 'Compound op');++ history.execute(compound);++ expect(cmd1.executed).toBe(true);+ expect(cmd2.executed).toBe(true);+ expect(history.historySize).toBe(1);+ });++ it('should undo compound command in reverse order', () => {+ const order: number[] = [];+ const cmd1 = new MergeableCommand(1, undefined, () => order.push(1));+ const cmd2 = new MergeableCommand(2, undefined, () => order.push(2));+ const compound = new CompoundCommand([cmd1, cmd2], 'Compound op');++ history.execute(compound);+ history.undo();++ expect(order).toEqual([2, 1]);+ });++ it('should mark compound as structural if any child is structural', () => {+ const cmd1 = new MockCommand();+ const cmd2 = new StructuralMockCommand();+ const compound = new CompoundCommand([cmd1, cmd2], 'Mixed compound');++ expect(compound.structural).toBe(true);+ });++ it('should not be structural if no children are structural', () => {+ const cmd1 = new MockCommand();+ const cmd2 = new MockCommand();+ const compound = new CompoundCommand([cmd1, cmd2], 'Non-structural compound');++ expect(compound.structural).toBe(false);+ });++ it('should have correct description', () => {+ const compound = new CompoundCommand([new MockCommand()], 'My description');++ history.execute(compound);++ expect(history.undoDescription).toBe('My description');+ });++ it('should redo compound command correctly', () => {+ const cmd1 = new MockCommand();+ const cmd2 = new MockCommand();+ const compound = new CompoundCommand([cmd1, cmd2], 'Compound op');++ history.execute(compound);+ history.undo();+ history.redo();++ expect(history.historySize).toBe(1);+ expect(history.canUndo()).toBe(true);+ expect(history.canRedo()).toBe(false);+ });+ });++ describe('structural flag', () => {+ it('should identify structural commands', () => {+ const cmd = new StructuralMockCommand();+ expect(cmd.structural).toBe(true);+ });++ it('should default structural to false', () => {+ const cmd = new MockCommand();+ expect(cmd.structural).toBe(false);+ });+ });++ describe('command identity', () => {+ it('should assign unique ids to commands', () => {+ const cmd1 = new MockCommand();+ const cmd2 = new MockCommand();++ expect(cmd1.id).not.toBe(cmd2.id);+ });++ it('should record timestamp on creation', () => {+ const before = Date.now();+ const cmd = new MockCommand();+ const after = Date.now();++ expect(cmd.timestamp).toBeGreaterThanOrEqual(before);+ expect(cmd.timestamp).toBeLessThanOrEqual(after);+ });});});diff --git a/editor/src/__tests__/store/EditorStore.test.ts b/editor/src/__tests__/store/EditorStore.test.tsindex 53cef1b22..d09aa7409 100644--- a/editor/src/__tests__/store/EditorStore.test.ts+++ b/editor/src/__tests__/store/EditorStore.test.ts@@ -1,8 +1,10 @@-import { describe, it, expect, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, vi } from 'vitest';import { EditorStore } from '../../store/EditorStore';import type { Entity } from 'esengine';+import type { SceneData, EntityData } from '../../types/SceneTypes';+import { createEmptyScene } from '../../types/SceneTypes';-describe('EditorStore multi-selection', () => {+describe('EditorStore', () => {let store: EditorStore;beforeEach(() => {@@ -10,162 +12,881 @@ describe('EditorStore multi-selection', () => {store.newScene('Test Scene');});- it('initializes with empty selection', () => {- expect(store.selectedEntities.size).toBe(0);- expect(store.selectedEntity).toBeNull();+ // =========================================================================+ // Scene Operations+ // =========================================================================++ describe('newScene', () => {+ it('creates scene with default entities', () => {+ expect(store.scene.name).toBe('Test Scene');+ expect(store.scene.entities.length).toBeGreaterThanOrEqual(2);+ });++ it('clears selection', () => {+ const entity = store.createEntity('Entity1');+ store.selectEntity(entity, 'replace');+ expect(store.selectedEntities.size).toBe(1);++ store.newScene('New Scene');+ expect(store.selectedEntities.size).toBe(0);+ });++ it('clears asset selection', () => {+ store.selectAsset({ path: 'test.png', type: 'image', name: 'test.png' });+ store.newScene('New Scene');+ expect(store.selectedAsset).toBeNull();+ });++ it('resets dirty flag', () => {+ store.createEntity('Entity1');+ expect(store.isDirty).toBe(true);++ store.newScene('New Scene');+ expect(store.isDirty).toBe(false);+ });++ it('clears file path', () => {+ store.loadScene(createEmptyScene(), '/path/to/scene.json');+ expect(store.filePath).toBe('/path/to/scene.json');++ store.newScene('New Scene');+ expect(store.filePath).toBeNull();+ });++ it('clears undo/redo history', () => {+ store.createEntity('Entity1');+ expect(store.canUndo).toBe(true);++ store.newScene('New Scene');+ expect(store.canUndo).toBe(false);+ expect(store.canRedo).toBe(false);+ });});- it('selects single entity with replace mode', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');+ describe('loadScene', () => {+ it('replaces scene data', () => {+ const scene = createEmptyScene('Loaded Scene');+ store.loadScene(scene, '/test/scene.json');- store.selectEntity(entity1, 'replace');- expect(store.selectedEntities.size).toBe(1);- expect(store.selectedEntities.has(entity1 as number)).toBe(true);- expect(store.selectedEntity).toBe(entity1);+ expect(store.scene.name).toBe('Loaded Scene');+ expect(store.filePath).toBe('/test/scene.json');+ });- store.selectEntity(entity2, 'replace');- expect(store.selectedEntities.size).toBe(1);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);- expect(store.selectedEntities.has(entity1 as number)).toBe(false);- });+ it('clears selection on load', () => {+ const entity = store.createEntity('Entity1');+ store.selectEntity(entity, 'replace');++ store.loadScene(createEmptyScene(), null);+ expect(store.selectedEntities.size).toBe(0);+ });++ it('resets dirty flag on load', () => {+ store.createEntity('Entity1');- it('adds entities with add mode', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');- const entity3 = store.createEntity('Entity3');+ store.loadScene(createEmptyScene(), null);+ expect(store.isDirty).toBe(false);+ });- store.selectEntity(entity1, 'replace');- store.selectEntity(entity2, 'add');- store.selectEntity(entity3, 'add');+ it('clears undo history on load', () => {+ store.createEntity('Entity1');- expect(store.selectedEntities.size).toBe(3);- expect(store.selectedEntities.has(entity1 as number)).toBe(true);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);- expect(store.selectedEntities.has(entity3 as number)).toBe(true);- expect(store.selectedEntity).toBeNull();+ store.loadScene(createEmptyScene(), null);+ expect(store.canUndo).toBe(false);+ });});- it('toggles entities with toggle mode', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');+ describe('markSaved', () => {+ it('clears dirty flag', () => {+ store.createEntity('Entity1');+ expect(store.isDirty).toBe(true);- store.selectEntity(entity1, 'replace');- expect(store.selectedEntities.size).toBe(1);+ store.markSaved();+ expect(store.isDirty).toBe(false);+ });- store.selectEntity(entity2, 'toggle');- expect(store.selectedEntities.size).toBe(2);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ it('updates file path when provided', () => {+ store.markSaved('/new/path.json');+ expect(store.filePath).toBe('/new/path.json');+ });- store.selectEntity(entity1, 'toggle');- expect(store.selectedEntities.size).toBe(1);- expect(store.selectedEntities.has(entity1 as number)).toBe(false);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ it('keeps existing file path when not provided', () => {+ store.loadScene(createEmptyScene(), '/original/path.json');+ store.createEntity('Entity1');+ store.markSaved();++ expect(store.filePath).toBe('/original/path.json');+ });});- it('selects range of entities', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');- const entity3 = store.createEntity('Entity3');- const entity4 = store.createEntity('Entity4');+ // =========================================================================+ // Multi-Selection+ // =========================================================================++ describe('multi-selection', () => {+ it('initializes with empty selection', () => {+ expect(store.selectedEntities.size).toBe(0);+ expect(store.selectedEntity).toBeNull();+ });++ it('selects single entity with replace mode', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');++ store.selectEntity(entity1, 'replace');+ expect(store.selectedEntities.size).toBe(1);+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);+ expect(store.selectedEntity).toBe(entity1);++ store.selectEntity(entity2, 'replace');+ expect(store.selectedEntities.size).toBe(1);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ expect(store.selectedEntities.has(entity1 as number)).toBe(false);+ });++ it('adds entities with add mode', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');+ const entity3 = store.createEntity('Entity3');++ store.selectEntity(entity1, 'replace');+ store.selectEntity(entity2, 'add');+ store.selectEntity(entity3, 'add');++ expect(store.selectedEntities.size).toBe(3);+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);+ expect(store.selectedEntity).toBeNull();+ });++ it('toggles entities with toggle mode', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');++ store.selectEntity(entity1, 'replace');+ expect(store.selectedEntities.size).toBe(1);++ store.selectEntity(entity2, 'toggle');+ expect(store.selectedEntities.size).toBe(2);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);++ store.selectEntity(entity1, 'toggle');+ expect(store.selectedEntities.size).toBe(1);+ expect(store.selectedEntities.has(entity1 as number)).toBe(false);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ });++ it('selects range of entities', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');+ const entity3 = store.createEntity('Entity3');+ const entity4 = store.createEntity('Entity4');++ store.selectRange(entity1 as number, entity3 as number);++ expect(store.selectedEntities.size).toBe(3);+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);+ expect(store.selectedEntities.has(entity4 as number)).toBe(false);+ });++ it('selects range in reverse order', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');+ const entity3 = store.createEntity('Entity3');++ store.selectRange(entity3 as number, entity1 as number);++ expect(store.selectedEntities.size).toBe(3);+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);+ });++ it('clears selection when selecting null', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');++ store.selectEntity(entity1, 'replace');+ store.selectEntity(entity2, 'add');+ expect(store.selectedEntities.size).toBe(2);++ store.selectEntity(null);+ expect(store.selectedEntities.size).toBe(0);+ expect(store.selectedEntity).toBeNull();+ });++ it('clears selection when selecting asset', () => {+ const entity1 = store.createEntity('Entity1');++ store.selectEntity(entity1, 'replace');+ expect(store.selectedEntities.size).toBe(1);++ store.selectAsset({ path: 'test.png', type: 'image', name: 'test.png' });+ expect(store.selectedEntities.size).toBe(0);+ });++ it('removes deleted entity from selection', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');++ store.selectEntity(entity1, 'replace');+ store.selectEntity(entity2, 'add');+ expect(store.selectedEntities.size).toBe(2);++ store.deleteEntity(entity1);+ expect(store.selectedEntities.size).toBe(1);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ });++ it('deletes all selected entities', () => {+ const initialCount = store.scene.entities.length;+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');+ const entity3 = store.createEntity('Entity3');++ store.selectEntity(entity1, 'replace');+ store.selectEntity(entity2, 'add');++ expect(store.scene.entities.length).toBe(initialCount + 3);+ store.deleteSelectedEntities();++ expect(store.scene.entities.length).toBe(initialCount + 1);+ expect(store.selectedEntities.size).toBe(0);+ expect(store.scene.entities.find(e => e.id === entity3 as number)).toBeDefined();+ });++ it('returns single entity for single selection', () => {+ const entity1 = store.createEntity('Entity1');++ store.selectEntity(entity1, 'replace');+ expect(store.selectedEntity).toBe(entity1);++ const entityData = store.getSelectedEntityData();+ expect(entityData).toBeDefined();+ expect(entityData?.id).toBe(entity1 as number);+ });++ it('returns null for multi-selection', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');++ store.selectEntity(entity1, 'replace');+ store.selectEntity(entity2, 'add');++ expect(store.selectedEntity).toBeNull();+ expect(store.getSelectedEntityData()).toBeNull();++ const entitiesData = store.getSelectedEntitiesData();+ expect(entitiesData.length).toBe(2);+ });- store.selectRange(entity1 as number, entity3 as number);+ it('selectEntities replaces entire selection', () => {+ const entity1 = store.createEntity('Entity1');+ const entity2 = store.createEntity('Entity2');+ const entity3 = store.createEntity('Entity3');++ store.selectEntity(entity1, 'replace');+ store.selectEntities([entity2 as number, entity3 as number]);- expect(store.selectedEntities.size).toBe(3);- expect(store.selectedEntities.has(entity1 as number)).toBe(true);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);- expect(store.selectedEntities.has(entity3 as number)).toBe(true);- expect(store.selectedEntities.has(entity4 as number)).toBe(false);+ expect(store.selectedEntities.size).toBe(2);+ expect(store.selectedEntities.has(entity1 as number)).toBe(false);+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);+ });});- it('selects range in reverse order', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');- const entity3 = store.createEntity('Entity3');+ // =========================================================================+ // Entity Operations+ // =========================================================================- store.selectRange(entity3 as number, entity1 as number);+ describe('entity operations', () => {+ it('creates entity with auto-generated name', () => {+ const entity = store.createEntity();+ const data = store.getEntityData(entity as number);+ expect(data).not.toBeNull();+ expect(data!.name).toMatch(/^Entity_\d+$/);+ });- expect(store.selectedEntities.size).toBe(3);- expect(store.selectedEntities.has(entity1 as number)).toBe(true);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);- expect(store.selectedEntities.has(entity3 as number)).toBe(true);- });+ it('creates entity with specified name', () => {+ const entity = store.createEntity('Player');+ const data = store.getEntityData(entity as number);+ expect(data!.name).toBe('Player');+ });++ it('creates entity as child of parent', () => {+ const parent = store.createEntity('Parent');+ const child = store.createEntity('Child', parent);++ const childData = store.getEntityData(child as number);+ expect(childData!.parent).toBe(parent as number);++ const parentData = store.getEntityData(parent as number);+ expect(parentData!.children).toContain(child as number);+ });++ it('deletes entity and removes from scene', () => {+ const entity = store.createEntity('ToDelete');+ const entityId = entity as number;++ expect(store.scene.entities.find(e => e.id === entityId)).toBeDefined();++ store.deleteEntity(entity);++ expect(store.scene.entities.find(e => e.id === entityId)).toBeUndefined();+ });- it('clears selection when selecting null', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');+ it('deletes entity with children removes all descendants', () => {+ const parent = store.createEntity('Parent');+ const child = store.createEntity('Child', parent);+ const grandchild = store.createEntity('Grandchild', child);- store.selectEntity(entity1, 'replace');- store.selectEntity(entity2, 'add');- expect(store.selectedEntities.size).toBe(2);+ store.deleteEntity(parent);- store.selectEntity(null);- expect(store.selectedEntities.size).toBe(0);- expect(store.selectedEntity).toBeNull();+ expect(store.scene.entities.find(e => e.id === parent as number)).toBeUndefined();+ expect(store.scene.entities.find(e => e.id === child as number)).toBeUndefined();+ expect(store.scene.entities.find(e => e.id === grandchild as number)).toBeUndefined();+ });++ it('renames entity', () => {+ const entity = store.createEntity('OldName');+ store.renameEntity(entity, 'NewName');++ const data = store.getEntityData(entity as number);+ expect(data!.name).toBe('NewName');+ });++ it('marks scene dirty after entity operations', () => {+ store.newScene('Clean');+ expect(store.isDirty).toBe(false);++ store.createEntity('Entity1');+ expect(store.isDirty).toBe(true);+ });++ it('auto-selects newly created entity', () => {+ const entity = store.createEntity('New');+ expect(store.selectedEntity).toBe(entity);+ });});- it('clears selection when selecting asset', () => {- const entity1 = store.createEntity('Entity1');+ // =========================================================================+ // Component Operations+ // =========================================================================++ describe('component operations', () => {+ it('adds component to entity', () => {+ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { color: { r: 255, g: 255, b: 255, a: 255 } });++ const comp = store.getComponent(entity, 'Sprite');+ expect(comp).not.toBeNull();+ expect(comp!.type).toBe('Sprite');+ });++ it('updates property on component', () => {+ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { color: { r: 255, g: 255, b: 255, a: 255 } });++ store.updateProperty(entity, 'Sprite', 'color', { r: 255, g: 255, b: 255, a: 255 }, { r: 128, g: 0, b: 0, a: 255 });++ const comp = store.getComponent(entity, 'Sprite');+ expect(comp!.data.color).toEqual({ r: 128, g: 0, b: 0, a: 255 });+ });++ it('updatePropertyDirect changes value without undo support', () => {+ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { opacity: 1.0 });++ const undoCountBefore = store.canUndo;+ store.updatePropertyDirect(entity, 'Sprite', 'opacity', 0.5);++ const comp = store.getComponent(entity, 'Sprite');+ expect(comp!.data.opacity).toBe(0.5);+ });++ it('getComponent returns null for missing component', () => {+ const entity = store.createEntity('Entity1');+ expect(store.getComponent(entity, 'NonExistent')).toBeNull();+ });++ it('getComponent returns null for missing entity', () => {+ expect(store.getComponent(9999 as Entity, 'Sprite')).toBeNull();+ });++ it('updateProperties changes multiple properties at once', () => {+ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'LocalTransform', {+ position: { x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 },+ });++ store.updateProperties(entity, 'LocalTransform', [+ { property: 'position', oldValue: { x: 0, y: 0, z: 0 }, newValue: { x: 10, y: 20, z: 0 } },+ { property: 'scale', oldValue: { x: 1, y: 1, z: 1 }, newValue: { x: 2, y: 2, z: 2 } },+ ]);++ const comp = store.getComponent(entity, 'LocalTransform');+ expect(comp!.data.position).toEqual({ x: 10, y: 20, z: 0 });+ expect(comp!.data.scale).toEqual({ x: 2, y: 2, z: 2 });+ });+ });++ // =========================================================================+ // Entity Hierarchy+ // =========================================================================++ describe('entity hierarchy', () => {+ it('reparents entity to new parent', () => {+ const parent1 = store.createEntity('Parent1');+ const parent2 = store.createEntity('Parent2');+ const child = store.createEntity('Child', parent1);++ store.reparentEntity(child, parent2);++ const childData = store.getEntityData(child as number);+ expect(childData!.parent).toBe(parent2 as number);++ const parent1Data = store.getEntityData(parent1 as number);+ expect(parent1Data!.children).not.toContain(child as number);- store.selectEntity(entity1, 'replace');- expect(store.selectedEntities.size).toBe(1);+ const parent2Data = store.getEntityData(parent2 as number);+ expect(parent2Data!.children).toContain(child as number);+ });- store.selectAsset({ path: 'test.png', type: 'image', name: 'test.png' });- expect(store.selectedEntities.size).toBe(0);+ it('reparents entity to root', () => {+ const parent = store.createEntity('Parent');+ const child = store.createEntity('Child', parent);++ store.reparentEntity(child, null);++ const childData = store.getEntityData(child as number);+ expect(childData!.parent).toBeNull();+ });});- it('removes deleted entity from selection', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');+ // =========================================================================+ // Undo/Redo+ // =========================================================================++ describe('undo/redo', () => {+ it('initially cannot undo or redo', () => {+ expect(store.canUndo).toBe(false);+ expect(store.canRedo).toBe(false);+ });++ it('can undo after creating entity', () => {+ store.createEntity('Entity1');+ expect(store.canUndo).toBe(true);+ });++ it('undo reverses entity creation', () => {+ const initialCount = store.scene.entities.length;+ const entity = store.createEntity('Entity1');++ expect(store.scene.entities.length).toBe(initialCount + 1);++ store.undo();++ expect(store.scene.entities.length).toBe(initialCount);+ });++ it('redo re-applies entity creation', () => {+ const initialCount = store.scene.entities.length;+ store.createEntity('Entity1');+ store.undo();++ expect(store.scene.entities.length).toBe(initialCount);++ store.redo();++ expect(store.scene.entities.length).toBe(initialCount + 1);+ });++ it('undo property change restores old value', () => {+ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { opacity: 1.0 });+ store.updateProperty(entity, 'Sprite', 'opacity', 1.0, 0.5);++ const comp = store.getComponent(entity, 'Sprite');+ expect(comp!.data.opacity).toBe(0.5);++ store.undo();++ const comp2 = store.getComponent(entity, 'Sprite');+ expect(comp2!.data.opacity).toBe(1.0);+ });++ it('redo property change applies new value', () => {+ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { opacity: 1.0 });+ store.updateProperty(entity, 'Sprite', 'opacity', 1.0, 0.5);+ store.undo();+ store.redo();++ const comp = store.getComponent(entity, 'Sprite');+ expect(comp!.data.opacity).toBe(0.5);+ });++ it('undo rename restores old name', () => {+ const entity = store.createEntity('OldName');+ store.renameEntity(entity, 'NewName');++ store.undo();++ const data = store.getEntityData(entity as number);+ expect(data!.name).toBe('OldName');+ });++ it('marks dirty after undo', () => {+ store.createEntity('Entity1');+ store.markSaved();+ expect(store.isDirty).toBe(false);- store.selectEntity(entity1, 'replace');- store.selectEntity(entity2, 'add');- expect(store.selectedEntities.size).toBe(2);+ store.undo();+ expect(store.isDirty).toBe(true);+ });- store.deleteEntity(entity1);- expect(store.selectedEntities.size).toBe(1);- expect(store.selectedEntities.has(entity2 as number)).toBe(true);+ it('marks dirty after redo', () => {+ store.createEntity('Entity1');+ store.undo();+ store.markSaved();++ store.redo();+ expect(store.isDirty).toBe(true);+ });+ });++ // =========================================================================+ // Subscriptions+ // =========================================================================++ describe('subscriptions', () => {+ it('subscribe returns unsubscribe function', () => {+ let callCount = 0;+ const unsubscribe = store.subscribe(() => callCount++);++ store.createEntity('Entity1');++ unsubscribe();+ });++ it('property change listener fires on updateProperty', () => {+ const events: Array<{ entity: number; componentType: string; propertyName: string }> = [];+ store.subscribeToPropertyChanges((event) => {+ events.push({ entity: event.entity, componentType: event.componentType, propertyName: event.propertyName });+ });++ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { opacity: 1.0 });+ store.updateProperty(entity, 'Sprite', 'opacity', 1.0, 0.5);++ expect(events.length).toBeGreaterThanOrEqual(1);+ const lastEvent = events[events.length - 1];+ expect(lastEvent.componentType).toBe('Sprite');+ expect(lastEvent.propertyName).toBe('opacity');+ });++ it('hierarchy change listener fires on reparent', () => {+ const events: Array<{ entity: number; newParent: number | null }> = [];+ store.subscribeToHierarchyChanges((event) => {+ events.push({ entity: event.entity, newParent: event.newParent });+ });++ const parent = store.createEntity('Parent');+ const child = store.createEntity('Child');+ store.reparentEntity(child, parent);++ expect(events.length).toBe(1);+ expect(events[0].entity).toBe(child as number);+ expect(events[0].newParent).toBe(parent as number);+ });++ it('entity lifecycle listener fires on create/delete', () => {+ const events: Array<{ entity: number; type: string }> = [];+ store.subscribeToEntityLifecycle((event) => {+ events.push({ entity: event.entity, type: event.type });+ });++ const entity = store.createEntity('Entity1');+ store.deleteEntity(entity);++ expect(events.length).toBe(2);+ expect(events[0].type).toBe('created');+ expect(events[1].type).toBe('deleted');+ });++ it('component change listener fires on add/remove', () => {+ const events: Array<{ entity: number; componentType: string; action: string }> = [];+ store.subscribeToComponentChanges((event) => {+ events.push({ entity: event.entity, componentType: event.componentType, action: event.action });+ });++ const entity = store.createEntity('Entity1');+ store.addComponent(entity, 'Sprite', { opacity: 1.0 });++ expect(events.length).toBe(1);+ expect(events[0].action).toBe('added');+ expect(events[0].componentType).toBe('Sprite');+ });++ it('unsubscribe stops notifications', () => {+ let callCount = 0;+ const unsubscribe = store.subscribeToEntityLifecycle(() => callCount++);++ store.createEntity('Entity1');+ expect(callCount).toBe(1);++ unsubscribe();+ store.createEntity('Entity2');+ expect(callCount).toBe(1);+ });++ it('focus entity listener fires', () => {+ const focusedEntities: number[] = [];+ store.onFocusEntity((id) => focusedEntities.push(id));++ const entity = store.createEntity('Entity1');+ store.focusEntity(entity as number);++ expect(focusedEntities).toContain(entity as number);+ });++ it('visibility listener fires on toggle', () => {+ const events: Array<{ entity: number; visible: boolean }> = [];+ store.subscribeToVisibilityChanges((event) => {+ events.push({ entity: event.entity, visible: event.visible });+ });++ const entity = store.createEntity('Entity1');+ store.toggleVisibility(entity as number);++ expect(events.length).toBeGreaterThanOrEqual(1);+ });});- it('deletes all selected entities', () => {- const initialCount = store.scene.entities.length;- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');- const entity3 = store.createEntity('Entity3');+ // =========================================================================+ // Visibility+ // =========================================================================++ describe('visibility', () => {+ it('entity is visible by default', () => {+ const entity = store.createEntity('Entity1');+ expect(store.isEntityVisible(entity as number)).toBe(true);+ });++ it('toggleVisibility hides visible entity', () => {+ const entity = store.createEntity('Entity1');+ store.toggleVisibility(entity as number);++ expect(store.isEntityVisible(entity as number)).toBe(false);+ });- store.selectEntity(entity1, 'replace');- store.selectEntity(entity2, 'add');+ it('toggleVisibility shows hidden entity', () => {+ const entity = store.createEntity('Entity1');+ store.toggleVisibility(entity as number);+ store.toggleVisibility(entity as number);- expect(store.scene.entities.length).toBe(initialCount + 3);- store.deleteSelectedEntities();+ expect(store.isEntityVisible(entity as number)).toBe(true);+ });- expect(store.scene.entities.length).toBe(initialCount + 1);- expect(store.selectedEntities.size).toBe(0);- expect(store.scene.entities.find(e => e.id === entity3 as number)).toBeDefined();+ it('returns true for non-existent entity (no data means not explicitly hidden)', () => {+ expect(store.isEntityVisible(99999)).toBe(true);+ });});- it('returns single entity for single selection', () => {- const entity1 = store.createEntity('Entity1');+ // =========================================================================+ // Scene Version+ // =========================================================================++ describe('scene version', () => {+ it('is a non-negative integer', () => {+ expect(store.sceneVersion).toBeGreaterThanOrEqual(0);+ expect(Number.isInteger(store.sceneVersion)).toBe(true);+ });+ });++ // =========================================================================+ // Entity Data Access+ // =========================================================================++ describe('entity data access', () => {+ it('getEntityData returns data for existing entity', () => {+ const entity = store.createEntity('TestEntity');+ const data = store.getEntityData(entity as number);++ expect(data).not.toBeNull();+ expect(data!.name).toBe('TestEntity');+ expect(data!.id).toBe(entity as number);+ });- store.selectEntity(entity1, 'replace');- expect(store.selectedEntity).toBe(entity1);+ it('getEntityData returns null for non-existent entity', () => {+ expect(store.getEntityData(99999)).toBeNull();+ });- const entityData = store.getSelectedEntityData();- expect(entityData).toBeDefined();- expect(entityData?.id).toBe(entity1 as number);+ it('getSelectedEntitiesData returns data for all selected', () => {+ const e1 = store.createEntity('E1');+ const e2 = store.createEntity('E2');+ const e3 = store.createEntity('E3');++ store.selectEntities([e1 as number, e2 as number, e3 as number]);++ const data = store.getSelectedEntitiesData();+ expect(data.length).toBe(3);+ });++ it('getSelectedEntitiesData filters out invalid entities', () => {+ const e1 = store.createEntity('E1');+ store.selectEntities([e1 as number, 99999]);++ const data = store.getSelectedEntitiesData();+ expect(data.length).toBe(1);+ });+ });++ // =========================================================================+ // Prefab-related queries (without async)+ // =========================================================================++ describe('prefab queries', () => {+ it('isPrefabInstance returns false for normal entities', () => {+ const entity = store.createEntity('Entity1');+ expect(store.isPrefabInstance(entity as number)).toBe(false);+ });++ it('isPrefabRoot returns false for normal entities', () => {+ const entity = store.createEntity('Entity1');+ expect(store.isPrefabRoot(entity as number)).toBe(false);+ });++ it('getPrefabInstanceId returns undefined for normal entities', () => {+ const entity = store.createEntity('Entity1');+ expect(store.getPrefabInstanceId(entity as number)).toBeUndefined();+ });++ it('getPrefabPath returns undefined for normal entities', () => {+ const entity = store.createEntity('Entity1');+ expect(store.getPrefabPath(entity as number)).toBeUndefined();+ });++ it('isEditingPrefab is false initially', () => {+ expect(store.isEditingPrefab).toBe(false);+ expect(store.prefabEditingPath).toBeNull();+ });});- it('returns null for multi-selection', () => {- const entity1 = store.createEntity('Entity1');- const entity2 = store.createEntity('Entity2');+ // =========================================================================+ // Integration: Scene Create -> Edit -> Save -> Reload -> Verify+ // =========================================================================++ describe('integration: scene lifecycle', () => {+ it('create entities, modify, save, reload, verify', () => {+ store.newScene('Integration Test');++ const entity1 = store.createEntity('Player');+ const entity2 = store.createEntity('Enemy');+ const entity3 = store.createEntity('Weapon', entity1);++ store.addComponent(entity1, 'Sprite', { opacity: 1.0, color: { r: 255, g: 0, b: 0, a: 255 } });+ store.addComponent(entity2, 'Sprite', { opacity: 0.5 });++ store.updateProperty(entity1, 'Sprite', 'opacity', 1.0, 0.8);+ store.renameEntity(entity2, 'Boss');++ const sceneCopy: SceneData = JSON.parse(JSON.stringify(store.scene));++ store.markSaved('/test/integration.json');+ expect(store.isDirty).toBe(false);++ store.loadScene(sceneCopy, '/test/integration.json');++ expect(store.scene.name).toBe('Integration Test');+ expect(store.filePath).toBe('/test/integration.json');++ const playerData = store.scene.entities.find(e => e.name === 'Player');+ expect(playerData).toBeDefined();+ const playerSprite = playerData!.components.find(c => c.type === 'Sprite');+ expect(playerSprite).toBeDefined();+ expect(playerSprite!.data.opacity).toBe(0.8);++ const bossData = store.scene.entities.find(e => e.name === 'Boss');+ expect(bossData).toBeDefined();++ const weaponData = store.scene.entities.find(e => e.name === 'Weapon');+ expect(weaponData).toBeDefined();+ expect(weaponData!.parent).toBe(playerData!.id);+ });++ it('undo/redo across multiple operation types', () => {+ const entity = store.createEntity('Player');+ store.addComponent(entity, 'Sprite', { opacity: 1.0 });+ store.updateProperty(entity, 'Sprite', 'opacity', 1.0, 0.5);+ store.renameEntity(entity, 'Hero');++ expect(store.getEntityData(entity as number)!.name).toBe('Hero');++ store.undo();+ expect(store.getEntityData(entity as number)!.name).toBe('Player');++ store.undo();+ expect(store.getComponent(entity, 'Sprite')!.data.opacity).toBe(1.0);++ store.redo();+ expect(store.getComponent(entity, 'Sprite')!.data.opacity).toBe(0.5);++ store.redo();+ expect(store.getEntityData(entity as number)!.name).toBe('Hero');+ });++ it('hierarchy operations with undo', () => {+ const parent = store.createEntity('Parent');+ const child = store.createEntity('Child');++ store.reparentEntity(child, parent);++ expect(store.getEntityData(child as number)!.parent).toBe(parent as number);+ expect(store.getEntityData(parent as number)!.children).toContain(child as number);++ store.undo();++ expect(store.getEntityData(child as number)!.parent).toBeNull();+ expect(store.getEntityData(parent as number)!.children).not.toContain(child as number);+ });++ it('delete entity with undo preserves data', () => {+ const entity = store.createEntity('ToDelete');+ store.addComponent(entity, 'Sprite', { opacity: 0.5 });+ const entityId = entity as number;++ store.deleteEntity(entity);+ expect(store.scene.entities.find(e => e.id === entityId)).toBeUndefined();++ store.undo();+ expect(store.scene.entities.find(e => e.id === entityId)).toBeDefined();++ const restored = store.getEntityData(entityId);+ expect(restored!.name).toBe('ToDelete');+ const comp = restored!.components.find(c => c.type === 'Sprite');+ expect(comp).toBeDefined();+ expect(comp!.data.opacity).toBe(0.5);+ });++ it('multiple entity deletion with compound undo', () => {+ const initialCount = store.scene.entities.length;+ const e1 = store.createEntity('E1');+ const e2 = store.createEntity('E2');+ const e3 = store.createEntity('E3');- store.selectEntity(entity1, 'replace');- store.selectEntity(entity2, 'add');+ store.selectEntity(e1, 'replace');+ store.selectEntity(e2, 'add');+ store.selectEntity(e3, 'add');- expect(store.selectedEntity).toBeNull();- expect(store.getSelectedEntityData()).toBeNull();+ store.deleteSelectedEntities();+ expect(store.scene.entities.length).toBe(initialCount);- const entitiesData = store.getSelectedEntitiesData();- expect(entitiesData.length).toBe(2);+ store.undo();+ expect(store.scene.entities.length).toBe(initialCount + 3);+ });});});diff --git a/editor/src/bridge/EditorBridge.ts b/editor/src/bridge/EditorBridge.tsindex ec15642c7..80db7ff3d 100644--- a/editor/src/bridge/EditorBridge.ts+++ b/editor/src/bridge/EditorBridge.ts@@ -38,14 +38,26 @@ export class EditorBridge {if (!this.module_ || !this.world_) return;const scene = this.store_.scene;+ const entityMap = new Map<number, Entity>();for (const entityData of scene.entities) {const entity = this.world_.spawn();+ entityMap.set(entityData.id, entity);for (const comp of entityData.components) {this.addComponentToRuntime(entity, comp);}}++ for (const entityData of scene.entities) {+ if (entityData.parent !== null) {+ const entity = entityMap.get(entityData.id);+ const parentEntity = entityMap.get(entityData.parent);+ if (entity !== undefined && parentEntity !== undefined) {+ this.world_.setParent(entity, parentEntity);+ }+ }+ }}syncFromRuntime(): SceneData {diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsindex a6f7e630b..76f38a2ef 100644--- a/editor/src/builder/ArtifactBuilder.ts+++ b/editor/src/builder/ArtifactBuilder.ts@@ -65,7 +65,14 @@ export async function buildArtifact(let atlasInputHash: string | undefined;if (buildCache) {const cacheData = await buildCache.loadCache(config.id || 'default');- atlasInputHash = await buildCache.computeAtlasInputHash(imagePaths);+ const allTextureMetadata: Record<string, unknown> = {};+ for (const { data } of sceneDataList) {+ const meta = data.textureMetadata as Record<string, unknown> | undefined;+ if (meta) {+ Object.assign(allTextureMetadata, meta);+ }+ }+ atlasInputHash = await buildCache.computeAtlasInputHash(imagePaths, allTextureMetadata);let cachedAtlas = null;if (cacheData?.atlasPages) {diff --git a/editor/src/builder/BuildCache.ts b/editor/src/builder/BuildCache.tsindex cfac5ed03..6764a0605 100644--- a/editor/src/builder/BuildCache.ts+++ b/editor/src/builder/BuildCache.ts@@ -268,9 +268,16 @@ export class BuildCache {}}- async computeAtlasInputHash(imagePaths: string[]): Promise<string> {+ async computeAtlasInputHash(+ imagePaths: string[],+ textureMetadata?: Record<string, unknown>+ ): Promise<string> {const sorted = [...imagePaths].sort();- return computeHash(JSON.stringify(sorted));+ const hashInput: Record<string, unknown> = { paths: sorted };+ if (textureMetadata && Object.keys(textureMetadata).length > 0) {+ hashInput.textureMetadata = textureMetadata;+ }+ return computeHash(JSON.stringify(hashInput));}serializeAtlasPages(pages: any[]): AtlasPageCache[] {diff --git a/editor/src/commands/PropertyCommand.ts b/editor/src/commands/PropertyCommand.tsindex 4452344b9..0053ac052 100644--- a/editor/src/commands/PropertyCommand.ts+++ b/editor/src/commands/PropertyCommand.ts@@ -11,7 +11,7 @@ import { BaseCommand, type Command } from './Command';// Constants// =============================================================================-const MERGE_WINDOW_MS = 500;+const MERGE_WINDOW_MS = 1000;// =============================================================================// PropertyCommanddiff --git a/editor/src/error/GlobalErrorHandler.ts b/editor/src/error/GlobalErrorHandler.tsindex 042463868..d6ee2a253 100644--- a/editor/src/error/GlobalErrorHandler.ts+++ b/editor/src/error/GlobalErrorHandler.ts@@ -1,5 +1,7 @@import { showErrorToast } from '../ui/Toast';+export type ErrorCategory = 'asset_missing' | 'invalid_schema' | 'wasm_crash' | 'unknown';+export function installGlobalErrorHandler(): void {window.addEventListener('error', (event) => {handleError(event.error || new Error(event.message));@@ -12,6 +14,44 @@ export function installGlobalErrorHandler(): void {});}+function categorizeError(error: Error): ErrorCategory {+ const msg = error.message.toLowerCase();++ if (msg.includes('failed to load') || msg.includes('not found') ||+ msg.includes('not embedded') || msg.includes('404') ||+ msg.includes('failed to fetch')) {+ return 'asset_missing';+ }++ if (msg.includes('invalid') && (msg.includes('schema') || msg.includes('format') || msg.includes('json')) ||+ msg.includes('unexpected token') || msg.includes('parse error')) {+ return 'invalid_schema';+ }++ if (msg.includes('wasm') || msg.includes('unreachable') ||+ msg.includes('RuntimeError') || msg.includes('memory access') ||+ error.name === 'RuntimeError') {+ return 'wasm_crash';+ }++ return 'unknown';+}++const CATEGORY_MESSAGES: Record<ErrorCategory, string> = {+ asset_missing: 'An asset file could not be found. Check that the file path is correct and the asset exists in the project.',+ invalid_schema: 'A file has an invalid format. It may be corrupted or use an unsupported schema version.',+ wasm_crash: 'The engine runtime encountered a fatal error. Try reloading the editor.',+ unknown: 'An unexpected error occurred. Check the console for details.',+};+function handleError(error: Error): void {- showErrorToast('An unexpected error occurred. Check console for details.');+ const category = categorizeError(error);++ console.error(`[ESEngine:${category}]`, {+ message: error.message,+ stack: error.stack,+ category,+ });++ showErrorToast(CATEGORY_MESSAGES[category], error.message);}diff --git a/editor/src/error/index.ts b/editor/src/error/index.tsindex fcc026055..1eb320e72 100644--- a/editor/src/error/index.ts+++ b/editor/src/error/index.ts@@ -1,4 +1,4 @@export { ErrorBoundary } from './ErrorBoundary';export type { ErrorBoundaryOptions } from './ErrorBoundary';export { createErrorFallback } from './ErrorFallback';-export { installGlobalErrorHandler } from './GlobalErrorHandler';+export { installGlobalErrorHandler, type ErrorCategory } from './GlobalErrorHandler';diff --git a/editor/src/index.ts b/editor/src/index.tsindex 5d428f1e3..fcc3d2c20 100644--- a/editor/src/index.ts+++ b/editor/src/index.ts@@ -45,6 +45,7 @@ export {EditorStore,getEditorStore,resetEditorStore,+ type DirtyFlag,type EditorState,type EditorListener,} from './store';diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.tsindex a2a1cc3bf..0c2c67a88 100644--- a/editor/src/panels/InspectorPanel.ts+++ b/editor/src/panels/InspectorPanel.ts@@ -127,7 +127,17 @@ export class InspectorPanel {const asset = this.store_.selectedAsset;if (selectedEntities.length === 1) {- this.renderEntityInspector(selectedEntities[0] as Entity);+ const entity = selectedEntities[0] as Entity;+ if (this.needsStructureRebuild(entity)) {+ this.rebuildEntityStructure(entity);+ } else if (this.currentEntity_ === entity) {+ this.updateEditors();+ this.updateVisibilityIcon();+ const entityData = this.store_.getSelectedEntityData();+ if (entityData) {+ renderMaterialPreview(this.materialPreviewState_, entity, entityData.components, this.store_);+ }+ }} else if (selectedEntities.length > 1) {this.renderMultiEntityInspector(selectedEntities as Entity[]);} else if (asset !== null) {@@ -137,6 +147,17 @@ export class InspectorPanel {}}+ private needsStructureRebuild(entity: Entity): boolean {+ if (entity !== this.currentEntity_) return true;+ if (this.currentAssetPath_ !== null) return true;++ const entityData = this.store_.getSelectedEntityData();+ const componentCount = entityData?.components.length ?? 0;+ const prefabPath = entityData?.prefab?.prefabPath;++ return componentCount !== this.currentComponentCount_ || prefabPath !== this.currentPrefabPath_;+ }+private renderEmptyState(): void {if (this.currentEntity_ === null && this.currentAssetPath_ === null) {return;@@ -156,25 +177,11 @@ export class InspectorPanel {// Entity Inspector// =========================================================================- private renderEntityInspector(entity: Entity): void {+ private rebuildEntityStructure(entity: Entity): void {const entityData = this.store_.getSelectedEntityData();const componentCount = entityData?.components.length ?? 0;const prefabPath = entityData?.prefab?.prefabPath;- const entityChanged = entity !== this.currentEntity_;- const componentsChanged = componentCount !== this.currentComponentCount_;- const prefabChanged = prefabPath !== this.currentPrefabPath_;- const wasAsset = this.currentAssetPath_ !== null;-- if (!entityChanged && !componentsChanged && !prefabChanged && !wasAsset) {- this.updateEditors();- this.updateVisibilityIcon();- if (entityData) {- renderMaterialPreview(this.materialPreviewState_, entity, entityData.components, this.store_);- }- return;- }-this.currentEntity_ = entity;this.currentAssetPath_ = null;this.currentComponentCount_ = componentCount;diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex b82dc2f2b..591336f98 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -51,6 +51,7 @@ export class SceneViewPanel {private unsubscribeFocus_: (() => void) | null = null;private animationId_: number | null = null;private continuousRender_ = false;+ private isDirty_ = true;private resizeObserver_: ResizeObserver | null = null;private projectPath_: string | null = null;private app_: App | null = null;@@ -859,17 +860,39 @@ export class SceneViewPanel {}private requestRender(): void {+ this.isDirty_ = true;if (this.animationId_ !== null) return;this.animationId_ = requestAnimationFrame(() => {this.animationId_ = null;- try {- this.render();- } catch (e) {- console.warn('[SceneViewPanel] Render error, skipping frame:', e);+ if (this.isDirty_) {+ this.isDirty_ = false;+ try {+ this.render();+ } catch (e) {+ console.warn('[SceneViewPanel] Render error, skipping frame:', e);+ }}if (this.continuousRender_) {- this.requestRender();+ this.scheduleNextFrame();+ }+ });+ }++ private scheduleNextFrame(): void {+ if (this.animationId_ !== null) return;+ this.animationId_ = requestAnimationFrame(() => {+ this.animationId_ = null;+ if (this.isDirty_) {+ this.isDirty_ = false;+ try {+ this.render();+ } catch (e) {+ console.warn('[SceneViewPanel] Render error, skipping frame:', e);+ }+ }+ if (this.continuousRender_) {+ this.scheduleNextFrame();}});}diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex 6e505323e..c8b58fa65 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -63,7 +63,9 @@ export interface EditorState {filePath: string | null;}-export type EditorListener = (state: EditorState) => void;+export type DirtyFlag = 'scene' | 'selection' | 'hierarchy' | 'property';++export type EditorListener = (state: EditorState, dirtyFlags?: ReadonlySet<DirtyFlag>) => void;export interface PropertyChangeEvent {entity: number;@@ -121,6 +123,7 @@ export class EditorStore {private componentChangeListeners_: Set<ComponentChangeListener> = new Set();private sceneSyncListeners_: Set<() => void> = new Set();private pendingNotify_ = false;+ private dirtyFlags_: Set<DirtyFlag> = new Set();private nextEntityId_ = 1;private sceneVersion_ = 0;private worldTransforms_ = new WorldTransformCache();@@ -221,7 +224,7 @@ export class EditorStore {this.rebuildEntityMap();this.worldTransforms_.setScene(this.state_.scene);this.notifySceneSync();- this.notify();+ this.notify('scene');}loadScene(scene: SceneData, filePath: string | null = null): void {@@ -237,7 +240,7 @@ export class EditorStore {this.rebuildEntityMap();this.worldTransforms_.setScene(scene);this.notifySceneSync();- this.notify();+ this.notify('scene');}markSaved(filePath: string | null = null): void {@@ -245,7 +248,7 @@ export class EditorStore {if (filePath) {this.state_.filePath = filePath;}- this.notify();+ this.notify('scene');}// =========================================================================@@ -275,7 +278,7 @@ export class EditorStore {if (!this.setsEqual(oldSelection, this.state_.selectedEntities)) {this.state_.selectedAsset = null;- this.notify();+ this.notify('selection');}}@@ -285,7 +288,7 @@ export class EditorStore {this.state_.selectedEntities.add(id);}this.state_.selectedAsset = null;- this.notify();+ this.notify('selection');}selectRange(fromEntity: number, toEntity: number): void {@@ -332,7 +335,7 @@ export class EditorStore {selectAsset(asset: AssetSelection | null): void {this.state_.selectedAsset = asset;this.state_.selectedEntities.clear();- this.notify();+ this.notify('selection');}getSelectedEntityData(): EntityData | null {@@ -775,7 +778,7 @@ export class EditorStore {}this.state_.isDirty = true;- this.notify();+ this.notify('scene');return true;}@@ -874,7 +877,7 @@ export class EditorStore {const synced = await syncPrefabInstances(saved.scene, editedPrefabPath);this.loadScene(saved.scene, saved.filePath);this.state_.isDirty = saved.isDirty || synced || saveFailed;- this.notify();+ this.notify('scene');}async savePrefabEditing(): Promise<boolean> {@@ -884,7 +887,7 @@ export class EditorStore {const saved = await savePrefabToPath(prefab, this.prefabEditingPath_);if (saved) {this.state_.isDirty = false;- this.notify();+ this.notify('scene');}return saved;}@@ -928,7 +931,10 @@ export class EditorStore {// =========================================================================notifyChange(): void {- this.notify();+ this.notify('scene');+ this.notify('selection');+ this.notify('hierarchy');+ this.notify('property');}subscribe(listener: EditorListener): () => void {@@ -983,7 +989,7 @@ export class EditorStore {this.syncDerivedProperties();this.notifySceneSync();- this.notify();+ this.notify(cmd.structural ? 'hierarchy' : 'scene');}private notifySceneSync(): void {@@ -992,14 +998,17 @@ export class EditorStore {}}- private notify(): void {+ private notify(flag: DirtyFlag = 'scene'): void {+ this.dirtyFlags_.add(flag);if (this.pendingNotify_) return;this.pendingNotify_ = true;this.sceneVersion_++;requestAnimationFrame(() => {this.pendingNotify_ = false;+ const flags = new Set(this.dirtyFlags_);+ this.dirtyFlags_.clear();for (const listener of this.listeners_) {- listener(this.state_);+ listener(this.state_, flags);}});}diff --git a/editor/src/store/index.ts b/editor/src/store/index.tsindex 2449b3b72..8ecacbc1d 100644--- a/editor/src/store/index.ts+++ b/editor/src/store/index.ts@@ -7,6 +7,7 @@ export {EditorStore,getEditorStore,resetEditorStore,+ type DirtyFlag,type EditorState,type EditorListener,type PropertyChangeEvent,diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 924c37aee..4cc8e7ea3 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -69,6 +69,8 @@ export class App {private physicsModule_?: unknown;private readonly installed_plugins_ = new Set<Plugin>();private error_handler_: ((error: unknown, systemName: string) => void) | null = null;+ private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;+ private frame_paused_ = false;private constructor() {this.world_ = new World();@@ -202,6 +204,11 @@ export class App {return this;}+ onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this {+ this.system_error_handler_ = handler;+ return this;+ }+// =========================================================================// Resource Access// =========================================================================@@ -266,6 +273,7 @@ export class App {this.updateTime(delta);this.world_.resetQueryPool();+ this.frame_paused_ = false;this.runSchedule(Schedule.First);@@ -385,7 +393,7 @@ export class App {private runSchedule(schedule: Schedule): void {let systems = this.systems_.get(schedule);- if (!systems || !this.runner_) {+ if (!systems || !this.runner_ || this.frame_paused_) {return;}@@ -402,6 +410,14 @@ export class App {if (this.error_handler_) {this.error_handler_(e, name);}+ if (this.system_error_handler_) {+ const err = e instanceof Error ? e : new Error(String(e));+ const action = this.system_error_handler_(err, name);+ if (action === 'pause') {+ this.frame_paused_ = true;+ return;+ }+ }}}}diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex c94195b51..5ffaae5a5 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -127,6 +127,7 @@ export class AssetServer {private groupAssets_ = new Map<string, AddressableManifestAsset[]>();private spineController_: SpineModuleController | null = null;private spineSkeletons_ = new Map<string, number>();+ private textureRefCounts_ = new Map<string, number>();constructor(module: ESEngineModule) {this.module_ = module;@@ -185,14 +186,28 @@ export class AssetServer {return this.textureCache_.has(this.textureCacheKey(source, true));}+ getTextureRefCount(source: string): number {+ let total = 0;+ for (const flip of [true, false]) {+ total += this.textureRefCounts_.get(this.textureCacheKey(source, flip)) ?? 0;+ }+ return total;+ }+releaseTexture(source: string): void {const rm = this.module_.getResourceManager();for (const flip of [true, false]) {const key = this.textureCacheKey(source, flip);const info = this.textureCache_.get(key);- if (info) {+ if (!info) continue;++ const count = (this.textureRefCounts_.get(key) ?? 1) - 1;+ if (count <= 0) {rm.releaseTexture(info.handle);this.textureCache_.delete(key);+ this.textureRefCounts_.delete(key);+ } else {+ this.textureRefCounts_.set(key, count);}}}@@ -208,6 +223,7 @@ export class AssetServer {this.materialLoader_.releaseAll();Material.releaseAll();this.textureCache_.clearAll();+ this.textureRefCounts_.clear();this.shaderCache_.clearAll();this.fontCache_.clearAll();this.prefabCache_.clearAll();@@ -651,7 +667,9 @@ export class AssetServer {private async loadTextureWithFlip(source: string, flip: boolean): Promise<TextureInfo> {const cacheKey = this.textureCacheKey(source, flip);- return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));+ const info = await this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));+ this.textureRefCounts_.set(cacheKey, (this.textureRefCounts_.get(cacheKey) ?? 0) + 1);+ return info;}private async loadTextureInternal(source: string, flip: boolean): Promise<TextureInfo> {diff --git a/sdk/src/query.ts b/sdk/src/query.tsindex 95243a4bc..be037cc46 100644--- a/sdk/src/query.ts+++ b/sdk/src/query.ts@@ -117,7 +117,11 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu*[Symbol.iterator](): Iterator<QueryResult<C>> {const { _mutIndices, _without } = this.descriptor_;const actualComponents = this.actualComponents_;- const entities = this.world_.getEntitiesWithComponents(this.allRequired_);+ const entities = this.world_.getEntitiesWithComponents(+ this.allRequired_,+ this.descriptor_._with,+ this.descriptor_._without+ );const compCount = actualComponents.length;const hasMut = _mutIndices.length > 0;const hasWithout = _without.length > 0;diff --git a/sdk/src/system.ts b/sdk/src/system.tsindex 9ea3b557f..e2b4046ca 100644--- a/sdk/src/system.ts+++ b/sdk/src/system.ts@@ -132,12 +132,16 @@ export class SystemRunner {args[i] = this.resolveParam(system._params[i]);}- (system._fn as (...args: unknown[]) => void)(...args);+ try {+ (system._fn as (...args: unknown[]) => void)(...args);- for (let i = 0; i < args.length; i++) {- if (args[i] instanceof CommandsInstance) {- (args[i] as CommandsInstance).flush();+ for (let i = 0; i < args.length; i++) {+ if (args[i] instanceof CommandsInstance) {+ (args[i] as CommandsInstance).flush();+ }}+ } finally {+ this.world_.resetIterationDepth();}}diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex 416752abb..c3419fdc0 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -136,6 +136,10 @@ export class World {}}+ resetIterationDepth(): void {+ this.iterationDepth_ = 0;+ }+isIterating(): boolean {return this.iterationDepth_ > 0;}@@ -356,12 +360,22 @@ export class World {this.queryCache_.clear();}- getEntitiesWithComponents(components: AnyComponentDef[]): Entity[] {- if (components.length === 0) {+ getEntitiesWithComponents(+ components: AnyComponentDef[],+ withFilters: AnyComponentDef[] = [],+ withoutFilters: AnyComponentDef[] = []+ ): Entity[] {+ if (components.length === 0 && withFilters.length === 0 && withoutFilters.length === 0) {return this.getAllEntities();}- const cacheKey = components.map(c => c._name).sort().join(',');+ let cacheKey = components.map(c => c._name).sort().join(',');+ if (withFilters.length > 0) {+ cacheKey += '|+' + withFilters.map(c => c._name).sort().join(',');+ }+ if (withoutFilters.length > 0) {+ cacheKey += '|-' + withoutFilters.map(c => c._name).sort().join(',');+ }const cached = this.queryCache_.get(cacheKey);if (cached && cached.version === this.worldVersion_) {return cached.result;diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex f85c6d037..a8fe0b94c 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -98,6 +98,13 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,if (shaderId == 0) return false;+ constexpr u32 MAX_UNIFORMS = 64;+ if (uniformCount > MAX_UNIFORMS) {+ ES_LOG_ERROR("Material {} has {} uniforms (max {}), clamping",+ materialId, uniformCount, MAX_UNIFORMS);+ uniformCount = MAX_UNIFORMS;+ }+if (uniformCount > 0 && uniformBufferPtr != 0) {const u8* ptr = reinterpret_cast<const u8*>(uniformBufferPtr);