Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ParticlePlugin.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 "ParticlePlugin.hpp"
7#ifdef ES_ENABLE_GPU_PARTICLES
9#endif
10#include "../rhi/Shader.hpp"
12#include "../rhi/Texture.hpp"
13#include "../draw/BatchVertex.hpp" // packColor
19
21#include <algorithm>
22#include <string>
23#include <cmath>
24
25namespace esengine {
26
27namespace {
28struct ParticleInstanceData {
29 f32 px, py, pz;
30 f32 sx, sy;
31 f32 rotation;
32 u32 color;
33 f32 uvOffsetX, uvOffsetY;
34 f32 uvScaleX, uvScaleY;
35 f32 age, random, intensity, lifetime;
36};
37static_assert(sizeof(ParticleInstanceData) == PARTICLE_INSTANCE_STRIDE, "instance stride must match the VAO layout");
38} // namespace
39
41 // Whether emitters that ask to simulate on the GPU can: the device says, and the CPU sim falls back where it cannot.
42#ifdef ES_ENABLE_GPU_PARTICLES
43 if (particle_system_ && ctx.frame && ctx.frame->gpuParticles()) {
44 particle_system_->setGpuAvailable(ctx.frame->gpuParticles()->available());
45 }
46#endif
47 // Particle instancing shader, authored as particle.esshader (single source,
48 // WGSL twin included) and embedded for the web build. Attribute locations
49 // are explicit, so no name bindings.
50 if (particle_shader_handle_.isValid()) ctx.resources.releaseShader(particle_shader_handle_);
51 const auto target = ctx.resources.preferredShaderTarget();
53 // The same feature a material's particle variant is compiled with, so the
54 // built-in fragment and an authored one sit on one vertex stage.
55 const std::vector<std::string> features{ "PARTICLE" };
56 resource::ShaderHandle& handle = particle_shader_handle_;
57 handle = ctx.resources.createShaderWithBindings(
60 {}, ctx.resources.preferredShaderLanguage(), ctx.resources.deferLinks());
61 Shader* shader = ctx.resources.getShader(handle);
62 if (shader && shader->isValid()) {
63 particle_shader_id_ = shader->getProgramId();
64 if (shader->language() == GfxShaderLanguage::GLSL_ES300) {
65 // Sampler seeding is a GLSL concept; on WGSL the texture rides the
66 // bind group. After it links: at once, or when a draw first needs it.
67 shader->whenLinked([](Shader& s) {
68 s.bind();
69 for (i32 unit = 0; unit < 8; ++unit) {
70 s.setUniform("u_textures[" + std::to_string(unit) + "]", unit);
71 }
72 s.unbind();
73 });
74 }
75 }
76}
77
79 auto& registry = collect_ctx.registry;
80 auto& clips = collect_ctx.clip_state;
81 auto& buffers = collect_ctx.buffer_pool;
82 auto& draw_list = collect_ctx.draw_list;
83 auto& ctx = collect_ctx.frame_context;
84 if (!particle_system_ || particle_shader_id_ == 0) return;
85
86 auto emitterView = registry.activeView<ecs::Transform, ecs::ParticleEmitter>();
87
88 for (auto entity : emitterView) {
89 if (!collect_ctx.accepts(entity)) continue;
90 const auto& emitter = emitterView.get<ecs::ParticleEmitter>(entity);
91 if (!emitter.enabled) continue;
92
93 auto& transform = emitterView.get<ecs::Transform>(entity);
94 transform.ensureDecomposed();
95
96 const auto* state = particle_system_->getState(entity);
97 if (!state) continue;
98
99 // A GPU emitter's particles are in a buffer a kernel writes: this frame's step is queued, and the draw is told
100 // where to read them. The CPU has nothing per particle to do.
101 BufferHandle gpuInstances = BufferHandle::Invalid;
103 u32 gpuSegmentCount = 0;
104 u32 particleCount = 0;
105 if (state->gpu) {
106#ifdef ES_ENABLE_GPU_PARTICLES
107 GpuParticles* gpu = ctx.frame ? ctx.frame->gpuParticles() : nullptr;
108 // The screen's overlay is not drawn through the graph the kernel runs in.
109 if (!gpu || collect_ctx.isOverlay()) continue;
110 buffers.reserveStream(LayoutId::ParticleInstance);
112 if (!particle_system_->peekGpuStep(entity, step)) continue;
113 if (!gpu->submit(entity, emitter, transform, *particle_system_, step, collect_ctx.camera.eye, gpuInstances, gpuSegments, gpuSegmentCount)) continue;
114 particleCount = step.drawCount;
115#else
116 continue; // no compute in this build: ParticleSystem never marks an emitter GPU-simulated
117#endif
118 } else {
119 particleCount = state->pool.aliveCount();
120 }
121 if (particleCount == 0) continue;
122
123 u32 textureId = ctx.white_texture_id;
124 if (emitter.texture.isValid()) {
125 Texture* tex = ctx.resources.getTexture(emitter.texture);
126 if (tex) textureId = tex->getId();
127 }
128
129 i32 cols = std::max(emitter.spriteColumns, 1);
130 i32 rows = std::max(emitter.spriteRows, 1);
131 f32 uvScaleX = 1.0f / static_cast<f32>(cols);
132 f32 uvScaleY = 1.0f / static_cast<f32>(rows);
133 bool sheet = (cols > 1 || rows > 1);
134
135 bool isLocalSpace = emitter.simulationSpace ==
136 static_cast<i32>(ecs::SimulationSpace::Local);
137 glm::vec3 emitterWorldPos = rebased(transform.worldPosition);
138 f32 emitterAngle = 0.0f;
139 glm::vec2 emitterScale(transform.worldScale);
140 f32 cosA = 1.0f, sinA = 0.0f;
141 if (isLocalSpace) {
142 const auto& rot = transform.worldRotation;
143 emitterAngle = 2.0f * std::atan2(rot.z, rot.w);
144 if (std::abs(emitterAngle) > 0.001f) {
145 cosA = std::cos(emitterAngle);
146 sinA = std::sin(emitterAngle);
147 }
148 }
149
150 BlendMode blendMode = static_cast<BlendMode>(emitter.blendMode);
151
152 u32 instByteOffset = 0;
153 ParticleInstanceData* inst = nullptr;
154 if (!state->gpu) {
155 instByteOffset = buffers.allocVertices(LayoutId::ParticleInstance,
156 particleCount * sizeof(ParticleInstanceData));
157 inst = reinterpret_cast<ParticleInstanceData*>(
158 buffers.vertexData(LayoutId::ParticleInstance) + instByteOffset);
159 }
160
161 const bool stretched = emitter.renderMode == static_cast<i32>(ecs::ParticleRenderMode::Stretched);
162 const f32 lengthScale = emitter.lengthScale;
163 const f32 velocityScale = emitter.velocityScale;
164 const f32 intensity = std::max(emitter.intensity, 0.0f);
165
166 u32 i = 0;
167 if (!state->gpu) state->pool.forEachAlive([&](const particle::Particle& p) {
168 glm::vec3 worldPos;
169 glm::vec2 size;
170 if (isLocalSpace) {
171 // The emitter's own turn is about Z, as a flat scene's is; depth
172 // rides through it untouched rather than being dropped.
173 glm::vec3 rel = p.position * glm::vec3(emitterScale, 1.0f);
174 if (std::abs(emitterAngle) > 0.001f) {
175 worldPos = emitterWorldPos +
176 glm::vec3(rel.x * cosA - rel.y * sinA, rel.x * sinA + rel.y * cosA, rel.z);
177 } else {
178 worldPos = emitterWorldPos + rel;
179 }
180 size = glm::vec2(p.size) * emitterScale;
181 } else {
182 worldPos = rebased(p.position);
183 size = glm::vec2(p.size);
184 }
185
186 f32 u0 = 0.0f, v0 = 0.0f;
187 if (sheet) {
188 i32 col = p.sprite_frame % cols;
189 i32 row = p.sprite_frame / cols;
190 u0 = static_cast<f32>(col) * uvScaleX;
191 v0 = static_cast<f32>(row) * uvScaleY;
192 }
193
194 f32 rotation = p.rotation;
195 if (stretched) {
196 glm::vec3 v = p.velocity + p.added_velocity;
197 if (isLocalSpace) {
198 const glm::vec2 flat = glm::vec2(v) * emitterScale;
199 v = glm::vec3(flat.x * cosA - flat.y * sinA, flat.x * sinA + flat.y * cosA, v.z);
200 }
201 const glm::vec2 seen = particle::velocityOnScreen(v, towardViewer(worldPos, collect_ctx.camera));
202 const particle::StretchedQuad quad = particle::stretchedQuad(seen, rotation, size.y, lengthScale, velocityScale);
203 rotation = quad.rotation;
204 size.y = quad.length;
205 }
206
207 ParticleInstanceData& d = inst[i++];
208 d.px = worldPos.x; d.py = worldPos.y; d.pz = worldPos.z;
209 d.sx = size.x; d.sy = size.y;
210 d.rotation = rotation;
211 d.color = packColor(p.color);
212 d.uvOffsetX = u0; d.uvOffsetY = v0;
213 d.uvScaleX = sheet ? uvScaleX : 1.0f;
214 d.uvScaleY = sheet ? uvScaleY : 1.0f;
215 d.age = p.lifetime > 0.0f ? std::min(p.age / p.lifetime, 1.0f) : 1.0f;
216 d.random = particle::unitHash(p.generation);
217 d.intensity = intensity;
218 d.lifetime = p.lifetime;
219 });
220
221 // A material owns shading fully: its program is this one compiled for the
222 // particle vertex source, so the author's fragment sees the same quad the
223 // built-in one does. A handle nothing registered draws plainly.
224 u32 shaderId = particle_shader_id_;
225 u32 materialId = 0;
226 BlendMode blend = blendMode;
227 // A material says how its particles meet the depth of the scene, as it does for a sprite or a trail: without one they are the
228 // flat quads a 2D scene draws, which test nothing.
229 bool materialDepth = false, depthTest = false, depthWrite = false;
230 if (emitter.material != 0 && ctx.materials) {
231 if (const MaterialRecord* m = ctx.materials->find(emitter.material)) {
232 const u32 program = ctx.materials->particleProgram(emitter.material, ctx.resources);
233 if (program != 0) {
234 shaderId = program;
235 materialId = emitter.material;
236 blend = m->blend;
237 materialDepth = true;
238 depthTest = m->depthTest;
239 depthWrite = m->depthWrite;
240 }
241 }
242 }
243
244 const i32 layer = collect_ctx.treeLayer(entity, emitter.layer);
245 BatchDrawKey key{
246 .stage = ctx.current_stage,
247 .layer = layer,
248 .shaderId = shaderId,
249 .blend = blend,
250 .textureId = textureId,
251 .depth = collect_ctx.sortDepth(emitterWorldPos),
252 // Sorted by world Y like every other draw — a burst left at y = 0
253 // loses to any sprite standing anywhere else, so an emitter placed on
254 // a character disappears behind them.
255 .y = emitterWorldPos.y,
256 .entity = entity,
257 .type = RenderType::Particle,
258 .materialId = materialId,
259 .layoutId = LayoutId::ParticleInstance,
260 .instanceCount = particleCount,
261 .instanceBuffer = gpuInstances,
262 };
263 if (materialDepth) {
264 key.depthTest = depthTest;
265 key.depthWrite = depthWrite;
266 }
267 // The stream's static unit-quad indices (offset 0) drawn once per particle,
268 // with the instance slice based at instByteOffset.
269 pushBatchDraw(draw_list, clips, instByteOffset, 0, 0, 6, key);
270
271 // A kernel writes a GPU emitter's trails as quads the particle draw already knows how to draw.
272 if (gpuSegments != BufferHandle::Invalid && gpuSegmentCount > 0) {
273 BatchDrawKey segmentKey = key;
274 segmentKey.textureId = ctx.white_texture_id;
275 segmentKey.instanceCount = gpuSegmentCount;
276 segmentKey.instanceBuffer = gpuSegments;
277 pushBatchDraw(draw_list, clips, 0, 0, 0, 6, segmentKey);
278 }
279
280 // --- Per-particle trails --------------------------------------------------
281 // Each live particle drags a tapering ribbon along its recorded path. Built on
282 // the CPU and streamed through the Batch face (triangle strip), exactly like the
283 // standalone TrailRenderer — no new GPU path. Off unless the emitter opts in.
284 if (!state->gpu && emitter.trailEnabled && emitter.trailWidth > 0.0f &&
285 state->trail_count.size() == state->pool.particles().size()) {
286 BatchDrawKey trailKey{
287 .stage = ctx.current_stage,
288 .layer = layer,
289 .shaderId = ctx.batch_shader_id,
290 .blend = blendMode,
291 .textureId = ctx.white_texture_id,
292 .depth = collect_ctx.sortDepth(emitterWorldPos),
293 .y = emitterWorldPos.y,
294 .entity = entity,
295 .type = RenderType::Trail,
296 };
297 const int keep = std::min(std::max(emitter.trailPoints, 2), particle::kMaxTrailPoints);
298 const auto& particles = state->pool.particles();
299 auto toWorld = [&](glm::vec3 pos) -> glm::vec3 {
300 if (!isLocalSpace) return pos;
301 glm::vec3 rel = pos * glm::vec3(emitterScale, 1.0f);
302 if (std::abs(emitterAngle) > 0.001f)
303 return emitterWorldPos +
304 glm::vec3(rel.x * cosA - rel.y * sinA, rel.x * sinA + rel.y * cosA, rel.z);
305 return emitterWorldPos + rel;
306 };
307
308 for (std::size_t idx = 0; idx < particles.size(); ++idx) {
309 const particle::Particle& p = particles[idx];
310 if (!p.alive || state->trail_count[idx] == 0) continue;
311 const glm::vec3* ring = &state->trail_pos[idx * particle::kMaxTrailPoints];
312
313 // Centerline: recorded points (oldest→newest) then the live head.
314 trail_center_.clear();
315 int m = std::min<int>(state->trail_count[idx], keep);
316 for (int k = 0; k < m; ++k) trail_center_.push_back(toWorld(ring[k]));
317 glm::vec3 head = toWorld(p.position);
318 glm::vec3 dHead = head - trail_center_.back();
319 if (glm::dot(dHead, dHead) > 1e-4f) trail_center_.push_back(head);
320 const int n = static_cast<int>(trail_center_.size());
321 if (n < 2) continue;
322
323 // 2 verts per point: t runs 0 at the faded zero-width tail (oldest) → 1
324 // at the full-width head carrying the particle's current colour.
325 // Widened along ribbonSide, so a trail whose centreline leaves the
326 // XY plane still presents its width to the viewer.
327 trail_verts_.clear();
328 glm::vec3 lastTangent(1.0f, 0.0f, 0.0f);
329 glm::vec3 lastSide(0.0f, 1.0f, 0.0f);
330 for (int j = 0; j < n; ++j) {
331 const glm::vec3& a = trail_center_[j == 0 ? 0 : j - 1];
332 const glm::vec3& b = trail_center_[j + 1 == n ? j : j + 1];
333 glm::vec3 seg = b - a;
334 f32 len = glm::length(seg);
335 glm::vec3 tangent = len > 1e-6f ? seg / len : lastTangent;
336 lastTangent = tangent;
337
338 f32 t = static_cast<f32>(j) / static_cast<f32>(n - 1);
339 f32 halfW = 0.5f * emitter.trailWidth * t;
340 glm::vec4 col = p.color;
341 col.a *= t;
342 u32 packed = packColor(col);
343
344 const glm::vec3& c = trail_center_[j];
345 const glm::vec3 side = ribbonSide(tangent, c, collect_ctx.camera, lastSide);
346 lastSide = side;
347 trail_verts_.push_back({c + side * halfW, packed, glm::vec2(1.0f - t, 0.0f)});
348 trail_verts_.push_back({c - side * halfW, packed, glm::vec2(1.0f - t, 1.0f)});
349 }
350
351 trail_indices_.clear();
352 for (int j = 0; j + 1 < n; ++j) {
353 u32 l0 = static_cast<u32>(j) * 2, r0 = l0 + 1, l1 = l0 + 2, r1 = l0 + 3;
354 trail_indices_.push_back(l0); trail_indices_.push_back(r0); trail_indices_.push_back(r1);
355 trail_indices_.push_back(l0); trail_indices_.push_back(r1); trail_indices_.push_back(l1);
356 }
357
358 appendIndexedBatch(buffers, draw_list, clips,
359 trail_verts_.data(), static_cast<u32>(trail_verts_.size()),
360 trail_indices_.data(), static_cast<u32>(trail_indices_.size()),
361 trailKey);
362 }
363 }
364 }
365}
366
367} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
Particles simulated by a compute kernel, drawn from the buffer the kernel wrote (WebGPU).
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
Parser for unified .esshader file format.
GPU shader program abstraction.
GPU texture abstraction for 2D images.
Unified Transform component with local and world-space data.
bool submit(Entity entity, const ecs::ParticleEmitter &emitter, const ecs::Transform &transform, particle::ParticleSystem &system, const particle::GpuStep &step, const glm::vec4 &eye, BufferHandle &instances, BufferHandle &segments, u32 &segmentCount)
Queues the step an emitter needs and says where its particles are. The step is committed to the emitt...
void init(RenderFrameContext &ctx) override
void collect(RenderCollectContext &ctx) override
GPU shader program for rendering.
Definition Shader.hpp:86
u32 getProgramId() const
Gets the program handle's raw value, for command payloads and sort keys.
Definition Shader.hpp:257
void bind() const
Binds the shader for rendering.
Definition Shader.cpp:151
GfxShaderLanguage language() const
The source language this program was compiled from.
Definition Shader.hpp:126
void whenLinked(std::function< void(Shader &)> fn)
Runs fn on this shader once it has linked: at once for one that has.
Definition Shader.cpp:164
void setUniform(const std::string &name, i32 value) const
Sets an integer uniform.
Definition Shader.cpp:422
bool isValid() const
Checks if the shader compiled and linked successfully.
Definition Shader.hpp:251
void unbind() const
Unbinds the shader.
Definition Shader.cpp:173
2D texture for GPU rendering
Definition Texture.hpp:116
u32 getId() const
Gets the texture handle's raw value, for command payloads and the WASM boundary.
Definition Texture.hpp:236
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
constexpr const char * PARTICLE
constexpr int kMaxTrailPoints
f32 unitHash(u32 v)
Definition Particle.hpp:32
StretchedQuad stretchedQuad(glm::vec2 velocity, f32 rotation, f32 size, f32 lengthScale, f32 velocityScale)
glm::vec2 velocityOnScreen(const glm::vec3 &velocity, const glm::vec3 &towardViewer)
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
void pushBatchDraw(DrawList &drawList, const ClipState &clips, u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount, const BatchDrawKey &key)
Atomic primitive: assemble + clip + push one DrawCommand for an index range ALREADY written into (or,...
u32 packColor(f32 r, f32 g, f32 b, f32 a)
glm::vec3 towardViewer(const glm::vec3 &worldPos, const CameraView &camera)
Decomposes transform and returns its world position shifted toward the camera by (1 - parallax); fact...
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
void appendIndexedBatch(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies verts into the Batch stream, then pushes one DrawCommand spanning them.
@ ParticleInstance
Instanced: a static unit quad + a per-particle instance stream.
Definition GfxEnums.hpp:90
static constexpr u32 PARTICLE_INSTANCE_STRIDE
Definition GfxEnums.hpp:122
static EstellaContext & ctx()
glm::vec3 ribbonSide(const glm::vec3 &tangent, const glm::vec3 &worldPos, const CameraView &camera, const glm::vec3 &lastSide)
The side vector a ribbon widens along: perpendicular to both its path and the viewer,...
float f32
32-bit floating point
Definition Types.hpp:59
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
A material's resolved render state (P0) plus its packed std140 constants (P1).
f32 sortDepth(const glm::vec3 &worldPos) const
The sort depth of a draw anchored at worldPos.
bool accepts(Entity entity) const
Whether entity belongs to THIS collect.
i32 treeLayer(Entity entity, i32 authored) const
The layer entity draws at: its place in a Canvas's tree, unless its author named one.
bool isOverlay() const
Whether this collect is the frame's screen overlay.
Unified transform component.
Definition Transform.hpp:45
What one frame asks of a GPU-simulated emitter: how long to advance, how many to spawn and where in t...
glm::vec3 added_velocity
Carried on top of velocity, outside gravity, damping and the speed limit.
Definition Particle.hpp:15
How a stretched particle's quad is laid along its velocity.
f32 rotation
Radians, counter-clockwise, turning the quad's +Y onto the velocity.
f32 length
The quad's extent along its Y.