projectile.cpp 52 KB

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