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
docs: update scene management, custom draw, and architecture documentation
esenginefac203eb7483
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex adf9371a5..50b805adf 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -216,6 +216,38 @@ The engine uses a compatibility layer (`weapp-adapter.js`) to provide browser-li3. **Minimal Allocations**: Entity recycling, pool-based allocation4. **Batch Rendering**: BatchRenderer2D for efficient sprite rendering+## Scene Management++The SDK provides a first-class scene management system built on top of ECS resources.++### Architecture++```+┌─────────────────────────────────────────────────────────────┐+│ SceneManager (Resource) │+│ ┌──────────────────────────────────────────────────────┐ │+│ │ Scene Registry │ │+│ │ configs_: Map<string, SceneConfig> │ │+│ └──────────────────────────────────────────────────────┘ │+│ ┌──────────────────────────────────────────────────────┐ │+│ │ Active Scenes │ │+│ │ scenes_: Map<string, SceneInstance> │ │+│ │ activeScene_ / additiveScenes_ │ │+│ └──────────────────────────────────────────────────────┘ │+│ ┌──────────────────────────────────────────────────────┐ │+│ │ Lifecycle: load → running → paused/sleeping → unload │ │+│ └──────────────────────────────────────────────────────┘ │+└─────────────────────────────────────────────────────────────┘+```++### Key Design Decisions++- **Single World**: All scenes share one ECS World. Entities are tagged with `SceneOwner` component to track ownership.+- **Camera Filtering**: The render system filters cameras by `SceneOwner`, only rendering cameras belonging to active scenes.+- **Draw Callback Scoping**: Custom draw callbacks are associated with scene names and filtered during render.+- **System Scoping**: Scene systems are wrapped to only execute when their scene status is 'running'.+- **Automatic Plugin**: `sceneManagerPlugin` is included in `createWebApp()` and runs a transition update system each frame.+## Future Improvements- [ ] Component groups for cache optimization@@ -224,3 +256,4 @@ The engine uses a compatibility layer (`weapp-adapter.js`) to provide browser-li- [x] Scene serialization- [x] Physics integration- [x] UI system+- [x] Scene managementdiff --git a/docs/astro/src/content/docs/guides/custom-draw.mdx b/docs/astro/src/content/docs/guides/custom-draw.mdxindex 0ee976436..8bdc1a6d7 100644--- a/docs/astro/src/content/docs/guides/custom-draw.mdx+++ b/docs/astro/src/content/docs/guides/custom-draw.mdx@@ -32,6 +32,32 @@ clearDrawCallbacks();`Draw.begin()` and `Draw.end()` are called internally by the engine. Only use the Draw API inside a registered callback.</Aside>+## Scene-Scoped Callbacks++When using the [Scene Manager](/microes/guides/scenes/#scene-manager), register draw callbacks through the `SceneContext` to automatically scope them to a scene. The callback is only executed when the scene is active and is automatically cleaned up when the scene unloads:++```typescript+app.registerScene({+ name: 'game',+ setup: (ctx) => {+ ctx.registerDrawCallback('game-grid', (elapsed) => {+ // only runs when 'game' scene is active+ Draw.line({ x: -1000, y: 0 }, { x: 1000, y: 0 }, { r: 0.3, g: 0.3, b: 0.3, a: 1 }, 1);+ });+ },+});+```++You can also pass a scene name directly to `registerDrawCallback`:++```typescript+import { registerDrawCallback } from 'esengine';++registerDrawCallback('my-callback', drawFn, 'game');+```++Callbacks with no scene association always execute regardless of which scenes are active.+## Drawing Primitives### Linesdiff --git a/docs/astro/src/content/docs/guides/scenes.mdx b/docs/astro/src/content/docs/guides/scenes.mdxindex 897177858..fe821aec9 100644--- a/docs/astro/src/content/docs/guides/scenes.mdx+++ b/docs/astro/src/content/docs/guides/scenes.mdx@@ -132,6 +132,217 @@ addSystem(defineSystem(Entities have a `visible` property (default `true`). When set to `false` in the editor, the entity's components are skipped during scene loading — it exists in the hierarchy but has no runtime behaviour. Use this to keep reference entities in the scene file without spawning them.+## 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.++<Aside type="note">+ If you are building an `App` manually, add the `sceneManagerPlugin` to enable scene management.+</Aside>++## Registering Scenes++Before the app starts, register each scene with a name, a path to its JSON file, and optional per-scene systems and lifecycle hooks:++```typescript+import { createWebApp, SceneManager, Schedule, type SceneConfig } from 'esengine';++const app = createWebApp(module);++app.registerScene({+ name: 'menu',+ path: '/scenes/menu.json',+ systems: [+ { schedule: Schedule.Update, system: menuUpdateSystem },+ ],+ setup: (ctx) => {+ ctx.registerDrawCallback('menu-particles', drawParticles);+ },+ cleanup: (ctx) => {+ // called before scene unload+ },+});++app.registerScene({ name: 'game', path: '/scenes/game.json' });+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 |++## Switching Scenes++Use `SceneManager` to switch between registered scenes. Switching unloads the current scene and loads the new one:++```typescript+const mgr = app.getResource(SceneManager);++// Simple switch (unloads old, loads new)+await mgr.switchTo('game');++// Switch with fade transition+await mgr.switchTo('game', { transition: 'fade', duration: 0.5 });+```++<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.+</Aside>++## Multi-Scene (Additive Loading)++Load additional scenes on top of the current primary scene. This is useful for HUDs, pause menus, or overlay layers:++```typescript+const mgr = app.getResource(SceneManager);++// Load a scene on top of the current one+await mgr.loadAdditive('hud');+await mgr.loadAdditive('pause-menu');++// Unload additive scene+await mgr.unload('pause-menu');+```++Additive scenes run their systems alongside the primary scene. Each loaded scene maintains its own lifecycle independently.++## Scene Lifecycle++Control whether a loaded scene's systems and entities are active:++```typescript+const mgr = app.getResource(SceneManager);++// Pause — systems stop, entities remain visible+mgr.pause('game');+mgr.resume('game');++// Sleep — systems stop, entities hidden+mgr.sleep('game');+mgr.wake('game');+```++| Method | Systems | Entities Visible |+|--------|---------|-----------------|+| `resume` / `wake` | Running | Yes |+| `pause` | Stopped | Yes |+| `sleep` | Stopped | No |++<Aside type="tip">+ Use `pause` for a pause menu overlay — the game world stays visible behind it. Use `sleep` to fully deactivate a scene that should not render at all.+</Aside>++## Scene Context++When a scene loads, its `setup` callback receives a `SceneContext` that provides scene-scoped operations:++```typescript+app.registerScene({+ name: 'game',+ path: '/scenes/game.json',+ setup: (ctx) => {+ // Spawn entities owned by this scene+ const e = ctx.spawn();++ // Register draw callbacks scoped to this scene+ ctx.registerDrawCallback('game-debug', drawDebug);++ // Add post-process effects scoped to this scene+ ctx.addPostProcessPass('bloom', bloomShader);++ // Mark entity as persistent (survives scene unload)+ ctx.setPersistent(e, true);+ },+});+```++Entities spawned through `SceneContext` are automatically tagged with a `SceneOwner` component and cleaned up when the scene unloads — unless marked as persistent.++### SceneOwner Component++Entities loaded from a scene file automatically get a `SceneOwner` component. Use it to check which scene owns an entity:++```typescript+import { SceneOwner } from 'esengine';++const owner = world.get(entity, SceneOwner);+console.log(owner.scene); // 'game'+console.log(owner.persistent); // false+```++### Scene-scoped Systems++Systems registered in a scene config only run when that scene's status is `'running'`. They are automatically wrapped so they skip execution when the scene is paused or sleeping:++```typescript+import { defineSystem, Query, Mut, LocalTransform, Schedule } from 'esengine';++const mySystem = defineSystem(+ [Query(Mut(LocalTransform))],+ (query) => {+ for (const [entity, transform] of query) {+ // runs only while 'game' scene is running+ }+ }+);++app.registerScene({+ name: 'game',+ path: '/scenes/game.json',+ systems: [{ schedule: Schedule.Update, system: mySystem }],+});+```++## Scene Transitions++For built-in visual transitions between scenes, use the standalone `transitionTo` helper:++```typescript+import { transitionTo } from 'esengine';++// Fade to black, switch, fade in+await transitionTo(app, 'game', { type: 'fade', duration: 1.0 });++// Crossfade between scenes+await transitionTo(app, 'game', { type: 'crossfade', duration: 0.5 });+```++| Transition Type | Description |+|----------------|-------------|+| `fade` | Fades to black, switches scene, fades in |+| `crossfade` | Blends the old and new scenes simultaneously |++## Querying Scene State++Inspect which scenes are loaded and their current 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+```++| 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 |+## Scene Data Types| Type | Fields |diff --git a/docs/astro/src/content/docs/zh/guides/custom-draw.mdx b/docs/astro/src/content/docs/zh/guides/custom-draw.mdxindex d11a8cf52..a14e0f9ef 100644--- a/docs/astro/src/content/docs/zh/guides/custom-draw.mdx+++ b/docs/astro/src/content/docs/zh/guides/custom-draw.mdx@@ -32,6 +32,32 @@ clearDrawCallbacks();`Draw.begin()` 和 `Draw.end()` 由引擎内部调用。只在注册的回调中使用 Draw API。</Aside>+## 场景作用域回调++使用[场景管理器](/microes/zh/guides/scenes/#场景管理器)时,通过 `SceneContext` 注册绘制回调,自动将其作用域限定到场景。回调仅在场景激活时执行,场景卸载时自动清理:++```typescript+app.registerScene({+ name: 'game',+ setup: (ctx) => {+ ctx.registerDrawCallback('game-grid', (elapsed) => {+ // 仅在 'game' 场景激活时运行+ Draw.line({ x: -1000, y: 0 }, { x: 1000, y: 0 }, { r: 0.3, g: 0.3, b: 0.3, a: 1 }, 1);+ });+ },+});+```++也可以直接向 `registerDrawCallback` 传递场景名:++```typescript+import { registerDrawCallback } from 'esengine';++registerDrawCallback('my-callback', drawFn, 'game');+```++没有关联场景的回调始终执行,不受当前活跃场景影响。+## 绘制图元### 线段diff --git a/docs/astro/src/content/docs/zh/guides/scenes.mdx b/docs/astro/src/content/docs/zh/guides/scenes.mdxindex 6bfb65bce..1363fe0dc 100644--- a/docs/astro/src/content/docs/zh/guides/scenes.mdx+++ b/docs/astro/src/content/docs/zh/guides/scenes.mdx@@ -1,6 +1,6 @@---title: 场景-description: 在 ESEngine 中创建、加载和查询场景+description: 在 ESEngine 中创建、加载和管理场景---import { Aside } from '@astrojs/starlight/components';@@ -132,6 +132,210 @@ addSystem(defineSystem(实体拥有 `visible` 属性(默认 `true`)。在编辑器中将其设为 `false` 时,场景加载会跳过该实体的组件 — 它在层级中存在但没有运行时行为。适合用于在场景文件中保留参考实体而不在运行时生成。+## 场景管理器++SDK 提供了 `SceneManager` 资源和 `sceneManagerPlugin` 插件,用于管理多个场景的加载、切换和生命周期。使用 `createWebApp()` 时会自动包含该插件,无需手动注册。++```typescript+import { SceneManager } from 'esengine';++const mgr = app.getResource(SceneManager);+```++## 注册场景++在应用启动前,使用 `app.registerScene()` 注册所有场景。每个场景需要一个唯一名称和场景文件路径,还可以配置专属系统、setup 回调和 cleanup 回调:++```typescript+import { SceneManager, type SceneConfig, Schedule } from 'esengine';++const app = createWebApp(module);++app.registerScene({+ name: 'menu',+ path: '/scenes/menu.json',+ systems: [+ { schedule: Schedule.Update, system: menuUpdateSystem },+ ],+ setup: (ctx) => {+ ctx.registerDrawCallback('menu-particles', drawParticles);+ },+ cleanup: (ctx) => {+ // 场景卸载前调用+ },+});++app.registerScene({ name: 'game', path: '/scenes/game.json' });+app.setInitialScene('menu');+app.run();+```++<Aside type="tip">+ `systems` 中注册的系统会自动包装为场景作用域系统,仅在该场景状态为 `running` 时执行。+</Aside>++## 切换场景++通过 `SceneManager` 的 `switchTo` 方法切换场景。切换会先卸载当前主场景,再加载目标场景:++```typescript+const mgr = app.getResource(SceneManager);++// 简单切换(卸载旧场景,加载新场景)+await mgr.switchTo('game');++// 带淡入淡出过渡的切换+await mgr.switchTo('game', { transition: 'fade', duration: 0.5 });+```++## 多场景(叠加加载)++除了切换主场景,还可以使用叠加加载在当前场景之上加载额外场景。适合用于 HUD、暂停菜单等需要与主场景共存的 UI 层:++```typescript+const mgr = app.getResource(SceneManager);++// 在当前场景上叠加加载+await mgr.loadAdditive('hud');+await mgr.loadAdditive('pause-menu');++// 卸载叠加场景+await mgr.unload('pause-menu');+```++<Aside type="note">+ 叠加场景与主场景独立运行,各自拥有独立的系统和生命周期。卸载叠加场景不会影响主场景。+</Aside>++## 场景生命周期++每个已加载的场景都有自己的状态。你可以暂停、恢复、休眠和唤醒场景:++```typescript+const mgr = app.getResource(SceneManager);++mgr.pause('game'); // 系统停止执行,实体保持可见+mgr.resume('game'); // 恢复系统执行++mgr.sleep('game'); // 系统停止执行,实体隐藏+mgr.wake('game'); // 恢复系统执行并显示实体+```++| 方法 | 系统执行 | 实体可见 |+|------|----------|----------|+| `resume` / `wake` | 是 | 是 |+| `pause` | 否 | 是 |+| `sleep` | 否 | 否 |++## 场景上下文++场景加载时,`setup` 回调接收一个 `SceneContext` 对象,用于执行作用域为当前场景的操作:++```typescript+app.registerScene({+ name: 'game',+ path: '/scenes/game.json',+ setup: (ctx) => {+ // 生成属于此场景的实体+ const e = ctx.spawn();++ // 注册作用域为此场景的绘制回调+ ctx.registerDrawCallback('game-debug', drawDebug);++ // 添加作用域为此场景的后处理效果+ ctx.addPostProcessPass('bloom', bloomShader);++ // 标记实体为持久(场景卸载时不销毁)+ ctx.setPersistent(e, true);+ },+});+```++通过 `ctx.spawn()` 生成的实体会自动获得 `SceneOwner` 组件,在场景卸载时会被一并销毁(除非标记为持久)。++### SceneOwner 组件++从场景文件加载的实体和通过 `ctx.spawn()` 生成的实体都会自动获得 `SceneOwner` 组件,用于标识实体所属的场景:++```typescript+import { SceneOwner } from 'esengine';++// 检查实体属于哪个场景+const owner = world.get(entity, SceneOwner);+console.log(owner.scene); // 'game'+console.log(owner.persistent); // false+```++### 场景作用域系统++在 `registerScene` 中通过 `systems` 注册的系统会自动包装,仅在场景状态为 `running` 时执行:++```typescript+import { defineSystem, Query, Mut, LocalTransform, Schedule } from 'esengine';++const mySystem = defineSystem(+ [Query(Mut(LocalTransform))],+ (query) => {+ for (const [entity, transform] of query) {+ // 更新变换+ }+ }+);++app.registerScene({+ name: 'game',+ path: '/scenes/game.json',+ systems: [{ schedule: Schedule.Update, system: mySystem }],+});+```++<Aside type="tip">+ 当场景处于 `paused` 或 `sleeping` 状态时,其作用域系统不会执行,无需手动判断场景状态。+</Aside>++## 场景过渡动画++使用 `transitionTo` 函数实现带动画效果的场景切换:++```typescript+import { transitionTo } from 'esengine';++// 淡出到黑色,切换场景,淡入+await transitionTo(app, 'game', { type: 'fade', duration: 1.0 });++// 交叉淡入淡出+await transitionTo(app, 'game', { type: 'crossfade', duration: 0.5 });+```++`transitionTo` 会处理旧场景的淡出、场景切换以及新场景的淡入,整个过程是异步的。++## 查询场景状态++`SceneManager` 提供了一组方法用于查询当前场景的状态:++```typescript+const mgr = app.getResource(SceneManager);++mgr.getActive(); // 当前主场景名,无主场景时返回 null+mgr.getActiveScenes(); // 所有状态为 'running' 的场景名数组+mgr.getLoaded(); // 所有已加载的场景名数组+mgr.isLoaded('game'); // 场景是否已加载+mgr.isPaused('game'); // 场景是否处于暂停状态+mgr.isSleeping('game'); // 场景是否处于休眠状态+mgr.getSceneStatus('game'); // 返回场景详细状态+```++`getSceneStatus` 的返回值类型为:++| 状态 | 说明 |+|------|------|+| `'loading'` | 场景正在加载中 |+| `'running'` | 场景正在运行 |+| `'paused'` | 场景已暂停(系统停止,实体可见) |+| `'sleeping'` | 场景已休眠(系统停止,实体隐藏) |+| `'unloading'` | 场景正在卸载中 |+| `null` | 场景未加载 |+## 场景数据类型| 类型 | 字段 |