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