projectile.cpp 50 KB

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