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 v0.12.0 changelog and update guides for new features
esengine15ba85c8fe7b
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex 4c2088b72..5c631ff6e 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -98,6 +98,7 @@ export default defineConfig({{ label: 'Widgets', translations: { 'zh-CN': '控件' }, slug: 'guides/ui-widgets' },{ label: 'Masking & SafeArea', translations: { 'zh-CN': '遮罩与安全区' }, slug: 'guides/ui-masking' },{ label: 'UI Builder', translations: { 'zh-CN': 'UI 构建器' }, slug: 'guides/ui-builder' },+ { label: 'Data Binding', translations: { 'zh-CN': '数据绑定' }, slug: 'guides/data-binding' },],},{@@ -155,6 +156,7 @@ export default defineConfig({label: 'Changelog',translations: { 'zh-CN': '更新日志' },items: [+ { label: 'v0.12.0', slug: 'changelog-v0120' },{ label: 'v0.11.0', slug: 'changelog-v0110' },{ label: 'v0.10.0', slug: 'changelog-v0100' },{ label: 'v0.9.2', slug: 'changelog-v092' },diff --git a/docs/astro/src/content/docs/changelog-v0120.mdx b/docs/astro/src/content/docs/changelog-v0120.mdxnew file mode 100644index 000000000..b5e34adfc--- /dev/null+++ b/docs/astro/src/content/docs/changelog-v0120.mdx@@ -0,0 +1,192 @@+---+title: v0.12.0+description: Estella v0.12.0 release notes+---++import { Aside } from '@astrojs/starlight/components';++<Aside type="tip">+v0.12.0 is a major release: a complete tilemap editor with painting tools, rich text with stroke/shadow, a data binding system, a new unified asset architecture, CollectionView for virtual scrolling, and a large SDK architecture overhaul with declarative system scheduling.+</Aside>++## Tilemap Editor v2++A complete tilemap editing system, replacing the previous Tiled-import-only workflow. You can now create, paint, and edit tilemaps entirely within the editor.++### Tile Palette & Painting Tools++A new Tile Palette panel provides 5 tools:++- **Brush**: paint individual tiles or stamp multi-tile regions+- **Rectangle Fill**: drag to fill a rectangular area+- **Bucket Fill**: flood-fill connected tiles (BFS, 10k tile limit)+- **Eraser**: remove tiles, also available via right-click with any tool+- **Picker**: sample a tile from the map to use as the current brush++Select stamp regions by dragging in the palette. Flip tiles horizontally/vertically with toolbar buttons.++### Infinite Maps & Chunk Rendering++Tilemaps now support infinite maps (sparse chunk storage). The renderer uses 16×16 chunks with dirty flags for incremental vertex rebuilds — only dirty or animated chunks are rebuilt each frame. Off-screen chunks are culled at the chunk level.++### Layer Management++Add, remove, rename, and reorder tilemap layers. Each layer renders independently with its own tile data and visibility toggle.++### Native Tilemap Creation++Create tilemaps directly from the Hierarchy context menu without needing an external Tiled editor. Infinite map mode is available in the creation dialog.++## Rich Text++The `Text` component now supports rich text with inline formatting tags:++- `<color=#FF0000>red text</color>` — colored text spans+- `<b>bold</b>`, `<i>italic</i>` — font style+- Inline images via `<img src="asset-path"/>` tags+- Enable with the `richText` toggle on the Text component++The parser is stack-based with per-run font measurement and automatic line breaking.++## Text Stroke & Shadow++New properties on the `Text` component:++- **Stroke**: `strokeColor` and `strokeWidth` for text outlines+- **Shadow**: `shadowColor`, `shadowBlur`, `shadowOffsetX`, `shadowOffsetY` for drop shadows++Stroke rendering draws all strokes before all fills to prevent visual overlap artifacts.++## Data Binding++A new `DataBinding` component connects component properties to expressions that update automatically each frame.++- **Template strings**: `"Score: {Score.value}"` — reference any resource or component property+- **Math expressions**: `"{Health.current} / {Health.max} * 100"` — recursive descent parser, no `eval` (WeChat compatible)+- **Auto type coercion**: string ↔ number conversions handled automatically+- **Editor UI**: custom property editor with dropdown for selecting target properties from the entity's components+- **LRU expression cache**: compiled expressions are cached for performance++Data binding evaluation is automatically skipped in editor edit mode to prevent scene corruption.++## Unified Assets Architecture++A new 4-layer asset system replaces the legacy `AssetServer`:++- **Assets**: user-facing API with typed `loadTexture()`, `loadSpine()`, `loadPrefab()` etc.+- **Catalog**: address resolution, atlas frame queries, label-based asset groups, dependency graph+- **AssetLoader**: pluggable typed loaders (texture, spine, material, font, audio, tilemap, timeline, animclip, prefab)+- **Backend**: platform-specific data fetching (HTTP, embedded, WeChat)++Build pipeline generates a manifest catalog for addressable asset loading. Existing `AssetServer` consumers have been migrated.++## CollectionView & Selectable++### CollectionView++A virtual scrolling system replacing `ListView`, with pluggable layout providers:++- **LinearLayout**: vertical or horizontal list+- **GridLayout**: fixed-column grid with row/column gap+- **FanLayout**: radial fan arrangement with configurable angle range++Uses an adapter pattern with item pooling for efficient rendering of large datasets.++### Selectable++New `Selectable` component (C++ builtin) with group-based mutual exclusion — selecting one entity in a group automatically deselects others. Select/deselect events are dispatched via `UIEvents`.++## Spine API Expansion++- **Animation queries**: query current animation state, track entries, and mix info at runtime+- **Event callbacks**: listen for Spine animation events (start, end, complete, custom events)+- **Constraint APIs**: read and modify IK, transform, and path constraints+- **Editor visibility**: SpineAnimation respects entity visibility toggling in the editor++## Physics API Expansion++- **Shape cast**: cast shapes through the physics world with configurable distance+- **AABB overlap**: query all bodies overlapping an axis-aligned bounding box+- **Mass data**: read and modify body mass, center of mass, and inertia at runtime+- **Joint state**: query joint reaction forces, anchor positions, and current limits++## Self-Describing Component Metadata++Component metadata (asset fields, color fields, entity references, animatable properties) is now auto-generated from C++ annotations via EHT codegen:++- `defineBuiltin()` reads defaults and field metadata from generated `COMPONENT_META`+- Editor `defineSchema()` infers Inspector property types from SDK metadata+- Animation target enums generated from `ES_ANIMATABLE` C++ annotations+- Ptr field layouts generated from C++ struct definitions for zero-copy WASM reads++## Declarative System Scheduling++### Run Conditions++Systems can declare execution pre-conditions via `runIf`:++```typescript+import { playModeOnly } from 'esengine';++app.addSystemToSchedule(Schedule.Update, mySystem, {+ runIf: playModeOnly,+});+```++Skipped systems have zero overhead — the condition is checked before parameter resolution.++### System & Plugin Name Constants++Compile-safe constants for all system ordering and plugin dependency references:++```typescript+import { SystemLabel, PluginName } from 'esengine';++app.addSystemToSchedule(Schedule.PostUpdate, mySystem, {+ runAfter: [SystemLabel.UILayout],+});+```++### Disabled Tag++New `Disabled` tag component for excluding entities from processing:++```typescript+import { Disabled } from 'esengine';++world.insert(entity, Disabled, {});+const active = Query(Transform).without(Disabled);+```++### Plugin Dependency Sorting++`app.addPlugins()` performs topological sorting on dependency declarations, allowing plugins in any order.++## Engine Internals++- Unified engine init via `corePlugin`, centralizing ResourceManager and static API lifecycle+- Extracted `App.runFrame_()` to unify tick/mainLoop scheduling logic+- O(1) entity name index updates via reverse `entityToName_` map+- Refactored `AssetRefCounter` with generic `RefMap` (175 → 99 lines)+- Shared `ensureUIRenderer()` utility in `uiHelpers`+- Editor schemas moved into plugin `register()` for lazy initialization+- Split `RenderFrame.cpp` into mask and submit files for maintainability+- Deduplicated `BatchVertex` and `packColor` into shared renderer header+- Generated `PTR_LAYOUTS` from C++ struct definitions, replacing manual offset tables+- Atomic state swap for scene operations prevents load/unload race conditions+- WASM error throttling prevents console flood from repeated C++ exceptions++## Bug Fixes++- Fixed entity name not available in spawn callbacks+- Fixed scene sleep/wake ignoring ShapeRenderer and ParticleEmitter+- Fixed input event listeners leaking on app destruction+- Fixed emscripten config not auto-generated on first compile+- Fixed emsdk cache file check after install+- Fixed editor visibility toggle for Image/UIRenderer components+- Fixed text overflow Visible mode clipping to container instead of expanding+- Fixed rich text stroke rendering order (strokes before fills)+- Fixed Play Mode script injection order (scripts loaded before scene deserialization)+- Fixed component schema preservation when script recompilation fails+- Fixed scene not synced before entering Play Mode+- Fixed circular schema imports causing editor startup failurediff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdxindex e9da1769a..43ff5ec98 100644--- a/docs/astro/src/content/docs/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx@@ -95,6 +95,51 @@ The engine uses topological sorting to determine the final execution order. If t`name` is the basis for ordering. Only systems that participate in ordering need a `name`. Systems without a name cannot be referenced by other systems.</Aside>+### Built-in System Labels++When ordering relative to built-in systems, use the `SystemLabel` constants instead of raw strings for compile-time safety:++```typescript+import { SystemLabel } from 'esengine';++app.addSystemToSchedule(Schedule.PostUpdate, myLayoutSystem, {+ runAfter: [SystemLabel.UILayout],+ runBefore: [SystemLabel.UIRenderOrder],+});+```++Available labels: `UILayout`, `UILayoutLate`, `UIRenderOrder`, `UIInteraction`, `Button`, `ScrollView`, `CollectionView`, `ListView`, `Text`, `Image`, `Focus`, `Tween`.++Similarly, use `PluginName` constants when declaring plugin dependencies:++```typescript+import { PluginName } from 'esengine';++class MyUIPlugin implements Plugin {+ dependencies = [PluginName.UILayout];+}+```++## Run Conditions++Systems can declare a pre-condition via `runIf`. The condition is evaluated before the system runs — if it returns `false`, the system is skipped entirely with zero overhead:++```typescript+import { playModeOnly } from 'esengine';++app.addSystemToSchedule(Schedule.Update, gameplaySystem, {+ runIf: playModeOnly,+});+```++`playModeOnly` is a built-in condition that returns `true` when running outside the editor, or inside the editor in Play Mode. You can write custom conditions — any `() => boolean` function works:++```typescript+app.addSystemToSchedule(Schedule.Update, debugSystem, {+ runIf: () => app.getResource(DebugConfig).enabled,+});+```+## System Parameters### Commandsdiff --git a/docs/astro/src/content/docs/guides/data-binding.mdx b/docs/astro/src/content/docs/guides/data-binding.mdxnew file mode 100644index 000000000..5f9668f16--- /dev/null+++ b/docs/astro/src/content/docs/guides/data-binding.mdx@@ -0,0 +1,103 @@+---+title: Data Binding+description: Reactive data binding for UI components in Estella+---++import { Aside } from '@astrojs/starlight/components';++The **DataBinding** component connects component properties to expressions that update automatically each frame. Use it to display resource values in UI text, drive progress bars from game state, or create reactive UI without writing custom systems.++## Quick Start++1. Add a `DataBinding` component to an entity that already has a `Text` component+2. Set the `source` to a resource name (e.g., `'GameState'`)+3. Add a binding entry mapping a target property to an expression++In the editor Inspector, the DataBinding section provides a visual editor for configuring bindings with a dropdown for selecting target properties.++## Component++| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `source` | string | `''` | Default resource name for expression lookups |+| `bindings` | BindingEntry[] | `[]` | Array of property-to-expression mappings |++Each `BindingEntry` has:++| Field | Type | Description |+|-------|------|-------------|+| `target` | string | Target property path (e.g., `'Text.content'`, `'ProgressBar.value'`) |+| `expression` | string | Expression to evaluate (template or math) |++## Expressions++### Template Strings++Reference resource or component properties with curly braces:++```+Score: {GameState.score}+HP: {Health.current} / {Health.max}+```++The expression system resolves `{ResourceName.property}` by looking up the named resource via the SDK resource registry.++### Math Expressions++Use arithmetic inside templates for computed values:++```+{Health.current} / {Health.max}+{Score.value} * 10 + {Bonus.multiplier}+```++Supported operators: `+`, `-`, `*`, `/`, `(`, `)`. The parser is a recursive descent parser — no `eval()` is used, making it safe for WeChat MiniGame and other restricted environments.++### Auto Type Coercion++- When targeting a `string` property (e.g., `Text.content`), the result is converted to string+- When targeting a `number` property (e.g., `ProgressBar.value`), the result is parsed as a number++## Example: Score Display++Define a resource and bind it to a Text entity:++```typescript+import { defineResource, addStartupSystem, defineSystem, Commands } from 'esengine';++const GameState = defineResource({ score: 0, level: 1 }, 'GameState');++addStartupSystem(defineSystem([Commands()], (cmds) => {+ cmds.insertResource(GameState, { score: 0, level: 1 });+}));+```++In the editor, add `DataBinding` to the score text entity:++- **Source**: `GameState`+- **Binding**: target = `Text.content`, expression = `Score: {GameState.score}`++The text updates automatically whenever `GameState.score` changes — no custom system needed.++## Example: Health Bar++Bind a `ProgressBar.value` to a computed expression:++- **Binding**: target = `ProgressBar.value`, expression = `{Health.current} / {Health.max}`++The progress bar tracks the health ratio reactively.++<Aside type="note">+Data binding evaluation is automatically skipped in editor edit mode to prevent scene data corruption. Bindings only execute in Play Mode and at runtime.+</Aside>++## Performance++- Compiled expressions are cached in an LRU cache — repeated evaluations reuse the compiled form+- The `DataBindingPlugin` runs in `Schedule.PreUpdate` before text and image systems, so bound values are always up-to-date when rendering++## Next Steps++- [Text & Image](/docs/guides/ui-text/) — text rendering and image display+- [UI Widgets](/docs/guides/ui-widgets/) — sliders, progress bars, and other controls+- [Resources](/docs/core-concepts/resources/) — defining and using global resourcesdiff --git a/docs/astro/src/content/docs/guides/physics/api.mdx b/docs/astro/src/content/docs/guides/physics/api.mdxindex c575bb560..119ebbe90 100644--- a/docs/astro/src/content/docs/guides/physics/api.mdx+++ b/docs/astro/src/content/docs/guides/physics/api.mdx@@ -33,12 +33,155 @@ addSystem(defineSystem(| `applyAngularImpulse(entity, impulse)` | Apply instant angular impulse || `setGravity(gravity)` | Change world gravity at runtime || `getGravity()` | Get current world gravity (Vec2) |+| `shapeCastCircle(center, radius, translation, maskBits?)` | Sweep a circle and return hits |+| `shapeCastBox(center, halfExtents, angle, translation, maskBits?)` | Sweep an oriented box and return hits |+| `shapeCastCapsule(center1, center2, radius, translation, maskBits?)` | Sweep a capsule and return hits |+| `overlapAABB(min, max, maskBits?)` | Query entities overlapping an AABB |+| `getMass(entity)` | Get body mass (kg) |+| `getInertia(entity)` | Get body rotational inertia |+| `getCenterOfMass(entity)` | Get body center of mass (Vec2, pixels) |+| `getMassData(entity)` | Get mass, inertia, and center of mass |## Force vs Impulse- **Force** is applied continuously each frame. The effect depends on the body's mass and is integrated over the physics timestep. Use for sustained push (e.g., rocket thrust, wind).- **Impulse** is applied instantly. It directly changes velocity, independent of frame rate. Use for one-time events (e.g., jump, explosion knockback).+## Shape Cast++*Added in v0.12.0.*++Shape casts sweep a shape along a translation vector and return all hits. They work like raycasts but with volume, useful for checking if a character can fit through a gap or predicting collisions along a path.++Each method returns `ShapeCastHit[]` with the same structure as `RaycastHit`:++| Field | Type | Description |+|-------|------|-------------|+| `entity` | Entity | The entity that was hit |+| `point` | Vec2 | Contact point in world pixels |+| `normal` | Vec2 | Surface normal at the contact |+| `fraction` | number | Fraction of the translation at contact (0..1) |++```typescript+// Circle cast: sweep a circle from `center` along `translation`+const hits = physics.shapeCastCircle(+ center, // Vec2 — origin+ radius, // number — circle radius (pixels)+ translation, // Vec2 — sweep direction and distance (pixels)+ maskBits, // number — collision layer mask (default 0xFFFF)+);++// Box cast: sweep an oriented box+const hits = physics.shapeCastBox(+ center, // Vec2 — box center+ halfExtents, // Vec2 — half width/height (pixels)+ angle, // number — rotation (radians)+ translation, // Vec2 — sweep vector (pixels)+ maskBits,+);++// Capsule cast: sweep a capsule defined by two circle centers + radius+const hits = physics.shapeCastCapsule(+ center1, // Vec2 — first circle center+ center2, // Vec2 — second circle center+ radius, // number — capsule radius (pixels)+ translation, // Vec2 — sweep vector (pixels)+ maskBits,+);+```++## AABB Overlap Query++*Added in v0.12.0.*++Query all entities whose colliders overlap an axis-aligned bounding box:++```typescript+const entities = physics.overlapAABB(+ { x: 100, y: 100 }, // min corner (pixels)+ { x: 300, y: 300 }, // max corner (pixels)+ 0xFFFF, // collision layer mask+);+for (const entity of entities) {+ // entity overlaps the AABB+}+```++Returns `Entity[]` with no duplicates.++## Mass Data++*Added in v0.12.0.*++Read mass properties of a rigid body at runtime:++```typescript+// Individual queries+const mass = physics.getMass(entity); // number (kg)+const inertia = physics.getInertia(entity); // number (kg*px^2)+const center = physics.getCenterOfMass(entity); // Vec2 (pixels)++// All at once+const data = physics.getMassData(entity);+// { mass: number, inertia: number, centerOfMass: Vec2 }+```++## Joint State Queries++*Added in v0.12.0.*++Runtime state control for Distance, Prismatic, and Wheel joints.++### Distance Joint++```typescript+// Query+const length = physics.getDistanceJointLength(entity); // rest length (px)+const current = physics.getDistanceJointCurrentLength(entity); // current length (px)+const force = physics.getDistanceJointMotorForce(entity);++// Modify+physics.setDistanceJointLength(entity, 200);+physics.enableDistanceJointSpring(entity, true);+physics.enableDistanceJointLimit(entity, true);+physics.setDistanceJointLimits(entity, 100, 300); // min, max (px)+physics.enableDistanceJointMotor(entity, true);+physics.setDistanceJointMotorSpeed(entity, 50);+physics.setDistanceJointMaxMotorForce(entity, 1000);+```++### Prismatic Joint++```typescript+// Query+const translation = physics.getPrismaticJointTranslation(entity); // current offset (px)+const speed = physics.getPrismaticJointSpeed(entity); // current speed (px/s)+const force = physics.getPrismaticJointMotorForce(entity);++// Modify+physics.enablePrismaticJointSpring(entity, true);+physics.enablePrismaticJointLimit(entity, true);+physics.setPrismaticJointLimits(entity, -100, 100); // lower, upper (px)+physics.enablePrismaticJointMotor(entity, true);+physics.setPrismaticJointMotorSpeed(entity, 80);+physics.setPrismaticJointMaxMotorForce(entity, 500);+```++### Wheel Joint++```typescript+// Query+const torque = physics.getWheelJointMotorTorque(entity);++// Modify+physics.enableWheelJointSpring(entity, true);+physics.enableWheelJointLimit(entity, true);+physics.setWheelJointLimits(entity, -50, 50); // lower, upper (px)+physics.enableWheelJointMotor(entity, true);+physics.setWheelJointMotorSpeed(entity, 60);+physics.setWheelJointMaxMotorTorque(entity, 200);+```+## See Also- [Physics Overview](./index.mdx) — setup, PPU, and body typesdiff --git a/docs/astro/src/content/docs/guides/spine.mdx b/docs/astro/src/content/docs/guides/spine.mdxindex d5d411eb0..2316b0c7e 100644--- a/docs/astro/src/content/docs/guides/spine.mdx+++ b/docs/astro/src/content/docs/guides/spine.mdx@@ -224,6 +224,105 @@ const skins = manager.getSkins(entity); // ['default', 'warrior']const bounds = manager.getBounds(entity); // { x, y, width, height }```+## Animation Queries & Events++*Added in v0.12.0.*++### Animation Queries++Use the `SpineManager` resource to query animation state at runtime:++```typescript+import { SpineManager } from 'esengine/spine';++const manager = app.getResource(SpineManager);++// List all available animations / skins for an entity+const anims = manager.getAnimations(entity); // ['idle', 'run', 'jump']+const skins = manager.getSkins(entity); // ['default', 'warrior']++// Get axis-aligned bounding box+const bounds = manager.getBounds(entity); // { x, y, width, height }+```++### Event Callbacks++Spine emits lifecycle and custom events each frame. The `SpineEvents` resource collects them into a read-only array you can consume in any system:++```typescript+import { defineSystem, addSystem, Res } from 'esengine';+import { SpineEvents } from 'esengine/spine';+import type { SpineEvent } from 'esengine/spine';++addSystem(defineSystem(+ [Res(SpineEvents)],+ (spineEvents) => {+ for (const evt of spineEvents.events) {+ switch (evt.type) {+ case 'complete':+ console.log(`${evt.animationName} finished on track ${evt.track}`);+ break;+ case 'event':+ // Custom event defined in Spine editor+ console.log(`Custom event: ${evt.eventName}`,+ evt.intValue, evt.floatValue, evt.stringValue);+ break;+ }+ }+ }+));+```++Event types: `start`, `interrupt`, `end`, `complete`, `event` (custom).++Each `SpineEvent` contains:++| Field | Type | Description |+|-------|------|-------------|+| `entity` | Entity | The entity that fired the event |+| `type` | SpineEventType | One of the event types listed above |+| `track` | number | Animation track index |+| `animationName` | string | Name of the animation |+| `eventName` | string? | Name of the custom event (only for `event` type) |+| `intValue` | number? | Integer payload (only for `event` type) |+| `floatValue` | number? | Float payload (only for `event` type) |+| `stringValue` | string? | String payload (only for `event` type) |++<Aside type="note">+ Events must be enabled per-entity before they are collected. Call `manager.enableEvents(entity)` once after the Spine asset is loaded.+</Aside>++### Constraint Control++Query and modify IK, transform, and path constraints at runtime:++```typescript+const manager = app.getResource(SpineManager);++// List all constraints on an entity+const constraints = manager.listConstraints(entity);+// { ik: ['aim-ik'], transform: ['hip-transform'], path: ['path-follow'] }++// IK: set target position with mix strength+manager.setIKTarget(entity, 'aim-ik', targetX, targetY, 1.0);++// Transform constraints: read and modify mix values+const tmix = manager.getTransformConstraintMix(entity, 'hip-transform');+// { mixRotate, mixX, mixY, mixScaleX, mixScaleY, mixShearY }+manager.setTransformConstraintMix(entity, 'hip-transform', {+ ...tmix!,+ mixRotate: 0.5,+});++// Path constraints: read and modify mix values+const pmix = manager.getPathConstraintMix(entity, 'path-follow');+// { position, spacing, mixRotate, mixX, mixY }+manager.setPathConstraintMix(entity, 'path-follow', {+ ...pmix!,+ mixRotate: 0.8,+});+```+## Multi-Texture BatchingSpine skeletons that use multiple atlas pages are automatically batched by the renderer. No additional configuration is needed — the C++ backend handles multi-texture setups transparently, keeping draw calls low even with complex multi-atlas characters.diff --git a/docs/astro/src/content/docs/guides/tilemap.mdx b/docs/astro/src/content/docs/guides/tilemap.mdxindex d06cb832b..9e7d31a95 100644--- a/docs/astro/src/content/docs/guides/tilemap.mdx+++ b/docs/astro/src/content/docs/guides/tilemap.mdx@@ -7,6 +7,44 @@ import { Aside } from '@astrojs/starlight/components';The tilemap system loads [Tiled](https://www.mapeditor.org/) maps (`.tmj` / `.json`) and renders tile layers with automatic camera culling, per-layer tint/opacity, parallax scrolling, and collision generation.+## Editor Tilemap Creation++You can create and paint tilemaps entirely within the editor — no external tools required.++### Creating a Tilemap++1. Right-click in the **Hierarchy** panel → **Create** → **Tilemap**+2. In the creation dialog, set the tile size and choose between **Finite** or **Infinite** map mode+3. Assign a tileset image in the **Tilemap** component Inspector++### Tile Palette++The **Tile Palette** panel opens automatically when a tilemap entity is selected. It provides 5 tools:++| Tool | Shortcut | Description |+|------|----------|-------------|+| Brush | B | Paint individual tiles or stamp multi-tile regions |+| Rectangle | R | Drag to fill a rectangular area |+| Bucket | G | Flood-fill connected tiles of the same type |+| Eraser | E | Remove tiles (also available via right-click with any tool) |+| Picker | I | Sample a tile from the map to use as the current brush |++**Stamp selection**: drag in the palette grid to select a multi-tile region, then paint with the brush tool to stamp the entire selection.++**Flip**: use the toolbar buttons to flip tiles horizontally or vertically before painting.++### Infinite Maps++Infinite maps use sparse chunk storage — only painted areas consume memory. The renderer uses 16×16 tile chunks with:++- **Dirty flags**: only chunks with changed tiles rebuild vertices each frame+- **Chunk-level culling**: off-screen chunks are skipped entirely+- **Animated tile tracking**: chunks without animated tiles skip rebuild checks++### Layer Management++Add, remove, rename, and reorder layers via the layer dropdown in the Tile Palette. Each layer has independent tile data and a visibility toggle.+## Quick StartThe simplest way to use tilemaps is through the editor:@@ -172,13 +210,20 @@ Low-level API for runtime tile manipulation:## Editor Workflow+You can create tilemaps in two ways:++**Option A — Paint natively in the editor** (recommended for new projects):+1. Right-click in the Hierarchy → **Create** → **Tilemap** (see [Editor Tilemap Creation](#editor-tilemap-creation) above)+2. Use the **Tile Palette** to paint, erase, and manage layers directly in the Scene View++**Option B — Import from Tiled**:1. Add a **Tilemap** component to an entity in the Hierarchy2. Set the **Source** field to a `.tmj` or `.json` Tiled map file using the asset picker3. The editor automatically loads the map, resolves tileset textures, and renders the layers4. Collision objects are visualized as gizmo overlays<Aside type="tip">- Design your maps in the [Tiled Map Editor](https://www.mapeditor.org/), export as JSON (`.tmj`), and place the file alongside your tileset images in the project assets folder.+ For imported maps, design in the [Tiled Map Editor](https://www.mapeditor.org/), export as JSON (`.tmj`), and place the file alongside your tileset images in the project assets folder.</Aside>## Layer Propertiesdiff --git a/docs/astro/src/content/docs/guides/ui-text.mdx b/docs/astro/src/content/docs/guides/ui-text.mdxindex 160996db9..743a18430 100644--- a/docs/astro/src/content/docs/guides/ui-text.mdx+++ b/docs/astro/src/content/docs/guides/ui-text.mdx@@ -22,6 +22,13 @@ Renders styled text into a `Sprite` texture automatically via `TextPlugin`.| `wordWrap` | boolean | `true` | Enable word wrapping || `overflow` | TextOverflow | `Visible` | `Visible` (0), `Clip` (1), `Ellipsis` (2) || `lineHeight` | number | `1.2` | Line height multiplier |+| `richText` | boolean | `false` | Enable rich text parsing |+| `strokeColor` | Color | `{r:0, g:0, b:0, a:0}` | Text outline color |+| `strokeWidth` | number | `0` | Text outline width in pixels |+| `shadowColor` | Color | `{r:0, g:0, b:0, a:0.5}` | Drop shadow color |+| `shadowBlur` | number | `0` | Shadow blur radius |+| `shadowOffsetX` | number | `0` | Shadow horizontal offset |+| `shadowOffsetY` | number | `0` | Shadow vertical offset |<Aside type="note">You don't need to configure the Sprite manually. `TextPlugin` creates and updates the texture from the Text content.@@ -43,6 +50,44 @@ addSystem(defineSystem());```+### Rich Text++Enable the `richText` property to use inline formatting tags:++```typescript+text.richText = true;+text.content = '<color=#FF0000>Red</color> and <b>bold</b> text';+```++Supported tags:++| Tag | Description | Example |+|-----|-------------|---------|+| `<color=#RRGGBB>` | Text color | `<color=#FF0000>red</color>` |+| `<b>` | Bold | `<b>bold text</b>` |+| `<i>` | Italic | `<i>italic text</i>` |+| `<img src="path"/>` | Inline image | `<img src="icons/star.png"/>` |++Tags can be nested: `<color=#00FF00><b>green bold</b></color>`++### Stroke & Shadow++Add outlines and drop shadows to any text:++```typescript+// Outline+text.strokeColor = { r: 0, g: 0, b: 0, a: 1 };+text.strokeWidth = 2;++// Drop shadow+text.shadowColor = { r: 0, g: 0, b: 0, a: 0.5 };+text.shadowBlur = 4;+text.shadowOffsetX = 2;+text.shadowOffsetY = 2;+```++Stroke and shadow work with both plain text and rich text. In rich text mode, strokes render correctly across all text runs (all strokes are drawn before any fills to prevent visual overlap).+## ImageDisplays images with support for slicing, tiling, and fill modes.diff --git a/docs/astro/src/content/docs/guides/ui-widgets.mdx b/docs/astro/src/content/docs/guides/ui-widgets.mdxindex f97e5434b..3b62101aa 100644--- a/docs/astro/src/content/docs/guides/ui-widgets.mdx+++ b/docs/astro/src/content/docs/guides/ui-widgets.mdx@@ -270,33 +270,74 @@ Scrollable container with momentum and elastic bounce.| `contentWidth` | number | `0` | Total width of scrollable content || `contentHeight` | number | `0` | Total height of scrollable content |-## ListView+## CollectionView-Virtual scrolling for large lists — only visible items are rendered.+Virtual scrolling for large datasets with pluggable layout providers and item pooling. Replaces the previous `ListView`.| Property | Type | Default | Description ||----------|------|---------|-------------|-| `itemHeight` | number | `40` | Fixed item height |-| `itemCount` | number | `0` | Total items |-| `scrollY` | number | `0` | Scroll position |+| `itemCount` | number | `0` | Total items in the dataset |+| `layout` | string | `'linear'` | Layout provider: `'linear'`, `'grid'`, or `'fan'` |+| `virtualized` | boolean | `true` | Enable virtual scrolling (only render visible items) || `overscan` | number | `2` | Extra items above/below viewport |+| `itemPrefab` | string | `''` | Prefab path for item template |++### Layout Providers++| Layout | Description | Key Config |+|--------|-------------|------------|+| **Linear** | Vertical or horizontal list | `direction`, `spacing` |+| **Grid** | Fixed-column grid | `columns`, `rowGap`, `columnGap` |+| **Fan** | Radial fan arrangement | `radius`, `startAngle`, `endAngle` |### Custom Item Renderer-Use `setListViewRenderer()` to define how each list item is populated. The callback receives the item index and the entity to configure:+Use `setCollectionAdapter()` to define how items are created and populated:```typescript-import { setListViewRenderer, Text, Sprite } from 'esengine';+import { setCollectionAdapter, Text } from 'esengine';-setListViewRenderer(listEntity, (index, itemEntity) => {- world.set(itemEntity, Text, { content: `Item ${index}`, fontSize: 16 });+setCollectionAdapter(collectionEntity, {+ makeItem(entity, world) {+ // Called once when a new item entity is created+ world.insert(entity, Text, { content: '', fontSize: 16 });+ },+ bindItem(entity, index, world) {+ // Called each time an item is bound to a data index+ const text = world.get(entity, Text);+ text.content = `Item ${index}`;+ world.set(entity, Text, text);+ },});```-| Parameter | Type | Description |-|-----------|------|-------------|-| `index` | number | 0-based index of the list item |-| `entity` | Entity | The spawned entity for this item — populate it with components |+Items are automatically pooled — recycled items call `bindItem` with new indices, so the number of active entities stays minimal regardless of dataset size.++## Selectable++Enables selection behavior with group-based mutual exclusion. When an entity in a group is selected, all other entities in the same group are automatically deselected.++| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `selected` | boolean | `false` | Selection state |+| `group` | number | `0` | Group ID for mutual exclusion (entities with the same group ID are mutually exclusive) |++Listen for selection changes:++```typescript+addSystem(defineSystem(+ [Res(UIEvents), Query(Selectable, Name)],+ (events, query) => {+ for (const e of events.query('select')) {+ for (const [entity, sel, name] of query) {+ if (entity === e.entity) {+ console.log(name.value, 'selected:', sel.selected);+ }+ }+ }+ }+));+```## TextInputdiff --git a/docs/astro/src/content/docs/zh/changelog-v0120.mdx b/docs/astro/src/content/docs/zh/changelog-v0120.mdxnew file mode 100644index 000000000..12deb300a--- /dev/null+++ b/docs/astro/src/content/docs/zh/changelog-v0120.mdx@@ -0,0 +1,192 @@+---+title: v0.12.0+description: Estella v0.12.0 更新日志+---++import { Aside } from '@astrojs/starlight/components';++<Aside type="tip">+v0.12.0 是一个大版本:完整的 Tilemap 编辑器与绘制工具、富文本描边/阴影、数据绑定系统、全新统一资产架构、CollectionView 虚拟滚动,以及 SDK 架构大幅重构(声明式系统调度)。+</Aside>++## Tilemap 编辑器 v2++全新的 Tilemap 编辑系统,替代之前仅支持导入 Tiled 的工作流。现在可以完全在编辑器内创建、绘制和编辑 Tilemap。++### 调色板与绘制工具++新增 Tile Palette 面板,提供 5 种工具:++- **笔刷**:绘制单个 Tile 或多 Tile 图章区域+- **矩形填充**:拖拽填充矩形区域+- **油漆桶**:洪水填充相连 Tile(BFS,10k Tile 上限)+- **橡皮擦**:清除 Tile,任何工具下右键也可擦除+- **吸管**:从地图采样 Tile 作为当前笔刷++在调色板中拖拽选择图章区域,工具栏按钮支持水平/垂直翻转。++### 无限地图与分块渲染++Tilemap 现在支持无限地图(稀疏分块存储)。渲染器使用 16×16 分块 + 脏标记实现增量顶点重建——每帧只重建脏块和动画块。屏幕外的分块在分块级别被剔除。++### 图层管理++支持添加、删除、重命名和重排序 Tilemap 图层。每个图层独立渲染,有各自的 Tile 数据和可见性开关。++### 原生 Tilemap 创建++从 Hierarchy 右键菜单直接创建 Tilemap,无需外部 Tiled 编辑器。创建对话框中可选无限地图模式。++## 富文本++`Text` 组件现在支持富文本内联格式标签:++- `<color=#FF0000>红色文字</color>` — 彩色文字片段+- `<b>粗体</b>`、`<i>斜体</i>` — 字体样式+- 内联图片 `<img src="资产路径"/>` 标签+- 在 Text 组件上启用 `richText` 开关++解析器基于栈结构,支持逐 run 字体测量和自动换行。++## 文字描边与阴影++`Text` 组件新增属性:++- **描边**:`strokeColor` 和 `strokeWidth` 用于文字轮廓+- **阴影**:`shadowColor`、`shadowBlur`、`shadowOffsetX`、`shadowOffsetY` 用于投影效果++描边渲染先绘制所有描边再绘制所有填充,避免视觉重叠问题。++## 数据绑定++新增 `DataBinding` 组件,将组件属性连接到每帧自动更新的表达式。++- **模板字符串**:`"分数: {Score.value}"` — 引用任意 Resource 或组件属性+- **数学表达式**:`"{Health.current} / {Health.max} * 100"` — 递归下降解析器,无 `eval`(微信兼容)+- **自动类型转换**:string ↔ number 自动处理+- **编辑器 UI**:自定义属性编辑器,下拉选择实体组件的目标属性+- **LRU 表达式缓存**:编译后的表达式被缓存以提升性能++编辑器编辑模式下自动跳过数据绑定求值,防止场景数据损坏。++## 统一资产架构++全新 4 层资产系统替代旧版 `AssetServer`:++- **Assets**:面向用户的 API,提供类型化的 `loadTexture()`、`loadSpine()`、`loadPrefab()` 等+- **Catalog**:地址解析、图集帧查询、标签资产分组、依赖图+- **AssetLoader**:可插拔类型加载器(texture、spine、material、font、audio、tilemap、timeline、animclip、prefab)+- **Backend**:平台特定的数据获取(HTTP、嵌入式、微信)++构建管线生成 manifest catalog 用于可寻址资产加载。已有的 `AssetServer` 消费端已全部迁移。++## CollectionView 与 Selectable++### CollectionView++虚拟滚动系统,替代 `ListView`,支持可插拔的布局提供者:++- **LinearLayout**:垂直或水平列表+- **GridLayout**:固定列数网格,支持行/列间距+- **FanLayout**:扇形排列,可配置角度范围++使用适配器模式 + 对象池实现大数据集的高效渲染。++### Selectable++新增 `Selectable` 组件(C++ 内置),支持组内互斥选择——选中一个实体时同组其他实体自动取消选中。通过 `UIEvents` 派发选中/取消选中事件。++## Spine API 扩展++- **动画查询**:运行时查询当前动画状态、轨道条目和混合信息+- **事件回调**:监听 Spine 动画事件(开始、结束、完成、自定义事件)+- **约束 API**:读取和修改 IK、变换和路径约束+- **编辑器可见性**:SpineAnimation 在编辑器中支持实体可见性切换++## Physics API 扩展++- **Shape Cast**:在物理世界中进行形状投射,可配置距离+- **AABB Overlap**:查询与轴对齐包围盒重叠的所有物体+- **质量数据**:运行时读取和修改物体质量、质心和惯性+- **关节状态**:查询关节反力、锚点位置和当前限制++## 自描述组件元数据++组件元数据(资产字段、颜色字段、实体引用、可动画属性)现由 EHT 代码生成工具从 C++ 注解自动生成:++- `defineBuiltin()` 从生成的 `COMPONENT_META` 读取默认值和字段元数据+- 编辑器 `defineSchema()` 从 SDK 元数据推断 Inspector 属性类型+- 动画目标枚举由 C++ 的 `ES_ANIMATABLE` 注解生成+- Ptr 字段布局由 C++ 结构体定义生成,实现零拷贝 WASM 读取++## 声明式系统调度++### 运行条件++系统可通过 `runIf` 声明执行前置条件:++```typescript+import { playModeOnly } from 'esengine';++app.addSystemToSchedule(Schedule.Update, mySystem, {+ runIf: playModeOnly,+});+```++被跳过的系统零开销——条件在参数解析前检查。++### System 与 Plugin 名称常量++所有系统排序和插件依赖引用均有编译安全的常量:++```typescript+import { SystemLabel, PluginName } from 'esengine';++app.addSystemToSchedule(Schedule.PostUpdate, mySystem, {+ runAfter: [SystemLabel.UILayout],+});+```++### Disabled 标签++新增 `Disabled` 标签组件,排除实体参与处理:++```typescript+import { Disabled } from 'esengine';++world.insert(entity, Disabled, {});+const active = Query(Transform).without(Disabled);+```++### 插件依赖排序++`app.addPlugins()` 对依赖声明执行拓扑排序,允许以任意顺序传入插件。++## 引擎内部改进++- 通过 `corePlugin` 统一引擎初始化,集中管理 ResourceManager 和静态 API 生命周期+- 提取 `App.runFrame_()` 统一 tick/mainLoop 调度逻辑+- O(1) 实体名称索引更新(反向 `entityToName_` Map)+- 使用泛型 `RefMap` 重构 `AssetRefCounter`(175 → 99 行)+- 共享 `ensureUIRenderer()` 工具函数至 `uiHelpers`+- 编辑器 Schema 定义移入插件 `register()` 实现懒初始化+- 拆分 `RenderFrame.cpp` 为 mask 和 submit 文件,提升可维护性+- 去重 `BatchVertex` 和 `packColor` 至共享渲染头文件+- 从 C++ 结构体定义生成 `PTR_LAYOUTS`,替代手写偏移表+- 场景操作使用原子状态交换,防止加载/卸载竞态+- WASM 错误节流,防止 C++ 重复异常导致控制台刷屏++## Bug 修复++- 修复 spawn 回调中实体名称不可用+- 修复场景 sleep/wake 忽略 ShapeRenderer 和 ParticleEmitter 组件+- 修复 App 销毁时输入事件监听器泄漏+- 修复首次编译时 emscripten 配置未自动生成+- 修复 emsdk 安装后缓存文件存在性检查+- 修复编辑器中 Image/UIRenderer 组件的可见性切换+- 修复 Text overflow Visible 模式裁剪到容器而非扩展+- 修复富文本描边渲染顺序(先描边后填充)+- 修复 Play Mode 脚本注入顺序(脚本在场景反序列化前加载)+- 修复脚本重编译失败时组件 Schema 丢失+- 修复进入 Play Mode 前场景未同步+- 修复循环 Schema 导入导致编辑器启动失败diff --git a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh/core-concepts/systems.mdxindex bbe074edf..f5857bf98 100644--- a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx@@ -95,6 +95,51 @@ const renderSystem = defineSystem(`name` 是排序的基础。只有需要参与排序的系统才必须指定 `name`,未指定名称的系统不能被其他系统引用。</Aside>+### 内置系统标签++当需要相对于内置系统排序时,使用 `SystemLabel` 常量代替原始字符串,获得编译期安全检查:++```typescript+import { SystemLabel } from 'esengine';++app.addSystemToSchedule(Schedule.PostUpdate, myLayoutSystem, {+ runAfter: [SystemLabel.UILayout],+ runBefore: [SystemLabel.UIRenderOrder],+});+```++可用标签:`UILayout`、`UILayoutLate`、`UIRenderOrder`、`UIInteraction`、`Button`、`ScrollView`、`CollectionView`、`ListView`、`Text`、`Image`、`Focus`、`Tween`。++类似地,声明插件依赖时使用 `PluginName` 常量:++```typescript+import { PluginName } from 'esengine';++class MyUIPlugin implements Plugin {+ dependencies = [PluginName.UILayout];+}+```++## 运行条件++系统可以通过 `runIf` 声明前置条件。条件在系统执行前求值——如果返回 `false`,系统被完全跳过,零开销:++```typescript+import { playModeOnly } from 'esengine';++app.addSystemToSchedule(Schedule.Update, gameplaySystem, {+ runIf: playModeOnly,+});+```++`playModeOnly` 是内置条件,在编辑器外运行时或编辑器 Play Mode 中返回 `true`。你也可以编写自定义条件——任何 `() => boolean` 函数都可以:++```typescript+app.addSystemToSchedule(Schedule.Update, debugSystem, {+ runIf: () => app.getResource(DebugConfig).enabled,+});+```+## 系统参数### Commandsdiff --git a/docs/astro/src/content/docs/zh/guides/data-binding.mdx b/docs/astro/src/content/docs/zh/guides/data-binding.mdxnew file mode 100644index 000000000..91dc233d0--- /dev/null+++ b/docs/astro/src/content/docs/zh/guides/data-binding.mdx@@ -0,0 +1,103 @@+---+title: 数据绑定+description: Estella 中 UI 组件的响应式数据绑定+---++import { Aside } from '@astrojs/starlight/components';++**DataBinding** 组件将组件属性连接到每帧自动更新的表达式。用它来在 UI 文字中显示资源值、用游戏状态驱动进度条,或创建响应式 UI 而无需编写自定义系统。++## 快速开始++1. 给已有 `Text` 组件的实体添加 `DataBinding` 组件+2. 将 `source` 设为资源名称(如 `'GameState'`)+3. 添加绑定条目,将目标属性映射到表达式++在编辑器 Inspector 中,DataBinding 区域提供可视化编辑器,支持下拉选择目标属性。++## 组件++| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `source` | string | `''` | 表达式查找的默认资源名称 |+| `bindings` | BindingEntry[] | `[]` | 属性到表达式的映射数组 |++每个 `BindingEntry` 包含:++| 字段 | 类型 | 说明 |+|------|------|------|+| `target` | string | 目标属性路径(如 `'Text.content'`、`'ProgressBar.value'`) |+| `expression` | string | 要求值的表达式(模板或数学表达式) |++## 表达式++### 模板字符串++用花括号引用资源或组件属性:++```+分数: {GameState.score}+HP: {Health.current} / {Health.max}+```++表达式系统通过 SDK 资源注册表查找 `{资源名.属性}` 进行解析。++### 数学表达式++在模板中使用算术运算计算值:++```+{Health.current} / {Health.max}+{Score.value} * 10 + {Bonus.multiplier}+```++支持的运算符:`+`、`-`、`*`、`/`、`(`、`)`。解析器使用递归下降算法——不使用 `eval()`,因此在微信小游戏等受限环境中安全可用。++### 自动类型转换++- 目标为 `string` 属性(如 `Text.content`)时,结果转为字符串+- 目标为 `number` 属性(如 `ProgressBar.value`)时,结果解析为数字++## 示例:分数显示++定义一个资源并绑定到 Text 实体:++```typescript+import { defineResource, addStartupSystem, defineSystem, Commands } from 'esengine';++const GameState = defineResource({ score: 0, level: 1 }, 'GameState');++addStartupSystem(defineSystem([Commands()], (cmds) => {+ cmds.insertResource(GameState, { score: 0, level: 1 });+}));+```++在编辑器中,给分数文字实体添加 `DataBinding`:++- **Source**:`GameState`+- **Binding**:target = `Text.content`,expression = `分数: {GameState.score}`++文字会在 `GameState.score` 变化时自动更新——无需自定义系统。++## 示例:血条++将 `ProgressBar.value` 绑定到计算表达式:++- **Binding**:target = `ProgressBar.value`,expression = `{Health.current} / {Health.max}`++进度条会响应式地跟踪生命值比例。++<Aside type="note">+数据绑定求值在编辑器编辑模式下自动跳过,防止场景数据损坏。绑定仅在 Play Mode 和运行时执行。+</Aside>++## 性能++- 编译后的表达式缓存在 LRU 缓存中——重复求值复用编译结果+- `DataBindingPlugin` 在 `Schedule.PreUpdate` 中运行,先于文本和图片系统,确保绑定值在渲染前已更新++## 下一步++- [文本与图片](/docs/zh/guides/ui-text/) — 文本渲染和图片显示+- [UI 控件](/docs/zh/guides/ui-widgets/) — 滑块、进度条等控件+- [资源](/docs/zh/core-concepts/resources/) — 定义和使用全局资源diff --git a/docs/astro/src/content/docs/zh/guides/physics/api.mdx b/docs/astro/src/content/docs/zh/guides/physics/api.mdxindex b31ed71b1..b45e98e53 100644--- a/docs/astro/src/content/docs/zh/guides/physics/api.mdx+++ b/docs/astro/src/content/docs/zh/guides/physics/api.mdx@@ -33,12 +33,155 @@ addSystem(defineSystem(| `applyAngularImpulse(entity, impulse)` | 施加瞬时角冲量 || `setGravity(gravity)` | 运行时修改世界重力 || `getGravity()` | 获取当前世界重力(Vec2) |+| `shapeCastCircle(center, radius, translation, maskBits?)` | 扫过圆形并返回碰撞结果 |+| `shapeCastBox(center, halfExtents, angle, translation, maskBits?)` | 扫过带旋转矩形并返回碰撞结果 |+| `shapeCastCapsule(center1, center2, radius, translation, maskBits?)` | 扫过胶囊体并返回碰撞结果 |+| `overlapAABB(min, max, maskBits?)` | 查询与 AABB 重叠的实体 |+| `getMass(entity)` | 获取刚体质量(kg) |+| `getInertia(entity)` | 获取刚体转动惯量 |+| `getCenterOfMass(entity)` | 获取刚体质心位置(Vec2,像素) |+| `getMassData(entity)` | 获取质量、惯量和质心 |## 力 vs 冲量- **力**每帧持续施加。效果取决于刚体质量,在物理时间步中积分。适用于持续推力(如火箭推进、风力)。- **冲量**瞬间施加。直接改变速度,与帧率无关。适用于一次性事件(如跳跃、爆炸击退)。+## 形状投射++*v0.12.0 新增。*++形状投射沿平移向量扫过一个形状并返回所有碰撞。类似射线检测但有体积,适用于判断角色能否通过缝隙或预测沿路径的碰撞。++每个方法返回 `ShapeCastHit[]`,结构与 `RaycastHit` 相同:++| 字段 | 类型 | 说明 |+|------|------|------|+| `entity` | Entity | 被碰撞的实体 |+| `point` | Vec2 | 世界像素坐标的接触点 |+| `normal` | Vec2 | 接触处的表面法线 |+| `fraction` | number | 平移距离上的碰撞分数(0..1) |++```typescript+// 圆形投射:从 center 沿 translation 扫过圆形+const hits = physics.shapeCastCircle(+ center, // Vec2 — 起点+ radius, // number — 圆形半径(像素)+ translation, // Vec2 — 扫过方向与距离(像素)+ maskBits, // number — 碰撞层掩码(默认 0xFFFF)+);++// 矩形投射:扫过带旋转的矩形+const hits = physics.shapeCastBox(+ center, // Vec2 — 矩形中心+ halfExtents, // Vec2 — 半宽/半高(像素)+ angle, // number — 旋转角度(弧度)+ translation, // Vec2 — 扫过向量(像素)+ maskBits,+);++// 胶囊投射:扫过由两个圆心 + 半径定义的胶囊体+const hits = physics.shapeCastCapsule(+ center1, // Vec2 — 第一个圆心+ center2, // Vec2 — 第二个圆心+ radius, // number — 胶囊半径(像素)+ translation, // Vec2 — 扫过向量(像素)+ maskBits,+);+```++## AABB 重叠查询++*v0.12.0 新增。*++查询所有碰撞体与轴对齐包围盒重叠的实体:++```typescript+const entities = physics.overlapAABB(+ { x: 100, y: 100 }, // 最小角(像素)+ { x: 300, y: 300 }, // 最大角(像素)+ 0xFFFF, // 碰撞层掩码+);+for (const entity of entities) {+ // entity 与 AABB 重叠+}+```++返回去重后的 `Entity[]`。++## 质量数据++*v0.12.0 新增。*++在运行时读取刚体的质量属性:++```typescript+// 单独查询+const mass = physics.getMass(entity); // number(kg)+const inertia = physics.getInertia(entity); // number(kg*px^2)+const center = physics.getCenterOfMass(entity); // Vec2(像素)++// 一次获取全部+const data = physics.getMassData(entity);+// { mass: number, inertia: number, centerOfMass: Vec2 }+```++## 关节状态查询++*v0.12.0 新增。*++Distance、Prismatic、Wheel 关节的运行时状态控制。++### Distance 关节++```typescript+// 查询+const length = physics.getDistanceJointLength(entity); // 静止长度(px)+const current = physics.getDistanceJointCurrentLength(entity); // 当前长度(px)+const force = physics.getDistanceJointMotorForce(entity);++// 修改+physics.setDistanceJointLength(entity, 200);+physics.enableDistanceJointSpring(entity, true);+physics.enableDistanceJointLimit(entity, true);+physics.setDistanceJointLimits(entity, 100, 300); // 最小、最大(px)+physics.enableDistanceJointMotor(entity, true);+physics.setDistanceJointMotorSpeed(entity, 50);+physics.setDistanceJointMaxMotorForce(entity, 1000);+```++### Prismatic 关节++```typescript+// 查询+const translation = physics.getPrismaticJointTranslation(entity); // 当前偏移(px)+const speed = physics.getPrismaticJointSpeed(entity); // 当前速度(px/s)+const force = physics.getPrismaticJointMotorForce(entity);++// 修改+physics.enablePrismaticJointSpring(entity, true);+physics.enablePrismaticJointLimit(entity, true);+physics.setPrismaticJointLimits(entity, -100, 100); // 下限、上限(px)+physics.enablePrismaticJointMotor(entity, true);+physics.setPrismaticJointMotorSpeed(entity, 80);+physics.setPrismaticJointMaxMotorForce(entity, 500);+```++### Wheel 关节++```typescript+// 查询+const torque = physics.getWheelJointMotorTorque(entity);++// 修改+physics.enableWheelJointSpring(entity, true);+physics.enableWheelJointLimit(entity, true);+physics.setWheelJointLimits(entity, -50, 50); // 下限、上限(px)+physics.enableWheelJointMotor(entity, true);+physics.setWheelJointMotorSpeed(entity, 60);+physics.setWheelJointMaxMotorTorque(entity, 200);+```+## 参见- [物理概述](./index.mdx) — 设置、PPU 与刚体类型diff --git a/docs/astro/src/content/docs/zh/guides/spine.mdx b/docs/astro/src/content/docs/zh/guides/spine.mdxindex 5af80b856..bd5544791 100644--- a/docs/astro/src/content/docs/zh/guides/spine.mdx+++ b/docs/astro/src/content/docs/zh/guides/spine.mdx@@ -224,6 +224,105 @@ const skins = manager.getSkins(entity); // ['default', 'warrior']const bounds = manager.getBounds(entity); // { x, y, width, height }```+## 动画查询与事件++*v0.12.0 新增。*++### 动画查询++通过 `SpineManager` 资源在运行时查询动画状态:++```typescript+import { SpineManager } from 'esengine/spine';++const manager = app.getResource(SpineManager);++// 列出实体的所有可用动画 / 皮肤+const anims = manager.getAnimations(entity); // ['idle', 'run', 'jump']+const skins = manager.getSkins(entity); // ['default', 'warrior']++// 获取轴对齐包围盒+const bounds = manager.getBounds(entity); // { x, y, width, height }+```++### 事件回调++Spine 每帧会发出生命周期事件和自定义事件。`SpineEvents` 资源会将它们收集到一个只读数组中,可在任何系统中消费:++```typescript+import { defineSystem, addSystem, Res } from 'esengine';+import { SpineEvents } from 'esengine/spine';+import type { SpineEvent } from 'esengine/spine';++addSystem(defineSystem(+ [Res(SpineEvents)],+ (spineEvents) => {+ for (const evt of spineEvents.events) {+ switch (evt.type) {+ case 'complete':+ console.log(`${evt.animationName} 在 track ${evt.track} 上播放完成`);+ break;+ case 'event':+ // 在 Spine 编辑器中定义的自定义事件+ console.log(`自定义事件: ${evt.eventName}`,+ evt.intValue, evt.floatValue, evt.stringValue);+ break;+ }+ }+ }+));+```++事件类型:`start`、`interrupt`、`end`、`complete`、`event`(自定义)。++每个 `SpineEvent` 包含:++| 字段 | 类型 | 说明 |+|------|------|------|+| `entity` | Entity | 触发事件的实体 |+| `type` | SpineEventType | 上述事件类型之一 |+| `track` | number | 动画轨道索引 |+| `animationName` | string | 动画名 |+| `eventName` | string? | 自定义事件名(仅 `event` 类型) |+| `intValue` | number? | 整数载荷(仅 `event` 类型) |+| `floatValue` | number? | 浮点载荷(仅 `event` 类型) |+| `stringValue` | string? | 字符串载荷(仅 `event` 类型) |++<Aside type="note">+ 需要先为实体启用事件才能收集。在 Spine 资源加载完成后调用一次 `manager.enableEvents(entity)`。+</Aside>++### 约束控制++在运行时查询和修改 IK、变换、路径约束:++```typescript+const manager = app.getResource(SpineManager);++// 列出实体上的所有约束+const constraints = manager.listConstraints(entity);+// { ik: ['aim-ik'], transform: ['hip-transform'], path: ['path-follow'] }++// IK:设置目标位置和混合强度+manager.setIKTarget(entity, 'aim-ik', targetX, targetY, 1.0);++// 变换约束:读取和修改混合值+const tmix = manager.getTransformConstraintMix(entity, 'hip-transform');+// { mixRotate, mixX, mixY, mixScaleX, mixScaleY, mixShearY }+manager.setTransformConstraintMix(entity, 'hip-transform', {+ ...tmix!,+ mixRotate: 0.5,+});++// 路径约束:读取和修改混合值+const pmix = manager.getPathConstraintMix(entity, 'path-follow');+// { position, spacing, mixRotate, mixX, mixY }+manager.setPathConstraintMix(entity, 'path-follow', {+ ...pmix!,+ mixRotate: 0.8,+});+```+## 多纹理批处理使用多个图集页的 Spine 骨骼会被渲染器自动批处理。无需额外配置 — C++ 后端透明地处理多纹理情况,即使是复杂的多图集角色也能保持较低的 draw call。diff --git a/docs/astro/src/content/docs/zh/guides/tilemap.mdx b/docs/astro/src/content/docs/zh/guides/tilemap.mdxindex ade1efcf1..1444926c5 100644--- a/docs/astro/src/content/docs/zh/guides/tilemap.mdx+++ b/docs/astro/src/content/docs/zh/guides/tilemap.mdx@@ -7,6 +7,44 @@ import { Aside } from '@astrojs/starlight/components';瓦片地图系统加载 [Tiled](https://www.mapeditor.org/) 地图(`.tmj` / `.json`),渲染瓦片图层,支持自动相机裁剪、逐图层着色/透明度、视差滚动和碰撞生成。+## 编辑器瓦片地图创建++你可以完全在编辑器内创建和绘制瓦片地图,无需任何外部工具。++### 创建瓦片地图++1. 在 **Hierarchy** 面板中右键 → **创建** → **Tilemap**+2. 在创建对话框中设置瓦片大小,选择 **有限** 或 **无限** 地图模式+3. 在 **Tilemap** 组件 Inspector 中分配 tileset 图片++### 瓦片调色板++选中瓦片地图实体时,**瓦片调色板** 面板会自动打开。它提供 5 种工具:++| 工具 | 快捷键 | 说明 |+|------|--------|------|+| 画笔 | B | 绘制单个瓦片或印章多瓦片区域 |+| 矩形 | R | 拖拽填充矩形区域 |+| 油漆桶 | G | 洪水填充相同类型的相邻瓦片 |+| 橡皮擦 | E | 擦除瓦片(任何工具下右键也可擦除) |+| 吸管 | I | 从地图中采样瓦片作为当前画笔 |++**印章选择**:在调色板网格中拖拽选择多瓦片区域,然后使用画笔工具印章绘制整个选区。++**翻转**:使用工具栏按钮在绘制前水平或垂直翻转瓦片。++### 无限地图++无限地图使用稀疏块存储——只有绘制过的区域占用内存。渲染器使用 16×16 瓦片块,具有以下特性:++- **脏标记**:只有瓦片发生变化的块才在每帧重建顶点+- **块级裁剪**:屏幕外的块完全跳过+- **动画瓦片追踪**:不包含动画瓦片的块跳过重建检查++### 图层管理++通过瓦片调色板中的图层下拉菜单添加、删除、重命名和重新排序图层。每个图层拥有独立的瓦片数据和可见性开关。+## 快速开始最简单的使用方式是通过编辑器:@@ -172,13 +210,20 @@ const entities = loadTiledMap(world, mapData, textureHandles, {## 编辑器工作流+你可以通过两种方式创建瓦片地图:++**方式 A — 在编辑器中原生绘制**(推荐新项目使用):+1. 在 Hierarchy 中右键 → **创建** → **Tilemap**(参见上方[编辑器瓦片地图创建](#编辑器瓦片地图创建))+2. 使用 **瓦片调色板** 直接在 Scene View 中绘制、擦除和管理图层++**方式 B — 从 Tiled 导入**:1. 在 Hierarchy 中为实体添加 **Tilemap** 组件2. 使用资源选择器将 **Source** 字段设置为 `.tmj` 或 `.json` Tiled 地图文件3. 编辑器自动加载地图、解析 tileset 纹理并渲染图层4. 碰撞对象显示为 Gizmo 叠加层<Aside type="tip">- 在 [Tiled Map Editor](https://www.mapeditor.org/) 中设计地图,导出为 JSON(`.tmj`),将文件和 tileset 图片放在项目资源文件夹中。+ 导入地图时,在 [Tiled Map Editor](https://www.mapeditor.org/) 中设计地图,导出为 JSON(`.tmj`),将文件和 tileset 图片放在项目资源文件夹中。</Aside>## 图层属性diff --git a/docs/astro/src/content/docs/zh/guides/ui-text.mdx b/docs/astro/src/content/docs/zh/guides/ui-text.mdxindex aa9668a0b..7503c8496 100644--- a/docs/astro/src/content/docs/zh/guides/ui-text.mdx+++ b/docs/astro/src/content/docs/zh/guides/ui-text.mdx@@ -22,6 +22,13 @@ import { Aside } from '@astrojs/starlight/components';| `wordWrap` | boolean | `true` | 启用自动换行 || `overflow` | TextOverflow | `Visible` | `Visible` (0)、`Clip` (1)、`Ellipsis` (2) || `lineHeight` | number | `1.2` | 行高倍率 |+| `richText` | boolean | `false` | 启用富文本解析 |+| `strokeColor` | Color | `{r:0, g:0, b:0, a:0}` | 文本描边颜色 |+| `strokeWidth` | number | `0` | 文本描边宽度(像素) |+| `shadowColor` | Color | `{r:0, g:0, b:0, a:0.5}` | 投影颜色 |+| `shadowBlur` | number | `0` | 投影模糊半径 |+| `shadowOffsetX` | number | `0` | 投影水平偏移 |+| `shadowOffsetY` | number | `0` | 投影垂直偏移 |<Aside type="note">无需手动配置 Sprite。`TextPlugin` 会自动从 Text 内容创建和更新纹理。@@ -43,6 +50,44 @@ addSystem(defineSystem());```+### 富文本++启用 `richText` 属性以使用内联格式标签:++```typescript+text.richText = true;+text.content = '<color=#FF0000>红色</color>和<b>粗体</b>文本';+```++支持的标签:++| 标签 | 说明 | 示例 |+|------|------|------|+| `<color=#RRGGBB>` | 文本颜色 | `<color=#FF0000>红色</color>` |+| `<b>` | 粗体 | `<b>粗体文本</b>` |+| `<i>` | 斜体 | `<i>斜体文本</i>` |+| `<img src="path"/>` | 内联图片 | `<img src="icons/star.png"/>` |++标签可以嵌套:`<color=#00FF00><b>绿色粗体</b></color>`++### 描边与投影++为任意文本添加描边和投影效果:++```typescript+// 描边+text.strokeColor = { r: 0, g: 0, b: 0, a: 1 };+text.strokeWidth = 2;++// 投影+text.shadowColor = { r: 0, g: 0, b: 0, a: 0.5 };+text.shadowBlur = 4;+text.shadowOffsetX = 2;+text.shadowOffsetY = 2;+```++描边和投影同时适用于普通文本和富文本。在富文本模式下,描边能够正确渲染所有文本片段(所有描边在填充之前绘制,以防止视觉重叠)。+## Image显示图片,支持切片、平铺和填充模式。diff --git a/docs/astro/src/content/docs/zh/guides/ui-widgets.mdx b/docs/astro/src/content/docs/zh/guides/ui-widgets.mdxindex 592aab163..b196f1b67 100644--- a/docs/astro/src/content/docs/zh/guides/ui-widgets.mdx+++ b/docs/astro/src/content/docs/zh/guides/ui-widgets.mdx@@ -270,33 +270,74 @@ addSystem(defineSystem(| `contentWidth` | number | `0` | 可滚动内容总宽度(由插件自动计算) || `contentHeight` | number | `0` | 可滚动内容总高度(由插件自动计算) |-## ListView+## CollectionView-大列表虚拟滚动——仅渲染可见项目。+大数据集虚拟滚动,支持可插拔的布局提供者和对象池。替代之前的 `ListView`。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `itemHeight` | number | `40` | 固定项目高度 |-| `itemCount` | number | `0` | 总项目数 |-| `scrollY` | number | `0` | 滚动位置 |+| `itemCount` | number | `0` | 数据集总项目数 |+| `layout` | string | `'linear'` | 布局提供者:`'linear'`、`'grid'` 或 `'fan'` |+| `virtualized` | boolean | `true` | 启用虚拟滚动(仅渲染可见项目) || `overscan` | number | `2` | 视口上下额外渲染的项目数 |+| `itemPrefab` | string | `''` | 项目模板的 Prefab 路径 |++### 布局提供者++| 布局 | 说明 | 关键配置 |+|------|------|----------|+| **Linear** | 垂直或水平列表 | `direction`、`spacing` |+| **Grid** | 固定列数网格 | `columns`、`rowGap`、`columnGap` |+| **Fan** | 扇形排列 | `radius`、`startAngle`、`endAngle` |### 自定义项目渲染器-使用 `setListViewRenderer()` 定义每个列表项的填充方式。回调接收项目索引和要配置的实体:+使用 `setCollectionAdapter()` 定义项目的创建和填充方式:```typescript-import { setListViewRenderer, Text, Sprite } from 'esengine';+import { setCollectionAdapter, Text } from 'esengine';-setListViewRenderer(listEntity, (index, itemEntity) => {- world.set(itemEntity, Text, { content: `Item ${index}`, fontSize: 16 });+setCollectionAdapter(collectionEntity, {+ makeItem(entity, world) {+ // 新项目实体创建时调用一次+ world.insert(entity, Text, { content: '', fontSize: 16 });+ },+ bindItem(entity, index, world) {+ // 每次项目绑定到数据索引时调用+ const text = world.get(entity, Text);+ text.content = `Item ${index}`;+ world.set(entity, Text, text);+ },});```-| 参数 | 类型 | 说明 |-|------|------|------|-| `index` | number | 列表项的 0 基索引 |-| `entity` | Entity | 该列表项的实体——用组件填充它 |+项目自动池化——回收的项目会以新索引调用 `bindItem`,无论数据集多大,活跃实体数都保持最小。++## Selectable++实现选择行为,支持组内互斥。同一组中的一个实体被选中时,其他实体自动取消选中。++| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `selected` | boolean | `false` | 选中状态 |+| `group` | number | `0` | 互斥组 ID(相同组 ID 的实体互斥) |++监听选择变化:++```typescript+addSystem(defineSystem(+ [Res(UIEvents), Query(Selectable, Name)],+ (events, query) => {+ for (const e of events.query('select')) {+ for (const [entity, sel, name] of query) {+ if (entity === e.entity) {+ console.log(name.value, '选中:', sel.selected);+ }+ }+ }+ }+));+```## TextInput