particleEmitter.cpp 89 KB

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