projectile.cpp 52 KB

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