Skip to content

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.

docs: add v0.5.1 changelog, new guides, and update existing docs

esengine436f3624a28c
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index 6b392fd92..592efa690 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "ESEngine Editor",
- "version": "0.5.0",
+ "version": "0.5.1",
"identifier": "com.esengine.editor",
"build": {
"frontendDist": "../dist",
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 6699716f5..dfc3ce3c0 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -106,6 +106,7 @@ export default defineConfig({
label: 'Changelog',
translations: { 'zh-CN': '更新日志' },
items: [
+ { label: 'v0.5.1', slug: 'changelog-v051' },
{ label: 'v0.5.0', slug: 'changelog-v050' },
{ label: 'v0.4.3', slug: 'changelog-v043' },
{ label: 'v0.4.2', slug: 'changelog-v042' },
diff --git a/docs/astro/src/content/docs/changelog-v051.mdx b/docs/astro/src/content/docs/changelog-v051.mdx
new file mode 100644
index 000000000..560a3db52
--- /dev/null
+++ b/docs/astro/src/content/docs/changelog-v051.mdx
@@ -0,0 +1,143 @@
+---
+title: v0.5.1
+description: ESEngine v0.5.1 release notes
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+<Aside type="tip">
+v0.5.1 brings a Game View panel with play mode, dockable panel layout, Content Drawer, scene management, project settings, and extensive editor and runtime improvements.
+</Aside>
+
+## Game View Panel
+
+- Added Game View panel with play/pause/stop controls and single-frame step
+- Resolution presets (Free Aspect, 16:9, 9:16, 4:3, 1:1) plus custom resolution input
+- Playback speed control and real-time FPS counter
+- Isolated iframe-based preview with its own WASM instance (preserves Scene View renderer)
+- Game panel available as a tab next to Scene in default layout
+
+## Play Mode
+
+- Hierarchy and Inspector panels display runtime entities during play
+- Hierarchy shows runtime entity tree with parent-child relationships
+- Inspector renders live runtime properties with auto-refresh
+- Runtime property editing via `world.insert()` for builtin components
+- Blue "RUNTIME" badge and top border indicate active play mode
+
+## Dockview Layout System
+
+- Replaced fixed splitter layout with dockview-core for drag-drop dockable panels
+- Tabbed panel groups, drag panels between groups, layout persistence in localStorage
+- "Reset Layout" command to restore default arrangement
+
+## Content Drawer
+
+- Content Drawer opens as a slide-up panel from statusbar (Ctrl+Space)
+- Auto-hides on click-outside or Escape key
+- "Dock in Layout" button moves content browser into dockview
+- Drawer and docked panel can coexist independently
+- Resizable drag handle with height persisted in localStorage
+- Pin button to keep drawer open
+
+## Scene Management
+
+- Added `SceneManager` resource with `load`/`unload`/`switchTo`/`loadAdditive`/`pause`/`resume`/`sleep`/`wake`
+- `SceneOwner` component for entity-to-scene lifetime tracking
+- Scene-scoped draw callbacks and camera filtering by active scenes
+- Built-in fade transition in `switchTo()` and standalone `transitionTo()` with fade/crossfade
+- `wrapSceneSystem()` for conditional system execution based on scene status
+- Integrated into build pipeline templates (Playable + WeChat)
+
+## Project Settings
+
+- Exposed 12 hardcoded defaults as configurable project settings
+- `RuntimeConfig` in SDK for runtime-configurable defaults (transition duration, default font, canvas scale mode, max delta time, fixed timestep iterations, text canvas size)
+- Editor Settings panel extended with Build and Runtime sections
+- Settings wired through preview config and build templates
+
+## SDK & Runtime
+
+- System dependency ordering via `runBefore`/`runAfter` with topological sort
+- Playback control API: `setPaused`, `stepFrame`, `setPlaySpeed`
+- Error handling: `onSystemError` callback per system, `onWasmError` boundary with graceful degradation
+- Centralized logger with pluggable handlers
+- Prefab nesting depth guard (`MAX_DEPTH=10`)
+- `AssetRefCounter` for asset usage monitoring
+- `setPipeline()` method replacing unsafe cast
+- Warning for unknown uniform names
+- Fix `EventSource`/`TextInput`/input listener leaks, add cleanup on `quit()`
+
+## Editor Improvements
+
+### Scene View
+
+- Marquee box selection (click-drag to select multiple entities)
+- Snap-to-grid (Ctrl+drag) with configurable grid size
+- Keyboard shortcuts: F (focus), Delete, arrow keys, zoom
+- Space+drag pan, Shift rotation angle snap
+- Adaptive grid subdivision
+
+### Inspector
+
+- Component context menu (reset, copy, paste, reorder)
+- Property reset-to-default
+- AddComponent keyboard navigation with search highlight
+- Responsive labels and component icons
+- Runtime entity property editing in play mode
+
+### Hierarchy
+
+- Inline rename (F2 / context menu / slow double-click)
+- Arrow key navigation with expand/collapse
+- Multi-select: Ctrl+click, Shift+click range, Ctrl+A select all
+- Cut (Ctrl+X), recursive duplicate, collapse/expand all
+- ARIA tree roles for accessibility
+
+### Content Browser
+
+- Fuzzy search with recursive file matching
+- Image thumbnails with LRU cache
+- Grid/list view toggle
+- Multi-select (Ctrl/Shift) with keyboard navigation
+- Empty state display and back button
+- ARIA grid role for accessibility
+
+### Output Panel
+
+- Timestamps on each log entry
+- Type filters (info/warn/error) with count badges
+- Search within output
+- Context menu copy and command grouping
+
+### Keyboard Shortcuts
+
+- Ctrl+X cut entities
+- Ctrl+Space toggle Content Drawer
+- Ctrl+1/2/3 panel focus
+- Ctrl+Shift+N new entity
+- Ctrl+Shift+Z redo
+- Ctrl+S save in input fields
+- Escape handling for dialogs and drawer
+
+## Performance
+
+- AABB-based frustum culling
+- Fast path for non-rotated quad rendering
+- Shader uniform lookups with pre-resolved integer location IDs
+- Shader hot-reload in editor mode
+
+## Bug Fixes
+
+- Fix `SceneManager.switchTo()` reentrancy during active transitions
+- Fix `SceneManager.load()`/`loadAdditive()` race conditions on concurrent loads
+- Fix `PostProcessPipeline` FBO leak on resize
+- Fix scene transition silent failures from unawaited promises
+- Fix editor panel memory leaks (canvas listeners, scroll listeners, context menu timers)
+- Fix entity selection not cleared after deletion
+- Fix stale undo closure, drag undo flooding, zoom DPR on Retina displays
+- Fix settings validation, color range, toast XSS, statusbar footer count
+- Fix `deleteSelectedEntities` undo collecting descendants before command execution
+- Fix prefab save with retry/discard dialog, add auto-save and recovery
+- Fix WebGL context init using `GL.registerContext` + `initRendererWithContext`
+- Fix runtime scene validation errors
diff --git a/docs/astro/src/content/docs/core-concepts/queries.mdx b/docs/astro/src/content/docs/core-concepts/queries.mdx
index 83d3d01af..a089192f1 100644
--- a/docs/astro/src/content/docs/core-concepts/queries.mdx
+++ b/docs/astro/src/content/docs/core-concepts/queries.mdx
@@ -147,6 +147,29 @@ addSystem(defineSystem(
));
```
+## Iteration Safety
+
+During query iteration, you **cannot** directly create or destroy entities, or insert or remove components. These operations modify the underlying data structures and would invalidate the iterator. The engine detects such operations during iteration and throws an error to prevent data corruption.
+
+The correct approach is to use `Commands` to defer modifications until after iteration completes:
+
+```typescript
+import { defineSystem, addSystem, Commands, Query, Health } from 'esengine';
+
+const despawnDead = defineSystem(
+ [Commands(), Query(Health)],
+ (commands, query) => {
+ for (const [entity, health] of query) {
+ if (health.value <= 0) {
+ commands.despawn(entity); // deferred, safe
+ }
+ }
+ }
+);
+```
+
+`Commands` operations are flushed after the current system function returns. At that point iteration has finished, so the modifications do not affect any in-progress traversal.
+
## Next Steps
- [Resources](/microes/core-concepts/resources/) — global singleton data like Time and Input
diff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdx
index 73f179b15..577b4a3de 100644
--- a/docs/astro/src/content/docs/core-concepts/systems.mdx
+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx
@@ -58,12 +58,48 @@ addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);
<Aside type="note">
The Fixed schedules (`FixedPreUpdate`, `FixedUpdate`, `FixedPostUpdate`) run at a fixed timestep of 1/60s using an accumulator. In a single frame they may execute zero or multiple times depending on the frame duration, up to a maximum of **8 iterations** per frame. Use them for physics and other deterministic logic that requires consistent time steps.
+
+ The maximum number of iterations is configurable via `RuntimeConfig`:
+
+ ```typescript
+ import { RuntimeConfig } from 'esengine';
+ RuntimeConfig.maxFixedSteps = 8; // default
+ ```
</Aside>
<Aside type="note">
Delta time is clamped to a maximum of **250ms** (0.25s). If a frame takes longer (e.g., due to a tab being inactive), the excess time is discarded to prevent large simulation jumps.
</Aside>
+## System Ordering
+
+By default, systems within the same Schedule run in registration order. If you need to enforce execution order between systems, use the third argument to `defineSystem` to specify `runBefore` or `runAfter`:
+
+```typescript
+import { defineSystem, Query, Res, Time, Mut, LocalTransform, Velocity, Sprite } from 'esengine';
+
+const movementSystem = defineSystem(
+ [Res(Time), Query(Mut(LocalTransform), Velocity)],
+ (time, query) => { /* ... */ },
+ { name: 'movement' }
+);
+
+const renderSystem = defineSystem(
+ [Query(LocalTransform, Sprite)],
+ (query) => { /* ... */ },
+ { name: 'render', runAfter: ['movement'] }
+);
+```
+
+- `runAfter: ['movement']` — the current system runs after `movement`
+- `runBefore: ['render']` — the current system runs before `render`
+
+The engine uses topological sorting to determine the final execution order. If the ordering constraints form a cycle, an error is thrown at startup.
+
+<Aside type="tip">
+ `name` is the basis for ordering. Only systems that participate in ordering need a `name`. Systems without a name cannot be referenced by other systems.
+</Aside>
+
## System Parameters
### Commands
diff --git a/docs/astro/src/content/docs/en/guides/debugging.mdx b/docs/astro/src/content/docs/en/guides/debugging.mdx
index d7e0393da..4dff9d86f 100644
--- a/docs/astro/src/content/docs/en/guides/debugging.mdx
+++ b/docs/astro/src/content/docs/en/guides/debugging.mdx
@@ -1,23 +1,157 @@
---
title: Debugging
-description: Debug ESEngine games with source maps, WASM debugging, and performance profiling
+description: ESEngine debugging tools and error handling
---
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.
+This guide covers ESEngine's runtime debugging tools, including error handling, playback control, the logger system, and editor debugging panels.
-## Source Maps
+## Error Handling
-### Editor Preview
+### System Error Handling
-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.
+When an ECS system throws an exception, the engine prints the error to the console and continues running by default. Register a handler with `app.onSystemError()` to control the post-error behaviour — return `'continue'` to keep executing subsequent systems, or `'pause'` to skip all remaining systems for the current frame:
-### Build Output
+```typescript
+app.onSystemError((error: Error, systemName?: string) => {
+ console.error(`System "${systemName}" failed:`, error.message);
+
+ if (error.message.includes('critical')) {
+ return 'pause';
+ }
+ return 'continue';
+});
+```
+
+After returning `'pause'`, systems that have not yet run in the current frame are skipped, but the render loop does not stop. All systems resume normal execution at the start of the next frame.
+
+### WASM Error Handling
+
+The C++ engine core runs via WebAssembly. Catch errors from the WASM layer with `app.onWasmError()`:
+
+```typescript
+app.onWasmError((error: unknown, context: string) => {
+ console.error(`WASM error in ${context}:`, error);
+});
+```
+
+The `context` parameter identifies the WASM operation that failed (e.g. rendering, physics), making it easier to locate the source of the problem.
+
+<Aside type="note">
+ WASM errors usually indicate abnormal internal engine state. If they occur frequently, check for invalid entity IDs or already-released resources.
+</Aside>
+
+## Playback Control
+
+The SDK provides methods to control game execution at runtime, useful for frame-by-frame debugging and slow-motion analysis.
+
+### Pause and Resume
+
+```typescript
+app.setPaused(true); // Pause: systems stop, only Last schedule (rendering) runs
+app.setPaused(false); // Resume normal execution
+
+app.isPaused(); // Query current pause state
+```
+
+While paused, the engine still runs the render loop (`Schedule.Last`), so the screen stays on the last rendered frame.
+
+### Single-Frame Stepping
+
+While paused, call `stepFrame()` to advance exactly one frame — a full system schedule runs then pauses again:
+
+```typescript
+app.setPaused(true);
+app.stepFrame(); // Execute one full frame of system scheduling
+```
-For playable ad builds, enable **Dev Build** in the build configuration to include source maps. Production builds strip source maps for smaller file size.
+### Play Speed
-For WeChat MiniGame builds, source maps are generated alongside the output. Enable **Source Maps** in WeChat DevTools settings to use them.
+Adjust time flow with `setPlaySpeed()`. The valid range is 0.1 to 4.0:
+
+```typescript
+app.setPlaySpeed(0.25); // Quarter speed — good for observing fast animations
+app.setPlaySpeed(2.0); // Double speed
+
+app.getPlaySpeed(); // Get the current speed multiplier
+```
+
+Play speed works by scaling each frame's `delta` time. All systems that read `Time.delta` are affected automatically.
+
+## Logger System
+
+The SDK provides a centralized logging system with level filtering and custom handlers.
+
+### LogLevel
+
+```typescript
+import { LogLevel, setLogLevel } from 'esengine';
+
+// Debug = 0, Info = 1, Warn = 2, Error = 3
+setLogLevel(LogLevel.Debug); // Output all levels
+setLogLevel(LogLevel.Warn); // Output Warn and Error only
+```
+
+### Using the Logger
+
+Log functions accept a category tag, a message, and optional additional data:
+
+```typescript
+import { debug, info, warn, error } from 'esengine';
+
+debug('Physics', 'Collision detected', { entityA: 1, entityB: 2 });
+info('Scene', 'Level loaded');
+warn('Asset', 'Texture not found, using fallback');
+error('Render', 'WebGL context lost');
+```
+
+The default `ConsoleLogHandler` formats output to the browser console:
+
+```
+[14:32:05.123] [INFO ] [Scene] Level loaded
+```
+
+### Custom LogHandler
+
+Implement the `LogHandler` interface to send logs to a custom destination (remote service, file, UI panel, etc.):
+
+```typescript
+import { getLogger, type LogHandler, type LogEntry } from 'esengine';
+
+const customHandler: LogHandler = {
+ handle(entry: LogEntry) {
+ // entry.timestamp, entry.level, entry.category, entry.message, entry.data
+ myRemoteService.send(entry);
+ }
+};
+
+const logger = getLogger();
+logger.addHandler(customHandler);
+
+// Remove a handler
+logger.removeHandler(customHandler);
+```
+
+## Editor Debugging
+
+### Output Panel
+
+The editor's Output panel captures all runtime console output:
+
+- **Timestamps** — each log entry includes millisecond-precision timing
+- **Type filtering** — filter by info, warn, or error
+- **Search** — search for keywords within log text
+
+### Game View Playback Controls
+
+The editor's Game View panel provides a graphical playback control toolbar:
+
+- **Play / Pause** — start or pause the game preview
+- **Step** — advance a single frame while paused
+- **Speed** — adjust playback speed
+
+These controls call the `setPaused()`, `stepFrame()`, and `setPlaySpeed()` APIs described above.
## WASM Debugging
@@ -45,12 +179,6 @@ This produces an unoptimized WASM binary with DWARF debug info. The binary is si
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
@@ -92,10 +220,6 @@ const narrowSystem = defineSystem(
);
```
-### 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"
diff --git a/docs/astro/src/content/docs/guides/game-view.mdx b/docs/astro/src/content/docs/guides/game-view.mdx
new file mode 100644
index 000000000..245f1c887
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/game-view.mdx
@@ -0,0 +1,113 @@
+---
+title: Game View
+description: Preview and debug your game inside the editor using the Game View panel
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+The **Game View** is the in-editor game preview panel. It provides playback controls, resolution simulation, and live debugging, so you can test game logic and visuals without leaving the editor.
+
+## Starting the Preview
+
+Click the **Play** button on the left side of the toolbar to start the game preview. The editor launches a preview server and loads the current project into the Game View.
+
+Click the **Stop** button to end the preview. The Game View returns to its initial blank state and the editor switches back to normal editing mode.
+
+## Playback Controls
+
+The toolbar provides the following playback controls:
+
+| Button | Function |
+|--------|----------|
+| **Play** | Start the game preview |
+| **Pause** | Pause the game, freezing the current frame |
+| **Resume** | Resume from a paused state |
+| **Step Frame** | Advance exactly one frame while paused — useful for frame-by-frame debugging |
+| **Stop** | Stop the preview and destroy the game instance |
+
+<Aside type="tip">
+ Step Frame is only available while paused. Combined with live data in the Inspector, it lets you observe exact state changes on each frame.
+</Aside>
+
+## Playback Speed
+
+The speed dropdown in the toolbar lets you adjust the game's running speed:
+
+- **0.25x** — quarter speed, useful for inspecting fast animations
+- **0.5x** — half speed
+- **1x** — normal speed (default)
+- **2x** — double speed
+- **4x** — four times speed, useful for skipping wait periods
+
+Speed changes take effect immediately without restarting the preview.
+
+## Resolution Settings
+
+The resolution dropdown in the toolbar offers several presets for simulating different screen sizes:
+
+| Preset | Resolution |
+|--------|------------|
+| Free | Fills the entire Game View area |
+| 16:9 | 1920 x 1080 |
+| 9:16 | 1080 x 1920 |
+| 4:3 | 1024 x 768 |
+| 3:4 | 768 x 1024 |
+| Custom | User-defined width and height |
+
+When **Free** is selected, the game fills the full Game View area. When a fixed resolution is selected, the preview scales proportionally to the target aspect ratio and is centered within the panel.
+
+Selecting **Custom** reveals width and height input fields that accept any value between 1 and 7680.
+
+<Aside type="note">
+ Resolution settings only affect the display area inside Game View. They do not change the resolution of actual build output.
+</Aside>
+
+## Play Mode
+
+When the preview starts, the editor enters **Play Mode** — a special runtime debugging mode. The Hierarchy and Inspector panels switch to their runtime views.
+
+### Hierarchy Panel
+
+While in Play Mode the Hierarchy panel changes as follows:
+
+- A blue border appears at the top, with a blue **RUNTIME** badge on the right side of the toolbar
+- The entity tree switches to the runtime entity list, showing every entity that currently exists in the game
+- Dynamically spawned entities (e.g. bullets, particle effects) appear in the list as well
+- Toolbar buttons for adding, duplicating, and expanding/collapsing are disabled
+- Drag-to-reorder, context menus, and double-click-to-rename are disabled
+- The status bar at the bottom displays the runtime entity count
+
+Click a runtime entity to inspect its component data in the Inspector.
+
+### Inspector Panel
+
+When a runtime entity is selected during Play Mode, the Inspector panel:
+
+- Displays a blue **RUNTIME** badge
+- Lists all runtime components on the entity with their current property values
+- Auto-refreshes property values periodically, reflecting live game state
+- Supports direct editing of numbers, booleans, strings, and vector properties — changes are sent to the game instance immediately
+
+<Aside type="caution">
+ Changes made in the Inspector during Play Mode only affect the running game instance. When you stop the preview, all runtime modifications are lost and the scene data reverts to its state before the preview started.
+</Aside>
+
+### Exiting Play Mode
+
+When you click **Stop**:
+
+- The game instance is destroyed and the preview is cleared
+- The Hierarchy panel restores the edit-mode entity tree, including its previous expand/collapse state
+- The Inspector panel returns to edit mode
+- No runtime modifications are saved to the scene file
+
+## FPS Display
+
+While the preview is running, the current frame rate (FPS) is displayed on the right side of the toolbar. The FPS indicator hides automatically when the preview stops.
+
+## Notes
+
+- Hierarchy editing features are disabled during Play Mode, including drag-to-reorder, context menus, and renaming
+- The runtime entity list refreshes periodically; with a large number of entities there may be a brief delay
+- Resolution can be changed while the preview is running — the preview resizes immediately
+- Input fields that are actively being edited in the Inspector are not overwritten by auto-refresh, so manual input is never interrupted
diff --git a/docs/astro/src/content/docs/guides/project-settings.mdx b/docs/astro/src/content/docs/guides/project-settings.mdx
new file mode 100644
index 000000000..e39847a6f
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/project-settings.mdx
@@ -0,0 +1,113 @@
+---
+title: Project Settings
+description: Configure runtime, build, and editor options for your ESEngine project
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Project settings provide centralized control over engine runtime parameters, physics simulation, build options, and editor behavior. All settings are automatically saved to the project configuration file and shared across team members.
+
+## Opening Settings
+
+Open the settings dialog from the menu bar via **Edit → Settings...** or with the keyboard shortcut `Ctrl+,` (`Cmd+,` on macOS). The left sidebar lists all setting categories; click a category to switch the content area on the right.
+
+## General
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| Language | select | `en` | Editor UI language |
+| Preview Port | number | `3456` | Local port for the preview server. Range: 1024–65535 |
+
+## Project
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| Spine Version | select | `none` | Spine runtime version to use. Options: `None`, `4.2`, `4.1`, `3.8`. The corresponding Spine WASM module is bundled automatically at build time. |
+| Project Name | string | empty | Project name displayed in the editor title bar |
+| Version | string | empty | Project version number |
+| Default Scene | string | empty | Scene path loaded at runtime startup |
+| Design Width | number | `1920` | Design resolution width in pixels |
+| Design Height | number | `1080` | Design resolution height in pixels |
+
+<Aside type="tip">
+ The design resolution defines the reference size for the Canvas component. Combined with the Canvas Scale Mode, it ensures your game adapts correctly to different screen sizes.
+</Aside>
+
+## Scene View
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| Show Grid | boolean | `true` | Display a background grid in the scene view |
+| Grid Color | color | `#333333` | Grid line color |
+| Grid Opacity | range | `1.0` | Grid transparency. Range: 0–1 |
+| Show Gizmos | boolean | `true` | Display gizmo overlays (transform handles, anchors, etc.) |
+| Show Selection Box | boolean | `true` | Display a bounding box around selected entities |
+| Show Colliders | boolean | `true` | Display physics collider wireframes |
+| Show Stats | boolean | `false` | Display frame rate and render statistics in the top-left corner of the scene view |
+| Grid Size | number | `50` | Grid cell size in pixels. Range: 5–500 |
+
+## Physics
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| Enable Physics | boolean | `false` | Enable physics simulation. When enabled, the physics WASM module is included in builds automatically. |
+| Gravity X | number | `0` | Horizontal gravity component |
+| Gravity Y | number | `-9.81` | Vertical gravity component (negative = downward) |
+| Fixed Timestep | number | `1/60` | Physics step interval in seconds. Minimum: 0.001 |
+| Sub-Step Count | number | `4` | Number of sub-steps per physics step. Range: 1–16. Higher values improve accuracy at the cost of performance. |
+
+## Build
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| Atlas Max Size | select | `2048` | Maximum texture atlas size in pixels. Options: `512`, `1024`, `2048`, `4096`. |
+| Atlas Padding | number | `2` | Spacing between textures in the atlas in pixels. Range: 0–16. Prevents edge bleeding during texture sampling. |
+
+<Aside type="note">
+ Atlas settings apply to all build configurations. Per-configuration options (scene lists, platform settings, etc.) are managed in the build panel — see the [Building](/guides/building) guide for details.
+</Aside>
+
+## Runtime
+
+Runtime settings control engine behavior during actual gameplay and take effect in both previews and final builds.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| Scene Transition Duration | number | `0.3` | Fade-in/fade-out duration for scene transitions in seconds. Range: 0–5 |
+| Scene Transition Color | color | `#000000` | Background color during scene transitions |
+| Default Font Family | string | `Arial` | Default font for text rendering. Applies to the Text and TextInput components. |
+| Canvas Scale Mode | select | `FixedHeight` | Canvas scaling strategy. Determines how the game adapts to different screen sizes. |
+| Canvas Match W/H | range | `0.5` | Width-to-height matching weight. Range: 0–1. Only visible when Scale Mode is `Match`. 0 = match width exactly, 1 = match height exactly. |
+| Max Delta Time | number | `0.25` | Maximum time step per frame in seconds. Range: 0.01–1. Prevents physics and animation jumps after long stalls. |
+| Max Fixed Steps | number | `8` | Maximum Fixed Update iterations per frame. Range: 1–64. Caps CPU overhead at low frame rates. |
+| Text Canvas Size | select | `512` | Off-screen canvas size used for text rendering. Options: `256`, `512`, `1024`, `2048`. Larger values support bigger text areas but consume more memory. |
+
+### Canvas Scale Mode Reference
+
+| Mode | Behavior |
+|------|----------|
+| **Fixed Width** | Keeps the design width constant; height scales based on the screen aspect ratio |
+| **Fixed Height** | Keeps the design height constant; width scales based on the screen aspect ratio |
+| **Expand** | Uses the larger of the width and height scale factors, ensuring the full design area is visible |
+| **Shrink** | Uses the smaller of the width and height scale factors, ensuring the screen is completely filled |
+| **Match** | Interpolates between the width and height scale factors, controlled by the Canvas Match W/H weight |
+
+## Using RuntimeConfig in the SDK
+
+The editor's runtime settings are written into the project configuration at build time. In scripts you can read or override these values through the `RuntimeConfig` object:
+
+```typescript
+import { RuntimeConfig } from 'esengine';
+
+RuntimeConfig.maxDeltaTime = 0.25;
+RuntimeConfig.maxFixedSteps = 8;
+RuntimeConfig.sceneTransitionDuration = 0.5;
+RuntimeConfig.defaultFontFamily = 'Noto Sans SC';
+RuntimeConfig.canvasScaleMode = 1; // 0=FixedWidth, 1=FixedHeight, 2=Expand, 3=Shrink, 4=Match
+RuntimeConfig.canvasMatchWidthOrHeight = 0.5;
+RuntimeConfig.textCanvasSize = 1024;
+```
+
+<Aside type="caution">
+ Modifying `RuntimeConfig` in code overrides the values from the editor settings. Use code overrides only when you need dynamic adjustments at runtime; for day-to-day configuration, use the settings dialog instead.
+</Aside>
diff --git a/docs/astro/src/content/docs/guides/scenes.mdx b/docs/astro/src/content/docs/guides/scenes.mdx
index fe821aec9..2e6542993 100644
--- a/docs/astro/src/content/docs/guides/scenes.mdx
+++ b/docs/astro/src/content/docs/guides/scenes.mdx
@@ -134,11 +134,13 @@ Entities have a `visible` property (default `true`). When set to `false` in the
## Scene Manager
-The `SceneManager` resource provides full control over loading, unloading, and switching between multiple scenes at runtime. It is automatically available when using `createWebApp()` — the `sceneManagerPlugin` is included by default.
+The SDK provides the `SceneManager` resource and `sceneManagerPlugin` for managing the loading, switching, and lifecycle of multiple scenes. When using `createWebApp()`, the plugin is included automatically -- no manual registration needed.
-<Aside type="note">
- If you are building an `App` manually, add the `sceneManagerPlugin` to enable scene management.
-</Aside>
+```typescript
+import { SceneManager } from 'esengine';
+
+const mgr = app.getResource(SceneManager);
+```
## Registering Scenes
@@ -168,13 +170,25 @@ app.setInitialScene('menu');
app.run();
```
-| Field | Type | Description |
-|-------|------|-------------|
-| `name` | string | Unique identifier for the scene |
-| `path` | string | Path to the scene JSON file |
-| `systems` | Array | Systems to run while this scene is active |
-| `setup` | (ctx: SceneContext) => void | Called after the scene loads |
-| `cleanup` | (ctx: SceneContext) => void | Called before the scene unloads |
+Instead of specifying a file path with `path`, you can pass scene data directly via `data`. This is useful for procedurally generated or in-memory scenes:
+
+```typescript
+app.registerScene({
+ name: 'procedural',
+ data: {
+ version: '1.0',
+ name: 'procedural',
+ entities: [],
+ },
+ setup: (ctx) => {
+ // generate entities programmatically
+ },
+});
+```
+
+<Aside type="tip">
+ Systems registered in `systems` are automatically wrapped as scene-scoped systems and only run while that scene's status is `running`.
+</Aside>
## Switching Scenes
@@ -188,10 +202,31 @@ await mgr.switchTo('game');
// Switch with fade transition
await mgr.switchTo('game', { transition: 'fade', duration: 0.5 });
+
+// Full transition options
+await mgr.switchTo('game', {
+ transition: 'fade',
+ duration: 1.0,
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ keepPersistent: true,
+ onStart: () => console.log('transition started'),
+ onComplete: () => console.log('transition finished'),
+});
```
-<Aside type="caution">
- `switchTo` is async — the old scene is fully unloaded and the new scene fully loaded before the promise resolves. Avoid calling it multiple times concurrently.
+Full `switchTo` options:
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `transition` | `'none' \| 'fade'` | `'none'` | Transition animation type |
+| `duration` | `number` | engine default | Total transition duration (seconds); fade-out and fade-in each take half |
+| `color` | `Color` | engine default | Mask colour for the fade |
+| `keepPersistent` | `boolean` | `true` | Whether to keep persistent entities |
+| `onStart` | `() => void` | - | Callback when the transition starts |
+| `onComplete` | `() => void` | - | Callback when the transition finishes |
+
+<Aside type="note">
+ Calling `switchTo` while a transition is in progress is ignored. Use `mgr.isTransitioning()` to check whether a transition is active.
</Aside>
## Multi-Scene (Additive Loading)
@@ -209,7 +244,9 @@ await mgr.loadAdditive('pause-menu');
await mgr.unload('pause-menu');
```
-Additive scenes run their systems alongside the primary scene. Each loaded scene maintains its own lifecycle independently.
+<Aside type="note">
+ Additive scenes run independently from the primary scene, each with its own systems and lifecycle. Unloading an additive scene does not affect the primary scene.
+</Aside>
## Scene Lifecycle
@@ -298,50 +335,74 @@ app.registerScene({
});
```
+<Aside type="tip">
+ When a scene is `paused` or `sleeping`, its scoped systems do not execute -- no need to check the scene state manually.
+</Aside>
+
## Scene Transitions
-For built-in visual transitions between scenes, use the standalone `transitionTo` helper:
+Use the `transitionTo` helper for animated scene switches:
```typescript
import { transitionTo } from 'esengine';
-// Fade to black, switch, fade in
+// Fade to black, switch scene, fade in
await transitionTo(app, 'game', { type: 'fade', duration: 1.0 });
-// Crossfade between scenes
-await transitionTo(app, 'game', { type: 'crossfade', duration: 0.5 });
+// Custom mask colour
+await transitionTo(app, 'game', {
+ type: 'fade',
+ duration: 0.5,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+});
```
-| Transition Type | Description |
-|----------------|-------------|
-| `fade` | Fades to black, switches scene, fades in |
-| `crossfade` | Blends the old and new scenes simultaneously |
+`transitionTo` is a convenience wrapper around `mgr.switchTo()`. It obtains the `SceneManager` resource internally and calls `switchTo`. The process is asynchronous — the old scene fades out, the scene switch executes, then the new scene fades in.
## Querying Scene State
-Inspect which scenes are loaded and their current status:
+`SceneManager` provides a set of methods for inspecting scene status:
```typescript
const mgr = app.getResource(SceneManager);
-mgr.getActive(); // current primary scene name or null
-mgr.getActiveScenes(); // all scenes with 'running' status
-mgr.getLoaded(); // all loaded scene names
-mgr.isLoaded('game'); // boolean
-mgr.isPaused('game'); // boolean
-mgr.isSleeping('game'); // boolean
-mgr.getSceneStatus('game'); // 'loading' | 'running' | 'paused' | 'sleeping' | 'unloading' | null
+mgr.getActive(); // current primary scene name, or null
+mgr.isActive('game'); // whether a given scene is the primary scene
+mgr.getActiveScenes(); // all scene names with 'running' status
+mgr.getLoaded(); // all loaded scene names
+mgr.isLoaded('game'); // whether the scene is loaded
+mgr.isPaused('game'); // whether the scene is paused
+mgr.isSleeping('game'); // whether the scene is sleeping
+mgr.isTransitioning(); // whether a scene transition is in progress
+mgr.getSceneStatus('game'); // detailed scene status
+mgr.getScene('game'); // get the scene's SceneContext, or null if not loaded
+mgr.getLoadOrder(); // scene names in load order
```
-| Method | Returns | Description |
-|--------|---------|-------------|
-| `getActive()` | `string \| null` | Name of the current primary scene |
-| `getActiveScenes()` | `string[]` | All scenes with `'running'` status |
-| `getLoaded()` | `string[]` | All loaded scene names (any status) |
-| `isLoaded(name)` | `boolean` | Whether the scene is currently loaded |
-| `isPaused(name)` | `boolean` | Whether the scene is paused |
-| `isSleeping(name)` | `boolean` | Whether the scene is sleeping |
-| `getSceneStatus(name)` | `string \| null` | Current status, or `null` if not loaded |
+`getSceneStatus` return values:
+
+| Status | Description |
+|--------|-------------|
+| `'loading'` | Scene is currently loading |
+| `'running'` | Scene is running |
+| `'paused'` | Scene is paused (systems stopped, entities visible) |
+| `'sleeping'` | Scene is sleeping (systems stopped, entities hidden) |
+| `'unloading'` | Scene is currently unloading |
+| `null` | Scene is not loaded |
+
+## Scene Layer Ordering
+
+When multiple scenes are loaded simultaneously, rendering and system execution follow load order. Use `bringToTop()` to move a scene to the top:
+
+```typescript
+const mgr = app.getResource(SceneManager);
+
+await mgr.loadAdditive('hud');
+await mgr.loadAdditive('dialog');
+
+mgr.bringToTop('hud');
+mgr.getLoadOrder(); // ['game', 'dialog', 'hud']
+```
## Scene Data Types
diff --git a/docs/astro/src/content/docs/zh/changelog-v051.mdx b/docs/astro/src/content/docs/zh/changelog-v051.mdx
new file mode 100644
index 000000000..a7e62150f
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/changelog-v051.mdx
@@ -0,0 +1,143 @@
+---
+title: v0.5.1
+description: ESEngine v0.5.1 更新日志
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+<Aside type="tip">
+v0.5.1 带来了 Game View 面板与播放模式、可停靠面板布局、Content Drawer、场景管理、项目设置,以及大量编辑器和运行时改进。
+</Aside>
+
+## Game View 面板
+
+- 新增 Game View 面板,支持播放/暂停/停止控制和单帧步进
+- 分辨率预设(Free Aspect、16:9、9:16、4:3、1:1)及自定义分辨率输入
+- 播放速度控制和实时 FPS 计数器
+- 基于 iframe 的隔离预览,拥有独立 WASM 实例(不影响 Scene View 渲染器)
+- Game 面板在默认布局中作为 Scene 旁边的标签页
+
+## 播放模式
+
+- 播放期间 Hierarchy 和 Inspector 面板显示运行时实体
+- Hierarchy 显示运行时实体树及父子层级关系
+- Inspector 渲染运行时实体属性并自动刷新
+- 通过 `world.insert()` 编辑内置组件的运行时属性
+- 蓝色 "RUNTIME" 徽章和顶部边框指示播放模式激活
+
+## Dockview 布局系统
+
+- 用 dockview-core 替换固定分割器布局,支持拖拽停靠面板
+- 标签式面板分组、跨组拖拽面板、布局持久化到 localStorage
+- "Reset Layout" 命令恢复默认排列
+
+## Content Drawer
+
+- Content Drawer 从状态栏滑出打开(Ctrl+Space)
+- 点击外部或按 Escape 自动隐藏
+- "Dock in Layout" 按钮将 Content Browser 移入 dockview
+- Drawer 和停靠面板可独立共存
+- 可拖拽调整高度,高度持久化到 localStorage
+- 固定按钮保持 Drawer 常开
+
+## 场景管理
+
+- 新增 `SceneManager` 资源,支持 `load`/`unload`/`switchTo`/`loadAdditive`/`pause`/`resume`/`sleep`/`wake`
+- `SceneOwner` 组件用于实体到场景的生命周期追踪
+- 场景范围的绘制回调和按活跃场景过滤相机
+- `switchTo()` 内置淡入淡出转场,`transitionTo()` 支持 fade/crossfade
+- `wrapSceneSystem()` 根据场景状态条件执行系统
+- 集成到构建管线模板(Playable + 微信)
+
+## 项目设置
+
+- 将 12 个硬编码默认值暴露为可配置的项目设置
+- SDK 中新增 `RuntimeConfig`,支持运行时可配置默认值(转场时长、默认字体、Canvas 缩放模式、最大 Delta Time、固定时间步迭代次数、文本 Canvas 尺寸)
+- 编辑器设置面板新增 Build 和 Runtime 分区
+- 设置通过预览配置和构建模板传递
+
+## SDK 和运行时
+
+- 系统依赖排序,通过 `runBefore`/`runAfter` 和拓扑排序实现
+- 播放控制 API:`setPaused`、`stepFrame`、`setPlaySpeed`
+- 错误处理:每个系统的 `onSystemError` 回调,`onWasmError` 错误边界支持优雅降级
+- 集中式日志系统,支持可插拔处理器
+- Prefab 嵌套深度保护(`MAX_DEPTH=10`)
+- `AssetRefCounter` 用于资产使用监控
+- `setPipeline()` 方法替换不安全的类型转换
+- 未知 uniform 名称警告
+- 修复 `EventSource`/`TextInput`/输入监听器泄漏,`quit()` 时添加清理
+
+## 编辑器改进
+
+### Scene View 场景视图
+
+- 框选(点击拖拽选择多个实体)
+- 吸附到网格(Ctrl+拖拽),网格大小可配置
+- 快捷键:F(聚焦)、Delete、方向键、缩放
+- Space+拖拽平移,Shift 旋转角度吸附
+- 自适应网格细分
+
+### Inspector 检查器
+
+- 组件右键菜单(重置、复制、粘贴、排序)
+- 属性重置为默认值
+- AddComponent 键盘导航,搜索高亮
+- 响应式标签和组件图标
+- 播放模式下编辑运行时实体属性
+
+### Hierarchy 层级
+
+- 内联重命名(F2 / 右键菜单 / 慢速双击)
+- 方向键导航,支持展开/折叠
+- 多选:Ctrl+点击、Shift+点击范围选择、Ctrl+A 全选
+- 剪切(Ctrl+X)、递归复制、全部折叠/展开
+- ARIA tree 角色提升无障碍性
+
+### Content Browser 内容浏览器
+
+- 模糊搜索,支持递归文件匹配
+- 图片缩略图,LRU 缓存
+- 网格/列表视图切换
+- 多选(Ctrl/Shift),键盘导航
+- 空状态显示和返回按钮
+- ARIA grid 角色提升无障碍性
+
+### Output 输出面板
+
+- 每条日志显示时间戳
+- 类型过滤器(info/warn/error),显示计数徽章
+- 输出内容搜索
+- 右键菜单复制和命令分组
+
+### 快捷键
+
+- Ctrl+X 剪切实体
+- Ctrl+Space 切换 Content Drawer
+- Ctrl+1/2/3 面板聚焦
+- Ctrl+Shift+N 新建实体
+- Ctrl+Shift+Z 重做
+- Ctrl+S 在输入框中保存
+- Escape 关闭对话框和 Drawer
+
+## 性能
+
+- 基于 AABB 的视锥剔除
+- 非旋转四边形渲染快速路径
+- Shader Uniform 查找使用预解析的整数位置 ID
+- 编辑器模式下的 Shader 热重载
+
+## Bug 修复
+
+- 修复 `SceneManager.switchTo()` 在活跃转场期间的重入问题
+- 修复 `SceneManager.load()`/`loadAdditive()` 并发加载同一场景的竞态条件
+- 修复 `PostProcessPipeline` 在 resize 时的 FBO 泄漏
+- 修复场景转场中未等待 promise 导致的静默失败
+- 修复编辑器面板内存泄漏(Canvas 监听器、滚动监听器、右键菜单定时器)
+- 修复实体删除后选择状态未清除
+- 修复撤销闭包过期、拖拽撤销泛滥、Retina 显示器缩放 DPR
+- 修复设置校验、颜色范围、toast XSS、状态栏计数
+- 修复 `deleteSelectedEntities` 在命令执行前收集后代的问题
+- 修复 Prefab 保存,增加重试/丢弃对话框和自动保存恢复
+- 修复 WebGL 上下文初始化,使用 `GL.registerContext` + `initRendererWithContext`
+- 修复运行时场景校验错误
diff --git a/docs/astro/src/content/docs/zh/core-concepts/queries.mdx b/docs/astro/src/content/docs/zh/core-concepts/queries.mdx
index 158a198f5..4fd1aa234 100644
--- a/docs/astro/src/content/docs/zh/core-concepts/queries.mdx
+++ b/docs/astro/src/content/docs/zh/core-concepts/queries.mdx
@@ -147,6 +147,29 @@ addSystem(defineSystem(
));
```
+## 迭代安全
+
+在查询迭代过程中,**不能**直接创建或销毁实体,也不能插入或移除组件。这些操作会改变底层数据结构,导致迭代器失效。引擎会在迭代期间检测到这类操作并抛出错误,防止数据损坏。
+
+正确做法是使用 `Commands` 将修改延迟到迭代结束后执行:
+
+```typescript
+import { defineSystem, addSystem, Commands, Query, Health } from 'esengine';
+
+const despawnDead = defineSystem(
+ [Commands(), Query(Health)],
+ (commands, query) => {
+ for (const [entity, health] of query) {
+ if (health.value <= 0) {
+ commands.despawn(entity); // 延迟执行,安全
+ }
+ }
+ }
+);
+```
+
+`Commands` 的操作会在当前系统函数返回后统一刷新(flush),此时迭代已结束,修改不会影响正在进行的遍历。
+
## 下一步
- [资源](/microes/zh/core-concepts/resources/) — 全局单例数据如 Time 和 Input
diff --git a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx
index 4e6063766..c6135dff5 100644
--- a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx
+++ b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx
@@ -58,12 +58,48 @@ addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);
<Aside type="note">
Fixed 系列调度(`FixedPreUpdate`、`FixedUpdate`、`FixedPostUpdate`)以 1/60s 固定步长运行,使用累加器驱动。一帧内可能执行零次或多次,取决于帧时长,每帧最多执行 **8 次迭代**。适用于物理等需要一致时间步的确定性逻辑。
+
+ 最大迭代次数可通过 `RuntimeConfig` 配置:
+
+ ```typescript
+ import { RuntimeConfig } from 'esengine';
+ RuntimeConfig.maxFixedSteps = 8; // 默认值
+ ```
</Aside>
<Aside type="note">
Delta time 被限制为最大 **250ms**(0.25s)。如果一帧用时更长(例如标签页不活跃),多余的时间会被丢弃以防止模拟出现大跳变。
</Aside>
+## 系统排序
+
+同一 Schedule 内的多个系统默认按注册顺序执行。如果系统之间有执行顺序依赖,可以通过 `defineSystem` 的第三个参数指定 `runBefore` 或 `runAfter`:
+
+```typescript
+import { defineSystem, Query, Res, Time, Mut, LocalTransform, Velocity, Sprite } from 'esengine';
+
+const movementSystem = defineSystem(
+ [Res(Time), Query(Mut(LocalTransform), Velocity)],
+ (time, query) => { /* ... */ },
+ { name: 'movement' }
+);
+
+const renderSystem = defineSystem(
+ [Query(LocalTransform, Sprite)],
+ (query) => { /* ... */ },
+ { name: 'render', runAfter: ['movement'] }
+);
+```
+
+- `runAfter: ['movement']` — 当前系统在 `movement` 之后执行
+- `runBefore: ['render']` — 当前系统在 `render` 之前执行
+
+引擎使用拓扑排序确定最终执行顺序。如果排序约束形成循环依赖,启动时会抛出错误。
+
+<Aside type="tip">
+ `name` 是排序的基础。只有需要参与排序的系统才必须指定 `name`,未指定名称的系统不能被其他系统引用。
+</Aside>
+
## 系统参数
### Commands
diff --git a/docs/astro/src/content/docs/zh/guides/debugging.mdx b/docs/astro/src/content/docs/zh/guides/debugging.mdx
index 3767808f5..ba0e1f591 100644
--- a/docs/astro/src/content/docs/zh/guides/debugging.mdx
+++ b/docs/astro/src/content/docs/zh/guides/debugging.mdx
@@ -1,23 +1,157 @@
---
title: 调试
-description: 使用 source maps、WASM 调试和性能分析调试 ESEngine 游戏
+description: ESEngine 调试工具和错误处理
---
import { Aside } from '@astrojs/starlight/components';
-本指南介绍 ESEngine 项目的调试技巧,包括 source maps、WASM 调试、性能分析以及常见错误的解决方案。
+本指南介绍 ESEngine 的运行时调试工具,包括错误处理、播放控制、日志系统和编辑器调试面板。
-## Source Maps
+## 错误处理
-### 编辑器预览
+### 系统错误处理
-在编辑器中预览时,source maps 默认启用。在预览窗口中打开浏览器 DevTools 即可设置断点并逐步执行 TypeScript 代码。
+当 ECS 系统抛出异常时,引擎默认会在控制台打印错误并继续运行。通过 `app.onSystemError()` 注册处理器可以控制出错后的行为——返回 `'continue'` 继续执行后续系统,返回 `'pause'` 暂停当前帧剩余的所有系统:
-### 构建产物
+```typescript
+app.onSystemError((error: Error, systemName?: string) => {
+ console.error(`System "${systemName}" failed:`, error.message);
+
+ if (error.message.includes('critical')) {
+ return 'pause';
+ }
+ return 'continue';
+});
+```
+
+返回 `'pause'` 后,当前帧中尚未执行的系统会被跳过,但渲染循环不会停止。下一帧开始时所有系统恢复正常执行。
+
+### WASM 错误处理
+
+C++ 引擎核心通过 WebAssembly 运行。当 WASM 层发生错误时,通过 `app.onWasmError()` 捕获:
+
+```typescript
+app.onWasmError((error: unknown, context: string) => {
+ console.error(`WASM error in ${context}:`, error);
+});
+```
+
+`context` 参数标识出错的 WASM 操作(如渲染、物理计算等),便于定位问题来源。
+
+<Aside type="note">
+ WASM 错误通常表示引擎内部状态异常。如果频繁出现,检查是否使用了无效的实体 ID 或已释放的资源。
+</Aside>
+
+## 播放控制
+
+SDK 提供了一组方法用于在运行时控制游戏的执行节奏,适用于逐帧调试和慢动作分析。
+
+### 暂停与恢复
+
+```typescript
+app.setPaused(true); // 暂停:系统停止执行,仅运行 Last schedule(渲染)
+app.setPaused(false); // 恢复正常执行
+
+app.isPaused(); // 查询当前暂停状态
+```
+
+暂停状态下引擎仍然运行渲染循环(`Schedule.Last`),画面会保持在最后一帧的状态。
+
+### 单帧步进
+
+暂停状态下调用 `stepFrame()` 可以推进一帧,执行完整的系统调度后再次暂停:
+
+```typescript
+app.setPaused(true);
+app.stepFrame(); // 执行一帧完整的系统调度
+```
-对于可玩广告构建,在构建配置中启用**开发构建**以包含 source maps。生产构建会移除 source maps 以减小文件体积。
+### 播放速度
-对于微信小游戏构建,source maps 会生成在输出目录中。在微信开发者工具设置中启用 **Source Maps** 即可使用。
+通过 `setPlaySpeed()` 调整时间流速,有效范围为 0.1 到 4.0:
+
+```typescript
+app.setPlaySpeed(0.25); // 四分之一速度,适合观察快速动画
+app.setPlaySpeed(2.0); // 双倍速度
+
+app.getPlaySpeed(); // 获取当前速度倍率
+```
+
+播放速度通过缩放每帧的 `delta` 时间实现。所有读取 `Time.delta` 的系统会自动受到影响。
+
+## 日志系统
+
+SDK 提供集中式日志系统,支持分级过滤和自定义处理。
+
+### LogLevel
+
+```typescript
+import { LogLevel, setLogLevel } from 'esengine';
+
+// Debug = 0, Info = 1, Warn = 2, Error = 3
+setLogLevel(LogLevel.Debug); // 输出所有级别
+setLogLevel(LogLevel.Warn); // 仅输出 Warn 和 Error
+```
+
+### 使用日志
+
+日志函数接受分类标签、消息和可选的附加数据:
+
+```typescript
+import { debug, info, warn, error } from 'esengine';
+
+debug('Physics', 'Collision detected', { entityA: 1, entityB: 2 });
+info('Scene', 'Level loaded');
+warn('Asset', 'Texture not found, using fallback');
+error('Render', 'WebGL context lost');
+```
+
+默认的 `ConsoleLogHandler` 会格式化输出到浏览器控制台:
+
+```
+[14:32:05.123] [INFO ] [Scene] Level loaded
+```
+
+### 自定义 LogHandler
+
+实现 `LogHandler` 接口可以将日志发送到自定义目标(如远程服务、文件、UI 面板):
+
+```typescript
+import { getLogger, type LogHandler, type LogEntry } from 'esengine';
+
+const customHandler: LogHandler = {
+ handle(entry: LogEntry) {
+ // entry.timestamp, entry.level, entry.category, entry.message, entry.data
+ myRemoteService.send(entry);
+ }
+};
+
+const logger = getLogger();
+logger.addHandler(customHandler);
+
+// 移除处理器
+logger.removeHandler(customHandler);
+```
+
+## 编辑器调试
+
+### Output 面板
+
+编辑器的 Output 面板捕获运行时的所有控制台输出:
+
+- **时间戳** — 每条日志附带精确到毫秒的时间
+- **类型过滤** — 按 info、warn、error 分类筛选
+- **搜索** — 在日志文本中搜索关键字
+
+### Game View 播放控制
+
+编辑器的 Game View 面板提供了图形化的播放控制工具栏:
+
+- **Play / Pause** — 启动或暂停游戏预览
+- **Step** — 暂停状态下单帧步进
+- **Speed** — 调整播放速度
+
+这些控件直接调用上述 `setPaused()`、`stepFrame()` 和 `setPlaySpeed()` API。
## WASM 调试
@@ -45,12 +179,6 @@ node build-tools/cli.js build -t web -d
WASM 调试仅在基于 Chromium 的浏览器中可用。Firefox 和 Safari 不支持基于 DWARF 的 WASM 调试。
</Aside>
-### 调试日志
-
-引擎提供了不同级别的日志宏。在 debug 构建中所有日志级别都会输出。在 release 构建中仅输出警告和错误。
-
-在 SDK 端,使用浏览器控制台。引擎会自动将 C++ 日志消息转发到 `console.log` / `console.warn` / `console.error`。
-
## 性能分析
### 帧时间
@@ -92,10 +220,6 @@ const narrowSystem = defineSystem(
);
```
-### 纹理图集效率
-
-大量独立纹理会导致更多 draw call。使用构建面板验证纹理是否被打包到图集中。超过图集页大小(默认 2048x2048)的纹理会作为单独的 draw call。
-
## 常见错误
### "WASM module failed to compile"
diff --git a/docs/astro/src/content/docs/zh/guides/game-view.mdx b/docs/astro/src/content/docs/zh/guides/game-view.mdx
new file mode 100644
index 000000000..11380ebf8
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/game-view.mdx
@@ -0,0 +1,113 @@
+---
+title: Game View
+description: 使用 Game View 面板预览和调试游戏
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+**Game View** 是编辑器中的游戏预览面板,提供播放控制、分辨率模拟和实时调试功能。你可以在不离开编辑器的情况下快速验证游戏逻辑和视觉效果。
+
+## 启动预览
+
+点击工具栏左侧的 **Play** 按钮启动游戏预览。编辑器会启动预览服务器并加载当前项目。
+
+点击 **Stop** 按钮停止预览,Game View 会回到初始的空白状态,编辑器恢复到正常编辑模式。
+
+## 播放控制
+
+工具栏提供以下播放控制按钮:
+
+| 按钮 | 功能 |
+|------|------|
+| **Play** | 启动游戏预览 |
+| **Pause** | 暂停游戏运行,保持画面冻结 |
+| **Resume** | 从暂停状态恢复运行 |
+| **Step Frame** | 暂停状态下单步执行一帧,适合逐帧调试 |
+| **Stop** | 停止预览,销毁游戏实例 |
+
+<Aside type="tip">
+ Step Frame 仅在暂停状态下可用。配合 Inspector 中的实时数据,可以精确观察每一帧的状态变化。
+</Aside>
+
+## 播放速度
+
+工具栏中的速度下拉菜单支持调整游戏运行速度:
+
+- **0.25x** — 四分之一速度,适合观察快速动画
+- **0.5x** — 半速
+- **1x** — 正常速度(默认)
+- **2x** — 两倍速
+- **4x** — 四倍速,适合快速跳过等待阶段
+
+速度调整会实时生效,无需重启预览。
+
+## 分辨率设置
+
+工具栏中的分辨率下拉菜单提供多种预设分辨率,用于模拟不同设备的屏幕尺寸:
+
+| 预设 | 分辨率 |
+|------|--------|
+| Free | 自适应面板大小 |
+| 16:9 | 1920 x 1080 |
+| 9:16 | 1080 x 1920 |
+| 4:3 | 1024 x 768 |
+| 3:4 | 768 x 1024 |
+| Custom | 自定义宽高 |
+
+选择 **Free** 时,游戏画面会填满整个 Game View 区域。选择固定分辨率时,游戏画面会按照目标宽高比等比缩放,在 Game View 区域内居中显示。
+
+选择 **Custom** 后会出现宽度和高度输入框,支持输入 1 到 7680 之间的任意分辨率值。
+
+<Aside type="note">
+ 分辨率设置仅影响 Game View 中的显示区域大小,不影响实际构建输出的分辨率。
+</Aside>
+
+## Play Mode
+
+启动预览后,编辑器进入 **Play Mode**。这是一个特殊的运行时调试模式,Hierarchy 面板和 Inspector 面板会切换到运行时视图。
+
+### Hierarchy 面板
+
+进入 Play Mode 后,Hierarchy 面板会发生以下变化:
+
+- 面板顶部出现蓝色边框,工具栏右侧显示蓝色 **RUNTIME** 标记
+- 实体树切换为运行时实体列表,显示游戏中实际存在的所有实体
+- 运行时动态生成的实体(如子弹、特效)也会出现在列表中
+- 工具栏的添加、复制、展开/折叠按钮被禁用
+- 拖拽排序、右键菜单、双击重命名等编辑操作被禁用
+- 底部状态栏显示运行时实体数量
+
+点击运行时实体可以在 Inspector 中查看其组件数据。
+
+### Inspector 面板
+
+在 Play Mode 下选中运行时实体后,Inspector 面板会:
+
+- 显示蓝色 **RUNTIME** 标记
+- 列出该实体的所有运行时组件及其当前属性值
+- 属性值每 500 毫秒自动刷新,反映游戏中的实时状态
+- 支持直接编辑数值、布尔值、字符串和向量属性,修改会立即发送到游戏实例中生效
+
+<Aside type="caution">
+ Play Mode 下在 Inspector 中做的修改仅影响运行中的游戏实例。停止预览后,所有运行时修改会丢失,场景数据恢复到启动预览前的状态。
+</Aside>
+
+### 退出 Play Mode
+
+点击 **Stop** 按钮后:
+
+- 游戏实例被销毁
+- Hierarchy 面板恢复编辑模式的实体树,展开状态自动还原
+- Inspector 面板恢复到编辑模式
+- 所有运行时修改不会保存到场景文件
+
+## FPS 显示
+
+预览运行时,工具栏右侧会实时显示当前帧率(FPS)。停止预览后 FPS 显示自动隐藏。
+
+## 注意事项
+
+- Play Mode 下 Hierarchy 面板的编辑功能被禁用,包括拖拽排序、右键菜单和重命名
+- 运行时实体列表会定期更新,大量实体时可能存在短暂延迟
+- 分辨率切换在预览运行中也可以使用,画面会立即调整大小
+- Inspector 中正在编辑的输入框不会被自动刷新覆盖,确保手动输入不被打断
diff --git a/docs/astro/src/content/docs/zh/guides/project-settings.mdx b/docs/astro/src/content/docs/zh/guides/project-settings.mdx
new file mode 100644
index 000000000..1739f19b4
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/project-settings.mdx
@@ -0,0 +1,113 @@
+---
+title: 项目设置
+description: 配置 ESEngine 项目的运行时、构建和编辑器参数
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+项目设置集中管理引擎运行时参数、物理模拟、构建选项和编辑器行为。所有设置会自动保存到项目配置文件中,在团队成员之间共享。
+
+## 打开设置
+
+通过菜单栏 **Edit → Settings...** 或快捷键 `Ctrl+,`(macOS 为 `Cmd+,`)打开设置对话框。左侧导航栏列出所有设置分类,点击分类切换右侧内容区域。
+
+## General
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| Language | select | `en` | 编辑器界面语言 |
+| Preview Port | number | `3456` | 预览服务器监听的本地端口,范围 1024–65535 |
+
+## Project
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| Spine Version | select | `none` | 使用的 Spine 运行时版本。可选 `None`、`4.2`、`4.1`、`3.8`。构建时会自动包含对应版本的 Spine WASM 模块。 |
+| Project Name | string | 空 | 项目名称,显示在编辑器标题栏 |
+| Version | string | 空 | 项目版本号 |
+| Default Scene | string | 空 | 运行时默认加载的场景路径 |
+| Design Width | number | `1920` | 设计分辨率宽度(像素) |
+| Design Height | number | `1080` | 设计分辨率高度(像素) |
+
+<Aside type="tip">
+ 设计分辨率决定了 Canvas 组件的基准尺寸。配合 Canvas Scale Mode 使用,可以让游戏在不同屏幕尺寸上正确适配。
+</Aside>
+
+## Scene View
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| Show Grid | boolean | `true` | 在场景视图中显示背景网格 |
+| Grid Color | color | `#333333` | 网格线颜色 |
+| Grid Opacity | range | `1.0` | 网格透明度,范围 0–1 |
+| Show Gizmos | boolean | `true` | 显示 Gizmo 辅助图形(变换手柄、锚点等) |
+| Show Selection Box | boolean | `true` | 显示选中实体的包围框 |
+| Show Colliders | boolean | `true` | 显示物理碰撞体的线框 |
+| Show Stats | boolean | `false` | 在场景视图左上角显示帧率和渲染统计 |
+| Grid Size | number | `50` | 网格单元大小(像素),范围 5–500 |
+
+## Physics
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| Enable Physics | boolean | `false` | 启用物理模拟。启用后构建会自动包含物理 WASM 模块。 |
+| Gravity X | number | `0` | 水平重力分量 |
+| Gravity Y | number | `-9.81` | 垂直重力分量(负数 = 向下) |
+| Fixed Timestep | number | `1/60` | 物理步进间隔(秒),最小值 0.001 |
+| Sub-Step Count | number | `4` | 每次物理步进的子步数,范围 1–16。值越大精度越高,性能开销越大。 |
+
+## Build
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| Atlas Max Size | select | `2048` | 纹理图集最大尺寸(像素)。可选 `512`、`1024`、`2048`、`4096`。 |
+| Atlas Padding | number | `2` | 图集中纹理之间的间距(像素),范围 0–16。防止纹理采样时出现边缘渗色。 |
+
+<Aside type="note">
+ 图集相关设置影响所有构建配置。单个构建配置的选项(场景列表、平台设置等)在构建面板中管理,详见[构建](/zh/guides/building)文档。
+</Aside>
+
+## Runtime
+
+运行时设置控制游戏实际运行时的引擎行为,在预览和构建产物中生效。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| Scene Transition Duration | number | `0.3` | 场景切换时的淡入淡出时长(秒),范围 0–5 |
+| Scene Transition Color | color | `#000000` | 场景切换过渡期间的背景颜色 |
+| Default Font Family | string | `Arial` | 文本渲染的默认字体。应用于 Text 和 TextInput 组件。 |
+| Canvas Scale Mode | select | `FixedHeight` | Canvas 适配模式。决定游戏画面如何适应不同屏幕尺寸。 |
+| Canvas Match W/H | range | `0.5` | 宽高匹配权重,范围 0–1。仅在 Scale Mode 为 `Match` 时可见。0 = 完全匹配宽度,1 = 完全匹配高度。 |
+| Max Delta Time | number | `0.25` | 单帧最大时间步长(秒),范围 0.01–1。防止长时间卡顿后的物理和动画跳变。 |
+| Max Fixed Steps | number | `8` | 每帧最大 Fixed Update 迭代次数,范围 1–64。限制低帧率时的 CPU 开销。 |
+| Text Canvas Size | select | `512` | 文本渲染使用的离屏 Canvas 尺寸。可选 `256`、`512`、`1024`、`2048`。值越大支持的文本区域越大,但内存占用更高。 |
+
+### Canvas Scale Mode 详解
+
+| 模式 | 行为 |
+|------|------|
+| **Fixed Width** | 保持设计宽度不变,高度根据屏幕比例缩放 |
+| **Fixed Height** | 保持设计高度不变,宽度根据屏幕比例缩放 |
+| **Expand** | 取宽度和高度中较大的缩放比,确保设计区域完全可见 |
+| **Shrink** | 取宽度和高度中较小的缩放比,确保屏幕被完全填充 |
+| **Match** | 在宽度和高度的缩放比之间插值,由 Canvas Match W/H 控制混合权重 |
+
+## SDK 中使用 RuntimeConfig
+
+编辑器中的运行时设置会在构建时写入项目配置。在脚本中,可以通过 `RuntimeConfig` 对象直接读取或覆盖这些值:
+
+```typescript
+import { RuntimeConfig } from 'esengine';
+
+RuntimeConfig.maxDeltaTime = 0.25;
+RuntimeConfig.maxFixedSteps = 8;
+RuntimeConfig.sceneTransitionDuration = 0.5;
+RuntimeConfig.defaultFontFamily = 'Noto Sans SC';
+RuntimeConfig.canvasScaleMode = 1; // 0=FixedWidth, 1=FixedHeight, 2=Expand, 3=Shrink, 4=Match
+RuntimeConfig.canvasMatchWidthOrHeight = 0.5;
+RuntimeConfig.textCanvasSize = 1024;
+```
+
+<Aside type="caution">
+ 在脚本中修改 `RuntimeConfig` 会覆盖编辑器设置中的值。建议仅在需要动态调整时使用代码修改,日常配置通过设置对话框管理。
+</Aside>
diff --git a/docs/astro/src/content/docs/zh/guides/scenes.mdx b/docs/astro/src/content/docs/zh/guides/scenes.mdx
index 1363fe0dc..724d7b483 100644
--- a/docs/astro/src/content/docs/zh/guides/scenes.mdx
+++ b/docs/astro/src/content/docs/zh/guides/scenes.mdx
@@ -170,6 +170,22 @@ app.setInitialScene('menu');
app.run();
```
+除了通过 `path` 指定场景文件路径外,也可以通过 `data` 直接传入场景数据对象,适用于动态生成或内存中的场景:
+
+```typescript
+app.registerScene({
+ name: 'procedural',
+ data: {
+ version: '1.0',
+ name: 'procedural',
+ entities: [],
+ },
+ setup: (ctx) => {
+ // 通过代码生成实体
+ },
+});
+```
+
<Aside type="tip">
`systems` 中注册的系统会自动包装为场景作用域系统,仅在该场景状态为 `running` 时执行。
</Aside>
@@ -186,8 +202,33 @@ await mgr.switchTo('game');
// 带淡入淡出过渡的切换
await mgr.switchTo('game', { transition: 'fade', duration: 0.5 });
+
+// 完整的切换选项
+await mgr.switchTo('game', {
+ transition: 'fade',
+ duration: 1.0,
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ keepPersistent: true,
+ onStart: () => console.log('transition started'),
+ onComplete: () => console.log('transition finished'),
+});
```
+`switchTo` 的完整选项:
+
+| 选项 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `transition` | `'none' \| 'fade'` | `'none'` | 过渡动画类型 |
+| `duration` | `number` | 引擎默认值 | 过渡总时长(秒),淡出和淡入各占一半 |
+| `color` | `Color` | 引擎默认值 | 淡入淡出的遮罩颜色 |
+| `keepPersistent` | `boolean` | `true` | 是否保留持久化实体 |
+| `onStart` | `() => void` | - | 过渡开始时的回调 |
+| `onComplete` | `() => void` | - | 过渡完成时的回调 |
+
+<Aside type="note">
+ 过渡进行中调用 `switchTo` 会被忽略。可通过 `mgr.isTransitioning()` 检查是否正在过渡。
+</Aside>
+
## 多场景(叠加加载)
除了切换主场景,还可以使用叠加加载在当前场景之上加载额外场景。适合用于 HUD、暂停菜单等需要与主场景共存的 UI 层:
@@ -303,11 +344,15 @@ import { transitionTo } from 'esengine';
// 淡出到黑色,切换场景,淡入
await transitionTo(app, 'game', { type: 'fade', duration: 1.0 });
-// 交叉淡入淡出
-await transitionTo(app, 'game', { type: 'crossfade', duration: 0.5 });
+// 自定义遮罩颜色
+await transitionTo(app, 'game', {
+ type: 'fade',
+ duration: 0.5,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+});
```
-`transitionTo` 会处理旧场景的淡出、场景切换以及新场景的淡入,整个过程是异步的。
+`transitionTo` 是对 `mgr.switchTo()` 的便捷封装,内部会获取 `SceneManager` 资源并调用 `switchTo`。整个过程是异步的——先淡出旧场景,执行场景切换,再淡入新场景。
## 查询场景状态
@@ -317,12 +362,16 @@ await transitionTo(app, 'game', { type: 'crossfade', duration: 0.5 });
const mgr = app.getResource(SceneManager);
mgr.getActive(); // 当前主场景名,无主场景时返回 null
+mgr.isActive('game'); // 判断指定场景是否为主场景
mgr.getActiveScenes(); // 所有状态为 'running' 的场景名数组
mgr.getLoaded(); // 所有已加载的场景名数组
mgr.isLoaded('game'); // 场景是否已加载
mgr.isPaused('game'); // 场景是否处于暂停状态
mgr.isSleeping('game'); // 场景是否处于休眠状态
+mgr.isTransitioning(); // 是否正在执行场景过渡
mgr.getSceneStatus('game'); // 返回场景详细状态
+mgr.getScene('game'); // 获取场景的 SceneContext,未加载时返回 null
+mgr.getLoadOrder(); // 按加载顺序返回场景名数组
```
`getSceneStatus` 的返回值类型为:
@@ -336,6 +385,20 @@ mgr.getSceneStatus('game'); // 返回场景详细状态
| `'unloading'` | 场景正在卸载中 |
| `null` | 场景未加载 |
+## 场景层序
+
+当多个场景同时加载时,渲染和系统执行按加载顺序进行。使用 `bringToTop()` 将指定场景移到最顶层:
+
+```typescript
+const mgr = app.getResource(SceneManager);
+
+await mgr.loadAdditive('hud');
+await mgr.loadAdditive('dialog');
+
+mgr.bringToTop('hud');
+mgr.getLoadOrder(); // ['game', 'dialog', 'hud']
+```
+
## 场景数据类型
| 类型 | 字段 |