Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(particle): add per-particle Trail module

yhh65721bd8a908
diff --git a/desktop/public/scenes/particle-trail.esscene b/desktop/public/scenes/particle-trail.esscene
new file mode 100644
index 000000000..07a1b6534
--- /dev/null
+++ b/desktop/public/scenes/particle-trail.esscene
@@ -0,0 +1,53 @@
+{
+ "version": "1.0",
+ "name": "ParticleTrail",
+ "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": "Comets",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ { "type": "ParticleEmitter", "data": {
+ "rate": 60,
+ "maxParticles": 120,
+ "lifetimeMin": 1.2,
+ "lifetimeMax": 1.6,
+ "shape": 0,
+ "speedMin": 260,
+ "speedMax": 320,
+ "angleSpreadMin": 0,
+ "angleSpreadMax": 360,
+ "startSizeMin": 10,
+ "startSizeMax": 12,
+ "endSizeMin": 3,
+ "endSizeMax": 4,
+ "sizeEasing": 2,
+ "startColor": { "r": 0.6, "g": 0.9, "b": 1, "a": 1 },
+ "endColor": { "r": 0.4, "g": 0.3, "b": 1, "a": 0 },
+ "simulationSpace": 0,
+ "looping": true,
+ "playOnStart": true,
+ "trailEnabled": true,
+ "trailWidth": 14,
+ "trailPoints": 8,
+ "trailMinDistance": 4,
+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0"
+ }}
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/particle-trail.textures.json b/desktop/public/scenes/particle-trail.textures.json
new file mode 100644
index 000000000..0acb647eb
--- /dev/null
+++ b/desktop/public/scenes/particle-trail.textures.json
@@ -0,0 +1,3 @@
+{
+ "24cb4e0f-7c75-4df4-9a4d-58480ee405c0": "/scenes/particle-demo/textures/particle.png"
+}
diff --git a/docs/astro/src/content/docs/guides/particle.mdx b/docs/astro/src/content/docs/guides/particle.mdx
index 20fac03e4..ea8f7bbaa 100644
--- a/docs/astro/src/content/docs/guides/particle.mdx
+++ b/docs/astro/src/content/docs/guides/particle.mdx
@@ -195,6 +195,17 @@ See [Noise & turbulence](#noise--turbulence-1) below.
See [Sub-emitters](#sub-emitters) below.
+### Trail
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `trailEnabled` | boolean | `false` | Drag a tapering ribbon behind each particle. Off = no history recorded. |
+| `trailWidth` | number | `8` | Ribbon width at the head; tapers to a point at the tail. |
+| `trailPoints` | number | `6` | History length in points (2..12) — longer = smoother, costlier streaks. |
+| `trailMinDistance` | number | `6` | Min world distance a particle must move before a new trail point is recorded. |
+
+See [Per-particle trails](#per-particle-trails) below.
+
## Emitter shapes
`EmitterShape` sets the spawn region and initial direction:
@@ -339,6 +350,35 @@ cmds.spawn()
In the editor, `subEmitter` is an entity picker — drop in any emitter entity from
the scene; the reference is remapped automatically when the scene loads.
+## Per-particle trails
+
+Turn on `trailEnabled` and every particle drags a tapering ribbon along its recent
+path — comet sparks, tracer rounds, swirling magic streaks. This is *distinct* from
+the standalone [`TrailRenderer`](/guides/trail/), which trails a single entity; here
+each of the (up to thousands of) particles gets its own streak.
+
+```typescript
+.insert(ParticleEmitter, {
+ rate: 40, speedMin: 220, speedMax: 420, lifetimeMin: 0.7, lifetimeMax: 1.2,
+ startColor: { r: 0.6, g: 0.9, b: 1, a: 1 }, endColor: { r: 0.2, g: 0.4, b: 1, a: 0 },
+ trailEnabled: true,
+ trailWidth: 10, // ribbon width at the particle, tapering to a point behind
+ trailPoints: 8, // how many path points to keep (2..12)
+ trailMinDistance: 5, // record a point every 5 world units of movement
+});
+```
+
+The ribbon takes the particle's **current colour** at the head and fades to
+transparent along its length, so trails inherit your colour-over-life automatically.
+It's built on the CPU and streamed through the same triangle-strip batch path as
+`TrailRenderer` — no special GPU path — so it sorts and blends like every other 2D
+renderable.
+
+Trails are opt-in because they cost more than plain particles: a short position
+history per particle (bounded by `trailPoints`) plus ribbon geometry each frame. Keep
+`trailPoints` modest (`6`–`8` is plenty) and lower `maxParticles` for heavy trailed
+effects.
+
## Simulation space
| Value | Particles follow the emitter? | Use for |
diff --git a/docs/astro/src/content/docs/zh-cn/guides/particle.mdx b/docs/astro/src/content/docs/zh-cn/guides/particle.mdx
index f67dd884b..f31025ecf 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/particle.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/particle.mdx
@@ -186,6 +186,17 @@ const spawnEmbers = defineSystem([Commands()], (cmds) => {
见下文[子发射器](#子发射器-1)。
+### 拖尾 (Trail)
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `trailEnabled` | boolean | `false` | 每个粒子拖一条渐细的 ribbon。关 = 不记录历史。 |
+| `trailWidth` | number | `8` | ribbon 头部宽度;向尾部收细到一点。 |
+| `trailPoints` | number | `6` | 历史点数(2..12)—— 越长越平滑但越贵。 |
+| `trailMinDistance` | number | `6` | 记录新拖尾点前粒子须移动的最小世界距离。 |
+
+见下文[逐粒子拖尾](#逐粒子拖尾)。
+
## 发射器形状
`EmitterShape` 设定生成区域与初始方向:
@@ -316,6 +327,30 @@ cmds.spawn()
在编辑器里,`subEmitter` 是一个实体选择器 —— 拖入场景中任意发射器实体即可;引用会在
场景加载时自动重映射。
+## 逐粒子拖尾
+
+打开 `trailEnabled`,每个粒子都会沿最近的运动轨迹拖出一条渐细的 ribbon —— 彗星火花、
+曳光弹、旋绕的魔法尾迹。这和独立的 [`TrailRenderer`](/zh-cn/guides/trail/) *不同*:后者
+给单个实体拖尾,而这里(可达数千个)每个粒子都有自己的尾迹。
+
+```typescript
+.insert(ParticleEmitter, {
+ rate: 40, speedMin: 220, speedMax: 420, lifetimeMin: 0.7, lifetimeMax: 1.2,
+ startColor: { r: 0.6, g: 0.9, b: 1, a: 1 }, endColor: { r: 0.2, g: 0.4, b: 1, a: 0 },
+ trailEnabled: true,
+ trailWidth: 10, // 粒子处的 ribbon 宽度,向后收细到一点
+ trailPoints: 8, // 保留多少轨迹点(2..12)
+ trailMinDistance: 5, // 每移动 5 个世界单位记录一个点
+});
+```
+
+ribbon 头部取粒子**当前颜色**,沿长度渐隐到透明,所以拖尾自动继承你的随生命颜色。它在
+CPU 上生成,走和 `TrailRenderer` 相同的三角带 batch 路径 —— 无特殊 GPU 路径 —— 因此
+和其他 2D 可渲染物一样排序混合。
+
+拖尾是可选项,因为它比普通粒子贵:每粒子一小段位置历史(受 `trailPoints` 限制)+ 每帧
+ribbon 几何。`trailPoints` 保持适中(`6`–`8` 足够),重拖尾特效请调低 `maxParticles`。
+
## 模拟空间
| 取值 | 粒子跟随发射器吗? | 用于 |
diff --git a/examples/particle-demo/README.md b/examples/particle-demo/README.md
index 634821f5c..71fc8b2af 100644
--- a/examples/particle-demo/README.md
+++ b/examples/particle-demo/README.md
@@ -1,6 +1,6 @@
# Particle Effects
-A gallery of the engine's `ParticleEmitter`. Page through eight composed effects
+A gallery of the engine's `ParticleEmitter`. Page through nine composed effects
with on-screen buttons, and click empty space to throw fireworks.
## Controls
@@ -18,8 +18,9 @@ with on-screen buttons, and click empty space to throw fireworks.
`Snowfall` (a wide, slow drift) · `Sparkles` (a twinkling field) ·
`Bursting Rockets` (**sub-emitter** — rockets that explode into a shell burst on
death) · `Turbulent Smoke` (curl-**noise** flow — smoke that rolls, embers that
-weave). Each mixes shape, velocity, colour/size-over-life, gravity, spin, blend
-mode, and now noise and sub-emitters — see `src/config.ts`.
+weave) · `Comet Trails` (per-particle **trail** — sparks that drag fading ribbons).
+Each mixes shape, velocity, colour/size-over-life, gravity, spin, blend mode, and
+now noise, sub-emitters and trails — see `src/config.ts`.
## How it works
@@ -54,7 +55,7 @@ assets/
textures/particle.png # soft radial particle sprite
src/
main.ts # registers the systems
- config.ts # the eight showcases, the firework, spawnShowcase()
+ config.ts # the nine showcases, the firework, spawnShowcase()
components.ts # tags (buttons, TexHolder, ShowcaseEmitter) + Burst
state.ts # the current showcase index
systems/
diff --git a/examples/particle-demo/src/config.ts b/examples/particle-demo/src/config.ts
index c1381e2c8..f694d7d76 100644
--- a/examples/particle-demo/src/config.ts
+++ b/examples/particle-demo/src/config.ts
@@ -166,6 +166,21 @@ export const SHOWCASES: Showcase[] = [
noiseStrength: 220, noiseFrequency: 0.012, noiseScrollSpeed: 0.6, noiseOctaves: 3 } },
],
},
+ {
+ // Shows off the per-particle Trail module: each spark drags a fading comet
+ // ribbon along its arc — the streak inherits the particle's colour.
+ name: 'Comet Trails',
+ emitters: [
+ { x: 0, y: -40, data: {
+ rate: 44, maxParticles: 130, lifetimeMin: 0.9, lifetimeMax: 1.5,
+ shape: EmitterShape.Circle, shapeRadius: 8, speedMin: 240, speedMax: 470,
+ startSizeMin: 8, startSizeMax: 12, endSizeMin: 2, endSizeMax: 4,
+ sizeEasing: ParticleEasing.EaseOut,
+ startColor: { r: 0.6, g: 0.9, b: 1, a: 1 }, endColor: { r: 0.5, g: 0.3, b: 1, a: 0 },
+ gravity: { x: 0, y: -150 },
+ trailEnabled: true, trailWidth: 12, trailPoints: 8, trailMinDistance: 5 } },
+ ],
+ },
];
export const SHOWCASE_COUNT = SHOWCASES.length;
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index f40cebfdb..422152fa5 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -15,7 +15,7 @@ import type { Dimension, Padding } from './wasm.generated';
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '5577bd3e60fc7bd7';
+export const ABI_LAYOUT_HASH = '12610f4b7cc99ebc';
export interface AssetFieldMeta {
field: string;
@@ -341,6 +341,10 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
subEmitterChance: 1,
subEmitterInheritVelocity: 0,
subEmitter: 0,
+ trailEnabled: false,
+ trailWidth: 8,
+ trailPoints: 6,
+ trailMinDistance: 6,
},
assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }],
entityFields: ['subEmitter'],
@@ -395,6 +399,10 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
subEmitterChance: { min: 0, max: 1, category: "SubEmitter" },
subEmitterInheritVelocity: { min: 0, max: 1, category: "SubEmitter" },
subEmitter: { category: "SubEmitter" },
+ trailEnabled: { category: "Trail" },
+ trailWidth: { min: 0, category: "Trail" },
+ trailPoints: { min: 2, max: 12, step: 1, category: "Trail" },
+ trailMinDistance: { min: 0, category: "Trail" },
},
},
RigidBody: {
@@ -886,6 +894,10 @@ export interface ParticleEmitterData {
subEmitterChance: number;
subEmitterInheritVelocity: number;
subEmitter: Entity;
+ trailEnabled: boolean;
+ trailWidth: number;
+ trailPoints: number;
+ trailMinDistance: number;
}
export interface RigidBodyData {
diff --git a/sdk/src/ecs/ptrAccessors.generated.ts b/sdk/src/ecs/ptrAccessors.generated.ts
index 6ba63da86..ded20d8f0 100644
--- a/sdk/src/ecs/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/ptrAccessors.generated.ts
@@ -571,6 +571,10 @@ export interface ParticleEmitterPtrData {
subEmitterChance: number;
subEmitterInheritVelocity: number;
subEmitter: number;
+ trailEnabled: boolean;
+ trailWidth: number;
+ trailPoints: number;
+ trailMinDistance: number;
}
export function fillParticleEmitter(
@@ -626,6 +630,10 @@ export function fillParticleEmitter(
out.subEmitterChance = f32[(ptr + 212) >> 2];
out.subEmitterInheritVelocity = f32[(ptr + 216) >> 2];
out.subEmitter = u32[(ptr + 220) >> 2];
+ out.trailEnabled = u8[ptr + 224] !== 0;
+ out.trailWidth = f32[(ptr + 228) >> 2];
+ out.trailPoints = u32[(ptr + 232) >> 2] | 0;
+ out.trailMinDistance = f32[(ptr + 236) >> 2];
}
export function writeParticleEmitter(
@@ -681,6 +689,10 @@ export function writeParticleEmitter(
f32[(ptr + 212) >> 2] = data.subEmitterChance;
f32[(ptr + 216) >> 2] = data.subEmitterInheritVelocity;
u32[(ptr + 220) >> 2] = data.subEmitter;
+ u8[ptr + 224] = data.trailEnabled ? 1 : 0;
+ f32[(ptr + 228) >> 2] = data.trailWidth;
+ u32[(ptr + 232) >> 2] = data.trailPoints | 0;
+ f32[(ptr + 236) >> 2] = data.trailMinDistance;
}
export function createParticleEmitterData(): ParticleEmitterPtrData {
@@ -734,6 +746,10 @@ export function createParticleEmitterData(): ParticleEmitterPtrData {
subEmitterChance: 0,
subEmitterInheritVelocity: 0,
subEmitter: 0,
+ trailEnabled: false,
+ trailWidth: 0,
+ trailPoints: 0,
+ trailMinDistance: 0,
};
}
diff --git a/sdk/src/ptrLayouts.generated.ts b/sdk/src/ptrLayouts.generated.ts
index 0738d5b32..c4a39235a 100644
--- a/sdk/src/ptrLayouts.generated.ts
+++ b/sdk/src/ptrLayouts.generated.ts
@@ -198,6 +198,10 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'subEmitterChance', type: 'f32', offset: 212 },
{ name: 'subEmitterInheritVelocity', type: 'f32', offset: 216 },
{ name: 'subEmitter', type: 'u32', offset: 220 },
+ { name: 'trailEnabled', type: 'bool', offset: 224 },
+ { name: 'trailWidth', type: 'f32', offset: 228 },
+ { name: 'trailPoints', type: 'i32', offset: 232 },
+ { name: 'trailMinDistance', type: 'f32', offset: 236 },
],
},
RigidBody: {
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index 268df4a6e..700fe69fe 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -363,6 +363,10 @@ export interface ParticleEmitter {
subEmitterChance: number;
subEmitterInheritVelocity: number;
subEmitter: number;
+ trailEnabled: boolean;
+ trailWidth: number;
+ trailPoints: number;
+ trailMinDistance: number;
}
export interface RigidBody {
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 6e4fd01be..dee50f499 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -487,6 +487,23 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"texture": {
"category": "Texture",
},
+ "trailEnabled": {
+ "category": "Trail",
+ },
+ "trailMinDistance": {
+ "category": "Trail",
+ "min": 0,
+ },
+ "trailPoints": {
+ "category": "Trail",
+ "max": 12,
+ "min": 2,
+ "step": 1,
+ },
+ "trailWidth": {
+ "category": "Trail",
+ "min": 0,
+ },
},
"ShadowCaster2D": {
"size": {
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 9c4e203bb..87e5562b4 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash c17d68a2673d20af
+ * @schema_hash 368b777854ab416e
*/
-#define ES_EDITOR_API_SCHEMA_HASH "c17d68a2673d20af"
+#define ES_EDITOR_API_SCHEMA_HASH "368b777854ab416e"
#include <emscripten/bind.h>
#include <string>
@@ -289,7 +289,11 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"subEmitterTrigger","type":"int","group":"ParticleEmitter"},
{"key":"subEmitterChance","type":"float","group":"ParticleEmitter"},
{"key":"subEmitterInheritVelocity","type":"float","group":"ParticleEmitter"},
- {"key":"subEmitter","type":"entity","group":"ParticleEmitter"}
+ {"key":"subEmitter","type":"entity","group":"ParticleEmitter"},
+ {"key":"trailEnabled","type":"bool","group":"ParticleEmitter"},
+ {"key":"trailWidth","type":"float","group":"ParticleEmitter"},
+ {"key":"trailPoints","type":"int","group":"ParticleEmitter"},
+ {"key":"trailMinDistance","type":"float","group":"ParticleEmitter"}
])JSON";
} else if (name == "RigidBody") {
return R"JSON([
@@ -905,6 +909,8 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "spriteFPS") { c.spriteFPS = value; }
else if (field == "subEmitterChance") { c.subEmitterChance = value; }
else if (field == "subEmitterInheritVelocity") { c.subEmitterInheritVelocity = value; }
+ else if (field == "trailWidth") { c.trailWidth = value; }
+ else if (field == "trailMinDistance") { c.trailMinDistance = value; }
else { return false; }
return true;
} else if (comp == "RigidBody") {
@@ -1254,6 +1260,8 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "spriteFPS") { return c.spriteFPS; }
else if (field == "subEmitterChance") { return c.subEmitterChance; }
else if (field == "subEmitterInheritVelocity") { return c.subEmitterInheritVelocity; }
+ else if (field == "trailWidth") { return c.trailWidth; }
+ else if (field == "trailMinDistance") { return c.trailMinDistance; }
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1521,6 +1529,7 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "simulationSpace") { c.simulationSpace = static_cast<i32>(value); }
else if (field == "subEmitterTrigger") { c.subEmitterTrigger = static_cast<i32>(value); }
else if (field == "subEmitter") { c.subEmitter = static_cast<u32>(value); }
+ else if (field == "trailPoints") { c.trailPoints = static_cast<i32>(value); }
else { return false; }
return true;
} else if (comp == "RigidBody") {
@@ -1683,6 +1692,7 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
else if (field == "simulationSpace") { return static_cast<i32>(c.simulationSpace); }
else if (field == "subEmitterTrigger") { return static_cast<i32>(c.subEmitterTrigger); }
else if (field == "subEmitter") { return static_cast<i32>(c.subEmitter); }
+ else if (field == "trailPoints") { return static_cast<i32>(c.trailPoints); }
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1814,6 +1824,7 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "playOnStart") { c.playOnStart = value; }
else if (field == "spriteLoop") { c.spriteLoop = value; }
else if (field == "enabled") { c.enabled = value; }
+ else if (field == "trailEnabled") { c.trailEnabled = value; }
else { return false; }
return true;
} else if (comp == "RigidBody") {
@@ -1951,6 +1962,7 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "playOnStart") { return c.playOnStart; }
else if (field == "spriteLoop") { return c.spriteLoop; }
else if (field == "enabled") { return c.enabled; }
+ else if (field == "trailEnabled") { return c.trailEnabled; }
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return false;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 88b948bbd..52c3ecc02 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -501,6 +501,10 @@ struct ParticleEmitterJS {
f32 subEmitterChance;
f32 subEmitterInheritVelocity;
u32 subEmitter;
+ bool trailEnabled;
+ f32 trailWidth;
+ i32 trailPoints;
+ f32 trailMinDistance;
};
esengine::ecs::ParticleEmitter particleemitterFromJS(const ParticleEmitterJS& js) {
@@ -554,6 +558,10 @@ esengine::ecs::ParticleEmitter particleemitterFromJS(const ParticleEmitterJS& js
c.subEmitterChance = js.subEmitterChance;
c.subEmitterInheritVelocity = js.subEmitterInheritVelocity;
c.subEmitter = js.subEmitter;
+ c.trailEnabled = js.trailEnabled;
+ c.trailWidth = js.trailWidth;
+ c.trailPoints = js.trailPoints;
+ c.trailMinDistance = js.trailMinDistance;
return c;
}
@@ -608,6 +616,10 @@ ParticleEmitterJS particleemitterToJS(const esengine::ecs::ParticleEmitter& c) {
js.subEmitterChance = c.subEmitterChance;
js.subEmitterInheritVelocity = c.subEmitterInheritVelocity;
js.subEmitter = c.subEmitter;
+ js.trailEnabled = c.trailEnabled;
+ js.trailWidth = c.trailWidth;
+ js.trailPoints = c.trailPoints;
+ js.trailMinDistance = c.trailMinDistance;
return js;
}
@@ -1106,7 +1118,11 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("subEmitterTrigger", &ParticleEmitterJS::subEmitterTrigger)
.field("subEmitterChance", &ParticleEmitterJS::subEmitterChance)
.field("subEmitterInheritVelocity", &ParticleEmitterJS::subEmitterInheritVelocity)
- .field("subEmitter", &ParticleEmitterJS::subEmitter);
+ .field("subEmitter", &ParticleEmitterJS::subEmitter)
+ .field("trailEnabled", &ParticleEmitterJS::trailEnabled)
+ .field("trailWidth", &ParticleEmitterJS::trailWidth)
+ .field("trailPoints", &ParticleEmitterJS::trailPoints)
+ .field("trailMinDistance", &ParticleEmitterJS::trailMinDistance);
value_object<RigidBodyJS>("RigidBody")
.field("bodyType", &RigidBodyJS::bodyType)
@@ -2020,6 +2036,10 @@ static_assert(offsetof(esengine::ecs::ParticleEmitter, subEmitterTrigger) == 208
static_assert(offsetof(esengine::ecs::ParticleEmitter, subEmitterChance) == 212, "ABI offset drift: esengine::ecs::ParticleEmitter.subEmitterChance (EHT expected 212)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, subEmitterInheritVelocity) == 216, "ABI offset drift: esengine::ecs::ParticleEmitter.subEmitterInheritVelocity (EHT expected 216)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, subEmitter) == 220, "ABI offset drift: esengine::ecs::ParticleEmitter.subEmitter (EHT expected 220)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, trailEnabled) == 224, "ABI offset drift: esengine::ecs::ParticleEmitter.trailEnabled (EHT expected 224)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, trailWidth) == 228, "ABI offset drift: esengine::ecs::ParticleEmitter.trailWidth (EHT expected 228)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, trailPoints) == 232, "ABI offset drift: esengine::ecs::ParticleEmitter.trailPoints (EHT expected 232)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, trailMinDistance) == 236, "ABI offset drift: esengine::ecs::ParticleEmitter.trailMinDistance (EHT expected 236)");
static_assert(offsetof(esengine::ecs::RigidBody, bodyType) == 0, "ABI offset drift: esengine::ecs::RigidBody.bodyType (EHT expected 0)");
static_assert(offsetof(esengine::ecs::RigidBody, gravityScale) == 4, "ABI offset drift: esengine::ecs::RigidBody.gravityScale (EHT expected 4)");
static_assert(offsetof(esengine::ecs::RigidBody, linearDamping) == 8, "ABI offset drift: esengine::ecs::RigidBody.linearDamping (EHT expected 8)");
@@ -2133,7 +2153,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "5577bd3e60fc7bd7";
+static const char* kEsAbiLayoutHash = "12610f4b7cc99ebc";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/ParticleEmitter.hpp b/src/esengine/ecs/components/ParticleEmitter.hpp
index 20f2f9403..485fbef32 100644
--- a/src/esengine/ecs/components/ParticleEmitter.hpp
+++ b/src/esengine/ecs/components/ParticleEmitter.hpp
@@ -217,6 +217,23 @@ struct ParticleEmitter {
ES_PROPERTY(entity_ref, category=SubEmitter)
u32 subEmitter{0};
+ // Per-particle trail — each particle drags a tapering ribbon along its recent
+ // path (comet tails, sparks, magic streaks). The ribbon reuses the same
+ // triangle-strip batch path as the standalone TrailRenderer; its head takes the
+ // particle's current colour and `trailWidth`, fading to a transparent point at
+ // the tail. Off by default (no history is recorded when disabled).
+ ES_PROPERTY(category=Trail)
+ bool trailEnabled{false};
+
+ ES_PROPERTY(min=0, category=Trail)
+ f32 trailWidth{8.0f};
+
+ ES_PROPERTY(min=2, max=12, step=1, category=Trail)
+ i32 trailPoints{6};
+
+ ES_PROPERTY(min=0, category=Trail)
+ f32 trailMinDistance{6.0f};
+
ParticleEmitter() = default;
};
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index 65984a2aa..56ebc174b 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -56,6 +56,15 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
auto& state = it->second;
+ // Size the per-particle trail history the first time this emitter uses
+ // trails (kept free when they're off). Sized before emission so a spawn
+ // this frame can reset its slot.
+ if (emitter.trailEnabled && state.trail_count.size() != state.pool.capacity()) {
+ state.trail_count.assign(state.pool.capacity(), 0);
+ state.trail_pos.assign(static_cast<std::size_t>(state.pool.capacity()) * kMaxTrailPoints,
+ glm::vec2(0.0f));
+ }
+
if (state.first_update && emitter.playOnStart) {
state.playing = true;
state.first_update = false;
@@ -236,6 +245,13 @@ void ParticleSystem::emitInto(const ecs::ParticleEmitter& emitter, EmitterState&
break;
}
+ // A reused pool slot must start with an empty trail, not the dead
+ // particle's history.
+ if (emitter.trailEnabled && !state.trail_count.empty()) {
+ auto idx = static_cast<std::size_t>(p - state.pool.particles().data());
+ if (idx < state.trail_count.size()) state.trail_count[idx] = 0;
+ }
+
p->lifetime = randomRange(emitter.lifetimeMin, emitter.lifetimeMax);
p->age = 0.0f;
@@ -384,6 +400,10 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
glm::vec2 noiseScroll(emitter.noiseScrollSpeed * state.noise_time *
emitter.noiseFrequency);
+ bool trailOn = emitter.trailEnabled && !state.trail_count.empty();
+ int trailKeep = std::clamp(emitter.trailPoints, 2, kMaxTrailPoints);
+ f32 trailMinDistSq = emitter.trailMinDistance * emitter.trailMinDistance;
+
dead_particle_indices_.clear();
state.pool.forEachAlive([&](Particle& p) {
@@ -415,6 +435,27 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
emitter.noiseStrength * dt;
}
+ // Record the settled position into this particle's trail ring (oldest→newest),
+ // gated by trailMinDistance so a slow particle doesn't pile up coincident points.
+ if (trailOn) {
+ auto idx = static_cast<std::size_t>(&p - state.pool.particles().data());
+ u8& cnt = state.trail_count[idx];
+ glm::vec2* ring = &state.trail_pos[idx * kMaxTrailPoints];
+ bool record = cnt == 0;
+ if (!record) {
+ glm::vec2 d = p.position - ring[cnt - 1];
+ record = glm::dot(d, d) >= trailMinDistSq;
+ }
+ if (record) {
+ if (cnt < trailKeep) {
+ ring[cnt++] = p.position;
+ } else {
+ for (int k = 1; k < trailKeep; ++k) ring[k - 1] = ring[k];
+ ring[trailKeep - 1] = p.position;
+ }
+ }
+ }
+
p.rotation += p.angular_velocity * dt;
if (sizeLut) {
diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hpp
index be94b236a..3db31821f 100644
--- a/src/esengine/particle/ParticleSystem.hpp
+++ b/src/esengine/particle/ParticleSystem.hpp
@@ -25,6 +25,11 @@ using ColorLut = std::array<glm::vec4, kColorLutSize>;
// Size-over-life: a scalar multiplier curve × the particle's start size.
using SizeLut = std::array<f32, kColorLutSize>;
+// Hard cap on a per-particle trail's recorded points (the ribbon has one segment
+// less). Bounds the per-emitter history buffer; the component's trailPoints picks
+// how many of these to actually keep.
+inline constexpr int kMaxTrailPoints = 12;
+
struct EmitterState {
ParticlePool pool;
f32 emission_accumulator = 0.0f;
@@ -36,6 +41,13 @@ struct EmitterState {
bool playing = false;
bool first_update = true;
+ // Per-particle trail history, keyed by pool index and only sized once an emitter
+ // enables trails (free otherwise). trail_pos is a flat [capacity × kMaxTrailPoints]
+ // ring of raw particle-space positions (oldest→newest); trail_count is how many
+ // slots each particle has filled.
+ std::vector<glm::vec2> trail_pos;
+ std::vector<u8> trail_count;
+
explicit EmitterState(u32 capacity) : pool(capacity) {}
};
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cpp
index a617c7d4b..704aec833 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp
@@ -14,6 +14,7 @@
#include "../../particle/ParticleSystem.hpp"
#include "../../particle/Particle.hpp"
+#include <algorithm>
#include <cmath>
namespace esengine {
@@ -162,6 +163,86 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
// The stream's static unit-quad indices (offset 0) drawn once per particle,
// with the instance slice based at instByteOffset.
pushBatchDraw(draw_list, clips, instByteOffset, 0, 0, 6, key);
+
+ // --- Per-particle trails --------------------------------------------------
+ // Each live particle drags a tapering ribbon along its recorded path. Built on
+ // the CPU and streamed through the Batch face (triangle strip), exactly like the
+ // standalone TrailRenderer — no new GPU path. Off unless the emitter opts in.
+ if (emitter.trailEnabled && emitter.trailWidth > 0.0f &&
+ state->trail_count.size() == state->pool.particles().size()) {
+ BatchDrawKey trailKey{
+ .stage = ctx.current_stage,
+ .layer = emitter.layer,
+ .shaderId = ctx.batch_shader_id,
+ .blend = blendMode,
+ .textureId = ctx.white_texture_id,
+ .depth = emitterWorldPos.z,
+ .y = emitterWorldPos.y,
+ .entity = entity,
+ .type = RenderType::Trail,
+ };
+ const int keep = std::min(std::max(emitter.trailPoints, 2), particle::kMaxTrailPoints);
+ const auto& particles = state->pool.particles();
+ auto toWorld = [&](glm::vec2 pos) -> glm::vec2 {
+ if (!isLocalSpace) return pos;
+ glm::vec2 rel = pos * emitterScale;
+ if (std::abs(emitterAngle) > 0.001f)
+ return glm::vec2(emitterWorldPos) +
+ glm::vec2(rel.x * cosA - rel.y * sinA, rel.x * sinA + rel.y * cosA);
+ return glm::vec2(emitterWorldPos) + rel;
+ };
+
+ for (std::size_t idx = 0; idx < particles.size(); ++idx) {
+ const particle::Particle& p = particles[idx];
+ if (!p.alive || state->trail_count[idx] == 0) continue;
+ const glm::vec2* ring = &state->trail_pos[idx * particle::kMaxTrailPoints];
+
+ // Centerline: recorded points (oldest→newest) then the live head.
+ trail_center_.clear();
+ int m = std::min<int>(state->trail_count[idx], keep);
+ for (int k = 0; k < m; ++k) trail_center_.push_back(toWorld(ring[k]));
+ glm::vec2 head = toWorld(p.position);
+ glm::vec2 dHead = head - trail_center_.back();
+ if (glm::dot(dHead, dHead) > 1e-4f) trail_center_.push_back(head);
+ const int n = static_cast<int>(trail_center_.size());
+ if (n < 2) continue;
+
+ // 2 verts per point: t runs 0 at the faded zero-width tail (oldest) → 1
+ // at the full-width head carrying the particle's current colour.
+ trail_verts_.clear();
+ glm::vec2 lastTangent(1.0f, 0.0f);
+ for (int j = 0; j < n; ++j) {
+ const glm::vec2& a = trail_center_[j == 0 ? 0 : j - 1];
+ const glm::vec2& b = trail_center_[j + 1 == n ? j : j + 1];
+ glm::vec2 seg = b - a;
+ f32 len = std::sqrt(seg.x * seg.x + seg.y * seg.y);
+ glm::vec2 tangent = len > 1e-6f ? seg / len : lastTangent;
+ lastTangent = tangent;
+ glm::vec2 perp(-tangent.y, tangent.x);
+
+ f32 t = static_cast<f32>(j) / static_cast<f32>(n - 1);
+ f32 halfW = 0.5f * emitter.trailWidth * t;
+ glm::vec4 col = p.color;
+ col.a *= t;
+ u32 packed = packColor(col);
+
+ trail_verts_.push_back({trail_center_[j] + perp * halfW, packed, glm::vec2(1.0f - t, 0.0f)});
+ trail_verts_.push_back({trail_center_[j] - perp * halfW, packed, glm::vec2(1.0f - t, 1.0f)});
+ }
+
+ trail_indices_.clear();
+ for (int j = 0; j + 1 < n; ++j) {
+ u32 l0 = static_cast<u32>(j) * 2, r0 = l0 + 1, l1 = l0 + 2, r1 = l0 + 3;
+ trail_indices_.push_back(l0); trail_indices_.push_back(r0); trail_indices_.push_back(r1);
+ trail_indices_.push_back(l0); trail_indices_.push_back(r1); trail_indices_.push_back(l1);
+ }
+
+ appendIndexedBatch(buffers, draw_list, clips,
+ trail_verts_.data(), static_cast<u32>(trail_verts_.size()),
+ trail_indices_.data(), static_cast<u32>(trail_indices_.size()),
+ trailKey);
+ }
+ }
}
}
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.hpp b/src/esengine/renderer/plugins/ParticlePlugin.hpp
index 1f1debe16..5f36b1226 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.hpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.hpp
@@ -3,6 +3,9 @@
#pragma once
#include "../RenderTypePlugin.hpp"
+#include "../BatchVertex.hpp"
+
+#include <vector>
namespace esengine {
@@ -22,6 +25,11 @@ public:
private:
particle::ParticleSystem* particle_system_ = nullptr;
u32 particle_shader_id_ = 0; // PARTICLE_INSTANCE program (GPU instancing)
+
+ // Reused per-frame scratch for per-particle trail ribbons.
+ std::vector<glm::vec2> trail_center_; ///< Centerline (world), oldest→head.
+ std::vector<BatchVertex> trail_verts_; ///< 2 verts per centerline point.
+ std::vector<u32> trail_indices_; ///< 6 indices per segment.
};
} // namespace esengine
diff --git a/tests/particle/test_particle.cpp b/tests/particle/test_particle.cpp
index 71e54f6cf..74ba9c478 100644
--- a/tests/particle/test_particle.cpp
+++ b/tests/particle/test_particle.cpp
@@ -442,6 +442,83 @@ TEST_CASE("system_subemitter_none_leaves_child_empty") {
CHECK_EQ(system.aliveCount(child), 0u);
}
+TEST_CASE("system_trail_records_history_for_moving_particles") {
+ ecs::Registry registry;
+ ParticleSystem system;
+
+ Entity e = registry.create();
+ registry.emplace<ecs::Transform>(e);
+ auto& emitter = registry.emplace<ecs::ParticleEmitter>(e);
+ emitter.rate = 200.0f;
+ emitter.lifetimeMin = emitter.lifetimeMax = 10.0f;
+ emitter.maxParticles = 50;
+ emitter.speedMin = emitter.speedMax = 300.0f; // fast → clears trailMinDistance each frame
+ emitter.shape = static_cast<i32>(ecs::EmitterShape::Point);
+ emitter.trailEnabled = true;
+ emitter.trailPoints = 6;
+ emitter.trailMinDistance = 2.0f;
+ emitter.playOnStart = true;
+
+ for (int i = 0; i < 8; ++i) system.update(registry, 0.05f);
+
+ const EmitterState* st = system.getState(e);
+ REQUIRE(st != nullptr);
+ bool anyTrail = false;
+ for (std::size_t idx = 0; idx < st->pool.particles().size(); ++idx) {
+ if (st->pool.particles()[idx].alive && st->trail_count[idx] >= 2) anyTrail = true;
+ }
+ CHECK(anyTrail);
+}
+
+TEST_CASE("system_trail_disabled_allocates_no_history") {
+ ecs::Registry registry;
+ ParticleSystem system;
+
+ Entity e = registry.create();
+ registry.emplace<ecs::Transform>(e);
+ auto& emitter = registry.emplace<ecs::ParticleEmitter>(e);
+ emitter.rate = 200.0f;
+ emitter.lifetimeMin = emitter.lifetimeMax = 10.0f;
+ emitter.maxParticles = 50;
+ emitter.speedMin = emitter.speedMax = 300.0f;
+ emitter.trailEnabled = false;
+ emitter.playOnStart = true;
+
+ for (int i = 0; i < 5; ++i) system.update(registry, 0.05f);
+
+ const EmitterState* st = system.getState(e);
+ REQUIRE(st != nullptr);
+ CHECK(st->trail_count.empty()); // no history buffers when trails are off
+}
+
+TEST_CASE("system_trail_slot_reuse_starts_empty") {
+ // A dead particle's slot reused by a new particle must not inherit its trail.
+ ecs::Registry registry;
+ ParticleSystem system;
+
+ Entity e = registry.create();
+ registry.emplace<ecs::Transform>(e);
+ auto& emitter = registry.emplace<ecs::ParticleEmitter>(e);
+ emitter.rate = 400.0f;
+ emitter.lifetimeMin = emitter.lifetimeMax = 0.05f; // die fast → slots recycle
+ emitter.maxParticles = 8;
+ emitter.speedMin = emitter.speedMax = 300.0f;
+ emitter.trailEnabled = true;
+ emitter.trailPoints = 6;
+ emitter.trailMinDistance = 1.0f;
+ emitter.playOnStart = true;
+
+ // Many short frames so slots die and are reused repeatedly.
+ for (int i = 0; i < 20; ++i) system.update(registry, 0.02f);
+
+ const EmitterState* st = system.getState(e);
+ REQUIRE(st != nullptr);
+ // No freshly-recycled slot should report more points than the configured cap.
+ for (std::size_t idx = 0; idx < st->pool.particles().size(); ++idx) {
+ CHECK(st->trail_count[idx] <= 6);
+ }
+}
+
TEST_CASE("system_size_interpolation") {
ecs::Registry registry;
ParticleSystem system;