Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ParticleSystem.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "ParticleSystem.hpp"
4#include "ParticleNoise.hpp"
5
6#include <algorithm>
7#include <chrono>
8#include <cmath>
9
13
14namespace esengine::particle {
15
18
20 rng_ = source.stream(kRandomStream);
21}
22
23void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
24 collision_queries_.clear(); collision_pending_.clear(); collision_events_.clear();
25 collision_stats_.clear(); collision_cameras_.clear();
26 event_attempts_ = 0; collision_child_bursts_ = 0;
27 if (!std::isfinite(frameDt) || frameDt < 0) return;
28 auto cameras = registry.activeView<ecs::Camera, ecs::Transform>();
29 for (auto entity : cameras) {
30 if (!cameras.get<ecs::Camera>(entity).isActive) continue;
31 auto& transform = cameras.get<ecs::Transform>(entity);
32 transform.ensureDecomposed();
33 collision_cameras_.push_back(transform.worldPosition);
34 }
35 if (!destroyConn_.isConnected()) {
36 destroyConn_ = registry.onDestroy([this](Entity entity) {
37 states_.erase(entity);
38 pending_play_.erase(entity);
39 colorLuts_.erase(entity);
40 sizeLuts_.erase(entity);
41 speedLuts_.erase(entity);
42 burstSchedules_.erase(entity);
43 });
44 }
45
46 // Flatten the active force fields once so the per-particle loop touches no
47 // components. Fields are world objects, applied to world-space particles.
48 force_fields_.clear();
49 auto ffView = registry.activeView<ecs::Transform, ecs::ParticleForceField>();
50 for (auto ffEntity : ffView) {
51 const auto& ff = ffView.get<ecs::ParticleForceField>(ffEntity);
52 if (!ff.enabled || ff.strength == 0.0f) continue;
53 auto& ffTransform = ffView.get<ecs::Transform>(ffEntity);
54 ffTransform.ensureDecomposed();
55 f32 dl = std::sqrt(ff.direction.x * ff.direction.x + ff.direction.y * ff.direction.y
56 + ff.direction.z * ff.direction.z);
58 inst.type = ff.type;
59 inst.position = ffTransform.worldPosition;
60 inst.direction = dl > 1e-6f ? ff.direction / dl : glm::vec3(1.0f, 0.0f, 0.0f);
61 inst.strength = ff.strength;
62 inst.radius = ff.radius;
63 inst.radiusSq = ff.radius * ff.radius;
64 inst.falloff = ff.falloff;
65 force_fields_.push_back(inst);
66 }
67
68 sdf_colliders_.clear();
69 auto colliderView = registry.activeView<ecs::Transform, ecs::ParticleCollider>();
70 for (auto colliderEntity : colliderView) {
71 const auto& collider = colliderView.get<ecs::ParticleCollider>(colliderEntity);
72 if (!collider.enabled) continue;
73 auto& colliderTransform = colliderView.get<ecs::Transform>(colliderEntity);
74 colliderTransform.ensureDecomposed();
75 const glm::vec3 scale = colliderTransform.worldScale;
77 inst.position = colliderTransform.worldPosition;
78 inst.rotation = colliderTransform.worldRotation;
79 inst.shape = static_cast<f32>(collider.shape);
80 inst.inverted = collider.inverted ? 1.0f : 0.0f;
81 inst.mask = collider.mask & 0xffffu;
82 // A distance function cannot be stretched and stay one, so a round shape takes the largest of its scale.
83 const f32 round = std::max({std::abs(scale.x), std::abs(scale.y), std::abs(scale.z)});
84 if (collider.shape == static_cast<i32>(ecs::ParticleColliderShape::Box)) {
85 inst.ext[0] = collider.halfExtents.x * std::abs(scale.x);
86 inst.ext[1] = collider.halfExtents.y * std::abs(scale.y);
87 inst.ext[2] = collider.halfExtents.z * std::abs(scale.z);
88 } else {
89 inst.ext[0] = collider.radius * round;
90 inst.ext[1] = collider.halfHeight * std::abs(scale.y);
91 }
92 sdf_colliders_.push_back(inst);
93 }
94
95 auto view = registry.activeView<ecs::Transform, ecs::ParticleEmitter>();
96 // A GPU parent's events feed its child in the kernel; the child cannot know how many slots that lights.
97 for (auto& [stateEntity, childState] : states_) childState.gpuFed = false;
98 for (auto parentEntity : view) {
99 const auto& parent = view.get<ecs::ParticleEmitter>(parentEntity);
100 if (parent.subEmitter == 0 || !parent.enabled) continue;
101 auto parentState = states_.find(parentEntity), childState = states_.find(Entity::fromRaw(parent.subEmitter));
102 if (parentState != states_.end() && childState != states_.end() && parentState->second.gpu && childState->second.gpu) {
103 childState->second.gpuFed = true;
104 }
105 }
106 // Share the App cap across active scene emitters. Rotate remainder slots so
107 // a budget smaller than the emitter count never permanently starves a tail.
108 collision_quotas_.clear();
109 scene_emitters_.clear();
110 for (auto entity : view) {
111 const auto& e = view.get<ecs::ParticleEmitter>(entity);
112 if (e.enabled && e.collisionEnabled && e.collisionMode != 0) scene_emitters_.push_back(entity);
113 }
114 const u32 n = static_cast<u32>(scene_emitters_.size());
115 for (u32 i = 0; i < n; ++i) {
116 const u32 rank = (i + n - collision_frame_ % n) % n;
117 collision_quotas_[scene_emitters_[i]] = query_budget_ / n + (rank < query_budget_ % n ? 1u : 0u);
118 }
119 ++collision_frame_;
120 for (auto entity : view) {
121 const auto& emitter = view.get<ecs::ParticleEmitter>(entity);
122 const auto& transform = view.get<ecs::Transform>(entity);
123
124 if (!emitter.enabled) {
125 continue;
126 }
127 // The emitter's own time: it runs at its simulation speed, so everything below (emission, ageing, motion) follows it.
128 const f32 dt = frameDt * std::max(emitter.simulationSpeed, 0.0f);
129
130 // A GPU emitter keeps no pool: its particles live in a GPU ring. Where the device cannot compute it
131 // is an ordinary emitter, capped so a million-particle setup cannot take the CPU down with it.
132 const bool useGpu = emitter.gpuSimulation && gpu_available_;
133 u32 capacity = static_cast<u32>(std::clamp(emitter.maxParticles, 0, 1'000'000));
134 if (emitter.gpuSimulation && !gpu_available_) capacity = std::min(capacity, kGpuFallbackCapacity);
135 if (useGpu) capacity = static_cast<u32>(std::clamp(emitter.maxParticles, 0, static_cast<i32>(kGpuMaxCapacity)));
136
137 auto it = states_.find(entity);
138 if (it != states_.end() && (it->second.gpu != useGpu || (useGpu && it->second.gpuCapacity != capacity))) {
139 // Changed how it simulates (or how big): the schedule carries over, so a burst already spent is not spent
140 // twice. The device is only known once the renderer has run, a frame after the first update, so an emitter
141 // that began on the CPU is moved to the GPU with as many particles as it had alive.
142 EmitterState old = std::move(it->second);
143 states_.erase(it);
144 auto [moved, _] = states_.emplace(entity, EmitterState(useGpu ? 0u : capacity));
145 EmitterState& next = moved->second;
147 next.elapsed_time = old.elapsed_time;
148 next.burst_timer = old.burst_timer;
149 next.burst_clock = old.burst_clock;
150 next.noise_time = old.noise_time;
151 next.playing = old.playing;
152 next.first_update = old.first_update;
153 next.gpu = useGpu;
154 next.gpuCapacity = useGpu ? capacity : 0;
155 if (useGpu) next.gpuBurst = std::min(old.pool.aliveCount(), capacity);
156 it = moved;
157 }
158 if (it == states_.end()) {
159 auto [insertIt, _] = states_.emplace(
160 entity,
161 // Clamp defensively: maxParticles is inspector-constrained (min=1)
162 // but a script, scene file, or replicated value bypasses that — a
163 // negative cast to u32 (or a multi-billion count) would resize the
164 // pool into a bad_alloc.
165 EmitterState(useGpu ? 0u : capacity)
166 );
167 it = insertIt;
168 it->second.gpu = useGpu;
169 it->second.gpuCapacity = useGpu ? capacity : 0;
170 if (emitter.playOnStart) {
171 it->second.playing = true;
172 }
173 // Apply a play() that arrived before this first update (playOnStart=false
174 // + an immediate trigger) instead of dropping it.
175 if (pending_play_.erase(entity) > 0) {
176 it->second.playing = true;
177 it->second.elapsed_time = 0.0f;
178 }
179 }
180
181 auto& state = it->second;
182
183 // Size the per-particle trail history the first time this emitter uses
184 // trails (kept free when they're off). Sized before emission so a spawn
185 // this frame can reset its slot.
186 if (emitter.trailEnabled && state.trail_count.size() != state.pool.capacity()) {
187 state.trail_count.assign(state.pool.capacity(), 0);
188 state.trail_pos.assign(static_cast<std::size_t>(state.pool.capacity()) * kMaxTrailPoints,
189 glm::vec3(0.0f));
190 }
191
192 if (state.first_update && emitter.playOnStart) {
193 state.playing = true;
194 state.first_update = false;
195 }
196
197 // The delay is time the emitter plays without emitting; the duration is counted from its end.
198 const f32 startDelay = std::max(emitter.startDelay, 0.0f);
199 bool emitting = state.playing;
200 if (!emitter.looping && state.elapsed_time >= startDelay + emitter.duration) {
201 emitting = false;
202 }
203
204 // The schedule is one thing whoever runs the particles: a GPU emitter only counts what is born.
205 auto emit = [&](u32 count, bool burst) {
206 if (!state.gpu) { emitParticles(emitter, transform, state, count); return; }
207 u32& pending = burst ? state.gpuBurst : state.gpuSmooth;
208 pending = std::min(pending + count, state.gpuCapacity);
209 };
210
211 if (emitting) {
212 state.elapsed_time += dt;
213 }
214 if (emitting && state.elapsed_time >= startDelay) {
215 if (auto schedule = burstSchedules_.find(entity); schedule != burstSchedules_.end()) {
216 const f32 clock = state.elapsed_time - startDelay;
217 const u32 due = burstsDue(schedule->second, state.burst_clock, clock, emitter.duration, emitter.looping);
218 state.burst_clock = clock;
219 if (due > 0) emit(due, true);
220 }
221 if (emitter.rate > 0.0f) {
222 state.emission_accumulator += emitter.rate * dt;
223 u32 toEmit = static_cast<u32>(state.emission_accumulator);
224 if (toEmit > 0) {
225 state.emission_accumulator -= static_cast<f32>(toEmit);
226 emit(toEmit, false);
227 }
228 }
229
230 if (emitter.burstCount > 0) {
231 if (state.burst_timer <= 0.0f) {
232 emit(static_cast<u32>(emitter.burstCount), true);
233 state.burst_timer = emitter.burstInterval;
234 }
235 state.burst_timer -= dt;
236 }
237 }
238
239 if (state.gpu) {
240 // The kernel does what updateParticles would; this side only keeps the clocks it needs.
241 state.noise_time += dt;
242 state.gpuDt += dt;
243 if (emitter.collisionEnabled) {
244 CollisionStats stats; stats.emitter = entity.raw;
245 stats.mode = static_cast<u32>(emitter.collisionMode);
246 for (const GpuCollisions& reported : gpu_collisions_) {
247 if (reported.entity != entity) continue;
248 stats.hits += reported.total;
249 stats.events += static_cast<u32>(reported.events.size());
250 stats.eventDropped += reported.total - static_cast<u32>(reported.events.size());
251 collision_events_.insert(collision_events_.end(), reported.events.begin(), reported.events.end());
252 }
253 collision_stats_.push_back(stats);
254 }
255 continue;
256 }
257
258 const EmitterFrame frame{transform.worldPosition, transform.worldRotation,
259 transform.worldScale};
260 bool isWorldSpace = emitter.simulationSpace ==
261 static_cast<i32>(ecs::SimulationSpace::World);
262
263 collision_emitter_ = entity;
264 collision_stats_index_ = collision_stats_.size();
265 if (emitter.collisionEnabled) {
266 CollisionStats stats; stats.emitter = entity.raw;
267 stats.mode = static_cast<u32>(emitter.collisionMode);
268 collision_stats_.push_back(stats);
269 }
270 auto lutIt = colorLuts_.find(entity);
271 auto sizeIt = sizeLuts_.find(entity);
272 auto speedIt = speedLuts_.find(entity);
273 updateParticles(emitter, state, dt,
274 lutIt != colorLuts_.end() ? &lutIt->second : nullptr,
275 sizeIt != sizeLuts_.end() ? &sizeIt->second : nullptr,
276 speedIt != speedLuts_.end() ? &speedIt->second : nullptr,
277 frame, isWorldSpace);
278
279 if (state.pool.capacity() > 0) {
280 const u32 step = std::max(1u, std::min(static_cast<u32>(std::clamp(emitter.collisionQueryBudget, 0, 4096)), collisionQuota(entity)));
281 state.collisionCursor = (state.collisionCursor + step) % std::max(1u,state.pool.aliveCount());
282 }
283
284 // Fire the child sub-emitter's burst at every birth/death queued this frame.
285 if (emitter.subEmitter != 0 && !subemit_requests_.empty()) {
286 drainSubEmitters(registry, entity, Entity::fromRaw(emitter.subEmitter),
287 emitter.subEmitterInheritVelocity, emitter.subEmitterChance);
288 }
289 }
290 gpu_collisions_.clear();
291}
292
294 auto it = states_.find(entity);
295 if (it != states_.end()) {
296 it->second.playing = true;
297 it->second.elapsed_time = 0.0f;
298 } else {
299 // State is created lazily on the first update; remember the trigger so it
300 // isn't lost when play() runs before this emitter's first update.
301 pending_play_.insert(entity);
302 }
303}
304
306 pending_play_.erase(entity);
307 auto it = states_.find(entity);
308 if (it != states_.end()) {
309 it->second.playing = false;
310 }
311}
312
314 pending_play_.erase(entity);
315 auto it = states_.find(entity);
316 if (it != states_.end()) {
317 it->second.pool.clear();
318 if (it->second.gpu) {
319 it->second.gpuSmooth = it->second.gpuBurst = it->second.gpuSpawned = 0;
320 it->second.gpuDt = 0.0f;
321 it->second.gpuReset = true;
322 }
323 it->second.emission_accumulator = 0.0f;
324 it->second.elapsed_time = 0.0f;
325 it->second.burst_timer = 0.0f;
326 it->second.burst_clock = -1.0f;
327 it->second.playing = false;
328 }
329}
330
331void ParticleSystem::setColorLut(Entity entity, const f32* rgba, i32 count) {
332 if (count != kColorLutSize || rgba == nullptr) {
333 colorLuts_.erase(entity); // 0 (or a mismatched bake) clears → fall back to start/end
334 return;
335 }
336 ColorLut& lut = colorLuts_[entity];
337 for (std::size_t i = 0; i < kColorLutSize; ++i) {
338 lut[i] = glm::vec4(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2], rgba[i * 4 + 3]);
339 }
340}
341
342void ParticleSystem::setSizeLut(Entity entity, const f32* values, i32 count) {
343 if (count != kColorLutSize || values == nullptr) {
344 sizeLuts_.erase(entity);
345 return;
346 }
347 SizeLut& lut = sizeLuts_[entity];
348 for (std::size_t i = 0; i < kColorLutSize; ++i) lut[i] = values[i];
349}
350
351void ParticleSystem::setSpeedLut(Entity entity, const f32* values, i32 count) {
352 if (count != kColorLutSize || values == nullptr) {
353 speedLuts_.erase(entity);
354 return;
355 }
356 SizeLut& lut = speedLuts_[entity];
357 for (std::size_t i = 0; i < kColorLutSize; ++i) lut[i] = values[i];
358}
359
360void ParticleSystem::setBursts(Entity entity, const f32* values, i32 count) {
361 if (count <= 0 || values == nullptr) {
362 burstSchedules_.erase(entity);
363 return;
364 }
365 std::vector<ScheduledBurst>& schedule = burstSchedules_[entity];
366 schedule.clear();
367 for (i32 i = 0; i < count && i < 64; ++i) {
368 schedule.push_back({values[i * 2], static_cast<u32>(std::max(values[i * 2 + 1], 0.0f))});
369 }
370}
371
373 auto it = states_.find(entity);
374 if (it != states_.end()) {
375 // The GPU keeps the truth; what this side can say is how many slots have ever held one, an upper bound.
376 if (it->second.gpu) return std::min(it->second.gpuSpawned, it->second.gpuCapacity);
377 return it->second.pool.aliveCount();
378 }
379 return 0;
380}
381
383 auto it = states_.find(entity);
384 if (it == states_.end() || !it->second.gpu) return false;
385 const EmitterState& state = it->second;
386 out = {};
387 out.capacity = state.gpuCapacity;
388 // A frame that went long (a stall, a hidden tab) is not simulated as one huge step.
389 out.dt = std::min(state.gpuDt, 0.1f);
390 out.noiseTime = state.noise_time;
391 out.reset = state.gpuReset;
392 out.smoothCount = std::min(state.gpuSmooth, state.gpuCapacity);
393 out.spawnCount = std::min(out.smoothCount + state.gpuBurst, state.gpuCapacity);
394 out.firstIndex = state.gpuSpawned;
395 out.drawCount = std::min(state.gpuSpawned + out.spawnCount, state.gpuCapacity);
396 out.fed = state.gpuFed;
397 if (state.gpuFed) out.drawCount = state.gpuCapacity;
398 return true;
399}
400
402 auto it = states_.find(entity);
403 if (it == states_.end() || !it->second.gpu) return;
404 EmitterState& state = it->second;
405 // A stall longer than a step is not replayed, and births past the ring's size were never going to be seen.
406 state.gpuDt = 0.0f;
407 state.gpuSmooth = state.gpuBurst = 0;
408 state.gpuSpawned += step.spawnCount;
409 if (step.reset) state.gpuReset = false;
410}
411
413 u32 total = 0;
414 for (const auto& [_, state] : states_) {
415 total += state.pool.aliveCount();
416 }
417 return total;
418}
419
421 auto it = states_.find(entity);
422 return it != states_.end() ? &it->second : nullptr;
423}
424
426 auto it = states_.find(entity);
427 return it != states_.end() ? &it->second : nullptr;
428}
429
430void ParticleSystem::emitParticles(const ecs::ParticleEmitter& emitter,
431 const ecs::Transform& transform,
432 EmitterState& state, u32 count) {
433 const EmitterFrame frame{transform.worldPosition, transform.worldRotation,
434 transform.worldScale};
435 bool isWorldSpace = emitter.simulationSpace ==
436 static_cast<i32>(ecs::SimulationSpace::World);
437 emitInto(emitter, state, frame, isWorldSpace, glm::vec3(0.0f), count,
438 /*allowBirthTrigger=*/true);
439}
440
441void ParticleSystem::emitInto(const ecs::ParticleEmitter& emitter, EmitterState& state,
442 const EmitterFrame& frame, bool isWorldSpace,
443 glm::vec3 velocityBias, u32 count, bool allowBirthTrigger, u32 depth,
444 const EmitterFrame* storageFrame) {
445 // Record each spawned particle for a Birth-triggered sub-emitter (in world
446 // space, since a sub-burst is a world event).
447 bool recordBirth = allowBirthTrigger &&
448 emitter.subEmitter != 0 &&
449 emitter.subEmitterTrigger ==
451
452 if (particle_limit_ != 0xffffffffu) {
453 const u32 alive = totalAliveParticles();
454 count = std::min(count, alive < particle_limit_ ? particle_limit_ - alive : 0u);
455 }
456 for (u32 i = 0; i < count; ++i) {
457 Particle* p = state.pool.allocate();
458 if (!p) {
459 break;
460 }
461
462 // A reused pool slot must start with an empty trail, not the dead
463 // particle's history.
464 if (emitter.trailEnabled && !state.trail_count.empty()) {
465 auto idx = static_cast<std::size_t>(p - state.pool.particles().data());
466 if (idx < state.trail_count.size()) state.trail_count[idx] = 0;
467 }
468
469 p->lifetime = randomRange(emitter.lifetimeMin, emitter.lifetimeMax);
470 p->age = 0.0f;
471
472 p->start_size = randomRange(emitter.startSizeMin, emitter.startSizeMax);
473 p->end_size = randomRange(emitter.endSizeMin, emitter.endSizeMax);
474 p->size = p->start_size;
475
476 p->start_color = emitter.startColor;
477 p->end_color = emitter.endColor;
478 p->color = p->start_color;
479
480 p->rotation = randomRange(emitter.rotationMin, emitter.rotationMax);
481 p->angular_velocity = randomRange(emitter.angularVelocityMin,
482 emitter.angularVelocityMax);
483
484 // ONE question to the shape, and the simulation asks nothing else: a new
485 // shape cannot teach the integrator a new kind of aim.
486 const SpawnSample sample =
487 sampleShape(emitter, [this](f32 a, f32 b) { return randomRange(a, b); });
488
489 p->position = isWorldSpace ? worldPointOf(sample.position, frame)
490 : sample.position * frame.scale;
491
492 const f32 speed = randomRange(emitter.speedMin, emitter.speedMax);
493 const glm::vec3 dir = isWorldSpace ? worldDirOf(sample.direction, frame)
494 : sample.direction;
495 p->velocity = dir * speed + velocityBias;
496 p->added_velocity = glm::vec3(randomRange(emitter.addedVelocityMin.x, emitter.addedVelocityMax.x),
497 randomRange(emitter.addedVelocityMin.y, emitter.addedVelocityMax.y),
498 randomRange(emitter.addedVelocityMin.z, emitter.addedVelocityMax.z));
499
500 p->sprite_frame = 0;
501 p->subEmitterDepth = depth;
502
503 if (recordBirth) {
504 glm::vec3 worldPos = isWorldSpace ? p->position
505 : frame.position + frame.rotation * p->position;
506 glm::vec3 worldVel = isWorldSpace ? p->velocity : frame.rotation * p->velocity;
507 subemit_requests_.push_back({worldPos, worldVel, p->subEmitterDepth});
508 }
509 if (storageFrame) {
510 const auto inverseRotation = glm::inverse(storageFrame->rotation);
511 p->position = inverseRotation * (p->position - storageFrame->position);
512 p->velocity = inverseRotation * p->velocity;
513 }
514 }
515}
516
517u32 ParticleSystem::emitAt(ecs::Registry& registry, Entity entity, u32 count, const glm::vec3& position,
518 const glm::vec3& normal, const glm::vec3& velocity) {
519 if (count == 0 || !registry.valid(entity) || !registry.has<ecs::ParticleEmitter>(entity)) return 0;
520 const auto& emitter = registry.get<ecs::ParticleEmitter>(entity);
521 if (emitter.gpuSimulation && gpu_available_) return 0;
522 auto it = states_.find(entity);
523 if (it == states_.end()) {
524 it = states_.emplace(entity, EmitterState(static_cast<u32>(std::clamp(emitter.maxParticles, 0, 1'000'000)))).first;
525 }
526 EmitterState& state = it->second;
527 if (state.gpu) return 0;
528
529 glm::quat rotation(1.0f, 0.0f, 0.0f, 0.0f);
530 glm::vec3 scale(1.0f);
531 EmitterFrame storage;
532 if (registry.has<ecs::Transform>(entity)) {
533 const auto& t = registry.get<ecs::Transform>(entity);
534 rotation = t.worldRotation;
535 scale = t.worldScale;
536 storage = {t.worldPosition, t.worldRotation, t.worldScale};
537 }
538 const f32 n = glm::length(normal);
539 if (n > 1e-6f) {
540 // The shortest turn from +Y onto the normal; straight down is a half turn about X.
541 const glm::vec3 to = normal / n;
542 const f32 d = glm::dot(glm::vec3(0.0f, 1.0f, 0.0f), to);
543 if (d < -0.9999f) rotation = glm::quat(0.0f, 1.0f, 0.0f, 0.0f);
544 else {
545 const glm::vec3 axis = glm::cross(glm::vec3(0.0f, 1.0f, 0.0f), to);
546 rotation = glm::normalize(glm::quat(1.0f + d, axis.x, axis.y, axis.z));
547 }
548 }
549 const bool local = emitter.simulationSpace == static_cast<i32>(ecs::SimulationSpace::Local);
550 const u32 before = state.pool.aliveCount();
551 emitInto(emitter, state, EmitterFrame{position, rotation, scale}, /*isWorldSpace=*/true, velocity, count,
552 /*allowBirthTrigger=*/true, 0, local ? &storage : nullptr);
553 return state.pool.aliveCount() - before;
554}
555
556u32 ParticleSystem::collisionQuota(Entity emitter) const {
557 const auto it = collision_quotas_.find(emitter);
558 return it != collision_quotas_.end() ? it->second : 0u;
559}
560
561void ParticleSystem::drainSubEmitters(ecs::Registry& registry, Entity parent, Entity child,
562 f32 inheritVelocity, f32 chance) {
563 drain_scratch_.clear();
564 drain_scratch_.swap(subemit_requests_);
565
566 if (child == parent || !registry.valid(child) || !registry.has<ecs::ParticleEmitter>(child)) {
567 return; // a deleted/retargeted child just drops its bursts
568 }
569 const auto& childEmitter = registry.get<ecs::ParticleEmitter>(child);
570
571 // The child's own state may not exist yet (it's created lazily when the main
572 // loop reaches it); make it on demand so a burst is never lost.
573 auto it = states_.find(child);
574 if (it == states_.end()) {
575 auto [insertIt, _] = states_.emplace(
576 child, EmitterState(static_cast<u32>(std::clamp(childEmitter.maxParticles, 0, 1'000'000))));
577 it = insertIt;
578 }
579 EmitterState& childState = it->second;
580 EmitterFrame storageFrame;
581 const bool local = childEmitter.simulationSpace == static_cast<i32>(ecs::SimulationSpace::Local);
582 if (local && registry.has<ecs::Transform>(child)) {
583 const auto& transform = registry.get<ecs::Transform>(child);
584 storageFrame = {transform.worldPosition, transform.worldRotation, transform.worldScale};
585 }
586
587 // The child's burstCount sizes each sub-burst (fall back to 1 so a misconfigured
588 // template still shows something).
589 u32 count = childEmitter.burstCount > 0 ? static_cast<u32>(childEmitter.burstCount) : 1;
590 count = std::min(count, childState.pool.capacity());
591 for (const auto& req : drain_scratch_) {
592 if (req.depth >= 8) continue;
593 if (chance < 1.0f && randomRange(0.0f, 1.0f) >= chance) {
594 continue;
595 }
596 // A sub-burst happens where the parent particle died, unrotated and
597 // unscaled: the child's own shape is what aims it, and a particle carries
598 // no orientation to inherit.
599 emitInto(childEmitter, childState, EmitterFrame{req.position, glm::quat(1, 0, 0, 0),
600 glm::vec3(1.0f)}, /*isWorldSpace=*/true,
601 req.velocity * inheritVelocity, count, /*allowBirthTrigger=*/false, req.depth + 1,
602 local ? &storageFrame : nullptr);
603 }
604}
605
606// Sample a baked color-over-life LUT at t∈[0,1] with linear interpolation between
607// the two nearest entries — the editor authors a gradient, TS bakes it to this.
608static glm::vec4 sampleColorLut(const ColorLut& lut, f32 t) {
609 f32 f = std::clamp(t, 0.0f, 1.0f) * static_cast<f32>(kColorLutSize - 1);
610 auto i = static_cast<std::size_t>(f);
611 std::size_t j = std::min(i + 1, static_cast<std::size_t>(kColorLutSize - 1));
612 return math::lerp(lut[i], lut[j], f - static_cast<f32>(i));
613}
614
615static f32 sampleSizeLut(const SizeLut& lut, f32 t) {
616 f32 f = std::clamp(t, 0.0f, 1.0f) * static_cast<f32>(kColorLutSize - 1);
617 auto i = static_cast<std::size_t>(f);
618 std::size_t j = std::min(i + 1, static_cast<std::size_t>(kColorLutSize - 1));
619 return math::lerp(lut[i], lut[j], f - static_cast<f32>(i));
620}
621
622// Fold one force field into a world-space particle's velocity.
623static void applyForceField(const ForceFieldInstance& ff, Particle& p, f32 dt) {
624 glm::vec3 toField = ff.position - p.position; // field ← particle
625 // The zone is a ball: a radius that drops depth pulls on particles a room away.
626 f32 distSq = toField.x * toField.x + toField.y * toField.y + toField.z * toField.z;
627 f32 factor = 1.0f;
628 if (ff.radius > 0.0f) {
629 if (distSq > ff.radiusSq) return; // outside the zone
630 if (ff.falloff) factor = 1.0f - std::sqrt(distSq) / ff.radius;
631 }
632 switch (static_cast<ecs::ForceFieldType>(ff.type)) {
634 p.velocity += ff.direction * (ff.strength * factor * dt);
635 break;
637 f32 d = std::sqrt(distSq);
638 if (d > 1e-4f) p.velocity += (toField / d) * (ff.strength * factor * dt);
639 break;
640 }
642 f32 d = std::sqrt(distSq);
643 if (d > 1e-4f) {
644 glm::vec3 radial = -toField / d; // field → particle
645 // A vortex needs an axis to swirl about, and the field's own
646 // direction is the one it has; world up when it names none.
647 glm::vec3 axis = glm::length(ff.direction) > 1e-6f
648 ? glm::normalize(ff.direction) : glm::vec3(0.0f, 0.0f, 1.0f);
649 glm::vec3 perp = glm::cross(axis, radial);
650 f32 pl = glm::length(perp);
651 if (pl > 1e-6f) p.velocity += (perp / pl) * (ff.strength * factor * dt);
652 }
653 break;
654 }
656 p.velocity *= (1.0f - std::min(ff.strength * factor * dt, 1.0f));
657 break;
658 }
659}
660
661void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
662 EmitterState& state, f32 dt,
663 const ColorLut* colorLut, const SizeLut* sizeLut,
664 const SizeLut* speedLut,
665 const EmitterFrame& frame,
666 bool isWorldSpace) {
667 auto sizeEasing = static_cast<EasingType>(emitter.sizeEasing);
668 auto colorEasing = static_cast<EasingType>(emitter.colorEasing);
669 i32 totalFrames = emitter.spriteColumns * emitter.spriteRows;
670
671 // Record dying particles for a Death-triggered sub-emitter (world space — a
672 // sub-burst is a world event). cos/sin convert a local-space death to world.
673 bool recordDeath = emitter.subEmitter != 0 &&
674 emitter.subEmitterTrigger ==
676
677 // Noise/Turbulence: a curl-noise flow field advected onto position. Strength 0
678 // samples nothing (the whole module is free when unused). The scroll offset
679 // drifts the field over a monotonic clock so pausing emission never snaps it.
680 state.noise_time += dt;
681 bool noiseOn = emitter.noiseStrength > 0.0f && emitter.noiseFrequency > 0.0f;
682 glm::vec2 noiseScroll(emitter.noiseScrollSpeed * state.noise_time *
683 emitter.noiseFrequency);
684
685 bool trailOn = emitter.trailEnabled && !state.trail_count.empty();
686 int trailKeep = std::clamp(emitter.trailPoints, 2, kMaxTrailPoints);
687 f32 trailMinDistSq = emitter.trailMinDistance * emitter.trailMinDistance;
688
689 bool collisionOn = emitter.collisionEnabled;
690
691 dead_particle_indices_.clear();
692 state.collisionOrdinal = 0;
693
694 state.pool.forEachAlive([&](Particle& p) {
695 p.age += dt;
696
697 if (p.age >= p.lifetime) {
698 if (recordDeath) {
699 glm::vec3 worldPos = isWorldSpace ? p.position
700 : frame.position + frame.rotation * p.position;
701 glm::vec3 worldVel = isWorldSpace ? p.velocity : frame.rotation * p.velocity;
702 subemit_requests_.push_back({worldPos, worldVel, p.subEmitterDepth});
703 }
704 u32 idx = static_cast<u32>(&p - &state.pool.particles()[0]);
705 dead_particle_indices_.push_back(idx);
706 return;
707 }
708
709 f32 t = p.age / p.lifetime;
710
711 p.velocity += emitter.gravity * dt;
712 if (isWorldSpace && !force_fields_.empty()) {
713 for (const auto& ff : force_fields_) applyForceField(ff, p, dt);
714 }
715 if (emitter.damping > 0.0f) {
716 p.velocity *= (1.0f - emitter.damping * dt);
717 }
718 if (emitter.speedLimit > 0.0f) {
719 p.velocity = limitedVelocity(p.velocity, emitter.speedLimit, emitter.limitDampen, dt);
720 }
721 // Applied to the STEP, not to velocity, so speed-over-life cannot become
722 // a second force system: gravity, damping and noise still accumulate into
723 // velocity exactly as before.
724 const glm::vec3 collisionFrom = p.position;
725 p.position += (p.velocity * (speedLut ? sampleSizeLut(*speedLut, t) : 1.0f) + p.added_velocity) * dt;
726
727 if (noiseOn) {
728 // The curl field is a 2D flow, sampled on the plane the particle is
729 // over. Depth passes through it: turbulence that also pushed on z
730 // would be a different field, not this one read further.
731 glm::vec2 sample = glm::vec2(p.position) * emitter.noiseFrequency + noiseScroll;
732 glm::vec2 flow = noise::curl(sample, emitter.noiseOctaves);
733 p.position += glm::vec3(flow, 0.0f) * emitter.noiseStrength * dt;
734 }
735
736 if (collisionOn) {
737 collisionStep(emitter, state, p, collisionFrom, frame, isWorldSpace);
738 if (p.age >= p.lifetime) {
739 dead_particle_indices_.push_back(static_cast<u32>(&p - state.pool.particles().data()));
740 return;
741 }
742 }
743
744 // Record the settled position into this particle's trail ring (oldest→newest),
745 // gated by trailMinDistance so a slow particle doesn't pile up coincident points.
746 if (trailOn) {
747 auto idx = static_cast<std::size_t>(&p - state.pool.particles().data());
748 u8& cnt = state.trail_count[idx];
749 glm::vec3* ring = &state.trail_pos[idx * kMaxTrailPoints];
750 bool record = cnt == 0;
751 if (!record) {
752 glm::vec3 d = p.position - ring[cnt - 1];
753 record = glm::dot(d, d) >= trailMinDistSq;
754 }
755 if (record) {
756 if (cnt < trailKeep) {
757 ring[cnt++] = p.position;
758 } else {
759 for (int k = 1; k < trailKeep; ++k) ring[k - 1] = ring[k];
760 ring[trailKeep - 1] = p.position;
761 }
762 }
763 }
764
765 p.rotation += p.angular_velocity * dt;
766
767 if (sizeLut) {
768 p.size = p.start_size * sampleSizeLut(*sizeLut, t);
769 } else {
770 f32 sizeT = applyEasing(sizeEasing, t);
771 p.size = math::lerp(p.start_size, p.end_size, sizeT);
772 }
773
774 if (colorLut) {
775 p.color = sampleColorLut(*colorLut, t);
776 } else {
777 f32 colorT = applyEasing(colorEasing, t);
778 p.color = math::lerp(p.start_color, p.end_color, colorT);
779 }
780
781 if (totalFrames > 1 && emitter.spriteFPS > 0.0f) {
782 f32 frameDuration = 1.0f / emitter.spriteFPS;
783 f32 rawFrame = p.age / frameDuration;
784 // Compute the wrap on the float (fmod) so a looping sheet actually
785 // cycles: clamping to [0,totalFrames-1] first would make the modulo an
786 // identity and freeze every particle on the last frame after one pass.
787 u16 frame;
788 if (emitter.spriteLoop) {
789 frame = static_cast<u16>(std::fmod(rawFrame, static_cast<f32>(totalFrames)));
790 } else {
791 frame = static_cast<u16>(std::min(rawFrame, static_cast<f32>(totalFrames - 1)));
792 }
793 p.sprite_frame = frame;
794 }
795 });
796
797 for (u32 idx : dead_particle_indices_) {
798 state.pool.deallocateByIndex(idx);
799 }
800}
801
802
803f32 ParticleSystem::randomRange(f32 min, f32 max) {
804 if (min >= max) {
805 return min;
806 }
807 std::uniform_real_distribution<f32> dist(min, max);
808 return dist(rng_);
809}
810
811// An aim in the emitter's own plane: an angle names a direction there, and the
812// emitter's rotation is what turns the plane. Aiming out of it is the emitter's
813// job to be turned, not this one's to invent a second angle nobody authored.
814
815namespace {
816bool finitePoint(glm::vec3 p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
817f32 unitValue(f32 x) { return std::isfinite(x) ? std::clamp(x, 0.0f, 1.0f) : 0.0f; }
818}
819
820void ParticleSystem::collisionStep(const ecs::ParticleEmitter& emitter, EmitterState& state,
821 Particle& p, glm::vec3 from, const EmitterFrame& frame, bool world) {
822 const u32 ordinal = state.collisionOrdinal++;
823 if (emitter.collisionMode == 0) { floorCollision(emitter, state, p, frame, world); return; }
824 if (emitter.collisionMode == static_cast<i32>(ecs::ParticleCollisionMode::Sdf)) { sdfCollision(emitter, state, p, frame, world); return; }
825 auto& stats = collision_stats_[collision_stats_index_];
826 auto fallback = [&] {
827 if (emitter.collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter, state, p, frame, world); }
828 };
829 // Depth is a picture only the GPU keeps; here it is what it is on any other unknown mode.
830 if (emitter.collisionMode != 1 && emitter.collisionMode != 2) { ++stats.unavailable; fallback(); return; }
831 const glm::vec3 start = world ? from : frame.position + frame.rotation * from;
832 const glm::vec3 end = world ? p.position : frame.position + frame.rotation * p.position;
833 glm::vec3 delta = end - start;
834 if (emitter.collisionMode == 1) delta.z = 0; // 2D queries never invent depth.
835 if ((emitter.collisionMask & 0xffffu) == 0) return;
836 if (!finitePoint(start) || !finitePoint(end) || !std::isfinite(glm::dot(delta,delta)) || glm::dot(delta, delta) < 1e-12f) return;
837 if (std::isfinite(emitter.collisionMaxDistance) && emitter.collisionMaxDistance > 0 && !collision_cameras_.empty()) {
838 const f32 maxSq = emitter.collisionMaxDistance * emitter.collisionMaxDistance;
839 bool near = false;
840 for (auto camera : collision_cameras_) {
841 const auto offset = end - camera;
842 if (glm::dot(offset, offset) <= maxSq) { near = true; break; }
843 }
844 if (!near) { ++stats.distanceSkipped; fallback(); return; }
845 }
846 const u32 slot = static_cast<u32>(&p - state.pool.particles().data());
847 const u32 limit = std::min(static_cast<u32>(std::clamp(emitter.collisionQueryBudget, 0, 4096)), collisionQuota(collision_emitter_));
848 const u32 alive = std::max(1u,state.pool.aliveCount());
849 const u32 rank = (ordinal + alive - state.collisionCursor % alive) % alive;
850 if (rank >= limit || stats.queries >= limit || collision_queries_.size() >= query_budget_) {
851 ++stats.budgetSkipped; fallback(); return;
852 }
853 collision_queries_.push_back({collision_emitter_.raw, slot, static_cast<u32>(emitter.collisionMode),
854 emitter.collisionMask & 0xffffu, start.x,start.y,start.z,delta.x,delta.y,delta.z});
855 collision_pending_.push_back({collision_emitter_, p.generation, frame, world, collision_stats_index_});
856 ++stats.queries;
857}
858
859void ParticleSystem::floorCollision(const ecs::ParticleEmitter& emitter, EmitterState& state,
860 Particle& p, const EmitterFrame& frame, bool world) {
861 const glm::vec3 point = world ? p.position : frame.position + frame.rotation * p.position;
862 const glm::vec3 velocity = world ? p.velocity : frame.rotation * p.velocity;
863 if (std::isfinite(emitter.collisionFloor) && point.y < emitter.collisionFloor && velocity.y < 0) {
864 collide(emitter, state, p, {point.x,emitter.collisionFloor,point.z}, {0,1,0}, 0xffffffffu, frame, world);
865 }
866}
867
868f32 sdfDistance(const SdfColliderInstance& c, const glm::vec3& point) {
869 const glm::vec3 q = glm::inverse(c.rotation) * (point - c.position);
870 f32 d = 0.0f;
871 if (c.shape > 1.5f) {
872 const f32 along = std::clamp(q.y, -c.ext[1], c.ext[1]);
873 d = glm::length(glm::vec3(q.x, q.y - along, q.z)) - c.ext[0];
874 } else if (c.shape > 0.5f) {
875 const glm::vec3 over = glm::abs(q) - glm::vec3(c.ext[0], c.ext[1], c.ext[2]);
876 d = glm::length(glm::max(over, glm::vec3(0.0f))) + std::min(std::max({over.x, over.y, over.z}), 0.0f);
877 } else {
878 d = glm::length(q) - c.ext[0];
879 }
880 return c.inverted > 0.5f ? -d : d;
881}
882
883void ParticleSystem::sdfCollision(const ecs::ParticleEmitter& emitter, EmitterState& state, Particle& p,
884 const EmitterFrame& frame, bool world) {
885 const glm::vec3 point = world ? p.position : frame.position + frame.rotation * p.position;
886 const glm::vec3 velocity = world ? p.velocity : frame.rotation * p.velocity;
887 const SdfColliderInstance* nearest = nullptr;
888 f32 least = 0.0f;
889 for (const SdfColliderInstance& c : sdf_colliders_) {
890 if ((c.mask & emitter.collisionMask) == 0) continue;
891 const f32 d = sdfDistance(c, point);
892 if (d < least) { least = d; nearest = &c; }
893 }
894 if (!nearest) return;
895 // The way out of the shape, measured: the same answer whichever shape it is.
896 const f32 e = std::max(0.01f, -least * 0.1f);
897 const glm::vec3 gradient(
898 sdfDistance(*nearest, point + glm::vec3(e, 0, 0)) - sdfDistance(*nearest, point - glm::vec3(e, 0, 0)),
899 sdfDistance(*nearest, point + glm::vec3(0, e, 0)) - sdfDistance(*nearest, point - glm::vec3(0, e, 0)),
900 sdfDistance(*nearest, point + glm::vec3(0, 0, e)) - sdfDistance(*nearest, point - glm::vec3(0, 0, e)));
901 const f32 size = glm::length(gradient);
902 if (size < 1e-6f) return;
903 const glm::vec3 normal = gradient / size;
904 if (glm::dot(velocity, normal) >= 0.0f) return;
905 collide(emitter, state, p, point - normal * least, normal, 0xffffffffu, frame, world);
906}
907
908void ParticleSystem::addGpuCollisions(Entity entity, u32 total, const CollisionEvent* events, u32 count) {
909 gpu_collisions_.push_back({entity, total, std::vector<CollisionEvent>(events, events + count)});
910}
911
912void ParticleSystem::collide(const ecs::ParticleEmitter& emitter, EmitterState& state, Particle& p,
913 glm::vec3 point, glm::vec3 normal, u32 body, const EmitterFrame& frame, bool world) {
914 auto& stats = collision_stats_[collision_stats_index_];
915 const u32 slot = static_cast<u32>(&p - state.pool.particles().data());
916 glm::vec3 velocity = world ? p.velocity : frame.rotation * p.velocity;
917 const glm::vec3 incoming = velocity;
918 const f32 approach = glm::dot(velocity, normal);
919 if (approach < 0) {
920 velocity = (velocity - normal * approach) * (1 - unitValue(emitter.collisionFriction))
921 - normal * approach * unitValue(emitter.collisionBounce);
922 }
923 p.position = world ? point : glm::inverse(frame.rotation) * (point - frame.position);
924 p.velocity = world ? velocity : glm::inverse(frame.rotation) * velocity;
925 p.age += unitValue(emitter.collisionLifetimeLoss) * p.lifetime;
926 ++stats.hits;
927 const bool child = emitter.subEmitter != 0 && emitter.subEmitterTrigger == static_cast<i32>(ecs::SubEmitterTrigger::Collision);
928 if (emitter.collisionEvents || child || collision_debug_) {
929 const u32 perEmitter = static_cast<u32>(std::clamp(emitter.collisionEventBudget, 0, 1024));
930 if (stats.events < perEmitter && event_attempts_ < event_budget_) {
931 ++stats.events; ++event_attempts_;
932 if (emitter.collisionEvents || collision_debug_) collision_events_.push_back({collision_emitter_.raw,slot,body,stats.mode,
933 point.x,point.y,point.z,normal.x,normal.y,normal.z,incoming.x,incoming.y,incoming.z,emitter.collisionEvents ? 1u : 0u});
934 if (child && p.subEmitterDepth < 8 && collision_child_bursts_ < event_budget_) {
935 subemit_requests_.push_back({point,velocity,p.subEmitterDepth}); ++collision_child_bursts_;
936 }
937 } else ++stats.eventDropped;
938 }
939 if (p.age >= p.lifetime && emitter.subEmitter != 0 && emitter.subEmitterTrigger == static_cast<i32>(ecs::SubEmitterTrigger::Death))
940 subemit_requests_.push_back({point,velocity,p.subEmitterDepth});
941}
942
944 // Consume once. A stale/repeated reply cannot bounce a particle twice.
945 for (std::size_t i = 0; i < collision_queries_.size(); ++i) {
946 const auto& query = collision_queries_[i]; const auto& pending = collision_pending_[i];
947 if (!registry.valid(pending.emitter) || !registry.has<ecs::ParticleEmitter>(pending.emitter)) continue;
948 auto stateIt = states_.find(pending.emitter);
949 if (stateIt == states_.end() || query.slot >= stateIt->second.pool.capacity()) continue;
950 auto& state = stateIt->second; auto& p = state.pool.particles()[query.slot];
951 if (!p.alive || p.generation != pending.generation) continue;
952 const auto& emitter = registry.get<ecs::ParticleEmitter>(pending.emitter);
953 if (!emitter.enabled || !emitter.collisionEnabled) continue;
954 collision_emitter_ = pending.emitter; collision_stats_index_ = pending.stats;
955 auto& stats = collision_stats_[pending.stats];
956 const CollisionReply reply = replies && i < count ? replies[i] : CollisionReply{2,0,0,0,0,0,0,0};
957 if (reply.status == 1) {
958 glm::vec3 normal(reply.nx,reply.ny,reply.nz), point(reply.x,reply.y,reply.z);
959 if (query.mode == 1) { normal.z = 0; point.z = pending.world ? p.position.z : (pending.frame.position + pending.frame.rotation * p.position).z; }
960 const f32 normSq = glm::dot(normal,normal);
961 const glm::vec3 from(query.ox,query.oy,query.oz), delta(query.dx,query.dy,query.dz);
962 // A provider must report a finite point on this segment; invalid replies
963 // are unavailable queries (same explicit fallback), never teleports.
964 const f32 deltaSq = glm::dot(delta,delta);
965 const f32 fraction = glm::dot(point - from,delta) / deltaSq;
966 glm::vec3 offset = point - (from + delta * fraction);
967 if (query.mode == 1) offset.z = 0;
968 if (finitePoint(normal) && finitePoint(point) && std::isfinite(normSq) && normSq > 1e-12f &&
969 fraction >= -1e-4f && fraction <= 1.0001f && glm::dot(offset,offset) <= std::max(1e-6f,deltaSq*1e-6f)) {
970 normal /= std::sqrt(normSq);
971 if (glm::dot(delta,normal) > 0) normal = -normal;
972 collide(emitter,state,p,point + normal * 1e-4f,normal,reply.body,pending.frame,pending.world);
973 } else { ++stats.unavailable; if (emitter.collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter,state,p,pending.frame,pending.world); } }
974 } else if (reply.status != 0) {
975 ++stats.unavailable;
976 if (emitter.collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter,state,p,pending.frame,pending.world); }
977 }
978 if (query.slot < state.trail_count.size() && state.trail_count[query.slot] > 0) {
979 const auto last = static_cast<std::size_t>(query.slot)*kMaxTrailPoints + state.trail_count[query.slot]-1;
980 state.trail_pos[last] = p.position;
981 }
982 if (p.age >= p.lifetime) state.pool.deallocateByIndex(query.slot);
983 if (!subemit_requests_.empty()) drainSubEmitters(registry,pending.emitter,Entity::fromRaw(emitter.subEmitter),emitter.subEmitterInheritVelocity,emitter.subEmitterChance);
984 }
985 collision_queries_.clear(); collision_pending_.clear();
986}
987
988} // namespace esengine::particle
Camera component for rendering viewpoints.
Deterministic curl-noise flow field for the particle Noise/Turbulence module — a pure-CPU,...
The engine's randomness, and the only place its seed lives.
std::mt19937 stream(std::string_view name) const
Central container for all entities and components.
Definition Registry.hpp:73
T & get(Entity entity)
Gets a component from an entity (must exist).
Definition Registry.hpp:649
bool has(Entity entity) const
Checks if an entity has a specific component.
Definition Registry.hpp:711
Connection onDestroy(DestroyCallback callback)
Subscribe to entity destruction.
Definition Registry.hpp:509
bool valid(Entity entity) const
Checks if an entity is currently valid.
Definition Registry.hpp:518
std::vector< Particle > & particles()
Definition Particle.hpp:49
void deallocateByIndex(u32 index)
Deallocate a particle by its pool index.
Definition Particle.cpp:50
const SizeLut * speedLut(Entity entity) const
void setSizeLut(Entity entity, const f32 *values, i32 count)
EmitterState * getState(Entity entity)
void update(ecs::Registry &registry, f32 dt)
void setBursts(Entity entity, const f32 *values, i32 count)
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.
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 setSpeedLut(Entity entity, const f32 *values, i32 count)
void setColorLut(Entity entity, const f32 *rgba, i32 count)
T lerp(const T &a, const T &b, float t)
Linear interpolation between two values.
Definition Math.hpp:142
glm::vec2 curl(glm::vec2 sample, i32 octaves)
constexpr int kColorLutSize
ecs::ParticleEasing EasingType
static f32 sampleSizeLut(const SizeLut &lut, f32 t)
static void applyForceField(const ForceFieldInstance &ff, Particle &p, f32 dt)
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.
f32 applyEasing(EasingType type, f32 t)
std::array< f32, kColorLutSize > SizeLut
SpawnSample sampleShape(const ecs::ParticleEmitter &emitter, const RandomRange &rand)
constexpr int kMaxTrailPoints
glm::vec3 limitedVelocity(glm::vec3 velocity, f32 limit, f32 dampen, f32 dt)
A particle's velocity after its speed limit has pulled it back.
glm::vec3 worldDirOf(const glm::vec3 &local, const EmitterFrame &f)
A local direction placed in the world — rotation ALONE.
std::array< glm::vec4, kColorLutSize > ColorLut
u32 burstsDue(const std::vector< ScheduledBurst > &schedule, f32 prev, f32 cur, f32 duration, bool looping)
How many particles the schedule releases while the emitter's clock goes from prev to cur.
static glm::vec4 sampleColorLut(const ColorLut &lut, f32 t)
glm::vec3 worldPointOf(const glm::vec3 &local, const EmitterFrame &f)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162
Camera component for rendering viewpoints.
Definition Camera.hpp:70
bool isActive
Whether this is the active camera.
Definition Camera.hpp:98
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.