explosion.cpp 49 KB

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