particleEmitter.cpp 89 KB

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