projectile.cpp 53 KB

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