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
feat(examples): timers, trails, render-texture and drawing demos
esenginea9c0541a166d
diff --git a/examples/README.md b/examples/README.mdindex 8d4e7a7a5..63b730d11 100644--- a/examples/README.md+++ b/examples/README.md@@ -17,6 +17,7 @@ for your own game.| **event-system** | ECS | Decoupled gameplay with typed events — collect, score, react. || **scene-flow** | Basics | Runtime scene flow — menu → level 1 → level 2 through `SceneManager` fade transitions, over a persistent shell scene. || **save-load** | Basics | Versioned persistence — `SaveManager` save/load with a live v1→v2 migration, plus raw `Storage` preferences. |+| **timers-demo** | Basics | `TimerManager` delays, intervals and handles — pause/resume/cancel/reset plus `timeScale`, replacing hand-rolled `time.delta` accumulators. || **sprite-rendering** | Rendering | Draw sprites with rotation, tint and flipping. || **sprite-animation** | Animation | Frame animation via `.esanim` clips with an idle/walk switcher. || **spine-demo** | Animation | A Spine skeleton cycling idle/walk/run/jump/shoot (1-5 to switch). |@@ -29,9 +30,12 @@ for your own game.| **physics-playground** | Physics | Drop balls and crates into a rigid-body sandbox. || **physics-spinner** | Physics | Revolute joints and continuous rotation. || **particle-demo** | Effects | A configurable particle emitter with additive blending. |+| **trail-demo** | Effects | The built-in `TrailRenderer` — comet, mouse-follow and dash trails with distinct width/color/blend configs, plus `Trail.clear` on teleport. || **postprocess-effects** | Effects | Full-screen post-processing: bloom, vignette, color grading. || **lighting-2d** | Rendering | Dynamic 2D lights and soft shadow casters over `Sprite.lit` surfaces. || **effects-gallery** | Rendering | The built-in material effect templates — hit flash, outline, dissolve, pixelate, UV scroll — with params driven from code. |+| **render-texture** | Rendering | Render-to-texture — a live minimap painted with the `Draw` API into a `RenderTexture`, resolution cycling on R. |+| **drawing-demo** | Rendering | The three drawing tiers — immediate `Draw` radar overlay, retained `Graphics` vector star, procedural `Mesh2D` ribbon. || **video-playback** | Rendering | Play a video on a Sprite with the declarative `Video` component — "a Sprite whose texture is alive". || **tilemap-demo** | Tilemap | Two scenes: a Tiled `.tmj` import and an engine-native `.estileset` — multi-tileset, parallax, animated water, per-tile collision. || **ui-controls** | UI | Buttons, sliders, toggles and progress bars. |diff --git a/examples/drawing-demo/.gitignore b/examples/drawing-demo/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/drawing-demo/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/drawing-demo/README.md b/examples/drawing-demo/README.mdnew file mode 100644index 000000000..e6de7cc68--- /dev/null+++ b/examples/drawing-demo/README.md@@ -0,0 +1,129 @@+# Custom Drawing++The engine's **three drawing tiers** side by side — when sprites and particles+can't express a visual, this is the layer underneath them:++| Zone | API | Model | Reach for it when |+|---|---|---|---|+| Left | `Draw` | **Immediate** — commands batch and clear every frame. | Debug overlays, gizmos, anything redrawn from scratch each frame. |+| Middle | `Graphics` | **Retained** path recorder — build once, replay with `flush()`. | Vector shapes with paths/béziers/arcs you don't want to re-tessellate per frame. |+| Right | `Mesh2D` | **Component** — an entity with sorting layers and materials. | Meshes that are part of the scene (sorted, saved, inspectable). |++Rule of thumb: if the visual belongs to the *scene*, make it a component; if it+belongs to a *frame* (debug, HUD-ish overlays, procedural effects), draw it in+a callback.++| Key | Action |+|---|---|+| **G** | `clear()` and re-record the retained star with new random parameters. |++## What it shows++- **Draw — the radar overlay** (`src/systems/radar.ts`). A draw callback runs+ inside the render pass every frame with the camera's view-projection already+ active; every ring, sweep line, and bounding box is re-issued from scratch.+ Animation is just "draw with different numbers next frame" — nothing is+ stored. The bounding boxes track real sprite entities: the movement system+ snapshots drone positions each update, and the callback draws over them —+ the classic debug-overlay pattern.+- **Graphics — the retained star** (`src/systems/star.ts`). `buildStar()`+ records the path once — star polygon, filled hub, arc brackets, a bézier+ swoosh (curves are subdivided *at record time*). After that, the per-frame+ cost is only `flush()`, which replays the recorded commands through `Draw`.+ Pressing **G** is the only time the path is rebuilt.+- **Mesh2D — the procedural ribbon** (`src/systems/ribbon.ts`). The `Ribbon`+ entity is authored in the scene with a `Mesh2D` component, so it sorts with+ sprites via `layer` and is saved and inspectable. Each frame the system+ regenerates the vertex positions and per-vertex colors (indices never change)+ and re-uploads through the **`Meshes2D` resource** —+ `meshes.setGeometry(entity, geometry)` is the supported mutation path; direct+ writes to the component's `geometry` field are not change-detected.++## API reference++### Draw (immediate, global)++```typescript+import { Draw, registerDrawCallback } from 'esengine';++registerDrawCallback('my-overlay', (elapsed) => {+ Draw.line(from, to, color, thickness);+ Draw.rect(center, size, color, filled); // rectOutline(center, size, color, thickness)+ Draw.circle(center, radius, color, filled, segments);+ Draw.circleOutline(center, radius, color, thickness, segments);+ Draw.texture(center, size, textureHandle, tint); // textureRotated adds radians+ Draw.setLayer(layer); // sorting of subsequent commands+ Draw.setDepth(depth);+ Draw.setBlendMode(mode);+});+```++Callbacks draw **on top of** the scene (`registerPreSceneDrawCallback` draws+under it); coordinates are world-space; rect/circle positions are **centers**.+Remove one with `unregisterDrawCallback(id)`.++### Graphics (retained recorder)++```typescript+import { Graphics } from 'esengine';++const g = new Graphics();+g.lineStyle(3, color); // stroke for subsequent path commands+g.beginFill(color); // fills rects and circles (paths stay strokes)+g.drawCircle(cx, cy, r);+g.endFill();+g.moveTo(x, y); g.lineTo(x, y); // polylines+g.curveTo(cpx, cpy, x, y); // quadratic bézier (cubicCurveTo for cubic)+g.arc(cx, cy, r, a0, a1); // also drawRect / drawRoundRect / drawEllipse+g.clear(); // start over (the G-key rebuild)++registerDrawCallback('shape', () => g.flush()); // replay every frame+```++### Mesh2D (component) + Meshes2D (resource)++```typescript+import { Meshes2D, Res, GetWorld } from 'esengine';++// geometry: positions as x,y pairs (component-local), optional per-vertex+// uvs (default 0,0 → vertex colors on the white texture) and colors+// (r,g,b,a floats), plus an indexed triangle list.+meshes.setGeometry(entity, { positions, colors, indices }); // re-uploads (validated)+meshes.getGeometry(entity); // last uploaded geometry+meshes.clearGeometry(entity); // valid state: renders nothing+```++The component shares the standard renderable surface: `texture`, `color`,+`layer`, `lit`, `parallax`, `material`. Geometry authored in a scene uploads+automatically on load.++## Files++- `src/systems/radar.ts` — drone movement + position snapshot, and the+ immediate-mode radar overlay draw callback.+- `src/systems/star.ts` — the retained `Graphics` star: build once, `flush()`+ per frame, G to rebuild.+- `src/systems/ribbon.ts` — per-frame ribbon regeneration through `Meshes2D`.+- `src/systems/setup.ts` — spawns the drone sprites the overlay tracks.+- `src/config.ts` — zone layout, radar/star/ribbon tuning, HSV palette helper.+- `assets/scenes/main.esscene` — camera, zone labels, and the `Ribbon` entity+ with its `Mesh2D` component.++## 中文摘要++本示例把引擎的**三层绘制 API** 并排展示:++- **`Draw`(左)**——立即模式:雷达罩的每一圈、扫描线、无人机包围盒都在+ draw callback 里逐帧重发;命令自动合批、帧末清空,「动画」就是下一帧画+ 不同的数字。包围盒追踪的是真实精灵实体——移动系统每帧快照位置,回调+ 在其上叠加,这正是调试覆盖层的经典写法。+- **`Graphics`(中)**——保留模式路径记录器:星形只在 `buildStar()` 时+ 记录一次(贝塞尔曲线在记录时细分),每帧只需 `flush()` 回放;按 **G**+ 以新参数 `clear()` 重录,这是唯一重建路径的时刻。+- **`Mesh2D`(右)**——组件网格:`Ribbon` 实体在场景中作者化,随 `layer`+ 与精灵排序;系统每帧重新生成顶点与逐顶点颜色,并通过 **`Meshes2D`**+ 资源 `setGeometry` 重新上传——这是受支持的运行时改几何路径(直接改+ 组件 `geometry` 字段不会被侦测)。++经验法则:属于**场景**的视觉(要排序、保存、可检查)用组件;属于**单帧**+的视觉(调试、覆盖层、程序化特效)在回调里画。diff --git a/examples/drawing-demo/assets/scenes/main.esscene b/examples/drawing-demo/assets/scenes/main.esscenenew file mode 100644index 000000000..89a52249f--- /dev/null+++ b/examples/drawing-demo/assets/scenes/main.esscene@@ -0,0 +1,131 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": { "x": 0, "y": 0, "z": 10 }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 360,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "LabelDraw",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": -420, "y": 230, "z": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Draw — immediate radar overlay",+ "fontSize": 20,+ "bold": true,+ "color": { "r": 0.45, "g": 0.95, "b": 0.62, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "LabelGraphics",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 230, "z": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Graphics — retained star",+ "fontSize": 20,+ "bold": true,+ "color": { "r": 0.55, "g": 0.75, "b": 1, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "LabelMesh",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 420, "y": 230, "z": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Mesh2D — procedural ribbon",+ "fontSize": 20,+ "bold": true,+ "color": { "r": 1, "g": 0.72, "b": 0.45, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 4,+ "name": "HintRebuild",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": -280, "z": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "G — rebuild the star with new parameters",+ "fontSize": 15,+ "bold": false,+ "color": { "r": 0.62, "g": 0.66, "b": 0.74, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 5,+ "name": "Ribbon",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 420, "y": -40, "z": 0 } } },+ {+ "type": "Mesh2D",+ "data": {+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "layer": 1+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/drawing-demo/assets/scenes/main.esscene.meta b/examples/drawing-demo/assets/scenes/main.esscene.metanew file mode 100644index 000000000..1b8b75c3a--- /dev/null+++ b/examples/drawing-demo/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "4939995b-788f-450e-a670-dfa8866be637",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/drawing-demo/project.esproject b/examples/drawing-demo/project.esprojectnew file mode 100644index 000000000..702a087fc--- /dev/null+++ b/examples/drawing-demo/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Custom Drawing",+ "description": "The three drawing tiers side by side: an immediate-mode Draw radar overlay, a retained Graphics star, and a procedural Mesh2D ribbon.",+ "tag": "Rendering",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 1280,+ "height": 720+ },+ "spineVersion": "none"+}diff --git a/examples/drawing-demo/src/components.ts b/examples/drawing-demo/src/components.tsnew file mode 100644index 000000000..92174ea87--- /dev/null+++ b/examples/drawing-demo/src/components.ts@@ -0,0 +1,5 @@+import { defineComponent } from 'esengine';++export const Drone = defineComponent('Drone', {+ seed: 0,+});diff --git a/examples/drawing-demo/src/config.ts b/examples/drawing-demo/src/config.tsnew file mode 100644index 000000000..561a90ee4--- /dev/null+++ b/examples/drawing-demo/src/config.ts@@ -0,0 +1,57 @@+import type { Color } from 'esengine';++export const RADAR = {+ center: { x: -420, y: -40 },+ radius: 150,+ rings: 3,+ sweepSpeed: 1.4,+ trailSteps: 10,+ trailSpread: 0.55,+ color: { r: 0.3, g: 0.95, b: 0.55, a: 1 } as Color,+};++export const DRONES = {+ count: 3,+ size: 22,+ boxMargin: 9,+ boxColor: { r: 1, g: 0.85, b: 0.3, a: 0.9 } as Color,+ colors: [+ { r: 0.95, g: 0.4, b: 0.4, a: 1 },+ { r: 0.4, g: 0.7, b: 0.95, a: 1 },+ { r: 0.9, g: 0.65, b: 0.95, a: 1 },+ ] as Color[],+};++export const STAR = {+ center: { x: 0, y: -40 },+ points: 7,+ outerRadius: 130,+ innerRadius: 58,+ hue: 0.58,+};++export const RIBBON = {+ halfLength: 170,+ halfWidth: 26,+ segments: 48,+ waveAmplitude: 58,+ waveFrequency: 2.2,+ scrollSpeed: 2.4,+};++/** HSV → Color (h/s/v in 0..1); the demo's one-stop palette knob. */+export function hsv(h: number, s: number, v: number, a = 1): Color {+ const i = Math.floor(((h % 1) + 1) % 1 * 6);+ const f = ((h % 1) + 1) % 1 * 6 - i;+ const p = v * (1 - s);+ const q = v * (1 - f * s);+ const t = v * (1 - (1 - f) * s);+ switch (i % 6) {+ case 0: return { r: v, g: t, b: p, a };+ case 1: return { r: q, g: v, b: p, a };+ case 2: return { r: p, g: v, b: t, a };+ case 3: return { r: p, g: q, b: v, a };+ case 4: return { r: t, g: p, b: v, a };+ default: return { r: v, g: p, b: q, a };+ }+}diff --git a/examples/drawing-demo/src/main.ts b/examples/drawing-demo/src/main.tsnew file mode 100644index 000000000..8f7d5c1f3--- /dev/null+++ b/examples/drawing-demo/src/main.ts@@ -0,0 +1,23 @@+// Custom Drawing — the engine's three drawing tiers side by side:+//+// • Draw — immediate mode: a radar overlay (sweep, pulse rings, drone+// bounding boxes) re-issued from scratch every frame in a draw callback.+// • Graphics — retained path recorder: a star built once and replayed with+// flush(); G clears and re-records it with new parameters.+// • Mesh2D — component mesh: a scene-authored ribbon whose vertices are+// regenerated each frame and re-uploaded through the Meshes2D resource.+//+// Importing radar.ts / star.ts registers their draw callbacks+// (registerDrawCallback) as a side effect; systems only feed them data.+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { setupSystem } from './systems/setup';+import { droneSystem } from './systems/radar';+import { starRebuildSystem } from './systems/star';+import { ribbonSystem } from './systems/ribbon';++addStartupSystem(setupSystem);+addSystemToSchedule(Schedule.Update, droneSystem);+addSystemToSchedule(Schedule.Update, starRebuildSystem);+addSystemToSchedule(Schedule.Update, ribbonSystem);diff --git a/examples/drawing-demo/src/systems/radar.ts b/examples/drawing-demo/src/systems/radar.tsnew file mode 100644index 000000000..9df7d465f--- /dev/null+++ b/examples/drawing-demo/src/systems/radar.ts@@ -0,0 +1,73 @@+import {+ defineSystem, Query, Mut, Res, Time, Transform,+ Draw, registerDrawCallback,+} from 'esengine';+import { Drone } from '../components';+import { RADAR, DRONES } from '../config';++// The Draw tier: an immediate-mode debug overlay. Every shape below is+// re-issued from scratch each frame inside a draw callback — Draw batches the+// commands and clears them after the frame, so animation is just "draw with+// different numbers next frame".++// The draw callback only receives `elapsed`, so the system that moves the+// drones snapshots their positions here for the overlay to read.+const blips: { x: number; y: number }[] = [];++export const droneSystem = defineSystem(+ [Query(Mut(Transform), Drone), Res(Time)],+ (query, time) => {+ blips.length = 0;+ const t = time.elapsed;+ for (const [_entity, transform, drone] of query) {+ const angle = t * (0.4 + drone.seed * 0.17) + drone.seed * 2.1;+ const r = RADAR.radius * (0.45 + 0.32 * Math.sin(t * 0.6 + drone.seed * 2.7));+ const x = RADAR.center.x + Math.cos(angle) * r;+ const y = RADAR.center.y + Math.sin(angle) * r;+ transform.position.x = x;+ transform.position.y = y;+ blips.push({ x, y });+ }+ },+ { name: 'DroneSystem' },+);++function drawRadar(elapsed: number): void {+ const { center, radius, color } = RADAR;++ for (let i = 1; i <= RADAR.rings; i++) {+ Draw.circleOutline(center, (radius * i) / RADAR.rings,+ { ...color, a: 0.3 }, 1, 48);+ }+ Draw.line({ x: center.x - radius, y: center.y }, { x: center.x + radius, y: center.y },+ { ...color, a: 0.18 });+ Draw.line({ x: center.x, y: center.y - radius }, { x: center.x, y: center.y + radius },+ { ...color, a: 0.18 });++ // Expanding pulse ring that fades as it grows.+ const pulse = (elapsed * 0.45) % 1;+ Draw.circleOutline(center, radius * pulse, { ...color, a: 0.5 * (1 - pulse) }, 2, 48);++ // Sweep line with a trail of ghost lines fading behind it.+ const sweep = -elapsed * RADAR.sweepSpeed;+ for (let i = 0; i < RADAR.trailSteps; i++) {+ const a = sweep + i * (RADAR.trailSpread / RADAR.trailSteps);+ const alpha = (1 - i / RADAR.trailSteps) * 0.85;+ Draw.line(center,+ { x: center.x + Math.cos(a) * radius, y: center.y + Math.sin(a) * radius },+ { ...color, a: alpha }, i === 0 ? 2 : 1);+ }+ Draw.circle(center, 5, color);++ // Bounding boxes over the drone sprites — the classic debug-overlay use.+ const box = DRONES.size + DRONES.boxMargin * 2;+ const ping = 1 + 0.15 * Math.sin(elapsed * 5);+ for (const blip of blips) {+ Draw.rectOutline(blip, { x: box, y: box }, DRONES.boxColor, 2);+ Draw.circleOutline(blip, box * 0.85 * ping, { ...DRONES.boxColor, a: 0.35 }, 1, 24);+ }+}++// Draw callbacks run inside the render pass, after the scene, with the active+// camera's view-projection already set — coordinates are world-space.+registerDrawCallback('radar-overlay', drawRadar);diff --git a/examples/drawing-demo/src/systems/ribbon.ts b/examples/drawing-demo/src/systems/ribbon.tsnew file mode 100644index 000000000..7163517bc--- /dev/null+++ b/examples/drawing-demo/src/systems/ribbon.ts@@ -0,0 +1,49 @@+import {+ defineSystem, GetWorld, Res, Time, Meshes2D, type Entity,+} from 'esengine';+import { RIBBON, hsv } from '../config';++// The Mesh2D tier: a component-owned triangle mesh. The Ribbon entity lives in+// the scene (sorted with sprites via `layer`, saved, inspectable); this system+// regenerates its vertices every frame and re-uploads through the Meshes2D+// resource — the supported mutation path (direct writes to the component's+// `geometry` field are not change-detected).++const N = RIBBON.segments;++// Index topology never changes — two triangles per segment, built once.+const indices: number[] = [];+for (let i = 0; i < N; i++) {+ const a = i * 2, b = i * 2 + 1, c = i * 2 + 2, d = i * 2 + 3;+ indices.push(a, b, c, b, d, c);+}++let ribbon: Entity | null = null;++export const ribbonSystem = defineSystem(+ [GetWorld(), Res(Meshes2D), Res(Time)],+ (world, meshes, time) => {+ if (ribbon === null) ribbon = world.findEntityByName('Ribbon');+ if (ribbon === null) return;++ const t = time.elapsed;+ const positions: number[] = [];+ const colors: number[] = [];+ for (let i = 0; i <= N; i++) {+ const s = i / N;+ const x = -RIBBON.halfLength + s * RIBBON.halfLength * 2;+ const envelope = Math.sin(s * Math.PI);+ const wave = Math.sin(s * RIBBON.waveFrequency * Math.PI * 2 - t * RIBBON.scrollSpeed)+ * RIBBON.waveAmplitude * envelope;+ const halfWidth = RIBBON.halfWidth * (0.25 + 0.75 * envelope);+ positions.push(x, wave + halfWidth, x, wave - halfWidth);++ const top = hsv(0.05 + s * 0.35 + t * 0.03, 0.85, 1);+ const bottom = hsv(0.05 + s * 0.35 + t * 0.03, 0.85, 0.45);+ colors.push(top.r, top.g, top.b, 1, bottom.r, bottom.g, bottom.b, 1);+ }++ meshes.setGeometry(ribbon, { positions, colors, indices });+ },+ { name: 'RibbonSystem' },+);diff --git a/examples/drawing-demo/src/systems/setup.ts b/examples/drawing-demo/src/systems/setup.tsnew file mode 100644index 000000000..21d0a52f9--- /dev/null+++ b/examples/drawing-demo/src/systems/setup.ts@@ -0,0 +1,24 @@+import { defineSystem, Commands, Transform, Sprite } from 'esengine';+import { Drone } from '../components';+import { RADAR, DRONES } from '../config';++// Spawns the radar's drone sprites — ordinary scene entities the immediate-mode+// overlay tracks. Everything else in the demo is drawn, not spawned.+export const setupSystem = defineSystem(+ [Commands()],+ (cmds) => {+ for (let i = 0; i < DRONES.count; i++) {+ cmds.spawn(`Drone${i}`)+ .insert(Transform, {+ position: { x: RADAR.center.x, y: RADAR.center.y, z: 0 },+ })+ .insert(Sprite, {+ size: { x: DRONES.size, y: DRONES.size },+ color: DRONES.colors[i % DRONES.colors.length],+ layer: 2,+ })+ .insert(Drone, { seed: i });+ }+ },+ { name: 'SetupSystem' },+);diff --git a/examples/drawing-demo/src/systems/star.ts b/examples/drawing-demo/src/systems/star.tsnew file mode 100644index 000000000..f12e406a1--- /dev/null+++ b/examples/drawing-demo/src/systems/star.ts@@ -0,0 +1,65 @@+import { defineSystem, Res, Input, Graphics, registerDrawCallback } from 'esengine';+import { STAR, hsv } from '../config';++// The Graphics tier: a retained path recorder. The star is BUILT once (path+// tessellation, curve subdivision) and the per-frame cost is only flush(),+// which replays the recorded commands through Draw. Press G to clear() and+// re-record with new parameters — the only time the path is rebuilt.++const g = new Graphics();++function buildStar(points: number, outerRadius: number, innerRadius: number, hue: number): void {+ g.clear();+ const { x: cx, y: cy } = STAR.center;++ // Filled hub (beginFill/endFill fill rects and circles; paths stay strokes).+ g.lineStyle(2, hsv(hue, 0.5, 1, 0.9));+ g.beginFill(hsv(hue, 0.75, 0.35, 0.9));+ g.drawCircle(cx, cy, innerRadius * 0.55, 40);+ g.endFill();++ // Star outline: alternate outer/inner vertices around the circle.+ g.lineStyle(3, hsv(hue, 0.55, 1));+ const step = Math.PI / points;+ const start = Math.PI / 2;+ g.moveTo(cx, cy + outerRadius);+ for (let i = 1; i <= points * 2; i++) {+ const r = i % 2 === 0 ? outerRadius : innerRadius;+ const a = start + i * step;+ g.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);+ }++ // Orbit ring and four arc brackets just outside it.+ g.lineStyle(1, hsv(hue, 0.35, 0.9, 0.5));+ g.drawCircle(cx, cy, outerRadius + 16, 64);+ g.lineStyle(3, hsv(hue, 0.35, 1, 0.8));+ for (let i = 0; i < 4; i++) {+ const a0 = i * (Math.PI / 2) + Math.PI / 8;+ g.moveTo(cx + Math.cos(a0) * (outerRadius + 26), cy + Math.sin(a0) * (outerRadius + 26));+ g.arc(cx, cy, outerRadius + 26, a0, a0 + Math.PI / 4);+ }++ // A quadratic-bézier swoosh under the star (curveTo subdivides on record).+ g.lineStyle(2, hsv(hue + 0.08, 0.5, 1, 0.8));+ g.moveTo(cx - outerRadius, cy - outerRadius - 42);+ g.curveTo(cx, cy - outerRadius + 8, cx + outerRadius, cy - outerRadius - 42);+}++buildStar(STAR.points, STAR.outerRadius, STAR.innerRadius, STAR.hue);++// flush() is the retained payoff: replaying recorded commands, no re-tessellation.+registerDrawCallback('star-shape', () => g.flush());++export const starRebuildSystem = defineSystem(+ [Res(Input)],+ (input) => {+ if (!input.isKeyPressed('KeyG')) return;+ buildStar(+ 5 + Math.floor(Math.random() * 6),+ 108 + Math.random() * 32,+ 42 + Math.random() * 34,+ Math.random(),+ );+ },+ { name: 'StarRebuildSystem' },+);diff --git a/examples/drawing-demo/tsconfig.json b/examples/drawing-demo/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/drawing-demo/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/examples/render-texture/.gitignore b/examples/render-texture/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/render-texture/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/render-texture/README.md b/examples/render-texture/README.mdnew file mode 100644index 000000000..fc5e6c4f1--- /dev/null+++ b/examples/render-texture/README.md@@ -0,0 +1,140 @@+# Render Texture++Offscreen rendering with the **`RenderTexture`** API — the engine surface+behind minimaps, live portraits, picture-in-picture, and cache-as-bitmap.++Colored shapes drift along orbits across a 3200×2000 world while the camera+only ever shows the middle 1280×720 — most shapes are offscreen at any moment.+A quad pinned to the top-right corner shows the whole world live: every frame+a system paints a schematic of the world into a `RenderTexture`, and the+quad's `Sprite` samples the target's `textureId`.++| Key | Action |+|---|---|+| **R** | Cycle the target's resolution: 96×60 → 192×120 → 384×240 → 768×480. The quad keeps the same on-screen size, so the fidelity change is obvious (and `resize` semantics are exercised — see below). |++## The exact flow the engine supports++`RenderTexture` is a **low-level** surface. Two things it does *not* do:++- **A camera cannot target a RenderTexture.** There is no "second camera+ rendering to an offscreen target" path.+- **It does not re-render the scene for you.** `begin`/`end` redirect whatever+ you draw with the immediate [`Draw` API](../../docs/astro/src/content/docs/guides/drawing.mdx)+ into the target, under a view-projection matrix you supply. Scene entities+ are not involved.++So a "minimap" here is *painted*, not re-rendered: the system queries the+shapes and draws one dot per shape with `Draw.rect`. (For a top-down minimap+that is also what most real games do.) The resulting `textureId` is an+ordinary texture handle usable anywhere — a `Sprite.texture`, `Draw.texture`,+a material texture parameter.++The full per-frame sequence, from `src/systems/minimap.ts`:++```typescript+RenderTexture.begin(rt, viewProjection); // binds the offscreen target+Draw.begin(viewProjection); // opens the immediate-draw batch+Renderer.setViewport(0, 0, rt.width, rt.height);++Draw.rect(...); // opaque background = the clear+Draw.rectOutline(...); // world border, camera view rect+Draw.rect(...); // one dot per shape++Draw.end(); // submits the batch into the target+RenderTexture.end(); // closes the pass, back to the screen+```++Four practical rules this example encodes:++1. **Run the pass outside the scene render.** A `begin`/`end` pair is a+ self-contained render pass. Do it from a `Schedule.Update` system (the+ engine renders in `Schedule.Last`) — *not* inside a `registerDrawCallback`+ callback, which runs in the middle of the on-screen pass.+2. **Set the viewport, after `Draw.begin`.** `Draw.begin` resets the GL+ viewport to the screen size, so call+ `Renderer.setViewport(0, 0, rt.width, rt.height)` after it (and before+ `Draw.end`, which is when the batch is actually submitted). No restore is+ needed — every on-screen camera pass sets its own viewport.+3. **The pass does not clear the target.** Contents persist between frames;+ the first opaque full-target rect is your clear (or a feature — leave+ trails by painting a translucent one).+4. **The view-projection is yours to build.** It defines what world-space+ region maps onto the target. This example's ortho spans the *world's*+ extents, so all painting happens in plain world coordinates and the matrix+ does the world→minimap mapping. (`ortho()` is five lines in+ `src/systems/minimap.ts`; the SDK does not export one.)++One display-side detail: the minimap quad's Sprite sets **`flipY: true`**.+A GL framebuffer's row 0 is the target's *bottom*, while an image texture's+row 0 is its *top* — sampling a RenderTexture with regular sprite UVs shows+it upside down, and `flipY` is the one-field fix.++## API reference++### `RenderTexture.create(options)` → `RenderTextureHandle`++```typescript+const rt = RenderTexture.create({ width: 384, height: 240, depth: false, filter: 'nearest' });+```++#### `RenderTextureOptions`++| Field | Type | Default | Description |+|---|---|---|---|+| `width` | number | — | Target width in pixels (required). |+| `height` | number | — | Target height in pixels (required). |+| `depth` | boolean | `true` | Attach a depth buffer. Turn off for pure 2D compositing (this example does) to save memory. |+| `filter` | `'nearest'` \| `'linear'` | `'nearest'` | Sampling filter when the result is drawn. `nearest` keeps low resolutions honestly blocky; `linear` smooths. |++#### `RenderTextureHandle`++| Field | Description |+|---|---|+| `textureId` | The color attachment as an ordinary texture handle — assign it to `Sprite.texture`, pass it to `Draw.texture`, bind it as a material param. |+| `width` / `height` | The target's size in pixels. |++### Methods++| Method | Does |+|---|---|+| `begin(rt, viewProjection)` | Redirects subsequent rendering into the target under the matrix you supply. **Does not clear** the target. |+| `end()` | Ends the offscreen pass; rendering goes back to the screen. |+| `resize(rt, width, height)` | Releases the old target and creates a fresh one, preserving `depth`/`filter`. **Returns a new handle — the old handle (and its `textureId`) is dead.** Re-point every consumer at the new `textureId`; this example syncs the quad's `Sprite.texture` to `rt.textureId` every frame, so pressing **R** just works. |+| `getDepthTexture(rt)` | The depth attachment as a sampleable texture handle (targets created with `depth: true` only). |+| `release(rt)` | Frees the target and its textures. |++## Files++- `src/systems/minimap.ts` — the heart of the example: creates the target,+ paints it every frame with the `Draw` API, cycles its resolution on **R**,+ and keeps the quad's `Sprite.texture` pointed at the current `textureId`.+- `src/systems/setup.ts` — spawns the world (ground-dot grid, border frame),+ the orbiting shapes, and the minimap quad (`flipY: true`).+- `src/systems/orbit.ts` — drifts each shape along its ellipse.+- `src/components.ts` — `Orbit` motion params, `Blip` / `Minimap` tags.+- `src/config.ts` — world extents, shape roster, minimap resolutions/placement.+- `assets/scenes/main.esscene` — the static scene camera + UI canvas; the rest+ is spawned from code.++## 中文摘要++本示例演示 **`RenderTexture`** 离屏渲染——小地图 / 画中画的引擎基础设施。++引擎支持的确切流程(诚实说明):**相机不能以 RenderTexture 为渲染目标**,+它也**不会替你重绘场景**;`begin`/`end` 之间用即时 `Draw` API 画什么,+什么就落进离屏目标,视图投影矩阵由你自己提供。得到的 `textureId` 是普通+纹理句柄,可赋给 `Sprite.texture` 等任何吃纹理的地方。++- 彩色方块沿椭圆轨道漂移,大部分时间在相机视野之外;右上角小地图每帧由+ 系统用 `Draw.rect` 重绘全世界(背景不透明矩形兼作清屏——pass 本身不清)。+- 按 **R** 循环切换目标分辨率;`resize` 会**返回新句柄、textureId 随之改变**,+ 所有消费者必须重新指向新 id(本例每帧同步 `Sprite.texture`)。+- 四条实践规则:在 `Schedule.Update` 里做离屏 pass(不要在 draw callback 里);+ `Draw.begin` 之后调 `Renderer.setViewport(0,0,rt.width,rt.height)`;+ 自己画清屏背景;正交矩阵自己搭(SDK 不导出 `ortho`)。+- 显示端细节:GL 帧缓冲第 0 行在底部,与图片纹理相反,采样会上下颠倒,+ 小地图 Sprite 用 `flipY: true` 一字段修正。++`RenderTextureOptions` 各字段(`width`/`height` 必填、`depth` 默认开、+`filter` 默认 `nearest`)见上方英文表格。diff --git a/examples/render-texture/assets/scenes/main.esscene b/examples/render-texture/assets/scenes/main.esscenenew file mode 100644index 000000000..222633051--- /dev/null+++ b/examples/render-texture/assets/scenes/main.esscene@@ -0,0 +1,57 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 360,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "UICanvas",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Canvas",+ "data": {+ "designResolution": {+ "x": 1280,+ "y": 720+ },+ "scaleMode": 2+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/render-texture/assets/scenes/main.esscene.meta b/examples/render-texture/assets/scenes/main.esscene.metanew file mode 100644index 000000000..0ffa95063--- /dev/null+++ b/examples/render-texture/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "77992c0e-9224-491b-8b7b-10b252ff1460",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/render-texture/project.esproject b/examples/render-texture/project.esprojectnew file mode 100644index 000000000..9724b052e--- /dev/null+++ b/examples/render-texture/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Render Texture",+ "description": "Offscreen rendering with RenderTexture: a live minimap painted with the Draw API every frame, displayed on a Sprite, with hot resolution switching.",+ "tag": "Rendering",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 1280,+ "height": 720+ },+ "spineVersion": "none"+}diff --git a/examples/render-texture/src/components.ts b/examples/render-texture/src/components.tsnew file mode 100644index 000000000..dead28b7a--- /dev/null+++ b/examples/render-texture/src/components.ts@@ -0,0 +1,19 @@+import { defineComponent, defineTag } from 'esengine';++// The project's declaration entry (src/components.ts): user component/tag+// definitions only — no systems. The editor extracts schemas from here so the+// inspector knows their fields without running project code.++/** Elliptical-orbit motion parameters for a drifting shape. */+export const Orbit = defineComponent('Orbit', {+ rx: 400,+ ry: 300,+ speed: 0.5,+ phase: 0,+});++/** Marks a shape the minimap plots (its Sprite provides color and size). */+export const Blip = defineTag('Blip');++/** Marks the corner quad whose Sprite.texture is the minimap RenderTexture. */+export const Minimap = defineTag('Minimap');diff --git a/examples/render-texture/src/config.ts b/examples/render-texture/src/config.tsnew file mode 100644index 000000000..4eaff9e38--- /dev/null+++ b/examples/render-texture/src/config.ts@@ -0,0 +1,55 @@+/** Half-extents of the world the shapes roam (world units). The camera only+ * shows ±640 × ±360 of it, so most shapes spend time offscreen — which is+ * what makes the minimap worth having. */+export const WORLD_HALF_W = 1600;+export const WORLD_HALF_H = 1000;++/** Half-extents of what the static scene camera shows (orthoSize 360 at 16:9). */+export const VIEW_HALF_W = 640;+export const VIEW_HALF_H = 360;++/** Spacing/size of the dim ground-dot grid that gives the world some texture. */+export const GRID_STEP = 200;+export const GRID_DOT = 12;++/**+ * Minimap RenderTexture resolutions the R key cycles through (all 16:10, the+ * world's aspect ratio, so nothing stretches). The on-screen quad keeps the+ * same DISPLAY size, so switching resolution visibly changes fidelity: 96×60+ * is chunky pixels, 768×480 is crisp.+ */+export const MINIMAP_RESOLUTIONS = [+ { w: 96, h: 60 },+ { w: 192, h: 120 },+ { w: 384, h: 240 },+ { w: 768, h: 480 },+];+export const MINIMAP_START_RESOLUTION = 2;++/** On-screen size and placement of the minimap quad (world units; the camera+ * is static at the origin so world units == design pixels here). */+export const MINIMAP_DISPLAY = { w: 320, h: 200 };+export const MINIMAP_MARGIN = 20;+export const MINIMAP_LAYER = 10;++/** World-space margin painted around the world border inside the minimap. */+export const MINIMAP_PAD = 80;++/** Blips are drawn at twice their true size on the map for legibility. */+export const BLIP_SCALE = 2;++/** The drifting shapes: orbit ellipse, angular speed (rad/s), start phase,+ * sprite size, and color. Negative speed = counter-clockwise. */+export const SHAPES: Array<{+ rx: number; ry: number; speed: number; phase: number;+ size: number;+ color: { r: number; g: number; b: number; a: number };+}> = [+ { rx: 420, ry: 260, speed: 0.7, phase: 0.0, size: 64, color: { r: 0.95, g: 0.45, b: 0.35, a: 1 } },+ { rx: 700, ry: 430, speed: -0.45, phase: 1.3, size: 80, color: { r: 0.4, g: 0.75, b: 1, a: 1 } },+ { rx: 950, ry: 600, speed: 0.32, phase: 2.4, size: 56, color: { r: 0.55, g: 0.9, b: 0.45, a: 1 } },+ { rx: 1180, ry: 740, speed: -0.24, phase: 4.1, size: 72, color: { r: 0.95, g: 0.8, b: 0.35, a: 1 } },+ { rx: 1400, ry: 880, speed: 0.18, phase: 5.2, size: 90, color: { r: 0.8, g: 0.55, b: 1, a: 1 } },+ { rx: 560, ry: 820, speed: 0.55, phase: 3.0, size: 48, color: { r: 0.4, g: 0.95, b: 0.85, a: 1 } },+ { rx: 1250, ry: 350, speed: -0.6, phase: 0.8, size: 60, color: { r: 1, g: 0.6, b: 0.8, a: 1 } },+];diff --git a/examples/render-texture/src/main.ts b/examples/render-texture/src/main.tsnew file mode 100644index 000000000..634d10016--- /dev/null+++ b/examples/render-texture/src/main.ts@@ -0,0 +1,24 @@+// Render Texture — offscreen rendering with the RenderTexture API:+//+// • A world of colored shapes drifts along orbits far beyond the camera's+// view — most of the world is offscreen at any moment.+// • A corner minimap quad shows all of it live: every frame a system paints+// the world schematically into a RenderTexture with the immediate Draw+// API, and the quad's Sprite samples the target's textureId.+// • R cycles the target's resolution through 96×60 → 192×120 → 384×240 →+// 768×480 at a fixed display size — resize() returns a NEW handle whose+// textureId the sprite must be re-pointed at.+//+// RenderTexture is a low-level surface: a camera cannot target it, and it does+// not re-render the scene. It redirects Draw commands issued between begin()+// and end() into an offscreen target, under a view-projection you supply.+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { setupSystem } from './systems/setup';+import { orbitSystem } from './systems/orbit';+import { minimapSystem } from './systems/minimap';++addStartupSystem(setupSystem);+addSystemToSchedule(Schedule.Update, orbitSystem);+addSystemToSchedule(Schedule.Update, minimapSystem);diff --git a/examples/render-texture/src/systems/minimap.ts b/examples/render-texture/src/systems/minimap.tsnew file mode 100644index 000000000..2c5eafcdb--- /dev/null+++ b/examples/render-texture/src/systems/minimap.ts@@ -0,0 +1,130 @@+import {+ defineSystem, Query, Mut, Res, Input, Transform, Sprite,+ RenderTexture, Renderer, Draw,+ type RenderTextureHandle,+} from 'esengine';+import { Blip, Minimap } from '../components';+import {+ WORLD_HALF_W, WORLD_HALF_H, VIEW_HALF_W, VIEW_HALF_H,+ MINIMAP_RESOLUTIONS, MINIMAP_START_RESOLUTION, MINIMAP_PAD, BLIP_SCALE,+} from '../config';++// The render-to-texture flow this engine supports:+//+// RenderTexture is a LOW-LEVEL surface — a camera cannot target it, and it+// does not re-render the scene for you. What it does is redirect whatever+// you draw with the immediate `Draw` API between `begin`/`end` into an+// offscreen target, under a view-projection matrix you supply. The handle's+// `textureId` is then an ordinary texture usable anywhere (here: the corner+// quad's `Sprite.texture`).+//+// So the minimap is painted, not re-rendered: each frame this system opens the+// target, lays down a background (the pass does NOT clear — the first opaque+// rect is the clear), draws the world border, the camera's view rectangle,+// and one dot per shape, then closes the target. Because the ortho matrix+// spans the WORLD's extents, everything is drawn in plain world coordinates —+// the matrix does the world→minimap mapping.+//+// This runs in Schedule.Update, before the engine's render system+// (Schedule.Last) draws the scene — a begin/end pair is a self-contained+// render pass, so it must not run inside the scene pass (e.g. inside a+// registerDrawCallback callback).++/** Column-major ortho projection (the view-projection RenderTexture.begin+ * wants). Not exported by the SDK — five lines to build yourself. */+function ortho(l: number, r: number, b: number, t: number): Float32Array {+ const m = new Float32Array(16);+ m[0] = 2 / (r - l);+ m[5] = 2 / (t - b);+ m[10] = -1;+ m[12] = -(r + l) / (r - l);+ m[13] = -(t + b) / (t - b);+ m[15] = 1;+ return m;+}++const MAP_VP = ortho(+ -WORLD_HALF_W - MINIMAP_PAD, WORLD_HALF_W + MINIMAP_PAD,+ -WORLD_HALF_H - MINIMAP_PAD, WORLD_HALF_H + MINIMAP_PAD,+);++let rt: RenderTextureHandle | null = null;+let resolutionIndex = MINIMAP_START_RESOLUTION;++export const minimapSystem = defineSystem(+ [Res(Input), Query(Transform, Sprite, Blip), Query(Mut(Sprite), Minimap)],+ (input, blips, minimapQuads) => {+ if (!rt) {+ const res = MINIMAP_RESOLUTIONS[resolutionIndex];+ // depth off: pure 2D compositing needs no depth buffer. nearest+ // filter: makes the low resolutions honestly blocky on screen.+ const created = RenderTexture.create({ width: res.w, height: res.h, depth: false, filter: 'nearest' });+ if (created.textureId === 0) {+ // Renderer not booted yet — try again next frame.+ RenderTexture.release(created);+ return;+ }+ rt = created;+ }++ // R cycles the target's resolution. resize() releases the old target+ // and returns a NEW handle — the textureId changes, so every consumer+ // must be re-pointed at it (done below, where the quad's Sprite is+ // synced to rt.textureId every frame).+ if (input.isKeyPressed('KeyR')) {+ resolutionIndex = (resolutionIndex + 1) % MINIMAP_RESOLUTIONS.length;+ const res = MINIMAP_RESOLUTIONS[resolutionIndex];+ rt = RenderTexture.resize(rt, res.w, res.h);+ }++ for (const [, sprite] of minimapQuads) {+ if (sprite.texture !== rt.textureId) sprite.texture = rt.textureId;+ }++ // --- The offscreen pass -------------------------------------------+ RenderTexture.begin(rt, MAP_VP);+ Draw.begin(MAP_VP);+ // Draw.begin resets the GL viewport to the SCREEN size; point it at+ // the target instead. Must come after Draw.begin, before Draw.end+ // (which is when the batched primitives are actually submitted). No+ // restore needed: every on-screen camera pass sets its own viewport.+ Renderer.setViewport(0, 0, rt.width, rt.height);++ // Opaque background first — the pass does not clear the target.+ Draw.rect(+ { x: 0, y: 0 },+ { x: (WORLD_HALF_W + MINIMAP_PAD) * 2, y: (WORLD_HALF_H + MINIMAP_PAD) * 2 },+ { r: 0.07, g: 0.09, b: 0.13, a: 1 },+ );++ // World border. Thicknesses are world units — the ortho maps ~8.6+ // world units to one texel at 384×240, so borders are drawn fat.+ Draw.rectOutline(+ { x: 0, y: 0 },+ { x: WORLD_HALF_W * 2, y: WORLD_HALF_H * 2 },+ { r: 0.45, g: 0.5, b: 0.6, a: 1 },+ 24,+ );++ // The rectangle the static scene camera actually shows.+ Draw.rectOutline(+ { x: 0, y: 0 },+ { x: VIEW_HALF_W * 2, y: VIEW_HALF_H * 2 },+ { r: 0.9, g: 0.92, b: 1, a: 0.55 },+ 18,+ );++ // One dot per shape, in its own color, exaggerated for legibility.+ for (const [, transform, sprite] of blips) {+ Draw.rect(+ { x: transform.position.x, y: transform.position.y },+ { x: sprite.size.x * BLIP_SCALE, y: sprite.size.y * BLIP_SCALE },+ sprite.color,+ );+ }++ Draw.end();+ RenderTexture.end();+ },+ { name: 'MinimapSystem' },+);diff --git a/examples/render-texture/src/systems/orbit.ts b/examples/render-texture/src/systems/orbit.tsnew file mode 100644index 000000000..f3864f0c5--- /dev/null+++ b/examples/render-texture/src/systems/orbit.ts@@ -0,0 +1,17 @@+import { defineSystem, Query, Mut, Res, Time, Transform } from 'esengine';+import { Orbit } from '../components';++// Drifts each shape along its ellipse. Most orbits reach far beyond the+// camera's ±640 × ±360 view, so shapes keep leaving the screen — watch the+// minimap to see where they went.+export const orbitSystem = defineSystem(+ [Query(Mut(Transform), Mut(Orbit)), Res(Time)],+ (query, time) => {+ for (const [, transform, orbit] of query) {+ orbit.phase += orbit.speed * time.delta;+ transform.position.x = Math.cos(orbit.phase) * orbit.rx;+ transform.position.y = Math.sin(orbit.phase) * orbit.ry;+ }+ },+ { name: 'OrbitSystem' },+);diff --git a/examples/render-texture/src/systems/setup.ts b/examples/render-texture/src/systems/setup.tsnew file mode 100644index 000000000..17c0b0add--- /dev/null+++ b/examples/render-texture/src/systems/setup.ts@@ -0,0 +1,81 @@+import { defineSystem, Commands, Transform, Sprite } from 'esengine';+import { Orbit, Blip, Minimap } from '../components';+import {+ WORLD_HALF_W, WORLD_HALF_H, VIEW_HALF_W, VIEW_HALF_H, GRID_STEP, GRID_DOT,+ MINIMAP_DISPLAY, MINIMAP_MARGIN, MINIMAP_LAYER, SHAPES,+} from '../config';++// Builds the world from code: a dim ground-dot grid, a border frame at the+// world's edge, the drifting shapes the minimap tracks, and the minimap quad+// itself. The quad's Sprite.texture starts at 0 — the minimap system points it+// at the RenderTexture's textureId on its first run (same first frame, before+// anything renders).+export const setupSystem = defineSystem(+ [Commands()],+ (cmds) => {+ for (let x = -WORLD_HALF_W; x <= WORLD_HALF_W; x += GRID_STEP) {+ for (let y = -WORLD_HALF_H; y <= WORLD_HALF_H; y += GRID_STEP) {+ cmds.spawn()+ .insert(Transform, { position: { x, y, z: 0 } })+ .insert(Sprite, {+ size: { x: GRID_DOT, y: GRID_DOT },+ color: { r: 0.22, g: 0.24, b: 0.28, a: 1 },+ layer: 0,+ });+ }+ }++ // Border frame marking the edge of the world the shapes roam.+ const frames = [+ { x: 0, y: WORLD_HALF_H, w: WORLD_HALF_W * 2, h: 8 },+ { x: 0, y: -WORLD_HALF_H, w: WORLD_HALF_W * 2, h: 8 },+ { x: -WORLD_HALF_W, y: 0, w: 8, h: WORLD_HALF_H * 2 },+ { x: WORLD_HALF_W, y: 0, w: 8, h: WORLD_HALF_H * 2 },+ ];+ for (const f of frames) {+ cmds.spawn()+ .insert(Transform, { position: { x: f.x, y: f.y, z: 0 } })+ .insert(Sprite, {+ size: { x: f.w, y: f.h },+ color: { r: 0.45, g: 0.5, b: 0.6, a: 1 },+ layer: 1,+ });+ }++ for (const s of SHAPES) {+ cmds.spawn()+ .insert(Transform, {+ position: { x: Math.cos(s.phase) * s.rx, y: Math.sin(s.phase) * s.ry, z: 0 },+ })+ .insert(Sprite, {+ size: { x: s.size, y: s.size },+ color: s.color,+ layer: 2,+ })+ .insert(Orbit, { rx: s.rx, ry: s.ry, speed: s.speed, phase: s.phase })+ .insert(Blip);+ }++ // The minimap quad, pinned to the view's top-right corner (the scene+ // camera is static at the origin, so world units == design pixels).+ // flipY compensates for GL framebuffer orientation: a RenderTexture's+ // row 0 is the target's BOTTOM, while an image texture's row 0 is its+ // top — sampling one with regular sprite UVs shows it upside down.+ cmds.spawn('Minimap')+ .insert(Transform, {+ position: {+ x: VIEW_HALF_W - MINIMAP_MARGIN - MINIMAP_DISPLAY.w / 2,+ y: VIEW_HALF_H - MINIMAP_MARGIN - MINIMAP_DISPLAY.h / 2,+ z: 0,+ },+ })+ .insert(Sprite, {+ size: { x: MINIMAP_DISPLAY.w, y: MINIMAP_DISPLAY.h },+ color: { r: 1, g: 1, b: 1, a: 1 },+ flipY: true,+ layer: MINIMAP_LAYER,+ })+ .insert(Minimap);+ },+ { name: 'SetupSystem' },+);diff --git a/examples/render-texture/tsconfig.json b/examples/render-texture/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/render-texture/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/examples/timers-demo/.gitignore b/examples/timers-demo/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/timers-demo/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/timers-demo/README.md b/examples/timers-demo/README.mdnew file mode 100644index 000000000..85eccbc39--- /dev/null+++ b/examples/timers-demo/README.md@@ -0,0 +1,105 @@+# Timers++Every gameplay codebase grows little `phase += time.delta; if (phase >= 0.8) {+phase -= 0.8; …}` accumulator systems. `TimerManager` (the `Timer` resource)+replaces that boilerplate with scheduled callbacks: **`delay()`** for one-shots,+**`interval()`** for repeats, and a **`TimerHandle`** to pause / resume / cancel+/ reset each one. This playground drives everything visual through timers:++- **Heartbeat** — an `interval(0.8, …)` kicks the red square's scale and bumps+ the counter; a per-frame system only decays the scale back. No accumulator.+- **Firework in 1s** — a `delay(1, …)` fuse bursts colored sparks, and a second+ `delay(1.4, …)` despawns the batch (delay-as-lifetime).+- **Countdown ×3** — `interval(1, cb, 3)` fires exactly three times, then+ removes itself (`isActive` flips to false with no `cancel()` call).+- **Spawner row** — an `interval(0.7, …)` drops drifting squares; Pause /+ Resume / Cancel / Restart exercise the full `TimerHandle` surface. Each+ drifter's death is a `delay(7, …)`.+- **Scale row** — sets `TimerManager.timeScale`. All timers slow down or speed+ up; the drifters keep falling at the same speed because motion runs on+ `Time.delta`, which the timer scale does not touch. Watch spawn density+ change while fall speed doesn't.++## API++The plugin is part of the default web/headless app plugin sets — nothing to+register. Get the manager in a system with `Res(TimerRes)`.++### `TimerManager`++| Member | Default | Semantics |+| ------ | ------- | --------- |+| `delay(seconds, cb)` | — | One-shot. Fires once when `elapsed >= seconds`, then the timer removes itself. Returns a `TimerHandle`. |+| `interval(seconds, cb, maxRepeat?)` | `maxRepeat = 0` | Repeating. First fire after `seconds`, then every `seconds`. `maxRepeat = 0` means forever; `maxRepeat = n` fires exactly `n` times, then the timer removes itself. |+| `timeScale` | `1` | Multiplies the dt fed to **all** timers (clamped to `>= 0`; `0` freezes them). Independent of `Time` — per-frame systems are unaffected. |+| `cancelAll()` | — | Removes every timer. |+| `activeCount` | — | Number of live timers (shown in the HUD's scale line). |+| `pause/resume/cancel/reset(id)` | — | Id-based forms of the handle methods below. |++### `TimerHandle` (returned by `delay` / `interval`)++| Member | Semantics |+| ------ | --------- |+| `pause()` / `resume()` | Freeze / unfreeze this timer's `elapsed` clock. Chainable. |+| `cancel()` | Remove the timer. A cancelled handle is dead — `resume()` on it is a no-op; schedule a new timer (the Restart button shows both paths). |+| `reset()` | Rewind `elapsed` and `repeatCount` to 0 on a live timer (a spent `maxRepeat` timer is already gone — reset can't revive it). |+| `isActive` | False once the timer fired its last shot or was cancelled. |+| `elapsed` | Seconds (scaled) into the current cycle. |+| `repeatCount` | Completed fires. **Inside the callback it is the count of *previous* fires** — it increments after the callback returns (the countdown uses this: first fire sees `0`). |+| `id` | Stable numeric id, usable with the manager's id-based methods. |++The callback receives the handle (`(t) => …`), so an infinite interval can+`t.cancel()` itself when a condition is met.++### The clock — what timers tick on++- The `TimerSystem` runs in **`Schedule.PreUpdate`** and advances every timer+ by `Time.delta * timeScale`. Callbacks therefore run **before** your Update+ systems in the same frame, on the main thread, in scheduling order.+- Firing is **frame-quantized**: a timer fires on the first tick at/past its+ deadline, so actual latency is up to one frame late. Don't use timers for+ sub-frame precision (audio scheduling, physics) — they're gameplay-grade.+- A timer fires **at most once per frame**. A long hitch doesn't burst-fire a+ short interval; the overshoot remainder is carried into the next cycle, so+ intervals don't drift over time.+- The system is gated `playModeOnly` — timers are **frozen in the editor's+ edit mode** and advance in play mode, like game time.++## Lifetime rules++Timers live on the `TimerManager` **app resource** — they are not attached to+entities or scenes:++- **Despawning an entity does not cancel timers** whose callbacks captured it.+ Either cancel the handle when the entity dies, or guard in the callback:+ `if (world.valid(entity)) world.despawn(entity)` (see `spawnDrifter`).+- **Loading another scene does not clear timers.** A pending callback will run+ against the new world; `findEntityByName` / `world.valid` guards keep that+ safe, or call `cancelAll()` / cancel your handles on teardown.+- A fresh play session builds a fresh app, so a fresh (empty) `TimerManager`.++## Timers vs `Time.delta` accumulation vs tween delays++| Use | When |+| --- | ---- |+| **`TimerManager`** | *Scheduling* — "in 2s", "every 0.7s", "3 times then stop", anything you'd otherwise write an accumulator for, especially when it must be pausable/cancellable from elsewhere (ability cooldowns, spawn waves, timed despawns, countdowns). |+| **`Time.delta` accumulation in a system** | *Continuous per-frame math* — integration, easing, decay, anything evaluated every frame anyway (`motion.ts` here). Also per-entity clocks you want serialized with the entity: component fields save/replicate; timers don't. |+| **Tween `delay` option** | A wait that exists only to sequence an *animation* (`tween(target, { delay: 0.3, … })`). The delay lives and dies with the tween — cancel the tween, the wait goes too. Don't schedule gameplay logic with it. |++Rule of thumb: timers decide **when**, systems compute **every frame**, tweens+animate **values**.++## Files++```+assets/+ scenes/main.esscene # camera, heart square, HUD panel (labels + empty button rows)+src/+ main.ts # registers the systems+ components.ts # Heart, Spark, Drifter+ state.ts # module state + the TimerHandles the buttons control+ systems/+ build.ts # schedules all timers, builds the buttons+ motion.ts # per-frame integration (sparks, drifters, heart decay)+ hud.ts # labels track state + live handle fields (elapsed, repeatCount)+```diff --git a/examples/timers-demo/assets/scenes/main.esscene b/examples/timers-demo/assets/scenes/main.esscenenew file mode 100644index 000000000..fd4c3bee8--- /dev/null+++ b/examples/timers-demo/assets/scenes/main.esscene@@ -0,0 +1,250 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": { "x": 0, "y": 0, "z": 10 }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Heart",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": -310, "y": -180, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 56, "y": 56 }, "color": { "r": 0.92, "g": 0.28, "b": 0.38, "a": 1 } } },+ { "type": "Heart", "data": {} }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Canvas",+ "parent": null,+ "children": [3],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "Canvas",+ "data": {+ "designResolution": { "x": 800, "y": 600 },+ "scaleMode": 2+ }+ },+ { "type": "UINode", "data": {} }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "Panel",+ "parent": 2,+ "children": [4, 5, 6, 7, 8, 9],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "width": { "value": 560, "unit": 0 },+ "height": { "value": 252, "unit": 0 },+ "insetLeft": { "value": 50, "unit": 1 },+ "insetTop": { "value": 16, "unit": 0 },+ "marginLeft": { "value": -280, "unit": 0 }+ }+ },+ {+ "type": "FlexContainer",+ "data": {+ "direction": 1,+ "justifyContent": 0,+ "alignItems": 3,+ "gap": { "x": 0, "y": 10 },+ "padding": { "left": 16, "top": 16, "right": 16, "bottom": 16 }+ }+ },+ {+ "type": "UIVisual",+ "data": {+ "visualType": 1,+ "color": { "r": 0.16, "g": 0.16, "b": 0.18, "a": 0.92 },+ "enabled": true+ }+ }+ ],+ "visible": true+ },+ {+ "id": 4,+ "name": "BeatLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 26, "unit": 0 } }+ },+ {+ "type": "Text",+ "data": {+ "content": "Heartbeats: 0",+ "fontSize": 18,+ "bold": true,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 5,+ "name": "SpawnerLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 18, "unit": 0 } }+ },+ {+ "type": "Text",+ "data": {+ "content": "Spawner: starting…",+ "fontSize": 13,+ "color": { "r": 0.72, "g": 0.75, "b": 0.8, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 6,+ "name": "StatusLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 18, "unit": 0 } }+ },+ {+ "type": "Text",+ "data": {+ "content": "Timers tick in PreUpdate — press a button.",+ "fontSize": 12,+ "color": { "r": 0.72, "g": 0.75, "b": 0.8, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 7,+ "name": "FxRow",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 36, "unit": 0 } }+ },+ {+ "type": "FlexContainer",+ "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }+ }+ ],+ "visible": true+ },+ {+ "id": 8,+ "name": "SpawnerRow",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 36, "unit": 0 } }+ },+ {+ "type": "FlexContainer",+ "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }+ }+ ],+ "visible": true+ },+ {+ "id": 9,+ "name": "ScaleRow",+ "parent": 3,+ "children": [10],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 36, "unit": 0 } }+ },+ {+ "type": "FlexContainer",+ "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }+ }+ ],+ "visible": true+ },+ {+ "id": 10,+ "name": "ScaleLabel",+ "parent": 9,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "flexGrow": 1, "alignSelf": 4 }+ },+ {+ "type": "Text",+ "data": {+ "content": "Timer scale: 1× (motion is unaffected)",+ "fontSize": 13,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/timers-demo/assets/scenes/main.esscene.meta b/examples/timers-demo/assets/scenes/main.esscene.metanew file mode 100644index 000000000..0578851b9--- /dev/null+++ b/examples/timers-demo/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "13b6767b-2477-42fc-ac78-cb25891af636",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/timers-demo/project.esproject b/examples/timers-demo/project.esprojectnew file mode 100644index 000000000..f715e71c8--- /dev/null+++ b/examples/timers-demo/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Timers",+ "description": "Delayed fireworks, heartbeat intervals and a controllable spawner — TimerManager instead of hand-rolled delta accumulators.",+ "tag": "Basics",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 800,+ "height": 600+ },+ "spineVersion": "none"+}diff --git a/examples/timers-demo/src/components.ts b/examples/timers-demo/src/components.tsnew file mode 100644index 000000000..cbde1848e--- /dev/null+++ b/examples/timers-demo/src/components.ts@@ -0,0 +1,16 @@+import { defineComponent } from 'esengine';++export const Heart = defineComponent('Heart', {+ beatScale: 1.35,+});++export const Spark = defineComponent('Spark', {+ vx: 0,+ vy: 0,+});++export const Drifter = defineComponent('Drifter', {+ vy: -110,+ baseX: 0,+ phase: 0,+});diff --git a/examples/timers-demo/src/main.ts b/examples/timers-demo/src/main.tsnew file mode 100644index 000000000..16651b9b9--- /dev/null+++ b/examples/timers-demo/src/main.ts@@ -0,0 +1,14 @@+// Timers — TimerManager scheduling (delay / interval / TimerHandle control /+// timeScale) instead of hand-rolled Time.delta accumulators.+import { addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { buildSystem } from './systems/build';+import { sparkSystem, drifterSystem, heartDecaySystem } from './systems/motion';+import { hudSystem } from './systems/hud';++addSystemToSchedule(Schedule.Update, buildSystem);+addSystemToSchedule(Schedule.Update, sparkSystem);+addSystemToSchedule(Schedule.Update, drifterSystem);+addSystemToSchedule(Schedule.Update, heartDecaySystem);+addSystemToSchedule(Schedule.Update, hudSystem);diff --git a/examples/timers-demo/src/state.ts b/examples/timers-demo/src/state.tsnew file mode 100644index 000000000..a46136e15--- /dev/null+++ b/examples/timers-demo/src/state.ts@@ -0,0 +1,14 @@+import type { TimerHandle } from 'esengine';++// Module state shared between the build system (which wires timers to buttons),+// the timer callbacks, and the HUD. Handles are kept here so any button can+// pause / resume / cancel a timer created elsewhere.+export const game = {+ built: false,+ beats: 0,+ spawned: 0,+ spawnerPaused: false,+ spawner: null as TimerHandle | null,+ countdown: null as TimerHandle | null,+ status: 'Timers tick in PreUpdate — press a button.',+};diff --git a/examples/timers-demo/src/systems/build.ts b/examples/timers-demo/src/systems/build.tsnew file mode 100644index 000000000..8f663806c--- /dev/null+++ b/examples/timers-demo/src/systems/build.ts@@ -0,0 +1,192 @@+// Wires the whole playground: schedules the heartbeat + spawner intervals and+// builds the buttons that drive one-shot delays, a limited-repeat countdown,+// TimerHandle control (pause/resume/cancel/reset) and the global timeScale.+import {+ defineSystem, Res, GetWorld,+ UIEvents, TimerRes, Transform, Sprite,+ createButton, themeColors, px,+} from 'esengine';+import type {+ Entity, World, Color, ThemeColors, UIEventQueue, TimerManager,+} from 'esengine';++import { Heart, Spark, Drifter } from '../components';+import { game } from '../state';++const BTN_H = 32;++const SPARK_COLORS: ReadonlyArray<Color> = [+ { r: 0.98, g: 0.8, b: 0.2, a: 1 },+ { r: 0.92, g: 0.28, b: 0.38, a: 1 },+ { r: 0.28, g: 0.54, b: 0.92, a: 1 },+ { r: 0.28, g: 0.92, b: 0.54, a: 1 },+ { r: 0.79, g: 0.28, b: 0.92, a: 1 },+];++export const buildSystem = defineSystem(+ [Res(UIEvents), Res(TimerRes), GetWorld()],+ (events: UIEventQueue, timers: TimerManager, world: World) => {+ if (game.built) return;++ const fxRow = world.findEntityByName('FxRow');+ const spawnerRow = world.findEntityByName('SpawnerRow');+ const scaleRow = world.findEntityByName('ScaleRow');+ if (fxRow === null || spawnerRow === null || scaleRow === null) return;+ game.built = true;++ // interval(seconds, cb): first fire after `seconds`, then every+ // `seconds`. The heartbeat replaces the classic "phase += time.delta;+ // if (phase >= BEAT) { phase -= BEAT; … }" accumulator system.+ timers.interval(0.8, () => {+ game.beats += 1;+ kickHeart(world);+ });++ startSpawner(world, timers);++ const c = themeColors();++ button(world, events, fxRow, c, true, 'Firework in 1s', 128, () => {+ game.status = 'Fuse lit — bursting in 1 second…';+ timers.delay(1, () => burstFirework(world, timers));+ });+ button(world, events, fxRow, c, false, 'Countdown ×3', 118, () => {+ // maxRepeat = 3: fires at t=1s, 2s, 3s, then removes itself —+ // isActive flips to false without any cancel() call.+ if (game.countdown?.isActive) return;+ game.status = 'Countdown: 3…';+ game.countdown = timers.interval(1, (t) => {+ // Inside a callback, repeatCount is the number of PREVIOUS+ // fires (it increments after the callback returns).+ const remaining = 2 - t.repeatCount;+ if (remaining > 0) {+ game.status = `Countdown: ${remaining}…`;+ } else {+ game.status = 'Lift-off!';+ burstFirework(world, timers);+ }+ }, 3);+ });++ button(world, events, spawnerRow, c, false, 'Pause', 92, () => {+ if (!game.spawner?.isActive) return;+ game.spawner.pause();+ game.spawnerPaused = true;+ game.status = 'Spawner paused — its elapsed clock freezes.';+ });+ button(world, events, spawnerRow, c, false, 'Resume', 92, () => {+ if (!game.spawner?.isActive) return;+ game.spawner.resume();+ game.spawnerPaused = false;+ game.status = 'Spawner resumed from where it froze.';+ });+ button(world, events, spawnerRow, c, false, 'Cancel', 92, () => {+ game.spawner?.cancel();+ game.spawnerPaused = false;+ game.status = 'Spawner cancelled — the handle is dead (isActive = false).';+ });+ button(world, events, spawnerRow, c, false, 'Restart', 92, () => {+ if (game.spawner?.isActive) {+ // reset() rewinds elapsed + repeatCount on a live timer.+ game.spawner.reset();+ game.spawner.resume();+ game.spawnerPaused = false;+ game.status = 'Live spawner reset() — cycle rewound to 0.';+ } else {+ // A cancelled handle cannot be revived; schedule a new timer.+ startSpawner(world, timers);+ game.status = 'Cancelled handle cannot restart — scheduled a new interval.';+ }+ });++ for (const scale of [0.5, 1, 2]) {+ button(world, events, scaleRow, c, false, `${scale}×`, 56, () => {+ timers.timeScale = scale;+ game.status = `TimerManager.timeScale = ${scale} — all timers, not Time.delta.`;+ });+ }+ },+ { name: 'BuildSystem' },+);++function startSpawner(world: World, timers: TimerManager): void {+ game.spawnerPaused = false;+ game.spawner = timers.interval(0.7, () => spawnDrifter(world, timers));+}++function spawnDrifter(world: World, timers: TimerManager): void {+ game.spawned += 1;+ const x = -360 + Math.random() * 720;+ const entity = world.spawn('Drifter');+ world.insert(entity, Transform, { position: { x, y: 340, z: 0 } });+ world.insert(entity, Sprite, {+ size: { x: 22, y: 22 },+ color: { ...SPARK_COLORS[game.spawned % SPARK_COLORS.length] },+ });+ world.insert(entity, Drifter, {+ vy: -(90 + Math.random() * 60),+ baseX: x,+ phase: Math.random() * Math.PI * 2,+ });++ // delay() as entity lifetime — no per-entity age accumulator. Timers are+ // app-scoped and outlive entities, so guard against the entity having been+ // despawned by something else before the timer fires.+ timers.delay(7, () => {+ if (world.valid(entity)) world.despawn(entity);+ });+}++function burstFirework(world: World, timers: TimerManager): void {+ const cx = -160 + Math.random() * 320;+ const cy = -220 + Math.random() * 160;+ const sparks: Entity[] = [];++ for (let i = 0; i < 14; i++) {+ const angle = (i / 14) * Math.PI * 2;+ const speed = 160 + Math.random() * 80;+ const entity = world.spawn('Spark');+ world.insert(entity, Transform, { position: { x: cx, y: cy, z: 0 } });+ world.insert(entity, Sprite, {+ size: { x: 14, y: 14 },+ color: { ...SPARK_COLORS[i % SPARK_COLORS.length] },+ });+ world.insert(entity, Spark, {+ vx: Math.cos(angle) * speed,+ vy: Math.sin(angle) * speed,+ });+ sparks.push(entity);+ }++ timers.delay(1.4, () => {+ for (const entity of sparks) {+ if (world.valid(entity)) world.despawn(entity);+ }+ });+}++function kickHeart(world: World): void {+ const heart = world.findEntityByName('Heart');+ if (heart === null || !world.has(heart, Transform)) return;+ const beat = world.get(heart, Heart);+ const t = world.get(heart, Transform);+ t.scale.x = beat.beatScale;+ t.scale.y = beat.beatScale;+ world.insert(heart, Transform, t);+}++function button(+ world: World, events: UIEventQueue, parent: Entity, c: ThemeColors,+ primary: boolean, label: string, width: number, onClick: () => void,+): void {+ const states = primary+ ? { normal: { color: c.primary }, hover: { color: c.primaryHover }, pressed: { color: c.primaryActive } }+ : { normal: { color: c.control }, hover: { color: c.controlHover }, pressed: { color: c.controlActive } };+ createButton({+ world, events, parent,+ node: { width: px(width), height: px(BTN_H) },+ states,+ text: { content: label, color: c.onPrimary, fontSize: 14 },+ onClick,+ });+}diff --git a/examples/timers-demo/src/systems/hud.ts b/examples/timers-demo/src/systems/hud.tsnew file mode 100644index 000000000..82fcaba37--- /dev/null+++ b/examples/timers-demo/src/systems/hud.ts@@ -0,0 +1,38 @@+import { defineSystem, Res, GetWorld, Text, TimerRes } from 'esengine';+import type { World, Entity, TextData, TimerManager } from 'esengine';++import { game } from '../state';++const cache = new Map<string, string>();++export const hudSystem = defineSystem(+ [Res(TimerRes), GetWorld()],+ (timers: TimerManager, world: World) => {+ setLabel(world, 'BeatLabel', `Heartbeats: ${game.beats}`);+ setLabel(world, 'SpawnerLabel', spawnerLine());+ setLabel(world, 'StatusLabel', game.status);+ setLabel(+ world, 'ScaleLabel',+ `Timer scale: ${timers.timeScale}× · active timers: ${timers.activeCount}`,+ );+ },+ { name: 'HudSystem' }+);++function spawnerLine(): string {+ const h = game.spawner;+ if (h === null) return 'Spawner: not started';+ if (!h.isActive) return `Spawner: cancelled · spawned ${game.spawned}`;+ const state = game.spawnerPaused ? 'paused' : 'running';+ return `Spawner: ${state} · spawned ${game.spawned} · cycle ${h.elapsed.toFixed(1)}s · fired ${h.repeatCount}×`;+}++function setLabel(world: World, name: string, content: string): void {+ if (cache.get(name) === content) return;+ const entity: Entity | null = world.findEntityByName(name);+ if (entity === null || !world.has(entity, Text)) return;+ const t = world.get(entity, Text) as TextData;+ t.content = content;+ world.insert(entity, Text, t);+ cache.set(name, content);+}diff --git a/examples/timers-demo/src/systems/motion.ts b/examples/timers-demo/src/systems/motion.tsnew file mode 100644index 000000000..7c982def9--- /dev/null+++ b/examples/timers-demo/src/systems/motion.ts@@ -0,0 +1,47 @@+// Per-frame motion stays on Time.delta — integration and smoothing belong to+// the frame loop. Timers only decide WHEN things happen (spawn, burst, despawn).+import {+ defineSystem, Query, Mut, Res, Time,+ Transform,+} from 'esengine';++import { Heart, Spark, Drifter } from '../components';++const GRAVITY = 420;++export const sparkSystem = defineSystem(+ [Query(Mut(Transform), Mut(Spark)), Res(Time)],+ (sparks, time) => {+ for (const [_entity, transform, spark] of sparks) {+ spark.vy -= GRAVITY * time.delta;+ transform.position.x += spark.vx * time.delta;+ transform.position.y += spark.vy * time.delta;+ }+ },+ { name: 'SparkSystem' }+);++export const drifterSystem = defineSystem(+ [Query(Mut(Transform), Drifter), Res(Time)],+ (drifters, time) => {+ for (const [_entity, transform, drifter] of drifters) {+ transform.position.y += drifter.vy * time.delta;+ transform.position.x =+ drifter.baseX + Math.sin(time.elapsed * 2 + drifter.phase) * 24;+ }+ },+ { name: 'DrifterSystem' }+);++// The heartbeat timer kicks scale up; this system only decays it back to 1.+export const heartDecaySystem = defineSystem(+ [Query(Mut(Transform), Heart), Res(Time)],+ (hearts, time) => {+ const k = Math.min(1, time.delta * 9);+ for (const [_entity, transform] of hearts) {+ transform.scale.x += (1 - transform.scale.x) * k;+ transform.scale.y += (1 - transform.scale.y) * k;+ }+ },+ { name: 'HeartDecaySystem' }+);diff --git a/examples/timers-demo/tsconfig.json b/examples/timers-demo/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/timers-demo/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/examples/trail-demo/.gitignore b/examples/trail-demo/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/trail-demo/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/trail-demo/README.md b/examples/trail-demo/README.mdnew file mode 100644index 000000000..f3e0cec50--- /dev/null+++ b/examples/trail-demo/README.md@@ -0,0 +1,110 @@+# Trails++A tour of the engine's **built-in trail renderer** — the `TrailRenderer`+component records an entity's world-space path and draws it as a tapering,+fading ribbon, entirely engine-side. Three emitters run distinct configs side+by side:++- **Comet** — rides a Lissajous figure with a long additive streak+ (1.4 s lifetime, 26 px head tapering to 0, warm → transparent gradient).+- **Follower** — eases toward the mouse cursor with a slim cool ribbon — the+ classic cursor trail, using mostly default settings.+- **Dasher** — click anywhere and it dashes there in 0.14 s, leaving a wide,+ short-lived additive burst (44 px head, 0.25 s lifetime).++| Input | Action |+|---|---|+| **Mouse move** | The cyan follower chases the cursor. |+| **Click** | The dasher dashes to the cursor (wide burst trail). |+| **E** | Toggle the comet's `emitting` — the streak stops growing and fades out in place; pressing again resumes recording. |+| **C** | `trail.clear(entity)` on every trail — all streaks vanish instantly. |+| **T** | Teleport the dasher home **with** a `clear`, so no streak spans the jump. |++## What it shows++- **Zero per-frame trail code.** Systems only move the emitters; the built-in+ `TrailSystem` (part of the default plugin set) records a point whenever an+ entity with a `TrailRenderer` has moved farther than `minVertexDistance`,+ ages points out after `time` seconds, and the renderer extrudes the ribbon —+ width and color interpolate from head to tail by each point's age. A live+ head vertex glues the ribbon to the entity between recorded points, so the+ trail never lags visually.+- **Component-level control** — `emitting: false` stops recording new points;+ the existing streak keeps aging and fades out where it was left.+ (`enabled: false` is stronger: it hides the ribbon *and* pauses aging, so+ the history is kept and re-enabling resumes the same streak.)+- **Resource-level control** — the `Trail` resource (`Res(Trail)`) exposes+ `clear(entity)`, which drops the recorded history instantly. Pair it with+ any teleport so the ribbon doesn't draw a streak across the jump.+- Trails record in **play mode** (and the editor's FX preview), like particles+ and physics — press Play to see them.++## `TrailRenderer` component++```typescript+cmds.spawn()+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, { size: { x: 22, y: 22 } })+ .insert(TrailRenderer, {+ time: 1.4,+ startWidth: 26,+ endWidth: 0,+ startColor: { r: 1, g: 0.72, b: 0.3, a: 0.9 },+ endColor: { r: 1, g: 0.2, b: 0.1, a: 0 },+ blendMode: BlendMode.Additive,+ });+```++| Field | Type | Default | Meaning |+|---|---|---|---|+| `time` | number | `0.5` | Seconds each recorded point lives before it fades out of the tail. |+| `minVertexDistance` | number | `5` | Minimum world distance the entity must move before a new point is recorded. Smaller = smoother, denser ribbon. |+| `emitting` | boolean | `true` | Record new points. `false` = stop recording: the streak stops growing and its points age out (fade in place). |+| `startWidth` | number | `20` | Full ribbon width (world units) at the head — the newest point. |+| `endWidth` | number | `0` | Full ribbon width at the tail — the oldest point. Width lerps head→tail by point age. |+| `startColor` | Color | `{1, 1, 1, 1}` | Color at the head (newest point). |+| `endColor` | Color | `{1, 1, 1, 0}` | Color at the tail (oldest point) — usually alpha 0 so the trail fades out. Color lerps by age. |+| `texture` | texture handle | `0` | Optional texture (0 = solid white). U runs head (0) → tail (1) along the ribbon, V spans its width. |+| `blendMode` | number | `0` | `BlendMode`: 0 Normal, 1 Additive (glow), 2 Multiply, 3 Screen, 4 PremultipliedAlpha. |+| `layer` | number | `0` | Sorting layer — draw order against other renderables. |+| `material` | material handle | `0` | Optional material override (custom shader/blend); advanced. |+| `enabled` | boolean | `true` | Master toggle: hides the ribbon and pauses simulation (recording *and* aging). History is kept, so re-enabling resumes the same streak. |++## `Trail` resource (`TrailAPI`)++Declare `Res(Trail)` as a system param (or `app.getResource(Trail)` outside+ECS code):++| Method | Meaning |+|---|---|+| `clear(entity)` | Drop the entity's recorded history — the streak vanishes instantly. Use before/after teleports. |+| `update(dt)` | Advance every trail (record + age out). Driven automatically each frame by the built-in `TrailSystem`; call it yourself only in a hand-rolled headless setup. |++## Files++- `src/systems/setup.ts` — spawns the three emitters with their trail configs+ and a floating label per emitter.+- `src/systems/motion.ts` — Lissajous comet, cursor-chasing follower, and the+ ease-out dash flight. No trail code — moving the Transform is enough.+- `src/systems/control.ts` — click → dash; E toggles `emitting`; C/T use the+ `Trail` resource's `clear`.+- `src/systems/labels.ts` — keeps each label floating above its emitter.+- `src/components.ts` — `Comet`/`Follower` tags, `Dasher` dash state, `LabelOf`.+- `src/config.ts` — path shapes, dash timing, sizes.+- `assets/scenes/main.esscene` — camera, dark background, title + hint UI; the+ emitters are spawned from code.++## 中文摘要++本示例演示引擎**内置拖尾渲染器**:给实体挂 `TrailRenderer` 组件,引擎每帧+自动记录其世界坐标轨迹并渲染成由头到尾渐细、渐隐的条带——项目代码只负责移动+实体。三个发射器并排展示不同配置:++- **Comet**——沿利萨茹曲线飞行,长加法混合拖尾(1.4 秒寿命,26px 头部渐细到 0)。+- **Follower**——追随鼠标的细蓝拖尾(基本使用默认参数)。+- **Dasher**——点击任意位置冲刺过去,留下 0.25 秒即逝的宽爆发拖尾。++按 **E** 切换彗星的 `emitting`(停止记录:轨迹不再增长、原地淡出,再按恢复+记录);按 **C** 调用 `Trail` 资源的 `clear(entity)` 立即清空所有拖尾;按+**T** 把 Dasher 传送回家并同时 `clear`——传送配合 clear 是标准用法,避免瞬移+画出一条横跨屏幕的拖尾。各字段的类型与默认值见上方英文表格。diff --git a/examples/trail-demo/assets/scenes/main.esscene b/examples/trail-demo/assets/scenes/main.esscenenew file mode 100644index 000000000..1ef688fd6--- /dev/null+++ b/examples/trail-demo/assets/scenes/main.esscene@@ -0,0 +1,221 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 360,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Background",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Sprite",+ "data": {+ "size": {+ "x": 1400,+ "y": 820+ },+ "color": {+ "r": 0.04,+ "g": 0.04,+ "b": 0.07,+ "a": 1+ },+ "layer": 0+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Canvas",+ "parent": null,+ "children": [+ 3,+ 4+ ],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Canvas",+ "data": {+ "designResolution": {+ "x": 1280,+ "y": 720+ },+ "scaleMode": 2,+ "backgroundColor": {+ "r": 0,+ "g": 0,+ "b": 0,+ "a": 0+ }+ }+ },+ {+ "type": "UINode",+ "data": {}+ }+ ]+ },+ {+ "id": 3,+ "name": "Title",+ "parent": 2,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "width": {+ "value": 600,+ "unit": 0+ },+ "height": {+ "value": 52,+ "unit": 0+ },+ "insetLeft": {+ "value": 0,+ "unit": 1+ },+ "marginLeft": {+ "value": 340,+ "unit": 0+ },+ "insetTop": {+ "value": 0,+ "unit": 1+ },+ "marginTop": {+ "value": 26,+ "unit": 0+ }+ }+ },+ {+ "type": "Text",+ "data": {+ "content": "Trail Renderer",+ "fontSize": 34,+ "color": {+ "r": 0.95,+ "g": 0.95,+ "b": 1,+ "a": 1+ },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "Hint",+ "parent": 2,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "width": {+ "value": 900,+ "unit": 0+ },+ "height": {+ "value": 24,+ "unit": 0+ },+ "insetLeft": {+ "value": 0,+ "unit": 1+ },+ "marginLeft": {+ "value": 190,+ "unit": 0+ },+ "insetTop": {+ "value": 0,+ "unit": 1+ },+ "marginTop": {+ "value": 690,+ "unit": 0+ }+ }+ },+ {+ "type": "Text",+ "data": {+ "content": "Move the mouse (cyan chases it) | click: dash | E freeze comet | C clear trails | T teleport dasher home",+ "fontSize": 16,+ "color": {+ "r": 0.72,+ "g": 0.76,+ "b": 0.86,+ "a": 0.9+ },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ]+ }+ ]+}diff --git a/examples/trail-demo/assets/scenes/main.esscene.meta b/examples/trail-demo/assets/scenes/main.esscene.metanew file mode 100644index 000000000..b2a7b321a--- /dev/null+++ b/examples/trail-demo/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "e4d0c4eb-9a45-43d7-bc19-23c328f37515",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/trail-demo/project.esproject b/examples/trail-demo/project.esprojectnew file mode 100644index 000000000..550f002ec--- /dev/null+++ b/examples/trail-demo/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Trails",+ "description": "The built-in TrailRenderer: a Lissajous comet, a cursor-chasing streak, and a click-to-dash burst, plus runtime control through the Trail resource.",+ "tag": "Effects",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 1280,+ "height": 720+ },+ "spineVersion": "none"+}diff --git a/examples/trail-demo/src/components.ts b/examples/trail-demo/src/components.tsnew file mode 100644index 000000000..8fa01c492--- /dev/null+++ b/examples/trail-demo/src/components.ts@@ -0,0 +1,27 @@+import { defineComponent, defineTag } from 'esengine';++// The project's declaration entry (src/components.ts): user component/tag+// definitions only — no systems. (TrailRenderer is an engine built-in, so it+// isn't declared here.)++/** Marks the emitter riding the Lissajous figure. */+export const Comet = defineTag('Comet');++/** Marks the emitter that eases toward the mouse cursor. */+export const Follower = defineTag('Follower');++/** The click-to-dash emitter and its in-flight dash state. */+export const Dasher = defineComponent('Dasher', {+ fromX: 0,+ fromY: 0,+ toX: 0,+ toY: 0,+ t: 0,+ active: false,+});++/** Pins a floating world-space label to its emitter (`target` entity id). */+export const LabelOf = defineComponent('LabelOf', {+ target: -1,+ offsetY: 34,+});diff --git a/examples/trail-demo/src/config.ts b/examples/trail-demo/src/config.tsnew file mode 100644index 000000000..323d5109b--- /dev/null+++ b/examples/trail-demo/src/config.ts@@ -0,0 +1,22 @@+/** Lissajous figure the comet rides: center, radii, angular frequencies. */+export const COMET = {+ centerX: -330,+ centerY: 20,+ radiusX: 250,+ radiusY: 200,+ freqX: 3,+ freqY: 2,+ speed: 0.55,+};++/** Follower chase stiffness — larger closes the gap to the cursor faster. */+export const FOLLOW_STIFFNESS = 9;++export const DASHER_HOME = { x: 330, y: -140 };++/** One dash's flight time in seconds — short and fast so the burst reads. */+export const DASH_DURATION = 0.14;++export const COMET_SIZE = 22;+export const FOLLOWER_SIZE = 16;+export const DASHER_SIZE = 30;diff --git a/examples/trail-demo/src/main.ts b/examples/trail-demo/src/main.tsnew file mode 100644index 000000000..47f153fee--- /dev/null+++ b/examples/trail-demo/src/main.ts@@ -0,0 +1,27 @@+// Trails — a tour of the built-in trail renderer (the `TrailRenderer`+// component + the `Trail` resource):+//+// • Comet — rides a Lissajous figure with a long additive streak+// (time 1.4 s, 26 px head tapering to 0, warm→transparent gradient).+// • Follower — eases toward the mouse cursor with a short cool ribbon,+// the classic cursor-trail.+// • Dasher — click anywhere and it dashes there in 0.14 s, leaving a+// wide short-lived burst (44 px head, 0.25 s lifetime, additive).+//+// Trail points are recorded and aged by the engine's TrailSystem (TrailPlugin,+// play mode); project systems only move the emitters. The keys demonstrate+// runtime control: E flips `emitting` (freeze — the streak fades in place),+// C calls `trail.clear()` on every trail, T teleports the dasher home with a+// `clear` so no streak spans the jump.+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { setupSystem } from './systems/setup';+import { motionSystem } from './systems/motion';+import { controlSystem } from './systems/control';+import { labelSystem } from './systems/labels';++addStartupSystem(setupSystem);+addSystemToSchedule(Schedule.Update, motionSystem);+addSystemToSchedule(Schedule.Update, controlSystem);+addSystemToSchedule(Schedule.Update, labelSystem);diff --git a/examples/trail-demo/src/systems/control.ts b/examples/trail-demo/src/systems/control.tsnew file mode 100644index 000000000..bdc823c83--- /dev/null+++ b/examples/trail-demo/src/systems/control.ts@@ -0,0 +1,59 @@+import {+ defineSystem, Query, Mut, Res, Input, Transform, TrailRenderer, UICameraInfo,+ Trail,+} from 'esengine';+import type { TrailAPI, UICameraData } from 'esengine';+import { Comet, Dasher } from '../components';+import { DASHER_HOME } from '../config';++// Input → trail control. Two things happen here:+// • component-level control: flipping TrailRenderer.emitting on the comet+// stops recording — the streak stops growing and fades out where it was+// left (recorded points still age); pressing E again resumes recording;+// • resource-level control: the `Trail` resource's clear(entity) drops an+// entity's recorded points instantly. C clears every trail; T pairs a+// teleport with a clear so no streak spans the jump — the canonical use.+export const controlSystem = defineSystem(+ [+ Res(Input),+ Res(Trail),+ Res(UICameraInfo),+ Query(Mut(Transform), Mut(Dasher)),+ Query(Mut(TrailRenderer), Comet),+ Query(TrailRenderer),+ ],+ (input, trail: TrailAPI, camera: UICameraData, dashers, cometTrails, allTrails) => {+ if (camera.valid && input.isMouseButtonPressed(0)) {+ for (const [, transform, dash] of dashers) {+ dash.fromX = transform.position.x;+ dash.fromY = transform.position.y;+ dash.toX = camera.worldMouseX;+ dash.toY = camera.worldMouseY;+ dash.t = 0;+ dash.active = true;+ }+ }++ if (input.isKeyPressed('KeyE')) {+ for (const [, trailRenderer] of cometTrails) {+ trailRenderer.emitting = !trailRenderer.emitting;+ }+ }++ if (input.isKeyPressed('KeyC')) {+ for (const [entity] of allTrails) {+ trail.clear(entity);+ }+ }++ if (input.isKeyPressed('KeyT')) {+ for (const [entity, transform, dash] of dashers) {+ dash.active = false;+ transform.position.x = DASHER_HOME.x;+ transform.position.y = DASHER_HOME.y;+ trail.clear(entity);+ }+ }+ },+ { name: 'ControlSystem' },+);diff --git a/examples/trail-demo/src/systems/labels.ts b/examples/trail-demo/src/systems/labels.tsnew file mode 100644index 000000000..2ed5cd7f1--- /dev/null+++ b/examples/trail-demo/src/systems/labels.ts@@ -0,0 +1,19 @@+import { defineSystem, Query, Mut, GetWorld, Transform } from 'esengine';+import type { TransformData } from 'esengine';+import { LabelOf } from '../components';++// Keeps each floating label a fixed offset above its emitter. Labels are+// separate entities (not children) so they stay upright and unscaled no matter+// what the emitter does.+export const labelSystem = defineSystem(+ [Query(Mut(Transform), LabelOf), GetWorld()],+ (labels, world) => {+ for (const [, transform, label] of labels) {+ if (!world.valid(label.target)) continue;+ const target = world.get(label.target, Transform) as TransformData;+ transform.position.x = target.position.x;+ transform.position.y = target.position.y + label.offsetY;+ }+ },+ { name: 'LabelSystem' },+);diff --git a/examples/trail-demo/src/systems/motion.ts b/examples/trail-demo/src/systems/motion.tsnew file mode 100644index 000000000..bd2edd949--- /dev/null+++ b/examples/trail-demo/src/systems/motion.ts@@ -0,0 +1,50 @@+import {+ defineSystem, Query, Mut, Res, Time, Transform, UICameraInfo,+} from 'esengine';+import type { UICameraData } from 'esengine';+import { Comet, Follower, Dasher } from '../components';+import { COMET, FOLLOW_STIFFNESS, DASH_DURATION } from '../config';++// Moves all three emitters. The trails need no per-frame code: the engine+// records each entity's world position whenever it has moved farther than its+// TrailRenderer.minVertexDistance.+export const motionSystem = defineSystem(+ [+ Query(Mut(Transform), Comet),+ Query(Mut(Transform), Follower),+ Query(Mut(Transform), Mut(Dasher)),+ Res(Time),+ Res(UICameraInfo),+ ],+ (comets, followers, dashers, time, camera: UICameraData) => {+ // Comet: x/y run sinusoids at different frequencies (Lissajous), so the+ // path keeps crossing itself and the trail's fade-out is easy to read.+ const phase = time.elapsed * COMET.speed;+ for (const [, transform] of comets) {+ transform.position.x = COMET.centerX + COMET.radiusX * Math.sin(COMET.freqX * phase);+ transform.position.y = COMET.centerY + COMET.radiusY * Math.sin(COMET.freqY * phase + Math.PI / 2);+ }++ // Follower: frame-rate-independent exponential ease toward the cursor.+ if (camera.valid) {+ const blend = 1 - Math.exp(-FOLLOW_STIFFNESS * time.delta);+ for (const [, transform] of followers) {+ transform.position.x += (camera.worldMouseX - transform.position.x) * blend;+ transform.position.y += (camera.worldMouseY - transform.position.y) * blend;+ }+ }++ // Dasher: advance an in-flight dash with an ease-out cubic, so most of+ // the distance is covered in the first frames — that speed spike is what+ // stretches the wide burst trail.+ for (const [, transform, dash] of dashers) {+ if (!dash.active) continue;+ dash.t = Math.min(dash.t + time.delta / DASH_DURATION, 1);+ const ease = 1 - Math.pow(1 - dash.t, 3);+ transform.position.x = dash.fromX + (dash.toX - dash.fromX) * ease;+ transform.position.y = dash.fromY + (dash.toY - dash.fromY) * ease;+ if (dash.t >= 1) dash.active = false;+ }+ },+ { name: 'MotionSystem' },+);diff --git a/examples/trail-demo/src/systems/setup.ts b/examples/trail-demo/src/systems/setup.tsnew file mode 100644index 000000000..38234b834--- /dev/null+++ b/examples/trail-demo/src/systems/setup.ts@@ -0,0 +1,95 @@+import {+ defineSystem, Commands, Transform, Sprite, TrailRenderer, Text,+ TextAlign, TextVerticalAlign, BlendMode,+} from 'esengine';+import type { Entity } from 'esengine';+import { Comet, Follower, Dasher, LabelOf } from '../components';+import { COMET, DASHER_HOME, COMET_SIZE, FOLLOWER_SIZE, DASHER_SIZE } from '../config';++// Spawns the three emitters, each pairing a small sprite with a differently+// tuned TrailRenderer, plus a floating world-space label per emitter (kept over+// its target by labelSystem). Trail recording itself is entirely engine-side.+export const setupSystem = defineSystem(+ [Commands()],+ (cmds) => {+ const label = (target: Entity, content: string) => {+ cmds.spawn()+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Text, {+ content,+ fontSize: 15,+ color: { r: 0.75, g: 0.78, b: 0.88, a: 0.9 },+ align: TextAlign.Center,+ verticalAlign: TextVerticalAlign.Bottom,+ })+ .insert(LabelOf, { target });+ };++ // Long additive streak: generous lifetime, wide head tapering to zero,+ // warm head fading to a fully transparent ember red.+ const comet = cmds.spawn('Comet')+ .insert(Transform, { position: { x: COMET.centerX, y: COMET.centerY, z: 0 } })+ .insert(Sprite, {+ size: { x: COMET_SIZE, y: COMET_SIZE },+ color: { r: 1, g: 0.85, b: 0.55, a: 1 },+ layer: 3,+ })+ .insert(TrailRenderer, {+ time: 1.4,+ minVertexDistance: 4,+ startWidth: 26,+ endWidth: 0,+ startColor: { r: 1, g: 0.72, b: 0.3, a: 0.9 },+ endColor: { r: 1, g: 0.2, b: 0.1, a: 0 },+ blendMode: BlendMode.Additive,+ layer: 2,+ })+ .insert(Comet)+ .id();+ label(comet, 'Comet — Lissajous, long additive trail (E freezes it)');++ // Cursor trail: default lifetime/spacing, slim cool ribbon, normal blend.+ const follower = cmds.spawn('Follower')+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, {+ size: { x: FOLLOWER_SIZE, y: FOLLOWER_SIZE },+ color: { r: 0.55, g: 0.95, b: 1, a: 1 },+ layer: 3,+ })+ .insert(TrailRenderer, {+ startWidth: 14,+ endWidth: 2,+ startColor: { r: 0.45, g: 0.9, b: 1, a: 0.85 },+ endColor: { r: 0.15, g: 0.35, b: 1, a: 0 },+ layer: 2,+ })+ .insert(Follower)+ .id();+ label(follower, 'Follower — chases the cursor');++ // Dash burst: very short lifetime with a wide head, so the streak is a+ // bright slash that vanishes almost immediately. Dense spacing keeps the+ // ribbon smooth over the fast 0.14 s flight.+ const dasher = cmds.spawn('Dasher')+ .insert(Transform, { position: { x: DASHER_HOME.x, y: DASHER_HOME.y, z: 0 } })+ .insert(Sprite, {+ size: { x: DASHER_SIZE, y: DASHER_SIZE },+ color: { r: 0.85, g: 0.7, b: 1, a: 1 },+ layer: 3,+ })+ .insert(TrailRenderer, {+ time: 0.25,+ minVertexDistance: 2,+ startWidth: 44,+ endWidth: 6,+ startColor: { r: 1, g: 1, b: 1, a: 0.95 },+ endColor: { r: 0.6, g: 0.3, b: 1, a: 0 },+ blendMode: BlendMode.Additive,+ layer: 2,+ })+ .insert(Dasher)+ .id();+ label(dasher, 'Dasher — click to dash (T teleports home + clear)');+ },+ { name: 'SetupSystem' },+);diff --git a/examples/trail-demo/tsconfig.json b/examples/trail-demo/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/trail-demo/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}