2
0

particleEmitter.cpp 80 KB

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