explosion.cpp 49 KB

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