explosion.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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/explosion.h"
  28. #include "core/resourceManager.h"
  29. #include "console/consoleTypes.h"
  30. #include "console/typeValidators.h"
  31. #include "sfx/sfxSystem.h"
  32. #include "sfx/sfxTrack.h"
  33. #include "sfx/sfxTypes.h"
  34. #include "scene/sceneManager.h"
  35. #include "scene/sceneRenderState.h"
  36. #include "lighting/lightInfo.h"
  37. #include "lighting/lightManager.h"
  38. #include "core/stream/bitStream.h"
  39. #include "sim/netConnection.h"
  40. #include "ts/tsShape.h"
  41. #include "ts/tsShapeInstance.h"
  42. #include "math/mRandom.h"
  43. #include "math/mathIO.h"
  44. #include "math/mathUtils.h"
  45. #include "T3D/debris.h"
  46. #include "T3D/gameBase/gameConnection.h"
  47. #include "T3D/fx/particleEmitter.h"
  48. #include "T3D/fx/cameraFXMgr.h"
  49. #include "T3D/debris.h"
  50. #include "T3D/shapeBase.h"
  51. #include "T3D/gameBase/gameProcess.h"
  52. #include "renderInstance/renderPassManager.h"
  53. #include "console/engineAPI.h"
  54. #include "sfx/sfxProfile.h"
  55. IMPLEMENT_CONOBJECT(Explosion);
  56. ConsoleDocClass( Explosion,
  57. "@brief The emitter for an explosion effect, with properties defined by a "
  58. "ExplosionData object.\n\n"
  59. "@ingroup FX\n"
  60. "The object will initiate the explosion effects automatically after being "
  61. "added to the simulation.\n"
  62. "@tsexample\n"
  63. "datablock ExplosionData( GrenadeSubExplosion )\n"
  64. "{\n"
  65. " offset = 0.25;\n"
  66. " emitter[0] = GrenadeExpSparkEmitter;\n\n"
  67. " lightStartRadius = 4.0;\n"
  68. " lightEndRadius = 0.0;\n"
  69. " lightStartColor = \"0.9 0.7 0.7\";\n"
  70. " lightEndColor = \"0.9 0.7 0.7\";\n"
  71. " lightStartBrightness = 2.0;\n"
  72. " lightEndBrightness = 0.0;\n"
  73. "};\n\n"
  74. "datablock ExplosionData( GrenadeLauncherExplosion )\n"
  75. "{\n"
  76. " soundProfile = GrenadeLauncherExplosionSound;\n"
  77. " lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal\n\n"
  78. " // Volume particles\n"
  79. " particleEmitter = GrenadeExpFireEmitter;\n"
  80. " particleDensity = 75;\n"
  81. " particleRadius = 2.25;\n\n"
  82. " // Point emission\n"
  83. " emitter[0] = GrenadeExpDustEmitter;\n"
  84. " emitter[1] = GrenadeExpSparksEmitter;\n"
  85. " emitter[2] = GrenadeExpSmokeEmitter;\n\n"
  86. " // Sub explosion objects\n"
  87. " subExplosion[0] = GrenadeSubExplosion;\n\n"
  88. " // Camera Shaking\n"
  89. " shakeCamera = true;\n"
  90. " camShakeFreq = \"10.0 11.0 9.0\";\n"
  91. " camShakeAmp = \"15.0 15.0 15.0\";\n"
  92. " camShakeDuration = 1.5;\n"
  93. " camShakeRadius = 20;\n\n"
  94. " // Exploding debris\n"
  95. " debris = GrenadeDebris;\n"
  96. " debrisThetaMin = 10;\n"
  97. " debrisThetaMax = 60;\n"
  98. " debrisNum = 4;\n"
  99. " debrisNumVariance = 2;\n"
  100. " debrisVelocity = 25;\n"
  101. " debrisVelocityVariance = 5;\n\n"
  102. " lightStartRadius = 4.0;\n"
  103. " lightEndRadius = 0.0;\n"
  104. " lightStartColor = \"1.0 1.0 1.0\";\n"
  105. " lightEndColor = \"1.0 1.0 1.0\";\n"
  106. " lightStartBrightness = 4.0;\n"
  107. " lightEndBrightness = 0.0;\n"
  108. " lightNormalOffset = 2.0;\n"
  109. "};\n\n"
  110. "function ServerPlayExplosion(%position, %datablock)\n"
  111. "{\n"
  112. " // Play the given explosion on every client.\n"
  113. " // The explosion will be transmitted as an event, not attached to any object.\n"
  114. " for(%idx = 0; %idx < ClientGroup.getCount(); %idx++)\n"
  115. " {\n"
  116. " %client = ClientGroup.getObject(%idx);\n"
  117. " commandToClient(%client, 'PlayExplosion', %position, %datablock.getId());\n"
  118. " }\n"
  119. "}\n\n"
  120. "function clientCmdPlayExplosion(%position, %effectDataBlock)\n"
  121. "{\n"
  122. " // Play an explosion sent by the server. Make sure this function is defined\n"
  123. " // on the client.\n"
  124. " if (isObject(%effectDataBlock))\n"
  125. " {\n"
  126. " new Explosion()\n"
  127. " {\n"
  128. " position = %position;\n"
  129. " dataBlock = %effectDataBlock;\n"
  130. " };\n"
  131. " }\n"
  132. "}\n\n"
  133. "// schedule an explosion\n"
  134. "schedule(1000, 0, ServerPlayExplosion, \"0 0 0\", GrenadeLauncherExplosion);\n"
  135. "@endtsexample"
  136. );
  137. #define MaxLightRadius 20
  138. MRandomLCG sgRandom(0xdeadbeef);
  139. //WLE - Vince - The defaults are bad, the whole point of calling this function\
  140. //is to determine the explosion coverage on a object. Why would you want them
  141. //To call this with a null for the ID? In fact, it just returns a 1f if
  142. //it can't find the object. Seems useless to me. Cause how can I apply
  143. //damage to a object that doesn't exist?
  144. //I could possible see a use with passing in a null covMask, but even that
  145. //sounds flaky because it will be 100 percent if your saying not to take
  146. //any thing in consideration for coverage. So I'm removing these defaults they are just bad.
  147. DefineEngineFunction(calcExplosionCoverage, F32, (Point3F pos, S32 id, U32 covMask),,
  148. "@brief Calculates how much an explosion effects a specific object.\n\n"
  149. "Use this to determine how much damage to apply to objects based on their "
  150. "distance from the explosion's center point, and whether the explosion is "
  151. "blocked by other objects.\n\n"
  152. "@param pos Center position of the explosion.\n"
  153. "@param id Id of the object of which to check coverage.\n"
  154. "@param covMask Mask of object types that may block the explosion.\n"
  155. "@return Coverage value from 0 (not affected by the explosion) to 1 (fully affected)\n\n"
  156. "@tsexample\n"
  157. "// Get the position of the explosion.\n"
  158. "%position = %explosion.getPosition();\n\n"
  159. "// Set a list of TypeMasks (defined in gameFunctioncs.cpp), seperated by the | character.\n"
  160. "%TypeMasks = $TypeMasks::StaticObjectType | $TypeMasks::ItemObjectType\n\n"
  161. "// Acquire the damage value from 0.0f - 1.0f.\n"
  162. "%coverage = calcExplosionCoverage( %position, %sceneObject, %TypeMasks );\n\n"
  163. "// Apply damage to object\n"
  164. "%sceneObject.applyDamage( %coverage * 20 );\n"
  165. "@endtsexample\n"
  166. "@ingroup FX")
  167. {
  168. Point3F center;
  169. SceneObject* sceneObject = NULL;
  170. if (Sim::findObject(id, sceneObject) == false) {
  171. Con::warnf(ConsoleLogEntry::General, "calcExplosionCoverage: couldn't find object: %d", id);
  172. return 1.0f;
  173. }
  174. if (sceneObject->isClientObject() || sceneObject->getContainer() == NULL) {
  175. Con::warnf(ConsoleLogEntry::General, "calcExplosionCoverage: object is on the client, or not in the container system");
  176. return 1.0f;
  177. }
  178. sceneObject->getObjBox().getCenter(&center);
  179. center.convolve(sceneObject->getScale());
  180. sceneObject->getTransform().mulP(center);
  181. RayInfo rayInfo;
  182. sceneObject->disableCollision();
  183. if (sceneObject->getContainer()->castRay(pos, center, covMask, &rayInfo) == true) {
  184. // Try casting up and then out
  185. if (sceneObject->getContainer()->castRay(pos, pos + Point3F(0.0f, 0.0f, 1.0f), covMask, &rayInfo) == false)
  186. {
  187. if (sceneObject->getContainer()->castRay(pos + Point3F(0.0f, 0.0f, 1.0f), center, covMask, &rayInfo) == false)
  188. {
  189. sceneObject->enableCollision();
  190. return 1.0f;
  191. }
  192. }
  193. sceneObject->enableCollision();
  194. return 0.0f;
  195. } else {
  196. sceneObject->enableCollision();
  197. return 1.0f;
  198. }
  199. }
  200. //----------------------------------------------------------------------------
  201. //
  202. IMPLEMENT_CO_DATABLOCK_V1(ExplosionData);
  203. ConsoleDocClass( ExplosionData,
  204. "@brief Defines the attributes of an Explosion: particleEmitters, debris, "
  205. "lighting and camera shake effects.\n"
  206. "@ingroup FX\n"
  207. );
  208. ExplosionData::ExplosionData()
  209. {
  210. dtsFileName = NULL;
  211. particleDensity = 10;
  212. particleRadius = 1.0f;
  213. faceViewer = false;
  214. soundProfile = NULL;
  215. particleEmitter = NULL;
  216. particleEmitterId = 0;
  217. explosionScale.set(1.0f, 1.0f, 1.0f);
  218. playSpeed = 1.0f;
  219. explosionShape = NULL;
  220. explosionAnimation = -1;
  221. dMemset( emitterList, 0, sizeof( emitterList ) );
  222. dMemset( emitterIDList, 0, sizeof( emitterIDList ) );
  223. dMemset( debrisList, 0, sizeof( debrisList ) );
  224. dMemset( debrisIDList, 0, sizeof( debrisIDList ) );
  225. debrisThetaMin = 0.0f;
  226. debrisThetaMax = 90.0f;
  227. debrisPhiMin = 0.0f;
  228. debrisPhiMax = 360.0f;
  229. debrisNum = 1;
  230. debrisNumVariance = 0;
  231. debrisVelocity = 2.0f;
  232. debrisVelocityVariance = 0.0f;
  233. dMemset( explosionList, 0, sizeof( explosionList ) );
  234. dMemset( explosionIDList, 0, sizeof( explosionIDList ) );
  235. delayMS = 0;
  236. delayVariance = 0;
  237. lifetimeMS = 1000;
  238. lifetimeVariance = 0;
  239. offset = 0.0f;
  240. shakeCamera = false;
  241. camShakeFreq.set( 10.0f, 10.0f, 10.0f );
  242. camShakeAmp.set( 1.0f, 1.0f, 1.0f );
  243. camShakeDuration = 1.5f;
  244. camShakeRadius = 10.0f;
  245. camShakeFalloff = 10.0f;
  246. for( U32 i=0; i<EC_NUM_TIME_KEYS; i++ )
  247. {
  248. times[i] = 1.0f;
  249. }
  250. times[0] = 0.0f;
  251. for( U32 j=0; j<EC_NUM_TIME_KEYS; j++ )
  252. {
  253. sizes[j].set( 1.0f, 1.0f, 1.0f );
  254. }
  255. //
  256. lightStartRadius = lightEndRadius = 0.0f;
  257. lightStartColor.set(1.0f,1.0f,1.0f);
  258. lightEndColor.set(1.0f,1.0f,1.0f);
  259. lightStartBrightness = 1.0f;
  260. lightEndBrightness = 1.0f;
  261. lightNormalOffset = 0.1f;
  262. }
  263. //#define TRACK_EXPLOSION_DATA_CLONES
  264. #ifdef TRACK_EXPLOSION_DATA_CLONES
  265. static int explosion_data_clones = 0;
  266. #endif
  267. ExplosionData::ExplosionData(const ExplosionData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  268. {
  269. #ifdef TRACK_EXPLOSION_DATA_CLONES
  270. explosion_data_clones++;
  271. if (explosion_data_clones == 1)
  272. Con::errorf("ExplosionData -- Clones are on the loose!");
  273. #endif
  274. dtsFileName = other.dtsFileName;
  275. faceViewer = other.faceViewer;
  276. particleDensity = other.particleDensity;
  277. particleRadius = other.particleRadius;
  278. soundProfile = other.soundProfile;
  279. particleEmitter = other.particleEmitter;
  280. particleEmitterId = other.particleEmitterId; // -- for pack/unpack of particleEmitter ptr
  281. explosionScale = other.explosionScale;
  282. playSpeed = other.playSpeed;
  283. explosionShape = other.explosionShape; // -- TSShape loaded using dtsFileName
  284. explosionAnimation = other.explosionAnimation; // -- from explosionShape sequence "ambient"
  285. dMemcpy( emitterList, other.emitterList, sizeof( emitterList ) );
  286. dMemcpy( emitterIDList, other.emitterIDList, sizeof( emitterIDList ) ); // -- for pack/unpack of emitterList ptrs
  287. dMemcpy( debrisList, other.debrisList, sizeof( debrisList ) );
  288. dMemcpy( debrisIDList, other.debrisIDList, sizeof( debrisIDList ) ); // -- for pack/unpack of debrisList ptrs
  289. debrisThetaMin = other.debrisThetaMin;
  290. debrisThetaMax = other.debrisThetaMax;
  291. debrisPhiMin = other.debrisPhiMin;
  292. debrisPhiMax = other.debrisPhiMax;
  293. debrisNum = other.debrisNum;
  294. debrisNumVariance = other.debrisNumVariance;
  295. debrisVelocity = other.debrisVelocity;
  296. debrisVelocityVariance = other.debrisVelocityVariance;
  297. dMemcpy( explosionList, other.explosionList, sizeof( explosionList ) );
  298. dMemcpy( explosionIDList, other.explosionIDList, sizeof( explosionIDList ) ); // -- for pack/unpack of explosionList ptrs
  299. delayMS = other.delayMS;
  300. delayVariance = other.delayVariance;
  301. lifetimeMS = other.lifetimeMS;
  302. lifetimeVariance = other.lifetimeVariance;
  303. offset = other.offset;
  304. dMemcpy( sizes, other.times, sizeof( sizes ) );
  305. dMemcpy( times, other.times, sizeof( times ) );
  306. shakeCamera = other.shakeCamera;
  307. camShakeFreq = other.camShakeFreq;
  308. camShakeAmp = other.camShakeAmp;
  309. camShakeDuration = other.camShakeDuration;
  310. camShakeRadius = other.camShakeRadius;
  311. camShakeFalloff = other.camShakeFalloff;
  312. lightStartRadius = other.lightStartRadius;
  313. lightEndRadius = other.lightEndRadius;
  314. lightStartColor = other.lightStartColor;
  315. lightEndColor = other.lightEndColor;
  316. lightStartBrightness = other.lightStartBrightness;
  317. lightEndBrightness = other.lightEndBrightness;
  318. lightNormalOffset = other.lightNormalOffset;
  319. // Note - Explosion calls mDataBlock->getName() in warning messages but
  320. // that should be safe.
  321. }
  322. ExplosionData::~ExplosionData()
  323. {
  324. if (!isTempClone())
  325. return;
  326. if (soundProfile && soundProfile->isTempClone())
  327. {
  328. delete soundProfile;
  329. soundProfile = 0;
  330. }
  331. // particleEmitter, emitterList[*], debrisList[*], explosionList[*] will delete themselves
  332. #ifdef TRACK_EXPLOSION_DATA_CLONES
  333. if (explosion_data_clones > 0)
  334. {
  335. explosion_data_clones--;
  336. if (explosion_data_clones == 0)
  337. Con::errorf("ExplosionData -- Clones eliminated!");
  338. }
  339. else
  340. Con::errorf("ExplosionData -- Too many clones deleted!");
  341. #endif
  342. }
  343. ExplosionData* ExplosionData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  344. {
  345. if (!owner || getSubstitutionCount() == 0)
  346. return this;
  347. ExplosionData* sub_explosion_db = new ExplosionData(*this, true);
  348. performSubstitutions(sub_explosion_db, owner, index);
  349. return sub_explosion_db;
  350. }
  351. void ExplosionData::initPersistFields()
  352. {
  353. addField( "explosionShape", TypeShapeFilename, Offset(dtsFileName, ExplosionData),
  354. "@brief Optional DTS or DAE shape to place at the center of the explosion.\n\n"
  355. "The <i>ambient</i> animation of this model will be played automatically at "
  356. "the start of the explosion." );
  357. addField( "explosionScale", TypePoint3F, Offset(explosionScale, ExplosionData),
  358. "\"X Y Z\" scale factor applied to the explosionShape model at the start "
  359. "of the explosion." );
  360. addField( "playSpeed", TypeF32, Offset(playSpeed, ExplosionData),
  361. "Time scale at which to play the explosionShape <i>ambient</i> sequence." );
  362. addField( "soundProfile", TYPEID< SFXTrack >(), Offset(soundProfile, ExplosionData),
  363. "Non-looping sound effect that will be played at the start of the explosion." );
  364. addField( "faceViewer", TypeBool, Offset(faceViewer, ExplosionData),
  365. "Controls whether the visual effects of the explosion always face the camera." );
  366. addField( "particleEmitter", TYPEID< ParticleEmitterData >(), Offset(particleEmitter, ExplosionData),
  367. "@brief Emitter used to generate a cloud of particles at the start of the explosion.\n\n"
  368. "Explosions can generate two different particle effects. The first is a "
  369. "single burst of particles at the start of the explosion emitted in a "
  370. "spherical cloud using particleEmitter.\n\n"
  371. "The second effect spawns the list of ParticleEmitters given by the emitter[] "
  372. "field. These emitters generate particles in the normal way throughout the "
  373. "lifetime of the explosion." );
  374. addField( "particleDensity", TypeS32, Offset(particleDensity, ExplosionData),
  375. "@brief Density of the particle cloud created at the start of the explosion.\n\n"
  376. "@see particleEmitter" );
  377. addField( "particleRadius", TypeF32, Offset(particleRadius, ExplosionData),
  378. "@brief Radial distance from the explosion center at which cloud particles "
  379. "are emitted.\n\n"
  380. "@see particleEmitter" );
  381. addField( "emitter", TYPEID< ParticleEmitterData >(), Offset(emitterList, ExplosionData), EC_NUM_EMITTERS,
  382. "@brief List of additional ParticleEmitterData objects to spawn with this "
  383. "explosion.\n\n"
  384. "@see particleEmitter" );
  385. addField( "debris", TYPEID< DebrisData >(), Offset(debrisList, ExplosionData), EC_NUM_DEBRIS_TYPES,
  386. "List of DebrisData objects to spawn with this explosion." );
  387. addField( "debrisThetaMin", TypeF32, Offset(debrisThetaMin, ExplosionData),
  388. "Minimum angle, from the horizontal plane, to eject debris from." );
  389. addField( "debrisThetaMax", TypeF32, Offset(debrisThetaMax, ExplosionData),
  390. "Maximum angle, from the horizontal plane, to eject debris from." );
  391. addField( "debrisPhiMin", TypeF32, Offset(debrisPhiMin, ExplosionData),
  392. "Minimum reference angle, from the vertical plane, to eject debris from." );
  393. addField( "debrisPhiMax", TypeF32, Offset(debrisPhiMax, ExplosionData),
  394. "Maximum reference angle, from the vertical plane, to eject debris from." );
  395. addField( "debrisNum", TypeS32, Offset(debrisNum, ExplosionData),
  396. "Number of debris objects to create." );
  397. addField( "debrisNumVariance", TypeS32, Offset(debrisNumVariance, ExplosionData),
  398. "Variance in the number of debris objects to create (must be from 0 - debrisNum)." );
  399. addField( "debrisVelocity", TypeF32, Offset(debrisVelocity, ExplosionData),
  400. "Velocity to toss debris at." );
  401. addField( "debrisVelocityVariance", TypeF32, Offset(debrisVelocityVariance, ExplosionData),
  402. "Variance in the debris initial velocity (must be >= 0)." );
  403. addField( "subExplosion", TYPEID< ExplosionData >(), Offset(explosionList, ExplosionData), EC_MAX_SUB_EXPLOSIONS,
  404. "List of additional ExplosionData objects to create at the start of the "
  405. "explosion." );
  406. addField( "delayMS", TypeS32, Offset(delayMS, ExplosionData),
  407. "Amount of time, in milliseconds, to delay the start of the explosion effect "
  408. "from the creation of the Explosion object." );
  409. addField( "delayVariance", TypeS32, Offset(delayVariance, ExplosionData),
  410. "Variance, in milliseconds, of delayMS." );
  411. addField( "lifetimeMS", TypeS32, Offset(lifetimeMS, ExplosionData),
  412. "@brief Lifetime, in milliseconds, of the Explosion object.\n\n"
  413. "@note If explosionShape is defined and contains an <i>ambient</i> animation, "
  414. "this field is ignored, and the playSpeed scaled duration of the animation "
  415. "is used instead." );
  416. addField( "lifetimeVariance", TypeS32, Offset(lifetimeVariance, ExplosionData),
  417. "Variance, in milliseconds, of the lifetimeMS of the Explosion object.\n" );
  418. addField( "offset", TypeF32, Offset(offset, ExplosionData),
  419. "@brief Offset distance (in a random direction) of the center of the explosion "
  420. "from the Explosion object position.\n\n"
  421. "Most often used to create some variance in position for subExplosion effects." );
  422. addField( "times", TypeF32, Offset(times, ExplosionData), EC_NUM_TIME_KEYS,
  423. "@brief Time keyframes used to scale the explosionShape model.\n\n"
  424. "Values should be in increasing order from 0.0 - 1.0, and correspond to "
  425. "the life of the Explosion where 0 is the beginning and 1 is the end of "
  426. "the explosion lifetime.\n"
  427. "@see lifetimeMS" );
  428. addField( "sizes", TypePoint3F, Offset(sizes, ExplosionData), EC_NUM_TIME_KEYS,
  429. "@brief \"X Y Z\" size keyframes used to scale the explosionShape model.\n\n"
  430. "The explosionShape (if defined) will be scaled using the times/sizes "
  431. "keyframes over the lifetime of the explosion.\n"
  432. "@see lifetimeMS" );
  433. addField( "shakeCamera", TypeBool, Offset(shakeCamera, ExplosionData),
  434. "Controls whether the camera shakes during this explosion." );
  435. addField( "camShakeFreq", TypePoint3F, Offset(camShakeFreq, ExplosionData),
  436. "Frequency of camera shaking, defined in the \"X Y Z\" axes." );
  437. addField( "camShakeAmp", TypePoint3F, Offset(camShakeAmp, ExplosionData),
  438. "@brief Amplitude of camera shaking, defined in the \"X Y Z\" axes.\n\n"
  439. "Set any value to 0 to disable shaking in that axis." );
  440. addField( "camShakeDuration", TypeF32, Offset(camShakeDuration, ExplosionData),
  441. "Duration (in seconds) to shake the camera." );
  442. addField( "camShakeRadius", TypeF32, Offset(camShakeRadius, ExplosionData),
  443. "Radial distance that a camera's position must be within relative to the "
  444. "center of the explosion to be shaken." );
  445. addField( "camShakeFalloff", TypeF32, Offset(camShakeFalloff, ExplosionData),
  446. "Falloff value for the camera shake." );
  447. addField( "lightStartRadius", TypeF32, Offset(lightStartRadius, ExplosionData),
  448. "@brief Initial radius of the PointLight created by this explosion.\n\n"
  449. "Radius is linearly interpolated from lightStartRadius to lightEndRadius "
  450. "over the lifetime of the explosion.\n"
  451. "@see lifetimeMS" );
  452. addField( "lightEndRadius", TypeF32, Offset(lightEndRadius, ExplosionData),
  453. "@brief Final radius of the PointLight created by this explosion.\n\n"
  454. "@see lightStartRadius" );
  455. addField( "lightStartColor", TypeColorF, Offset(lightStartColor, ExplosionData),
  456. "@brief Initial color of the PointLight created by this explosion.\n\n"
  457. "Color is linearly interpolated from lightStartColor to lightEndColor "
  458. "over the lifetime of the explosion.\n"
  459. "@see lifetimeMS" );
  460. addField( "lightEndColor", TypeColorF, Offset(lightEndColor, ExplosionData),
  461. "@brief Final color of the PointLight created by this explosion.\n\n"
  462. "@see lightStartColor" );
  463. addField( "lightStartBrightness", TypeF32, Offset(lightStartBrightness, ExplosionData),
  464. "@brief Initial brightness of the PointLight created by this explosion.\n\n"
  465. "Brightness is linearly interpolated from lightStartBrightness to "
  466. "lightEndBrightness over the lifetime of the explosion.\n"
  467. "@see lifetimeMS" );
  468. addField("lightEndBrightness", TypeF32, Offset(lightEndBrightness, ExplosionData),
  469. "@brief Final brightness of the PointLight created by this explosion.\n\n"
  470. "@see lightStartBrightness" );
  471. addField( "lightNormalOffset", TypeF32, Offset(lightNormalOffset, ExplosionData),
  472. "Distance (in the explosion normal direction) of the PointLight position "
  473. "from the explosion center." );
  474. // disallow some field substitutions
  475. onlyKeepClearSubstitutions("debris"); // subs resolving to "~~", or "~0" are OK
  476. onlyKeepClearSubstitutions("emitter");
  477. onlyKeepClearSubstitutions("particleEmitter");
  478. onlyKeepClearSubstitutions("soundProfile");
  479. onlyKeepClearSubstitutions("subExplosion");
  480. Parent::initPersistFields();
  481. }
  482. bool ExplosionData::onAdd()
  483. {
  484. if (Parent::onAdd() == false)
  485. return false;
  486. if (explosionScale.x < 0.01f || explosionScale.y < 0.01f || explosionScale.z < 0.01f)
  487. {
  488. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s)::onAdd: ExplosionScale components must be >= 0.01", getName());
  489. explosionScale.x = explosionScale.x < 0.01f ? 0.01f : explosionScale.x;
  490. explosionScale.y = explosionScale.y < 0.01f ? 0.01f : explosionScale.y;
  491. explosionScale.z = explosionScale.z < 0.01f ? 0.01f : explosionScale.z;
  492. }
  493. if (debrisThetaMin < 0.0f)
  494. {
  495. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMin < 0.0", getName());
  496. debrisThetaMin = 0.0f;
  497. }
  498. if (debrisThetaMax > 180.0f)
  499. {
  500. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMax > 180.0", getName());
  501. debrisThetaMax = 180.0f;
  502. }
  503. if (debrisThetaMin > debrisThetaMax) {
  504. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMin > debrisThetaMax", getName());
  505. debrisThetaMin = debrisThetaMax;
  506. }
  507. if (debrisPhiMin < 0.0f)
  508. {
  509. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMin < 0.0", getName());
  510. debrisPhiMin = 0.0f;
  511. }
  512. if (debrisPhiMax > 360.0f)
  513. {
  514. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMax > 360.0", getName());
  515. debrisPhiMax = 360.0f;
  516. }
  517. if (debrisPhiMin > debrisPhiMax) {
  518. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMin > debrisPhiMax", getName());
  519. debrisPhiMin = debrisPhiMax;
  520. }
  521. if (debrisNum > 1000) {
  522. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisNum > 1000", getName());
  523. debrisNum = 1000;
  524. }
  525. if (debrisNumVariance > 1000) {
  526. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisNumVariance > 1000", getName());
  527. debrisNumVariance = 1000;
  528. }
  529. if (debrisVelocity < 0.1f)
  530. {
  531. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisVelocity < 0.1", getName());
  532. debrisVelocity = 0.1f;
  533. }
  534. if (debrisVelocityVariance > 1000) {
  535. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisVelocityVariance > 1000", getName());
  536. debrisVelocityVariance = 1000;
  537. }
  538. if (playSpeed < 0.05f)
  539. {
  540. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) playSpeed < 0.05", getName());
  541. playSpeed = 0.05f;
  542. }
  543. if (lifetimeMS < 1) {
  544. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) lifetimeMS < 1", getName());
  545. lifetimeMS = 1;
  546. }
  547. if (lifetimeVariance > lifetimeMS) {
  548. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) lifetimeVariance > lifetimeMS", getName());
  549. lifetimeVariance = lifetimeMS;
  550. }
  551. if (delayMS < 0) {
  552. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) delayMS < 0", getName());
  553. delayMS = 0;
  554. }
  555. if (delayVariance > delayMS) {
  556. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) delayVariance > delayMS", getName());
  557. delayVariance = delayMS;
  558. }
  559. if (offset < 0.0f)
  560. {
  561. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) offset < 0.0", getName());
  562. offset = 0.0f;
  563. }
  564. S32 i;
  565. for( i=0; i<EC_NUM_DEBRIS_TYPES; i++ )
  566. {
  567. if( !debrisList[i] && debrisIDList[i] != 0 )
  568. {
  569. if( !Sim::findObject( debrisIDList[i], debrisList[i] ) )
  570. {
  571. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(debris): 0x%x", debrisIDList[i] );
  572. }
  573. }
  574. }
  575. for( i=0; i<EC_NUM_EMITTERS; i++ )
  576. {
  577. if( !emitterList[i] && emitterIDList[i] != 0 )
  578. {
  579. if( Sim::findObject( emitterIDList[i], emitterList[i] ) == false)
  580. {
  581. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(particle emitter): 0x%x", emitterIDList[i] );
  582. }
  583. }
  584. }
  585. for( S32 k=0; k<EC_MAX_SUB_EXPLOSIONS; k++ )
  586. {
  587. if( !explosionList[k] && explosionIDList[k] != 0 )
  588. {
  589. if( Sim::findObject( explosionIDList[k], explosionList[k] ) == false)
  590. {
  591. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(explosion): 0x%x", explosionIDList[k] );
  592. }
  593. }
  594. }
  595. return true;
  596. }
  597. void ExplosionData::packData(BitStream* stream)
  598. {
  599. Parent::packData(stream);
  600. stream->writeString(dtsFileName);
  601. sfxWrite( stream, soundProfile );
  602. if (stream->writeFlag(particleEmitter))
  603. stream->writeRangedU32(particleEmitter->getId(),DataBlockObjectIdFirst,DataBlockObjectIdLast);
  604. stream->writeInt(particleDensity, 14);
  605. stream->write(particleRadius);
  606. stream->writeFlag(faceViewer);
  607. if(stream->writeFlag(explosionScale.x != 1 || explosionScale.y != 1 || explosionScale.z != 1))
  608. {
  609. stream->writeInt((S32)(explosionScale.x * 100), 16);
  610. stream->writeInt((S32)(explosionScale.y * 100), 16);
  611. stream->writeInt((S32)(explosionScale.z * 100), 16);
  612. }
  613. stream->writeInt((S32)(playSpeed * 20), 14);
  614. stream->writeRangedU32((U32)debrisThetaMin, 0, 180);
  615. stream->writeRangedU32((U32)debrisThetaMax, 0, 180);
  616. stream->writeRangedU32((U32)debrisPhiMin, 0, 360);
  617. stream->writeRangedU32((U32)debrisPhiMax, 0, 360);
  618. stream->writeRangedU32((U32)debrisNum, 0, 1000);
  619. stream->writeRangedU32(debrisNumVariance, 0, 1000);
  620. stream->writeInt((S32)(debrisVelocity * 10), 14);
  621. stream->writeRangedU32((U32)(debrisVelocityVariance * 10), 0, 10000);
  622. stream->writeInt(delayMS >> 5, 16);
  623. stream->writeInt(delayVariance >> 5, 16);
  624. stream->writeInt(lifetimeMS >> 5, 16);
  625. stream->writeInt(lifetimeVariance >> 5, 16);
  626. stream->write(offset);
  627. stream->writeFlag( shakeCamera );
  628. stream->write(camShakeFreq.x);
  629. stream->write(camShakeFreq.y);
  630. stream->write(camShakeFreq.z);
  631. stream->write(camShakeAmp.x);
  632. stream->write(camShakeAmp.y);
  633. stream->write(camShakeAmp.z);
  634. stream->write(camShakeDuration);
  635. stream->write(camShakeRadius);
  636. stream->write(camShakeFalloff);
  637. for( S32 j=0; j<EC_NUM_DEBRIS_TYPES; j++ )
  638. {
  639. if( stream->writeFlag( debrisList[j] ) )
  640. {
  641. stream->writeRangedU32( debrisList[j]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  642. }
  643. }
  644. S32 i;
  645. for( i=0; i<EC_NUM_EMITTERS; i++ )
  646. {
  647. if( stream->writeFlag( emitterList[i] != NULL ) )
  648. {
  649. stream->writeRangedU32( emitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  650. }
  651. }
  652. for( i=0; i<EC_MAX_SUB_EXPLOSIONS; i++ )
  653. {
  654. if( stream->writeFlag( explosionList[i] != NULL ) )
  655. {
  656. stream->writeRangedU32( explosionList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  657. }
  658. }
  659. U32 count;
  660. for(count = 0; count < EC_NUM_TIME_KEYS; count++)
  661. if(times[count] >= 1)
  662. break;
  663. count++;
  664. if(count > EC_NUM_TIME_KEYS)
  665. count = EC_NUM_TIME_KEYS;
  666. stream->writeRangedU32(count, 0, EC_NUM_TIME_KEYS);
  667. for( i=0; i<count; i++ )
  668. stream->writeFloat( times[i], 8 );
  669. for( i=0; i<count; i++ )
  670. {
  671. stream->writeRangedU32((U32)(sizes[i].x * 100), 0, 16000);
  672. stream->writeRangedU32((U32)(sizes[i].y * 100), 0, 16000);
  673. stream->writeRangedU32((U32)(sizes[i].z * 100), 0, 16000);
  674. }
  675. // Dynamic light info
  676. stream->writeFloat(lightStartRadius/MaxLightRadius, 8);
  677. stream->writeFloat(lightEndRadius/MaxLightRadius, 8);
  678. stream->writeFloat(lightStartColor.red,7);
  679. stream->writeFloat(lightStartColor.green,7);
  680. stream->writeFloat(lightStartColor.blue,7);
  681. stream->writeFloat(lightEndColor.red,7);
  682. stream->writeFloat(lightEndColor.green,7);
  683. stream->writeFloat(lightEndColor.blue,7);
  684. stream->writeFloat(lightStartBrightness/MaxLightRadius, 8);
  685. stream->writeFloat(lightEndBrightness/MaxLightRadius, 8);
  686. stream->write(lightNormalOffset);
  687. }
  688. void ExplosionData::unpackData(BitStream* stream)
  689. {
  690. Parent::unpackData(stream);
  691. dtsFileName = stream->readSTString();
  692. sfxRead( stream, &soundProfile );
  693. if (stream->readFlag())
  694. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  695. else
  696. particleEmitterId = 0;
  697. particleDensity = stream->readInt(14);
  698. stream->read(&particleRadius);
  699. faceViewer = stream->readFlag();
  700. if(stream->readFlag())
  701. {
  702. explosionScale.x = stream->readInt(16) / 100.0f;
  703. explosionScale.y = stream->readInt(16) / 100.0f;
  704. explosionScale.z = stream->readInt(16) / 100.0f;
  705. }
  706. else
  707. explosionScale.set(1,1,1);
  708. playSpeed = stream->readInt(14) / 20.0f;
  709. debrisThetaMin = stream->readRangedU32(0, 180);
  710. debrisThetaMax = stream->readRangedU32(0, 180);
  711. debrisPhiMin = stream->readRangedU32(0, 360);
  712. debrisPhiMax = stream->readRangedU32(0, 360);
  713. debrisNum = stream->readRangedU32(0, 1000);
  714. debrisNumVariance = stream->readRangedU32(0, 1000);
  715. debrisVelocity = stream->readInt(14) / 10.0f;
  716. debrisVelocityVariance = stream->readRangedU32(0, 10000) / 10.0f;
  717. delayMS = stream->readInt(16) << 5;
  718. delayVariance = stream->readInt(16) << 5;
  719. lifetimeMS = stream->readInt(16) << 5;
  720. lifetimeVariance = stream->readInt(16) << 5;
  721. stream->read(&offset);
  722. shakeCamera = stream->readFlag();
  723. stream->read(&camShakeFreq.x);
  724. stream->read(&camShakeFreq.y);
  725. stream->read(&camShakeFreq.z);
  726. stream->read(&camShakeAmp.x);
  727. stream->read(&camShakeAmp.y);
  728. stream->read(&camShakeAmp.z);
  729. stream->read(&camShakeDuration);
  730. stream->read(&camShakeRadius);
  731. stream->read(&camShakeFalloff);
  732. for( S32 j=0; j<EC_NUM_DEBRIS_TYPES; j++ )
  733. {
  734. if( stream->readFlag() )
  735. {
  736. debrisIDList[j] = (S32) stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  737. }
  738. }
  739. U32 i;
  740. for( i=0; i<EC_NUM_EMITTERS; i++ )
  741. {
  742. if( stream->readFlag() )
  743. {
  744. emitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  745. }
  746. }
  747. for( S32 k=0; k<EC_MAX_SUB_EXPLOSIONS; k++ )
  748. {
  749. if( stream->readFlag() )
  750. {
  751. explosionIDList[k] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  752. }
  753. }
  754. U32 count = stream->readRangedU32(0, EC_NUM_TIME_KEYS);
  755. for( i=0; i<count; i++ )
  756. times[i] = stream->readFloat(8);
  757. for( i=0; i<count; i++ )
  758. {
  759. sizes[i].x = stream->readRangedU32(0, 16000) / 100.0f;
  760. sizes[i].y = stream->readRangedU32(0, 16000) / 100.0f;
  761. sizes[i].z = stream->readRangedU32(0, 16000) / 100.0f;
  762. }
  763. //
  764. lightStartRadius = stream->readFloat(8) * MaxLightRadius;
  765. lightEndRadius = stream->readFloat(8) * MaxLightRadius;
  766. lightStartColor.red = stream->readFloat(7);
  767. lightStartColor.green = stream->readFloat(7);
  768. lightStartColor.blue = stream->readFloat(7);
  769. lightEndColor.red = stream->readFloat(7);
  770. lightEndColor.green = stream->readFloat(7);
  771. lightEndColor.blue = stream->readFloat(7);
  772. lightStartBrightness = stream->readFloat(8) * MaxLightRadius;
  773. lightEndBrightness = stream->readFloat(8) * MaxLightRadius;
  774. stream->read( &lightNormalOffset );
  775. }
  776. bool ExplosionData::preload(bool server, String &errorStr)
  777. {
  778. if (Parent::preload(server, errorStr) == false)
  779. return false;
  780. if( !server )
  781. {
  782. String sfxErrorStr;
  783. if( !sfxResolve( &soundProfile, sfxErrorStr ) )
  784. Con::errorf(ConsoleLogEntry::General, "Error, unable to load sound profile for explosion datablock: %s", sfxErrorStr.c_str());
  785. if (!particleEmitter && particleEmitterId != 0)
  786. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  787. Con::errorf(ConsoleLogEntry::General, "Error, unable to load particle emitter for explosion datablock");
  788. }
  789. if (dtsFileName && dtsFileName[0]) {
  790. explosionShape = ResourceManager::get().load(dtsFileName);
  791. if (!bool(explosionShape)) {
  792. errorStr = String::ToString("ExplosionData: Couldn't load shape \"%s\"", dtsFileName);
  793. return false;
  794. }
  795. // Resolve animations
  796. explosionAnimation = explosionShape->findSequence("ambient");
  797. // Preload textures with a dummy instance...
  798. TSShapeInstance* pDummy = new TSShapeInstance(explosionShape, !server);
  799. delete pDummy;
  800. } else {
  801. explosionShape = NULL;
  802. explosionAnimation = -1;
  803. }
  804. return true;
  805. }
  806. //--------------------------------------------------------------------------
  807. //--------------------------------------
  808. //
  809. Explosion::Explosion()
  810. : mDataBlock( NULL )
  811. {
  812. mTypeMask |= ExplosionObjectType | LightObjectType;
  813. mExplosionInstance = NULL;
  814. mExplosionThread = NULL;
  815. dMemset( mEmitterList, 0, sizeof( mEmitterList ) );
  816. mMainEmitter = NULL;
  817. mFade = 1;
  818. mDelayMS = 0;
  819. mCurrMS = 0;
  820. mEndingMS = 1000;
  821. mActive = false;
  822. mCollideType = 0;
  823. mInitialNormal.set( 0.0f, 0.0f, 1.0f );
  824. mRandAngle = sgRandom.randF( 0.0f, 1.0f ) * M_PI_F * 2.0f;
  825. mLight = LIGHTMGR->createLightInfo();
  826. mNetFlags.set( IsGhost );
  827. ss_object = 0;
  828. ss_index = 0;
  829. mDataBlock = 0;
  830. soundProfile_clone = 0;
  831. mRandomVal = 0;
  832. }
  833. Explosion::~Explosion()
  834. {
  835. if( mExplosionInstance )
  836. {
  837. delete mExplosionInstance;
  838. mExplosionInstance = NULL;
  839. mExplosionThread = NULL;
  840. }
  841. SAFE_DELETE(mLight);
  842. if (soundProfile_clone)
  843. {
  844. delete soundProfile_clone;
  845. soundProfile_clone = 0;
  846. }
  847. if (mDataBlock && mDataBlock->isTempClone())
  848. {
  849. delete mDataBlock;
  850. mDataBlock = 0;
  851. }
  852. }
  853. void Explosion::setInitialState(const Point3F& point, const Point3F& normal, const F32 fade)
  854. {
  855. setPosition(point);
  856. mInitialNormal = normal;
  857. mFade = fade;
  858. }
  859. //--------------------------------------------------------------------------
  860. void Explosion::initPersistFields()
  861. {
  862. Parent::initPersistFields();
  863. addField("initialNormal", TypePoint3F, Offset(mInitialNormal, Explosion), "Initial starting Normal.");
  864. //
  865. }
  866. //--------------------------------------------------------------------------
  867. bool Explosion::onAdd()
  868. {
  869. // first check if we have a server connection, if we dont then this is on the server
  870. // and we should exit, then check if the parent fails to add the object
  871. GameConnection *conn = GameConnection::getConnectionToServer();
  872. if ( !conn || !Parent::onAdd() )
  873. return false;
  874. if( !mDataBlock )
  875. {
  876. Con::errorf("Explosion::onAdd - Fail - No datablok");
  877. return false;
  878. }
  879. mDelayMS = mDataBlock->delayMS + sgRandom.randI( -mDataBlock->delayVariance, mDataBlock->delayVariance );
  880. mEndingMS = mDataBlock->lifetimeMS + sgRandom.randI( -mDataBlock->lifetimeVariance, mDataBlock->lifetimeVariance );
  881. if( mFabs( mDataBlock->offset ) > 0.001f )
  882. {
  883. MatrixF axisOrient = MathUtils::createOrientFromDir( mInitialNormal );
  884. MatrixF trans = getTransform();
  885. Point3F randVec;
  886. randVec.x = sgRandom.randF( -1.0f, 1.0f );
  887. randVec.y = sgRandom.randF( 0.0f, 1.0f );
  888. randVec.z = sgRandom.randF( -1.0f, 1.0f );
  889. randVec.normalize();
  890. randVec *= mDataBlock->offset;
  891. axisOrient.mulV( randVec );
  892. trans.setPosition( trans.getPosition() + randVec );
  893. setTransform( trans );
  894. }
  895. // shake camera
  896. if( mDataBlock->shakeCamera )
  897. {
  898. // first check if explosion is near player
  899. GameConnection* connection = GameConnection::getConnectionToServer();
  900. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  901. bool applyShake = true;
  902. if( obj )
  903. {
  904. ShapeBase* cObj = obj;
  905. while((cObj = cObj->getControlObject()) != 0)
  906. {
  907. if(cObj->useObjsEyePoint())
  908. {
  909. applyShake = false;
  910. break;
  911. }
  912. }
  913. }
  914. if( applyShake && obj )
  915. {
  916. VectorF diff = obj->getPosition() - getPosition();
  917. F32 dist = diff.len();
  918. if( dist < mDataBlock->camShakeRadius )
  919. {
  920. CameraShake *camShake = new CameraShake;
  921. camShake->setDuration( mDataBlock->camShakeDuration );
  922. camShake->setFrequency( mDataBlock->camShakeFreq );
  923. F32 falloff = dist / mDataBlock->camShakeRadius;
  924. falloff = 1.0f + falloff * 10.0f;
  925. falloff = 1.0f / (falloff * falloff);
  926. VectorF shakeAmp = mDataBlock->camShakeAmp * falloff;
  927. camShake->setAmplitude( shakeAmp );
  928. camShake->setFalloff( mDataBlock->camShakeFalloff );
  929. camShake->init();
  930. gCamFXMgr.addFX( camShake );
  931. }
  932. }
  933. }
  934. if( mDelayMS == 0 )
  935. {
  936. if( !explode() )
  937. {
  938. return false;
  939. }
  940. }
  941. gClientSceneGraph->addObjectToScene(this);
  942. removeFromProcessList();
  943. ClientProcessList::get()->addObject(this);
  944. mRandomVal = sgRandom.randF();
  945. NetConnection* pNC = NetConnection::getConnectionToServer();
  946. AssertFatal(pNC != NULL, "Error, must have a connection to the server!");
  947. pNC->addObject(this);
  948. // Initialize the light structure and register as a dynamic light
  949. if (mDataBlock->lightStartRadius != 0.0f || mDataBlock->lightEndRadius)
  950. {
  951. mLight->setType( LightInfo::Point );
  952. mLight->setRange( mDataBlock->lightStartRadius );
  953. mLight->setColor( mDataBlock->lightStartColor );
  954. }
  955. return true;
  956. }
  957. void Explosion::onRemove()
  958. {
  959. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  960. {
  961. if( mEmitterList[i] )
  962. {
  963. mEmitterList[i]->deleteWhenEmpty();
  964. mEmitterList[i] = NULL;
  965. }
  966. }
  967. if( mMainEmitter )
  968. {
  969. mMainEmitter->deleteWhenEmpty();
  970. mMainEmitter = NULL;
  971. }
  972. removeFromScene();
  973. Parent::onRemove();
  974. }
  975. bool Explosion::onNewDataBlock( GameBaseData *dptr, bool reload )
  976. {
  977. mDataBlock = dynamic_cast<ExplosionData*>( dptr );
  978. if (!mDataBlock || !Parent::onNewDataBlock( dptr, reload ))
  979. return false;
  980. if (mDataBlock->isTempClone())
  981. return true;
  982. scriptOnNewDataBlock();
  983. return true;
  984. }
  985. //--------------------------------------------------------------------------
  986. void Explosion::prepRenderImage( SceneRenderState* state )
  987. {
  988. prepBatchRender( state );
  989. }
  990. void Explosion::setCurrentScale()
  991. {
  992. F32 t = F32(mCurrMS) / F32(mEndingMS);
  993. for( U32 i = 1; i < ExplosionData::EC_NUM_TIME_KEYS; i++ )
  994. {
  995. if( mDataBlock->times[i] >= t )
  996. {
  997. F32 firstPart = t - mDataBlock->times[i-1];
  998. F32 total = mDataBlock->times[i] -
  999. mDataBlock->times[i-1];
  1000. firstPart /= total;
  1001. mObjScale = (mDataBlock->sizes[i-1] * (1.0f - firstPart)) +
  1002. (mDataBlock->sizes[i] * firstPart);
  1003. return;
  1004. }
  1005. }
  1006. }
  1007. //--------------------------------------------------------------------------
  1008. // Make the explosion face the viewer (if desired)
  1009. //--------------------------------------------------------------------------
  1010. void Explosion::prepModelView(SceneRenderState* state)
  1011. {
  1012. MatrixF rotMatrix( true );
  1013. Point3F targetVector;
  1014. if( mDataBlock->faceViewer )
  1015. {
  1016. targetVector = getPosition() - state->getCameraPosition();
  1017. targetVector.normalize();
  1018. // rotate explosion each time so it's a little different
  1019. rotMatrix.set( EulerF( 0.0f, mRandAngle, 0.0f ) );
  1020. }
  1021. else
  1022. {
  1023. targetVector = mInitialNormal;
  1024. }
  1025. MatrixF explOrient = MathUtils::createOrientFromDir( targetVector );
  1026. explOrient.mul( rotMatrix );
  1027. explOrient.setPosition( getPosition() );
  1028. setCurrentScale();
  1029. explOrient.scale( mObjScale );
  1030. GFX->setWorldMatrix( explOrient );
  1031. }
  1032. //--------------------------------------------------------------------------
  1033. // Render object
  1034. //--------------------------------------------------------------------------
  1035. void Explosion::prepBatchRender(SceneRenderState* state)
  1036. {
  1037. if ( !mExplosionInstance )
  1038. return;
  1039. MatrixF proj = GFX->getProjectionMatrix();
  1040. RectI viewport = GFX->getViewport();
  1041. // Set up our TS render state here.
  1042. TSRenderState rdata;
  1043. rdata.setSceneState( state );
  1044. // We might have some forward lit materials
  1045. // so pass down a query to gather lights.
  1046. LightQuery query;
  1047. query.init( getWorldSphere() );
  1048. rdata.setLightQuery( &query );
  1049. // render mesh
  1050. GFX->pushWorldMatrix();
  1051. prepModelView( state );
  1052. mExplosionInstance->animate();
  1053. mExplosionInstance->render( rdata );
  1054. GFX->popWorldMatrix();
  1055. GFX->setProjectionMatrix( proj );
  1056. GFX->setViewport( viewport );
  1057. }
  1058. void Explosion::submitLights( LightManager *lm, bool staticLighting )
  1059. {
  1060. if ( staticLighting )
  1061. return;
  1062. // Update the light's info and add it to the scene, the light will
  1063. // only be visible for this current frame.
  1064. mLight->setPosition( getRenderTransform().getPosition() + mInitialNormal * mDataBlock->lightNormalOffset );
  1065. F32 t = F32(mCurrMS) / F32(mEndingMS);
  1066. mLight->setRange( mDataBlock->lightStartRadius +
  1067. (mDataBlock->lightEndRadius - mDataBlock->lightStartRadius) * t );
  1068. mLight->setColor( mDataBlock->lightStartColor +
  1069. (mDataBlock->lightEndColor - mDataBlock->lightStartColor) * t );
  1070. mLight->setBrightness( mDataBlock->lightStartBrightness +
  1071. (mDataBlock->lightEndBrightness - mDataBlock->lightStartBrightness) * t );
  1072. lm->registerGlobalLight( mLight, this );
  1073. }
  1074. //--------------------------------------------------------------------------
  1075. void Explosion::processTick(const Move*)
  1076. {
  1077. mCurrMS += TickMs;
  1078. if( mCurrMS >= mEndingMS )
  1079. {
  1080. deleteObject();
  1081. return;
  1082. }
  1083. if( (mCurrMS > mDelayMS) && !mActive )
  1084. explode();
  1085. }
  1086. void Explosion::advanceTime(F32 dt)
  1087. {
  1088. if (dt == 0.0f)
  1089. return;
  1090. GameConnection* conn = GameConnection::getConnectionToServer();
  1091. if(!conn)
  1092. return;
  1093. updateEmitters( dt );
  1094. if( mExplosionInstance )
  1095. mExplosionInstance->advanceTime(dt, mExplosionThread);
  1096. }
  1097. //----------------------------------------------------------------------------
  1098. // Update emitters
  1099. //----------------------------------------------------------------------------
  1100. void Explosion::updateEmitters( F32 dt )
  1101. {
  1102. Point3F pos = getPosition();
  1103. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1104. {
  1105. if( mEmitterList[i] )
  1106. {
  1107. mEmitterList[i]->emitParticles( pos, pos, mInitialNormal, Point3F( 0.0f, 0.0f, 0.0f ), (U32)(dt * 1000));
  1108. }
  1109. }
  1110. }
  1111. //----------------------------------------------------------------------------
  1112. // Launch Debris
  1113. //----------------------------------------------------------------------------
  1114. void Explosion::launchDebris( Point3F &axis )
  1115. {
  1116. GameConnection* conn = GameConnection::getConnectionToServer();
  1117. if(!conn)
  1118. return;
  1119. bool hasDebris = false;
  1120. for( S32 j=0; j<ExplosionData::EC_NUM_DEBRIS_TYPES; j++ )
  1121. {
  1122. if( mDataBlock->debrisList[j] )
  1123. {
  1124. hasDebris = true;
  1125. break;
  1126. }
  1127. }
  1128. if( !hasDebris )
  1129. {
  1130. return;
  1131. }
  1132. Point3F axisx;
  1133. if (mFabs(axis.z) < 0.999f)
  1134. mCross(axis, Point3F(0.0f, 0.0f, 1.0f), &axisx);
  1135. else
  1136. mCross(axis, Point3F(0.0f, 1.0f, 0.0f), &axisx);
  1137. axisx.normalize();
  1138. Point3F pos( 0.0f, 0.0f, 0.5f );
  1139. pos += getPosition();
  1140. U32 numDebris = mDataBlock->debrisNum + sgRandom.randI( -mDataBlock->debrisNumVariance, mDataBlock->debrisNumVariance );
  1141. for( S32 i=0; i<numDebris; i++ )
  1142. {
  1143. Point3F launchDir = MathUtils::randomDir( axis, mDataBlock->debrisThetaMin, mDataBlock->debrisThetaMax,
  1144. mDataBlock->debrisPhiMin, mDataBlock->debrisPhiMax );
  1145. F32 debrisVel = mDataBlock->debrisVelocity + mDataBlock->debrisVelocityVariance * sgRandom.randF( -1.0f, 1.0f );
  1146. launchDir *= debrisVel;
  1147. Debris *debris = new Debris;
  1148. debris->setSubstitutionData(ss_object, ss_index);
  1149. debris->setDataBlock(mDataBlock->debrisList[0]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1150. debris->setTransform( getTransform() );
  1151. debris->init( pos, launchDir );
  1152. if( !debris->registerObject() )
  1153. {
  1154. Con::warnf( ConsoleLogEntry::General, "Could not register debris for class: %s", mDataBlock->getName() );
  1155. delete debris;
  1156. debris = NULL;
  1157. }
  1158. }
  1159. }
  1160. //----------------------------------------------------------------------------
  1161. // Spawn sub explosions
  1162. //----------------------------------------------------------------------------
  1163. void Explosion::spawnSubExplosions()
  1164. {
  1165. GameConnection* conn = GameConnection::getConnectionToServer();
  1166. if(!conn)
  1167. return;
  1168. for( S32 i=0; i<ExplosionData::EC_MAX_SUB_EXPLOSIONS; i++ )
  1169. {
  1170. if( mDataBlock->explosionList[i] )
  1171. {
  1172. MatrixF trans = getTransform();
  1173. Explosion* pExplosion = new Explosion;
  1174. pExplosion->setSubstitutionData(ss_object, ss_index);
  1175. pExplosion->setDataBlock(mDataBlock->explosionList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1176. pExplosion->setTransform( trans );
  1177. pExplosion->setInitialState( trans.getPosition(), mInitialNormal, 1);
  1178. if (!pExplosion->registerObject())
  1179. delete pExplosion;
  1180. }
  1181. }
  1182. }
  1183. //----------------------------------------------------------------------------
  1184. // Explode
  1185. //----------------------------------------------------------------------------
  1186. bool Explosion::explode()
  1187. {
  1188. mActive = true;
  1189. GameConnection* conn = GameConnection::getConnectionToServer();
  1190. if(!conn)
  1191. return false;
  1192. launchDebris( mInitialNormal );
  1193. spawnSubExplosions();
  1194. if (bool(mDataBlock->explosionShape) && mDataBlock->explosionAnimation != -1) {
  1195. mExplosionInstance = new TSShapeInstance(mDataBlock->explosionShape, true);
  1196. mExplosionThread = mExplosionInstance->addThread();
  1197. mExplosionInstance->setSequence(mExplosionThread, mDataBlock->explosionAnimation, 0);
  1198. mExplosionInstance->setTimeScale(mExplosionThread, mDataBlock->playSpeed);
  1199. mCurrMS = 0;
  1200. mEndingMS = U32(mExplosionInstance->getScaledDuration(mExplosionThread) * 1000.0f);
  1201. mObjScale.convolve(mDataBlock->explosionScale);
  1202. mObjBox = mDataBlock->explosionShape->mBounds;
  1203. resetWorldBox();
  1204. }
  1205. SFXProfile* sound_prof = dynamic_cast<SFXProfile*>(mDataBlock->soundProfile);
  1206. if (sound_prof)
  1207. {
  1208. soundProfile_clone = sound_prof->cloneAndPerformSubstitutions(ss_object, ss_index);
  1209. SFX->playOnce( soundProfile_clone, &getTransform() );
  1210. if (!soundProfile_clone->isTempClone())
  1211. soundProfile_clone = 0;
  1212. }
  1213. if (mDataBlock->particleEmitter) {
  1214. mMainEmitter = new ParticleEmitter;
  1215. mMainEmitter->setDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index));
  1216. mMainEmitter->registerObject();
  1217. mMainEmitter->emitParticles(getPosition(), mInitialNormal, mDataBlock->particleRadius,
  1218. Point3F::Zero, U32(mDataBlock->particleDensity * mFade));
  1219. }
  1220. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1221. {
  1222. if( mDataBlock->emitterList[i] != NULL )
  1223. {
  1224. ParticleEmitter * pEmitter = new ParticleEmitter;
  1225. pEmitter->setDataBlock(mDataBlock->emitterList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1226. if( !pEmitter->registerObject() )
  1227. {
  1228. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  1229. SAFE_DELETE(pEmitter);
  1230. }
  1231. mEmitterList[i] = pEmitter;
  1232. }
  1233. }
  1234. return true;
  1235. }