22#include <unordered_map>
29constexpr float kRad2Deg = 180.f / 3.14159265358979323846f;
31void appendParticleItem(
const ParticleEmitter::Config &cfg,
const ParticleEmitter::Draw &
draw,
32 const Particle &
p,
int order, std::vector<graphics::DrawItem2D> &
out) {
34 if (!evaluated)
return;
35 const auto& appearance = evaluated.value();
36 graphics::DrawItem2D item;
37 item.x = appearance.x;
38 item.y = appearance.y;
39 item.w = appearance.w;
40 item.h = appearance.h;
41 item.rotation = appearance.rotation;
44 item.color = appearance.color;
45 item.layer =
draw.layer;
46 item.blend =
draw.blend;
47 item.texture =
draw.texture;
48 item.normal = cfg.materialMode ==
"lit" ?
draw.normalTexture :
nullptr;
49 item.shader =
draw.shader;
50 item.canvas =
draw.canvas;
51 item.camera =
draw.camera;
52 item.receiveLight = cfg.materialMode ==
"lit";
53 item.litPath = item.receiveLight && item.texture !=
nullptr && item.normal !=
nullptr && item.shader ==
nullptr;
54 item.sceneColorDistortion = cfg.materialMode ==
"distortion";
55 item.distortionStrength = cfg.distortionStrength;
56 if (
draw.texture && (cfg.hframes > 1 || cfg.vframes > 1)) {
57 item.u0 = appearance.u0;
58 item.v0 = appearance.v0;
59 item.u1 = appearance.u1;
60 item.v1 = appearance.v1;
66void appendEmitterItems(
const ParticleEmitter::Config& cfg,
const ParticleEmitter::Sim& sim,
67 const ParticleEmitter::Draw&
draw,
int&
order, std::vector<graphics::DrawItem2D>&
out) {
68 if (cfg.sortMode ==
"none") {
69 for (
int i = 0; i < sim.alive; ++i) appendParticleItem(cfg,
draw, sim.particles[std::size_t(i)],
order++,
out);
73 std::vector<int>
indices(std::size_t(sim.alive));
74 for (
int i = 0; i < sim.alive; ++i)
indices[std::size_t(i)] = i;
75 auto age = [&](
int index) {
76 const Particle&
p = sim.particles[std::size_t(
index)];
77 return p.lifetime > 0.f ? 1.f -
p.life /
p.lifetime : 1.f;
79 if (cfg.sortMode ==
"oldest") {
80 std::stable_sort(
indices.begin(),
indices.end(), [&](
int a,
int b) { return age(a) > age(b); });
81 }
else if (cfg.sortMode ==
"youngest") {
82 std::stable_sort(
indices.begin(),
indices.end(), [&](
int a,
int b) { return age(a) < age(b); });
83 }
else if (cfg.sortMode ==
"distance" &&
draw.camera) {
84 const float cameraX =
draw.camera->data()->x;
85 const float cameraY =
draw.camera->data()->y;
87 const Particle&
p = sim.particles[std::size_t(
index)];
88 const float dx =
p.x - cameraX;
89 const float dy =
p.y - cameraY;
93 [&](
int a,
int b) { return distanceSquared(a) > distanceSquared(b); });
98int appendRibbonItems(
const ParticleEmitter::Config& cfg,
const ParticleEmitter::Sim& sim,
99 const ParticleEmitter::Draw&
draw,
int&
order, std::vector<graphics::DrawItem2D>&
out) {
101 for (
int i = 1; i < sim.alive; ++i) {
102 const Particle&
previous = sim.particles[std::size_t(i - 1)];
103 const Particle&
current = sim.particles[std::size_t(i)];
107 if (
length < cfg.ribbonMinSegmentLength)
continue;
110 auto& item =
out.back();
111 const float h = item.h * cfg.ribbonWidth;
116 item.rotation = std::atan2(
dy,
dx) * kRad2Deg;
123bool emitterOffscreen(
const ParticleEmitter::Config &cfg,
const ParticleEmitter::Draw &
draw) {
124 auto *cam =
draw.camera;
125 if (!cam)
return false;
126 if (cfg.cullDistance > 0.f) {
127 const float dx = cfg.x - cam->data()->x;
128 const float dy = cfg.y - cam->data()->y;
129 if (
dx *
dx +
dy *
dy > cfg.cullDistance * cfg.cullDistance)
return true;
131 auto *gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
132 if (!gfx)
return false;
133 const float viewW =
draw.canvas ? float(
draw.canvas->getWidth()) : float(gfx->getWidth());
134 const float viewH =
draw.canvas ? float(
draw.canvas->getHeight()) : float(gfx->getHeight());
135 if (viewW <= 0.f || viewH <= 0.f)
return false;
136 const float z = cam->data()->zoom > 0.f ? cam->data()->zoom : 1e-4f;
137 const float sx = (cfg.x - cam->data()->x) *
z + viewW * 0.5f;
138 const float sy = (cfg.y - cam->data()->y) *
z + viewH * 0.5f;
139 const float maxHalf =
140 std::max(cfg.particleW, cfg.particleH) *
141 std::max(std::abs(cfg.sizeStart), std::abs(cfg.sizeEnd)) * 0.5f +
144 cfg.speedMax * cfg.lifeMax + std::max(cfg.areaX, cfg.areaY) + maxHalf;
148int64_t fileModtime(
const std::string &
path) {
149 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>(
"Filesystem");
150 if (!fs) fs = eve::filesystem::Filesystem::create();
152 if (!fs->getInfo(
path,
info))
return -1;
156int liveParticleCount(ParticleEmitter*
emitter) {
158 return gpu->residentActive ?
gpu->estimatedAlive +
emitter->sim()->alive :
emitter->sim()->alive;
161graphics::GpuParticleSpawn gpuSpawn(
const Particle& particle, std::uint32_t birthSerial) {
162 graphics::GpuParticleSpawn
out;
165 out.vx = particle.vx;
166 out.vy = particle.vy;
167 out.life = particle.life;
168 out.lifetime = particle.lifetime;
169 out.size = particle.size;
170 out.rotation = particle.rot;
171 out.spin = particle.spin;
172 out.frame = particle.frame;
173 out.radial = particle.radial;
174 out.tangential = particle.tangential;
175 out.ax = particle.ax;
176 out.ay = particle.ay;
177 out.noisePhase = particle.noisePhase;
178 out.birthSerial = std::bit_cast<float>(birthSerial);
182void deactivateResidentGpu(graphics::Graphics* gfx, ParticleEmitter::GpuSim&
gpu) {
184 if (
auto*
gp = gfx->gpuParticles())
gp->releaseGpuParticleEmitter(
gpu.residentHandle);
186 gpu.residentActive =
false;
187 gpu.estimatedAlive = 0;
189 gpu.deathTimes.clear();
190 gpu.pendingWorldOffsetX = 0.f;
191 gpu.pendingWorldOffsetY = 0.f;
192 gpu.nextBirthSerial = 1;
196 bool legacyControls) {
200 if (!gfx || !(gfx->gpuParticles() && gfx->gpuParticles()->canSubmitGpuParticles()))
204 gpu->residentHandle = gfx->gpuParticles()->createGpuParticleEmitter(std::uint32_t(sim->particles.size()));
208 const bool hadLastPosition = sim->hasLastPos;
209 const float previousX = sim->lastX;
210 const float previousY = sim->lastY;
211 const int capacity = int(sim->particles.size());
212 const int conservativeRoom = std::max(0,
capacity -
gpu->estimatedAlive - sim->alive);
213 if (sim->spawnQuota < 0)
214 sim->spawnQuota = conservativeRoom;
216 sim->spawnQuota = std::min(sim->spawnQuota, conservativeRoom);
218 float simulatedDt = 0.f;
219 if (legacyControls) {
224 simulatedDt =
static_cast<float>(
step.delta.seconds());
226 gpu->timeline += simulatedDt;
227 auto minHeap = std::greater<float>{};
228 while (!
gpu->deathTimes.empty() &&
gpu->deathTimes.front() <= float(
gpu->timeline) + 1e-6f) {
229 std::pop_heap(
gpu->deathTimes.begin(),
gpu->deathTimes.end(), minHeap);
230 gpu->deathTimes.pop_back();
233 const int room = std::max(0,
capacity -
int(
gpu->deathTimes.size()));
234 const int accepted = std::min(sim->alive, room);
235 if (sim->alive > accepted) sim->droppedSpawnsThisFrame += sim->alive -
accepted;
236 std::vector<graphics::GpuParticleSpawn> spawns;
237 spawns.reserve(std::size_t(accepted));
238 for (
int i = 0; i <
accepted; ++i) {
239 const Particle& particle = sim->particles[std::size_t(i)];
240 if (particle.life <= 0.f)
continue;
241 spawns.push_back(gpuSpawn(particle,
gpu->nextBirthSerial++));
242 gpu->deathTimes.push_back(
float(
gpu->timeline) + particle.life);
243 std::push_heap(
gpu->deathTimes.begin(),
gpu->deathTimes.end(), minHeap);
246 graphics::GpuParticleUpdate update;
247 update.dt = simulatedDt;
248 update.emitterX = cfg->x;
249 update.emitterY = cfg->y;
250 update.gravityX = cfg->gravityX;
251 update.gravityY = cfg->gravityY;
252 update.damping = cfg->damping;
253 update.velocityLimit = cfg->limitVelocity;
254 update.noiseStrength = cfg->noiseStrength;
255 update.noiseFrequency = cfg->noiseFrequency;
256 update.noiseSpeed = cfg->noiseSpeed;
257 update.time = sim->emitterAge;
258 update.frameRate = cfg->frameRate;
259 if (cfg->simSpace ==
"local" && hadLastPosition) {
260 update.localOffsetX = cfg->x - previousX;
261 update.localOffsetY = cfg->y - previousY;
263 update.localOffsetX +=
gpu->pendingWorldOffsetX;
264 update.localOffsetY +=
gpu->pendingWorldOffsetY;
266 if (!gfx->gpuParticles()->updateGpuParticleEmitter(
gpu->residentHandle, update, spawns.data(),
267 std::uint32_t(spawns.size()))) {
271 if (!
gpu->residentActive) deactivateResidentGpu(gfx, *
gpu);
276 for (
int i = 0; i < sim->alive; ++i) sim->particles[std::size_t(i)].life = 0.f;
278 gpu->residentActive =
true;
279 gpu->estimatedAlive = int(
gpu->deathTimes.size());
280 gpu->pendingWorldOffsetX = 0.f;
281 gpu->pendingWorldOffsetY = 0.f;
288 if (
step.delta.nanoseconds() < 0)
290 "particle simulation delta must be non-negative"));
291 const float dt =
static_cast<float>(
step.delta.seconds());
292 if (!std::isfinite(
dt))
294 "particle simulation delta is outside float range"));
304 auto &
stats = nextStats;
305 const auto begin = std::chrono::steady_clock::now();
307 if (ecs::current()->getManager<ParticleEmitter>() ==
nullptr) {
312 std::vector<ParticleEmitter *> allEmitters;
313 std::vector<ParticleEmitter *> emitters;
315 auto view = ecs::View<ParticleEmitter, ParticleEmitter::Config>();
316 for (
auto it =
view.begin(); it !=
view.end(); ++it) {
318 if (!cfg->entity)
continue;
319 allEmitters.push_back(cfg->entity);
320 auto sim = cfg->entity->sim();
321 if (!legacyControls && sim->hasSimulationTick &&
step.tick <= sim->simulationTick)
324 "particle simulation tick must advance monotonically for every emitter"));
325 if (sim->active || liveParticleCount(cfg->entity) > 0) emitters.push_back(cfg->entity);
329 return a->config()->priority > b->config()->priority;
333 stats.emittersTotal = int(emitters.size());
334 for (
auto *
emitter : allEmitters) {
337 sim->spawnedThisFrame = 0;
338 sim->droppedSpawnsThisFrame = 0;
339 sim->spawnQuota = budget.maxParticles > 0 ? 0 : -1;
341 int reservedAlive = 0;
342 for (
auto*
emitter : emitters) reservedAlive += liveParticleCount(
emitter);
344 auto* gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
346 int processedAlive = 0;
347 for (
auto *
emitter : emitters) {
351 const int aliveBefore = liveParticleCount(
emitter);
352 reservedAlive -= aliveBefore;
354 if (budget.qualityLevel < cfg->minimumQuality) {
355 ++
stats.emittersQualitySkipped;
356 processedAlive += aliveBefore;
360 const bool offscreen = emitterOffscreen(*cfg, *
draw);
361 const bool culled = cfg->cullingMode ==
"pause" ? offscreen
362 : cfg->cullingMode ==
"always" ? false
363 : (aliveBefore <= 0 && offscreen);
365 ++
stats.emittersCulled;
366 processedAlive += aliveBefore;
370 if (budget.maxSimulatedEmitters > 0 &&
371 stats.emittersSimulated >= budget.maxSimulatedEmitters) {
372 ++
stats.emittersBudgetSkipped;
373 processedAlive += aliveBefore;
377 int spawnQuota = cfg->maxSpawnPerFrame > 0 ? cfg->maxSpawnPerFrame : -1;
378 if (budget.maxParticles > 0) {
379 const int existingTotal = processedAlive + aliveBefore + reservedAlive;
380 const int globalRoom = std::max(0, budget.maxParticles - existingTotal);
381 spawnQuota = spawnQuota < 0 ? globalRoom : std::min(spawnQuota, globalRoom);
383 sim->spawnQuota = spawnQuota;
385 auto attach =
emitter->attach();
386 auto skinSrc =
emitter->skinSource();
387 auto gpuSim =
emitter->gpuSim();
389 const bool gpuEligible =
emitter->isGpuFeatureSetSupported();
390 if (gpuSim->residentActive && (!cfg->gpuSimulation || !gpuEligible)) deactivateResidentGpu(gfx, *gpuSim);
391 const bool wantsResident = cfg->gpuSimulation && gpuEligible;
392 bool handled =
false;
394 sim->recording.invalidate();
395 auto gpuAdvance = advanceResidentGpu(gfx,
emitter,
step, legacyControls);
397 handled = std::move(gpuAdvance).takeValue();
407 ++
stats.emittersSimulated;
408 processedAlive += liveParticleCount(
emitter);
409 if (budget.maxParticles > 0 || cfg->maxSpawnPerFrame > 0) sim->spawnQuota = 0;
412 stats.particlesAfter = 0;
413 stats.particlesSpawned = 0;
414 stats.droppedSpawns = 0;
415 for (
auto *
emitter : allEmitters) {
419 stats.particlesSpawned += sim->spawnedThisFrame;
420 stats.droppedSpawns += sim->droppedSpawnsThisFrame;
421 if (
gpu->residentActive) {
422 ++
stats.gpuResidentEmitters;
423 stats.gpuResidentParticles +=
gpu->estimatedAlive;
425 sim->spawnQuota = -1;
427 stats.particlesKilled =
428 std::max(0,
stats.particlesBefore +
stats.particlesSpawned -
stats.particlesAfter);
430 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() -
begin)
433 if (!legacyControls) {
434 for (
auto *
emitter : allEmitters) {
436 sim->simulationTick =
step.tick;
437 sim->hasSimulationTick =
true;
451 duration.ignore(
"legacy particle update received an invalid duration");
455 .ignore(
"legacy particle update facade");
460 std::vector<graphics::DrawItem2D>& items,
int&
order,
461 bool respectSceneCulling,
bool& usedCanvas,
bool& culled) {
464 if (!
draw->visible ||
alive <= 0)
return 0;
466 if (respectSceneCulling &&
467 (budget.qualityLevel < cfg->minimumQuality || emitterOffscreen(*cfg, *
draw))) {
468 culled =
true;
return 0;
470 if (
gpu->residentActive) {
500 return gpu->estimatedAlive;
501 culled =
true;
return 0;
503 if (
draw->canvas) usedCanvas =
true;
504 if (cfg->renderMode ==
"ribbon")
return appendRibbonItems(*cfg, *sim, *
draw,
order, items);
505 appendEmitterItems(*cfg, *sim, *
draw,
order, items);
return sim->alive;
510 if (!gfx || !
emitter)
return 0;
511 std::vector<graphics::DrawItem2D> items;
bool usedCanvas=
false, culled=
false;
513 const int rendered=appendOneEmitter(*gfx,*
emitter,items,
order,
false,usedCanvas,culled);
521 stats.renderedParticles = 0;
522 stats.renderCulledEmitters = 0;
523 stats.renderMs = 0.0;
524 const auto begin = std::chrono::steady_clock::now();
526 if (ecs::current()->getManager<ParticleEmitter>() ==
nullptr)
return;
528 std::vector<graphics::DrawItem2D> items;
531 bool anyCanvas =
false;
533 for (
auto it =
view.begin(); it !=
view.end(); ++it) {
534 auto [cfg, sim,
draw] = *it; (void)sim; (void)
draw;
538 stats.renderedParticles += appendOneEmitter(*gfx,*
emitter,items,
order,
true,anyCanvas,culled);
539 if(culled) ++
stats.renderCulledEmitters;
547 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() -
begin)
552 if (ecs::current()->getManager<ParticleEmitter>() ==
nullptr)
return;
556 std::vector<ParticleEmitter *> emitters;
558 auto view = ecs::View<ParticleEmitter, ParticleEmitter::Config>();
559 for (
auto it =
view.begin(); it !=
view.end(); ++it) {
561 if (cfg->entity) emitters.push_back(cfg->entity);
566 for (
auto *em : emitters) {
567 auto cfg = em->config();
568 auto sim = em->sim();
569 auto draw = em->draw();
570 auto lights = em->lights();
571 if (!cfg->lights.enabled) {
572 for (
auto *l :
lights->pool)
573 if (l) l->setEnabled(
false);
576 const int maxL = cfg->lights.max > 0 ? (cfg->lights.max > 8 ? 8 : cfg->lights.max) : 0;
577 while (
int(
lights->pool.size()) < maxL)
579 const int n = sim->alive < maxL ? sim->alive : maxL;
580 for (
int i = 0; i < maxL; ++i) {
583 const Particle &
p = sim->particles[size_t(i)];
586 l->
setColor(cfg->lights.r, cfg->lights.g, cfg->lights.b, cfg->lights.intensity);
597 if (ecs::current()->getManager<ParticleEmitter>() ==
nullptr)
return 0;
604 ecs::View<ParticleEmitter, ParticleEmitter::Config, ParticleEmitter::Resource>();
605 for (
auto it =
view.begin(); it !=
view.end(); ++it) {
606 auto [cfg, res] = *it;
607 if (!cfg->entity)
continue;
608 if (res->path.empty()) {
612 if (!res->autoReload) {
617 const int64_t mt = fileModtime(res->path);
622 if (mt == res->modtime) {
std::vector< eve::ProcgenProbeDesc > lights
std::vector< std::uint32_t > indices
std::shared_ptr< OceanGpuSpectrum > gpu
std::shared_ptr< const OceanSprayFrame > previous
std::vector< BakedParticleSample > particles
std::vector< EquipmentStat > stats
std::unique_ptr< TrailEmitter > emitter
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
virtual Texture * getSceneLinearDepthTexture()
Sampleable scene linear depth in [0,1], or nullptr when unavailable.
virtual IGpuParticles * gpuParticles() noexcept
Borrow the backend particle compute surface when present.
int getWidth() const
Returns the width.
virtual void setCanvas(Canvas *canvas)=0
nullptr or this → screen. Switching flushes pending draws to the previous target.
int getHeight() const
Returns the height.
Declarative 2D light. Collected by RenderSystem (max 8 per canvas/frame). type: "point" | "dir" | "sp...
void setPosition(float x, float y)
void setColor(float r, float g, float b, float intensity=1.f)
void setCanvas(Canvas *canvas)
void setEnabled(bool enabled)
static Light2D * createLight(const std::string &type="point")
void setRadius(float radius)
static void drawItems(Graphics &gfx, std::vector< DrawItem2D > &items, bool present)
Sort and draw items. If present=true, calls gfx.present() at the end. Map::render uses present=false ...
ECS emitter entity. Script configures components; ParticleSimSystem / ParticleRenderSystem drive per-...
static void update()
Updates .
static void render(graphics::Graphics *gfx)
Renders .
static int renderEmitter(graphics::Graphics *gfx, ParticleEmitter *emitter)
Draw exactly one emitter without traversing the global ECS registry.
static eve::Result< void > advance(const eve::SimulationStep &step)
Advances emitters using one scheduler-owned deterministic step.
static void update(float dt)
Legacy seconds facade; conversion and Result consumption are explicit.
constexpr GpuParticleHandle kInvalidGpuParticleHandle
Invalid GPU particle handle returned when the backend cannot allocate the resource.
@ Ribbon
Connect birth-ordered neighbors into ribbon segments.
ParticleBudgetConfig & particleBudgetConfig()
Mutable process-wide scalability configuration.
EVENGINE_API_DOMAINS float advanceEmitterSim(ParticleEmitter::Config &cfg, ParticleEmitter::Sim &sim, float dt)
Apply playback speed and optional bounded fixed stepping before simulation.
bool reloadConfigFile(ParticleEmitter *emitter, std::string *error)
Re-read Resource.path if set; updates modtime.
eve::Result< void > runParticleSimulation(const eve::SimulationStep &step, bool legacyControls)
const ParticleFrameStats & particleFrameStats()
Statistics for the most recently processed particle frame.
Result< ParticleAppearance > evaluateParticleAppearance(const ParticleEmitter::Config &cfg, const Particle &p)
Evaluate the same CPU sprite curves and render mode for live rendering and bake capture....
ParticleFrameStats & mutableParticleFrameStats()
Internal mutable statistics used by particle systems.
void syncEmitterSources(ParticleEmitter::Config &cfg, ParticleEmitter::Sim &, ParticleEmitter::Attach &attach, ParticleEmitter::SkinSource &skinSrc)
Sync bone attach + refresh skin cache; call before stepEmitterSim when using Attach/SkinSource.
Result< void > accepted()
Build a successful write/validation result.
float distanceSquared(float ax, float ay, float bx, float by)
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
One deterministic fixed-step emitted by SimulationClock.
Parameters for rendering a resident GPU particle emitter.
GpuParticleSortMode sortMode
GpuParticleFacingMode facing
float ribbonMinSegmentLength
float axisRotationRadians
@ MtimePollingReloadFailed
Counters from the most recent particle update and render pass.
eve::SimulationTick simulationTick
Simulation tick that produced the latest simulation counters.
Single live particle (CPU simulation).