projectile.cpp 53 KB

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