projectile.cpp 54 KB

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