]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/shiphit.cpp
warning cleanup
[taylor/freespace2.git] / src / ship / shiphit.cpp
1 /*
2  * $Logfile: /Freespace2/code/Ship/ShipHit.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Code to deal with a ship getting hit by something, be it a missile, dog, or ship.
8  *
9  * $Log$
10  * Revision 1.3  2002/06/02 04:26:34  relnev
11  * warning cleanup
12  *
13  * Revision 1.2  2002/05/03 13:34:34  theoddone33
14  * More stuff compiles
15  *
16  * Revision 1.1.1.1  2002/05/03 03:28:10  root
17  * Initial import.
18  *
19  * 
20  * 61    9/14/99 3:26a Dave
21  * Fixed laser fogging problem in nebula (D3D)> Fixed multiplayer
22  * respawn-too-early problem. Made a few crash points safe.
23  * 
24  * 60    9/13/99 4:52p Dave
25  * RESPAWN FIX
26  * 
27  * 59    9/09/99 11:17a Jimb
28  * Removed bogus Int3() in do_subobj_hit_stuff(). 
29  * 
30  * 58    9/07/99 4:01p Dave
31  * Fixed up a string.tbl paroblem (self destruct message). Make sure IPX
32  * does everything properly (setting up address when binding). Remove
33  * black rectangle background from UI_INPUTBOX.
34  * 
35  * 57    9/03/99 11:39p Mikek
36  * Fix problem in sm3-01 of dual-fired Helios bombs only doing 1/4 damage.
37  * 
38  * 56    9/03/99 2:24p Mikek
39  * Decrease overall damage done to player at Medium and Hard.  I believe
40  * this was the major culprit in Flak cannons being so nasty.  The firing
41  * rate seems to not have been an issue.
42  * 
43  * 55    9/02/99 11:55a Mikek
44  * Zero damage to small ship subsystems from shockwaves.
45  * 
46  * 54    9/01/99 10:15a Dave
47  * 
48  * 53    8/27/99 10:42a Andsager
49  * Don't reposition shockwave for BIG only HUGE ships
50  * 
51  * 52    8/27/99 1:34a Andsager
52  * Modify damage by shockwaves for BIG|HUGE ships.  Modify shockwave damge
53  * when weapon blows up.
54  * 
55  * 51    8/26/99 10:46p Andsager
56  * Apply shockwave damage to lethality.
57  * 
58  * 50    8/26/99 8:52p Dave
59  * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
60  * 
61  * 49    8/26/99 5:14p Andsager
62  * 
63  * 48    8/26/99 9:45a Dave
64  * First pass at easter eggs and cheats.
65  * 
66  * 47    8/23/99 11:59a Andsager
67  * Force choice of big fireball when Knossos destroyed.  Allow logging of
68  * ship destroyed when no killer_name (ie, from debug).
69  * 
70  * 46    8/22/99 5:53p Dave
71  * Scoring fixes. Added self destruct key. Put callsigns in the logfile
72  * instead of ship designations for multiplayer players.
73  * 
74  * 45    8/22/99 1:19p Dave
75  * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
76  * which d3d cards are detected.
77  * 
78  * 44    8/20/99 5:09p Andsager
79  * Second pass on Knossos device explosion
80  * 
81  * 43    8/20/99 1:42p Andsager
82  * Frist pass on Knossos explosion.
83  * 
84  * 42    8/06/99 9:46p Dave
85  * Hopefully final changes for the demo.
86  * 
87  * 41    8/03/99 11:02p Dave
88  * Maybe fixed sync problems in multiplayer.
89  * 
90  * 40    8/02/99 1:59p Dave
91  * Fixed improper damage application to subobjects on a "big damage" ship.
92  * 
93  * 39    7/24/99 1:54p Dave
94  * Hud text flash gauge. Reworked dead popup to use 4 buttons in red-alert
95  * missions.
96  * 
97  * 38    7/19/99 7:20p Dave
98  * Beam tooling. Specialized player-killed-self messages. Fixed d3d nebula
99  * pre-rendering.
100  * 
101  * 37    7/09/99 12:51a Andsager
102  * Modify engine wash (1) less damage (2) only at a closer range (3) no
103  * damage when engine is disabled
104  * 
105  * 36    6/30/99 5:53p Dave
106  * Put in new anti-camper code.
107  * 
108  * 35    6/28/99 4:51p Andsager
109  * Add ship-guardian sexp (does not allow ship to be killed)
110  * 
111  * 34    6/21/99 7:25p Dave
112  * netplayer pain packet. Added type E unmoving beams.
113  * 
114  * 33    6/10/99 3:43p Dave
115  * Do a better job of syncing text colors to HUD gauges.
116  * 
117  * 32    5/27/99 12:14p Andsager
118  * Some fixes for live debris when more than one subsys on ship with live
119  * debris.  Set subsys strength (when 0) blows off subsystem.
120  * sexp_hits_left_subsystem works for SUBSYSTEM_UNKNOWN.
121  * 
122  * 31    5/21/99 5:03p Andsager
123  * Add code to display engine wash death.  Modify ship_kill_packet
124  * 
125  * 30    5/21/99 1:44p Andsager
126  * Add engine wash gauge
127  * 
128  * 29    5/14/99 11:50a Andsager
129  * Added vaporize for SMALL ships hit by HUGE beams.  Modified dying
130  * frame.  Enlarged debris shards and range at which visible.
131  * 
132  * 28    5/12/99 2:55p Andsager
133  * Implemented level 2 tag as priority in turret object selection
134  * 
135  * 27    5/11/99 10:16p Andsager
136  * First pass on engine wash effect.  Rotation (control input), damage,
137  * shake.  
138  * 
139  * 26    4/28/99 11:13p Dave
140  * Temporary checkin of artillery code.
141  * 
142  * 25    4/23/99 12:01p Johnson
143  * Added SIF_HUGE_SHIP
144  * 
145  * 24    4/20/99 3:43p Andsager
146  * Added normal parameter to ship_apply_local_damage for case of ship_ship
147  * collision.
148  * 
149  * 23    4/16/99 5:54p Dave
150  * Support for on/off style "stream" weapons. Real early support for
151  * target-painting lasers.
152  * 
153  * 22    3/29/99 6:17p Dave
154  * More work on demo system. Got just about everything in except for
155  * blowing ships up, secondary weapons and player death/warpout.
156  * 
157  * 21    3/19/99 9:51a Dave
158  * Checkin to repair massive source safe crash. Also added support for
159  * pof-style nebulae, and some new weapons code.
160  * 
161  * 21    3/15/99 6:45p Daveb
162  * Put in rough nebula bitmap support.
163  * 
164  * 20    3/10/99 6:51p Dave
165  * Changed the way we buffer packets for all clients. Optimized turret
166  * fired packets. Did some weapon firing optimizations.
167  * 
168  * 19    2/26/99 6:01p Andsager
169  * Add sexp has-been-tagged-delay and cap-subsys-cargo-known-delay
170  * 
171  * 18    2/26/99 5:39p Johnson
172  * Put in some handling code for an assert().
173  * 
174  * 17    2/11/99 5:22p Andsager
175  * Fixed bugs, generalized block Sexp_variables
176  * 
177  * 16    2/05/99 10:38a Johnson
178  * Fixed improper object array reference. 
179  * 
180  * 15    2/04/99 1:23p Andsager
181  * Apply max spark limit to ships created in mission parse
182  * 
183  * 14    1/30/99 1:29a Dave
184  * Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot
185  * screen.  Fixed beam weapon death messages.
186  * 
187  * 13    1/29/99 2:08a Dave
188  * Fixed beam weapon collisions with players. Reduced size of scoring
189  * struct for multiplayer. Disabled PXO.
190  * 
191  * 12    1/27/99 10:25p Andsager
192  * Added OEM sparks - make intelligent choice of next spark location for
193  * cruiser and cap ships
194  * 
195  * 11    1/25/99 5:03a Dave
196  * First run of stealth, AWACS and TAG missile support. New mission type
197  * :)
198  * 
199  * 10    1/21/99 4:22p Anoop
200  * Removed bogus Int3() from show_dead_message(...)
201  * 
202  * 9     1/12/99 5:45p Dave
203  * Moved weapon pipeline in multiplayer to almost exclusively client side.
204  * Very good results. Bandwidth goes down, playability goes up for crappy
205  * connections. Fixed object update problem for ship subsystems.
206  * 
207  * 8     12/23/98 2:53p Andsager
208  * Added ship activation and gas collection subsystems, removed bridge
209  * 
210  * 7     11/17/98 4:27p Andsager
211  * Stop sparks from emitting from destroyed subobjects
212  * 
213  * 6     11/09/98 2:11p Dave
214  * Nebula optimizations.
215  * 
216  * 5     10/26/98 9:42a Dave
217  * Early flak gun support.
218  * 
219  * 4     10/20/98 1:39p Andsager
220  * Make so sparks follow animated ship submodels.  Modify
221  * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
222  * submodel_num.  Add submodel_num to multiplayer hit packet.
223  * 
224  * 3     10/13/98 9:29a Dave
225  * Started neatening up freespace.h. Many variables renamed and
226  * reorganized. Added AlphaColors.[h,cpp]
227  * 
228  * 2     10/07/98 10:53a Dave
229  * Initial checkin.
230  * 
231  * 1     10/07/98 10:51a Dave
232  * 
233  * 145   9/01/98 6:48p Dave
234  * Energy suck weapon. Removed a couple of now-bogus asserts in tracker
235  * code.
236  * 
237  * 144   8/25/98 1:48p Dave
238  * First rev of EMP effect. Player side stuff basically done. Next comes
239  * AI code.
240  * 
241  * 143   6/09/98 10:31a Hoffoss
242  * Created index numbers for all xstr() references.  Any new xstr() stuff
243  * added from here on out should be added to the end if the list.  The
244  * current list count can be found in FreeSpace.cpp (search for
245  * XSTR_SIZE).
246  * 
247  * 142   5/24/98 8:49p Allender
248  * put in Int3() to try and trap nasty error in multiplayer
249  * 
250  * 141   5/22/98 12:08p Mike
251  * Don't create "Disarmed" event for small ships.
252  * 
253  * 140   5/22/98 11:00a Mike
254  * Balance sm3-09a.
255  * 
256  * 139   5/18/98 12:41a Allender
257  * fixed subsystem problems on clients (i.e. not reporting properly on
258  * damage indicator).  Fixed ingame join problem with respawns.  minor
259  * comm menu stuff
260  * 
261  * 138   5/13/98 6:54p Dave
262  * More sophistication to PXO interface. Changed respawn checking so
263  * there's no window for desynchronization between the server and the
264  * clients.
265  * 
266  * 137   5/11/98 11:37a Mike
267  * Don't allow deathroll duration for large ships to be shortened by
268  * excess damage.
269  * 
270  * 136   5/10/98 11:30p Mike
271  * Better firing of bombs, less likely to go into strafe mode.
272  * 
273  * 135   5/07/98 12:24a Hoffoss
274  * Finished up sidewinder force feedback support.
275  * 
276  * 134   5/06/98 8:47a Andsager
277  * Initial check in, allow ship sparks to turn on and off depending on
278  * damage.
279  * 
280  * 133   5/06/98 1:12a Allender
281  * fix sequencing names, added nprintf to help respawn debugging
282  * 
283  * 132   5/04/98 4:07p Andsager
284  * Reduce deathroll rotvel cap and average by 25%.
285  * 
286  * 131   5/04/98 11:12a Mike
287  * Make kamikaze ships detonate on impact -- no death roll.
288  * 
289  * 130   4/30/98 12:17a Andsager
290  * Increase deathroll time for big ships and decrease max rotvel for big
291  * ships
292  * 
293  * 129   4/27/98 6:02p Dave
294  * Modify how missile scoring works. Fixed a team select ui bug. Speed up
295  * multi_lag system. Put in new main hall.
296  * 
297  * 128   4/27/98 2:23p Andsager
298  * Create fireballs on destroying subsystems of big ships.  Limit number
299  * of sparks on small ships.
300  * 
301  * 127   4/24/98 5:35p Andsager
302  * Fix sparks sometimes drawing not on model.  If ship is sphere in
303  * collision, don't draw sparks.  Modify ship_apply_local_damage() to take
304  * parameter no_spark.
305  * 
306  * 126   4/23/98 4:47p Andsager
307  * Make deathroll rotvel have z component largest.
308  * 
309  * 125   4/22/98 9:10a Andsager
310  * Resrore z component of deathroll rotvel, as before.  
311  * 
312  * 124   4/21/98 11:20p Andsager
313  * Modify deatroll rotvel. Fix bug getting only positive values.  Add
314  * random to current rotvel, make z rotvel always larger than x or y.
315  * Move call to shipfx_large_blowup_init into Ship.cpp.
316  * 
317  * 123   4/21/98 10:38a Mike
318  * Don't allow player to take _any_ kind of damage past stage 2 of
319  * warpout.
320  * 
321  * 122   4/20/98 5:10p John
322  * Took out cap of number of shards using num_particles.
323  * 
324  * 121   4/17/98 1:17p Mike
325  * Fix bug with uninitialized damage_to_apply.
326  * 
327  * 120   4/17/98 11:05a Mike
328  * Make number of pieces of small debris created by subsystem hits be
329  * based on detail level.
330  * Fix location of turret subsystem.  Was doubly globalizing, very bad on
331  * large ships!
332  * 
333  * 119   4/16/98 3:40p Mike
334  * Make subsys destroyed messages only get sent once.
335  * 
336  * 118   4/15/98 11:06p Mike
337  * Better balance of damage done to subsystems by shockwaves.
338  * 
339  * 117   4/15/98 10:13p Mike
340  * Fix application of damage to subsystems.
341  * 
342  * 116   4/14/98 9:15p John
343  * Added flag to specify which ships get the new large ship exploding
344  * effect.
345  * 
346  * 115   4/14/98 4:56p John
347  * Hooked in Andsager's large ship exploding code, but it is temporarily
348  * disabled.
349  * 
350  * 114   4/12/98 11:16a John
351  * Made palette red hit effect more proportional to damage.
352  * 
353  * 113   4/10/98 12:16p Allender
354  * fix ship hit kill and debris packets
355  * 
356  * 112   4/10/98 1:38a Allender
357  * fix bug with -1 vs 255 (for current secondary bank).  Undid previous
358  * code for ship_kill packets.
359  * 
360  * 111   4/09/98 5:44p Allender
361  * multiplayer network object fixes.  debris and self destructed ships
362  * should all sync up.  Fix problem where debris pieces (hull pieces) were
363  * not getting a net signature
364  * 
365  * 110   4/09/98 5:27p Mike
366  * Speed up deathrolls for smaller ships a bit.
367  * 
368  * 109   4/06/98 7:13p Allender
369  * generate the death text
370  * 
371  * 108   4/01/98 1:48p Allender
372  * major changes to ship collision in multiplayer.  Clients now do own
373  * ship/ship collisions (with their own ship only)  Modifed the hull
374  * update packet to be sent quicker when object is target of player.
375  * 
376  * 107   3/31/98 5:19p John
377  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
378  * bunch of debug stuff out of player file.  Made model code be able to
379  * unload models and malloc out only however many models are needed.
380  *  
381  * 
382  * 106   3/30/98 2:38p Mike
383  * Add asteroid_density to detail level support.
384  * No force explosion damage in training missions.
385  * Make cargo deathrolls shorter.
386  * 
387  * 105   3/30/98 1:08a Lawrance
388  * Implement "blast" icon.  Blink HUD icon when player ship is hit by a
389  * blast.
390  * 
391  * 104   3/24/98 4:26p Lawrance
392  * Make finding out if player killed self easier and more reliable
393  * 
394  * 103   3/24/98 2:16p Mike
395  * Fix bug with variation in death roll rotational velocity.  It wasn't
396  * getting initialized!
397  * 
398  * 102   3/21/98 3:36p Lawrance
399  * Let damage gauge know when player has taken damage.
400  * 
401  * 101   3/21/98 3:37p Mike
402  * Fix/optimize attacking of big ships.
403  * 
404  * 100   3/19/98 5:35p Lawrance
405  * Correctly inform player if killed by ship explosion.
406  *
407  * $NoKeywords: $
408  */
409
410 #include "pstypes.h"
411 #include "object.h"
412 #include "fvi.h"
413 #include "physics.h"
414 #include "vecmat.h"
415 #include "ship.h"
416 #include "model.h"
417 #include "key.h"
418 #include "weapon.h"
419 #include "radar.h"
420 #include "2d.h"
421 #include "3d.h"
422 #include "floating.h"
423 #include "ai.h"
424 #include "ailocal.h"
425 #include "fireballs.h"
426 #include "debris.h"
427 #include "hud.h"
428 #include "timer.h"
429 #include "cfile.h"
430 #include "missionlog.h"
431 #include "missionparse.h"
432 #include "bmpman.h"
433 #include "joy.h"
434 #include "joy_ff.h"
435 #include "player.h"
436 #include "parselo.h"
437 #include "freespace.h"
438 #include "sound.h"
439 #include "linklist.h"
440 #include "hudets.h"
441 #include "hudtarget.h"
442 #include "multi.h"
443 #include "multiutil.h"
444 #include "aigoals.h"
445 #include "gamesnd.h"
446 #include "eventmusic.h"
447 #include "shipfx.h"
448 #include "sexp.h"
449 #include "gamesequence.h"
450 #include "objectsnd.h"
451 #include "cmeasure.h"
452 #include "animplay.h"
453 #include "controlsconfig.h"
454 #include "afterburner.h"
455 #include "shockwave.h"
456 #include "hudsquadmsg.h"
457 #include "swarm.h"
458 #include "shiphit.h"
459 #include "multimsgs.h"
460 #include "particle.h"
461 #include "multi_respawn.h"
462 #include "popup.h"
463 #include "emp.h"
464 #include "beam.h"
465 #include "demo.h"
466 #include "multi_pmsg.h"
467
468 //#pragma optimize("", off)
469 //#pragma auto_inline(off)
470
471 typedef struct spark_pair {
472         int index1, index2;
473         float dist;
474 } spark_pair;
475
476 #define MAX_SPARK_PAIRS         ((MAX_SHIP_HITS * MAX_SHIP_HITS - MAX_SHIP_HITS) / 2)
477
478 #define BIG_SHIP_MIN_RADIUS     80.0f   //      ship radius above which death rolls can't be shortened by excessive damage
479
480 vector  Dead_camera_pos;
481 vector  Original_vec_to_deader;
482
483 //      Decrease damage applied to a subsystem based on skill level.
484 float   Skill_level_subsys_damage_scale[NUM_SKILL_LEVELS] = {0.2f, 0.4f, 0.6f, 0.8f, 1.0f};
485
486 bool is_subsys_destroyed(ship *shipp, int submodel)
487 {
488         ship_subsys *subsys;
489
490         if (submodel == -1) {
491                 false;
492         }
493
494         for ( subsys=GET_FIRST(&shipp->subsys_list); subsys != END_OF_LIST(&shipp->subsys_list); subsys = GET_NEXT(subsys) ) {
495                 if (subsys->system_info->subobj_num == submodel) {
496                         if (subsys->current_hits > 0) {
497                                 return false;
498                         } else {
499                                 return true;
500                         }
501                 }
502         }
503
504         return false;
505 }
506
507 // do_subobj_destroyed_stuff is called when a subobject for a ship is killed.  Separated out
508 // to separate function on 10/15/97 by MWA for easy multiplayer access.  It does all of the
509 // cool things like blowing off the model (if applicable, writing the logs, etc)
510 void do_subobj_destroyed_stuff( ship *ship_p, ship_subsys *subsys, vector* hitpos )
511 {
512         ship_info *sip;
513         object *ship_obj;
514         model_subsystem *psub;
515         vector  g_subobj_pos;
516         int type, i, log_index;
517
518         // get some local variables
519         sip = &Ship_info[ship_p->ship_info_index];
520         ship_obj = &Objects[ship_p->objnum];
521         psub = subsys->system_info;
522         type = psub->type;
523         get_subsystem_world_pos(ship_obj, subsys, &g_subobj_pos);
524
525         // create fireballs when subsys destroy for large ships.
526         object* objp = &Objects[ship_p->objnum];
527         if (objp->radius > 100.0f) {
528                 // number of fireballs determined by radius of subsys
529                 int num_fireballs;
530                 if ( psub->radius < 3 ) {
531                         num_fireballs = 1;
532                 } else {
533                          num_fireballs = 5;
534                 }
535
536                 vector temp_vec, center_to_subsys, rand_vec;
537                 vm_vec_sub(&center_to_subsys, &g_subobj_pos, &objp->pos);
538                 for (int i=0; i<num_fireballs; i++) {
539                         if (i==0) {
540                                 // make first fireball at hitpos
541                                 if (hitpos) {
542                                         temp_vec = *hitpos;
543                                 } else {
544                                         temp_vec = g_subobj_pos;
545                                 }
546                         } else {
547                                 // make other fireballs at random positions, but try to keep on the surface
548                                 vm_vec_rand_vec_quick(&rand_vec);
549                                 float dot = vm_vec_dotprod(&center_to_subsys, &rand_vec);
550                                 vm_vec_scale_add2(&rand_vec, &center_to_subsys, -dot/vm_vec_mag_squared(&center_to_subsys));
551                                 vm_vec_scale_add(&temp_vec, &g_subobj_pos, &rand_vec, 0.5f*psub->radius);
552                         }
553
554                         // scale fireball size according to size of subsystem, but not less than 10
555                         float fireball_rad = psub->radius * 0.2f;
556                         if (fireball_rad < 10) {
557                                 fireball_rad = 10.0f;
558                         }
559
560                         vector fb_vel;
561                         vm_vec_crossprod(&fb_vel, &objp->phys_info.rotvel, &center_to_subsys);
562                         vm_vec_add2(&fb_vel, &objp->phys_info.vel);
563                         fireball_create( &temp_vec, FIREBALL_EXPLOSION_MEDIUM, OBJ_INDEX(objp), fireball_rad, 0, &fb_vel );
564                 }
565         }
566
567         if ( MULTIPLAYER_MASTER ) {
568                 int index;
569
570                 index = ship_get_index_from_subsys(subsys, ship_p->objnum);
571                 
572                 vector hit;
573                 if (hitpos) {
574                         hit = *hitpos;
575                 } else {
576                         hit = g_subobj_pos;
577                 }
578                 send_subsystem_destroyed_packet( ship_p, index, hit );
579         }
580
581         // next do a quick sanity check on the current hits that we are keeping for the generic subsystems
582         // I think that there might be rounding problems with the floats.  This code keeps us safe.
583         if ( ship_p->subsys_info[type].num == 1 ) {
584                 ship_p->subsys_info[type].current_hits = 0.0f;
585         } else {
586                 float hits;
587                 ship_subsys *ssp;
588
589                 hits = 0.0f;
590                 for ( ssp=GET_FIRST(&ship_p->subsys_list); ssp != END_OF_LIST(&ship_p->subsys_list); ssp = GET_NEXT(ssp) ) {
591                         if ( ssp->system_info->type == type )
592                                 hits += ssp->current_hits;
593                 }
594                 ship_p->subsys_info[type].current_hits = hits;
595         }
596
597         // store an event in the event log.  Also, determine if all turrets or all
598         // engines have been destroyed (if the subsystem is a turret or engine).
599         // put a disabled or disarmed entry in the log if this is the case
600         // 
601         // MWA -- 1/8/98  A problem was found when trying to determine (via sexpression) when some subsystems
602         // were destroyed.  The bottom line is that is the psub->name and psub->subobj_name are different,
603         // then direct detection doesn't work.  (This scenario happens mainly with turrets and probably with
604         // engines).  So, my solution is to encode the ship_info index, and the subsystem index into one
605         // integer, and pass that as the "index" parameter to add_entry.  We'll use that information to
606         // print out the info in the mission log.
607         Assert( ship_p->ship_info_index < 65535 );
608
609         // get the "index" of this subsystem in the ship info structure.
610         for ( i = 0; i < sip->n_subsystems; i++ ) {
611                 if ( &(sip->subsystems[i]) == psub )
612                         break;
613         }
614         Assert( i < sip->n_subsystems );
615         Assert( i < 65535 );
616         log_index = ((ship_p->ship_info_index << 16) & 0xffff0000) | (i & 0xffff);
617
618         // Don't log or display info about the activation subsytem
619         int display = (psub->type != SUBSYSTEM_ACTIVATION);
620         if (display) {
621                 mission_log_add_entry(LOG_SHIP_SUBSYS_DESTROYED, ship_p->ship_name, psub->subobj_name, log_index );
622                 if ( ship_obj == Player_obj ) {
623                         snd_play( &Snds[SND_SUBSYS_DIE_1], 0.0f );
624                         HUD_printf(XSTR( "Your %s subsystem has been destroyed", 499), psub->name);
625                 }
626         }
627
628         if ( psub->type == SUBSYSTEM_TURRET ) {
629                 if ( ship_p->subsys_info[type].current_hits == 0.0f ) {
630                         //      Don't create "disarmed" event for small ships.
631                         if (!(Ship_info[ship_p->ship_info_index].flags & SIF_SMALL_SHIP)) {
632                                 mission_log_add_entry(LOG_SHIP_DISARMED, ship_p->ship_name, NULL );
633                                 // ship_p->flags |= SF_DISARMED;
634                         }
635                 }
636         } else if (psub->type == SUBSYSTEM_ENGINE ) {
637                 // when an engine is destroyed, we must change the max velocity of the ship
638                 // to be some fraction of its normal maximum value
639
640                 if ( ship_p->subsys_info[type].current_hits == 0.0f ) {
641                         mission_log_add_entry(LOG_SHIP_DISABLED, ship_p->ship_name, NULL );
642                         ship_p->flags |= SF_DISABLED;                           // add the disabled flag
643                 }
644         }
645
646         if ( psub->subobj_num > -1 )    {
647                 shipfx_blow_off_subsystem(ship_obj,ship_p,subsys,&g_subobj_pos);
648                 subsys->submodel_info_1.blown_off = 1;
649         }
650
651         if ( (psub->subobj_num != psub->turret_gun_sobj) && (psub->turret_gun_sobj >-1) )               {
652                 subsys->submodel_info_2.blown_off = 1;
653         }
654
655         // play sound effect when subsys gets blown up
656         int sound_index=-1;
657         if ( Ship_info[ship_p->ship_info_index].flags & SIF_HUGE_SHIP ) {
658                 sound_index=SND_CAPSHIP_SUBSYS_EXPLODE;
659         } else if ( Ship_info[ship_p->ship_info_index].flags & SIF_BIG_SHIP ) {
660                 sound_index=SND_SUBSYS_EXPLODE;
661         }
662         if ( sound_index >= 0 ) {
663                 snd_play_3d( &Snds[sound_index], &g_subobj_pos, &View_position );
664         }
665 }
666
667 // Return weapon type that is associated with damaging_objp
668 // input:       damaging_objp           =>      object pointer responsible for damage
669 //      exit:           -1              =>      no weapon type is associated with damage object
670 //                              >=0     =>      weapon type associated with damage object
671 int shiphit_get_damage_weapon(object *damaging_objp)
672 {
673         int weapon_info_index = -1;
674
675         if ( damaging_objp ) {
676                 switch(damaging_objp->type) {
677                 case OBJ_WEAPON:
678                         weapon_info_index = Weapons[damaging_objp->instance].weapon_info_index;
679                         break;
680                 case OBJ_SHOCKWAVE:
681                         weapon_info_index = shockwave_weapon_index(damaging_objp->instance);
682                         break;
683                 default:
684                         weapon_info_index = -1;
685                         break;
686                 }
687         }
688
689         return weapon_info_index;
690 }
691
692 //      Return range at which this object can apply damage.
693 //      Based on object type and subsystem type.
694 float subsys_get_range(object *other_obj, ship_subsys *subsys)
695 {
696         float   range;
697
698         if (other_obj->type == OBJ_SHOCKWAVE) {
699                 range = Shockwaves[other_obj->instance].outer_radius * 0.75f;   //      Shockwaves were too lethal to subsystems.
700         } else if ( subsys->system_info->type == SUBSYSTEM_TURRET ) {
701                 range = subsys->system_info->radius*3;
702         } else {
703                 range = subsys->system_info->radius*2;
704         }
705
706         return range;
707 }
708
709 #define MAX_DEBRIS_SHARDS       16              // cap the amount of debris shards that fly off per hit
710
711 // Make some random debris particles.  Previous way was not very random.  Create debris 75% of the time.
712 // Don't worry about multiplayer since this debris is the small stuff that cannot collide
713 void create_subsys_debris(object *ship_obj, vector *hitpos)
714 {
715         float show_debris = frand();
716         
717         if ( show_debris <= 0.75f ) {
718                 int ndebris;
719
720                 ndebris = (int)(show_debris * Detail.num_small_debris) + 1;                     // number of pieces of debris to create
721
722                 if ( ndebris > MAX_DEBRIS_SHARDS )
723                         ndebris = MAX_DEBRIS_SHARDS;
724
725                 //mprintf(( "Damage = %.1f, ndebris=%d\n", show_debris, ndebris ));
726                 for (int i=0; i<ndebris; i++ )  {
727                         debris_create( ship_obj, -1, -1, hitpos, hitpos, 0, 1.0f );
728                 }
729         }
730 }
731
732 void create_vaporize_debris(object *ship_obj, vector *hitpos)
733 {
734         int ndebris;
735         float show_debris = frand();
736
737         ndebris = (int)(4.0f * ((0.5f + show_debris) * Detail.num_small_debris)) + 5;                   // number of pieces of debris to create
738
739         if ( ndebris > MAX_DEBRIS_SHARDS ) {
740                 ndebris = MAX_DEBRIS_SHARDS;
741         }
742
743         //mprintf(( "Damage = %.1f, ndebris=%d\n", show_debris, ndebris ));
744         for (int i=0; i<ndebris; i++ )  {
745                 debris_create( ship_obj, -1, -1, hitpos, hitpos, 0, 1.4f );
746         }
747 }
748
749 #define MAX_SUBSYS_LIST 32
750
751 typedef struct {
752         float   dist;
753         float   range;
754         ship_subsys     *ptr;
755 } sublist;
756
757 // do_subobj_hit_stuff() is called when a collision is detected between a ship and something
758 // else.  This is where we see if any sub-objects on the ship should take damage.
759 //
760 //      Depending on where the collision occurs, the sub-system and surrounding hull will take 
761 // different amounts of damage.  The amount of damage a sub-object takes depending on how
762 // close the colliding object is to the center of the sub-object.  The remaining hull damage
763 // will be returned to the caller via the damage parameter.
764 //
765 //
766 // 0   -> 0.5 radius   : 100% subobject    0%  hull
767 // 0.5 -> 1.0 radius   :  50% subobject   50%  hull
768 // 1.0 -> 2.0 radius   :  25% subobject   75%  hull
769 //     >  2.0 radius   :   0% subobject  100%  hull
770 //
771 //
772 // The weapon damage is not neccesarily distributed evently between sub-systems when more than
773 // one sub-system is to take damage.  Whenever damage is to be assigned to a sub-system, the above
774 // percentages are used.  So, if more than one sub-object is taking damage, the second sub-system
775 // to be assigned damage will take less damage.  Eg. weapon hits in the 25% damage range of two
776 // subsytems, and the weapon damage is 12.  First subsystem takes 3 points damage.  Second subsystem
777 // will take 0.25*9 = 2.25 damage.  Should be close enough for most cases, and hull would receive 
778 // 0.75 * 9 = 6.75 damage.
779 //
780 //      Used to use the following constants, but now damage is linearly scaled up to 2x the subsystem
781 //      radius.  Same damage applied as defined by constants below.
782 //
783 //      Returns unapplied damage, which will probably be applied to the hull.
784 //
785 // Shockwave damage is handled here.  If other_obj->type == OBJ_SHOCKWAVE, it's a shockwave.
786 // apply the same damage to all subsystems.
787 //      Note: A negative damage number means to destroy the corresponding subsystem.  For example, call with -SUBSYSTEM_ENGINE to destroy engine.
788
789 float do_subobj_hit_stuff(object *ship_obj, object *other_obj, vector *hitpos, float damage)
790 {
791         vector                  g_subobj_pos;
792         float                           damage_left;
793         int                             weapon_info_index;
794         ship_subsys             *subsys;
795         ship                            *ship_p;
796         sublist                 subsys_list[MAX_SUBSYS_LIST];
797         vector                  hitpos2;
798
799         ship_p = &Ships[ship_obj->instance];
800
801         //      Don't damage player subsystems in a training mission.
802         if ( The_mission.game_type & MISSION_TYPE_TRAINING ) {
803                 if (ship_obj == Player_obj){
804                         return damage;
805                 }
806         }
807
808         //      Shockwave damage is applied like weapon damage.  It gets consumed.
809         if (other_obj->type == OBJ_SHOCKWAVE) {
810                 //      MK, 9/2/99.  Shockwaves do zero subsystem damage on small ships.
811                 if ( Ship_info[ship_p->ship_info_index].flags & (SIF_SMALL_SHIP))
812                         return damage;
813                 else {
814
815                         damage_left = Shockwaves[other_obj->instance].damage/4.0f;
816                 }
817                 hitpos2 = other_obj->pos;
818         } else {
819                 damage_left = damage;
820                 hitpos2 = *hitpos;
821         }
822
823         // scale subsystem damage if appropriate
824         weapon_info_index = shiphit_get_damage_weapon(other_obj);
825         if ((other_obj->type == OBJ_WEAPON) && ( weapon_info_index >= 0 )) {
826                 damage_left *= Weapon_info[weapon_info_index].subsystem_factor;
827         }
828
829
830 #ifndef NDEBUG
831         float hitpos_dist = vm_vec_dist( hitpos, &ship_obj->pos );      
832         if ( hitpos_dist > ship_obj->radius * 2.0f )    {
833                 mprintf(( "BOGUS HITPOS PASSED TO DO_SUBOBJ_HIT_STUFF (%.1f > %.1f)!\n", hitpos_dist, ship_obj->radius * 2.0f ));
834                 // Int3();      // Get John ASAP!!!!  Someone passed a local coordinate instead of world for hitpos probably.
835         }
836 #endif
837
838         create_subsys_debris(ship_obj, hitpos);
839
840         //      First, create a list of the N subsystems within range.
841         //      Then, one at a time, process them in order.
842         int     count = 0;
843         for ( subsys=GET_FIRST(&ship_p->subsys_list); subsys != END_OF_LIST(&ship_p->subsys_list); subsys = GET_NEXT(subsys) ) {
844                 #ifndef NDEBUG
845                 //      Debug option.  If damage is negative of subsystem type, then just destroy that subsystem.
846                 if (damage < 0.0f) {
847                         // single player or multiplayer
848                         Assert(Player_ai->targeted_subsys != NULL);
849                         if ( (subsys == Player_ai->targeted_subsys) && (subsys->current_hits > 0) ) {
850                                 Assert(subsys->system_info->type == (int) -damage);
851                                 ship_p->subsys_info[subsys->system_info->type].current_hits -= subsys->current_hits;
852                                 if (ship_p->subsys_info[subsys->system_info->type].current_hits < 0) {
853                                         ship_p->subsys_info[subsys->system_info->type].current_hits = 0.0f;
854                                 }
855                                 subsys->current_hits = 0.0f;
856                                 do_subobj_destroyed_stuff( ship_p, subsys, hitpos );
857                                 continue;
858                         } else {
859                                 continue;
860                         }
861                 }
862                 #endif
863                 
864                 if (subsys->current_hits > 0.0f) {
865                         float   dist;
866
867                         // calculate the distance between the hit and the subsystem center
868                         get_subsystem_world_pos(ship_obj, subsys, &g_subobj_pos);
869                         dist = vm_vec_dist_quick(&hitpos2, &g_subobj_pos);
870
871                         float range = subsys_get_range(other_obj, subsys);
872
873                         if ( dist < range) {
874                                 subsys_list[count].dist = dist;
875                                 subsys_list[count].range = range;
876                                 subsys_list[count].ptr = subsys;
877                                 count++;
878
879                                 if (count >= MAX_SUBSYS_LIST){
880                                         break;
881                                 }
882                         }
883                 }
884         }
885
886         //      Now scan the sorted list of subsystems in range.
887         //      Apply damage to the nearest one first, subtracting off damage as we go.
888         int     i, j;
889         for (j=0; j<count; j++) {
890                 float   dist, range;
891                 ship_subsys     *subsys;
892
893                 int     min_index = -1;
894                 float   min_dist = 9999999.9f;
895
896                 for (i=0; i<count; i++) {
897                         if (subsys_list[i].dist < min_dist) {
898                                 min_dist = subsys_list[i].dist;
899                                 min_index = i;
900                         }
901                 }
902                 Assert(min_index != -1);
903
904                 float   damage_to_apply = 0.0f;
905                 subsys = subsys_list[min_index].ptr;
906                 range = subsys_list[min_index].range;
907                 dist = subsys_list[min_index].dist;
908                 subsys_list[min_index].dist = 9999999.9f;       //      Make sure we don't use this one again.
909
910                 //      HORRIBLE HACK!
911                 //      MK, 9/4/99
912                 //      When Helios bombs are dual fired against the Juggernaut in sm3-01 (FS2), they often
913                 //      miss their target.  There is code dating to FS1 in the collision code to detect that a bomb or
914                 //      missile has somehow missed its target.  It gets its lifeleft set to 0.1 and then it detonates.
915                 //      Unfortunately, the shockwave damage was cut by 4 above.  So boost it back up here.
916                 if ((dist < 10.0f) && (other_obj->type == OBJ_SHOCKWAVE)) {
917                         damage_left *= 4.0f * Weapon_info[weapon_info_index].subsystem_factor;;
918                 }
919
920 //              if (damage_left > 100.0f)
921 //                      nprintf(("AI", "Applying %7.3f damage to subsystem %7.3f units away.\n", damage_left, dist));
922
923                 if ( dist < range/2.0f ) {
924                         damage_to_apply = damage_left;
925                 } else if ( dist < range ) {
926                         damage_to_apply = damage_left * (1.0f - dist/range);
927                 }
928
929                 // if we're not in CLIENT_NODAMAGE multiplayer mode (which is a the NEW way of doing things)
930                 if (damage_to_apply > 0.1f && !(MULTIPLAYER_CLIENT) && !(Game_mode & GM_DEMO_PLAYBACK)) {
931                         //      Decrease damage to subsystems to player ships.
932                         if (ship_obj->flags & OF_PLAYER_SHIP){
933                                 damage_to_apply *= Skill_level_subsys_damage_scale[Game_skill_level];
934                         }
935                 
936                         subsys->current_hits -= damage_to_apply;
937                         ship_p->subsys_info[subsys->system_info->type].current_hits -= damage_to_apply;
938                         damage_left -= damage_to_apply;         // decrease the damage left to apply to the ship subsystems
939
940                         if (subsys->current_hits < 0.0f) {
941                                 damage_left -= subsys->current_hits;
942                                 ship_p->subsys_info[subsys->system_info->type].current_hits -= subsys->current_hits;
943                                 subsys->current_hits = 0.0f;                                    // set to 0 so repair on subsystem takes immediate effect
944                         }
945
946                         if ( ship_p->subsys_info[subsys->system_info->type].current_hits < 0.0f ){
947                                 ship_p->subsys_info[subsys->system_info->type].current_hits = 0.0f;
948                         }
949
950                         // multiplayer clients never blow up subobj stuff on their own
951                         if ( (subsys->current_hits <= 0.0f) && !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK)){
952                                 do_subobj_destroyed_stuff( ship_p, subsys, hitpos );
953                         }
954
955                         if (damage_left <= 0)   { // no more damage to distribute, so stop checking
956                                 damage_left = 0.0f;
957                                 break;
958                         }
959                 }
960 //nprintf(("AI", "j=%i, sys = %s, dam = %6.1f, dam left = %6.1f, subhits = %5.0f\n", j, subsys->system_info->name, damage_to_apply, damage_left, subsys->current_hits));
961         }
962
963         //      Note: I changed this to return damage_left and it completely screwed up balance.
964         //      It had taken a few MX-50s to destory an Anubis (with 40% hull), then it took maybe ten.
965         //      So, I left it alone. -- MK, 4/15/98
966         return damage;
967 }
968
969 // Store who/what killed the player, so we can tell the player how he died
970 void shiphit_record_player_killer(object *killer_objp, player *p)
971 {
972         switch (killer_objp->type) {
973
974         case OBJ_WEAPON:
975                 p->killer_objtype=OBJ_WEAPON;
976                 p->killer_weapon_index=Weapons[killer_objp->instance].weapon_info_index;
977                 p->killer_species = Ship_info[Ships[Objects[killer_objp->parent].instance].ship_info_index].species;
978
979                 if ( &Objects[killer_objp->parent] == Player_obj ) {
980                         // killed by a missile?
981                         if(Weapon_info[p->killer_weapon_index].subtype == WP_MISSILE){
982                                 p->flags |= PLAYER_FLAGS_KILLED_SELF_MISSILES;
983                         } else {
984                                 p->flags |= PLAYER_FLAGS_KILLED_SELF_UNKNOWN;
985                         }
986                 }
987
988                 // in multiplayer, record callsign of killer if killed by another player
989                 if ( (Game_mode & GM_MULTIPLAYER) && ( Objects[killer_objp->parent].flags & OF_PLAYER_SHIP) ) {
990                         int pnum;
991
992                         pnum = multi_find_player_by_object( &Objects[killer_objp->parent] );
993                         if ( pnum != -1 ) {
994                                 strcpy(p->killer_parent_name, Net_players[pnum].player->callsign);
995                         } else {
996                                 nprintf(("Network", "Couldn't find player object of weapon for killer of %s\n", p->callsign));
997                         }
998                 } else {
999                         strcpy(p->killer_parent_name, Ships[Objects[killer_objp->parent].instance].ship_name);
1000                 }
1001                 break;
1002
1003         case OBJ_SHOCKWAVE:
1004                 p->killer_objtype=OBJ_SHOCKWAVE;
1005                 p->killer_weapon_index=shockwave_weapon_index(killer_objp->instance);
1006                 p->killer_species = Ship_info[Ships[Objects[killer_objp->parent].instance].ship_info_index].species;
1007
1008                 if ( &Objects[killer_objp->parent] == Player_obj ) {
1009                         p->flags |= PLAYER_FLAGS_KILLED_SELF_SHOCKWAVE;
1010                 }
1011
1012                 if ( (Game_mode & GM_MULTIPLAYER) && ( Objects[killer_objp->parent].flags & OF_PLAYER_SHIP) ) {
1013                         int pnum;
1014
1015                         pnum = multi_find_player_by_object( &Objects[killer_objp->parent] );
1016                         if ( pnum != -1 ) {
1017                                 strcpy(p->killer_parent_name, Net_players[pnum].player->callsign);
1018                         } else {
1019                                 nprintf(("Network", "Couldn't find player object of shockwave for killer of %s\n", p->callsign));
1020                         }
1021                 } else {
1022                         strcpy(p->killer_parent_name, Ships[Objects[killer_objp->parent].instance].ship_name);
1023                 }
1024                 break;
1025
1026         case OBJ_SHIP:
1027                 p->killer_objtype=OBJ_SHIP;
1028                 p->killer_weapon_index=-1;
1029                 p->killer_species = Ship_info[Ships[killer_objp->instance].ship_info_index].species;
1030
1031                 if ( Ships[killer_objp->instance].flags & SF_EXPLODED ) {
1032                         p->flags |= PLAYER_FLAGS_KILLED_BY_EXPLOSION;
1033                 }
1034
1035                 if ( Ships[Objects[p->objnum].instance].wash_killed ) {
1036                         p->flags |= PLAYER_FLAGS_KILLED_BY_ENGINE_WASH;
1037                 }
1038
1039                 // in multiplayer, record callsign of killer if killed by another player
1040                 if ( (Game_mode & GM_MULTIPLAYER) && (killer_objp->flags & OF_PLAYER_SHIP) ) {
1041                         int pnum;
1042
1043                         pnum = multi_find_player_by_object( killer_objp );
1044                         if ( pnum != -1 ) {
1045                                 strcpy(p->killer_parent_name, Net_players[pnum].player->callsign);
1046                         } else {
1047                                 nprintf(("Network", "Couldn't find player object for killer of %s\n", p->callsign));
1048                         }
1049                 } else {
1050                         strcpy(p->killer_parent_name, Ships[killer_objp->instance].ship_name);
1051                 }
1052                 break;
1053         
1054         case OBJ_DEBRIS:
1055         case OBJ_ASTEROID:
1056                 if ( killer_objp->type == OBJ_DEBRIS ) {
1057                         p->killer_objtype = OBJ_DEBRIS;
1058                 } else {
1059                         p->killer_objtype = OBJ_ASTEROID;
1060                 }
1061                 p->killer_weapon_index=-1;
1062                 p->killer_species = SPECIES_NONE;
1063                 p->killer_parent_name[0] = '\0';
1064                 break;
1065
1066         case OBJ_BEAM:
1067                 int beam_obj;
1068                 beam_obj = beam_get_parent(killer_objp);
1069                 p->killer_species = SPECIES_NONE;               
1070                 p->killer_objtype = OBJ_BEAM;
1071                 if(beam_obj != -1){                     
1072                         if((Objects[beam_obj].type == OBJ_SHIP) && (Objects[beam_obj].instance >= 0)){
1073                                 strcpy(p->killer_parent_name, Ships[Objects[beam_obj].instance].ship_name);
1074                         }
1075                         p->killer_species = Ship_info[Ships[Objects[beam_obj].instance].ship_info_index].species;
1076                 } else {                        
1077                         strcpy(p->killer_parent_name, "");
1078                 }
1079                 break;
1080         
1081         case OBJ_NONE:
1082                 if ( Game_mode & GM_MULTIPLAYER ) {
1083                         Int3();
1084                 }
1085                 p->killer_objtype=-1;
1086                 p->killer_weapon_index=-1;
1087                 p->killer_parent_name[0]=0;
1088                 p->killer_species = SPECIES_NONE;
1089                 break;
1090
1091         default:
1092                 Int3();
1093                 break;
1094         }
1095 }
1096
1097 //      Say dead stuff.
1098 void show_dead_message(object *ship_obj, object *other_obj)
1099 {
1100         int pnum;
1101         player *player_p;
1102
1103         // not doing anything when a non player dies.
1104         if ( !(ship_obj->flags & OF_PLAYER_SHIP) ){
1105                 return;
1106         }
1107
1108         if(other_obj == NULL){
1109                 return;
1110         }
1111
1112         // Get a pointer to the player (we are assured a player ship was killed)
1113         if ( Game_mode & GM_NORMAL ) {
1114                 player_p = Player;
1115         } else {
1116                 // in multiplayer, get a pointer to the player that died.
1117                 pnum = multi_find_player_by_object( ship_obj );
1118                 if ( pnum == -1 ) {
1119                         //Int3();                               // this condition is bad bad bad -- get Allender
1120                         return;
1121                 }
1122                 player_p = Net_players[pnum].player;
1123         }
1124
1125         // multiplayer clients should already have this information.
1126         if ( !MULTIPLAYER_CLIENT ){
1127                 shiphit_record_player_killer( other_obj, player_p );
1128         }
1129
1130         // display a hud message is the guy killed isn't me (multiplayer only)
1131         /*
1132         if ( (Game_mode & GM_MULTIPLAYER) && (ship_obj != Player_obj) ) {
1133                 char death_text[256];
1134
1135                 player_generate_death_text( player_p, death_text );
1136                 HUD_sourced_printf(HUD_SOURCE_HIDDEN, death_text);
1137         }
1138         */
1139 }
1140
1141 /* JAS: THIS DOESN'T SEEM TO BE USED, SO I COMMENTED IT OUT
1142 //      Apply damage to a ship, destroying if necessary, etc.
1143 //      Returns portion of damage that exceeds ship shields, ie the "unused" portion of the damage.
1144 //      Note: This system does not use the mesh shield.  It applies damage to the overall ship shield.
1145 float apply_damage_to_ship(object *objp, float damage)
1146 {
1147         float   _ss;
1148
1149         add_shield_strength(objp, -damage);
1150
1151         // check if shields are below 0%, if so take leftover damage and apply to ship integrity
1152         if ((_ss = get_shield_strength(objp)) < 0.0f ) {
1153                 damage = -_ss;
1154                 set_shield_strength(objp, 0.0f);
1155         } else
1156                 damage = 0.0f;
1157
1158         return damage;
1159 }
1160 */
1161
1162 //      Do music processing for a ship hit.
1163 void ship_hit_music(object *ship_obj, object *other_obj)
1164 {
1165         ship* ship_p = &Ships[ship_obj->instance];
1166
1167         // Switch to battle track when a ship is hit by fire 
1168         //
1169         // If the ship hit has an AI class of none, it is a Cargo, NavBuoy or other non-aggressive
1170         // ship, so don't start the battle music        
1171         if (stricmp(Ai_class_names[Ai_info[ship_p->ai_index].ai_class], NOX("none"))) {
1172                 int team_1, team_2;
1173                 // Only start if ship hit and firing ship are from different teams
1174                 team_1 = Ships[ship_obj->instance].team;
1175                 switch ( other_obj->type ) {
1176                         case OBJ_SHIP:
1177                                 team_2 = Ships[other_obj->instance].team;
1178                                 if ( !stricmp(Ai_class_names[Ai_info[Ships[other_obj->instance].ai_index].ai_class], NOX("none")) ) {
1179                                         team_1 = team_2;
1180                                 }
1181                                 break;
1182
1183                         case OBJ_WEAPON:
1184                                 // parent of weapon is object num of ship that fired it
1185                                 team_2 = Ships[Objects[other_obj->parent].instance].team;       
1186                                 break;
1187
1188                         default:
1189                                 team_2 = team_1;
1190                                 break;  // Unexpected object type collided with ship, no big deal.
1191                 } // end switch
1192
1193                 if ( team_1 != team_2 )
1194                         event_music_battle_start();
1195         }
1196 }
1197
1198 //      Make sparks fly off a ship.
1199 // Currently used in misison_parse to create partially damaged ships.
1200 // NOTE: hitpos is in model coordinates on the detail[0] submodel (highest detail hull)
1201 // WILL NOT WORK RIGHT IF ON A ROTATING SUBMODEL
1202 void ship_hit_sparks_no_rotate(object *ship_obj, vector *hitpos)
1203 {
1204         ship            *ship_p = &Ships[ship_obj->instance];
1205
1206         int n = ship_p->num_hits;
1207         if (n >= MAX_SHIP_HITS) {
1208                 n = rand() % MAX_SHIP_HITS;
1209         } else {
1210                 ship_p->num_hits++;
1211         }
1212
1213         // No rotation.  Just make the spark
1214         ship_p->sparks[n].pos = *hitpos;
1215         ship_p->sparks[n].submodel_num = -1;
1216
1217         shipfx_emit_spark(ship_obj->instance, n);               // Create the first wave of sparks
1218
1219         if ( n == 0 )   {
1220                 ship_p->next_hit_spark = timestamp(0);          // when a hit spot will spark
1221         }
1222 }
1223
1224 // find the max number of sparks allowed for ship
1225 // limited for fighter by hull % others by radius.
1226 int get_max_sparks(object* ship_obj)
1227 {
1228         Assert(ship_obj->type == OBJ_SHIP);
1229         Assert((ship_obj->instance >= 0) && (ship_obj->instance < MAX_SHIPS));
1230         if(ship_obj->type != OBJ_SHIP){
1231                 return 1;
1232         }
1233         if((ship_obj->instance < 0) || (ship_obj->instance >= MAX_SHIPS)){
1234                 return 1;
1235         }
1236
1237         ship *ship_p = &Ships[ship_obj->instance];
1238         ship_info* si = &Ship_info[ship_p->ship_info_index];
1239         if (si->flags & SIF_FIGHTER) {
1240                 float hull_percent = ship_obj->hull_strength / Ship_info[ship_p->ship_info_index].initial_hull_strength;
1241
1242                 if (hull_percent > 0.8f) {
1243                         return 1;
1244                 } else if (hull_percent > 0.3f) {
1245                         return 2;
1246                 } else {
1247                         return 3;
1248                 }
1249         } else {
1250                 int num_sparks = (int) (ship_obj->radius * 0.08f);
1251                 if (num_sparks < 3) {
1252                         return 3;
1253                 } else if (num_sparks > MAX_SHIP_HITS) {
1254                         return MAX_SHIP_HITS;
1255                 } else {
1256                         return num_sparks;
1257                 }
1258         }
1259 }
1260
1261
1262 // helper function to qsort, sorting spark pairs by distance
1263 int spark_compare( const void *elem1, const void *elem2 )
1264 {
1265         spark_pair *pair1 = (spark_pair *) elem1;
1266         spark_pair *pair2 = (spark_pair *) elem2;
1267
1268         Assert(pair1->dist >= 0);
1269         Assert(pair2->dist >= 0);
1270
1271         if ( pair1->dist <  pair2->dist ) {
1272                 return -1;
1273         } else {
1274                 return 1;
1275         }
1276 }
1277
1278 // for big ships, when all spark slots are filled, make intelligent choice of one to be recycled
1279 int choose_next_spark(object *ship_obj, vector *hitpos)
1280 {
1281         int i, j, count, num_sparks, num_spark_pairs, spark_num;
1282         vector world_hitpos[MAX_SHIP_HITS];
1283         spark_pair spark_pairs[MAX_SPARK_PAIRS];
1284         ship *shipp = &Ships[ship_obj->instance];
1285
1286         // only choose next spark when all slots are full
1287         Assert(get_max_sparks(ship_obj) == Ships[ship_obj->instance].num_hits);
1288
1289         // get num_sparks
1290         num_sparks = Ships[ship_obj->instance].num_hits;
1291         Assert(num_sparks <= MAX_SHIP_HITS);
1292
1293         // get num_spark_paris -- only sort these
1294         num_spark_pairs = (num_sparks * num_sparks - num_sparks) / 2;
1295
1296         // get the world hitpos for all sparks
1297         bool model_started = false;
1298         for (spark_num=0; spark_num<num_sparks; spark_num++) {
1299                 if (shipp->sparks[spark_num].submodel_num != -1) {
1300                         if ( !model_started) {
1301                                 model_started = true;
1302                                 ship_model_start(ship_obj);
1303                         }
1304                         model_find_world_point(&world_hitpos[spark_num], &shipp->sparks[spark_num].pos, shipp->modelnum, shipp->sparks[spark_num].submodel_num, &ship_obj->orient, &ship_obj->pos);
1305                 } else {
1306                         // rotate sparks correctly with current ship orient
1307                         vm_vec_unrotate(&world_hitpos[spark_num], &shipp->sparks[spark_num].pos, &ship_obj->orient);
1308                         vm_vec_add2(&world_hitpos[spark_num], &ship_obj->pos);
1309                 }
1310         }
1311
1312         if (model_started) {
1313                 ship_model_stop(ship_obj);
1314         }
1315
1316         // check we're not making a spark in the same location as a current one
1317         for (i=0; i<num_sparks; i++) {
1318                 float dist = vm_vec_dist_squared(&world_hitpos[i], hitpos);
1319                 if (dist < 1) {
1320                         return i;
1321                 }
1322         }
1323
1324         // not same location, so maybe do random recyling
1325         if (frand() > 0.5f) {
1326                 return (rand() % num_sparks);
1327         }
1328
1329         // initialize spark pairs
1330         for (i=0; i<num_spark_pairs; i++) {
1331                 spark_pairs[i].index1 = 0;
1332                 spark_pairs[i].index2 = 0;
1333                 spark_pairs[i].dist = FLT_MAX;
1334         }
1335
1336         // set spark pairs
1337         count = 0;
1338         for (i=1; i<num_sparks; i++) {
1339                 for (j=0; j<i; j++) {
1340                         spark_pairs[count].index1 = i;
1341                         spark_pairs[count].index2 = j;
1342                         spark_pairs[count++].dist = vm_vec_dist_squared(&world_hitpos[i], &world_hitpos[j]);
1343                 }
1344         }
1345         Assert(count == num_spark_pairs);
1346
1347         // sort pairs
1348         qsort(spark_pairs, count, sizeof(spark_pair), spark_compare);
1349         //mprintf(("Min spark pair dist %.1f\n", spark_pairs[0].dist));
1350
1351         // look through the first few sorted pairs, counting number of indices of closest pair
1352         int index1 = spark_pairs[0].index1;
1353         int index2 = spark_pairs[0].index2;
1354         int count1 = 0;
1355         int count2 = 0;
1356
1357         for (i=1; i<6; i++) {
1358                 if (spark_pairs[i].index1 == index1) {
1359                         count1++;
1360                 }
1361                 if (spark_pairs[i].index2 == index1) {
1362                         count1++;
1363                 }
1364                 if (spark_pairs[i].index1 == index2) {
1365                         count2++;
1366                 }
1367                 if (spark_pairs[i].index2 == index2) {
1368                         count2++;
1369                 }
1370         }
1371
1372         // recycle spark which has most indices in sorted list of pairs
1373         if (count1 > count2) {
1374                 return index1;
1375         } else {
1376                 return index2;
1377         }
1378 }
1379
1380
1381 //      Make sparks fly off a ship.
1382 void ship_hit_create_sparks(object *ship_obj, vector *hitpos, int submodel_num)
1383 {
1384         vector  tempv;
1385         ship            *ship_p = &Ships[ship_obj->instance];
1386
1387         int n, max_sparks;
1388
1389         n = ship_p->num_hits;
1390         max_sparks = get_max_sparks(ship_obj);
1391
1392         if (n >= max_sparks)    {
1393                 if ( Ship_info[ship_p->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP) ) {
1394                         // large ship, choose intelligently
1395                         n = choose_next_spark(ship_obj, hitpos);
1396                 } else {
1397                         // otherwise, normal choice
1398                         n = rand() % max_sparks;
1399                 }
1400         } else {
1401                 ship_p->num_hits++;
1402         }
1403
1404         ship *pship = &Ships[ship_obj->instance];
1405
1406         bool instancing = false;
1407         // decide whether to do instancing
1408         if (submodel_num != -1) {
1409                 polymodel *pm = model_get(pship->modelnum);
1410                 if (pm->detail[0] != submodel_num) {
1411                         // submodel is not hull
1412                         // OPTIMIZE ... check if submodel can not rotate
1413                         instancing = true;
1414                 }
1415         }
1416
1417         if (instancing) {
1418                 // get the hit position in the subobject RF
1419                 ship_model_start(ship_obj);
1420                 vector temp_zero, temp_x, temp_y, temp_z;
1421                 model_find_world_point(&temp_zero, &vmd_zero_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1422                 model_find_world_point(&temp_x, &vmd_x_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1423                 model_find_world_point(&temp_y, &vmd_y_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1424                 model_find_world_point(&temp_z, &vmd_z_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1425                 ship_model_stop(ship_obj);
1426
1427                 // find submodel x,y,z axes
1428                 vm_vec_sub2(&temp_x, &temp_zero);
1429                 vm_vec_sub2(&temp_y, &temp_zero);
1430                 vm_vec_sub2(&temp_z, &temp_zero);
1431
1432                 // find displacement from submodel origin
1433                 vector diff;
1434                 vm_vec_sub(&diff, hitpos, &temp_zero);
1435
1436                 // find displacement from submodel origin in submodel RF
1437                 ship_p->sparks[n].pos.x = vm_vec_dotprod(&diff, &temp_x);
1438                 ship_p->sparks[n].pos.y = vm_vec_dotprod(&diff, &temp_y);
1439                 ship_p->sparks[n].pos.z = vm_vec_dotprod(&diff, &temp_z);
1440                 ship_p->sparks[n].submodel_num = submodel_num;
1441                 ship_p->sparks[n].end_time = timestamp(-1);
1442         } else {
1443                 // Rotate hitpos into ship_obj's frame of reference.
1444                 vm_vec_sub(&tempv, hitpos, &ship_obj->pos);
1445                 vm_vec_rotate(&ship_p->sparks[n].pos, &tempv, &ship_obj->orient);
1446                 ship_p->sparks[n].submodel_num = -1;
1447                 ship_p->sparks[n].end_time = timestamp(-1);
1448         }
1449
1450         // Create the first wave of sparks
1451         shipfx_emit_spark(ship_obj->instance, n);
1452
1453         if ( n == 0 )   {
1454                 ship_p->next_hit_spark = timestamp(0);          // when a hit spot will spark
1455         }
1456 }
1457
1458 //      Called from ship_hit_kill() when we detect the player has been killed.
1459 void player_died_start(object *killer_objp)
1460 {
1461         nprintf(("Network", "starting my player death\n"));
1462         gameseq_post_event(GS_EVENT_DEATH_DIED);        
1463         
1464 /*      vm_vec_scale_add(&Dead_camera_pos, &Player_obj->pos, &Player_obj->orient.fvec, -10.0f);
1465         vm_vec_scale_add2(&Dead_camera_pos, &Player_obj->orient.uvec, 3.0f);
1466         vm_vec_scale_add2(&Dead_camera_pos, &Player_obj->orient.rvec, 5.0f);
1467 */
1468
1469         //      Create a good vector for the camera to move along during death sequence.
1470         object  *other_objp = NULL;
1471
1472         // on multiplayer clients, there have been occasions where we haven't been able to determine
1473         // the killer of a ship (due to bogus/mismatched/timed-out signatures on the client side).  If
1474         // we don't know the killer, use the Player_obj as the other_objp for camera position.
1475         if ( killer_objp ) {
1476                 switch (killer_objp->type) {
1477                 case OBJ_WEAPON:
1478                 case OBJ_SHOCKWAVE:
1479                         other_objp = &Objects[killer_objp->parent];
1480                         break;
1481                 case OBJ_SHIP:
1482                 case OBJ_DEBRIS:
1483                 case OBJ_ASTEROID:
1484                 case OBJ_NONE:  //      Something that just got deleted due to also dying -- it happened to me! --MK.           
1485                         other_objp = killer_objp;
1486                         break;
1487
1488                 case OBJ_BEAM:
1489                         int beam_obj_parent;
1490                         beam_obj_parent = beam_get_parent(killer_objp);
1491                         if(beam_obj_parent == -1){
1492                                 other_objp = killer_objp;
1493                         } else {
1494                                 other_objp = &Objects[beam_obj_parent];
1495                         }
1496                         break;
1497
1498                 default:
1499                         Int3();         //      Killed by an object of a peculiar type.  What is it?
1500                         other_objp = killer_objp;       //      Enable to continue, just in case we shipped it with this bug...
1501                 }
1502         } else {
1503                 other_objp = Player_obj;
1504         }
1505
1506         vm_vec_add(&Original_vec_to_deader, &Player_obj->orient.fvec, &Player_obj->orient.rvec);
1507         vm_vec_scale(&Original_vec_to_deader, 2.0f);
1508         vm_vec_add2(&Original_vec_to_deader, &Player_obj->orient.uvec);
1509         vm_vec_normalize(&Original_vec_to_deader);
1510
1511         vector  vec_from_killer;
1512         vector  *side_vec;
1513         float           dist;
1514
1515         Assert(other_objp != NULL);
1516
1517         if (Player_obj == other_objp) {
1518                 dist = 50.0f;
1519                 vec_from_killer = Player_obj->orient.fvec;
1520         } else {
1521                 dist = vm_vec_normalized_dir(&vec_from_killer, &Player_obj->pos, &other_objp->pos);
1522         }
1523
1524         if (dist > 100.0f)
1525                 dist = 100.0f;
1526         vm_vec_scale_add(&Dead_camera_pos, &Player_obj->pos, &vec_from_killer, dist);
1527
1528         float   dot = vm_vec_dot(&Player_obj->orient.rvec, &vec_from_killer);
1529         if (fl_abs(dot) > 0.8f)
1530                 side_vec = &Player_obj->orient.fvec;
1531         else
1532                 side_vec = &Player_obj->orient.rvec;
1533         
1534         vm_vec_scale_add2(&Dead_camera_pos, side_vec, 10.0f);
1535
1536         Player_ai->target_objnum = -1;          //      Clear targeting.  Otherwise, camera pulls away from player as soon as he blows up.
1537
1538         // stop any playing emp effect
1539         emp_stop_local();
1540 }
1541
1542
1543 #define DEATHROLL_TIME                                          3000                    //      generic deathroll is 3 seconds (3 * 1000 milliseconds)
1544 #define MIN_PLAYER_DEATHROLL_TIME               1000                    // at least one second deathroll for a player
1545 #define DEATHROLL_ROTVEL_CAP                            6.3f                    // maximum added deathroll rotvel in rad/sec (about 1 rev / sec)
1546 #define DEATHROLL_ROTVEL_MIN                            0.8f                    // minimum added deathroll rotvel in rad/sec (about 1 rev / 12 sec)
1547 #define DEATHROLL_MASS_STANDARD                 50                              // approximate mass of lightest ship
1548 #define DEATHROLL_VELOCITY_STANDARD     70                              // deathroll rotvel is scaled according to ship velocity
1549 #define DEATHROLL_ROTVEL_SCALE                  4                               // constant determines how quickly deathroll rotvel is ramped up  (smaller is faster)
1550
1551 void ai_announce_ship_dying(object *dying_objp);
1552
1553 void saturate_fabs(float *f, float max)
1554 {
1555         if ( fl_abs(*f) > max) {
1556                 if (*f > 0)
1557                         *f = max;
1558                 else
1559                         *f = -max;
1560         }
1561 }
1562
1563 // function to do generic things when a ship explodes
1564 void ship_generic_kill_stuff( object *objp, float percent_killed )
1565 {
1566         float rotvel_mag;
1567         int     delta_time;
1568         ship    *sp;
1569
1570         Assert(objp->type == OBJ_SHIP);
1571         Assert(objp->instance >= 0 && objp->instance < MAX_SHIPS );
1572         if((objp->type != OBJ_SHIP) || (objp->instance < 0) || (objp->instance >= MAX_SHIPS)){
1573                 return;
1574         }
1575         sp = &Ships[objp->instance];
1576         ship_info *sip = &Ship_info[sp->ship_info_index];
1577
1578         // if recording demo
1579         if(Game_mode & GM_DEMO_RECORD){
1580                 demo_POST_ship_kill(objp);
1581         }
1582
1583         ai_announce_ship_dying(objp);
1584
1585         sp->flags |= SF_DYING;
1586         objp->phys_info.flags |= (PF_DEAD_DAMP | PF_REDUCED_DAMP);
1587         delta_time = (int) (DEATHROLL_TIME);
1588
1589         //      For smaller ships, subtract off time proportional to excess damage delivered.
1590         if (objp->radius < BIG_SHIP_MIN_RADIUS)
1591                 delta_time -=  (int) (1.01f - 4*percent_killed);
1592
1593         //      Cut down cargo death rolls.  Looks a little silly. -- MK, 3/30/98.
1594         if (sip->flags & SIF_CARGO) {
1595                 delta_time /= 4;
1596         }
1597         
1598         //      Prevent bogus timestamps.
1599         if (delta_time < 2)
1600                 delta_time = 2;
1601         
1602         if (objp->flags & OF_PLAYER_SHIP) {
1603                 //      Note: Kamikaze ships have no minimum death time.
1604                 if (!(Ai_info[Ships[objp->instance].ai_index].ai_flags & AIF_KAMIKAZE) && (delta_time < MIN_PLAYER_DEATHROLL_TIME))
1605                         delta_time = MIN_PLAYER_DEATHROLL_TIME;
1606         }
1607
1608         //nprintf(("AI", "ShipHit.cpp: Frame %i, Gametime = %7.3f, Ship %s will die in %7.3f seconds.\n", Framecount, f2fl(Missiontime), Ships[objp->instance].ship_name, (float) delta_time/1000.0f));
1609
1610         //      Make big ships have longer deathrolls.
1611         //      This is debug code by MK to increase the deathroll time so ships have time to evade the shockwave.
1612         //      Perhaps deathroll time should be specified in ships.tbl.
1613         float damage = ship_get_exp_damage(objp);
1614
1615         if (damage >= 250.0f)
1616                 delta_time += 3000 + (int)(damage*4.0f + 4.0f*objp->radius);
1617
1618         if (Ai_info[sp->ai_index].ai_flags & AIF_KAMIKAZE)
1619                 delta_time = 2;
1620
1621         // Knossos gets 7-10 sec to die, time for "little" explosions
1622         if (Ship_info[sp->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
1623                 delta_time = 7000 + (int)(frand() * 3000.0f);
1624                 Ship_info[sp->ship_info_index].explosion_propagates = 0;
1625         }
1626         sp->final_death_time = timestamp(delta_time);   // Give him 3 secs to explode
1627
1628         if (sp->flags & SF_VAPORIZE) {
1629                 // Assert(Ship_info[sp->ship_info_index].flags & SIF_SMALL_SHIP);
1630
1631                 // LIVE FOR 100 MS
1632                 sp->final_death_time = timestamp(100);
1633         }
1634
1635         //nprintf(("AI", "Time = %7.3f: final_death_time set to %7.3f\n", (float) timestamp_ticker/1000.0f, (float) sp->final_death_time/1000.0f));
1636
1637         sp->pre_death_explosion_happened = 0;                           // The little fireballs haven't came in yet.
1638
1639         sp->next_fireball = timestamp(0);       //start one right away
1640
1641         ai_deathroll_start(objp);
1642
1643         // play death roll begin sound
1644         sp->death_roll_snd = snd_play_3d( &Snds[SND_DEATH_ROLL], &objp->pos, &View_position, objp->radius );
1645         if (objp == Player_obj)
1646                 joy_ff_deathroll();
1647
1648         // apply a whack
1649         //      rotational velocity proportional to original translational velocity, with a bit added in.
1650         //      Also, preserve half of original rotational velocity.
1651
1652         // At standard speed (70) and standard mass (50), deathroll rotvel should be capped at DEATHROLL_ROTVEL_CAP
1653         // Minimum deathroll velocity is set    DEATHROLL_ROTVEL_MIN
1654         // At lower speed, lower death rotvel (scaled linearly)
1655         // At higher mass, lower death rotvel (scaled logarithmically)
1656         // variable scale calculates the deathroll rotational velocity magnitude
1657         float logval = (float) log10(objp->phys_info.mass / (0.05f*DEATHROLL_MASS_STANDARD));
1658         float velval = ((vm_vec_mag_quick(&objp->phys_info.vel) + 3.0f) / DEATHROLL_VELOCITY_STANDARD);
1659         float   p1 = (float) (DEATHROLL_ROTVEL_CAP - DEATHROLL_ROTVEL_MIN);
1660
1661         rotvel_mag = (float) DEATHROLL_ROTVEL_MIN * 2.0f/(logval + 2.0f);
1662         rotvel_mag += (float) (p1 * velval/logval) * 0.75f;
1663
1664         // set so maximum velocity from rotation is less than 200
1665         if (rotvel_mag*objp->radius > 150) {
1666                 rotvel_mag = 150.0f / objp->radius;
1667         }
1668
1669         if (sp->dock_objnum_when_dead != -1) {
1670                 // don't change current rotvel
1671                 sp->deathroll_rotvel = objp->phys_info.rotvel;
1672         } else {
1673                 // if added rotvel is too random, we should decrease the random component, putting a const in front of the rotvel.
1674                 sp->deathroll_rotvel = objp->phys_info.rotvel;
1675                 sp->deathroll_rotvel.x += (frand() - 0.5f) * 2.0f * rotvel_mag;
1676                 saturate_fabs(&sp->deathroll_rotvel.x, 0.75f*DEATHROLL_ROTVEL_CAP);
1677                 sp->deathroll_rotvel.y += (frand() - 0.5f) * 3.0f * rotvel_mag;
1678                 saturate_fabs(&sp->deathroll_rotvel.y, 0.75f*DEATHROLL_ROTVEL_CAP);
1679                 sp->deathroll_rotvel.z += (frand() - 0.5f) * 6.0f * rotvel_mag;
1680                 // make z component  2x larger than larger of x,y
1681                 float largest_mag = max(fl_abs(sp->deathroll_rotvel.x), fl_abs(sp->deathroll_rotvel.y));
1682                 if (fl_abs(sp->deathroll_rotvel.z) < 2.0f*largest_mag) {
1683                         sp->deathroll_rotvel.z *= (2.0f * largest_mag / fl_abs(sp->deathroll_rotvel.z));
1684                 }
1685                 saturate_fabs(&sp->deathroll_rotvel.z, 0.75f*DEATHROLL_ROTVEL_CAP);
1686                 // nprintf(("Physics", "Frame: %i rotvel_mag: %5.2f, rotvel: (%4.2f, %4.2f, %4.2f)\n", Framecount, rotvel_mag, sp->deathroll_rotvel.x, sp->deathroll_rotvel.y, sp->deathroll_rotvel.z));
1687         }
1688
1689         
1690         // blow out his reverse thrusters. Or drag, same thing.
1691         objp->phys_info.rotdamp = (float) DEATHROLL_ROTVEL_SCALE / rotvel_mag;
1692         objp->phys_info.side_slip_time_const = 10000.0f;
1693
1694         vm_vec_zero(&objp->phys_info.max_vel);          // make so he can't turn on his own VOLITION anymore.
1695
1696         vm_vec_zero(&objp->phys_info.max_rotvel);       // make so he can't change speed on his own VOLITION anymore.
1697
1698 }
1699
1700 // called from ship_hit_kill if the ship is vaporized
1701 void ship_vaporize(ship *shipp)
1702 {
1703         object *ship_obj;
1704
1705         // sanity
1706         Assert(shipp != NULL);
1707         if(shipp == NULL){
1708                 return;
1709         }
1710         Assert((shipp->objnum >= 0) && (shipp->objnum < MAX_OBJECTS));
1711         if((shipp->objnum < 0) || (shipp->objnum >= MAX_OBJECTS)){
1712                 return;
1713         }
1714         ship_obj = &Objects[shipp->objnum];
1715
1716         // create debris shards
1717         create_vaporize_debris(ship_obj, &ship_obj->pos);
1718 }
1719
1720 //      *ship_obj was hit and we've determined he's been killed!  By *other_obj!
1721 void ship_hit_kill(object *ship_obj, object *other_obj, float percent_killed, int self_destruct)
1722 {
1723         ship *sp;
1724         char *killer_ship_name;
1725         int killer_damage_percent = 0;
1726         object *killer_objp = NULL;
1727
1728         sp = &Ships[ship_obj->instance];
1729         show_dead_message(ship_obj, other_obj);
1730
1731         if (ship_obj == Player_obj) {
1732                 player_died_start(other_obj);
1733         }
1734
1735         // maybe vaporize him
1736         if(sp->flags & SF_VAPORIZE){
1737                 ship_vaporize(sp);
1738         }
1739
1740         // hehe
1741         extern void game_tst_mark(object *objp, ship *shipp);
1742         game_tst_mark(ship_obj, sp);
1743
1744         // single player and multiplayer masters evaluate the scoring and kill stuff
1745         if ( !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK)) {
1746                 scoring_eval_kill( ship_obj );
1747
1748                 // ship is destroyed -- send this event to the mission log stuff to record this event.  Try to find who
1749                 // killed this ship.  scoring_eval_kill above should leave the obj signature of the ship who killed
1750                 // this guy (or a -1 if no one got the kill).
1751                 killer_ship_name = NULL;
1752                 killer_damage_percent = -1;
1753                 if ( sp->damage_ship_id[0] != -1 ) {
1754                         object *objp;
1755                         int sig;
1756
1757                         sig = sp->damage_ship_id[0];
1758                         for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
1759                                 if ( objp->signature == sig ){
1760                                         break;
1761                                 }
1762                         }
1763                         // if the object isn't around, the try to find the object in the list of ships which has exited                 
1764                         if ( objp != END_OF_LIST(&obj_used_list) ) {
1765                                 Assert ( (objp->type == OBJ_SHIP ) || (objp->type == OBJ_GHOST) );                                      // I suppose that this should be true
1766                                 killer_ship_name = Ships[objp->instance].ship_name;
1767
1768                                 killer_objp = objp;
1769                         } else {
1770                                 int ei;
1771
1772                                 ei = ship_find_exited_ship_by_signature( sig );
1773                                 if ( ei != -1 ){
1774                                         killer_ship_name = Ships_exited[ei].ship_name;
1775                                 }
1776                         }
1777                         killer_damage_percent = (int)(sp->damage_ship[0] * 100.0f);
1778                 }               
1779
1780                 if(!self_destruct){
1781                         // multiplayer
1782                         if(Game_mode & GM_MULTIPLAYER){
1783                                 char name1[256] = "";
1784                                 char name2[256] = "";
1785                                 int np_index;
1786
1787                                 // get first name                               
1788                                 np_index = multi_find_player_by_object(ship_obj);                               
1789                                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && (Net_players[np_index].player != NULL)){
1790                                         strcpy(name1, Net_players[np_index].player->callsign);
1791                                 } else {
1792                                         strcpy(name1, sp->ship_name);
1793                                 }
1794
1795                                 // argh
1796                                 if((killer_objp != NULL) || (killer_ship_name != NULL)){
1797
1798                                         // second name
1799                                         if(killer_objp == NULL){
1800                                                 strcpy(name2, killer_ship_name);
1801                                         } else {
1802                                                 np_index = multi_find_player_by_object(killer_objp);
1803                                                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && (Net_players[np_index].player != NULL)){
1804                                                         strcpy(name2, Net_players[np_index].player->callsign);
1805                                                 } else {
1806                                                         strcpy(name2, killer_ship_name);
1807                                                 }
1808                                         }                                       
1809                                 }
1810
1811                                 mission_log_add_entry(LOG_SHIP_DESTROYED, name1, name2, killer_damage_percent);
1812                         } else {
1813                                 // DKA: 8/23/99 allow message log in single player with no killer name
1814                                 //if(killer_ship_name != NULL){
1815                                 mission_log_add_entry(LOG_SHIP_DESTROYED, sp->ship_name, killer_ship_name, killer_damage_percent);
1816                                 //}
1817                         }
1818                 }
1819
1820                 // maybe praise the player for this kill
1821                 if ( (killer_damage_percent > 10) && (other_obj != NULL) && (other_obj->parent_sig == Player_obj->signature) ) {
1822                         ship_maybe_praise_player(sp);
1823                 }
1824         }
1825
1826         ship_generic_kill_stuff( ship_obj, percent_killed );
1827
1828         // mwa -- removed 2/25/98 -- why is this here?  ship_obj->flags &= ~(OF_PLAYER_SHIP);
1829         // if it is for observers, must deal with it a separate way!!!!
1830         if ( MULTIPLAYER_MASTER ) {
1831                 // check to see if this ship needs to be respawned
1832                 multi_respawn_check(ship_obj);          
1833                         
1834                 // send the kill packet to all players
1835                 // maybe send vaporize packet to all players
1836                 send_ship_kill_packet( ship_obj, other_obj, percent_killed, self_destruct );
1837         }       
1838
1839         // If ship from a player wing ship has died, then maybe play a scream
1840         if ( !(ship_obj->flags & OF_PLAYER_SHIP) && (sp->flags & SF_FROM_PLAYER_WING) ) {
1841                 ship_maybe_scream(sp);
1842         }
1843
1844         // If player is dying, have wingman lament (only in single player)
1845         if ( (Game_mode & GM_NORMAL) && (ship_obj == Player_obj) ) {
1846                 ship_maybe_lament();
1847         }
1848 }
1849
1850 // function to simply explode a ship where it is currently at
1851 void ship_self_destruct( object *objp )
1852 {       
1853         Assert ( objp->type == OBJ_SHIP );
1854
1855         // try and find a player
1856         if((Game_mode & GM_MULTIPLAYER) && (multi_find_player_by_object(objp) >= 0)){
1857                 int np_index = multi_find_player_by_object(objp);
1858                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && (Net_players[np_index].player != NULL)){
1859                         mission_log_add_entry(LOG_SELF_DESTRUCT, Net_players[np_index].player->callsign, NULL );
1860                 } else {
1861                         mission_log_add_entry(LOG_SELF_DESTRUCT, Ships[objp->instance].ship_name, NULL );
1862                 }
1863         } else {
1864                 mission_log_add_entry(LOG_SELF_DESTRUCT, Ships[objp->instance].ship_name, NULL );
1865         }
1866         
1867         // check to see if this ship needs to be respawned
1868         if(MULTIPLAYER_MASTER){
1869                 // player ship?
1870                 int np_index = multi_find_player_by_object(objp);
1871                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && MULTI_CONNECTED(Net_players[np_index]) && (Net_players[np_index].player != NULL)){
1872                         char msg[512] = "";
1873                         sprintf(msg, "%s %s", Net_players[np_index].player->callsign, XSTR("Self destructed", 1476));
1874
1875                         // send a message
1876                         send_game_chat_packet(Net_player, msg, MULTI_MSG_ALL, NULL, NULL, 2);
1877
1878                         // printf
1879                         if(!(Game_mode & GM_STANDALONE_SERVER)){
1880                                 HUD_printf(msg);
1881                         }
1882                 }
1883         }
1884
1885         // self destruct
1886         ship_hit_kill(objp, NULL, 1.0f, 1);     
1887 }
1888
1889 extern int Homing_hits, Homing_misses;
1890
1891 // Call this instead of physics_apply_whack directly to 
1892 // deal with two ships docking properly.
1893 void ship_apply_whack(vector *force, vector *new_pos, object *objp)
1894 {
1895         if (objp->type == OBJ_SHIP)     {
1896                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_SUPPORT | SIF_CARGO)) {
1897                         int     docked_to_objnum;       
1898                         ai_info *aip;
1899
1900                         aip = &Ai_info[Ships[objp->instance].ai_index];
1901                 
1902                         if (aip->ai_flags & AIF_DOCKED) {
1903                                 docked_to_objnum = aip->dock_objnum;
1904                                 if (aip->dock_objnum != -1) {
1905                                         physics_apply_whack(force, new_pos, &Objects[docked_to_objnum].phys_info, &Objects[docked_to_objnum].orient, Objects[docked_to_objnum].phys_info.mass + objp->phys_info.mass);
1906                                         return;
1907                                 }
1908                         }
1909                 }
1910         }
1911         if (objp == Player_obj) {
1912                 nprintf(("Sandeep", "Playing stupid joystick effect\n"));
1913                 vector test;
1914                 vm_vec_unrotate(&test, force, &objp->orient);
1915
1916                 game_whack_apply( -test.x, -test.y );
1917         }
1918                                         
1919         physics_apply_whack(force, new_pos, &objp->phys_info, &objp->orient, objp->phys_info.mass);
1920 }
1921
1922 float Skill_level_player_damage_scale[NUM_SKILL_LEVELS] = {0.25f, 0.5f, 0.65f, 0.85f, 1.0f};
1923
1924
1925 // If a ship is dying and it gets hit, shorten its deathroll.
1926 //      But, if it's a player, don't decrease below MIN_PLAYER_DEATHROLL_TIME
1927 void shiphit_hit_after_death(object *ship_obj, float damage)
1928 {
1929         float   percent_killed;
1930         int     delta_time, time_remaining;
1931         ship    *shipp = &Ships[ship_obj->instance];
1932         ship_info       *sip = &Ship_info[shipp->ship_info_index];
1933
1934         // Since the explosion has two phases (final_death_time and really_final_death_time)
1935         // we should only shorten the deathroll time if that is the phase we're in.
1936         // And you can tell by seeing if the timestamp is valid, since it gets set to
1937         // invalid after it does the first large explosion.
1938         if ( !timestamp_valid(shipp->final_death_time) )        {
1939                 return;
1940         }
1941
1942         // Don't adjust vaporized ship
1943         if (shipp->flags & SF_VAPORIZE) {
1944                 return;
1945         }
1946
1947         //      Don't shorten deathroll on very large ships.
1948         if (ship_obj->radius > BIG_SHIP_MIN_RADIUS)
1949                 return;
1950
1951         percent_killed = damage/sip->initial_hull_strength;
1952         if (percent_killed > 1.0f)
1953                 percent_killed = 1.0f;
1954
1955         delta_time = (int) (4 * DEATHROLL_TIME * percent_killed);
1956         time_remaining = timestamp_until(shipp->final_death_time);
1957
1958         //nprintf(("AI", "Gametime = %7.3f, Time until %s dies = %7.3f, delta = %7.3f\n", f2fl(Missiontime), Ships[ship_obj->instance].ship_name, (float)time_remaining/1000.0f, delta_time));
1959         if (ship_obj->flags & OF_PLAYER_SHIP)
1960                 if (time_remaining < MIN_PLAYER_DEATHROLL_TIME)
1961                         return;
1962
1963         // nprintf(("AI", "Subtracting off %7.3f seconds from deathroll, reducing to %7.3f\n", (float) delta_time/1000.0f, (float) (time_remaining - delta_time)/1000.0f));
1964
1965         delta_time = time_remaining - delta_time;
1966         if (ship_obj->flags & OF_PLAYER_SHIP)
1967                 if (delta_time < MIN_PLAYER_DEATHROLL_TIME)
1968                         delta_time = MIN_PLAYER_DEATHROLL_TIME;
1969
1970         //      Prevent bogus timestamp.
1971         if (delta_time < 2)
1972                 delta_time = 2;
1973
1974         shipp->final_death_time = timestamp(delta_time);        // Adjust time until explosion.
1975 }
1976
1977 MONITOR( ShipHits );
1978 MONITOR( ShipNumDied );
1979
1980 int maybe_shockwave_damage_adjust(object *ship_obj, object *other_obj, float *damage)
1981 {
1982         ship_subsys *subsys;
1983         ship *shipp;
1984         float dist, nearest_dist = FLT_MAX;
1985         vector g_subobj_pos;
1986         float max_damage;
1987         shockwave *sw;
1988
1989         Assert(ship_obj->type == OBJ_SHIP);
1990         if (other_obj->type != OBJ_SHOCKWAVE) {
1991                 return 0;
1992         }
1993
1994         if (!(Ship_info[Ships[ship_obj->instance].ship_info_index].flags & SIF_HUGE_SHIP)) {
1995                 return 0;
1996         }
1997
1998         shipp = &Ships[ship_obj->instance];
1999         sw = &Shockwaves[other_obj->instance];
2000
2001         // find closest subsystem distance to shockwave origin
2002         for (subsys=GET_FIRST(&shipp->subsys_list); subsys != END_OF_LIST(&shipp->subsys_list); subsys = GET_NEXT(subsys) ) {
2003                 get_subsystem_world_pos(ship_obj, subsys, &g_subobj_pos);
2004                 dist = vm_vec_dist_quick(&g_subobj_pos, &other_obj->pos);
2005
2006                 if (dist < nearest_dist) {
2007                         nearest_dist = dist;
2008                 }
2009         }
2010
2011         // get max damage and adjust if needed to account for shockwave created from destroyed weapon
2012         max_damage = sw->damage;
2013         if (sw->flags & SW_WEAPON_KILL) {
2014                 max_damage *= 4.0f;
2015         }
2016
2017         // scale damage
2018         // floor of 25%, max if within inner_radius, linear between
2019         if (nearest_dist > sw->outer_radius) {
2020                 *damage = max_damage / 4.0f;
2021         } else if (nearest_dist < sw->inner_radius) {
2022                 *damage = max_damage;
2023         } else {
2024                 *damage = max_damage * (1.0f - 0.75f * (nearest_dist - sw->inner_radius) / (sw->outer_radius - sw->inner_radius));
2025         }
2026
2027         return 1;
2028 }
2029
2030 // ------------------------------------------------------------------------
2031 // ship_do_damage()
2032 //
2033 // Do damage assessment on a ship.    This should only be called
2034 // internally by ship_apply_global_damage and ship_apply_local_damage
2035 //
2036 // 
2037 //      input:  ship_obj                =>              object pointer for ship receiving damage
2038 //                              other_obj       =>              object pointer to object causing damage
2039 //                              hitpos          =>              impact world pos on the ship 
2040 //                              TODO:   get a better value for hitpos
2041 //                              damage          =>              damage to apply to the ship
2042 //                              shield_quadrant => which part of shield takes damage, -1 if not shield hit
2043 //                              wash_damage     =>              1 if damage is done by engine wash
2044 void ai_update_lethality(object *ship_obj, object *weapon_obj, float damage);
2045 static void ship_do_damage(object *ship_obj, object *other_obj, vector *hitpos, float damage, int shield_quadrant, int wash_damage=0)
2046 {
2047         ship *shipp;    
2048         float subsystem_damage = damage;                        // damage to be applied to subsystems
2049
2050         Assert(ship_obj->instance >= 0);
2051         Assert(ship_obj->type == OBJ_SHIP);
2052         shipp = &Ships[ship_obj->instance];
2053
2054         // maybe adjust damage done by shockwave for BIG|HUGE
2055         maybe_shockwave_damage_adjust(ship_obj, other_obj, &damage);
2056
2057         // update lethality of ship doing damage
2058         int update_lethality = FALSE;
2059         update_lethality = ((other_obj != NULL) && (other_obj->type == OBJ_WEAPON) && (other_obj->instance >= 0) && (other_obj->instance < MAX_WEAPONS));
2060         update_lethality = update_lethality || ((other_obj != NULL) && (other_obj->type == OBJ_SHOCKWAVE) && (other_obj->instance >= 0) && (other_obj->instance < MAX_SHOCKWAVES));
2061         if (update_lethality) {
2062                 ai_update_lethality(ship_obj, other_obj, damage);
2063         }
2064
2065         // if this is a weapon
2066         if((other_obj != NULL) && (other_obj->type == OBJ_WEAPON) && (other_obj->instance >= 0) && (other_obj->instance < MAX_WEAPONS)){
2067                 damage *= weapon_get_damage_scale(&Weapon_info[Weapons[other_obj->instance].weapon_info_index], other_obj, ship_obj);
2068         }
2069
2070         MONITOR_INC( ShipHits, 1 );
2071
2072         //      Don't damage player ship in the process of warping out.
2073         if ( Player->control_mode >= PCM_WARPOUT_STAGE2 )       {
2074                 if ( ship_obj == Player_obj ){
2075                         return;
2076                 }
2077         }
2078
2079         if ( (other_obj != NULL) && (other_obj->type == OBJ_WEAPON) ) {         
2080                 // for tvt and dogfight missions, don't scale damage
2081                 if( (Game_mode & GM_MULTIPLAYER) && ((Netgame.type_flags & NG_TYPE_TEAM) || (Netgame.type_flags & NG_TYPE_DOGFIGHT)) ){
2082                 } else {
2083                         // Do a little "skill" balancing for the player in single player and coop multiplayer
2084                         if (ship_obj->flags & OF_PLAYER_SHIP)   {
2085                                 damage *= Skill_level_player_damage_scale[Game_skill_level];
2086                                 subsystem_damage *= Skill_level_player_damage_scale[Game_skill_level];
2087                         }               
2088                 }
2089         }
2090
2091         // if this is not a laser, or i'm not a multiplayer client
2092         // apply pain to me
2093         if((other_obj != NULL) && ((Weapon_info[Weapons[other_obj->instance].weapon_info_index].subtype != WP_LASER) || !MULTIPLAYER_CLIENT) && (Player_obj != NULL) && (ship_obj == Player_obj)){
2094                 ship_hit_pain(damage);
2095         }       
2096
2097         // If the ship is invulnerable, do nothing
2098         if (ship_obj->flags & OF_INVULNERABLE)  {
2099                 return;
2100         }
2101
2102         //      if ship is already dying, shorten deathroll.
2103         if (shipp->flags & SF_DYING) {
2104                 shiphit_hit_after_death(ship_obj, damage);
2105                 return;
2106         }
2107         
2108         //      If we hit the shield, reduce it's strength and found
2109         // out how much damage is left over.
2110         if ( shield_quadrant > -1 && !(ship_obj->flags & OF_NO_SHIELDS) )       {
2111                 float shield_factor = -1.0f;
2112                 int     weapon_info_index;              
2113
2114                 weapon_info_index = shiphit_get_damage_weapon(other_obj);
2115                 if ( weapon_info_index >= 0 ) {
2116                         shield_factor = Weapon_info[weapon_info_index].shield_factor;
2117                 }
2118
2119                 if ( shield_factor >= 0 ) {
2120                         damage *= shield_factor;
2121                         subsystem_damage *= shield_factor;
2122                 }
2123
2124                 if ( damage > 0 ) {
2125                         float pre_shield = damage;
2126
2127                         damage = apply_damage_to_shield(ship_obj, shield_quadrant, damage);
2128
2129                         if(damage > 0.0f){
2130                                 subsystem_damage *= (damage / pre_shield);
2131                         } else {
2132                                 subsystem_damage = 0.0f;
2133                         }
2134                 }
2135
2136                 // if shield damage was increased, don't carry over leftover damage at scaled level
2137                 if ( shield_factor > 1 ) {
2138                         damage /= shield_factor;
2139
2140                         subsystem_damage /= shield_factor;
2141                 }
2142         }
2143                         
2144         // Apply leftover damage to the ship's subsystem and hull.
2145         if ( (damage > 0.0f) || (subsystem_damage > 0.0f) )     {
2146                 int     weapon_info_index;              
2147
2148                 float pre_subsys = subsystem_damage;
2149                 subsystem_damage = do_subobj_hit_stuff(ship_obj, other_obj, hitpos, subsystem_damage);
2150                 if(subsystem_damage > 0.0f){
2151                         damage *= (subsystem_damage / pre_subsys);
2152                 } else {
2153                         damage = 0.0f;
2154                 }
2155
2156                 // continue with damage?
2157                 if(damage > 0.0){
2158                         weapon_info_index = shiphit_get_damage_weapon(other_obj);
2159                         if ( weapon_info_index >= 0 ) {
2160                                 if (Weapon_info[weapon_info_index].wi_flags & WIF_PUNCTURE) {
2161                                         damage /= 4;
2162                                 }
2163
2164                                 damage *= Weapon_info[weapon_info_index].armor_factor;
2165                         }
2166
2167                         // if ship is flagged as can not die, don't let it die
2168                         if (ship_obj->flags & OF_GUARDIAN) {
2169                                 float min_hull_strength = 0.01f * Ship_info[Ships[ship_obj->instance].ship_info_index].initial_hull_strength;
2170                                 if ( (ship_obj->hull_strength - damage) < min_hull_strength ) {
2171                                         // find damage needed to take object to min hull strength
2172                                         damage = ship_obj->hull_strength - min_hull_strength;
2173
2174                                         // make sure damage is positive
2175                                         damage = max(0, damage);
2176                                 }
2177                         }
2178
2179                         // multiplayer clients don't do damage
2180                         if(((Game_mode & GM_MULTIPLAYER) && MULTIPLAYER_CLIENT) || (Game_mode & GM_DEMO_PLAYBACK)){
2181                         } else {
2182                                 ship_obj->hull_strength -= damage;              
2183                         }
2184
2185                         // let damage gauge know that player ship just took damage
2186                         if ( Player_obj == ship_obj ) {
2187                                 hud_gauge_popup_start(HUD_DAMAGE_GAUGE, 5000);
2188                         }
2189                 
2190                         // DB - removed 1/12/99 - scoring code properly bails if MULTIPLAYER_CLIENT
2191                         // in multiplayer, if I am not the host, get out of this function here!!
2192                         //if ( (Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER) ) {
2193                                 //return;
2194                         //}             
2195
2196                         switch (other_obj->type) {
2197                         case OBJ_SHOCKWAVE:
2198                                 scoring_add_damage(ship_obj,other_obj,damage);
2199                                 break;
2200                         case OBJ_ASTEROID:
2201                                 // don't call scoring for asteroids
2202                                 break;
2203                         case OBJ_WEAPON:
2204                                 if((other_obj->parent < 0) || (other_obj->parent >= MAX_OBJECTS)){
2205                                         scoring_add_damage(ship_obj, NULL, damage);
2206                                 } else {
2207                                         scoring_add_damage(ship_obj, &Objects[other_obj->parent], damage);
2208                                 }
2209                                 break;
2210                         default:
2211                                 break;
2212                         }
2213
2214                         if (ship_obj->hull_strength <= 0.0f) {
2215
2216                                 MONITOR_INC( ShipNumDied, 1 );
2217
2218                                 ship_info       *sip = &Ship_info[shipp->ship_info_index];
2219
2220                                 // If massive beam hitting small ship, vaporize  otherwise normal damage pipeline
2221                                 // Only vaporize once
2222                                 // multiplayer clients should skip this
2223                                 if(!MULTIPLAYER_CLIENT){
2224                                         if ( !(shipp->flags & SF_VAPORIZE) ) {
2225                                                 // Only small ships can be vaporized
2226                                                 if (sip->flags & (SIF_SMALL_SHIP)) {
2227                                                         if (other_obj->type == OBJ_BEAM) {
2228                                                                 int beam_weapon_info_index = beam_get_weapon_info_index(other_obj);
2229                                                                 if ( (beam_weapon_info_index > -1) && (Weapon_info[beam_weapon_info_index].wi_flags & (WIF_BEAM|WIF_HUGE)) ) {                                                          
2230                                                                         // Flag as vaporized
2231                                                                         shipp->flags |= SF_VAPORIZE;                                                            
2232                                                                 }
2233                                                         }
2234                                                 }
2235                                         }
2236                                 }
2237                                 
2238                                 // maybe engine wash death
2239                                 if (wash_damage) {
2240                                         shipp->wash_killed = 1;
2241                                 }
2242
2243                                 float percent_killed = -ship_obj->hull_strength/sip->initial_hull_strength;
2244                                 if (percent_killed > 1.0f){
2245                                         percent_killed = 1.0f;
2246                                 }
2247
2248                                 if ( !(shipp->flags & SF_DYING) && !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK)){  // if not killed, then kill
2249                                         ship_hit_kill(ship_obj, other_obj, percent_killed, 0);
2250                                 }
2251                         }
2252                 }
2253         }
2254
2255         // if the hitting object is a weapon, maybe do some fun stuff here
2256         if(other_obj->type == OBJ_WEAPON){
2257                 weapon_info *wip;
2258                 Assert(other_obj->instance >= 0);
2259                 if(other_obj->instance < 0){
2260                         return;
2261                 }
2262                 Assert(Weapons[other_obj->instance].weapon_info_index >= 0);
2263                 if(Weapons[other_obj->instance].weapon_info_index < 0){
2264                         return;
2265                 }
2266                 wip = &Weapon_info[Weapons[other_obj->instance].weapon_info_index];
2267
2268                 // if its a leech weapon
2269                 if(wip->wi_flags & WIF_ENERGY_SUCK){
2270                         // reduce afterburner fuel
2271                         shipp->afterburner_fuel -= wip->afterburner_reduce;
2272                         shipp->afterburner_fuel = (shipp->afterburner_fuel < 0.0f) ? 0.0f : shipp->afterburner_fuel;
2273
2274                         // reduce weapon energy
2275                         shipp->weapon_energy -= wip->weapon_reduce;
2276                         shipp->weapon_energy = (shipp->weapon_energy < 0.0f) ? 0.0f : shipp->weapon_energy;
2277                 }
2278         }
2279 }
2280
2281 // This gets called to apply damage when something hits a particular point on a ship.
2282 // This assumes that whoever called this knows if the shield got hit or not.
2283 // hitpos is in world coordinates.
2284 // if shield_quadrant is not -1, then that part of the shield takes damage properly.
2285 void ship_apply_local_damage(object *ship_obj, object *other_obj, vector *hitpos, float damage, int shield_quadrant, bool create_spark, int submodel_num, vector *hit_normal)
2286 {
2287         ship *ship_p    = &Ships[ship_obj->instance];   
2288
2289         //      If got hit by a weapon, tell the AI so it can react.  Only do this line in single player,
2290         // or if I am the master in a multiplayer game
2291         if ( other_obj->type == OBJ_WEAPON && ( !(Game_mode & GM_MULTIPLAYER) || ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)) )) {
2292                 weapon  *wp;
2293
2294                 wp = &Weapons[other_obj->instance];
2295                 //      If weapon hits ship on same team and that ship not targeted and parent of weapon not player,
2296                 //      don't do damage.
2297                 //      Ie, player can always do damage.  AI can only damage team if that ship is targeted.
2298                 if (wp->target_num != ship_obj-Objects) {
2299                         if ((ship_p->team == wp->team) && !(Objects[other_obj->parent].flags & OF_PLAYER_SHIP) ) {
2300                                 /*char  ship_name[64];
2301
2302                                 if (other_obj->parent_type == OBJ_SHIP) {
2303                                         strcpy(ship_name, Ships[Objects[other_obj->parent].instance].ship_name);
2304                                 } else
2305                                         strcpy(ship_name, XSTR("[not a ship]",-1));
2306                                 */
2307                                 // nprintf(("AI", "Ignoring hit on %s by weapon #%i, parent = %s\n", ship_p->ship_name, other_obj-Objects, ship_name));
2308                                 return;
2309                         }
2310                 }
2311         }
2312
2313         // only want to check the following in single player or if I am the multiplayer game server
2314         if ( !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK) && ((other_obj->type == OBJ_SHIP) || (other_obj->type == OBJ_WEAPON)) ){
2315                 ai_ship_hit(ship_obj, other_obj, hitpos, shield_quadrant, hit_normal);
2316         }
2317
2318         //      Cut damage done on the player by 4x in training missions, but do full accredidation
2319         if ( The_mission.game_type & MISSION_TYPE_TRAINING ){
2320                 if (ship_obj == Player_obj){
2321                         damage /= 4.0f;
2322                 }
2323         }       
2324
2325         // send a packet in multiplayer -- but don't sent it if the ship is already dying.  Clients can
2326         // take care of dealing with ship hits after a ship is already dead.
2327         // if ( (MULTIPLAYER_MASTER) && !(ship_p->flags & SF_DYING) ){
2328                 // if this is a player ship which is not mine, send him a ship hit packet
2329                 // int np_index = multi_find_player_by_object(ship_obj);
2330                 // if((np_index > 0) && (np_index < MAX_PLAYERS) && (np_index != MY_NET_PLAYER_NUM) && MULTI_CONNECTED(Net_players[np_index])){
2331                         // send_ship_hit_packet( ship_obj, other_obj, hitpos, damage, shield_quadrant, submodel_num, &Net_players[np_index]);
2332                 // }
2333         // }
2334
2335         // maybe tag the ship
2336         if(!MULTIPLAYER_CLIENT && (other_obj->type == OBJ_WEAPON) && (Weapon_info[Weapons[other_obj->instance].weapon_info_index].wi_flags & WIF_TAG)) {
2337                 if (Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_level == 1) {
2338                         Ships[ship_obj->instance].tag_left = Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_time;
2339                         Ships[ship_obj->instance].tag_total = Ships[ship_obj->instance].tag_left;
2340                         if (Ships[ship_obj->instance].time_first_tagged == 0) {
2341                                 Ships[ship_obj->instance].time_first_tagged = Missiontime;
2342                         }
2343                         mprintf(("TAGGED %s for %f seconds\n", Ships[ship_obj->instance].ship_name, Ships[ship_obj->instance].tag_left));
2344                 } else if (Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_level == 2) {
2345                         Ships[ship_obj->instance].level2_tag_left = Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_time;
2346                         Ships[ship_obj->instance].level2_tag_total = Ships[ship_obj->instance].level2_tag_left;
2347                         if (Ships[ship_obj->instance].time_first_tagged == 0) {
2348                                 Ships[ship_obj->instance].time_first_tagged = Missiontime;
2349                         }
2350                         mprintf(("Level 2 TAGGED %s for %f seconds\n", Ships[ship_obj->instance].ship_name, Ships[ship_obj->instance].level2_tag_left));
2351                 } else {
2352                         Int3(); // unknown tag level
2353                 }
2354         }
2355
2356
2357 #ifndef NDEBUG
2358         if (other_obj->type == OBJ_WEAPON) {
2359                 weapon_info     *wip = &Weapon_info[Weapons[other_obj->instance].weapon_info_index];
2360                 if (wip->wi_flags & WIF_HOMING) {
2361                         Homing_hits++;
2362                         // nprintf(("AI", " Hit!  Hits = %i/%i\n", Homing_hits, (Homing_hits + Homing_misses)));
2363                 }
2364         }
2365 #endif
2366
2367         
2368         if ( Event_Music_battle_started == 0 )  {
2369                 ship_hit_music(ship_obj, other_obj);
2370         }
2371         
2372
2373         if (damage < 0.0f){
2374                 damage = 0.0f;
2375         }
2376
2377         // evaluate any possible player stats implications
2378         scoring_eval_hit(ship_obj,other_obj);
2379
2380         ship_do_damage(ship_obj, other_obj, hitpos, damage, shield_quadrant );
2381
2382         // DA 5/5/98: move ship_hit_create_sparks() after do_damage() since number of sparks depends on hull strength
2383         // doesn't hit shield and we want sparks
2384         if ((shield_quadrant == MISS_SHIELDS) && create_spark)  {
2385                 // check if subsys destroyed
2386                 if ( !is_subsys_destroyed(ship_p, submodel_num) ) {
2387                         ship_hit_create_sparks(ship_obj, hitpos, submodel_num);
2388                 }
2389                 //fireball_create( hitpos, FIREBALL_SHIP_EXPLODE1, OBJ_INDEX(ship_obj), 0.25f );
2390         }
2391 }
2392
2393
2394
2395 // This gets called to apply damage when a damaging force hits a ship, but at no 
2396 // point in particular.  Like from a shockwave.   This routine will see if the
2397 // shield got hit and if so, apply damage to it.
2398 // You can pass force_center==NULL if you the damage doesn't come from anywhere,
2399 // like for debug keys to damage an object or something.  It will 
2400 // assume damage is non-directional and will apply it correctly.   
2401 void ship_apply_global_damage(object *ship_obj, object *other_obj, vector *force_center, float damage )
2402 {                               
2403         vector tmp, world_hitpos;
2404
2405         if ( force_center )     {
2406                 int shield_quad;
2407                 vector local_hitpos;
2408
2409                 // find world hitpos
2410                 vm_vec_sub( &tmp, force_center, &ship_obj->pos );
2411                 vm_vec_normalize_safe( &tmp );
2412                 vm_vec_scale_add( &world_hitpos, &ship_obj->pos, &tmp, ship_obj->radius );
2413
2414                 // Rotate world_hitpos into local coordinates (local_hitpos)
2415                 vm_vec_sub(&tmp, &world_hitpos, &ship_obj->pos );
2416                 vm_vec_rotate( &local_hitpos, &tmp, &ship_obj->orient );
2417
2418                 // shield_quad = quadrant facing the force_center
2419                 shield_quad = get_quadrant(&local_hitpos);
2420
2421                 // world_hitpos use force_center for shockwave
2422                 if (other_obj->type == OBJ_SHOCKWAVE && Ship_info[Ships[ship_obj->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
2423                         world_hitpos = *force_center;
2424                 }
2425
2426                 // Do damage on local point             
2427                 ship_do_damage(ship_obj, other_obj, &world_hitpos, damage, shield_quad );
2428         } else {
2429                 // Since an force_center wasn't specified, this is probably just a debug key
2430                 // to kill an object.   So pick a shield quadrant and a point on the
2431                 // radius of the object.   
2432                 vm_vec_scale_add( &world_hitpos, &ship_obj->pos, &ship_obj->orient.fvec, ship_obj->radius );
2433
2434                 for (int i=0; i<MAX_SHIELD_SECTIONS; i++){
2435                         ship_do_damage(ship_obj, other_obj, &world_hitpos, damage/MAX_SHIELD_SECTIONS, i);
2436                 }
2437         }
2438
2439         // AL 3-30-98: Show flashing blast icon if player ship has taken blast damage
2440         if ( ship_obj == Player_obj ) {
2441                 // only show blast icon if playing on medium skill or lower
2442                 if ( Game_skill_level <= 2 ) {
2443                         hud_start_text_flash(XSTR("Blast", 1428), 2000);
2444                 }
2445         }
2446
2447         // evaluate any player stats scoring conditions (specifically, blasts from remotely detonated secondary weapons)
2448         scoring_eval_hit(ship_obj,other_obj,1); 
2449 }
2450
2451 void ship_apply_wash_damage(object *ship_obj, object *other_obj, float damage)
2452 {
2453         vector world_hitpos, direction_vec, rand_vec;
2454
2455         // Since an force_center wasn't specified, this is probably just a debug key
2456         // to kill an object.   So pick a shield quadrant and a point on the
2457         // radius of the object
2458         vm_vec_rand_vec_quick(&rand_vec);
2459         vm_vec_scale_add(&direction_vec, &ship_obj->orient.fvec, &rand_vec, 0.5f);
2460         vm_vec_normalize_quick(&direction_vec);
2461         vm_vec_scale_add( &world_hitpos, &ship_obj->pos, &direction_vec, ship_obj->radius );
2462
2463         // Do damage to hull and not to shields
2464         ship_do_damage(ship_obj, other_obj, &world_hitpos, damage, -1, 1);
2465
2466         // AL 3-30-98: Show flashing blast icon if player ship has taken blast damage
2467         if ( ship_obj == Player_obj ) {
2468                 // only show blast icon if playing on medium skill or lower
2469                 if ( Game_skill_level <= 2 ) {
2470                         hud_start_text_flash(XSTR("Engine Wash", 1429), 2000);
2471                 }
2472         }
2473
2474         // evaluate any player stats scoring conditions (specifically, blasts from remotely detonated secondary weapons)
2475         scoring_eval_hit(ship_obj,other_obj,1);
2476 }
2477
2478 // player pain
2479 void ship_hit_pain(float damage)
2480 {
2481         game_flash( damage/15.0f, -damage/30.0f, -damage/30.0f );
2482
2483         // kill any active popups when you get hit.
2484         if ( Game_mode & GM_MULTIPLAYER ){
2485                 popup_kill_any_active();
2486         }
2487 }
2488