A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
docs: update v0.6.0 documentation across all pages
esengine534895cdf0a0
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex dfc3ce3c0..54de442ea 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -55,6 +55,8 @@ export default defineConfig({{ label: 'Systems', translations: { 'zh-CN': '系统' }, slug: 'core-concepts/systems' },{ label: 'Queries', translations: { 'zh-CN': '查询' }, slug: 'core-concepts/queries' },{ label: 'Resources', translations: { 'zh-CN': '资源' }, slug: 'core-concepts/resources' },+ { label: 'Change Detection', translations: { 'zh-CN': '变更检测' }, slug: 'core-concepts/change-detection' },+ { label: 'Events', translations: { 'zh-CN': '事件' }, slug: 'core-concepts/events' },],},{@@ -106,6 +108,7 @@ export default defineConfig({label: 'Changelog',translations: { 'zh-CN': '更新日志' },items: [+ { label: 'v0.6.0', slug: 'changelog-v060' },{ label: 'v0.5.1', slug: 'changelog-v051' },{ label: 'v0.5.0', slug: 'changelog-v050' },{ label: 'v0.4.3', slug: 'changelog-v043' },diff --git a/docs/astro/src/content/docs/changelog-v060.mdx b/docs/astro/src/content/docs/changelog-v060.mdxnew file mode 100644index 000000000..a61375062--- /dev/null+++ b/docs/astro/src/content/docs/changelog-v060.mdx@@ -0,0 +1,101 @@+---+title: v0.6.0+description: ESEngine v0.6.0 release notes+---++import { Aside } from '@astrojs/starlight/components';++<Aside type="tip">+v0.6.0 is a major engine update: UI layout migrated to C++/WASM, Transform unified into a single component, ECS registry rebuilt with generational handles, and new systems for change detection, events, asset importing, and live-edit play mode.+</Aside>++## UI System Overhaul++- Migrated UI layout computation from TypeScript to C++/WASM for significantly improved performance+- Added new UI components: ProgressBar, Dropdown, Toggle, and quick-create templates+- Rewrote UI framework architecture with extracted `walkParentChain` helper for cleaner hierarchy traversal+- Enhanced layout system with proper anchor mode handling and slider drag fixes+- Editor schemas auto-generated for all UI components++## ECS Core Enhancements++### Unified Transform++- Merged `LocalTransform` and `WorldTransform` into a single `Transform` component+- Simplifies the API — no more juggling two separate transform types++### Generational Handles++- Rebuilt ECS registry with flat vector pools and generational entity handles+- Eliminates stale entity reference bugs and improves cache locality+- Significant iteration performance improvement for large entity counts++### Change Detection & Events++- Added ECS change detection system for tracking component modifications+- New event system for decoupled entity-to-entity and system-to-system communication++## Live-Edit Play Mode++- Full live editing of entity properties while the game is running+- Changes in the editor are reflected in real-time in the running game+- Shared Scene/Game view using an offscreen WebGL canvas (no more iframe duplication)+- Replaced `RuntimeSyncService` with lightweight inline renderer sync++## Asset Importer Pipeline++- New asset importer system with per-platform override support+- Define platform-specific asset processing rules (e.g., different texture compression for WeChat vs Playable)+- Integrated into the existing build pipeline++## Multi-Window Support++- Detach any editor panel into a separate OS window+- Independent window lifecycle with full panel functionality preserved+- Panels can be re-docked back into the main window++## Editor Improvements++- Compound entity creation (e.g., Button, Slider) auto-selects the root entity in hierarchy+- Per-component enabled/disabled toggle in Inspector+- Live preview toggle in Scene View settings+- Scene View zoom-to-cursor fix and overlay scale correction+- Removed addressable groups from bottom dock panel+- Improved dropdown placeholder rendering and inspector schema handling++## Performance++- **ECS Registry**: Flat vector pools replace sparse sets, ~2x faster iteration on views+- **TransformSystem**: Fused double iteration into single pass with nameLen bounds check+- **Root Transform**: Fast path skips matrix multiplication for root entities+- **GL Flush**: Removed redundant GL state calls in render flush++## SDK & Runtime++- Enhanced `World.query()` API with improved ergonomics+- `App.tick()` lifecycle improvements and scene asset lifecycle management+- Component registry consolidation and DRY scene loading+- System ordering fixes and toggle performance improvement (O(n²) → O(n))++## Platform Fixes++- **WeChat MiniGame**: Use `wx.getSystemInfoSync` for correct safe area insets+- **Playable Ads**: Resolved entity reference warnings in builds and prefab instantiation+- **Native**: Guard stencil GL calls with `ES_PLATFORM_WEB` for native build compatibility++## Bug Fixes++- Fix text disappearing after entity creation due to C++ entity ID recycling+- Fix UIRect layout for mixed anchor modes+- Fix zero UIRect size when fill anchors collapse at slider minimum+- Fix slider fill position and progress bar layout sync+- Fix progress bar fill positioning and UIRect move gizmo support+- Fix input touch ID tracking and spine cache key collision+- Fix dropdown placeholder, color NaN values, and texture handle guards+- Fix renderer correctness issues and reduce draw call overhead++## Other++- Upgraded spine-runtimes to 4.2.104+- Added SDK integration tests for UI, layout, slider, and app tick+- Updated `eht.py` codegen for vector types and dual outputdiff --git a/docs/astro/src/content/docs/core-concepts/change-detection.mdx b/docs/astro/src/content/docs/core-concepts/change-detection.mdxnew file mode 100644index 000000000..0c06a70dd--- /dev/null+++ b/docs/astro/src/content/docs/core-concepts/change-detection.mdx@@ -0,0 +1,174 @@+---+title: Change Detection+description: Reacting to component additions, modifications, and removals in ESEngine+---++import { Aside } from '@astrojs/starlight/components';++Change detection lets systems react only when components are added, modified, or removed — instead of processing every entity every frame. This is essential for performance when you have many entities but only a few change per frame.++## Added++`Added()` filters a query to only yield entities where a component was added since the system last ran:++```typescript+import { defineSystem, addSystem, Query, Added, Transform, Sprite } from 'esengine';++addSystem(defineSystem(+ [Query(Added(Sprite), Transform)],+ (query) => {+ for (const [entity, sprite, transform] of query) {+ // Only runs for entities that just received a Sprite+ console.log('New sprite at', transform.position.x, transform.position.y);+ }+ }+));+```++An entity appears in an `Added` query in the frame it was spawned or the frame a component was inserted. It won't appear again unless the component is removed and re-added.++## Changed++`Changed()` filters a query to only yield entities where a component value was modified:++```typescript+import { defineSystem, addSystem, Query, Changed, Mut, Health, Sprite } from 'esengine';++const healthBarSystem = defineSystem(+ [Query(Changed(Health), Mut(Sprite))],+ (query) => {+ for (const [entity, health, sprite] of query) {+ // Only runs when Health was actually modified+ sprite.size.x = (health.current / health.max) * 100;+ }+ }+);+```++A component is marked as changed whenever `world.insert()`, `world.set()`, or `Commands.insert()` is called on it — even if the new value is identical to the old one.++<Aside type="tip">+`Added` is a subset of `Changed`. When a component is first added, it counts as both added *and* changed.+</Aside>++## Removed++`Removed()` is a standalone query type (not a filter on `Query`). It yields the entity IDs of entities that had a specific component removed:++```typescript+import { defineSystem, addSystem, Removed, Commands, Health } from 'esengine';++addSystem(defineSystem(+ [Removed(Health), Commands()],+ (removed, cmds) => {+ for (const entity of removed) {+ // Health was removed — despawn the entity+ cmds.despawn(entity);+ }+ }+));+```++<Aside type="caution">+`Removed` only gives you the entity ID, not the component data (the data is already gone). If you need the old value, copy it elsewhere before removing.+</Aside>++Removed entries are kept in a buffer for 2 ticks, then automatically cleaned up. This means a system running every frame will always see removals in time.++## Combining Filters++You can mix `Added`, `Changed`, and `Removed` in the same system:++```typescript+import { defineSystem, Query, Added, Changed, Removed, Mut, Transform, Velocity, Health, Commands } from 'esengine';++defineSystem(+ [+ Query(Added(Velocity), Transform),+ Query(Changed(Health), Mut(Sprite)),+ Removed(Health),+ Commands(),+ ],+ (newVelocities, damagedEntities, removedHealth, cmds) => {+ for (const [entity, velocity, transform] of newVelocities) {+ // Initialize movement+ }++ for (const [entity, health, sprite] of damagedEntities) {+ // Update health bar+ }++ for (const entity of removedHealth) {+ cmds.despawn(entity);+ }+ }+);+```++Change filters also work with `.with()` and `.without()`:++```typescript+Query(Changed(Health)).with(Player) // Changed health on players only+Query(Added(Sprite)).without(UIRect) // New sprites that aren't UI elements+```++## How It Works++ESEngine uses **tick-based tracking**:++1. The world maintains a global tick counter that increments once per frame+2. Every component insertion or modification records the current tick+3. Every system records the tick of its last run+4. When a system runs, change filters compare: *component tick > system's last-run tick*++This means:+- A system that runs every frame sees changes from the previous frame+- A system that skips frames (e.g., via `wrapSceneSystem`) will see all accumulated changes since it last ran+- No manual "dirty flag" management is needed — it's fully automatic++## Common Patterns++### Sync Transform to Render Position++```typescript+const syncRenderSystem = defineSystem(+ [Query(Changed(Transform), Sprite)],+ (query) => {+ for (const [entity, transform, sprite] of query) {+ updateRenderPosition(entity, transform.position);+ }+ }+);+```++### React to Spawns++```typescript+const onSpawnSystem = defineSystem(+ [Query(Added(Transform), Sprite)],+ (query) => {+ for (const [entity, transform, sprite] of query) {+ playSpawnAnimation(entity);+ }+ }+);+```++### Cleanup on Component Removal++```typescript+const cleanupSystem = defineSystem(+ [Removed(RigidBody)],+ (removed) => {+ for (const entity of removed) {+ destroyPhysicsBody(entity);+ }+ }+);+```++## Next Steps++- [Events](/microes/core-concepts/events/) — send and receive messages between systems+- [Queries](/microes/core-concepts/queries/) — basic query filters and iteration+- [Systems](/microes/core-concepts/systems/) — system definition and schedulingdiff --git a/docs/astro/src/content/docs/core-concepts/components.mdx b/docs/astro/src/content/docs/core-concepts/components.mdxindex 80f0d5a14..a1dedda90 100644--- a/docs/astro/src/content/docs/core-concepts/components.mdx+++ b/docs/astro/src/content/docs/core-concepts/components.mdx@@ -11,7 +11,7 @@ Components are data attached to entities. In ESEngine, you **define** componentsBuiltin components are always available in the editor. They are backed by the C++ backend.-### LocalTransform+### TransformPosition, rotation, and scale of an entity.@@ -21,9 +21,13 @@ Position, rotation, and scale of an entity.| `rotation` | Quat | Quaternion `{ w, x, y, z }` || `scale` | Vec3 | Scale factor `{ x, y, z }` |+<Aside type="note">+ In previous versions, `LocalTransform` and `WorldTransform` were separate components. They have been unified into a single `Transform`. The old names still work as aliases but `Transform` is the recommended import.+</Aside>+### Sprite-2D sprite rendering. Requires `LocalTransform` to be visible. See [Sprite guide](/microes/guides/sprite/) for full details.+2D sprite rendering. Requires `Transform` to be visible. See [Sprite guide](/microes/guides/sprite/) for full details.### Camera@@ -78,11 +82,11 @@ Entity hierarchy for scene graphs.### SpineAnimation-Spine skeletal animation playback. Requires `LocalTransform`. See [Spine Animation guide](/microes/guides/spine/) for full details.+Spine skeletal animation playback. Requires `Transform`. See [Spine Animation guide](/microes/guides/spine/) for full details.### BitmapText-GPU-rendered text using pre-baked bitmap font atlases (BMFont format). Requires `LocalTransform`. See [Bitmap Text guide](/microes/guides/bitmap-text/) for full details.+GPU-rendered text using pre-baked bitmap font atlases (BMFont format). Requires `Transform`. See [Bitmap Text guide](/microes/guides/bitmap-text/) for full details.| Property | Type | Description ||----------|------|-------------|@@ -125,7 +129,7 @@ UI layout rectangle. Defines anchored layout for UI elements.### UIMask-Clips child entities to the parent's `UIRect` bounds. Requires `UIRect` and `LocalTransform` on the same entity. See [UI & Text guide](/microes/guides/ui/) for details.+Clips child entities to the parent's `UIRect` bounds. Requires `UIRect` and `Transform` on the same entity. See [UI & Text guide](/microes/guides/ui/) for details.| Property | Type | Default | Description ||----------|------|---------|-------------|@@ -148,10 +152,6 @@ Button behavior for UI elements. Requires `Interactable` and `UIRect`.| `state` | number | `0` (Normal) | 0=Normal, 1=Hovered, 2=Pressed, 3=Disabled || `transition` | ButtonTransition \| null | `null` | Color transition for each state |-### ScreenSpace--Tag component that marks an entity as a screen-space UI root. Children of a ScreenSpace entity are laid out in screen coordinates via their `UIRect`. Requires `UIRect` and `LocalTransform`.-### NameA string identifier for the entity. Useful for finding entities by name at runtime.@@ -166,7 +166,7 @@ Physics components require the `PhysicsPlugin`. See [Physics guide](/microes/gui#### RigidBody-Physics body attached to an entity. Requires `LocalTransform`.+Physics body attached to an entity. Requires `Transform`.| Property | Type | Default | Description ||----------|------|---------|-------------|@@ -212,6 +212,21 @@ Physics body attached to an entity. Requires `LocalTransform`.| `restitution` | number | `0.0` | Bounciness || `isSensor` | boolean | `false` | Trigger-only (no physical response) |+## Component Enabled Toggle++Components that have an `enabled` property in their definition display a checkbox in the Inspector header. Unchecking it sets `enabled` to `false`, which the corresponding system can use to skip processing.++This applies to builtin components like `Interactable`, `UIMask`, and `RigidBody`, as well as any custom component that includes an `enabled` field:++```typescript+const MyComponent = defineComponent('MyComponent', {+ enabled: true,+ speed: 100,+});+```++When disabled, the component header in the Inspector is visually dimmed.+## Custom Components### defineComponent@@ -262,7 +277,7 @@ Attach `Player` to an entity in the editor, then query it:```typescriptaddSystem(defineSystem(- [Query(LocalTransform, Player)],+ [Query(Transform, Player)],(query) => {for (const [entity, transform] of query) {// only processes entities with the Player tag@@ -280,14 +295,14 @@ addSystem(defineSystem(For entities created at runtime (bullets, particles, effects), use `Commands`:```typescript-import { addStartupSystem, defineSystem, Commands, Sprite, LocalTransform } from 'esengine';+import { addStartupSystem, defineSystem, Commands, Sprite, Transform } from 'esengine';addStartupSystem(defineSystem([Commands()],(cmds) => {const entity = cmds.spawn().insert(Sprite, { size: { x: 10, y: 10 } })- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } }).id();}));@@ -303,3 +318,4 @@ cmds.entity(entity).remove(Velocity);- [Systems](/microes/core-concepts/systems/) — logic that operates on components- [Queries](/microes/core-concepts/queries/) — finding entities by component+- [Change Detection](/microes/core-concepts/change-detection/) — reacting to component changesdiff --git a/docs/astro/src/content/docs/core-concepts/ecs.mdx b/docs/astro/src/content/docs/core-concepts/ecs.mdxindex 95a9dfeb3..954baa72e 100644--- a/docs/astro/src/content/docs/core-concepts/ecs.mdx+++ b/docs/astro/src/content/docs/core-concepts/ecs.mdx@@ -12,7 +12,7 @@ ESEngine uses an Entity-Component-System (ECS) architecture for game object mana| Concept | Role | Example ||---------|------|---------|| **Entity** | A unique identifier (just a number) | Player, Enemy, Bullet |-| **Component** | Data attached to an entity | LocalTransform, Sprite, Health |+| **Component** | Data attached to an entity | Transform, Sprite, Health || **System** | Logic that operates on entities with specific components | MovementSystem, RenderSystem |<Aside type="tip">@@ -35,9 +35,9 @@ GameObjectECS approach — compose behaviors freely:```-Player = Entity + LocalTransform + Sprite + Health + PlayerInput-Enemy = Entity + LocalTransform + Sprite + Health + AI-Bullet = Entity + LocalTransform + Sprite + Velocity + Damage+Player = Entity + Transform + Sprite + Health + PlayerInput+Enemy = Entity + Transform + Sprite + Health + AI+Bullet = Entity + Transform + Sprite + Velocity + Damage```Benefits:@@ -49,9 +49,11 @@ Benefits:## Entities-An entity is just a number (ID). In ESEngine, entities are typically created in the **scene editor** — you place them visually, add components, and configure their properties.+An entity is a lightweight handle with two parts: an **index** and a **generation**. The index identifies the slot in memory, while the generation tracks how many times that slot has been recycled.-Entities can also be spawned at runtime with `Commands` (e.g. bullets, particles):+This **generational handle** design means that when an entity is despawned and its slot is reused by a new entity, any stale references to the old entity are automatically detected — their generation won't match. This prevents bugs where code accidentally operates on a recycled entity.++In practice, you don't need to think about generations — just use the `Entity` type as an opaque handle. Entities are typically created in the **scene editor**, or spawned at runtime with `Commands`:```typescriptimport { defineSystem, addStartupSystem, Commands, type Entity } from 'esengine';@@ -66,7 +68,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {Components are data attached to entities. You **define** components in code, then **attach** them to entities in the scene editor.-- **Builtin components** — LocalTransform, Sprite, Camera, etc. (always available in the editor)+- **Builtin components** — Transform, Sprite, Camera, etc. (always available in the editor)- **Custom components** — defined with `defineComponent` / `defineTag` (appear in the editor after saving)```typescript@@ -85,11 +87,11 @@ See [Components](/microes/core-concepts/components/) for the full API.Systems are functions that query entities with specific components and operate on them. They run automatically on all matching entities in the scene.```typescript-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform } from 'esengine';import { Health } from './components';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Health)],+ [Res(Time), Query(Mut(Transform), Health)],(time, query) => {for (const [entity, transform, health] of query) {if (health.current <= 0) {@@ -148,6 +150,10 @@ The `World` stores all entities and components. In your scripts, you interact wi| Remove a component at runtime | `Commands()` → `cmds.entity(e).remove(Component)` || Read a resource | `Res(ResourceType)` || Mutate a resource | `ResMut(ResourceType)` |+| React to added components | `Query(Added(Component))` |+| React to changed components | `Query(Changed(Component))` |+| React to removed components | `Removed(Component)` |+| Send events between systems | `EventWriter(Event)` / `EventReader(Event)` |See [Systems](/microes/core-concepts/systems/) and [Queries](/microes/core-concepts/queries/) for detailed usage.@@ -157,3 +163,5 @@ See [Systems](/microes/core-concepts/systems/) and [Queries](/microes/core-conce- [Systems](/microes/core-concepts/systems/) — defining and scheduling systems- [Queries](/microes/core-concepts/queries/) — querying entities- [Resources](/microes/core-concepts/resources/) — global singleton data+- [Change Detection](/microes/core-concepts/change-detection/) — reacting to component changes+- [Events](/microes/core-concepts/events/) — decoupled inter-system communicationdiff --git a/docs/astro/src/content/docs/core-concepts/events.mdx b/docs/astro/src/content/docs/core-concepts/events.mdxnew file mode 100644index 000000000..72206f983--- /dev/null+++ b/docs/astro/src/content/docs/core-concepts/events.mdx@@ -0,0 +1,190 @@+---+title: Events+description: Sending and receiving messages between systems in ESEngine+---++import { Aside } from '@astrojs/starlight/components';++Events let systems communicate without knowing about each other. One system sends an event, and any number of other systems can read it — with no direct coupling between them.++## Defining Events++Define an event with `defineEvent` and a TypeScript interface for its payload:++```typescript+import { defineEvent } from 'esengine';++interface DamageEvent {+ target: Entity;+ amount: number;+ source?: Entity;+}++const Damage = defineEvent<DamageEvent>('Damage');+```++## Sending Events++Use `EventWriter` as a system parameter to send events:++```typescript+import { defineSystem, addSystem, EventWriter, Query, Health } from 'esengine';++addSystem(defineSystem(+ [EventWriter(Damage), Query(Health, Enemy)],+ (writer, query) => {+ for (const [entity, health] of query) {+ if (health.current <= 0) {+ writer.send({ target: entity, amount: 0 });+ }+ }+ }+));+```++You can call `writer.send()` multiple times in a single system — all events are collected.++## Reading Events++Use `EventReader` as a system parameter to receive events:++```typescript+import { defineSystem, addSystem, EventReader, Commands } from 'esengine';++addSystem(defineSystem(+ [EventReader(Damage)],+ (events) => {+ for (const event of events) {+ console.log(`Entity ${event.target} took ${event.amount} damage`);+ }+ }+));+```++`EventReader` is iterable — use `for...of` to process each event. It also provides utility methods:++```typescript+events.isEmpty() // true if no events this frame+events.toArray() // collect all events into an array+```++Multiple systems can read the same event type. Each reader sees all events from the previous frame.++## Event Lifecycle++Events use a **double-buffered** design:++1. **Frame start**: buffers swap — events written last frame become readable, old read buffer is cleared+2. **During frame**: writers push to the write buffer, readers read from the read buffer+3. **Next frame**: swap again++```+Frame 1: systemA sends Damage ──────────────────┐+Frame 2: systemB reads Damage (from frame 1) ◄───┘+ systemA sends new Damage ──────────────┐+Frame 3: systemB reads Damage (from frame 2) ◄──┘+ frame 1 events are gone+```++<Aside type="note">+Events last exactly **1 frame**. If no system reads them, they are silently discarded on the next swap. This is by design — events are for frame-to-frame communication, not persistent state.+</Aside>++## Practical Example: Damage System++A complete example with three decoupled systems:++```typescript+import { defineEvent, defineSystem, addSystem, EventWriter, EventReader, Query, Mut, Commands, Health, Sprite } from 'esengine';++// 1. Define the event+interface DamageEvent {+ target: Entity;+ amount: number;+}+const Damage = defineEvent<DamageEvent>('Damage');++// 2. Combat system — detects hits and sends damage events+const combatSystem = defineSystem(+ [EventWriter(Damage), Query(Transform, Projectile), Query(Transform, Health, Enemy)],+ (damage, projectiles, enemies) => {+ for (const [_, pTransform, proj] of projectiles) {+ for (const [enemy, eTransform] of enemies) {+ if (distance(pTransform, eTransform) < proj.radius) {+ damage.send({ target: enemy, amount: proj.power });+ }+ }+ }+ }+);++// 3. Health system — applies damage+const healthSystem = defineSystem(+ [EventReader(Damage), Query(Mut(Health))],+ (events, query) => {+ for (const { target, amount } of events) {+ const result = query.get(target);+ if (result) {+ const [_, health] = result;+ health.current -= amount;+ }+ }+ }+);++// 4. VFX system — shows hit effects (reads same events)+const hitVFXSystem = defineSystem(+ [EventReader(Damage), Query(Transform)],+ (events, query) => {+ for (const { target } of events) {+ const result = query.get(target);+ if (result) {+ const [_, transform] = result;+ spawnHitParticle(transform.position);+ }+ }+ }+);+```++Three systems, one event type, zero direct dependencies between them.++## Multiple Event Types++A system can write and read multiple event types:++```typescript+const PlayerDied = defineEvent<{ entity: Entity }>('PlayerDied');+const ScoreChanged = defineEvent<{ delta: number }>('ScoreChanged');++defineSystem(+ [EventReader(Damage), EventWriter(PlayerDied), EventWriter(ScoreChanged)],+ (damageEvents, deathWriter, scoreWriter) => {+ for (const { target, amount } of damageEvents) {+ if (isPlayer(target) && getHealth(target) <= 0) {+ deathWriter.send({ entity: target });+ scoreWriter.send({ delta: -100 });+ }+ }+ }+);+```++## When to Use Events vs Direct Queries++| Use Events | Use Queries |+|-----------|-------------|+| One-shot notifications (hit, died, scored) | Continuous state (position, health) |+| Multiple consumers need the same data | Single system owns the logic |+| Decoupled systems across different modules | Tightly related systems |+| Timing matters (happened *this* frame) | Current value matters |++<Aside type="tip">+If you find yourself adding a boolean flag component just to signal "something happened" and clearing it next frame — that's a perfect candidate for an event instead.+</Aside>++## Next Steps++- [Change Detection](/microes/core-concepts/change-detection/) — react to component additions and modifications+- [Systems](/microes/core-concepts/systems/) — system parameters and scheduling+- [Resources](/microes/core-concepts/resources/) — global singleton datadiff --git a/docs/astro/src/content/docs/core-concepts/queries.mdx b/docs/astro/src/content/docs/core-concepts/queries.mdxindex a089192f1..f2d08c696 100644--- a/docs/astro/src/content/docs/core-concepts/queries.mdx+++ b/docs/astro/src/content/docs/core-concepts/queries.mdx@@ -10,9 +10,9 @@ Queries let you iterate over entities that have specific components. They are thA query matches all entities in the scene that have **all** the listed components:```typescript-import { defineSystem, addSystem, Query, Mut, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Query, Mut, Transform, Sprite } from 'esengine';-addSystem(defineSystem([Query(Mut(LocalTransform), Sprite)], (query) => {+addSystem(defineSystem([Query(Mut(Transform), Sprite)], (query) => {for (const [entity, transform, sprite] of query) {transform.position.x += 1;}@@ -26,10 +26,10 @@ The `for...of` loop yields tuples of `[entity, ...components]` in the same orderBy default, query results are read-only. Use `Mut()` to get mutable access to specific components:```typescript-import { Query, Mut, LocalTransform, Sprite } from 'esengine';+import { Query, Mut, Transform, Sprite } from 'esengine';defineSystem(- [Query(Mut(LocalTransform), Sprite)],+ [Query(Mut(Transform), Sprite)],(query) => {for (const [entity, transform, sprite] of query) {transform.position.x += 1; // writable@@ -77,6 +77,55 @@ query.count(); // number of matching entitiesquery.toArray(); // collect all results into an array```+## Change Detection Filters++Wrap components in `Added()`, `Changed()`, or use `Removed()` to react to component lifecycle events.++### Added++Match entities that received a component since the last time this system ran:++```typescript+import { Query, Added, Transform } from 'esengine';++defineSystem([Query(Added(Transform))], (query) => {+ for (const [entity, transform] of query) {+ console.log('New transform on', entity);+ }+});+```++### Changed++Match entities whose component data was mutated (via `Mut()`) since the last tick:++```typescript+import { Query, Changed, Mut, Text } from 'esengine';++defineSystem([Query(Changed(Text))], (query) => {+ for (const [entity, text] of query) {+ console.log('Text changed on', entity, text.content);+ }+});+```++### Removed++`Removed()` is a standalone parameter (not inside `Query`). It yields entities that had a component removed since the last tick:++```typescript+import { Removed } from 'esengine';+import { Health } from './components';++defineSystem([Removed(Health)], (removed) => {+ for (const entity of removed) {+ console.log('Health removed from', entity);+ }+});+```++See [Change Detection](/microes/core-concepts/change-detection/) for details on how tick-based tracking works.+## Multiple QueriesA system can have multiple queries to cross-reference different entity types:@@ -88,7 +137,7 @@ const Player = defineTag('Player');const Enemy = defineTag('Enemy');defineSystem(- [Query(LocalTransform, Player), Query(LocalTransform, Enemy)],+ [Query(Transform, Player), Query(Transform, Enemy)],(players, enemies) => {for (const [_, playerTransform] of players) {for (const [_, enemyTransform] of enemies) {@@ -104,10 +153,10 @@ defineSystem(Queries are often used together with resources:```typescript-import { Res, Time, Input, Query, Mut, LocalTransform } from 'esengine';+import { Res, Time, Input, Query, Mut, Transform } from 'esengine';defineSystem(- [Res(Time), Res(Input), Query(Mut(LocalTransform), Player)],+ [Res(Time), Res(Input), Query(Mut(Transform), Player)],(time, input, query) => {for (const [entity, transform] of query) {if (input.isKeyDown('KeyD')) {@@ -123,14 +172,14 @@ defineSystem(Define `Hitbox`, `Player`, and `Enemy` components, attach them to entities in the scene editor, then query:```typescript-import { defineSystem, defineComponent, defineTag, addSystem, Query, LocalTransform } from 'esengine';+import { defineSystem, defineComponent, defineTag, addSystem, Query, Transform } from 'esengine';const Hitbox = defineComponent('Hitbox', { width: 50, height: 50 });const Player = defineTag('Player');const Enemy = defineTag('Enemy');addSystem(defineSystem(- [Query(LocalTransform, Hitbox, Player), Query(LocalTransform, Hitbox, Enemy)],+ [Query(Transform, Hitbox, Player), Query(Transform, Hitbox, Enemy)],(players, enemies) => {for (const [_, pPos, pBox] of players) {for (const [_, ePos, eBox] of enemies) {@@ -172,5 +221,7 @@ const despawnDead = defineSystem(## Next Steps+- [Change Detection](/microes/core-concepts/change-detection/) — tick-based tracking for Added, Changed, Removed+- [Events](/microes/core-concepts/events/) — decoupled inter-system communication- [Resources](/microes/core-concepts/resources/) — global singleton data like Time and Input- [Components](/microes/core-concepts/components/) — all builtin and custom component typesdiff --git a/docs/astro/src/content/docs/core-concepts/resources.mdx b/docs/astro/src/content/docs/core-concepts/resources.mdxindex 18baad3ee..14bf8440f 100644--- a/docs/astro/src/content/docs/core-concepts/resources.mdx+++ b/docs/astro/src/content/docs/core-concepts/resources.mdx@@ -88,6 +88,23 @@ defineSystem([Res(Input)], (input) => {| `isMouseButtonReleased(button)` | Mouse button was released this frame || `getScrollDelta()` | Returns `{ x, y }` scroll delta |+### UIEvents++UI interaction events collected each frame. Available when UI plugins are active (default).++```typescript+import { Res } from 'esengine';+import { UIEvents } from 'esengine';++defineSystem([Res(UIEvents)], (events) => {+ for (const e of events.query('click')) {+ console.log('Clicked:', e.entity);+ }+});+```++See [UI & Text](/microes/guides/ui/) for the full list of event types.+## Custom Resources### defineResource@@ -136,7 +153,7 @@ Define a `Coin` tag, attach it to coin entities in the scene, and track score wiimport {defineSystem, defineResource, defineTag,addStartupSystem, addSystem, Commands, Query, ResMut,- LocalTransform+ Transform} from 'esengine';const Score = defineResource({ value: 0 });@@ -148,7 +165,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {}));addSystem(defineSystem(- [Commands(), ResMut(Score), Query(LocalTransform, Player), Query(LocalTransform, Coin)],+ [Commands(), ResMut(Score), Query(Transform, Player), Query(Transform, Coin)],(cmds, score, players, coins) => {for (const [_, pPos] of players) {for (const [coinEntity, cPos] of coins) {@@ -168,3 +185,4 @@ addSystem(defineSystem(- [Systems](/microes/core-concepts/systems/) — how systems use resources and queries- [Components](/microes/core-concepts/components/) — data attached to entities+- [Events](/microes/core-concepts/events/) — decoupled inter-system communicationdiff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdxindex 577b4a3de..e65af7865 100644--- a/docs/astro/src/content/docs/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx@@ -10,10 +10,10 @@ Systems contain game logic. They declare what data they need via parameters, and## Defining Systems```typescript-import { defineSystem, Res, Time, Query, Mut, LocalTransform, Velocity } from 'esengine';+import { defineSystem, Res, Time, Query, Mut, Transform, Velocity } from 'esengine';const movementSystem = defineSystem(- [Res(Time), Query(Mut(LocalTransform), Velocity)],+ [Res(Time), Query(Mut(Transform), Velocity)],(time, query) => {for (const [entity, transform, velocity] of query) {transform.position.x += velocity.linear.x * time.delta;@@ -23,11 +23,11 @@ const movementSystem = defineSystem();```-This system automatically processes every entity in the scene that has both `LocalTransform` and `Velocity` components.+This system automatically processes every entity in the scene that has both `Transform` and `Velocity` components.`defineSystem` takes two arguments:-1. **Parameters** — an array of `Query`, `Res`, `ResMut`, or `Commands` descriptors+1. **Parameters** — an array of `Query`, `Res`, `ResMut`, `Commands`, `EventWriter`, or `EventReader` descriptors2. **Function** — receives the resolved parameters in the same order## Registering Systems@@ -76,16 +76,16 @@ addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);By default, systems within the same Schedule run in registration order. If you need to enforce execution order between systems, use the third argument to `defineSystem` to specify `runBefore` or `runAfter`:```typescript-import { defineSystem, Query, Res, Time, Mut, LocalTransform, Velocity, Sprite } from 'esengine';+import { defineSystem, Query, Res, Time, Mut, Transform, Velocity, Sprite } from 'esengine';const movementSystem = defineSystem(- [Res(Time), Query(Mut(LocalTransform), Velocity)],+ [Res(Time), Query(Mut(Transform), Velocity)],(time, query) => { /* ... */ },{ name: 'movement' });const renderSystem = defineSystem(- [Query(LocalTransform, Sprite)],+ [Query(Transform, Sprite)],(query) => { /* ... */ },{ name: 'render', runAfter: ['movement'] });@@ -107,14 +107,14 @@ The engine uses topological sorting to determine the final execution order. If tCreate, modify, and destroy entities at runtime:```typescript-import { Commands, Sprite, LocalTransform, Velocity, defineResource } from 'esengine';+import { Commands, Sprite, Transform, Velocity, defineResource } from 'esengine';const Score = defineResource({ value: 0 });defineSystem([Commands()], (cmds) => {// Spawn a new entity with components (chainable)const bullet = cmds.spawn()- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } }).insert(Sprite, { size: { x: 8, y: 8 } }).id();@@ -159,9 +159,9 @@ defineSystem([Commands()], (cmds) => {Iterate entities with specific components:```typescript-import { Query, Mut, LocalTransform, Sprite } from 'esengine';+import { Query, Mut, Transform, Sprite } from 'esengine';-defineSystem([Query(Mut(LocalTransform), Sprite)], (query) => {+defineSystem([Query(Mut(Transform), Sprite)], (query) => {for (const [entity, transform, sprite] of query) {transform.position.x += 1;}@@ -192,11 +192,41 @@ defineSystem([ResMut(GameState)], (state) => {See [Resources](/microes/core-concepts/resources/) for the full API.+### EventWriter++Send events from a system:++```typescript+import { defineEvent, EventWriter } from 'esengine';++const DamageEvent = defineEvent<{ target: number; amount: number }>('Damage');++defineSystem([EventWriter(DamageEvent)], (writer) => {+ writer.send({ target: enemy, amount: 25 });+});+```++### EventReader++Receive events sent by other systems:++```typescript+import { EventReader } from 'esengine';++defineSystem([EventReader(DamageEvent)], (reader) => {+ for (const event of reader) {+ console.log(`${event.target} took ${event.amount} damage`);+ }+});+```++See [Events](/microes/core-concepts/events/) for the full API.+### Combining Parameters```typescriptdefineSystem(- [Commands(), Res(Time), Res(Input), Query(Mut(LocalTransform), Velocity)],+ [Commands(), Res(Time), Res(Input), Query(Mut(Transform), Velocity)],(cmds, time, input, query) => {// All parameters available}@@ -215,11 +245,11 @@ export const Speed = defineComponent('Speed', { value: 200 });```typescript// src/systems/movement.ts-import { defineSystem, addSystem, Res, Time, Input, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Time, Input, Query, Mut, Transform } from 'esengine';import { Speed } from '../components/Speed';addSystem(defineSystem(- [Res(Time), Res(Input), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Res(Input), Query(Mut(Transform), Speed)],(time, input, query) => {for (const [entity, transform, speed] of query) {if (input.isKeyDown('KeyD')) {@@ -241,3 +271,5 @@ Each system runs inside its own try/catch boundary. If a system throws an error,- [Queries](/microes/core-concepts/queries/) — query filters and iteration methods- [Resources](/microes/core-concepts/resources/) — global singleton data+- [Change Detection](/microes/core-concepts/change-detection/) — reacting to component changes+- [Events](/microes/core-concepts/events/) — decoupled inter-system communicationdiff --git a/docs/astro/src/content/docs/en/guides/debugging.mdx b/docs/astro/src/content/docs/en/guides/debugging.mdxindex 4dff9d86f..cf47c83ea 100644--- a/docs/astro/src/content/docs/en/guides/debugging.mdx+++ b/docs/astro/src/content/docs/en/guides/debugging.mdx@@ -211,7 +211,7 @@ If a system with a broad query runs slowly, narrow the query by adding more spec```typescriptconst narrowSystem = defineSystem(- [Query(Mut(LocalTransform), Velocity, Player)],+ [Query(Mut(Transform), Velocity, Player)],(query) => {for (const [entity, transform, velocity] of query) {transform.position.x += velocity.linear.x;diff --git a/docs/astro/src/content/docs/getting-started/introduction.mdx b/docs/astro/src/content/docs/getting-started/introduction.mdxindex 0c8302cc6..1f0936846 100644--- a/docs/astro/src/content/docs/getting-started/introduction.mdx+++ b/docs/astro/src/content/docs/getting-started/introduction.mdx@@ -12,12 +12,12 @@ ESEngine is a lightweight 2D game engine with a **TypeScript SDK** powered by aUse the editor to create projects, place entities in scenes, and attach components visually. Write game logic in TypeScript — define custom components and systems that operate on scene entities:```typescript-import { defineComponent, defineSystem, addSystem, Query, Mut, Res, Time, LocalTransform } from 'esengine';+import { defineComponent, defineSystem, addSystem, Query, Mut, Res, Time, Transform } from 'esengine';const Speed = defineComponent('Speed', { value: 200 });addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Query(Mut(Transform), Speed)],(time, query) => {for (const [entity, transform, speed] of query) {transform.position.x += speed.value * time.delta;diff --git a/docs/astro/src/content/docs/getting-started/quick-start.mdx b/docs/astro/src/content/docs/getting-started/quick-start.mdxindex 7adae737b..341f293cd 100644--- a/docs/astro/src/content/docs/getting-started/quick-start.mdx+++ b/docs/astro/src/content/docs/getting-started/quick-start.mdx@@ -19,7 +19,7 @@ Let's create a simple game that animates a sprite. This will introduce you to th3. **Add a Sprite entity** in the editor- In the Hierarchy panel, create a new entity and add `LocalTransform` and `Sprite` components to it. Set the Sprite size to `100 x 100` and pick a color.+ In the Hierarchy panel, create a new entity and add `Transform` and `Sprite` components to it. Set the Sprite size to `100 x 100` and pick a color.4. **Create `src/main.ts`** with the following code:@@ -31,12 +31,12 @@ Let's create a simple game that animates a sprite. This will introduce you to thMut,Res,Time,- LocalTransform,+ Transform,Sprite,} from 'esengine';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Sprite)],+ [Res(Time), Query(Mut(Transform), Sprite)],(time, query) => {for (const [entity, transform, sprite] of query) {transform.position.x = Math.sin(time.elapsed) * 100;@@ -56,7 +56,7 @@ Let's create a simple game that animates a sprite. This will introduce you to thIn ESEngine, entities and their components are created in the **scene editor**. Your code doesn't create them — it defines **systems** that query and operate on scene entities.-The sprite you placed in step 3 already has `LocalTransform` and `Sprite` components. The system in step 4 finds it via `Query(Mut(LocalTransform), Sprite)` and animates it.+The sprite you placed in step 3 already has `Transform` and `Sprite` components. The system in step 4 finds it via `Query(Mut(Transform), Sprite)` and animates it.### Custom Components@@ -73,11 +73,11 @@ After saving, the `Speed` component appears in the editor's "Add Component" menu```typescript// src/systems/movement.ts-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform } from 'esengine';import { Speed } from '../components/Speed';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Query(Mut(Transform), Speed)],(time, query) => {for (const [entity, transform, speed] of query) {transform.position.x += speed.value * time.delta;@@ -110,14 +110,14 @@ addSystemToSchedule(Schedule.FixedUpdate, system); // runs at fixed intervalsUse `Commands` when you need to create entities at runtime (e.g. bullets, particles):```typescript-import { addStartupSystem, defineSystem, Commands, Sprite, LocalTransform } from 'esengine';+import { addStartupSystem, defineSystem, Commands, Sprite, Transform } from 'esengine';addStartupSystem(defineSystem([Commands()],(cmds) => {cmds.spawn().insert(Sprite, { size: { x: 10, y: 10 } })- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } });+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } });}));```diff --git a/docs/astro/src/content/docs/guides/custom-draw.mdx b/docs/astro/src/content/docs/guides/custom-draw.mdxindex 8bdc1a6d7..f8bec9610 100644--- a/docs/astro/src/content/docs/guides/custom-draw.mdx+++ b/docs/astro/src/content/docs/guides/custom-draw.mdx@@ -192,13 +192,13 @@ const primitives = Draw.getPrimitiveCount();```typescriptimport { registerDrawCallback, Draw } from 'esengine';-import { defineSystem, addSystem, Query, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Query, Transform } from 'esengine';import { BoxCollider } from 'esengine/physics';const boxes: Array<{ x: number; y: number; w: number; h: number }> = [];addSystem(defineSystem(- [Query(LocalTransform, BoxCollider)],+ [Query(Transform, BoxCollider)],(query) => {boxes.length = 0;for (const [entity, transform, collider] of query) {diff --git a/docs/astro/src/content/docs/guides/game-view.mdx b/docs/astro/src/content/docs/guides/game-view.mdxindex 245f1c887..37a801747 100644--- a/docs/astro/src/content/docs/guides/game-view.mdx+++ b/docs/astro/src/content/docs/guides/game-view.mdx@@ -5,7 +5,7 @@ description: Preview and debug your game inside the editor using the Game View pimport { Aside } from '@astrojs/starlight/components';-The **Game View** is the in-editor game preview panel. It provides playback controls, resolution simulation, and live debugging, so you can test game logic and visuals without leaving the editor.+The **Game View** is the in-editor game preview panel. It provides playback controls, resolution simulation, live property editing, and runtime debugging — so you can test and tweak game logic without leaving the editor.## Starting the Preview@@ -13,6 +13,10 @@ Click the **Play** button on the left side of the toolbar to start the game prevClick the **Stop** button to end the preview. The Game View returns to its initial blank state and the editor switches back to normal editing mode.+### Shared Canvas++The Scene View and Game View share a single offscreen WebGL canvas. When the preview starts, both views render from the same pipeline — the Scene View shows the editor viewport with gizmos, and the Game View shows the game camera output. This avoids duplicating the WASM instance and keeps memory usage low.+## Playback ControlsThe toolbar provides the following playback controls:@@ -66,6 +70,10 @@ Selecting **Custom** reveals width and height input fields that accept any valueWhen the preview starts, the editor enters **Play Mode** — a special runtime debugging mode. The Hierarchy and Inspector panels switch to their runtime views.+### State Snapshot++On entering play mode the editor takes a **full snapshot** of the current scene — entity tree, component data, selection state, and dirty flags. When you stop the preview, the snapshot is restored and all runtime modifications are discarded. This means you can freely experiment during play without affecting your saved scene.+### Hierarchy PanelWhile in Play Mode the Hierarchy panel changes as follows:@@ -88,19 +96,65 @@ When a runtime entity is selected during Play Mode, the Inspector panel:- Auto-refreshes property values periodically, reflecting live game state- Supports direct editing of numbers, booleans, strings, and vector properties — changes are sent to the game instance immediately-<Aside type="caution">- Changes made in the Inspector during Play Mode only affect the running game instance. When you stop the preview, all runtime modifications are lost and the scene data reverts to its state before the preview started.-</Aside>-### Exiting Play ModeWhen you click **Stop**:- The game instance is destroyed and the preview is cleared+- The scene is restored from the snapshot taken at play start- The Hierarchy panel restores the edit-mode entity tree, including its previous expand/collapse state- The Inspector panel returns to edit mode- No runtime modifications are saved to the scene file+## Live Editing++During play mode you can edit entity properties in the Inspector and see the effect in real time. This is useful for tuning values like speed, gravity, or UI positions while the game is running.++### What You Can Edit++| Property Type | Editable |+|---------------|----------|+| Numbers (int, float) | Yes |+| Booleans | Yes |+| Strings | Yes |+| Vectors (Vec2, Vec3) | Yes |+| Colors | Yes |+| Enums | Yes |++You can also perform structural changes through the runtime API:++- **Spawn** new entities+- **Despawn** existing entities+- **Add** or **remove** components on an entity+- **Rename** and **reparent** entities++### What You Cannot Edit++- **Scene View gizmos** are disabled during play — you cannot drag entities to move them visually+- **Component reordering** is not available+- **Prefab editing** is disabled+- **Visibility toggle** does not apply during play++<Aside type="caution">+ All live edits are temporary. When you stop the preview, the scene reverts to the snapshot. There is no way to selectively keep play-mode changes.+</Aside>++### Editing Workflow++A typical live-edit workflow:++1. **Play** — start the preview+2. **Select** a runtime entity in the Hierarchy+3. **Tweak** property values in the Inspector (e.g., adjust a speed or offset)+4. **Observe** the change immediately in the Game View+5. **Pause + Step** to inspect frame-by-frame behavior+6. **Stop** — note down the values you liked+7. **Apply** the values to the scene in edit mode++<Aside type="tip">+ Input fields being actively edited are never overwritten by auto-refresh, so your typing is never interrupted.+</Aside>+## FPS DisplayWhile the preview is running, the current frame rate (FPS) is displayed on the right side of the toolbar. The FPS indicator hides automatically when the preview stops.@@ -110,4 +164,4 @@ While the preview is running, the current frame rate (FPS) is displayed on the r- Hierarchy editing features are disabled during Play Mode, including drag-to-reorder, context menus, and renaming- The runtime entity list refreshes periodically; with a large number of entities there may be a brief delay- Resolution can be changed while the preview is running — the preview resizes immediately-- Input fields that are actively being edited in the Inspector are not overwritten by auto-refresh, so manual input is never interrupted+- The shared canvas supports only one active game camera at a timediff --git a/docs/astro/src/content/docs/guides/input.mdx b/docs/astro/src/content/docs/guides/input.mdxindex d1ab4aef4..27fb2533a 100644--- a/docs/astro/src/content/docs/guides/input.mdx+++ b/docs/astro/src/content/docs/guides/input.mdx@@ -12,10 +12,10 @@ ESEngine provides input handling through the `Input` resource. The `InputPlugin`Access input state through the `Res(Input)` system parameter:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Input, Query, Mut, Transform } from 'esengine';addSystem(defineSystem(- [Res(Input), Query(Mut(LocalTransform))],+ [Res(Input), Query(Mut(Transform))],(input, query) => {for (const [entity, transform] of query) {if (input.isKeyDown('KeyW')) {@@ -135,14 +135,14 @@ Define `Player` and `MoveSpeed` components, attach them to an entity in the scen```typescriptimport {defineSystem, defineComponent, defineTag, addSystem,- Res, Input, Time, Query, Mut, LocalTransform+ Res, Input, Time, Query, Mut, Transform} from 'esengine';const Player = defineTag('Player');const MoveSpeed = defineComponent('MoveSpeed', { value: 200 });addSystem(defineSystem(- [Res(Input), Res(Time), Query(Mut(LocalTransform), MoveSpeed, Player)],+ [Res(Input), Res(Time), Query(Mut(Transform), MoveSpeed, Player)],(input, time, query) => {for (const [entity, transform, speed] of query) {const velocity = { x: 0, y: 0 };diff --git a/docs/astro/src/content/docs/guides/physics.mdx b/docs/astro/src/content/docs/guides/physics.mdxindex f345a9b23..216fe6beb 100644--- a/docs/astro/src/content/docs/guides/physics.mdx+++ b/docs/astro/src/content/docs/guides/physics.mdx@@ -32,7 +32,7 @@ Position conversion is handled automatically — entity positions (in pixels) ar## Components-Add physics components to entities in the scene editor alongside `LocalTransform`.+Add physics components to entities in the scene editor alongside `Transform`.### RigidBody@@ -120,7 +120,7 @@ addSystem(defineSystem(Set up a ground, player, and coin sensor in the editor, then handle events in code:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Input, Query, Mut, Transform } from 'esengine';import { RigidBody, PhysicsEvents } from 'esengine/physics';import { Player, Coin } from './components';@@ -135,9 +135,9 @@ addSystem(defineSystem(```**Editor setup:**-- **Ground**: `LocalTransform` + `RigidBody` (bodyType=0 Static) + `BoxCollider` (halfExtents=`{x:10, y:0.5}`) + `Sprite`-- **Player**: `LocalTransform` + `RigidBody` (bodyType=2 Dynamic, fixedRotation=true) + `BoxCollider` + `Sprite` + `Player` tag-- **Coin**: `LocalTransform` + `RigidBody` (bodyType=0 Static) + `CircleCollider` (isSensor=true) + `Sprite` + `Coin` tag+- **Ground**: `Transform` + `RigidBody` (bodyType=0 Static) + `BoxCollider` (halfExtents=`{x:10, y:0.5}`) + `Sprite`+- **Player**: `Transform` + `RigidBody` (bodyType=2 Dynamic, fixedRotation=true) + `BoxCollider` + `Sprite` + `Player` tag+- **Coin**: `Transform` + `RigidBody` (bodyType=0 Static) + `CircleCollider` (isSensor=true) + `Sprite` + `Coin` tag## Physics API (Advanced)diff --git a/docs/astro/src/content/docs/guides/plugins.mdx b/docs/astro/src/content/docs/guides/plugins.mdxindex 75e6b2ac9..0735bffde 100644--- a/docs/astro/src/content/docs/guides/plugins.mdx+++ b/docs/astro/src/content/docs/guides/plugins.mdx@@ -24,10 +24,23 @@ When you create a project in the editor, all built-in plugins are active by defa| Plugin | Components ||--------|-----------|| Text | `Text` -- renders text content to sprite textures each frame |-| UI Mask | `UIMask` -- stencil-based masking for UI elements |-| UI Layout | `UIRect`, `ScreenSpace` -- anchored UI layout relative to camera |+| Image | `Image` -- displays images with slicing, tiling, and fill modes |+| UI Mask | `UIMask` -- scissor/stencil-based masking for UI elements |+| UI Layout | `UIRect` -- anchored UI layout relative to camera |+| UI Render Order | Automatic render order assignment for UI hierarchies || UI Interaction | `Interactable`, `Button`, `UIInteraction`, `UIEvents` -- pointer hit-testing and button states || Text Input | `TextInput` -- editable text fields with platform input |+| Toggle | `Toggle`, `ToggleGroup` -- checkbox and radio-button behavior |+| Slider | `Slider` -- interactive value slider with fill and handle |+| Progress Bar | `ProgressBar` -- non-interactive progress display |+| Dropdown | `Dropdown` -- dropdown list selector |+| Scroll View | `ScrollView` -- scrollable container with momentum and elastic bounce |+| List View | `ListView` -- virtual scrolling for large lists |+| Drag | `Draggable` -- drag-to-move on UI elements |+| Focus | `Focusable` -- keyboard focus and Tab navigation |+| Safe Area | `SafeArea` -- adapts layout to device safe areas (notches, rounded corners) |+| Layout Group | `LayoutGroup` -- grid-like layout with direction, spacing, and alignment |+| Flex Layout | `FlexContainer`, `FlexItem` -- CSS Flexbox-like automatic child arrangement |All of these are active by default in every project. You can use their components directly from the editor's component picker -- no setup required.@@ -111,6 +124,26 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {}));```+### Events++Events enable decoupled communication between systems:++```typescript+import { defineEvent, EventWriter, EventReader, defineSystem, addSystem } from 'esengine';++const ScoreEvent = defineEvent<{ points: number }>('Score');++addSystem(defineSystem([EventWriter(ScoreEvent)], (writer) => {+ writer.send({ points: 10 });+}));++addSystem(defineSystem([EventReader(ScoreEvent)], (reader) => {+ for (const e of reader) {+ console.log('Scored:', e.points);+ }+}));+```+## System ScheduleSystems run in a defined order each frame:diff --git a/docs/astro/src/content/docs/guides/prefabs.mdx b/docs/astro/src/content/docs/guides/prefabs.mdxindex 10949a42b..3d7c41de3 100644--- a/docs/astro/src/content/docs/guides/prefabs.mdx+++ b/docs/astro/src/content/docs/guides/prefabs.mdx@@ -76,7 +76,7 @@ const { root } = await prefabs.instantiate('prefabs/Enemy.esprefab', {{prefabEntityId: 1,type: 'property',- componentType: 'LocalTransform',+ componentType: 'Transform',propertyName: 'position',value: { x: 200, y: 100, z: 0 },},diff --git a/docs/astro/src/content/docs/guides/rendering.mdx b/docs/astro/src/content/docs/guides/rendering.mdxindex 0dfea558b..e8b160b0d 100644--- a/docs/astro/src/content/docs/guides/rendering.mdx+++ b/docs/astro/src/content/docs/guides/rendering.mdx@@ -45,10 +45,10 @@ For screen adaptation and resolution scaling, attach a `Canvas` component to theQuery the camera entity and modify its transform:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform, Camera } from 'esengine';+import { defineSystem, addSystem, Res, Input, Query, Mut, Transform, Camera } from 'esengine';addSystem(defineSystem(- [Res(Input), Query(Mut(LocalTransform), Camera)],+ [Res(Input), Query(Mut(Transform), Camera)],(input, query) => {for (const [entity, transform, camera] of query) {if (input.isKeyDown('ArrowLeft')) {@@ -87,17 +87,17 @@ Both cameras render side by side. Cameras with the same priority render in entit## Transform-Every visible entity needs a `LocalTransform`. Add it to entities in the scene editor and configure position, rotation, and scale in the inspector.+Every visible entity needs a `Transform`. Add it to entities in the scene editor and configure position, rotation, and scale in the inspector.### RotationRotation uses quaternions. For 2D rotation around the Z-axis:```typescript-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform, Sprite } from 'esengine';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Sprite)],+ [Res(Time), Query(Mut(Transform), Sprite)],(time, query) => {for (const [entity, transform, sprite] of query) {const angle = time.elapsed;diff --git a/docs/astro/src/content/docs/guides/scenes.mdx b/docs/astro/src/content/docs/guides/scenes.mdxindex 2e6542993..dd59a351a 100644--- a/docs/astro/src/content/docs/guides/scenes.mdx+++ b/docs/astro/src/content/docs/guides/scenes.mdx@@ -26,7 +26,7 @@ A scene file contains:"parent": null,"children": [2],"components": [- { "type": "LocalTransform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },{ "type": "Sprite", "data": { "texture": "player.png", "size": { "x": 32, "y": 32 } } }]}@@ -47,10 +47,10 @@ After building your project, the engine automatically loads the scene, resolvesEvery entity loaded from a scene receives a built-in `Name` component with the name assigned in the editor. Query `Name` to find entities:```typescript-import { defineSystem, addStartupSystem, Query, Name, LocalTransform } from 'esengine';+import { defineSystem, addStartupSystem, Query, Name, Transform } from 'esengine';addStartupSystem(defineSystem(- [Query(Name, LocalTransform)],+ [Query(Name, Transform)],(query) => {for (const [entity, name, transform] of query) {if (name.value === 'Player') {@@ -66,12 +66,12 @@ addStartupSystem(defineSystem(Use a `Query` to find entities by their components:```typescript-import { defineSystem, addSystem, defineTag, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, defineTag, Query, Mut, Transform } from 'esengine';const Player = defineTag('Player');addSystem(defineSystem(- [Query(Mut(LocalTransform), Player)],+ [Query(Mut(Transform), Player)],(query) => {for (const [entity, transform] of query) {// process each player@@ -85,10 +85,10 @@ addSystem(defineSystem(Use the `Children` component to walk the entity tree:```typescript-import { defineSystem, addSystem, Query, Children, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Query, Children, Transform } from 'esengine';addSystem(defineSystem(- [Query(Children, LocalTransform)],+ [Query(Children, Transform)],(query) => {for (const [entity, children, transform] of query) {// children.entities contains child entity IDs@@ -101,21 +101,21 @@ addSystem(defineSystem(Scene entities can form a tree via parent-child relationships. Set up parent-child relationships in the editor — the engine manages `Parent` and `Children` components automatically.-When a parent's `LocalTransform` changes, the engine propagates the transform to all descendants via the `WorldTransform` component.+When a parent's `Transform` changes, the engine automatically propagates the world transform to all descendants.## Dynamic EntitiesYou can spawn and despawn entities at runtime using `Commands`:```typescript-import { defineSystem, addSystem, Commands, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Commands, Transform, Sprite } from 'esengine';addSystem(defineSystem([Commands()],(commands) => {// Spawn a new entity with componentscommands.spawn()- .insert(LocalTransform, { position: { x: 100, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } })+ .insert(Transform, { position: { x: 100, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } }).insert(Sprite, { texture: bulletTexture, color: { r: 1, g: 1, b: 1, a: 1 }, size: { x: 8, y: 8 } });// Despawn an entity@@ -317,10 +317,10 @@ console.log(owner.persistent); // falseSystems registered in a scene config only run when that scene's status is `'running'`. They are automatically wrapped so they skip execution when the scene is paused or sleeping:```typescript-import { defineSystem, Query, Mut, LocalTransform, Schedule } from 'esengine';+import { defineSystem, Query, Mut, Transform, Schedule } from 'esengine';const mySystem = defineSystem(- [Query(Mut(LocalTransform))],+ [Query(Mut(Transform))],(query) => {for (const [entity, transform] of query) {// runs only while 'game' scene is runningdiff --git a/docs/astro/src/content/docs/guides/spine.mdx b/docs/astro/src/content/docs/guides/spine.mdxindex 60d71eed5..aca091d1e 100644--- a/docs/astro/src/content/docs/guides/spine.mdx+++ b/docs/astro/src/content/docs/guides/spine.mdx@@ -5,7 +5,7 @@ description: Spine skeletal animation in ESEngineimport { Aside } from '@astrojs/starlight/components';-The `SpineAnimation` component plays [Spine](http://esotericsoftware.com/) skeletal animations. Add it to an entity in the scene editor along with `LocalTransform`.+The `SpineAnimation` component plays [Spine](http://esotericsoftware.com/) skeletal animations. Add it to an entity in the scene editor along with `Transform`.<Aside type="note">Since v0.3.0, Spine uses standalone WASM modules (`spine38` / `spine41` / `spine42`) instead of being bundled into the engine core. Select the Spine version in the editor under **Settings → Project → Spine Version** (`3.8`, `4.1`, or `4.2`). The editor loads the matching runtime automatically — no code is needed. New projects default to **None** — you must select a Spine version to enable Spine.@@ -32,7 +32,7 @@ The `SpineAnimation` component plays [Spine](http://esotericsoftware.com/) skele## Setup1. Place Spine export files (`.json` + `.atlas` + images) in your project's `assets/` folder-2. In the scene editor: create an entity → add `LocalTransform` and `SpineAnimation`+2. In the scene editor: create an entity → add `Transform` and `SpineAnimation`3. Set `skeletonPath` and `atlasPath` to point to your Spine files4. Set `animation` to the name of the animation to play@@ -101,7 +101,7 @@ Define a `CharacterState` component, attach it with `SpineAnimation` on the enti```typescriptimport {defineComponent, defineSystem, addSystem,- Res, Input, Time, Query, Mut, LocalTransform, SpineAnimation+ Res, Input, Time, Query, Mut, Transform, SpineAnimation} from 'esengine';const CharacterState = defineComponent('CharacterState', {@@ -110,7 +110,7 @@ const CharacterState = defineComponent('CharacterState', {});addSystem(defineSystem(- [Res(Input), Res(Time), Query(Mut(LocalTransform), Mut(SpineAnimation), Mut(CharacterState))],+ [Res(Input), Res(Time), Query(Mut(Transform), Mut(SpineAnimation), Mut(CharacterState))],(input, time, query) => {for (const [entity, transform, spine, state] of query) {let moving = false;diff --git a/docs/astro/src/content/docs/guides/sprite.mdx b/docs/astro/src/content/docs/guides/sprite.mdxindex 841f1c395..0bed1c347 100644--- a/docs/astro/src/content/docs/guides/sprite.mdx+++ b/docs/astro/src/content/docs/guides/sprite.mdx@@ -5,7 +5,7 @@ description: 2D sprite rendering in ESEngineimport { Aside } from '@astrojs/starlight/components';-The `Sprite` component is the primary way to display 2D graphics. Add it to an entity in the scene editor along with `LocalTransform` to make the entity visible.+The `Sprite` component is the primary way to display 2D graphics. Add it to an entity in the scene editor along with `Transform` to make the entity visible.## Properties@@ -23,15 +23,15 @@ The `Sprite` component is the primary way to display 2D graphics. Add it to an e## Basic Usage-In the scene editor: create an entity → add `LocalTransform` and `Sprite` → set size and color in the inspector.+In the scene editor: create an entity → add `Transform` and `Sprite` → set size and color in the inspector.To modify sprites at runtime, query them in a system:```typescript-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform, Sprite } from 'esengine';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Sprite)],+ [Res(Time), Query(Mut(Transform), Sprite)],(time, query) => {for (const [entity, transform, sprite] of query) {transform.position.x = Math.sin(time.elapsed) * 100;@@ -135,7 +135,7 @@ Sprites are sorted by the following priority (highest first):For sprites created at runtime (bullets, particles):```typescript-import { defineSystem, addSystem, Commands, Sprite, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Commands, Sprite, Transform } from 'esengine';addSystem(defineSystem([Commands()],@@ -145,7 +145,7 @@ addSystem(defineSystem(size: { x: 10, y: 10 },color: { r: 1, g: 1, b: 0, a: 1 }})- .insert(LocalTransform, {+ .insert(Transform, {position: { x: 0, y: 0, z: 0 }});}diff --git a/docs/astro/src/content/docs/guides/ui.mdx b/docs/astro/src/content/docs/guides/ui.mdxindex a6183ef44..8daa6856c 100644--- a/docs/astro/src/content/docs/guides/ui.mdx+++ b/docs/astro/src/content/docs/guides/ui.mdx@@ -1,337 +1,418 @@---title: UI & Text-description: Text rendering and UI layout components in ESEngine+description: UI components, layout, interaction, and text rendering in ESEngine---import { Aside } from '@astrojs/starlight/components';-The `Text` and `UIRect` components work together with `Sprite` to render text in your game. The `TextPlugin` automatically converts text content into textures each frame.+ESEngine provides a complete UI framework with layout, interaction, text rendering, and a library of ready-made widgets. Layout computation runs in C++/WASM for performance, while all components are configured from TypeScript.-## Setup+<Aside type="note">+ All UI plugins are registered automatically by `createWebApp()`. No manual setup is needed.+</Aside>-In the scene editor: create an entity → add `LocalTransform`, `Sprite`, `Text`, and `UIRect` components.+## Quick Start-- **Text** — defines the text content and style (font, size, color, alignment)-- **UIRect** — defines the layout rectangle (size, anchor, pivot)-- **Sprite** — used internally by the text system to display the rendered texture+In the editor: right-click the Hierarchy → **Create** → **UI** → choose a widget (Button, Slider, Text, etc.). The editor creates the entity hierarchy with all required components pre-configured.-<Aside type="note">- You don't need to configure the Sprite component manually. The `TextPlugin` automatically creates and updates the sprite texture from the Text content.-</Aside>+To create UI from code:-## Text Properties+```typescript+import { defineSystem, addStartupSystem, Commands, Transform, Sprite, UIRect, Text, Parent } from 'esengine';++addStartupSystem(defineSystem([Commands()], (cmds) => {+ const root = cmds.spawn()+ .insert(Transform)+ .insert(UIRect, { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } })+ .id();++ cmds.spawn()+ .insert(Transform)+ .insert(Sprite)+ .insert(UIRect, { size: { x: 200, y: 40 } })+ .insert(Text, { content: 'Hello World', fontSize: 24 })+ .insert(Parent, { entity: root });+}));+```-| Property | Type | Default | Description |-|----------|------|---------|-------------|-| `content` | string | `''` | Text content to display |-| `fontFamily` | string | `'Arial'` | Font family name |-| `fontSize` | number | `24` | Font size in pixels |-| `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color RGBA (0–1) |-| `align` | TextAlign | `Left` | Horizontal alignment (editor defaults to `Center`) |-| `verticalAlign` | TextVerticalAlign | `Top` | Vertical alignment (editor defaults to `Middle`) |-| `wordWrap` | boolean | `true` | Enable automatic word wrapping |-| `overflow` | TextOverflow | `Visible` | Overflow handling mode |-| `lineHeight` | number | `1.2` | Line height multiplier |+## Layout++### UIRect-## UIRect Properties+Every UI element needs a `UIRect` to participate in layout. It defines position and size relative to the parent using an anchor-based system.| Property | Type | Default | Description ||----------|------|---------|-------------|-| `anchorMin` | Vec2 | `{0.5, 0.5}` | Bottom-left anchor relative to parent (0–1 range) |-| `anchorMax` | Vec2 | `{0.5, 0.5}` | Top-right anchor relative to parent (0–1 range) |+| `anchorMin` | Vec2 | `{0.5, 0.5}` | Bottom-left anchor (0–1) |+| `anchorMax` | Vec2 | `{0.5, 0.5}` | Top-right anchor (0–1) || `offsetMin` | Vec2 | `{0, 0}` | Pixel offset from anchorMin || `offsetMax` | Vec2 | `{0, 0}` | Pixel offset from anchorMax |-| `size` | Vec2 | `{100, 100}` | Width and height (used when anchorMin equals anchorMax) |+| `size` | Vec2 | `{100, 100}` | Width and height (when anchors are equal) || `pivot` | Vec2 | `{0.5, 0.5}` | Pivot point for rotation and scaling |-When `anchorMin` equals `anchorMax`, the element has a fixed `size` positioned at the anchor point. When they differ, the element stretches between the two anchors and `size` is computed automatically by `UILayoutPlugin`.+When `anchorMin` equals `anchorMax`, the element has a fixed `size` at the anchor point. When they differ, the element stretches between anchors and size is computed automatically.-## Enums+### FlexContainer-### TextAlign+CSS Flexbox-like layout for automatic child arrangement.-| Value | Name | Description |-|-------|------|-------------|-| 0 | `Left` | Align text to the left edge |-| 1 | `Center` | Center text horizontally |-| 2 | `Right` | Align text to the right edge |+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `direction` | FlexDirection | `Row` | `Row`, `Column`, `RowReverse`, `ColumnReverse` |+| `wrap` | FlexWrap | `NoWrap` | `NoWrap`, `Wrap` |+| `justifyContent` | JustifyContent | `Start` | `Start`, `Center`, `End`, `SpaceBetween`, `SpaceAround`, `SpaceEvenly` |+| `alignItems` | AlignItems | `Stretch` | `Start`, `Center`, `End`, `Stretch` |+| `gap` | Vec2 | `{0, 0}` | Spacing between items |+| `padding` | Vec4 | `{0, 0, 0, 0}` | Top, Right, Bottom, Left padding |-### TextVerticalAlign+### FlexItem-| Value | Name | Description |-|-------|------|-------------|-| 0 | `Top` | Align text to the top |-| 1 | `Middle` | Center text vertically |-| 2 | `Bottom` | Align text to the bottom |+Child properties for entities inside a `FlexContainer`.-### TextOverflow+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `flexGrow` | number | `0` | How much the item grows to fill space |+| `flexShrink` | number | `1` | How much the item shrinks when space is tight |+| `flexBasis` | number | `-1` | Base size before grow/shrink (-1 = auto) |+| `order` | number | `0` | Display order override |-| Value | Name | Description |-|-------|------|-------------|-| 0 | `Visible` | Text overflows the rectangle boundary |-| 1 | `Clip` | Text is clipped at the boundary |-| 2 | `Ellipsis` | Truncated text shows "..." |+### LayoutGroup-## Modifying Text at Runtime+Grid-like layout with direction, spacing, and alignment.-To update text content or style during gameplay, query the `Text` component with `Mut()`:+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `direction` | LayoutDirection | `Horizontal` | `Horizontal` (0), `Vertical` (1) |+| `spacing` | number | `0` | Space between children |+| `padding` | object | `{left:0, top:0, right:0, bottom:0}` | Border spacing |+| `childAlignment` | ChildAlignment | `Start` | `Start`, `Center`, `End` |+| `reverseOrder` | boolean | `false` | Reverse layout order |-```typescript-import { defineSystem, addSystem, Query, Mut } from 'esengine';-import { Text } from 'esengine';+## Text-addSystem(defineSystem(- [Query(Mut(Text))],- (query) => {- for (const [entity, text] of query) {- text.content = 'Updated!';- text.fontSize = 32;- }- }-));-```+### Text Component-<Aside type="caution">- Always use `Mut(Text)` when modifying text properties. Without `Mut()`, the component is read-only.-</Aside>+Renders styled text into a `Sprite` texture automatically via `TextPlugin`.-## Example: Dynamic Scoreboard+**Setup:** Add `Transform`, `Sprite`, `UIRect`, and `Text` to an entity.-A common pattern is a score display that updates when a value changes:+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `content` | string | `''` | Text content |+| `fontFamily` | string | `'Arial'` | Font family name |+| `fontSize` | number | `24` | Font size in pixels |+| `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color RGBA |+| `align` | TextAlign | `Left` | `Left` (0), `Center` (1), `Right` (2) |+| `verticalAlign` | TextVerticalAlign | `Top` | `Top` (0), `Middle` (1), `Bottom` (2) |+| `wordWrap` | boolean | `true` | Enable word wrapping |+| `overflow` | TextOverflow | `Visible` | `Visible` (0), `Clip` (1), `Ellipsis` (2) |+| `lineHeight` | number | `1.2` | Line height multiplier |-```typescript-import { defineComponent, defineTag, defineSystem, addSystem, Query, Mut } from 'esengine';-import { Text } from 'esengine';+<Aside type="note">+ You don't need to configure the Sprite manually. `TextPlugin` creates and updates the texture from the Text content.+</Aside>-const ScoreDisplay = defineTag('ScoreDisplay');+### Modifying Text at Runtime-const GameState = defineComponent('GameState', {- score: 0,-});+```typescript+import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';addSystem(defineSystem(- [Query(Mut(Text), ScoreDisplay), Query(GameState)],- (displayQuery, stateQuery) => {- let score = 0;- for (const [, state] of stateQuery) {- score = state.score;- }- for (const [, text] of displayQuery) {- text.content = `Score: ${score}`;+ [Query(Mut(Text))],+ (query) => {+ for (const [entity, text] of query) {+ text.content = 'Updated!';+ text.fontSize = 32;}}));```-In the editor: create a text entity with `Text`, `UIRect`, `Sprite`, `LocalTransform`, and the `ScoreDisplay` tag.+### Image-## UIMask+Displays images with support for slicing, tiling, and fill modes.-`UIMask` clips child entities to the parent entity's `UIRect` bounds. Any child that extends beyond the rectangle is visually cropped.+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `texture` | number | — | Texture asset handle |+| `color` | Color | `{r:1, g:1, b:1, a:1}` | Color tint |+| `imageType` | ImageType | `Simple` | `Simple` (0), `Sliced` (1), `Tiled` (2), `Filled` (3) |+| `fillMethod` | FillMethod | `Horizontal` | `Horizontal` (0), `Vertical` (1) |+| `fillOrigin` | FillOrigin | `Left` | `Left` (0), `Right` (1), `Bottom` (2), `Top` (3) |+| `fillAmount` | number | `1` | Fill progress 0–1 |+| `preserveAspect` | boolean | `false` | Maintain aspect ratio |+| `enabled` | boolean | `true` | Visibility toggle |-**Setup:** Add `UIMask`, `UIRect`, and `LocalTransform` to the parent entity. All child entities (and their descendants) will be clipped to this rectangle.+## Interaction-<Aside type="note">- `UIMaskPlugin` is registered automatically by `createWebApp()`. No manual setup is needed.-</Aside>+### Interactable-### UIMask Properties+Marks a UI entity as interactive (receives pointer events). Required for all interactive widgets.| Property | Type | Default | Description ||----------|------|---------|-------------|-| `enabled` | boolean | `true` | Whether clipping is active |+| `enabled` | boolean | `true` | Whether interaction is active |+| `blockRaycast` | boolean | `true` | Block events from reaching elements behind |-### Nesting+### UIInteraction-When a child entity also has `UIMask`, its clip rectangle is the intersection of its own `UIRect` and the parent's clip rect. This allows nested scroll areas or layered clipping.+Automatically added by the plugin to entities with `Interactable`. Provides per-entity state:-<Aside type="caution">- `UIMask` only clips **child** entities — the entity with UIMask itself is not clipped.-</Aside>+| Property | Type | Description |+|----------|------|-------------|+| `hovered` | boolean | Pointer is over this entity |+| `pressed` | boolean | Entity is being pressed |+| `justPressed` | boolean | Press started this frame |+| `justReleased` | boolean | Press released this frame |-### Example: Scrollable List+### UIEvents-Create a mask container, then move child entities to scroll:+The `UIEvents` resource collects interaction events each frame:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform, Children } from 'esengine';-import { UIMask } from 'esengine';-import { ScrollList } from './components';+import { defineSystem, addSystem, Res } from 'esengine';+import { UIEvents } from 'esengine';addSystem(defineSystem(- [Res(Input), Query(Children, UIMask, ScrollList), Query(Mut(LocalTransform))],- (input, maskQuery, childQuery) => {- const scrollDelta = input.getScrollDelta();- if (scrollDelta.y === 0) return;-- for (const [entity, children] of maskQuery) {- for (const [childEntity, transform] of childQuery) {- if (children.entities.includes(childEntity)) {- transform.position.y += scrollDelta.y * 20;- }- }+ [Res(UIEvents)],+ (events) => {+ for (const e of events.query('click')) {+ console.log('Clicked:', e.entity);}}));```-## UI Interaction+**Event types:** `click`, `press`, `release`, `hover_enter`, `hover_exit`, `focus`, `blur`, `submit`, `change`, `drag_start`, `drag_move`, `drag_end`, `scroll`-ESEngine provides a built-in UI interaction system for handling hover, press, and click events on UI elements.+Events bubble up the entity hierarchy. If a parent has `Interactable` with `blockRaycast: true`, bubbling stops there.-### Setup+### Focusable-Add the `Interactable` component to any UI entity with `UIRect` and `LocalTransform`. The `UIInteractionPlugin` (registered automatically by `createWebApp()`) performs hit testing each frame and manages interaction state.--### Interactable--Marks an entity as interactive.+Enables keyboard focus and Tab navigation.| Property | Type | Default | Description ||----------|------|---------|-------------|-| `enabled` | boolean | `true` | Whether interaction is enabled |+| `tabIndex` | number | `0` | Focus order (lower = earlier) |+| `isFocused` | boolean | `false` | Current focus state |++## Widgets### Button-Adds a state machine on top of `Interactable` with optional color transitions.+State machine on top of `Interactable` with optional color transitions.| Property | Type | Default | Description ||----------|------|---------|-------------|-| `state` | ButtonState | `Normal` | Current button state (read-only at runtime) |-| `transition` | ButtonTransition \| null | `null` | Color transition configuration |--**ButtonState:** `Normal` (0), `Hovered` (1), `Pressed` (2), `Disabled` (3)--When `transition` is set, the `Sprite` color is automatically updated on state change:+| `state` | ButtonState | `Normal` | `Normal` (0), `Hovered` (1), `Pressed` (2), `Disabled` (3) |+| `transition` | ColorTransition \| null | `null` | Color per state |```typescript-import { defineSystem, Commands, Button, Interactable } from 'esengine';--defineSystem([Commands()], (cmds) => {- cmds.entity(entity).insert(Button, {- state: 0,- transition: {- normalColor: { r: 1, g: 1, b: 1, a: 1 },- hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },- pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },- disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },- },- });+cmds.entity(button).insert(Button, {+ state: 0,+ transition: {+ normalColor: { r: 1, g: 1, b: 1, a: 1 },+ hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },+ pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },+ disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },+ },});```-### UIInteraction+### Toggle-Automatically added by the plugin to entities with `Interactable`. Provides per-entity state:+Checkbox with optional group for mutual exclusion.-| Property | Type | Description |-|----------|------|-------------|-| `hovered` | boolean | Pointer is over this entity |-| `pressed` | boolean | Entity is being pressed |-| `justPressed` | boolean | Press started this frame |-| `justReleased` | boolean | Press released this frame |+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `isOn` | boolean | `true` | Toggle state |+| `graphicEntity` | Entity | `0` | Child entity to show/hide (checkmark) |+| `group` | Entity | `0` | ToggleGroup entity for radio-button behavior |+| `transition` | ColorTransition \| null | `null` | Color transition |-### UIEvents+**ToggleGroup** — attach to a parent entity to make child toggles mutually exclusive:-The `UIEvents` resource collects interaction events each frame. Query it in systems:+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `allowSwitchOff` | boolean | `false` | Allow all toggles to be off |-```typescript-import { defineSystem, addSystem, Res } from 'esengine';-import { UIEvents } from 'esengine';+### Slider++Interactive value slider with a fill and optional draggable handle.+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `value` | number | `0` | Current value |+| `minValue` | number | `0` | Minimum value |+| `maxValue` | number | `1` | Maximum value |+| `direction` | FillDirection | `LeftToRight` | `LeftToRight` (0), `RightToLeft` (1), `BottomToTop` (2), `TopToBottom` (3) |+| `fillEntity` | Entity | `0` | Child entity for fill visualization |+| `handleEntity` | Entity | `0` | Child entity for draggable handle |+| `wholeNumbers` | boolean | `false` | Snap to integers |++Listen for value changes:++```typescriptaddSystem(defineSystem(- [Res(UIEvents)],- (events) => {- for (const e of events.query('click')) {- console.log('Clicked entity:', e.entity);+ [Res(UIEvents), Query(Slider)],+ (events, query) => {+ for (const e of events.query('change')) {+ for (const [entity, slider] of query) {+ if (entity === e.entity) {+ console.log('Slider value:', slider.value);+ }+ }}}));```-**Event types:** `click`, `press`, `release`, `hover_enter`, `hover_exit`, `submit`, `change`+### ProgressBar-### ScreenSpace+Non-interactive progress display.-A tag component for root UI entities. Entities with `ScreenSpace`, `UIRect`, and `LocalTransform` are laid out relative to the camera bounds by `UILayoutPlugin`.+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `value` | number | `0` | Progress 0–1 |+| `fillEntity` | Entity | `0` | Child entity for fill |+| `direction` | FillDirection | `LeftToRight` | Fill direction |```typescript-import { defineSystem, Commands, ScreenSpace, UIRect, LocalTransform } from 'esengine';--defineSystem([Commands()], (cmds) => {- cmds.entity(entity)- .insert(ScreenSpace)- .insert(UIRect, {- anchorMin: { x: 0, y: 0 },- anchorMax: { x: 1, y: 1 },- offsetMin: { x: 0, y: 0 },- offsetMax: { x: 0, y: 0 },- size: { x: 100, y: 100 },- pivot: { x: 0.5, y: 0.5 },- });-});+// Update progress+addSystem(defineSystem(+ [Res(Time), Query(Mut(ProgressBar))],+ (time, query) => {+ for (const [entity, bar] of query) {+ bar.value = Math.min(1, bar.value + time.delta * 0.1);+ }+ }+));```-<Aside type="note">- Both `UILayoutPlugin` and `UIInteractionPlugin` are registered automatically by `createWebApp()`. No manual setup is needed.-</Aside>+### Dropdown++Dropdown list selector.-## TextInput+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `options` | string[] | `[]` | Option labels |+| `selectedIndex` | number | `-1` | Selected option index |+| `isOpen` | boolean | `false` | List visibility |+| `listEntity` | Entity | `0` | Child entity for dropdown list |+| `labelEntity` | Entity | `0` | Child entity for selected label |-`TextInput` renders an editable text field. The `TextInputPlugin` handles keyboard input, cursor blinking, and texture rendering automatically.+### ScrollView-### Setup+Scrollable container with momentum and elastic bounce.-In the editor: create an entity via right-click → **Create** → **UI** → **TextInput**, or manually add `LocalTransform`, `UIRect`, `Interactable`, and `TextInput` components.+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `contentEntity` | Entity | `0` | Child holding scrollable content |+| `horizontalEnabled` | boolean | `false` | Enable horizontal scroll |+| `verticalEnabled` | boolean | `true` | Enable vertical scroll |+| `scrollX` | number | `0` | Current horizontal offset |+| `scrollY` | number | `0` | Current vertical offset |+| `inertia` | boolean | `true` | Enable momentum scrolling |+| `decelerationRate` | number | `0.135` | Momentum friction |+| `elastic` | boolean | `true` | Bounce at edges |+| `wheelSensitivity` | number | `0.1` | Mouse wheel amount |-<Aside type="note">- The plugin automatically adds a `Sprite` component if missing — no manual setup needed. `TextInputPlugin` is registered automatically by `createWebApp()`.-</Aside>+### ListView-### TextInput Properties+Virtual scrolling for large lists — only visible items are rendered.| Property | Type | Default | Description ||----------|------|---------|-------------|-| `value` | string | `''` | Current text content |-| `placeholder` | string | `''` | Hint text shown when empty |-| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | Placeholder text color |-| `fontFamily` | string | `'Arial'` | Font family name |-| `fontSize` | number | `16` | Font size in pixels |+| `itemHeight` | number | `40` | Fixed item height |+| `itemCount` | number | `0` | Total items |+| `scrollY` | number | `0` | Scroll position |+| `overscan` | number | `2` | Extra items above/below viewport |++### TextInput++Editable text field with cursor, selection, and placeholder.++| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `value` | string | `''` | Current text |+| `placeholder` | string | `''` | Hint when empty |+| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | Placeholder color |+| `fontFamily` | string | `'Arial'` | Font family |+| `fontSize` | number | `16` | Font size || `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color |-| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | Background fill color |-| `padding` | number | `6` | Padding in pixels |+| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | Background color |+| `padding` | number | `6` | Internal padding || `maxLength` | number | `0` | Max characters (0 = unlimited) |-| `multiline` | boolean | `false` | Allow multi-line input |-| `password` | boolean | `false` | Mask text with bullets |-| `readOnly` | boolean | `false` | Prevent user input |+| `multiline` | boolean | `false` | Allow line breaks |+| `password` | boolean | `false` | Mask text |+| `readOnly` | boolean | `false` | Prevent editing |++**Events:** `change` (value changed), `submit` (Enter pressed in single-line mode)++### Draggable++Enables drag-to-move on a UI element.-The `focused`, `cursorPos`, and `dirty` properties are managed internally by the plugin.+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `enabled` | boolean | `true` | Enable dragging |+| `dragThreshold` | number | `5` | Pixels before drag starts |+| `lockX` | boolean | `false` | Lock horizontal movement |+| `lockY` | boolean | `false` | Lock vertical movement |++## Masking-### Reading Input at Runtime+### UIMask++Clips child entities to the parent's `UIRect` bounds.++| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `enabled` | boolean | `true` | Whether clipping is active |+| `mode` | MaskMode | `Scissor` | `Scissor` (0), `Stencil` (1) |++Nested `UIMask` entities clip to the intersection of all parent masks.++<Aside type="caution">+ `UIMask` only clips **child** entities — the entity with UIMask itself is not clipped.+</Aside>++## SafeArea++Adapts layout to device safe areas (notches, rounded corners). Useful for mobile and WeChat MiniGame.++| Property | Type | Default | Description |+|----------|------|---------|-------------|+| `applyTop` | boolean | `true` | Apply to top edge |+| `applyBottom` | boolean | `true` | Apply to bottom edge |+| `applyLeft` | boolean | `true` | Apply to left edge |+| `applyRight` | boolean | `true` | Apply to right edge |++## Example: Score Display```typescript-import { defineSystem, addSystem, Query, Res } from 'esengine';-import { TextInput, UIEvents } from 'esengine';+import { defineTag, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';++const ScoreDisplay = defineTag('ScoreDisplay');+const GameState = defineComponent('GameState', { score: 0 });addSystem(defineSystem(- [Query(TextInput), Res(UIEvents)],- (query, events) => {- for (const e of events.query('submit')) {- for (const [entity, input] of query) {- if (entity === e.entity) {- console.log('Submitted:', input.value);- }- }+ [Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],+ (displays, stateQuery) => {+ if (stateQuery.isEmpty()) return;+ const [, state] = stateQuery.single()!;+ for (const [, text] of displays) {+ text.content = `Score: ${state.score}`;}}));```-**TextInput events:** `change` (value changed), `submit` (Enter pressed in single-line mode)+Uses [Change Detection](/microes/core-concepts/change-detection/) to only update text when the score actually changes.## Next Steps- [Components](/microes/core-concepts/components/) — all builtin components- [Sprite](/microes/guides/sprite/) — sprite rendering details- [Bitmap Text](/microes/guides/bitmap-text/) — GPU-rendered bitmap font text-- [Asset Loading](/microes/guides/assets/) — loading textures and other assets+- [Input Handling](/microes/guides/input/) — keyboard, mouse, and touch inputdiff --git a/docs/astro/src/content/docs/index.mdx b/docs/astro/src/content/docs/index.mdxindex 0203d351c..8710e0d1d 100644--- a/docs/astro/src/content/docs/index.mdx+++ b/docs/astro/src/content/docs/index.mdx@@ -42,13 +42,13 @@ Define a custom component, attach it to entities in the scene editor, then write```typescriptimport {defineComponent, defineSystem, addSystem,- Query, Mut, Res, Time, LocalTransform+ Query, Mut, Res, Time, Transform} from 'esengine';const Speed = defineComponent('Speed', { value: 200 });addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Query(Mut(Transform), Speed)],(time, query) => {for (const [entity, transform, speed] of query) {transform.position.x += speed.value * time.delta;diff --git a/docs/astro/src/content/docs/zh/changelog-v060.mdx b/docs/astro/src/content/docs/zh/changelog-v060.mdxnew file mode 100644index 000000000..0dbd1975e--- /dev/null+++ b/docs/astro/src/content/docs/zh/changelog-v060.mdx@@ -0,0 +1,101 @@+---+title: v0.6.0+description: ESEngine v0.6.0 更新日志+---++import { Aside } from '@astrojs/starlight/components';++<Aside type="tip">+v0.6.0 是一次重大引擎更新:UI 布局迁入 C++/WASM、Transform 统一为单一组件、ECS Registry 重建为 generational handle 架构,并新增变更检测、事件系统、资产导入管线和实时编辑播放模式。+</Aside>++## UI 系统重构++- UI 布局计算从 TypeScript 迁移到 C++/WASM,性能显著提升+- 新增 UI 组件:ProgressBar、Dropdown、Toggle 及快速创建模板+- 重写 UI 框架架构,提取 `walkParentChain` 辅助函数简化层级遍历+- 增强布局系统,正确处理混合锚点模式,修复 Slider 拖拽问题+- 所有 UI 组件自动生成编辑器 Schema++## ECS 核心增强++### Transform 统一++- 将 `LocalTransform` 和 `WorldTransform` 合并为单一 `Transform` 组件+- 简化 API,不再需要在两种 Transform 类型之间切换++### Generational Handle++- 使用 flat vector pool 和 generational entity handle 重建 ECS Registry+- 消除过期实体引用 bug,提升缓存局部性+- 大量实体场景下迭代性能显著提升++### 变更检测与事件系统++- 新增 ECS 变更检测系统,可追踪组件修改+- 新增事件系统,支持实体间和系统间的解耦通信++## 实时编辑播放模式++- 游戏运行期间可完全实时编辑实体属性+- 编辑器中的修改实时反映到运行中的游戏+- Scene/Game 共享视图使用离屏 WebGL Canvas(不再使用 iframe 复制)+- 用轻量级内联 renderer sync 替代 `RuntimeSyncService`++## 资产导入管线++- 全新资产导入系统,支持按平台 override+- 可定义平台特定的资产处理规则(如微信和 Playable 使用不同纹理压缩)+- 集成到现有构建管线++## 多窗口支持++- 任意编辑器面板可拆分为独立 OS 窗口+- 独立窗口生命周期,完整保留面板功能+- 面板可重新停靠回主窗口++## 编辑器改进++- 复合实体创建(如 Button、Slider)后自动选中 Hierarchy 中的根实体+- Inspector 中每个组件支持启用/禁用开关+- Scene View 设置中增加实时预览切换+- 修复 Scene View 缩放到光标的符号错误和 overlay 缩放+- 移除底部 Dock 面板中的 Addressable Groups+- 改进 Dropdown 占位符渲染和 Inspector Schema 处理++## 性能++- **ECS Registry**:flat vector pool 替代 sparse set,视图迭代速度提升约 2 倍+- **TransformSystem**:两次遍历融合为单次,增加 nameLen 边界检查+- **Root Transform**:根实体跳过矩阵乘法的快速路径+- **GL Flush**:移除渲染 flush 中的冗余 GL 状态调用++## SDK 和运行时++- 增强 `World.query()` API,改善易用性+- `App.tick()` 生命周期改进和场景资产生命周期管理+- 组件注册表整合,场景加载 DRY 化+- 修复系统执行顺序,Toggle 性能从 O(n²) 优化到 O(n)++## 平台修复++- **微信小游戏**:使用 `wx.getSystemInfoSync` 获取正确的安全区域 insets+- **可玩广告**:修复构建中的实体引用警告和 Prefab 实例化问题+- **原生平台**:为原生构建兼容性添加 `ES_PLATFORM_WEB` stencil GL 调用保护++## Bug 修复++- 修复 C++ Entity ID 回收导致创建实体后文本消失+- 修复 UIRect 混合锚点模式布局+- 修复 Slider 最小值时 fill anchors 归零导致 UIRect 尺寸为 0+- 修复 Slider fill 位置和 ProgressBar 布局同步+- 修复 ProgressBar fill 定位和 UIRect 移动 Gizmo+- 修复触摸 ID 追踪和 Spine 缓存 key 碰撞+- 修复 Dropdown 占位符、颜色 NaN 值和纹理 handle 守卫+- 修复渲染器正确性问题,减少 draw call 开销++## 其他++- 升级 spine-runtimes 到 4.2.104+- 新增 SDK 集成测试,覆盖 UI、Layout、Slider 和 App Tick+- 更新 `eht.py` codegen,支持 vector 类型和双输出diff --git a/docs/astro/src/content/docs/zh/core-concepts/change-detection.mdx b/docs/astro/src/content/docs/zh/core-concepts/change-detection.mdxnew file mode 100644index 000000000..cecc35769--- /dev/null+++ b/docs/astro/src/content/docs/zh/core-concepts/change-detection.mdx@@ -0,0 +1,174 @@+---+title: 变更检测+description: 在 ESEngine 中响应组件的添加、修改和移除+---++import { Aside } from '@astrojs/starlight/components';++变更检测让系统仅在组件被添加、修改或移除时才做出响应,而不是每帧处理所有实体。当场景中有大量实体但每帧只有少数发生变化时,这对性能至关重要。++## Added++`Added()` 过滤查询,仅返回自系统上次运行以来新增了某组件的实体:++```typescript+import { defineSystem, addSystem, Query, Added, Transform, Sprite } from 'esengine';++addSystem(defineSystem(+ [Query(Added(Sprite), Transform)],+ (query) => {+ for (const [entity, sprite, transform] of query) {+ // 仅对刚获得 Sprite 的实体执行+ console.log('New sprite at', transform.position.x, transform.position.y);+ }+ }+));+```++实体在被创建或被插入组件的那一帧出现在 `Added` 查询中,之后不会再出现,除非组件被移除后重新添加。++## Changed++`Changed()` 过滤查询,仅返回组件值被修改过的实体:++```typescript+import { defineSystem, addSystem, Query, Changed, Mut, Health, Sprite } from 'esengine';++const healthBarSystem = defineSystem(+ [Query(Changed(Health), Mut(Sprite))],+ (query) => {+ for (const [entity, health, sprite] of query) {+ // 仅在 Health 被修改时执行+ sprite.size.x = (health.current / health.max) * 100;+ }+ }+);+```++当 `world.insert()`、`world.set()` 或 `Commands.insert()` 被调用时,组件会被标记为已变更——即使新值与旧值相同。++<Aside type="tip">+`Added` 是 `Changed` 的子集。当组件首次被添加时,它同时被视为 added 和 changed。+</Aside>++## Removed++`Removed()` 是独立的查询类型(不是 `Query` 的过滤器)。它返回被移除了特定组件的实体 ID:++```typescript+import { defineSystem, addSystem, Removed, Commands, Health } from 'esengine';++addSystem(defineSystem(+ [Removed(Health), Commands()],+ (removed, cmds) => {+ for (const entity of removed) {+ // Health 被移除了——销毁实体+ cmds.despawn(entity);+ }+ }+));+```++<Aside type="caution">+`Removed` 只提供实体 ID,不包含组件数据(数据已被删除)。如果需要旧值,请在移除前将其复制到其他地方。+</Aside>++移除记录在缓冲区中保留 2 个 tick,之后自动清理。这意味着每帧运行的系统总能及时看到移除事件。++## 组合过滤器++可以在同一个系统中混合使用 `Added`、`Changed` 和 `Removed`:++```typescript+import { defineSystem, Query, Added, Changed, Removed, Mut, Transform, Velocity, Health, Commands } from 'esengine';++defineSystem(+ [+ Query(Added(Velocity), Transform),+ Query(Changed(Health), Mut(Sprite)),+ Removed(Health),+ Commands(),+ ],+ (newVelocities, damagedEntities, removedHealth, cmds) => {+ for (const [entity, velocity, transform] of newVelocities) {+ // 初始化移动+ }++ for (const [entity, health, sprite] of damagedEntities) {+ // 更新血条+ }++ for (const entity of removedHealth) {+ cmds.despawn(entity);+ }+ }+);+```++变更过滤器也兼容 `.with()` 和 `.without()`:++```typescript+Query(Changed(Health)).with(Player) // 仅玩家的 Health 变更+Query(Added(Sprite)).without(UIRect) // 新 Sprite 但非 UI 元素+```++## 工作原理++ESEngine 使用**基于 tick 的追踪**:++1. World 维护一个全局 tick 计数器,每帧递增一次+2. 每次组件插入或修改都会记录当前 tick+3. 每个系统记录其上次运行的 tick+4. 系统运行时,变更过滤器比较:*组件 tick > 系统上次运行 tick*++这意味着:+- 每帧运行的系统会看到上一帧的变更+- 跳帧的系统(如通过 `wrapSceneSystem`)会看到自上次运行以来的所有累积变更+- 无需手动管理 "dirty flag"——完全自动++## 常用模式++### 同步 Transform 到渲染位置++```typescript+const syncRenderSystem = defineSystem(+ [Query(Changed(Transform), Sprite)],+ (query) => {+ for (const [entity, transform, sprite] of query) {+ updateRenderPosition(entity, transform.position);+ }+ }+);+```++### 响应实体生成++```typescript+const onSpawnSystem = defineSystem(+ [Query(Added(Transform), Sprite)],+ (query) => {+ for (const [entity, transform, sprite] of query) {+ playSpawnAnimation(entity);+ }+ }+);+```++### 组件移除时清理++```typescript+const cleanupSystem = defineSystem(+ [Removed(RigidBody)],+ (removed) => {+ for (const entity of removed) {+ destroyPhysicsBody(entity);+ }+ }+);+```++## 下一步++- [事件](/microes/zh/core-concepts/events/) — 在系统之间发送和接收消息+- [查询](/microes/zh/core-concepts/queries/) — 基本查询过滤和迭代+- [系统](/microes/zh/core-concepts/systems/) — 系统定义和调度diff --git a/docs/astro/src/content/docs/zh/core-concepts/components.mdx b/docs/astro/src/content/docs/zh/core-concepts/components.mdxindex 7a69c8827..73af14915 100644--- a/docs/astro/src/content/docs/zh/core-concepts/components.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/components.mdx@@ -11,7 +11,7 @@ import { Aside } from '@astrojs/starlight/components';内置组件在编辑器中始终可用,由 C++ 后端支持。-### LocalTransform+### Transform实体的位置、旋转和缩放。@@ -21,9 +21,13 @@ import { Aside } from '@astrojs/starlight/components';| `rotation` | Quat | 四元数 `{ w, x, y, z }` || `scale` | Vec3 | 缩放因子 `{ x, y, z }` |+<Aside type="note">+ 在之前的版本中,`LocalTransform` 和 `WorldTransform` 是两个独立组件。现在已统一为单一的 `Transform`。旧名称仍可作为别名使用,但推荐导入 `Transform`。+</Aside>+### Sprite-2D 精灵渲染。需要 `LocalTransform` 才能显示。详见[精灵指南](/microes/zh/guides/sprite/)。+2D 精灵渲染。需要 `Transform` 才能显示。详见[精灵指南](/microes/zh/guides/sprite/)。### Camera@@ -78,11 +82,11 @@ import { Aside } from '@astrojs/starlight/components';### SpineAnimation-Spine 骨骼动画播放。需要 `LocalTransform`。详见 [Spine 动画指南](/microes/zh/guides/spine/)。+Spine 骨骼动画播放。需要 `Transform`。详见 [Spine 动画指南](/microes/zh/guides/spine/)。### BitmapText-使用预烘焙位图字体图集(BMFont 格式)进行 GPU 渲染的文本。需要 `LocalTransform`。详见[位图文本指南](/microes/zh/guides/bitmap-text/)。+使用预烘焙位图字体图集(BMFont 格式)进行 GPU 渲染的文本。需要 `Transform`。详见[位图文本指南](/microes/zh/guides/bitmap-text/)。| 属性 | 类型 | 说明 ||------|------|------|@@ -125,7 +129,7 @@ UI 布局矩形。定义 UI 元素的锚点布局。### UIMask-将子实体裁剪到父级 `UIRect` 边界内。需要在同一实体上同时挂载 `UIRect` 和 `LocalTransform`。详见 [UI 与文本指南](/microes/zh/guides/ui/)。+将子实体裁剪到父级 `UIRect` 边界内。需要在同一实体上同时挂载 `UIRect` 和 `Transform`。详见 [UI 与文本指南](/microes/zh/guides/ui/)。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|@@ -148,10 +152,6 @@ UI 元素的按钮行为。需要 `Interactable` 和 `UIRect`。| `state` | number | `0`(Normal) | 0=正常, 1=悬停, 2=按下, 3=禁用 || `transition` | ButtonTransition \| null | `null` | 各状态的颜色过渡 |-### ScreenSpace--标签组件,将实体标记为屏幕空间 UI 根节点。ScreenSpace 实体的子级通过 `UIRect` 在屏幕坐标中布局。需要 `UIRect` 和 `LocalTransform`。-### Name实体的字符串标识符,用于在运行时按名称查找实体。@@ -166,7 +166,7 @@ UI 元素的按钮行为。需要 `Interactable` 和 `UIRect`。#### RigidBody-附加到实体的物理刚体。需要 `LocalTransform`。+附加到实体的物理刚体。需要 `Transform`。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|@@ -212,6 +212,21 @@ UI 元素的按钮行为。需要 `Interactable` 和 `UIRect`。| `restitution` | number | `0.0` | 弹性(弹力) || `isSensor` | boolean | `false` | 仅触发(无物理响应) |+## 组件启用开关++定义中包含 `enabled` 属性的组件会在 Inspector 的组件标题栏显示一个复选框。取消勾选会将 `enabled` 设为 `false`,对应的系统可以据此跳过处理。++这适用于内置组件(如 `Interactable`、`UIMask`、`RigidBody`),也适用于任何包含 `enabled` 字段的自定义组件:++```typescript+const MyComponent = defineComponent('MyComponent', {+ enabled: true,+ speed: 100,+});+```++禁用时,Inspector 中的组件标题栏会变暗显示。+## 自定义组件### defineComponent@@ -262,7 +277,7 @@ export const Enemy = defineTag('Enemy');```typescriptaddSystem(defineSystem(- [Query(LocalTransform, Player)],+ [Query(Transform, Player)],(query) => {for (const [entity, transform] of query) {// 只处理带有 Player 标签的实体@@ -280,14 +295,14 @@ addSystem(defineSystem(需要在运行时创建实体时(如子弹、粒子、特效),使用 `Commands`:```typescript-import { addStartupSystem, defineSystem, Commands, Sprite, LocalTransform } from 'esengine';+import { addStartupSystem, defineSystem, Commands, Sprite, Transform } from 'esengine';addStartupSystem(defineSystem([Commands()],(cmds) => {const entity = cmds.spawn().insert(Sprite, { size: { x: 10, y: 10 } })- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } }).id();}));@@ -303,3 +318,4 @@ cmds.entity(entity).remove(Velocity);- [系统](/microes/zh/core-concepts/systems/) — 操作组件的逻辑- [查询](/microes/zh/core-concepts/queries/) — 按组件查找实体+- [变更检测](/microes/zh/core-concepts/change-detection/) — 响应组件变更diff --git a/docs/astro/src/content/docs/zh/core-concepts/ecs.mdx b/docs/astro/src/content/docs/zh/core-concepts/ecs.mdxindex fcf9e0767..f85531931 100644--- a/docs/astro/src/content/docs/zh/core-concepts/ecs.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/ecs.mdx@@ -12,7 +12,7 @@ ESEngine 使用实体-组件-系统(ECS)架构管理游戏对象。ECS 将**| 概念 | 角色 | 示例 ||------|------|------|| **实体 (Entity)** | 唯一标识符(只是一个数字) | 玩家、敌人、子弹 |-| **组件 (Component)** | 附加在实体上的数据 | LocalTransform、Sprite、Health |+| **组件 (Component)** | 附加在实体上的数据 | Transform、Sprite、Health || **系统 (System)** | 操作具有特定组件的实体的逻辑 | 移动系统、渲染系统 |<Aside type="tip">@@ -35,9 +35,9 @@ GameObjectECS 方式 — 自由组合行为:```-Player = Entity + LocalTransform + Sprite + Health + PlayerInput-Enemy = Entity + LocalTransform + Sprite + Health + AI-Bullet = Entity + LocalTransform + Sprite + Velocity + Damage+Player = Entity + Transform + Sprite + Health + PlayerInput+Enemy = Entity + Transform + Sprite + Health + AI+Bullet = Entity + Transform + Sprite + Velocity + Damage```优势:@@ -49,9 +49,11 @@ Bullet = Entity + LocalTransform + Sprite + Velocity + Damage## 实体-实体只是一个数字(ID)。在 ESEngine 中,实体通常在**场景编辑器**中创建 — 可视化地放置、添加组件、配置属性。+实体是一个轻量级句柄,由两部分组成:**索引**和**世代**。索引标识内存中的槽位,世代追踪该槽位被回收利用的次数。-运行时也可以通过 `Commands` 创建实体(如子弹、粒子):+这种 **generational handle** 设计意味着,当实体被销毁且其槽位被新实体复用时,任何指向旧实体的过期引用都会被自动检测——它们的世代号不匹配。这防止了代码意外操作已回收实体的 bug。++实际使用中不需要关心世代——只需将 `Entity` 类型当作不透明句柄使用。实体通常在**场景编辑器**中创建,也可以通过 `Commands` 在运行时生成:```typescriptimport { defineSystem, addStartupSystem, Commands, type Entity } from 'esengine';@@ -66,7 +68,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {组件是附加在实体上的数据。在代码中**定义**组件,然后在场景编辑器中**挂载**到实体上。-- **内置组件** — LocalTransform、Sprite、Camera 等(编辑器中始终可用)+- **内置组件** — Transform、Sprite、Camera 等(编辑器中始终可用)- **自定义组件** — 用 `defineComponent` / `defineTag` 定义(保存后出现在编辑器中)```typescript@@ -85,11 +87,11 @@ const Player = defineTag('Player');系统是查询具有特定组件的实体并操作它们的函数。它们自动运行在场景中所有匹配的实体上。```typescript-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform } from 'esengine';import { Health } from './components';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Health)],+ [Res(Time), Query(Mut(Transform), Health)],(time, query) => {for (const [entity, transform, health] of query) {if (health.current <= 0) {@@ -148,6 +150,10 @@ addSystem(defineSystem(| 运行时移除组件 | `Commands()` → `cmds.entity(e).remove(Component)` || 读取资源 | `Res(ResourceType)` || 修改资源 | `ResMut(ResourceType)` |+| 响应新增组件 | `Query(Added(Component))` |+| 响应变更组件 | `Query(Changed(Component))` |+| 响应移除组件 | `Removed(Component)` |+| 系统间发送事件 | `EventWriter(Event)` / `EventReader(Event)` |详见[系统](/microes/zh/core-concepts/systems/)和[查询](/microes/zh/core-concepts/queries/)。@@ -157,3 +163,5 @@ addSystem(defineSystem(- [系统](/microes/zh/core-concepts/systems/) — 定义和调度系统- [查询](/microes/zh/core-concepts/queries/) — 查询实体- [资源](/microes/zh/core-concepts/resources/) — 全局单例数据+- [变更检测](/microes/zh/core-concepts/change-detection/) — 响应组件变更+- [事件](/microes/zh/core-concepts/events/) — 解耦的系统间通信diff --git a/docs/astro/src/content/docs/zh/core-concepts/events.mdx b/docs/astro/src/content/docs/zh/core-concepts/events.mdxnew file mode 100644index 000000000..2f565e9e3--- /dev/null+++ b/docs/astro/src/content/docs/zh/core-concepts/events.mdx@@ -0,0 +1,190 @@+---+title: 事件+description: 在 ESEngine 中系统之间发送和接收消息+---++import { Aside } from '@astrojs/starlight/components';++事件让系统之间无需互相知晓即可通信。一个系统发送事件,其他任意数量的系统都可以读取——系统之间没有直接耦合。++## 定义事件++使用 `defineEvent` 和 TypeScript 接口定义事件:++```typescript+import { defineEvent } from 'esengine';++interface DamageEvent {+ target: Entity;+ amount: number;+ source?: Entity;+}++const Damage = defineEvent<DamageEvent>('Damage');+```++## 发送事件++使用 `EventWriter` 作为系统参数来发送事件:++```typescript+import { defineSystem, addSystem, EventWriter, Query, Health } from 'esengine';++addSystem(defineSystem(+ [EventWriter(Damage), Query(Health, Enemy)],+ (writer, query) => {+ for (const [entity, health] of query) {+ if (health.current <= 0) {+ writer.send({ target: entity, amount: 0 });+ }+ }+ }+));+```++在一个系统中可以多次调用 `writer.send()`——所有事件都会被收集。++## 读取事件++使用 `EventReader` 作为系统参数来接收事件:++```typescript+import { defineSystem, addSystem, EventReader, Commands } from 'esengine';++addSystem(defineSystem(+ [EventReader(Damage)],+ (events) => {+ for (const event of events) {+ console.log(`Entity ${event.target} took ${event.amount} damage`);+ }+ }+));+```++`EventReader` 是可迭代的——使用 `for...of` 处理每个事件。它还提供工具方法:++```typescript+events.isEmpty() // 本帧是否没有事件+events.toArray() // 将所有事件收集为数组+```++多个系统可以读取同一事件类型,每个 reader 都能看到上一帧的所有事件。++## 事件生命周期++事件使用**双缓冲**设计:++1. **帧开始**:缓冲区交换——上一帧写入的事件变为可读,旧的读取缓冲区被清空+2. **帧内**:writer 向写缓冲区推送,reader 从读缓冲区读取+3. **下一帧**:再次交换++```+帧 1: systemA 发送 Damage ──────────────────┐+帧 2: systemB 读取 Damage(来自帧 1)◄───────┘+ systemA 发送新 Damage ────────────────┐+帧 3: systemB 读取 Damage(来自帧 2)◄──────┘+ 帧 1 的事件已消失+```++<Aside type="note">+事件恰好持续 **1 帧**。如果没有系统读取,它们会在下次交换时被静默丢弃。这是有意为之——事件用于帧间通信,不是持久状态。+</Aside>++## 实战示例:伤害系统++一个完整的示例,包含三个解耦的系统:++```typescript+import { defineEvent, defineSystem, addSystem, EventWriter, EventReader, Query, Mut, Commands, Health, Sprite } from 'esengine';++// 1. 定义事件+interface DamageEvent {+ target: Entity;+ amount: number;+}+const Damage = defineEvent<DamageEvent>('Damage');++// 2. 战斗系统——检测命中并发送伤害事件+const combatSystem = defineSystem(+ [EventWriter(Damage), Query(Transform, Projectile), Query(Transform, Health, Enemy)],+ (damage, projectiles, enemies) => {+ for (const [_, pTransform, proj] of projectiles) {+ for (const [enemy, eTransform] of enemies) {+ if (distance(pTransform, eTransform) < proj.radius) {+ damage.send({ target: enemy, amount: proj.power });+ }+ }+ }+ }+);++// 3. 生命系统——应用伤害+const healthSystem = defineSystem(+ [EventReader(Damage), Query(Mut(Health))],+ (events, query) => {+ for (const { target, amount } of events) {+ const result = query.get(target);+ if (result) {+ const [_, health] = result;+ health.current -= amount;+ }+ }+ }+);++// 4. 特效系统——显示命中效果(读取相同事件)+const hitVFXSystem = defineSystem(+ [EventReader(Damage), Query(Transform)],+ (events, query) => {+ for (const { target } of events) {+ const result = query.get(target);+ if (result) {+ const [_, transform] = result;+ spawnHitParticle(transform.position);+ }+ }+ }+);+```++三个系统,一种事件类型,彼此之间零直接依赖。++## 多种事件类型++一个系统可以写入和读取多种事件类型:++```typescript+const PlayerDied = defineEvent<{ entity: Entity }>('PlayerDied');+const ScoreChanged = defineEvent<{ delta: number }>('ScoreChanged');++defineSystem(+ [EventReader(Damage), EventWriter(PlayerDied), EventWriter(ScoreChanged)],+ (damageEvents, deathWriter, scoreWriter) => {+ for (const { target, amount } of damageEvents) {+ if (isPlayer(target) && getHealth(target) <= 0) {+ deathWriter.send({ entity: target });+ scoreWriter.send({ delta: -100 });+ }+ }+ }+);+```++## 何时使用事件 vs 直接查询++| 使用事件 | 使用查询 |+|---------|---------|+| 一次性通知(命中、死亡、得分) | 持续状态(位置、生命值) |+| 多个消费者需要相同数据 | 单个系统拥有逻辑 |+| 跨模块的解耦系统 | 紧密相关的系统 |+| 时机很重要(*这一帧*发生的) | 当前值更重要 |++<Aside type="tip">+如果你发现自己添加了一个布尔标记组件,只是为了表示"发生了某事",然后下一帧清除它——这正是使用事件的完美场景。+</Aside>++## 下一步++- [变更检测](/microes/zh/core-concepts/change-detection/) — 响应组件的添加和修改+- [系统](/microes/zh/core-concepts/systems/) — 系统参数和调度+- [资源](/microes/zh/core-concepts/resources/) — 全局单例数据diff --git a/docs/astro/src/content/docs/zh/core-concepts/queries.mdx b/docs/astro/src/content/docs/zh/core-concepts/queries.mdxindex 4fd1aa234..e89eda90c 100644--- a/docs/astro/src/content/docs/zh/core-concepts/queries.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/queries.mdx@@ -10,9 +10,9 @@ description: 在 ESEngine 中按组件查询实体查询匹配场景中所有拥有**全部**列出组件的实体:```typescript-import { defineSystem, addSystem, Query, Mut, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Query, Mut, Transform, Sprite } from 'esengine';-addSystem(defineSystem([Query(Mut(LocalTransform), Sprite)], (query) => {+addSystem(defineSystem([Query(Mut(Transform), Sprite)], (query) => {for (const [entity, transform, sprite] of query) {transform.position.x += 1;}@@ -26,10 +26,10 @@ addSystem(defineSystem([Query(Mut(LocalTransform), Sprite)], (query) => {默认情况下,查询结果是只读的。使用 `Mut()` 获取特定组件的可变访问:```typescript-import { Query, Mut, LocalTransform, Sprite } from 'esengine';+import { Query, Mut, Transform, Sprite } from 'esengine';defineSystem(- [Query(Mut(LocalTransform), Sprite)],+ [Query(Mut(Transform), Sprite)],(query) => {for (const [entity, transform, sprite] of query) {transform.position.x += 1; // 可写@@ -77,6 +77,55 @@ query.count(); // 匹配的实体数量query.toArray(); // 将所有结果收集到数组中```+## 变更检测过滤器++用 `Added()`、`Changed()` 包裹组件,或使用 `Removed()` 来响应组件的生命周期事件。++### Added++匹配自上次系统运行以来新增了组件的实体:++```typescript+import { Query, Added, Transform } from 'esengine';++defineSystem([Query(Added(Transform))], (query) => {+ for (const [entity, transform] of query) {+ console.log('New transform on', entity);+ }+});+```++### Changed++匹配自上次 tick 以来组件数据被修改(通过 `Mut()`)的实体:++```typescript+import { Query, Changed, Mut, Text } from 'esengine';++defineSystem([Query(Changed(Text))], (query) => {+ for (const [entity, text] of query) {+ console.log('Text changed on', entity, text.content);+ }+});+```++### Removed++`Removed()` 是独立参数(不在 `Query` 内部)。它返回自上次 tick 以来被移除了指定组件的实体:++```typescript+import { Removed } from 'esengine';+import { Health } from './components';++defineSystem([Removed(Health)], (removed) => {+ for (const entity of removed) {+ console.log('Health removed from', entity);+ }+});+```++详见[变更检测](/microes/zh/core-concepts/change-detection/)了解基于 tick 的追踪机制。+## 多个查询一个系统可以有多个查询来交叉引用不同类型的实体:@@ -88,7 +137,7 @@ const Player = defineTag('Player');const Enemy = defineTag('Enemy');defineSystem(- [Query(LocalTransform, Player), Query(LocalTransform, Enemy)],+ [Query(Transform, Player), Query(Transform, Enemy)],(players, enemies) => {for (const [_, playerTransform] of players) {for (const [_, enemyTransform] of enemies) {@@ -104,10 +153,10 @@ defineSystem(查询经常与资源一起使用:```typescript-import { Res, Time, Input, Query, Mut, LocalTransform } from 'esengine';+import { Res, Time, Input, Query, Mut, Transform } from 'esengine';defineSystem(- [Res(Time), Res(Input), Query(Mut(LocalTransform), Player)],+ [Res(Time), Res(Input), Query(Mut(Transform), Player)],(time, input, query) => {for (const [entity, transform] of query) {if (input.isKeyDown('KeyD')) {@@ -123,14 +172,14 @@ defineSystem(定义 `Hitbox`、`Player` 和 `Enemy` 组件,在场景编辑器中挂载到实体上,然后查询:```typescript-import { defineSystem, defineComponent, defineTag, addSystem, Query, LocalTransform } from 'esengine';+import { defineSystem, defineComponent, defineTag, addSystem, Query, Transform } from 'esengine';const Hitbox = defineComponent('Hitbox', { width: 50, height: 50 });const Player = defineTag('Player');const Enemy = defineTag('Enemy');addSystem(defineSystem(- [Query(LocalTransform, Hitbox, Player), Query(LocalTransform, Hitbox, Enemy)],+ [Query(Transform, Hitbox, Player), Query(Transform, Hitbox, Enemy)],(players, enemies) => {for (const [_, pPos, pBox] of players) {for (const [_, ePos, eBox] of enemies) {@@ -172,5 +221,7 @@ const despawnDead = defineSystem(## 下一步+- [变更检测](/microes/zh/core-concepts/change-detection/) — 基于 tick 的 Added、Changed、Removed 追踪+- [事件](/microes/zh/core-concepts/events/) — 解耦的系统间通信- [资源](/microes/zh/core-concepts/resources/) — 全局单例数据如 Time 和 Input- [组件](/microes/zh/core-concepts/components/) — 所有内置和自定义组件类型diff --git a/docs/astro/src/content/docs/zh/core-concepts/resources.mdx b/docs/astro/src/content/docs/zh/core-concepts/resources.mdxindex 90c428a46..fed799f2d 100644--- a/docs/astro/src/content/docs/zh/core-concepts/resources.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/resources.mdx@@ -88,6 +88,23 @@ defineSystem([Res(Input)], (input) => {| `isMouseButtonReleased(button)` | 鼠标按钮在这帧被释放 || `getScrollDelta()` | 返回 `{ x, y }` 滚轮增量 |+### UIEvents++每帧收集的 UI 交互事件。UI 插件激活时自动可用(默认)。++```typescript+import { Res } from 'esengine';+import { UIEvents } from 'esengine';++defineSystem([Res(UIEvents)], (events) => {+ for (const e of events.query('click')) {+ console.log('Clicked:', e.entity);+ }+});+```++详见 [UI 与文本](/microes/zh/guides/ui/)了解完整的事件类型列表。+## 自定义资源### defineResource@@ -136,7 +153,7 @@ defineSystem([ResMut(GameState)], (state) => {import {defineSystem, defineResource, defineTag,addStartupSystem, addSystem, Commands, Query, ResMut,- LocalTransform+ Transform} from 'esengine';const Score = defineResource({ value: 0 });@@ -148,7 +165,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {}));addSystem(defineSystem(- [Commands(), ResMut(Score), Query(LocalTransform, Player), Query(LocalTransform, Coin)],+ [Commands(), ResMut(Score), Query(Transform, Player), Query(Transform, Coin)],(cmds, score, players, coins) => {for (const [_, pPos] of players) {for (const [coinEntity, cPos] of coins) {@@ -168,3 +185,4 @@ addSystem(defineSystem(- [系统](/microes/zh/core-concepts/systems/) — 系统如何使用资源和查询- [组件](/microes/zh/core-concepts/components/) — 附加在实体上的数据+- [事件](/microes/zh/core-concepts/events/) — 解耦的系统间通信diff --git a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh/core-concepts/systems.mdxindex c6135dff5..7c5d3e0b8 100644--- a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx@@ -10,10 +10,10 @@ import { Aside } from '@astrojs/starlight/components';## 定义系统```typescript-import { defineSystem, Res, Time, Query, Mut, LocalTransform, Velocity } from 'esengine';+import { defineSystem, Res, Time, Query, Mut, Transform, Velocity } from 'esengine';const movementSystem = defineSystem(- [Res(Time), Query(Mut(LocalTransform), Velocity)],+ [Res(Time), Query(Mut(Transform), Velocity)],(time, query) => {for (const [entity, transform, velocity] of query) {transform.position.x += velocity.linear.x * time.delta;@@ -23,11 +23,11 @@ const movementSystem = defineSystem();```-此系统自动处理场景中所有同时拥有 `LocalTransform` 和 `Velocity` 组件的实体。+此系统自动处理场景中所有同时拥有 `Transform` 和 `Velocity` 组件的实体。`defineSystem` 接受两个参数:-1. **参数列表** — `Query`、`Res`、`ResMut` 或 `Commands` 描述符的数组+1. **参数列表** — `Query`、`Res`、`ResMut`、`Commands`、`EventWriter` 或 `EventReader` 描述符的数组2. **函数** — 按相同顺序接收解析后的参数## 注册系统@@ -76,16 +76,16 @@ addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);同一 Schedule 内的多个系统默认按注册顺序执行。如果系统之间有执行顺序依赖,可以通过 `defineSystem` 的第三个参数指定 `runBefore` 或 `runAfter`:```typescript-import { defineSystem, Query, Res, Time, Mut, LocalTransform, Velocity, Sprite } from 'esengine';+import { defineSystem, Query, Res, Time, Mut, Transform, Velocity, Sprite } from 'esengine';const movementSystem = defineSystem(- [Res(Time), Query(Mut(LocalTransform), Velocity)],+ [Res(Time), Query(Mut(Transform), Velocity)],(time, query) => { /* ... */ },{ name: 'movement' });const renderSystem = defineSystem(- [Query(LocalTransform, Sprite)],+ [Query(Transform, Sprite)],(query) => { /* ... */ },{ name: 'render', runAfter: ['movement'] });@@ -107,14 +107,14 @@ const renderSystem = defineSystem(在运行时创建、修改和销毁实体:```typescript-import { Commands, Sprite, LocalTransform, Velocity, defineResource } from 'esengine';+import { Commands, Sprite, Transform, Velocity, defineResource } from 'esengine';const Score = defineResource({ value: 0 });defineSystem([Commands()], (cmds) => {// 创建新实体并添加组件(可链式调用)const bullet = cmds.spawn()- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } }).insert(Sprite, { size: { x: 8, y: 8 } }).id();@@ -159,9 +159,9 @@ defineSystem([Commands()], (cmds) => {遍历具有特定组件的实体:```typescript-import { Query, Mut, LocalTransform, Sprite } from 'esengine';+import { Query, Mut, Transform, Sprite } from 'esengine';-defineSystem([Query(Mut(LocalTransform), Sprite)], (query) => {+defineSystem([Query(Mut(Transform), Sprite)], (query) => {for (const [entity, transform, sprite] of query) {transform.position.x += 1;}@@ -192,11 +192,41 @@ defineSystem([ResMut(GameState)], (state) => {详见[资源](/microes/zh/core-concepts/resources/)。+### EventWriter++从系统中发送事件:++```typescript+import { defineEvent, EventWriter } from 'esengine';++const DamageEvent = defineEvent<{ target: number; amount: number }>('Damage');++defineSystem([EventWriter(DamageEvent)], (writer) => {+ writer.send({ target: enemy, amount: 25 });+});+```++### EventReader++接收其他系统发送的事件:++```typescript+import { EventReader } from 'esengine';++defineSystem([EventReader(DamageEvent)], (reader) => {+ for (const event of reader) {+ console.log(`${event.target} took ${event.amount} damage`);+ }+});+```++详见[事件](/microes/zh/core-concepts/events/)。+### 组合参数```typescriptdefineSystem(- [Commands(), Res(Time), Res(Input), Query(Mut(LocalTransform), Velocity)],+ [Commands(), Res(Time), Res(Input), Query(Mut(Transform), Velocity)],(cmds, time, input, query) => {// 所有参数都可用}@@ -215,11 +245,11 @@ export const Speed = defineComponent('Speed', { value: 200 });```typescript// src/systems/movement.ts-import { defineSystem, addSystem, Res, Time, Input, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Time, Input, Query, Mut, Transform } from 'esengine';import { Speed } from '../components/Speed';addSystem(defineSystem(- [Res(Time), Res(Input), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Res(Input), Query(Mut(Transform), Speed)],(time, input, query) => {for (const [entity, transform, speed] of query) {if (input.isKeyDown('KeyD')) {@@ -241,3 +271,5 @@ addSystem(defineSystem(- [查询](/microes/zh/core-concepts/queries/) — 查询过滤器和迭代方法- [资源](/microes/zh/core-concepts/resources/) — 全局单例数据+- [变更检测](/microes/zh/core-concepts/change-detection/) — 响应组件变更+- [事件](/microes/zh/core-concepts/events/) — 解耦的系统间通信diff --git a/docs/astro/src/content/docs/zh/getting-started/introduction.mdx b/docs/astro/src/content/docs/zh/getting-started/introduction.mdxindex ea888f8c7..d363822b8 100644--- a/docs/astro/src/content/docs/zh/getting-started/introduction.mdx+++ b/docs/astro/src/content/docs/zh/getting-started/introduction.mdx@@ -12,12 +12,12 @@ ESEngine 是一个轻量级 2D 游戏引擎,提供 **TypeScript SDK**,后端使用编辑器创建项目、在场景中放置实体、可视化地挂载组件。在 TypeScript 中编写游戏逻辑 — 定义自定义组件和操作场景实体的系统:```typescript-import { defineComponent, defineSystem, addSystem, Query, Res, Time, Mut, LocalTransform } from 'esengine';+import { defineComponent, defineSystem, addSystem, Query, Res, Time, Mut, Transform } from 'esengine';const Speed = defineComponent('Speed', { value: 200 });addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Query(Mut(Transform), Speed)],(time, query) => {for (const [entity, transform, speed] of query) {transform.position.x += speed.value * time.delta;diff --git a/docs/astro/src/content/docs/zh/getting-started/quick-start.mdx b/docs/astro/src/content/docs/zh/getting-started/quick-start.mdxindex d7866c428..53f54ab4f 100644--- a/docs/astro/src/content/docs/zh/getting-started/quick-start.mdx+++ b/docs/astro/src/content/docs/zh/getting-started/quick-start.mdx@@ -19,7 +19,7 @@ import { Steps, Aside } from '@astrojs/starlight/components';3. **在编辑器中添加 Sprite 实体**- 在 Hierarchy 面板中创建新实体,添加 `LocalTransform` 和 `Sprite` 组件。设置 Sprite 尺寸为 `100 x 100`,选择一个颜色。+ 在 Hierarchy 面板中创建新实体,添加 `Transform` 和 `Sprite` 组件。设置 Sprite 尺寸为 `100 x 100`,选择一个颜色。4. **创建 `src/main.ts`**,填入以下代码:@@ -31,12 +31,12 @@ import { Steps, Aside } from '@astrojs/starlight/components';Res,Time,Mut,- LocalTransform,+ Transform,Sprite,} from 'esengine';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Sprite)],+ [Res(Time), Query(Mut(Transform), Sprite)],(time, query) => {for (const [entity, transform, sprite] of query) {transform.position.x = Math.sin(time.elapsed) * 100;@@ -56,7 +56,7 @@ import { Steps, Aside } from '@astrojs/starlight/components';在 ESEngine 中,实体和组件在**场景编辑器**中创建。你的代码不创建它们 — 而是定义**系统**来查询和操作场景中的实体。-第 3 步放置的精灵已经有 `LocalTransform` 和 `Sprite` 组件。第 4 步的系统通过 `Query(Mut(LocalTransform), Sprite)` 找到它并执行动画。+第 3 步放置的精灵已经有 `Transform` 和 `Sprite` 组件。第 4 步的系统通过 `Query(Mut(Transform), Sprite)` 找到它并执行动画。### 自定义组件@@ -73,11 +73,11 @@ export const Speed = defineComponent('Speed', { value: 200 });```typescript// src/systems/movement.ts-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform } from 'esengine';import { Speed } from '../components/Speed';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Query(Mut(Transform), Speed)],(time, query) => {for (const [entity, transform, speed] of query) {transform.position.x += speed.value * time.delta;@@ -110,14 +110,14 @@ addSystemToSchedule(Schedule.FixedUpdate, system); // 固定间隔运行需要在运行时创建实体时(如子弹、粒子),使用 `Commands`:```typescript-import { addStartupSystem, defineSystem, Commands, Sprite, LocalTransform } from 'esengine';+import { addStartupSystem, defineSystem, Commands, Sprite, Transform } from 'esengine';addStartupSystem(defineSystem([Commands()],(cmds) => {cmds.spawn().insert(Sprite, { size: { x: 10, y: 10 } })- .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } });+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } });}));```diff --git a/docs/astro/src/content/docs/zh/guides/custom-draw.mdx b/docs/astro/src/content/docs/zh/guides/custom-draw.mdxindex a14e0f9ef..370c0d8dd 100644--- a/docs/astro/src/content/docs/zh/guides/custom-draw.mdx+++ b/docs/astro/src/content/docs/zh/guides/custom-draw.mdx@@ -192,13 +192,13 @@ const primitives = Draw.getPrimitiveCount();```typescriptimport { registerDrawCallback, Draw } from 'esengine';-import { defineSystem, addSystem, Query, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Query, Transform } from 'esengine';import { BoxCollider } from 'esengine/physics';const boxes: Array<{ x: number; y: number; w: number; h: number }> = [];addSystem(defineSystem(- [Query(LocalTransform, BoxCollider)],+ [Query(Transform, BoxCollider)],(query) => {boxes.length = 0;for (const [entity, transform, collider] of query) {diff --git a/docs/astro/src/content/docs/zh/guides/debugging.mdx b/docs/astro/src/content/docs/zh/guides/debugging.mdxindex ba0e1f591..233182e6e 100644--- a/docs/astro/src/content/docs/zh/guides/debugging.mdx+++ b/docs/astro/src/content/docs/zh/guides/debugging.mdx@@ -211,7 +211,7 @@ console.log('Primitives:', Draw.getPrimitiveCount());```typescriptconst narrowSystem = defineSystem(- [Query(Mut(LocalTransform), Velocity, Player)],+ [Query(Mut(Transform), Velocity, Player)],(query) => {for (const [entity, transform, velocity] of query) {transform.position.x += velocity.linear.x;diff --git a/docs/astro/src/content/docs/zh/guides/game-view.mdx b/docs/astro/src/content/docs/zh/guides/game-view.mdxindex 11380ebf8..94640d2ee 100644--- a/docs/astro/src/content/docs/zh/guides/game-view.mdx+++ b/docs/astro/src/content/docs/zh/guides/game-view.mdx@@ -5,7 +5,7 @@ description: 使用 Game View 面板预览和调试游戏import { Aside } from '@astrojs/starlight/components';-**Game View** 是编辑器中的游戏预览面板,提供播放控制、分辨率模拟和实时调试功能。你可以在不离开编辑器的情况下快速验证游戏逻辑和视觉效果。+**Game View** 是编辑器中的游戏预览面板,提供播放控制、分辨率模拟、实时属性编辑和运行时调试功能。你可以在不离开编辑器的情况下快速验证和调整游戏逻辑。## 启动预览@@ -13,6 +13,10 @@ import { Aside } from '@astrojs/starlight/components';点击 **Stop** 按钮停止预览,Game View 会回到初始的空白状态,编辑器恢复到正常编辑模式。+### 共享 Canvas++Scene View 和 Game View 共享同一个离屏 WebGL Canvas。预览启动后,两个视图从同一渲染管线输出——Scene View 显示带 Gizmo 的编辑器视口,Game View 显示游戏相机画面。这避免了 WASM 实例的重复创建,保持较低的内存占用。+## 播放控制工具栏提供以下播放控制按钮:@@ -66,6 +70,10 @@ import { Aside } from '@astrojs/starlight/components';启动预览后,编辑器进入 **Play Mode**。这是一个特殊的运行时调试模式,Hierarchy 面板和 Inspector 面板会切换到运行时视图。+### 状态快照++进入 Play Mode 时,编辑器会对当前场景拍摄**完整快照**——包括实体树、组件数据、选择状态和修改标记。停止预览时,快照会被恢复,所有运行时修改都会被丢弃。这意味着你可以在播放期间自由实验,不会影响已保存的场景。+### Hierarchy 面板进入 Play Mode 后,Hierarchy 面板会发生以下变化:@@ -85,22 +93,68 @@ import { Aside } from '@astrojs/starlight/components';- 显示蓝色 **RUNTIME** 标记- 列出该实体的所有运行时组件及其当前属性值-- 属性值每 500 毫秒自动刷新,反映游戏中的实时状态+- 属性值定期自动刷新,反映游戏中的实时状态- 支持直接编辑数值、布尔值、字符串和向量属性,修改会立即发送到游戏实例中生效-<Aside type="caution">- Play Mode 下在 Inspector 中做的修改仅影响运行中的游戏实例。停止预览后,所有运行时修改会丢失,场景数据恢复到启动预览前的状态。-</Aside>-### 退出 Play Mode点击 **Stop** 按钮后:- 游戏实例被销毁+- 场景从 Play 启动时的快照恢复- Hierarchy 面板恢复编辑模式的实体树,展开状态自动还原- Inspector 面板恢复到编辑模式- 所有运行时修改不会保存到场景文件+## 实时编辑++Play Mode 下可以在 Inspector 中编辑实体属性,修改会实时反映到游戏中。这对于调试速度、重力、UI 位置等参数非常实用。++### 可编辑的属性++| 属性类型 | 可编辑 |+|---------|--------|+| 数值(int、float) | 是 |+| 布尔值 | 是 |+| 字符串 | 是 |+| 向量(Vec2、Vec3) | 是 |+| 颜色 | 是 |+| 枚举 | 是 |++还可以通过运行时 API 进行结构性操作:++- **创建**新实体+- **销毁**现有实体+- **添加**或**移除**实体上的组件+- **重命名**和**重设父级**++### 不可编辑的内容++- **Scene View Gizmo** 在 Play 期间被禁用——不能通过拖拽 Gizmo 移动实体+- **组件排序**不可用+- **Prefab 编辑**被禁用+- **可见性开关**在 Play 期间不生效++<Aside type="caution">+ 所有实时编辑都是临时的。停止预览后,场景会恢复到快照状态。无法选择性保留 Play Mode 中的修改。+</Aside>++### 编辑工作流++典型的实时编辑工作流:++1. **Play** — 启动预览+2. **选择** Hierarchy 中的运行时实体+3. **调整** Inspector 中的属性值(如速度、偏移量)+4. **观察** Game View 中的实时效果+5. **暂停 + 单步** 逐帧检查行为+6. **Stop** — 记下满意的数值+7. **应用** 在编辑模式下将数值写入场景++<Aside type="tip">+ 正在编辑的输入框不会被自动刷新覆盖,确保手动输入不被打断。+</Aside>+## FPS 显示预览运行时,工具栏右侧会实时显示当前帧率(FPS)。停止预览后 FPS 显示自动隐藏。@@ -110,4 +164,4 @@ import { Aside } from '@astrojs/starlight/components';- Play Mode 下 Hierarchy 面板的编辑功能被禁用,包括拖拽排序、右键菜单和重命名- 运行时实体列表会定期更新,大量实体时可能存在短暂延迟- 分辨率切换在预览运行中也可以使用,画面会立即调整大小-- Inspector 中正在编辑的输入框不会被自动刷新覆盖,确保手动输入不被打断+- 共享 Canvas 同一时间仅支持一个活跃的游戏相机diff --git a/docs/astro/src/content/docs/zh/guides/input.mdx b/docs/astro/src/content/docs/zh/guides/input.mdxindex ac8d8e993..a55dac0e2 100644--- a/docs/astro/src/content/docs/zh/guides/input.mdx+++ b/docs/astro/src/content/docs/zh/guides/input.mdx@@ -12,10 +12,10 @@ ESEngine 通过 `Input` 资源提供输入处理。`InputPlugin` 由 `createWebA通过 `Res(Input)` 系统参数访问输入状态:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Input, Query, Mut, Transform } from 'esengine';addSystem(defineSystem(- [Res(Input), Query(Mut(LocalTransform))],+ [Res(Input), Query(Mut(Transform))],(input, query) => {for (const [entity, transform] of query) {if (input.isKeyDown('KeyW')) {@@ -135,14 +135,14 @@ if (input.isMouseButtonDown(0)) {```typescriptimport {defineSystem, defineComponent, defineTag, addSystem,- Res, Input, Time, Query, Mut, LocalTransform+ Res, Input, Time, Query, Mut, Transform} from 'esengine';const Player = defineTag('Player');const MoveSpeed = defineComponent('MoveSpeed', { value: 200 });addSystem(defineSystem(- [Res(Input), Res(Time), Query(Mut(LocalTransform), MoveSpeed, Player)],+ [Res(Input), Res(Time), Query(Mut(Transform), MoveSpeed, Player)],(input, time, query) => {for (const [entity, transform, speed] of query) {const velocity = { x: 0, y: 0 };diff --git a/docs/astro/src/content/docs/zh/guides/physics.mdx b/docs/astro/src/content/docs/zh/guides/physics.mdxindex 251b92f7a..bb2dbdf6f 100644--- a/docs/astro/src/content/docs/zh/guides/physics.mdx+++ b/docs/astro/src/content/docs/zh/guides/physics.mdx@@ -32,7 +32,7 @@ import { Aside } from '@astrojs/starlight/components';## 组件-在场景编辑器中将物理组件与 `LocalTransform` 一起添加到实体上。+在场景编辑器中将物理组件与 `Transform` 一起添加到实体上。### RigidBody@@ -120,7 +120,7 @@ addSystem(defineSystem(在编辑器中设置地面、玩家和金币传感器,然后用代码处理事件:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Res, Input, Query, Mut, Transform } from 'esengine';import { RigidBody, PhysicsEvents } from 'esengine/physics';import { Player, Coin } from './components';@@ -135,9 +135,9 @@ addSystem(defineSystem(```**编辑器设置:**-- **地面**:`LocalTransform` + `RigidBody`(bodyType=0 Static)+ `BoxCollider`(halfExtents=`{x:10, y:0.5}`)+ `Sprite`-- **玩家**:`LocalTransform` + `RigidBody`(bodyType=2 Dynamic,fixedRotation=true)+ `BoxCollider` + `Sprite` + `Player` 标签-- **金币**:`LocalTransform` + `RigidBody`(bodyType=0 Static)+ `CircleCollider`(isSensor=true)+ `Sprite` + `Coin` 标签+- **地面**:`Transform` + `RigidBody`(bodyType=0 Static)+ `BoxCollider`(halfExtents=`{x:10, y:0.5}`)+ `Sprite`+- **玩家**:`Transform` + `RigidBody`(bodyType=2 Dynamic,fixedRotation=true)+ `BoxCollider` + `Sprite` + `Player` 标签+- **金币**:`Transform` + `RigidBody`(bodyType=0 Static)+ `CircleCollider`(isSensor=true)+ `Sprite` + `Coin` 标签## Physics API(进阶)diff --git a/docs/astro/src/content/docs/zh/guides/plugins.mdx b/docs/astro/src/content/docs/zh/guides/plugins.mdxindex 3e2521143..bf555e8f3 100644--- a/docs/astro/src/content/docs/zh/guides/plugins.mdx+++ b/docs/astro/src/content/docs/zh/guides/plugins.mdx@@ -24,10 +24,23 @@ import { Aside } from '@astrojs/starlight/components';| 插件 | 组件 ||------|------|| 文本 | `Text` — 每帧将文本内容渲染为精灵纹理 |-| UI 遮罩 | `UIMask` — 基于模板测试的 UI 元素遮罩 |-| UI 布局 | `UIRect`、`ScreenSpace` — 相对于相机的锚点 UI 布局 |+| 图片 | `Image` — 显示图片,支持切片、平铺和填充模式 |+| UI 遮罩 | `UIMask` — 基于裁剪/模板测试的 UI 元素遮罩 |+| UI 布局 | `UIRect` — 相对于相机的锚点 UI 布局 |+| UI 渲染排序 | 自动为 UI 层级分配渲染顺序 || UI 交互 | `Interactable`、`Button`、`UIInteraction`、`UIEvents` — 指针命中测试和按钮状态 || 文本输入 | `TextInput` — 可编辑的文本输入框,使用平台原生输入 |+| 开关 | `Toggle`、`ToggleGroup` — 复选框和单选按钮行为 |+| 滑块 | `Slider` — 带填充和拖拽手柄的交互式值滑块 |+| 进度条 | `ProgressBar` — 非交互式进度显示 |+| 下拉框 | `Dropdown` — 下拉列表选择器 |+| 滚动视图 | `ScrollView` — 支持惯性和弹性回弹的可滚动容器 |+| 列表视图 | `ListView` — 大列表的虚拟滚动 |+| 拖拽 | `Draggable` — UI 元素的拖拽移动 |+| 焦点 | `Focusable` — 键盘焦点和 Tab 导航 |+| 安全区域 | `SafeArea` — 适配设备安全区域(刘海、圆角) |+| 布局组 | `LayoutGroup` — 带方向、间距和对齐的网格式布局 |+| 弹性布局 | `FlexContainer`、`FlexItem` — 类 CSS Flexbox 的自动子元素排列 |以上插件在每个项目中默认激活。你可以直接从编辑器的组件选择器中使用它们的组件——无需任何设置。@@ -111,6 +124,26 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {}));```+### 事件++事件用于系统间的解耦通信:++```typescript+import { defineEvent, EventWriter, EventReader, defineSystem, addSystem } from 'esengine';++const ScoreEvent = defineEvent<{ points: number }>('Score');++addSystem(defineSystem([EventWriter(ScoreEvent)], (writer) => {+ writer.send({ points: 10 });+}));++addSystem(defineSystem([EventReader(ScoreEvent)], (reader) => {+ for (const e of reader) {+ console.log('Scored:', e.points);+ }+}));+```+## 系统调度系统按照定义的顺序在每帧中执行:diff --git a/docs/astro/src/content/docs/zh/guides/prefabs.mdx b/docs/astro/src/content/docs/zh/guides/prefabs.mdxindex a9576a48b..87259cc49 100644--- a/docs/astro/src/content/docs/zh/guides/prefabs.mdx+++ b/docs/astro/src/content/docs/zh/guides/prefabs.mdx@@ -76,7 +76,7 @@ const { root } = await prefabs.instantiate('prefabs/Enemy.esprefab', {{prefabEntityId: 1,type: 'property',- componentType: 'LocalTransform',+ componentType: 'Transform',propertyName: 'position',value: { x: 200, y: 100, z: 0 },},diff --git a/docs/astro/src/content/docs/zh/guides/rendering.mdx b/docs/astro/src/content/docs/zh/guides/rendering.mdxindex 39ab7e991..fcf910e41 100644--- a/docs/astro/src/content/docs/zh/guides/rendering.mdx+++ b/docs/astro/src/content/docs/zh/guides/rendering.mdx@@ -45,10 +45,10 @@ ESEngine 使用基于组件的渲染系统。在场景编辑器中为实体添查询相机实体并修改其 transform:```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform, Camera } from 'esengine';+import { defineSystem, addSystem, Res, Input, Query, Mut, Transform, Camera } from 'esengine';addSystem(defineSystem(- [Res(Input), Query(Mut(LocalTransform), Camera)],+ [Res(Input), Query(Mut(Transform), Camera)],(input, query) => {for (const [entity, transform, camera] of query) {if (input.isKeyDown('ArrowLeft')) {@@ -87,17 +87,17 @@ addSystem(defineSystem(## Transform-每个可见实体都需要 `LocalTransform`。在场景编辑器中添加并在检查器中配置位置、旋转和缩放。+每个可见实体都需要 `Transform`。在场景编辑器中添加并在检查器中配置位置、旋转和缩放。### 旋转旋转使用四元数。绕 Z 轴的 2D 旋转:```typescript-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform, Sprite } from 'esengine';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Sprite)],+ [Res(Time), Query(Mut(Transform), Sprite)],(time, query) => {for (const [entity, transform, sprite] of query) {const angle = time.elapsed;diff --git a/docs/astro/src/content/docs/zh/guides/scenes.mdx b/docs/astro/src/content/docs/zh/guides/scenes.mdxindex 724d7b483..958795bd3 100644--- a/docs/astro/src/content/docs/zh/guides/scenes.mdx+++ b/docs/astro/src/content/docs/zh/guides/scenes.mdx@@ -26,7 +26,7 @@ import { Aside } from '@astrojs/starlight/components';"parent": null,"children": [2],"components": [- { "type": "LocalTransform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },{ "type": "Sprite", "data": { "texture": "player.png", "size": { "x": 32, "y": 32 } } }]}@@ -47,10 +47,10 @@ import { Aside } from '@astrojs/starlight/components';从场景加载的每个实体都会自动获得内置的 `Name` 组件,包含在编辑器中指定的名字。通过查询 `Name` 来查找实体:```typescript-import { defineSystem, addStartupSystem, Query, Name, LocalTransform } from 'esengine';+import { defineSystem, addStartupSystem, Query, Name, Transform } from 'esengine';addStartupSystem(defineSystem(- [Query(Name, LocalTransform)],+ [Query(Name, Transform)],(query) => {for (const [entity, name, transform] of query) {if (name.value === 'Player') {@@ -66,12 +66,12 @@ addStartupSystem(defineSystem(使用 `Query` 按组件查找实体:```typescript-import { defineSystem, addSystem, defineTag, Query, Mut, LocalTransform } from 'esengine';+import { defineSystem, addSystem, defineTag, Query, Mut, Transform } from 'esengine';const Player = defineTag('Player');addSystem(defineSystem(- [Query(Mut(LocalTransform), Player)],+ [Query(Mut(Transform), Player)],(query) => {for (const [entity, transform] of query) {// 处理每个玩家@@ -85,10 +85,10 @@ addSystem(defineSystem(使用 `Children` 组件遍历实体树:```typescript-import { defineSystem, addSystem, Query, Children, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Query, Children, Transform } from 'esengine';addSystem(defineSystem(- [Query(Children, LocalTransform)],+ [Query(Children, Transform)],(query) => {for (const [entity, children, transform] of query) {// children.entities 包含子实体 ID@@ -101,21 +101,21 @@ addSystem(defineSystem(场景实体可以通过父子关系形成树状结构。在编辑器中设置父子关系 — 引擎会自动管理 `Parent` 和 `Children` 组件。-当父实体的 `LocalTransform` 变化时,引擎会通过 `WorldTransform` 组件将变换传播到所有后代。+当父实体的 `Transform` 变化时,引擎会自动将世界变换传播到所有后代。## 动态实体你可以在运行时使用 `Commands` 生成和销毁实体:```typescript-import { defineSystem, addSystem, Commands, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Commands, Transform, Sprite } from 'esengine';addSystem(defineSystem([Commands()],(commands) => {// 生成一个带组件的新实体commands.spawn()- .insert(LocalTransform, { position: { x: 100, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } })+ .insert(Transform, { position: { x: 100, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } }).insert(Sprite, { texture: bulletTexture, color: { r: 1, g: 1, b: 1, a: 1 }, size: { x: 8, y: 8 } });// 销毁实体@@ -312,10 +312,10 @@ console.log(owner.persistent); // false在 `registerScene` 中通过 `systems` 注册的系统会自动包装,仅在场景状态为 `running` 时执行:```typescript-import { defineSystem, Query, Mut, LocalTransform, Schedule } from 'esengine';+import { defineSystem, Query, Mut, Transform, Schedule } from 'esengine';const mySystem = defineSystem(- [Query(Mut(LocalTransform))],+ [Query(Mut(Transform))],(query) => {for (const [entity, transform] of query) {// 更新变换diff --git a/docs/astro/src/content/docs/zh/guides/spine.mdx b/docs/astro/src/content/docs/zh/guides/spine.mdxindex b5636591d..ff2aa8b24 100644--- a/docs/astro/src/content/docs/zh/guides/spine.mdx+++ b/docs/astro/src/content/docs/zh/guides/spine.mdx@@ -5,7 +5,7 @@ description: ESEngine 中的 Spine 骨骼动画import { Aside } from '@astrojs/starlight/components';-`SpineAnimation` 组件播放 [Spine](http://esotericsoftware.com/) 骨骼动画。在场景编辑器中将它和 `LocalTransform` 一起添加到实体上。+`SpineAnimation` 组件播放 [Spine](http://esotericsoftware.com/) 骨骼动画。在场景编辑器中将它和 `Transform` 一起添加到实体上。<Aside type="note">从 v0.3.0 起,Spine 使用独立的 WASM 模块(`spine38` / `spine41` / `spine42`),不再内置于引擎核心。在编辑器中通过 **Settings → Project → Spine Version** 选择版本(`3.8`、`4.1` 或 `4.2`),编辑器会自动加载对应的运行时,无需编写代码。新项目默认为 **None**(不加载 Spine 运行时),需要使用 Spine 时必须显式选择版本。@@ -32,7 +32,7 @@ import { Aside } from '@astrojs/starlight/components';## 设置步骤1. 将 Spine 导出文件(`.json` + `.atlas` + 图片)放到项目的 `assets/` 文件夹-2. 在场景编辑器中:创建实体 → 添加 `LocalTransform` 和 `SpineAnimation`+2. 在场景编辑器中:创建实体 → 添加 `Transform` 和 `SpineAnimation`3. 设置 `skeletonPath` 和 `atlasPath` 指向 Spine 文件4. 设置 `animation` 为要播放的动画名@@ -101,7 +101,7 @@ spine.color = { r: 1, g: 1, b: 1, a: 0.5 }; // 50% 透明```typescriptimport {defineComponent, defineSystem, addSystem,- Res, Input, Time, Query, Mut, LocalTransform, SpineAnimation+ Res, Input, Time, Query, Mut, Transform, SpineAnimation} from 'esengine';const CharacterState = defineComponent('CharacterState', {@@ -110,7 +110,7 @@ const CharacterState = defineComponent('CharacterState', {});addSystem(defineSystem(- [Res(Input), Res(Time), Query(Mut(LocalTransform), Mut(SpineAnimation), Mut(CharacterState))],+ [Res(Input), Res(Time), Query(Mut(Transform), Mut(SpineAnimation), Mut(CharacterState))],(input, time, query) => {for (const [entity, transform, spine, state] of query) {let moving = false;diff --git a/docs/astro/src/content/docs/zh/guides/sprite.mdx b/docs/astro/src/content/docs/zh/guides/sprite.mdxindex 6b3dc26da..743a4f6ab 100644--- a/docs/astro/src/content/docs/zh/guides/sprite.mdx+++ b/docs/astro/src/content/docs/zh/guides/sprite.mdx@@ -5,7 +5,7 @@ description: ESEngine 中的 2D 精灵渲染import { Aside } from '@astrojs/starlight/components';-`Sprite` 组件是显示 2D 图形的主要方式。在场景编辑器中将它和 `LocalTransform` 一起添加到实体上即可显示。+`Sprite` 组件是显示 2D 图形的主要方式。在场景编辑器中将它和 `Transform` 一起添加到实体上即可显示。## 属性@@ -23,15 +23,15 @@ import { Aside } from '@astrojs/starlight/components';## 基本用法-在场景编辑器中:创建实体 → 添加 `LocalTransform` 和 `Sprite` → 在检查器中设置尺寸和颜色。+在场景编辑器中:创建实体 → 添加 `Transform` 和 `Sprite` → 在检查器中设置尺寸和颜色。在系统中操作精灵:```typescript-import { defineSystem, addSystem, Res, Time, Query, Mut, LocalTransform, Sprite } from 'esengine';+import { defineSystem, addSystem, Res, Time, Query, Mut, Transform, Sprite } from 'esengine';addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Sprite)],+ [Res(Time), Query(Mut(Transform), Sprite)],(time, query) => {for (const [entity, transform, sprite] of query) {transform.position.x = Math.sin(time.elapsed) * 100;@@ -135,7 +135,7 @@ addSystem(defineSystem(运行时创建精灵(子弹、粒子等):```typescript-import { defineSystem, addSystem, Commands, Sprite, LocalTransform } from 'esengine';+import { defineSystem, addSystem, Commands, Sprite, Transform } from 'esengine';addSystem(defineSystem([Commands()],@@ -145,7 +145,7 @@ addSystem(defineSystem(size: { x: 10, y: 10 },color: { r: 1, g: 1, b: 0, a: 1 }})- .insert(LocalTransform, {+ .insert(Transform, {position: { x: 0, y: 0, z: 0 }});}diff --git a/docs/astro/src/content/docs/zh/guides/ui.mdx b/docs/astro/src/content/docs/zh/guides/ui.mdxindex dd86eef71..59573ba3b 100644--- a/docs/astro/src/content/docs/zh/guides/ui.mdx+++ b/docs/astro/src/content/docs/zh/guides/ui.mdx@@ -1,84 +1,121 @@---title: UI 与文本-description: ESEngine 中的文本渲染和 UI 布局组件+description: ESEngine 中的 UI 组件、布局、交互和文本渲染---import { Aside } from '@astrojs/starlight/components';-`Text` 和 `UIRect` 组件配合 `Sprite` 实现游戏中的文本渲染。`TextPlugin` 会在每帧自动将文本内容转换为纹理。+ESEngine 提供了完整的 UI 框架,包含布局、交互、文本渲染和一系列预制控件。布局计算在 C++/WASM 中运行以确保性能,所有组件通过 TypeScript 配置。-## 设置步骤+<Aside type="note">+ 所有 UI 插件由 `createWebApp()` 自动注册,无需手动设置。+</Aside>-在场景编辑器中:创建实体 → 添加 `LocalTransform`、`Sprite`、`Text` 和 `UIRect` 组件。+## 快速开始-- **Text** — 定义文本内容和样式(字体、大小、颜色、对齐)-- **UIRect** — 定义布局矩形(尺寸、锚点、旋转中心)-- **Sprite** — 文本系统内部使用,用于显示渲染后的纹理+在编辑器中:右键 Hierarchy → **Create** → **UI** → 选择一个控件(Button、Slider、Text 等)。编辑器会创建预配置好所有必需组件的实体层级。-<Aside type="note">- 无需手动配置 Sprite 组件。`TextPlugin` 会自动根据 Text 内容创建和更新精灵纹理。-</Aside>+通过代码创建 UI:++```typescript+import { defineSystem, addStartupSystem, Commands, Transform, Sprite, UIRect, Text, Parent } from 'esengine';++addStartupSystem(defineSystem([Commands()], (cmds) => {+ const root = cmds.spawn()+ .insert(Transform)+ .insert(UIRect, { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } })+ .id();++ cmds.spawn()+ .insert(Transform)+ .insert(Sprite)+ .insert(UIRect, { size: { x: 200, y: 40 } })+ .insert(Text, { content: 'Hello World', fontSize: 24 })+ .insert(Parent, { entity: root });+}));+```++## 布局-## Text 属性+### UIRect++每个 UI 元素都需要 `UIRect` 来参与布局。它使用锚点系统定义相对于父级的位置和尺寸。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `content` | string | `''` | 显示的文本内容 |-| `fontFamily` | string | `'Arial'` | 字体名称 |-| `fontSize` | number | `24` | 字号(像素) |-| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 RGBA(0–1) |-| `align` | TextAlign | `Left` | 水平对齐方式(编辑器默认为 `Center`) |-| `verticalAlign` | TextVerticalAlign | `Top` | 垂直对齐方式(编辑器默认为 `Middle`) |-| `wordWrap` | boolean | `true` | 启用自动换行 |-| `overflow` | TextOverflow | `Visible` | 溢出处理模式 |-| `lineHeight` | number | `1.2` | 行高倍率 |+| `anchorMin` | Vec2 | `{0.5, 0.5}` | 左下锚点(0–1) |+| `anchorMax` | Vec2 | `{0.5, 0.5}` | 右上锚点(0–1) |+| `offsetMin` | Vec2 | `{0, 0}` | 相对 anchorMin 的像素偏移 |+| `offsetMax` | Vec2 | `{0, 0}` | 相对 anchorMax 的像素偏移 |+| `size` | Vec2 | `{100, 100}` | 宽高(锚点相等时使用) |+| `pivot` | Vec2 | `{0.5, 0.5}` | 旋转和缩放中心点 |++当 `anchorMin` 等于 `anchorMax` 时,元素在锚点处具有固定 `size`。当两者不同时,元素在锚点之间拉伸,尺寸自动计算。++### FlexContainer-## UIRect 属性+类似 CSS Flexbox 的自动子元素排列布局。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `anchorMin` | Vec2 | `{0.5, 0.5}` | 相对于父级的左下角锚点(0–1 范围) |-| `anchorMax` | Vec2 | `{0.5, 0.5}` | 相对于父级的右上角锚点(0–1 范围) |-| `offsetMin` | Vec2 | `{0, 0}` | 从 anchorMin 的像素偏移 |-| `offsetMax` | Vec2 | `{0, 0}` | 从 anchorMax 的像素偏移 |-| `size` | Vec2 | `{100, 100}` | 宽高(anchorMin 等于 anchorMax 时使用) |-| `pivot` | Vec2 | `{0.5, 0.5}` | 旋转和缩放的中心点 |+| `direction` | FlexDirection | `Row` | `Row`、`Column`、`RowReverse`、`ColumnReverse` |+| `wrap` | FlexWrap | `NoWrap` | `NoWrap`、`Wrap` |+| `justifyContent` | JustifyContent | `Start` | `Start`、`Center`、`End`、`SpaceBetween`、`SpaceAround`、`SpaceEvenly` |+| `alignItems` | AlignItems | `Stretch` | `Start`、`Center`、`End`、`Stretch` |+| `gap` | Vec2 | `{0, 0}` | 子元素间距 |+| `padding` | Vec4 | `{0, 0, 0, 0}` | 上、右、下、左内边距 |-当 `anchorMin` 等于 `anchorMax` 时,元素具有固定 `size`,定位在锚点位置。当两者不同时,元素在两个锚点之间拉伸,`size` 由 `UILayoutPlugin` 自动计算。+### FlexItem-## 枚举类型+`FlexContainer` 内子实体的 Flex 属性。-### TextAlign+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `flexGrow` | number | `0` | 扩展以填充空间的比例 |+| `flexShrink` | number | `1` | 空间不足时收缩的比例 |+| `flexBasis` | number | `-1` | 扩展/收缩前的基础尺寸(-1 = 自动) |+| `order` | number | `0` | 显示顺序覆盖 |-| 值 | 名称 | 说明 |-|----|------|------|-| 0 | `Left` | 左对齐 |-| 1 | `Center` | 居中对齐 |-| 2 | `Right` | 右对齐 |+### LayoutGroup-### TextVerticalAlign+带方向、间距和对齐的网格式布局。-| 值 | 名称 | 说明 |-|----|------|------|-| 0 | `Top` | 顶部对齐 |-| 1 | `Middle` | 垂直居中 |-| 2 | `Bottom` | 底部对齐 |+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `direction` | LayoutDirection | `Horizontal` | `Horizontal` (0)、`Vertical` (1) |+| `spacing` | number | `0` | 子元素间距 |+| `padding` | object | `{left:0, top:0, right:0, bottom:0}` | 边距 |+| `childAlignment` | ChildAlignment | `Start` | `Start`、`Center`、`End` |+| `reverseOrder` | boolean | `false` | 反向排列 |-### TextOverflow+## 文本-| 值 | 名称 | 说明 |-|----|------|------|-| 0 | `Visible` | 文本溢出矩形边界 |-| 1 | `Clip` | 在边界处裁剪 |-| 2 | `Ellipsis` | 截断处显示省略号 |+### Text 组件-## 运行时修改文本+通过 `TextPlugin` 自动将样式化文本渲染为 `Sprite` 纹理。-在系统中通过 `Mut()` 查询 `Text` 组件来更新文本内容或样式:+**设置:** 在实体上添加 `Transform`、`Sprite`、`UIRect` 和 `Text`。++| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `content` | string | `''` | 文本内容 |+| `fontFamily` | string | `'Arial'` | 字体名称 |+| `fontSize` | number | `24` | 字号(像素) |+| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 RGBA |+| `align` | TextAlign | `Left` | `Left` (0)、`Center` (1)、`Right` (2) |+| `verticalAlign` | TextVerticalAlign | `Top` | `Top` (0)、`Middle` (1)、`Bottom` (2) |+| `wordWrap` | boolean | `true` | 启用自动换行 |+| `overflow` | TextOverflow | `Visible` | `Visible` (0)、`Clip` (1)、`Ellipsis` (2) |+| `lineHeight` | number | `1.2` | 行高倍率 |++<Aside type="note">+ 无需手动配置 Sprite。`TextPlugin` 会自动从 Text 内容创建和更新纹理。+</Aside>++### 运行时修改文本```typescript-import { defineSystem, addSystem, Query, Mut } from 'esengine';-import { Text } from 'esengine';+import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';addSystem(defineSystem([Query(Mut(Text))],@@ -91,83 +128,138 @@ addSystem(defineSystem());```-<Aside type="caution">- 修改文本属性时必须使用 `Mut(Text)`。不使用 `Mut()` 时组件为只读。-</Aside>+### Image-## 示例:动态计分板+显示图片,支持切片、平铺和填充模式。-一种常见模式是在数值变化时更新分数显示:+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `texture` | number | — | 纹理资产句柄 |+| `color` | Color | `{r:1, g:1, b:1, a:1}` | 颜色着色 |+| `imageType` | ImageType | `Simple` | `Simple` (0)、`Sliced` (1)、`Tiled` (2)、`Filled` (3) |+| `fillMethod` | FillMethod | `Horizontal` | `Horizontal` (0)、`Vertical` (1) |+| `fillOrigin` | FillOrigin | `Left` | `Left` (0)、`Right` (1)、`Bottom` (2)、`Top` (3) |+| `fillAmount` | number | `1` | 填充进度 0–1 |+| `preserveAspect` | boolean | `false` | 保持宽高比 |+| `enabled` | boolean | `true` | 可见性开关 |-```typescript-import { defineComponent, defineTag, defineSystem, addSystem, Query, Mut } from 'esengine';-import { Text } from 'esengine';+## 交互-const ScoreDisplay = defineTag('ScoreDisplay');+### Interactable-const GameState = defineComponent('GameState', {- score: 0,-});+将 UI 实体标记为可交互(接收指针事件)。所有交互控件都需要此组件。++| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `enabled` | boolean | `true` | 是否启用交互 |+| `blockRaycast` | boolean | `true` | 阻止事件传递到后面的元素 |++### UIInteraction++由插件自动添加到拥有 `Interactable` 的实体上,提供逐实体状态:++| 属性 | 类型 | 说明 |+|------|------|------|+| `hovered` | boolean | 指针悬停在此实体上 |+| `pressed` | boolean | 实体正被按下 |+| `justPressed` | boolean | 本帧开始按下 |+| `justReleased` | boolean | 本帧释放按下 |++### UIEvents++`UIEvents` 资源收集每帧的交互事件:++```typescript+import { defineSystem, addSystem, Res } from 'esengine';+import { UIEvents } from 'esengine';addSystem(defineSystem(- [Query(Mut(Text), ScoreDisplay), Query(GameState)],- (displayQuery, stateQuery) => {- let score = 0;- for (const [, state] of stateQuery) {- score = state.score;- }- for (const [, text] of displayQuery) {- text.content = `分数:${score}`;+ [Res(UIEvents)],+ (events) => {+ for (const e of events.query('click')) {+ console.log('点击了:', e.entity);}}));```-在编辑器中:创建一个文本实体,添加 `Text`、`UIRect`、`Sprite`、`LocalTransform` 和 `ScoreDisplay` 标签。+**事件类型:** `click`、`press`、`release`、`hover_enter`、`hover_exit`、`focus`、`blur`、`submit`、`change`、`drag_start`、`drag_move`、`drag_end`、`scroll`-## UIMask+事件沿实体层级向上冒泡。如果父级的 `Interactable` 设置了 `blockRaycast: true`,冒泡在此停止。-`UIMask` 将子实体裁剪到父实体的 `UIRect` 边界内。任何超出矩形的子实体部分会被视觉裁切。+### Focusable-**设置:** 在父实体上添加 `UIMask`、`UIRect` 和 `LocalTransform`。所有子实体(及其后代)都会被裁剪到该矩形范围内。+启用键盘焦点和 Tab 导航。-<Aside type="note">- `UIMaskPlugin` 由 `createWebApp()` 自动注册,无需手动设置。-</Aside>+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `tabIndex` | number | `0` | 焦点顺序(越小越早) |+| `isFocused` | boolean | `false` | 当前焦点状态 |-### UIMask 属性+## 控件++### Button++在 `Interactable` 之上的状态机,支持可选颜色过渡。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `enabled` | boolean | `true` | 是否启用裁剪 |+| `state` | ButtonState | `Normal` | `Normal` (0)、`Hovered` (1)、`Pressed` (2)、`Disabled` (3) |+| `transition` | ColorTransition \| null | `null` | 各状态颜色 |-### 嵌套遮罩+```typescript+cmds.entity(button).insert(Button, {+ state: 0,+ transition: {+ normalColor: { r: 1, g: 1, b: 1, a: 1 },+ hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },+ pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },+ disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },+ },+});+```-当子实体也拥有 `UIMask` 时,其裁剪矩形为自身 `UIRect` 与父级裁剪矩形的交集。这允许嵌套滚动区域或分层裁剪。+### Toggle-<Aside type="caution">- `UIMask` 只裁剪**子实体** — 拥有 UIMask 的实体自身不会被裁剪。-</Aside>+复选框,可选分组实现互斥。-### 示例:可滚动列表+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `isOn` | boolean | `true` | 开关状态 |+| `graphicEntity` | Entity | `0` | 显示/隐藏的子实体(勾选标记) |+| `group` | Entity | `0` | ToggleGroup 实体,实现单选按钮行为 |+| `transition` | ColorTransition \| null | `null` | 颜色过渡 |-创建遮罩容器,然后移动子实体来实现滚动:+**ToggleGroup** — 挂载到父实体使子级 Toggle 互斥:-```typescript-import { defineSystem, addSystem, Res, Input, Query, Mut, LocalTransform, Children } from 'esengine';-import { UIMask } from 'esengine';-import { ScrollList } from './components';+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `allowSwitchOff` | boolean | `false` | 允许所有 Toggle 关闭 |++### Slider++交互式数值滑块,带填充和可选可拖拽手柄。++| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `value` | number | `0` | 当前值 |+| `minValue` | number | `0` | 最小值 |+| `maxValue` | number | `1` | 最大值 |+| `direction` | FillDirection | `LeftToRight` | `LeftToRight` (0)、`RightToLeft` (1)、`BottomToTop` (2)、`TopToBottom` (3) |+| `fillEntity` | Entity | `0` | 填充可视化的子实体 |+| `handleEntity` | Entity | `0` | 可拖拽手柄的子实体 |+| `wholeNumbers` | boolean | `false` | 吸附到整数 |+监听值变化:++```typescriptaddSystem(defineSystem(- [Res(Input), Query(Children, UIMask, ScrollList), Query(Mut(LocalTransform))],- (input, maskQuery, childQuery) => {- const scrollDelta = input.getScrollDelta();- if (scrollDelta.y === 0) return;-- for (const [entity, children] of maskQuery) {- for (const [childEntity, transform] of childQuery) {- if (children.entities.includes(childEntity)) {- transform.position.y += scrollDelta.y * 20;+ [Res(UIEvents), Query(Slider)],+ (events, query) => {+ for (const e of events.query('change')) {+ for (const [entity, slider] of query) {+ if (entity === e.entity) {+ console.log('滑块值:', slider.value);}}}@@ -175,163 +267,151 @@ addSystem(defineSystem());```-## UI 交互+### ProgressBar-ESEngine 提供了内置的 UI 交互系统,用于处理 UI 元素的悬停、按压和点击事件。+非交互式进度条显示。-### 设置+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `value` | number | `0` | 进度 0–1 |+| `fillEntity` | Entity | `0` | 填充的子实体 |+| `direction` | FillDirection | `LeftToRight` | 填充方向 |-在任何拥有 `UIRect` 和 `LocalTransform` 的 UI 实体上添加 `Interactable` 组件。`UIInteractionPlugin`(由 `createWebApp()` 自动注册)每帧执行命中检测并管理交互状态。+```typescript+addSystem(defineSystem(+ [Res(Time), Query(Mut(ProgressBar))],+ (time, query) => {+ for (const [entity, bar] of query) {+ bar.value = Math.min(1, bar.value + time.delta * 0.1);+ }+ }+));+```-### Interactable+### Dropdown-标记实体为可交互。+下拉列表选择器。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `enabled` | boolean | `true` | 是否启用交互 |+| `options` | string[] | `[]` | 选项标签 |+| `selectedIndex` | number | `-1` | 选中项索引 |+| `isOpen` | boolean | `false` | 列表可见性 |+| `listEntity` | Entity | `0` | 下拉列表的子实体 |+| `labelEntity` | Entity | `0` | 显示选中标签的子实体 |-### Button+### ScrollView-在 `Interactable` 基础上添加状态机,支持可选的颜色过渡。+带惯性和弹性回弹的滚动容器。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `state` | ButtonState | `Normal` | 当前按钮状态(运行时只读) |-| `transition` | ButtonTransition \| null | `null` | 颜色过渡配置 |--**ButtonState:** `Normal` (0)、`Hovered` (1)、`Pressed` (2)、`Disabled` (3)--设置 `transition` 后,状态变化时 `Sprite` 颜色会自动更新:--```typescript-import { defineSystem, Commands, Button, Interactable } from 'esengine';--defineSystem([Commands()], (cmds) => {- cmds.entity(entity).insert(Button, {- state: 0,- transition: {- normalColor: { r: 1, g: 1, b: 1, a: 1 },- hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },- pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },- disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },- },- });-});-```+| `contentEntity` | Entity | `0` | 持有可滚动内容的子实体 |+| `horizontalEnabled` | boolean | `false` | 启用水平滚动 |+| `verticalEnabled` | boolean | `true` | 启用垂直滚动 |+| `scrollX` | number | `0` | 当前水平偏移 |+| `scrollY` | number | `0` | 当前垂直偏移 |+| `inertia` | boolean | `true` | 启用惯性滚动 |+| `decelerationRate` | number | `0.135` | 惯性摩擦力 |+| `elastic` | boolean | `true` | 边缘回弹 |+| `wheelSensitivity` | number | `0.1` | 鼠标滚轮灵敏度 |-### UIInteraction+### ListView-由插件自动添加到拥有 `Interactable` 的实体上,提供逐实体状态:+大列表虚拟滚动——仅渲染可见项目。-| 属性 | 类型 | 说明 |-|------|------|------|-| `hovered` | boolean | 指针悬停在该实体上 |-| `pressed` | boolean | 实体正在被按压 |-| `justPressed` | boolean | 本帧开始按压 |-| `justReleased` | boolean | 本帧释放按压 |--### UIEvents+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `itemHeight` | number | `40` | 固定项目高度 |+| `itemCount` | number | `0` | 总项目数 |+| `scrollY` | number | `0` | 滚动位置 |+| `overscan` | number | `2` | 视口上下额外渲染的项目数 |-`UIEvents` 资源在每帧收集交互事件。在系统中查询:+### TextInput-```typescript-import { defineSystem, addSystem, Res } from 'esengine';-import { UIEvents } from 'esengine';+可编辑文本输入框,支持光标、选择和占位符。-addSystem(defineSystem(- [Res(UIEvents)],- (events) => {- for (const e of events.query('click')) {- console.log('点击了实体:', e.entity);- }- }-));-```+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `value` | string | `''` | 当前文本 |+| `placeholder` | string | `''` | 为空时的提示 |+| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | 占位符颜色 |+| `fontFamily` | string | `'Arial'` | 字体 |+| `fontSize` | number | `16` | 字号 |+| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 |+| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | 背景颜色 |+| `padding` | number | `6` | 内边距 |+| `maxLength` | number | `0` | 最大字符数(0 = 无限) |+| `multiline` | boolean | `false` | 允许换行 |+| `password` | boolean | `false` | 密码遮罩 |+| `readOnly` | boolean | `false` | 禁止编辑 |-**事件类型:** `click`、`press`、`release`、`hover_enter`、`hover_exit`、`submit`、`change`+**事件:** `change`(值变化)、`submit`(单行模式下按 Enter)-### ScreenSpace+### Draggable-用于根 UI 实体的标签组件。拥有 `ScreenSpace`、`UIRect` 和 `LocalTransform` 的实体会由 `UILayoutPlugin` 相对于相机边界进行布局。+启用 UI 元素的拖拽移动。-```typescript-import { defineSystem, Commands, ScreenSpace, UIRect, LocalTransform } from 'esengine';--defineSystem([Commands()], (cmds) => {- cmds.entity(entity)- .insert(ScreenSpace)- .insert(UIRect, {- anchorMin: { x: 0, y: 0 },- anchorMax: { x: 1, y: 1 },- offsetMin: { x: 0, y: 0 },- offsetMax: { x: 0, y: 0 },- size: { x: 100, y: 100 },- pivot: { x: 0.5, y: 0.5 },- });-});-```+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `enabled` | boolean | `true` | 启用拖拽 |+| `dragThreshold` | number | `5` | 开始拖拽前的像素移动距离 |+| `lockX` | boolean | `false` | 锁定水平移动 |+| `lockY` | boolean | `false` | 锁定垂直移动 |-<Aside type="note">- `UILayoutPlugin` 和 `UIInteractionPlugin` 均由 `createWebApp()` 自动注册,无需手动设置。-</Aside>+## 遮罩-## TextInput+### UIMask-`TextInput` 渲染一个可编辑文本输入框。`TextInputPlugin` 自动处理键盘输入、光标闪烁和纹理渲染。+将子实体裁剪到父级 `UIRect` 边界内。-### 设置步骤+| 属性 | 类型 | 默认值 | 说明 |+|------|------|--------|------|+| `enabled` | boolean | `true` | 是否启用裁剪 |+| `mode` | MaskMode | `Scissor` | `Scissor` (0)、`Stencil` (1) |-在编辑器中:通过右键 → **Create** → **UI** → **TextInput** 创建实体,或手动添加 `LocalTransform`、`UIRect`、`Interactable` 和 `TextInput` 组件。+嵌套 `UIMask` 实体会裁剪到所有父级遮罩的交集区域。-<Aside type="note">- 插件会在缺少 `Sprite` 组件时自动添加,无需手动设置。`TextInputPlugin` 由 `createWebApp()` 自动注册。+<Aside type="caution">+ `UIMask` 只裁剪**子**实体——拥有 UIMask 的实体本身不会被裁剪。</Aside>-### TextInput 属性+## SafeArea++适配设备安全区域(刘海、圆角)。适用于移动端和微信小游戏。| 属性 | 类型 | 默认值 | 说明 ||------|------|--------|------|-| `value` | string | `''` | 当前文本内容 |-| `placeholder` | string | `''` | 为空时显示的提示文本 |-| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | 提示文本颜色 |-| `fontFamily` | string | `'Arial'` | 字体名称 |-| `fontSize` | number | `16` | 字号(像素) |-| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 |-| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | 背景填充颜色 |-| `padding` | number | `6` | 内边距(像素) |-| `maxLength` | number | `0` | 最大字符数(0 = 不限) |-| `multiline` | boolean | `false` | 允许多行输入 |-| `password` | boolean | `false` | 用圆点遮蔽文本 |-| `readOnly` | boolean | `false` | 禁止用户输入 |+| `applyTop` | boolean | `true` | 应用到顶部 |+| `applyBottom` | boolean | `true` | 应用到底部 |+| `applyLeft` | boolean | `true` | 应用到左侧 |+| `applyRight` | boolean | `true` | 应用到右侧 |-`focused`、`cursorPos` 和 `dirty` 属性由插件内部管理。--### 运行时读取输入+## 示例:分数显示```typescript-import { defineSystem, addSystem, Query, Res } from 'esengine';-import { TextInput, UIEvents } from 'esengine';+import { defineTag, defineComponent, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';++const ScoreDisplay = defineTag('ScoreDisplay');+const GameState = defineComponent('GameState', { score: 0 });addSystem(defineSystem(- [Query(TextInput), Res(UIEvents)],- (query, events) => {- for (const e of events.query('submit')) {- for (const [entity, input] of query) {- if (entity === e.entity) {- console.log('提交内容:', input.value);- }- }+ [Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],+ (displays, stateQuery) => {+ if (stateQuery.isEmpty()) return;+ const [, state] = stateQuery.single()!;+ for (const [, text] of displays) {+ text.content = `分数:${state.score}`;}}));```-**TextInput 事件:** `change`(值变更)、`submit`(单行模式下按回车)+使用[变更检测](/microes/zh/core-concepts/change-detection/),仅在分数实际变化时更新文本。## 下一步- [组件](/microes/zh/core-concepts/components/) — 所有内置组件-- [精灵](/microes/zh/guides/sprite/) — 精灵渲染详解+- [精灵](/microes/zh/guides/sprite/) — 精灵渲染详情- [位图文本](/microes/zh/guides/bitmap-text/) — GPU 渲染的位图字体文本-- [资源加载](/microes/zh/guides/assets/) — 加载纹理和其他资源+- [输入处理](/microes/zh/guides/input/) — 键盘、鼠标和触摸输入diff --git a/docs/astro/src/content/docs/zh/index.mdx b/docs/astro/src/content/docs/zh/index.mdxindex 874a7854b..17dc71ba9 100644--- a/docs/astro/src/content/docs/zh/index.mdx+++ b/docs/astro/src/content/docs/zh/index.mdx@@ -42,13 +42,13 @@ import { Card, CardGrid } from '@astrojs/starlight/components';```typescriptimport {defineComponent, defineSystem, addSystem,- Query, Res, Time, Mut, LocalTransform+ Query, Res, Time, Mut, Transform} from 'esengine';const Speed = defineComponent('Speed', { value: 200 });addSystem(defineSystem(- [Res(Time), Query(Mut(LocalTransform), Speed)],+ [Res(Time), Query(Mut(Transform), Speed)],(time, query) => {for (const [entity, transform, speed] of query) {transform.position.x += speed.value * time.delta;