Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ParticleSystem.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4
5#include "../core/Types.hpp"
6#include "../math/Math.hpp"
7#include "../ecs/Registry.hpp"
12#include "Particle.hpp"
13#include "ParticleBursts.hpp"
14#include "ParticleEasing.hpp"
15#include "ParticleShapes.hpp"
16
17#include <unordered_map>
18#include <unordered_set>
19#include <functional>
20#include <random>
21#include <array>
22#include <algorithm>
24
25namespace esengine { class RandomSource; }
26
27namespace esengine::particle {
28
29// Resolution of the per-emitter over-life lookup tables (baked in TS from a
30// gradient/curve, sampled here per particle). 32 keeps them smooth and small.
31ES_CONST(ts=GRADIENT_LUT_SIZE)
32inline constexpr int kColorLutSize = 32;
33using ColorLut = std::array<glm::vec4, kColorLutSize>;
34// Size-over-life: a scalar multiplier curve × the particle's start size.
35using SizeLut = std::array<f32, kColorLutSize>;
36
37// Hard cap on a per-particle trail's recorded points (the ribbon has one segment
38// less). Bounds the per-emitter history buffer; the component's trailPoints picks
39// how many of these to actually keep.
40inline constexpr int kMaxTrailPoints = 12;
41
42// A scene force field flattened to what the per-particle inner loop needs, gathered
43// once per update() so the hot loop touches no components.
45 i32 type = 0;
46 glm::vec3 position{0.0f};
47 glm::vec3 direction{1.0f, 0.0f, 0.0f}; // pre-normalized (Directional only)
48 f32 strength = 0.0f;
49 f32 radius = 0.0f; // 0 = unbounded
50 f32 radiusSq = 0.0f;
51 bool falloff = true;
52};
53
54// A scene ParticleCollider flattened to what a distance function needs, gathered once per update(). The GPU kernel
55// reads the same record: three vec4s and four words, so the layout is the same in both languages.
57 glm::vec3 position{0.0f};
58 f32 shape = 0.0f;
59 glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};
60 f32 ext[3] = {0.0f, 0.0f, 0.0f}; // sphere: radius. box: half extents. capsule: radius, half height.
61 f32 inverted = 0.0f;
62 u32 mask = 0xffffu;
63 u32 pad[3] = {0, 0, 0};
64};
65
66f32 sdfDistance(const SdfColliderInstance& c, const glm::vec3& point);
67
68// Fixed-width batch records shared by Web and native heaps. Integers keep their
69// bits (including generational entity IDs); they are not converted through float.
75 u32 status, body; // 0 miss, 1 hit, 2 backend unavailable
76 f32 x, y, z, nx, ny, nz;
77};
87static_assert(sizeof(CollisionQuery) == 40 && sizeof(CollisionReply) == 32);
88static_assert(sizeof(CollisionEvent) == 56 && sizeof(CollisionStats) == 40);
89
91struct GpuStep {
92 f32 dt = 0.0f;
93 f32 noiseTime = 0.0f;
99 bool reset = false;
100 bool fed = false;
101};
102
110 // Monotonic clock for the noise field's scroll — advances every update
111 // regardless of play/stop so the turbulence never snaps when emission pauses.
113 bool playing = false;
114 bool first_update = true;
115
116 // Per-particle trail history, keyed by pool index and only sized once an emitter
117 // enables trails (free otherwise). trail_pos is a flat [capacity × kMaxTrailPoints]
118 // ring of raw particle-space positions (oldest→newest); trail_count is how many
119 // slots each particle has filled.
120 std::vector<glm::vec3> trail_pos;
121 std::vector<u8> trail_count;
122
124
125 // GPU simulation: the emitter keeps its schedule here (rate, bursts, duration) and the particles live in
126 // a GPU ring this state only counts. The pool stays empty, so a million-particle emitter costs no heap.
127 bool gpu = false;
129 f32 gpuDt = 0.0f;
132 bool gpuReset = false;
133 bool gpuFed = false;
134
135 explicit EmitterState(u32 capacity) : pool(capacity) {}
136};
137
139public:
141 static constexpr const char* kRandomStream = "particles";
142
144
147 void reseedFrom(const esengine::RandomSource& source);
148
149 void update(ecs::Registry& registry, f32 dt);
150
153 void setGpuAvailable(bool available) { gpu_available_ = available; }
154 bool gpuAvailable() const { return gpu_available_; }
155 static constexpr u32 kGpuMaxCapacity = 2'000'000;
156 static constexpr u32 kGpuFallbackCapacity = 20'000;
157
161 bool peekGpuStep(Entity entity, GpuStep& out) const;
163 void commitGpuStep(Entity entity, const GpuStep& step);
164 const std::vector<ForceFieldInstance>& forceFields() const { return force_fields_; }
165 const std::vector<SdfColliderInstance>& sdfColliders() const { return sdf_colliders_; }
166
168 void addGpuCollisions(Entity entity, u32 total, const CollisionEvent* events, u32 count);
169
170 // update() integrates; resolveCollisions() completes all queries in this same
171 // frame before rendering. No reply survives into the next update.
172 const std::vector<CollisionQuery>& collisionQueries() const { return collision_queries_; }
173 const std::vector<CollisionEvent>& collisionEvents() const { return collision_events_; }
174 const std::vector<CollisionStats>& collisionStats() const { return collision_stats_; }
175 void setCollisionBudget(u32 queries, u32 events, bool debug = false) {
176 collision_debug_ = debug;
177 query_budget_ = std::min(queries, 65536u); event_budget_ = std::min(events, 16384u);
178 }
179 void resolveCollisions(ecs::Registry& registry, const CollisionReply* replies, u32 count);
180
181 void play(Entity entity);
182 void stop(Entity entity);
183 void reset(Entity entity);
184
185 u32 aliveCount(Entity entity) const;
186
196 u32 emitAt(ecs::Registry& registry, Entity entity, u32 count, const glm::vec3& position,
197 const glm::vec3& normal, const glm::vec3& velocity);
198 u32 totalAliveParticles() const;
199 void setParticleLimit(u32 limit) { particle_limit_ = limit; }
200
201 template<typename Fn>
202 void forEachParticle(Entity entity, Fn&& fn) const {
203 auto it = states_.find(entity);
204 if (it != states_.end()) it->second.pool.forEachAlive(fn);
205 }
206
208 const EmitterState* getState(Entity entity) const;
209
212 void setColorLut(Entity entity, const f32* rgba, i32 count);
214 void setSizeLut(Entity entity, const f32* values, i32 count);
215
219 void setSpeedLut(Entity entity, const f32* values, i32 count);
220
223 void setBursts(Entity entity, const f32* values, i32 count);
224
226 const ColorLut* colorLut(Entity entity) const { auto it = colorLuts_.find(entity); return it == colorLuts_.end() ? nullptr : &it->second; }
227 const SizeLut* sizeLut(Entity entity) const { auto it = sizeLuts_.find(entity); return it == sizeLuts_.end() ? nullptr : &it->second; }
228 const SizeLut* speedLut(Entity entity) const { auto it = speedLuts_.find(entity); return it == speedLuts_.end() ? nullptr : &it->second; }
229
230private:
231 void emitParticles(const ecs::ParticleEmitter& emitter,
232 const ecs::Transform& transform,
233 EmitterState& state, u32 count);
234
235 // Shared spawn core: seed `count` particles into `state` from `emitter`'s
236 // config at `frame`, adding `velocityBias` to each (a sub-emitter burst
237 // inherits the parent particle's motion that way).
238 // `allowBirthTrigger` records Birth events for a nested sub-emitter; false for a
239 // sub-burst's own spawn so a drain can't re-enter the request buffer it's reading.
240 void emitInto(const ecs::ParticleEmitter& emitter, EmitterState& state,
241 const EmitterFrame& frame, bool isWorldSpace,
242 glm::vec3 velocityBias, u32 count, bool allowBirthTrigger, u32 depth = 0,
243 const EmitterFrame* storageFrame = nullptr);
244
245 // Fire the referenced child emitter's burst at each pending sub-emit request.
246 void drainSubEmitters(ecs::Registry& registry, Entity parent, Entity child,
247 f32 inheritVelocity, f32 chance);
248
249 void updateParticles(const ecs::ParticleEmitter& emitter, EmitterState& state, f32 dt,
250 const ColorLut* colorLut, const SizeLut* sizeLut,
251 const SizeLut* speedLut,
252 const EmitterFrame& frame, bool isWorldSpace);
253 void collisionStep(const ecs::ParticleEmitter&, EmitterState&, Particle&, glm::vec3 from,
254 const EmitterFrame&, bool world);
255 void collide(const ecs::ParticleEmitter&, EmitterState&, Particle&, glm::vec3 point,
256 glm::vec3 normal, u32 body, const EmitterFrame&, bool world);
257 void floorCollision(const ecs::ParticleEmitter&, EmitterState&, Particle&, const EmitterFrame&, bool world);
258 void sdfCollision(const ecs::ParticleEmitter&, EmitterState&, Particle&, const EmitterFrame&, bool world);
259 f32 randomRange(f32 min, f32 max);
260 u32 collisionQuota(Entity emitter) const;
261
262
263
264 // A parent particle's birth/death position + velocity, queued during a parent's
265 // update and drained into its child sub-emitter right after.
266 struct SubEmitRequest { glm::vec3 position; glm::vec3 velocity; u32 depth = 0; };
267 std::vector<SubEmitRequest> subemit_requests_;
268
269 struct PendingCollision { Entity emitter; u32 generation; EmitterFrame frame; bool world; std::size_t stats; };
270 std::vector<CollisionQuery> collision_queries_;
271 std::vector<PendingCollision> collision_pending_;
272 std::vector<CollisionEvent> collision_events_;
273 std::vector<CollisionStats> collision_stats_;
274 std::vector<glm::vec3> collision_cameras_;
275 Entity collision_emitter_{};
276 std::size_t collision_stats_index_ = 0;
277 u32 query_budget_ = 4096, event_budget_ = 1024, event_attempts_ = 0;
278 u32 collision_child_bursts_ = 0;
279 u32 collision_frame_ = 0;
280 bool collision_debug_ = false;
281 std::unordered_map<Entity, u32> collision_quotas_;
282 std::vector<Entity> scene_emitters_;
283 std::vector<SubEmitRequest> drain_scratch_;
284 std::unordered_map<Entity, EmitterState> states_;
285 // A play() that arrives before the emitter's first update (its state isn't
286 // created yet) is remembered here and applied on state creation, not dropped.
287 std::unordered_set<Entity> pending_play_;
288 std::unordered_map<Entity, ColorLut> colorLuts_;
289 std::unordered_map<Entity, SizeLut> sizeLuts_;
290 std::unordered_map<Entity, SizeLut> speedLuts_;
291 std::unordered_map<Entity, std::vector<ScheduledBurst>> burstSchedules_;
292 std::mt19937 rng_;
293 bool gpu_available_ = false;
294 u32 particle_limit_ = 0xffffffffu;
295 std::vector<u32> dead_particle_indices_;
296 // Active scene force fields, rebuilt each update() and applied to world-space
297 // particles during integration.
298 std::vector<ForceFieldInstance> force_fields_;
299 std::vector<SdfColliderInstance> sdf_colliders_;
300 struct GpuCollisions { Entity entity; u32 total; std::vector<CollisionEvent> events; };
301 std::vector<GpuCollisions> gpu_collisions_;
302 // RAII: auto-unregisters from the registry's onDestroy when this system is
303 // destroyed, so a torn-down system never leaves a dangling `this` behind.
304 Connection destroyConn_;
305};
306
307} // namespace esengine::particle
Math utilities and GLM configuration for ESEngine.
A shape particles bounce off without any physics: a signed distance a compute kernel can answer per p...
A scene-placed force zone that pushes every world-space particle near it.
Where a particle is born and which way it leaves — a pure function of the emitter's own configuration...
Reflection and metadata system for automatic binding generation.
#define ES_CONST(...)
Mark a constant that CROSSES the boundary, so EHT emits its TS twin.
Central ECS registry for entity and component management.
Unified Transform component with local and world-space data.
Core type definitions and utilities for ESEngine.
Central container for all entities and components.
Definition Registry.hpp:73
const SizeLut * speedLut(Entity entity) const
void setSizeLut(Entity entity, const f32 *values, i32 count)
EmitterState * getState(Entity entity)
void forEachParticle(Entity entity, Fn &&fn) const
void update(ecs::Registry &registry, f32 dt)
const std::vector< ForceFieldInstance > & forceFields() const
const std::vector< SdfColliderInstance > & sdfColliders() const
const std::vector< CollisionStats > & collisionStats() const
void setBursts(Entity entity, const f32 *values, i32 count)
const std::vector< CollisionQuery > & collisionQueries() const
static constexpr u32 kGpuFallbackCapacity
void reseedFrom(const esengine::RandomSource &source)
const SizeLut * sizeLut(Entity entity) const
u32 aliveCount(Entity entity) const
void addGpuCollisions(Entity entity, u32 total, const CollisionEvent *events, u32 count)
Collisions a kernel reported, a frame or two late since they come back from the GPU; they reach the g...
u32 emitAt(ecs::Registry &registry, Entity entity, u32 count, const glm::vec3 &position, const glm::vec3 &normal, const glm::vec3 &velocity)
Spawn count of entity's particles at a world point, now: an impact's sparks, a muzzle's flash,...
void resolveCollisions(ecs::Registry &registry, const CollisionReply *replies, u32 count)
void commitGpuStep(Entity entity, const GpuStep &step)
The kernel ran this step: the time and births it covered are spent.
const std::vector< CollisionEvent > & collisionEvents() const
static constexpr const char * kRandomStream
const ColorLut * colorLut(Entity entity) const
The over-life curves an entity was given, for the GPU kernel to read; null where none was set.
bool peekGpuStep(Entity entity, GpuStep &out) const
void setCollisionBudget(u32 queries, u32 events, bool debug=false)
void setSpeedLut(Entity entity, const f32 *values, i32 count)
void setColorLut(Entity entity, const f32 *rgba, i32 count)
constexpr int kColorLutSize
f32 sdfDistance(const SdfColliderInstance &c, const glm::vec3 &point)
How far a world point is outside a collider, negative inside; what the kernel's sdfOne answers.
std::array< f32, kColorLutSize > SizeLut
constexpr int kMaxTrailPoints
std::array< glm::vec4, kColorLutSize > ColorLut
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
Unified transform component.
Definition Transform.hpp:45
std::vector< glm::vec3 > trail_pos
f32 burst_clock
Where the scheduled bursts last looked: the emitting clock of the previous step, below zero before th...
What one frame asks of a GPU-simulated emitter: how long to advance, how many to spawn and where in t...
bool fed
A GPU parent's events spawn into it, so any slot may be live whatever was scheduled.
u32 firstIndex
Absolute index of the first particle born this step (slot = index % capacity).
u32 spawnCount
Born this step: smoothCount spread across dt, then the rest as one burst.
bool reset
Kill everything first (a reset() since the last step).
u32 drawCount
Slots that may hold a live particle once this step has run.