bullet.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. /*
  2. ** Command & Conquer Renegade(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /***********************************************************************************************
  19. *** Confidential - Westwood Studios ***
  20. ***********************************************************************************************
  21. * *
  22. * Project Name : Commando *
  23. * *
  24. * $Archive:: /Commando/Code/Combat/bullet.cpp $*
  25. * *
  26. * $Author:: Byon_g $*
  27. * *
  28. * $Modtime:: 3/13/02 5:22p $*
  29. * *
  30. * $Revision:: 164 $*
  31. * *
  32. *---------------------------------------------------------------------------------------------*
  33. * Functions: *
  34. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  35. #include "bullet.h"
  36. #include "projectile.h"
  37. #include "combat.h" // for collision groups (should be damage.h?)
  38. #include "pscene.h"
  39. #include "weaponmanager.h"
  40. #include "assets.h"
  41. #include "debug.h"
  42. #include "armedgameobj.h"
  43. #include "crandom.h"
  44. #include "surfaceeffects.h"
  45. #include "mesh.h"
  46. #include "wwaudio.h"
  47. #include "explosion.h"
  48. #include "building.h"
  49. #include "persistfactory.h"
  50. #include "wwphysids.h"
  51. #include "damageablestaticphys.h"
  52. #include "wwprofile.h"
  53. #include "part_emt.h"
  54. #include "realcrc.h"
  55. #include "soldier.h"
  56. #include "segline.h"
  57. #include "timeddecophys.h"
  58. #include "simplegameobj.h"
  59. #include "c4.h"
  60. /*
  61. ** Constants for this module
  62. */
  63. const float _INSTANT_BULLET_THRESHHOLD = 400; // If speed is >= _INSTANT_BULLET_THRESHHOLD m/s, treat it an an instant bullet
  64. /**
  65. ** BeamEffectManagerClass
  66. ** This is a static object that simply manages the active beam effect. Its job is to cache un-used beams
  67. ** so that we aren't allocating them at run time and to add new beam effects to the scene when needed.
  68. */
  69. class BeamEffectManagerClass : public CombatPhysObserverClass
  70. {
  71. public:
  72. void Init( void ) {}
  73. void Shutdown( void );
  74. /*
  75. ** Create a beam effect and put it in the scene. Whenever possible, this function
  76. ** tries to recycle a previously created beam effect
  77. */
  78. void Create_Beam_Effect(const AmmoDefinitionClass * ammo_def,const Vector3 & p0,const Vector3 & p1);
  79. /*
  80. ** PhysObserver Interface - whenever a beam expires, we put it into a list so we can
  81. ** recycle it next time we need a beam effect
  82. */
  83. virtual void Object_Removed_From_Scene(PhysClass * observed_obj);
  84. private:
  85. void Internal_Get_New_Beam(SegmentedLineClass ** beam_model,TimedDecorationPhysClass ** beam_wrapper);
  86. RefMultiListClass<TimedDecorationPhysClass> UnusedBeamList;
  87. };
  88. static BeamEffectManagerClass _TheBeamEffectManager;
  89. void BeamEffectManagerClass::Shutdown( void )
  90. {
  91. while (UnusedBeamList.Peek_Head()) {
  92. UnusedBeamList.Release_Head();
  93. }
  94. }
  95. void BeamEffectManagerClass::Create_Beam_Effect(const AmmoDefinitionClass * ammo_def,const Vector3 & p0,const Vector3 & p1)
  96. {
  97. SegmentedLineClass * beam_model = NULL;
  98. TimedDecorationPhysClass * beam_wrapper = NULL;
  99. Internal_Get_New_Beam(&beam_model,&beam_wrapper);
  100. // line effect from "start" to "data.Position"
  101. static Vector3 points[2];
  102. points[0] = p0;
  103. points[1] = p1;
  104. const int BEAM_SUBDIVISION = 4;
  105. const float BASE_AMPLITUDE = 0.3f;
  106. const float AMPLITUDE_PER_METER = 0.04f;
  107. /*
  108. ** User controlled settings
  109. */
  110. TextureClass * beam_texture = Get_Texture_From_Filename(ammo_def->BeamTexture);
  111. beam_model->Set_Texture(beam_texture);
  112. REF_PTR_RELEASE(beam_texture);
  113. beam_model->Set_Points(2,points);
  114. beam_model->Set_Width(ammo_def->BeamWidth);
  115. beam_model->Set_Color(ammo_def->BeamColor);
  116. beam_model->Set_UV_Offset_Rate(Vector2(0,1.0f / ammo_def->BeamTime));
  117. if (ammo_def->BeamSubdivisionEnabled) {
  118. beam_model->Set_Noise_Amplitude((BASE_AMPLITUDE + AMPLITUDE_PER_METER * (p1-p0).Quick_Length()) * ammo_def->BeamSubdivisionScale);
  119. beam_model->Set_Subdivision_Levels(BEAM_SUBDIVISION);
  120. } else {
  121. beam_model->Set_Noise_Amplitude(0.0f);
  122. beam_model->Set_Subdivision_Levels(0);
  123. }
  124. /*
  125. ** Constants; I don't let the user control these for now
  126. */
  127. beam_model->Set_Texture_Tile_Factor(1.0f); // Only relevant for TILED_TEXTURE_MAP mode
  128. beam_model->Set_Texture_Mapping_Mode(SegLineRendererClass::UNIFORM_WIDTH_TEXTURE_MAP);
  129. beam_model->Set_Opacity(1.0f);
  130. beam_model->Set_Shader(ShaderClass::_PresetAdditiveShader);
  131. beam_model->Set_Merge_Abort_Factor(1.0f);
  132. beam_model->Set_Merge_Intersections(false);
  133. beam_model->Set_Disable_Sorting(false);
  134. beam_model->Set_Freeze_Random(ammo_def->BeamSubdivisionFrozen);
  135. beam_model->Set_End_Caps(ammo_def->BeamEndCaps);
  136. beam_model->Reset_Line();
  137. beam_wrapper->Set_Lifetime(ammo_def->BeamTime);
  138. beam_wrapper->Set_Transform(Matrix3D(1));
  139. beam_wrapper->Enable_Is_Pre_Lit(true);
  140. COMBAT_SCENE->Add_Dynamic_Object(beam_wrapper);
  141. REF_PTR_RELEASE(beam_wrapper);
  142. REF_PTR_RELEASE(beam_model);
  143. REF_PTR_RELEASE(beam_texture);
  144. }
  145. void BeamEffectManagerClass::Object_Removed_From_Scene(PhysClass * observed_obj)
  146. {
  147. /*
  148. ** One of the "beams" that we are observing expired and was removed from the scene so
  149. ** lets put it in the list for future re-use
  150. */
  151. UnusedBeamList.Add((TimedDecorationPhysClass *)observed_obj);
  152. }
  153. void BeamEffectManagerClass::Internal_Get_New_Beam(SegmentedLineClass ** set_beam_model,TimedDecorationPhysClass ** set_beam_wrapper)
  154. {
  155. if (UnusedBeamList.Is_Empty()) {
  156. SegmentedLineClass * beam_model = NEW_REF(SegmentedLineClass,());
  157. TimedDecorationPhysClass * beam_wrapper = NEW_REF(TimedDecorationPhysClass,());
  158. beam_wrapper->Enable_Dont_Save(true);
  159. beam_wrapper->Set_Collision_Group(UNCOLLIDEABLE_GROUP);
  160. beam_wrapper->Set_Model(beam_model);
  161. beam_wrapper->Set_Observer(this);
  162. *set_beam_model = beam_model;
  163. *set_beam_wrapper = beam_wrapper; // refs returned to the caller
  164. } else {
  165. *set_beam_wrapper = UnusedBeamList.Remove_Head(); // refs returned to the caller
  166. *set_beam_model = (SegmentedLineClass *)((*set_beam_wrapper)->Get_Model());
  167. }
  168. }
  169. /*
  170. ** Core Bullet Data for simulation
  171. */
  172. class BulletDataClass {
  173. public:
  174. BulletDataClass( const AmmoDefinitionClass * def = NULL, const ArmedGameObj * owner = NULL,
  175. const Vector3 & position = Vector3(0,0,0), const Vector3 & velocity = Vector3(0,0,0) ) :
  176. AmmoDefinition( def ),
  177. Owner( owner ),
  178. Position( position ),
  179. Velocity( velocity ),
  180. SoftPierceCount( 0 ),
  181. Destroy( false ),
  182. DidExplode( false ),
  183. LastHitID( 0 ),
  184. GrenadeSafetyTimer( 0 )
  185. {}
  186. ArmedGameObj * Get_Owner( void ) const { return (ArmedGameObj *)Owner.Get_Ptr(); }
  187. CollisionReactionType Bullet_Collision_Occurred( const CollisionEventClass & event );
  188. ExpirationReactionType Bullet_Expired();
  189. const AmmoDefinitionClass *AmmoDefinition;
  190. GameObjReference Owner;
  191. Vector3 Position;
  192. Vector3 Velocity;
  193. int SoftPierceCount;
  194. bool Destroy;
  195. bool DidExplode;
  196. int LastHitID;
  197. float GrenadeSafetyTimer;
  198. };
  199. /*
  200. ** Bullet_Collision_Occured
  201. */
  202. CollisionReactionType BulletDataClass::Bullet_Collision_Occurred( const CollisionEventClass & event )
  203. {
  204. WWPROFILE( "Bullet Collision Occurred" );
  205. WWASSERT(event.OtherObj);
  206. WWASSERT(event.CollisionResult != NULL);
  207. // WWDEBUG_SAY(( "Bullet Collision\n" ));
  208. //
  209. // Pre-calculate some useful variables
  210. //
  211. CollisionReactionType return_value = COLLISION_REACTION_DEFAULT;
  212. OffenseObjectClass offense( AmmoDefinition->Damage, (int)AmmoDefinition->Warhead, Get_Owner() );
  213. offense.EnableClientDamage = true; // Only bullets apply to client damage;
  214. const Vector3 & collision_point = event.CollisionResult->ContactPoint;
  215. const Vector3 & collision_normal = event.CollisionResult->Normal;
  216. PhysicalGameObj * other = NULL;
  217. BuildingGameObj * building = NULL;
  218. if ( event.OtherObj->Get_Observer() != NULL ) {
  219. other = ((CombatPhysObserverClass *)event.OtherObj->Get_Observer())->As_PhysicalGameObj();
  220. building = ((CombatPhysObserverClass *)event.OtherObj->Get_Observer())->As_BuildingGameObj();
  221. }
  222. //
  223. // If the bullet hits its owner or its owner's vehicle, allow it to continue
  224. // Also, if it is a simple "Hidden Object", allow the bullet to continue
  225. //
  226. if ( other != NULL && Get_Owner() != NULL ) {
  227. SimpleGameObj * simple = other->As_SimpleGameObj();
  228. VehicleGameObj * vehicle = other->As_VehicleGameObj();
  229. SoldierGameObj * soldier = Get_Owner()->As_SoldierGameObj();
  230. if ( vehicle != NULL && soldier != NULL && vehicle == soldier->Get_Vehicle() ) {
  231. // Debug_Say(( "Bullet Hitting its owner's vehicle\n" ));
  232. return COLLISION_REACTION_NO_BOUNCE;
  233. }
  234. if ( other == Get_Owner() ) {
  235. // Debug_Say(( "Bullet Hitting its owner\n" ));
  236. return COLLISION_REACTION_NO_BOUNCE;
  237. }
  238. if ((simple != NULL) && (simple->Is_Hidden_Object())) {
  239. return COLLISION_REACTION_NO_BOUNCE;
  240. }
  241. }
  242. //
  243. // Apply Graphical Effects.
  244. // If the mesh is shatterable it is shattered, Apply a surface effect depending on the surface type
  245. // that was collided with. In the case that the mesh was shattered, we disable surface effect decals.
  246. //
  247. bool shattered = false;
  248. if ((event.CollidedRenderObj != NULL) && (event.CollidedRenderObj->Class_ID() == RenderObjClass::CLASSID_MESH)) {
  249. MeshClass * mesh = (MeshClass *)event.CollidedRenderObj;
  250. if ((mesh->Get_W3D_Flags() & W3D_MESH_FLAG_SHATTERABLE) && (mesh->Is_Not_Hidden_At_All())) {
  251. PhysicsSceneClass::Get_Instance()->Shatter_Mesh( mesh,
  252. collision_point,
  253. collision_normal,
  254. Velocity );
  255. // remeber that we shattered the mesh so that we don't create decals later
  256. shattered = true;
  257. // Bullets always pass through shattered objects because we sometimes have two-layered
  258. // windows that have different materials on the two sides. We don't want bullets to ever
  259. // shatter only one "side" of a window!
  260. return_value = COLLISION_REACTION_NO_BOUNCE;
  261. }
  262. }
  263. // Ignore backfaces (after shattering for windows)
  264. float dot = Vector3::Dot_Product( event.CollisionResult->Normal, Velocity );
  265. if ( dot > 0 ) {
  266. return COLLISION_REACTION_NO_BOUNCE;
  267. }
  268. //
  269. // Apply Damage
  270. // There are several types of objects that can be damaged: normal dynamic game objects, damageable static
  271. // physics objects, and buildings. A building is damaged whenever any of its meshes or aggregates are
  272. // hit by a bullet.
  273. // Also, we only apply damage if the mesh wasn't shattered. Bullets pretend like nothing happened
  274. // if they shatter something.
  275. //
  276. if (!shattered) {
  277. const char * collided_obj_name = NULL;
  278. if ( event.CollidedRenderObj != NULL ) {
  279. collided_obj_name = event.CollidedRenderObj->Get_Name();
  280. }
  281. if ( other ) { // if hitting a game object,
  282. if ( other->Get_ID() == LastHitID ) {
  283. // Debug_Say(( "Double Hit\n" ));
  284. return COLLISION_REACTION_NO_BOUNCE;
  285. }
  286. if ( GrenadeSafetyTimer > 0 ) {
  287. // only if the other is not an enemy
  288. if ( other && Get_Owner() && !other->Is_Enemy( Get_Owner() ) ) {
  289. return COLLISION_REACTION_DEFAULT; // Just bounce
  290. }
  291. }
  292. LastHitID = other->Get_ID();
  293. // Apply Bullet Damage to a game object
  294. // Allow it to happen for clients, so we can get the repair effect
  295. // if ( CombatManager::I_Am_Server() ) {
  296. other->Apply_Damage_Extended( offense, 1.0f, Velocity, collided_obj_name );
  297. // If the bullet is hitting C4, also apply damage to the object the C4 is
  298. // attached to. This is a fix for the "C4 armor" exploit.
  299. if (other->As_C4GameObj() != NULL) {
  300. ScriptableGameObj * host = other->As_C4GameObj()->Get_Stuck_Object();
  301. if ((host != NULL) && (host->As_PhysicalGameObj() != NULL)) {
  302. host->As_PhysicalGameObj()->Apply_Damage_Extended( offense, 1.0f, Velocity, NULL );
  303. }
  304. }
  305. // }
  306. if ( ( !other->Is_Soft() ) ||
  307. ( ++SoftPierceCount >= AmmoDefinition->SoftPierceLimit ) ) {
  308. if ( AmmoDefinition->ExplosionDefID ) {
  309. ExplosionManager::Create_Explosion_At( AmmoDefinition->ExplosionDefID, collision_point, Get_Owner(), -collision_normal, other );
  310. }
  311. Destroy = true;
  312. return_value = COLLISION_REACTION_STOP_MOTION;
  313. } else {
  314. return_value = COLLISION_REACTION_NO_BOUNCE;
  315. }
  316. } else { // if hitting terain
  317. if ( GrenadeSafetyTimer > 0 ) {
  318. Debug_Say(( "Safety\n" ));
  319. return COLLISION_REACTION_DEFAULT; // Just bounce
  320. }
  321. // If hitting a building, apply damage to it
  322. if ( building != NULL ) { // && CombatManager::I_Am_Server() ) {
  323. building->Apply_Damage_Building( offense, event.OtherObj->As_StaticPhysClass() );
  324. }
  325. // Check for damage to a DamageableStaticPhys object
  326. // For now I'm using the persist factory chunk-ID for RTTI... If a better solution
  327. // turns up we should change this.
  328. if ( event.OtherObj->Get_Factory().Chunk_ID() == PHYSICS_CHUNKID_DAMAGEABLESTATICPHYS
  329. // && CombatManager::I_Am_Server()
  330. )
  331. {
  332. DamageableStaticPhysClass * damphys = (DamageableStaticPhysClass *)event.OtherObj;
  333. OffenseObjectClass offense( AmmoDefinition->Damage, (int)AmmoDefinition->Warhead, Get_Owner() );
  334. offense.EnableClientDamage = true; // Only bullets apply to client damage;
  335. damphys->Apply_Damage_Static( offense );
  336. }
  337. // check for a non-stopping surface
  338. if ( !SurfaceEffectsManager::Does_Surface_Stop_Bullets( event.CollisionResult->SurfaceType ) ) {
  339. return_value = COLLISION_REACTION_NO_BOUNCE;
  340. } else {
  341. // If the ammo explodes when it hits terrain, then create an explosion and kill the bullet
  342. if ( AmmoDefinition->TerrainActivated ) {
  343. if ( AmmoDefinition->ExplosionDefID ) {
  344. ExplosionManager::Create_Explosion_At( AmmoDefinition->ExplosionDefID, collision_point, Get_Owner(), -collision_normal, building );
  345. DidExplode = true;
  346. }
  347. Destroy = true;
  348. return_value = COLLISION_REACTION_STOP_MOTION;
  349. }
  350. }
  351. }
  352. }
  353. // Only make a bullet hit if it doesn't make an explosion
  354. if ( !DidExplode ) {
  355. Matrix3D surface_tm;
  356. surface_tm.Look_At(collision_point,collision_point-collision_normal,FreeRandom.Get_Float(0,DEG_TO_RADF(360)));
  357. int my_type = AmmoDefinition->HitterType;
  358. bool allow_decals = (shattered == false);
  359. if ( (float)AmmoDefinition->Damage < 0.0f ) {
  360. allow_decals = false;
  361. }
  362. SurfaceEffectsManager::Apply_Effect( event.CollisionResult->SurfaceType, my_type, surface_tm, event.OtherObj, Get_Owner(), allow_decals );
  363. }
  364. return return_value;
  365. }
  366. ExpirationReactionType BulletDataClass::Bullet_Expired( void )
  367. {
  368. Destroy = true;
  369. if ( AmmoDefinition->TimeActivated && AmmoDefinition->ExplosionDefID && !DidExplode ) {
  370. ExplosionManager::Create_Explosion_At( AmmoDefinition->ExplosionDefID, Position, Get_Owner() );
  371. }
  372. return EXPIRATION_DENIED; // Don't let it die, I'll pull it from the scene later
  373. }
  374. /*
  375. ** BulletClass (for non-instant bullets)
  376. */
  377. class BulletClass : public CombatPhysObserverClass, public MultiListObjectClass, public PostLoadableClass {
  378. public:
  379. ~BulletClass( void );
  380. void Init( const BulletDataClass & data, float progress_time, const Vector3 & target, DamageableGameObj * target_object = NULL );
  381. void Shutdown( void );
  382. void Think( void );
  383. // Save / Load
  384. virtual bool Save( ChunkSaveClass & csave );
  385. virtual bool Load( ChunkLoadClass & cload );
  386. virtual void On_Post_Load(void);
  387. bool Is_Valid( void ) { return BulletData.AmmoDefinition != NULL; }
  388. // Collision
  389. virtual CollisionReactionType Collision_Occurred( const CollisionEventClass & event );
  390. virtual ExpirationReactionType Object_Expired( PhysClass * observed_obj );
  391. private:
  392. BulletDataClass BulletData;
  393. ProjectileClass * Projectile; // for physics
  394. Vector3 TargetVector;
  395. GameObjReference TargetObject;
  396. float TrackingErrorTimer;
  397. Vector3 TrackingError;
  398. long ModelNameCRC;
  399. BulletClass( void );
  400. friend class BulletManager;
  401. };
  402. BulletClass::BulletClass( void ) :
  403. Projectile( NULL ),
  404. TargetVector( 0,0,0 ),
  405. TrackingErrorTimer( 0 ),
  406. TrackingError( 0,0,0 ),
  407. ModelNameCRC( 0 )
  408. {
  409. WWASSERT( Projectile == NULL );
  410. Projectile = NEW_REF( ProjectileClass, () );
  411. Projectile->Set_Collision_Group( BULLET_COLLISION_GROUP );
  412. }
  413. BulletClass::~BulletClass( void )
  414. {
  415. if ( Projectile != NULL ) {
  416. Projectile->Set_Observer(NULL);
  417. Projectile->Release_Ref();
  418. Projectile = NULL;
  419. }
  420. }
  421. void BulletClass::Init( const BulletDataClass & data, float progress_time, const Vector3 & target, DamageableGameObj * target_object )
  422. {
  423. WWPROFILE( "Bullet Init" );
  424. BulletData.AmmoDefinition = data.AmmoDefinition;
  425. BulletData.Owner = data.Get_Owner();
  426. BulletData.SoftPierceCount = data.SoftPierceCount;
  427. BulletData.Destroy = data.Destroy;
  428. BulletData.LastHitID = 0; // We haven't hit anyone yet.
  429. BulletData.DidExplode = false;
  430. BulletData.GrenadeSafetyTimer = data.GrenadeSafetyTimer;
  431. if ( data.AmmoDefinition ) {
  432. BulletData.GrenadeSafetyTimer = data.AmmoDefinition->GrenadeSafetyTime;
  433. }
  434. TargetVector = target;
  435. TargetObject = target_object;
  436. TrackingErrorTimer = 0;
  437. TrackingError = Vector3( 0,0,0 );
  438. Projectile->Set_Observer( this );
  439. Projectile->Set_Bounce_Count( BulletData.AmmoDefinition->MaxBounces );
  440. if ( BulletData.AmmoDefinition ) {
  441. Projectile->Set_Gravity_Multiplier( BulletData.AmmoDefinition->Gravity );
  442. Projectile->Set_Elasticity( BulletData.AmmoDefinition->Elasticity );
  443. }
  444. Projectile->Enable_Is_Pre_Lit(true); // bullets don't get lighting.
  445. if ( Projectile->Peek_Model() != NULL &&
  446. Projectile->Peek_Model()->Get_Name() != NULL &&
  447. BulletData.AmmoDefinition->ModelName.Compare_No_Case( Projectile->Peek_Model()->Get_Name() ) == 0 ) {
  448. // We don't need to do anything
  449. } else {
  450. RenderObjClass * model = NULL;
  451. model = WW3DAssetManager::Get_Instance ()->Create_Render_Obj( BulletData.AmmoDefinition->ModelName );
  452. // If no name is given, lets create the NULL render obj
  453. if ( model == NULL ) {
  454. Debug_Say(( "Bullet Not Found \"%s\" \n", BulletData.AmmoDefinition->ModelName ));
  455. model = WW3DAssetManager::Get_Instance ()->Create_Render_Obj( "NULL" );
  456. }
  457. Projectile->Set_Model( model );
  458. if (model) {
  459. if ( BulletData.AmmoDefinition->ModelName.Compare_No_Case( model->Get_Name() ) != 0 ) {
  460. Debug_Say(( "Possible bullet twiddler!! %s %s\n", BulletData.AmmoDefinition->ModelName, model->Get_Name() ));
  461. }
  462. // ModelNameCRC = CRC_Stringi( model->Get_Name() );
  463. ModelNameCRC = CRC_Stringi( BulletData.AmmoDefinition->ModelName );
  464. model->Release_Ref();
  465. }
  466. else {
  467. ModelNameCRC = 0xFFFFFFFF;
  468. }
  469. }
  470. if (Projectile->Get_Gravity_Multiplier() < 0.1f) {
  471. Projectile->Set_Orientation_Mode_Aligned_Fixed();
  472. } else {
  473. Projectile->Set_Orientation_Mode_Aligned();
  474. }
  475. COMBAT_SCENE->Add_Dynamic_Object( Projectile );
  476. float duration = (float) BulletData.AmmoDefinition->Range / (float) BulletData.AmmoDefinition->Velocity;
  477. if (duration <= 0.0) {
  478. Debug_Say(( "NULL DURATION\n" ));
  479. }
  480. Projectile->Set_Lifetime( duration * 1.2f );
  481. Projectile->Set_Position( data.Position );
  482. WWASSERT(data.Velocity.Is_Valid());
  483. Projectile->Set_Velocity( data.Velocity );
  484. // If there are any emitters in this model, reset them for our new position
  485. RenderObjClass * model = Projectile->Peek_Model();
  486. model->Restart();
  487. // Timestep last, incase it gets shutdown during this call
  488. if ( data.Get_Owner() != NULL ) {
  489. data.Get_Owner()->Peek_Physical_Object()->Inc_Ignore_Counter();
  490. }
  491. Projectile->Timestep( progress_time );
  492. if ( data.Get_Owner() != NULL ) {
  493. data.Get_Owner()->Peek_Physical_Object()->Dec_Ignore_Counter();
  494. }
  495. }
  496. void BulletClass::Shutdown( void )
  497. {
  498. if ( Projectile != NULL ) {
  499. COMBAT_SCENE->Remove_Object( Projectile );
  500. Projectile->Set_Observer( NULL );
  501. }
  502. BulletData.AmmoDefinition = NULL;
  503. BulletData.Owner = NULL;
  504. }
  505. /*
  506. ** BulletClass Save and Load
  507. */
  508. enum {
  509. CHUNKID_VARIABLES = 910991544,
  510. CHUNKID_OWNER,
  511. CHUNKID_TARGET_OBJECT,
  512. MICROCHUNKID_AMMO_DEFINITION_ID = 1,
  513. MICROCHUNKID_PROJECTILE,
  514. MICROCHUNKID_SOFT_PIERCE_COUNT,
  515. MICROCHUNKID_DESTROY,
  516. MICROCHUNKID_TARGET_VECTOR,
  517. MICROCHUNKID_TRACKING_ERROR_TIMER,
  518. MICROCHUNKID_TRACKING_ERROR,
  519. MICROCHUNKID_MODEL_NAME_CRC,
  520. };
  521. bool BulletClass::Save( ChunkSaveClass & csave )
  522. {
  523. csave.Begin_Chunk( CHUNKID_VARIABLES );
  524. WWASSERT( BulletData.AmmoDefinition != NULL );
  525. int def_id = BulletData.AmmoDefinition->Get_ID();
  526. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_AMMO_DEFINITION_ID, def_id );
  527. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_PROJECTILE, Projectile );
  528. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_SOFT_PIERCE_COUNT, BulletData.SoftPierceCount );
  529. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_DESTROY, BulletData.Destroy );
  530. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_TARGET_VECTOR, TargetVector );
  531. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_TRACKING_ERROR_TIMER, TrackingErrorTimer );
  532. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_TRACKING_ERROR, TrackingError );
  533. WRITE_MICRO_CHUNK( csave, MICROCHUNKID_MODEL_NAME_CRC, ModelNameCRC );
  534. csave.End_Chunk();
  535. if ( BulletData.Get_Owner() != NULL ) {
  536. csave.Begin_Chunk( CHUNKID_OWNER );
  537. BulletData.Owner.Save( csave );
  538. csave.End_Chunk();
  539. }
  540. if ( TargetObject.Get_Ptr() != NULL ) {
  541. csave.Begin_Chunk( CHUNKID_TARGET_OBJECT );
  542. TargetObject.Save( csave );
  543. csave.End_Chunk();
  544. }
  545. return true;
  546. }
  547. bool BulletClass::Load( ChunkLoadClass & cload )
  548. {
  549. while (cload.Open_Chunk()) {
  550. switch(cload.Cur_Chunk_ID()) {
  551. case CHUNKID_VARIABLES:
  552. {
  553. int def_id = 0;
  554. while (cload.Open_Micro_Chunk()) {
  555. switch(cload.Cur_Micro_Chunk_ID()) {
  556. READ_MICRO_CHUNK( cload, MICROCHUNKID_AMMO_DEFINITION_ID, def_id );
  557. READ_MICRO_CHUNK( cload, MICROCHUNKID_PROJECTILE, Projectile );
  558. READ_MICRO_CHUNK( cload, MICROCHUNKID_SOFT_PIERCE_COUNT, BulletData.SoftPierceCount );
  559. READ_MICRO_CHUNK( cload, MICROCHUNKID_DESTROY, BulletData.Destroy );
  560. READ_MICRO_CHUNK( cload, MICROCHUNKID_TARGET_VECTOR, TargetVector );
  561. READ_MICRO_CHUNK( cload, MICROCHUNKID_TRACKING_ERROR_TIMER, TrackingErrorTimer );
  562. READ_MICRO_CHUNK( cload, MICROCHUNKID_TRACKING_ERROR, TrackingError );
  563. READ_MICRO_CHUNK( cload, MICROCHUNKID_MODEL_NAME_CRC, ModelNameCRC );
  564. default:
  565. Debug_Say(("Unhandled Micro Chunk:%d File:%s Line:%d\r\n",cload.Cur_Micro_Chunk_ID(),__FILE__,__LINE__));
  566. break;
  567. }
  568. cload.Close_Micro_Chunk();
  569. }
  570. WWASSERT( BulletData.AmmoDefinition == NULL );
  571. BulletData.AmmoDefinition = WeaponManager::Find_Ammo_Definition( def_id );
  572. WWASSERT( BulletData.AmmoDefinition != NULL );
  573. WWASSERT( Projectile != NULL );
  574. if ( Projectile != NULL ) {
  575. REQUEST_REF_COUNTED_POINTER_REMAP( (RefCountClass **)&Projectile );
  576. }
  577. break;
  578. }
  579. case CHUNKID_OWNER:
  580. BulletData.Owner.Load( cload );
  581. break;
  582. case CHUNKID_TARGET_OBJECT:
  583. TargetObject.Load( cload );
  584. break;
  585. default:
  586. Debug_Say(("Unhandled Chunk:%d File:%s Line:%d\r\n",cload.Cur_Chunk_ID(),__FILE__,__LINE__));
  587. break;
  588. }
  589. cload.Close_Chunk();
  590. }
  591. SaveLoadSystemClass::Register_Post_Load_Callback(this);
  592. return true;
  593. }
  594. void BulletClass::On_Post_Load (void)
  595. {
  596. // Plug ourselves back into the physics object as an observer
  597. WWASSERT(Projectile != NULL);
  598. Projectile->Set_Observer(this);
  599. return ;
  600. }
  601. CollisionReactionType BulletClass::Collision_Occurred( const CollisionEventClass & event )
  602. {
  603. // Copy the data from the Projectile
  604. Projectile->Get_Velocity( &BulletData.Velocity );
  605. Projectile->Get_Position( &BulletData.Position );
  606. CollisionReactionType result = BulletData.Bullet_Collision_Occurred( event );
  607. if ( BulletData.Destroy ) {
  608. Shutdown();
  609. }
  610. return result;
  611. }
  612. ExpirationReactionType BulletClass::Object_Expired(PhysClass * observed_obj)
  613. {
  614. // Copy the data from the Projectile
  615. Projectile->Get_Velocity( &BulletData.Velocity );
  616. Projectile->Get_Position( &BulletData.Position );
  617. ExpirationReactionType result = BulletData.Bullet_Expired();
  618. if ( BulletData.Destroy ) {
  619. Shutdown();
  620. }
  621. return result;
  622. }
  623. #define RANDOM_VECTOR( spread ) Vector3( FreeRandom.Get_Float( -(spread), (spread) ), \
  624. FreeRandom.Get_Float( -(spread), (spread) ), \
  625. FreeRandom.Get_Float( 0, (spread) ) )
  626. void BulletClass::Think( void )
  627. {
  628. WWPROFILE( "Bullet Think" );
  629. // Count down safety timer
  630. BulletData.GrenadeSafetyTimer -= TimeManager::Get_Frame_Seconds();
  631. if ( BulletData.GrenadeSafetyTimer < 0 ) {
  632. BulletData.GrenadeSafetyTimer = 0;
  633. }
  634. // Handle Homing Bullets
  635. if ( BulletData.AmmoDefinition->IsTracking ) {
  636. // Track your target object
  637. DamageableGameObj * target_obj = (DamageableGameObj *)TargetObject.Get_Ptr();
  638. if ( target_obj != NULL ) {
  639. if ( target_obj->As_PhysicalGameObj() ) {
  640. TargetVector = target_obj->As_PhysicalGameObj()->Get_Bullseye_Position();
  641. } else {
  642. target_obj->Get_Position( &TargetVector );
  643. }
  644. }
  645. Vector3 target_vector = TargetVector;
  646. Vector3 obj_pos;
  647. Projectile->Get_Transform().Get_Translation( &obj_pos );
  648. // Debug_Say(( "Bullet Tracking %f %f %f\n", obj_pos.X, obj_pos.Y, obj_pos.Z ));
  649. target_vector -= obj_pos;
  650. // Find distance to target
  651. float target_distance = target_vector.Length();
  652. TrackingErrorTimer -= TimeManager::Get_Frame_Seconds();
  653. if ( TrackingErrorTimer < 0 ) {
  654. TrackingErrorTimer = FreeRandom.Get_Float( 0.1f, 0.4f );
  655. TrackingError = RANDOM_VECTOR( BulletData.AmmoDefinition->RandomTrackingScale * target_distance / 2 );
  656. }
  657. target_vector += TrackingError;
  658. target_vector.Normalize();
  659. Vector3 current_vector;
  660. Projectile->Get_Velocity( &current_vector );
  661. current_vector.Normalize();
  662. Vector3 cross = Vector3::Cross_Product( current_vector, target_vector );
  663. // only re-aim if cross product not near zero
  664. if ( cross.Length() > WWMATH_EPSILON ) {
  665. float dot = Vector3::Dot_Product( target_vector, current_vector );
  666. if ( WWMath::Fabs(dot) >= 1.0f ) {
  667. // No turning needed
  668. } else {
  669. float angle = WWMath::Fast_Acos( dot );
  670. float allowed_turn = BulletData.AmmoDefinition->TurnRate * TimeManager::Get_Frame_Seconds();
  671. if ( angle > allowed_turn ) {
  672. angle = allowed_turn;
  673. }
  674. cross.Normalize();
  675. Matrix3D tm(cross,angle);
  676. Vector3 current_vector;
  677. Projectile->Get_Velocity( &current_vector );
  678. WWASSERT(current_vector.Is_Valid());
  679. current_vector = tm.Rotate_Vector( current_vector );
  680. WWASSERT(current_vector.Is_Valid());
  681. Projectile->Set_Velocity( current_vector );
  682. }
  683. }
  684. }
  685. }
  686. /*
  687. ** Instant Bullet Code
  688. */
  689. void Simulate_Instant_Bullet( BulletDataClass & data, float progress_time )
  690. {
  691. WWPROFILE("Simulate_Instant_Bullet");
  692. // WWASSERT(data.Position.Is_Valid());
  693. // WWASSERT(data.Velocity.Is_Valid());
  694. Vector3 start = data.Position;
  695. Vector3 end = data.Velocity;
  696. end.Normalize();
  697. end = start + (end * data.AmmoDefinition->Range);
  698. // This is that last object we choose to ignore
  699. PhysClass *blocker = NULL;
  700. // Always ignore the owner
  701. if ( data.Get_Owner() != NULL ) {
  702. if ( data.Get_Owner()->Peek_Physical_Object() != NULL ) {
  703. data.Get_Owner()->Peek_Physical_Object()->Inc_Ignore_Counter();
  704. }
  705. }
  706. bool done = false;
  707. int hit_counter = 0;
  708. const int MAX_HITS = 5;
  709. while ( !done && (hit_counter < MAX_HITS)) {
  710. hit_counter++;
  711. // Check for collisions in the path of the object
  712. CastResultStruct res;
  713. LineSegClass ray( data.Position, end );
  714. PhysRayCollisionTestClass raytest(ray,&res,BULLET_COLLISION_GROUP,COLLISION_TYPE_PROJECTILE);
  715. {WWPROFILE("Cast_Ray");
  716. PhysicsSceneClass::Get_Instance()->Cast_Ray(raytest);
  717. }
  718. // If the result was a "startbad", we are done
  719. if (raytest.Result->StartBad) {
  720. // Debug_Say(( "Simulate_Instant_Bullet Startbad\n" ));
  721. done = true;
  722. } else {
  723. if (raytest.Result->Fraction < 1.0f) {
  724. // If there was a collision, set us at the point of collision
  725. // Also, fill in the cast result struct.
  726. ray.Compute_Point(raytest.Result->Fraction,&(raytest.Result->ContactPoint));
  727. data.Position = raytest.Result->ContactPoint;
  728. // Notify the parties involved
  729. WWASSERT(raytest.CollidedPhysObj != NULL);
  730. CollisionReactionType reaction = COLLISION_REACTION_DEFAULT;
  731. CollisionEventClass event;
  732. event.CollisionResult = raytest.Result;
  733. event.CollidedRenderObj = raytest.CollidedRenderObj;
  734. event.OtherObj = raytest.CollidedPhysObj;
  735. reaction |= data.Bullet_Collision_Occurred(event);
  736. if ( reaction & COLLISION_REACTION_NO_BOUNCE ) {
  737. // We were requested to fly through. Mark the current blocker as ignore
  738. // so we collide with him no more this pass
  739. if ( blocker ) { // Stop ignoring the last blocker
  740. blocker->Dec_Ignore_Counter();
  741. }
  742. blocker = raytest.CollidedPhysObj;
  743. if ( blocker ) { // Start ignoring this blocker
  744. blocker->Inc_Ignore_Counter();
  745. }
  746. } else {
  747. done = true;
  748. }
  749. } else {
  750. done = true;
  751. data.Position = end;
  752. }
  753. }
  754. }
  755. if ( blocker ) { // Stop ignoring the last blocker
  756. blocker->Dec_Ignore_Counter();
  757. }
  758. // stop ignoring the owner
  759. if ( data.Get_Owner() != NULL ) {
  760. if ( data.Get_Owner()->Peek_Physical_Object() != NULL ) {
  761. data.Get_Owner()->Peek_Physical_Object()->Dec_Ignore_Counter();
  762. }
  763. }
  764. // If not destroyed, Expire..
  765. if ( !data.Destroy ) {
  766. data.Bullet_Expired();
  767. }
  768. // If the definition requests a beam effect, launch it
  769. if (data.AmmoDefinition->BeamEnabled) {
  770. _TheBeamEffectManager.Create_Beam_Effect(data.AmmoDefinition,start,data.Position);
  771. }
  772. }
  773. /*
  774. ** BulletManager
  775. */
  776. MultiListClass<BulletClass> LiveBulletList;
  777. MultiListClass<BulletClass> DeadBulletList;
  778. void BulletManager::Init( void )
  779. {
  780. _TheBeamEffectManager.Init();
  781. }
  782. void BulletManager::Shutdown( void )
  783. {
  784. while ( !LiveBulletList.Is_Empty() ) {
  785. delete LiveBulletList.Remove_Head();
  786. }
  787. while ( !DeadBulletList.Is_Empty() ) {
  788. delete DeadBulletList.Remove_Head();
  789. }
  790. _TheBeamEffectManager.Shutdown();
  791. }
  792. void BulletManager::Update( void )
  793. {
  794. MultiListIterator<BulletClass> it( &LiveBulletList );;
  795. while (!it.Is_Done()) {
  796. BulletClass * bullet = it.Peek_Obj();
  797. if (bullet->BulletData.Destroy) {
  798. bullet->Shutdown();
  799. it.Remove_Current_Object();
  800. DeadBulletList.Add( bullet );
  801. } else {
  802. bullet->Think();
  803. it.Next();
  804. }
  805. }
  806. }
  807. #define BULLET_SPEED_CHEAT 0
  808. void BulletManager::Create_Bullet( const AmmoDefinitionClass * def, const Vector3 & position,
  809. const Vector3 & velocity, const ArmedGameObj * owner, float progress_time, const Vector3 & target,
  810. DamageableGameObj * target_obj )
  811. {
  812. WWASSERT(velocity.Is_Valid());
  813. BulletDataClass data( def, owner, position, velocity );
  814. #if BULLET_SPEED_CHEAT
  815. if ( (float)def->Velocity >= _INSTANT_BULLET_THRESHHOLD/3 ) {
  816. #else
  817. if ( (float)def->Velocity >= _INSTANT_BULLET_THRESHHOLD ) {
  818. #endif
  819. Simulate_Instant_Bullet( data, progress_time );
  820. return;
  821. }
  822. WWPROFILE( "Create Bullet" );
  823. BulletClass * bullet = NULL;
  824. // Find a bullet
  825. long crc = CRC_Stringi( def->ModelName );
  826. MultiListIterator<BulletClass> it( &DeadBulletList );;
  827. while ( !it.Is_Done() && bullet == NULL ) {
  828. BulletClass * test_bullet = it.Peek_Obj();
  829. if ( test_bullet->ModelNameCRC == crc ) {
  830. bullet = test_bullet;
  831. it.Remove_Current_Object();
  832. } else {
  833. it.Next();
  834. }
  835. }
  836. if ( bullet == NULL ) {
  837. bullet = new BulletClass();
  838. }
  839. if ( bullet != NULL ) {
  840. bullet->Init( data, progress_time, target, target_obj );
  841. LiveBulletList.Add( bullet );
  842. }
  843. }
  844. /*
  845. ** Save & Load
  846. */
  847. enum {
  848. CHUNKID_BULLET = 916991653,
  849. };
  850. bool BulletManager::Save( ChunkSaveClass &csave )
  851. {
  852. MultiListIterator<BulletClass> it( &LiveBulletList );;
  853. while (!it.Is_Done()) {
  854. BulletClass * bullet = it.Peek_Obj();
  855. // Only save valid bullets
  856. if ( bullet->Is_Valid() ) {
  857. csave.Begin_Chunk( CHUNKID_BULLET );
  858. bullet->Save( csave );
  859. csave.End_Chunk();
  860. }
  861. it.Next();
  862. }
  863. return true;
  864. }
  865. bool BulletManager::Load( ChunkLoadClass &cload )
  866. {
  867. while (cload.Open_Chunk()) {
  868. switch(cload.Cur_Chunk_ID()) {
  869. case CHUNKID_BULLET:
  870. {
  871. BulletClass * bullet = new BulletClass();
  872. bullet->Load( cload );
  873. LiveBulletList.Add( bullet );
  874. break;
  875. }
  876. default:
  877. Debug_Say(( "Unrecognized BulletManager chunkID %d\n", cload.Cur_Chunk_ID() ));
  878. break;
  879. }
  880. cload.Close_Chunk();
  881. }
  882. return true;
  883. }