projectile.cpp 51 KB

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