projectile.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  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/projectile.h"
  28. #include "scene/sceneRenderState.h"
  29. #include "scene/sceneManager.h"
  30. #include "lighting/lightInfo.h"
  31. #include "lighting/lightManager.h"
  32. #include "console/consoleTypes.h"
  33. #include "console/typeValidators.h"
  34. #include "core/resourceManager.h"
  35. #include "core/stream/bitStream.h"
  36. #include "T3D/fx/explosion.h"
  37. #include "T3D/shapeBase.h"
  38. #include "ts/tsShapeInstance.h"
  39. #include "sfx/sfxTrack.h"
  40. #include "sfx/sfxSource.h"
  41. #include "sfx/sfxSystem.h"
  42. #include "sfx/sfxTypes.h"
  43. #include "math/mathUtils.h"
  44. #include "math/mathIO.h"
  45. #include "sim/netConnection.h"
  46. #include "T3D/fx/particleEmitter.h"
  47. #include "T3D/fx/splash.h"
  48. #include "T3D/physics/physicsPlugin.h"
  49. #include "T3D/physics/physicsWorld.h"
  50. #include "gfx/gfxTransformSaver.h"
  51. #include "T3D/containerQuery.h"
  52. #include "T3D/decal/decalManager.h"
  53. #include "T3D/decal/decalData.h"
  54. #include "T3D/lightDescription.h"
  55. #include "console/engineAPI.h"
  56. IMPLEMENT_CO_DATABLOCK_V1(ProjectileData);
  57. ConsoleDocClass( ProjectileData,
  58. "@brief Stores properties for an individual projectile type.\n"
  59. "@tsexample\n"
  60. "datablock ProjectileData(GrenadeLauncherProjectile)\n"
  61. "{\n"
  62. " projectileShapeName = \"art/shapes/weapons/SwarmGun/rocket.dts\";\n"
  63. "directDamage = 30;\n"
  64. "radiusDamage = 30;\n"
  65. "damageRadius = 5;\n"
  66. "areaImpulse = 2000;\n"
  67. "explosion = GrenadeLauncherExplosion;\n"
  68. "waterExplosion = GrenadeLauncherWaterExplosion;\n"
  69. "decal = ScorchRXDecal;\n"
  70. "splash = GrenadeSplash;\n"
  71. "particleEmitter = GrenadeProjSmokeTrailEmitter;\n"
  72. "particleWaterEmitter = GrenadeTrailWaterEmitter;\n"
  73. "muzzleVelocity = 30;\n"
  74. "velInheritFactor = 0.3;\n"
  75. "armingDelay = 2000;\n"
  76. "lifetime = 10000;\n"
  77. "fadeDelay = 4500;\n"
  78. "bounceElasticity = 0.4;\n"
  79. "bounceFriction = 0.3;\n"
  80. "isBallistic = true;\n"
  81. "gravityMod = 0.9;\n"
  82. "lightDesc = GrenadeLauncherLightDesc;\n"
  83. "damageType = \"GrenadeDamage\";\n"
  84. "};\n"
  85. "@endtsexample\n"
  86. "@ingroup gameObjects\n"
  87. );
  88. IMPLEMENT_CO_NETOBJECT_V1(Projectile);
  89. ConsoleDocClass( Projectile,
  90. "@brief Base projectile class. Uses the ProjectileData class for properties of individual projectiles.\n"
  91. "@ingroup gameObjects\n"
  92. );
  93. IMPLEMENT_CALLBACK( ProjectileData, onExplode, void, ( Projectile* proj, Point3F pos, F32 fade ),
  94. ( proj, pos, fade ),
  95. "@brief Called when a projectile explodes.\n\n"
  96. "This function is only called on server objects.\n"
  97. "@param proj The exploding projectile.\n"
  98. "@param pos The position of the explosion.\n"
  99. "@param fade The current fadeValue of the projectile, affects its visibility.\n\n"
  100. "@see Projectile\n"
  101. );
  102. IMPLEMENT_CALLBACK( ProjectileData, onCollision, void, ( Projectile* proj, SceneObject* col, F32 fade, Point3F pos, Point3F normal ),
  103. ( proj, col, fade, pos, normal ),
  104. "@brief Called when a projectile collides with another object.\n\n"
  105. "This function is only called on server objects."
  106. "@param proj The projectile colliding with SceneObject col.\n"
  107. "@param col The SceneObject hit by the projectile.\n"
  108. "@param fade The current fadeValue of the projectile, affects its visibility.\n"
  109. "@param pos The position of the collision.\n"
  110. "@param normal The normal of the collision.\n"
  111. "@see Projectile\n"
  112. );
  113. const U32 Projectile::csmStaticCollisionMask = TerrainObjectType | StaticShapeObjectType;
  114. const U32 Projectile::csmDynamicCollisionMask = PlayerObjectType | VehicleObjectType;
  115. const U32 Projectile::csmDamageableMask = Projectile::csmDynamicCollisionMask;
  116. U32 Projectile::smProjectileWarpTicks = 5;
  117. //--------------------------------------------------------------------------
  118. //
  119. ProjectileData::ProjectileData()
  120. {
  121. INIT_ASSET(ProjectileShape);
  122. INIT_ASSET(ProjectileSound);
  123. explosion = NULL;
  124. explosionId = 0;
  125. waterExplosion = NULL;
  126. waterExplosionId = 0;
  127. //hasLight = false;
  128. //lightRadius = 1;
  129. //lightColor.set(1, 1, 1);
  130. lightDesc = NULL;
  131. faceViewer = false;
  132. scale.set( 1.0f, 1.0f, 1.0f );
  133. isBallistic = false;
  134. velInheritFactor = 1.0f;
  135. muzzleVelocity = 50;
  136. impactForce = 0.0f;
  137. armingDelay = 0;
  138. fadeDelay = 20000 / 32;
  139. lifetime = 20000 / 32;
  140. activateSeq = -1;
  141. maintainSeq = -1;
  142. gravityMod = 1.0;
  143. bounceElasticity = 0.999f;
  144. bounceFriction = 0.3f;
  145. particleEmitter = NULL;
  146. particleEmitterId = 0;
  147. particleWaterEmitter = NULL;
  148. particleWaterEmitterId = 0;
  149. splash = NULL;
  150. splashId = 0;
  151. decal = NULL;
  152. decalId = 0;
  153. lightDesc = NULL;
  154. lightDescId = 0;
  155. }
  156. ProjectileData::ProjectileData(const ProjectileData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  157. {
  158. faceViewer = other.faceViewer; // -- always set to false
  159. scale = other.scale;
  160. velInheritFactor = other.velInheritFactor;
  161. muzzleVelocity = other.muzzleVelocity;
  162. impactForce = other.impactForce;
  163. isBallistic = other.isBallistic;
  164. bounceElasticity = other.bounceElasticity;
  165. bounceFriction = other.bounceFriction;
  166. gravityMod = other.gravityMod;
  167. lifetime = other.lifetime;
  168. armingDelay = other.armingDelay;
  169. fadeDelay = other.fadeDelay;
  170. explosion = other.explosion;
  171. explosionId = other.explosionId; // -- for pack/unpack of explosion ptr
  172. waterExplosion = other.waterExplosion;
  173. waterExplosionId = other.waterExplosionId; // -- for pack/unpack of waterExplosion ptr
  174. splash = other.splash;
  175. splashId = other.splashId; // -- for pack/unpack of splash ptr
  176. decal = other.decal;
  177. decalId = other.decalId; // -- for pack/unpack of decal ptr
  178. CLONE_ASSET(ProjectileSound);
  179. lightDesc = other.lightDesc;
  180. lightDescId = other.lightDescId; // -- for pack/unpack of lightDesc ptr
  181. CLONE_ASSET(ProjectileShape);// -- TSShape loads using mProjectileShapeName
  182. activateSeq = other.activateSeq; // -- from projectileShape sequence "activate"
  183. maintainSeq = other.maintainSeq; // -- from projectileShape sequence "maintain"
  184. particleEmitter = other.particleEmitter;
  185. particleEmitterId = other.particleEmitterId; // -- for pack/unpack of particleEmitter ptr
  186. particleWaterEmitter = other.particleWaterEmitter;
  187. particleWaterEmitterId = other.particleWaterEmitterId; // -- for pack/unpack of particleWaterEmitter ptr
  188. }
  189. //--------------------------------------------------------------------------
  190. void ProjectileData::initPersistFields()
  191. {
  192. docsURL;
  193. addGroup("Shapes");
  194. addProtectedField("projectileShapeName", TypeShapeFilename, Offset(mProjectileShapeName, ProjectileData), &_setProjectileShapeData, &defaultProtectedGetFn,
  195. "@brief File path to the model of the projectile.\n\n", AbstractClassRep::FIELD_HideInInspectors);
  196. INITPERSISTFIELD_SHAPEASSET(ProjectileShape, ProjectileData, "@brief The model of the projectile.\n\n");
  197. addField("scale", TypePoint3F, Offset(scale, ProjectileData),
  198. "@brief Scale to apply to the projectile's size.\n\n"
  199. "@note This is applied after SceneObject::scale\n");
  200. endGroup("Shapes");
  201. addGroup("Particle Effects");
  202. addField("particleEmitter", TYPEID< ParticleEmitterData >(), Offset(particleEmitter, ProjectileData),
  203. "@brief Particle emitter datablock used to generate particles while the projectile is outside of water.\n\n"
  204. "@note If datablocks are defined for both particleEmitter and particleWaterEmitter, both effects will play "
  205. "as the projectile enters or leaves water.\n\n"
  206. "@see particleWaterEmitter\n");
  207. addField("particleWaterEmitter", TYPEID< ParticleEmitterData >(), Offset(particleWaterEmitter, ProjectileData),
  208. "@brief Particle emitter datablock used to generate particles while the projectile is submerged in water.\n\n"
  209. "@note If datablocks are defined for both particleWaterEmitter and particleEmitter , both effects will play "
  210. "as the projectile enters or leaves water.\n\n"
  211. "@see particleEmitter\n");
  212. addField("explosion", TYPEID< ExplosionData >(), Offset(explosion, ProjectileData),
  213. "@brief Explosion datablock used when the projectile explodes outside of water.\n\n");
  214. addField("waterExplosion", TYPEID< ExplosionData >(), Offset(waterExplosion, ProjectileData),
  215. "@brief Explosion datablock used when the projectile explodes underwater.\n\n");
  216. addField("splash", TYPEID< SplashData >(), Offset(splash, ProjectileData),
  217. "@brief Splash datablock used to create splash effects as the projectile enters or leaves water\n\n");
  218. addField("decal", TYPEID< DecalData >(), Offset(decal, ProjectileData),
  219. "@brief Decal datablock used for decals placed at projectile explosion points.\n\n");
  220. endGroup("Particle Effects");
  221. addGroup("Sounds");
  222. INITPERSISTFIELD_SOUNDASSET(ProjectileSound, ProjectileData, "The sound for the projectile.");
  223. endGroup("Sounds");
  224. addGroup("Light Emitter");
  225. addField("lightDesc", TYPEID< LightDescription >(), Offset(lightDesc, ProjectileData),
  226. "@brief LightDescription datablock used for lights attached to the projectile.\n\n");
  227. endGroup("Light Emitter");
  228. addGroup("Physics");
  229. addProtectedFieldV("lifetime", TypeRangedS32, Offset(lifetime, ProjectileData), &setLifetime, &getScaledValue, &CommonValidators::NaturalNumber,
  230. "@brief Amount of time, in milliseconds, before the projectile is removed from the simulation.\n\n"
  231. "Used with fadeDelay to determine the transparency of the projectile at a given time. "
  232. "A projectile may exist up to a maximum of 131040ms (or 4095 ticks) as defined by Projectile::MaxLivingTicks in the source code."
  233. "@see fadeDelay");
  234. addProtectedFieldV("armingDelay", TypeRangedS32, Offset(armingDelay, ProjectileData), &setArmingDelay, &getScaledValue, &CommonValidators::PositiveInt,
  235. "@brief Amount of time, in milliseconds, before the projectile will cause damage or explode on impact.\n\n"
  236. "This value must be equal to or less than the projectile's lifetime.\n\n"
  237. "@see lifetime");
  238. addProtectedFieldV("fadeDelay", TypeRangedS32, Offset(fadeDelay, ProjectileData), &setFadeDelay, &getScaledValue, &CommonValidators::NaturalNumber,
  239. "@brief Amount of time, in milliseconds, before the projectile begins to fade out.\n\n"
  240. "This value must be smaller than the projectile's lifetime to have an affect.");
  241. addField("isBallistic", TypeBool, Offset(isBallistic, ProjectileData),
  242. "@brief Detetmines if the projectile should be affected by gravity and whether or not "
  243. "it bounces before exploding.\n\n");
  244. addFieldV("velInheritFactor", TypeRangedF32, Offset(velInheritFactor, ProjectileData), &CommonValidators::F32Range,
  245. "@brief Amount of velocity the projectile recieves from the source that created it.\n\n"
  246. "Use an amount between 0 and 1 for the best effect. "
  247. "This value is never modified by the engine.\n"
  248. "@note This value by default is not transmitted between the server and the client.");
  249. addFieldV("muzzleVelocity", TypeRangedF32, Offset(muzzleVelocity, ProjectileData), &CommonValidators::PositiveFloat,
  250. "@brief Amount of velocity the projectile recieves from the \"muzzle\" of the gun.\n\n"
  251. "Used with velInheritFactor to determine the initial velocity of the projectile. "
  252. "This value is never modified by the engine.\n\n"
  253. "@note This value by default is not transmitted between the server and the client.\n\n"
  254. "@see velInheritFactor");
  255. addFieldV("impactForce", TypeRangedF32, Offset(impactForce, ProjectileData), &CommonValidators::PositiveFloat);
  256. addFieldV("bounceElasticity", TypeRangedF32, Offset(bounceElasticity, ProjectileData), &CommonValidators::PositiveFloat,
  257. "@brief Influences post-bounce velocity of a projectile that does not explode on contact.\n\n"
  258. "Scales the velocity from a bounce after friction is taken into account. "
  259. "A value of 1.0 will leave it's velocity unchanged while values greater than 1.0 will increase it.\n");
  260. addFieldV("bounceFriction", TypeRangedF32, Offset(bounceFriction, ProjectileData), &CommonValidators::PositiveFloat,
  261. "@brief Factor to reduce post-bounce velocity of a projectile that does not explode on contact.\n\n"
  262. "Reduces bounce velocity by this factor and a multiple of the tangent to impact. "
  263. "Used to simulate surface friction.\n");
  264. addFieldV("gravityMod", TypeRangedF32, Offset(gravityMod, ProjectileData), &CommonValidators::F32Range,
  265. "@brief Scales the influence of gravity on the projectile.\n\n"
  266. "The larger this value is, the more that gravity will affect the projectile. "
  267. "A value of 1.0 will assume \"normal\" influence upon it.\n"
  268. "The magnitude of gravity is assumed to be 9.81 m/s/s\n\n"
  269. "@note ProjectileData::isBallistic must be true for this to have any affect.");
  270. endGroup("Physics");
  271. Parent::initPersistFields();
  272. // disallow some field substitutions
  273. onlyKeepClearSubstitutions("explosion");
  274. onlyKeepClearSubstitutions("particleEmitter");
  275. onlyKeepClearSubstitutions("particleWaterEmitter");
  276. onlyKeepClearSubstitutions("sound");
  277. onlyKeepClearSubstitutions("splash");
  278. onlyKeepClearSubstitutions("waterExplosion");
  279. }
  280. //--------------------------------------------------------------------------
  281. bool ProjectileData::onAdd()
  282. {
  283. if(!Parent::onAdd())
  284. return false;
  285. return true;
  286. }
  287. bool ProjectileData::preload(bool server, String &errorStr)
  288. {
  289. if (Parent::preload(server, errorStr) == false)
  290. return false;
  291. if( !server )
  292. {
  293. if (!particleEmitter && particleEmitterId != 0)
  294. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  295. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(particleEmitter): %d", particleEmitterId);
  296. if (!particleWaterEmitter && particleWaterEmitterId != 0)
  297. if (Sim::findObject(particleWaterEmitterId, particleWaterEmitter) == false)
  298. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(particleWaterEmitter): %d", particleWaterEmitterId);
  299. if (!explosion && explosionId != 0)
  300. if (Sim::findObject(explosionId, explosion) == false)
  301. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(explosion): %d", explosionId);
  302. if (!waterExplosion && waterExplosionId != 0)
  303. if (Sim::findObject(waterExplosionId, waterExplosion) == false)
  304. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(waterExplosion): %d", waterExplosionId);
  305. if (!splash && splashId != 0)
  306. if (Sim::findObject(splashId, splash) == false)
  307. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(splash): %d", splashId);
  308. if (!decal && decalId != 0)
  309. if (Sim::findObject(decalId, decal) == false)
  310. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(decal): %d", decalId);
  311. if (!isProjectileSoundValid())
  312. {
  313. //return false; -TODO: trigger asset download
  314. }
  315. if (!lightDesc && lightDescId != 0)
  316. if (Sim::findObject(lightDescId, lightDesc) == false)
  317. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockid(lightDesc): %d", lightDescId);
  318. }
  319. if (mProjectileShapeAssetId != StringTable->EmptyString())
  320. {
  321. //If we've got a shapeAsset assigned for our projectile, but we failed to load the shape data itself, report the error
  322. if (!mProjectileShape)
  323. {
  324. errorStr = String::ToString("ProjectileData::load: Couldn't load shape \"%s\"", mProjectileShapeAssetId);
  325. return false;
  326. }
  327. else
  328. {
  329. activateSeq = mProjectileShape->findSequence("activate");
  330. maintainSeq = mProjectileShape->findSequence("maintain");
  331. TSShapeInstance* pDummy = new TSShapeInstance(mProjectileShape, !server);
  332. delete pDummy;
  333. }
  334. }
  335. return true;
  336. }
  337. //--------------------------------------------------------------------------
  338. void ProjectileData::packData(BitStream* stream)
  339. {
  340. Parent::packData(stream);
  341. PACKDATA_ASSET(ProjectileShape);
  342. stream->writeFlag(faceViewer);
  343. if(stream->writeFlag(scale.x != 1 || scale.y != 1 || scale.z != 1))
  344. {
  345. stream->write(scale.x);
  346. stream->write(scale.y);
  347. stream->write(scale.z);
  348. }
  349. if (stream->writeFlag(particleEmitter != NULL))
  350. stream->writeRangedU32(particleEmitter->getId(), DataBlockObjectIdFirst,
  351. DataBlockObjectIdLast);
  352. if (stream->writeFlag(particleWaterEmitter != NULL))
  353. stream->writeRangedU32(particleWaterEmitter->getId(), DataBlockObjectIdFirst,
  354. DataBlockObjectIdLast);
  355. if (stream->writeFlag(explosion != NULL))
  356. stream->writeRangedU32(explosion->getId(), DataBlockObjectIdFirst,
  357. DataBlockObjectIdLast);
  358. if (stream->writeFlag(waterExplosion != NULL))
  359. stream->writeRangedU32(waterExplosion->getId(), DataBlockObjectIdFirst,
  360. DataBlockObjectIdLast);
  361. if (stream->writeFlag(splash != NULL))
  362. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst,
  363. DataBlockObjectIdLast);
  364. if (stream->writeFlag(decal != NULL))
  365. stream->writeRangedU32(decal->getId(), DataBlockObjectIdFirst,
  366. DataBlockObjectIdLast);
  367. PACKDATA_ASSET(ProjectileSound);
  368. if ( stream->writeFlag(lightDesc != NULL))
  369. stream->writeRangedU32(lightDesc->getId(), DataBlockObjectIdFirst,
  370. DataBlockObjectIdLast);
  371. stream->write(impactForce);
  372. // stream->writeRangedU32(lifetime, 0, Projectile::MaxLivingTicks);
  373. // stream->writeRangedU32(armingDelay, 0, Projectile::MaxLivingTicks);
  374. // stream->writeRangedU32(fadeDelay, 0, Projectile::MaxLivingTicks);
  375. // [tom, 3/21/2007] Changing these to write all 32 bits as the previous
  376. // code limited these to a max value of 4095.
  377. stream->write(lifetime);
  378. stream->write(armingDelay);
  379. stream->write(fadeDelay);
  380. if(stream->writeFlag(isBallistic))
  381. {
  382. stream->write(gravityMod);
  383. stream->write(bounceElasticity);
  384. stream->write(bounceFriction);
  385. }
  386. }
  387. void ProjectileData::unpackData(BitStream* stream)
  388. {
  389. Parent::unpackData(stream);
  390. UNPACKDATA_ASSET(ProjectileShape);
  391. faceViewer = stream->readFlag();
  392. if(stream->readFlag())
  393. {
  394. stream->read(&scale.x);
  395. stream->read(&scale.y);
  396. stream->read(&scale.z);
  397. }
  398. else
  399. scale.set(1,1,1);
  400. if (stream->readFlag())
  401. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  402. if (stream->readFlag())
  403. particleWaterEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  404. if (stream->readFlag())
  405. explosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  406. if (stream->readFlag())
  407. waterExplosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  408. if (stream->readFlag())
  409. splashId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  410. if (stream->readFlag())
  411. decalId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  412. UNPACKDATA_ASSET(ProjectileSound);
  413. if (stream->readFlag())
  414. lightDescId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  415. // [tom, 3/21/2007] See comment in packData()
  416. // lifetime = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  417. // armingDelay = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  418. // fadeDelay = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  419. stream->read(&impactForce);
  420. stream->read(&lifetime);
  421. stream->read(&armingDelay);
  422. stream->read(&fadeDelay);
  423. isBallistic = stream->readFlag();
  424. if(isBallistic)
  425. {
  426. stream->read(&gravityMod);
  427. stream->read(&bounceElasticity);
  428. stream->read(&bounceFriction);
  429. }
  430. }
  431. bool ProjectileData::setLifetime( void *obj, const char *index, const char *data )
  432. {
  433. S32 value = dAtoi(data);
  434. value = scaleValue(value);
  435. ProjectileData *object = static_cast<ProjectileData*>(obj);
  436. object->lifetime = value;
  437. return false;
  438. }
  439. bool ProjectileData::setArmingDelay( void *obj, const char *index, const char *data )
  440. {
  441. S32 value = dAtoi(data);
  442. value = scaleValue(value);
  443. ProjectileData *object = static_cast<ProjectileData*>(obj);
  444. object->armingDelay = value;
  445. return false;
  446. }
  447. bool ProjectileData::setFadeDelay( void *obj, const char *index, const char *data )
  448. {
  449. S32 value = dAtoi(data);
  450. value = scaleValue(value);
  451. ProjectileData *object = static_cast<ProjectileData*>(obj);
  452. object->fadeDelay = value;
  453. return false;
  454. }
  455. const char *ProjectileData::getScaledValue( void *obj, const char *data)
  456. {
  457. S32 value = dAtoi(data);
  458. value = scaleValue(value, false);
  459. String stringData = String::ToString(value);
  460. char *strBuffer = Con::getReturnBuffer(stringData.size());
  461. dMemcpy( strBuffer, stringData, stringData.size() );
  462. return strBuffer;
  463. }
  464. S32 ProjectileData::scaleValue( S32 value, bool down )
  465. {
  466. S32 minV = 0;
  467. S32 maxV = Projectile::MaxLivingTicks;
  468. // scale down to ticks before we validate
  469. if( down )
  470. value /= TickMs;
  471. if(value < minV || value > maxV)
  472. {
  473. Con::errorf("ProjectileData::scaleValue(S32 value = %d, bool down = %b) - Scaled value must be between %d and %d", value, down, minV, maxV);
  474. if(value < minV)
  475. value = minV;
  476. else if(value > maxV)
  477. value = maxV;
  478. }
  479. // scale up from ticks after we validate
  480. if( !down )
  481. value *= TickMs;
  482. return value;
  483. }
  484. //--------------------------------------------------------------------------
  485. //--------------------------------------
  486. //
  487. Projectile::Projectile()
  488. : mPhysicsWorld( NULL ),
  489. mDataBlock( NULL ),
  490. mParticleEmitter( NULL ),
  491. mParticleWaterEmitter( NULL ),
  492. mSound( NULL ),
  493. mCurrPosition( 0, 0, 0 ),
  494. mCurrVelocity( 0, 0, 1 ),
  495. mSourceObjectId( -1 ),
  496. mSourceObjectSlot( -1 ),
  497. mCurrTick( 0 ),
  498. mProjectileShape( NULL ),
  499. mActivateThread( NULL ),
  500. mMaintainThread( NULL ),
  501. mHasExploded( false ),
  502. mFadeValue( 1.0f )
  503. {
  504. // Todo: ScopeAlways?
  505. mNetFlags.set(Ghostable);
  506. mTypeMask |= ProjectileObjectType | LightObjectType | DynamicShapeObjectType;
  507. mLight = LightManager::createLightInfo();
  508. mLight->setType( LightInfo::Point );
  509. mLightState.clear();
  510. mLightState.setLightInfo( mLight );
  511. mDataBlock = 0;
  512. ignoreSourceTimeout = false;
  513. dynamicCollisionMask = csmDynamicCollisionMask;
  514. staticCollisionMask = csmStaticCollisionMask;
  515. }
  516. Projectile::~Projectile()
  517. {
  518. SAFE_DELETE(mLight);
  519. delete mProjectileShape;
  520. mProjectileShape = NULL;
  521. if (mDataBlock && mDataBlock->isTempClone())
  522. {
  523. delete mDataBlock;
  524. mDataBlock = 0;
  525. }
  526. }
  527. //--------------------------------------------------------------------------
  528. void Projectile::initPersistFields()
  529. {
  530. docsURL;
  531. addGroup("Physics");
  532. addProtectedField("initialPosition", TypePoint3F, Offset(mInitialPosition, Projectile), &_setInitialPosition, &defaultProtectedGetFn,
  533. "@brief Starting position for the projectile.\n\n");
  534. //addField("initialPosition", TypePoint3F, Offset(mCurrPosition, Projectile),
  535. // "@brief Starting position for the projectile.\n\n");
  536. addProtectedField("initialVelocity", TypePoint3F, Offset(mInitialVelocity, Projectile), &_setInitialVelocity, &defaultProtectedGetFn,
  537. "@brief Starting velocity for the projectile.\n\n");
  538. //addField("initialVelocity", TypePoint3F, Offset(mCurrVelocity, Projectile),
  539. // "@brief Starting velocity for the projectile.\n\n");
  540. endGroup("Physics");
  541. addGroup("Source");
  542. addField("sourceObject", TypeS32, Offset(mSourceObjectId, Projectile),
  543. "@brief ID number of the object that fired the projectile.\n\n"
  544. "@note If the projectile was fired by a WeaponImage, sourceObject will be "
  545. "the object that owns the WeaponImage. This is usually the player.");
  546. addField("sourceSlot", TypeS32, Offset(mSourceObjectSlot, Projectile),
  547. "@brief The sourceObject's weapon slot that the projectile originates from.\n\n");
  548. addField("ignoreSourceTimeout", TypeBool, Offset(ignoreSourceTimeout, Projectile));
  549. endGroup("Source");
  550. Parent::initPersistFields();
  551. }
  552. bool Projectile::_setInitialPosition( void *object, const char *index, const char *data )
  553. {
  554. Projectile* p = static_cast<Projectile*>( object );
  555. if ( p )
  556. {
  557. Point3F pos;
  558. S32 count = dSscanf( data, "%f %f %f",
  559. &pos.x, &pos.y, &pos.z);
  560. if ( (count != 3) )
  561. {
  562. Con::printf("Projectile: Failed to parse initial position \"px py pz\" from '%s'", data);
  563. return false;
  564. }
  565. p->setInitialPosition( pos );
  566. }
  567. return false;
  568. }
  569. void Projectile::setInitialPosition( const Point3F& pos )
  570. {
  571. mInitialPosition = pos;
  572. mCurrPosition = pos;
  573. }
  574. bool Projectile::_setInitialVelocity( void *object, const char *index, const char *data )
  575. {
  576. Projectile* p = static_cast<Projectile*>( object );
  577. if ( p )
  578. {
  579. Point3F vel;
  580. S32 count = dSscanf( data, "%f %f %f",
  581. &vel.x, &vel.y, &vel.z);
  582. if ( (count != 3) )
  583. {
  584. Con::printf("Projectile: Failed to parse initial velocity \"vx vy vz\" from '%s'", data);
  585. return false;
  586. }
  587. p->setInitialVelocity( vel );
  588. }
  589. return false;
  590. }
  591. void Projectile::setInitialVelocity( const Point3F& vel )
  592. {
  593. mInitialVelocity = vel;
  594. mCurrVelocity = vel;
  595. }
  596. //--------------------------------------------------------------------------
  597. bool Projectile::calculateImpact(float,
  598. Point3F& pointOfImpact,
  599. float& impactTime)
  600. {
  601. Con::warnf(ConsoleLogEntry::General, "Projectile::calculateImpact: Should never be called");
  602. impactTime = 0;
  603. pointOfImpact.set(0, 0, 0);
  604. return false;
  605. }
  606. //--------------------------------------------------------------------------
  607. F32 Projectile::getUpdatePriority(CameraScopeQuery *camInfo, U32 updateMask, S32 updateSkips)
  608. {
  609. F32 ret = Parent::getUpdatePriority(camInfo, updateMask, updateSkips);
  610. // if the camera "owns" this object, it should have a slightly higher priority
  611. if(mSourceObject == camInfo->camera)
  612. return ret + 0.2;
  613. return ret;
  614. }
  615. bool Projectile::onAdd()
  616. {
  617. if(!Parent::onAdd())
  618. return false;
  619. if( !mDataBlock )
  620. {
  621. Con::errorf("Projectile::onAdd - Fail - Not datablock");
  622. return false;
  623. }
  624. if (isServerObject())
  625. {
  626. ShapeBase* ptr;
  627. if (Sim::findObject(mSourceObjectId, ptr))
  628. {
  629. mSourceObject = ptr;
  630. // Since we later do processAfter( mSourceObject ) we must clearProcessAfter
  631. // if it is deleted. SceneObject already handles this in onDeleteNotify so
  632. // all we need to do is register for the notification.
  633. deleteNotify( ptr );
  634. }
  635. else
  636. {
  637. if (mSourceObjectId != -1)
  638. Con::errorf(ConsoleLogEntry::General, "Projectile::onAdd: mSourceObjectId is invalid");
  639. mSourceObject = NULL;
  640. }
  641. // If we're on the server, we need to inherit some of our parent's velocity
  642. //
  643. mCurrTick = 0;
  644. scriptOnAdd();
  645. }
  646. else
  647. {
  648. if (bool(mDataBlock->mProjectileShape))
  649. {
  650. mProjectileShape = new TSShapeInstance(mDataBlock->mProjectileShape, isClientObject());
  651. if (mDataBlock->activateSeq != -1)
  652. {
  653. mActivateThread = mProjectileShape->addThread();
  654. mProjectileShape->setTimeScale(mActivateThread, 1);
  655. mProjectileShape->setSequence(mActivateThread, mDataBlock->activateSeq, 0);
  656. }
  657. }
  658. if (mDataBlock->particleEmitter != NULL)
  659. {
  660. ParticleEmitter* pEmitter = new ParticleEmitter;
  661. pEmitter->onNewDataBlock(mDataBlock->particleEmitter,false);
  662. if (pEmitter->registerObject() == false)
  663. {
  664. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  665. delete pEmitter;
  666. pEmitter = NULL;
  667. }
  668. mParticleEmitter = pEmitter;
  669. }
  670. if (mDataBlock->particleWaterEmitter != NULL)
  671. {
  672. ParticleEmitter* pEmitter = new ParticleEmitter;
  673. pEmitter->onNewDataBlock(mDataBlock->particleWaterEmitter,false);
  674. if (pEmitter->registerObject() == false)
  675. {
  676. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  677. delete pEmitter;
  678. pEmitter = NULL;
  679. }
  680. mParticleWaterEmitter = pEmitter;
  681. }
  682. }
  683. if (mSourceObject.isValid())
  684. processAfter(mSourceObject);
  685. // Setup our bounding box
  686. if (bool(mDataBlock->mProjectileShape) == true)
  687. mObjBox = mDataBlock->mProjectileShape->mBounds;
  688. else
  689. mObjBox = Box3F(Point3F(0, 0, 0), Point3F(0, 0, 0));
  690. MatrixF initialTransform( true );
  691. initialTransform.setPosition( mCurrPosition );
  692. setTransform( initialTransform ); // calls resetWorldBox
  693. addToScene();
  694. if ( PHYSICSMGR )
  695. mPhysicsWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  696. return true;
  697. }
  698. void Projectile::onRemove()
  699. {
  700. if( !mParticleEmitter.isNull() )
  701. {
  702. mParticleEmitter->deleteWhenEmpty();
  703. mParticleEmitter = NULL;
  704. }
  705. if( !mParticleWaterEmitter.isNull() )
  706. {
  707. mParticleWaterEmitter->deleteWhenEmpty();
  708. mParticleWaterEmitter = NULL;
  709. }
  710. SFX_DELETE( mSound );
  711. removeFromScene();
  712. Parent::onRemove();
  713. }
  714. bool Projectile::onNewDataBlock( GameBaseData *dptr, bool reload )
  715. {
  716. mDataBlock = dynamic_cast<ProjectileData*>( dptr );
  717. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  718. return false;
  719. if ( isGhost() )
  720. {
  721. // Create the sound ahead of time. This reduces runtime
  722. // costs and makes the system easier to understand.
  723. SFX_DELETE( mSound );
  724. if ( mDataBlock->getProjectileSound() )
  725. mSound = SFX->createSource( mDataBlock->getProjectileSoundProfile() );
  726. }
  727. return true;
  728. }
  729. void Projectile::submitLights( LightManager *lm, bool staticLighting )
  730. {
  731. if ( staticLighting || mHasExploded || !mDataBlock->lightDesc )
  732. return;
  733. mDataBlock->lightDesc->submitLight( &mLightState, getRenderTransform(), lm, this );
  734. }
  735. bool Projectile::pointInWater(const Point3F &point)
  736. {
  737. // This is pretty much a hack so we can use the existing ContainerQueryInfo
  738. // and findObject router.
  739. // We only care if we intersect with water at all
  740. // so build a box at the point that has only 1 z extent.
  741. // And test if water coverage is anything other than zero.
  742. Box3F boundsBox( point, point );
  743. boundsBox.maxExtents.z += 1.0f;
  744. ContainerQueryInfo info;
  745. info.box = boundsBox;
  746. info.mass = 0.0f;
  747. // Find and retreive physics info from intersecting WaterObject(s)
  748. if(mContainer != NULL)
  749. {
  750. mContainer->findObjects( boundsBox, WaterObjectType, findRouter, &info );
  751. }
  752. else
  753. {
  754. // Handle special case where the projectile has exploded prior to having
  755. // called onAdd() on the client. This occurs when the projectile on the
  756. // server is created and then explodes in the same network update tick.
  757. // On the client end in NetConnection::ghostReadPacket() the ghost is
  758. // created and then Projectile::unpackUpdate() is called prior to the
  759. // projectile being registered. Within unpackUpdate() the explosion
  760. // is triggered, but without being registered onAdd() isn't called and
  761. // the container is not set. As all we're doing is checking if the
  762. // given explosion point is within water, we should be able to use the
  763. // global container here. We could likely always get away with this,
  764. // but using the actual defined container when possible is the right
  765. // thing to do. DAW
  766. AssertFatal(isClientObject(), "Server projectile has not been properly added");
  767. gClientContainer.findObjects( boundsBox, WaterObjectType, findRouter, &info );
  768. }
  769. return ( info.waterCoverage > 0.0f );
  770. }
  771. //----------------------------------------------------------------------------
  772. void Projectile::emitParticles(const Point3F& from, const Point3F& to, const Point3F& vel, const U32 ms)
  773. {
  774. if ( mHasExploded )
  775. return;
  776. Point3F axis = -vel;
  777. if( axis.isZero() )
  778. axis.set( 0.0, 0.0, 1.0 );
  779. else
  780. axis.normalize();
  781. bool fromWater = pointInWater(from);
  782. bool toWater = pointInWater(to);
  783. if (!fromWater && !toWater && bool(mParticleEmitter)) // not in water
  784. mParticleEmitter->emitParticles(from, to, axis, vel, ms);
  785. else if (fromWater && toWater && bool(mParticleWaterEmitter)) // in water
  786. mParticleWaterEmitter->emitParticles(from, to, axis, vel, ms);
  787. else if (!fromWater && toWater && mDataBlock->splash) // entering water
  788. {
  789. // cast the ray to get the surface point of the water
  790. RayInfo rInfo;
  791. if (gClientContainer.castRay(from, to, WaterObjectType, &rInfo))
  792. {
  793. MatrixF trans = getTransform();
  794. trans.setPosition(rInfo.point);
  795. Splash *splash = new Splash();
  796. splash->onNewDataBlock(mDataBlock->splash, false);
  797. splash->setTransform(trans);
  798. splash->setInitialState(trans.getPosition(), Point3F(0.0, 0.0, 1.0));
  799. if (!splash->registerObject())
  800. {
  801. delete splash;
  802. splash = NULL;
  803. }
  804. // create an emitter for the particles out of water and the particles in water
  805. if (mParticleEmitter)
  806. mParticleEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  807. if (mParticleWaterEmitter)
  808. mParticleWaterEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  809. }
  810. }
  811. else if (fromWater && !toWater && mDataBlock->splash) // leaving water
  812. {
  813. // cast the ray in the opposite direction since that point is out of the water, otherwise
  814. // we hit water immediately and wont get the appropriate surface point
  815. RayInfo rInfo;
  816. if (gClientContainer.castRay(to, from, WaterObjectType, &rInfo))
  817. {
  818. MatrixF trans = getTransform();
  819. trans.setPosition(rInfo.point);
  820. Splash *splash = new Splash();
  821. splash->onNewDataBlock(mDataBlock->splash,false);
  822. splash->setTransform(trans);
  823. splash->setInitialState(trans.getPosition(), Point3F(0.0, 0.0, 1.0));
  824. if (!splash->registerObject())
  825. {
  826. delete splash;
  827. splash = NULL;
  828. }
  829. // create an emitter for the particles out of water and the particles in water
  830. if (mParticleEmitter)
  831. mParticleEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  832. if (mParticleWaterEmitter)
  833. mParticleWaterEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  834. }
  835. }
  836. }
  837. void Projectile::explode( const Point3F &p, const Point3F &n, const U32 collideType )
  838. {
  839. // Make sure we don't explode twice...
  840. if ( mHasExploded )
  841. return;
  842. mHasExploded = true;
  843. // Move the explosion point slightly off the surface to avoid problems with radius damage
  844. Point3F explodePos = p + n * 0.001f;
  845. if ( isServerObject() )
  846. {
  847. // Do what the server needs to do, damage the surrounding objects, etc.
  848. mExplosionPosition = explodePos;
  849. mExplosionNormal = n;
  850. mCollideHitType = collideType;
  851. mDataBlock->onExplode_callback( this, mExplosionPosition, mFadeValue );
  852. setMaskBits(ExplosionMask);
  853. // Just wait till the timeout to self delete. This
  854. // gives server object time to get ghosted to the client.
  855. }
  856. else
  857. {
  858. // Client just plays the explosion at the right place...
  859. //
  860. Explosion* pExplosion = NULL;
  861. if (mDataBlock->waterExplosion && pointInWater(p))
  862. {
  863. pExplosion = new Explosion;
  864. pExplosion->onNewDataBlock(mDataBlock->waterExplosion, false);
  865. }
  866. else
  867. if (mDataBlock->explosion)
  868. {
  869. pExplosion = new Explosion;
  870. pExplosion->onNewDataBlock(mDataBlock->explosion, false);
  871. }
  872. if( pExplosion )
  873. {
  874. MatrixF xform(true);
  875. xform.setPosition(explodePos);
  876. pExplosion->setTransform(xform);
  877. pExplosion->setInitialState(explodePos, n);
  878. pExplosion->setCollideType( collideType );
  879. if (pExplosion->registerObject() == false)
  880. {
  881. Con::errorf(ConsoleLogEntry::General, "Projectile(%s)::explode: couldn't register explosion",
  882. mDataBlock->getName() );
  883. delete pExplosion;
  884. pExplosion = NULL;
  885. }
  886. }
  887. // Client (impact) decal.
  888. if ( mDataBlock->decal )
  889. gDecalManager->addDecal(p, n, 0.0f, mDataBlock->decal);
  890. // Client object
  891. updateSound();
  892. }
  893. /*
  894. // Client and Server both should apply forces to PhysicsWorld objects
  895. // within the explosion.
  896. if ( false && mPhysicsWorld )
  897. {
  898. F32 force = 200.0f;
  899. mPhysicsWorld->explosion( p, 15.0f, force );
  900. }
  901. */
  902. }
  903. void Projectile::updateSound()
  904. {
  905. if (!mDataBlock->isProjectileSoundValid())
  906. return;
  907. if ( mSound )
  908. {
  909. if ( mHasExploded )
  910. mSound->stop();
  911. else
  912. {
  913. if ( !mSound->isPlaying() )
  914. mSound->play();
  915. mSound->setVelocity( getVelocity() );
  916. mSound->setTransform( getRenderTransform() );
  917. }
  918. }
  919. }
  920. void Projectile::processTick( const Move *move )
  921. {
  922. Parent::processTick( move );
  923. mCurrTick++;
  924. simulate( TickSec );
  925. }
  926. void Projectile::simulate( F32 dt )
  927. {
  928. if ( isServerObject() && mCurrTick >= mDataBlock->lifetime )
  929. {
  930. deleteObject();
  931. return;
  932. }
  933. if ( mHasExploded )
  934. return;
  935. // ... otherwise, we have to do some simulation work.
  936. RayInfo rInfo;
  937. Point3F oldPosition;
  938. Point3F newPosition;
  939. oldPosition = mCurrPosition;
  940. if ( mDataBlock->isBallistic )
  941. mCurrVelocity.z -= 9.81 * mDataBlock->gravityMod * dt;
  942. newPosition = oldPosition + mCurrVelocity * dt;
  943. // disable the source objects collision reponse for a short time while we
  944. // determine if the projectile is capable of moving from the old position
  945. // to the new position, otherwise we'll hit ourself
  946. bool disableSourceObjCollision = (mSourceObject.isValid() && (ignoreSourceTimeout || mCurrTick <= SourceIdTimeoutTicks));
  947. if ( disableSourceObjCollision )
  948. mSourceObject->disableCollision();
  949. disableCollision();
  950. // Determine if the projectile is going to hit any object between the previous
  951. // position and the new position. This code is executed both on the server
  952. // and on the client (for prediction purposes). It is possible that the server
  953. // will have registered a collision while the client prediction has not. If this
  954. // happens the client will be corrected in the next packet update.
  955. // Raycast the abstract PhysicsWorld if a PhysicsPlugin exists.
  956. bool hit = false;
  957. if ( mPhysicsWorld )
  958. hit = mPhysicsWorld->castRay( oldPosition, newPosition, &rInfo, Point3F( newPosition - oldPosition) * mDataBlock->impactForce );
  959. else
  960. hit = getContainer()->castRay(oldPosition, newPosition, dynamicCollisionMask | staticCollisionMask, &rInfo);
  961. if ( hit )
  962. {
  963. // make sure the client knows to bounce
  964. if(isServerObject() && (rInfo.object->getTypeMask() & staticCollisionMask) == 0)
  965. setMaskBits( BounceMask );
  966. MatrixF xform( true );
  967. xform.setColumn( 3, rInfo.point );
  968. setTransform( xform );
  969. mCurrPosition = rInfo.point;
  970. // Get the object type before the onCollision call, in case
  971. // the object is destroyed.
  972. U32 objectType = rInfo.object->getTypeMask();
  973. // re-enable the collision response on the source object since
  974. // we need to process the onCollision and explode calls
  975. if ( disableSourceObjCollision )
  976. mSourceObject->enableCollision();
  977. // Ok, here is how this works:
  978. // onCollision is called to notify the server scripts that a collision has occurred, then
  979. // a call to explode is made to start the explosion process. The call to explode is made
  980. // twice, once on the server and once on the client.
  981. // The server process is responsible for two things:
  982. // 1) setting the ExplosionMask network bit to guarantee that the client calls explode
  983. // 2) initiate the explosion process on the server scripts
  984. // The client process is responsible for only one thing:
  985. // 1) drawing the appropriate explosion
  986. // It is possible that during the processTick the server may have decided that a hit
  987. // has occurred while the client prediction has decided that a hit has not occurred.
  988. // In this particular scenario the client will have failed to call onCollision and
  989. // explode during the processTick. However, the explode function will be called
  990. // during the next packet update, due to the ExplosionMask network bit being set.
  991. // onCollision will remain uncalled on the client however, therefore no client
  992. // specific code should be placed inside the function!
  993. onCollision( rInfo.point, rInfo.normal, rInfo.object );
  994. // Next order of business: do we explode on this hit?
  995. if ( mCurrTick > mDataBlock->armingDelay || mDataBlock->armingDelay == 0 )
  996. {
  997. mCurrVelocity = Point3F::Zero;
  998. explode( rInfo.point, rInfo.normal, objectType );
  999. }
  1000. if ( mDataBlock->isBallistic )
  1001. {
  1002. // Otherwise, this represents a bounce. First, reflect our velocity
  1003. // around the normal...
  1004. Point3F bounceVel = mCurrVelocity - rInfo.normal * (mDot( mCurrVelocity, rInfo.normal ) * 2.0);
  1005. mCurrVelocity = bounceVel;
  1006. // Add in surface friction...
  1007. Point3F tangent = bounceVel - rInfo.normal * mDot(bounceVel, rInfo.normal);
  1008. mCurrVelocity -= tangent * mDataBlock->bounceFriction;
  1009. // Now, take elasticity into account for modulating the speed of the grenade
  1010. mCurrVelocity *= mDataBlock->bounceElasticity;
  1011. // Set the new position to the impact and the bounce
  1012. // will apply on the next frame.
  1013. //F32 timeLeft = 1.0f - rInfo.t;
  1014. newPosition = oldPosition = rInfo.point + rInfo.normal * 0.05f;
  1015. }
  1016. else
  1017. {
  1018. mCurrVelocity = Point3F::Zero;
  1019. }
  1020. }
  1021. // re-enable the collision response on the source object now
  1022. // that we are done processing the ballistic movement
  1023. if ( disableSourceObjCollision )
  1024. mSourceObject->enableCollision();
  1025. enableCollision();
  1026. if ( isClientObject() )
  1027. {
  1028. emitParticles( mCurrPosition, newPosition, mCurrVelocity, U32( dt * 1000.0f ) );
  1029. updateSound();
  1030. }
  1031. mCurrDeltaBase = newPosition;
  1032. mCurrBackDelta = mCurrPosition - newPosition;
  1033. mCurrPosition = newPosition;
  1034. MatrixF xform( true );
  1035. xform.setColumn( 3, mCurrPosition );
  1036. setTransform( xform );
  1037. }
  1038. void Projectile::advanceTime(F32 dt)
  1039. {
  1040. Parent::advanceTime(dt);
  1041. if ( mHasExploded || dt == 0.0)
  1042. return;
  1043. if (mActivateThread &&
  1044. mProjectileShape->getDuration(mActivateThread) > mProjectileShape->getTime(mActivateThread) + dt)
  1045. {
  1046. mProjectileShape->advanceTime(dt, mActivateThread);
  1047. }
  1048. else
  1049. {
  1050. if (mMaintainThread)
  1051. {
  1052. mProjectileShape->advanceTime(dt, mMaintainThread);
  1053. }
  1054. else if (mActivateThread && mDataBlock->maintainSeq != -1)
  1055. {
  1056. mMaintainThread = mProjectileShape->addThread();
  1057. mProjectileShape->setTimeScale(mMaintainThread, 1);
  1058. mProjectileShape->setSequence(mMaintainThread, mDataBlock->maintainSeq, 0);
  1059. mProjectileShape->advanceTime(dt, mMaintainThread);
  1060. }
  1061. }
  1062. }
  1063. void Projectile::interpolateTick(F32 delta)
  1064. {
  1065. Parent::interpolateTick(delta);
  1066. if( mHasExploded )
  1067. return;
  1068. Point3F interpPos = mCurrDeltaBase + mCurrBackDelta * delta;
  1069. Point3F dir = mCurrVelocity;
  1070. if(dir.isZero())
  1071. dir.set(0,0,1);
  1072. else
  1073. dir.normalize();
  1074. MatrixF xform(true);
  1075. xform = MathUtils::createOrientFromDir(dir);
  1076. xform.setPosition(interpPos);
  1077. setRenderTransform(xform);
  1078. // fade out the projectile image
  1079. S32 time = (S32)(mCurrTick - delta);
  1080. if(time > mDataBlock->fadeDelay)
  1081. {
  1082. F32 fade = F32(time - mDataBlock->fadeDelay);
  1083. mFadeValue = 1.0 - (fade / F32(mDataBlock->lifetime));
  1084. }
  1085. else
  1086. mFadeValue = 1.0;
  1087. updateSound();
  1088. }
  1089. //--------------------------------------------------------------------------
  1090. void Projectile::onCollision(const Point3F& hitPosition, const Point3F& hitNormal, SceneObject* hitObject)
  1091. {
  1092. // No client specific code should be placed or branched from this function
  1093. if(isClientObject())
  1094. return;
  1095. if (hitObject != NULL && isServerObject())
  1096. {
  1097. mDataBlock->onCollision_callback( this, hitObject, mFadeValue, hitPosition, hitNormal );
  1098. }
  1099. }
  1100. //--------------------------------------------------------------------------
  1101. U32 Projectile::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  1102. {
  1103. U32 retMask = Parent::packUpdate( con, mask, stream );
  1104. const bool isInitalUpdate = mask & GameBase::InitialUpdateMask;
  1105. // InitialUpdateMask
  1106. if ( stream->writeFlag( isInitalUpdate ) )
  1107. {
  1108. stream->writeRangedU32( mCurrTick, 0, MaxLivingTicks );
  1109. if ( mSourceObject.isValid() )
  1110. {
  1111. // Potentially have to write this to the client, let's make sure it has a
  1112. // ghost on the other side...
  1113. S32 ghostIndex = con->getGhostIndex( mSourceObject );
  1114. if ( stream->writeFlag( ghostIndex != -1 ) )
  1115. {
  1116. stream->writeRangedU32( U32(ghostIndex),
  1117. 0,
  1118. NetConnection::MaxGhostCount );
  1119. stream->writeRangedU32( U32(mSourceObjectSlot),
  1120. 0,
  1121. ShapeBase::MaxMountedImages - 1 );
  1122. stream->writeFlag(ignoreSourceTimeout);
  1123. }
  1124. else
  1125. // have not recieved the ghost for the source object yet, try again later
  1126. retMask |= GameBase::InitialUpdateMask;
  1127. }
  1128. else
  1129. stream->writeFlag( false );
  1130. }
  1131. // ExplosionMask
  1132. //
  1133. // ExplosionMask will be set during the initial update but hidden is
  1134. // only true if we have really exploded.
  1135. if ( stream->writeFlag( ( mask & ExplosionMask ) && mHasExploded ) )
  1136. {
  1137. mathWrite(*stream, mExplosionPosition);
  1138. mathWrite(*stream, mExplosionNormal);
  1139. stream->write(mCollideHitType);
  1140. }
  1141. // BounceMask
  1142. if ( stream->writeFlag( mask & BounceMask ) )
  1143. {
  1144. // Bounce against dynamic object
  1145. mathWrite(*stream, mCurrPosition);
  1146. mathWrite(*stream, mCurrVelocity);
  1147. }
  1148. return retMask;
  1149. }
  1150. void Projectile::unpackUpdate(NetConnection* con, BitStream* stream)
  1151. {
  1152. Parent::unpackUpdate(con, stream);
  1153. if ( stream->readFlag() ) // InitialUpdateMask
  1154. {
  1155. mCurrTick = stream->readRangedU32( 0, MaxLivingTicks );
  1156. if ( stream->readFlag() )
  1157. {
  1158. mSourceObjectId = stream->readRangedU32( 0, NetConnection::MaxGhostCount );
  1159. mSourceObjectSlot = stream->readRangedU32( 0, ShapeBase::MaxMountedImages - 1 );
  1160. ignoreSourceTimeout = stream->readFlag();
  1161. NetObject* pObject = con->resolveGhost( mSourceObjectId );
  1162. if ( pObject != NULL )
  1163. mSourceObject = dynamic_cast<ShapeBase*>( pObject );
  1164. }
  1165. else
  1166. {
  1167. mSourceObjectId = -1;
  1168. mSourceObjectSlot = -1;
  1169. mSourceObject = NULL;
  1170. }
  1171. }
  1172. if ( stream->readFlag() ) // ExplosionMask
  1173. {
  1174. Point3F explodePoint;
  1175. Point3F explodeNormal;
  1176. mathRead( *stream, &explodePoint );
  1177. mathRead( *stream, &explodeNormal );
  1178. stream->read( &mCollideHitType );
  1179. // start the explosion visuals
  1180. explode( explodePoint, explodeNormal, mCollideHitType );
  1181. }
  1182. if ( stream->readFlag() ) // BounceMask
  1183. {
  1184. Point3F pos;
  1185. mathRead( *stream, &pos );
  1186. mathRead( *stream, &mCurrVelocity );
  1187. mCurrDeltaBase = pos;
  1188. mCurrBackDelta = mCurrPosition - pos;
  1189. mCurrPosition = pos;
  1190. setPosition( mCurrPosition );
  1191. }
  1192. }
  1193. //--------------------------------------------------------------------------
  1194. void Projectile::prepRenderImage( SceneRenderState* state )
  1195. {
  1196. if (mHasExploded || mFadeValue <= (1.0/255.0))
  1197. return;
  1198. if ( mDataBlock->lightDesc )
  1199. {
  1200. mDataBlock->lightDesc->prepRender( state, &mLightState, getRenderTransform() );
  1201. }
  1202. /*
  1203. if ( mFlareData )
  1204. {
  1205. mFlareState.fullBrightness = mDataBlock->lightDesc->mBrightness;
  1206. mFlareState.scale = mFlareScale;
  1207. mFlareState.lightInfo = mLight;
  1208. mFlareState.lightMat = getTransform();
  1209. mFlareData->prepRender( state, &mFlareState );
  1210. }
  1211. */
  1212. prepBatchRender( state );
  1213. }
  1214. void Projectile::prepBatchRender( SceneRenderState *state )
  1215. {
  1216. if ( !mProjectileShape )
  1217. return;
  1218. GFXTransformSaver saver;
  1219. // Set up our TS render state.
  1220. TSRenderState rdata;
  1221. rdata.setSceneState( state );
  1222. // We might have some forward lit materials
  1223. // so pass down a query to gather lights.
  1224. LightQuery query;
  1225. query.init( getWorldSphere() );
  1226. rdata.setLightQuery( &query );
  1227. MatrixF mat = getRenderTransform();
  1228. mat.scale( mObjScale );
  1229. mat.scale( mDataBlock->scale );
  1230. GFX->setWorldMatrix( mat );
  1231. mProjectileShape->setDetailFromPosAndScale( state, mat.getPosition(), mObjScale );
  1232. mProjectileShape->animate();
  1233. mProjectileShape->render( rdata );
  1234. }
  1235. DefineEngineMethod(Projectile, presimulate, void, (F32 seconds), (1.0f),
  1236. "@brief Updates the projectile's positional and collision information.\n\n"
  1237. "This function will first delete the projectile if it is a server object and is outside it's ProjectileData::lifetime. "
  1238. "Also responsible for applying gravity, determining collisions, triggering explosions, "
  1239. "emitting trail particles, and calculating bounces if necessary."
  1240. "@param seconds Amount of time, in seconds since the simulation's start, to advance.\n"
  1241. "@tsexample\n"
  1242. "// Tell the projectile to process a simulation event, and provide the amount of time\n"
  1243. "// that has passed since the simulation began.\n"
  1244. "%seconds = 2.0;\n"
  1245. "%projectile.presimulate(%seconds);\n"
  1246. "@endtsexample\n"
  1247. "@note This function is not called if the SimObject::hidden is true.")
  1248. {
  1249. object->simulate( seconds );
  1250. }