particleEmitter.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/fx/particleEmitter.h"
  28. #include "scene/sceneManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "console/consoleTypes.h"
  31. #include "console/typeValidators.h"
  32. #include "core/stream/bitStream.h"
  33. #include "core/strings/stringUnit.h"
  34. #include "math/mRandom.h"
  35. #include "gfx/gfxDevice.h"
  36. #include "gfx/primBuilder.h"
  37. #include "gfx/gfxStringEnumTranslate.h"
  38. #include "renderInstance/renderPassManager.h"
  39. #include "T3D/gameBase/gameProcess.h"
  40. #include "lighting/lightInfo.h"
  41. #include "console/engineAPI.h"
  42. #if defined(AFX_CAP_PARTICLE_POOLS)
  43. #include "afx/util/afxParticlePool.h"
  44. #endif
  45. Point3F ParticleEmitter::mWindVelocity( 0.0, 0.0, 0.0 );
  46. const F32 ParticleEmitter::AgedSpinToRadians = (1.0f/1000.0f) * (1.0f/360.0f) * M_PI_F * 2.0f;
  47. IMPLEMENT_CO_DATABLOCK_V1(ParticleEmitterData);
  48. IMPLEMENT_CONOBJECT(ParticleEmitter);
  49. ConsoleDocClass( ParticleEmitter,
  50. "@brief This object is responsible for spawning particles.\n\n"
  51. "@note This class is not normally instantiated directly - to place a simple "
  52. "particle emitting object in the scene, use a ParticleEmitterNode instead.\n\n"
  53. "This class is the main interface for creating particles - though it is "
  54. "usually only accessed from within another object like ParticleEmitterNode "
  55. "or WheeledVehicle. If using this object class (via C++) directly, be aware "
  56. "that it does <b>not</b> track changes in source axis or velocity over the "
  57. "course of a single update, so emitParticles should be called at a fairly "
  58. "fine grain. The emitter will potentially track the last particle to be "
  59. "created into the next call to this function in order to create a uniformly "
  60. "random time distribution of the particles.\n\n"
  61. "If the object to which the emitter is attached is in motion, it should try "
  62. "to ensure that for call (n+1) to this function, start is equal to the end "
  63. "from call (n). This will ensure a uniform spatial distribution.\n\n"
  64. "@ingroup FX\n"
  65. "@see ParticleEmitterData\n"
  66. "@see ParticleEmitterNode\n"
  67. );
  68. ConsoleDocClass( ParticleEmitterData,
  69. "@brief Defines particle emission properties such as ejection angle, period "
  70. "and velocity for a ParticleEmitter.\n\n"
  71. "@tsexample\n"
  72. "datablock ParticleEmitterData( GrenadeExpDustEmitter )\n"
  73. "{\n"
  74. " ejectionPeriodMS = 1;\n"
  75. " periodVarianceMS = 0;\n"
  76. " ejectionVelocity = 15;\n"
  77. " velocityVariance = 0.0;\n"
  78. " ejectionOffset = 0.0;\n"
  79. " thetaMin = 85;\n"
  80. " thetaMax = 85;\n"
  81. " thetaVariance = 0;\n"
  82. " phiReferenceVel = 0;\n"
  83. " phiVariance = 360;\n"
  84. " overrideAdvance = false;\n"
  85. " lifetimeMS = 200;\n"
  86. " particles = \"GrenadeExpDust\";\n"
  87. "};\n"
  88. "@endtsexample\n\n"
  89. "@ingroup FX\n"
  90. "@see ParticleEmitter\n"
  91. "@see ParticleData\n"
  92. "@see ParticleEmitterNode\n"
  93. );
  94. static const F32 sgDefaultEjectionOffset = 0.f;
  95. static const F32 sgDefaultPhiReferenceVel = 0.f;
  96. static const F32 sgDefaultPhiVariance = 360.f;
  97. //-----------------------------------------------------------------------------
  98. // ParticleEmitterData
  99. //-----------------------------------------------------------------------------
  100. ParticleEmitterData::ParticleEmitterData()
  101. {
  102. VECTOR_SET_ASSOCIATION(particleDataBlocks);
  103. VECTOR_SET_ASSOCIATION(dataBlockIds);
  104. ejectionPeriodMS = 100; // 10 Particles Per second
  105. periodVarianceMS = 0; // exactly
  106. ejectionVelocity = 2.0f; // From 1.0 - 3.0 meters per sec
  107. velocityVariance = 1.0f;
  108. ejectionOffset = sgDefaultEjectionOffset; // ejection from the emitter point
  109. ejectionOffsetVariance = 0.0f;
  110. thetaMin = 0.0f; // All heights
  111. thetaMax = 90.0f;
  112. thetaVariance = 0.0f;
  113. phiReferenceVel = sgDefaultPhiReferenceVel; // All directions
  114. phiVariance = sgDefaultPhiVariance;
  115. softnessDistance = 1.0f;
  116. ambientFactor = 0.0f;
  117. lifetimeMS = 0;
  118. lifetimeVarianceMS = 0;
  119. overrideAdvance = true;
  120. orientParticles = false;
  121. orientOnVelocity = true;
  122. ribbonParticles = false;
  123. useEmitterSizes = false;
  124. useEmitterColors = false;
  125. particleString = NULL;
  126. partListInitSize = 0;
  127. // These members added for support of user defined blend factors
  128. // and optional particle sorting.
  129. blendStyle = ParticleRenderInst::BlendUndefined;
  130. sortParticles = false;
  131. renderReflection = true;
  132. glow = false;
  133. reverseOrder = false;
  134. textureName = 0;
  135. textureHandle = 0;
  136. highResOnly = true;
  137. alignParticles = false;
  138. alignDirection = Point3F(0.0f, 1.0f, 0.0f);
  139. ejectionInvert = false;
  140. fade_color = false;
  141. fade_alpha = false;
  142. fade_size = false;
  143. parts_per_eject = 1;
  144. use_emitter_xfm = false;
  145. #if defined(AFX_CAP_PARTICLE_POOLS)
  146. pool_datablock = 0;
  147. pool_index = 0;
  148. pool_depth_fade = false;
  149. pool_radial_fade = false;
  150. do_pool_id_convert = false;
  151. #endif
  152. }
  153. // Enum tables used for fields blendStyle, srcBlendFactor, dstBlendFactor.
  154. // Note that the enums for srcBlendFactor and dstBlendFactor are consistent
  155. // with the blending enums used in Torque Game Builder.
  156. typedef ParticleRenderInst::BlendStyle ParticleBlendStyle;
  157. DefineEnumType( ParticleBlendStyle );
  158. ImplementEnumType( ParticleBlendStyle,
  159. "The type of visual blending style to apply to the particles.\n"
  160. "@ingroup FX\n\n")
  161. { ParticleRenderInst::BlendNormal, "NORMAL", "No blending style.\n" },
  162. { ParticleRenderInst::BlendAdditive, "ADDITIVE", "Adds the color of the pixel to the frame buffer with full alpha for each pixel.\n" },
  163. { ParticleRenderInst::BlendSubtractive, "SUBTRACTIVE", "Subtractive Blending. Reverses the color model, causing dark colors to have a stronger visual effect.\n" },
  164. { ParticleRenderInst::BlendPremultAlpha, "PREMULTALPHA", "Color blends with the colors of the imagemap rather than the alpha.\n" },
  165. EndImplementEnumType;
  166. IRangeValidator ejectPeriodIValidator(1, 2047);
  167. IRangeValidator periodVarianceIValidator(0, 2047);
  168. FRangeValidator ejectionFValidator(0.f, 655.35f);
  169. FRangeValidator velVarianceFValidator(0.f, 163.83f);
  170. FRangeValidator thetaFValidator(0.f, 180.f);
  171. FRangeValidator phiFValidator(0.f, 360.f);
  172. //-----------------------------------------------------------------------------
  173. // initPersistFields
  174. //-----------------------------------------------------------------------------
  175. void ParticleEmitterData::initPersistFields()
  176. {
  177. docsURL;
  178. addGroup( "ParticleEmitterData" );
  179. addFieldV("ejectionPeriodMS", TYPEID< S32 >(), Offset(ejectionPeriodMS, ParticleEmitterData), &ejectPeriodIValidator,
  180. "Time (in milliseconds) between each particle ejection." );
  181. addFieldV("periodVarianceMS", TYPEID< S32 >(), Offset(periodVarianceMS, ParticleEmitterData), &periodVarianceIValidator,
  182. "Variance in ejection period, from 1 - ejectionPeriodMS." );
  183. addFieldV( "ejectionVelocity", TYPEID< F32 >(), Offset(ejectionVelocity, ParticleEmitterData), &ejectionFValidator,
  184. "Particle ejection velocity." );
  185. addFieldV( "velocityVariance", TYPEID< F32 >(), Offset(velocityVariance, ParticleEmitterData), &velVarianceFValidator,
  186. "Variance for ejection velocity, from 0 - ejectionVelocity." );
  187. addFieldV( "ejectionOffset", TYPEID< F32 >(), Offset(ejectionOffset, ParticleEmitterData), &ejectionFValidator,
  188. "Distance along ejection Z axis from which to eject particles." );
  189. addFieldV( "ejectionOffsetVariance", TYPEID< F32 >(), Offset(ejectionOffsetVariance, ParticleEmitterData), &ejectionFValidator,
  190. "Distance Padding along ejection Z axis from which to eject particles." );
  191. addFieldV( "thetaMin", TYPEID< F32 >(), Offset(thetaMin, ParticleEmitterData), &thetaFValidator,
  192. "Minimum angle, from the horizontal plane, to eject from." );
  193. addFieldV( "thetaMax", TYPEID< F32 >(), Offset(thetaMax, ParticleEmitterData), &thetaFValidator,
  194. "Maximum angle, from the horizontal plane, to eject particles from." );
  195. addFieldV( "thetaVariance", TYPEID< F32 >(), Offset(thetaVariance, ParticleEmitterData), &thetaFValidator,
  196. "Angle variance from the previous particle, from 0 - 180." );
  197. addFieldV( "phiReferenceVel", TYPEID< F32 >(), Offset(phiReferenceVel, ParticleEmitterData), &phiFValidator,
  198. "Reference angle, from the vertical plane, to eject particles from." );
  199. addFieldV( "phiVariance", TYPEID< F32 >(), Offset(phiVariance, ParticleEmitterData), &phiFValidator,
  200. "Variance from the reference angle, from 0 - 360." );
  201. addField( "softnessDistance", TYPEID< F32 >(), Offset(softnessDistance, ParticleEmitterData),
  202. "For soft particles, the distance (in meters) where particles will be "
  203. "faded based on the difference in depth between the particle and the "
  204. "scene geometry." );
  205. addField( "ambientFactor", TYPEID< F32 >(), Offset(ambientFactor, ParticleEmitterData),
  206. "Used to generate the final particle color by controlling interpolation "
  207. "between the particle color and the particle color multiplied by the "
  208. "ambient light color." );
  209. addField( "overrideAdvance", TYPEID< bool >(), Offset(overrideAdvance, ParticleEmitterData),
  210. "If false, particles emitted in the same frame have their positions "
  211. "adjusted. If true, adjustment is skipped and particles will clump "
  212. "together." );
  213. addField( "orientParticles", TYPEID< bool >(), Offset(orientParticles, ParticleEmitterData),
  214. "If true, Particles will always face the camera." );
  215. addField( "orientOnVelocity", TYPEID< bool >(), Offset(orientOnVelocity, ParticleEmitterData),
  216. "If true, particles will be oriented to face in the direction they are moving." );
  217. addField( "ribbonParticles", TYPEID< bool >(), Offset(ribbonParticles, ParticleEmitterData),
  218. "If true, particles are rendered as a continous ribbon." );
  219. addField( "particles", TYPEID< StringTableEntry >(), Offset(particleString, ParticleEmitterData),
  220. "@brief List of space or TAB delimited ParticleData datablock names.\n\n"
  221. "A random one of these datablocks is selected each time a particle is "
  222. "emitted." );
  223. addField( "lifetimeMS", TYPEID< S32 >(), Offset(lifetimeMS, ParticleEmitterData),
  224. "Lifetime of emitted particles (in milliseconds)." );
  225. addField("lifetimeVarianceMS", TYPEID< S32 >(), Offset(lifetimeVarianceMS, ParticleEmitterData),
  226. "Variance in particle lifetime from 0 - lifetimeMS." );
  227. addField( "useEmitterSizes", TYPEID< bool >(), Offset(useEmitterSizes, ParticleEmitterData),
  228. "@brief If true, use emitter specified sizes instead of datablock sizes.\n"
  229. "Useful for Debris particle emitters that control the particle size." );
  230. addField( "useEmitterColors", TYPEID< bool >(), Offset(useEmitterColors, ParticleEmitterData),
  231. "@brief If true, use emitter specified colors instead of datablock colors.\n\n"
  232. "Useful for ShapeBase dust and WheeledVehicle wheel particle emitters that use "
  233. "the current material to control particle color." );
  234. /// These fields added for support of user defined blend factors and optional particle sorting.
  235. //@{
  236. addField( "blendStyle", TYPEID< ParticleRenderInst::BlendStyle >(), Offset(blendStyle, ParticleEmitterData),
  237. "String value that controls how emitted particles blend with the scene." );
  238. addField( "sortParticles", TYPEID< bool >(), Offset(sortParticles, ParticleEmitterData),
  239. "If true, particles are sorted furthest to nearest.");
  240. addField( "reverseOrder", TYPEID< bool >(), Offset(reverseOrder, ParticleEmitterData),
  241. "@brief If true, reverses the normal draw order of particles.\n\n"
  242. "Particles are normally drawn from newest to oldest, or in Z order "
  243. "(furthest first) if sortParticles is true. Setting this field to "
  244. "true will reverse that order: oldest first, or nearest first if "
  245. "sortParticles is true." );
  246. addField( "textureName", TYPEID< StringTableEntry >(), Offset(textureName, ParticleEmitterData),
  247. "Optional texture to override ParticleData::textureName." );
  248. addField( "alignParticles", TYPEID< bool >(), Offset(alignParticles, ParticleEmitterData),
  249. "If true, particles always face along the axis defined by alignDirection." );
  250. addProtectedField( "alignDirection", TYPEID< Point3F>(), Offset(alignDirection, ParticleEmitterData), &ParticleEmitterData::_setAlignDirection, &defaultProtectedGetFn,
  251. "The direction aligned particles should face, only valid if alignParticles is true." );
  252. addField( "highResOnly", TYPEID< bool >(), Offset(highResOnly, ParticleEmitterData),
  253. "This particle system should not use the mixed-resolution renderer. "
  254. "If your particle system has large amounts of overdraw, consider "
  255. "disabling this option." );
  256. addField( "renderReflection", TYPEID< bool >(), Offset(renderReflection, ParticleEmitterData),
  257. "Controls whether particles are rendered onto reflective surfaces like water." );
  258. addField("glow", TYPEID< bool >(), Offset(glow, ParticleEmitterData),
  259. "If true, the particles are rendered to the glow buffer as well.");
  260. //@}
  261. endGroup( "ParticleEmitterData" );
  262. addGroup("AFX");
  263. addField("ejectionInvert", TypeBool, Offset(ejectionInvert, ParticleEmitterData));
  264. addField("fadeColor", TypeBool, Offset(fade_color, ParticleEmitterData));
  265. addField("fadeAlpha", TypeBool, Offset(fade_alpha, ParticleEmitterData));
  266. addField("fadeSize", TypeBool, Offset(fade_size, ParticleEmitterData));
  267. // useEmitterTransform currently does not work in TGEA or T3D
  268. addField("useEmitterTransform", TypeBool, Offset(use_emitter_xfm, ParticleEmitterData));
  269. endGroup("AFX");
  270. #if defined(AFX_CAP_PARTICLE_POOLS)
  271. addGroup("AFX Pooled Particles");
  272. addField("poolData", TYPEID<afxParticlePoolData>(), Offset(pool_datablock, ParticleEmitterData));
  273. addField("poolIndex", TypeS32, Offset(pool_index, ParticleEmitterData));
  274. addField("poolDepthFade", TypeBool, Offset(pool_depth_fade, ParticleEmitterData));
  275. addField("poolRadialFade", TypeBool, Offset(pool_radial_fade, ParticleEmitterData));
  276. endGroup("AFX Pooled Particles");
  277. #endif
  278. // disallow some field substitutions
  279. disableFieldSubstitutions("particles");
  280. onlyKeepClearSubstitutions("poolData"); // subs resolving to "~~", or "~0" are OK
  281. Parent::initPersistFields();
  282. }
  283. bool ParticleEmitterData::_setAlignDirection( void *object, const char *index, const char *data )
  284. {
  285. ParticleEmitterData *p = static_cast<ParticleEmitterData*>( object );
  286. Con::setData( TypePoint3F, &p->alignDirection, 0, 1, &data );
  287. p->alignDirection.normalizeSafe();
  288. // we already set the field
  289. return false;
  290. }
  291. //-----------------------------------------------------------------------------
  292. // packData
  293. //-----------------------------------------------------------------------------
  294. void ParticleEmitterData::packData(BitStream* stream)
  295. {
  296. Parent::packData(stream);
  297. stream->writeInt(ejectionPeriodMS, 11); // must match limit on valid range in ParticleEmitterData::initPersistFields
  298. stream->writeInt(periodVarianceMS, 11);
  299. stream->writeInt((S32)(ejectionVelocity * 100), 16);
  300. stream->writeInt((S32)(velocityVariance * 100), 14);
  301. if( stream->writeFlag( ejectionOffset != sgDefaultEjectionOffset ) )
  302. stream->writeInt((S32)(ejectionOffset * 100), 16);
  303. if( stream->writeFlag( ejectionOffsetVariance != 0.0f ) )
  304. stream->writeInt((S32)(ejectionOffsetVariance * 100), 16);
  305. stream->writeRangedU32((U32)thetaMin, 0, 180);
  306. stream->writeRangedU32((U32)thetaMax, 0, 180);
  307. stream->writeRangedU32((U32)thetaVariance, 0, 180);
  308. if( stream->writeFlag( phiReferenceVel != sgDefaultPhiReferenceVel ) )
  309. stream->writeRangedU32((U32)phiReferenceVel, 0, 360);
  310. if( stream->writeFlag( phiVariance != sgDefaultPhiVariance ) )
  311. stream->writeRangedU32((U32)phiVariance, 0, 360);
  312. stream->write( softnessDistance );
  313. stream->write( ambientFactor );
  314. stream->writeFlag(overrideAdvance);
  315. stream->writeFlag(orientParticles);
  316. stream->writeFlag(orientOnVelocity);
  317. stream->writeFlag(ribbonParticles);
  318. stream->write( lifetimeMS );
  319. stream->write( lifetimeVarianceMS );
  320. stream->writeFlag(useEmitterSizes);
  321. stream->writeFlag(useEmitterColors);
  322. stream->write(dataBlockIds.size());
  323. for (U32 i = 0; i < dataBlockIds.size(); i++)
  324. stream->write(dataBlockIds[i]);
  325. stream->writeFlag(sortParticles);
  326. stream->writeFlag(reverseOrder);
  327. if (stream->writeFlag(textureName != 0))
  328. stream->writeString(textureName);
  329. if (stream->writeFlag(alignParticles))
  330. {
  331. stream->write(alignDirection.x);
  332. stream->write(alignDirection.y);
  333. stream->write(alignDirection.z);
  334. }
  335. stream->writeFlag(highResOnly);
  336. stream->writeFlag(renderReflection);
  337. stream->writeFlag(glow);
  338. stream->writeInt( blendStyle, 4 );
  339. stream->writeFlag(ejectionInvert);
  340. stream->writeFlag(fade_color);
  341. stream->writeFlag(fade_alpha);
  342. stream->writeFlag(fade_size);
  343. stream->writeFlag(use_emitter_xfm);
  344. #if defined(AFX_CAP_PARTICLE_POOLS)
  345. if (stream->writeFlag(pool_datablock))
  346. {
  347. stream->writeRangedU32(mPacked ? SimObjectId((uintptr_t)pool_datablock) : pool_datablock->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
  348. stream->write(pool_index);
  349. stream->writeFlag(pool_depth_fade);
  350. stream->writeFlag(pool_radial_fade);
  351. }
  352. #endif
  353. }
  354. //-----------------------------------------------------------------------------
  355. // unpackData
  356. //-----------------------------------------------------------------------------
  357. void ParticleEmitterData::unpackData(BitStream* stream)
  358. {
  359. Parent::unpackData(stream);
  360. ejectionPeriodMS = stream->readInt(11);
  361. periodVarianceMS = stream->readInt(11);
  362. ejectionVelocity = stream->readInt(16) / 100.0f;
  363. velocityVariance = stream->readInt(14) / 100.0f;
  364. if( stream->readFlag() )
  365. ejectionOffset = stream->readInt(16) / 100.0f;
  366. else
  367. ejectionOffset = sgDefaultEjectionOffset;
  368. if( stream->readFlag() )
  369. ejectionOffsetVariance = stream->readInt(16) / 100.0f;
  370. else
  371. ejectionOffsetVariance = 0.0f;
  372. thetaMin = (F32)stream->readRangedU32(0, 180);
  373. thetaMax = (F32)stream->readRangedU32(0, 180);
  374. thetaVariance = (F32)stream->readRangedU32(0, 180);
  375. if( stream->readFlag() )
  376. phiReferenceVel = (F32)stream->readRangedU32(0, 360);
  377. else
  378. phiReferenceVel = sgDefaultPhiReferenceVel;
  379. if( stream->readFlag() )
  380. phiVariance = (F32)stream->readRangedU32(0, 360);
  381. else
  382. phiVariance = sgDefaultPhiVariance;
  383. stream->read( &softnessDistance );
  384. stream->read( &ambientFactor );
  385. overrideAdvance = stream->readFlag();
  386. orientParticles = stream->readFlag();
  387. orientOnVelocity = stream->readFlag();
  388. ribbonParticles = stream->readFlag();
  389. stream->read( &lifetimeMS );
  390. stream->read( &lifetimeVarianceMS );
  391. useEmitterSizes = stream->readFlag();
  392. useEmitterColors = stream->readFlag();
  393. U32 size; stream->read(&size);
  394. dataBlockIds.setSize(size);
  395. for (U32 i = 0; i < dataBlockIds.size(); i++)
  396. stream->read(&dataBlockIds[i]);
  397. sortParticles = stream->readFlag();
  398. reverseOrder = stream->readFlag();
  399. textureName = (stream->readFlag()) ? stream->readSTString() : 0;
  400. alignParticles = stream->readFlag();
  401. if (alignParticles)
  402. {
  403. stream->read(&alignDirection.x);
  404. stream->read(&alignDirection.y);
  405. stream->read(&alignDirection.z);
  406. }
  407. highResOnly = stream->readFlag();
  408. renderReflection = stream->readFlag();
  409. glow = stream->readFlag();
  410. blendStyle = stream->readInt( 4 );
  411. ejectionInvert = stream->readFlag();
  412. fade_color = stream->readFlag();
  413. fade_alpha = stream->readFlag();
  414. fade_size = stream->readFlag();
  415. use_emitter_xfm = stream->readFlag();
  416. #if defined(AFX_CAP_PARTICLE_POOLS)
  417. if (stream->readFlag())
  418. {
  419. pool_datablock = (afxParticlePoolData*)(uintptr_t)stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  420. stream->read(&pool_index);
  421. pool_depth_fade = stream->readFlag();
  422. pool_radial_fade = stream->readFlag();
  423. do_pool_id_convert = true;
  424. }
  425. #endif
  426. }
  427. //-----------------------------------------------------------------------------
  428. // onAdd
  429. //-----------------------------------------------------------------------------
  430. bool ParticleEmitterData::onAdd()
  431. {
  432. if( Parent::onAdd() == false )
  433. return false;
  434. // if (overrideAdvance == true) {
  435. // Con::errorf(ConsoleLogEntry::General, "ParticleEmitterData: Not going to work. Fix it!");
  436. // return false;
  437. // }
  438. // Validate the parameters...
  439. //
  440. if( ejectionPeriodMS < 1 )
  441. {
  442. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) period < 1 ms", getName());
  443. ejectionPeriodMS = 1;
  444. }
  445. if( periodVarianceMS >= ejectionPeriodMS )
  446. {
  447. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) periodVariance >= period", getName());
  448. periodVarianceMS = ejectionPeriodMS - 1;
  449. }
  450. if( ejectionVelocity < 0.0f )
  451. {
  452. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionVelocity < 0.0f", getName());
  453. ejectionVelocity = 0.0f;
  454. }
  455. if( velocityVariance < 0.0f )
  456. {
  457. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) velocityVariance < 0.0f", getName());
  458. velocityVariance = 0.0f;
  459. }
  460. if( velocityVariance > ejectionVelocity )
  461. {
  462. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) velocityVariance > ejectionVelocity", getName());
  463. velocityVariance = ejectionVelocity;
  464. }
  465. if( ejectionOffset < 0.0f )
  466. {
  467. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionOffset < 0", getName());
  468. ejectionOffset = 0.0f;
  469. }
  470. if( ejectionOffsetVariance < 0.0f )
  471. {
  472. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionOffset < 0", getName());
  473. ejectionOffsetVariance = 0.0f;
  474. }
  475. if( thetaMin < 0.0f )
  476. {
  477. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMin < 0.0", getName());
  478. thetaMin = 0.0f;
  479. }
  480. if( thetaMax > 180.0f )
  481. {
  482. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMax > 180.0", getName());
  483. thetaMax = 180.0f;
  484. }
  485. if( thetaMin > thetaMax )
  486. {
  487. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMin > thetaMax", getName());
  488. thetaMin = thetaMax;
  489. }
  490. if( thetaVariance > 180.0f )
  491. {
  492. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaVariance > 180.0", getName());
  493. thetaVariance = 180.0f;
  494. }
  495. if( thetaVariance < 0.0f )
  496. {
  497. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaVariance < 0.0", getName());
  498. thetaVariance = 0.0f;
  499. }
  500. if( phiVariance < 0.0f || phiVariance > 360.0f )
  501. {
  502. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid phiVariance", getName());
  503. phiVariance = phiVariance < 0.0f ? 0.0f : 360.0f;
  504. }
  505. if( thetaVariance < 0.0f || thetaVariance > 180.0f )
  506. {
  507. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid thetaVariance", getName());
  508. thetaVariance = thetaVariance < 0.0f ? 0.0f : 180.0f;
  509. }
  510. if ( softnessDistance < 0.0f )
  511. {
  512. Con::warnf( ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid softnessDistance", getName() );
  513. softnessDistance = 0.0f;
  514. }
  515. if (particleString == NULL && dataBlockIds.size() == 0)
  516. {
  517. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) no particleString, invalid datablock", getName());
  518. return false;
  519. }
  520. if (particleString && particleString[0] == '\0')
  521. {
  522. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) no particleString, invalid datablock", getName());
  523. return false;
  524. }
  525. if (particleString && dStrlen(particleString) > 255)
  526. {
  527. Con::errorf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particle string too long [> 255 chars]", getName());
  528. return false;
  529. }
  530. if( lifetimeMS < 0 )
  531. {
  532. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) lifetimeMS < 0.0f", getName());
  533. lifetimeMS = 0;
  534. }
  535. if( lifetimeVarianceMS > lifetimeMS )
  536. {
  537. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) lifetimeVarianceMS >= lifetimeMS", getName());
  538. lifetimeVarianceMS = lifetimeMS;
  539. }
  540. // load the particle datablocks...
  541. //
  542. if( particleString != NULL )
  543. {
  544. // particleString is once again a list of particle datablocks so it
  545. // must be parsed to extract the particle references.
  546. // First we parse particleString into a list of particle name tokens
  547. Vector<char*> dataBlocks(__FILE__, __LINE__);
  548. dsize_t tokLen = dStrlen(particleString) + 1;
  549. char* tokCopy = new char[tokLen];
  550. dStrcpy(tokCopy, particleString, tokLen);
  551. char* currTok = dStrtok(tokCopy, " \t");
  552. while (currTok != NULL)
  553. {
  554. dataBlocks.push_back(currTok);
  555. currTok = dStrtok(NULL, " \t");
  556. }
  557. if (dataBlocks.size() == 0)
  558. {
  559. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid particles string. No datablocks found", getName());
  560. delete [] tokCopy;
  561. return false;
  562. }
  563. // Now we convert the particle name tokens into particle datablocks and IDs
  564. particleDataBlocks.clear();
  565. dataBlockIds.clear();
  566. for (U32 i = 0; i < dataBlocks.size(); i++)
  567. {
  568. ParticleData* pData = NULL;
  569. if (Sim::findObject(dataBlocks[i], pData) == false)
  570. {
  571. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dataBlocks[i]);
  572. }
  573. else
  574. {
  575. particleDataBlocks.push_back(pData);
  576. dataBlockIds.push_back(pData->getId());
  577. }
  578. }
  579. // cleanup
  580. delete [] tokCopy;
  581. // check that we actually found some particle datablocks
  582. if (particleDataBlocks.size() == 0)
  583. {
  584. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName());
  585. return false;
  586. }
  587. }
  588. return true;
  589. }
  590. //-----------------------------------------------------------------------------
  591. // preload
  592. //-----------------------------------------------------------------------------
  593. bool ParticleEmitterData::preload(bool server, String &errorStr)
  594. {
  595. if( Parent::preload(server, errorStr) == false )
  596. return false;
  597. particleDataBlocks.clear();
  598. for (U32 i = 0; i < dataBlockIds.size(); i++)
  599. {
  600. ParticleData* pData = NULL;
  601. if (Sim::findObject(dataBlockIds[i], pData) == false)
  602. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %d", getName(), dataBlockIds[i]);
  603. else
  604. particleDataBlocks.push_back(pData);
  605. }
  606. if (!server)
  607. {
  608. #if defined(AFX_CAP_PARTICLE_POOLS)
  609. if (do_pool_id_convert)
  610. {
  611. SimObjectId db_id = (SimObjectId)(uintptr_t)pool_datablock;
  612. if (db_id != 0)
  613. {
  614. // try to convert id to pointer
  615. if (!Sim::findObject(db_id, pool_datablock))
  616. {
  617. Con::errorf("ParticleEmitterData::reload() -- bad datablockId: 0x%x (poolData)", db_id);
  618. }
  619. }
  620. do_pool_id_convert = false;
  621. }
  622. #endif
  623. // load emitter texture if specified
  624. if (textureName && textureName[0])
  625. {
  626. textureHandle = GFXTexHandle(textureName, &GFXStaticTextureSRGBProfile, avar("%s() - textureHandle (line %d)", __FUNCTION__, __LINE__));
  627. if (!textureHandle)
  628. {
  629. errorStr = String::ToString("Missing particle emitter texture: %s", textureName);
  630. return false;
  631. }
  632. }
  633. // otherwise, check that all particles refer to the same texture
  634. else if (particleDataBlocks.size() > 1)
  635. {
  636. StringTableEntry txr_name = particleDataBlocks[0]->getTexture();
  637. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  638. {
  639. // warn if particle textures are inconsistent
  640. if (particleDataBlocks[i]->getTexture() != txr_name)
  641. {
  642. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particles reference different textures.", getName());
  643. break;
  644. }
  645. }
  646. }
  647. }
  648. // if blend-style is undefined check legacy useInvAlpha settings
  649. if (blendStyle == ParticleRenderInst::BlendUndefined && particleDataBlocks.size() > 0)
  650. {
  651. bool useInvAlpha = particleDataBlocks[0]->useInvAlpha;
  652. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  653. {
  654. // warn if blend-style legacy useInvAlpha settings are inconsistent
  655. if (particleDataBlocks[i]->useInvAlpha != useInvAlpha)
  656. {
  657. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particles have inconsistent useInvAlpha settings.", getName());
  658. break;
  659. }
  660. }
  661. blendStyle = (useInvAlpha) ? ParticleRenderInst::BlendNormal : ParticleRenderInst::BlendAdditive;
  662. }
  663. if( !server )
  664. {
  665. allocPrimBuffer();
  666. }
  667. return true;
  668. }
  669. //-----------------------------------------------------------------------------
  670. // alloc PrimitiveBuffer
  671. // The datablock allocates this static index buffer because it's the same
  672. // for all of the emitters - each particle quad uses the same index ordering
  673. //-----------------------------------------------------------------------------
  674. void ParticleEmitterData::allocPrimBuffer( S32 overrideSize )
  675. {
  676. // calculate particle list size
  677. AssertFatal(particleDataBlocks.size() > 0, "Error, no particles found." );
  678. if (particleDataBlocks.empty()) return;
  679. U32 maxPartLife = particleDataBlocks[0]->lifetimeMS + particleDataBlocks[0]->lifetimeVarianceMS;
  680. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  681. {
  682. U32 mpl = particleDataBlocks[i]->lifetimeMS + particleDataBlocks[i]->lifetimeVarianceMS;
  683. if (mpl > maxPartLife)
  684. maxPartLife = mpl;
  685. }
  686. partListInitSize = maxPartLife / (ejectionPeriodMS - periodVarianceMS);
  687. partListInitSize += 8; // add 8 as "fudge factor" to make sure it doesn't realloc if it goes over by 1
  688. if (parts_per_eject > 1)
  689. partListInitSize *= parts_per_eject;
  690. // if override size is specified, then the emitter overran its buffer and needs a larger allocation
  691. if( overrideSize != -1 )
  692. {
  693. partListInitSize = overrideSize;
  694. }
  695. // create index buffer based on that size
  696. U32 indexListSize = partListInitSize * 6; // 6 indices per particle
  697. U16 *indices = new U16[ indexListSize ];
  698. for( U32 i=0; i<partListInitSize; i++ )
  699. {
  700. // this index ordering should be optimal (hopefully) for the vertex cache
  701. U16 *idx = &indices[i*6];
  702. volatile U32 offset = i * 4; // set to volatile to fix VC6 Release mode compiler bug
  703. idx[0] = 0 + offset;
  704. idx[1] = 1 + offset;
  705. idx[2] = 3 + offset;
  706. idx[3] = 1 + offset;
  707. idx[4] = 3 + offset;
  708. idx[5] = 2 + offset;
  709. }
  710. U16 *ibIndices;
  711. GFXBufferType bufferType = GFXBufferTypeStatic;
  712. primBuff.set( GFX, indexListSize, 0, bufferType );
  713. primBuff.lock( &ibIndices );
  714. dMemcpy( ibIndices, indices, indexListSize * sizeof(U16) );
  715. primBuff.unlock();
  716. delete [] indices;
  717. }
  718. //#define TRACK_PARTICLE_EMITTER_DATA_CLONES
  719. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  720. static int emitter_data_clones = 0;
  721. #endif
  722. ParticleEmitterData::ParticleEmitterData(const ParticleEmitterData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  723. {
  724. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  725. emitter_data_clones++;
  726. if (emitter_data_clones == 1)
  727. Con::errorf("ParticleEmitterData -- Clones are on the loose!");
  728. #endif
  729. ejectionPeriodMS = other.ejectionPeriodMS;
  730. periodVarianceMS = other.periodVarianceMS;
  731. ejectionVelocity = other.ejectionVelocity;
  732. velocityVariance = other.velocityVariance;
  733. ejectionOffset = other.ejectionOffset;
  734. ejectionOffsetVariance = other.ejectionOffsetVariance;
  735. thetaMin = other.thetaMin;
  736. thetaMax = other.thetaMax;
  737. thetaVariance = other.thetaVariance;
  738. phiReferenceVel = other.phiReferenceVel;
  739. phiVariance = other.phiVariance;
  740. softnessDistance = other.softnessDistance;
  741. ambientFactor = other.ambientFactor;
  742. lifetimeMS = other.lifetimeMS;
  743. lifetimeVarianceMS = other.lifetimeVarianceMS;
  744. overrideAdvance = other.overrideAdvance;
  745. orientParticles = other.orientParticles;
  746. orientOnVelocity = other.orientOnVelocity;
  747. ribbonParticles = other.ribbonParticles;
  748. useEmitterSizes = other.useEmitterSizes;
  749. useEmitterColors = other.useEmitterColors;
  750. alignParticles = other.alignParticles;
  751. alignDirection = other.alignDirection;
  752. particleString = other.particleString;
  753. particleDataBlocks = other.particleDataBlocks; // -- derived from particleString
  754. dataBlockIds = other.dataBlockIds; // -- derived from particleString
  755. partListInitSize = other.partListInitSize; // -- approx calc from other fields
  756. primBuff = other.primBuff;
  757. blendStyle = other.blendStyle;
  758. sortParticles = other.sortParticles;
  759. reverseOrder = other.reverseOrder;
  760. textureName = other.textureName;
  761. textureHandle = other.textureHandle; // -- TextureHandle loads using textureName
  762. highResOnly = other.highResOnly;
  763. glow = other.glow;
  764. renderReflection = other.renderReflection;
  765. fade_color = other.fade_color;
  766. fade_size = other.fade_size;
  767. fade_alpha = other.fade_alpha;
  768. ejectionInvert = other.ejectionInvert;
  769. parts_per_eject = other.parts_per_eject; // -- set to 1 (used by subclasses)
  770. use_emitter_xfm = other.use_emitter_xfm;
  771. #if defined(AFX_CAP_PARTICLE_POOLS)
  772. pool_datablock = other.pool_datablock;
  773. pool_index = other.pool_index;
  774. pool_depth_fade = other.pool_depth_fade;
  775. pool_radial_fade = other.pool_radial_fade;
  776. do_pool_id_convert = other.do_pool_id_convert; // -- flags pool id conversion need
  777. #endif
  778. }
  779. ParticleEmitterData::~ParticleEmitterData()
  780. {
  781. if (!isTempClone())
  782. return;
  783. for (S32 i = 0; i < particleDataBlocks.size(); i++)
  784. {
  785. if (particleDataBlocks[i] && particleDataBlocks[i]->isTempClone())
  786. {
  787. delete particleDataBlocks[i];
  788. particleDataBlocks[i] = 0;
  789. }
  790. }
  791. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  792. if (emitter_data_clones > 0)
  793. {
  794. emitter_data_clones--;
  795. if (emitter_data_clones == 0)
  796. Con::errorf("ParticleEmitterData -- Clones eliminated!");
  797. }
  798. else
  799. Con::errorf("ParticleEmitterData -- Too many clones deleted!");
  800. #endif
  801. }
  802. ParticleEmitterData* ParticleEmitterData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  803. {
  804. if (!owner)
  805. return this;
  806. bool clone_parts_db = false;
  807. // note -- this could be checked when the particle blocks are evaluated
  808. for (S32 i = 0; i < this->particleDataBlocks.size(); i++)
  809. {
  810. if (this->particleDataBlocks[i] && (this->particleDataBlocks[i]->getSubstitutionCount() > 0))
  811. {
  812. clone_parts_db = true;
  813. break;
  814. }
  815. }
  816. ParticleEmitterData* sub_emitter_db = this;
  817. if (this->getSubstitutionCount() > 0 || clone_parts_db)
  818. {
  819. sub_emitter_db = new ParticleEmitterData(*this, true);
  820. performSubstitutions(sub_emitter_db, owner, index);
  821. if (clone_parts_db)
  822. {
  823. for (S32 i = 0; i < sub_emitter_db->particleDataBlocks.size(); i++)
  824. {
  825. if (sub_emitter_db->particleDataBlocks[i] && (sub_emitter_db->particleDataBlocks[i]->getSubstitutionCount() > 0))
  826. {
  827. ParticleData* orig_db = sub_emitter_db->particleDataBlocks[i];
  828. sub_emitter_db->particleDataBlocks[i] = new ParticleData(*orig_db, true);
  829. orig_db->performSubstitutions(sub_emitter_db->particleDataBlocks[i], owner, index);
  830. }
  831. }
  832. }
  833. }
  834. return sub_emitter_db;
  835. }
  836. //-----------------------------------------------------------------------------
  837. // ParticleEmitter
  838. //-----------------------------------------------------------------------------
  839. ParticleEmitter::ParticleEmitter()
  840. {
  841. mDeleteWhenEmpty = false;
  842. mDeleteOnTick = false;
  843. mInternalClock = 0;
  844. mNextParticleTime = 0;
  845. mLastPosition.set(0, 0, 0);
  846. mHasLastPosition = false;
  847. mLifetimeMS = 0;
  848. mElapsedTimeMS = 0;
  849. part_store = 0;
  850. part_freelist = NULL;
  851. part_list_head.next = NULL;
  852. n_part_capacity = 0;
  853. n_parts = 0;
  854. mThetaOld = 0;
  855. mPhiOld = 0;
  856. mCurBuffSize = 0;
  857. mDead = false;
  858. mDataBlock = NULL;
  859. // ParticleEmitter should be allocated on the client only.
  860. mNetFlags.set( IsGhost );
  861. fade_amt = 1.0f;
  862. forced_bbox = false;
  863. db_temp_clone = false;
  864. pos_pe.set(0,0,0);
  865. sort_priority = 0;
  866. mDataBlock = 0;
  867. std::fill_n(sizes, ParticleData::PDC_NUM_KEYS, 0.0f);
  868. #if defined(AFX_CAP_PARTICLE_POOLS)
  869. pool = 0;
  870. #endif
  871. }
  872. //-----------------------------------------------------------------------------
  873. // destructor
  874. //-----------------------------------------------------------------------------
  875. ParticleEmitter::~ParticleEmitter()
  876. {
  877. for( S32 i = 0; i < part_store.size(); i++ )
  878. {
  879. delete [] part_store[i];
  880. }
  881. if (db_temp_clone && mDataBlock && mDataBlock->isTempClone())
  882. {
  883. for (S32 i = 0; i < mDataBlock->particleDataBlocks.size(); i++)
  884. {
  885. if (mDataBlock->particleDataBlocks[i] && mDataBlock->particleDataBlocks[i]->isTempClone())
  886. {
  887. delete mDataBlock->particleDataBlocks[i];
  888. mDataBlock->particleDataBlocks[i] = 0;
  889. }
  890. }
  891. delete mDataBlock;
  892. mDataBlock = 0;
  893. }
  894. }
  895. //-----------------------------------------------------------------------------
  896. // onAdd
  897. //-----------------------------------------------------------------------------
  898. bool ParticleEmitter::onAdd()
  899. {
  900. if( !Parent::onAdd() )
  901. return false;
  902. // add to client side mission cleanup
  903. SimGroup *cleanup = dynamic_cast<SimGroup *>( Sim::findObject( "ClientMissionCleanup") );
  904. if( cleanup != NULL )
  905. {
  906. cleanup->addObject( this );
  907. }
  908. removeFromProcessList();
  909. F32 radius = 5.0;
  910. mObjBox.minExtents = Point3F(-radius, -radius, -radius);
  911. mObjBox.maxExtents = Point3F(radius, radius, radius);
  912. resetWorldBox();
  913. #if defined(AFX_CAP_PARTICLE_POOLS)
  914. if (pool)
  915. pool->addParticleEmitter(this);
  916. #endif
  917. return true;
  918. }
  919. //-----------------------------------------------------------------------------
  920. // onRemove
  921. //-----------------------------------------------------------------------------
  922. void ParticleEmitter::onRemove()
  923. {
  924. #if defined(AFX_CAP_PARTICLE_POOLS)
  925. if (pool)
  926. {
  927. pool->removeParticleEmitter(this);
  928. pool = 0;
  929. }
  930. #endif
  931. removeFromScene();
  932. Parent::onRemove();
  933. }
  934. //-----------------------------------------------------------------------------
  935. // onNewDataBlock
  936. //-----------------------------------------------------------------------------
  937. bool ParticleEmitter::onNewDataBlock( GameBaseData *dptr, bool reload )
  938. {
  939. mDataBlock = dynamic_cast<ParticleEmitterData*>( dptr );
  940. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  941. return false;
  942. mLifetimeMS = mDataBlock->lifetimeMS;
  943. if( mDataBlock->lifetimeVarianceMS )
  944. {
  945. mLifetimeMS += S32( gRandGen.randI() % (2 * mDataBlock->lifetimeVarianceMS + 1)) - S32(mDataBlock->lifetimeVarianceMS );
  946. }
  947. // Allocate particle structures and init the freelist. Member part_store
  948. // is a Vector so that we can allocate more particles if partListInitSize
  949. // turns out to be too small.
  950. //
  951. if (mDataBlock->partListInitSize > 0)
  952. {
  953. for( S32 i = 0; i < part_store.size(); i++ )
  954. {
  955. delete [] part_store[i];
  956. }
  957. part_store.clear();
  958. n_part_capacity = mDataBlock->partListInitSize;
  959. Particle* store_block = new Particle[n_part_capacity];
  960. part_store.push_back(store_block);
  961. part_freelist = store_block;
  962. Particle* last_part = part_freelist;
  963. Particle* part = last_part+1;
  964. for( S32 i = 1; i < n_part_capacity; i++, part++, last_part++ )
  965. {
  966. last_part->next = part;
  967. }
  968. store_block[n_part_capacity-1].next = NULL;
  969. part_list_head.next = NULL;
  970. n_parts = 0;
  971. }
  972. if (mDataBlock->isTempClone())
  973. {
  974. db_temp_clone = true;
  975. return true;
  976. }
  977. scriptOnNewDataBlock();
  978. return true;
  979. }
  980. //-----------------------------------------------------------------------------
  981. // getCollectiveColor
  982. //-----------------------------------------------------------------------------
  983. LinearColorF ParticleEmitter::getCollectiveColor()
  984. {
  985. U32 count = 0;
  986. LinearColorF color = LinearColorF(0.0f, 0.0f, 0.0f);
  987. count = n_parts;
  988. for( Particle* part = part_list_head.next; part != NULL; part = part->next )
  989. {
  990. color += part->color;
  991. }
  992. if(count > 0)
  993. {
  994. color /= F32(count);
  995. }
  996. //if(color.red == 0.0f && color.green == 0.0f && color.blue == 0.0f)
  997. // color = color;
  998. return color;
  999. }
  1000. //-----------------------------------------------------------------------------
  1001. // prepRenderImage
  1002. //-----------------------------------------------------------------------------
  1003. void ParticleEmitter::prepRenderImage(SceneRenderState* state)
  1004. {
  1005. #if defined(AFX_CAP_PARTICLE_POOLS)
  1006. if (pool)
  1007. return;
  1008. #endif
  1009. if( state->isReflectPass() && !getDataBlock()->renderReflection )
  1010. return;
  1011. // Never render into shadows.
  1012. if (state->isShadowPass())
  1013. return;
  1014. PROFILE_SCOPE(ParticleEmitter_prepRenderImage);
  1015. if ( mDead ||
  1016. n_parts == 0 ||
  1017. part_list_head.next == NULL )
  1018. return;
  1019. RenderPassManager *renderManager = state->getRenderPass();
  1020. const Point3F &camPos = state->getCameraPosition();
  1021. copyToVB( camPos, state->getAmbientLightColor() );
  1022. if (!mVertBuff.isValid())
  1023. return;
  1024. ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>();
  1025. ri->vertBuff = &mVertBuff;
  1026. ri->primBuff = &getDataBlock()->primBuff;
  1027. ri->translucentSort = true;
  1028. ri->type = RenderPassManager::RIT_Particle;
  1029. ri->sortDistSq = getRenderWorldBox().getSqDistanceToPoint( camPos );
  1030. ri->defaultKey = (-sort_priority*100);
  1031. // Draw the system offscreen unless the highResOnly flag is set on the datablock
  1032. ri->systemState = ( getDataBlock()->highResOnly ? PSS_AwaitingHighResDraw : PSS_AwaitingOffscreenDraw );
  1033. ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() *
  1034. GFX->getViewMatrix() *
  1035. GFX->getWorldMatrix() );
  1036. // Update position on the matrix before multiplying it
  1037. mBBObjToWorld.setPosition(mLastPosition);
  1038. ri->bbModelViewProj = renderManager->allocUniqueXform( *ri->modelViewProj * mBBObjToWorld );
  1039. ri->wsPosition = getWorldTransform().getPosition();
  1040. ri->count = n_parts;
  1041. ri->blendStyle = mDataBlock->blendStyle;
  1042. ri->glow = mDataBlock->glow;
  1043. // use first particle's texture unless there is an emitter texture to override it
  1044. if (mDataBlock->textureHandle)
  1045. ri->diffuseTex = &*(mDataBlock->textureHandle);
  1046. else
  1047. ri->diffuseTex = &*(part_list_head.next->dataBlock->getTextureResource());
  1048. ri->softnessDistance = mDataBlock->softnessDistance;
  1049. // Sort by texture too.
  1050. ri->defaultKey = ri->diffuseTex ? (uintptr_t)ri->diffuseTex : (uintptr_t)ri->vertBuff;
  1051. renderManager->addInst( ri );
  1052. }
  1053. //-----------------------------------------------------------------------------
  1054. // setSizes
  1055. //-----------------------------------------------------------------------------
  1056. void ParticleEmitter::setSizes( F32 *sizeList )
  1057. {
  1058. for( S32 i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  1059. {
  1060. sizes[i] = sizeList[i];
  1061. }
  1062. }
  1063. //-----------------------------------------------------------------------------
  1064. // setColors
  1065. //-----------------------------------------------------------------------------
  1066. void ParticleEmitter::setColors( LinearColorF *colorList )
  1067. {
  1068. for( S32 i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  1069. {
  1070. colors[i] = colorList[i];
  1071. }
  1072. }
  1073. //-----------------------------------------------------------------------------
  1074. // deleteWhenEmpty
  1075. //-----------------------------------------------------------------------------
  1076. void ParticleEmitter::deleteWhenEmpty()
  1077. {
  1078. // if the following asserts fire, there is a reasonable chance that you are trying to delete a particle emitter
  1079. // that has already been deleted (possibly by ClientMissionCleanup). If so, use a SimObjectPtr to the emitter and check it
  1080. // for null before calling this function.
  1081. AssertFatal(isProperlyAdded(), "ParticleEmitter must be registed before calling deleteWhenEmpty");
  1082. AssertFatal(!mDead, "ParticleEmitter already deleted");
  1083. AssertFatal(!isDeleted(), "ParticleEmitter already deleted");
  1084. AssertFatal(!isRemoved(), "ParticleEmitter already removed");
  1085. // this check is for non debug case, so that we don't write in to freed memory
  1086. bool okToDelete = !mDead && isProperlyAdded() && !isDeleted() && !isRemoved();
  1087. if (okToDelete)
  1088. {
  1089. mDeleteWhenEmpty = true;
  1090. if( !n_parts )
  1091. {
  1092. // We're already empty, so delete us now.
  1093. mDead = true;
  1094. deleteObject();
  1095. }
  1096. else
  1097. AssertFatal( getSceneManager() != NULL, "ParticleEmitter not on process list and won't get ticked to death" );
  1098. }
  1099. }
  1100. //-----------------------------------------------------------------------------
  1101. // emitParticles
  1102. //-----------------------------------------------------------------------------
  1103. void ParticleEmitter::emitParticles(const Point3F& point,
  1104. const bool useLastPosition,
  1105. const Point3F& axis,
  1106. const Point3F& velocity,
  1107. const U32 numMilliseconds)
  1108. {
  1109. if( mDead ) return;
  1110. // lifetime over - no more particles
  1111. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1112. {
  1113. return;
  1114. }
  1115. pos_pe = point;
  1116. Point3F realStart;
  1117. if( useLastPosition && mHasLastPosition )
  1118. realStart = mLastPosition;
  1119. else
  1120. realStart = point;
  1121. emitParticles(realStart, point,
  1122. axis,
  1123. velocity,
  1124. numMilliseconds);
  1125. }
  1126. //-----------------------------------------------------------------------------
  1127. // emitParticles
  1128. //-----------------------------------------------------------------------------
  1129. void ParticleEmitter::emitParticles(const Point3F& start,
  1130. const Point3F& end,
  1131. const Point3F& axis,
  1132. const Point3F& velocity,
  1133. const U32 numMilliseconds)
  1134. {
  1135. if( mDead ) return;
  1136. if( mDataBlock->particleDataBlocks.empty() )
  1137. return;
  1138. // lifetime over - no more particles
  1139. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1140. {
  1141. return;
  1142. }
  1143. U32 currTime = 0;
  1144. bool particlesAdded = false;
  1145. Point3F axisx;
  1146. if( mFabs(axis.z) < 0.9f )
  1147. mCross(axis, Point3F(0, 0, 1), &axisx);
  1148. else
  1149. mCross(axis, Point3F(0, 1, 0), &axisx);
  1150. axisx.normalize();
  1151. if( mNextParticleTime != 0 )
  1152. {
  1153. // Need to handle next particle
  1154. //
  1155. if( mNextParticleTime > numMilliseconds )
  1156. {
  1157. // Defer to next update
  1158. // (Note that this introduces a potential spatial irregularity if the owning
  1159. // object is accelerating, and updating at a low frequency)
  1160. //
  1161. mNextParticleTime -= numMilliseconds;
  1162. mInternalClock += numMilliseconds;
  1163. mLastPosition = end;
  1164. mHasLastPosition = true;
  1165. return;
  1166. }
  1167. else
  1168. {
  1169. currTime += mNextParticleTime;
  1170. mInternalClock += mNextParticleTime;
  1171. // Emit particle at curr time
  1172. // Create particle at the correct position
  1173. Point3F pos;
  1174. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  1175. addParticle(pos, axis, velocity, axisx, numMilliseconds-currTime);
  1176. particlesAdded = true;
  1177. mNextParticleTime = 0;
  1178. }
  1179. }
  1180. while( currTime < numMilliseconds )
  1181. {
  1182. S32 nextTime = mDataBlock->ejectionPeriodMS;
  1183. if( mDataBlock->periodVarianceMS != 0 )
  1184. {
  1185. nextTime += S32(gRandGen.randI() % (2 * mDataBlock->periodVarianceMS + 1)) -
  1186. S32(mDataBlock->periodVarianceMS);
  1187. }
  1188. AssertFatal(nextTime > 0, "Error, next particle ejection time must always be greater than 0");
  1189. if( currTime + nextTime > numMilliseconds )
  1190. {
  1191. mNextParticleTime = (currTime + nextTime) - numMilliseconds;
  1192. mInternalClock += numMilliseconds - currTime;
  1193. AssertFatal(mNextParticleTime > 0, "Error, should not have deferred this particle!");
  1194. break;
  1195. }
  1196. currTime += nextTime;
  1197. mInternalClock += nextTime;
  1198. // Create particle at the correct position
  1199. Point3F pos;
  1200. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  1201. addParticle(pos, axis, velocity, axisx, numMilliseconds-currTime);
  1202. particlesAdded = true;
  1203. // This override-advance code is restored in order to correctly adjust
  1204. // animated parameters of particles allocated within the same frame
  1205. // update. Note that ordering is important and this code correctly
  1206. // adds particles in the same newest-to-oldest ordering of the link-list.
  1207. //
  1208. // NOTE: We are assuming that the just added particle is at the head of our
  1209. // list. If that changes, so must this...
  1210. U32 advanceMS = numMilliseconds - currTime;
  1211. if (mDataBlock->overrideAdvance == false && advanceMS != 0)
  1212. {
  1213. Particle* last_part = part_list_head.next;
  1214. if (advanceMS > last_part->totalLifetime)
  1215. {
  1216. part_list_head.next = last_part->next;
  1217. n_parts--;
  1218. last_part->next = part_freelist;
  1219. part_freelist = last_part;
  1220. }
  1221. else
  1222. {
  1223. if (advanceMS != 0)
  1224. {
  1225. F32 t = F32(advanceMS) / 1000.0;
  1226. Point3F a = last_part->acc;
  1227. a -= last_part->vel * last_part->dataBlock->dragCoefficient;
  1228. a += mWindVelocity * last_part->dataBlock->windCoefficient;
  1229. //a += Point3F(0.0f, 0.0f, -9.81f) * last_part->dataBlock->gravityCoefficient;
  1230. a.z += -9.81f*last_part->dataBlock->gravityCoefficient; // as long as gravity is a constant, this is faster
  1231. last_part->vel += a * t;
  1232. //last_part->pos += last_part->vel * t;
  1233. last_part->pos_local += last_part->vel * t;
  1234. // AFX -- allow subclasses to adjust the particle params here
  1235. sub_particleUpdate(last_part);
  1236. if (last_part->dataBlock->constrain_pos)
  1237. last_part->pos = last_part->pos_local + this->pos_pe;
  1238. else
  1239. last_part->pos = last_part->pos_local;
  1240. updateKeyData( last_part );
  1241. }
  1242. }
  1243. }
  1244. }
  1245. // DMMFIX: Lame and slow...
  1246. if( particlesAdded == true )
  1247. updateBBox();
  1248. if( n_parts > 0 && getSceneManager() == NULL )
  1249. {
  1250. gClientSceneGraph->addObjectToScene(this);
  1251. ClientProcessList::get()->addObject(this);
  1252. }
  1253. mLastPosition = end;
  1254. mHasLastPosition = true;
  1255. }
  1256. //-----------------------------------------------------------------------------
  1257. // emitParticles
  1258. //-----------------------------------------------------------------------------
  1259. void ParticleEmitter::emitParticles(const Point3F& rCenter,
  1260. const Point3F& rNormal,
  1261. const F32 radius,
  1262. const Point3F& velocity,
  1263. S32 count)
  1264. {
  1265. if( mDead ) return;
  1266. // lifetime over - no more particles
  1267. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1268. {
  1269. return;
  1270. }
  1271. Point3F axisx, axisy;
  1272. Point3F axisz = rNormal;
  1273. if( axisz.isZero() )
  1274. {
  1275. axisz.set( 0.0, 0.0, 1.0 );
  1276. }
  1277. if( mFabs(axisz.z) < 0.98 )
  1278. {
  1279. mCross(axisz, Point3F(0, 0, 1), &axisy);
  1280. axisy.normalize();
  1281. }
  1282. else
  1283. {
  1284. mCross(axisz, Point3F(0, 1, 0), &axisy);
  1285. axisy.normalize();
  1286. }
  1287. mCross(axisz, axisy, &axisx);
  1288. axisx.normalize();
  1289. // Should think of a better way to distribute the
  1290. // particles within the hemisphere.
  1291. for( S32 i = 0; i < count; i++ )
  1292. {
  1293. Point3F pos = axisx * (radius * (1 - (2 * gRandGen.randF())));
  1294. pos += axisy * (radius * (1 - (2 * gRandGen.randF())));
  1295. pos += axisz * (radius * gRandGen.randF());
  1296. Point3F axis = pos;
  1297. axis.normalize();
  1298. pos += rCenter;
  1299. addParticle(pos, axis, velocity, axisz, 0);
  1300. }
  1301. // Set world bounding box
  1302. mObjBox.minExtents = rCenter - Point3F(radius, radius, radius);
  1303. mObjBox.maxExtents = rCenter + Point3F(radius, radius, radius);
  1304. resetWorldBox();
  1305. // Make sure we're part of the world
  1306. if( n_parts > 0 && getSceneManager() == NULL )
  1307. {
  1308. gClientSceneGraph->addObjectToScene(this);
  1309. ClientProcessList::get()->addObject(this);
  1310. }
  1311. mHasLastPosition = false;
  1312. }
  1313. //-----------------------------------------------------------------------------
  1314. // updateBBox - SLOW, bad news
  1315. //-----------------------------------------------------------------------------
  1316. void ParticleEmitter::updateBBox()
  1317. {
  1318. if (forced_bbox)
  1319. return;
  1320. Point3F minPt(1e10, 1e10, 1e10);
  1321. Point3F maxPt(-1e10, -1e10, -1e10);
  1322. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1323. {
  1324. Point3F particleSize(part->size * 0.5f);
  1325. F32 motion = getMax((part->vel.len() * part->totalLifetime / 1000.0f), 1.0f);
  1326. minPt.setMin(part->pos - particleSize - Point3F(motion));
  1327. maxPt.setMax(part->pos + particleSize + Point3F(motion));
  1328. }
  1329. mObjBox = Box3F(minPt, maxPt);
  1330. MatrixF temp = getTransform();
  1331. setTransform(temp);
  1332. mBBObjToWorld.identity();
  1333. Point3F boxScale = mObjBox.getExtents();
  1334. boxScale.x = getMax(boxScale.x, 1.0f);
  1335. boxScale.y = getMax(boxScale.y, 1.0f);
  1336. boxScale.z = getMax(boxScale.z, 1.0f);
  1337. mBBObjToWorld.scale(boxScale);
  1338. #if defined(AFX_CAP_PARTICLE_POOLS)
  1339. if (pool)
  1340. pool->updatePoolBBox(this);
  1341. #endif
  1342. }
  1343. //-----------------------------------------------------------------------------
  1344. // addParticle
  1345. //-----------------------------------------------------------------------------
  1346. void ParticleEmitter::addParticle(const Point3F& pos, const Point3F& axis, const Point3F& vel,
  1347. const Point3F& axisx, const U32 age_offset)
  1348. {
  1349. n_parts++;
  1350. if (n_parts > n_part_capacity || n_parts > mDataBlock->partListInitSize)
  1351. {
  1352. // In an emergency we allocate additional particles in blocks of 16.
  1353. // This should happen rarely.
  1354. Particle* store_block = new Particle[16];
  1355. part_store.push_back(store_block);
  1356. n_part_capacity += 16;
  1357. for (S32 i = 0; i < 16; i++)
  1358. {
  1359. store_block[i].next = part_freelist;
  1360. part_freelist = &store_block[i];
  1361. }
  1362. mDataBlock->allocPrimBuffer(n_part_capacity); // allocate larger primitive buffer or will crash
  1363. }
  1364. Particle* pNew = part_freelist;
  1365. part_freelist = pNew->next;
  1366. pNew->next = part_list_head.next;
  1367. part_list_head.next = pNew;
  1368. // for earlier access to constrain_pos, the ParticleData datablock is chosen here instead
  1369. // of later in the method.
  1370. U32 dBlockIndex = gRandGen.randI() % mDataBlock->particleDataBlocks.size();
  1371. ParticleData* part_db = mDataBlock->particleDataBlocks[dBlockIndex];
  1372. // set start position to world or local space
  1373. Point3F pos_start;
  1374. if (part_db->constrain_pos)
  1375. pos_start.set(0,0,0);
  1376. else
  1377. pos_start = pos;
  1378. Point3F ejectionAxis = axis;
  1379. F32 theta = 0.0f;
  1380. F32 thetaTarget = (mDataBlock->thetaMax + mDataBlock->thetaMin) / 2.0f;
  1381. if (mDataBlock->thetaVariance <= 0.0f)
  1382. theta = (mDataBlock->thetaMax - mDataBlock->thetaMin) * gRandGen.randF() + mDataBlock->thetaMin;
  1383. else
  1384. {
  1385. F32 thetaDelta = ( gRandGen.randF() - 0.5f) * mDataBlock->thetaVariance * 2.0f;
  1386. thetaDelta += ( (thetaTarget - mThetaOld) / mDataBlock->thetaMax ) * mDataBlock->thetaVariance * 0.25f;
  1387. theta = mThetaOld + thetaDelta;
  1388. }
  1389. mThetaOld = theta;
  1390. F32 ref = (F32(mInternalClock) / 1000.0) * mDataBlock->phiReferenceVel;
  1391. F32 phi = 0.0f;
  1392. if (mDataBlock->thetaVariance <= 0.0f)
  1393. {
  1394. phi = ref + gRandGen.randF() * mDataBlock->phiVariance;
  1395. }
  1396. else
  1397. {
  1398. F32 phiDelta = (gRandGen.randF() - 0.5f) * mDataBlock->thetaVariance * 2.0f;
  1399. phi = ref + mPhiOld + phiDelta;
  1400. if (phi > mDataBlock->phiVariance)
  1401. phi += fabs(phiDelta) * -2.0f;
  1402. if (phi < 0.0f)
  1403. phi += fabs(phiDelta) * 2.0f;
  1404. }
  1405. mPhiOld = phi;
  1406. // Both phi and theta are in degs. Create axis angles out of them, and create the
  1407. // appropriate rotation matrix...
  1408. AngAxisF thetaRot(axisx, theta * (M_PI / 180.0));
  1409. AngAxisF phiRot(axis, phi * (M_PI / 180.0));
  1410. MatrixF temp(true);
  1411. thetaRot.setMatrix(&temp);
  1412. temp.mulP(ejectionAxis);
  1413. phiRot.setMatrix(&temp);
  1414. temp.mulP(ejectionAxis);
  1415. F32 initialVel = mDataBlock->ejectionVelocity;
  1416. initialVel += (mDataBlock->velocityVariance * 2.0f * gRandGen.randF()) - mDataBlock->velocityVariance;
  1417. pNew->pos = pos_start + (ejectionAxis * (mDataBlock->ejectionOffset + mDataBlock->ejectionOffsetVariance* gRandGen.randF()) );
  1418. pNew->pos_local = pNew->pos;
  1419. pNew->vel = mDataBlock->ejectionInvert ? ejectionAxis * -initialVel : ejectionAxis * initialVel;
  1420. if (mDataBlock->orientParticles)
  1421. pNew->orientDir = ejectionAxis;
  1422. else
  1423. // note -- for non-oriented particles, we use orientDir.x to store the billboard start angle.
  1424. pNew->orientDir.x = mDegToRad(part_db->start_angle + part_db->angle_variance*2.0f*gRandGen.randF() - part_db->angle_variance);
  1425. pNew->acc.set(0, 0, 0);
  1426. pNew->currentAge = age_offset;
  1427. pNew->t_last = 0.0f;
  1428. // ribbon particles only use the first particle
  1429. if(mDataBlock->ribbonParticles)
  1430. {
  1431. mDataBlock->particleDataBlocks[0]->initializeParticle(pNew, vel);
  1432. }
  1433. else
  1434. {
  1435. dBlockIndex = gRandGen.randI() % mDataBlock->particleDataBlocks.size();
  1436. mDataBlock->particleDataBlocks[dBlockIndex]->initializeParticle(pNew, vel);
  1437. }
  1438. updateKeyData( pNew );
  1439. }
  1440. //-----------------------------------------------------------------------------
  1441. // processTick
  1442. //-----------------------------------------------------------------------------
  1443. void ParticleEmitter::processTick(const Move*)
  1444. {
  1445. if( mDeleteOnTick == true )
  1446. {
  1447. mDead = true;
  1448. deleteObject();
  1449. }
  1450. }
  1451. //-----------------------------------------------------------------------------
  1452. // advanceTime
  1453. //-----------------------------------------------------------------------------
  1454. void ParticleEmitter::advanceTime(F32 dt)
  1455. {
  1456. if( dt < 0.00001 ) return;
  1457. Parent::advanceTime(dt);
  1458. if( dt > 0.5 ) dt = 0.5;
  1459. if( mDead ) return;
  1460. mElapsedTimeMS += (S32)(dt * 1000.0f);
  1461. U32 numMSToUpdate = (U32)(dt * 1000.0f);
  1462. if( numMSToUpdate == 0 ) return;
  1463. // TODO: Prefetch
  1464. // remove dead particles
  1465. Particle* last_part = &part_list_head;
  1466. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1467. {
  1468. part->currentAge += numMSToUpdate;
  1469. if (part->currentAge > part->totalLifetime)
  1470. {
  1471. n_parts--;
  1472. last_part->next = part->next;
  1473. part->next = part_freelist;
  1474. part_freelist = part;
  1475. part = last_part;
  1476. }
  1477. else
  1478. {
  1479. last_part = part;
  1480. }
  1481. }
  1482. AssertFatal( n_parts >= 0, "ParticleEmitter: negative part count!" );
  1483. if (n_parts < 1 && mDeleteWhenEmpty)
  1484. {
  1485. mDeleteOnTick = true;
  1486. return;
  1487. }
  1488. if( numMSToUpdate != 0 && n_parts > 0 )
  1489. {
  1490. update( numMSToUpdate );
  1491. }
  1492. }
  1493. //-----------------------------------------------------------------------------
  1494. // Update key related particle data
  1495. //-----------------------------------------------------------------------------
  1496. void ParticleEmitter::updateKeyData( Particle *part )
  1497. {
  1498. //Ensure that our lifetime is never below 0
  1499. if( part->totalLifetime < 1 )
  1500. part->totalLifetime = 1;
  1501. if (part->currentAge > part->totalLifetime)
  1502. part->currentAge = part->totalLifetime;
  1503. F32 t = (F32)part->currentAge / (F32)part->totalLifetime;
  1504. for( U32 i = 1; i < ParticleData::PDC_NUM_KEYS; i++ )
  1505. {
  1506. if( part->dataBlock->times[i] >= t )
  1507. {
  1508. F32 firstPart = t - part->dataBlock->times[i-1];
  1509. F32 total = part->dataBlock->times[i] -
  1510. part->dataBlock->times[i-1];
  1511. firstPart /= total;
  1512. if( mDataBlock->useEmitterColors )
  1513. {
  1514. part->color.interpolate(colors[i-1], colors[i], firstPart);
  1515. }
  1516. else
  1517. {
  1518. part->color.interpolate(part->dataBlock->colors[i-1],
  1519. part->dataBlock->colors[i],
  1520. firstPart);
  1521. }
  1522. if( mDataBlock->useEmitterSizes )
  1523. {
  1524. part->size = (sizes[i-1] * (1.0 - firstPart)) +
  1525. (sizes[i] * firstPart);
  1526. }
  1527. else
  1528. {
  1529. part->size = (part->dataBlock->sizes[i-1] * (1.0 - firstPart)) +
  1530. (part->dataBlock->sizes[i] * firstPart);
  1531. part->size *= part->dataBlock->sizeBias;
  1532. }
  1533. if (mDataBlock->fade_color)
  1534. {
  1535. if (mDataBlock->fade_alpha)
  1536. part->color *= fade_amt;
  1537. else
  1538. {
  1539. part->color.red *= fade_amt;
  1540. part->color.green *= fade_amt;
  1541. part->color.blue *= fade_amt;
  1542. }
  1543. }
  1544. else if (mDataBlock->fade_alpha)
  1545. part->color.alpha *= fade_amt;
  1546. if (mDataBlock->fade_size)
  1547. part->size *= fade_amt;
  1548. break;
  1549. }
  1550. }
  1551. }
  1552. //-----------------------------------------------------------------------------
  1553. // Update particles
  1554. //-----------------------------------------------------------------------------
  1555. // AFX CODE BLOCK (enhanced-emitter) <<
  1556. void ParticleEmitter::update( U32 ms )
  1557. {
  1558. F32 t = F32(ms)/1000.0f; // AFX -- moved outside loop, no need to recalculate this for every particle
  1559. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1560. {
  1561. Point3F a = part->acc;
  1562. a -= part->vel * part->dataBlock->dragCoefficient;
  1563. a += mWindVelocity * part->dataBlock->windCoefficient;
  1564. a.z += -9.81f*part->dataBlock->gravityCoefficient; // AFX -- as long as gravity is a constant, this is faster
  1565. part->vel += a * t;
  1566. part->pos_local += part->vel * t;
  1567. // AFX -- allow subclasses to adjust the particle params here
  1568. sub_particleUpdate(part);
  1569. if (part->dataBlock->constrain_pos)
  1570. part->pos = part->pos_local + this->pos_pe;
  1571. else
  1572. part->pos = part->pos_local;
  1573. updateKeyData( part );
  1574. }
  1575. }
  1576. //-----------------------------------------------------------------------------
  1577. // Copy particles to vertex buffer
  1578. //-----------------------------------------------------------------------------
  1579. // structure used for particle sorting.
  1580. struct SortParticle
  1581. {
  1582. Particle* p;
  1583. F32 k;
  1584. };
  1585. // qsort callback function for particle sorting
  1586. S32 QSORT_CALLBACK cmpSortParticles(const void* p1, const void* p2)
  1587. {
  1588. const SortParticle* sp1 = (const SortParticle*)p1;
  1589. const SortParticle* sp2 = (const SortParticle*)p2;
  1590. if (sp2->k > sp1->k)
  1591. return 1;
  1592. else if (sp2->k == sp1->k)
  1593. return 0;
  1594. else
  1595. return -1;
  1596. }
  1597. void ParticleEmitter::copyToVB( const Point3F &camPos, const LinearColorF &ambientColor )
  1598. {
  1599. static Vector<SortParticle> orderedVector(__FILE__, __LINE__);
  1600. PROFILE_START(ParticleEmitter_copyToVB);
  1601. PROFILE_START(ParticleEmitter_copyToVB_Sort);
  1602. // build sorted list of particles (far to near)
  1603. if (mDataBlock->sortParticles)
  1604. {
  1605. orderedVector.clear();
  1606. MatrixF modelview = GFX->getWorldMatrix();
  1607. Point3F viewvec; modelview.getRow(1, &viewvec);
  1608. // add each particle and a distance based sort key to orderedVector
  1609. for (Particle* pp = part_list_head.next; pp != NULL; pp = pp->next)
  1610. {
  1611. orderedVector.increment();
  1612. orderedVector.last().p = pp;
  1613. orderedVector.last().k = mDot(pp->pos, viewvec);
  1614. }
  1615. // qsort the list into far to near ordering
  1616. dQsort(orderedVector.address(), orderedVector.size(), sizeof(SortParticle), cmpSortParticles);
  1617. }
  1618. PROFILE_END();
  1619. static Vector<ParticleVertexType> tempBuff(2048);
  1620. tempBuff.reserve( n_parts*4 + 64); // make sure tempBuff is big enough
  1621. ParticleVertexType *buffPtr = tempBuff.address(); // use direct pointer (faster)
  1622. if (mDataBlock->ribbonParticles)
  1623. {
  1624. PROFILE_START(ParticleEmitter_copyToVB_Ribbon);
  1625. if (mDataBlock->reverseOrder)
  1626. {
  1627. Particle* oldPtr = NULL;
  1628. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr -= 4)
  1629. {
  1630. setupRibbon(partPtr, partPtr->next, oldPtr, camPos, ambientColor, buffPtr);
  1631. oldPtr = partPtr;
  1632. }
  1633. }
  1634. else
  1635. {
  1636. Particle* oldPtr = NULL;
  1637. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr += 4)
  1638. {
  1639. setupRibbon(partPtr, partPtr->next, oldPtr, camPos, ambientColor, buffPtr);
  1640. oldPtr = partPtr;
  1641. }
  1642. }
  1643. PROFILE_END();
  1644. }
  1645. else if (mDataBlock->orientParticles)
  1646. {
  1647. PROFILE_START(ParticleEmitter_copyToVB_Orient);
  1648. if (mDataBlock->reverseOrder)
  1649. {
  1650. buffPtr += 4*(n_parts-1);
  1651. // do sorted-oriented particles
  1652. if (mDataBlock->sortParticles)
  1653. {
  1654. SortParticle* partPtr = orderedVector.address();
  1655. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1656. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1657. }
  1658. // do unsorted-oriented particles
  1659. else
  1660. {
  1661. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1662. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1663. }
  1664. }
  1665. else
  1666. {
  1667. // do sorted-oriented particles
  1668. if (mDataBlock->sortParticles)
  1669. {
  1670. SortParticle* partPtr = orderedVector.address();
  1671. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1672. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1673. }
  1674. // do unsorted-oriented particles
  1675. else
  1676. {
  1677. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1678. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1679. }
  1680. }
  1681. PROFILE_END();
  1682. }
  1683. else if (mDataBlock->alignParticles)
  1684. {
  1685. PROFILE_START(ParticleEmitter_copyToVB_Aligned);
  1686. if (mDataBlock->reverseOrder)
  1687. {
  1688. buffPtr += 4*(n_parts-1);
  1689. // do sorted-oriented particles
  1690. if (mDataBlock->sortParticles)
  1691. {
  1692. SortParticle* partPtr = orderedVector.address();
  1693. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1694. setupAligned(partPtr->p, ambientColor, buffPtr);
  1695. }
  1696. // do unsorted-oriented particles
  1697. else
  1698. {
  1699. Particle *partPtr = part_list_head.next;
  1700. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1701. setupAligned(partPtr, ambientColor, buffPtr);
  1702. }
  1703. }
  1704. else
  1705. {
  1706. // do sorted-oriented particles
  1707. if (mDataBlock->sortParticles)
  1708. {
  1709. SortParticle* partPtr = orderedVector.address();
  1710. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1711. setupAligned(partPtr->p, ambientColor, buffPtr);
  1712. }
  1713. // do unsorted-oriented particles
  1714. else
  1715. {
  1716. Particle *partPtr = part_list_head.next;
  1717. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1718. setupAligned(partPtr, ambientColor, buffPtr);
  1719. }
  1720. }
  1721. PROFILE_END();
  1722. }
  1723. else
  1724. {
  1725. PROFILE_START(ParticleEmitter_copyToVB_NonOriented);
  1726. // somewhat odd ordering so that texture coordinates match the oriented
  1727. // particles
  1728. Point3F basePoints[4];
  1729. basePoints[0] = Point3F(-1.0, 0.0, 1.0);
  1730. basePoints[1] = Point3F(-1.0, 0.0, -1.0);
  1731. basePoints[2] = Point3F( 1.0, 0.0, -1.0);
  1732. basePoints[3] = Point3F( 1.0, 0.0, 1.0);
  1733. MatrixF camView = GFX->getWorldMatrix();
  1734. camView.transpose(); // inverse - this gets the particles facing camera
  1735. if (mDataBlock->reverseOrder)
  1736. {
  1737. buffPtr += 4*(n_parts-1);
  1738. // do sorted-billboard particles
  1739. if (mDataBlock->sortParticles)
  1740. {
  1741. SortParticle *partPtr = orderedVector.address();
  1742. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr-=4 )
  1743. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1744. }
  1745. // do unsorted-billboard particles
  1746. else
  1747. {
  1748. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1749. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1750. }
  1751. }
  1752. else
  1753. {
  1754. // do sorted-billboard particles
  1755. if (mDataBlock->sortParticles)
  1756. {
  1757. SortParticle *partPtr = orderedVector.address();
  1758. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr+=4 )
  1759. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1760. }
  1761. // do unsorted-billboard particles
  1762. else
  1763. {
  1764. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1765. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1766. }
  1767. }
  1768. PROFILE_END();
  1769. }
  1770. PROFILE_START(ParticleEmitter_copyToVB_LockCopy);
  1771. // create new VB if emitter size grows
  1772. if( !mVertBuff || n_parts > mCurBuffSize )
  1773. {
  1774. mCurBuffSize = n_parts;
  1775. mVertBuff.set( GFX, n_parts * 4, GFXBufferTypeDynamic );
  1776. }
  1777. // lock and copy tempBuff to video RAM
  1778. ParticleVertexType *verts = mVertBuff.lock();
  1779. dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(ParticleVertexType) );
  1780. mVertBuff.unlock();
  1781. PROFILE_END();
  1782. PROFILE_END();
  1783. }
  1784. //-----------------------------------------------------------------------------
  1785. // Set up particle for billboard style render
  1786. //-----------------------------------------------------------------------------
  1787. void ParticleEmitter::setupBillboard( Particle *part,
  1788. Point3F *basePts,
  1789. const MatrixF &camView,
  1790. const LinearColorF &ambientColor,
  1791. ParticleVertexType *lVerts )
  1792. {
  1793. F32 width = part->size * 0.5f;
  1794. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1795. F32 sy, cy;
  1796. mSinCos(spinAngle, sy, cy);
  1797. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1798. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1799. // fill four verts, use macro and unroll loop
  1800. #define fillVert(){ \
  1801. lVerts->point.x = cy * basePts->x - sy * basePts->z; \
  1802. lVerts->point.y = 0.0f; \
  1803. lVerts->point.z = sy * basePts->x + cy * basePts->z; \
  1804. camView.mulV( lVerts->point ); \
  1805. lVerts->point *= width; \
  1806. lVerts->point += part->pos; \
  1807. lVerts->color = partCol.toColorI(); } \
  1808. // Here we deal with UVs for animated particle (billboard)
  1809. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1810. {
  1811. S32 fm = (S32)(part->currentAge*(1.0/1000.0)*part->dataBlock->framesPerSec);
  1812. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1813. S32 uv[4];
  1814. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1815. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1816. uv[2] = uv[1] + 1;
  1817. uv[3] = uv[0] + 1;
  1818. fillVert();
  1819. // Here and below, we copy UVs from particle datablock's current frame's UVs (billboard)
  1820. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1821. ++lVerts;
  1822. ++basePts;
  1823. fillVert();
  1824. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1825. ++lVerts;
  1826. ++basePts;
  1827. fillVert();
  1828. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1829. ++lVerts;
  1830. ++basePts;
  1831. fillVert();
  1832. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1833. ++lVerts;
  1834. ++basePts;
  1835. return;
  1836. }
  1837. fillVert();
  1838. // Here and below, we copy UVs from particle datablock's texCoords (billboard)
  1839. lVerts->texCoord = part->dataBlock->texCoords[0];
  1840. ++lVerts;
  1841. ++basePts;
  1842. fillVert();
  1843. lVerts->texCoord = part->dataBlock->texCoords[1];
  1844. ++lVerts;
  1845. ++basePts;
  1846. fillVert();
  1847. lVerts->texCoord = part->dataBlock->texCoords[2];
  1848. ++lVerts;
  1849. ++basePts;
  1850. fillVert();
  1851. lVerts->texCoord = part->dataBlock->texCoords[3];
  1852. ++lVerts;
  1853. ++basePts;
  1854. }
  1855. //-----------------------------------------------------------------------------
  1856. // Set up oriented particle
  1857. //-----------------------------------------------------------------------------
  1858. void ParticleEmitter::setupOriented( Particle *part,
  1859. const Point3F &camPos,
  1860. const LinearColorF &ambientColor,
  1861. ParticleVertexType *lVerts )
  1862. {
  1863. Point3F dir;
  1864. if( mDataBlock->orientOnVelocity )
  1865. {
  1866. // don't render oriented particle if it has no velocity
  1867. if( part->vel.magnitudeSafe() == 0.0 ) return;
  1868. dir = part->vel;
  1869. }
  1870. else
  1871. {
  1872. dir = part->orientDir;
  1873. }
  1874. Point3F dirFromCam = part->pos - camPos;
  1875. Point3F crossDir;
  1876. mCross( dirFromCam, dir, &crossDir );
  1877. crossDir.normalize();
  1878. dir.normalize();
  1879. F32 width = part->size * 0.5f;
  1880. dir *= width;
  1881. crossDir *= width;
  1882. Point3F start = part->pos - dir;
  1883. Point3F end = part->pos + dir;
  1884. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1885. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1886. const ColorI color = partCol.toColorI();
  1887. // Here we deal with UVs for animated particle (oriented)
  1888. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1889. {
  1890. // Let particle compute the UV indices for current frame
  1891. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1892. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1893. S32 uv[4];
  1894. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1895. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1896. uv[2] = uv[1] + 1;
  1897. uv[3] = uv[0] + 1;
  1898. lVerts->point = start + crossDir;
  1899. lVerts->color = color;
  1900. // Here and below, we copy UVs from particle datablock's current frame's UVs (oriented)
  1901. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1902. ++lVerts;
  1903. lVerts->point = start - crossDir;
  1904. lVerts->color = color;
  1905. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1906. ++lVerts;
  1907. lVerts->point = end - crossDir;
  1908. lVerts->color = color;
  1909. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1910. ++lVerts;
  1911. lVerts->point = end + crossDir;
  1912. lVerts->color = color;
  1913. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1914. ++lVerts;
  1915. return;
  1916. }
  1917. lVerts->point = start + crossDir;
  1918. lVerts->color = color;
  1919. // Here and below, we copy UVs from particle datablock's texCoords (oriented)
  1920. lVerts->texCoord = part->dataBlock->texCoords[1];
  1921. ++lVerts;
  1922. lVerts->point = start - crossDir;
  1923. lVerts->color = color;
  1924. lVerts->texCoord = part->dataBlock->texCoords[2];
  1925. ++lVerts;
  1926. lVerts->point = end - crossDir;
  1927. lVerts->color = color;
  1928. lVerts->texCoord = part->dataBlock->texCoords[3];
  1929. ++lVerts;
  1930. lVerts->point = end + crossDir;
  1931. lVerts->color = color;
  1932. lVerts->texCoord = part->dataBlock->texCoords[0];
  1933. ++lVerts;
  1934. }
  1935. void ParticleEmitter::setupAligned( const Particle *part,
  1936. const LinearColorF &ambientColor,
  1937. ParticleVertexType *lVerts )
  1938. {
  1939. // The aligned direction will always be normalized.
  1940. Point3F dir = mDataBlock->alignDirection;
  1941. // Find a right vector for this particle.
  1942. Point3F right;
  1943. if (mFabs(dir.y) > mFabs(dir.z))
  1944. mCross(Point3F::UnitZ, dir, &right);
  1945. else
  1946. mCross(Point3F::UnitY, dir, &right);
  1947. right.normalize();
  1948. // If we have a spin velocity.
  1949. if ( !mIsZero( part->spinSpeed ) )
  1950. {
  1951. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1952. // This is an inline quaternion vector rotation which
  1953. // is faster that QuatF.mulP(), but generates different
  1954. // results and hence cannot replace it right now.
  1955. F32 sin, qw;
  1956. mSinCos( spinAngle * 0.5f, sin, qw );
  1957. F32 qx = dir.x * sin;
  1958. F32 qy = dir.y * sin;
  1959. F32 qz = dir.z * sin;
  1960. F32 vx = ( right.x * qw ) + ( right.z * qy ) - ( right.y * qz );
  1961. F32 vy = ( right.y * qw ) + ( right.x * qz ) - ( right.z * qx );
  1962. F32 vz = ( right.z * qw ) + ( right.y * qx ) - ( right.x * qy );
  1963. F32 vw = ( right.x * qx ) + ( right.y * qy ) + ( right.z * qz );
  1964. right.x = ( qw * vx ) + ( qx * vw ) + ( qy * vz ) - ( qz * vy );
  1965. right.y = ( qw * vy ) + ( qy * vw ) + ( qz * vx ) - ( qx * vz );
  1966. right.z = ( qw * vz ) + ( qz * vw ) + ( qx * vy ) - ( qy * vx );
  1967. }
  1968. // Get the cross vector.
  1969. Point3F cross;
  1970. mCross(right, dir, &cross);
  1971. F32 width = part->size * 0.5f;
  1972. right *= width;
  1973. cross *= width;
  1974. Point3F start = part->pos - right;
  1975. Point3F end = part->pos + right;
  1976. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1977. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1978. const ColorI color = partCol.toColorI();
  1979. // Here we deal with UVs for animated particle
  1980. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1981. {
  1982. // Let particle compute the UV indices for current frame
  1983. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1984. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1985. S32 uv[4];
  1986. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1987. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1988. uv[2] = uv[1] + 1;
  1989. uv[3] = uv[0] + 1;
  1990. lVerts->point = start + cross;
  1991. lVerts->color = color;
  1992. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1993. ++lVerts;
  1994. lVerts->point = start - cross;
  1995. lVerts->color = color;
  1996. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1997. ++lVerts;
  1998. lVerts->point = end - cross;
  1999. lVerts->color = color;
  2000. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  2001. ++lVerts;
  2002. lVerts->point = end + cross;
  2003. lVerts->color = color;
  2004. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  2005. ++lVerts;
  2006. }
  2007. else
  2008. {
  2009. // Here and below, we copy UVs from particle datablock's texCoords
  2010. lVerts->point = start + cross;
  2011. lVerts->color = color;
  2012. lVerts->texCoord = part->dataBlock->texCoords[0];
  2013. ++lVerts;
  2014. lVerts->point = start - cross;
  2015. lVerts->color = color;
  2016. lVerts->texCoord = part->dataBlock->texCoords[1];
  2017. ++lVerts;
  2018. lVerts->point = end - cross;
  2019. lVerts->color = color;
  2020. lVerts->texCoord = part->dataBlock->texCoords[2];
  2021. ++lVerts;
  2022. lVerts->point = end + cross;
  2023. lVerts->color = color;
  2024. lVerts->texCoord = part->dataBlock->texCoords[3];
  2025. ++lVerts;
  2026. }
  2027. }
  2028. void ParticleEmitter::setupRibbon(Particle *part,
  2029. Particle *next,
  2030. Particle *prev,
  2031. const Point3F &camPos,
  2032. const LinearColorF &ambientColor,
  2033. ParticleVertexType *lVerts)
  2034. {
  2035. Point3F dir, dirFromCam;
  2036. Point3F crossDir, crossDirNext;
  2037. Point3F start, end;
  2038. LinearColorF prevCol;
  2039. static Point3F crossDirPrev;
  2040. static int position;
  2041. static F32 alphaMod, alphaModEnd;
  2042. const F32 ambientLerp = mClampF(mDataBlock->ambientFactor, 0.0f, 1.0f);
  2043. LinearColorF partCol = mLerp(part->color, (part->color * ambientColor), ambientLerp);
  2044. if (part->currentAge > part->totalLifetime)
  2045. {
  2046. F32 alphaDeath = (part->currentAge - part->totalLifetime) / 200.0f;
  2047. if (alphaDeath > 1.0f)
  2048. alphaDeath = 1.0f;
  2049. alphaDeath = 1.0f - alphaDeath;
  2050. partCol.alpha *= alphaDeath;
  2051. }
  2052. start = part->pos;
  2053. position++;
  2054. if (next == NULL && prev == NULL) {
  2055. // a ribbon of just one particle
  2056. position = 0;
  2057. if (part->vel.magnitudeSafe() == 0.0)
  2058. dir = part->orientDir;
  2059. else
  2060. dir = part->vel;
  2061. dir.normalize();
  2062. dirFromCam = part->pos - camPos;
  2063. mCross(dirFromCam, dir, &crossDir);
  2064. crossDir.normalize();
  2065. crossDir = crossDir * part->size * 0.5;
  2066. crossDirPrev = crossDir;
  2067. partCol.alpha = 0.0f;
  2068. prevCol = partCol;
  2069. end = part->pos;
  2070. }
  2071. else if (next == NULL && prev != NULL)
  2072. {
  2073. // last link in the chain, also the oldest
  2074. dir = part->pos - prev->pos;
  2075. dir.normalize();
  2076. dirFromCam = part->pos - camPos;
  2077. mCross(dirFromCam, dir, &crossDir);
  2078. crossDir.normalize();
  2079. crossDir = crossDir * part->size * 0.5;
  2080. end = prev->pos;
  2081. partCol.alpha = 0.0f;
  2082. prevCol = mLerp(prev->color, (prev->color * ambientColor), ambientLerp);
  2083. prevCol.alpha *= alphaModEnd;
  2084. }
  2085. else if (next != NULL && prev == NULL)
  2086. {
  2087. // first link in chain, newest particle
  2088. // since we draw from current to previous, this one isn't drawn
  2089. position = 0;
  2090. dir = next->pos - part->pos;
  2091. dir.normalize();
  2092. dirFromCam = part->pos - camPos;
  2093. mCross(dirFromCam, dir, &crossDir);
  2094. crossDir.normalize();
  2095. crossDir = crossDir * part->size * 0.5f;
  2096. crossDirPrev = crossDir;
  2097. partCol.alpha = 0.0f;
  2098. prevCol = partCol;
  2099. alphaModEnd = 0.0f;
  2100. end = part->pos;
  2101. }
  2102. else
  2103. {
  2104. // middle of chain
  2105. dir = next->pos - prev->pos;
  2106. dir.normalize();
  2107. dirFromCam = part->pos - camPos;
  2108. mCross(dirFromCam, dir, &crossDir);
  2109. crossDir.normalize();
  2110. crossDir = crossDir * part->size * 0.5;
  2111. prevCol = mLerp(prev->color, (prev->color * ambientColor), ambientLerp);
  2112. if (position == 1)
  2113. {
  2114. // the second particle has a few tweaks for alpha, to smoothly match the first particle
  2115. // we only want to do this once when the particle first fades in, and avoid a strobing effect
  2116. alphaMod = (float(part->currentAge) / float(part->currentAge - prev->currentAge)) - 1.0f;
  2117. if (alphaMod > 1.0f)
  2118. alphaMod = 1.0f;
  2119. partCol.alpha *= alphaMod;
  2120. prevCol.alpha = 0.0f;
  2121. if (next->next == NULL)
  2122. alphaModEnd = alphaMod;
  2123. //Con::printf("alphaMod: %f", alphaMod );
  2124. }
  2125. else if (position == 2)
  2126. {
  2127. prevCol.alpha *= alphaMod;
  2128. alphaMod = 0.0f;
  2129. }
  2130. if (next->next == NULL && position > 1)
  2131. {
  2132. // next to last particle, start the fade out
  2133. alphaModEnd = (float(next->totalLifetime - next->currentAge)) / (float(part->totalLifetime - part->currentAge));
  2134. alphaModEnd *= 2.0f;
  2135. if (alphaModEnd > 1.0f)
  2136. alphaModEnd = 1.0f;
  2137. partCol.alpha *= alphaModEnd;
  2138. //Con::printf("alphaMod: %f Lifetime: %d Age: %d", alphaMod, part->totalLifetime, part->currentAge );
  2139. }
  2140. end = prev->pos;
  2141. }
  2142. ColorI pCol = partCol.toColorI();
  2143. // Here we deal with UVs for animated particle (oriented)
  2144. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  2145. {
  2146. // Let particle compute the UV indices for current frame
  2147. S32 fm = (S32)(part->currentAge*(1.0f / 1000.0f)*part->dataBlock->framesPerSec);
  2148. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  2149. S32 uv[4];
  2150. uv[0] = fm_tile + fm_tile / part->dataBlock->animTexTiling.x;
  2151. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  2152. uv[2] = uv[1] + 1;
  2153. uv[3] = uv[0] + 1;
  2154. lVerts->point = start + crossDir;
  2155. lVerts->color = pCol;
  2156. // Here and below, we copy UVs from particle datablock's current frame's UVs (oriented)
  2157. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  2158. ++lVerts;
  2159. lVerts->point = start - crossDir;
  2160. lVerts->color = pCol;
  2161. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  2162. ++lVerts;
  2163. lVerts->point = end - crossDirPrev;
  2164. lVerts->color = pCol;
  2165. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  2166. ++lVerts;
  2167. lVerts->point = end + crossDirPrev;
  2168. lVerts->color = pCol;
  2169. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  2170. ++lVerts;
  2171. crossDirPrev = crossDir;
  2172. return;
  2173. }
  2174. lVerts->point = start + crossDir;
  2175. lVerts->color = pCol;
  2176. // Here and below, we copy UVs from particle datablock's texCoords (oriented)
  2177. lVerts->texCoord = part->dataBlock->texCoords[0];
  2178. ++lVerts;
  2179. lVerts->point = start - crossDir;
  2180. lVerts->color = pCol;
  2181. lVerts->texCoord = part->dataBlock->texCoords[1];
  2182. ++lVerts;
  2183. lVerts->point = end - crossDirPrev;
  2184. lVerts->color = pCol;
  2185. lVerts->texCoord = part->dataBlock->texCoords[2];
  2186. ++lVerts;
  2187. lVerts->point = end + crossDirPrev;
  2188. lVerts->color = pCol;
  2189. lVerts->texCoord = part->dataBlock->texCoords[3];
  2190. ++lVerts;
  2191. crossDirPrev = crossDir;
  2192. }
  2193. bool ParticleEmitterData::reload()
  2194. {
  2195. // Clear out current particle data.
  2196. dataBlockIds.clear();
  2197. particleDataBlocks.clear();
  2198. // Parse out particle string.
  2199. U32 numUnits = 0;
  2200. if( particleString )
  2201. numUnits = StringUnit::getUnitCount( particleString, " \t" );
  2202. if( !particleString || !particleString[ 0 ] || !numUnits )
  2203. {
  2204. Con::errorf( "ParticleEmitterData(%s) has an empty particles string.", getName() );
  2205. mReloadSignal.trigger();
  2206. return false;
  2207. }
  2208. for( U32 i = 0; i < numUnits; ++ i )
  2209. {
  2210. const char* dbName = StringUnit::getUnit( particleString, i, " \t" );
  2211. ParticleData* data = NULL;
  2212. if( !Sim::findObject( dbName, data ) )
  2213. {
  2214. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dbName );
  2215. continue;
  2216. }
  2217. particleDataBlocks.push_back( data );
  2218. dataBlockIds.push_back( data->getId() );
  2219. }
  2220. // Check that we actually found some particle datablocks.
  2221. if( particleDataBlocks.empty() )
  2222. {
  2223. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName() );
  2224. mReloadSignal.trigger();
  2225. return false;
  2226. }
  2227. // Trigger reload.
  2228. mReloadSignal.trigger();
  2229. return true;
  2230. }
  2231. DefineEngineMethod(ParticleEmitterData, reload, void,(),,
  2232. "Reloads the ParticleData datablocks and other fields used by this emitter.\n"
  2233. "@tsexample\n"
  2234. "// Get the editor's current particle emitter\n"
  2235. "%emitter = PE_EmitterEditor.currEmitter\n\n"
  2236. "// Change a field value\n"
  2237. "%emitter.setFieldValue( %propertyField, %value );\n\n"
  2238. "// Reload this emitter\n"
  2239. "%emitter.reload();\n"
  2240. "@endtsexample\n")
  2241. {
  2242. object->reload();
  2243. }
  2244. void ParticleEmitter::emitParticlesExt(const MatrixF& xfm, const Point3F& point,
  2245. const Point3F& velocity, const U32 numMilliseconds)
  2246. {
  2247. if (mDataBlock->use_emitter_xfm)
  2248. {
  2249. Point3F zero_point(0.0f, 0.0f, 0.0f);
  2250. this->pos_pe = zero_point;
  2251. this->setTransform(xfm);
  2252. Point3F axis(0.0,0.0,1.0);
  2253. xfm.mulV(axis);
  2254. emitParticles(zero_point, true, axis, velocity, numMilliseconds);
  2255. }
  2256. else
  2257. {
  2258. this->pos_pe = point;
  2259. Point3F axis(0.0,0.0,1.0);
  2260. xfm.mulV(axis);
  2261. emitParticles(point, true, axis, velocity, numMilliseconds);
  2262. }
  2263. }
  2264. void ParticleEmitter::setForcedObjBox(Box3F& box)
  2265. {
  2266. mObjBox = box;
  2267. forced_bbox = true;
  2268. #if defined(AFX_CAP_PARTICLE_POOLS)
  2269. if (pool)
  2270. pool->updatePoolBBox(this);
  2271. #endif
  2272. }
  2273. void ParticleEmitter::setSortPriority(S8 priority)
  2274. {
  2275. sort_priority = (priority == 0) ? 1 : priority;
  2276. #if defined(AFX_CAP_PARTICLE_POOLS)
  2277. if (pool)
  2278. pool->setSortPriority(sort_priority);
  2279. #endif
  2280. }