projectile.cpp 49 KB

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