Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ParticleEmitter.h"
21 :
22 : #include "graphics/LOSTexture.h"
23 : #include "graphics/LightEnv.h"
24 : #include "graphics/ParticleEmitterType.h"
25 : #include "graphics/ParticleManager.h"
26 : #include "graphics/RenderableObject.h"
27 : #include "graphics/TextureManager.h"
28 : #include "lib/debug.h"
29 : #include "maths/Matrix3D.h"
30 : #include "ps/CStrIntern.h"
31 : #include "ps/CStrInternStatic.h"
32 : #include "ps/memory/AllocatorAdapter.h"
33 : #include "ps/memory/LinearAllocator.h"
34 : #include "renderer/Renderer.h"
35 : #include "renderer/Scene.h"
36 : #include "renderer/SceneRenderer.h"
37 : #include "renderer/backend/Format.h"
38 : #include "renderer/backend/IBuffer.h"
39 : #include "renderer/backend/IDeviceCommandContext.h"
40 : #include "renderer/backend/IShaderProgram.h"
41 :
42 : #include <array>
43 : #include <cmath>
44 : #include <cstdint>
45 :
46 : namespace
47 : {
48 :
49 : struct ParticleYoungestInFrontCompare
50 : {
51 0 : bool operator()(const SParticle& lhs, const SParticle& rhs) const
52 : {
53 0 : return lhs.age > rhs.age;
54 : }
55 : };
56 :
57 : struct ParticleOldestInFrontCompare
58 : {
59 0 : bool operator()(const SParticle& lhs, const SParticle& rhs) const
60 : {
61 0 : return lhs.age < rhs.age;
62 : }
63 : };
64 :
65 : struct ParticleClosestInFrontCompare
66 : {
67 0 : bool operator()(const SParticle& lhs, const SParticle& rhs) const
68 : {
69 0 : return cameraForward.Dot(lhs.pos) > cameraForward.Dot(rhs.pos);
70 : }
71 :
72 : CVector3D cameraForward;
73 : };
74 :
75 : } // anonymous namespace
76 :
77 0 : CParticleEmitter::CParticleEmitter(const CParticleEmitterType& type) :
78 0 : m_Type(type), m_LastUpdateTime(type.m_Manager.GetCurrentTime()),
79 0 : m_IndexArray(Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
80 0 : m_VertexArray(Renderer::Backend::IBuffer::Type::VERTEX,
81 : Renderer::Backend::IBuffer::Usage::DYNAMIC | Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
82 0 : m_VertexUVArray(Renderer::Backend::IBuffer::Type::VERTEX,
83 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
84 0 : m_LastFrameNumber(-1), m_UseInstancing{type.m_Manager.ShouldUseInstancing()}
85 : {
86 : // If we should start with particles fully emitted, pretend that we
87 : // were created in the past so the first update will produce lots of
88 : // particles.
89 : // TODO: instead of this, maybe it would make more sense to do a full
90 : // lifetime-length update of all emitters when the game first starts
91 : // (so that e.g. buildings constructed later on won't have fully-started
92 : // emitters, but those at the start will)?
93 0 : if (m_Type.m_StartFull)
94 0 : m_LastUpdateTime -= m_Type.m_MaxLifetime;
95 :
96 0 : m_Particles.reserve(m_Type.m_MaxParticles);
97 :
98 0 : m_AttributePos.format = Renderer::Backend::Format::R32G32B32_SFLOAT;
99 0 : m_VertexArray.AddAttribute(&m_AttributePos);
100 :
101 0 : m_AttributeColor.format = Renderer::Backend::Format::R8G8B8A8_UNORM;
102 0 : m_VertexArray.AddAttribute(&m_AttributeColor);
103 :
104 0 : m_AttributeAxisX.format = Renderer::Backend::Format::R32G32B32A32_SFLOAT;
105 0 : m_VertexArray.AddAttribute(&m_AttributeAxisX);
106 :
107 0 : m_AttributeAxisY.format = Renderer::Backend::Format::R32G32B32A32_SFLOAT;
108 0 : m_VertexArray.AddAttribute(&m_AttributeAxisY);
109 :
110 0 : m_VertexArray.SetNumberOfVertices(m_UseInstancing ? m_Type.m_MaxParticles : m_Type.m_MaxParticles * 4);
111 0 : m_VertexArray.Layout();
112 :
113 0 : m_AttributeUV.format = Renderer::Backend::Format::R32G32_SFLOAT;
114 0 : m_VertexUVArray.AddAttribute(&m_AttributeUV);
115 :
116 0 : m_VertexUVArray.SetNumberOfVertices(m_UseInstancing ? 4 : m_Type.m_MaxParticles * 4);
117 0 : m_VertexUVArray.Layout();
118 :
119 0 : VertexArrayIterator<float[2]> attrUV = m_AttributeUV.GetIterator<float[2]>();
120 0 : for (uint32_t index{0}; index < (m_UseInstancing ? 1u : m_Type.m_MaxParticles); ++index)
121 : {
122 0 : (*attrUV)[0] = 1;
123 0 : (*attrUV)[1] = 0;
124 0 : ++attrUV;
125 0 : (*attrUV)[0] = 0;
126 0 : (*attrUV)[1] = 0;
127 0 : ++attrUV;
128 0 : (*attrUV)[0] = 0;
129 0 : (*attrUV)[1] = 1;
130 0 : ++attrUV;
131 0 : (*attrUV)[0] = 1;
132 0 : (*attrUV)[1] = 1;
133 0 : ++attrUV;
134 : }
135 :
136 0 : m_VertexUVArray.Upload();
137 0 : m_VertexUVArray.FreeBackingStore();
138 :
139 0 : m_IndexArray.SetNumberOfVertices(m_UseInstancing ? 6 : m_Type.m_MaxParticles * 6);
140 0 : m_IndexArray.Layout();
141 0 : VertexArrayIterator<std::uint16_t> index = m_IndexArray.GetIterator();
142 0 : for (std::uint16_t i = 0; i < (m_UseInstancing ? 1 : m_Type.m_MaxParticles); ++i)
143 : {
144 0 : *index++ = i*4 + 0;
145 0 : *index++ = i*4 + 1;
146 0 : *index++ = i*4 + 2;
147 0 : *index++ = i*4 + 2;
148 0 : *index++ = i*4 + 3;
149 0 : *index++ = i*4 + 0;
150 : }
151 0 : m_IndexArray.Upload();
152 0 : m_IndexArray.FreeBackingStore();
153 :
154 0 : const uint32_t stride{m_VertexArray.GetStride()};
155 0 : const Renderer::Backend::VertexAttributeRate dynamicDataRate{
156 0 : m_UseInstancing
157 0 : ? Renderer::Backend::VertexAttributeRate::PER_INSTANCE
158 : : Renderer::Backend::VertexAttributeRate::PER_VERTEX};
159 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 5> attributes{{
160 : {Renderer::Backend::VertexAttributeStream::UV0,
161 0 : m_AttributeUV.format, m_AttributeUV.offset, m_VertexUVArray.GetStride(),
162 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
163 : {Renderer::Backend::VertexAttributeStream::POSITION,
164 0 : m_AttributePos.format, m_AttributePos.offset, stride,
165 : dynamicDataRate, 1},
166 : {Renderer::Backend::VertexAttributeStream::COLOR,
167 0 : m_AttributeColor.format, m_AttributeColor.offset, stride,
168 : dynamicDataRate, 1},
169 : {Renderer::Backend::VertexAttributeStream::UV1,
170 0 : m_AttributeAxisX.format, m_AttributeAxisX.offset, stride,
171 : dynamicDataRate, 1},
172 : {Renderer::Backend::VertexAttributeStream::UV2,
173 0 : m_AttributeAxisY.format, m_AttributeAxisY.offset, stride,
174 : dynamicDataRate, 1},
175 0 : }};
176 0 : m_VertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
177 0 : }
178 :
179 0 : void CParticleEmitter::UpdateArrayData(int frameNumber)
180 : {
181 0 : if (m_LastFrameNumber == frameNumber)
182 0 : return;
183 :
184 0 : PS::Memory::ScopedLinearAllocator scopedLinearAllocator{g_Renderer.GetLinearAllocator()};
185 :
186 0 : using ParticlesVector = std::vector<SParticle, PS::Memory::AllocatorAdapter<SParticle, PS::Memory::ScopedLinearAllocator>>;
187 0 : ParticlesVector sortedParticles((ParticlesVector::allocator_type(scopedLinearAllocator)));
188 :
189 0 : m_LastFrameNumber = frameNumber;
190 :
191 : // Update m_Particles
192 0 : m_Type.UpdateEmitter(*this, m_Type.m_Manager.GetCurrentTime() - m_LastUpdateTime);
193 0 : m_LastUpdateTime = m_Type.m_Manager.GetCurrentTime();
194 :
195 : // Regenerate the vertex array data:
196 :
197 0 : VertexArrayIterator<CVector3D> attrPos = m_AttributePos.GetIterator<CVector3D>();
198 0 : VertexArrayIterator<SColor4ub> attrColor = m_AttributeColor.GetIterator<SColor4ub>();
199 0 : VertexArrayIterator<CVector4D> attrAxisX = m_AttributeAxisX.GetIterator<CVector4D>();
200 0 : VertexArrayIterator<CVector4D> attrAxisY = m_AttributeAxisY.GetIterator<CVector4D>();
201 :
202 0 : ENSURE(m_Particles.size() <= m_Type.m_MaxParticles);
203 :
204 0 : CBoundingBoxAligned bounds;
205 :
206 0 : if (m_Type.m_SortMode != CParticleEmitterType::SortMode::UNSPECIFIED)
207 : {
208 0 : sortedParticles.insert(sortedParticles.end(), m_Particles.begin(), m_Particles.end());
209 :
210 0 : switch (m_Type.m_SortMode)
211 : {
212 0 : case CParticleEmitterType::SortMode::YOUNGEST_IN_FRONT:
213 0 : std::sort(sortedParticles.begin(), sortedParticles.end(), ParticleYoungestInFrontCompare{});
214 : break;
215 0 : case CParticleEmitterType::SortMode::OLDEST_IN_FRONT:
216 0 : std::sort(sortedParticles.begin(), sortedParticles.end(), ParticleOldestInFrontCompare{});
217 : break;
218 0 : case CParticleEmitterType::SortMode::CLOSEST_IN_FRONT:
219 0 : std::sort(sortedParticles.begin(), sortedParticles.end(), ParticleClosestInFrontCompare{
220 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetOrientation().GetIn()});
221 : break;
222 : default:
223 : break;
224 : }
225 : }
226 :
227 0 : m_NumberOfVisibleParticles = 0;
228 :
229 0 : const std::span<SParticle> particles{
230 0 : m_Type.m_SortMode == CParticleEmitterType::SortMode::UNSPECIFIED ?
231 0 : std::span<SParticle>{m_Particles} : std::span<SParticle>{sortedParticles}};
232 :
233 0 : if (m_UseInstancing)
234 : {
235 0 : for (const SParticle& particle : particles)
236 : {
237 0 : if (particle.age > particle.maxAge || particle.color.A == 0)
238 0 : continue;
239 :
240 0 : ++m_NumberOfVisibleParticles;
241 :
242 0 : bounds += particle.pos;
243 :
244 0 : *attrPos++ = particle.pos;
245 :
246 0 : SColor4ub color{particle.color};
247 :
248 : // Special case: If the blending depends on the source color, not the source alpha,
249 : // then pre-multiply by the alpha. (This is kind of a hack.)
250 0 : if (m_Type.m_BlendMode == CParticleEmitterType::BlendMode::OVERLAY ||
251 : m_Type.m_BlendMode == CParticleEmitterType::BlendMode::MULTIPLY)
252 : {
253 0 : color.R = (color.R * color.A) / 255;
254 0 : color.G = (color.G * color.A) / 255;
255 0 : color.B = (color.B * color.A) / 255;
256 : }
257 :
258 0 : *attrColor++ = color;
259 :
260 0 : const CVector4D axisXAndSize{
261 0 : particle.axisX.X, particle.axisX.Y, particle.axisX.Z, particle.size};
262 0 : const CVector4D axisYAndAngle{
263 0 : particle.axisY.X, particle.axisY.Y, particle.axisY.Z, particle.angle};
264 :
265 0 : *attrAxisX++ = axisXAndSize;
266 0 : *attrAxisY++ = axisYAndAngle;
267 : }
268 : }
269 : else
270 : {
271 0 : for (const SParticle& particle : particles)
272 : {
273 0 : if (particle.age > particle.maxAge || particle.color.A == 0)
274 0 : continue;
275 :
276 0 : ++m_NumberOfVisibleParticles;
277 :
278 0 : bounds += particle.pos;
279 :
280 0 : *attrPos++ = particle.pos;
281 0 : *attrPos++ = particle.pos;
282 0 : *attrPos++ = particle.pos;
283 0 : *attrPos++ = particle.pos;
284 :
285 0 : SColor4ub color{particle.color};
286 :
287 : // Special case: If the blending depends on the source color, not the source alpha,
288 : // then pre-multiply by the alpha. (This is kind of a hack.)
289 0 : if (m_Type.m_BlendMode == CParticleEmitterType::BlendMode::OVERLAY ||
290 : m_Type.m_BlendMode == CParticleEmitterType::BlendMode::MULTIPLY)
291 : {
292 0 : color.R = (color.R * color.A) / 255;
293 0 : color.G = (color.G * color.A) / 255;
294 0 : color.B = (color.B * color.A) / 255;
295 : }
296 :
297 0 : *attrColor++ = color;
298 0 : *attrColor++ = color;
299 0 : *attrColor++ = color;
300 0 : *attrColor++ = color;
301 :
302 0 : const CVector4D axisXAndSize{
303 0 : particle.axisX.X, particle.axisX.Y, particle.axisX.Z, particle.size};
304 0 : const CVector4D axisYAndAngle{
305 0 : particle.axisY.X, particle.axisY.Y, particle.axisY.Z, particle.angle};
306 :
307 0 : *attrAxisX++ = axisXAndSize;
308 0 : *attrAxisX++ = axisXAndSize;
309 0 : *attrAxisX++ = axisXAndSize;
310 0 : *attrAxisX++ = axisXAndSize;
311 :
312 0 : *attrAxisY++ = axisYAndAngle;
313 0 : *attrAxisY++ = axisYAndAngle;
314 0 : *attrAxisY++ = axisYAndAngle;
315 0 : *attrAxisY++ = axisYAndAngle;
316 : }
317 : }
318 :
319 0 : m_ParticleBounds = bounds;
320 :
321 0 : m_VertexArray.Upload();
322 0 : }
323 :
324 0 : void CParticleEmitter::PrepareForRendering()
325 : {
326 0 : m_VertexArray.PrepareForRendering();
327 0 : m_VertexUVArray.PrepareForRendering();
328 0 : }
329 :
330 0 : void CParticleEmitter::UploadData(
331 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
332 : {
333 0 : m_VertexArray.UploadIfNeeded(deviceCommandContext);
334 0 : m_VertexUVArray.UploadIfNeeded(deviceCommandContext);
335 0 : }
336 :
337 0 : void CParticleEmitter::Bind(
338 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
339 : Renderer::Backend::IShaderProgram* shader)
340 : {
341 0 : m_Type.m_Texture->UploadBackendTextureIfNeeded(deviceCommandContext);
342 :
343 0 : CLOSTexture& los = g_Renderer.GetSceneRenderer().GetScene().GetLOSTexture();
344 0 : deviceCommandContext->SetTexture(
345 0 : shader->GetBindingSlot(str_losTex), los.GetTextureSmooth());
346 0 : deviceCommandContext->SetUniform(
347 0 : shader->GetBindingSlot(str_losTransform),
348 0 : los.GetTextureMatrix()[0], los.GetTextureMatrix()[12]);
349 :
350 0 : g_Renderer.GetSceneRenderer().GetLightEnv().Bind(deviceCommandContext, shader);
351 :
352 0 : deviceCommandContext->SetTexture(
353 0 : shader->GetBindingSlot(str_baseTex), m_Type.m_Texture->GetBackendTexture());
354 0 : }
355 :
356 0 : void CParticleEmitter::RenderArray(
357 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
358 : {
359 0 : if (m_NumberOfVisibleParticles == 0)
360 : return;
361 :
362 0 : const uint32_t stride = m_VertexArray.GetStride();
363 0 : const uint32_t firstVertexOffset = m_VertexArray.GetOffset() * stride;
364 :
365 0 : deviceCommandContext->SetVertexInputLayout(m_VertexInputLayout);
366 :
367 0 : deviceCommandContext->SetVertexBuffer(
368 : 0, m_VertexUVArray.GetBuffer(),
369 0 : m_VertexUVArray.GetStride() * m_VertexUVArray.GetOffset());
370 0 : deviceCommandContext->SetVertexBuffer(
371 : 1, m_VertexArray.GetBuffer(), firstVertexOffset);
372 0 : deviceCommandContext->SetIndexBuffer(m_IndexArray.GetBuffer());
373 :
374 0 : if (m_UseInstancing)
375 0 : deviceCommandContext->DrawIndexedInstanced(m_IndexArray.GetOffset(), 6, 0, m_NumberOfVisibleParticles, 0);
376 : else
377 0 : deviceCommandContext->DrawIndexed(m_IndexArray.GetOffset(), m_NumberOfVisibleParticles * 6, 0);
378 :
379 0 : g_Renderer.GetStats().m_DrawCalls++;
380 0 : g_Renderer.GetStats().m_Particles += m_NumberOfVisibleParticles;
381 : }
382 :
383 0 : void CParticleEmitter::AddParticle(const SParticle& particle)
384 : {
385 0 : if (m_NextParticleIdx >= m_Particles.size())
386 0 : m_Particles.push_back(particle);
387 : else
388 0 : m_Particles[m_NextParticleIdx] = particle;
389 :
390 0 : m_NextParticleIdx = (m_NextParticleIdx + 1) % m_Type.m_MaxParticles;
391 0 : }
392 :
393 0 : void CParticleEmitter::SetEntityVariable(const std::string& name, float value)
394 : {
395 0 : m_EntityVariables[name] = value;
396 0 : }
397 :
398 0 : CModelParticleEmitter::CModelParticleEmitter(const CParticleEmitterType& type)
399 0 : : m_Type{type}, m_Emitter{std::make_unique<CParticleEmitter>(m_Type)}
400 : {
401 0 : }
402 :
403 0 : CModelParticleEmitter::~CModelParticleEmitter()
404 : {
405 0 : m_Type.m_Manager.AddUnattachedEmitter(std::move(m_Emitter));
406 0 : }
407 :
408 0 : void CModelParticleEmitter::SetEntityVariable(const std::string& name, float value)
409 : {
410 0 : m_Emitter->SetEntityVariable(name, value);
411 0 : }
412 :
413 0 : std::unique_ptr<CModelAbstract> CModelParticleEmitter::Clone() const
414 : {
415 0 : return std::make_unique<CModelParticleEmitter>(m_Type);
416 : }
417 :
418 0 : void CModelParticleEmitter::CalcBounds()
419 : {
420 : // TODO: we ought to compute sensible bounds here, probably based on the
421 : // current computed particle positions plus the emitter type's largest
422 : // potential bounding box at the current position
423 :
424 0 : m_WorldBounds = m_Type.CalculateBounds(m_Emitter->GetPosition(), m_Emitter->GetParticleBounds());
425 0 : }
426 :
427 0 : void CModelParticleEmitter::ValidatePosition()
428 : {
429 : // TODO: do we need to do anything here?
430 :
431 : // This is a convenient (though possibly not particularly appropriate) place
432 : // to invalidate bounds so they'll be recomputed from the recent particle data
433 0 : InvalidateBounds();
434 0 : }
435 :
436 0 : void CModelParticleEmitter::InvalidatePosition()
437 : {
438 0 : }
439 :
440 0 : void CModelParticleEmitter::SetTransform(const CMatrix3D& transform)
441 : {
442 0 : if (m_Transform == transform)
443 : return;
444 :
445 0 : m_Emitter->SetPosition(transform.GetTranslation());
446 0 : m_Emitter->SetRotation(transform.GetRotation());
447 :
448 : // call base class to set transform on this object
449 0 : CRenderableObject::SetTransform(transform);
450 : }
|