2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include <dali-toolkit/internal/particle-system/particle-emitter-impl.h>
19 #include <dali-toolkit/internal/particle-system/particle-list-impl.h>
20 #include <dali-toolkit/internal/particle-system/particle-renderer-impl.h>
21 #include <dali/devel-api/rendering/renderer-devel.h>
23 #include <dali/devel-api/actors/actor-devel.h>
24 #include <dali/devel-api/common/capabilities.h>
25 #include <dali/graphics-api/graphics-buffer.h>
26 #include <dali/graphics-api/graphics-controller.h>
27 #include <dali/graphics-api/graphics-program.h>
28 #include <dali/graphics-api/graphics-shader.h>
30 namespace Dali::Toolkit::ParticleSystem::Internal
32 ParticleRenderer::ParticleRenderer()
34 mStreamBufferUpdateCallback = Dali::VertexBufferUpdateCallback::New(this, &ParticleRenderer::OnStreamBufferUpdate);
37 void ParticleRenderer::SetEmitter(ParticleSystem::Internal::ParticleEmitter* emitter)
42 void ParticleRenderer::SetTexture(const Dali::Texture& texture)
47 void ParticleRenderer::SetBlendingMode(BlendingMode blendingMode)
49 mBlendingMode = blendingMode;
52 void ParticleRenderer::CreateShader()
54 // Create shader dynamically
55 auto& list = GetImplementation(mEmitter->GetParticleList());
56 auto streamCount = list.GetStreamCount();
58 static const char* ATTR_GLSL_TYPES[] =
60 "float", "vec2", "vec3", "vec4", "int", "ivec2", "ivec3", "ivec4"};
62 static const Property::Type ATTR_TYPES[] =
64 Property::Type::FLOAT,
65 Property::Type::VECTOR2,
66 Property::Type::VECTOR3,
67 Property::Type::VECTOR4,
68 Property::Type::INTEGER,
69 Property::Type::VECTOR2, // This represents floats but by binary write it shouldn't matter (?)
70 Property::Type::VECTOR3,
71 Property::Type::VECTOR4,
76 Vertex2D(const Vector2& _co, const Vector2& _uv)
85 uint32_t streamElementSize = 0u;
86 Property::Map streamAtttributes;
89 for(auto i = 0u; i < streamCount; ++i)
91 // Don't add local streams to the shader
92 if(!list.IsStreamLocal(i))
94 uint32_t dataTypeSize = list.GetStreamDataTypeSize(i);
95 auto dataTypeIndex = uint32_t(list.GetStreamDataType(i));
96 const auto& streamName = list.GetStreamName(i);
97 streamElementSize += dataTypeSize;
99 if(streamName.empty())
101 sprintf(key, "aStreamAttr_%d", i);
105 sprintf(key, "%s", streamName.c_str());
107 streamAtttributes.Add(key, ATTR_TYPES[dataTypeIndex]);
109 // Add shader attribute line
110 ss << "INPUT mediump " << ATTR_GLSL_TYPES[dataTypeIndex] << " " << key << ";\n";
114 auto streamAttributesStr = ss.str();
117 * - The MVP comes from the Actor that the particle renderer is attached to
118 * - Attributes are added dynamically based on the particle system properties
119 * - There are two buffers bound
120 * * Geometry buffer (in this instance, a quad)
121 * * ParticleSystem stream buffer with interleaved data
122 * - ParticleSystem buffer is being updated every frame
124 std::string vertexShaderCode = streamAttributesStr + std::string(
126 "INPUT mediump vec2 aPosition;\n\
127 INPUT mediump vec2 aTexCoords;\n\
129 uniform mediump mat4 uMvpMatrix;\n\
130 uniform mediump vec3 uSize;\n\
131 uniform lowp vec4 uColor;\n\
133 OUTPUT mediump vec2 vTexCoord;\n\
134 OUTPUT mediump vec4 vColor;\n\
138 vec4 pos = vec4(aPosition, 0.0, 1.0) * vec4(aStreamScale, 1.0);\n\
139 vec4 position = pos + vec4(aStreamPosition, 0.0);\n\
140 vTexCoord = aTexCoords;\n\
141 vColor = uColor * aStreamColor;\n\
142 gl_Position = uMvpMatrix * position ;\n\
145 std::string fragmentShaderCode =
147 "INPUT mediump vec2 vTexCoord;\n\
148 INPUT mediump vec4 vColor;\n\
149 uniform sampler2D sTexture;\n\
153 lowp vec4 col = TEXTURE(sTexture, vTexCoord) * vColor;\n\
154 if(col.a < 0.1) { discard; }\
158 mShader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + vertexShaderCode, Dali::Shader::GetFragmentShaderPrefix() + fragmentShaderCode);
159 mGeometry = Geometry::New();
161 // Configure geometry attributes
162 Property::Map geometryMap;
163 geometryMap.Add("aPosition", Dali::Property::VECTOR2);
164 geometryMap.Add("aTexCoords", Dali::Property::VECTOR2);
166 // One vertex buffer with geometry
167 VertexBuffer vertexBuffer0 = VertexBuffer::New(geometryMap);
169 // fill the buffer entirely
171 const static Vector2 C(0.5f, 0.5f);
174 Vertex2D a0{Vector2(0.0f, 0.0f) - C, Vector2(0.0f, 0.0f)};
175 Vertex2D a1{Vector2(1.0f, 0.0f) - C, Vector2(1.0f, 0.0f)};
176 Vertex2D a2{Vector2(1.0f, 1.0f) - C, Vector2(1.0f, 1.0f)};
177 Vertex2D a3{Vector2(0.0f, 0.0f) - C, Vector2(0.0f, 0.0f)};
178 Vertex2D a4{Vector2(1.0f, 1.0f) - C, Vector2(1.0f, 1.0f)};
179 Vertex2D a5{Vector2(0.0f, 1.0f) - C, Vector2(0.0f, 1.0f)};
182 std::vector<Quad2D> quads;
183 quads.resize(mEmitter->GetParticleList().GetCapacity());
184 std::fill(quads.begin(), quads.end(), QUAD);
185 vertexBuffer0.SetData(quads.data(), 6u * quads.size());
187 // Second vertex buffer with stream data
188 VertexBuffer vertexBuffer1 = VertexBuffer::New(streamAtttributes);
191 * For more efficient stream management we need to support glVertexAttribDivisor() function.
192 * This will allow step 1 attribute per 4 vertices (GLES3+). Problem: DALi doesn't support instancing
194 * For older GLES2 we need to duplicate stream data (4x more memory in case of using a quad geometry)
196 * Point-sprites may be of use in the future (problem: point sprites use screen space)
199 // Based on the particle system, populate buffer
200 mGeometry.AddVertexBuffer(vertexBuffer0);
201 mGeometry.AddVertexBuffer(vertexBuffer1);
203 mGeometry.SetType(Geometry::TRIANGLES);
205 mVertexBuffer = vertexBuffer0;
206 mStreamBuffer = vertexBuffer1;
208 // Set some initial data for streambuffer to force initialization
209 std::vector<uint8_t> data;
210 // Resize using only-non local streams
211 auto elementSize = mEmitter->GetParticleList().GetParticleDataSize(false);
212 data.resize(elementSize *
213 mEmitter->GetParticleList().GetCapacity() * 6u);
214 mStreamBuffer.SetData(data.data(), mEmitter->GetParticleList().GetCapacity() * 6u); // needed to initialize
217 mStreamBuffer.SetVertexBufferUpdateCallback(std::move(mStreamBufferUpdateCallback));
219 mRenderer = Renderer::New(mGeometry, mShader);
221 mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY);
222 // If no texture created, the substitute rect 2x2 texture will be used
225 mTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, 2u, 2u);
226 auto* pixelArray = new uint32_t[4]{
227 0xFF0000FF, 0xFF0000FF, 0xFF0000FF, 0xFF0000FF};
229 auto pixelData = PixelData::New(reinterpret_cast<uint8_t*>(pixelArray), 16, 2, 2, Pixel::Format::RGBA8888, PixelData::DELETE_ARRAY);
230 mTexture.Upload(pixelData);
233 mTextureSet = TextureSet::New();
234 mTextureSet.SetTexture(0, mTexture);
235 // mTextureSet.SetSampler(0, Sampler());
237 mRenderer.SetTextures(mTextureSet);
239 // Attach renderer to the parent actor
240 mEmitter->GetActor().AddRenderer(mRenderer);
242 if(mBlendingMode == BlendingMode::SCREEN)
244 if(Dali::Capabilities::IsBlendEquationSupported(Dali::DevelBlendEquation::SCREEN))
246 mEmitter->GetActor().SetProperty(Dali::DevelActor::Property::BLEND_EQUATION, Dali::DevelBlendEquation::SCREEN);
248 else // Fallback to default
250 mRenderer.SetProperty(Renderer::Property::BLEND_EQUATION_RGB, BlendEquation::ADD);
255 mRenderer.SetProperty(Renderer::Property::BLEND_EQUATION_RGB, BlendEquation::ADD);
259 uint32_t ParticleRenderer::OnStreamBufferUpdate(void* streamData, size_t size)
261 auto& list = GetImplementation(mEmitter->GetParticleList());
263 auto particleCount = list.GetActiveParticleCount(); // active particle count
264 auto particleMaxCount = list.GetParticleCount();
270 auto streamCount = list.GetStreamCount();
272 auto elementSize = 0u; // elements size should be cached (it's also stride of buffer) (in bytes)
273 for(auto i = 0u; i < streamCount; ++i)
275 if(!list.IsStreamLocal(i))
277 elementSize += list.GetStreamDataTypeSize(i);
281 // Prepare source buffer (MUST BE OPTIMIZED TO AVOID ALLOCATING AND COPYING!!)
282 auto totalSize = particleMaxCount * elementSize * 6u;
284 // buffer sizes must match
285 if(totalSize != size)
291 auto* dst = reinterpret_cast<uint8_t*>(streamData);
293 auto& particles = list.GetParticles();
295 // prepare worker threads
296 auto workerCount = GetThreadPool().GetWorkerCount();
298 // divide particles if over the threshold
300 [[maybe_unused]] bool runParallel = true;
301 if(!mEmitter->IsParallelProcessingEnabled() || particleCount < workerCount * 10) // don't run parallel if only a few particles to update
308 [[maybe_unused]] auto partialSize = (particleCount / workerCount);
312 UpdateTask(Internal::ParticleRenderer& renderer, Internal::ParticleList& list, uint32_t particleStartIndex, uint32_t particleCount, void* basePtr)
315 startIndex(particleStartIndex),
316 count(particleCount),
317 ptr(reinterpret_cast<uint8_t*>(basePtr))
324 owner.UpdateParticlesTask(particleList, startIndex, count, ptr);
327 Internal::ParticleRenderer& owner;
328 Internal::ParticleList& particleList;
334 std::vector<UpdateTask> tasks;
335 tasks.reserve(workerCount);
336 std::vector<Task> taskQueue;
337 auto count = partialSize;
339 for(auto i = 0u; i < workerCount; ++i)
341 auto index = i * partialSize;
344 // make sure there's no leftover particles!
345 if(i == workerCount - 1 && index + count < particleCount)
347 count = particleCount - index;
350 tasks.emplace_back(*this, list, index, count, streamData);
351 taskQueue.emplace_back([&t = tasks.back()](uint32_t threadId)
355 // Execute worker tasks
356 auto future = GetThreadPool().SubmitTasks(taskQueue, 0);
361 // less particles so run on a single thread
364 for(auto& p : particles)
366 // without instancing we need to duplicate data 4 times per each quad
367 auto* particleDst = dst;
368 for(auto s = 0u; s < streamCount; ++s)
370 if(!list.IsStreamLocal(s))
372 // Pointer to stream value
373 auto* valuePtr = &p.GetByIndex<uint8_t*>(s);
376 auto dataSize = list.GetStreamDataTypeSize(s);
378 memcpy(dst, valuePtr, dataSize);
382 // Replicate data 5 more times for each vertex (GLES2)
383 memcpy(dst, particleDst, elementSize);
385 memcpy(dst, particleDst, elementSize);
387 memcpy(dst, particleDst, elementSize);
389 memcpy(dst, particleDst, elementSize);
391 memcpy(dst, particleDst, elementSize);
395 return particleCount * 6u; // return number of elements to render
398 Renderer ParticleRenderer::GetRenderer() const
403 void ParticleRenderer::UpdateParticlesTask(Internal::ParticleList& list,
404 uint32_t particleStartIndex,
405 uint32_t particleCount,
408 auto& particles = list.GetParticles();
409 auto streamCount = list.GetStreamCount();
410 auto elementSize = list.GetStreamElementSize(false);
412 // calculate begin of buffer
413 uint8_t* dst = (basePtr + (elementSize * 6u) * particleStartIndex);
415 auto it = particles.begin();
416 std::advance(it, particleStartIndex);
418 for(; particleCount; particleCount--, it++)
420 ParticleSystem::Particle& p = *it;
421 // without instancing we need to duplicate data 4 times per each quad
422 auto* particleDst = dst;
423 for(auto s = 0u; s < streamCount; ++s)
425 if(!list.IsStreamLocal(s))
427 // Pointer to stream value
428 auto* valuePtr = &p.GetByIndex<uint8_t*>(s);
431 auto dataSize = list.GetStreamDataTypeSize(s);
433 memcpy(dst, valuePtr, dataSize);
437 // Replicate data 5 more times for each vertex (GLES2)
438 memcpy(dst, particleDst, elementSize);
440 memcpy(dst, particleDst, elementSize);
442 memcpy(dst, particleDst, elementSize);
444 memcpy(dst, particleDst, elementSize);
446 memcpy(dst, particleDst, elementSize);
451 bool ParticleRenderer::Initialize()
463 } // namespace Dali::Toolkit::ParticleSystem::Internal