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: add RenderTexture guide, Commands API, render stats, v0.4.1 changelog
esenginea19ed3ff4a13
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex 47cf73ebb..566b08e66 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -71,6 +71,7 @@ export default defineConfig({{ label: 'Bitmap Text', translations: { 'zh-CN': '位图文本' }, slug: 'guides/bitmap-text' },{ label: 'Custom Draw', translations: { 'zh-CN': '自定义绘制' }, slug: 'guides/custom-draw' },{ label: 'Post-Processing', translations: { 'zh-CN': '后处理效果' }, slug: 'guides/post-processing' },+ { label: 'Render Texture', translations: { 'zh-CN': '渲染纹理' }, slug: 'guides/render-texture' },],},{ label: 'Scenes', translations: { 'zh-CN': '场景' }, slug: 'guides/scenes' },@@ -87,6 +88,7 @@ export default defineConfig({label: 'Changelog',translations: { 'zh-CN': '更新日志' },items: [+ { label: 'v0.4.1', slug: 'changelog-v041' },{ label: 'v0.4.0', slug: 'changelog-v040' },{ label: 'v0.3.0', slug: 'changelog' },],diff --git a/docs/astro/src/content/docs/changelog-v041.mdx b/docs/astro/src/content/docs/changelog-v041.mdxnew file mode 100644index 000000000..47778ee57--- /dev/null+++ b/docs/astro/src/content/docs/changelog-v041.mdx@@ -0,0 +1,69 @@+---+title: v0.4.1+description: ESEngine v0.4.1 release notes+---++import { Aside } from '@astrojs/starlight/components';++## Multi-Camera Rendering++- Added viewport fields (`viewportX`, `viewportY`, `viewportW`, `viewportH`) and `clearFlags` to Camera component+- Per-camera render pipeline with viewport/scissor support for split-screen and minimap use cases+- Camera priority-based render ordering+- Editor scene view with per-camera color coding, camera icons, priority labels, and viewport preview overlay++## BitmapText & BMFont++- Added `BitmapText` component for GPU-rendered bitmap font text with color, fontSize, alignment, spacing, and layer sorting+- BMFont parser (`.fnt` text format) and LabelAtlas creation via the batch renderer+- Editor support: font loading, inspector UI, thumbnail preview, click-to-navigate, and Tab navigation in BitmapFont glyph list++## UIMask++- Added `UIMask` clip rect component for rectangular UI clipping+- Clip rect computation with proper hierarchy support++## Spine Runtime Optional++- Spine runtime is now optional — `none` is the default when no Spine assets are used+- Reduces build size for projects that don't use Spine animation++## Name Component++- Added `Name` component, automatically assigned to entities loaded from scenes+- Added `findEntityByName()` utility for entity lookup by name++## Editor Improvements++- File rename support with `.meta` file handling+- Duplicate filename and illegal character validation+- Error toast notifications for all file operations+- Improved entity duplicate naming from `_copy` to `(N)` pattern++## Performance++- Cached `entityCount()` with O(1) counter instead of O(n) scan+- Replaced Camera/Canvas linear scans with C++ ECS view queries, eliminating ~4000 WASM bridge calls per frame+- Reuse `ext_vertex_storage_` buffers instead of clear+realloc each frame+- Replaced O(n²) selection sort with `std::sort` in `Registry::sort()`+- SpineRenderer: pre-allocate VAO/VBO/EBO, reuse with dynamic capacity+- BatchRenderer: only bind active texture slots instead of all 8+- Nine-slice: hoist texture slot lookup outside loop+- TransformSystem: merge double iteration into single pass+- SystemRunner: cache args array per system to avoid per-frame allocation++## Documentation++- Added Commands API reference with full `EntityCommands` builder API+- Added RenderTexture off-screen rendering guide+- Added Render Stats and Render Stages to the rendering guide+- Added ECS interaction guide — mapping from user intent to system parameters+- Added BitmapText, UIMask, Name, LabelAtlas component docs+- Rewrote scene examples to use proper system patterns (`Query`, `Commands`)++## Bug Fixes++- Fixed use-after-free on registry disposal by adding `disconnectCpp`+- Fixed unnecessary scene reloads on entity selection+- Fixed WASM error handling for missing modules+- Fixed SpineExtension memory leak by using static local instancesdiff --git a/docs/astro/src/content/docs/core-concepts/ecs.mdx b/docs/astro/src/content/docs/core-concepts/ecs.mdxindex 6af994c93..95a9dfeb3 100644--- a/docs/astro/src/content/docs/core-concepts/ecs.mdx+++ b/docs/astro/src/content/docs/core-concepts/ecs.mdx@@ -133,6 +133,24 @@ See [Systems](/microes/core-concepts/systems/) for the full API.4. **Update loop** — systems query and process scene entities every frame5. **Render** — the C++ backend automatically renders all entities with `Sprite` and `Camera` components+## How You Interact with ECS++The `World` stores all entities and components. In your scripts, you interact with it through system parameters:++| What you want to do | System parameter |+|---------------------|-----------------|+| Iterate entities with specific components | `Query(ComponentA, ComponentB)` |+| Read component data | `Query(Component)` — data comes with iteration |+| Mutate component data | `Query(Mut(Component))` — wrap with `Mut` |+| Spawn a new entity | `Commands()` → `cmds.spawn()` |+| Despawn an entity | `Commands()` → `cmds.despawn(entity)` |+| Add a component at runtime | `Commands()` → `cmds.entity(e).insert(Component, data)` |+| Remove a component at runtime | `Commands()` → `cmds.entity(e).remove(Component)` |+| Read a resource | `Res(ResourceType)` |+| Mutate a resource | `ResMut(ResourceType)` |++See [Systems](/microes/core-concepts/systems/) and [Queries](/microes/core-concepts/queries/) for detailed usage.+## Next Steps- [Components](/microes/core-concepts/components/) — builtin and custom componentsdiff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdxindex d63f31527..26939286d 100644--- a/docs/astro/src/content/docs/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx@@ -64,20 +64,54 @@ addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);### Commands-Spawn and despawn entities at runtime:+Create, modify, and destroy entities at runtime:```typescript-import { Commands } from 'esengine';+import { Commands, Sprite, LocalTransform } from 'esengine';defineSystem([Commands()], (cmds) => {- cmds.spawn()- .insert(Sprite, { size: { x: 50, y: 50 } })- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } });-- cmds.despawn(entity);+ // Spawn a new entity with components (chainable)+ const bullet = cmds.spawn()+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, { size: { x: 8, y: 8 } })+ .id();++ // Modify an existing entity+ cmds.entity(bullet)+ .insert(Velocity, { linear: { x: 100, y: 0 } })+ .remove(Sprite);++ // Despawn an entity+ cmds.despawn(bullet);++ // Insert a resource+ cmds.insertResource(Score, { value: 0 });});```+#### Commands API++| Method | Returns | Description |+|--------|---------|-------------|+| `cmds.spawn()` | `EntityCommands` | Create a new entity, returns a builder |+| `cmds.entity(entity)` | `EntityCommands` | Get a builder for an existing entity |+| `cmds.despawn(entity)` | `Commands` | Queue entity for destruction |+| `cmds.insertResource(res, value)` | `Commands` | Insert or overwrite a resource |++#### EntityCommands API++`spawn()` and `entity()` return an `EntityCommands` builder. All methods are chainable:++| Method | Returns | Description |+|--------|---------|-------------|+| `.insert(component, data?)` | `this` | Add or update a component |+| `.remove(component)` | `this` | Remove a component |+| `.id()` | `Entity` | Get the entity ID |++<Aside type="note">+ Commands are buffered and applied at the end of the current schedule stage, not immediately. The exception is `.id()` — calling it triggers immediate entity creation so the ID is available right away.+</Aside>+### QueryIterate entities with specific components:diff --git a/docs/astro/src/content/docs/guides/render-texture.mdx b/docs/astro/src/content/docs/guides/render-texture.mdxnew file mode 100644index 000000000..7ccd8413c--- /dev/null+++ b/docs/astro/src/content/docs/guides/render-texture.mdx@@ -0,0 +1,115 @@+---+title: Render Texture+description: Off-screen rendering with RenderTexture in ESEngine+---++import { Aside } from '@astrojs/starlight/components';++A **RenderTexture** lets you render a scene (or part of it) to an off-screen texture instead of the screen. This is useful for minimaps, mirrors, portals, post-processing inputs, and any effect that requires capturing rendered output.++## Creating a RenderTexture++```typescript+import { RenderTexture, type RenderTextureHandle } from 'esengine';++const rt: RenderTextureHandle = RenderTexture.create({+ width: 512,+ height: 512,+ depth: true,+ filter: 'linear',+});+```++### RenderTextureOptions++| Field | Type | Default | Description |+|-------|------|---------|-------------|+| `width` | `number` | — | Texture width in pixels |+| `height` | `number` | — | Texture height in pixels |+| `depth` | `boolean` | `false` | Attach a depth buffer |+| `filter` | `'nearest' \| 'linear'` | `'nearest'` | Texture filtering mode |++## Rendering to Texture++Wrap your draw calls between `begin()` and `end()`. Everything rendered in between goes to the texture instead of the screen:++```typescript+import { RenderTexture, Draw } from 'esengine';++RenderTexture.begin(rt, viewProjectionMatrix);++Draw.rect(0, 0, 100, 100, { r: 1, g: 0, b: 0, a: 1 });++RenderTexture.end();+```++The `viewProjection` parameter is a `Float32Array` containing the 4x4 view-projection matrix that defines the camera for this off-screen render pass.++<Aside type="note">+ `begin()` sets the render target and viewport. `end()` restores the previous render target. Always call `end()` after `begin()`.+</Aside>++## Using the Result++After rendering, `rt.textureId` holds the GPU texture ID. Use it anywhere a texture is expected:++```typescript+import { Draw, Sprite } from 'esengine';++Draw.texture(rt.textureId, 0, 0, rt.width, rt.height);+```++You can also assign it to a Sprite's texture for entity-based rendering.++## Depth Texture++If the RenderTexture was created with `depth: true`, retrieve the depth texture for effects like shadow mapping:++```typescript+const depthTextureId = RenderTexture.getDepthTexture(rt);+```++## Lifecycle++### Resizing++When the target resolution changes (e.g. window resize), resize the RenderTexture:++```typescript+const resized = RenderTexture.resize(rt, newWidth, newHeight);+```++`resize()` returns a new `RenderTextureHandle`. Use the returned handle going forward.++### Releasing++Release GPU resources when the RenderTexture is no longer needed:++```typescript+RenderTexture.release(rt);+```++## API Reference++| Method | Returns | Description |+|--------|---------|-------------|+| `RenderTexture.create(options)` | `RenderTextureHandle` | Create a new render texture |+| `RenderTexture.begin(rt, viewProjection)` | `void` | Begin rendering to texture |+| `RenderTexture.end()` | `void` | End rendering to texture |+| `RenderTexture.getDepthTexture(rt)` | `number` | Get depth texture ID |+| `RenderTexture.resize(rt, width, height)` | `RenderTextureHandle` | Resize render texture |+| `RenderTexture.release(rt)` | `void` | Release GPU resources |++### RenderTextureHandle++| Field | Type | Description |+|-------|------|-------------|+| `textureId` | `number` | GPU texture ID for the color attachment |+| `width` | `number` | Current width in pixels |+| `height` | `number` | Current height in pixels |++## Next Steps++- [Custom Draw](/microes/guides/custom-draw/) — immediate-mode drawing API+- [Post-Processing](/microes/guides/post-processing/) — full-screen effects+- [Materials & Shaders](/microes/guides/materials/) — custom shadersdiff --git a/docs/astro/src/content/docs/guides/rendering.mdx b/docs/astro/src/content/docs/guides/rendering.mdxindex 5fc3d8345..81ed3e917 100644--- a/docs/astro/src/content/docs/guides/rendering.mdx+++ b/docs/astro/src/content/docs/guides/rendering.mdx@@ -133,6 +133,47 @@ Set these values in the inspector when placing entities, or modify them at runtiThe C++ backend handles all WebGL rendering. You just set component data and the engine draws everything automatically each frame.</Aside>+## Render Stats++Use `Renderer.getStats()` to get per-frame rendering statistics, useful for profiling and debug overlays:++```typescript+import { Renderer, type RenderStats } from 'esengine';++const stats: RenderStats = Renderer.getStats();+console.log(`Draw calls: ${stats.drawCalls}, Triangles: ${stats.triangles}`);+```++| Field | Type | Description |+|-------|------|-------------|+| `drawCalls` | `number` | Total WebGL draw calls this frame |+| `triangles` | `number` | Total triangles rendered |+| `sprites` | `number` | Sprites drawn |+| `text` | `number` | Text elements drawn |+| `spine` | `number` | Spine skeletons drawn |+| `meshes` | `number` | Custom meshes drawn |+| `culled` | `number` | Objects culled (not drawn) |++## Render Stages++The rendering pipeline is divided into stages that execute in order. Each stage draws a category of objects:++| Stage | Value | Description |+|-------|-------|-------------|+| `Background` | 0 | Background layers (skyboxes, backgrounds) |+| `Opaque` | 1 | Opaque geometry (no transparency) |+| `Transparent` | 2 | Transparent/alpha-blended objects |+| `Overlay` | 3 | UI and overlay elements (drawn on top) |++When using [Custom Draw](/microes/guides/custom-draw/), specify a `RenderStage` to control when your draw commands execute relative to the built-in rendering:++```typescript+import { Draw, RenderStage } from 'esengine';++Draw.bindStage(RenderStage.Overlay);+Draw.rect(0, 0, 100, 50, { r: 0, g: 0, b: 0, a: 0.5 });+```+## Next Steps- [Canvas & Resolution](/microes/guides/canvas/) — screen adaptation and scale modes@@ -141,4 +182,5 @@ Set these values in the inspector when placing entities, or modify them at runti- [Bitmap Text](/microes/guides/bitmap-text/) — GPU-rendered bitmap font text- [Custom Draw](/microes/guides/custom-draw/) — immediate-mode drawing for debug visualization and dynamic graphics- [Post-Processing](/microes/guides/post-processing/) — full-screen effects (blur, vignette, grayscale)+- [Render Texture](/microes/guides/render-texture/) — off-screen rendering for minimaps, mirrors, and effects- [Geometry & Meshes](/microes/guides/geometry/) — custom mesh creation for advanced renderingdiff --git a/docs/astro/src/content/docs/guides/scenes.mdx b/docs/astro/src/content/docs/guides/scenes.mdxindex 0d9f76ef9..722bb0385 100644--- a/docs/astro/src/content/docs/guides/scenes.mdx+++ b/docs/astro/src/content/docs/guides/scenes.mdx@@ -38,47 +38,38 @@ A scene file contains:In the editor, scenes are loaded automatically — you only write scripts that define components and systems.-After building your project, the runtime loader handles scene loading:--```typescript-import { loadSceneWithAssets, type SceneData } from 'esengine';--const sceneData: SceneData = await fetch('/scene.json').then(r => r.json());-const entityMap = await loadSceneWithAssets(world, sceneData, { assetServer });-```--<Aside type="tip">- `loadSceneWithAssets` automatically loads textures, materials, and Spine assets referenced in the scene. Use `loadSceneData` if you don't need asset loading.-</Aside>+After building your project, the engine automatically loads the scene, resolves all referenced assets (textures, materials, Spine), and creates a default camera if none exists. You don't need to handle scene loading manually.## Finding Entities### By Name-Every entity loaded from a scene receives a built-in `Name` component with the name assigned in the editor. Use `findEntityByName` to look up entities:+Every entity loaded from a scene receives a built-in `Name` component with the name assigned in the editor. Query `Name` to find entities:```typescript-import { findEntityByName } from 'esengine';+import { defineSystem, addStartupSystem, Query, Name, LocalTransform } from 'esengine';-const player = findEntityByName(world, 'Player');-if (player !== null) {- const transform = world.get(player, LocalTransform);-}+addStartupSystem(defineSystem(+ [Query(Name, LocalTransform)],+ (query) => {+ for (const [entity, name, transform] of query) {+ if (name.value === 'Player') {+ // found the player entity+ }+ }+ }+));```### By Component or Tag-Use `getEntitiesWithComponents` or a `Query` to find entities by their components:+Use a `Query` to find entities by their components:```typescript-import { defineTag, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, defineTag, Query, Mut, LocalTransform } from 'esengine';const Player = defineTag('Player');-// Direct lookup-const players = world.getEntitiesWithComponents([Player]);--// In a systemaddSystem(defineSystem([Query(Mut(LocalTransform), Player)],(query) => {@@ -91,30 +82,24 @@ addSystem(defineSystem(### Traversing the Hierarchy-Use the `Parent` and `Children` components to walk the entity tree:+Use the `Children` component to walk the entity tree:```typescript-import { Parent, Children } from 'esengine';+import { defineSystem, addSystem, Query, Children, LocalTransform } from 'esengine';-const children = world.get(entity, Children);-if (children) {- for (const child of children.entities) {- const childTransform = world.get(child, LocalTransform);+addSystem(defineSystem(+ [Query(Children, LocalTransform)],+ (query) => {+ for (const [entity, children, transform] of query) {+ // children.entities contains child entity IDs+ }}-}+));```## Entity Hierarchy-Scene entities can form a tree via parent-child relationships. The engine manages `Parent` and `Children` components automatically.--```typescript-// Set parent (adds Parent component to child, updates Children on parent)-world.setParent(child, parent);--// Remove parent (child becomes a root entity)-world.removeParent(child);-```+Scene entities can form a tree via parent-child relationships. Set up parent-child relationships in the editor — the engine manages `Parent` and `Children` components automatically.When a parent's `LocalTransform` changes, the engine propagates the transform to all descendants via the `WorldTransform` component.@@ -142,3 +127,11 @@ addSystem(defineSystem(<Aside type="note">Commands are buffered and applied at the end of the current schedule stage, not immediately.</Aside>++## Scene Data Types++| Type | Fields |+|------|--------|+| `SceneData` | `version: string, name: string, entities: SceneEntityData[], textureMetadata?: Record<string, TextureMetadata>` |+| `SceneEntityData` | `id: number, name: string, parent: number \| null, children: number[], components: SceneComponentData[]` |+| `SceneComponentData` | `type: string, data: Record<string, unknown>` |diff --git a/docs/astro/src/content/docs/zh/changelog-v041.mdx b/docs/astro/src/content/docs/zh/changelog-v041.mdxnew file mode 100644index 000000000..41e17d251--- /dev/null+++ b/docs/astro/src/content/docs/zh/changelog-v041.mdx@@ -0,0 +1,69 @@+---+title: v0.4.1+description: ESEngine v0.4.1 更新日志+---++import { Aside } from '@astrojs/starlight/components';++## 多相机渲染++- Camera 组件新增视口字段(`viewportX`、`viewportY`、`viewportW`、`viewportH`)和 `clearFlags`+- 逐相机渲染管线,支持视口/裁剪用于分屏和小地图场景+- 基于优先级的相机渲染排序+- 编辑器场景视图新增逐相机颜色编码、相机图标、优先级标签和视口预览叠加++## BitmapText 与 BMFont++- 新增 `BitmapText` 组件,GPU 渲染位图字体文本,支持颜色、字号、对齐、间距和层级排序+- BMFont 解析器(`.fnt` 文本格式)和 LabelAtlas 创建,通过批处理渲染器实现+- 编辑器支持:字体加载、检查器 UI、缩略图预览、点击导航和 Tab 键在 BitmapFont 字形列表中导航++## UIMask++- 新增 `UIMask` 裁剪矩形组件,用于矩形 UI 裁剪+- 裁剪矩形计算支持正确的层级传播++## Spine 运行时可选++- Spine 运行时现在是可选的 — 没有 Spine 资源时默认为 `none`+- 减小不使用 Spine 动画的项目构建体积++## Name 组件++- 新增 `Name` 组件,从场景加载的实体自动赋值+- 新增 `findEntityByName()` 工具函数,按名称查找实体++## 编辑器改进++- 支持文件重命名,自动处理 `.meta` 文件+- 重复文件名和非法字符校验+- 所有文件操作的错误 toast 通知+- 改进实体复制命名,从 `_copy` 改为 `(N)` 模式++## 性能优化++- `entityCount()` 使用 O(1) 计数器缓存,替代 O(n) 扫描+- Camera/Canvas 线性扫描替换为 C++ ECS 视图查询,消除每帧约 4000 次 WASM 桥调用+- 复用 `ext_vertex_storage_` 缓冲区,避免每帧 clear+realloc+- `Registry::sort()` 中的 O(n²) 选择排序替换为 `std::sort`+- SpineRenderer:预分配 VAO/VBO/EBO,动态容量复用+- BatchRenderer:仅绑定活跃纹理槽而非全部 8 个+- 九宫格:将纹理槽查找提出循环外+- TransformSystem:双次迭代合并为单次+- SystemRunner:按系统缓存参数数组,避免每帧分配++## 文档++- 新增 Commands API 参考,包含完整的 `EntityCommands` 构建器 API+- 新增 RenderTexture 离屏渲染指南+- 渲染指南新增渲染统计和渲染阶段+- 新增 ECS 交互指南 — 用户意图到系统参数的映射表+- 新增 BitmapText、UIMask、Name、LabelAtlas 组件文档+- 重写场景示例,使用正确的系统模式(`Query`、`Commands`)++## Bug 修复++- 修复 Registry 释放时 use-after-free,新增 `disconnectCpp`+- 修复选择实体时不必要的场景重新加载+- 修复缺失模块时的 WASM 错误处理+- 修复 SpineExtension 内存泄漏,使用静态局部实例diff --git a/docs/astro/src/content/docs/zh/core-concepts/ecs.mdx b/docs/astro/src/content/docs/zh/core-concepts/ecs.mdxindex c559f504b..fcf9e0767 100644--- a/docs/astro/src/content/docs/zh/core-concepts/ecs.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/ecs.mdx@@ -133,6 +133,24 @@ addSystem(defineSystem(4. **更新循环** — 系统每帧查询和处理场景中的实体5. **渲染** — C++ 后端自动渲染所有拥有 `Sprite` 和 `Camera` 组件的实体+## 如何与 ECS 交互++`World` 存储所有实体和组件。在脚本中,通过系统参数与之交互:++| 你想做什么 | 系统参数 |+|-----------|---------|+| 遍历具有特定组件的实体 | `Query(ComponentA, ComponentB)` |+| 读取组件数据 | `Query(Component)` — 数据随迭代获取 |+| 修改组件数据 | `Query(Mut(Component))` — 用 `Mut` 包裹 |+| 创建新实体 | `Commands()` → `cmds.spawn()` |+| 销毁实体 | `Commands()` → `cmds.despawn(entity)` |+| 运行时添加组件 | `Commands()` → `cmds.entity(e).insert(Component, data)` |+| 运行时移除组件 | `Commands()` → `cmds.entity(e).remove(Component)` |+| 读取资源 | `Res(ResourceType)` |+| 修改资源 | `ResMut(ResourceType)` |++详见[系统](/microes/zh/core-concepts/systems/)和[查询](/microes/zh/core-concepts/queries/)。+## 下一步- [组件](/microes/zh/core-concepts/components/) — 内置和自定义组件diff --git a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh/core-concepts/systems.mdxindex 69d8069e1..b7aafd9c1 100644--- a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx@@ -64,20 +64,54 @@ addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);### Commands-在运行时创建和销毁实体:+在运行时创建、修改和销毁实体:```typescript-import { Commands } from 'esengine';+import { Commands, Sprite, LocalTransform } from 'esengine';defineSystem([Commands()], (cmds) => {- cmds.spawn()- .insert(Sprite, { size: { x: 50, y: 50 } })- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } });-- cmds.despawn(entity);+ // 创建新实体并添加组件(可链式调用)+ const bullet = cmds.spawn()+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, { size: { x: 8, y: 8 } })+ .id();++ // 修改已有实体+ cmds.entity(bullet)+ .insert(Velocity, { linear: { x: 100, y: 0 } })+ .remove(Sprite);++ // 销毁实体+ cmds.despawn(bullet);++ // 插入资源+ cmds.insertResource(Score, { value: 0 });});```+#### Commands API++| 方法 | 返回值 | 说明 |+|------|--------|------|+| `cmds.spawn()` | `EntityCommands` | 创建新实体,返回构建器 |+| `cmds.entity(entity)` | `EntityCommands` | 获取已有实体的构建器 |+| `cmds.despawn(entity)` | `Commands` | 将实体加入销毁队列 |+| `cmds.insertResource(res, value)` | `Commands` | 插入或覆盖资源 |++#### EntityCommands API++`spawn()` 和 `entity()` 返回 `EntityCommands` 构建器,所有方法可链式调用:++| 方法 | 返回值 | 说明 |+|------|--------|------|+| `.insert(component, data?)` | `this` | 添加或更新组件 |+| `.remove(component)` | `this` | 移除组件 |+| `.id()` | `Entity` | 获取实体 ID |++<Aside type="note">+ Commands 是缓冲的,在当前调度阶段结束时才应用。例外是 `.id()` — 调用它会立即创建实体,使 ID 可以马上使用。+</Aside>+### Query遍历具有特定组件的实体:diff --git a/docs/astro/src/content/docs/zh/guides/render-texture.mdx b/docs/astro/src/content/docs/zh/guides/render-texture.mdxnew file mode 100644index 000000000..ca53934ca--- /dev/null+++ b/docs/astro/src/content/docs/zh/guides/render-texture.mdx@@ -0,0 +1,115 @@+---+title: 渲染纹理+description: 在 ESEngine 中使用 RenderTexture 进行离屏渲染+---++import { Aside } from '@astrojs/starlight/components';++**RenderTexture** 可以将场景(或部分场景)渲染到离屏纹理而非屏幕上。适用于小地图、镜像、传送门、后处理输入,以及任何需要捕获渲染输出的效果。++## 创建 RenderTexture++```typescript+import { RenderTexture, type RenderTextureHandle } from 'esengine';++const rt: RenderTextureHandle = RenderTexture.create({+ width: 512,+ height: 512,+ depth: true,+ filter: 'linear',+});+```++### RenderTextureOptions++| 字段 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `width` | `number` | — | 纹理宽度(像素) |+| `height` | `number` | — | 纹理高度(像素) |+| `depth` | `boolean` | `false` | 是否附加深度缓冲 |+| `filter` | `'nearest' \| 'linear'` | `'nearest'` | 纹理过滤模式 |++## 渲染到纹理++在 `begin()` 和 `end()` 之间进行绘制调用。期间渲染的所有内容都会输出到纹理而非屏幕:++```typescript+import { RenderTexture, Draw } from 'esengine';++RenderTexture.begin(rt, viewProjectionMatrix);++Draw.rect(0, 0, 100, 100, { r: 1, g: 0, b: 0, a: 1 });++RenderTexture.end();+```++`viewProjection` 参数是一个 `Float32Array`,包含 4x4 视图-投影矩阵,定义此离屏渲染通道的相机。++<Aside type="note">+ `begin()` 设置渲染目标和视口。`end()` 恢复之前的渲染目标。`begin()` 之后必须调用 `end()`。+</Aside>++## 使用渲染结果++渲染完成后,`rt.textureId` 包含 GPU 纹理 ID。可以在任何需要纹理的地方使用:++```typescript+import { Draw, Sprite } from 'esengine';++Draw.texture(rt.textureId, 0, 0, rt.width, rt.height);+```++也可以将其赋值给 Sprite 的 texture 用于基于实体的渲染。++## 深度纹理++如果创建 RenderTexture 时启用了 `depth: true`,可以获取深度纹理用于阴影映射等效果:++```typescript+const depthTextureId = RenderTexture.getDepthTexture(rt);+```++## 生命周期++### 调整大小++当目标分辨率变化时(如窗口调整),调整 RenderTexture 大小:++```typescript+const resized = RenderTexture.resize(rt, newWidth, newHeight);+```++`resize()` 返回新的 `RenderTextureHandle`,后续应使用返回的句柄。++### 释放资源++不再需要 RenderTexture 时释放 GPU 资源:++```typescript+RenderTexture.release(rt);+```++## API 参考++| 方法 | 返回值 | 说明 |+|------|--------|------|+| `RenderTexture.create(options)` | `RenderTextureHandle` | 创建新的渲染纹理 |+| `RenderTexture.begin(rt, viewProjection)` | `void` | 开始渲染到纹理 |+| `RenderTexture.end()` | `void` | 结束渲染到纹理 |+| `RenderTexture.getDepthTexture(rt)` | `number` | 获取深度纹理 ID |+| `RenderTexture.resize(rt, width, height)` | `RenderTextureHandle` | 调整渲染纹理大小 |+| `RenderTexture.release(rt)` | `void` | 释放 GPU 资源 |++### RenderTextureHandle++| 字段 | 类型 | 说明 |+|------|------|------|+| `textureId` | `number` | 颜色附件的 GPU 纹理 ID |+| `width` | `number` | 当前宽度(像素) |+| `height` | `number` | 当前高度(像素) |++## 下一步++- [自定义绘制](/microes/zh/guides/custom-draw/) — 即时模式绘制 API+- [后处理效果](/microes/zh/guides/post-processing/) — 全屏效果+- [材质与着色器](/microes/zh/guides/materials/) — 自定义着色器diff --git a/docs/astro/src/content/docs/zh/guides/rendering.mdx b/docs/astro/src/content/docs/zh/guides/rendering.mdxindex 6c6fbb158..9d4c64801 100644--- a/docs/astro/src/content/docs/zh/guides/rendering.mdx+++ b/docs/astro/src/content/docs/zh/guides/rendering.mdx@@ -133,6 +133,47 @@ transform.scale = { x: -1, y: 1, z: 1 }; // 水平翻转C++ 后端负责所有 WebGL 渲染。你只需设置组件数据,引擎每帧自动绘制一切。</Aside>+## 渲染统计++使用 `Renderer.getStats()` 获取每帧渲染统计数据,可用于性能分析和调试面板:++```typescript+import { Renderer, type RenderStats } from 'esengine';++const stats: RenderStats = Renderer.getStats();+console.log(`Draw calls: ${stats.drawCalls}, Triangles: ${stats.triangles}`);+```++| 字段 | 类型 | 说明 |+|------|------|------|+| `drawCalls` | `number` | 本帧 WebGL draw call 总数 |+| `triangles` | `number` | 渲染的三角形总数 |+| `sprites` | `number` | 绘制的精灵数 |+| `text` | `number` | 绘制的文本元素数 |+| `spine` | `number` | 绘制的 Spine 骨骼数 |+| `meshes` | `number` | 绘制的自定义网格数 |+| `culled` | `number` | 被裁剪的对象数(未绘制) |++## 渲染阶段++渲染管线分为多个阶段,按顺序执行。每个阶段绘制一类对象:++| 阶段 | 值 | 说明 |+|------|-----|------|+| `Background` | 0 | 背景层(天空盒、背景) |+| `Opaque` | 1 | 不透明几何体(无透明度) |+| `Transparent` | 2 | 透明/Alpha 混合对象 |+| `Overlay` | 3 | UI 和覆盖元素(绘制在最上层) |++使用[自定义绘制](/microes/zh/guides/custom-draw/)时,指定 `RenderStage` 来控制绘制命令相对于内置渲染的执行时机:++```typescript+import { Draw, RenderStage } from 'esengine';++Draw.bindStage(RenderStage.Overlay);+Draw.rect(0, 0, 100, 50, { r: 0, g: 0, b: 0, a: 0.5 });+```+## 下一步- [Canvas 与分辨率](/microes/zh/guides/canvas/) — 屏幕适配与缩放模式@@ -141,4 +182,5 @@ transform.scale = { x: -1, y: 1, z: 1 }; // 水平翻转- [位图文本](/microes/zh/guides/bitmap-text/) — GPU 渲染的位图字体文本- [自定义绘制](/microes/zh/guides/custom-draw/) — 即时模式绘图,用于调试可视化和动态图形- [后处理效果](/microes/zh/guides/post-processing/) — 全屏效果(模糊、暗角、灰度)+- [渲染纹理](/microes/zh/guides/render-texture/) — 离屏渲染,用于小地图、镜像和特效- [几何体与网格](/microes/zh/guides/geometry/) — 自定义网格创建diff --git a/docs/astro/src/content/docs/zh/guides/scenes.mdx b/docs/astro/src/content/docs/zh/guides/scenes.mdxindex abff5337c..bf3b758d6 100644--- a/docs/astro/src/content/docs/zh/guides/scenes.mdx+++ b/docs/astro/src/content/docs/zh/guides/scenes.mdx@@ -38,47 +38,38 @@ import { Aside } from '@astrojs/starlight/components';在编辑器中,场景会自动加载 — 你只需编写定义组件和系统的脚本。-构建项目后,运行时加载器负责场景加载:--```typescript-import { loadSceneWithAssets, type SceneData } from 'esengine';--const sceneData: SceneData = await fetch('/scene.json').then(r => r.json());-const entityMap = await loadSceneWithAssets(world, sceneData, { assetServer });-```--<Aside type="tip">- `loadSceneWithAssets` 会自动加载场景中引用的纹理、材质和 Spine 资源。如果不需要资源加载,可以使用 `loadSceneData`。-</Aside>+构建项目后,引擎会自动加载场景、解析所有引用的资源(纹理、材质、Spine),并在没有相机时创建默认相机。你不需要手动处理场景加载。## 查找实体### 按名字查找-从场景加载的每个实体都会自动获得内置的 `Name` 组件,包含在编辑器中指定的名字。使用 `findEntityByName` 查找实体:+从场景加载的每个实体都会自动获得内置的 `Name` 组件,包含在编辑器中指定的名字。通过查询 `Name` 来查找实体:```typescript-import { findEntityByName } from 'esengine';+import { defineSystem, addStartupSystem, Query, Name, LocalTransform } from 'esengine';-const player = findEntityByName(world, 'Player');-if (player !== null) {- const transform = world.get(player, LocalTransform);-}+addStartupSystem(defineSystem(+ [Query(Name, LocalTransform)],+ (query) => {+ for (const [entity, name, transform] of query) {+ if (name.value === 'Player') {+ // 找到了玩家实体+ }+ }+ }+));```### 按组件或标签查找-使用 `getEntitiesWithComponents` 或 `Query` 按组件查找实体:+使用 `Query` 按组件查找实体:```typescript-import { defineTag, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, defineTag, Query, Mut, LocalTransform } from 'esengine';const Player = defineTag('Player');-// 直接查找-const players = world.getEntitiesWithComponents([Player]);--// 在系统中addSystem(defineSystem([Query(Mut(LocalTransform), Player)],(query) => {@@ -91,30 +82,24 @@ addSystem(defineSystem(### 遍历层级-使用 `Parent` 和 `Children` 组件遍历实体树:+使用 `Children` 组件遍历实体树:```typescript-import { Parent, Children } from 'esengine';+import { defineSystem, addSystem, Query, Children, LocalTransform } from 'esengine';-const children = world.get(entity, Children);-if (children) {- for (const child of children.entities) {- const childTransform = world.get(child, LocalTransform);+addSystem(defineSystem(+ [Query(Children, LocalTransform)],+ (query) => {+ for (const [entity, children, transform] of query) {+ // children.entities 包含子实体 ID+ }}-}+));```## 实体层级-场景实体可以通过父子关系形成树状结构。引擎会自动管理 `Parent` 和 `Children` 组件。--```typescript-// 设置父实体(给子实体添加 Parent 组件,更新父实体的 Children)-world.setParent(child, parent);--// 移除父实体(子实体变为根实体)-world.removeParent(child);-```+场景实体可以通过父子关系形成树状结构。在编辑器中设置父子关系 — 引擎会自动管理 `Parent` 和 `Children` 组件。当父实体的 `LocalTransform` 变化时,引擎会通过 `WorldTransform` 组件将变换传播到所有后代。@@ -142,3 +127,11 @@ addSystem(defineSystem(<Aside type="note">Commands 是缓冲的,在当前调度阶段结束时应用,不会立即生效。</Aside>++## 场景数据类型++| 类型 | 字段 |+|------|------|+| `SceneData` | `version: string, name: string, entities: SceneEntityData[], textureMetadata?: Record<string, TextureMetadata>` |+| `SceneEntityData` | `id: number, name: string, parent: number \| null, children: number[], components: SceneComponentData[]` |+| `SceneComponentData` | `type: string, data: Record<string, unknown>` |