particleEmitter.cpp 68 KB

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