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