载入中...
搜索中...
未找到
ParticleSystem.cpp
浏览该文件的文档.
1// eve-hot-path
3#include "common/Module.h"
5#include "graphics/Canvas.h"
8#include "graphics/Graphics.h"
9#include "graphics/Light.h"
15
16#include <algorithm>
17#include <bit>
18#include <chrono>
19#include <cmath>
20#include <functional>
21#include <string>
22#include <unordered_map>
23#include <vector>
24
25namespace eve::particles {
26
27namespace {
28
29constexpr float kRad2Deg = 180.f / 3.14159265358979323846f;
30
31void appendParticleItem(const ParticleEmitter::Config &cfg, const ParticleEmitter::Draw &draw,
32 const Particle &p, int order, std::vector<graphics::DrawItem2D> &out) {
33 const auto evaluated = evaluateParticleAppearance(cfg, p);
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;
42 item.order = order;
43 item.hasOrder = true;
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;
61 item.hasUV = true;
62 }
63 out.push_back(item);
64}
65
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);
70 return;
71 }
72
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;
78 };
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;
86 auto distanceSquared = [&](int index) {
87 const Particle& p = sim.particles[std::size_t(index)];
88 const float dx = p.x - cameraX;
89 const float dy = p.y - cameraY;
90 return dx * dx + dy * dy;
91 };
92 std::stable_sort(indices.begin(), indices.end(),
93 [&](int a, int b) { return distanceSquared(a) > distanceSquared(b); });
94 }
95 for (int index : indices) appendParticleItem(cfg, draw, sim.particles[std::size_t(index)], order++, out);
96}
97
98int appendRibbonItems(const ParticleEmitter::Config& cfg, const ParticleEmitter::Sim& sim,
99 const ParticleEmitter::Draw& draw, int& order, std::vector<graphics::DrawItem2D>& out) {
100 int segments = 0;
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)];
104 const float dx = current.x - previous.x;
105 const float dy = current.y - previous.y;
106 const float length = std::sqrt(dx * dx + dy * dy);
107 if (length < cfg.ribbonMinSegmentLength) continue;
108
109 appendParticleItem(cfg, draw, current, order++, out);
110 auto& item = out.back();
111 const float h = item.h * cfg.ribbonWidth;
112 item.x = (previous.x + current.x - length) * 0.5f;
113 item.y = (previous.y + current.y - h) * 0.5f;
114 item.w = length;
115 item.h = h;
116 item.rotation = std::atan2(dy, dx) * kRad2Deg;
117 ++segments;
118 }
119 return segments;
120}
121
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;
130 }
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 +
142 1.f;
143 const float margin =
144 cfg.speedMax * cfg.lifeMax + std::max(cfg.areaX, cfg.areaY) + maxHalf;
145 return sx < -margin || sx > viewW + margin || sy < -margin || sy > viewH + margin;
146}
147
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;
153 return info.modtime;
154}
155
156int liveParticleCount(ParticleEmitter* emitter) {
157 auto gpu = emitter->gpuSim();
158 return gpu->residentActive ? gpu->estimatedAlive + emitter->sim()->alive : emitter->sim()->alive;
159}
160
161graphics::GpuParticleSpawn gpuSpawn(const Particle& particle, std::uint32_t birthSerial) {
162 graphics::GpuParticleSpawn out;
163 out.x = particle.x;
164 out.y = particle.y;
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);
179 return out;
180}
181
182void deactivateResidentGpu(graphics::Graphics* gfx, ParticleEmitter::GpuSim& gpu) {
183 if (gfx && gpu.residentHandle != graphics::kInvalidGpuParticleHandle)
184 if (auto* gp = gfx->gpuParticles()) gp->releaseGpuParticleEmitter(gpu.residentHandle);
186 gpu.residentActive = false;
187 gpu.estimatedAlive = 0;
188 gpu.timeline = 0.0;
189 gpu.deathTimes.clear();
190 gpu.pendingWorldOffsetX = 0.f;
191 gpu.pendingWorldOffsetY = 0.f;
192 gpu.nextBirthSerial = 1;
193}
194
195eve::Result<bool> advanceResidentGpu(graphics::Graphics *gfx, ParticleEmitter *emitter, const eve::SimulationStep &step,
196 bool legacyControls) {
197 auto cfg = emitter->config();
198 auto sim = emitter->sim();
199 auto gpu = emitter->gpuSim();
200 if (!gfx || !(gfx->gpuParticles() && gfx->gpuParticles()->canSubmitGpuParticles()))
201 return eve::Result<bool>::success(false);
202
203 if (gpu->residentHandle == graphics::kInvalidGpuParticleHandle) {
204 gpu->residentHandle = gfx->gpuParticles()->createGpuParticleEmitter(std::uint32_t(sim->particles.size()));
205 if (gpu->residentHandle == graphics::kInvalidGpuParticleHandle) return eve::Result<bool>::success(false);
206 }
207
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;
215 else
216 sim->spawnQuota = std::min(sim->spawnQuota, conservativeRoom);
217
218 float simulatedDt = 0.f;
219 if (legacyControls) {
220 simulatedDt = advanceEmitterSim(*cfg, *sim, static_cast<float>(step.delta.seconds()));
221 } else {
222 auto simulation = advanceEmitterSim(*cfg, *sim, step);
223 if (!simulation) return eve::Result<bool>::failure(simulation.status());
224 simulatedDt = static_cast<float>(step.delta.seconds());
225 }
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();
231 }
232
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);
244 }
245
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;
262 }
263 update.localOffsetX += gpu->pendingWorldOffsetX;
264 update.localOffsetY += gpu->pendingWorldOffsetY;
265
266 if (!gfx->gpuParticles()->updateGpuParticleEmitter(gpu->residentHandle, update, spawns.data(),
267 std::uint32_t(spawns.size()))) {
268 // Before activation the CPU state remains authoritative and already
269 // advanced. Once resident, a transient submit failure freezes state
270 // rather than losing it through an implicit CPU migration.
271 if (!gpu->residentActive) deactivateResidentGpu(gfx, *gpu);
272 gpu->failed = true;
273 return eve::Result<bool>::success(true);
274 }
275
276 for (int i = 0; i < sim->alive; ++i) sim->particles[std::size_t(i)].life = 0.f;
277 sim->alive = 0;
278 gpu->residentActive = true;
279 gpu->estimatedAlive = int(gpu->deathTimes.size());
280 gpu->pendingWorldOffsetX = 0.f;
281 gpu->pendingWorldOffsetY = 0.f;
282 return eve::Result<bool>::success(true);
283}
284
285} // namespace
286
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"));
295
296 // Build the complete frame record off to the side. Checked failures must
297 // not publish counters that describe only the prefix of a frame; the
298 // previous published record remains the observable snapshot until the
299 // simulation reaches its commit point below.
300 ParticleFrameStats nextStats;
301 const uint64_t nextFrame = particleFrameStats().frameIndex + 1;
302 nextStats.frameIndex = nextFrame;
303 nextStats.simulationTick = step.tick;
304 auto &stats = nextStats;
305 const auto begin = std::chrono::steady_clock::now();
306
307 if (ecs::current()->getManager<ParticleEmitter>() == nullptr) {
308 mutableParticleFrameStats() = nextStats;
310 }
311
312 std::vector<ParticleEmitter *> allEmitters;
313 std::vector<ParticleEmitter *> emitters;
314 {
315 auto view = ecs::View<ParticleEmitter, ParticleEmitter::Config>();
316 for (auto it = view.begin(); it != view.end(); ++it) {
317 auto [cfg] = *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);
326 }
327 }
328 std::stable_sort(emitters.begin(), emitters.end(), [](ParticleEmitter *a, ParticleEmitter *b) {
329 return a->config()->priority > b->config()->priority;
330 });
331
332 const auto &budget = particleBudgetConfig();
333 stats.emittersTotal = int(emitters.size());
334 for (auto *emitter : allEmitters) {
335 auto sim = emitter->sim();
336 stats.particlesBefore += liveParticleCount(emitter);
337 sim->spawnedThisFrame = 0;
338 sim->droppedSpawnsThisFrame = 0;
339 sim->spawnQuota = budget.maxParticles > 0 ? 0 : -1;
340 }
341 int reservedAlive = 0;
342 for (auto* emitter : emitters) reservedAlive += liveParticleCount(emitter);
343
344 auto* gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
345
346 int processedAlive = 0;
347 for (auto *emitter : emitters) {
348 auto cfg = emitter->config();
349 auto sim = emitter->sim();
350 auto draw = emitter->draw();
351 const int aliveBefore = liveParticleCount(emitter);
352 reservedAlive -= aliveBefore;
353
354 if (budget.qualityLevel < cfg->minimumQuality) {
355 ++stats.emittersQualitySkipped;
356 processedAlive += aliveBefore;
357 continue;
358 }
359
360 const bool offscreen = emitterOffscreen(*cfg, *draw);
361 const bool culled = cfg->cullingMode == "pause" ? offscreen
362 : cfg->cullingMode == "always" ? false
363 : (aliveBefore <= 0 && offscreen);
364 if (culled) {
365 ++stats.emittersCulled;
366 processedAlive += aliveBefore;
367 continue;
368 }
369
370 if (budget.maxSimulatedEmitters > 0 &&
371 stats.emittersSimulated >= budget.maxSimulatedEmitters) {
372 ++stats.emittersBudgetSkipped;
373 processedAlive += aliveBefore;
374 continue;
375 }
376
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);
382 }
383 sim->spawnQuota = spawnQuota;
384
385 auto attach = emitter->attach();
386 auto skinSrc = emitter->skinSource();
387 auto gpuSim = emitter->gpuSim();
388 syncEmitterSources(*cfg, *sim, *attach, *skinSrc);
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;
393 if (wantsResident) {
394 sim->recording.invalidate();
395 auto gpuAdvance = advanceResidentGpu(gfx, emitter, step, legacyControls);
396 if (!gpuAdvance) return eve::Result<void>::failure(gpuAdvance.status());
397 handled = std::move(gpuAdvance).takeValue();
398 }
399 if (!handled) {
400 if (legacyControls)
401 advanceEmitterSim(*cfg, *sim, dt);
402 else {
403 auto cpuAdvance = advanceEmitterSim(*cfg, *sim, step);
404 if (!cpuAdvance) return eve::Result<void>::failure(cpuAdvance.status());
405 }
406 }
407 ++stats.emittersSimulated;
408 processedAlive += liveParticleCount(emitter);
409 if (budget.maxParticles > 0 || cfg->maxSpawnPerFrame > 0) sim->spawnQuota = 0;
410 }
411
412 stats.particlesAfter = 0;
413 stats.particlesSpawned = 0;
414 stats.droppedSpawns = 0;
415 for (auto *emitter : allEmitters) {
416 auto sim = emitter->sim();
417 auto gpu = emitter->gpuSim();
418 stats.particlesAfter += liveParticleCount(emitter);
419 stats.particlesSpawned += sim->spawnedThisFrame;
420 stats.droppedSpawns += sim->droppedSpawnsThisFrame;
421 if (gpu->residentActive) {
422 ++stats.gpuResidentEmitters;
423 stats.gpuResidentParticles += gpu->estimatedAlive;
424 }
425 sim->spawnQuota = -1;
426 }
427 stats.particlesKilled =
428 std::max(0, stats.particlesBefore + stats.particlesSpawned - stats.particlesAfter);
429 stats.simulationMs =
430 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin)
431 .count();
432
433 if (!legacyControls) {
434 for (auto *emitter : allEmitters) {
435 auto sim = emitter->sim();
436 sim->simulationTick = step.tick;
437 sim->hasSimulationTick = true;
438 }
439 }
440 mutableParticleFrameStats() = nextStats;
442}
443
447
450 if (!duration) {
451 duration.ignore("legacy particle update received an invalid duration");
452 return;
453 }
454 runParticleSimulation({eve::SimulationTick(1), std::move(duration).takeValue()}, true)
455 .ignore("legacy particle update facade");
456}
457
458namespace {
459int appendOneEmitter(graphics::Graphics& gfx, ParticleEmitter& emitter,
460 std::vector<graphics::DrawItem2D>& items, int& order,
461 bool respectSceneCulling, bool& usedCanvas, bool& culled) {
462 auto cfg = emitter.config(); auto sim = emitter.sim(); auto draw = emitter.draw();
463 auto gpu = emitter.gpuSim(); const int alive = liveParticleCount(&emitter);
464 if (!draw->visible || alive <= 0) return 0;
465 const auto& budget = particleBudgetConfig();
466 if (respectSceneCulling &&
467 (budget.qualityLevel < cfg->minimumQuality || emitterOffscreen(*cfg, *draw))) {
468 culled = true; return 0;
469 }
470 if (gpu->residentActive) {
472 gpuDraw.texture = draw->texture; gpuDraw.sceneDepth = gfx.getSceneLinearDepthTexture();
473 gpuDraw.blend = draw->blend; gpuDraw.viewportWidth = float(gfx.getWidth());
474 gpuDraw.viewportHeight = float(gfx.getHeight());
475 if (draw->camera) { gpuDraw.cameraEnabled = true; gpuDraw.cameraX = draw->camera->data()->x;
476 gpuDraw.cameraY = draw->camera->data()->y; gpuDraw.cameraZoom = draw->camera->data()->zoom; }
477 gpuDraw.particleWidth = cfg->particleW; gpuDraw.particleHeight = cfg->particleH;
478 gpuDraw.sizeStart = cfg->sizeStart; gpuDraw.sizeEnd = cfg->sizeEnd;
479 gpuDraw.stretchFactor = cfg->stretchFactor;
480 gpuDraw.facing = cfg->renderMode == "stretched" ? graphics::GpuParticleFacingMode::Velocity
481 : cfg->renderMode == "axis" ? graphics::GpuParticleFacingMode::Axis
482 : cfg->renderMode == "ribbon" ? graphics::GpuParticleFacingMode::Ribbon
484 gpuDraw.axisRotationRadians = cfg->renderAxisDegrees / kRad2Deg;
485 gpuDraw.ribbonWidth = cfg->ribbonWidth;
486 gpuDraw.ribbonMinSegmentLength = cfg->ribbonMinSegmentLength;
487 gpuDraw.softParticles = cfg->softParticles; gpuDraw.particleDepth = cfg->softParticleDepth;
488 gpuDraw.softFadeDistance = cfg->softFadeDistance;
489 gpuDraw.colorStart[0]=cfg->colorStart.r; gpuDraw.colorStart[1]=cfg->colorStart.g;
490 gpuDraw.colorStart[2]=cfg->colorStart.b; gpuDraw.colorStart[3]=cfg->colorStart.a;
491 gpuDraw.colorEnd[0]=cfg->colorEnd.r; gpuDraw.colorEnd[1]=cfg->colorEnd.g;
492 gpuDraw.colorEnd[2]=cfg->colorEnd.b; gpuDraw.colorEnd[3]=cfg->colorEnd.a;
493 gpuDraw.hframes=cfg->hframes; gpuDraw.vframes=cfg->vframes;
494 gpuDraw.sortMode = cfg->renderMode == "ribbon" ? graphics::GpuParticleSortMode::Birth
495 : cfg->sortMode == "oldest" ? graphics::GpuParticleSortMode::Oldest
496 : cfg->sortMode == "youngest" ? graphics::GpuParticleSortMode::Youngest
497 : cfg->sortMode == "distance" ? graphics::GpuParticleSortMode::Distance
499 if (auto* gp = gfx.gpuParticles(); gp && gp->drawGpuParticleEmitter(gpu->residentHandle, gpuDraw))
500 return gpu->estimatedAlive;
501 culled = true; return 0;
502 }
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;
506}
507}
508
510 if (!gfx || !emitter) return 0;
511 std::vector<graphics::DrawItem2D> items; bool usedCanvas=false, culled=false;
512 int order=0;
513 const int rendered=appendOneEmitter(*gfx,*emitter,items,order,false,usedCanvas,culled);
514 if(!items.empty()) graphics::RenderSystem::drawItems(*gfx,items,false);
515 if (usedCanvas) gfx->setCanvas();
516 return rendered;
517}
518
521 stats.renderedParticles = 0;
522 stats.renderCulledEmitters = 0;
523 stats.renderMs = 0.0;
524 const auto begin = std::chrono::steady_clock::now();
525 if (!gfx) return;
526 if (ecs::current()->getManager<ParticleEmitter>() == nullptr) return;
527
528 std::vector<graphics::DrawItem2D> items;
531 bool anyCanvas = false;
532 int order = 0;
533 for (auto it = view.begin(); it != view.end(); ++it) {
534 auto [cfg, sim, draw] = *it; (void)sim; (void)draw;
535 auto* emitter = cfg->entity;
536 if (!emitter) continue;
537 bool culled=false;
538 stats.renderedParticles += appendOneEmitter(*gfx,*emitter,items,order,true,anyCanvas,culled);
539 if(culled) ++stats.renderCulledEmitters;
540 }
541
542 // Unified 2D sprite path: rotation / flipbook UV / blend / layer sorting
543 // and camera handling all come from RenderSystem::drawItems.
544 if (!items.empty()) graphics::RenderSystem::drawItems(*gfx, items, false);
545 if (anyCanvas) gfx->setCanvas();
546 stats.renderMs =
547 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin)
548 .count();
549}
550
552 if (ecs::current()->getManager<ParticleEmitter>() == nullptr) return;
553
554 // Pass 1: collect emitters. Creating Light2D entities inside a deferred
555 // View would stage them and invalidate stored raw pointers on publish.
556 std::vector<ParticleEmitter *> emitters;
557 {
558 auto view = ecs::View<ParticleEmitter, ParticleEmitter::Config>();
559 for (auto it = view.begin(); it != view.end(); ++it) {
560 auto [cfg] = *it;
561 if (cfg->entity) emitters.push_back(cfg->entity);
562 }
563 }
564
565 // Pass 2: create/sync lights with no View active (stable entity pointers).
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);
574 continue;
575 }
576 const int maxL = cfg->lights.max > 0 ? (cfg->lights.max > 8 ? 8 : cfg->lights.max) : 0;
577 while (int(lights->pool.size()) < maxL)
578 lights->pool.push_back(graphics::Light2D::createLight());
579 const int n = sim->alive < maxL ? sim->alive : maxL;
580 for (int i = 0; i < maxL; ++i) {
581 graphics::Light2D *l = lights->pool[size_t(i)];
582 if (i < n) {
583 const Particle &p = sim->particles[size_t(i)];
584 l->setPosition(p.x, p.y);
585 l->setRadius(cfg->lights.radius);
586 l->setColor(cfg->lights.r, cfg->lights.g, cfg->lights.b, cfg->lights.intensity);
587 l->setCanvas(draw->canvas);
588 l->setEnabled(true);
589 } else {
590 l->setEnabled(false);
591 }
592 }
593 }
594}
595
597 if (ecs::current()->getManager<ParticleEmitter>() == nullptr) return 0;
598
599 // Watch events are drained by load.nut / HotReload. This polling path is a
600 // deliberate, explicit file-state observation for hosts that do not
601 // deliver a watch event; its result is recorded on each Resource.
602 int reloaded = 0;
603 auto view =
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()) {
610 continue;
611 }
612 if (!res->autoReload) {
614 continue;
615 }
616
617 const int64_t mt = fileModtime(res->path);
618 if (mt < 0) {
620 continue;
621 }
622 if (mt == res->modtime) {
624 continue;
625 }
626 if (reloadConfigFile(cfg->entity, nullptr)) {
628 ++reloaded;
629 } else {
631 }
632 }
633 return reloaded;
634}
635
636} // namespace eve::particles
double z
float duration
glm::vec4 p[6]
std::vector< eve::ProcgenProbeDesc > lights
std::uint32_t alive
std::uint32_t capacity
glm::vec3 n
Definition Grass.cpp:63
std::vector< std::uint32_t > indices
int h
float length
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
MeshVfxBatchedDraw draw
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec3 dx
double dt
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
gpgpu::Gpgpu & gp
Definition OnnxGpgpu.cpp:42
std::vector< BakedParticleSample > particles
std::string path
Definition PlayHost.cpp:111
std::vector< EquipmentStat > stats
ScriptStructure out
size_t begin
double current
float dy
Definition Shadow.cpp:151
std::unique_ptr< TrailEmitter > emitter
int margin
int segments
Definition TreeMesh.cpp:281
float step
Definition TreeMesh.cpp:451
uint32_t index
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.
Definition Time.cpp:17
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
virtual Texture * getSceneLinearDepthTexture()
Sampleable scene linear depth in [0,1], or nullptr when unavailable.
Definition Graphics.h:1077
virtual IGpuParticles * gpuParticles() noexcept
Borrow the backend particle compute surface when present.
Definition Graphics.h:344
int getWidth() const
Returns the width.
Definition Graphics.h:489
virtual void setCanvas(Canvas *canvas)=0
nullptr or this → screen. Switching flushes pending draws to the previous target.
int getHeight() const
Returns the height.
Definition Graphics.h:491
Declarative 2D light. Collected by RenderSystem (max 8 per canvas/frame). type: "point" | "dir" | "sp...
Definition Light.h:63
void setPosition(float x, float y)
Definition Light.cpp:38
void setColor(float r, float g, float b, float intensity=1.f)
Definition Light.cpp:54
void setCanvas(Canvas *canvas)
Definition Light.cpp:89
void setEnabled(bool enabled)
Definition Light.cpp:75
static Light2D * createLight(const std::string &type="point")
Definition Light.cpp:8
void setRadius(float radius)
Definition Light.cpp:62
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 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.
Definition Time.h:31
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Parameters for rendering a resident GPU particle emitter.
GpuParticleSortMode sortMode
GpuParticleFacingMode facing
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).
glm::uvec4 info