particleEmitter.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  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. glow = other.glow;
  729. renderReflection = other.renderReflection;
  730. fade_color = other.fade_color;
  731. fade_size = other.fade_size;
  732. fade_alpha = other.fade_alpha;
  733. ejectionInvert = other.ejectionInvert;
  734. parts_per_eject = other.parts_per_eject; // -- set to 1 (used by subclasses)
  735. use_emitter_xfm = other.use_emitter_xfm;
  736. #if defined(AFX_CAP_PARTICLE_POOLS)
  737. pool_datablock = other.pool_datablock;
  738. pool_index = other.pool_index;
  739. pool_depth_fade = other.pool_depth_fade;
  740. pool_radial_fade = other.pool_radial_fade;
  741. do_pool_id_convert = other.do_pool_id_convert; // -- flags pool id conversion need
  742. #endif
  743. }
  744. ParticleEmitterData::~ParticleEmitterData()
  745. {
  746. if (!isTempClone())
  747. return;
  748. for (S32 i = 0; i < particleDataBlocks.size(); i++)
  749. {
  750. if (particleDataBlocks[i] && particleDataBlocks[i]->isTempClone())
  751. {
  752. delete particleDataBlocks[i];
  753. particleDataBlocks[i] = 0;
  754. }
  755. }
  756. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  757. if (emitter_data_clones > 0)
  758. {
  759. emitter_data_clones--;
  760. if (emitter_data_clones == 0)
  761. Con::errorf("ParticleEmitterData -- Clones eliminated!");
  762. }
  763. else
  764. Con::errorf("ParticleEmitterData -- Too many clones deleted!");
  765. #endif
  766. }
  767. ParticleEmitterData* ParticleEmitterData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  768. {
  769. if (!owner)
  770. return this;
  771. bool clone_parts_db = false;
  772. // note -- this could be checked when the particle blocks are evaluated
  773. for (S32 i = 0; i < this->particleDataBlocks.size(); i++)
  774. {
  775. if (this->particleDataBlocks[i] && (this->particleDataBlocks[i]->getSubstitutionCount() > 0))
  776. {
  777. clone_parts_db = true;
  778. break;
  779. }
  780. }
  781. ParticleEmitterData* sub_emitter_db = this;
  782. if (this->getSubstitutionCount() > 0 || clone_parts_db)
  783. {
  784. sub_emitter_db = new ParticleEmitterData(*this, true);
  785. performSubstitutions(sub_emitter_db, owner, index);
  786. if (clone_parts_db)
  787. {
  788. for (S32 i = 0; i < sub_emitter_db->particleDataBlocks.size(); i++)
  789. {
  790. if (sub_emitter_db->particleDataBlocks[i] && (sub_emitter_db->particleDataBlocks[i]->getSubstitutionCount() > 0))
  791. {
  792. ParticleData* orig_db = sub_emitter_db->particleDataBlocks[i];
  793. sub_emitter_db->particleDataBlocks[i] = new ParticleData(*orig_db, true);
  794. orig_db->performSubstitutions(sub_emitter_db->particleDataBlocks[i], owner, index);
  795. }
  796. }
  797. }
  798. }
  799. return sub_emitter_db;
  800. }
  801. //-----------------------------------------------------------------------------
  802. // ParticleEmitter
  803. //-----------------------------------------------------------------------------
  804. ParticleEmitter::ParticleEmitter()
  805. {
  806. mDeleteWhenEmpty = false;
  807. mDeleteOnTick = false;
  808. mInternalClock = 0;
  809. mNextParticleTime = 0;
  810. mLastPosition.set(0, 0, 0);
  811. mHasLastPosition = false;
  812. mLifetimeMS = 0;
  813. mElapsedTimeMS = 0;
  814. part_store = 0;
  815. part_freelist = NULL;
  816. part_list_head.next = NULL;
  817. n_part_capacity = 0;
  818. n_parts = 0;
  819. mCurBuffSize = 0;
  820. mDead = false;
  821. mDataBlock = NULL;
  822. // ParticleEmitter should be allocated on the client only.
  823. mNetFlags.set( IsGhost );
  824. fade_amt = 1.0f;
  825. forced_bbox = false;
  826. db_temp_clone = false;
  827. pos_pe.set(0,0,0);
  828. sort_priority = 0;
  829. mDataBlock = 0;
  830. std::fill_n(sizes, ParticleData::PDC_NUM_KEYS, 0.0f);
  831. #if defined(AFX_CAP_PARTICLE_POOLS)
  832. pool = 0;
  833. #endif
  834. }
  835. //-----------------------------------------------------------------------------
  836. // destructor
  837. //-----------------------------------------------------------------------------
  838. ParticleEmitter::~ParticleEmitter()
  839. {
  840. for( S32 i = 0; i < part_store.size(); i++ )
  841. {
  842. delete [] part_store[i];
  843. }
  844. if (db_temp_clone && mDataBlock && mDataBlock->isTempClone())
  845. {
  846. for (S32 i = 0; i < mDataBlock->particleDataBlocks.size(); i++)
  847. {
  848. if (mDataBlock->particleDataBlocks[i] && mDataBlock->particleDataBlocks[i]->isTempClone())
  849. {
  850. delete mDataBlock->particleDataBlocks[i];
  851. mDataBlock->particleDataBlocks[i] = 0;
  852. }
  853. }
  854. delete mDataBlock;
  855. mDataBlock = 0;
  856. }
  857. }
  858. //-----------------------------------------------------------------------------
  859. // onAdd
  860. //-----------------------------------------------------------------------------
  861. bool ParticleEmitter::onAdd()
  862. {
  863. if( !Parent::onAdd() )
  864. return false;
  865. // add to client side mission cleanup
  866. SimGroup *cleanup = dynamic_cast<SimGroup *>( Sim::findObject( "ClientMissionCleanup") );
  867. if( cleanup != NULL )
  868. {
  869. cleanup->addObject( this );
  870. }
  871. removeFromProcessList();
  872. F32 radius = 5.0;
  873. mObjBox.minExtents = Point3F(-radius, -radius, -radius);
  874. mObjBox.maxExtents = Point3F(radius, radius, radius);
  875. resetWorldBox();
  876. #if defined(AFX_CAP_PARTICLE_POOLS)
  877. if (pool)
  878. pool->addParticleEmitter(this);
  879. #endif
  880. return true;
  881. }
  882. //-----------------------------------------------------------------------------
  883. // onRemove
  884. //-----------------------------------------------------------------------------
  885. void ParticleEmitter::onRemove()
  886. {
  887. #if defined(AFX_CAP_PARTICLE_POOLS)
  888. if (pool)
  889. {
  890. pool->removeParticleEmitter(this);
  891. pool = 0;
  892. }
  893. #endif
  894. removeFromScene();
  895. Parent::onRemove();
  896. }
  897. //-----------------------------------------------------------------------------
  898. // onNewDataBlock
  899. //-----------------------------------------------------------------------------
  900. bool ParticleEmitter::onNewDataBlock( GameBaseData *dptr, bool reload )
  901. {
  902. mDataBlock = dynamic_cast<ParticleEmitterData*>( dptr );
  903. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  904. return false;
  905. mLifetimeMS = mDataBlock->lifetimeMS;
  906. if( mDataBlock->lifetimeVarianceMS )
  907. {
  908. mLifetimeMS += S32( gRandGen.randI() % (2 * mDataBlock->lifetimeVarianceMS + 1)) - S32(mDataBlock->lifetimeVarianceMS );
  909. }
  910. // Allocate particle structures and init the freelist. Member part_store
  911. // is a Vector so that we can allocate more particles if partListInitSize
  912. // turns out to be too small.
  913. //
  914. if (mDataBlock->partListInitSize > 0)
  915. {
  916. for( S32 i = 0; i < part_store.size(); i++ )
  917. {
  918. delete [] part_store[i];
  919. }
  920. part_store.clear();
  921. n_part_capacity = mDataBlock->partListInitSize;
  922. Particle* store_block = new Particle[n_part_capacity];
  923. part_store.push_back(store_block);
  924. part_freelist = store_block;
  925. Particle* last_part = part_freelist;
  926. Particle* part = last_part+1;
  927. for( S32 i = 1; i < n_part_capacity; i++, part++, last_part++ )
  928. {
  929. last_part->next = part;
  930. }
  931. store_block[n_part_capacity-1].next = NULL;
  932. part_list_head.next = NULL;
  933. n_parts = 0;
  934. }
  935. if (mDataBlock->isTempClone())
  936. {
  937. db_temp_clone = true;
  938. return true;
  939. }
  940. scriptOnNewDataBlock();
  941. return true;
  942. }
  943. //-----------------------------------------------------------------------------
  944. // getCollectiveColor
  945. //-----------------------------------------------------------------------------
  946. LinearColorF ParticleEmitter::getCollectiveColor()
  947. {
  948. U32 count = 0;
  949. LinearColorF color = LinearColorF(0.0f, 0.0f, 0.0f);
  950. count = n_parts;
  951. for( Particle* part = part_list_head.next; part != NULL; part = part->next )
  952. {
  953. color += part->color;
  954. }
  955. if(count > 0)
  956. {
  957. color /= F32(count);
  958. }
  959. //if(color.red == 0.0f && color.green == 0.0f && color.blue == 0.0f)
  960. // color = color;
  961. return color;
  962. }
  963. //-----------------------------------------------------------------------------
  964. // prepRenderImage
  965. //-----------------------------------------------------------------------------
  966. void ParticleEmitter::prepRenderImage(SceneRenderState* state)
  967. {
  968. #if defined(AFX_CAP_PARTICLE_POOLS)
  969. if (pool)
  970. return;
  971. #endif
  972. if( state->isReflectPass() && !getDataBlock()->renderReflection )
  973. return;
  974. // Never render into shadows.
  975. if (state->isShadowPass())
  976. return;
  977. PROFILE_SCOPE(ParticleEmitter_prepRenderImage);
  978. if ( mDead ||
  979. n_parts == 0 ||
  980. part_list_head.next == NULL )
  981. return;
  982. RenderPassManager *renderManager = state->getRenderPass();
  983. const Point3F &camPos = state->getCameraPosition();
  984. copyToVB( camPos, state->getAmbientLightColor() );
  985. if (!mVertBuff.isValid())
  986. return;
  987. ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>();
  988. ri->vertBuff = &mVertBuff;
  989. ri->primBuff = &getDataBlock()->primBuff;
  990. ri->translucentSort = true;
  991. ri->type = RenderPassManager::RIT_Particle;
  992. ri->sortDistSq = getRenderWorldBox().getSqDistanceToPoint( camPos );
  993. ri->defaultKey = (-sort_priority*100);
  994. // Draw the system offscreen unless the highResOnly flag is set on the datablock
  995. ri->systemState = ( getDataBlock()->highResOnly ? PSS_AwaitingHighResDraw : PSS_AwaitingOffscreenDraw );
  996. ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() *
  997. GFX->getViewMatrix() *
  998. GFX->getWorldMatrix() );
  999. // Update position on the matrix before multiplying it
  1000. mBBObjToWorld.setPosition(mLastPosition);
  1001. ri->bbModelViewProj = renderManager->allocUniqueXform( *ri->modelViewProj * mBBObjToWorld );
  1002. ri->wsPosition = getWorldTransform().getPosition();
  1003. ri->count = n_parts;
  1004. ri->blendStyle = mDataBlock->blendStyle;
  1005. ri->glow = mDataBlock->glow;
  1006. // use first particle's texture unless there is an emitter texture to override it
  1007. if (mDataBlock->textureHandle)
  1008. ri->diffuseTex = &*(mDataBlock->textureHandle);
  1009. else
  1010. ri->diffuseTex = &*(part_list_head.next->dataBlock->textureHandle);
  1011. ri->softnessDistance = mDataBlock->softnessDistance;
  1012. // Sort by texture too.
  1013. ri->defaultKey = ri->diffuseTex ? (uintptr_t)ri->diffuseTex : (uintptr_t)ri->vertBuff;
  1014. renderManager->addInst( ri );
  1015. }
  1016. //-----------------------------------------------------------------------------
  1017. // setSizes
  1018. //-----------------------------------------------------------------------------
  1019. void ParticleEmitter::setSizes( F32 *sizeList )
  1020. {
  1021. for( S32 i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  1022. {
  1023. sizes[i] = sizeList[i];
  1024. }
  1025. }
  1026. //-----------------------------------------------------------------------------
  1027. // setColors
  1028. //-----------------------------------------------------------------------------
  1029. void ParticleEmitter::setColors( LinearColorF *colorList )
  1030. {
  1031. for( S32 i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  1032. {
  1033. colors[i] = colorList[i];
  1034. }
  1035. }
  1036. //-----------------------------------------------------------------------------
  1037. // deleteWhenEmpty
  1038. //-----------------------------------------------------------------------------
  1039. void ParticleEmitter::deleteWhenEmpty()
  1040. {
  1041. // if the following asserts fire, there is a reasonable chance that you are trying to delete a particle emitter
  1042. // that has already been deleted (possibly by ClientMissionCleanup). If so, use a SimObjectPtr to the emitter and check it
  1043. // for null before calling this function.
  1044. AssertFatal(isProperlyAdded(), "ParticleEmitter must be registed before calling deleteWhenEmpty");
  1045. AssertFatal(!mDead, "ParticleEmitter already deleted");
  1046. AssertFatal(!isDeleted(), "ParticleEmitter already deleted");
  1047. AssertFatal(!isRemoved(), "ParticleEmitter already removed");
  1048. // this check is for non debug case, so that we don't write in to freed memory
  1049. bool okToDelete = !mDead && isProperlyAdded() && !isDeleted() && !isRemoved();
  1050. if (okToDelete)
  1051. {
  1052. mDeleteWhenEmpty = true;
  1053. if( !n_parts )
  1054. {
  1055. // We're already empty, so delete us now.
  1056. mDead = true;
  1057. deleteObject();
  1058. }
  1059. else
  1060. AssertFatal( getSceneManager() != NULL, "ParticleEmitter not on process list and won't get ticked to death" );
  1061. }
  1062. }
  1063. //-----------------------------------------------------------------------------
  1064. // emitParticles
  1065. //-----------------------------------------------------------------------------
  1066. void ParticleEmitter::emitParticles(const Point3F& point,
  1067. const bool useLastPosition,
  1068. const Point3F& axis,
  1069. const Point3F& velocity,
  1070. const U32 numMilliseconds)
  1071. {
  1072. if( mDead ) return;
  1073. // lifetime over - no more particles
  1074. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1075. {
  1076. return;
  1077. }
  1078. pos_pe = point;
  1079. Point3F realStart;
  1080. if( useLastPosition && mHasLastPosition )
  1081. realStart = mLastPosition;
  1082. else
  1083. realStart = point;
  1084. emitParticles(realStart, point,
  1085. axis,
  1086. velocity,
  1087. numMilliseconds);
  1088. }
  1089. //-----------------------------------------------------------------------------
  1090. // emitParticles
  1091. //-----------------------------------------------------------------------------
  1092. void ParticleEmitter::emitParticles(const Point3F& start,
  1093. const Point3F& end,
  1094. const Point3F& axis,
  1095. const Point3F& velocity,
  1096. const U32 numMilliseconds)
  1097. {
  1098. if( mDead ) return;
  1099. if( mDataBlock->particleDataBlocks.empty() )
  1100. return;
  1101. // lifetime over - no more particles
  1102. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1103. {
  1104. return;
  1105. }
  1106. U32 currTime = 0;
  1107. bool particlesAdded = false;
  1108. Point3F axisx;
  1109. if( mFabs(axis.z) < 0.9f )
  1110. mCross(axis, Point3F(0, 0, 1), &axisx);
  1111. else
  1112. mCross(axis, Point3F(0, 1, 0), &axisx);
  1113. axisx.normalize();
  1114. if( mNextParticleTime != 0 )
  1115. {
  1116. // Need to handle next particle
  1117. //
  1118. if( mNextParticleTime > numMilliseconds )
  1119. {
  1120. // Defer to next update
  1121. // (Note that this introduces a potential spatial irregularity if the owning
  1122. // object is accelerating, and updating at a low frequency)
  1123. //
  1124. mNextParticleTime -= numMilliseconds;
  1125. mInternalClock += numMilliseconds;
  1126. mLastPosition = end;
  1127. mHasLastPosition = true;
  1128. return;
  1129. }
  1130. else
  1131. {
  1132. currTime += mNextParticleTime;
  1133. mInternalClock += mNextParticleTime;
  1134. // Emit particle at curr time
  1135. // Create particle at the correct position
  1136. Point3F pos;
  1137. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  1138. addParticle(pos, axis, velocity, axisx, numMilliseconds-currTime);
  1139. particlesAdded = true;
  1140. mNextParticleTime = 0;
  1141. }
  1142. }
  1143. while( currTime < numMilliseconds )
  1144. {
  1145. S32 nextTime = mDataBlock->ejectionPeriodMS;
  1146. if( mDataBlock->periodVarianceMS != 0 )
  1147. {
  1148. nextTime += S32(gRandGen.randI() % (2 * mDataBlock->periodVarianceMS + 1)) -
  1149. S32(mDataBlock->periodVarianceMS);
  1150. }
  1151. AssertFatal(nextTime > 0, "Error, next particle ejection time must always be greater than 0");
  1152. if( currTime + nextTime > numMilliseconds )
  1153. {
  1154. mNextParticleTime = (currTime + nextTime) - numMilliseconds;
  1155. mInternalClock += numMilliseconds - currTime;
  1156. AssertFatal(mNextParticleTime > 0, "Error, should not have deferred this particle!");
  1157. break;
  1158. }
  1159. currTime += nextTime;
  1160. mInternalClock += nextTime;
  1161. // Create particle at the correct position
  1162. Point3F pos;
  1163. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  1164. addParticle(pos, axis, velocity, axisx, numMilliseconds-currTime);
  1165. particlesAdded = true;
  1166. // This override-advance code is restored in order to correctly adjust
  1167. // animated parameters of particles allocated within the same frame
  1168. // update. Note that ordering is important and this code correctly
  1169. // adds particles in the same newest-to-oldest ordering of the link-list.
  1170. //
  1171. // NOTE: We are assuming that the just added particle is at the head of our
  1172. // list. If that changes, so must this...
  1173. U32 advanceMS = numMilliseconds - currTime;
  1174. if (mDataBlock->overrideAdvance == false && advanceMS != 0)
  1175. {
  1176. Particle* last_part = part_list_head.next;
  1177. if (advanceMS > last_part->totalLifetime)
  1178. {
  1179. part_list_head.next = last_part->next;
  1180. n_parts--;
  1181. last_part->next = part_freelist;
  1182. part_freelist = last_part;
  1183. }
  1184. else
  1185. {
  1186. if (advanceMS != 0)
  1187. {
  1188. F32 t = F32(advanceMS) / 1000.0;
  1189. Point3F a = last_part->acc;
  1190. a -= last_part->vel * last_part->dataBlock->dragCoefficient;
  1191. a += mWindVelocity * last_part->dataBlock->windCoefficient;
  1192. //a += Point3F(0.0f, 0.0f, -9.81f) * last_part->dataBlock->gravityCoefficient;
  1193. a.z += -9.81f*last_part->dataBlock->gravityCoefficient; // as long as gravity is a constant, this is faster
  1194. last_part->vel += a * t;
  1195. //last_part->pos += last_part->vel * t;
  1196. last_part->pos_local += last_part->vel * t;
  1197. // AFX -- allow subclasses to adjust the particle params here
  1198. sub_particleUpdate(last_part);
  1199. if (last_part->dataBlock->constrain_pos)
  1200. last_part->pos = last_part->pos_local + this->pos_pe;
  1201. else
  1202. last_part->pos = last_part->pos_local;
  1203. updateKeyData( last_part );
  1204. }
  1205. }
  1206. }
  1207. }
  1208. // DMMFIX: Lame and slow...
  1209. if( particlesAdded == true )
  1210. updateBBox();
  1211. if( n_parts > 0 && getSceneManager() == NULL )
  1212. {
  1213. gClientSceneGraph->addObjectToScene(this);
  1214. ClientProcessList::get()->addObject(this);
  1215. }
  1216. mLastPosition = end;
  1217. mHasLastPosition = true;
  1218. }
  1219. //-----------------------------------------------------------------------------
  1220. // emitParticles
  1221. //-----------------------------------------------------------------------------
  1222. void ParticleEmitter::emitParticles(const Point3F& rCenter,
  1223. const Point3F& rNormal,
  1224. const F32 radius,
  1225. const Point3F& velocity,
  1226. S32 count)
  1227. {
  1228. if( mDead ) return;
  1229. // lifetime over - no more particles
  1230. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1231. {
  1232. return;
  1233. }
  1234. Point3F axisx, axisy;
  1235. Point3F axisz = rNormal;
  1236. if( axisz.isZero() )
  1237. {
  1238. axisz.set( 0.0, 0.0, 1.0 );
  1239. }
  1240. if( mFabs(axisz.z) < 0.98 )
  1241. {
  1242. mCross(axisz, Point3F(0, 0, 1), &axisy);
  1243. axisy.normalize();
  1244. }
  1245. else
  1246. {
  1247. mCross(axisz, Point3F(0, 1, 0), &axisy);
  1248. axisy.normalize();
  1249. }
  1250. mCross(axisz, axisy, &axisx);
  1251. axisx.normalize();
  1252. // Should think of a better way to distribute the
  1253. // particles within the hemisphere.
  1254. for( S32 i = 0; i < count; i++ )
  1255. {
  1256. Point3F pos = axisx * (radius * (1 - (2 * gRandGen.randF())));
  1257. pos += axisy * (radius * (1 - (2 * gRandGen.randF())));
  1258. pos += axisz * (radius * gRandGen.randF());
  1259. Point3F axis = pos;
  1260. axis.normalize();
  1261. pos += rCenter;
  1262. addParticle(pos, axis, velocity, axisz, 0);
  1263. }
  1264. // Set world bounding box
  1265. mObjBox.minExtents = rCenter - Point3F(radius, radius, radius);
  1266. mObjBox.maxExtents = rCenter + Point3F(radius, radius, radius);
  1267. resetWorldBox();
  1268. // Make sure we're part of the world
  1269. if( n_parts > 0 && getSceneManager() == NULL )
  1270. {
  1271. gClientSceneGraph->addObjectToScene(this);
  1272. ClientProcessList::get()->addObject(this);
  1273. }
  1274. mHasLastPosition = false;
  1275. }
  1276. //-----------------------------------------------------------------------------
  1277. // updateBBox - SLOW, bad news
  1278. //-----------------------------------------------------------------------------
  1279. void ParticleEmitter::updateBBox()
  1280. {
  1281. if (forced_bbox)
  1282. return;
  1283. Point3F minPt(1e10, 1e10, 1e10);
  1284. Point3F maxPt(-1e10, -1e10, -1e10);
  1285. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1286. {
  1287. Point3F particleSize(part->size * 0.5f, 0.0f, part->size * 0.5f);
  1288. minPt.setMin( part->pos - particleSize );
  1289. maxPt.setMax( part->pos + particleSize );
  1290. }
  1291. mObjBox = Box3F(minPt, maxPt);
  1292. MatrixF temp = getTransform();
  1293. setTransform(temp);
  1294. mBBObjToWorld.identity();
  1295. Point3F boxScale = mObjBox.getExtents();
  1296. boxScale.x = getMax(boxScale.x, 1.0f);
  1297. boxScale.y = getMax(boxScale.y, 1.0f);
  1298. boxScale.z = getMax(boxScale.z, 1.0f);
  1299. mBBObjToWorld.scale(boxScale);
  1300. #if defined(AFX_CAP_PARTICLE_POOLS)
  1301. if (pool)
  1302. pool->updatePoolBBox(this);
  1303. #endif
  1304. }
  1305. //-----------------------------------------------------------------------------
  1306. // addParticle
  1307. //-----------------------------------------------------------------------------
  1308. void ParticleEmitter::addParticle(const Point3F& pos, const Point3F& axis, const Point3F& vel,
  1309. const Point3F& axisx, const U32 age_offset)
  1310. {
  1311. n_parts++;
  1312. if (n_parts > n_part_capacity || n_parts > mDataBlock->partListInitSize)
  1313. {
  1314. // In an emergency we allocate additional particles in blocks of 16.
  1315. // This should happen rarely.
  1316. Particle* store_block = new Particle[16];
  1317. part_store.push_back(store_block);
  1318. n_part_capacity += 16;
  1319. for (S32 i = 0; i < 16; i++)
  1320. {
  1321. store_block[i].next = part_freelist;
  1322. part_freelist = &store_block[i];
  1323. }
  1324. mDataBlock->allocPrimBuffer(n_part_capacity); // allocate larger primitive buffer or will crash
  1325. }
  1326. Particle* pNew = part_freelist;
  1327. part_freelist = pNew->next;
  1328. pNew->next = part_list_head.next;
  1329. part_list_head.next = pNew;
  1330. // for earlier access to constrain_pos, the ParticleData datablock is chosen here instead
  1331. // of later in the method.
  1332. U32 dBlockIndex = gRandGen.randI() % mDataBlock->particleDataBlocks.size();
  1333. ParticleData* part_db = mDataBlock->particleDataBlocks[dBlockIndex];
  1334. // set start position to world or local space
  1335. Point3F pos_start;
  1336. if (part_db->constrain_pos)
  1337. pos_start.set(0,0,0);
  1338. else
  1339. pos_start = pos;
  1340. Point3F ejectionAxis = axis;
  1341. F32 theta = (mDataBlock->thetaMax - mDataBlock->thetaMin) * gRandGen.randF() +
  1342. mDataBlock->thetaMin;
  1343. F32 ref = (F32(mInternalClock) / 1000.0) * mDataBlock->phiReferenceVel;
  1344. F32 phi = ref + gRandGen.randF() * mDataBlock->phiVariance;
  1345. // Both phi and theta are in degs. Create axis angles out of them, and create the
  1346. // appropriate rotation matrix...
  1347. AngAxisF thetaRot(axisx, theta * (M_PI / 180.0));
  1348. AngAxisF phiRot(axis, phi * (M_PI / 180.0));
  1349. MatrixF temp(true);
  1350. thetaRot.setMatrix(&temp);
  1351. temp.mulP(ejectionAxis);
  1352. phiRot.setMatrix(&temp);
  1353. temp.mulP(ejectionAxis);
  1354. F32 initialVel = mDataBlock->ejectionVelocity;
  1355. initialVel += (mDataBlock->velocityVariance * 2.0f * gRandGen.randF()) - mDataBlock->velocityVariance;
  1356. pNew->pos = pos_start + (ejectionAxis * (mDataBlock->ejectionOffset + mDataBlock->ejectionOffsetVariance* gRandGen.randF()) );
  1357. pNew->pos_local = pNew->pos;
  1358. pNew->vel = mDataBlock->ejectionInvert ? ejectionAxis * -initialVel : ejectionAxis * initialVel;
  1359. if (mDataBlock->orientParticles)
  1360. pNew->orientDir = ejectionAxis;
  1361. else
  1362. // note -- for non-oriented particles, we use orientDir.x to store the billboard start angle.
  1363. pNew->orientDir.x = mDegToRad(part_db->start_angle + part_db->angle_variance*2.0f*gRandGen.randF() - part_db->angle_variance);
  1364. pNew->acc.set(0, 0, 0);
  1365. pNew->currentAge = age_offset;
  1366. pNew->t_last = 0.0f;
  1367. mDataBlock->particleDataBlocks[dBlockIndex]->initializeParticle(pNew, vel);
  1368. updateKeyData( pNew );
  1369. }
  1370. //-----------------------------------------------------------------------------
  1371. // processTick
  1372. //-----------------------------------------------------------------------------
  1373. void ParticleEmitter::processTick(const Move*)
  1374. {
  1375. if( mDeleteOnTick == true )
  1376. {
  1377. mDead = true;
  1378. deleteObject();
  1379. }
  1380. }
  1381. //-----------------------------------------------------------------------------
  1382. // advanceTime
  1383. //-----------------------------------------------------------------------------
  1384. void ParticleEmitter::advanceTime(F32 dt)
  1385. {
  1386. if( dt < 0.00001 ) return;
  1387. Parent::advanceTime(dt);
  1388. if( dt > 0.5 ) dt = 0.5;
  1389. if( mDead ) return;
  1390. mElapsedTimeMS += (S32)(dt * 1000.0f);
  1391. U32 numMSToUpdate = (U32)(dt * 1000.0f);
  1392. if( numMSToUpdate == 0 ) return;
  1393. // TODO: Prefetch
  1394. // remove dead particles
  1395. Particle* last_part = &part_list_head;
  1396. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1397. {
  1398. part->currentAge += numMSToUpdate;
  1399. if (part->currentAge > part->totalLifetime)
  1400. {
  1401. n_parts--;
  1402. last_part->next = part->next;
  1403. part->next = part_freelist;
  1404. part_freelist = part;
  1405. part = last_part;
  1406. }
  1407. else
  1408. {
  1409. last_part = part;
  1410. }
  1411. }
  1412. AssertFatal( n_parts >= 0, "ParticleEmitter: negative part count!" );
  1413. if (n_parts < 1 && mDeleteWhenEmpty)
  1414. {
  1415. mDeleteOnTick = true;
  1416. return;
  1417. }
  1418. if( numMSToUpdate != 0 && n_parts > 0 )
  1419. {
  1420. update( numMSToUpdate );
  1421. }
  1422. }
  1423. //-----------------------------------------------------------------------------
  1424. // Update key related particle data
  1425. //-----------------------------------------------------------------------------
  1426. void ParticleEmitter::updateKeyData( Particle *part )
  1427. {
  1428. //Ensure that our lifetime is never below 0
  1429. if( part->totalLifetime < 1 )
  1430. part->totalLifetime = 1;
  1431. if (part->currentAge > part->totalLifetime)
  1432. part->currentAge = part->totalLifetime;
  1433. F32 t = (F32)part->currentAge / (F32)part->totalLifetime;
  1434. for( U32 i = 1; i < ParticleData::PDC_NUM_KEYS; i++ )
  1435. {
  1436. if( part->dataBlock->times[i] >= t )
  1437. {
  1438. F32 firstPart = t - part->dataBlock->times[i-1];
  1439. F32 total = part->dataBlock->times[i] -
  1440. part->dataBlock->times[i-1];
  1441. firstPart /= total;
  1442. if( mDataBlock->useEmitterColors )
  1443. {
  1444. part->color.interpolate(colors[i-1], colors[i], firstPart);
  1445. }
  1446. else
  1447. {
  1448. part->color.interpolate(part->dataBlock->colors[i-1],
  1449. part->dataBlock->colors[i],
  1450. firstPart);
  1451. }
  1452. if( mDataBlock->useEmitterSizes )
  1453. {
  1454. part->size = (sizes[i-1] * (1.0 - firstPart)) +
  1455. (sizes[i] * firstPart);
  1456. }
  1457. else
  1458. {
  1459. part->size = (part->dataBlock->sizes[i-1] * (1.0 - firstPart)) +
  1460. (part->dataBlock->sizes[i] * firstPart);
  1461. part->size *= part->dataBlock->sizeBias;
  1462. }
  1463. if (mDataBlock->fade_color)
  1464. {
  1465. if (mDataBlock->fade_alpha)
  1466. part->color *= fade_amt;
  1467. else
  1468. {
  1469. part->color.red *= fade_amt;
  1470. part->color.green *= fade_amt;
  1471. part->color.blue *= fade_amt;
  1472. }
  1473. }
  1474. else if (mDataBlock->fade_alpha)
  1475. part->color.alpha *= fade_amt;
  1476. if (mDataBlock->fade_size)
  1477. part->size *= fade_amt;
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. //-----------------------------------------------------------------------------
  1483. // Update particles
  1484. //-----------------------------------------------------------------------------
  1485. void ParticleEmitter::update( U32 ms )
  1486. {
  1487. F32 t = F32(ms)/1000.0f; // AFX -- moved outside loop, no need to recalculate this for every particle
  1488. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1489. {
  1490. Point3F a = part->acc;
  1491. a -= part->vel * part->dataBlock->dragCoefficient;
  1492. a += mWindVelocity * part->dataBlock->windCoefficient;
  1493. a.z += -9.81f*part->dataBlock->gravityCoefficient; // AFX -- as long as gravity is a constant, this is faster
  1494. part->vel += a * t;
  1495. part->pos_local += part->vel * t;
  1496. // AFX -- allow subclasses to adjust the particle params here
  1497. sub_particleUpdate(part);
  1498. if (part->dataBlock->constrain_pos)
  1499. part->pos = part->pos_local + this->pos_pe;
  1500. else
  1501. part->pos = part->pos_local;
  1502. updateKeyData( part );
  1503. }
  1504. }
  1505. //-----------------------------------------------------------------------------
  1506. // Copy particles to vertex buffer
  1507. //-----------------------------------------------------------------------------
  1508. // structure used for particle sorting.
  1509. struct SortParticle
  1510. {
  1511. Particle* p;
  1512. F32 k;
  1513. };
  1514. // qsort callback function for particle sorting
  1515. S32 QSORT_CALLBACK cmpSortParticles(const void* p1, const void* p2)
  1516. {
  1517. const SortParticle* sp1 = (const SortParticle*)p1;
  1518. const SortParticle* sp2 = (const SortParticle*)p2;
  1519. if (sp2->k > sp1->k)
  1520. return 1;
  1521. else if (sp2->k == sp1->k)
  1522. return 0;
  1523. else
  1524. return -1;
  1525. }
  1526. void ParticleEmitter::copyToVB( const Point3F &camPos, const LinearColorF &ambientColor )
  1527. {
  1528. static Vector<SortParticle> orderedVector(__FILE__, __LINE__);
  1529. PROFILE_START(ParticleEmitter_copyToVB);
  1530. PROFILE_START(ParticleEmitter_copyToVB_Sort);
  1531. // build sorted list of particles (far to near)
  1532. if (mDataBlock->sortParticles)
  1533. {
  1534. orderedVector.clear();
  1535. MatrixF modelview = GFX->getWorldMatrix();
  1536. Point3F viewvec; modelview.getRow(1, &viewvec);
  1537. // add each particle and a distance based sort key to orderedVector
  1538. for (Particle* pp = part_list_head.next; pp != NULL; pp = pp->next)
  1539. {
  1540. orderedVector.increment();
  1541. orderedVector.last().p = pp;
  1542. orderedVector.last().k = mDot(pp->pos, viewvec);
  1543. }
  1544. // qsort the list into far to near ordering
  1545. dQsort(orderedVector.address(), orderedVector.size(), sizeof(SortParticle), cmpSortParticles);
  1546. }
  1547. PROFILE_END();
  1548. static Vector<ParticleVertexType> tempBuff(2048);
  1549. tempBuff.reserve( n_parts*4 + 64); // make sure tempBuff is big enough
  1550. ParticleVertexType *buffPtr = tempBuff.address(); // use direct pointer (faster)
  1551. if (mDataBlock->orientParticles)
  1552. {
  1553. PROFILE_START(ParticleEmitter_copyToVB_Orient);
  1554. if (mDataBlock->reverseOrder)
  1555. {
  1556. buffPtr += 4*(n_parts-1);
  1557. // do sorted-oriented particles
  1558. if (mDataBlock->sortParticles)
  1559. {
  1560. SortParticle* partPtr = orderedVector.address();
  1561. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1562. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1563. }
  1564. // do unsorted-oriented particles
  1565. else
  1566. {
  1567. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1568. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1569. }
  1570. }
  1571. else
  1572. {
  1573. // do sorted-oriented particles
  1574. if (mDataBlock->sortParticles)
  1575. {
  1576. SortParticle* partPtr = orderedVector.address();
  1577. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1578. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1579. }
  1580. // do unsorted-oriented particles
  1581. else
  1582. {
  1583. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1584. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1585. }
  1586. }
  1587. PROFILE_END();
  1588. }
  1589. else if (mDataBlock->alignParticles)
  1590. {
  1591. PROFILE_START(ParticleEmitter_copyToVB_Aligned);
  1592. if (mDataBlock->reverseOrder)
  1593. {
  1594. buffPtr += 4*(n_parts-1);
  1595. // do sorted-oriented particles
  1596. if (mDataBlock->sortParticles)
  1597. {
  1598. SortParticle* partPtr = orderedVector.address();
  1599. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1600. setupAligned(partPtr->p, ambientColor, buffPtr);
  1601. }
  1602. // do unsorted-oriented particles
  1603. else
  1604. {
  1605. Particle *partPtr = part_list_head.next;
  1606. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1607. setupAligned(partPtr, ambientColor, buffPtr);
  1608. }
  1609. }
  1610. else
  1611. {
  1612. // do sorted-oriented particles
  1613. if (mDataBlock->sortParticles)
  1614. {
  1615. SortParticle* partPtr = orderedVector.address();
  1616. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1617. setupAligned(partPtr->p, ambientColor, buffPtr);
  1618. }
  1619. // do unsorted-oriented particles
  1620. else
  1621. {
  1622. Particle *partPtr = part_list_head.next;
  1623. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1624. setupAligned(partPtr, ambientColor, buffPtr);
  1625. }
  1626. }
  1627. PROFILE_END();
  1628. }
  1629. else
  1630. {
  1631. PROFILE_START(ParticleEmitter_copyToVB_NonOriented);
  1632. // somewhat odd ordering so that texture coordinates match the oriented
  1633. // particles
  1634. Point3F basePoints[4];
  1635. basePoints[0] = Point3F(-1.0, 0.0, 1.0);
  1636. basePoints[1] = Point3F(-1.0, 0.0, -1.0);
  1637. basePoints[2] = Point3F( 1.0, 0.0, -1.0);
  1638. basePoints[3] = Point3F( 1.0, 0.0, 1.0);
  1639. MatrixF camView = GFX->getWorldMatrix();
  1640. camView.transpose(); // inverse - this gets the particles facing camera
  1641. if (mDataBlock->reverseOrder)
  1642. {
  1643. buffPtr += 4*(n_parts-1);
  1644. // do sorted-billboard particles
  1645. if (mDataBlock->sortParticles)
  1646. {
  1647. SortParticle *partPtr = orderedVector.address();
  1648. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr-=4 )
  1649. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1650. }
  1651. // do unsorted-billboard particles
  1652. else
  1653. {
  1654. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1655. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1656. }
  1657. }
  1658. else
  1659. {
  1660. // do sorted-billboard particles
  1661. if (mDataBlock->sortParticles)
  1662. {
  1663. SortParticle *partPtr = orderedVector.address();
  1664. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr+=4 )
  1665. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1666. }
  1667. // do unsorted-billboard particles
  1668. else
  1669. {
  1670. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1671. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1672. }
  1673. }
  1674. PROFILE_END();
  1675. }
  1676. PROFILE_START(ParticleEmitter_copyToVB_LockCopy);
  1677. // create new VB if emitter size grows
  1678. if( !mVertBuff || n_parts > mCurBuffSize )
  1679. {
  1680. mCurBuffSize = n_parts;
  1681. mVertBuff.set( GFX, n_parts * 4, GFXBufferTypeDynamic );
  1682. }
  1683. // lock and copy tempBuff to video RAM
  1684. ParticleVertexType *verts = mVertBuff.lock();
  1685. dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(ParticleVertexType) );
  1686. mVertBuff.unlock();
  1687. PROFILE_END();
  1688. PROFILE_END();
  1689. }
  1690. //-----------------------------------------------------------------------------
  1691. // Set up particle for billboard style render
  1692. //-----------------------------------------------------------------------------
  1693. void ParticleEmitter::setupBillboard( Particle *part,
  1694. Point3F *basePts,
  1695. const MatrixF &camView,
  1696. const LinearColorF &ambientColor,
  1697. ParticleVertexType *lVerts )
  1698. {
  1699. F32 width = part->size * 0.5f;
  1700. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1701. F32 sy, cy;
  1702. mSinCos(spinAngle, sy, cy);
  1703. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1704. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1705. // fill four verts, use macro and unroll loop
  1706. #define fillVert(){ \
  1707. lVerts->point.x = cy * basePts->x - sy * basePts->z; \
  1708. lVerts->point.y = 0.0f; \
  1709. lVerts->point.z = sy * basePts->x + cy * basePts->z; \
  1710. camView.mulV( lVerts->point ); \
  1711. lVerts->point *= width; \
  1712. lVerts->point += part->pos; \
  1713. lVerts->color = partCol.toColorI(); } \
  1714. // Here we deal with UVs for animated particle (billboard)
  1715. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1716. {
  1717. S32 fm = (S32)(part->currentAge*(1.0/1000.0)*part->dataBlock->framesPerSec);
  1718. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1719. S32 uv[4];
  1720. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1721. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1722. uv[2] = uv[1] + 1;
  1723. uv[3] = uv[0] + 1;
  1724. fillVert();
  1725. // Here and below, we copy UVs from particle datablock's current frame's UVs (billboard)
  1726. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1727. ++lVerts;
  1728. ++basePts;
  1729. fillVert();
  1730. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1731. ++lVerts;
  1732. ++basePts;
  1733. fillVert();
  1734. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1735. ++lVerts;
  1736. ++basePts;
  1737. fillVert();
  1738. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1739. ++lVerts;
  1740. ++basePts;
  1741. return;
  1742. }
  1743. fillVert();
  1744. // Here and below, we copy UVs from particle datablock's texCoords (billboard)
  1745. lVerts->texCoord = part->dataBlock->texCoords[0];
  1746. ++lVerts;
  1747. ++basePts;
  1748. fillVert();
  1749. lVerts->texCoord = part->dataBlock->texCoords[1];
  1750. ++lVerts;
  1751. ++basePts;
  1752. fillVert();
  1753. lVerts->texCoord = part->dataBlock->texCoords[2];
  1754. ++lVerts;
  1755. ++basePts;
  1756. fillVert();
  1757. lVerts->texCoord = part->dataBlock->texCoords[3];
  1758. ++lVerts;
  1759. ++basePts;
  1760. }
  1761. //-----------------------------------------------------------------------------
  1762. // Set up oriented particle
  1763. //-----------------------------------------------------------------------------
  1764. void ParticleEmitter::setupOriented( Particle *part,
  1765. const Point3F &camPos,
  1766. const LinearColorF &ambientColor,
  1767. ParticleVertexType *lVerts )
  1768. {
  1769. Point3F dir;
  1770. if( mDataBlock->orientOnVelocity )
  1771. {
  1772. // don't render oriented particle if it has no velocity
  1773. if( part->vel.magnitudeSafe() == 0.0 ) return;
  1774. dir = part->vel;
  1775. }
  1776. else
  1777. {
  1778. dir = part->orientDir;
  1779. }
  1780. Point3F dirFromCam = part->pos - camPos;
  1781. Point3F crossDir;
  1782. mCross( dirFromCam, dir, &crossDir );
  1783. crossDir.normalize();
  1784. dir.normalize();
  1785. F32 width = part->size * 0.5f;
  1786. dir *= width;
  1787. crossDir *= width;
  1788. Point3F start = part->pos - dir;
  1789. Point3F end = part->pos + dir;
  1790. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1791. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1792. const ColorI color = partCol.toColorI();
  1793. // Here we deal with UVs for animated particle (oriented)
  1794. if (part->dataBlock->animateTexture)
  1795. {
  1796. // Let particle compute the UV indices for current frame
  1797. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1798. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1799. S32 uv[4];
  1800. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1801. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1802. uv[2] = uv[1] + 1;
  1803. uv[3] = uv[0] + 1;
  1804. lVerts->point = start + crossDir;
  1805. lVerts->color = color;
  1806. // Here and below, we copy UVs from particle datablock's current frame's UVs (oriented)
  1807. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1808. ++lVerts;
  1809. lVerts->point = start - crossDir;
  1810. lVerts->color = color;
  1811. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1812. ++lVerts;
  1813. lVerts->point = end - crossDir;
  1814. lVerts->color = color;
  1815. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1816. ++lVerts;
  1817. lVerts->point = end + crossDir;
  1818. lVerts->color = color;
  1819. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1820. ++lVerts;
  1821. return;
  1822. }
  1823. lVerts->point = start + crossDir;
  1824. lVerts->color = color;
  1825. // Here and below, we copy UVs from particle datablock's texCoords (oriented)
  1826. lVerts->texCoord = part->dataBlock->texCoords[1];
  1827. ++lVerts;
  1828. lVerts->point = start - crossDir;
  1829. lVerts->color = color;
  1830. lVerts->texCoord = part->dataBlock->texCoords[2];
  1831. ++lVerts;
  1832. lVerts->point = end - crossDir;
  1833. lVerts->color = color;
  1834. lVerts->texCoord = part->dataBlock->texCoords[3];
  1835. ++lVerts;
  1836. lVerts->point = end + crossDir;
  1837. lVerts->color = color;
  1838. lVerts->texCoord = part->dataBlock->texCoords[0];
  1839. ++lVerts;
  1840. }
  1841. void ParticleEmitter::setupAligned( const Particle *part,
  1842. const LinearColorF &ambientColor,
  1843. ParticleVertexType *lVerts )
  1844. {
  1845. // The aligned direction will always be normalized.
  1846. Point3F dir = mDataBlock->alignDirection;
  1847. // Find a right vector for this particle.
  1848. Point3F right;
  1849. if (mFabs(dir.y) > mFabs(dir.z))
  1850. mCross(Point3F::UnitZ, dir, &right);
  1851. else
  1852. mCross(Point3F::UnitY, dir, &right);
  1853. right.normalize();
  1854. // If we have a spin velocity.
  1855. if ( !mIsZero( part->spinSpeed ) )
  1856. {
  1857. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1858. // This is an inline quaternion vector rotation which
  1859. // is faster that QuatF.mulP(), but generates different
  1860. // results and hence cannot replace it right now.
  1861. F32 sin, qw;
  1862. mSinCos( spinAngle * 0.5f, sin, qw );
  1863. F32 qx = dir.x * sin;
  1864. F32 qy = dir.y * sin;
  1865. F32 qz = dir.z * sin;
  1866. F32 vx = ( right.x * qw ) + ( right.z * qy ) - ( right.y * qz );
  1867. F32 vy = ( right.y * qw ) + ( right.x * qz ) - ( right.z * qx );
  1868. F32 vz = ( right.z * qw ) + ( right.y * qx ) - ( right.x * qy );
  1869. F32 vw = ( right.x * qx ) + ( right.y * qy ) + ( right.z * qz );
  1870. right.x = ( qw * vx ) + ( qx * vw ) + ( qy * vz ) - ( qz * vy );
  1871. right.y = ( qw * vy ) + ( qy * vw ) + ( qz * vx ) - ( qx * vz );
  1872. right.z = ( qw * vz ) + ( qz * vw ) + ( qx * vy ) - ( qy * vx );
  1873. }
  1874. // Get the cross vector.
  1875. Point3F cross;
  1876. mCross(right, dir, &cross);
  1877. F32 width = part->size * 0.5f;
  1878. right *= width;
  1879. cross *= width;
  1880. Point3F start = part->pos - right;
  1881. Point3F end = part->pos + right;
  1882. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1883. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1884. const ColorI color = partCol.toColorI();
  1885. // Here we deal with UVs for animated particle
  1886. if (part->dataBlock->animateTexture)
  1887. {
  1888. // Let particle compute the UV indices for current frame
  1889. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1890. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1891. S32 uv[4];
  1892. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1893. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1894. uv[2] = uv[1] + 1;
  1895. uv[3] = uv[0] + 1;
  1896. lVerts->point = start + cross;
  1897. lVerts->color = color;
  1898. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1899. ++lVerts;
  1900. lVerts->point = start - cross;
  1901. lVerts->color = color;
  1902. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1903. ++lVerts;
  1904. lVerts->point = end - cross;
  1905. lVerts->color = color;
  1906. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1907. ++lVerts;
  1908. lVerts->point = end + cross;
  1909. lVerts->color = color;
  1910. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1911. ++lVerts;
  1912. }
  1913. else
  1914. {
  1915. // Here and below, we copy UVs from particle datablock's texCoords
  1916. lVerts->point = start + cross;
  1917. lVerts->color = color;
  1918. lVerts->texCoord = part->dataBlock->texCoords[0];
  1919. ++lVerts;
  1920. lVerts->point = start - cross;
  1921. lVerts->color = color;
  1922. lVerts->texCoord = part->dataBlock->texCoords[1];
  1923. ++lVerts;
  1924. lVerts->point = end - cross;
  1925. lVerts->color = color;
  1926. lVerts->texCoord = part->dataBlock->texCoords[2];
  1927. ++lVerts;
  1928. lVerts->point = end + cross;
  1929. lVerts->color = color;
  1930. lVerts->texCoord = part->dataBlock->texCoords[3];
  1931. ++lVerts;
  1932. }
  1933. }
  1934. bool ParticleEmitterData::reload()
  1935. {
  1936. // Clear out current particle data.
  1937. dataBlockIds.clear();
  1938. particleDataBlocks.clear();
  1939. // Parse out particle string.
  1940. U32 numUnits = 0;
  1941. if( particleString )
  1942. numUnits = StringUnit::getUnitCount( particleString, " \t" );
  1943. if( !particleString || !particleString[ 0 ] || !numUnits )
  1944. {
  1945. Con::errorf( "ParticleEmitterData(%s) has an empty particles string.", getName() );
  1946. mReloadSignal.trigger();
  1947. return false;
  1948. }
  1949. for( U32 i = 0; i < numUnits; ++ i )
  1950. {
  1951. const char* dbName = StringUnit::getUnit( particleString, i, " \t" );
  1952. ParticleData* data = NULL;
  1953. if( !Sim::findObject( dbName, data ) )
  1954. {
  1955. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dbName );
  1956. continue;
  1957. }
  1958. particleDataBlocks.push_back( data );
  1959. dataBlockIds.push_back( data->getId() );
  1960. }
  1961. // Check that we actually found some particle datablocks.
  1962. if( particleDataBlocks.empty() )
  1963. {
  1964. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName() );
  1965. mReloadSignal.trigger();
  1966. return false;
  1967. }
  1968. // Trigger reload.
  1969. mReloadSignal.trigger();
  1970. return true;
  1971. }
  1972. DefineEngineMethod(ParticleEmitterData, reload, void,(),,
  1973. "Reloads the ParticleData datablocks and other fields used by this emitter.\n"
  1974. "@tsexample\n"
  1975. "// Get the editor's current particle emitter\n"
  1976. "%emitter = PE_EmitterEditor.currEmitter\n\n"
  1977. "// Change a field value\n"
  1978. "%emitter.setFieldValue( %propertyField, %value );\n\n"
  1979. "// Reload this emitter\n"
  1980. "%emitter.reload();\n"
  1981. "@endtsexample\n")
  1982. {
  1983. object->reload();
  1984. }
  1985. void ParticleEmitter::emitParticlesExt(const MatrixF& xfm, const Point3F& point,
  1986. const Point3F& velocity, const U32 numMilliseconds)
  1987. {
  1988. if (mDataBlock->use_emitter_xfm)
  1989. {
  1990. Point3F zero_point(0.0f, 0.0f, 0.0f);
  1991. this->pos_pe = zero_point;
  1992. this->setTransform(xfm);
  1993. Point3F axis(0.0,0.0,1.0);
  1994. xfm.mulV(axis);
  1995. emitParticles(zero_point, true, axis, velocity, numMilliseconds);
  1996. }
  1997. else
  1998. {
  1999. this->pos_pe = point;
  2000. Point3F axis(0.0,0.0,1.0);
  2001. xfm.mulV(axis);
  2002. emitParticles(point, true, axis, velocity, numMilliseconds);
  2003. }
  2004. }
  2005. void ParticleEmitter::setForcedObjBox(Box3F& box)
  2006. {
  2007. mObjBox = box;
  2008. forced_bbox = true;
  2009. #if defined(AFX_CAP_PARTICLE_POOLS)
  2010. if (pool)
  2011. pool->updatePoolBBox(this);
  2012. #endif
  2013. }
  2014. void ParticleEmitter::setSortPriority(S8 priority)
  2015. {
  2016. sort_priority = (priority == 0) ? 1 : priority;
  2017. #if defined(AFX_CAP_PARTICLE_POOLS)
  2018. if (pool)
  2019. pool->setSortPriority(sort_priority);
  2020. #endif
  2021. }