ParticleEmitterComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/Components/ParticleEmitterComponent.h>
  6. #include <AnKi/Scene/SceneGraph.h>
  7. #include <AnKi/Scene/SceneNode.h>
  8. #include <AnKi/Scene/Components/MoveComponent.h>
  9. #include <AnKi/Resource/ParticleEmitterResource.h>
  10. #include <AnKi/Resource/ResourceManager.h>
  11. #include <AnKi/Physics/PhysicsBody.h>
  12. #include <AnKi/Physics/PhysicsCollisionShape.h>
  13. #include <AnKi/Physics/PhysicsWorld.h>
  14. #include <AnKi/Math.h>
  15. #include <AnKi/Renderer/RenderQueue.h>
  16. namespace anki {
  17. static Vec3 getRandom(const Vec3& min, const Vec3& max)
  18. {
  19. Vec3 out;
  20. out.x() = mix(min.x(), max.x(), getRandomRange(0.0f, 1.0f));
  21. out.y() = mix(min.y(), max.y(), getRandomRange(0.0f, 1.0f));
  22. out.z() = mix(min.z(), max.z(), getRandomRange(0.0f, 1.0f));
  23. return out;
  24. }
  25. /// Particle base
  26. class ParticleEmitterComponent::ParticleBase
  27. {
  28. public:
  29. Second m_timeOfBirth; ///< Keep the time of birth for nice effects
  30. Second m_timeOfDeath = -1.0; ///< Time of death. If < 0.0 then dead
  31. F32 m_initialSize;
  32. F32 m_finalSize;
  33. F32 m_crntSize;
  34. F32 m_initialAlpha;
  35. F32 m_finalAlpha;
  36. F32 m_crntAlpha;
  37. Vec3 m_crntPosition;
  38. Bool isDead() const
  39. {
  40. return m_timeOfDeath < 0.0;
  41. }
  42. /// Kill the particle
  43. void killCommon()
  44. {
  45. ANKI_ASSERT(m_timeOfDeath > 0.0);
  46. m_timeOfDeath = -1.0;
  47. }
  48. /// Revive the particle
  49. void reviveCommon(const ParticleEmitterProperties& props, Second crntTime)
  50. {
  51. ANKI_ASSERT(isDead());
  52. // life
  53. m_timeOfDeath = crntTime + getRandomRange(props.m_particle.m_minLife, props.m_particle.m_maxLife);
  54. m_timeOfBirth = crntTime;
  55. // Size
  56. m_initialSize = getRandomRange(props.m_particle.m_minInitialSize, props.m_particle.m_maxInitialSize);
  57. m_finalSize = getRandomRange(props.m_particle.m_minFinalSize, props.m_particle.m_maxFinalSize);
  58. // Alpha
  59. m_initialAlpha = getRandomRange(props.m_particle.m_minInitialAlpha, props.m_particle.m_maxInitialAlpha);
  60. m_finalAlpha = getRandomRange(props.m_particle.m_minFinalAlpha, props.m_particle.m_maxFinalAlpha);
  61. }
  62. /// Common sumulation code
  63. void simulateCommon(Second crntTime)
  64. {
  65. const F32 lifeFactor = F32((crntTime - m_timeOfBirth) / (m_timeOfDeath - m_timeOfBirth));
  66. m_crntSize = mix(m_initialSize, m_finalSize, lifeFactor);
  67. m_crntAlpha = mix(m_initialAlpha, m_finalAlpha, lifeFactor);
  68. }
  69. };
  70. /// Simple particle for simple simulation
  71. class ParticleEmitterComponent::SimpleParticle : public ParticleEmitterComponent::ParticleBase
  72. {
  73. public:
  74. Vec3 m_velocity = Vec3(0.0f);
  75. Vec3 m_acceleration = Vec3(0.0f);
  76. void kill()
  77. {
  78. killCommon();
  79. }
  80. void revive(const ParticleEmitterProperties& props, const Transform& trf, Second crntTime)
  81. {
  82. reviveCommon(props, crntTime);
  83. m_velocity = Vec3(0.0f);
  84. m_acceleration = getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity);
  85. // Set the initial position
  86. m_crntPosition = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  87. m_crntPosition += trf.getOrigin().xyz();
  88. }
  89. void simulate(Second prevUpdateTime, Second crntTime)
  90. {
  91. simulateCommon(crntTime);
  92. const F32 dt = F32(crntTime - prevUpdateTime);
  93. const Vec3 xp = m_crntPosition;
  94. const Vec3 xc = m_acceleration * (dt * dt) + m_velocity * dt + xp;
  95. m_crntPosition = xc;
  96. m_velocity += m_acceleration * dt;
  97. }
  98. };
  99. /// Particle for bullet simulations
  100. class ParticleEmitterComponent::PhysicsParticle : public ParticleEmitterComponent::ParticleBase
  101. {
  102. public:
  103. PhysicsBodyPtr m_body;
  104. PhysicsParticle(const PhysicsBodyInitInfo& init, ParticleEmitterComponent* component)
  105. {
  106. m_body = PhysicsWorld::getSingleton().newInstance<PhysicsBody>(init);
  107. m_body->setUserData(component);
  108. m_body->activate(false);
  109. m_body->setMaterialGroup(PhysicsMaterialBit::kParticle);
  110. m_body->setMaterialMask(PhysicsMaterialBit::kStaticGeometry);
  111. m_body->setAngularFactor(Vec3(0.0f));
  112. }
  113. void kill()
  114. {
  115. killCommon();
  116. m_body->activate(false);
  117. }
  118. void revive(const ParticleEmitterProperties& props, const Transform& trf, Second crntTime)
  119. {
  120. reviveCommon(props, crntTime);
  121. // pre calculate
  122. const Bool forceFlag = props.forceEnabled();
  123. const Bool worldGravFlag = props.wordGravityEnabled();
  124. // Activate it
  125. m_body->activate(true);
  126. m_body->setLinearVelocity(Vec3(0.0f));
  127. m_body->setAngularVelocity(Vec3(0.0f));
  128. m_body->clearForces();
  129. // force
  130. if(forceFlag)
  131. {
  132. Vec3 forceDir = getRandom(props.m_particle.m_minForceDirection, props.m_particle.m_maxForceDirection);
  133. forceDir.normalize();
  134. // The forceDir depends on the particle emitter rotation
  135. forceDir = trf.getRotation().getRotationPart() * forceDir;
  136. const F32 forceMag =
  137. getRandomRange(props.m_particle.m_minForceMagnitude, props.m_particle.m_maxForceMagnitude);
  138. m_body->applyForce(forceDir * forceMag, Vec3(0.0f));
  139. }
  140. // gravity
  141. if(!worldGravFlag)
  142. {
  143. m_body->setGravity(getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity));
  144. }
  145. // Starting pos. In local space
  146. Vec3 pos = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  147. pos = trf.transform(pos);
  148. m_body->setTransform(Transform(pos.xyz0(), trf.getRotation(), 1.0f));
  149. m_crntPosition = pos;
  150. }
  151. void simulate([[maybe_unused]] Second prevUpdateTime, Second crntTime)
  152. {
  153. simulateCommon(crntTime);
  154. m_crntPosition = m_body->getTransform().getOrigin().xyz();
  155. }
  156. };
  157. ParticleEmitterComponent::ParticleEmitterComponent(SceneNode* node)
  158. : SceneComponent(node, getStaticClassId())
  159. , m_node(node)
  160. , m_spatial(this)
  161. {
  162. }
  163. ParticleEmitterComponent::~ParticleEmitterComponent()
  164. {
  165. m_simpleParticles.destroy(m_node->getMemoryPool());
  166. m_physicsParticles.destroy(m_node->getMemoryPool());
  167. GpuSceneMemoryPool& gpuScenePool = GpuSceneMemoryPool::getSingleton();
  168. gpuScenePool.deferredFree(m_gpuScenePositions);
  169. gpuScenePool.deferredFree(m_gpuSceneScales);
  170. gpuScenePool.deferredFree(m_gpuSceneAlphas);
  171. gpuScenePool.deferredFree(m_gpuSceneUniforms);
  172. if(m_gpuSceneIndex != kMaxU32)
  173. {
  174. m_node->getSceneGraph().getAllGpuSceneContiguousArrays().deferredFree(
  175. GpuSceneContiguousArrayType::kParticleEmitters, m_gpuSceneIndex);
  176. }
  177. m_spatial.removeFromOctree(m_node->getSceneGraph().getOctree());
  178. }
  179. void ParticleEmitterComponent::loadParticleEmitterResource(CString filename)
  180. {
  181. // Load
  182. ParticleEmitterResourcePtr rsrc;
  183. const Error err = getExternalSubsystems(*m_node).m_resourceManager->loadResource(filename, rsrc);
  184. if(err)
  185. {
  186. ANKI_SCENE_LOGE("Failed to load particle emitter");
  187. return;
  188. }
  189. m_particleEmitterResource = std::move(rsrc);
  190. m_props = m_particleEmitterResource->getProperties();
  191. m_resourceUpdated = true;
  192. // Cleanup
  193. m_simpleParticles.destroy(m_node->getMemoryPool());
  194. m_physicsParticles.destroy(m_node->getMemoryPool());
  195. GpuSceneMemoryPool& gpuScenePool = GpuSceneMemoryPool::getSingleton();
  196. gpuScenePool.deferredFree(m_gpuScenePositions);
  197. gpuScenePool.deferredFree(m_gpuSceneScales);
  198. gpuScenePool.deferredFree(m_gpuSceneAlphas);
  199. gpuScenePool.deferredFree(m_gpuSceneUniforms);
  200. if(m_gpuSceneIndex != kMaxU32)
  201. {
  202. m_node->getSceneGraph().getAllGpuSceneContiguousArrays().deferredFree(
  203. GpuSceneContiguousArrayType::kParticleEmitters, m_gpuSceneIndex);
  204. }
  205. // Init particles
  206. m_simulationType = (m_props.m_usePhysicsEngine) ? SimulationType::kPhysicsEngine : SimulationType::kSimple;
  207. if(m_simulationType == SimulationType::kPhysicsEngine)
  208. {
  209. PhysicsCollisionShapePtr collisionShape =
  210. PhysicsWorld::getSingleton().newInstance<PhysicsSphere>(m_props.m_particle.m_minInitialSize / 2.0f);
  211. PhysicsBodyInitInfo binit;
  212. binit.m_shape = std::move(collisionShape);
  213. m_physicsParticles.resizeStorage(m_node->getMemoryPool(), m_props.m_maxNumOfParticles);
  214. for(U32 i = 0; i < m_props.m_maxNumOfParticles; i++)
  215. {
  216. binit.m_mass = getRandomRange(m_props.m_particle.m_minMass, m_props.m_particle.m_maxMass);
  217. m_physicsParticles.emplaceBack(m_node->getMemoryPool(), binit, this);
  218. }
  219. }
  220. else
  221. {
  222. m_simpleParticles.create(m_node->getMemoryPool(), m_props.m_maxNumOfParticles);
  223. }
  224. // GPU scene allocations
  225. gpuScenePool.allocate(sizeof(Vec3) * m_props.m_maxNumOfParticles, alignof(F32), m_gpuScenePositions);
  226. gpuScenePool.allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32), m_gpuSceneAlphas);
  227. gpuScenePool.allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32), m_gpuSceneScales);
  228. gpuScenePool.allocate(m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getSizeInBytes(),
  229. alignof(U32), m_gpuSceneUniforms);
  230. m_gpuSceneIndex = m_node->getSceneGraph().getAllGpuSceneContiguousArrays().allocate(
  231. GpuSceneContiguousArrayType::kParticleEmitters);
  232. }
  233. Error ParticleEmitterComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  234. {
  235. if(!m_particleEmitterResource.isCreated()) [[unlikely]]
  236. {
  237. updated = false;
  238. return Error::kNone;
  239. }
  240. updated = true;
  241. Vec3* positions;
  242. F32* scales;
  243. F32* alphas;
  244. Aabb aabbWorld;
  245. if(m_simulationType == SimulationType::kSimple)
  246. {
  247. simulate(info.m_previousTime, info.m_currentTime, WeakArray<SimpleParticle>(m_simpleParticles), positions,
  248. scales, alphas, aabbWorld);
  249. }
  250. else
  251. {
  252. ANKI_ASSERT(m_simulationType == SimulationType::kPhysicsEngine);
  253. simulate(info.m_previousTime, info.m_currentTime, WeakArray<PhysicsParticle>(m_physicsParticles), positions,
  254. scales, alphas, aabbWorld);
  255. }
  256. m_spatial.setBoundingShape(aabbWorld);
  257. m_spatial.update(info.m_node->getSceneGraph().getOctree());
  258. // Upload to the GPU scene
  259. GpuSceneMicroPatcher& patcher = GpuSceneMicroPatcher::getSingleton();
  260. if(m_aliveParticleCount > 0)
  261. {
  262. patcher.newCopy(*info.m_framePool, m_gpuScenePositions.m_offset, sizeof(Vec3) * m_aliveParticleCount,
  263. positions);
  264. patcher.newCopy(*info.m_framePool, m_gpuSceneScales.m_offset, sizeof(F32) * m_aliveParticleCount, scales);
  265. patcher.newCopy(*info.m_framePool, m_gpuSceneAlphas.m_offset, sizeof(F32) * m_aliveParticleCount, alphas);
  266. }
  267. if(m_resourceUpdated)
  268. {
  269. GpuSceneParticleEmitter particles = {};
  270. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = U32(m_gpuScenePositions.m_offset);
  271. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = U32(m_gpuSceneAlphas.m_offset);
  272. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = U32(m_gpuSceneScales.m_offset);
  273. const PtrSize offset = m_gpuSceneIndex * sizeof(GpuSceneParticleEmitter)
  274. + info.m_node->getSceneGraph().getAllGpuSceneContiguousArrays().getArrayBase(
  275. GpuSceneContiguousArrayType::kParticleEmitters);
  276. patcher.newCopy(*info.m_framePool, offset, sizeof(GpuSceneParticleEmitter), &particles);
  277. patcher.newCopy(*info.m_framePool, m_gpuSceneUniforms.m_offset,
  278. m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getSizeInBytes(),
  279. m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getBegin());
  280. }
  281. m_resourceUpdated = false;
  282. return Error::kNone;
  283. }
  284. template<typename TParticle>
  285. void ParticleEmitterComponent::simulate(Second prevUpdateTime, Second crntTime, WeakArray<TParticle> particles,
  286. Vec3*& positions, F32*& scales, F32*& alphas, Aabb& aabbWorld)
  287. {
  288. // - Deactivate the dead particles
  289. // - Calc the AABB
  290. // - Calc the instancing stuff
  291. Vec3 aabbMin(kMaxF32);
  292. Vec3 aabbMax(kMinF32);
  293. m_aliveParticleCount = 0;
  294. positions = static_cast<Vec3*>(
  295. m_node->getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(Vec3), alignof(Vec3)));
  296. scales = static_cast<F32*>(
  297. m_node->getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  298. alphas = static_cast<F32*>(
  299. m_node->getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  300. F32 maxParticleSize = -1.0f;
  301. for(TParticle& particle : particles)
  302. {
  303. if(particle.isDead())
  304. {
  305. // if its already dead so dont deactivate it again
  306. continue;
  307. }
  308. if(particle.m_timeOfDeath < crntTime)
  309. {
  310. // Just died
  311. particle.kill();
  312. }
  313. else
  314. {
  315. // It's alive
  316. // This will calculate a new world transformation
  317. particle.simulate(prevUpdateTime, crntTime);
  318. const Vec3& origin = particle.m_crntPosition;
  319. aabbMin = aabbMin.min(origin);
  320. aabbMax = aabbMax.max(origin);
  321. positions[m_aliveParticleCount] = origin;
  322. scales[m_aliveParticleCount] = particle.m_crntSize;
  323. maxParticleSize = max(maxParticleSize, particle.m_crntSize);
  324. alphas[m_aliveParticleCount] = clamp(particle.m_crntAlpha, 0.0f, 1.0f);
  325. ++m_aliveParticleCount;
  326. }
  327. }
  328. // AABB
  329. if(m_aliveParticleCount != 0)
  330. {
  331. ANKI_ASSERT(maxParticleSize > 0.0f);
  332. const Vec3 min = aabbMin - maxParticleSize;
  333. const Vec3 max = aabbMax + maxParticleSize;
  334. aabbWorld = Aabb(min, max);
  335. }
  336. else
  337. {
  338. aabbWorld = Aabb(Vec3(0.0f), Vec3(0.001f));
  339. positions = nullptr;
  340. alphas = scales = nullptr;
  341. }
  342. //
  343. // Emit new particles
  344. //
  345. if(m_timeLeftForNextEmission <= 0.0)
  346. {
  347. U particleCount = 0; // How many particles I am allowed to emmit
  348. for(TParticle& particle : particles)
  349. {
  350. if(!particle.isDead())
  351. {
  352. // its alive so skip it
  353. continue;
  354. }
  355. particle.revive(m_props, m_node->getWorldTransform(), crntTime);
  356. // do the rest
  357. ++particleCount;
  358. if(particleCount >= m_props.m_particlesPerEmission)
  359. {
  360. break;
  361. }
  362. } // end for all particles
  363. m_timeLeftForNextEmission = m_props.m_emissionPeriod;
  364. } // end if can emit
  365. else
  366. {
  367. m_timeLeftForNextEmission -= crntTime - prevUpdateTime;
  368. }
  369. }
  370. void ParticleEmitterComponent::setupRenderableQueueElements(RenderingTechnique technique, StackMemoryPool& tmpPool,
  371. WeakArray<RenderableQueueElement>& outRenderables) const
  372. {
  373. if(!(m_particleEmitterResource->getMaterial()->getRenderingTechniques() & RenderingTechniqueBit(1 << technique))
  374. || m_aliveParticleCount == 0)
  375. {
  376. outRenderables.setArray(nullptr, 0);
  377. return;
  378. }
  379. RenderingKey key;
  380. key.setRenderingTechnique(technique);
  381. ShaderProgramPtr prog;
  382. m_particleEmitterResource->getRenderingInfo(key, prog);
  383. RenderableQueueElement* el = static_cast<RenderableQueueElement*>(
  384. tmpPool.allocate(sizeof(RenderableQueueElement), alignof(RenderableQueueElement)));
  385. el->m_mergeKey = 0; // Not mergable
  386. el->m_program = prog.get();
  387. el->m_worldTransformsOffset = 0;
  388. el->m_uniformsOffset = U32(m_gpuSceneUniforms.m_offset);
  389. el->m_geometryOffset = U32(m_gpuSceneIndex * sizeof(GpuSceneParticleEmitter)
  390. + m_node->getSceneGraph().getAllGpuSceneContiguousArrays().getArrayBase(
  391. GpuSceneContiguousArrayType::kParticleEmitters));
  392. el->m_boneTransformsOffset = 0;
  393. el->m_vertexCount = 6 * m_aliveParticleCount;
  394. el->m_firstVertex = 0;
  395. el->m_indexed = false;
  396. el->m_primitiveTopology = PrimitiveTopology::kTriangles;
  397. el->m_aabbMin = m_spatial.getAabbWorldSpace().getMin().xyz();
  398. el->m_aabbMax = m_spatial.getAabbWorldSpace().getMax().xyz();
  399. outRenderables.setArray(el, 1);
  400. }
  401. } // end namespace anki