ParticleSystemRenderer.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. //
  2. // ParticleSystemRenderer.cpp
  3. // cocos2d_libs
  4. //
  5. // Created by 徐俊杰 on 2020/4/24.
  6. //
  7. #include "rparticle/ParticleSystemRenderer.h"
  8. #include "rparticle/ParticleSystemParticle.h"
  9. #include "rparticle/Utilities/StrideIterator.h"
  10. #include "rparticle/Macros/RParticleGlobalStuff.h"
  11. #include "rparticle/Utilities/Transform.h"
  12. #include "2d/CCCamera.h"
  13. #include "base/ccMacros.h"
  14. #include "renderer/ccGLStateCache.h"
  15. #include "renderer/CCGLProgram.h"
  16. #include "renderer/CCRenderer.h"
  17. #include <algorithm>
  18. #include "rparticle/Serialize/TransferFunctions/SerializeTransfer.h"
  19. using namespace cocos2d;
  20. NS_RRP_BEGIN
  21. //PROFILER_INFORMATION(gParticlesSort, "ParticleSystem.Sort", kProfilerParticles)
  22. //PROFILER_INFORMATION(gParticlesSingleProfile, "ParticleSystem.RenderSingle", kProfilerParticles)
  23. //PROFILER_INFORMATION(gParticlesBatchProfile, "ParticleSystem.RenderBatch", kProfilerParticles)
  24. //PROFILER_INFORMATION(gSubmitVBOParticleProfile, "Mesh.SubmitVBO", kProfilerRender)
  25. enum { kMaxQuads = 65536/4 - 4 }; // so we fit into 16 bit indices, minus some more just in case
  26. #define DEBUG_PARTICLE_SORTING (0)
  27. #if UNITY_WII
  28. #define kMaxNumParticlesPerBatch (65536/6)
  29. #else
  30. #define kMaxNumParticlesPerBatch (std::min<int>(kDynamicBatchingIndicesThreshold/6, kMaxQuads))
  31. #endif
  32. //struct ParticleSystemVertex
  33. //{
  34. // Vector3f vert;
  35. // Vector3f normal;
  36. // ColorRGBAf color;
  37. // Vector2f uv;
  38. // Vector4f tangent; // Here, we put 2nd uv + blend factor
  39. //};
  40. struct ParticleSystemGeomConstInputData
  41. {
  42. Matrix4x4f m_ViewMatrix;
  43. Vector3f m_CameraVelocity;
  44. //Object* m_Renderer;
  45. UInt16 const* m_MeshIndexBuffer[ParticleSystemRendererData::kMaxNumParticleMeshes];
  46. int m_MeshIndexCount[ParticleSystemRendererData::kMaxNumParticleMeshes];
  47. int m_NumTilesX;
  48. int m_NumTilesY;
  49. float maxPlaneScale;
  50. float maxOrthoSize;
  51. float numUVFrame;
  52. float animUScale;
  53. float animVScale;
  54. Vector3f xSpan;
  55. Vector3f ySpan;
  56. bool usesSheetIndex;
  57. int uvModuleMode;
  58. float bentNormalFactor;
  59. Vector3f bentNormalVector;
  60. bool isSpriteFrame;
  61. RRP_PARTICLEQUAD_VERTEX_INFO* vertexInfo;
  62. Vector3f globalScale;
  63. };
  64. inline void ScaleMatrix(Matrix4x4f& matrix, float scale)
  65. {
  66. matrix.m[0] *= scale;
  67. matrix.m[1] *= scale;
  68. matrix.m[2] *= scale;
  69. matrix.m[4] *= scale;
  70. matrix.m[5] *= scale;
  71. matrix.m[6] *= scale;
  72. matrix.m[8] *= scale;
  73. matrix.m[9] *= scale;
  74. matrix.m[10] *= scale;
  75. }
  76. static ParticleSystemVertex* _vbPtr = nullptr;
  77. struct ParticleSort
  78. {
  79. inline static void SetValues(ParticleSort& sort, UInt32 inIndex, int inIntValue)
  80. {
  81. sort.index = inIndex;
  82. sort.intValue = inIntValue;
  83. }
  84. inline static bool CompareValue (const ParticleSort& left, const ParticleSort& right)
  85. {
  86. return (left.intValue < right.intValue);
  87. }
  88. inline static void Swap(ParticleSort* oneOfThem, ParticleSort* theOtherOne)
  89. {
  90. ParticleSort temp = *oneOfThem;
  91. *oneOfThem = *theOtherOne;
  92. *theOtherOne = temp;
  93. }
  94. UInt32 index;
  95. int intValue;
  96. };
  97. //bool ParticleSystemRenderer::init(){
  98. // //if(!Node::init()){
  99. // // return false;
  100. // //}
  101. // //this->setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_COLOR));
  102. // return true;
  103. //}
  104. //ParticleSystemRenderer* ParticleSystemRenderer::create() {
  105. // ParticleSystemRenderer * ret = new (std::nothrow) ParticleSystemRenderer();
  106. // if (ret && ret->init()) {
  107. // //ret->autorelease();
  108. // } else {
  109. // CC_SAFE_DELETE(ret);
  110. // }
  111. // return ret;
  112. //}
  113. void GenerateSortIndices(ParticleSort* indices, const Vector3f& distFactor, const ParticleSystemParticles& ps, ParticleSystemSortMode sortMode)
  114. {
  115. const size_t particleCount = ps.array_size();
  116. if(sortMode == kSSMByDistance)
  117. for(int i = 0; i < particleCount; i++)
  118. ParticleSort::SetValues(indices[i], i, (int)(Dot (distFactor, ps.position[i]) * 40000.0f));
  119. else if(sortMode == kSSMOldestFirst)
  120. for(int i = 0; i < particleCount; i++)
  121. ParticleSort::SetValues(indices[i], i, (int)((ps.startLifetime[i]- ps.lifetime[i]) * -40000.0f));
  122. else if(sortMode == kSSMYoungestFirst)
  123. for(int i = 0; i < particleCount; i++)
  124. ParticleSort::SetValues(indices[i], i, (int)((ps.startLifetime[i]- ps.lifetime[i]) * 40000.0f));
  125. }
  126. template<bool sortTempData>
  127. void ApplySortRemap(ParticleSort* particleSortIndexBuffer, ParticleSystemParticlesTempData* tempData, ParticleSystemParticles& ps)
  128. {
  129. const size_t count = ps.array_size();
  130. for(int i = 0; i < count; i++)
  131. {
  132. int dst = particleSortIndexBuffer[i].intValue;
  133. while(i != dst)
  134. {
  135. ParticleSort::Swap(&particleSortIndexBuffer[i], &particleSortIndexBuffer[dst]);
  136. ps.element_swap(i, dst);
  137. if(sortTempData)
  138. tempData->element_swap(i, dst);
  139. dst = particleSortIndexBuffer[i].intValue;
  140. }
  141. }
  142. }
  143. void Sort (const Matrix4x4f& matrix, ParticleSystemParticles& ps, ParticleSystemSortMode mode, ParticleSystemParticlesTempData* tempData, bool sortTempData)
  144. {
  145. //PROFILER_AUTO_GFX(gParticlesSort, 0);
  146. DebugAssert(mode != kSSMNone);
  147. const Vector3f distFactor = Vector3f (matrix.Get (2, 0), matrix.Get (2, 1), + matrix.Get (2, 2));
  148. const size_t count = ps.array_size();
  149. ParticleSort* particleSortIndexBuffer;
  150. //ALLOC_TEMP(particleSortIndexBuffer, ParticleSort, count);
  151. particleSortIndexBuffer = (ParticleSort*)malloc(sizeof(ParticleSort) * count);
  152. GenerateSortIndices(&particleSortIndexBuffer[0], distFactor, ps, mode);
  153. // Sort
  154. std::sort(&particleSortIndexBuffer[0], &particleSortIndexBuffer[0] + count, ParticleSort::CompareValue);
  155. // Create inverse mapping
  156. for(int i = 0; i < count; i++)
  157. particleSortIndexBuffer[particleSortIndexBuffer[i].index].intValue = i;
  158. if(sortTempData)
  159. ApplySortRemap<true>(particleSortIndexBuffer, tempData, ps);
  160. else
  161. ApplySortRemap<false>(particleSortIndexBuffer, tempData, ps);
  162. free(particleSortIndexBuffer);
  163. }
  164. struct ParticleMeshData
  165. {
  166. int vertexCount;
  167. StrideIterator<Vector3f> positions;
  168. StrideIterator<Vector3f> normals;
  169. StrideIterator<Vector4f> tangents;
  170. StrideIterator<ColorRGBA32> colors;
  171. StrideIterator<Vector2f> texCoords;
  172. int indexCount;
  173. const UInt16* indexBuffer;
  174. };
  175. template<bool hasNormals, bool hasTangents>
  176. void TransformParticleMesh(const ParticleMeshData& src, ColorRGBA32 particleColor,
  177. const Matrix4x4f& xform, const Matrix4x4f& xformNoScale, UInt8** dest)
  178. {
  179. for(int vertex = 0; vertex < src.vertexCount; vertex++)
  180. {
  181. // Vertex format is position, color, uv, and optional normals and tangents
  182. xform.MultiplyPoint3(src.positions[vertex], *reinterpret_cast<Vector3f*>(*dest));
  183. *dest += sizeof(Vector3f);
  184. if (hasNormals)
  185. {
  186. xformNoScale.MultiplyVector3(src.normals[vertex], *reinterpret_cast<Vector3f*>(*dest));
  187. *dest += sizeof(Vector3f);
  188. }
  189. auto tempColor = particleColor;
  190. tempColor *= src.colors[vertex];
  191. *reinterpret_cast<ColorRGBA32*>(*dest) = tempColor;
  192. *dest += sizeof(ColorRGBA32);
  193. *reinterpret_cast<Vector2f*>(*dest) = src.texCoords[vertex];
  194. *dest += sizeof(Vector2f);
  195. // Tangent is last in vertex format
  196. if (hasTangents)
  197. {
  198. Vector3f newTangent = xformNoScale.MultiplyVector3((const Vector3f&)src.tangents[vertex]);
  199. //*reinterpret_cast<Vector4f*>(*dest) = Vector4f(newTangent, src.tangents[vertex].w);
  200. *reinterpret_cast<Vector4f*>(*dest) = Vector4f(newTangent.x, newTangent.y, newTangent.z, src.tangents[vertex].w);
  201. *dest += sizeof(Vector4f);
  202. }
  203. }
  204. }
  205. ParticleSystemRenderer::ParticleSystemRenderer (/*MemLabelId label, ObjectCreationMode mode*/)
  206. //: Super(kRendererParticleSystem, label, mode)
  207. : m_LocalSpaceAABB (Vector3f::ZERO, Vector3f::ZERO)
  208. {
  209. //setName(COMPONENT_PS_RENDERER);
  210. //SetVisible (false);
  211. //for (int i = 0; i < ParticleSystemRendererData::kMaxNumParticleMeshes; ++i)
  212. // m_Data.cachedMeshUserNode[i].SetData (this);
  213. #if UNITY_EDITOR
  214. m_EditorEnabled = true;
  215. #endif
  216. }
  217. ParticleSystemRenderer::~ParticleSystemRenderer ()
  218. {
  219. }
  220. //void ParticleSystemRenderer::InitializeClass ()
  221. //{
  222. // REGISTER_MESSAGE_PTR (ParticleSystemRenderer, kDidDeleteMesh, OnDidDeleteMesh, Mesh);
  223. //}
  224. //void ParticleSystemRenderer::AwakeFromLoad (AwakeFromLoadMode awakeMode)
  225. //{
  226. // Super::AwakeFromLoad (awakeMode);
  227. // UpdateCachedMesh ();
  228. //}
  229. //void ParticleSystemRenderer::UpdateCachedMesh ()
  230. //{
  231. // int dst = 0;
  232. // for(int src = 0; src < ParticleSystemRendererData::kMaxNumParticleMeshes; src++)
  233. // {
  234. // m_Data.cachedMesh[src] = NULL;
  235. // m_Data.cachedMeshUserNode[src].RemoveFromList ();
  236. //
  237. // Mesh* mesh = m_Mesh[src];
  238. // if (mesh)
  239. // {
  240. // if (mesh->GetSubMeshCount() == 1)
  241. // {
  242. // m_Data.cachedMesh[dst] = mesh;
  243. // const SubMesh& sm = mesh->GetSubMeshFast(0);
  244. // const UInt16* buffer = mesh->GetSubMeshBuffer16(0);
  245. //
  246. // if (sm.topology == kPrimitiveTriangleStripDeprecated)
  247. // {
  248. // const int capacity = CountTrianglesInStrip(buffer, sm.indexCount) * 3;
  249. // m_CachedIndexBuffer[dst].resize_uninitialized(capacity);
  250. // Destripify(buffer, sm.indexCount, m_CachedIndexBuffer[dst].begin(), capacity);
  251. // }
  252. // else if (sm.topology == kPrimitiveTriangles)
  253. // {
  254. // const int capacity = sm.indexCount;
  255. // m_CachedIndexBuffer[dst].resize_uninitialized(capacity);
  256. // memcpy(m_CachedIndexBuffer[dst].begin(), buffer, capacity*kVBOIndexSize);
  257. // }
  258. // else
  259. // {
  260. // m_CachedIndexBuffer[dst].resize_uninitialized(0);
  261. // }
  262. //
  263. // // Hook into mesh's user notifications.
  264. // mesh->AddObjectUser (m_Data.cachedMeshUserNode[dst]);
  265. //
  266. // dst++;
  267. // }
  268. // else
  269. // {
  270. // m_Data.cachedMesh[src] = NULL;
  271. // m_CachedIndexBuffer[src].resize_uninitialized(0);
  272. // AssertString ("Particle system meshes will only work with exactly one (1) sub mesh");
  273. // }
  274. // }
  275. // }
  276. //}
  277. //void ParticleSystemRenderer::OnDidDeleteMesh (Mesh* mesh)
  278. //{
  279. // // Clear out cached pointer to mesh.
  280. // for (int i = 0; i < ParticleSystemRendererData::kMaxNumParticleMeshes; ++i)
  281. // {
  282. // if (m_Data.cachedMesh[i] != mesh)
  283. // continue;
  284. //
  285. // m_Data.cachedMesh[i] = NULL;
  286. // m_Data.cachedMeshUserNode[i].RemoveFromList ();
  287. // }
  288. //}
  289. //void ParticleSystemRenderer::GetLocalAABB (AABB& result)
  290. //{
  291. // result = m_LocalSpaceAABB;
  292. //}
  293. //void ParticleSystemRenderer::GetWorldAABB (AABB& result)
  294. //{
  295. // TransformAABB (m_LocalSpaceAABB, GetTransform ().GetPosition (), GetTransform ().GetRotation (), result);
  296. //}
  297. float ParticleSystemRenderer::GetSortingFudge () const
  298. {
  299. return m_Data.sortingFudge;
  300. }
  301. //void ParticleSystemRenderer::CheckConsistency ()
  302. //{
  303. // Super::CheckConsistency ();
  304. // m_Data.maxParticleSize = std::max (0.0F, m_Data.maxParticleSize);
  305. // m_Data.normalDirection = clamp<float>(m_Data.normalDirection, 0.0f, 1.0f);
  306. //}
  307. void ParticleSystemRenderer::Reset ()
  308. {
  309. //Super::Reset ();
  310. m_Data.orthographic = false;
  311. m_Data.scale = 1.0F;
  312. m_Data.renderMode = kSRMBillboard;
  313. m_Data.lengthScale = 2.0F;
  314. m_Data.velocityScale = 0.0F;
  315. m_Data.cameraVelocityScale = 0.0F;
  316. m_Data.maxParticleSize = 0.5F;
  317. m_Data.sortingFudge = 0.0F;
  318. m_Data.sortMode = kSSMNone;
  319. m_Data.normalDirection = 1.0f;
  320. //for(int i = 0; i < ParticleSystemRendererData::kMaxNumParticleMeshes; i++)
  321. // m_Mesh[i] = NULL;
  322. //m_LocalSpaceAABB.SetCenterAndExtent (Vector3f::ZERO, Vector3f::ZERO);
  323. m_LocalSpaceAABB.set(Vector3f::ZERO, Vector3f::ZERO);
  324. #if UNITY_EDITOR
  325. m_EditorEnabled = true;
  326. #endif
  327. }
  328. //void ParticleSystemRenderer::UpdateRenderer ()
  329. //{
  330. // ParticleSystem* system = QueryComponent(ParticleSystem);
  331. // if (system)
  332. // {
  333. // SetVisible (true);
  334. // BoundsChanged();
  335. // }
  336. // else
  337. // {
  338. // UpdateManagerState (false);
  339. // }
  340. //
  341. // Super::UpdateRenderer ();
  342. //}
  343. //void ParticleSystemRenderer::Update (const AABB& aabb)
  344. //{
  345. // m_LocalSpaceAABB = aabb;
  346. // UpdateManagerState (true);
  347. //}
  348. void ParticleSystemRenderer::RendererBecameVisible()
  349. {
  350. //Super::RendererBecameVisible();
  351. //ParticleSystem* system = QueryComponent(ParticleSystem);
  352. //if(system)
  353. // system->RendererBecameVisible();
  354. }
  355. void ParticleSystemRenderer::RendererBecameInvisible()
  356. {
  357. //Super::RendererBecameInvisible();
  358. //ParticleSystem* system = QueryComponent(ParticleSystem);
  359. //if(system)
  360. // system->RendererBecameInvisible();
  361. }
  362. //void ParticleSystemRenderer::UpdateLocalAABB()
  363. //{
  364. // AABB aabb;
  365. // GetLocalAABB(aabb);
  366. // m_TransformInfo.localAABB = aabb;
  367. //}
  368. template<ParticleSystemRenderMode renderMode>
  369. void GenerateParticleGeometry (ParticleSystemVertex* vbPtr,
  370. const ParticleSystemGeomConstInputData& constData,
  371. const ParticleSystemRendererData& rendererData,
  372. const ParticleSystemParticles& ps,
  373. const ParticleSystemParticlesTempData& psTemp,
  374. size_t startIndex,
  375. size_t endIndex,
  376. const Matrix4x4f& worldViewMatrix,
  377. const Matrix4x4f& viewToWorldMatrix)
  378. {
  379. float maxPlaneScale = constData.maxPlaneScale;
  380. float maxOrthoSize = constData.maxOrthoSize;
  381. float numUVFrame = constData.numUVFrame;
  382. Vector3f xSpan = constData.xSpan;
  383. Vector3f ySpan = constData.ySpan;
  384. Vector3f cameraVelocity = constData.m_CameraVelocity * rendererData.cameraVelocityScale;
  385. int numTilesX = constData.m_NumTilesX;
  386. float animUScale = constData.animUScale;
  387. float animVScale = constData.animVScale;
  388. bool usesSheetIndex = constData.usesSheetIndex;
  389. int uvModuleMode = constData.uvModuleMode;
  390. float lengthScale = rendererData.lengthScale;
  391. float velocityScale = rendererData.velocityScale;
  392. float bentNormalFactor = constData.bentNormalFactor;
  393. Vector3f bentNormalVector = constData.bentNormalVector;
  394. bool isSpriteFrame = constData.isSpriteFrame;
  395. const RRP_PARTICLEQUAD_VERTEX_INFO* vertexInfo = constData.vertexInfo;
  396. auto frameCount = rendererData.cachedVertexInfos.size();
  397. Matrix3x3f scaleMatrix;
  398. scaleMatrix.SetScale(constData.globalScale);
  399. // Vector2f uv[4] = { Vector2f(0.0f, 1.0f),
  400. // Vector2f(1.0f, 1.0f),
  401. // Vector2f(1.0f, 0.0f),
  402. // Vector2f(0.0f, 0.0f)};
  403. // Vector4f uv2[4] = { Vector4f(0.0f, 1.0f, 0.0f, 0.0f),
  404. // Vector4f(1.0f, 1.0f, 0.0f, 0.0f),
  405. // Vector4f(1.0f, 0.0f, 0.0f, 0.0f),
  406. // Vector4f(0.0f, 0.0f, 0.0f, 0.0f)};
  407. Tex2F uv[4] = {
  408. vertexInfo->tl,
  409. vertexInfo->tr,
  410. vertexInfo->br,
  411. vertexInfo->bl
  412. };
  413. float invAnimVScale = 1.0f - animVScale;
  414. #if REDREAM_EDITOR
  415. auto stageContentToWorldMatrix = Transform::GetContentToWorldMatrix();
  416. #endif
  417. for( size_t i = startIndex; i < endIndex; ++i )
  418. {
  419. if (usesSheetIndex && uvModuleMode == 1 && frameCount > 0) {
  420. auto sheetIndex = psTemp.sheetIndex[i] * frameCount;
  421. const int index0 = FloorfToIntPos (sheetIndex);
  422. vertexInfo = &rendererData.cachedVertexInfos[index0];
  423. uv[0] = vertexInfo->tl,
  424. uv[1] = vertexInfo->tr;
  425. uv[2] = vertexInfo->br;
  426. uv[3] = vertexInfo->bl;
  427. }
  428. Vector3f vert[4];
  429. Vector3f n0, n1;
  430. Vector3f position;
  431. worldViewMatrix.MultiplyPoint3 (ps.position[i], position);
  432. // Constrain the size to be a fraction of the viewport size.
  433. // v[0].z * / farPlaneZ * farPlaneWorldSpaceLength * maxLength[0...1]
  434. // Also all valid z's are negative so we just negate the whole equation
  435. // float maxWorldSpaceLength = position.z * maxPlaneScale + maxOrthoSize;
  436. // float hsize = std::min (psTemp.size[i], maxWorldSpaceLength) * 0.5f;
  437. float hsize = psTemp.size[i] * 0.5f;
  438. if (renderMode == kSRMBillboard)
  439. {
  440. float r = ps.rotation[i] * kDeg2Rad;
  441. float s = Sin (r);
  442. float c = Cos (r);
  443. if (isSpriteFrame) {
  444. GLfloat x1 = -hsize * vertexInfo->centerPercentage.left;
  445. GLfloat y1 = -hsize * vertexInfo->centerPercentage.bottom;
  446. GLfloat x2 = hsize * vertexInfo->centerPercentage.right;
  447. GLfloat y2 = hsize * vertexInfo->centerPercentage.top;
  448. vert[0] = position + scaleMatrix.MultiplyVector3(Vec3(x1 * c + y2 * s, y2 * c - x1 * s, 0.0f));
  449. vert[1] = position + scaleMatrix.MultiplyVector3(Vec3(x2 * c + y2 * s, y2 * c - x2 * s, 0.0f));
  450. vert[2] = position + scaleMatrix.MultiplyVector3(Vec3(x2 * c + y1 * s, y1 * c - x2 * s, 0.0f));
  451. vert[3] = position + scaleMatrix.MultiplyVector3(Vec3(x1 * c + y1 * s, y1 * c - x1 * s, 0.0f));
  452. } else {
  453. n0 = scaleMatrix.MultiplyVector3(Vector3f(-c+s, s+c, 0.0f) * hsize);
  454. n1 = scaleMatrix.MultiplyVector3(Vector3f( c+s, -s+c, 0.0f) * hsize);
  455. vert[0] = position + n0;
  456. vert[1] = position + n1;
  457. vert[2] = position - n0;
  458. vert[3] = position - n1;
  459. }
  460. }
  461. else if (renderMode == kSRMBillboardFixedHorizontal || renderMode == kSRMBillboardFixedVertical)
  462. {
  463. float s = Sin ((ps.rotation[i]+0.78539816339744830961566084581988f) * kDeg2Rad);
  464. float c = Cos ((ps.rotation[i]+0.78539816339744830961566084581988f) * kDeg2Rad);
  465. n0 = scaleMatrix.MultiplyVector3((xSpan*c + ySpan*s) * hsize);
  466. n1 = scaleMatrix.MultiplyVector3((ySpan*c - xSpan*s) * hsize);
  467. vert[0] = position + n0;
  468. vert[1] = position + n1;
  469. vert[2] = position - n0;
  470. vert[3] = position - n1;
  471. }
  472. else if (renderMode == kSRMStretch3D)
  473. {
  474. //RH BUG FOR LATER: Here we see the stretching bug as described by case no 434115...this is a Flash VM error, where a writeFloat (or readFloat) fails.
  475. Vector3f velocity;
  476. worldViewMatrix.MultiplyVector3(ps.velocity[i] + ps.animatedVelocity[i], velocity);
  477. velocity -= cameraVelocity;
  478. float sqrVelocity = SqrMagnitude (velocity);
  479. auto camPos = Camera::getDefaultCamera()->getPosition3D();
  480. position -= camPos;
  481. Vector2f delta;
  482. Vector3f endProj;
  483. bool nonZeroVelocity = sqrVelocity > Vector3f::epsilon;
  484. if (nonZeroVelocity)
  485. {
  486. endProj = position - velocity * (velocityScale + FastInvSqrt (sqrVelocity) * (lengthScale * psTemp.size[i]));
  487. delta.x = position.z*endProj.y - position.y*endProj.z;
  488. delta.y = position.x*endProj.z - position.z*endProj.x;
  489. delta = NormalizeFast(delta);
  490. }
  491. else
  492. {
  493. endProj = position;
  494. delta = Vector2f::UNIT_X;
  495. }
  496. n0 = n1 = scaleMatrix.MultiplyVector3(Vector3f(delta.x, delta.y, 0.0f) * hsize);
  497. if (isSpriteFrame) {
  498. n0 *= vertexInfo->centerPercentage.top;
  499. n1 *= vertexInfo->centerPercentage.bottom;
  500. auto posTemp = position;
  501. position = endProj.lerp(position, vertexInfo->centerPercentage.left * 0.5f + 0.5f);
  502. endProj = posTemp.lerp(endProj, vertexInfo->centerPercentage.right * 0.5f + 0.5f);
  503. }
  504. position += camPos;
  505. endProj += camPos;
  506. vert[0] = position + n0;
  507. vert[1] = endProj + n0;
  508. vert[2] = endProj - n1;
  509. vert[3] = position - n1;
  510. }
  511. // UV animation
  512. float sheetIndex;
  513. if(usesSheetIndex && uvModuleMode == 0 && !isSpriteFrame)
  514. {
  515. // TODO: Pretty much the perfect candidate for SIMD
  516. sheetIndex = psTemp.sheetIndex[i] * numUVFrame;
  517. Assert (psTemp.sheetIndex[i] >= 0.0f && psTemp.sheetIndex[i] <= 1.0f);
  518. const int index0 = FloorfToIntPos (sheetIndex);
  519. const int index1 = index0 + 1;
  520. Vector2f offset0, offset1;
  521. const float blend = sheetIndex - (float)index0;
  522. int vIdx = index0 / numTilesX;
  523. int uIdx = index0 - vIdx * numTilesX;
  524. offset0.x = (float)uIdx * animUScale;
  525. // offset0.y = invAnimVScale - (float)vIdx * animVScale;
  526. offset0.y = (float)vIdx * animVScale;
  527. vIdx = index1 / numTilesX;
  528. uIdx = index1 - vIdx * numTilesX;
  529. offset1.x = (float)uIdx * animUScale;
  530. // offset1.y = invAnimVScale - (float)vIdx * animVScale;
  531. offset1.y = (float)vIdx * animVScale;
  532. // uv[0].set(offset0.x, offset0.y + animVScale );
  533. // uv[1].set(offset0.x + animUScale, offset0.y + animVScale );
  534. // uv[2].set(offset0.x + animUScale, offset0.y );
  535. // uv[3].set(offset0.x, offset0.y );
  536. uv[0].u = offset0.x; uv[0].v = offset0.y; // invers v, top-left
  537. uv[1].u = offset0.x + animUScale; uv[1].v = offset0.y; // invers v, top-right
  538. uv[2].u = offset0.x + animUScale; uv[2].v = offset0.y + animVScale; // invers v, bottom-right
  539. uv[3].u = offset0.x; uv[3].v = offset0.y + animVScale; // invers v, bottom-left
  540. // uv2[0].set(offset1.x, offset1.y + animVScale, blend, 0.0f );
  541. // uv2[1].set(offset1.x + animUScale, offset1.y + animVScale, blend, 0.0f );
  542. // uv2[2].set(offset1.x + animUScale, offset1.y, blend, 0.0f );
  543. // uv2[3].set(offset1.x, offset1.y, blend, 0.0f );
  544. }
  545. n0 = viewToWorldMatrix.MultiplyVector3(n0 * bentNormalFactor);
  546. n1 = viewToWorldMatrix.MultiplyVector3(n1 * bentNormalFactor);
  547. // ColorRGBAf color = ColorRGBAf(psTemp.color[i]);
  548. auto& color = psTemp.color[i];
  549. #if REDREAM_EDITOR
  550. for (int i = 0; i < 4; i++) {
  551. vert[i] = stageContentToWorldMatrix.MultiplyPoint3(vert[i]);
  552. }
  553. #endif
  554. vbPtr->tl.vertices = vert[0];
  555. // vbPtr[0].normal = bentNormalVector + n0;
  556. vbPtr->tl.colors = color;
  557. vbPtr->tl.texCoords = Tex2F(uv[0]);
  558. // vbPtr[0].tangent = uv2[0];
  559. vbPtr->tr.vertices = vert[1];
  560. // vbPtr[1].normal = bentNormalVector + n1;
  561. vbPtr->tr.colors = color;
  562. vbPtr->tr.texCoords = Tex2F(uv[1]);
  563. // vbPtr[1].tangent = uv2[1];
  564. vbPtr->br.vertices = vert[2];
  565. // vbPtr[2].normal = bentNormalVector - n0;
  566. vbPtr->br.colors = color;
  567. vbPtr->br.texCoords = Tex2F(uv[2]);
  568. // vbPtr[2].tangent = uv2[2];
  569. vbPtr->bl.vertices = vert[3];
  570. // vbPtr[3].normal = bentNormalVector - n1;
  571. vbPtr->bl.colors = color;
  572. vbPtr->bl.texCoords = Tex2F(uv[3]);
  573. // vbPtr[3].tangent = uv2[3];
  574. // Next four vertices
  575. // vbPtr += 4;
  576. vbPtr++;
  577. }
  578. }
  579. //static void DrawMeshParticles (const ParticleSystemGeomConstInputData& constInput, const ParticleSystemRendererData& rendererData, const Matrix4x4f& worldMatrix, const ParticleSystemParticles& ps, const ParticleSystemParticlesTempData& psTemp, const ChannelAssigns& channels)
  580. //{
  581. // int numMeshes = 0;
  582. // ParticleMeshData particleMeshes[ParticleSystemRendererData::kMaxNumParticleMeshes];
  583. // Vector3f defaultNormal(0, 0, 0);
  584. // Vector4f defaultTangent(0, 0, 0, 0);
  585. // ColorRGBA32 defaultColor(255, 255, 255, 255);
  586. // Vector2f defaultTexCoords(0, 0);
  587. // for(int i = 0; i < ParticleSystemRendererData::kMaxNumParticleMeshes; i++)
  588. // {
  589. // if(constInput.m_MeshIndexCount[i] == 0)
  590. // break;
  591. // const Mesh* mesh = rendererData.cachedMesh[i];
  592. // if(mesh == NULL || !mesh->HasVertexData())
  593. // break;
  594. // ParticleMeshData& dest = particleMeshes[i];
  595. // dest.vertexCount = mesh->GetVertexCount();
  596. // dest.positions = mesh->GetVertexBegin();
  597. // dest.normals = mesh->GetNormalBegin();
  598. // if (dest.normals.IsNull())
  599. // dest.normals = StrideIterator<Vector3f>(&defaultNormal, 0);
  600. // dest.tangents = mesh->GetTangentBegin();
  601. // if (dest.tangents.IsNull())
  602. // dest.tangents = StrideIterator<Vector4f>(&defaultTangent, 0);
  603. // dest.texCoords = mesh->GetUvBegin();
  604. // if (dest.texCoords.IsNull())
  605. // dest.texCoords = StrideIterator<Vector2f>(&defaultTexCoords, 0);
  606. // dest.colors = mesh->GetColorBegin();
  607. // if (dest.colors.IsNull())
  608. // dest.colors = StrideIterator<ColorRGBA32>(&defaultColor, 0);
  609. // dest.indexCount = constInput.m_MeshIndexCount[i];
  610. // dest.indexBuffer = constInput.m_MeshIndexBuffer[i];
  611. // numMeshes++;
  612. // }
  613. //
  614. // if(0 == numMeshes)
  615. // return;
  616. //
  617. // GfxDevice& device = GetGfxDevice();
  618. //
  619. // Matrix4x4f viewMatrix;
  620. // CopyMatrix (device.GetViewMatrix (), viewMatrix.GetPtr ());
  621. //
  622. // const size_t particleCount = ps.array_size ();
  623. //
  624. // float probability = 1.0f / (float)numMeshes;
  625. //
  626. // // @TODO: We should move all these platform dependent numbers into Gfx specific code and get it from there.
  627. // const int kMaxVertices = 65536;
  628. //
  629. //#if UNITY_WII
  630. // const int kMaxIndices = 65536;
  631. //#else
  632. // const int kMaxIndices = kDynamicBatchingIndicesThreshold;
  633. //#endif
  634. //
  635. // int particleOffset = 0;
  636. // while (particleOffset < particleCount)
  637. // {
  638. // int numVertices = 0;
  639. // int numIndices = 0;
  640. // int particleCountBatch = 0;
  641. //
  642. // // Figure out batch size
  643. // for(int i = particleOffset; i < particleCount; i++)
  644. // {
  645. // const float randomValue = GenerateRandom(ps.randomSeed[i] + kParticleSystemMeshSelectionId);
  646. // int lastNumVertices = 0;
  647. // int lastNumIndices = 0;
  648. // for(int j = 0; j < numMeshes; j++)
  649. // {
  650. // const float lower = probability * j;
  651. // const float upper = probability * (j + 1);
  652. // if((randomValue >= lower) && (randomValue <= upper))
  653. // {
  654. // lastNumVertices = particleMeshes[j].vertexCount;
  655. // lastNumIndices = particleMeshes[j].indexCount;
  656. // break;
  657. // }
  658. // }
  659. // if((numVertices >= kMaxVertices) || (numIndices >= kMaxIndices))
  660. // {
  661. // break;
  662. // }
  663. // else
  664. // {
  665. // numVertices += lastNumVertices;
  666. // numIndices += lastNumIndices;
  667. // particleCountBatch++;
  668. // }
  669. // }
  670. //
  671. // const int vertexCount = numVertices;
  672. // const int indexCount = numIndices;
  673. //
  674. // // Figure out if normals and tangents are needed by shader
  675. // UInt32 normalTangentMask = channels.GetSourceMap() & VERTEX_FORMAT2(Normal, Tangent);
  676. //
  677. // // Tangents requires normals
  678. // if( normalTangentMask & VERTEX_FORMAT1(Tangent) )
  679. // normalTangentMask |= VERTEX_FORMAT1(Normal);
  680. //
  681. // // Get VBO chunk
  682. // DynamicVBO& vbo = device.GetDynamicVBO();
  683. // UInt8* vbPtr = NULL;
  684. // UInt16* ibPtr = NULL;
  685. // const UInt32 mandatoryChannels = VERTEX_FORMAT3(Vertex, Color, TexCoord0);
  686. // if( !vbo.GetChunk( mandatoryChannels | normalTangentMask,
  687. // vertexCount, indexCount,
  688. // DynamicVBO::kDrawIndexedTriangles,
  689. // (void**)&vbPtr, (void**)&ibPtr ) )
  690. // {
  691. // return;
  692. // }
  693. //
  694. // int vertexOffset = 0;
  695. // int indexOffset = 0;
  696. // const int startIndex = particleOffset;
  697. // const int endIndex = particleOffset + particleCountBatch;
  698. // for( int i = startIndex; i < endIndex; ++i )
  699. // {
  700. // const Vector3f position = ps.position[i];
  701. // const float rotation = ps.rotation[i];
  702. // const float size = psTemp.size[i];
  703. // const Vector3f axisOfRotation = NormalizeSafe (ps.axisOfRotation[i], Vector3f::yAxis);
  704. // const ColorRGBA32 particleColor = psTemp.color[i];
  705. //
  706. // // Only shared part is actually rotation. xformNoScale doesn't need a translation, so no need to copy that data
  707. // Matrix4x4f xformNoScale;
  708. // xformNoScale.SetTR (position, AxisAngleToQuaternion (axisOfRotation, rotation));
  709. //
  710. // Matrix4x4f xform = xformNoScale;
  711. // ScaleMatrix(xform, size);
  712. //
  713. // // Figure out which mesh to use
  714. // const float randomValue = GenerateRandom(ps.randomSeed[i] + kParticleSystemMeshSelectionId);
  715. // int meshIndex = 0;
  716. // for(int j = 0; j < numMeshes; j++)
  717. // {
  718. // const float lower = probability * j;
  719. // const float upper = probability * (j + 1);
  720. // if((randomValue >= lower) && (randomValue <= upper))
  721. // {
  722. // meshIndex = j;
  723. // break;
  724. // }
  725. // }
  726. //
  727. // const ParticleMeshData& mesh = particleMeshes[meshIndex];
  728. //
  729. // // Fill up vbo here
  730. // if( normalTangentMask == VERTEX_FORMAT2(Normal, Tangent) )
  731. // TransformParticleMesh<true, true>(mesh, particleColor, xform, xformNoScale, &vbPtr);
  732. // else if( normalTangentMask == VERTEX_FORMAT1(Normal) )
  733. // TransformParticleMesh<true, false>(mesh, particleColor, xform, xformNoScale, &vbPtr);
  734. // else if( normalTangentMask == 0 )
  735. // TransformParticleMesh<false, false>(mesh, particleColor, xform, xformNoScale, &vbPtr);
  736. // else
  737. // ErrorString("Invalid normalTangentMask");
  738. //
  739. // const int meshIndexMax = mesh.indexCount - 2;
  740. // for(int index = 0; index < meshIndexMax; index+=3)
  741. // {
  742. // ibPtr[index+0] = mesh.indexBuffer[index+0] + vertexOffset;
  743. // ibPtr[index+1] = mesh.indexBuffer[index+1] + vertexOffset;
  744. // ibPtr[index+2] = mesh.indexBuffer[index+2] + vertexOffset;
  745. // }
  746. // ibPtr += mesh.indexCount;
  747. //
  748. // vertexOffset += mesh.vertexCount;
  749. // indexOffset += mesh.indexCount;
  750. // }
  751. //
  752. // vbo.ReleaseChunk (vertexCount, indexCount);
  753. // device.SetViewMatrix(viewMatrix.GetPtr());
  754. // device.SetWorldMatrix(worldMatrix.GetPtr());
  755. // vbo.DrawChunk (channels);
  756. // GPU_TIMESTAMP();
  757. //
  758. // particleOffset += particleCountBatch;
  759. // }
  760. //}
  761. static void DrawParticlesInternal(const ParticleSystemGeomConstInputData& constData, const ParticleSystemRendererData& rendererData, const Matrix4x4f& worldViewMatrix, const Matrix4x4f& viewToWorldMatrix, const ParticleSystemParticles& ps, const ParticleSystemParticlesTempData& psTemp, ParticleSystemVertex* vbPtr, const size_t particleOffset, const size_t numParticles, int renderMode)
  762. {
  763. const size_t endIndex = particleOffset + numParticles;
  764. //renderMode = kSRMStretch3D;
  765. if (renderMode == kSRMBillboard)
  766. GenerateParticleGeometry<kSRMBillboard> (vbPtr, constData, rendererData, ps, psTemp, particleOffset, endIndex, worldViewMatrix, viewToWorldMatrix);
  767. if (renderMode == kSRMStretch3D)
  768. GenerateParticleGeometry<kSRMStretch3D> (vbPtr, constData, rendererData, ps, psTemp, particleOffset, endIndex, worldViewMatrix, viewToWorldMatrix);
  769. if (renderMode == kSRMBillboardFixedHorizontal)
  770. GenerateParticleGeometry<kSRMBillboardFixedHorizontal> (vbPtr, constData, rendererData, ps, psTemp, particleOffset, endIndex, worldViewMatrix, viewToWorldMatrix);
  771. if (renderMode == kSRMBillboardFixedVertical)
  772. GenerateParticleGeometry<kSRMBillboardFixedVertical> (vbPtr, constData, rendererData, ps, psTemp, particleOffset, endIndex, worldViewMatrix, viewToWorldMatrix);
  773. }
  774. static void DrawParticles(const ParticleSystemGeomConstInputData& constData, const ParticleSystemRendererData& rendererData, const Matrix4x4f& worldViewMatrix, const Matrix4x4f& viewToWorldMatrix, const ParticleSystemParticles& ps, const ParticleSystemParticlesTempData& psTemp, ParticleSystemVertex* vbPtr)
  775. {
  776. //GfxDevice& device = GetGfxDevice();
  777. const size_t particleCount = ps.array_size();
  778. if(vbPtr)
  779. {
  780. DrawParticlesInternal(constData, rendererData, worldViewMatrix, viewToWorldMatrix, ps, psTemp, vbPtr, 0, particleCount, rendererData.renderMode);
  781. }
  782. else
  783. {
  784. int particleOffset = 0;
  785. while (particleOffset < particleCount)
  786. {
  787. const int particleCountBatch = std::min(kMaxNumParticlesPerBatch, (int)particleCount - particleOffset);
  788. unsigned int vertexCnount = sizeof(V3F_C4B_T2F);
  789. vbPtr = (ParticleSystemVertex*)malloc(vertexCnount * particleCountBatch * 4);
  790. DrawParticlesInternal(constData, rendererData, worldViewMatrix, viewToWorldMatrix, ps, psTemp, vbPtr, particleOffset, particleCountBatch, rendererData.renderMode);
  791. particleOffset += particleCountBatch;
  792. GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POSITION |
  793. GL::VERTEX_ATTRIB_FLAG_COLOR |
  794. GL::VERTEX_ATTRIB_FLAG_TEX_COORD);
  795. glBindBuffer(GL_ARRAY_BUFFER, 0);
  796. if (rendererData.orthographic)
  797. {
  798. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, vertexCnount, &(vbPtr->tl.vertices));
  799. }
  800. else
  801. {
  802. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, vertexCnount, &(vbPtr->tl.vertices));
  803. }
  804. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, vertexCnount, &(vbPtr->tl.texCoords));
  805. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, vertexCnount, &(vbPtr->tl.colors));
  806. GLuint* vertexIndexBuff = new GLuint[particleCountBatch * 6];
  807. for(int particleIdx = 0; particleIdx < particleCountBatch; particleIdx++){
  808. int idx0 = particleIdx * 4 + 0;
  809. int idx1 = particleIdx * 4 + 1;
  810. int idx2 = particleIdx * 4 + 2;
  811. int idx3 = particleIdx * 4 + 3;
  812. vertexIndexBuff[particleIdx * 6 + 0] = idx0;
  813. vertexIndexBuff[particleIdx * 6 + 1] = idx1;
  814. vertexIndexBuff[particleIdx * 6 + 2] = idx2;
  815. vertexIndexBuff[particleIdx * 6 + 3] = idx3;
  816. vertexIndexBuff[particleIdx * 6 + 4] = idx2;
  817. vertexIndexBuff[particleIdx * 6 + 5] = idx1;
  818. }
  819. glDrawElements(GL_TRIANGLES, particleCountBatch * 6, GL_UNSIGNED_INT, vertexIndexBuff);
  820. delete[] vertexIndexBuff;
  821. free(vbPtr);
  822. CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, vertexCnount);
  823. CHECK_GL_ERROR_DEBUG();
  824. }
  825. }
  826. }
  827. void ParticleSystemRenderer::CalculateTotalParticleCount(UInt32& totalNumberOfParticles, RParticleSystem& system, bool first)
  828. {
  829. //ParticleSystemRenderer* renderer = system.QueryComponent(RParticleSystemRenderer);
  830. //if(!renderer || first)
  831. //{
  832. // totalNumberOfParticles += system.GetParticleCount();
  833. // Transform* t = system.QueryComponent (Transform);
  834. // if (t == NULL)
  835. // return;
  836. // for (Transform::iterator i=t->begin ();i != t->end ();i++)
  837. // {
  838. // ParticleSystem* child = (**i).QueryComponent(ParticleSystem);
  839. // if (child)
  840. // CalculateTotalParticleCount(totalNumberOfParticles, *child, false);
  841. // }
  842. //}
  843. totalNumberOfParticles += system.GetParticleCount();
  844. }
  845. void ParticleSystemRenderer::CombineParticleBuffersRec(int& offset, ParticleSystemParticles& ps, ParticleSystemParticlesTempData& psTemp, RParticleSystem& system, bool first, bool needsAxisOfRotation)
  846. {
  847. if(first)
  848. {
  849. int particleCount = system.GetParticleCount();
  850. ps.array_merge_preallocated(system.GetParticles(), offset, needsAxisOfRotation, false);
  851. if(system.m_ReadOnlyState->useLocalSpace)
  852. {
  853. Matrix4x4f localToWorld = system.getNodeToWorldTransform();
  854. int endIndex = offset + particleCount;
  855. for(int i = offset; i < endIndex; i++)
  856. ps.position[i] = localToWorld.MultiplyPoint3(ps.position[i]);
  857. for(int i = offset; i < endIndex; i++)
  858. ps.velocity[i] = localToWorld.MultiplyVector3(ps.velocity[i]);
  859. for(int i = offset; i < endIndex; i++)
  860. ps.animatedVelocity[i] = localToWorld.MultiplyVector3(ps.animatedVelocity[i]);
  861. if(ps.usesAxisOfRotation)
  862. for(int i = offset; i < endIndex; i++)
  863. ps.axisOfRotation[i] = localToWorld.MultiplyVector3(ps.axisOfRotation[i]);
  864. }
  865. RParticleSystem::UpdateModulesNonIncremental(system, ps, psTemp, offset, offset + particleCount);
  866. offset += particleCount;
  867. }
  868. }
  869. void ParticleSystemRenderer::SetUsesAxisOfRotationRec(RParticleSystem& shuriken, bool first)
  870. {
  871. if(first)
  872. {
  873. shuriken.SetUsesAxisOfRotation();
  874. }
  875. }
  876. //void ParticleSystemRenderer::CombineBoundsRec(RParticleSystem& shuriken, MinMaxAABB& aabb, bool first)
  877. //{
  878. // ParticleSystemRenderer* renderer = shuriken.QueryComponent(ParticleSystemRenderer);
  879. // if(!renderer || first)
  880. // {
  881. // AABB result = shuriken.m_State->minMaxAABB;
  882. // if(!shuriken.m_ReadOnlyState->useLocalSpace)
  883. // InverseTransformAABB (result, renderer->GetTransform().GetPosition (), renderer->GetTransform().GetRotation (), result);
  884. //
  885. // if(first)
  886. // aabb = result;
  887. // else
  888. // aabb.Encapsulate(result);
  889. //
  890. // Transform* t = shuriken.QueryComponent (Transform);
  891. // if (t == NULL)
  892. // return;
  893. // for (Transform::iterator i=t->begin ();i != t->end ();i++)
  894. // {
  895. // ParticleSystem* shuriken = (**i).QueryComponent(ParticleSystem);
  896. // if (shuriken)
  897. // CombineBoundsRec(*shuriken, aabb, false);
  898. // }
  899. // }
  900. //}
  901. void ParticleSystemRenderer::Render (RParticleSystem* system, ParticleSystemVertex* vbPtr/* int materialIndex, const ChannelAssigns& channels*/, const Matrix4x4f &transform)
  902. {
  903. //ParticleSystem::SyncJobs();
  904. //ParticleSystem* system = QueryComponent(ParticleSystem);
  905. //if(!system)
  906. // return;
  907. //// Can't render without an active camera (case 568930)
  908. //// Can remove check when we finally kill Renderer.Render()
  909. //if (!GetCurrentCameraPtr())
  910. // return;
  911. //PROFILER_AUTO_GFX(gParticlesSingleProfile, this);
  912. RParticleSystem::SyncJobs();
  913. UInt32 numParticles = 0;
  914. CalculateTotalParticleCount(numParticles, *system, true);
  915. if(numParticles)
  916. RenderInternal(*system, *this, vbPtr, numParticles, transform);
  917. }
  918. //void ParticleSystemRenderer::RenderMultiple (const BatchInstanceData* instances, size_t count, const ChannelAssigns& channels)
  919. //{
  920. // ParticleSystem::SyncJobs();
  921. //
  922. // size_t numParticlesBatch = 0;
  923. //
  924. // BatchInstanceData const* instancesEnd = instances + count;
  925. // BatchInstanceData const* iBatchBegin = instances;
  926. // BatchInstanceData const* iBatchEnd = instances;
  927. // while(iBatchEnd != instancesEnd)
  928. // {
  929. // Assert(iBatchEnd->renderer->GetRendererType() == kRendererParticleSystem);
  930. // ParticleSystemRenderer* psRenderer = (ParticleSystemRenderer*)iBatchEnd->renderer;
  931. // Assert(psRenderer->GetRenderMode() != kSRMMesh);
  932. // ParticleSystem* system = psRenderer->QueryComponent(ParticleSystem);
  933. // if (!system )
  934. // {
  935. // iBatchEnd++;
  936. // continue;
  937. // }
  938. // UInt32 numParticles = 0;
  939. // psRenderer->CalculateTotalParticleCount(numParticles, *system, true);
  940. //
  941. // if((numParticlesBatch + numParticles) <= kMaxNumParticlesPerBatch)
  942. // {
  943. // numParticlesBatch += numParticles;
  944. // iBatchEnd++;
  945. // }
  946. // else
  947. // {
  948. // if(numParticlesBatch)
  949. // {
  950. // RenderBatch(iBatchBegin, iBatchEnd - iBatchBegin, numParticlesBatch, channels);
  951. // numParticlesBatch = 0;
  952. // iBatchBegin = iBatchEnd;
  953. // }
  954. // else // Can't fit in one draw call
  955. // {
  956. // RenderBatch(iBatchEnd, 1, numParticles, channels);
  957. // iBatchEnd++;
  958. // iBatchBegin = iBatchEnd;
  959. // }
  960. // }
  961. // }
  962. //
  963. // if((iBatchBegin != iBatchEnd) && numParticlesBatch)
  964. // RenderBatch(iBatchBegin, iBatchEnd - iBatchBegin, numParticlesBatch, channels);
  965. //}
  966. //void ParticleSystemRenderer::RenderBatch (const BatchInstanceData* instances, size_t count, size_t numParticles, const ChannelAssigns& channels)
  967. //{
  968. // DebugAssert(numParticles);
  969. //
  970. // GfxDevice& device = GetGfxDevice();
  971. //
  972. // const MaterialPropertyBlock* customProps = count > 0 ? instances[0].renderer->GetCustomProperties() : NULL;
  973. // if (customProps)
  974. // device.SetMaterialProperties (*customProps);
  975. //
  976. // Matrix4x4f viewMatrix;
  977. // CopyMatrix (device.GetViewMatrix (), viewMatrix.GetPtr ());
  978. //
  979. // ParticleSystemVertex* vbPtr = 0;
  980. // DynamicVBO& vbo = device.GetDynamicVBO();
  981. // if(numParticles <= kMaxNumParticlesPerBatch)
  982. // {
  983. // if( !vbo.GetChunk( (1<<kShaderChannelVertex) | (1<<kShaderChannelNormal) | (1<<kShaderChannelTexCoord0) | (1<<kShaderChannelColor) | (1<<kShaderChannelTangent),
  984. // numParticles * 4, 0,
  985. // DynamicVBO::kDrawQuads,
  986. // (void**)&vbPtr, NULL ) )
  987. // {
  988. // return;
  989. // }
  990. // }
  991. //
  992. // PROFILER_AUTO_GFX(gParticlesBatchProfile, 0);
  993. //
  994. // // Allocate VBO if count is not above threshold. Else just pass null down
  995. // BatchInstanceData const* iBatchBegin = instances;
  996. // BatchInstanceData const* instancesEnd = instances + count;
  997. // size_t particleOffset = 0;
  998. // while (iBatchBegin != instancesEnd)
  999. // {
  1000. // Assert(iBatchBegin->renderer->GetRendererType() == kRendererParticleSystem);
  1001. // ParticleSystemRenderer* psRenderer = (ParticleSystemRenderer*)iBatchBegin->renderer;
  1002. // Assert(psRenderer->GetRenderMode() != kSRMMesh);
  1003. // ParticleSystem* system = psRenderer->QueryComponent(ParticleSystem);
  1004. // UInt32 particleCountTotal = 0;
  1005. // if (system)
  1006. // {
  1007. // // It would be nice to filter out NULL particle systems earlier, but we don't (case 504744)
  1008. // CalculateTotalParticleCount(particleCountTotal, *system, true);
  1009. // if(particleCountTotal)
  1010. // RenderInternal(*system, *psRenderer, channels, vbPtr + particleOffset * 4, particleCountTotal);
  1011. // }
  1012. // iBatchBegin++;
  1013. // particleOffset += particleCountTotal;
  1014. // }
  1015. //
  1016. // if(vbPtr)
  1017. // {
  1018. // vbo.ReleaseChunk (numParticles * 4, 0);
  1019. //
  1020. // // Draw
  1021. // device.SetViewMatrix (Matrix4x4f::identity.GetPtr()); // implicitly sets world to identity
  1022. //
  1023. // PROFILER_BEGIN(gSubmitVBOParticleProfile, 0)
  1024. // vbo.DrawChunk (channels);
  1025. // GPU_TIMESTAMP();
  1026. // PROFILER_END
  1027. //
  1028. // if (count > 1)
  1029. // device.AddBatchingStats(numParticles * 2, numParticles * 4, count);
  1030. //
  1031. // device.SetViewMatrix(viewMatrix.GetPtr());
  1032. // }
  1033. //}
  1034. void ParticleSystemRenderer::RenderInternal (RParticleSystem& system, const ParticleSystemRenderer& renderer, ParticleSystemVertex* vbPtr, UInt32 particleCountTotal, const Matrix4x4f &transform)
  1035. {
  1036. Assert(particleCountTotal);
  1037. #if UNITY_EDITOR
  1038. if (!renderer.m_EditorEnabled)
  1039. return;
  1040. #endif
  1041. //c-edit GfxDevice& device = GetGfxDevice();
  1042. // Render matrix
  1043. Matrix4x4f viewMatrix;
  1044. viewMatrix = Matrix4x4f::IDENTITY;
  1045. //c-edit CopyMatrix (device.GetViewMatrix (), viewMatrix.GetPtr ());
  1046. ParticleSystemParticles* ps = &system.GetParticles ();
  1047. size_t particleCount = ps->array_size ();
  1048. AssertBreak(particleCountTotal >= particleCount);
  1049. UInt8* combineBuffer = 0;
  1050. ParticleSystemParticles combineParticles;
  1051. if(particleCountTotal > particleCount)
  1052. {
  1053. particleCount = particleCountTotal;
  1054. combineBuffer = ALLOC_TEMP_MANUAL(UInt8, particleCountTotal * ParticleSystemParticles::GetParticleSize());
  1055. combineParticles.array_assign_external((void*)&combineBuffer[0], particleCountTotal);
  1056. ps = &combineParticles;
  1057. }
  1058. if(!particleCount)
  1059. return;
  1060. const bool needsAxisOfRotation = !renderer.GetScreenSpaceRotation();
  1061. if(needsAxisOfRotation)
  1062. {
  1063. SetUsesAxisOfRotationRec (system, true);
  1064. }
  1065. ParticleSystemSortMode sortMode = (ParticleSystemSortMode)renderer.m_Data.sortMode;
  1066. bool isInLocalSpace = system.m_ReadOnlyState->useLocalSpace && !combineBuffer;
  1067. Matrix4x4f worldMatrix = Matrix4x4f::IDENTITY;
  1068. #if REDREAM_EDITOR
  1069. if(isInLocalSpace){
  1070. //worldMatrix = system.GetComponent (Transform).GetLocalToWorldMatrixNoScale ();
  1071. worldMatrix = Transform::GetLocalToWorldMatrixNoScale(&system);
  1072. }
  1073. #else
  1074. if(isInLocalSpace){
  1075. //worldMatrix = system.GetComponent (Transform).GetLocalToWorldMatrixNoScale ();
  1076. worldMatrix = transform;
  1077. } else {
  1078. worldMatrix = Director::getInstance()->getRunningScene()->getNodeToParentTransform();
  1079. }
  1080. #endif
  1081. ParticleSystemParticlesTempData psTemp;
  1082. psTemp.color = ALLOC_TEMP_MANUAL(ColorRGBA32, particleCount);
  1083. psTemp.size = ALLOC_TEMP_MANUAL(float, particleCount);
  1084. psTemp.sheetIndex = 0;
  1085. psTemp.particleCount = particleCount;
  1086. psTemp.particleSysytemWorldPos = ALLOC_TEMP_MANUAL(Vec3, particleCount);
  1087. if(combineBuffer)
  1088. {
  1089. int offset = 0;
  1090. CombineParticleBuffersRec(offset, *ps, psTemp, system, true, needsAxisOfRotation);
  1091. if (kSSMNone != sortMode)
  1092. Sort(viewMatrix, *ps, sortMode, &psTemp, true);
  1093. }
  1094. else
  1095. {
  1096. if(system.m_UVModule->GetEnabled())
  1097. psTemp.sheetIndex = ALLOC_TEMP_MANUAL(float, particleCount);
  1098. if (kSSMNone != sortMode)
  1099. {
  1100. Matrix4x4f objectToViewMatrix;
  1101. MultiplyMatrices3x4(viewMatrix, worldMatrix, objectToViewMatrix);
  1102. Sort(objectToViewMatrix, *ps, sortMode, 0, false);
  1103. }
  1104. RParticleSystem::UpdateModulesNonIncremental(system, *ps, psTemp, 0, particleCount);
  1105. }
  1106. if (system._opacityModifyRGB) {
  1107. for (int i = 0; i < particleCount; i++) {
  1108. auto& color = psTemp.color[i];
  1109. color.r *= color.a / 255.0f;
  1110. color.g *= color.a / 255.0f;
  1111. color.b *= color.a / 255.0f;
  1112. }
  1113. }
  1114. // Constrain the size to be a fraction of the viewport size.
  1115. // In perspective case, max size is (z*factorA). In ortho case, max size is just factorB. To have both
  1116. // without branches, we do (z*factorA+factorB) and set one of factors to zero.
  1117. float maxPlaneScale = 0.0f;
  1118. float maxOrthoSize = 0.0f;
  1119. // Getting the camera isn't totally free, so do it once.
  1120. Camera* camera = Camera::getDefaultCamera();
  1121. //if (!camera.GetOrthographic())
  1122. // maxPlaneScale = -camera.CalculateFarPlaneWorldSpaceLength() * renderer.m_Data.maxParticleSize / camera.GetFar();
  1123. //else
  1124. // maxOrthoSize = camera.CalculateFarPlaneWorldSpaceLength() * renderer.m_Data.maxParticleSize;
  1125. //maxOrthoSize = camera->getFarPlane() * renderer.m_Data.maxParticleSize;
  1126. if (true){
  1127. Size fSize = Director::getInstance()->getOpenGLView()->getFrameSize();
  1128. float len = Vec2(fSize.width, fSize.height).getLength();
  1129. maxPlaneScale = - len * renderer.m_Data.maxParticleSize / camera->getFarPlane();
  1130. //maxPlaneScale = -camera.CalculateFarPlaneWorldSpaceLength() * renderer.m_Data.maxParticleSize / camera.GetFar();
  1131. //maxPlaneScale =
  1132. }
  1133. else{
  1134. //maxOrthoSize = camera.CalculateFarPlaneWorldSpaceLength() * renderer.m_Data.maxParticleSize;
  1135. Size fSize = Director::getInstance()->getOpenGLView()->getFrameSize();
  1136. float len = Vec2(fSize.width, fSize.height).getLength();
  1137. maxOrthoSize = len * renderer.m_Data.maxParticleSize;
  1138. }
  1139. int numMeshes = 0;
  1140. for(int i = 0; i < ParticleSystemRendererData::kMaxNumParticleMeshes; i++)
  1141. if(renderer.m_Data.cachedMesh[i])
  1142. numMeshes++;
  1143. ParticleSystemGeomConstInputData constData;
  1144. constData.m_ViewMatrix = viewMatrix;
  1145. //constData.m_CameraVelocity = viewMatrix.MultiplyVector3(camera.GetVelocity ());
  1146. constData.m_CameraVelocity = viewMatrix.MultiplyVector3(Vec3::ZERO);
  1147. //TODO
  1148. //constData.m_Renderer = (Object*)&renderer;
  1149. //for(int i = 0; i < numMeshes; i++)
  1150. //{
  1151. // constData.m_MeshIndexBuffer[i] = renderer.m_CachedIndexBuffer[i].begin();
  1152. // constData.m_MeshIndexCount[i] = renderer.m_CachedIndexBuffer[i].size();
  1153. // AssertBreak((constData.m_MeshIndexCount[i] % 3) == 0);
  1154. //}
  1155. system.GetNumTiles(constData.m_NumTilesX, constData.m_NumTilesY);
  1156. constData.maxPlaneScale = maxPlaneScale;
  1157. constData.maxOrthoSize = maxOrthoSize;
  1158. constData.numUVFrame = constData.m_NumTilesX * constData.m_NumTilesY;
  1159. constData.animUScale = 1.0f / (float)constData.m_NumTilesX;
  1160. constData.animVScale = 1.0f / (float)constData.m_NumTilesY;
  1161. constData.xSpan = Vector3f(-1.0f,0.0f,0.0f);
  1162. constData.ySpan = Vector3f(0.0f,0.0f,1.0f);
  1163. if (renderer.m_Data.renderMode == kSRMBillboardFixedVertical)
  1164. {
  1165. constData.ySpan = Vector3f(0.0f,1.0f,0.0f);
  1166. const Vector3f zSpan = viewMatrix.MultiplyVector3 (Vector3f::UNIT_Z);// (RotateVectorByQuat (cameraRotation, Vector3f(0.0f,0.0f,1.0f));
  1167. constData.xSpan = NormalizeSafe (Cross (constData.ySpan, zSpan));
  1168. }
  1169. constData.xSpan = viewMatrix.MultiplyVector3(constData.xSpan);
  1170. constData.ySpan = viewMatrix.MultiplyVector3(constData.ySpan);
  1171. constData.usesSheetIndex = psTemp.sheetIndex != NULL;
  1172. constData.uvModuleMode = system.getUVModuleMode();
  1173. constData.isSpriteFrame = system._isSpriteFrame;
  1174. constData.vertexInfo = &system._vertexInfo;
  1175. const float bentNormalAngle = renderer.m_Data.normalDirection * 90.0f * kDeg2Rad;
  1176. const float scale = (renderer.m_Data.renderMode == kSRMBillboard) ? 0.707106781f : 1.0f;
  1177. Matrix4x4f viewToWorldMatrix;
  1178. Matrix4x4f::Invert_General3D(viewMatrix, viewToWorldMatrix);
  1179. Matrix4x4f worldViewMatrix;
  1180. //MultiplyMatrices4x4(&viewMatrix, &worldMatrix, &worldViewMatrix);
  1181. Matrix4x4f::multiply(viewMatrix, worldMatrix, &worldViewMatrix);
  1182. Vector3f billboardNormal = Vector3f::UNIT_Z;
  1183. if((renderer.m_Data.renderMode == kSRMBillboardFixedHorizontal) || (renderer.m_Data.renderMode == kSRMBillboardFixedVertical))
  1184. billboardNormal = viewMatrix.MultiplyVector3 (NormalizeSafe (Cross (constData.xSpan, constData.ySpan)));
  1185. constData.bentNormalVector = viewToWorldMatrix.MultiplyVector3(Sin(bentNormalAngle) * billboardNormal);
  1186. constData.bentNormalFactor = Cos(bentNormalAngle) * scale;
  1187. switch (system.getScalingMode()) {
  1188. case kParticleSystemScalingModeHierarchy:
  1189. transform.decompose(&constData.globalScale, nullptr, nullptr);
  1190. break;
  1191. case kParticleSystemScalingModeLocal:
  1192. system.getNodeToParentTransform().decompose(&constData.globalScale, nullptr, nullptr);
  1193. break;
  1194. case kParticleSystemScalingModeShape:
  1195. constData.globalScale.set(1, 1, 1);
  1196. break;
  1197. }
  1198. if (renderer.m_Data.renderMode == kSRMMesh){
  1199. //DrawMeshParticles (constData, renderer.m_Data, worldMatrix, *ps, psTemp);
  1200. }else{
  1201. DrawParticles(constData, renderer.m_Data, worldViewMatrix, viewToWorldMatrix, *ps, psTemp, vbPtr);
  1202. //const size_t particleCount = ps->array_size();
  1203. //DrawParticlesInternal(constData, renderer.m_Data, worldViewMatrix, viewToWorldMatrix, *ps, psTemp, vbPtr, 0, particleCount, renderer.m_Data.renderMode);
  1204. }
  1205. FREE_TEMP_MANUAL(psTemp.color);
  1206. FREE_TEMP_MANUAL(psTemp.size);
  1207. FREE_TEMP_MANUAL(psTemp.particleSysytemWorldPos);
  1208. if(psTemp.sheetIndex)
  1209. FREE_TEMP_MANUAL(psTemp.sheetIndex);
  1210. if(combineBuffer)
  1211. FREE_TEMP_MANUAL(combineBuffer);
  1212. }
  1213. template<class TransferFunction>
  1214. void ParticleSystemRenderer::Transfer (TransferFunction& transfer)
  1215. {
  1216. // Super::Transfer (transfer);
  1217. transfer.Transfer (m_Data.scale, "m_Scale");
  1218. transfer.Transfer (m_Data.renderMode, "m_RenderMode");
  1219. transfer.Transfer (m_Data.maxParticleSize, "m_MaxParticleSize");
  1220. transfer.Transfer (m_Data.cameraVelocityScale, "m_CameraVelocityScale");
  1221. transfer.Transfer (m_Data.velocityScale, "m_VelocityScale");
  1222. transfer.Transfer (m_Data.lengthScale, "m_LengthScale");
  1223. transfer.Transfer (m_Data.sortingFudge, "m_SortingFudge");
  1224. transfer.Transfer (m_Data.normalDirection, "m_NormalDirection");
  1225. transfer.Transfer (m_Data.sortMode, "m_SortMode");
  1226. //TODO: Mesh
  1227. //transfer.Transfer (m_Mesh[0], "m_Mesh");
  1228. //transfer.Transfer (m_Mesh[1], "m_Mesh1");
  1229. //transfer.Transfer (m_Mesh[2], "m_Mesh2");
  1230. //transfer.Transfer (m_Mesh[3], "m_Mesh3");
  1231. }
  1232. INSTANTIATE_TEMPLATE_TRANSFER(ParticleSystemRenderer)
  1233. NS_RRP_END