explosion.cpp 51 KB

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