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(guides): cover the undocumented public surface (en + zh-cn)

yhh84a56b33e0a1
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 617fda4ed..02476fcf5 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -93,6 +93,7 @@ export default defineConfig({
{ label: 'Post-processing', translations: { 'zh-CN': '后处理' }, slug: 'guides/postprocess' },
{ label: 'Materials & Shaders', translations: { 'zh-CN': '材质与着色器' }, slug: 'guides/material' },
{ label: '2D Lighting & Shadows', translations: { 'zh-CN': '2D 光照与阴影' }, slug: 'guides/lighting' },
+ { label: 'Custom Drawing', translations: { 'zh-CN': '自定义绘制' }, slug: 'guides/drawing' },
],
},
{
diff --git a/docs/astro/src/content/docs/core-concepts/components.mdx b/docs/astro/src/content/docs/core-concepts/components.mdx
index 2c2b930b4..d20453879 100644
--- a/docs/astro/src/content/docs/core-concepts/components.mdx
+++ b/docs/astro/src/content/docs/core-concepts/components.mdx
@@ -1,6 +1,6 @@
---
title: Components
-description: Declaring and using components with defineComponent.
+description: Declaring and using components — defineComponent, field types, tags, editor metadata, and the built-in component set.
---
A **component** is a small, plain data struct attached to an entity. Declare one
@@ -17,13 +17,71 @@ The defaults define both the shape (fields and types) and the initial values a
new instance gets. Components are pure data — no methods, no behavior. Behavior
lives in [systems](/docs/core-concepts/systems/).
-## Built-in components
+## Field types
+
+A field's type is inferred from its default. Numbers, booleans, and strings work
+as you'd expect, and structured shapes get matching editor controls:
+
+```typescript
+const Missile = defineComponent('Missile', {
+ speed: 400, // number
+ homing: true, // boolean
+ targetTag: '', // string
+ velocity: { x: 0, y: 0 }, // vector — edited as an X/Y pair
+ tint: { r: 1, g: 1, b: 1, a: 1 }, // {r,g,b,a} fields render a color picker
+});
+```
+
+## Tags — components with no data
+
+A **tag** is a zero-field marker used purely for filtering — `Player`, `Enemy`,
+`Frozen`. Declare it with `defineTag` and use it in queries with `.with()` /
+`.without()`:
+
+```typescript
+import { defineTag, defineSystem, Query, Mut, Transform } from 'esengine';
+
+const Player = defineTag('Player');
+const Frozen = defineTag('Frozen');
-The SDK ships engine components you query alongside your own, for example:
+defineSystem([Query(Mut(Transform)).with(Player).without(Frozen)], (q) => { /* … */ });
+```
+
+## Editor metadata
+
+A third argument controls how fields present in the editor's Details panel —
+ranges, sliders, units, enums, and asset pickers:
+
+```typescript
+const Turret = defineComponent('Turret', {
+ range: 300,
+ mode: 0,
+}, {
+ fields: {
+ range: { min: 0, max: 1000, slider: true, unit: 'px' },
+ mode: { enum: [{ label: 'Idle', value: 0 }, { label: 'Attack', value: 1 }] },
+ },
+});
+```
+
+Useful `fields` options: `min` / `max` / `step`, `slider`, `unit`, `enum`
+(dropdown storing the option's int), `flags` (bitmask multi-select), `tooltip`.
+Other component-level metadata: `assetFields` (marks a field as an asset
+reference, so Details renders a picker and the cook ships the dependency),
+`animatableFields` (which fields the [Sequencer](/docs/guides/timeline/) can
+key — defaults to all numeric fields), `transient` (never saved into the scene —
+for per-frame runtime state), and `replicatedFields` (synced by
+[networking](/docs/guides/networking/)'s state replication).
-- `Transform` — position, rotation, and scale.
-- `Sprite` — a textured quad.
-- `Camera` — a view into the world.
+## Built-in components
+
+The SDK ships ~30 engine components you query alongside your own — `Transform`,
+`Sprite`, `ShapeRenderer`, `Camera`, `Light2D`, `ParticleEmitter`,
+`SpineAnimation`, `TilemapLayer`, the UI set, the physics colliders, and more.
+Each is documented in its subsystem guide:
+[Sprites & Rendering](/docs/guides/sprites/), [Camera](/docs/guides/camera/),
+[2D Lighting](/docs/guides/lighting/), [Physics](/docs/guides/physics/),
+[Tilemaps](/docs/guides/tilemap/), [UI](/docs/guides/ui/).
## Reading and writing
@@ -36,6 +94,11 @@ Query(Mut(Transform), Speed)
// Transform is written; Speed is read-only
```
+Because writes are tracked, systems can also react to lifecycle:
+`Added(Comp)` / `Changed(Comp)` narrow a query to entities whose component just
+appeared / just changed — see [Systems](/docs/core-concepts/systems/) for the
+full query vocabulary.
+
<br />
Under the hood a component is a C++ struct annotated with `ES_COMPONENT` /
diff --git a/docs/astro/src/content/docs/core-concepts/ecs.mdx b/docs/astro/src/content/docs/core-concepts/ecs.mdx
index 20ef3f30b..156eb52bd 100644
--- a/docs/astro/src/content/docs/core-concepts/ecs.mdx
+++ b/docs/astro/src/content/docs/core-concepts/ecs.mdx
@@ -16,9 +16,9 @@ lives in systems that run over that data.
## Why data-oriented
-Components are stored in a single cache-friendly layer (a sparse set) so that a
-system iterating "all entities with a `Transform` and a `Speed`" walks
-contiguous memory. Storage lives in the C++/WebAssembly core, and the SDK reads
+Components are stored in cache-friendly pools — one densely packed sparse set
+per component type — so a system iterating "all entities with a `Transform` and
+a `Speed`" walks contiguous memory. Storage lives in the C++/WebAssembly core, and the SDK reads
it with zero copies through a generated, hash-checked memory layout — so the
TypeScript and C++ views of a component can never silently drift apart.
@@ -29,8 +29,11 @@ You compose a game from three SDK primitives:
- [`defineComponent`](/docs/core-concepts/components/) — declare a component type.
- [`defineSystem`](/docs/core-concepts/systems/) — declare a system and what it
queries.
-- `App` / plugins — assemble systems, resources, and subsystems (physics, spine,
- tilemap, UI, audio, scene) into a running game.
+- [`App` / plugins](/docs/core-concepts/plugins-resources/) — assemble systems,
+ resources, and subsystems ([physics](/docs/guides/physics/),
+ [spine](/docs/guides/spine/), [tilemap](/docs/guides/tilemap/),
+ [UI](/docs/guides/ui/), [audio](/docs/guides/audio/),
+ [scene](/docs/guides/scene/)) into a running game.
```typescript
import { App } from 'esengine';
diff --git a/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx b/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx
index e39ea5950..28a0f9b3e 100644
--- a/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx
+++ b/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx
@@ -22,23 +22,42 @@ defineSystem([Res(Audio)], (audio) => {
Every subsystem's imperative API is reached the same way:
-| Subsystem | Resource | Import from |
+| Subsystem | Resource | Guide |
|---|---|---|
-| Input | `Res(Input)` | `esengine` |
-| Audio | `Res(Audio)` | `esengine` |
-| Assets | `Res(Assets)` | `esengine` |
-| Tilemaps | `Res(Tilemaps)` | `esengine` |
-| Particles | `Res(Particle)` | `esengine` |
-| Post-processing | `Res(PostProcess)` | `esengine` |
-| Scenes | `Res(SceneManager)` | `esengine` |
-| Tweens | `Res(Tween)` | `esengine` |
-| Animator | `Res(AnimatorController)` | `esengine` |
-| Physics | `Res(PhysicsAPI)` | `esengine/physics` |
-| Spine | `Res(Spine)` | `esengine/spine` |
+| Input | `Res(Input)` | [Input](/docs/guides/input/) |
+| Audio | `Res(Audio)` | [Audio](/docs/guides/audio/) |
+| Assets | `Res(Assets)` | [Assets](/docs/guides/assets/) |
+| Tilemaps | `Res(Tilemaps)` | [Tilemaps](/docs/guides/tilemap/) |
+| Particles | `Res(Particle)` | [Particles](/docs/guides/particle/) |
+| Post-processing | `Res(PostProcess)` | [Post-processing](/docs/guides/postprocess/) |
+| Scenes | `Res(SceneManager)` | [Scenes](/docs/guides/scene/) |
+| Tweens | `Res(Tween)` | [Animation](/docs/guides/animation/) |
+| Frame animation | `Res(SpriteAnimation)` | [Animation](/docs/guides/animation/) |
+| Animator | `Res(AnimatorController)` | [Animation](/docs/guides/animation/) |
+| Timers | `Res(TimerRes)` | [Scripting](/docs/guides/scripting/) |
+| Timeline | `Res(Timeline)` | [Timeline](/docs/guides/timeline/) |
+| Prefabs | `Res(Prefabs)` | [Prefabs](/docs/guides/prefab/) |
+| Navigation / AI | `Res(Nav)` | [Gameplay AI](/docs/guides/ai/) |
+| Localization | `Res(Localization)` | [Localization](/docs/guides/localization/) |
+| Camera view | `Res(CameraView)` | [Camera](/docs/guides/camera/) |
+| UI events | `Res(UIEvents)` | [UI](/docs/guides/ui/) |
+| Physics | `Res(PhysicsAPI)` — from `esengine/physics` | [Physics](/docs/guides/physics/) |
+| Spine | `Res(Spine)` — from `esengine/spine` | [Spine](/docs/guides/spine/) |
Physics and Spine are **optional side-modules** loaded on demand, so their APIs
live on subpaths to keep the base bundle small; everything else is in the main
-`esengine` package.
+`esengine` package. All the base subsystems above ship in the standard app — no
+plugin wiring needed.
+
+Some subsystems also publish **event resources** on the same pattern — a
+resource whose contents are this frame's events, read the same frame:
+`Res(PhysicsEvents)` (contacts), `Res(SpineEvents)` (animation events),
+`Res(UIEvents)` (clicks and input from widgets).
+
+<br />
+
+`Res(X)` gives read access; use `ResMut(X)` when the system **replaces or
+mutates the resource's state** — same contract as `Mut` on components.
## Components vs. resources
diff --git a/docs/astro/src/content/docs/getting-started/installation.mdx b/docs/astro/src/content/docs/getting-started/installation.mdx
index 5c1399c65..ac1c99432 100644
--- a/docs/astro/src/content/docs/getting-started/installation.mdx
+++ b/docs/astro/src/content/docs/getting-started/installation.mdx
@@ -12,10 +12,12 @@ import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
1. Download the latest editor from the
[releases page](https://github.com/esengine/estella/releases).
- 2. Install and open it, then click **New Project**.
+ 2. Install and open it, then click **New project**.
- 3. Enter a project name and location, and click **Create**. The editor opens
- a default scene with a Camera entity.
+ 3. Pick a template — the **Blank** starter, or one of the bundled
+ **Examples** — enter a project name and location, and click
+ **Create project**. With Blank, the editor opens a default scene with a
+ Camera entity.
</Steps>
@@ -34,12 +36,13 @@ import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
<Steps>
- 1. Clone and install:
+ 1. Clone (with submodules) and install:
```bash
- git clone https://github.com/esengine/estella.git
+ git clone --recursive https://github.com/esengine/estella.git
cd estella
pnpm install
+ pnpm emsdk:setup # one-time: installs Emscripten 5.0.0 into tools/emsdk
```
2. Build the engine, SDK, and sync to the editor:
diff --git a/docs/astro/src/content/docs/getting-started/quick-start.mdx b/docs/astro/src/content/docs/getting-started/quick-start.mdx
index 542198a17..98809a00e 100644
--- a/docs/astro/src/content/docs/getting-started/quick-start.mdx
+++ b/docs/astro/src/content/docs/getting-started/quick-start.mdx
@@ -10,10 +10,10 @@ with a system written in TypeScript.
<Steps>
-1. **Create a project.** In the editor, click **New Project**, pick the
- **Blank** starter template, name it, and click **Create**. You get a default
- scene with a Camera entity. (The **Examples** templates are full sample
- projects if you'd rather explore a finished game.)
+1. **Create a project.** In the editor, click **New project**, pick the
+ **Blank** starter template, name it, and click **Create project**. You get a
+ default scene with a Camera entity. (The **Examples** templates are full
+ sample projects if you'd rather explore a finished game.)
2. **Add an entity.** In the scene hierarchy, add an entity and give it a
`Sprite` and a `Transform` component in the inspector.
diff --git a/docs/astro/src/content/docs/guides/drawing.mdx b/docs/astro/src/content/docs/guides/drawing.mdx
new file mode 100644
index 000000000..3ff6e6852
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/drawing.mdx
@@ -0,0 +1,116 @@
+---
+title: Custom Drawing
+description: Draw beyond components — immediate-mode primitives with Draw, vector paths with Graphics, custom triangle meshes with Mesh2D, and offscreen render textures.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Most visuals are components — [sprites](/docs/guides/sprites/), tilemaps,
+particles. When you need something they can't express — debug overlays, procedural
+shapes, custom geometry — the engine exposes its drawing layer directly.
+
+## Draw callbacks
+
+Register a callback and it runs inside the render pass every frame, with the
+camera's view-projection already active — no setup, just draw:
+
+```typescript
+import { registerDrawCallback, Draw } from 'esengine';
+
+registerDrawCallback('debug-overlay', (elapsed) => {
+ Draw.line({ x: 0, y: 0 }, { x: 100, y: 50 }, { r: 1, g: 0, b: 0, a: 1 }, 2);
+ Draw.circleOutline({ x: 0, y: 0 }, aggroRadius, { r: 1, g: 1, b: 0, a: 0.5 });
+});
+```
+
+Callbacks draw **on top of** the scene; `registerPreSceneDrawCallback` draws
+**under** it (its callback receives `{ width, height, elapsed }`). Remove one
+with `unregisterDrawCallback(id)`. All coordinates are world-space.
+
+<Aside type="tip">
+ A callback registered while a scene is active can be scoped to it —
+ `sceneContext.registerDrawCallback(id, fn)` on the context returned by
+ `loadAdditive` — so it's cleaned up with the scene and only draws while the
+ scene is active.
+</Aside>
+
+## The `Draw` API
+
+`Draw` is an immediate-mode singleton — commands are batched automatically and
+cleared every frame, so call it each frame you want the shape visible:
+
+| Method | Draws |
+|---|---|
+| `line(from, to, color, thickness?)` | A line segment (thickness in px, default `1`). |
+| `rect(pos, size, color, filled?)` / `rectOutline(pos, size, color, thickness?)` | A rectangle — `pos` is the **center**. |
+| `circle(center, radius, color, filled?, segments?)` / `circleOutline(…)` | A circle (default `32` segments). |
+| `texture(pos, size, textureHandle, tint?)` | A textured quad. |
+| `textureRotated(pos, size, rotation, textureHandle, tint?)` | Same, rotated (radians). |
+| `setLayer(layer)` / `setDepth(depth)` | Sorting of subsequent commands. |
+| `setBlendMode(mode)` / `setDepthTest(on)` | Blend / depth state for subsequent commands. |
+| `getDrawCallCount()` / `getPrimitiveCount()` | Frame stats. |
+
+## Vector paths: `Graphics`
+
+For shapes built from paths — polylines, béziers, arcs, rounded rects —
+`Graphics` records a path and replays it through `Draw` when you `flush()`:
+
+```typescript
+import { Graphics, registerDrawCallback } from 'esengine';
+
+const g = new Graphics();
+g.lineStyle(2, { r: 1, g: 1, b: 1, a: 1 });
+g.beginFill({ r: 0, g: 0.5, b: 1, a: 1 });
+g.drawRoundRect(-50, -25, 100, 50, 8);
+g.endFill();
+g.moveTo(0, 0);
+g.curveTo(50, 80, 100, 0); // quadratic bézier
+
+registerDrawCallback('hud-shape', () => g.flush());
+```
+
+Path methods: `moveTo` / `lineTo`, `curveTo` (quadratic) / `cubicCurveTo`,
+`arc`, `drawRect` / `drawRoundRect` / `drawCircle` / `drawEllipse`, `clear()`.
+`lineStyle(thickness, color)` sets the stroke; `beginFill(color)` / `endFill()`
+fill **rects and circles** (path outlines stay strokes). The path is retained —
+build it once, `flush()` it every frame.
+
+## Custom meshes: `Mesh2D`
+
+`Mesh2D` is a component that renders an arbitrary indexed triangle list —
+procedural terrain slices, radial health arcs, water surfaces. Author the
+geometry on the component (positions as x,y pairs; optional per-vertex UVs and
+colors):
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Mesh2D, {
+ geometry: {
+ positions: [0, 0, 100, 0, 50, 80],
+ colors: [1,0,0,1, 0,1,0,1, 0,0,1,1],
+ indices: [0, 1, 2],
+ },
+ });
+```
+
+The mesh shares the standard renderable surface: `texture`, `color`, `layer`,
+`lit`, `parallax`, and `material`. Geometry set in a scene (or at spawn) uploads
+automatically; to **mutate it at runtime**, go through the `Meshes2D` resource —
+`setGeometry(entity, geometry)` re-uploads (indices are validated engine-side),
+`getGeometry` / `clearGeometry` round it out. Direct writes to the `geometry`
+field alone are not change-detected.
+
+## Offscreen targets: `RenderTexture`
+
+For advanced setups — minimaps, portraits, mirrors — `RenderTexture.create({
+width, height })` allocates an offscreen target; wrap draw commands in
+`RenderTexture.begin(rt, viewProjection)` / `end()` to render into it, and
+`release(rt)` when done. This is a low-level surface (you supply the
+view-projection matrix yourself) — see the TypeScript API reference for details.
+
+## See also
+
+- [Sprites & Rendering](/docs/guides/sprites/) — the component path for images and shapes.
+- [Materials & Shaders](/docs/guides/material/) — custom shaders for any renderable.
+- [Camera](/docs/guides/camera/) — where the view-projection your callbacks draw under comes from.
diff --git a/docs/astro/src/content/docs/guides/input.mdx b/docs/astro/src/content/docs/guides/input.mdx
index dbff73d2c..6155845a6 100644
--- a/docs/astro/src/content/docs/guides/input.mdx
+++ b/docs/astro/src/content/docs/guides/input.mdx
@@ -1,6 +1,6 @@
---
title: Input
-description: The complete input reference — keyboard, mouse, touch, and gamepad through the Input resource, plus world-space cursor.
+description: The complete input reference — keyboard, mouse, touch, and gamepad through the Input resource, named rebindable actions with InputMap, touch gestures, and the world-space cursor.
---
import { Aside } from '@astrojs/starlight/components';
@@ -79,6 +79,100 @@ const jump = defineSystem([Query(Mut(CharacterController)), Res(Input)], (player
correctly from any schedule. Step-accurate edge delivery covers keyboard and mouse
buttons; gamepad edges are frame-granular.</Aside>
+## Input actions (`InputMap`)
+
+Hard-coded key checks scatter device knowledge through gameplay code. An **input
+map** names each action once — with as many keyboard / mouse / gamepad bindings as
+you like — and gameplay queries the action by name:
+
+```typescript
+import {
+ defineInputMap, Button, Axis2D,
+ Key, Keys2D, Stick, GpButton, GamepadButton,
+} from 'esengine';
+
+export const Controls = defineInputMap({
+ Move: Axis2D(Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'), Stick('left')),
+ Jump: Button(Key('Space'), GpButton(GamepadButton.South)),
+});
+```
+
+`defineInputMap` registers its own per-frame evaluation (after input is polled,
+before `Update`), so the map is live immediately — import it into any system and
+query:
+
+```typescript
+const dir = Controls.axis2d('Move'); // { x, y }, length ≤ 1
+if (Controls.pressed('Jump')) { /* this-frame edge */ }
+```
+
+| Query | Returns |
+|---|---|
+| `down(name)` | Held — the action's magnitude is ≥ 0.5. |
+| `pressed(name)` / `released(name)` | This-frame edges. |
+| `value(name)` | Button `0..1` · axis `-1..1` · axis2d magnitude `0..1`. |
+| `axis2d(name)` | `{ x, y }` direction (normalized when longer than 1). |
+
+An action is `Button(…)`, `Axis1D(…)`, or `Axis2D(…)`; each takes any number of
+bindings, and multiple bindings sum (then clamp), so keyboard and gamepad coexist:
+
+| Binding | Feeds | Meaning |
+|---|---|---|
+| `Key(code)` | button / axis | One keyboard key. |
+| `MouseButton(b)` | button / axis | A mouse button. |
+| `GpButton(btn, pad?)` | button / axis | A gamepad button (analog value for triggers). |
+| `GpAxis(axis, pad?, scale?)` | axis | A raw gamepad axis. |
+| `Keys1D(neg, pos)` | axis | Two keys → a signed 1D axis. |
+| `Keys2D(up, down, left, right)` | axis2d | Four keys → a 2D direction. |
+| `Stick('left' \| 'right', pad?)` | axis2d | A gamepad stick (up = +y, matching `Keys2D`). |
+
+### Rebinding & persistence
+
+Bindings are plain serializable data, so a controls screen stays small:
+
+```typescript
+// "Press any input…" — captures the next key / gamepad button (mouse is opt-in)
+await Controls.rebind('Jump'); // replace; { append: true } adds instead
+Controls.save('controls'); // persist to platform Storage
+// on boot:
+Controls.load('controls'); // re-apply saved bindings (if any)
+```
+
+`getBindings` / `setBindings` inspect and edit bindings programmatically, and
+`cancelListen()` aborts a pending capture (it resolves with `null`).
+
+### Data-driven maps (`.inputmap`)
+
+A whole map also serializes as an asset: create a **New Input Map** in the
+editor's Content Browser, then build the live map with `loadInputMapAsset(json)`
+instead of `defineInputMap`. `toAsset()` produces the same format from code.
+
+## Touch gestures
+
+`GestureDetector` turns raw touches into tap / long-press / swipe / pinch
+callbacks. Construct it over the `Input` resource and drive it from a system:
+
+```typescript
+import { defineSystem, Res, Input, Time, GestureDetector } from 'esengine';
+
+let gestures: GestureDetector | null = null;
+
+const gestureSystem = defineSystem([Res(Input), Res(Time)], (input, time) => {
+ if (!gestures) {
+ gestures = new GestureDetector(input);
+ gestures.onTap = (x, y) => { /* screen px */ };
+ gestures.onLongPress = (x, y) => { /* held ~0.5 s without moving */ };
+ gestures.onSwipe = (dir, speed) => { /* 'left' | 'right' | 'up' | 'down' */ };
+ gestures.onPinch = (scale, cx, cy) => { /* two-finger zoom factor per frame */ };
+ }
+ gestures.update(time.delta);
+});
+```
+
+A tap is a touch under 0.3 s with less than 10 px of travel; a swipe needs ≥ 50 px
+at ≥ 200 px/s; pinch reports the frame-to-frame scale of a two-finger spread with
+its center point.
+
## Reference
| Group | Methods |
diff --git a/docs/astro/src/content/docs/guides/scene.mdx b/docs/astro/src/content/docs/guides/scene.mdx
index 27b0c83c3..46d7571f1 100644
--- a/docs/astro/src/content/docs/guides/scene.mdx
+++ b/docs/astro/src/content/docs/guides/scene.mdx
@@ -1,6 +1,6 @@
---
title: Scenes
-description: The complete guide to scenes — switching, additive loading, querying state, and how systems are gated per scene, via Res(SceneManager).
+description: The complete guide to scenes — switching, additive loading, streaming open-world cells, querying state, and how systems are gated per scene, via Res(SceneManager).
---
import { Aside } from '@astrojs/starlight/components';
@@ -34,6 +34,29 @@ await scenes.loadAdditive('pause-menu', (loaded, total) => { /* progress */ });
await scenes.unload('pause-menu');
```
+## Scene streaming (open worlds)
+
+For worlds too big to load at once, the `SceneStreaming` resource loads and
+unloads **cells** — additive scenes placed in world space — around a focus point:
+
+```typescript
+import { defineSystem, Res, SceneStreaming } from 'esengine';
+
+const setupStreaming = defineSystem([Res(SceneStreaming)], (streaming) => {
+ streaming.configure({ loadRadius: 1200, unloadRadius: 1600 });
+ streaming.register({ scene: 'cells/forest', x: 0, y: 0, radius: 800 });
+ streaming.register({ scene: 'cells/village', x: 1500, y: 0, radius: 800 });
+ streaming.setFocusEntity(player); // or setFocus(x, y) each frame
+});
+```
+
+Each frame, cells within `loadRadius` of the focus load additively and cells
+beyond `unloadRadius` unload — the gap between the radii is hysteresis, so a
+player standing at a border doesn't thrash loads. `policy: 'sleep'` **sleeps**
+cells instead of unloading: entities stay in memory, disabled and hidden, so
+re-entering is instant at the cost of memory. Cell scenes are ordinary project
+scenes referenced by name (see below).
+
## Scenes in a build
Every scene in the project's scenes folder ships with an export and registers as a
@@ -56,8 +79,11 @@ ship the startup scene only. See
| `unload(name, options?)` | Unload a scene (async; optional transition). |
| `getActive()` | The active scene name, or `null`. |
| `getActiveScenes()` | All active (additive) scene names. |
+| `pause(name)` / `resume(name)` | Suspend / resume a loaded scene's updates. |
+| `sleep(name)` / `wake(name)` | Suspend **and hide** a scene's entities (kept in memory; waking restores them instantly). |
| `isLoaded(name)` | Whether a scene is loaded. |
| `isActive(name)` | Whether a scene is active. |
+| `isPaused(name)` / `isSleeping(name)` | The suspension states above. |
| `isTransitioning()` | `true` during a `switchTo` transition. |
## Best practices
diff --git a/docs/astro/src/content/docs/guides/scripting.mdx b/docs/astro/src/content/docs/guides/scripting.mdx
index f510e5abb..39ed74d84 100644
--- a/docs/astro/src/content/docs/guides/scripting.mdx
+++ b/docs/astro/src/content/docs/guides/scripting.mdx
@@ -162,6 +162,35 @@ export const Thruster = defineBehavior('Thruster', {
Available phases include `Startup`, `PreUpdate`, `Update`, `PostUpdate`, and the fixed
trio `FixedPreUpdate` / `FixedUpdate` / `FixedPostUpdate`.
+## Timers
+
+For "in 2 seconds…" / "every 0.5 s…" logic, the built-in **timer** resource beats
+hand-rolled elapsed-time bookkeeping. It ticks with the engine loop (so it pauses
+with the game, unlike `setTimeout`):
+
+```typescript
+import { defineSystem, Res, TimerRes } from 'esengine';
+
+const arm = defineSystem([Res(TimerRes)], (timers) => {
+ timers.delay(2, () => explode()); // once, in 2 s
+ const h = timers.interval(0.5, (t) => spawnWave()); // repeating
+ timers.interval(1, (t) => tick(), 3); // exactly 3 times
+ h.pause(); h.resume(); h.cancel(); h.reset(); // handle controls
+});
+```
+
+| Member | Description |
+|---|---|
+| `delay(seconds, cb)` | Run once after `seconds`; returns a `TimerHandle`. |
+| `interval(seconds, cb, maxRepeat?)` | Run every `seconds`; `maxRepeat` `0` = forever. |
+| handle `pause()` / `resume()` / `cancel()` / `reset()` | Control one timer (chainable). |
+| handle `isActive` / `elapsed` / `repeatCount` | Inspect it. |
+| `cancelAll()` · `activeCount` | Manage the whole set. |
+| `timeScale` | Slow / speed every timer at once (`0` freezes). |
+
+Timers advance in play mode only — in the editor's edit mode they hold, like the
+rest of game time.
+
## How it fits together
A behavior is not a special case — it compiles to exactly one `defineComponent` plus
diff --git a/docs/astro/src/content/docs/guides/sprites.mdx b/docs/astro/src/content/docs/guides/sprites.mdx
index c1ed84625..b5a4d83dc 100644
--- a/docs/astro/src/content/docs/guides/sprites.mdx
+++ b/docs/astro/src/content/docs/guides/sprites.mdx
@@ -1,6 +1,6 @@
---
title: Sprites & Rendering
-description: Draw 2D images with the Sprite component — textures, tint and transparency, size and pivot, flipping, sorting layers and draw order, parallax, and the ShapeRenderer for primitives.
+description: Draw 2D images with the Sprite component — textures, tint and transparency, size and pivot, flipping, sorting layers and draw order, parallax — plus ShapeRenderer primitives, sprite filters, motion trails, and world-space bitmap text.
---
import { Aside } from '@astrojs/starlight/components';
@@ -127,6 +127,25 @@ To make a sprite respond to `Light2D` lights, the simplest path is to set
normal maps or a fully custom look, use a **Lit-2D material** instead. Either way,
see [2D Lighting & Shadows](/docs/guides/lighting/).
+### Sprite filters (outline, glow, drop shadow)
+
+For the most common per-sprite effects you don't need to write a shader —
+`SpriteFilter` builds a ready-made material you assign to `sprite.material`:
+
+```typescript
+import { SpriteFilter } from 'esengine';
+
+sprite.material = SpriteFilter.createOutline({ color: { r: 1, g: 1, b: 1, a: 1 }, width: 2 });
+sprite.material = SpriteFilter.createGlow(); // warm outline preset
+sprite.material = SpriteFilter.createDropShadow({ offsetX: 3, offsetY: 3, blur: 2 });
+```
+
+Tweak a live filter with `setOutlineColor` / `setOutlineWidth` /
+`setShadowOffset` / `setShadowBlur` (selection pulses, hit flashes). Each call
+creates a material — share one handle across sprites that use the same look, and
+pass `texelSize: { x: 1/texWidth, y: 1/texHeight }` for exact pixel widths on
+textures that aren't 512×512.
+
## Shapes without a texture
For solid circles, capsules, and rounded rectangles — placeholders, bars, debug
@@ -148,6 +167,52 @@ cmds.spawn()
`ShapeRenderer` shares the sorting `layer` and `color` conventions with `Sprite`.
+## Motion trails
+
+**`TrailRenderer`** draws a world-space ribbon along an entity's recent path —
+sword swipes, dashes, projectile streaks. Add the component and move the entity;
+the engine records the position history and renders the taper for you:
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(TrailRenderer, { time: 0.4, startWidth: 24, blendMode: 1 }); // additive glow
+```
+
+| Field | Default | Description |
+|---|---|---|
+| `time` | `0.5` | Seconds each trail point lives before fading out of the tail. |
+| `minVertexDistance` | `5` | Min world distance moved before a new point is recorded (`0` = every frame). |
+| `emitting` | `true` | `false` freezes emission — the streak detaches and fades in place. |
+| `startWidth` / `endWidth` | `20` / `0` | Ribbon width at the head / tail (`0` tapers to a line). |
+| `startColor` / `endColor` | white / white α 0 | Color lerped head → tail; tail alpha 0 is the fade-out. |
+| `texture` | `0` | Texture along the ribbon (U runs head→tail); `0` = vertex colors only. |
+| `blendMode` | `0` | `0` Normal, `1` Additive (glow), `2` Multiply. |
+| `layer` / `material` | `0` / `0` | The usual sorting layer / custom material. |
+
+The `Trail` resource (`Res(Trail)`) adds `clear(entity)` to drop an entity's
+history instantly — e.g. when teleporting, so the trail doesn't streak across the
+map.
+
+## Bitmap text in the world
+
+**`BitmapText`** renders world-space text from a prebaked bitmap font — damage
+numbers, name tags, retro UI. Point `font` at a **BMFont** asset (`.fnt` text or
+`.bmfont` JSON) and set `text`:
+
+| Field | Default | Description |
+|---|---|---|
+| `text` | `''` | The string to draw. |
+| `font` | `0` | The bitmap-font asset (`.fnt` / `.bmfont`). |
+| `fontSize` | `1` | Scale over the font's authored size. |
+| `align` | `Left` | `Left` / `Center` / `Right`. |
+| `spacing` | `0` | Extra per-character spacing. |
+| `color` | `{1,1,1,1}` | Tint — animatable (flash a damage number). |
+| `layer` / `parallax` | `0` / `{1,1}` | Same sorting layer / parallax semantics as `Sprite`. |
+
+For screen-space UI text (layout, wrapping, SDF sharpness), use the UI `Text`
+widget instead — see [UI](/docs/guides/ui/).
+
## In the editor
- **Create → Sprite** adds a sprite entity, or **drag an image** from the Content
diff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdx
index 109ca445a..d303c1b3d 100644
--- a/docs/astro/src/content/docs/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/guides/ui-components.mdx
@@ -1,6 +1,6 @@
---
title: UI Components
-description: The built-in widget factories — Button, Toggle, Slider, Progress, Dropdown, and Dialog — their options and imperative handles, built on the UI component model.
+description: The built-in widget factories — Button, Toggle, Slider, Progress, Dropdown, Dialog, and ListView — plus text input, drag & drop, keyboard focus, mobile safe areas, and theming.
---
import { Aside } from '@astrojs/starlight/components';
@@ -282,6 +282,78 @@ list.data.setItems(freshList); // replace all
`item`, and give the data source a `getItemType(i)`.
</Aside>
+## Text input
+
+`TextInput` is a component, not a factory: put it on a UI entity and it becomes an
+editable field — background, caret, placeholder, and IME plumbing included:
+
+```typescript
+import { spawnUIEntity, TextInput, px } from 'esengine';
+
+const field = spawnUIEntity({ world, parent, node: { width: px(240), height: px(32) } });
+world.insert(field, TextInput, { placeholder: 'Your name', maxLength: 20 });
+
+events.on(field, 'change', () => { /* value edited */ });
+events.on(field, 'submit', () => save(world.get(field, TextInput).value)); // Enter
+```
+
+| Field | Default | Description |
+|---|---|---|
+| `value` / `placeholder` | `''` | Content / hint shown while empty. |
+| `maxLength` | `0` | Character cap (`0` = unlimited). |
+| `multiline` | `false` | Enter inserts a newline instead of submitting. |
+| `password` | `false` | Mask the characters. |
+| `readOnly` | `false` | Focusable but not editable. |
+| `fontSize` / `fontFamily` | `16` / `Arial` | Text style — `color`, `placeholderColor`, `backgroundColor`, and `padding` (`6`) round out the look. |
+
+Click (or Tab to) the field to focus it; **Escape** blurs, **Enter** fires
+`submit` on single-line fields.
+
+<Aside type="note">
+ Text input runs in **play mode only** and needs a browser DOM (it drives a
+ hidden native textarea for IME support) — it's inert in the editor's edit view.
+</Aside>
+
+## Drag & drop
+
+Add `Draggable` to any interactable UI entity and pointer drags move it — its
+absolute `UINode` insets when it has one, otherwise its `Transform`:
+
+```typescript
+world.insert(entity, Draggable, { dragThreshold: 5, lockY: true });
+events.on(entity, 'drag_start', () => { /* also 'drag_move' and 'drag_end' */ });
+```
+
+`lockX` / `lockY` constrain the axis and `constraintMin` / `constraintMax` clamp
+the range; the auto-inserted `DragState` component exposes the live drag
+(`isDragging`, `deltaWorld`, `totalDeltaWorld`, …). There's no built-in
+drop-target concept — decide what the drop hit in your `drag_end` handler.
+
+## Keyboard focus
+
+Entities with a `Focusable` component participate in keyboard focus: **click**
+focuses, **Tab / Shift+Tab** cycles (ordered by `tabIndex` ascending, skipping
+disabled widgets, wrapping at the ends). The `FocusManager` resource exposes
+`focusedEntity` plus `focus(entity)` / `blur()` for programmatic control, and
+focused entities receive `focus` / `blur` events on the UI event bus.
+`TextInput` adds its own `Focusable` automatically.
+
+## Safe area (mobile notches)
+
+Add `SafeArea` to a full-screen, absolutely-positioned `UINode` container and its
+insets track the platform safe area — device notches, rounded corners, the WeChat
+capsule — so children laid out inside never hide under hardware. `applyTop` /
+`applyBottom` / `applyLeft` / `applyRight` (all default `true`) pick which edges
+apply.
+
+## Theming
+
+Widget colors come from a shared token set: `getTheme()` / `setTheme(tokens)`
+with roles like `surface`, `control`, `controlHover`, `primary`, `onPrimary`,
+`track`, and `backdrop` (`DARK_TOKENS` is the built-in dark theme). `setTheme`
+affects widgets **constructed afterwards** — set your theme once at startup,
+before building UI; widgets already on screen keep their baked colors.
+
## Editor prefabs
The same widgets ship as editor prefabs, so **Create… → UI** drops a ready-made
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/components.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/components.mdx
index 2d8e50aed..f5522135d 100644
--- a/docs/astro/src/content/docs/zh-cn/core-concepts/components.mdx
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/components.mdx
@@ -1,6 +1,6 @@
---
title: 组件
-description: 用 defineComponent 声明和使用组件。
+description: 声明和使用组件——defineComponent、字段类型、标签组件、编辑器元数据与内置组件集。
---
**组件**是挂在实体上的一小块纯数据结构。用 `defineComponent` 声明一个组件,给它一个
@@ -16,13 +16,66 @@ const Health = defineComponent('Health', { current: 100, max: 100 });
默认值同时定义了组件的形状(字段与类型)和新实例的初始值。组件是纯数据——没有方法、
没有行为。行为存在于[系统](/docs/zh-cn/core-concepts/systems/)里。
-## 内置组件
+## 字段类型
+
+字段的类型由默认值推断。数字、布尔、字符串如你所想,结构化形状会得到对应的编辑器
+控件:
+
+```typescript
+const Missile = defineComponent('Missile', {
+ speed: 400, // number
+ homing: true, // boolean
+ targetTag: '', // string
+ velocity: { x: 0, y: 0 }, // 向量——以 X/Y 一对编辑
+ tint: { r: 1, g: 1, b: 1, a: 1 }, // {r,g,b,a} 字段渲染成拾色器
+});
+```
+
+## 标签——没有数据的组件
+
+**标签(tag)**是零字段的标记组件,纯粹用于过滤——`Player`、`Enemy`、`Frozen`。
+用 `defineTag` 声明,在查询里配合 `.with()` / `.without()` 使用:
+
+```typescript
+import { defineTag, defineSystem, Query, Mut, Transform } from 'esengine';
+
+const Player = defineTag('Player');
+const Frozen = defineTag('Frozen');
-SDK 自带一批引擎组件,你可以和自己的组件一起查询,例如:
+defineSystem([Query(Mut(Transform)).with(Player).without(Frozen)], (q) => { /* … */ });
+```
+
+## 编辑器元数据
+
+第三个参数控制字段在编辑器 Details 面板里的呈现——范围、滑杆、单位、枚举:
+
+```typescript
+const Turret = defineComponent('Turret', {
+ range: 300,
+ mode: 0,
+}, {
+ fields: {
+ range: { min: 0, max: 1000, slider: true, unit: 'px' },
+ mode: { enum: [{ label: 'Idle', value: 0 }, { label: 'Attack', value: 1 }] },
+ },
+});
+```
+
+常用的 `fields` 选项:`min` / `max` / `step`、`slider`、`unit`、`enum`(下拉,
+存储选项的整数值)、`flags`(位掩码多选)、`tooltip`。其他组件级元数据:
+`assetFields`(把字段标记为资产引用,Details 渲染选择器、cook 会带上依赖)、
+`animatableFields`([Sequencer](/docs/zh-cn/guides/timeline/) 可打关键帧的字段
+——默认为全部数字字段)、`transient`(永不存进场景——用于逐帧运行时状态),以及
+`replicatedFields`(由[联网](/docs/zh-cn/guides/networking/)的状态复制同步)。
-- `Transform` —— 位置、旋转与缩放。
-- `Sprite` —— 一个带贴图的四边形。
-- `Camera` —— 观察世界的视图。
+## 内置组件
+
+SDK 自带约 30 个引擎组件,与你自己的组件一起查询——`Transform`、`Sprite`、
+`ShapeRenderer`、`Camera`、`Light2D`、`ParticleEmitter`、`SpineAnimation`、
+`TilemapLayer`、UI 组件族、物理碰撞体等等。各自在对应的子系统指南里有完整文档:
+[精灵与渲染](/docs/zh-cn/guides/sprites/)、[相机](/docs/zh-cn/guides/camera/)、
+[2D 光照](/docs/zh-cn/guides/lighting/)、[物理](/docs/zh-cn/guides/physics/)、
+[瓦片地图](/docs/zh-cn/guides/tilemap/)、[UI](/docs/zh-cn/guides/ui/)。
## 读取与写入
@@ -34,6 +87,10 @@ Query(Mut(Transform), Speed)
// Transform 会被写入;Speed 只读
```
+因为写入被跟踪,系统也能响应生命周期:`Added(Comp)` / `Changed(Comp)` 把查询收窄到
+组件刚出现 / 刚变化的实体——完整的查询词汇见
+[系统](/docs/zh-cn/core-concepts/systems/)。
+
<br />
在底层,一个组件是带 `ES_COMPONENT` / `ES_PROPERTY` 注解的 C++ 结构体;跨边界的内存
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/ecs.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/ecs.mdx
index 79cef4f3d..4259e37a7 100644
--- a/docs/astro/src/content/docs/zh-cn/core-concepts/ecs.mdx
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/ecs.mdx
@@ -14,8 +14,8 @@ Estella 构建在 **Entity-Component-System**(ECS,实体-组件-系统)架
## 为什么要数据导向
-组件存放在单一、缓存友好的存储层(稀疏集,sparse set)里,因此一个系统遍历
-「所有同时拥有 `Transform` 与 `Speed` 的实体」时走的是连续内存。存储位于
+组件存放在缓存友好的池里——每个组件类型一个紧密排布的稀疏集(sparse set)——
+因此一个系统遍历「所有同时拥有 `Transform` 与 `Speed` 的实体」时走的是连续内存。存储位于
C++/WebAssembly 内核中,SDK 通过一份生成并经哈希校验的内存布局**零拷贝**读取它——
于是同一个组件的 TypeScript 视图与 C++ 视图永远不会悄悄地对不上。
@@ -25,8 +25,11 @@ C++/WebAssembly 内核中,SDK 通过一份生成并经哈希校验的内存布
- [`defineComponent`](/docs/zh-cn/core-concepts/components/) —— 声明一个组件类型。
- [`defineSystem`](/docs/zh-cn/core-concepts/systems/) —— 声明一个系统及其查询。
-- `App` / 插件 —— 把系统、资源与各子系统(物理、Spine、瓦片地图、UI、音频、场景)
- 组装成一个运行中的游戏。
+- [`App` / 插件](/docs/zh-cn/core-concepts/plugins-resources/) —— 把系统、资源与
+ 各子系统([物理](/docs/zh-cn/guides/physics/)、[Spine](/docs/zh-cn/guides/spine/)、
+ [瓦片地图](/docs/zh-cn/guides/tilemap/)、[UI](/docs/zh-cn/guides/ui/)、
+ [音频](/docs/zh-cn/guides/audio/)、[场景](/docs/zh-cn/guides/scene/))组装成一个
+ 运行中的游戏。
```typescript
import { App } from 'esengine';
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx
index 514bc080d..288edb5d4 100644
--- a/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx
@@ -20,22 +20,39 @@ defineSystem([Res(Audio)], (audio) => {
每个子系统的命令式 API 都用同一种方式取用:
-| 子系统 | 资源 | 导入自 |
+| 子系统 | 资源 | 指南 |
|---|---|---|
-| 输入 | `Res(Input)` | `esengine` |
-| 音频 | `Res(Audio)` | `esengine` |
-| 资源 | `Res(Assets)` | `esengine` |
-| 瓦片地图 | `Res(Tilemaps)` | `esengine` |
-| 粒子 | `Res(Particle)` | `esengine` |
-| 后处理 | `Res(PostProcess)` | `esengine` |
-| 场景 | `Res(SceneManager)` | `esengine` |
-| 补间 | `Res(Tween)` | `esengine` |
-| 动画机 | `Res(AnimatorController)` | `esengine` |
-| 物理 | `Res(PhysicsAPI)` | `esengine/physics` |
-| Spine | `Res(Spine)` | `esengine/spine` |
+| 输入 | `Res(Input)` | [输入](/docs/zh-cn/guides/input/) |
+| 音频 | `Res(Audio)` | [音频](/docs/zh-cn/guides/audio/) |
+| 资源 | `Res(Assets)` | [资源](/docs/zh-cn/guides/assets/) |
+| 瓦片地图 | `Res(Tilemaps)` | [瓦片地图](/docs/zh-cn/guides/tilemap/) |
+| 粒子 | `Res(Particle)` | [粒子](/docs/zh-cn/guides/particle/) |
+| 后处理 | `Res(PostProcess)` | [后处理](/docs/zh-cn/guides/postprocess/) |
+| 场景 | `Res(SceneManager)` | [场景](/docs/zh-cn/guides/scene/) |
+| 补间 | `Res(Tween)` | [动画](/docs/zh-cn/guides/animation/) |
+| 帧动画 | `Res(SpriteAnimation)` | [动画](/docs/zh-cn/guides/animation/) |
+| 动画机 | `Res(AnimatorController)` | [动画](/docs/zh-cn/guides/animation/) |
+| 计时器 | `Res(TimerRes)` | [脚本](/docs/zh-cn/guides/scripting/) |
+| 时间轴 | `Res(Timeline)` | [时间轴](/docs/zh-cn/guides/timeline/) |
+| 预制体 | `Res(Prefabs)` | [预制体](/docs/zh-cn/guides/prefab/) |
+| 导航 / AI | `Res(Nav)` | [游戏 AI](/docs/zh-cn/guides/ai/) |
+| 本地化 | `Res(Localization)` | [本地化](/docs/zh-cn/guides/localization/) |
+| 相机视图 | `Res(CameraView)` | [相机](/docs/zh-cn/guides/camera/) |
+| UI 事件 | `Res(UIEvents)` | [UI](/docs/zh-cn/guides/ui/) |
+| 物理 | `Res(PhysicsAPI)` —— 来自 `esengine/physics` | [物理](/docs/zh-cn/guides/physics/) |
+| Spine | `Res(Spine)` —— 来自 `esengine/spine` | [Spine](/docs/zh-cn/guides/spine/) |
物理和 Spine 是**可选 side-module**,按需加载,因此它们的 API 放在子路径上以保持基础
-包精简;其余都在主 `esengine` 包里。
+包精简;其余都在主 `esengine` 包里。上表的基础子系统都随标准 App 附带——无需接线。
+
+有些子系统还按同一范式发布**事件资源**——内容是本帧事件、当帧读取的资源:
+`Res(PhysicsEvents)`(碰撞接触)、`Res(SpineEvents)`(动画事件)、
+`Res(UIEvents)`(控件的点击与输入)。
+
+<br />
+
+`Res(X)` 是读取;当系统要**替换或改动资源的状态**时用 `ResMut(X)`——与组件上的
+`Mut` 是同一契约。
## 组件 vs 资源
diff --git a/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx b/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx
index 581560f6a..8392f9654 100644
--- a/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/getting-started/installation.mdx
@@ -11,10 +11,11 @@ import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
1. 从[发布页](https://github.com/esengine/estella/releases)下载最新版编辑器。
- 2. 安装并打开,点击 **New Project**(新建项目)。
+ 2. 安装并打开,点击 **New project**(新建项目)。
- 3. 填写项目名称与位置,点击 **Create**(创建)。编辑器会打开一个带有相机实体的
- 默认场景。
+ 3. 选一个模板——**Blank** 起始模板,或随附的 **Examples** 示例项目——填写项目
+ 名称与位置,点击 **Create project**(创建项目)。选 Blank 时,编辑器会打开
+ 一个带有相机实体的默认场景。
</Steps>
@@ -33,12 +34,13 @@ import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
<Steps>
- 1. 克隆并安装依赖:
+ 1. 克隆(带子模块)并安装依赖:
```bash
- git clone https://github.com/esengine/estella.git
+ git clone --recursive https://github.com/esengine/estella.git
cd estella
pnpm install
+ pnpm emsdk:setup # 一次性:把 Emscripten 5.0.0 装进 tools/emsdk
```
2. 构建引擎、SDK 并同步到编辑器:
diff --git a/docs/astro/src/content/docs/zh-cn/getting-started/quick-start.mdx b/docs/astro/src/content/docs/zh-cn/getting-started/quick-start.mdx
index a792e44f1..96bc1d800 100644
--- a/docs/astro/src/content/docs/zh-cn/getting-started/quick-start.mdx
+++ b/docs/astro/src/content/docs/zh-cn/getting-started/quick-start.mdx
@@ -10,9 +10,9 @@ import { Steps, Aside } from '@astrojs/starlight/components';
<Steps>
-1. **创建项目。** 在编辑器中点击 **New Project**,选 **Blank** 起始模板,命名后点击
- **Create**。你会得到一个带相机实体的默认场景。(想直接看成品的话,**Examples**
- 模板是完整的示例项目。)
+1. **创建项目。** 在编辑器中点击 **New project**,选 **Blank** 起始模板,命名后点击
+ **Create project**。你会得到一个带相机实体的默认场景。(想直接看成品的话,
+ **Examples** 模板是完整的示例项目。)
2. **添加实体。** 在场景层级里新建一个实体,在检视面板中给它加上 `Sprite` 与
`Transform` 组件。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx b/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx
new file mode 100644
index 000000000..63c466941
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx
@@ -0,0 +1,107 @@
+---
+title: 自定义绘制
+description: 超出组件的绘制——用 Draw 画即时模式图元、用 Graphics 画矢量路径、用 Mesh2D 画自定义三角网格,以及离屏渲染纹理。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+大多数视觉是组件——[精灵](/docs/zh-cn/guides/sprites/)、瓦片地图、粒子。当它们
+表达不了你要的东西——调试覆盖层、程序化形状、自定义几何——引擎把绘制层直接暴露
+给你。
+
+## 绘制回调
+
+注册一个回调,它每帧在渲染通道内执行,相机的 view-projection 已经就位——无需任何
+设置,直接画:
+
+```typescript
+import { registerDrawCallback, Draw } from 'esengine';
+
+registerDrawCallback('debug-overlay', (elapsed) => {
+ Draw.line({ x: 0, y: 0 }, { x: 100, y: 50 }, { r: 1, g: 0, b: 0, a: 1 }, 2);
+ Draw.circleOutline({ x: 0, y: 0 }, aggroRadius, { r: 1, g: 1, b: 0, a: 0.5 });
+});
+```
+
+回调画在场景**之上**;`registerPreSceneDrawCallback` 画在场景**之下**(其回调收到
+`{ width, height, elapsed }`)。用 `unregisterDrawCallback(id)` 移除。坐标都是
+世界空间。
+
+<Aside type="tip">
+ 场景激活期间注册的回调可以限定到该场景——在 `loadAdditive` 返回的上下文上调
+ `sceneContext.registerDrawCallback(id, fn)`——随场景清理,只在场景激活时绘制。
+</Aside>
+
+## `Draw` API
+
+`Draw` 是一个即时模式单例——命令自动合批、每帧清空,所以想让形状可见就每帧画:
+
+| 方法 | 画什么 |
+|---|---|
+| `line(from, to, color, thickness?)` | 一条线段(粗细单位 px,默认 `1`)。 |
+| `rect(pos, size, color, filled?)` / `rectOutline(pos, size, color, thickness?)` | 一个矩形——`pos` 是**中心**。 |
+| `circle(center, radius, color, filled?, segments?)` / `circleOutline(…)` | 一个圆(默认 `32` 段)。 |
+| `texture(pos, size, textureHandle, tint?)` | 一个贴图四边形。 |
+| `textureRotated(pos, size, rotation, textureHandle, tint?)` | 同上,带旋转(弧度)。 |
+| `setLayer(layer)` / `setDepth(depth)` | 后续命令的排序。 |
+| `setBlendMode(mode)` / `setDepthTest(on)` | 后续命令的混合 / 深度状态。 |
+| `getDrawCallCount()` / `getPrimitiveCount()` | 本帧统计。 |
+
+## 矢量路径:`Graphics`
+
+由路径构成的形状——折线、贝塞尔、圆弧、圆角矩形——用 `Graphics` 记录路径,
+`flush()` 时经 `Draw` 回放:
+
+```typescript
+import { Graphics, registerDrawCallback } from 'esengine';
+
+const g = new Graphics();
+g.lineStyle(2, { r: 1, g: 1, b: 1, a: 1 });
+g.beginFill({ r: 0, g: 0.5, b: 1, a: 1 });
+g.drawRoundRect(-50, -25, 100, 50, 8);
+g.endFill();
+g.moveTo(0, 0);
+g.curveTo(50, 80, 100, 0); // 二次贝塞尔
+
+registerDrawCallback('hud-shape', () => g.flush());
+```
+
+路径方法:`moveTo` / `lineTo`、`curveTo`(二次)/ `cubicCurveTo`、`arc`、
+`drawRect` / `drawRoundRect` / `drawCircle` / `drawEllipse`、`clear()`。
+`lineStyle(thickness, color)` 设描边;`beginFill(color)` / `endFill()` 的填充
+支持**矩形和圆**(路径轮廓保持描边)。路径是保留的——构建一次,每帧 `flush()`。
+
+## 自定义网格:`Mesh2D`
+
+`Mesh2D` 组件渲染任意的索引三角形列表——程序化地形切片、径向血条弧、水面。
+在组件上编写几何(positions 是 x,y 对;逐顶点 UV 与颜色可选):
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Mesh2D, {
+ geometry: {
+ positions: [0, 0, 100, 0, 50, 80],
+ colors: [1,0,0,1, 0,1,0,1, 0,0,1,1],
+ indices: [0, 1, 2],
+ },
+ });
+```
+
+网格共享标准渲染面:`texture`、`color`、`layer`、`lit`、`parallax` 和
+`material`。场景里(或生成时)设置的几何自动上传;要在**运行时改几何**,走
+`Meshes2D` 资源——`setGeometry(entity, geometry)` 重新上传(索引在引擎侧校验),
+另有 `getGeometry` / `clearGeometry`。只改 `geometry` 字段本身不会被变更检测。
+
+## 离屏目标:`RenderTexture`
+
+进阶用法——小地图、头像、镜面——`RenderTexture.create({ width, height })` 分配
+一个离屏目标;把绘制命令包在 `RenderTexture.begin(rt, viewProjection)` / `end()`
+之间即渲染进去,用完 `release(rt)`。这是低层接口(view-projection 矩阵由你提供)
+——细节见 TypeScript API 参考。
+
+## 参见
+
+- [精灵与渲染](/docs/zh-cn/guides/sprites/) —— 图像与形状的组件路径。
+- [材质与着色器](/docs/zh-cn/guides/material/) —— 给任何渲染体上自定义着色器。
+- [相机](/docs/zh-cn/guides/camera/) —— 回调所用 view-projection 的来源。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/input.mdx b/docs/astro/src/content/docs/zh-cn/guides/input.mdx
index 5e17729e6..9dd888357 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/input.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/input.mdx
@@ -1,6 +1,6 @@
---
title: 输入
-description: 输入完整参考——通过 Input 资源读取键盘、鼠标、触摸与手柄,以及世界空间光标。
+description: 输入完整参考——通过 Input 资源读取键盘、鼠标、触摸与手柄,用 InputMap 做可改键的命名动作,触摸手势,以及世界空间光标。
---
import { Aside } from '@astrojs/starlight/components';
@@ -74,6 +74,97 @@ const jump = defineSystem([Query(Mut(CharacterController)), Res(Input)], (player
<Aside type="note">按住状态(`isKeyDown`)是电平触发,本就能在任意 schedule 正确读取。
按步精确的边沿投递覆盖键盘与鼠标按键;手柄边沿是按帧粒度的。</Aside>
+## 输入动作(`InputMap`)
+
+写死的按键检查会把设备细节散落进玩法代码。**输入映射**给每个动作起一次名——
+键盘 / 鼠标 / 手柄绑定随便挂多少个——玩法按名字查询动作:
+
+```typescript
+import {
+ defineInputMap, Button, Axis2D,
+ Key, Keys2D, Stick, GpButton, GamepadButton,
+} from 'esengine';
+
+export const Controls = defineInputMap({
+ Move: Axis2D(Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'), Stick('left')),
+ Jump: Button(Key('Space'), GpButton(GamepadButton.South)),
+});
+```
+
+`defineInputMap` 自己注册每帧求值(在输入轮询之后、`Update` 之前),映射立即可用
+——在任何系统里导入并查询:
+
+```typescript
+const dir = Controls.axis2d('Move'); // { x, y },长度 ≤ 1
+if (Controls.pressed('Jump')) { /* 本帧边沿 */ }
+```
+
+| 查询 | 返回 |
+|---|---|
+| `down(name)` | 按住——动作幅度 ≥ 0.5。 |
+| `pressed(name)` / `released(name)` | 本帧边沿。 |
+| `value(name)` | button `0..1` · axis `-1..1` · axis2d 的幅度 `0..1`。 |
+| `axis2d(name)` | `{ x, y }` 方向(超过 1 时归一化)。 |
+
+动作是 `Button(…)`、`Axis1D(…)` 或 `Axis2D(…)`;各接任意数量的绑定,多个绑定
+求和(再钳制),键盘与手柄自然共存:
+
+| 绑定 | 供给 | 含义 |
+|---|---|---|
+| `Key(code)` | button / axis | 一个键盘键。 |
+| `MouseButton(b)` | button / axis | 一个鼠标键。 |
+| `GpButton(btn, pad?)` | button / axis | 一个手柄键(扳机给模拟值)。 |
+| `GpAxis(axis, pad?, scale?)` | axis | 一根原始手柄轴。 |
+| `Keys1D(neg, pos)` | axis | 两个键 → 带符号的 1D 轴。 |
+| `Keys2D(up, down, left, right)` | axis2d | 四个键 → 2D 方向。 |
+| `Stick('left' \| 'right', pad?)` | axis2d | 一根手柄摇杆(上 = +y,与 `Keys2D` 一致)。 |
+
+### 改键与持久化
+
+绑定是普通的可序列化数据,所以按键设置界面写起来很小:
+
+```typescript
+// "按任意键…"——捕获下一个按键 / 手柄键(鼠标需显式开启)
+await Controls.rebind('Jump'); // 替换;{ append: true } 则追加
+Controls.save('controls'); // 持久化到平台 Storage
+// 启动时:
+Controls.load('controls'); // 重新应用已存的绑定(如有)
+```
+
+`getBindings` / `setBindings` 以编程方式查看和编辑绑定;`cancelListen()` 中止
+挂起的捕获(以 `null` 解析)。
+
+### 数据驱动的映射(`.inputmap`)
+
+整张映射也能序列化为资产:在编辑器内容浏览器里**新建 Input Map**,然后用
+`loadInputMapAsset(json)` 代替 `defineInputMap` 构建。`toAsset()` 从代码产出
+同样的格式。
+
+## 触摸手势
+
+`GestureDetector` 把原始触摸变成点按 / 长按 / 滑动 / 捏合回调。基于 `Input`
+资源构建一次,在系统里驱动:
+
+```typescript
+import { defineSystem, Res, Input, Time, GestureDetector } from 'esengine';
+
+let gestures: GestureDetector | null = null;
+
+const gestureSystem = defineSystem([Res(Input), Res(Time)], (input, time) => {
+ if (!gestures) {
+ gestures = new GestureDetector(input);
+ gestures.onTap = (x, y) => { /* 屏幕 px */ };
+ gestures.onLongPress = (x, y) => { /* 原地按住约 0.5 s */ };
+ gestures.onSwipe = (dir, speed) => { /* 'left' | 'right' | 'up' | 'down' */ };
+ gestures.onPinch = (scale, cx, cy) => { /* 逐帧的双指缩放系数 */ };
+ }
+ gestures.update(time.delta);
+});
+```
+
+点按 = 0.3 s 内、移动小于 10 px;滑动需 ≥ 50 px 且 ≥ 200 px/s;捏合报告双指
+间距逐帧的缩放系数及中心点。
+
## 参考
| 分组 | 方法 |
diff --git a/docs/astro/src/content/docs/zh-cn/guides/scene.mdx b/docs/astro/src/content/docs/zh-cn/guides/scene.mdx
index 61b9678e5..7424e43c3 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/scene.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/scene.mdx
@@ -1,6 +1,6 @@
---
title: 场景
-description: 场景的完整指南——切换、叠加加载、查询状态,以及系统如何按场景门控,通过 Res(SceneManager)。
+description: 场景的完整指南——切换、叠加加载、开放世界单元流送、查询状态,以及系统如何按场景门控,通过 Res(SceneManager)。
---
import { Aside } from '@astrojs/starlight/components';
@@ -31,6 +31,27 @@ await scenes.loadAdditive('pause-menu', (loaded, total) => { /* progress */ });
await scenes.unload('pause-menu');
```
+## 场景流送(开放世界)
+
+世界大到装不下时,用 `SceneStreaming` 资源围绕一个焦点加载与卸载**单元
+(cell)**——摆在世界空间里的叠加场景:
+
+```typescript
+import { defineSystem, Res, SceneStreaming } from 'esengine';
+
+const setupStreaming = defineSystem([Res(SceneStreaming)], (streaming) => {
+ streaming.configure({ loadRadius: 1200, unloadRadius: 1600 });
+ streaming.register({ scene: 'cells/forest', x: 0, y: 0, radius: 800 });
+ streaming.register({ scene: 'cells/village', x: 1500, y: 0, radius: 800 });
+ streaming.setFocusEntity(player); // 或每帧 setFocus(x, y)
+});
+```
+
+每帧,距焦点小于 `loadRadius` 的单元叠加加载,超出 `unloadRadius` 的卸载——两个
+半径之间是滞回带,玩家站在边界不会来回抖动。`policy: 'sleep'` 用**休眠**代替
+卸载:实体留在内存里、被禁用并隐藏,重进即恢复,代价是内存。单元场景就是普通的
+项目场景,按名字引用(见下)。
+
## 构建里的场景
项目场景目录下的每个场景都会随导出发布,并注册为 `switchTo` 的目标。场景的**名字**是它
@@ -50,8 +71,11 @@ await scenes.unload('pause-menu');
| `unload(name, options?)` | 卸载一个场景(异步;可选过渡)。 |
| `getActive()` | 活动场景名,或 `null`。 |
| `getActiveScenes()` | 所有活动(叠加)场景名。 |
+| `pause(name)` / `resume(name)` | 挂起 / 恢复一个已加载场景的更新。 |
+| `sleep(name)` / `wake(name)` | 挂起**并隐藏**场景的实体(留在内存;唤醒即刻恢复)。 |
| `isLoaded(name)` | 场景是否已加载。 |
| `isActive(name)` | 场景是否活动。 |
+| `isPaused(name)` / `isSleeping(name)` | 上述两种挂起状态。 |
| `isTransitioning()` | `switchTo` 过渡期间为 `true`。 |
## 最佳实践
diff --git a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
index 25da15f19..7dfa7a542 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
@@ -151,6 +151,33 @@ export const Thruster = defineBehavior('Thruster', {
可用的相位包括 `Startup`、`PreUpdate`、`Update`、`PostUpdate`,以及固定三件套
`FixedPreUpdate` / `FixedUpdate` / `FixedPostUpdate`。
+## 计时器
+
+"2 秒后…" / "每 0.5 秒…"这类逻辑,用内置的**计时器**资源比手搓累计时间干净。
+它随引擎循环走(所以和 `setTimeout` 不同,会跟游戏一起暂停):
+
+```typescript
+import { defineSystem, Res, TimerRes } from 'esengine';
+
+const arm = defineSystem([Res(TimerRes)], (timers) => {
+ timers.delay(2, () => explode()); // 2 秒后执行一次
+ const h = timers.interval(0.5, (t) => spawnWave()); // 重复执行
+ timers.interval(1, (t) => tick(), 3); // 恰好 3 次
+ h.pause(); h.resume(); h.cancel(); h.reset(); // 句柄控制
+});
+```
+
+| 成员 | 说明 |
+|---|---|
+| `delay(seconds, cb)` | `seconds` 后执行一次;返回 `TimerHandle`。 |
+| `interval(seconds, cb, maxRepeat?)` | 每 `seconds` 执行;`maxRepeat` 为 `0` = 无限。 |
+| 句柄 `pause()` / `resume()` / `cancel()` / `reset()` | 控制单个计时器(可链式)。 |
+| 句柄 `isActive` / `elapsed` / `repeatCount` | 查看状态。 |
+| `cancelAll()` · `activeCount` | 管理全体。 |
+| `timeScale` | 一次性放慢 / 加速所有计时器(`0` 冻结)。 |
+
+计时器只在播放模式推进——编辑器编辑态下与其余游戏时间一样保持不动。
+
## 它如何组合
一个 behavior 并不是特例——它编译成恰好一个 `defineComponent` 加一个 `defineSystem`。当你的逻辑
diff --git a/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx b/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
index 0d349acb8..51c938619 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
@@ -1,6 +1,6 @@
---
title: 精灵与渲染
-description: 用 Sprite 组件绘制 2D 图像——纹理、着色与透明、尺寸与轴心、翻转、排序层与绘制顺序、视差,以及绘制基本图元的 ShapeRenderer。
+description: 用 Sprite 组件绘制 2D 图像——纹理、着色与透明、尺寸与轴心、翻转、排序层与绘制顺序、视差——外加 ShapeRenderer 图元、精灵滤镜、拖尾与世界空间位图文字。
---
import { Aside } from '@astrojs/starlight/components';
@@ -110,6 +110,24 @@ sprite.layer = 2; // 例如 "Foreground" —— 画在上面
(用平面法线受光)。需要法线贴图或完全自定义的观感时,改用 **Lit-2D 材质**。两种方式都见
[2D 光照与阴影](/docs/zh-cn/guides/lighting/)。
+### 精灵滤镜(描边、发光、投影)
+
+最常见的逐精灵效果不用写着色器——`SpriteFilter` 直接构建一个现成材质,赋给
+`sprite.material`:
+
+```typescript
+import { SpriteFilter } from 'esengine';
+
+sprite.material = SpriteFilter.createOutline({ color: { r: 1, g: 1, b: 1, a: 1 }, width: 2 });
+sprite.material = SpriteFilter.createGlow(); // 暖色描边预设
+sprite.material = SpriteFilter.createDropShadow({ offsetX: 3, offsetY: 3, blur: 2 });
+```
+
+用 `setOutlineColor` / `setOutlineWidth` / `setShadowOffset` / `setShadowBlur`
+实时调一个已生效的滤镜(选中脉冲、受击闪白)。每次调用都创建一个材质——观感相同
+的精灵共享同一个句柄;纹理不是 512×512 时传
+`texelSize: { x: 1/texWidth, y: 1/texHeight }` 以获得精确的像素宽度。
+
## 不带纹理的图元
要画实心圆、胶囊和圆角矩形——占位、进度条、调试覆盖——用 **`ShapeRenderer`** 而不是纹理
@@ -130,6 +148,50 @@ cmds.spawn()
`ShapeRenderer` 与 `Sprite` 共享排序 `layer` 和 `color` 约定。
+## 拖尾
+
+**`TrailRenderer`** 沿实体最近的路径画一条世界空间条带——刀光、冲刺、弹道
+残影。加上组件、移动实体即可;位置历史由引擎记录,锥形收窄也替你渲染:
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(TrailRenderer, { time: 0.4, startWidth: 24, blendMode: 1 }); // 加法发光
+```
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `time` | `0.5` | 每个拖尾点存活的秒数,之后从尾部淡出。 |
+| `minVertexDistance` | `5` | 记录新点所需的最小移动距离(`0` = 每帧记录)。 |
+| `emitting` | `true` | `false` 冻结发射——条带脱离实体、原地淡出。 |
+| `startWidth` / `endWidth` | `20` / `0` | 头 / 尾的条带宽度(`0` 收窄成线)。 |
+| `startColor` / `endColor` | 白 / 白 α 0 | 头到尾插值;尾部 alpha 0 即淡出。 |
+| `texture` | `0` | 沿条带采样的纹理(U 从头到尾);`0` = 仅顶点色。 |
+| `blendMode` | `0` | `0` 正常、`1` 加法(发光)、`2` 乘法。 |
+| `layer` / `material` | `0` / `0` | 常规排序层 / 自定义材质。 |
+
+`Trail` 资源(`Res(Trail)`)提供 `clear(entity)`,立刻丢弃某实体的历史——比如
+传送时,免得拖尾划过整张地图。
+
+## 世界空间位图文字
+
+**`BitmapText`** 用预烘焙的位图字体渲染世界空间文字——伤害数字、名牌、复古
+UI。把 `font` 指向一个 **BMFont** 资产(`.fnt` 文本或 `.bmfont` JSON),设置
+`text` 即可:
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `text` | `''` | 要绘制的字符串。 |
+| `font` | `0` | 位图字体资产(`.fnt` / `.bmfont`)。 |
+| `fontSize` | `1` | 相对字体原生尺寸的缩放。 |
+| `align` | `Left` | `Left` / `Center` / `Right`。 |
+| `spacing` | `0` | 逐字符的额外间距。 |
+| `color` | `{1,1,1,1}` | 着色——可动画(闪一下伤害数字)。 |
+| `layer` / `parallax` | `0` / `{1,1}` | 与 `Sprite` 相同的排序层 / 视差语义。 |
+
+屏幕空间的 UI 文字(布局、换行、SDF 锐度)请用 UI 的 `Text` 控件——见
+[UI](/docs/zh-cn/guides/ui/)。
+
## 在编辑器里
- **创建 → 精灵** 添加一个精灵实体,或从内容浏览器**把图拖**进视口,生成一个已带纹理的精灵。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
index 929e03a6d..4392bacba 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
@@ -1,6 +1,6 @@
---
title: UI 控件
-description: 内置控件工厂——Button、Toggle、Slider、Progress、Dropdown、Dialog——它们的选项与命令式句柄,构建在 UI 组件模型之上。
+description: 内置控件工厂——Button、Toggle、Slider、Progress、Dropdown、Dialog、ListView——外加文本输入、拖放、键盘焦点、移动端安全区与主题。
---
import { Aside } from '@astrojs/starlight/components';
@@ -269,6 +269,74 @@ list.data.setItems(freshList); // 全替换
的映射代替单个 `item`,并给数据源一个 `getItemType(i)`。
</Aside>
+## 文本输入
+
+`TextInput` 是组件而不是工厂:放到一个 UI 实体上,它就成为可编辑的输入框——背景、
+光标、占位提示和 IME 管线都齐了:
+
+```typescript
+import { spawnUIEntity, TextInput, px } from 'esengine';
+
+const field = spawnUIEntity({ world, parent, node: { width: px(240), height: px(32) } });
+world.insert(field, TextInput, { placeholder: '你的名字', maxLength: 20 });
+
+events.on(field, 'change', () => { /* 内容被编辑 */ });
+events.on(field, 'submit', () => save(world.get(field, TextInput).value)); // 回车
+```
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `value` / `placeholder` | `''` | 内容 / 为空时显示的提示。 |
+| `maxLength` | `0` | 字符上限(`0` = 不限)。 |
+| `multiline` | `false` | 回车插入换行而不是提交。 |
+| `password` | `false` | 掩码显示。 |
+| `readOnly` | `false` | 可聚焦但不可编辑。 |
+| `fontSize` / `fontFamily` | `16` / `Arial` | 文字样式——`color`、`placeholderColor`、`backgroundColor` 和 `padding`(`6`)补全观感。 |
+
+点击(或 Tab 到)输入框即聚焦;**Escape** 失焦,单行输入框按**回车**触发
+`submit`。
+
+<Aside type="note">
+ 文本输入只在**播放模式**运行,且需要浏览器 DOM(它驱动一个隐藏的原生
+ textarea 以支持 IME)——在编辑器编辑态下不生效。
+</Aside>
+
+## 拖放
+
+给任何可交互的 UI 实体加 `Draggable`,指针拖动就能移动它——有 `UINode` 时移动
+其绝对 inset,否则移动 `Transform`:
+
+```typescript
+world.insert(entity, Draggable, { dragThreshold: 5, lockY: true });
+events.on(entity, 'drag_start', () => { /* 还有 'drag_move' 与 'drag_end' */ });
+```
+
+`lockX` / `lockY` 锁轴,`constraintMin` / `constraintMax` 钳制范围;自动插入的
+`DragState` 组件暴露实时拖动数据(`isDragging`、`deltaWorld`、`totalDeltaWorld`
+等)。没有内置的放置目标(drop target)概念——在你的 `drag_end` 处理器里自行
+判定落点。
+
+## 键盘焦点
+
+带 `Focusable` 组件的实体参与键盘焦点:**点击**聚焦,**Tab / Shift+Tab** 轮换
+(按 `tabIndex` 升序,跳过禁用控件,到头回绕)。`FocusManager` 资源暴露
+`focusedEntity` 以及 `focus(entity)` / `blur()` 供编程控制,被聚焦的实体在 UI
+事件总线上收到 `focus` / `blur` 事件。`TextInput` 会自动加上自己的 `Focusable`。
+
+## 安全区(移动端刘海)
+
+给一个全屏、绝对定位的 `UINode` 容器加 `SafeArea`,它的 inset 就会跟随平台
+安全区——刘海、圆角、微信胶囊——里面布局的子节点永远不会被硬件遮住。
+`applyTop` / `applyBottom` / `applyLeft` / `applyRight`(默认全 `true`)选择
+生效的边。
+
+## 主题
+
+控件颜色来自一套共享令牌:`getTheme()` / `setTheme(tokens)`,角色包括
+`surface`、`control`、`controlHover`、`primary`、`onPrimary`、`track`、
+`backdrop`(`DARK_TOKENS` 是内置的暗色主题)。`setTheme` 只影响**之后构建**的
+控件——在启动时、搭 UI 之前设好主题;已经在屏幕上的控件保持既有颜色。
+
## 编辑器预制体
这些控件同时作为编辑器预制体提供,所以 **创建… → UI** 会把现成的 Button、Toggle、Slider 等放进