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): emission stops asking for an angle and starts asking the shape where and which way

esengine22b7cfe9feb8
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 71fc54ac9..45d5c1678 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -29,7 +29,7 @@ env:
test_registry_ondestroy test_view_api_matrix
test_shader_device test_draw_params test_texture_fb test_buffer_device
test_compressed_format test_batch_builder test_boundary_span test_webgpu_device
- test_clip_depth test_shadow_atlas
+ test_clip_depth test_shadow_atlas test_particle_shapes
test_text_edit test_render_graph test_device_loss test_physics_interpolation
test_bitmap_font test_texture_cache test_aot_host test_aot_conformance
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 3621e6dc8..1e8a72283 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -2394,8 +2394,10 @@
"values": [
"Point",
"Circle",
- "Rectangle",
- "Cone"
+ "Box",
+ "Cone",
+ "Sphere",
+ "Hemisphere"
]
},
{
diff --git a/examples/particle-demo/src/config.ts b/examples/particle-demo/src/config.ts
index 83fcbe00b..f50e085d8 100644
--- a/examples/particle-demo/src/config.ts
+++ b/examples/particle-demo/src/config.ts
@@ -110,7 +110,7 @@ export const SHOWCASES: Showcase[] = [
emitters: [
{ x: 0, y: 380, data: {
rate: 90, maxParticles: 800, lifetimeMin: 5, lifetimeMax: 8,
- shape: EmitterShape.Rectangle, shapeSize: { x: 1320, y: 12, z: 0 },
+ shape: EmitterShape.Box, shapeSize: { x: 1320, y: 12, z: 0 },
speedMin: 40, speedMax: 90, angleSpreadMin: 250, angleSpreadMax: 290,
startSizeMin: 5, startSizeMax: 11, endSizeMin: 5, endSizeMax: 11,
startColor: { r: 1, g: 1, b: 1, a: 0.9 }, endColor: { r: 0.85, g: 0.92, b: 1, a: 0.5 },
@@ -123,7 +123,7 @@ export const SHOWCASES: Showcase[] = [
emitters: [
{ x: 0, y: 0, data: {
rate: 70, maxParticles: 320, lifetimeMin: 1.0, lifetimeMax: 2.2,
- shape: EmitterShape.Rectangle, shapeSize: { x: 1120, y: 620, z: 0 },
+ shape: EmitterShape.Box, shapeSize: { x: 1120, y: 620, z: 0 },
speedMin: 5, speedMax: 25, startSizeMin: 3, startSizeMax: 9,
endSizeMin: 0, endSizeMax: 0, sizeEasing: ParticleEasing.EaseInOut,
startColor: { r: 1, g: 1, b: 0.8, a: 1 }, endColor: { r: 0.6, g: 0.8, b: 1, a: 0 },
diff --git a/examples/third-person-3d/assets/scenes/main.esscene b/examples/third-person-3d/assets/scenes/main.esscene
index 14530e4f1..febad6ec2 100644
--- a/examples/third-person-3d/assets/scenes/main.esscene
+++ b/examples/third-person-3d/assets/scenes/main.esscene
@@ -297,7 +297,8 @@
"children": [
6,
7,
- 8
+ 8,
+ 13
],
"visible": true,
"components": [
@@ -602,6 +603,125 @@
}
}
]
+ },
+ {
+ "id": 13,
+ "name": "FootDust",
+ "parent": 5,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": -78,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "ParticleEmitter",
+ "data": {
+ "rate": 14,
+ "maxParticles": 48,
+ "lifetimeMin": 0.35,
+ "lifetimeMax": 0.6,
+ "shape": 5,
+ "shapeRadius": 18,
+ "speedMin": 18,
+ "speedMax": 42,
+ "startSizeMin": 10,
+ "startSizeMax": 16,
+ "endSizeMin": 22,
+ "endSizeMax": 30,
+ "sizeEasing": 2,
+ "startColor": {
+ "r": 0.74,
+ "g": 0.68,
+ "b": 0.56,
+ "a": 0.22
+ },
+ "endColor": {
+ "r": 0.66,
+ "g": 0.62,
+ "b": 0.54,
+ "a": 0.0
+ },
+ "gravity": {
+ "x": 0,
+ "y": 26,
+ "z": 0
+ },
+ "damping": 1.6,
+ "blendMode": 0,
+ "layer": 0,
+ "simulationSpace": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 14,
+ "name": "AirMotes",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 220,
+ "z": -400
+ }
+ }
+ },
+ {
+ "type": "ParticleEmitter",
+ "data": {
+ "rate": 11,
+ "maxParticles": 150,
+ "lifetimeMin": 6.0,
+ "lifetimeMax": 11.0,
+ "shape": 4,
+ "shapeRadius": 900,
+ "speedMin": 4,
+ "speedMax": 16,
+ "startSizeMin": 3,
+ "startSizeMax": 6,
+ "endSizeMin": 3,
+ "endSizeMax": 6,
+ "startColor": {
+ "r": 1.0,
+ "g": 0.97,
+ "b": 0.85,
+ "a": 0.2
+ },
+ "endColor": {
+ "r": 1.0,
+ "g": 0.95,
+ "b": 0.8,
+ "a": 0.0
+ },
+ "colorEasing": 3,
+ "gravity": {
+ "x": 0,
+ "y": -3,
+ "z": 0
+ },
+ "damping": 0.4,
+ "noiseStrength": 26,
+ "noiseFrequency": 0.004,
+ "noiseScrollSpeed": 0.25,
+ "blendMode": 1,
+ "layer": 0,
+ "simulationSpace": 0
+ }
+ }
+ ]
}
]
}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 4aec7628d..5cea48bad 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 84 beta · 1560 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"97a5a526f33a8a4b"
+"fac7d5103ea562aa"
```
## ANCHOR_AXES — const @experimental
@@ -3030,10 +3030,12 @@ Partial<Record<SideModuleId, EmbeddedSideModuleEntry>>
## EmitterShape — enum @beta
```
+Box = 2
Circle = 1
Cone = 3
+Hemisphere = 5
Point = 0
-Rectangle = 2
+Sphere = 4
```
## EngineApi — type @experimental
@@ -5358,6 +5360,7 @@ play: (entity: Entity) => void
reset: (entity: Entity) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
+setSpeedLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 44445021b..7a9e216f4 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 89 beta · 1579 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"97a5a526f33a8a4b"
+"fac7d5103ea562aa"
```
## ANCHOR_AXES — const @experimental
@@ -3038,10 +3038,12 @@ Partial<Record<SideModuleId, EmbeddedSideModuleEntry>>
## EmitterShape — enum @beta
```
+Box = 2
Circle = 1
Cone = 3
+Hemisphere = 5
Point = 0
-Rectangle = 2
+Sphere = 4
```
## EngineApi — type @experimental
@@ -5541,6 +5543,7 @@ play: (entity: Entity) => void
reset: (entity: Entity) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
+setSpeedLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index af7079455..bd2c5da92 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -3025,10 +3025,12 @@ Partial<Record<SideModuleId, EmbeddedSideModuleEntry>>
## EmitterShape — enum @beta
```
+Box = 2
Circle = 1
Cone = 3
+Hemisphere = 5
Point = 0
-Rectangle = 2
+Sphere = 4
```
## EngineApi — type @experimental
@@ -5353,6 +5355,7 @@ play: (entity: Entity) => void
reset: (entity: Entity) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
+setSpeedLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 52c5f942f..5b53bf9d9 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -3025,10 +3025,12 @@ Partial<Record<SideModuleId, EmbeddedSideModuleEntry>>
## EmitterShape — enum @beta
```
+Box = 2
Circle = 1
Cone = 3
+Hemisphere = 5
Point = 0
-Rectangle = 2
+Sphere = 4
```
## EngineApi — type @experimental
@@ -5599,6 +5601,7 @@ play: (entity: Entity) => void
reset: (entity: Entity) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
+setSpeedLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index f3788fb3b..4ef26951f 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -309,6 +309,7 @@ particle_play: ((registry: CppRegistry, entity: number) => void) | undefined
particle_reset: ((registry: CppRegistry, entity: number) => void) | undefined
particle_set_color_lut: ((entity: number, ptr: number, count: number) => void) | undefined
particle_set_size_lut: ((entity: number, ptr: number, count: number) => void) | undefined
+particle_set_speed_lut: ((entity: number, ptr: number, count: number) => void) | undefined
particle_stop: ((registry: CppRegistry, entity: number) => void) | undefined
particle_update: ((registry: CppRegistry, dt: number) => void) | undefined
postprocess_addPass: (name: string, shaderHandle: number) => number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f7fa6ee7f..c4fc2ac2a 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -3025,10 +3025,12 @@ Partial<Record<SideModuleId, EmbeddedSideModuleEntry>>
## EmitterShape — enum @beta
```
+Box = 2
Circle = 1
Cone = 3
+Hemisphere = 5
Point = 0
-Rectangle = 2
+Sphere = 4
```
## EngineApi — type @experimental
@@ -5360,6 +5362,7 @@ play: (entity: Entity) => void
reset: (entity: Entity) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
+setSpeedLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 8f618f66d..226b75ff5 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -78,6 +78,7 @@ export interface NativeEngineApi {
particle_reset?(registry: unknown, entity: number): void;
particle_set_color_lut?(entity: number, ptr: number, count: number): void;
particle_set_size_lut?(entity: number, ptr: number, count: number): void;
+ particle_set_speed_lut?(entity: number, ptr: number, count: number): void;
particle_stop?(registry: unknown, entity: number): void;
particle_update?(registry: unknown, dt: number): void;
postprocess_addPass?(name: string, shaderHandle: number): number;
@@ -316,6 +317,7 @@ export function createNativeEngineApi(
bind('particle_reset', 'es_particle_reset', true);
bind('particle_set_color_lut', 'es_particle_set_color_lut', false);
bind('particle_set_size_lut', 'es_particle_set_size_lut', false);
+ bind('particle_set_speed_lut', 'es_particle_set_speed_lut', false);
bind('particle_stop', 'es_particle_stop', true);
bind('particle_update', 'es_particle_update', true);
bind('postprocess_addPass', 'es_postprocess_addPass', false);
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 30a36a0c3..6e4893a58 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '97a5a526f33a8a4b';
+export const ABI_LAYOUT_HASH = 'fac7d5103ea562aa';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -597,14 +597,14 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
maxParticles: { min: 1, step: 1, category: "Emission" },
lifetimeMin: { min: 0, category: "Lifetime" },
lifetimeMax: { min: 0, category: "Lifetime" },
- shape: { enum: [{ label: 'Point', value: 0 }, { label: 'Circle', value: 1 }, { label: 'Rectangle', value: 2 }, { label: 'Cone', value: 3 }], category: "Shape" },
- shapeRadius: { min: 0, category: "Shape", shownWhen: { field: "shape", values: [1, 3] } },
+ shape: { enum: [{ label: 'Point', value: 0 }, { label: 'Circle', value: 1 }, { label: 'Box', value: 2 }, { label: 'Cone', value: 3 }, { label: 'Sphere', value: 4 }, { label: 'Hemisphere', value: 5 }], category: "Shape" },
+ shapeRadius: { min: 0, category: "Shape", shownWhen: { field: "shape", values: [1, 3, 4, 5] } },
shapeSize: { category: "Shape", shownWhen: { field: "shape", values: [2] } },
shapeAngle: { unit: "°", category: "Shape", shownWhen: { field: "shape", values: [3] } },
speedMin: { category: "Velocity" },
speedMax: { category: "Velocity" },
- angleSpreadMin: { unit: "°", category: "Velocity" },
- angleSpreadMax: { unit: "°", category: "Velocity" },
+ angleSpreadMin: { unit: "°", category: "Velocity", shownWhen: { field: "shape", values: [0, 2] } },
+ angleSpreadMax: { unit: "°", category: "Velocity", shownWhen: { field: "shape", values: [0, 2] } },
startSizeMin: { min: 0, category: "Size" },
startSizeMax: { min: 0, category: "Size" },
endSizeMin: { min: 0, category: "Size" },
diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.ts
index 7dd0b304b..1df97b1c1 100644
--- a/sdk/src/particle/ParticleAPI.ts
+++ b/sdk/src/particle/ParticleAPI.ts
@@ -59,6 +59,15 @@ export class ParticleAPI {
this.uploadLut(this.module_.particle_set_size_lut, entity, lut, 1);
}
+ /**
+ * Speed-over-life multiplier. Scales how fast a particle travels along the
+ * trajectory it already has — gravity, damping and noise still accumulate
+ * into its velocity, so this is not a second force system.
+ */
+ setSpeedLut(entity: Entity, lut: Float32Array | null): void {
+ this.uploadLut(this.module_.particle_set_speed_lut, entity, lut, 1);
+ }
+
// Copy a Float32Array into the core's heap and hand its offset + element count
// (length / `stride`) to the C++ setter, then free; null/empty clears. The heap
// is wasm linear memory on the web and the host's arena on a device — the same
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index b81c021cb..e12c57e0b 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -459,6 +459,7 @@ export interface ESEngineModule {
particle_set_color_lut?(entity: number, ptr: number, count: number): void;
/** Upload/clear an entity's baked size-over-life multiplier LUT. */
particle_set_size_lut?(entity: number, ptr: number, count: number): void;
+ particle_set_speed_lut?(entity: number, ptr: number, count: number): void;
trail_update?(registry: CppRegistry, dt: number): void;
trail_clear?(registry: CppRegistry, entity: number): void;
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 9b2568767..f594ebd00 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -105,8 +105,10 @@ export enum EasingType {
export enum EmitterShape {
Point = 0,
Circle = 1,
- Rectangle = 2,
+ Box = 2,
Cone = 3,
+ Sphere = 4,
+ Hemisphere = 5,
}
export enum FlexDirection {
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index a5f70b776..7b7f075f8 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -386,10 +386,24 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"ParticleEmitter": {
"angleSpreadMax": {
"category": "Velocity",
+ "shownWhen": {
+ "field": "shape",
+ "values": [
+ 0,
+ 2,
+ ],
+ },
"unit": "°",
},
"angleSpreadMin": {
"category": "Velocity",
+ "shownWhen": {
+ "field": "shape",
+ "values": [
+ 0,
+ 2,
+ ],
+ },
"unit": "°",
},
"angularVelocityMax": {
@@ -612,13 +626,21 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"value": 1,
},
{
- "label": "Rectangle",
+ "label": "Box",
"value": 2,
},
{
"label": "Cone",
"value": 3,
},
+ {
+ "label": "Sphere",
+ "value": 4,
+ },
+ {
+ "label": "Hemisphere",
+ "value": 5,
+ },
],
},
"shapeAngle": {
@@ -639,6 +661,8 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"values": [
1,
3,
+ 4,
+ 5,
],
},
},
diff --git a/sdk/tests/particle.test.ts b/sdk/tests/particle.test.ts
index 04401b58d..5cf7589cd 100644
--- a/sdk/tests/particle.test.ts
+++ b/sdk/tests/particle.test.ts
@@ -72,7 +72,7 @@ describe('Particle Enums', () => {
const { EmitterShape } = await import('../src/ecs/component');
expect(EmitterShape.Point).toBe(0);
expect(EmitterShape.Circle).toBe(1);
- expect(EmitterShape.Rectangle).toBe(2);
+ expect(EmitterShape.Box).toBe(2);
expect(EmitterShape.Cone).toBe(3);
});
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 5ab7adb18..a2ab3447d 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 e6b42602c58bf96a
+ * @schema_hash 4dea57b14e10801b
*/
-#define ES_EDITOR_API_SCHEMA_HASH "e6b42602c58bf96a"
+#define ES_EDITOR_API_SCHEMA_HASH "4dea57b14e10801b"
#include <emscripten/bind.h>
#include <string>
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index c52ce6204..59c418248 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -533,6 +533,11 @@ void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count) {
if (!g_particleSystem) return;
g_particleSystem->setSizeLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
}
+
+void particle_set_speed_lut(u32 entity, uintptr_t ptr, i32 count) {
+ if (!g_particleSystem) return;
+ g_particleSystem->setSpeedLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
+}
#endif
void trail_update(ecs::Registry& registry, f32 dt) {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index fc22ce5e0..b467bd2c0 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -95,6 +95,8 @@ void particle_reset(ecs::Registry& registry, u32 entity);
u32 particle_getAliveCount(u32 entity);
void particle_set_color_lut(u32 entity, uintptr_t ptr, i32 count);
void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count);
+/** Speed-over-life multiplier LUT: scales the step, never the forces. */
+void particle_set_speed_lut(u32 entity, uintptr_t ptr, i32 count);
#endif
void trail_update(ecs::Registry& registry, f32 dt);
void trail_clear(ecs::Registry& registry, u32 entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 49e83bc5c..927e75df3 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -152,8 +152,10 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {
enum_<esengine::ecs::EmitterShape>("EmitterShape")
.value("Point", esengine::ecs::EmitterShape::Point)
.value("Circle", esengine::ecs::EmitterShape::Circle)
- .value("Rectangle", esengine::ecs::EmitterShape::Rectangle)
- .value("Cone", esengine::ecs::EmitterShape::Cone);
+ .value("Box", esengine::ecs::EmitterShape::Box)
+ .value("Cone", esengine::ecs::EmitterShape::Cone)
+ .value("Sphere", esengine::ecs::EmitterShape::Sphere)
+ .value("Hemisphere", esengine::ecs::EmitterShape::Hemisphere);
enum_<esengine::ecs::FlexDirection>("FlexDirection")
.value("Row", esengine::ecs::FlexDirection::Row)
@@ -3116,7 +3118,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "97a5a526f33a8a4b";
+static const char* kEsAbiLayoutHash = "fac7d5103ea562aa";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 2e86f782b..04a6a9a3c 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -691,6 +691,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("particle_getAliveCount", &esengine::particle_getAliveCount);
emscripten::function("particle_set_color_lut", &esengine::particle_set_color_lut);
emscripten::function("particle_set_size_lut", &esengine::particle_set_size_lut);
+ emscripten::function("particle_set_speed_lut", &esengine::particle_set_speed_lut);
#endif
emscripten::function("trail_update", &esengine::trail_update);
emscripten::function("trail_clear", &esengine::trail_clear);
diff --git a/src/esengine/ecs/components/ParticleEmitter.hpp b/src/esengine/ecs/components/ParticleEmitter.hpp
index 0a3e08aba..998b1f4ee 100644
--- a/src/esengine/ecs/components/ParticleEmitter.hpp
+++ b/src/esengine/ecs/components/ParticleEmitter.hpp
@@ -9,12 +9,16 @@
namespace esengine::ecs {
+// Local +Y is the axis every directed shape points along, so an unrotated
+// emitter aims up — where every 2D cone has always aimed. Values are serialized.
ES_ENUM(stability=beta)
enum class EmitterShape : i32 {
Point = 0,
Circle = 1,
- Rectangle = 2,
+ Box = 2,
Cone = 3,
+ Sphere = 4,
+ Hemisphere = 5,
};
// Single source of the easing choice serialized by sizeEasing/colorEasing; the
@@ -78,10 +82,12 @@ struct ParticleEmitter {
ES_PROPERTY(enum=EmitterShape, category=Shape)
i32 shape{static_cast<i32>(EmitterShape::Cone)};
- ES_PROPERTY(min=0, category=Shape, shown_when=shape:Circle|Cone)
+ ES_PROPERTY(min=0, category=Shape, shown_when=shape:Circle|Cone|Sphere|Hemisphere)
f32 shapeRadius{100.0f};
- ES_PROPERTY(category=Shape, shown_when=shape:Rectangle)
+ // A filled VOLUME, not a surface: shapeSize.z of 0 is the flat rectangle every
+ // 2D emitter spawned from, so one field spells both.
+ ES_PROPERTY(category=Shape, shown_when=shape:Box)
glm::vec3 shapeSize{100.0f, 100.0f, 0.0f};
ES_PROPERTY(unit="°", category=Shape, shown_when=shape:Cone)
@@ -94,10 +100,13 @@ struct ParticleEmitter {
ES_PROPERTY(category=Velocity)
f32 speedMax{500.0f};
- ES_PROPERTY(unit="°", category=Velocity)
+ // Aim for the shapes that HAVE no aim of their own (Point, Box): an angle in
+ // the emitter's local XY plane. Circle, Cone, Sphere and Hemisphere carry a
+ // direction intrinsically and ignore these.
+ ES_PROPERTY(unit="°", category=Velocity, shown_when=shape:Point|Box)
f32 angleSpreadMin{0.0f};
- ES_PROPERTY(unit="°", category=Velocity)
+ ES_PROPERTY(unit="°", category=Velocity, shown_when=shape:Point|Box)
f32 angleSpreadMax{360.0f};
// Size
diff --git a/src/esengine/particle/ParticleShapes.hpp b/src/esengine/particle/ParticleShapes.hpp
new file mode 100644
index 000000000..0db801ee6
--- /dev/null
+++ b/src/esengine/particle/ParticleShapes.hpp
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ParticleShapes.hpp
+ * @brief Where a particle is born and which way it leaves — a pure function of
+ * the emitter's own configuration.
+ * @details Header-only and free of the simulation, because it is the one part of
+ * emission that is a DISTRIBUTION rather than a frame: a rendered picture
+ * is a projection and cannot answer whether directions are isotropic, so
+ * the shapes are tested here as the distributions they are.
+ *
+ * Every shape answers in the same two terms, so the integrator never
+ * learns a new kind of aim. Local +Y is the axis a directed shape points
+ * along — where a 2D cone has always pointed.
+ */
+#pragma once
+
+#include "../core/Types.hpp"
+#include "../math/Math.hpp"
+#include "../ecs/components/ParticleEmitter.hpp"
+
+#include <cmath>
+#include <functional>
+
+namespace esengine::particle {
+
+/** A uniform draw in [a, b). Injected so a test can be deterministic. */
+using RandomRange = std::function<f32(f32, f32)>;
+
+/** Where the emitter stands, how it is aimed, how big its shape is — the whole
+ * of what a spawn needs from a Transform. */
+struct EmitterFrame {
+ glm::vec3 position{0.0f};
+ glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};
+ glm::vec3 scale{1.0f};
+};
+
+/** A local point placed in the world: scale sizes the shape, rotation aims it. */
+inline glm::vec3 worldPointOf(const glm::vec3& local, const EmitterFrame& f) {
+ return f.position + f.rotation * (local * f.scale);
+}
+
+/**
+ * @brief A local direction placed in the world — rotation ALONE.
+ * @details Scaling an aim would skew a cone's half-angle and translating one
+ * would make it depend on where the emitter stands.
+ */
+inline glm::vec3 worldDirOf(const glm::vec3& local, const EmitterFrame& f) {
+ return f.rotation * local;
+}
+
+/** One birth, in EMITTER LOCAL space. */
+struct SpawnSample {
+ glm::vec3 position{0.0f};
+ glm::vec3 direction{0.0f, 1.0f, 0.0f};
+};
+
+/**
+ * @brief A direction inside the cap of half-angle @p halfAngle about local +Y.
+ * @details cos(theta) is what must be uniform, not theta: sampling the angle
+ * crowds the axis, the same mistake latitude/longitude makes at a
+ * sphere's poles. PI/2 is the +Y hemisphere and PI the whole sphere, so
+ * one function is Cone, Hemisphere and Sphere.
+ */
+inline glm::vec3 coneDirection(f32 halfAngle, const RandomRange& rand) {
+ const f32 cosTheta = rand(std::cos(halfAngle), 1.0f);
+ const f32 sinTheta = std::sqrt(std::max(0.0f, 1.0f - cosTheta * cosTheta));
+ const f32 phi = rand(0.0f, math::TWO_PI);
+ return glm::vec3(sinTheta * std::cos(phi), cosTheta, sinTheta * std::sin(phi));
+}
+
+/** One sample from @p emitter's shape, in emitter local space. */
+inline SpawnSample sampleShape(const ecs::ParticleEmitter& emitter, const RandomRange& rand) {
+ SpawnSample s;
+ // Point and Box have no aim of their own, so they take one: an angle in the
+ // emitter's local XY plane, which is what every 2D emitter has always meant.
+ auto planarAim = [&] {
+ const f32 a = rand(emitter.angleSpreadMin, emitter.angleSpreadMax) * math::DEG_TO_RAD;
+ return glm::vec3(std::cos(a), std::sin(a), 0.0f);
+ };
+
+ switch (static_cast<ecs::EmitterShape>(emitter.shape)) {
+ case ecs::EmitterShape::Circle: {
+ // A disc in the emitter's LOCAL plane, not the world's — a rotated
+ // emitter carries its circle with it.
+ const f32 angle = rand(0.0f, math::TWO_PI);
+ const f32 radius = rand(0.0f, emitter.shapeRadius);
+ s.position = glm::vec3(std::cos(angle) * radius, std::sin(angle) * radius, 0.0f);
+ s.direction = radius > 0.001f ? s.position / radius : planarAim();
+ break;
+ }
+ case ecs::EmitterShape::Box: {
+ // A filled VOLUME. A depthless one is the rectangle 2D always had.
+ s.position = glm::vec3(
+ rand(-emitter.shapeSize.x * 0.5f, emitter.shapeSize.x * 0.5f),
+ rand(-emitter.shapeSize.y * 0.5f, emitter.shapeSize.y * 0.5f),
+ emitter.shapeSize.z > 0.0f
+ ? rand(-emitter.shapeSize.z * 0.5f, emitter.shapeSize.z * 0.5f) : 0.0f);
+ s.direction = planarAim();
+ break;
+ }
+ case ecs::EmitterShape::Cone: {
+ const f32 halfAngle = emitter.shapeAngle * 0.5f * math::DEG_TO_RAD;
+ s.direction = coneDirection(halfAngle, rand);
+ // Spawn spread sampled INDEPENDENTLY of the velocity, so a particle's
+ // birthplace does not predict where it goes.
+ s.position = coneDirection(halfAngle, rand) * rand(0.0f, emitter.shapeRadius);
+ break;
+ }
+ case ecs::EmitterShape::Sphere:
+ case ecs::EmitterShape::Hemisphere: {
+ const bool full = static_cast<ecs::EmitterShape>(emitter.shape)
+ == ecs::EmitterShape::Sphere;
+ const f32 half = full ? math::PI : math::HALF_PI;
+ s.direction = coneDirection(half, rand);
+ // Uniform through the VOLUME: a radius linear in the draw piles the
+ // particles at the centre, which is a ball made of a spike.
+ s.position = coneDirection(half, rand)
+ * (emitter.shapeRadius * std::cbrt(rand(0.0f, 1.0f)));
+ break;
+ }
+ case ecs::EmitterShape::Point:
+ default:
+ s.direction = planarAim();
+ break;
+ }
+ return s;
+}
+
+} // namespace esengine::particle
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index cbaacf46d..790d8bb2a 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -25,6 +25,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
pending_play_.erase(entity);
colorLuts_.erase(entity);
sizeLuts_.erase(entity);
+ speedLuts_.erase(entity);
});
}
@@ -124,21 +125,19 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
}
}
- glm::vec3 emitterPos = transform.worldPosition;
- f32 emitterAngle = 0.0f;
- if (transform.worldRotation.w != 1.0f || transform.worldRotation.z != 0.0f) {
- emitterAngle = 2.0f * std::atan2(transform.worldRotation.z,
- transform.worldRotation.w);
- }
+ const EmitterFrame frame{transform.worldPosition, transform.worldRotation,
+ transform.worldScale};
bool isWorldSpace = emitter.simulationSpace ==
static_cast<i32>(ecs::SimulationSpace::World);
auto lutIt = colorLuts_.find(entity);
auto sizeIt = sizeLuts_.find(entity);
+ auto speedIt = speedLuts_.find(entity);
updateParticles(emitter, state, dt,
lutIt != colorLuts_.end() ? &lutIt->second : nullptr,
sizeIt != sizeLuts_.end() ? &sizeIt->second : nullptr,
- emitterPos, emitterAngle, isWorldSpace);
+ speedIt != speedLuts_.end() ? &speedIt->second : nullptr,
+ frame, isWorldSpace);
// Fire the child sub-emitter's burst at every birth/death queued this frame.
if (emitter.subEmitter != 0 && !subemit_requests_.empty()) {
@@ -200,6 +199,15 @@ void ParticleSystem::setSizeLut(Entity entity, const f32* values, i32 count) {
for (std::size_t i = 0; i < kColorLutSize; ++i) lut[i] = values[i];
}
+void ParticleSystem::setSpeedLut(Entity entity, const f32* values, i32 count) {
+ if (count != kColorLutSize || values == nullptr) {
+ speedLuts_.erase(entity);
+ return;
+ }
+ SizeLut& lut = speedLuts_[entity];
+ for (std::size_t i = 0; i < kColorLutSize; ++i) lut[i] = values[i];
+}
+
u32 ParticleSystem::aliveCount(Entity entity) const {
auto it = states_.find(entity);
if (it != states_.end()) {
@@ -234,30 +242,19 @@ const EmitterState* ParticleSystem::getState(Entity entity) const {
return it != states_.end() ? &it->second : nullptr;
}
-// Turn a vector about Z by a precomputed cos/sin — the emitter's own rotation,
-// which is a turn in the plane whether or not the particle has depth. Depth rides
-// through it, as it does under any rotation about the axis it lies on.
-static inline glm::vec3 rotate2(glm::vec3 v, f32 cosA, f32 sinA) {
- return glm::vec3(v.x * cosA - v.y * sinA, v.x * sinA + v.y * cosA, v.z);
-}
-
void ParticleSystem::emitParticles(const ecs::ParticleEmitter& emitter,
const ecs::Transform& transform,
EmitterState& state, u32 count) {
- glm::vec3 emitterPos = transform.worldPosition;
- f32 emitterAngle = 0.0f;
- if (transform.worldRotation.w != 1.0f || transform.worldRotation.z != 0.0f) {
- emitterAngle = 2.0f * std::atan2(transform.worldRotation.z,
- transform.worldRotation.w);
- }
+ const EmitterFrame frame{transform.worldPosition, transform.worldRotation,
+ transform.worldScale};
bool isWorldSpace = emitter.simulationSpace ==
static_cast<i32>(ecs::SimulationSpace::World);
- emitInto(emitter, state, emitterPos, emitterAngle, isWorldSpace, glm::vec3(0.0f), count,
+ emitInto(emitter, state, frame, isWorldSpace, glm::vec3(0.0f), count,
/*allowBirthTrigger=*/true);
}
void ParticleSystem::emitInto(const ecs::ParticleEmitter& emitter, EmitterState& state,
- glm::vec3 emitterPos, f32 emitterAngle, bool isWorldSpace,
+ const EmitterFrame& frame, bool isWorldSpace,
glm::vec3 velocityBias, u32 count, bool allowBirthTrigger) {
// Record each spawned particle for a Birth-triggered sub-emitter (in world
// space, since a sub-burst is a world event).
@@ -265,8 +262,6 @@ void ParticleSystem::emitInto(const ecs::ParticleEmitter& emitter, EmitterState&
emitter.subEmitter != 0 &&
emitter.subEmitterTrigger ==
static_cast<i32>(ecs::SubEmitterTrigger::Birth);
- f32 cosA = std::cos(emitterAngle);
- f32 sinA = std::sin(emitterAngle);
for (u32 i = 0; i < count; ++i) {
Particle* p = state.pool.allocate();
@@ -296,58 +291,25 @@ void ParticleSystem::emitInto(const ecs::ParticleEmitter& emitter, EmitterState&
p->angular_velocity = randomRange(emitter.angularVelocityMin,
emitter.angularVelocityMax);
- glm::vec3 offset = randomShapeOffset(emitter);
- if (isWorldSpace) {
- // Rotate the spawn footprint by the emitter angle so the emission
- // shape agrees with the (already-rotated) velocity below; otherwise a
- // rotated world-space cone/box spawns along its unrotated axis while
- // the flow points elsewhere. `offset` itself stays unrotated — the
- // Circle aim reads it and gets the same rotation applied once, below.
- p->position = emitterPos + rotate2(offset, cosA, sinA);
- } else {
- p->position = offset;
- }
+ // ONE question to the shape, and the simulation asks nothing else: a new
+ // shape cannot teach the integrator a new kind of aim.
+ const SpawnSample sample =
+ sampleShape(emitter, [this](f32 a, f32 b) { return randomRange(a, b); });
- f32 speed = randomRange(emitter.speedMin, emitter.speedMax);
- glm::vec3 dir;
- auto shape = static_cast<ecs::EmitterShape>(emitter.shape);
- switch (shape) {
- case ecs::EmitterShape::Circle: {
- f32 offsetLen = glm::length(offset);
- if (offsetLen > 0.001f) {
- dir = offset / offsetLen;
- } else {
- dir = randomDirection(0.0f, 360.0f);
- }
- break;
- }
- case ecs::EmitterShape::Cone: {
- f32 halfAngle = emitter.shapeAngle * 0.5f * math::DEG_TO_RAD;
- f32 angle = randomRange(-halfAngle, halfAngle);
- dir = glm::vec3(std::sin(angle), std::cos(angle), 0.0f);
- break;
- }
- // Point and Rectangle share one aiming rule: the shape decides WHERE a
- // particle spawns (a single point vs. a filled box), while angleSpread
- // decides which way it flies. Circle and Cone override this with their
- // own radial / conic aim, which is intrinsic to those shapes.
- case ecs::EmitterShape::Rectangle:
- case ecs::EmitterShape::Point:
- default:
- dir = randomDirection(emitter.angleSpreadMin, emitter.angleSpreadMax);
- break;
- }
- if (isWorldSpace) {
- dir = rotate2(dir, cosA, sinA);
- }
+ p->position = isWorldSpace ? worldPointOf(sample.position, frame)
+ : sample.position * frame.scale;
+
+ const f32 speed = randomRange(emitter.speedMin, emitter.speedMax);
+ const glm::vec3 dir = isWorldSpace ? worldDirOf(sample.direction, frame)
+ : sample.direction;
p->velocity = dir * speed + velocityBias;
p->sprite_frame = 0;
if (recordBirth) {
glm::vec3 worldPos = isWorldSpace ? p->position
- : emitterPos + rotate2(p->position, cosA, sinA);
- glm::vec3 worldVel = isWorldSpace ? p->velocity : rotate2(p->velocity, cosA, sinA);
+ : frame.position + frame.rotation * p->position;
+ glm::vec3 worldVel = isWorldSpace ? p->velocity : frame.rotation * p->velocity;
subemit_requests_.push_back({worldPos, worldVel});
}
}
@@ -383,7 +345,11 @@ void ParticleSystem::drainSubEmitters(ecs::Registry& registry, Entity child,
if (chance < 1.0f && randomRange(0.0f, 1.0f) >= chance) {
continue;
}
- emitInto(childEmitter, childState, req.position, 0.0f, /*isWorldSpace=*/true,
+ // A sub-burst happens where the parent particle died, unrotated and
+ // unscaled: the child's own shape is what aims it, and a particle carries
+ // no orientation to inherit.
+ emitInto(childEmitter, childState, EmitterFrame{req.position, glm::quat(1, 0, 0, 0),
+ glm::vec3(1.0f)}, /*isWorldSpace=*/true,
req.velocity * inheritVelocity, count, /*allowBirthTrigger=*/false);
}
}
@@ -446,7 +412,8 @@ static void applyForceField(const ForceFieldInstance& ff, Particle& p, f32 dt) {
void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
EmitterState& state, f32 dt,
const ColorLut* colorLut, const SizeLut* sizeLut,
- glm::vec3 emitterPos, f32 emitterAngle,
+ const SizeLut* speedLut,
+ const EmitterFrame& frame,
bool isWorldSpace) {
auto sizeEasing = static_cast<EasingType>(emitter.sizeEasing);
auto colorEasing = static_cast<EasingType>(emitter.colorEasing);
@@ -457,8 +424,6 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
bool recordDeath = emitter.subEmitter != 0 &&
emitter.subEmitterTrigger ==
static_cast<i32>(ecs::SubEmitterTrigger::Death);
- f32 cosA = std::cos(emitterAngle);
- f32 sinA = std::sin(emitterAngle);
// Noise/Turbulence: a curl-noise flow field advected onto position. Strength 0
// samples nothing (the whole module is free when unused). The scroll offset
@@ -482,8 +447,8 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
if (p.age >= p.lifetime) {
if (recordDeath) {
glm::vec3 worldPos = isWorldSpace ? p.position
- : emitterPos + rotate2(p.position, cosA, sinA);
- glm::vec3 worldVel = isWorldSpace ? p.velocity : rotate2(p.velocity, cosA, sinA);
+ : frame.position + frame.rotation * p.position;
+ glm::vec3 worldVel = isWorldSpace ? p.velocity : frame.rotation * p.velocity;
subemit_requests_.push_back({worldPos, worldVel});
}
u32 idx = static_cast<u32>(&p - &state.pool.particles()[0]);
@@ -500,7 +465,10 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
if (emitter.damping > 0.0f) {
p.velocity *= (1.0f - emitter.damping * dt);
}
- p.position += p.velocity * dt;
+ // Applied to the STEP, not to velocity, so speed-over-life cannot become
+ // a second force system: gravity, damping and noise still accumulate into
+ // velocity exactly as before.
+ p.position += p.velocity * (speedLut ? sampleSizeLut(*speedLut, t) : 1.0f) * dt;
if (noiseOn) {
// The curl field is a 2D flow, sampled on the plane the particle is
@@ -594,39 +562,4 @@ f32 ParticleSystem::randomRange(f32 min, f32 max) {
// An aim in the emitter's own plane: an angle names a direction there, and the
// emitter's rotation is what turns the plane. Aiming out of it is the emitter's
// job to be turned, not this one's to invent a second angle nobody authored.
-glm::vec3 ParticleSystem::randomDirection(f32 angleMin, f32 angleMax) {
- f32 angleDeg = randomRange(angleMin, angleMax);
- f32 angleRad = angleDeg * math::DEG_TO_RAD;
- return glm::vec3(std::cos(angleRad), std::sin(angleRad), 0.0f);
-}
-
-glm::vec3 ParticleSystem::randomShapeOffset(const ecs::ParticleEmitter& emitter) {
- auto shape = static_cast<ecs::EmitterShape>(emitter.shape);
- switch (shape) {
- case ecs::EmitterShape::Circle: {
- f32 angle = randomRange(0.0f, math::TWO_PI);
- f32 radius = randomRange(0.0f, emitter.shapeRadius);
- return glm::vec3(std::cos(angle) * radius, std::sin(angle) * radius, 0.0f);
- }
- case ecs::EmitterShape::Rectangle: {
- // A BOX where the scene gives it depth: `shapeSize.z` of 0 is the flat
- // rectangle every 2D emitter has spawned from, so one field covers both.
- f32 x = randomRange(-emitter.shapeSize.x * 0.5f, emitter.shapeSize.x * 0.5f);
- f32 y = randomRange(-emitter.shapeSize.y * 0.5f, emitter.shapeSize.y * 0.5f);
- f32 z = emitter.shapeSize.z > 0.0f
- ? randomRange(-emitter.shapeSize.z * 0.5f, emitter.shapeSize.z * 0.5f) : 0.0f;
- return glm::vec3(x, y, z);
- }
- case ecs::EmitterShape::Cone: {
- f32 halfAngle = emitter.shapeAngle * 0.5f * math::DEG_TO_RAD;
- f32 angle = randomRange(-halfAngle, halfAngle);
- return glm::vec3(std::sin(angle), std::cos(angle), 0.0f)
- * randomRange(0.0f, emitter.shapeRadius);
- }
- case ecs::EmitterShape::Point:
- default:
- return glm::vec3(0.0f);
- }
-}
-
} // namespace esengine::particle
diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hpp
index c551eb30b..75536833d 100644
--- a/src/esengine/particle/ParticleSystem.hpp
+++ b/src/esengine/particle/ParticleSystem.hpp
@@ -10,6 +10,7 @@
#include "../ecs/components/ParticleForceField.hpp"
#include "Particle.hpp"
#include "ParticleEasing.hpp"
+#include "ParticleShapes.hpp"
#include <unordered_map>
#include <unordered_set>
@@ -99,18 +100,23 @@ public:
/** Set/clear an entity's size-over-life multiplier LUT (× the particle's start size). */
void setSizeLut(Entity entity, const f32* values, i32 count);
+ /** Set/clear an entity's speed-over-life multiplier LUT. It scales how fast a
+ * particle travels along the trajectory it already has — it is not a force,
+ * and gravity, damping and noise still accumulate into velocity as before. */
+ void setSpeedLut(Entity entity, const f32* values, i32 count);
+
private:
void emitParticles(const ecs::ParticleEmitter& emitter,
const ecs::Transform& transform,
EmitterState& state, u32 count);
- // Shared spawn core: seed `count` particles into `state` from `emitter`'s config,
- // originating at world `emitterPos`/`emitterAngle`, adding `velocityBias` to each
- // (used by sub-emitter bursts to inherit the parent particle's motion).
+ // Shared spawn core: seed `count` particles into `state` from `emitter`'s
+ // config at `frame`, adding `velocityBias` to each (a sub-emitter burst
+ // inherits the parent particle's motion that way).
// `allowBirthTrigger` records Birth events for a nested sub-emitter; false for a
// sub-burst's own spawn so a drain can't re-enter the request buffer it's reading.
void emitInto(const ecs::ParticleEmitter& emitter, EmitterState& state,
- glm::vec3 emitterPos, f32 emitterAngle, bool isWorldSpace,
+ const EmitterFrame& frame, bool isWorldSpace,
glm::vec3 velocityBias, u32 count, bool allowBirthTrigger);
// Fire the referenced child emitter's burst at each pending sub-emit request.
@@ -119,11 +125,11 @@ private:
void updateParticles(const ecs::ParticleEmitter& emitter, EmitterState& state, f32 dt,
const ColorLut* colorLut, const SizeLut* sizeLut,
- glm::vec3 emitterPos, f32 emitterAngle, bool isWorldSpace);
+ const SizeLut* speedLut,
+ const EmitterFrame& frame, bool isWorldSpace);
f32 randomRange(f32 min, f32 max);
- glm::vec3 randomDirection(f32 angleMin, f32 angleMax);
- glm::vec3 randomShapeOffset(const ecs::ParticleEmitter& emitter);
+
// A parent particle's birth/death position + velocity, queued during a parent's
// update and drained into its child sub-emitter right after.
@@ -136,6 +142,7 @@ private:
std::unordered_set<Entity> pending_play_;
std::unordered_map<Entity, ColorLut> colorLuts_;
std::unordered_map<Entity, SizeLut> sizeLuts_;
+ std::unordered_map<Entity, SizeLut> speedLuts_;
std::mt19937 rng_;
std::vector<u32> dead_particle_indices_;
// Active scene force fields, rebuilt each update() and applied to world-space
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index f689783b1..0f1dfccbe 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -189,6 +189,16 @@ add_test(NAME test_clip_depth COMMAND test_clip_depth)
# the arithmetic a frame cannot show: which square a claim hands out, and what a
# refused one leaves behind. Whether a light READS the square it was given is a
# pixel question, and point-shadow asks it.
+# Emission shapes: the sampler is a pure function of the emitter's config, so the
+# distributions are asked here rather than through a frame that could not show a
+# bias along the view axis. Header-only — no engine to link.
+add_executable(test_particle_shapes particle/test_particle_shapes.cpp)
+target_include_directories(test_particle_shapes PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+)
+add_test(NAME test_particle_shapes COMMAND test_particle_shapes)
+
add_executable(test_shadow_atlas renderer/test_shadow_atlas.cpp)
target_include_directories(test_shadow_atlas PRIVATE
${CMAKE_SOURCE_DIR}/src
diff --git a/tests/particle/test_particle.cpp b/tests/particle/test_particle.cpp
index 954e895b6..76f3448d8 100644
--- a/tests/particle/test_particle.cpp
+++ b/tests/particle/test_particle.cpp
@@ -354,7 +354,7 @@ TEST_CASE("system_noise_advects_otherwise_static_particles") {
emitter.speedMin = emitter.speedMax = 0.0f;
emitter.gravity = glm::vec3(0.0f);
// Spread the spawn across the field so particles sample varied, non-zero curl.
- emitter.shape = static_cast<i32>(ecs::EmitterShape::Rectangle);
+ emitter.shape = static_cast<i32>(ecs::EmitterShape::Box);
emitter.shapeSize = glm::vec3(800.0f, 800.0f, 0.0f);
emitter.noiseStrength = 500.0f;
emitter.noiseFrequency = 0.01f;
@@ -859,7 +859,7 @@ TEST_CASE("shape_rectangle_within_bounds") {
Entity e = registry.create();
registry.emplace<ecs::Transform>(e);
auto& emitter = registry.emplace<ecs::ParticleEmitter>(e);
- emitter.shape = static_cast<i32>(ecs::EmitterShape::Rectangle);
+ emitter.shape = static_cast<i32>(ecs::EmitterShape::Box);
emitter.shapeSize = glm::vec3(10.0f, 6.0f, 0.0f);
emitter.rate = 1000.0f;
emitter.lifetimeMin = 10.0f;
@@ -1361,7 +1361,7 @@ TEST_CASE("shape_rectangle_direction_follows_angle_spread") {
Entity e = registry.create();
registry.emplace<ecs::Transform>(e);
auto& emitter = registry.emplace<ecs::ParticleEmitter>(e);
- emitter.shape = static_cast<i32>(ecs::EmitterShape::Rectangle);
+ emitter.shape = static_cast<i32>(ecs::EmitterShape::Box);
emitter.shapeSize = glm::vec3(10.0f, 6.0f, 0.0f);
emitter.rate = 1000.0f;
emitter.lifetimeMin = 10.0f;
diff --git a/tests/particle/test_particle_shapes.cpp b/tests/particle/test_particle_shapes.cpp
new file mode 100644
index 000000000..54ee68b57
--- /dev/null
+++ b/tests/particle/test_particle_shapes.cpp
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file test_particle_shapes.cpp — emission shapes as the DISTRIBUTIONS they are.
+ *
+ * A frame cannot answer "is this isotropic": a projection hides a bias along the
+ * view axis. Header-only, so these run in the local harness.
+ */
+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
+#include <doctest.h>
+
+#include <esengine/particle/ParticleShapes.hpp>
+#include <algorithm>
+#include <glm/gtc/quaternion.hpp>
+#include <cmath>
+
+using namespace esengine;
+using namespace esengine::particle;
+
+// ============================================================================
+// Spawn shapes — the distributions, asked as distributions
+// ============================================================================
+
+namespace {
+
+// A cheap deterministic uniform, so a failure is a bug and never a seed.
+struct Lcg {
+ u32 s = 12345u;
+ f32 operator()(f32 a, f32 b) {
+ s = s * 1664525u + 1013904223u;
+ return a + (b - a) * (static_cast<f32>((s >> 8) & 0xFFFFFFu) / 16777216.0f);
+ }
+};
+
+ecs::ParticleEmitter emitterWith(ecs::EmitterShape shape) {
+ ecs::ParticleEmitter e{};
+ e.shape = static_cast<i32>(shape);
+ e.shapeRadius = 100.0f;
+ e.shapeAngle = 30.0f;
+ return e;
+}
+
+constexpr u32 kSamples = 60000;
+
+} // namespace
+
+TEST_CASE("sphere_directions_have_no_polar_bias") {
+ Lcg rng;
+ auto e = emitterWith(ecs::EmitterShape::Sphere);
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+
+ // Six axis-aligned half-spaces. Uniform directions put half the samples in
+ // each, and a latitude/longitude parameterisation does not: it crowds the
+ // poles, which shows up as +Y/-Y holding more than their share.
+ u32 pos[3] = {0, 0, 0};
+ // Equal-area bands about the polar axis. Splitting the FULL range of y into
+ // four equal slabs is the sharper question: a pole-crowding sampler fills the
+ // outer slabs and starves the middle ones even while the halves stay even.
+ u32 band[4] = {0, 0, 0, 0};
+ for (u32 i = 0; i < kSamples; ++i) {
+ const glm::vec3 d = sampleShape(e, rand).direction;
+ CHECK(std::abs(glm::length(d) - 1.0f) < 1e-3f);
+ if (d.x > 0.0f) ++pos[0];
+ if (d.y > 0.0f) ++pos[1];
+ if (d.z > 0.0f) ++pos[2];
+ band[std::min(3, static_cast<i32>((d.y + 1.0f) * 2.0f))]++;
+ }
+ const f32 half = static_cast<f32>(kSamples) * 0.5f;
+ for (u32 axis : pos) CHECK(std::abs(static_cast<f32>(axis) - half) < half * 0.03f);
+ const f32 quarter = static_cast<f32>(kSamples) * 0.25f;
+ for (u32 b : band) CHECK(std::abs(static_cast<f32>(b) - quarter) < quarter * 0.05f);
+}
+
+TEST_CASE("hemisphere_stays_in_its_half_and_is_not_a_flat_circle") {
+ Lcg rng;
+ auto e = emitterWith(ecs::EmitterShape::Hemisphere);
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+
+ u32 offAxis = 0; // any real depth at all — a Circle would have none
+ f32 sumY = 0.0f;
+ for (u32 i = 0; i < kSamples; ++i) {
+ const glm::vec3 d = sampleShape(e, rand).direction;
+ CHECK(d.y >= -1e-4f); // the +Y half, and nothing outside it
+ if (std::abs(d.z) > 0.05f) ++offAxis;
+ sumY += d.y;
+ }
+ // A hemisphere that quietly degenerated into a ring in the XY plane would put
+ // every sample at z == 0; a real one spreads through the third dimension.
+ CHECK(offAxis > kSamples / 3);
+ // Mean height of a uniform hemisphere is 1/2. A ring would read ~0.64, a
+ // cosine-weighted lobe ~0.67 — both far outside this window.
+ CHECK(std::abs(sumY / static_cast<f32>(kSamples) - 0.5f) < 0.02f);
+}
+
+TEST_CASE("cone_is_a_solid_angle_about_local_up") {
+ Lcg rng;
+ auto e = emitterWith(ecs::EmitterShape::Cone);
+ e.shapeAngle = 30.0f; // half-angle 15 degrees
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+
+ const f32 cosHalf = std::cos(15.0f * math::DEG_TO_RAD);
+ u32 offAxis = 0;
+ for (u32 i = 0; i < kSamples; ++i) {
+ const glm::vec3 d = sampleShape(e, rand).direction;
+ CHECK(d.y >= cosHalf - 1e-3f); // inside the cap, about +Y
+ if (std::abs(d.z) > 0.02f) ++offAxis;
+ }
+ // A planar fan would leave z at zero for every sample.
+ CHECK(offAxis > kSamples / 4);
+}
+
+TEST_CASE("point_and_box_keep_the_planar_aim_2d_content_authored") {
+ Lcg rng;
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+ for (auto shape : {ecs::EmitterShape::Point, ecs::EmitterShape::Box}) {
+ auto e = emitterWith(shape);
+ e.angleSpreadMin = 90.0f;
+ e.angleSpreadMax = 90.0f;
+ const glm::vec3 d = sampleShape(e, rand).direction;
+ // 90 degrees in the local plane is +Y, exactly where it always pointed.
+ CHECK(d.y > 0.999f);
+ CHECK(std::abs(d.z) < 1e-5f);
+ }
+}
+
+TEST_CASE("box_fills_its_volume_and_a_flat_one_stays_flat") {
+ Lcg rng;
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+ auto e = emitterWith(ecs::EmitterShape::Box);
+ e.shapeSize = glm::vec3(200.0f, 100.0f, 0.0f);
+ for (u32 i = 0; i < 2000; ++i) {
+ const glm::vec3 p = sampleShape(e, rand).position;
+ CHECK(std::abs(p.x) <= 100.0f);
+ CHECK(std::abs(p.y) <= 50.0f);
+ CHECK(p.z == 0.0f); // a depthless box is the rectangle 2D always had
+ }
+ e.shapeSize.z = 60.0f;
+ u32 withDepth = 0;
+ for (u32 i = 0; i < 2000; ++i) {
+ if (std::abs(sampleShape(e, rand).position.z) > 1.0f) ++withDepth;
+ }
+ CHECK(withDepth > 1800);
+}
+
+// ============================================================================
+// The emitter's own frame
+// ============================================================================
+
+TEST_CASE("a rotated emitter carries its cone with it") {
+ Lcg rng;
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+ auto e = emitterWith(ecs::EmitterShape::Cone);
+ e.shapeAngle = 20.0f;
+
+ // 90 degrees about X takes local +Y onto world +Z. An emitter whose rotation
+ // is read as a single angle about the view axis cannot express this at all:
+ // it would keep firing along +Y however the emitter is turned.
+ const EmitterFrame turned{glm::vec3(0.0f),
+ glm::angleAxis(math::HALF_PI, glm::vec3(1.0f, 0.0f, 0.0f)),
+ glm::vec3(1.0f)};
+ const EmitterFrame still{};
+
+ glm::vec3 meanStill(0.0f), meanTurned(0.0f);
+ for (u32 i = 0; i < kSamples; ++i) {
+ meanStill += worldDirOf(sampleShape(e, rand).direction, still);
+ meanTurned += worldDirOf(sampleShape(e, rand).direction, turned);
+ }
+ meanStill /= static_cast<f32>(kSamples);
+ meanTurned /= static_cast<f32>(kSamples);
+
+ CHECK(meanStill.y > 0.97f); // unturned: up
+ CHECK(meanTurned.z > 0.97f); // turned: along +Z
+ CHECK(std::abs(meanTurned.y) < 0.03f); // and nothing left pointing up
+}
+
+TEST_CASE("scale sizes the shape and leaves the aim alone") {
+ Lcg rng;
+ std::function<f32(f32, f32)> rand = [&](f32 a, f32 b) { return rng(a, b); };
+ auto e = emitterWith(ecs::EmitterShape::Box);
+ e.shapeSize = glm::vec3(100.0f, 100.0f, 100.0f);
+ const EmitterFrame big{glm::vec3(7.0f, 0.0f, 0.0f), glm::quat(1, 0, 0, 0), glm::vec3(3.0f)};
+
+ f32 maxExtent = 0.0f;
+ for (u32 i = 0; i < 4000; ++i) {
+ const SpawnSample s = sampleShape(e, rand);
+ const glm::vec3 w = worldPointOf(s.position, big);
+ maxExtent = std::max(maxExtent, std::abs(w.x - big.position.x));
+ // Translation must not reach the aim, or where the emitter STANDS would
+ // decide which way its particles fly.
+ CHECK(std::abs(glm::length(worldDirOf(s.direction, big)) - 1.0f) < 1e-4f);
+ }
+ CHECK(maxExtent > 140.0f); // 50 * 3 = 150, so a scaled box is really bigger
+ CHECK(maxExtent <= 150.1f);
+}