]> icculus.org git repositories - taylor/freespace2.git/blob - src/weapon/weapons.cpp
stub/warning removal.
[taylor/freespace2.git] / src / weapon / weapons.cpp
1 /*
2  * $Logfile: /Freespace2/code/Weapon/Weapons.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Code to handle the weapon systems
8  *
9  * $Log$
10  * Revision 1.5  2002/06/05 08:05:29  relnev
11  * stub/warning removal.
12  *
13  * reworked the sound code.
14  *
15  * Revision 1.4  2002/06/01 03:32:00  relnev
16  * fix texture loading mistake.
17  *
18  * enable some d3d stuff for opengl also
19  *
20  * Revision 1.3  2002/05/28 08:52:03  relnev
21  * implemented two assembly stubs.
22  *
23  * cleaned up a few warnings.
24  *
25  * added a little demo hackery to make it progress a little farther.
26  *
27  * Revision 1.2  2002/05/07 03:16:53  theoddone33
28  * The Great Newline Fix
29  *
30  * Revision 1.1.1.1  2002/05/03 03:28:11  root
31  * Initial import.
32  *
33  * 
34  * 69    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  * 68    9/14/99 1:32a Andsager
39  * Better LOD for weapon explosions when behind.  Move point ahead to get
40  * vertex and then find size.
41  * 
42  * 67    9/07/99 1:10p Mikek
43  * Fix code I busted due to adding lifeleft to missiles.
44  * 
45  * 66    9/07/99 12:20a Andsager
46  * LOD less agressive at lower hardware detail level
47  * 
48  * 65    9/06/99 7:21p Dave
49  * Commented out bad lifeleft scaling code in weapon_set_tracking_info()
50  * 
51  * 64    9/06/99 3:23p Andsager
52  * Make fireball and weapon expl ani LOD choice look at resolution of the
53  * bitmap
54  * 
55  * 63    9/06/99 12:46a Andsager
56  * Add weapon_explosion_ani LOD
57  * 
58  * 62    9/05/99 11:24p Mikek
59  * Fixed problems caused by earlier checkin (that was rolled back).
60  * Problem was wp->target_pos was not set for swarmers.
61  * 
62  * More tweaking of missile behavior.  Also add 20% to lifetime of a
63  * locked missile.
64  * 
65  * [Rolled back -- MK] 63    9/05/99 2:23p Mikek
66  * Make aspect seekers a little less likely to miss their target.
67  * Mysterious why they do it so often.  Maybe fix for FS3...
68  * 
69  * [Rolled back -- MK] 62    9/04/99 12:09p Mikek
70  * Limit number of spawned weapons that can home on player based on skill
71  * level.  Works same as for non-spawned weapons.  Only do in single
72  * player.
73  * 
74  * 61    8/27/99 1:34a Andsager
75  * Modify damage by shockwaves for BIG|HUGE ships.  Modify shockwave damge
76  * when weapon blows up.
77  * 
78  * 60    8/24/99 10:47a Jefff
79  * tech room weapon anims.  added tech anim field to weapons.tbl
80  * 
81  * 59    8/16/99 11:58p Andsager
82  * Disable collision on proximity for ships with SIF_DONT_COLLIDE_INVIS
83  * hulls.
84  * 
85  * 58    8/10/99 5:30p Jefff
86  * Added tech_title string to weapon_info.  Changed parser accordingly.
87  * 
88  * 57    8/05/99 2:06a Dave
89  * Whee.
90  * 
91  * 56    8/02/99 5:16p Dave
92  * Bumped up weapon title string length from 32 to 48
93  * 
94  * 55    7/29/99 5:41p Jefff
95  * Sound hooks for cmeasure success
96  * 
97  * 54    7/24/99 1:54p Dave
98  * Hud text flash gauge. Reworked dead popup to use 4 buttons in red-alert
99  * missions.
100  * 
101  * 53    7/19/99 7:20p Dave
102  * Beam tooling. Specialized player-killed-self messages. Fixed d3d nebula
103  * pre-rendering.
104  * 
105  * 52    7/18/99 12:32p Dave
106  * Randomly oriented shockwaves.
107  * 
108  * 51    7/16/99 1:50p Dave
109  * 8 bit aabitmaps. yay.
110  * 
111  * 50    7/15/99 9:20a Andsager
112  * FS2_DEMO initial checkin
113  * 
114  * 49    7/08/99 10:53a Dave
115  * New multiplayer interpolation scheme. Not 100% done yet, but still
116  * better than the old way.
117  * 
118  * 48    7/02/99 4:31p Dave
119  * Much more sophisticated lightning support.
120  * 
121  * 47    7/01/99 5:57p Johnson
122  * Oops. Fixed big ship damage.
123  * 
124  * 46    7/01/99 4:23p Dave
125  * Full support for multiple linked ambient engine sounds. Added "big
126  * damage" flag.
127  * 
128  * 45    6/30/99 5:53p Dave
129  * Put in new anti-camper code.
130  * 
131  * 44    6/22/99 3:24p Danw
132  * Fixed incorrect weapon hit sound culling.
133  * 
134  * 43    6/21/99 7:25p Dave
135  * netplayer pain packet. Added type E unmoving beams.
136  * 
137  * 42    6/14/99 10:45a Dave
138  * Made beam weapons specify accuracy by skill level in the weapons.tbl
139  * 
140  * 41    6/11/99 11:13a Dave
141  * last minute changes before press tour build.
142  * 
143  * 40    6/04/99 2:16p Dave
144  * Put in shrink effect for beam weapons.
145  * 
146  * 39    6/01/99 8:35p Dave
147  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
148  * awacs-set-radius sexpression.
149  * 
150  * 38    6/01/99 3:52p Dave
151  * View footage screen. Fixed xstrings to not display the & symbol. Popup,
152  * dead popup, pxo find player popup, pxo private room popup.
153  * 
154  * 37    5/27/99 6:17p Dave
155  * Added in laser glows.
156  * 
157  * 36    5/20/99 7:00p Dave
158  * Added alternate type names for ships. Changed swarm missile table
159  * entries.
160  * 
161  * 35    5/08/99 8:25p Dave
162  * Upped object pairs. First run of nebula lightning.
163  * 
164  * 34    4/28/99 11:13p Dave
165  * Temporary checkin of artillery code.
166  * 
167  * 33    4/28/99 3:11p Andsager
168  * Stagger turret weapon fire times.  Make turrets smarter when target is
169  * protected or beam protected.  Add weaopn range to weapon info struct.
170  * 
171  * 32    4/22/99 11:06p Dave
172  * Final pass at beam weapons. Solidified a lot of stuff. All that remains
173  * now is to tweak and fix bugs as they come up. No new beam weapon
174  * features.
175  * 
176  * 31    4/19/99 11:01p Dave
177  * More sophisticated targeting laser support. Temporary checkin.
178  * 
179  * 30    4/16/99 5:54p Dave
180  * Support for on/off style "stream" weapons. Real early support for
181  * target-painting lasers.
182  * 
183  * 29    4/07/99 6:22p Dave
184  * Fred and Freespace support for multiple background bitmaps and suns.
185  * Fixed link errors on all subprojects. Moved encrypt_init() to
186  * cfile_init() and lcl_init(), since its safe to call twice.
187  * 
188  * 28    4/02/99 1:35p Dave
189  * Removed weapon hit packet. No good for causing pain.
190  * 
191  * 27    4/02/99 9:55a Dave
192  * Added a few more options in the weapons.tbl for beam weapons. Attempt
193  * at putting "pain" packets into multiplayer.
194  * 
195  * 26    3/31/99 9:26p Dave
196  * Don't load beam textures when in Fred.
197  * 
198  * 25    3/31/99 8:24p Dave
199  * Beefed up all kinds of stuff, incluging beam weapons, nebula effects
200  * and background nebulae. Added per-ship non-dimming pixel colors.
201  * 
202  * 24    3/23/99 2:29p Andsager
203  * Fix shockwaves for kamikazi and Fred defined.  Collect together
204  * shockwave_create_info struct.
205  * 
206  * 23    3/23/99 11:03a Dave
207  * Added a few new fields and fixed parsing code for new weapon stuff.
208  * 
209  * 22    3/19/99 9:52a Dave
210  * Checkin to repair massive source safe crash. Also added support for
211  * pof-style nebulae, and some new weapons code.
212  * 
213  * 24    3/15/99 6:45p Daveb
214  * Put in rough nebula bitmap support.
215  * 
216  * 23    3/12/99 3:19p Enricco
217  * Remove spurious Int3()
218  * 
219  * 22    3/11/99 5:53p Dave
220  * More network optimization. Spliced in Dell OEM planet bitmap crap.
221  * 
222  * 21    3/10/99 6:51p Dave
223  * Changed the way we buffer packets for all clients. Optimized turret
224  * fired packets. Did some weapon firing optimizations.
225  * 
226  * 20    2/24/99 4:02p Dave
227  * Fixed weapon locking and homing problems for multiplayer dogfight mode.
228  * 
229  * 19    2/05/99 12:52p Dave
230  * Fixed Glide nondarkening textures.
231  * 
232  * 18    1/29/99 12:47a Dave
233  * Put in sounds for beam weapon. A bunch of interface screens (tech
234  * database stuff).
235  * 
236  * 17    1/27/99 9:56a Dave
237  * Temporary checkin of beam weapons for Dan to make cool sounds.
238  * 
239  * 16    1/25/99 5:03a Dave
240  * First run of stealth, AWACS and TAG missile support. New mission type
241  * :)
242  * 
243  * 15    1/24/99 11:37p Dave
244  * First full rev of beam weapons. Very customizable. Removed some bogus
245  * Int3()'s in low level net code.
246  * 
247  * 14    1/21/99 10:45a Dave
248  * More beam weapon stuff. Put in warmdown time.
249  * 
250  * 13    1/12/99 5:45p Dave
251  * Moved weapon pipeline in multiplayer to almost exclusively client side.
252  * Very good results. Bandwidth goes down, playability goes up for crappy
253  * connections. Fixed object update problem for ship subsystems.
254  * 
255  * 12    1/08/99 2:08p Dave
256  * Fixed software rendering for pofview. Super early support for AWACS and
257  * beam weapons.
258  * 
259  * 11    1/06/99 2:24p Dave
260  * Stubs and release build fixes.
261  * 
262  * 10    12/01/98 6:12p Johnson
263  * Make sure to page in weapon impact animations as xparent textures.
264  * 
265  * 9     11/20/98 4:08p Dave
266  * Fixed flak effect in multiplayer.
267  * 
268  * 8     11/14/98 5:33p Dave
269  * Lots of nebula work. Put in ship contrails.
270  * 
271  * 7     11/05/98 4:18p Dave
272  * First run nebula support. Beefed up localization a bit. Removed all
273  * conditional compiles for foreign versions. Modified mission file
274  * format.
275  * 
276  * 6     10/26/98 9:42a Dave
277  * Early flak gun support.
278  * 
279  * 5     10/23/98 3:51p Dave
280  * Full support for tstrings.tbl and foreign languages. All that remains
281  * is to make it active in Fred.
282  * 
283  * 4     10/07/98 6:27p Dave
284  * Globalized mission and campaign file extensions. Removed Silent Threat
285  * special code. Moved \cache \players and \multidata into the \data
286  * directory.
287  * 
288  * 3     10/07/98 4:49p Andsager
289  * don't do weapon swap (was needed for mission disk)
290  * 
291  * 2     10/07/98 10:54a Dave
292  * Initial checkin.
293  * 
294  * 1     10/07/98 10:51a Dave
295  * 
296  * 314   9/21/98 11:19p Dave
297  * Weapon name fix.
298  * 
299  * 313   9/19/98 4:33p Adam
300  * Changed default values for particle spew (used on Leech Cannon)
301  * 
302  * 312   9/13/98 10:51p Dave
303  * Put in newfangled icons for mission simulator room. New mdisk.vp
304  * checksum and file length.
305  * 
306  * 311   9/13/98 4:29p Andsager
307  * Maintain Weapon_info compataiblity with mission disk
308  * 
309  * 310   9/13/98 4:26p Andsager
310  * 
311  * 309   9/01/98 4:25p Dave
312  * Put in total (I think) backwards compatibility between mission disk
313  * freespace and non mission disk freespace, including pilot files and
314  * campaign savefiles.
315  * 
316  * 308   8/28/98 3:29p Dave
317  * EMP effect done. AI effects may need some tweaking as required.
318  * 
319  * 307   8/25/98 1:49p Dave
320  * First rev of EMP effect. Player side stuff basically done. Next comes
321  * AI code.
322  * 
323  * 306   8/18/98 10:15a Dave
324  * Touchups on the corkscrew missiles. Added particle spewing weapons.
325  * 
326  * 305   8/17/98 5:07p Dave
327  * First rev of corkscrewing missiles.
328  * 
329  * 304   6/30/98 2:23p Dave
330  * Revised object update system. Removed updates for all weapons. Put
331  * button info back into control info packet.
332  * 
333  * 303   6/22/98 8:36a Allender
334  * revamping of homing weapon system.  don't send as object updates
335  * anymore
336  * 
337  * 302   5/24/98 2:25p Allender
338  * be sure that homing missiles die on client when lifeleft gets too
339  * negative (lost packets)
340  * 
341  * 301   5/20/98 5:47p Sandeep
342  * 
343  * 300   5/18/98 1:58a Mike
344  * Make Phoenix not be fired at fighters (but yes bombers).
345  * Improve positioning of ships in guard mode.
346  * Make turrets on player ship not fire near end of support ship docking.
347  * 
348  * $NoKeywords: $
349  */
350
351 #include <stdlib.h>
352
353 #include "pstypes.h"
354 #include "systemvars.h"
355 #include "vecmat.h"
356 #include "tmapper.h"
357 #include "2d.h"
358 #include "3d.h"
359 #include "bmpman.h"
360 #include "model.h"
361 #include "key.h"
362 #include "physics.h"
363 #include "floating.h"
364 #include "model.h"
365 #include "lighting.h"
366 #include "object.h"
367 #include "weapon.h"
368 #include "ship.h"
369 #include "fireballs.h"
370 #include "player.h"
371 #include "hudtarget.h"
372 #include "freespace.h"
373 #include "radar.h"
374 #include "ai.h"
375 #include "sound.h"
376 #include "multi.h"
377 #include "multimsgs.h"
378 #include "linklist.h"
379 #include "timer.h"
380 #include "gamesnd.h"
381 #include "cmeasure.h"
382 #include "shockwave.h"
383 #include "model.h"
384 #include "staticrand.h"
385 #include "swarm.h"
386 #include "multiutil.h"
387 #include "shiphit.h"
388 #include "trails.h"
389 #include "hud.h"
390 #include "objcollide.h"
391 #include "aibig.h"
392 #include "particle.h"
393 #include "asteroid.h"
394 #include "joy_ff.h"
395 #include "multi_obj.h"
396 #include "corkscrew.h"
397 #include "emp.h"
398 #include "localize.h"
399 #include "flak.h"
400 #include "muzzleflash.h"
401
402 #ifndef NDEBUG
403 int Weapon_flyby_sound_enabled = 1;
404 DCF_BOOL( weapon_flyby, Weapon_flyby_sound_enabled )
405 #endif
406
407 static int Weapon_flyby_sound_timer;    
408
409 weapon Weapons[MAX_WEAPONS];
410 weapon_info Weapon_info[MAX_WEAPON_TYPES];
411
412 #define         MISSILE_OBJ_USED        (1<<0)                  // flag used in missile_obj struct
413 #define         MAX_MISSILE_OBJS        MAX_WEAPONS             // max number of missiles tracked in missile list
414 missile_obj Missile_objs[MAX_MISSILE_OBJS];     // array used to store missile object indexes
415 missile_obj Missile_obj_list;                                           // head of linked list of missile_obj structs
416
417
418 // WEAPON EXPLOSION INFO
419 #define MAX_weapon_expl_lod                                             4
420 #define MAX_Weapon_expl_info                                    3
421
422 typedef struct weapon_expl_lod {
423         char    filename[MAX_FILENAME_LEN];
424         int     bitmap_id;
425         int     num_frames;
426         int     fps;
427 } weapon_expl_lod;
428
429 typedef struct weapon_expl_info {
430         int                                     lod_count;      
431         weapon_expl_lod         lod[MAX_weapon_expl_lod];
432 } weapon_expl_info;
433
434 weapon_expl_info Weapon_expl_info[MAX_Weapon_expl_info];
435
436 int Num_weapon_expl = 0;
437
438 int Num_weapon_types = 0;
439
440 int Num_weapons = 0;
441 int Weapons_inited = 0;
442
443 int laser_model_inner = -1;
444 int laser_model_outer = -1;
445
446 int missile_model = -1;
447
448 char    *Weapon_names[MAX_WEAPON_TYPES];
449
450 int     First_secondary_index = -1;
451
452 #define MAX_SPAWN_WEAPONS       10                      //      Up to 10 weapons can spawn weapons.
453
454 int     Num_spawn_types;
455 char    Spawn_names[MAX_SPAWN_WEAPONS][NAME_LENGTH];
456
457 int Num_player_weapon_precedence;                               // Number of weapon types in Player_weapon_precedence
458 int Player_weapon_precedence[MAX_WEAPON_TYPES]; // Array of weapon types, precedence list for player weapon selection
459
460 // Used to avoid playing too many impact sounds in too short a time interval.
461 // This will elimate the odd "stereo" effect that occurs when two weapons impact at 
462 // nearly the same time, like from a double laser (also saves sound channels!)
463 #define IMPACT_SOUND_DELTA      50              // in milliseconds
464 int             Weapon_impact_timer;                    // timer, initalized at start of each mission
465
466 // energy suck defines
467 #define ESUCK_DEFAULT_WEAPON_REDUCE                             (10.0f)
468 #define ESUCK_DEFAULT_AFTERBURNER_REDUCE                (10.0f)
469
470 // scale factor for supercaps taking damage from weapons which are not "supercap" weapons
471 #define SUPERCAP_DAMAGE_SCALE                   0.25f
472
473 // scale factor for big ships getting hit by flak
474 #define FLAK_DAMAGE_SCALE                               0.05f
475
476 extern int Max_allowed_player_homers[];
477 extern int compute_num_homing_objects(object *target_objp);
478
479 // 
480 void parse_weapon_expl_tbl()
481 {
482         int     rval, idx;
483         char base_filename[256] = "";
484
485         // open localization
486         lcl_ext_open();
487
488         if ((rval = setjmp(parse_abort)) != 0) {
489                 Error(LOCATION, "Unable to parse weapon_expl.tbl!  Code = %i.\n", rval);
490         }
491         else {
492                 read_file_text(NOX("weapon_expl.tbl"));
493                 reset_parse();          
494         }
495
496         Num_weapon_expl = 0;
497         required_string("#Start");
498         while (required_string_either("#End","$Name:")) {
499                 Assert( Num_weapon_expl < MAX_Weapon_expl_info);
500
501                 // base filename
502                 required_string("$Name:");
503                 stuff_string(base_filename, F_NAME, NULL);
504
505                 // # of lod levels - make sure old fireball.tbl is compatible
506                 Weapon_expl_info[Num_weapon_expl].lod_count = 1;
507                 if(optional_string("$LOD:")){
508                         stuff_int(&Weapon_expl_info[Num_weapon_expl].lod_count);
509                 }
510
511                 // stuff default filename
512                 strcpy(Weapon_expl_info[Num_weapon_expl].lod[0].filename, base_filename);
513
514                 // stuff LOD level filenames
515                 for(idx=1; idx<Weapon_expl_info[Num_weapon_expl].lod_count; idx++){
516                         if(idx >= MAX_weapon_expl_lod){
517                                 break;
518                         }
519
520                         sprintf(Weapon_expl_info[Num_weapon_expl].lod[idx].filename, "%s_%d", base_filename, idx);
521                 }
522
523                 Num_weapon_expl++;
524         }
525         required_string("#End");
526
527         // close localization
528         lcl_ext_close();
529 }
530
531 int get_weapon_expl_info_index(char *filename)
532 {
533         for (int i=0; i<MAX_Weapon_expl_info; i++) {
534                 if ( stricmp(Weapon_expl_info[i].lod[0].filename, filename) == 0) {
535                         return i;
536                 }
537         }
538
539         return -1;
540 }
541 // ----------------------------------------------------------------------
542 // missile_obj_list_init()
543 //
544 // Clear out the Missile_obj_list
545 //
546 void missile_obj_list_init()
547 {
548         int i;
549
550         list_init(&Missile_obj_list);
551         for ( i = 0; i < MAX_MISSILE_OBJS; i++ ) {
552                 Missile_objs[i].flags = 0;
553         }
554 }
555
556 // ---------------------------------------------------
557 // missile_obj_list_add()
558 //
559 // Function to add a node from the Missile_obj_list.  Only
560 // called from weapon_create()
561 int missile_obj_list_add(int objnum)
562 {
563         int i;
564
565         for ( i = 0; i < MAX_MISSILE_OBJS; i++ ) {
566                 if ( !(Missile_objs[i].flags & MISSILE_OBJ_USED) )
567                         break;
568         }
569         if ( i == MAX_MISSILE_OBJS ) {
570                 Error(LOCATION, "Fatal Error: Ran out of missile object nodes\n");
571                 return -1;
572         }
573         
574         Missile_objs[i].flags = 0;
575         Missile_objs[i].objnum = objnum;
576         list_append(&Missile_obj_list, &Missile_objs[i]);
577         Missile_objs[i].flags |= MISSILE_OBJ_USED;
578
579         return i;
580 }
581
582 // ---------------------------------------------------
583 // missle_obj_list_remove()
584 //
585 // Function to remove a node from the Missile_obj_list.  Only
586 // called from weapon_delete()
587 void missle_obj_list_remove(int index)
588 {
589         Assert(index >= 0 && index < MAX_MISSILE_OBJS);
590         list_remove(&Missile_obj_list, &Missile_objs[index]);   
591         Missile_objs[index].flags = 0;
592 }
593
594 // ---------------------------------------------------
595 // missile_obj_list_rebuild()
596 //
597 // Called by the save/restore code to rebuild Missile_obj_list
598 //
599 void missile_obj_list_rebuild()
600 {
601         object *objp;
602
603         missile_obj_list_init();
604
605         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
606                 if ( objp->type == OBJ_WEAPON && Weapon_info[Weapons[objp->instance].weapon_info_index].subtype == WP_MISSILE ) {
607                         Weapons[objp->instance].missile_list_index = missile_obj_list_add(OBJ_INDEX(objp));
608                 }
609         }
610 }
611
612 // If this is a player countermeasure, let the player know he evaded a missile
613 void weapon_maybe_alert_cmeasure_success(object *objp)
614 {
615         if ( objp->type == OBJ_CMEASURE ) {
616                 cmeasure *cmp;
617                 cmp = &Cmeasures[objp->instance];
618                 if ( cmp->source_objnum == OBJ_INDEX(Player_obj) ) {
619                         hud_start_text_flash(XSTR("Evaded", 1430), 800);
620                         snd_play(&Snds[SND_MISSILE_EVADED_POPUP]);
621                 } else if ( Objects[cmp->source_objnum].flags & OF_PLAYER_SHIP ) {
622                         send_countermeasure_success_packet( cmp->source_objnum );
623                 }
624         }
625 }
626
627 // ---------------------------------------------------
628 // missile_obj_return_address()
629 //
630 // Called externally to generate an address from an index into
631 // the Missile_objs[] array
632 //
633 missile_obj *missile_obj_return_address(int index)
634 {
635         Assert(index >= 0 && index < MAX_MISSILE_OBJS);
636         return &Missile_objs[index];
637 }
638
639 //      Return the index of Weapon_info[].name that is *name.
640 int weapon_info_lookup(char *name)
641 {
642         int     i;
643
644         for (i=0; i<Num_weapon_types; i++)
645                 if (!stricmp(name, Weapon_info[i].name))
646                         return i;
647
648         return -1;
649 }
650
651 #define DEFAULT_WEAPON_SPAWN_COUNT      10
652
653 //      Parse the weapon flags.
654 void parse_wi_flags(weapon_info *weaponp)
655 {
656         char    weapon_strings[MAX_WEAPON_FLAGS][NAME_LENGTH];
657         int     num_strings;
658
659         required_string("$Flags:");
660
661         num_strings = stuff_string_list(weapon_strings, MAX_WEAPON_FLAGS);
662         
663         for (int i=0; i<num_strings; i++) {
664                 if (!stricmp(NOX("Electronics"), weapon_strings[i]))
665                         weaponp->wi_flags |= WIF_ELECTRONICS;           
666                 else if (!strnicmp(NOX("Spawn"), weapon_strings[i], 5)) {
667                         if (weaponp->spawn_type == -1) {
668                                 int     skip_length, name_length;
669                                 char    *temp_string;
670
671                                 temp_string = weapon_strings[i];
672
673                                 weaponp->wi_flags |= WIF_SPAWN;
674                                 weaponp->spawn_type = (short)Num_spawn_types;
675                                 skip_length = strlen(NOX("Spawn")) + strspn(&temp_string[strlen(NOX("Spawn"))], NOX(" \t"));
676                                 char *num_start = strchr(&temp_string[skip_length], ',');
677                                 if (num_start == NULL) {
678                                         weaponp->spawn_count = DEFAULT_WEAPON_SPAWN_COUNT;
679                                         name_length = 999;
680                                 } else {
681                                         weaponp->spawn_count = (short)atoi(num_start+1);
682                                         name_length = num_start - temp_string - skip_length;
683                                 }
684
685                                 strncpy(Spawn_names[Num_spawn_types++], &(weapon_strings[i][skip_length]), name_length);
686                                 Assert(Num_spawn_types < MAX_SPAWN_WEAPONS);
687                         } else
688                                 Warning(LOCATION, "Illegal to have two spawn types for one weapon.\n"
689                                                                                 "Ignoring weapon %s", weapon_strings[i]);
690                 } else if (!stricmp(NOX("Remote Detonate"), weapon_strings[i]))
691                         weaponp->wi_flags |= WIF_REMOTE;
692                 else if (!stricmp(NOX("Puncture"), weapon_strings[i]))
693                         weaponp->wi_flags |= WIF_PUNCTURE;              
694                 else if (!stricmp(NOX("Big Ship"), weapon_strings[i]))
695                         weaponp->wi_flags |= WIF_BIG_ONLY;
696                 else if (!stricmp(NOX("Huge"), weapon_strings[i]))
697                         weaponp->wi_flags |= WIF_HUGE;
698                 else if (!stricmp(NOX("Bomber+"), weapon_strings[i]))
699                         weaponp->wi_flags |= WIF_BOMBER_PLUS;
700                 else if (!stricmp(NOX("child"), weapon_strings[i]))
701                         weaponp->wi_flags |= WIF_CHILD;
702                 else if (!stricmp(NOX("Bomb"), weapon_strings[i]))
703                         weaponp->wi_flags |= WIF_BOMB;
704                 else if (!stricmp(NOX("No Dumbfire"), weapon_strings[i]))
705                         weaponp->wi_flags |= WIF_NO_DUMBFIRE;
706                 else if (!stricmp(NOX("In tech database"), weapon_strings[i]))
707                         weaponp->wi_flags |= WIF_IN_TECH_DATABASE;
708                 else if (!stricmp(NOX("Player allowed"), weapon_strings[i]))
709                         weaponp->wi_flags |= WIF_PLAYER_ALLOWED;                
710                 else if (!stricmp(NOX("Particle Spew"), weapon_strings[i]))
711                         weaponp->wi_flags |= WIF_PARTICLE_SPEW;
712                 else if (!stricmp(NOX("EMP"), weapon_strings[i]))
713                         weaponp->wi_flags |= WIF_EMP;
714                 else if (!stricmp(NOX("Esuck"), weapon_strings[i]))
715                         weaponp->wi_flags |= WIF_ENERGY_SUCK;
716                 else if (!stricmp(NOX("Flak"), weapon_strings[i]))
717                         weaponp->wi_flags |= WIF_FLAK;
718                 else if (!stricmp(NOX("Corkscrew"), weapon_strings[i]))
719                         weaponp->wi_flags |= WIF_CORKSCREW;
720                 else if (!stricmp(NOX("Shudder"), weapon_strings[i]))
721                         weaponp->wi_flags |= WIF_SHUDDER;               
722                 else if (!stricmp(NOX("lockarm"), weapon_strings[i]))
723                         weaponp->wi_flags |= WIF_LOCKARM;               
724                 else if (!stricmp(NOX("beam"), weapon_strings[i]))
725                         weaponp->wi_flags |= WIF_BEAM;
726                 else if (!stricmp(NOX("stream"), weapon_strings[i]))
727                         weaponp->wi_flags |= WIF_STREAM;
728                 else if (!stricmp(NOX("supercap"), weapon_strings[i]))
729                         weaponp->wi_flags |= WIF_SUPERCAP;
730                 else
731                         Warning(LOCATION, "Bogus string in weapon flags: %s\n", weapon_strings[i]);
732         }       
733
734         // SWARM, CORKSCREW and FLAK should be mutually exclusive
735         if(weaponp->wi_flags & WIF_FLAK){
736                 Assert(!(weaponp->wi_flags & WIF_CORKSCREW) && !(weaponp->wi_flags & WIF_SWARM));
737         }
738         if(weaponp->wi_flags & WIF_CORKSCREW){
739                 Assert(!(weaponp->wi_flags & WIF_FLAK) && !(weaponp->wi_flags & WIF_SWARM));
740         }
741         if(weaponp->wi_flags & WIF_SWARM){
742                 Assert(!(weaponp->wi_flags & WIF_CORKSCREW) && !(weaponp->wi_flags & WIF_FLAK));
743         }
744
745         // make sure flak guns are only placed on turrets
746         if(weaponp->wi_flags & WIF_FLAK){
747                 Assert(weaponp->wi_flags & WIF_BIG_ONLY);
748         }
749 }
750
751 // function to parse the information for a specific weapon type.        
752 // return 0 if successful, otherwise return -1
753 #define WEAPONS_MULTITEXT_LENGTH 2048
754
755 int parse_weapon()
756 {
757         char buf[WEAPONS_MULTITEXT_LENGTH];
758         weapon_info *wip;
759         char fname[255] = "";
760         int idx;
761
762         wip = &Weapon_info[Num_weapon_types];
763
764         wip->wi_flags = 0;
765
766         required_string("$Name:");
767         stuff_string(wip->name, F_NAME, NULL);
768         diag_printf ("Weapon name -- %s\n", wip->name);
769
770         // AL 28-3-98: If this is a demo build, we only want to parse weapons that are preceded with
771         //             the '@' symbol
772         #ifdef DEMO // not needed FS2_DEMO (separate table file)
773                 if ( wip->name[0] != '@' ) {
774                         // advance to next weapon, and return -1
775
776                         if ( skip_to_start_of_strings("$Name:", "#End") != 1 ) {
777                                 Int3();
778                         }
779                         return -1;
780                 }
781         #endif
782
783         if ( wip->name[0] == '@' ) {
784                 char old_name[NAME_LENGTH];
785                 strcpy(old_name, wip->name);
786                 strcpy(wip->name, old_name+1);
787         }
788
789         wip->title[0] = 0;
790         if (optional_string("+Title:")) {
791                 stuff_string(wip->title, F_NAME, NULL, WEAPON_TITLE_LEN);
792         }
793
794         wip->desc = NULL;
795         if (optional_string("+Description:")) {
796                 stuff_string(buf, F_MULTITEXT, NULL);
797                 wip->desc = strdup(buf);
798         }
799
800         wip->tech_title[0] = 0;
801         if (optional_string("+Tech Title:")) {
802                 stuff_string(wip->tech_title, F_NAME, NULL, NAME_LENGTH);
803         }
804
805         wip->tech_anim_filename[0] = 0;
806         if (optional_string("+Tech Anim:")) {
807                 stuff_string(wip->tech_anim_filename, F_NAME, NULL, NAME_LENGTH);
808         }
809
810         wip->tech_desc = NULL;
811         if (optional_string("+Tech Description:")) {
812                 stuff_string(buf, F_MULTITEXT, NULL, WEAPONS_MULTITEXT_LENGTH);
813                 wip->tech_desc = strdup(buf);
814         }
815
816         //      Read the model file.  It can be a POF file or none.
817         //      If there is no model file (Model file: = "none") then we use our special
818         //      laser renderer which requires inner, middle and outer information.
819         required_string("$Model file:");
820         stuff_string(wip->pofbitmap_name, F_NAME, NULL);
821         diag_printf ("Model pof file -- %s\n", wip->pofbitmap_name );
822         if ( stricmp(wip->pofbitmap_name, NOX("none")) ) {
823                 wip->model_num = -1;                            
824                 wip->render_type = WRT_POF;
825                 wip->laser_bitmap = -1;
826         } else {
827                 //      No POF or AVI file specified, render as special laser type.
828                 ubyte r,g,b;
829
830                 wip->render_type = WRT_LASER;
831                 wip->model_num = -1;
832
833                 // laser bitmap itself
834                 required_string("@Laser Bitmap:");
835                 stuff_string(wip->pofbitmap_name, F_NAME, NULL);
836                 wip->laser_bitmap = -1;
837                 if(!Fred_running){
838                         wip->laser_bitmap = bm_load( wip->pofbitmap_name );
839                 }
840
841                 // optional laser glow
842                 wip->laser_glow_bitmap = -1;
843                 if(optional_string("@Laser Glow:")){
844                         stuff_string(fname, F_NAME, NULL);              
845                         if(!Fred_running){
846                                 wip->laser_glow_bitmap = bm_load( fname );
847
848                                 // might as well lock it down as an aabitmap now
849                                 if(wip->laser_glow_bitmap >= 0){
850                                         bm_lock(wip->laser_glow_bitmap, 8, BMP_AABITMAP);
851                                         bm_unlock(wip->laser_glow_bitmap);
852                                 }
853                         }
854                 }
855                 
856                 required_string("@Laser Color:");
857                 stuff_byte(&r); stuff_byte(&g); stuff_byte(&b);
858                 gr_init_color( &wip->laser_color_1, r, g, b );
859
860                 // optional string for cycling laser colors
861                 gr_init_color(&wip->laser_color_2, 0, 0, 0);
862                 if(optional_string("@Laser Color2:")){
863                         stuff_byte(&r); stuff_byte(&g); stuff_byte(&b);
864                         gr_init_color( &wip->laser_color_2, r, g, b );
865                 }
866
867                 required_string("@Laser Length:");
868                 stuff_float(&wip->laser_length);
869                 
870                 required_string("@Laser Head Radius:");
871                 stuff_float(&wip->laser_head_radius);
872
873                 required_string("@Laser Tail Radius:");
874                 stuff_float(&wip->laser_tail_radius );
875         }
876
877         required_string("$Mass:");
878         stuff_float( &(wip->mass) );
879         diag_printf ("Weapon mass -- %7.3f\n", wip->mass);
880
881         required_string("$Velocity:");
882         stuff_float( &(wip->max_speed) );
883         diag_printf ("Weapon mass -- %7.3f\n", wip->max_speed);
884
885         required_string("$Fire Wait:");
886         stuff_float( &(wip->fire_wait) );
887         diag_printf ("Weapon fire wait -- %7.3f\n", wip->fire_wait);
888
889         required_string("$Damage:");
890         stuff_float(&wip->damage);
891
892         // secondary weapons require these values
893         if (First_secondary_index != -1) {
894                 required_string("$Blast Force:");
895                 stuff_float( &(wip->blast_force) );
896                 diag_printf ("Weapon blast force -- %7.3f\n", wip->blast_force);
897
898                 required_string("$Inner Radius:");
899                 stuff_float( &(wip->inner_radius) );
900                 if ( wip->inner_radius != 0 ) {
901                         wip->wi_flags |= WIF_AREA_EFFECT;
902                 }
903                 diag_printf ("Weapon inner blast radius -- %7.3f\n", wip->inner_radius);
904
905                 required_string("$Outer Radius:");
906                 stuff_float( &(wip->outer_radius) );
907                 if ( wip->outer_radius != 0 ) {
908                         wip->wi_flags |= WIF_AREA_EFFECT;
909                 }
910                 diag_printf ("Weapon outer blast radius -- %7.3f\n", wip->outer_radius);
911
912                 required_string("$Shockwave Speed:");
913                 stuff_float( &(wip->shockwave_speed) );
914                 if ( wip->shockwave_speed != 0 ) {
915                         wip->wi_flags |= WIF_SHOCKWAVE;
916                 }
917                 diag_printf ("Shockwave speed -- %7.3f\n", wip->shockwave_speed);
918         } 
919         // for primary weapons they're optional
920         else {
921                 if(optional_string("$Blast Force:")){
922                         stuff_float( &(wip->blast_force) );
923                         diag_printf ("Weapon blast force -- %7.3f\n", wip->blast_force);
924                 }
925
926                 if(optional_string("$Inner Radius:")){
927                         stuff_float( &(wip->inner_radius) );
928                         if ( wip->inner_radius != 0 ) {
929                                 wip->wi_flags |= WIF_AREA_EFFECT;
930                         }
931                         diag_printf ("Weapon inner blast radius -- %7.3f\n", wip->inner_radius);
932                 }
933
934                 if(optional_string("$Outer Radius:")){
935                         stuff_float( &(wip->outer_radius) );
936                         if ( wip->outer_radius != 0 ) {
937                                 wip->wi_flags |= WIF_AREA_EFFECT;
938                         }
939                         diag_printf ("Weapon outer blast radius -- %7.3f\n", wip->outer_radius);
940                 }
941
942                 if(optional_string("$Shockwave Speed:")){
943                         stuff_float( &(wip->shockwave_speed) );
944                         if ( wip->shockwave_speed != 0 ) {
945                                 wip->wi_flags |= WIF_SHOCKWAVE;
946                         }
947                         diag_printf ("Shockwave speed -- %7.3f\n", wip->shockwave_speed);
948                 }
949         }
950
951         required_string("$Armor Factor:");
952         stuff_float(&wip->armor_factor);
953
954         required_string("$Shield Factor:");
955         stuff_float(&wip->shield_factor);
956
957         required_string("$Subsystem Factor:");
958         stuff_float(&wip->subsystem_factor);
959
960         required_string("$Lifetime:");
961         stuff_float(&wip->lifetime);
962
963         required_string("$Energy Consumed:");
964         stuff_float(&wip->energy_consumed);
965
966         required_string("$Cargo Size:");
967         stuff_float(&wip->cargo_size);
968
969         int is_homing=0;
970         required_string("$Homing:");
971         stuff_boolean(&is_homing);
972
973         if (is_homing == 1) {
974                 char    temp_type[128];
975
976                 // the following five items only need to be recorded if the weapon is a homing weapon
977                 required_string("+Type:");
978                 stuff_string(temp_type, F_NAME, NULL);
979
980                 if (!stricmp(temp_type, NOX("HEAT"))) {
981                         float   view_cone_angle;
982
983                         wip->wi_flags |= WIF_HOMING_HEAT | WIF_TURNS;
984
985                         required_string("+Turn Time:");                 
986                         stuff_float(&wip->turn_time);
987
988                         required_string("+View Cone:");
989                         stuff_float(&view_cone_angle);
990
991                         wip->fov = (float)cos((float)(ANG_TO_RAD(view_cone_angle/2.0f)));
992
993                 } else if (!stricmp(temp_type, NOX("ASPECT"))) {
994                         wip->wi_flags |= WIF_HOMING_ASPECT | WIF_TURNS;
995
996                         required_string("+Turn Time:");                 
997                         stuff_float(&wip->turn_time);
998
999                         required_string("+Min Lock Time:");                     // minimum time (in seconds) to achieve lock
1000                         stuff_float(&wip->min_lock_time);
1001
1002                         required_string("+Lock Pixels/Sec:");           // pixels/sec moved while locking
1003                         stuff_int(&wip->lock_pixels_per_sec);
1004
1005                         required_string("+Catch-up Pixels/Sec:");       // pixels/sec moved while catching-up for a lock
1006                         stuff_int(&wip->catchup_pixels_per_sec);
1007
1008                         required_string("+Catch-up Penalty:");          // number of extra pixels to move while locking as a penalty for catching up for a lock
1009                         stuff_int(&wip->catchup_pixel_penalty);
1010                 } else
1011                         Error(LOCATION, "Illegal homing type = %s.\nMust be HEAT or ASPECT.\n", temp_type);
1012
1013         }
1014
1015         // swarm missiles
1016         int s_count;
1017         wip->swarm_count = -1;
1018         if(optional_string("$Swarm:")){
1019                 wip->swarm_count = SWARM_DEFAULT_NUM_MISSILES_FIRED;
1020                 stuff_int(&s_count);
1021                 wip->swarm_count = (short)s_count;
1022
1023                 // flag as being a swarm weapon
1024                 wip->wi_flags |= WIF_SWARM;
1025         }
1026
1027         required_string("$LaunchSnd:");
1028         stuff_int(&wip->launch_snd);
1029
1030         required_string("$ImpactSnd:");
1031         stuff_int(&wip->impact_snd);
1032
1033         if (First_secondary_index != -1) {
1034                 required_string("$FlyBySnd:");
1035                 stuff_int(&wip->flyby_snd);
1036         }
1037
1038         //      Secondary weapons are required to have a rearm rate.
1039         if (First_secondary_index != -1) {
1040                 required_string( "$Rearm Rate:");
1041                 stuff_float( &wip->rearm_rate );
1042                 if (wip->rearm_rate > 0.1f)
1043                         wip->rearm_rate = 1.0f/wip->rearm_rate;
1044                 else
1045                         wip->rearm_rate = 1.0f;
1046         }
1047
1048         wip->weapon_range = 999999999.9f;
1049         if (optional_string("+Weapon Range:")) {
1050                 stuff_float(&wip->weapon_range);
1051         }
1052
1053         wip->spawn_type = -1;
1054         parse_wi_flags(wip);
1055
1056         char trail_name[MAX_FILENAME_LEN] = "";
1057         trail_info *ti = &wip->tr_info;
1058         memset(ti, 0, sizeof(trail_info));
1059         if(optional_string("$Trail:")){ 
1060                 wip->wi_flags |= WIF_TRAIL;             // missile leaves a trail
1061
1062                 required_string("+Start Width:");
1063                 stuff_float(&ti->w_start);
1064
1065                 required_string("+End Width:");
1066                 stuff_float(&ti->w_end);
1067
1068                 required_string("+Start Alpha:");
1069                 stuff_float(&ti->a_start);
1070
1071                 required_string("+End Alpha:");
1072                 stuff_float(&ti->a_end);                
1073
1074                 required_string("+Max Life:");
1075                 stuff_float(&ti->max_life);
1076
1077                 ti->stamp = fl2i(1000.0f*ti->max_life)/(NUM_TRAIL_SECTIONS+1);
1078
1079                 required_string("+Bitmap:");
1080                 stuff_string(trail_name, F_NAME, NULL);
1081                 ti->bitmap = bm_load(trail_name);
1082                 // wip->delta_time = fl2i(1000.0f*wip->max_life)/(NUM_TRAIL_SECTIONS+1);                // time between sections.  max_life / num_sections basically.
1083         }
1084
1085         // read in filename for icon that is used in weapons selection
1086         wip->icon_filename[0] = 0;
1087         if ( optional_string("$Icon:") ) {
1088                 stuff_string(wip->icon_filename, F_NAME, NULL);
1089         }
1090
1091         // read in filename for animation that is used in weapons selection
1092         wip->anim_filename[0] = 0;
1093         if ( optional_string("$Anim:") ) {
1094                 stuff_string(wip->anim_filename, F_NAME, NULL);
1095         }
1096
1097         wip->impact_weapon_expl_index = -1;
1098         if ( optional_string("$Impact Explosion:") ) {
1099                 char impact_ani_file[FILESPEC_LENGTH];
1100                 stuff_string(impact_ani_file, F_NAME, NULL);
1101                 if ( stricmp(impact_ani_file,NOX("none")))      {
1102                         wip->impact_weapon_expl_index = get_weapon_expl_info_index(impact_ani_file);
1103                         //int num_frames, fps;
1104                         //wip->impact_explosion_ani = bm_load_animation( impact_ani_file, &num_frames, &fps, 1 );
1105
1106                         required_string("$Impact Explosion Radius:");
1107                         stuff_float(&wip->impact_explosion_radius);
1108                 }
1109         }
1110
1111         // muzzle flash
1112         char mflash_string[255] = "";
1113         wip->muzzle_flash = -1;
1114         if( optional_string("$Muzzleflash:") ){
1115                 stuff_string(mflash_string, F_NAME, NULL);
1116
1117                 // look it up
1118                 wip->muzzle_flash = mflash_lookup(mflash_string);
1119
1120                 if(wip->muzzle_flash >= 0){                     
1121                         wip->wi_flags |= WIF_MFLASH;
1122                 }
1123         }
1124
1125         // EMP optional stuff (if WIF_EMP is not set, none of this matters, anyway)
1126         if( optional_string("$EMP Intensity:") ){
1127                 stuff_float(&wip->emp_intensity);
1128         } else {
1129                 wip->emp_intensity = EMP_DEFAULT_INTENSITY;
1130         }
1131         if( optional_string("$EMP Time:") ){
1132                 stuff_float(&wip->emp_time);
1133         } else {
1134                 wip->emp_intensity = EMP_DEFAULT_TIME;
1135         }
1136
1137         // Energy suck optional stuff (if WIF_ENERGY_SUCK is not set, none of this matters anyway)
1138         if( optional_string("$Leech Weapon:") ){
1139                 stuff_float(&wip->weapon_reduce);
1140         } else {
1141                 wip->weapon_reduce = ESUCK_DEFAULT_WEAPON_REDUCE;
1142         }
1143         if( optional_string("$Leech Afterburner:") ){
1144                 stuff_float(&wip->afterburner_reduce);
1145         } else {
1146                 wip->afterburner_reduce = ESUCK_DEFAULT_AFTERBURNER_REDUCE;
1147         }
1148
1149         // beam weapon optional stuff
1150         wip->b_info.beam_type = -1;
1151         wip->b_info.beam_life = -1.0f;
1152         wip->b_info.beam_warmup = -1;
1153         wip->b_info.beam_warmdown = -1;
1154         wip->b_info.beam_muzzle_radius = 0.0f;
1155         wip->b_info.beam_particle_count = -1;
1156         wip->b_info.beam_particle_radius = 0.0f;
1157         wip->b_info.beam_particle_angle = 0.0f;
1158         wip->b_info.beam_particle_ani = -1;     
1159         wip->b_info.beam_loop_sound = -1;
1160         wip->b_info.beam_warmup_sound = -1;
1161         wip->b_info.beam_warmdown_sound = -1;
1162         wip->b_info.beam_num_sections = 0;
1163         wip->b_info.beam_glow_bitmap = -1;
1164         wip->b_info.beam_shots = 0;
1165         wip->b_info.beam_shrink_factor = 0.0f;
1166         wip->b_info.beam_shrink_pct = 0.0f;
1167         if( optional_string("$BeamInfo:")){
1168                 // beam type
1169                 required_string("+Type:");
1170                 stuff_int(&wip->b_info.beam_type);
1171
1172                 // how long it lasts
1173                 required_string("+Life:");
1174                 stuff_float(&wip->b_info.beam_life);
1175
1176                 // warmup time
1177                 required_string("+Warmup:");
1178                 stuff_int(&wip->b_info.beam_warmup);
1179
1180                 // warmdowm time
1181                 required_string("+Warmdown:");
1182                 stuff_int(&wip->b_info.beam_warmdown);
1183
1184                 // muzzle glow radius
1185                 required_string("+Radius:");
1186                 stuff_float(&wip->b_info.beam_muzzle_radius);
1187
1188                 // particle spew count
1189                 required_string("+PCount:");
1190                 stuff_int(&wip->b_info.beam_particle_count);
1191
1192                 // particle radius
1193                 required_string("+PRadius:");
1194                 stuff_float(&wip->b_info.beam_particle_radius);
1195
1196                 // angle off turret normal
1197                 required_string("+PAngle:");
1198                 stuff_float(&wip->b_info.beam_particle_angle);
1199
1200                 // particle bitmap/ani          
1201                 required_string("+PAni:");
1202                 stuff_string(fname, F_NAME, NULL);
1203                 if(!Fred_running){
1204                         int num_frames, fps;
1205                         wip->b_info.beam_particle_ani = bm_load_animation(fname, &num_frames, &fps, 1);
1206                 }
1207
1208                 // magic miss #
1209                 required_string("+Miss Factor:");               
1210                 for(idx=0; idx<NUM_SKILL_LEVELS; idx++){
1211                         wip->b_info.beam_miss_factor[idx] = 0.00001f;
1212                         stuff_float(&wip->b_info.beam_miss_factor[idx]);
1213                 }
1214
1215                 // beam fire sound
1216                 required_string("+BeamSound:");
1217                 stuff_int(&wip->b_info.beam_loop_sound);
1218
1219                 // warmup sound
1220                 required_string("+WarmupSound:");
1221                 stuff_int(&wip->b_info.beam_warmup_sound);
1222
1223                 // warmdown sound
1224                 required_string("+WarmdownSound:");
1225                 stuff_int(&wip->b_info.beam_warmdown_sound);
1226
1227                 // glow bitmap
1228                 required_string("+Muzzleglow:");
1229                 stuff_string(fname, F_NAME, NULL);
1230                 if(!Fred_running){
1231                         wip->b_info.beam_glow_bitmap = bm_load(fname);
1232                 }
1233
1234                 // # of shots (only used for type D beams)
1235                 required_string("+Shots:");
1236                 stuff_int(&wip->b_info.beam_shots);
1237
1238                 // shrinkage
1239                 required_string("+ShrinkFactor:");
1240                 stuff_float(&wip->b_info.beam_shrink_factor);
1241                 required_string("+ShrinkPct:");
1242                 stuff_float(&wip->b_info.beam_shrink_pct);
1243
1244                 // beam sections
1245                 while( optional_string("$Section:") ){
1246                         beam_weapon_section_info i;
1247                         char tex_name[255] = "";
1248                         
1249                         // section width
1250                         required_string("+Width:");
1251                         stuff_float(&i.width);
1252
1253                         // texture
1254                         required_string("+Texture:");
1255                         stuff_string(tex_name, F_NAME, NULL);
1256                         i.texture = -1;
1257                         if(!Fred_running){
1258                                 i.texture = bm_load(tex_name);
1259                                 if(i.texture >= 0){
1260                                         bm_lock(i.texture, 16, BMP_TEX_OTHER);
1261                                         bm_unlock(i.texture);
1262                                 }
1263                         }
1264
1265                         // rgba inner
1266                         required_string("+RGBA Inner:");
1267                         stuff_byte(&i.rgba_inner[0]);
1268                         stuff_byte(&i.rgba_inner[1]);
1269                         stuff_byte(&i.rgba_inner[2]);
1270                         stuff_byte(&i.rgba_inner[3]);
1271
1272                         // rgba outer
1273                         required_string("+RGBA Outer:");
1274                         stuff_byte(&i.rgba_outer[0]);
1275                         stuff_byte(&i.rgba_outer[1]);
1276                         stuff_byte(&i.rgba_outer[2]);
1277                         stuff_byte(&i.rgba_outer[3]);
1278
1279                         // flicker
1280                         required_string("+Flicker:");
1281                         stuff_float(&i.flicker);                        
1282
1283                         // zadd
1284                         required_string("+Zadd:");
1285                         stuff_float(&i.z_add);
1286
1287                         // maybe copy it
1288                         if(wip->b_info.beam_num_sections < MAX_BEAM_SECTIONS - 1){
1289                                 wip->b_info.sections[wip->b_info.beam_num_sections++] = i;
1290                         }
1291                 }               
1292         }
1293
1294         // tag weapon optional stuff
1295         wip->tag_level = -1;
1296         wip->tag_time = -1.0f;
1297         if( optional_string("$Tag:")){
1298                 stuff_int(&wip->tag_level);
1299                 stuff_float(&wip->tag_time);            
1300                 wip->wi_flags |= WIF_TAG;
1301         }       
1302
1303         return 0;
1304 }
1305
1306 // function to parse the information for a specific ship type.  
1307 void parse_cmeasure()
1308 {
1309         cmeasure_info *cmeasurep;
1310
1311         cmeasurep = &Cmeasure_info[Num_cmeasure_types];
1312
1313         required_string("$Name:");
1314         stuff_string(cmeasurep->cmeasure_name, F_NAME, NULL);
1315
1316 /*$Name:                                        Type One
1317 $Velocity:                              20.0                            ;; speed relative to ship, rear-fired until POF info added, MK, 5/22/97
1318 $Fire Wait:                             0.5
1319 $Lifetime Min:                  1.0                             ;; Minimum lifetime
1320 $Lifetime Max:                  2.0                             ;; Maximum lifetime.  Actual lifetime is rand(min..max).
1321 $LaunchSnd:                             counter_1.wav,  .8, 10, 300     ;; countermeasure 1 fired (sound is 3d)
1322 */
1323
1324         required_string("$Velocity:");
1325         stuff_float( &(cmeasurep->max_speed) );
1326
1327         required_string("$Fire Wait:");
1328         stuff_float( &(cmeasurep->fire_wait) );
1329
1330         required_string("$Lifetime Min:");
1331         stuff_float(&cmeasurep->life_min);
1332
1333         required_string("$Lifetime Max:");
1334         stuff_float(&cmeasurep->life_max);
1335
1336         required_string("$LaunchSnd:");
1337         stuff_int(&cmeasurep->launch_sound);
1338
1339         required_string("$Model:");
1340         stuff_string(cmeasurep->pof_name, F_NAME, NULL);
1341         cmeasurep->model_num = -1;              
1342 }
1343
1344
1345 //      For all weapons that spawn weapons, given an index at weaponp->spawn_type,
1346 // convert the strings in Spawn_names to indices in the Weapon_types array.
1347 void translate_spawn_types()
1348 {
1349         int     i,j;
1350
1351         for (i=0; i<Num_weapon_types; i++)
1352                 if (Weapon_info[i].spawn_type != -1) {
1353                         int     spawn_type = Weapon_info[i].spawn_type;
1354
1355                         for (j=0; j<Num_weapon_types; j++)
1356                                 if (!stricmp(Spawn_names[spawn_type], Weapon_info[j].name)) {
1357                                         Weapon_info[i].spawn_type = (short)j;
1358                                         if (i == j){
1359                                                 Warning(LOCATION, "Weapon %s spawns itself.  Infinite recursion?\n", Weapon_info[i].name);
1360                                         }
1361                                 }
1362                 }
1363 }
1364
1365 void parse_weaponstbl()
1366 {
1367         // open localization
1368         lcl_ext_open();
1369
1370         read_file_text("weapons.tbl");
1371         reset_parse();
1372
1373         Num_weapon_types = 0;
1374         First_secondary_index = -1;
1375         Num_spawn_types = 0;
1376         
1377         required_string("#Primary Weapons");
1378         while (required_string_either("#End", "$Name:")) {
1379                 Assert( Num_weapon_types < MAX_WEAPON_TYPES );
1380                 // AL 28-3-98: If parse_weapon() fails, try next .tbl weapon
1381                 if ( parse_weapon() ) {
1382                         continue;
1383                 }
1384                 Weapon_info[Num_weapon_types].subtype = WP_LASER;
1385                 Num_weapon_types++;
1386         }
1387         required_string("#End");
1388
1389         required_string("#Secondary Weapons");
1390         First_secondary_index = Num_weapon_types;
1391         while (required_string_either("#End", "$Name:")) {
1392                 Assert( Num_weapon_types < MAX_WEAPON_TYPES );
1393                 // AL 28-3-98: If parse_weapon() fails, try next .tbl weapon
1394                 if ( parse_weapon() ) {
1395                         continue;
1396                 }
1397                 Weapon_info[Num_weapon_types].subtype = WP_MISSILE;
1398                 Num_weapon_types++;
1399         }
1400         required_string("#End");
1401
1402         required_string("#Beam Weapons");
1403         while (required_string_either("#End", "$Name:")) {
1404                 Assert( Num_weapon_types < MAX_WEAPON_TYPES );
1405                 // AL 28-3-98: If parse_weapon() fails, try next .tbl weapon
1406                 if ( parse_weapon() ) {
1407                         continue;
1408                 }
1409                 Weapon_info[Num_weapon_types].subtype = WP_BEAM;
1410                 Num_weapon_types++;
1411         }
1412         required_string("#End");
1413
1414         required_string("#Countermeasures");
1415         while (required_string_either("#End", "$Name:")) {
1416                 Assert( Num_cmeasure_types < MAX_CMEASURE_TYPES );
1417                 parse_cmeasure();
1418                 Num_cmeasure_types++;
1419         }
1420
1421         required_string("#End");
1422
1423         // Read in a list of weapon_info indicies that are an ordering of the player weapon precedence.
1424         // This list is used to select an alternate weapon when a particular weapon is not available
1425         // during weapon selection.
1426         required_string("$Player Weapon Precedence:");
1427         Num_player_weapon_precedence = stuff_int_list(Player_weapon_precedence, MAX_WEAPON_TYPES, WEAPON_LIST_TYPE);
1428
1429         translate_spawn_types();
1430
1431         // close localization
1432         lcl_ext_close();
1433 }
1434
1435 void create_weapon_names()
1436 {
1437         int     i;
1438
1439         for (i=0; i<Num_weapon_types; i++)
1440                 Weapon_names[i] = Weapon_info[i].name;
1441 }
1442
1443 // This will get called once at game startup
1444 void weapon_init()
1445 {
1446         int rval;
1447
1448         if ( !Weapons_inited ) {
1449 #ifndef FS2_DEMO // TODO - this seems to work? unless it's breaking that multiplayer mission...
1450                 // parse weapon_exp.tbl
1451                 parse_weapon_expl_tbl();
1452 #else
1453                 STUB_FUNCTION;
1454 #endif
1455                 // parse weapons.tbl
1456                 if ((rval = setjmp(parse_abort)) != 0) {
1457                         Error(LOCATION, "Error parsing 'weapons.tbl'\r\nError code = %i.\r\n", rval);
1458                 } else {                        
1459                         parse_weaponstbl();
1460                         create_weapon_names();
1461                         Weapons_inited = 1;
1462                 }
1463         }
1464
1465         weapon_level_init();
1466 }
1467
1468
1469 // This will get called at the start of each level.
1470 void weapon_level_init()
1471 {
1472         int i;
1473
1474         // Reset everything between levels
1475         Num_weapons = 0;
1476         for (i=0; i<MAX_WEAPONS; i++)   {
1477                 Weapons[i].objnum = -1;
1478                 Weapons[i].weapon_info_index = -1;
1479         }
1480
1481         trail_level_init();             // reset all missile trails
1482
1483         swarm_level_init();
1484         missile_obj_list_init();
1485         
1486         cscrew_level_init();
1487
1488         // emp effect
1489         emp_level_init();
1490
1491         Weapon_flyby_sound_timer = timestamp(0);
1492         Weapon_impact_timer = 1;        // inited each level, used to reduce impact sounds
1493 }
1494
1495 MONITOR( NumWeaponsRend );      
1496
1497 float weapon_glow_scale_f = 2.3f;
1498 float weapon_glow_scale_r = 2.3f;
1499 float weapon_glow_scale_l = 1.5f;
1500 float weapon_glow_alpha_d3d = 0.85f;
1501 float weapon_glow_alpha_glide = 0.99f;
1502 void weapon_render(object *obj)
1503 {
1504         int num;
1505         weapon_info *wip;
1506         weapon *wp;
1507         color c;
1508
1509         MONITOR_INC(NumWeaponsRend, 1);
1510
1511         Assert(obj->type == OBJ_WEAPON);
1512
1513         num = obj->instance;
1514         wp = &Weapons[num];
1515         wip = &Weapon_info[Weapons[num].weapon_info_index];
1516
1517         switch (wip->render_type) {
1518                 case WRT_LASER: {
1519                         // turn off fogging for good measure
1520                         gr_fog_set(GR_FOGMODE_NONE, 0, 0, 0);
1521
1522                         if (wip->laser_bitmap >= 0) {                                   
1523                                 gr_set_color_fast(&wip->laser_color_1);
1524                                 gr_set_bitmap(wip->laser_bitmap, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, 0.99999f);
1525
1526                                 vector headp;
1527                                 vm_vec_scale_add(&headp, &obj->pos, &obj->orient.fvec, wip->laser_length);
1528                                 wp->weapon_flags &= ~WF_CONSIDER_FOR_FLYBY_SOUND;
1529                                 if ( g3_draw_laser(&headp, wip->laser_head_radius, &obj->pos, wip->laser_tail_radius) ) {
1530                                         wp->weapon_flags |= WF_CONSIDER_FOR_FLYBY_SOUND;
1531                                 }
1532                         }                       
1533
1534                         // maybe draw laser glow bitmap
1535                         if(wip->laser_glow_bitmap >= 0){
1536                                 // get the laser color
1537                                 weapon_get_laser_color(&c, obj);
1538
1539                                 vector headp2;                  
1540                                 vm_vec_scale_add(&headp2, &obj->pos, &obj->orient.fvec, wip->laser_length * weapon_glow_scale_l);
1541                                 gr_set_bitmap(wip->laser_glow_bitmap, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, (gr_screen.mode == GR_DIRECT3D || gr_screen.mode == GR_OPENGL) ? weapon_glow_alpha_d3d : weapon_glow_alpha_glide);
1542                                 g3_draw_laser_rgb(&headp2, wip->laser_head_radius * weapon_glow_scale_f, &obj->pos, wip->laser_tail_radius * weapon_glow_scale_r, c.red, c.green, c.blue);
1543                         }                                               
1544                         break;
1545                 }
1546
1547                 case WRT_POF:   {
1548                                 uint render_flags = MR_NORMAL|MR_IS_MISSILE|MR_NO_LIGHTING;
1549
1550                                 model_clear_instance(wip->model_num);
1551
1552                                 if ( (wip->wi_flags & WIF_THRUSTER) && (wp->thruster_bitmap > -1) ) {
1553                                         float   ft;
1554
1555                                         //      Add noise to thruster geometry.
1556                                         //ft = obj->phys_info.forward_thrust;                                   
1557                                         ft = 1.0f;              // Always use 1.0f for missiles                                 
1558                                         ft *= (1.0f + frand()/5.0f - 1.0f/10.0f);
1559                                         if (ft > 1.0f)
1560                                                 ft = 1.0f;
1561
1562                                         model_set_thrust( wip->model_num, ft, wp->thruster_bitmap, wp->thruster_glow_bitmap, wp->thruster_glow_noise);
1563                                         render_flags |= MR_SHOW_THRUSTERS;
1564                                 }
1565
1566                                 model_render(wip->model_num, &obj->orient, &obj->pos, render_flags);
1567
1568                                 // render a missile plume as well
1569                                 /*
1570                                 static int plume = -1;  
1571                                 extern float Interp_thrust_twist;
1572                                 extern float Interp_thrust_twist2;
1573                                 if(plume == -1){
1574                                         plume = model_load("plume01.pof", -1, NULL);
1575                                 }
1576                                 if(plume != -1){
1577                                         Interp_thrust_twist = tw;
1578                                         Interp_thrust_twist2 = tw2;
1579                                         model_set_alpha(plume_alpha);
1580                                         model_render(plume, &obj->orient, &obj->pos, MR_ALL_XPARENT);
1581                                         Interp_thrust_twist = -1.0f;
1582                                         Interp_thrust_twist2 = -1.0f;
1583                                 }
1584                                 */
1585                         }
1586                         break;
1587
1588                 default:
1589                         Warning(LOCATION, "Unknown weapon rendering type = %i\n", wip->render_type);
1590         }
1591 }
1592
1593 void weapon_delete(object *obj)
1594 {
1595         weapon *wp;
1596         int num;
1597
1598         num = obj->instance;
1599
1600         Assert( Weapons[num].objnum == OBJ_INDEX(obj));
1601         wp = &Weapons[num];
1602
1603         Assert(wp->weapon_info_index >= 0);
1604         wp->weapon_info_index = -1;
1605         if (wp->swarm_index >= 0) {
1606                 swarm_delete(wp->swarm_index);
1607                 wp->swarm_index = -1;
1608         }
1609
1610         if(wp->cscrew_index >= 0) {
1611                 cscrew_delete(wp->cscrew_index);
1612                 wp->cscrew_index = -1;
1613         }
1614
1615         if (wp->missile_list_index >= 0) {
1616                 missle_obj_list_remove(wp->missile_list_index);
1617                 wp->missile_list_index = -1;
1618         }
1619
1620         if (wp->flak_index >= 0){
1621                 flak_delete(wp->flak_index);
1622                 wp->flak_index = -1;
1623         }
1624
1625         if (wp->trail_num > -1) {
1626                 trail_object_died(wp->trail_num);
1627         }
1628
1629         wp->objnum = -1;
1630         Num_weapons--;
1631         Assert(Num_weapons >= 0);
1632 }
1633
1634 // Check if missile is newly locked onto the Player, maybe play a launch warning
1635 void weapon_maybe_play_warning(weapon *wp)
1636 {
1637         if ( wp->homing_object == Player_obj ) {
1638                 if ( !(wp->weapon_flags & WF_LOCK_WARNING_PLAYED) ) {
1639                         wp->weapon_flags |= WF_LOCK_WARNING_PLAYED;
1640                         if ( Weapon_info[wp->weapon_info_index].wi_flags & WIF_HOMING_HEAT ) {
1641                                 snd_play(&Snds[SND_HEATLOCK_WARN]);
1642                         } else {
1643                                 Assert(Weapon_info[wp->weapon_info_index].wi_flags & WIF_HOMING_ASPECT);
1644                                 snd_play(&Snds[SND_ASPECTLOCK_WARN]);
1645                         }
1646                 }
1647         }
1648 }
1649
1650 #define CMEASURE_DETONATE_DISTANCE              40.0f
1651
1652 //      Detonate all missiles near this countermeasure.
1653 void detonate_nearby_missiles(cmeasure *cmp)
1654 {
1655         missile_obj     *mop;
1656         vector          cmeasure_pos;
1657
1658         cmeasure_pos = Objects[cmp->objnum].pos;
1659
1660         mop = GET_FIRST(&Missile_obj_list);
1661         while(mop != END_OF_LIST(&Missile_obj_list)) {
1662                 object  *objp;
1663                 weapon  *wp;
1664
1665                 objp = &Objects[mop->objnum];
1666                 wp = &Weapons[objp->instance];
1667
1668                 if (wp->team != cmp->team) {
1669                         if ( Missiontime - wp->creation_time > F1_0/2) {
1670                                 if (vm_vec_dist_quick(&cmeasure_pos, &objp->pos) < CMEASURE_DETONATE_DISTANCE) {
1671                                         if (wp->lifeleft > 0.2f) { 
1672                                                 //nprintf(("Jim", "Frame %i: Cmeasure #%i detonating weapon #%i\n", Framecount, cmp-Cmeasures, wp-Weapons));
1673                                                 wp->lifeleft = 0.2f;
1674                                                 // nprintf(("AI", "Frame %i: Flagging weapon %i for detonation.\n", Framecount, wp-Weapons));
1675                                         }
1676                                 }
1677                         }
1678                 }
1679
1680                 mop = mop->next;
1681         }
1682 }
1683
1684 //      Find an object for weapon #num (object *weapon_objp) to home on due to heat.
1685 void find_homing_object(object *weapon_objp, int num)
1686 {
1687         object          *objp, *old_homing_objp;
1688         weapon_info     *wip;
1689         weapon          *wp;
1690         float                   best_dist;
1691
1692         wp = &Weapons[num];
1693
1694         wip = &Weapon_info[Weapons[num].weapon_info_index];
1695
1696         best_dist = 99999.9f;
1697
1698         // save the old homing object so that multiplayer servers can give the right information
1699         // to clients if the object changes
1700         old_homing_objp = wp->homing_object;
1701
1702         wp->homing_object = &obj_used_list;
1703
1704         //      Scan all objects, find a weapon to home on.
1705         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
1706                 if ((objp->type == OBJ_SHIP) || (objp->type == OBJ_CMEASURE)) {
1707                         if (objp->type == OBJ_CMEASURE)
1708                                 if (Cmeasures[objp->instance].flags & CMF_DUD_HEAT)
1709                                         continue;
1710
1711                         int homing_object_team = obj_team(objp);
1712                         if ( (homing_object_team != wp->team) || (homing_object_team == TEAM_TRAITOR) ) {
1713                                 float           dist;
1714                                 float           dot;
1715                                 vector  vec_to_object;
1716
1717                                 // AL 2-17-98: If ship is immune to sensors, can't home on it (Sandeep says so)!
1718                                 if ( objp->type == OBJ_SHIP ) {
1719                                         if ( Ships[objp->instance].flags & SF_HIDDEN_FROM_SENSORS ) {
1720                                                 continue;
1721                                         }
1722
1723                                         //      MK, 9/4/99.
1724                                         //      If this is a player object, make sure there aren't already too many homers.
1725                                         //      Only in single player.  In multiplayer, we don't want to restrict it in dogfight on team vs. team.
1726                                         //      For co-op, it's probably also OK.
1727                                         if (!( Game_mode & GM_MULTIPLAYER )) {
1728                                                 int     num_homers = compute_num_homing_objects(objp);
1729                                                 if (Max_allowed_player_homers[Game_skill_level] < num_homers)
1730                                                         continue;
1731                                         }
1732                                 }
1733
1734                                 dist = vm_vec_normalized_dir(&vec_to_object, &objp->pos, &weapon_objp->pos);
1735
1736                                 if (objp->type == OBJ_CMEASURE)
1737                                         dist *= 0.5f;
1738
1739                                 dot = vm_vec_dot(&vec_to_object, &weapon_objp->orient.fvec);
1740
1741                                 if (dot > wip->fov) {
1742                                         if (dist < best_dist) {
1743                                                 best_dist = dist;
1744                                                 wp->homing_object = objp;
1745                                                 wp->target_sig = objp->signature;
1746
1747                                                 weapon_maybe_alert_cmeasure_success(objp);
1748                                         }
1749                                 }
1750                         }
1751                 }
1752         }
1753
1754 //      if (wp->homing_object->type == OBJ_CMEASURE)
1755 //              nprintf(("AI", "Frame %i: Weapon #%i homing on cmeasure #%i\n", Framecount, num, objp-Objects));
1756
1757         if (wp->homing_object == Player_obj)
1758                 weapon_maybe_play_warning(wp);
1759
1760         // if the old homing object is different that the new one, send a packet to clients
1761         if ( MULTIPLAYER_MASTER && (old_homing_objp != wp->homing_object) ) {
1762                 send_homing_weapon_info( num );
1763         }
1764 }
1765
1766 //      Scan all countermeasures.  Maybe make weapon_objp home on it.
1767 void find_homing_object_cmeasures_1(object *weapon_objp)
1768 {
1769         object  *objp;
1770         weapon  *wp;
1771         weapon_info     *wip;
1772         float           best_dot, dist, dot;
1773
1774         wp = &Weapons[weapon_objp->instance];
1775         wip = &Weapon_info[wp->weapon_info_index];
1776
1777         best_dot = wip->fov;                    //      Note, setting to this avoids comparison below.
1778
1779         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
1780                 if (objp->type == OBJ_CMEASURE) {
1781                         vector  vec_to_object;
1782                         dist = vm_vec_normalized_dir(&vec_to_object, &objp->pos, &weapon_objp->pos);
1783
1784                         if (dist < MAX_CMEASURE_TRACK_DIST) {
1785                                 float   chance;
1786                                 if (wip->wi_flags & WIF_HOMING_ASPECT) {
1787                                         chance = 1.0f/2.0f;     //      aspect seeker this likely to chase a countermeasure
1788                                 } else {
1789                                         chance = 1.0f/1.5f;     //      heat seeker this likely to chase a countermeasure
1790                                 }
1791                                 if ((objp->signature != wp->cmeasure_ignore_objnum) && (objp->signature != wp->cmeasure_chase_objnum)) {
1792                                         if (frand() < chance) {
1793                                                 wp->cmeasure_ignore_objnum = objp->signature;   //      Don't process this countermeasure again.
1794                                                 //nprintf(("Jim", "Frame %i: Weapon #%i ignoring cmeasure #%i\n", Framecount, OBJ_INDEX(weapon_objp), objp->signature));
1795                                         } else  {
1796                                                 wp->cmeasure_chase_objnum = objp->signature;    //      Don't process this countermeasure again.
1797                                                 //nprintf(("Jim", "Frame %i: Weapon #%i CHASING cmeasure #%i\n", Framecount, OBJ_INDEX(weapon_objp), objp->signature));
1798                                         }
1799                                 }
1800                                 
1801                                 if (objp->signature != wp->cmeasure_ignore_objnum) {
1802
1803                                         dot = vm_vec_dot(&vec_to_object, &weapon_objp->orient.fvec);
1804
1805                                         if (dot > best_dot) {
1806                                                 //nprintf(("Jim", "Frame %i: Weapon #%i homing on cmeasure #%i\n", Framecount, weapon_objp-Objects, objp->signature));
1807                                                 best_dot = dot;
1808                                                 wp->homing_object = objp;
1809                                                 weapon_maybe_alert_cmeasure_success(objp);
1810                                         }
1811                                 }
1812                         }
1813                 }
1814         }
1815 }
1816
1817
1818 //      Someone launched countermeasures.
1819 //      For all heat-seeking homing objects, see if should favor tracking a countermeasure instead.
1820 void find_homing_object_cmeasures()
1821 {
1822         object  *weapon_objp;
1823
1824         // nprintf(("AI", "Scanning for countermeasures in frame %i\n", Framecount));
1825
1826         if (Cmeasures_homing_check == 0)
1827                 return;
1828
1829         if (Cmeasures_homing_check <= 0)
1830                 Cmeasures_homing_check = 1;
1831
1832         Cmeasures_homing_check--;
1833
1834         for (weapon_objp = GET_FIRST(&obj_used_list); weapon_objp != END_OF_LIST(&obj_used_list); weapon_objp = GET_NEXT(weapon_objp) ) {
1835                 if (weapon_objp->type == OBJ_WEAPON) {
1836                         weapon_info     *wip = &Weapon_info[Weapons[weapon_objp->instance].weapon_info_index];
1837
1838                         if (wip->wi_flags & WIF_HOMING)
1839                                 find_homing_object_cmeasures_1(weapon_objp);
1840                 }
1841         }
1842
1843 }
1844
1845 //      Find object with signature "sig" and make weapon home on it.
1846 void find_homing_object_by_sig(object *weapon_objp, int sig)
1847 {
1848         ship_obj                *sop;
1849         weapon          *wp;
1850         object          *old_homing_objp;
1851
1852         wp = &Weapons[weapon_objp->instance];
1853
1854         // save the old object so that multiplayer masters know whether to send a homing update packet
1855         old_homing_objp = wp->homing_object;
1856
1857         sop = GET_FIRST(&Ship_obj_list);
1858         while(sop != END_OF_LIST(&Ship_obj_list)) {
1859                 object  *objp;
1860
1861                 objp = &Objects[sop->objnum];
1862                 if (objp->signature == sig) {
1863                         wp->homing_object = objp;
1864                         wp->target_sig = objp->signature;
1865                         break;
1866                 }
1867
1868                 sop = sop->next;
1869         }
1870
1871         // if the old homing object is different that the new one, send a packet to clients
1872         if ( MULTIPLAYER_MASTER && (old_homing_objp != wp->homing_object) ) {
1873                 send_homing_weapon_info( weapon_objp->instance );
1874         }
1875
1876 }
1877
1878 //      Make weapon num home.  It's also object *obj.
1879 void weapon_home(object *obj, int num, float frame_time)
1880 {
1881         weapon          *wp;
1882         weapon_info     *wip;
1883         object          *hobjp;
1884
1885         Assert(obj->type == OBJ_WEAPON);
1886         Assert(obj->instance == num);
1887         wp = &Weapons[num];
1888         wip = &Weapon_info[wp->weapon_info_index];
1889         hobjp = Weapons[num].homing_object;
1890
1891         //      If not 1/2 second gone by, don't home yet.
1892         if ((hobjp == &obj_used_list) || ( f2fl(Missiontime - wp->creation_time) < 0.25f )) {
1893                 //      If this is a heat seeking homing missile and 1/2 second has elapsed since firing
1894                 //      and we don't have a target (else we wouldn't be inside the IF), find a new target.
1895                 if (wip->wi_flags & WIF_HOMING_HEAT)
1896                         if ( f2fl(Missiontime - wp->creation_time) > 0.5f )
1897                                 find_homing_object(obj, num);
1898
1899                 if (obj->phys_info.speed > wip->max_speed) {
1900                         obj->phys_info.speed -= frame_time * 4;
1901                         vm_vec_copy_scale( &obj->phys_info.desired_vel, &obj->orient.fvec, obj->phys_info.speed);
1902                 } else if ((obj->phys_info.speed < wip->max_speed/4) && (wip->wi_flags & WIF_HOMING_HEAT)) {
1903                         obj->phys_info.speed = wip->max_speed/4;
1904                         vm_vec_copy_scale( &obj->phys_info.desired_vel, &obj->orient.fvec, obj->phys_info.speed);
1905                 }
1906
1907 /*      Removed code that makes bombs drop for a bit.  They looked odd and it was confusing.  People wondered where their weapons went.
1908                 //      Make bombs drop down for first second of life.
1909                 if (wip->wi_flags & WIF_BOMB) {
1910                         if (wip->lifetime - wp->lifeleft < 0.5f) {
1911                                 float   time_scale = wip->lifetime - wp->lifeleft;
1912                                 vm_vec_scale_add2(&obj->phys_info.desired_vel, &obj->orient.uvec, (time_scale - 0.5f) * max(10.0f, obj->phys_info.speed/2.0f));
1913                         }
1914                 }
1915 */
1916                 return;
1917         }
1918
1919         // AL 4-8-98: If orgiginal target for aspect lock missile is lost, stop homing
1920         if (wip->wi_flags & WIF_HOMING_ASPECT) {
1921                 if ( wp->target_sig > 0 ) {
1922                         if ( wp->homing_object->signature != wp->target_sig ) {
1923                                 wp->homing_object = &obj_used_list;
1924                                 return;
1925                         }
1926                 }
1927         }
1928
1929         // AL 4-13-98: Stop homing on a subsystem if parent ship has changed
1930         if (wip->wi_flags & WIF_HOMING_HEAT) {
1931                 if ( wp->target_sig > 0 ) {
1932                         if ( wp->homing_object->signature != wp->target_sig ) {
1933                                 wp->homing_subsys = NULL;
1934                         }
1935                 }
1936         }
1937
1938 /*
1939         if (hobjp->type == OBJ_NONE) {
1940                 find_homing_object(obj, num);
1941                 return;
1942         }
1943 */
1944
1945         switch (hobjp->type) {
1946         case OBJ_NONE:
1947                 if (wip->wi_flags & WIF_HOMING_ASPECT)
1948                         find_homing_object_by_sig(obj, wp->target_sig);
1949                 else
1950                         find_homing_object(obj, num);
1951                 return;
1952                 break;
1953         case OBJ_SHIP:
1954                 if (hobjp->signature != wp->target_sig) {
1955                         if (wip->wi_flags & WIF_HOMING_ASPECT)
1956                                 find_homing_object_by_sig(obj, wp->target_sig);
1957                         else
1958                                 find_homing_object(obj, num);
1959                         return;
1960                 }
1961                 break;
1962         case OBJ_WEAPON:
1963                 // only allowed to home on bombs
1964                 Assert(Weapon_info[Weapons[hobjp->instance].weapon_info_index].wi_flags & WIF_BOMB);
1965                 if (wip->wi_flags & WIF_HOMING_ASPECT)
1966                         find_homing_object_by_sig(obj, wp->target_sig);
1967                 else
1968                         find_homing_object(obj, num);
1969                 break;
1970         case OBJ_CMEASURE:
1971                 break;
1972         default:
1973                 return;
1974         }
1975
1976         //      See if this weapon is the nearest homing object to the object it is homing on.
1977         //      If so, update some fields in the target object's ai_info.
1978         if (hobjp != &obj_used_list) {
1979                 float   dist;
1980
1981                 dist = vm_vec_dist_quick(&obj->pos, &hobjp->pos);
1982
1983                 if (hobjp->type == OBJ_SHIP) {
1984                         ai_info *aip;
1985
1986                         aip = &Ai_info[Ships[hobjp->instance].ai_index];
1987
1988                         if ((aip->nearest_locked_object == -1) || (dist < aip->nearest_locked_distance)) {
1989                                 aip->nearest_locked_object = obj-Objects;
1990                                 aip->nearest_locked_distance = dist;
1991                         }
1992                 }
1993         }
1994
1995         //      If the object it is homing on is still valid, home some more!
1996         if (hobjp != &obj_used_list) {
1997                 float           old_dot, vel;
1998                 vector  vec_to_goal;
1999                 vector  target_pos;     // position of what the homing missile is seeking
2000
2001                 vm_vec_zero(&target_pos);
2002
2003                 // the homing missile may be seeking a subsystem on a ship.  If so, we need to calculate the
2004                 // world coordinates of that subsystem so the homing missile can seek it out.
2005                 //      For now, March 7, 1997, MK, heat seeking homing missiles will be able to home on
2006                 //      any subsystem.  Probably makes sense for them to only home on certain kinds of subsystems.
2007                 if ( wp->homing_subsys != NULL ) {
2008                         get_subsystem_world_pos(hobjp, Weapons[num].homing_subsys, &target_pos);
2009                         wp->homing_pos = target_pos;    // store the homing position in weapon data
2010                         Assert( !vm_is_vec_nan(&wp->homing_pos) );
2011                 } else {
2012                         float   fov;
2013                         float   dist;
2014
2015                         dist = vm_vec_dist_quick(&obj->pos, &hobjp->pos);
2016                         if (hobjp->type == OBJ_CMEASURE) {
2017                                 if (dist < CMEASURE_DETONATE_DISTANCE) {
2018                                         cmeasure        *cmp;
2019
2020                                         cmp = &Cmeasures[hobjp->instance];
2021
2022                                         //      Make this missile detonate soon.  Not right away, not sure why.  Seems better.
2023                                         if (cmp->team != wp->team) {
2024                                                 detonate_nearby_missiles(cmp);
2025                                                 //nprintf(("AI", "Frame %i: Weapon %i hit cmeasure, will die!\n", Framecount, wp-Weapons));
2026                                                 return;
2027                                         }
2028                                 }
2029                         }
2030
2031                         fov = 0.8f;
2032                         if (wip->fov > 0.8f)
2033                                 fov = wip->fov;
2034
2035                         int pick_homing_point = 0;
2036                         if ( IS_VEC_NULL(&wp->homing_pos) ) {
2037                                 pick_homing_point = 1;
2038                         }
2039
2040                         //      Update homing position if it hasn't been set, you're within 500 meters, or every half second, approximately.
2041                         //      For large objects, don't lead them.
2042                         if (hobjp->radius < 40.0f) {
2043                                 target_pos = hobjp->pos;
2044                                 wp->homing_pos = target_pos;
2045                         } else if ( pick_homing_point || (dist < 500.0f) || (rand_chance(flFrametime, 2.0f)) ) {
2046
2047                                 if (hobjp->type == OBJ_SHIP) {
2048                                         if ( !pick_homing_point ) {
2049                                                 // ensure that current attack point is only updated in world coords (ie not pick a different vertex)
2050                                                 wp->pick_big_attack_point_timestamp = 0;
2051                                         }
2052
2053                                         if ( pick_homing_point ) {
2054                                                 // If *any* player is parent of homing missile, then use position where lock indicator is
2055                                                 if ( Objects[obj->parent].flags & OF_PLAYER_SHIP ) {
2056                                                         player *pp;
2057
2058                                                         // determine the player
2059                                                         pp = Player;
2060                                                         if ( Game_mode & GM_MULTIPLAYER ) {
2061                                                                 int pnum;
2062
2063                                                                 pnum = multi_find_player_by_object( &Objects[obj->parent] );
2064                                                                 if ( pnum != -1 ){
2065                                                                         pp = Net_players[pnum].player;
2066                                                                 }
2067                                                         }
2068
2069                                                         // If player has apect lock, we don't want to find a homing point on the closest
2070                                                         // octant... setting the timestamp to 0 ensures this.
2071                                                         if (wip->wi_flags & WIF_HOMING_ASPECT) {
2072                                                                 wp->pick_big_attack_point_timestamp = 0;
2073                                                         } else {
2074                                                                 wp->pick_big_attack_point_timestamp = 1;
2075                                                         }
2076
2077                                                         if ( pp && pp->locking_subsys ) {
2078                                                                 wp->big_attack_point = pp->locking_subsys->system_info->pnt;
2079                                                         } else {
2080                                                                 vm_vec_zero(&wp->big_attack_point);
2081                                                         }
2082                                                 }
2083                                         }
2084
2085                                         ai_big_pick_attack_point(hobjp, obj, &target_pos, fov);
2086
2087                                 } else {
2088                                         target_pos = hobjp->pos;
2089                                 }
2090
2091                                 wp->homing_pos = target_pos;
2092                                 Assert( !vm_is_vec_nan(&wp->homing_pos) );
2093                                 // nprintf(("AI", "Attack point = %7.3f %7.3f %7.3f\n", target_pos.x, target_pos.y, target_pos.z));
2094                         } else
2095                                 target_pos = wp->homing_pos;
2096                 }
2097
2098                 //      Couldn't find a lock.
2099                 if (IS_VEC_NULL(&target_pos))
2100                         return;
2101
2102                 //      Cause aspect seeking weapon to home at target's predicted position.
2103                 //      But don't use predicted position if dot product small or negative.
2104                 //      If do this, with a ship headed towards missile, could choose a point behind missile.``1
2105                 float   dist_to_target, time_to_target;
2106                 
2107                 dist_to_target = vm_vec_normalized_dir(&vec_to_goal, &target_pos, &obj->pos);
2108                 time_to_target = dist_to_target/wip->max_speed;
2109
2110                 vector  tvec;
2111                 tvec = obj->phys_info.vel;
2112                 vm_vec_normalize(&tvec);
2113
2114                 old_dot = vm_vec_dot(&tvec, &vec_to_goal);
2115
2116                 //      If a weapon has missed its target, detonate it.
2117                 //      This solves the problem of a weapon circling the center of a subsystem that has been blown away.
2118                 //      Problem: It does not do impact damage, just proximity damage.
2119                 if ((dist_to_target < flFrametime * obj->phys_info.speed * 4.0f + 10.0f) && (old_dot < 0.0f)) {
2120                         int kill_missile = TRUE;
2121                         if (wp->homing_object) {
2122                                 if (wp->homing_object->type == OBJ_SHIP) {
2123                                         ship *shipp = &Ships[wp->homing_object->instance];
2124                                         if (Ship_info[shipp->ship_info_index].flags & SIF_DONT_COLLIDE_INVIS) {
2125                                                 kill_missile = FALSE;
2126                                         }
2127                                 }
2128                         }
2129                         
2130                         if (kill_missile && (wp->lifeleft > 0.01f)) {
2131                                 wp->lifeleft = 0.01f;
2132                         }
2133                 }
2134
2135                 //      Only lead target if more than one second away.  Otherwise can miss target.  I think this
2136                 //      is what's causing Harbingers to miss the super destroyer. -- MK, 4/15/98
2137                 if ((wip->wi_flags & WIF_HOMING_ASPECT) && (old_dot > 0.1f) && (time_to_target > 0.1f))
2138                         vm_vec_scale_add2(&target_pos, &hobjp->phys_info.vel, min(time_to_target, 2.0f));
2139
2140                 //nprintf(("AI", "Dot = %7.3f, dist = %7.3f, time_to = %6.3f, deg/sec = %7.3f\n", old_dot, dist_to_target, time_to_target, angles/flFrametime));
2141
2142                 // nprintf(("AI", "Weapon %i, lifeleft = %7.3f, dist = %7.3f, dot = %6.3f\n", num, Weapons[num].lifeleft, vm_vec_dist_quick(&obj->pos, &Weapons[num].homing_object->pos), old_dot));
2143
2144                 //      If a HEAT seeking (rather than ASPECT seeking) homing missile, verify that target is in viewcone.
2145                 if (wip->wi_flags & WIF_HOMING_HEAT) {
2146                         if ((old_dot < wip->fov) && (dist_to_target > wip->inner_radius*1.1f)) {        //      Delay finding new target one frame to allow detonation.
2147                                 find_homing_object(obj, num);
2148                                 return;                 //      Maybe found a new homing object.  Return, process more next frame.
2149                         } else  //      Subtract out life based on how far from target this missile points.
2150                                 if (wip->fov < 0.95f) {
2151                                         wp->lifeleft -= flFrametime * (0.95f - old_dot);
2152                                         //Should only happen when time is compressed.
2153                                         //if (flFrametime * (1.0f - old_dot) > 1.0f)
2154                                         //      Int3();
2155                                 }
2156                 } else if (wip->wi_flags & WIF_HOMING_ASPECT) { //      subtract life as if max turn is 90 degrees.
2157                         if (wip->fov < 0.95f)
2158                                 wp->lifeleft -= flFrametime * (0.95f - old_dot);
2159                 } else
2160                         Assert(0);      //      Hmm, a homing missile, but not aspect or heat?
2161
2162
2163                 //      Control speed based on dot product to goal.  If close to straight ahead, move
2164                 //      at max speed, else move slower based on how far from ahead.
2165                 if (old_dot < 0.90f) {
2166                         obj->phys_info.speed = max(0.2f, old_dot* (float) fabs(old_dot));
2167                         if (obj->phys_info.speed < wip->max_speed*0.75f)
2168                                 obj->phys_info.speed = wip->max_speed*0.75f;
2169                 } else
2170                         obj->phys_info.speed = wip->max_speed;
2171
2172                 //      For first second of weapon's life, it doesn't fly at top speed.  It ramps up.
2173                 if (Missiontime - wp->creation_time < i2f(1)) {
2174                         float   t;
2175
2176                         t = f2fl(Missiontime - wp->creation_time);
2177                         obj->phys_info.speed *= t*t;
2178                 }
2179
2180                 Assert( obj->phys_info.speed > 0.0f );
2181
2182                 vm_vec_copy_scale( &obj->phys_info.desired_vel, &obj->orient.fvec, obj->phys_info.speed);
2183
2184                 // turn the missile towards the target only if non-swarm.  Homing swarm missiles choose
2185                 // a different vector to turn towards, this is done in swarm_update_direction().
2186 //              if ( !(wip->wi_flags & WIF_SWARM) ) {
2187                 if ( wp->swarm_index < 0 ) {
2188                         // nprintf(("AI", "Dot, dist = %7.3f, %7.3f, target pos = %7.3f %7.3f %7.3f\n", old_dot, vm_vec_dist_quick(&obj->pos, &target_pos), target_pos.x, target_pos.y, target_pos.z));
2189                         ai_turn_towards_vector(&target_pos, obj, frame_time, wip->turn_time, NULL, NULL, 0.0f, 0, NULL);
2190                         vel = vm_vec_mag(&obj->phys_info.desired_vel);
2191
2192                         vm_vec_copy_scale(&obj->phys_info.desired_vel, &obj->orient.fvec, vel);
2193
2194                 }
2195
2196 /*              //      If this weapon shot past its target, make it detonate.
2197                 if ((old_dot < 0.0f) && (dist_to_target < 50.0f)) {
2198                         if (wp->lifeleft > 0.01f)
2199                                 wp->lifeleft = 0.01f;
2200                 }
2201 */      }
2202 }
2203
2204 // as Mike K did with ships -- break weapon into process_pre and process_post for code to execute
2205 // before and after physics movement
2206
2207 void weapon_process_pre( object *obj, float frame_time)
2208 {
2209         // if the object is a corkscrew style weapon, process it now
2210         if((obj->type == OBJ_WEAPON) && (Weapons[obj->instance].cscrew_index >= 0)){
2211                 cscrew_process_pre(obj);
2212         }
2213
2214         // if the weapon is a flak weapon, maybe detonate it early
2215         if((obj->type == OBJ_WEAPON) && (Weapon_info[Weapons[obj->instance].weapon_info_index].wi_flags & WIF_FLAK) && (Weapons[obj->instance].flak_index >= 0)){
2216                 flak_maybe_detonate(obj);               
2217         }
2218 }
2219
2220 int     Homing_hits = 0, Homing_misses = 0;
2221
2222
2223 MONITOR( NumWeapons );  
2224
2225 // maybe play a "whizz sound" if close enough to view position
2226 void weapon_maybe_play_flyby_sound(object *weapon_objp, weapon *wp)
2227 {       
2228         // do a quick out if not a laser
2229         if ( Weapon_info[wp->weapon_info_index].subtype != WP_LASER ) {
2230                 return;
2231         }
2232
2233         // don't play flyby sounds too close together
2234         if ( !timestamp_elapsed(Weapon_flyby_sound_timer) ) {
2235                 return;
2236         }
2237
2238         if ( !(wp->weapon_flags & WF_PLAYED_FLYBY_SOUND) && (wp->weapon_flags & WF_CONSIDER_FOR_FLYBY_SOUND) ) {
2239                 float           dist, dot, radius;
2240
2241                 dist = vm_vec_dist_quick(&weapon_objp->pos, &Eye_position);
2242
2243                 if ( Viewer_obj ) {
2244                         radius = Viewer_obj->radius;
2245                 } else {
2246                         radius = 0.0f;
2247                 }
2248
2249                 if ( (dist > radius) && (dist < 55) ) {
2250                         vector  vec_to_weapon;
2251
2252                         vm_vec_sub(&vec_to_weapon, &weapon_objp->pos, &Eye_position);
2253                         vm_vec_normalize(&vec_to_weapon);
2254
2255                         // ensure laser is in front of eye
2256                         dot = vm_vec_dot(&vec_to_weapon, &Eye_matrix.fvec);
2257                         if ( dot < 0.1 ) {
2258                                 return;
2259                         }
2260
2261                         // ensure that laser is moving in similar direction to fvec
2262                         dot = vm_vec_dot(&vec_to_weapon, &weapon_objp->orient.fvec);
2263                         
2264 //                      nprintf(("Alan", "Weapon dot: %.2f\n", dot));
2265                         if ( (dot < -0.80) && (dot > -0.98) ) {
2266                                 snd_play_3d( &Snds[SND_WEAPON_FLYBY], &weapon_objp->pos, &Eye_position );
2267                                 Weapon_flyby_sound_timer = timestamp(200);
2268                                 wp->weapon_flags |= WF_PLAYED_FLYBY_SOUND;
2269                         }
2270                 }
2271         }
2272 }
2273
2274 // process a weapon after physics movement.  MWA reorders some of the code on 8/13 for multiplayer.  When
2275 // adding something to this function, decide whether or not a client in a multiplayer game needs to do
2276 // what is normally done in a single player game.  Things like plotting an object on a radar, effect
2277 // for exhaust are things that are done on all machines.  Things which calculate weapon targets, new
2278 // velocities, etc, are server only functions and should go after the if ( !MULTIPLAYER_MASTER ) statement
2279 // See Allender if you cannot decide what to do.
2280 void weapon_process_post(object * obj, float frame_time)
2281 {
2282         int                     num;    
2283         weapon_info     *wip;
2284         weapon          *wp;
2285
2286         MONITOR_INC( NumWeapons, 1 );   
2287         
2288         Assert(obj->type == OBJ_WEAPON);
2289
2290         num = obj->instance;
2291
2292 #ifndef NDEBUG
2293         int objnum = OBJ_INDEX(obj);
2294         Assert( Weapons[num].objnum == objnum );
2295 #endif
2296
2297         wp = &Weapons[num];
2298
2299         wp->lifeleft -= frame_time;
2300         wip = &Weapon_info[wp->weapon_info_index];
2301
2302         // check life left.  Multiplayer client code will go through here as well.  We must be careful in weapon_hit
2303         // when killing a missile that spawn child weapons!!!!
2304         if ( wp->lifeleft < 0.0f ) {
2305                 if ( wip->subtype & WP_MISSILE ) {
2306                         if(Game_mode & GM_MULTIPLAYER){                         
2307                                 if ( !MULTIPLAYER_CLIENT || (MULTIPLAYER_CLIENT && (wp->lifeleft < -2.0f)) || (MULTIPLAYER_CLIENT && (wip->wi_flags & WIF_CHILD))) {                                    // don't call this function multiplayer client -- host will send this packet to us
2308                                         // nprintf(("AI", "Frame %i: Weapon %i detonated, dist = %7.3f!\n", Framecount, obj-Objects));
2309                                         weapon_detonate(obj);                                   
2310                                 }
2311                         } else {
2312                                 // nprintf(("AI", "Frame %i: Weapon %i detonated, dist = %7.3f!\n", Framecount, obj-Objects));
2313                                 weapon_detonate(obj);                                                                   
2314                         }
2315                         if (wip->wi_flags & WIF_HOMING) {
2316                                 Homing_misses++;
2317                                 // nprintf(("AI", "Miss!  Hits = %i/%i\n", Homing_hits, (Homing_hits + Homing_misses)));
2318                         }
2319                 } else {
2320                         obj->flags |= OF_SHOULD_BE_DEAD;
2321 //                      demo_do_flag_dead(OBJ_INDEX(obj));
2322                 }
2323
2324                 return;
2325         }
2326
2327         // plot homing missiles on the radar
2328         if (wip->wi_flags & WIF_HOMING) {
2329                 if ( hud_gauge_active(HUD_RADAR) ) {
2330                         radar_plot_object( obj );
2331                 }
2332         }
2333
2334         // trail missiles
2335         if ((wip->wi_flags & WIF_TRAIL) && !(wip->wi_flags & WIF_CORKSCREW)) {
2336                 if ( wp->trail_num > -1 )       {
2337                         if (trail_stamp_elapsed(wp->trail_num)) {
2338
2339                                 trail_add_segment( wp->trail_num, &obj->pos );
2340                                 
2341                                 trail_set_stamp(wp->trail_num);
2342                         } else {
2343                                 trail_set_segment( wp->trail_num, &obj->pos );
2344                         }
2345
2346                 }
2347         }
2348
2349         if ( wip->wi_flags & WIF_THRUSTER )     {
2350                 ship_do_weapon_thruster_frame( wp, obj, flFrametime );  
2351         }
2352
2353         // maybe play a "whizz sound" if close enough to view position
2354         #ifndef NDEBUG
2355         if ( Weapon_flyby_sound_enabled ) {
2356                 weapon_maybe_play_flyby_sound(obj, wp);
2357         }
2358         #else
2359                 weapon_maybe_play_flyby_sound(obj, wp);
2360         #endif  
2361         
2362         //      If our target is still valid, then update some info.
2363         if (wp->target_num != -1) {
2364                 if (Objects[wp->target_num].signature == wp->target_sig) {
2365                         float           cur_dist;
2366                         vector  v0;
2367
2368                         vm_vec_avg(&v0, &obj->pos, &obj->last_pos);
2369
2370                         cur_dist = vm_vec_dist_quick(&v0, &Objects[wp->target_num].pos);
2371
2372                         if (cur_dist < wp->nearest_dist) {
2373                                 wp->nearest_dist = cur_dist;
2374                         } else if (cur_dist > wp->nearest_dist + 1.0f) {
2375                                 float           dot;
2376                                 vector  tvec;
2377                                 ai_info *parent_aip;
2378                                 float           lead_scale = 0.0f;
2379
2380                                 parent_aip = NULL;
2381                                 if (obj->parent != Player_obj-Objects) {
2382                                         parent_aip = &Ai_info[Ships[Objects[obj->parent].instance].ai_index];
2383                                         lead_scale = parent_aip->lead_scale;
2384                                 }
2385
2386                                 vm_vec_normalized_dir(&tvec, &v0, &Objects[wp->target_num].pos);
2387                                 dot = vm_vec_dot(&tvec, &Objects[wp->target_num].orient.fvec);
2388                                 // nprintf(("AI", "Miss dot = %7.3f, dist = %7.3f, lead_scale = %7.3f\n", dot, cur_dist, lead_scale));
2389                                 wp->target_num = -1;
2390
2391                                 //      Learn!  If over-shooting or under-shooting, compensate.
2392                                 //      Really need to compensate for left/right errors.  This does no good against someone circling
2393                                 //      in a plane perpendicular to the attacker's forward vector.
2394                                 if (parent_aip != NULL) {
2395                                         if (cur_dist > 100.0f)
2396                                                 parent_aip->lead_scale = 0.0f;
2397
2398                                         if (dot < -0.1f){
2399                                                 parent_aip->lead_scale += cur_dist/2000.0f;
2400                                         } else if (dot > 0.1f) {
2401                                                 parent_aip->lead_scale -= cur_dist/2000.0f;
2402                                         }
2403                                         
2404                                         if (fl_abs(parent_aip->lead_scale) > 1.0f){
2405                                                 parent_aip->lead_scale *= 0.9f;
2406                                         }
2407                                 }
2408                         }
2409                 }
2410         }
2411
2412         if(wip->wi_flags & WIF_PARTICLE_SPEW){
2413                 weapon_maybe_spew_particle(obj);
2414         }
2415
2416         // a single player or multiplayer server function -- it affects actual weapon movement.
2417         if (wip->wi_flags & WIF_HOMING) {
2418                 weapon_home(obj, num, frame_time);
2419
2420 /*              if (wip->wi_flags & WIF_BOMB) {
2421                         if (wip->lifetime - obj->lifeleft < 1.0f) {
2422                                 
2423                         }
2424                 }
2425 */              
2426                 // If this is a swarm type missile, 
2427 //              if ( wip->wi_flags & WIF_SWARM ) 
2428                 if ( wp->swarm_index >= 0 ) {
2429                         swarm_update_direction(obj, frame_time);
2430                 }
2431
2432                 if( wp->cscrew_index >= 0) {
2433                         cscrew_process_post(obj);                       
2434                 }
2435         }
2436 }
2437
2438 //      Update weapon tracking information.
2439 void weapon_set_tracking_info(int weapon_objnum, int parent_objnum, int target_objnum, int target_is_locked, ship_subsys *target_subsys)
2440 {
2441         int                     ai_index;
2442         object          *parent_objp;
2443         weapon          *wp;
2444         weapon_info     *wip;
2445         int targeting_same = 0;
2446
2447         if ( weapon_objnum < 0 ) {
2448                 return;
2449         }
2450
2451         Assert(Objects[weapon_objnum].type == OBJ_WEAPON);
2452
2453         wp = &Weapons[Objects[weapon_objnum].instance];
2454         wip = &Weapon_info[wp->weapon_info_index];
2455         parent_objp = &Objects[parent_objnum];
2456
2457         Assert(parent_objp->type == OBJ_SHIP);
2458         ai_index = Ships[parent_objp->instance].ai_index;
2459
2460         if ( ai_index >= 0 ) {
2461                 int target_team = -1;
2462                 if ( target_objnum >= 0 ) {
2463                         int obj_type = Objects[target_objnum].type;
2464                         if ( (obj_type == OBJ_SHIP) || (obj_type == OBJ_WEAPON) ) {
2465                                 target_team = obj_team(&Objects[target_objnum]);
2466                         }
2467                 }
2468         
2469                 // determining if we're targeting the same team
2470                 if(Ships[parent_objp->instance].team == target_team){
2471                         targeting_same = 1;
2472                 } else {
2473                         targeting_same = 0;
2474                 }
2475
2476                 if ((target_objnum != -1) && (!targeting_same || ((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT) && (target_team == TEAM_TRAITOR))) ) {
2477                         wp->target_num = target_objnum;
2478                         wp->target_sig = Objects[target_objnum].signature;
2479                         wp->nearest_dist = 99999.0f;
2480                         if ( (wip->wi_flags & WIF_HOMING_ASPECT) && target_is_locked) {
2481                                 wp->homing_object = &Objects[target_objnum];
2482                                 wp->homing_subsys = target_subsys;
2483                                 weapon_maybe_play_warning(wp);
2484                         } else if ( wip->wi_flags & WIF_HOMING_HEAT ) {
2485                                 //      Make a heat seeking missile try to home.  If the target is outside the view cone, it will
2486                                 //      immediately drop it and try to find one in its view cone.
2487                                 if (target_objnum != -1) {
2488                                         wp->homing_object = &Objects[target_objnum];
2489                                         weapon_maybe_play_warning(wp);
2490                                 } else
2491                                         wp->homing_object = &obj_used_list;
2492
2493                                 wp->homing_subsys = target_subsys;
2494                         }
2495                 } else {
2496                         wp->target_num = -1;
2497                         wp->target_sig = -1;
2498                 }
2499
2500                 //      If missile is locked on target, increase its lifetime by 20% since missiles can be fired at limit of range
2501                 //      as defined by velocity*lifeleft, but missiles often slow down a bit, plus can be fired at a moving away target.
2502                 //      Confusing to many players when their missiles run out of gas before getting to target.  
2503                 // DB - removed 7:14 pm 9/6/99. was totally messing up lifetimes for all weapons.
2504                 //      MK, 7:11 am, 9/7/99.  Put it back in, but with a proper check here to make sure it's an aspect seeker and
2505                 //      put a sanity check in the color changing laser code that was broken by this code.
2506                 if (target_is_locked && (wp->target_num != -1) && (wip->wi_flags & WIF_HOMING_ASPECT) ) {
2507                         wp->lifeleft *= 1.2f;
2508                 }
2509
2510                 ai_update_danger_weapon(target_objnum, weapon_objnum);          
2511         }
2512 }
2513
2514
2515 // weapon_create() will create a weapon object
2516 //
2517 // Returns:  index of weapon in the Objects[] array, -1 if the weapon object was not created
2518 int Weapons_created = 0;
2519 int weapon_create( vector * pos, matrix * orient, int weapon_id, int parent_objnum, int secondary_flag, int group_id, int is_locked )
2520 {
2521         int                     n, objnum;
2522         int num_deleted;
2523         object          *objp, *parent_objp;
2524         weapon          *wp;
2525         weapon_info     *wip;
2526
2527         Assert(weapon_id >= 0 && weapon_id < Num_weapon_types);
2528
2529         // beam weapons should never come through here!
2530         Assert(!(Weapon_info[weapon_id].wi_flags & WIF_BEAM));
2531
2532         num_deleted = 0;
2533         if (Num_weapons >= MAX_WEAPONS-5) {
2534
2535                 //No, do remove for AI ships -- MK, 3/12/98  // don't need to try and delete weapons for ai ships
2536                 //if ( !(Objects[parent_objnum].flags & OF_PLAYER_SHIP) )
2537                 //      return -1;
2538
2539                 num_deleted = collide_remove_weapons();
2540                 nprintf(("WARNING", "Deleted %d weapons because of lack of slots\n", num_deleted));
2541                 if (num_deleted == 0){
2542                         return -1;
2543                 }
2544         }
2545
2546         for (n=0; n<MAX_WEAPONS; n++ ){
2547                 if (Weapons[n].weapon_info_index < 0){
2548                         break;
2549                 }
2550         }
2551
2552         if (n == MAX_WEAPONS) {
2553                 // if we supposedly deleted weapons above, what happened here!!!!
2554                 if (num_deleted){
2555                         Int3();                         // get allender -- something funny is going on!!!
2556                 }
2557
2558                 return -1;
2559         }
2560
2561         Weapons_created++;
2562         objnum = obj_create( OBJ_WEAPON, parent_objnum, n, orient, pos, 2.0f, OF_RENDERS | OF_COLLIDES | OF_PHYSICS );
2563         Assert(objnum >= 0);
2564         Assert(First_secondary_index != -1);
2565         objp = &Objects[objnum];
2566
2567         parent_objp = NULL;
2568         if(parent_objnum >= 0){
2569                 parent_objp = &Objects[parent_objnum];
2570         }
2571
2572         // Create laser n!
2573         wp = &Weapons[n];
2574         wip = &Weapon_info[weapon_id];
2575
2576         // check if laser or dumbfire missile
2577         // set physics flag to allow optimization
2578         if ((wip->subtype == WP_LASER) || ((wip->subtype == WP_MISSILE) && !(wip->wi_flags & WIF_HOMING))) {
2579                 // set physics flag
2580                 objp->phys_info.flags |= PF_CONST_VEL;
2581         }
2582
2583         wp->weapon_info_index = weapon_id;
2584         wp->lifeleft = wip->lifetime;
2585
2586         wp->objnum = objnum;
2587         wp->homing_object = &obj_used_list;             //      Assume not homing on anything.
2588         wp->homing_subsys = NULL;
2589         wp->creation_time = Missiontime;
2590         wp->group_id = group_id;
2591
2592         // we don't necessarily need a parent
2593         if(parent_objp != NULL){
2594                 Assert(parent_objp->type == OBJ_SHIP);  //      Get Mike, a non-ship has fired a weapon!
2595                 Assert((parent_objp->instance >= 0) && (parent_objp->instance < MAX_SHIPS));
2596                 wp->team = Ships[parent_objp->instance].team;
2597                 wp->species = Ship_info[Ships[parent_objp->instance].ship_info_index].species;
2598         } else {
2599                 wp->team = 0;
2600                 wp->species = 0;
2601         }
2602         wp->turret_subsys = NULL;
2603         vm_vec_zero(&wp->homing_pos);
2604         wp->weapon_flags = 0;
2605         wp->target_sig = -1;
2606         wp->cmeasure_ignore_objnum = -1;
2607         wp->cmeasure_chase_objnum = -1;
2608
2609         // Init the thruster info
2610         wp->thruster_bitmap = -1;
2611         wp->thruster_frame = 0.0f;
2612         wp->thruster_glow_bitmap = -1;
2613         wp->thruster_glow_noise = 1.0f;
2614         wp->thruster_glow_frame = 0.0f;
2615
2616         if ( wip->wi_flags & WIF_SWARM ) {
2617                 wp->swarm_index = (short)swarm_create();
2618         } else {
2619                 wp->swarm_index = -1;
2620         }               
2621
2622         // if this is a particle spewing weapon, setup some stuff
2623         if(wip->wi_flags & WIF_PARTICLE_SPEW){
2624                 wp->particle_spew_time = -1;            
2625         }
2626
2627         // assign the network signature.  The starting sig is sent to all clients, so this call should
2628         // result in the same net signature numbers getting assigned to every player in the game
2629         if ( Game_mode & GM_MULTIPLAYER ) {
2630                 if(wip->subtype == WP_MISSILE){
2631                         Objects[objnum].net_signature = multi_assign_network_signature( MULTI_SIG_NON_PERMANENT );
2632
2633                         // for weapons that respawn, add the number of respawnable weapons to the net signature pool
2634                         // to reserve N signatures for the spawned weapons
2635                         if ( wip->wi_flags & WIF_SPAWN ){
2636                                 multi_set_network_signature( (ushort)(Objects[objnum].net_signature + wip->spawn_count), MULTI_SIG_NON_PERMANENT );
2637                         }
2638                 } else {
2639                         Objects[objnum].net_signature = multi_assign_network_signature( MULTI_SIG_NON_PERMANENT );
2640                 }
2641                 // for multiplayer clients, when creating lasers, add some more life to the lasers.  This helps
2642                 // to overcome some problems associated with lasers dying on client machine before they get message
2643                 // from server saying it hit something.
2644                 // removed 1/13/98 -- MWA if ( MULTIPLAYER_CLIENT && (wip->subtype == WP_LASER) )
2645                 //      removed 1/13/98 -- MWA  wp->lifeleft += 1.5f;
2646         }
2647
2648         //      Make remote detonate missiles look like they're getting detonated by firer simply by giving them variable lifetimes.
2649         if (!(Objects[parent_objnum].flags & OF_PLAYER_SHIP) && (wip->wi_flags & WIF_REMOTE)) {
2650                 float rand_val;
2651
2652                 if ( Game_mode & GM_NORMAL ){
2653                         rand_val = frand();
2654                 } else {
2655                         rand_val = static_randf(Objects[objnum].net_signature);
2656                 }
2657
2658                 wp->lifeleft = wp->lifeleft/2.0f + rand_val * wp->lifeleft/2.0f;
2659         }
2660
2661         objp->phys_info.mass = wip->mass;
2662         objp->phys_info.side_slip_time_const = 0.0f;
2663         objp->phys_info.rotdamp = 0.0f;
2664         vm_vec_zero(&objp->phys_info.max_vel);
2665         objp->phys_info.max_vel.z = wip->max_speed;
2666         vm_vec_zero(&objp->phys_info.max_rotvel);
2667         objp->shields[0] = wip->damage;
2668         if (wip->wi_flags & WIF_BOMB){
2669                 objp->hull_strength = 50.0f;
2670         } else {
2671                 objp->hull_strength = 0.0f;
2672         }
2673
2674         if ( wip->subtype == WP_MISSILE ){
2675                 objp->radius = model_get_radius(wip->model_num);
2676         } else if ( wip->subtype == WP_LASER ) {
2677                 objp->radius = wip->laser_head_radius;
2678         }
2679
2680         //      Set desired velocity and initial velocity.
2681         //      For lasers, velocity is always the same.
2682         //      For missiles, it is a small amount plus the firing ship's velocity.
2683         //      For missiles, the velocity trends towards some goal.
2684         //      Note: If you change how speed works here, such as adding in speed of parent ship, you'll need to change the AI code
2685         //      that predicts collision points.  See Mike Kulas or Dave Andsager.  (Or see ai_get_weapon_speed().)
2686         if (!(wip->wi_flags & WIF_HOMING)) {
2687                 vm_vec_copy_scale(&objp->phys_info.desired_vel, &objp->orient.fvec, objp->phys_info.max_vel.z );
2688                 objp->phys_info.vel = objp->phys_info.desired_vel;
2689                 objp->phys_info.speed = vm_vec_mag(&objp->phys_info.desired_vel);
2690         } else {                
2691                 //      For weapons that home, set velocity to sum of forward component of parent's velocity and 1/4 weapon's max speed.
2692                 //      Note that it is important to extract the forward component of the parent's velocity to factor out sliding, else
2693                 //      the missile will not be moving forward.
2694                 if(parent_objp != NULL){
2695                         vm_vec_copy_scale(&objp->phys_info.desired_vel, &objp->orient.fvec, vm_vec_dot(&parent_objp->phys_info.vel, &parent_objp->orient.fvec) + objp->phys_info.max_vel.z/4 );
2696                 } else {
2697                         vm_vec_copy_scale(&objp->phys_info.desired_vel, &objp->orient.fvec, objp->phys_info.max_vel.z/4 );
2698                 }
2699                 objp->phys_info.vel = objp->phys_info.desired_vel;
2700                 objp->phys_info.speed = vm_vec_mag(&objp->phys_info.vel);
2701         }
2702
2703         // create the corkscrew
2704         if ( wip->wi_flags & WIF_CORKSCREW ) {
2705                 wp->cscrew_index = (short)cscrew_create(objp);
2706         } else {
2707                 wp->cscrew_index = -1;
2708         }
2709
2710         // if this is a flak weapon shell, make it so
2711         // NOTE : this function will change some fundamental things about the weapon object
2712         if ( wip->wi_flags & WIF_FLAK ){
2713                 flak_create(wp);
2714         } else {
2715                 wp->flak_index = -1;
2716         }       
2717
2718         wp->missile_list_index = -1;
2719         // If this is a missile, then add it to the Missile_obj_list
2720         if ( wip->subtype == WP_MISSILE ) {
2721                 wp->missile_list_index = missile_obj_list_add(objnum);
2722         }
2723
2724         if (wip->wi_flags & WIF_TRAIL /*&& !(wip->wi_flags & WIF_CORKSCREW) */) {
2725                 wp->trail_num = trail_create(wip->tr_info);             
2726
2727                 if ( wp->trail_num > -1 )       {
2728                         // Add two segments.  One to stay at launch pos, one to move.
2729                         trail_add_segment( wp->trail_num, &objp->pos );
2730                         trail_add_segment( wp->trail_num, &objp->pos );
2731                 }
2732         }
2733
2734         // Ensure weapon flyby sound doesn't get played for player lasers
2735         if ( parent_objp == Player_obj ) {
2736                 wp->weapon_flags |= WF_PLAYED_FLYBY_SOUND;
2737         }
2738
2739         wp->pick_big_attack_point_timestamp = timestamp(1);
2740
2741         //      Set detail levels for POF-type weapons.
2742         if (Weapon_info[wp->weapon_info_index].model_num != -1) {
2743                 polymodel * pm;
2744                 int     i;
2745                 pm = model_get(Weapon_info[wp->weapon_info_index].model_num);
2746
2747                 for (i=0; i<pm->n_detail_levels; i++){
2748                         pm->detail_depth[i] = (objp->radius*20.0f + 20.0f) * i;
2749                 }
2750         }
2751
2752                 // if the weapon was fired locked
2753         if(is_locked){
2754                 wp->weapon_flags |= WF_LOCKED_WHEN_FIRED;
2755         }
2756
2757         Num_weapons++;
2758         return objnum;
2759 }
2760
2761 //      Spawn child weapons from object *objp.
2762 void spawn_child_weapons(object *objp)
2763 {
2764         int     i;
2765         int     child_id;
2766         int     parent_num;
2767         ushort starting_sig;
2768         weapon  *wp;
2769         weapon_info     *wip;
2770
2771         Assert(objp->type == OBJ_WEAPON);
2772         Assert((objp->instance >= 0) && (objp->instance < MAX_WEAPONS));
2773
2774         wp = &Weapons[objp->instance];
2775         Assert((wp->weapon_info_index >= 0) && (wp->weapon_info_index < MAX_WEAPON_TYPES));
2776         wip = &Weapon_info[wp->weapon_info_index];
2777
2778         child_id = wip->spawn_type;
2779
2780         parent_num = objp->parent;
2781
2782         if ((Objects[parent_num].type != objp->parent_type) || (Objects[parent_num].signature != objp->parent_sig)) {
2783                 mprintf(("Warning: Parent of spawn weapon does not exist.  Not spawning.\n"));
2784                 return;
2785         }
2786
2787         starting_sig = 0;
2788         if ( Game_mode & GM_MULTIPLAYER ) {             
2789                 // get the next network signature and save it.  Set the next usable network signature to be
2790                 // the passed in objects signature + 1.  We "reserved" N of these slots when we created objp
2791                 // for it's spawned children.
2792                 starting_sig = multi_get_next_network_signature( MULTI_SIG_NON_PERMANENT );
2793                 multi_set_network_signature( objp->net_signature, MULTI_SIG_NON_PERMANENT );
2794         }
2795
2796         for (i=0; i<wip->spawn_count; i++) {
2797                 int             weapon_objnum;
2798                 vector  tvec, pos;
2799                 matrix  orient;
2800
2801                 // for multiplayer, use the static randvec functions based on the network signatures to provide
2802                 // the randomness so that it is the same on all machines.
2803                 if ( Game_mode & GM_MULTIPLAYER ){
2804                         static_randvec(objp->net_signature + i, &tvec);
2805                 } else {
2806                         vm_vec_rand_vec_quick(&tvec);
2807                 }
2808                 vm_vec_scale_add(&pos, &objp->pos, &tvec, objp->radius);
2809
2810                 vm_vector_2_matrix(&orient, &tvec, NULL, NULL);
2811                 weapon_objnum = weapon_create(&pos, &orient, child_id, parent_num, 1, -1, wp->weapon_flags & WF_LOCKED_WHEN_FIRED);
2812
2813                 //      Assign a little randomness to lifeleft so they don't all disappear at the same time.
2814                 if (weapon_objnum != -1) {
2815                         float rand_val;
2816
2817                         if ( Game_mode & GM_NORMAL ){
2818                                 rand_val = frand();
2819                         } else {
2820                                 rand_val = static_randf(objp->net_signature + i);
2821                         }
2822
2823                         Weapons[Objects[weapon_objnum].instance].lifeleft *= rand_val*0.4f + 0.8f;
2824                 }
2825
2826         }
2827
2828         // in multiplayer, reset the next network signature to the one that was saved.
2829         if ( Game_mode & GM_MULTIPLAYER ){
2830                 multi_set_network_signature( starting_sig, MULTI_SIG_NON_PERMANENT );
2831         }
2832 }
2833
2834 // -----------------------------------------------------------------------
2835 // weapon_hit_do_sound()
2836 //
2837 // Play a sound effect when a weapon hits a ship
2838 //
2839 // To elimate the "stereo" effect of two lasers hitting at nearly
2840 // the same time, and to reduce the number of sound channels used,
2841 // only play one impact sound if IMPACT_SOUND_DELTA has elapsed
2842 //
2843 // Note: Uses Weapon_impact_timer global for timer variable
2844 //
2845 void weapon_hit_do_sound(object *hit_obj, weapon_info *wip, vector *hitpos)
2846 {
2847         int     is_hull_hit;
2848         float shield_str;
2849
2850         // If non-missiles (namely lasers) expire without hitting a ship, don't play impact sound
2851         if      ( wip->subtype != WP_MISSILE ) {                
2852                 if ( !hit_obj ) {
2853                         // flak weapons make sounds             
2854                         if(wip->wi_flags & WIF_FLAK){
2855                                 snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );                           
2856                         }
2857                         return;
2858                 }
2859
2860                 switch(hit_obj->type) {
2861                 case OBJ_SHIP:
2862                         // do nothing
2863                         break;
2864
2865                 case OBJ_ASTEROID:
2866                         if ( timestamp_elapsed(Weapon_impact_timer) ) {
2867                                 snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
2868                                 Weapon_impact_timer = timestamp(IMPACT_SOUND_DELTA);
2869                         }
2870                         return;
2871                         break;
2872
2873                 default:
2874                         return;
2875                 }
2876         }
2877
2878         if ( hit_obj == NULL ) {
2879                 snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
2880                 return;
2881         }
2882
2883         if ( timestamp_elapsed(Weapon_impact_timer) ) {
2884
2885                 is_hull_hit = 1;
2886                 if ( hit_obj->type == OBJ_SHIP ) {
2887                         shield_str = ship_quadrant_shield_strength(hit_obj, hitpos);
2888                 } else {
2889                         shield_str = 0.0f;
2890                 }
2891
2892                 // play a shield hit if shields are above 10% max in this quadrant
2893                 if ( shield_str > 0.1f ) {
2894                         is_hull_hit = 0;
2895                 }
2896
2897                 if ( !is_hull_hit ) {
2898                         // Play a shield impact sound effect
2899                         if ( hit_obj == Player_obj ) {
2900                                 snd_play_3d( &Snds[SND_SHIELD_HIT_YOU], hitpos, &Eye_position );
2901                                 // AL 12-15-97: Add missile impact sound even when shield is hit
2902                                 if ( wip->subtype == WP_MISSILE ) {
2903                                         snd_play_3d( &Snds[SND_PLAYER_HIT_MISSILE], hitpos, &Eye_position);
2904                                 }
2905                         } else {
2906                                 snd_play_3d( &Snds[SND_SHIELD_HIT], hitpos, &Eye_position );
2907                         }
2908                 } else {
2909                         // Play a hull impact sound effect
2910                         switch ( wip->subtype ) {
2911                                 case WP_LASER:
2912                                         if ( hit_obj == Player_obj )
2913                                                 snd_play_3d( &Snds[SND_PLAYER_HIT_LASER], hitpos, &Eye_position );
2914                                         else {
2915                                                 if ( wip->impact_snd != -1 ) {
2916                                                         snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
2917                                                 }
2918                                         }
2919                                         break;
2920                                 case WP_MISSILE:
2921                                         if ( hit_obj == Player_obj ) 
2922                                                 snd_play_3d( &Snds[SND_PLAYER_HIT_MISSILE], hitpos, &Eye_position);
2923                                         else {
2924                                                 if ( wip->impact_snd != -1 ) {
2925                                                         snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
2926                                                 }
2927                                         }
2928                                         break;
2929                                 default:        
2930                                         nprintf(("Warning","WARNING ==> Cannot determine sound to play for weapon impact\n"));
2931                                         break;
2932                         } // end switch
2933                 }
2934
2935                 Weapon_impact_timer = timestamp(IMPACT_SOUND_DELTA);
2936         }
2937 }
2938
2939 // distrupt any subsystems that fall into damage sphere of this Electronics missile
2940 //
2941 // input:       ship_obj                =>              pointer to ship that holds subsystem
2942 //                              blast_pos       =>              world pos of weapon blast
2943 //                              wi_index                =>              weapon info index of weapon causing blast
2944 void weapon_do_electronics_affect(object *ship_objp, vector *blast_pos, int wi_index)
2945 {
2946         weapon_info                     *wip;
2947         ship                                    *shipp;
2948         ship_subsys                     *ss;
2949         model_subsystem *psub;
2950         vector                          subsys_world_pos;
2951         float                                   dist;
2952
2953         shipp = &Ships[ship_objp->instance];
2954         wip = &Weapon_info[wi_index];
2955
2956         for ( ss = GET_FIRST(&shipp->subsys_list); ss != END_OF_LIST(&shipp->subsys_list); ss = GET_NEXT(ss) ) {
2957                 psub = ss->system_info;
2958
2959                 // convert subsys point to world coords
2960                 vm_vec_unrotate(&subsys_world_pos, &psub->pnt, &ship_objp->orient);
2961                 vm_vec_add2(&subsys_world_pos, &ship_objp->pos);
2962
2963                 // see if subsys point is within damage sphere
2964                 dist = vm_vec_dist_quick(blast_pos, &subsys_world_pos); 
2965                 if ( dist < wip->outer_radius ) {
2966                         ship_subsys_set_disrupted(ss, fl2i(6000.0f + frand()*4000.0f));
2967                 }
2968         }
2969 }
2970
2971 //      ----------------------------------------------------------------------
2972 //      weapon_area_calc_damage()
2973 //
2974 // Calculate teh damage for an object based on the location of an area-effect
2975 // explosion.
2976 //
2977 // input:               objp                    =>              object pointer ship receiving blast effect
2978 //                                      pos                     =>              world pos of blast center
2979 //                                      inner_rad       =>              smallest radius at which full damage is done
2980 //                                      outer_rad       =>              radius at which no damage is done
2981 //                                      max_blast       =>              maximum blast possible from explosion
2982 //                                      max_damage      =>              maximum damage possible from explosion
2983 //                                      blast                   =>              OUTPUT PARAMETER: receives blast value from explosion
2984 //                                      damage          =>              OUTPUT PARAMETER: receives damage value from explosion
2985 //                                      limit                   =>              a limit on the area, needed for shockwave damage
2986 //
2987 //      returns:                no damage occurred      =>              -1
2988 //                                      damage occured                  =>              0
2989 //
2990 int weapon_area_calc_damage(object *objp, vector *pos, float inner_rad, float outer_rad, float max_blast, float max_damage, float *blast, float *damage, float limit)
2991 {
2992         float                   dist, max_dist, min_dist;
2993
2994         // only blast ships and asteroids
2995         if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID)) {
2996                 return -1;
2997         }
2998
2999         max_dist = objp->radius + outer_rad;
3000         dist = vm_vec_dist_quick(&objp->pos, pos);      
3001         if ( (dist > max_dist) || (dist > (limit+objp->radius)) ) {
3002                 return -1;      // spheres don't intersect at all
3003         }
3004
3005         if ( dist < (inner_rad+objp->radius) ) {
3006                 // damage is maximum within inner radius
3007                 *damage = max_damage;
3008                 *blast = max_blast;
3009         } else {
3010                 float dist_to_outer_rad_squared, total_dist_squared;
3011                 min_dist = dist - objp->radius;
3012                 Assert(min_dist < outer_rad);
3013                 dist_to_outer_rad_squared = (outer_rad-min_dist)*(outer_rad-min_dist);
3014                 total_dist_squared = (inner_rad-outer_rad)*(inner_rad-outer_rad);
3015                 // AL 2-24-98: drop off damage relative to square of distance
3016                 Assert(dist_to_outer_rad_squared <= total_dist_squared);
3017                 *damage = max_damage * dist_to_outer_rad_squared/total_dist_squared;
3018
3019
3020 //              *damage = (min_dist - outer_rad) * max_damage/(inner_rad - outer_rad);
3021                 *blast =  (min_dist - outer_rad) * max_blast /(inner_rad - outer_rad);
3022         }
3023
3024         // nprintf(("AI", "Frame %i: Damage = %7.3f, %7.3f meters away.\n", Framecount, *damage, dist));
3025
3026         return 0;
3027 }
3028
3029 //      ----------------------------------------------------------------------
3030 //      weapon_area_apply_blast()
3031 //
3032 // Apply the blast effects of an explosion to a ship
3033 //
3034 // input:       force_apply_pos =>              world pos of where force is applied to object
3035 //                              ship_obj                                =>              object pointer of ship receiving the blast
3036 //                              blast_pos                       =>              world pos of blast center
3037 //                              blast                                   =>              force of blast
3038 //                              make_shockwave          =>              boolean, whether to create a shockwave or not
3039 //
3040 void weapon_area_apply_blast(vector *force_apply_pos, object *ship_obj, vector *blast_pos, float blast, int make_shockwave)
3041 {
3042         #define SHAKE_CONST 3000
3043         vector          force, vec_blast_to_ship, vec_ship_to_impact;
3044         polymodel               *pm;
3045
3046         // apply blast force based on distance from center of explosion
3047         vm_vec_sub(&vec_blast_to_ship, &ship_obj->pos, blast_pos);
3048         vm_vec_normalize_safe(&vec_blast_to_ship);
3049         vm_vec_copy_scale(&force, &vec_blast_to_ship, blast );
3050
3051
3052         vm_vec_sub(&vec_ship_to_impact, blast_pos, &ship_obj->pos);
3053
3054         pm = model_get(Ships[ship_obj->instance].modelnum);
3055         Assert ( pm != NULL );
3056
3057         if (make_shockwave) {
3058                 physics_apply_shock (&force, blast, &ship_obj->phys_info, &ship_obj->orient, &pm->mins, &pm->maxs, pm->rad);
3059                 if (ship_obj == Player_obj) {
3060                         joy_ff_play_vector_effect(&vec_blast_to_ship, blast * 2.0f);
3061                 }
3062         } else {
3063                 ship_apply_whack( &force, &vec_ship_to_impact, ship_obj);
3064         }
3065 }
3066
3067 //      ----------------------------------------------------------------------
3068 //      weapon_do_area_effect()
3069 //
3070 // Do the area effect for a weapon
3071 //
3072 // input:       wobjp                   =>              object pointer to weapon causing explosion
3073 //                              pos                     =>              world pos of explosion center
3074 //                              other_obj       =>              object pointer to ship that weapon impacted on (can be NULL)
3075 //
3076 void weapon_do_area_effect(object *wobjp, vector *pos, object *other_obj)
3077 {
3078         weapon_info     *wip;
3079         weapon *wp;
3080         object          *objp;
3081         float                   damage, blast;
3082
3083         wip = &Weapon_info[Weapons[wobjp->instance].weapon_info_index]; 
3084         wp = &Weapons[wobjp->instance];
3085         Assert(wip->inner_radius != 0); 
3086
3087         // only blast ships and asteroids
3088         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
3089                 if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) ) {
3090                         continue;
3091                 }
3092         
3093                 if ( objp->type == OBJ_SHIP ) {
3094                         // don't blast navbuoys
3095                         if ( ship_get_SIF(objp->instance) & SIF_NAVBUOY ) {
3096                                 continue;
3097                         }
3098                 }
3099
3100                 if ( weapon_area_calc_damage(objp, pos, wip->inner_radius, wip->outer_radius, wip->blast_force, wip->damage, &blast, &damage, wip->outer_radius) == -1 ){
3101                         continue;
3102                 }
3103
3104                 // scale damage
3105                 damage *= weapon_get_damage_scale(wip, wobjp, other_obj);               
3106
3107                 switch ( objp->type ) {
3108                 case OBJ_SHIP:
3109                         ship_apply_global_damage(objp, wobjp, pos, damage);
3110                         weapon_area_apply_blast(NULL, objp, pos, blast, 0);                     
3111                         break;
3112                 case OBJ_ASTEROID:
3113                         asteroid_hit(objp, NULL, NULL, damage);
3114                         break;
3115                 default:
3116                         Int3();
3117                         break;
3118                 }       
3119
3120         }       // end for
3121
3122         // if this weapon has the "Electronics" flag set, then disrupt subsystems in sphere
3123         if ( (other_obj != NULL) && (wip->wi_flags & WIF_ELECTRONICS) ) {
3124                 if ( other_obj->type == OBJ_SHIP ) {
3125                         weapon_do_electronics_affect(other_obj, pos, Weapons[wobjp->instance].weapon_info_index);
3126                 }
3127         }
3128 }
3129
3130
3131 //      ----------------------------------------------------------------------
3132 //      weapon_hit()
3133 //
3134 // This function is called when a weapon hits something (or, in the case of
3135 // missiles explodes for any particular reason)
3136 //
3137 void weapon_hit( object * weapon_obj, object * other_obj, vector * hitpos )
3138 {
3139         Assert(weapon_obj != NULL);
3140         if(weapon_obj == NULL){
3141                 return;
3142         }
3143         Assert((weapon_obj->type == OBJ_WEAPON) && (weapon_obj->instance >= 0) && (weapon_obj->instance < MAX_WEAPONS));
3144         if((weapon_obj->type != OBJ_WEAPON) || (weapon_obj->instance < 0) || (weapon_obj->instance >= MAX_WEAPONS)){
3145                 return;
3146         }
3147
3148         int                     num = weapon_obj->instance;
3149         int                     weapon_type = Weapons[num].weapon_info_index;
3150         object          *weapon_parent_objp;
3151         weapon_info     *wip;
3152         // int np_index;
3153
3154         Assert((weapon_type >= 0) && (weapon_type < MAX_WEAPONS));
3155         if((weapon_type < 0) || (weapon_type >= MAX_WEAPONS)){
3156                 return;
3157         }
3158         wip = &Weapon_info[weapon_type];
3159         weapon_parent_objp = &Objects[weapon_obj->parent];
3160
3161         // if this is the player ship, and is a laser hit, skip it. wait for player "pain" to take care of it
3162         // if( ((wip->subtype != WP_LASER) || !MULTIPLAYER_CLIENT) && (Player_obj != NULL) && (other_obj == Player_obj) ){
3163         if((other_obj != Player_obj) || (wip->subtype != WP_LASER) || !MULTIPLAYER_CLIENT){
3164                 weapon_hit_do_sound(other_obj, wip, hitpos);
3165         }
3166
3167         if ( wip->impact_weapon_expl_index > -1 )       {
3168                 int expl_ani_handle = weapon_get_expl_handle(wip->impact_weapon_expl_index, hitpos, wip->impact_explosion_radius);
3169                 particle_create( hitpos, &vmd_zero_vector, 0.0f, wip->impact_explosion_radius, PARTICLE_BITMAP_PERSISTENT, expl_ani_handle );
3170         }
3171
3172         weapon_obj->flags |= OF_SHOULD_BE_DEAD;
3173
3174         int sw_flag = SW_WEAPON;
3175
3176         // check if this is an area effect weapon
3177         if ( wip->wi_flags & WIF_AREA_EFFECT ) {
3178         // if ( wip->subtype & WP_MISSILE && wip->wi_flags & WIF_AREA_EFFECT ) {
3179                 if ( wip->wi_flags & WIF_SHOCKWAVE ) {
3180                         float actual_damage = wip->damage;
3181                         // Shockwaves caused by weapons hitting weapons are 1/4 as powerful
3182                         if ( ((other_obj) && (other_obj->type == OBJ_WEAPON)) || (Weapons[num].weapon_flags & WF_DESTROYED_BY_WEAPON)) {
3183                                 actual_damage /= 4.0f;
3184                                 sw_flag |= SW_WEAPON_KILL;
3185                         }
3186                         shockwave_create_info sci;
3187                         sci.blast = wip->blast_force;
3188                         sci.damage = actual_damage;
3189                         sci.inner_rad = wip->inner_radius;
3190                         sci.outer_rad = wip->outer_radius;
3191                         sci.speed = wip->shockwave_speed;
3192                         sci.rot_angle = 0.0f;
3193
3194                         shockwave_create(OBJ_INDEX(weapon_obj), hitpos, &sci, sw_flag);
3195 //                      snd_play_3d( &Snds[SND_SHOCKWAVE_IMPACT], hitpos, &Eye_position );
3196                 }
3197                 else {
3198                         weapon_do_area_effect(weapon_obj, hitpos, other_obj);
3199                 }
3200         }
3201
3202         // check if this is an EMP weapon
3203         if(wip->wi_flags & WIF_EMP){
3204                 emp_apply(&weapon_obj->pos, wip->inner_radius, wip->outer_radius, wip->emp_intensity, wip->emp_time);
3205         }       
3206
3207         // spawn weapons - note the change from FS 1 multiplayer.
3208         if (wip->wi_flags & WIF_SPAWN){
3209                 spawn_child_weapons(weapon_obj);
3210         }       
3211 }
3212
3213 void weapon_detonate(object *objp)
3214 {
3215         Assert(objp != NULL);
3216         if(objp == NULL){
3217                 return;
3218         }
3219         Assert((objp->type == OBJ_WEAPON) && (objp->instance >= 0));
3220         if((objp->type != OBJ_WEAPON) || (objp->instance < 0)){
3221                 return;
3222         }       
3223
3224         // send a detonate packet in multiplayer
3225         if(MULTIPLAYER_MASTER){
3226                 send_weapon_detonate_packet(objp);
3227         }
3228
3229         // call weapon hit
3230         weapon_hit(objp, NULL, &objp->pos);
3231 }
3232
3233 //      Return the Weapon_info[] index of the weapon with name *name.
3234 int weapon_name_lookup(char *name)
3235 {
3236         int     i;
3237
3238         for ( i=0; i < Num_weapon_types; i++) {
3239                 if (!stricmp(name, Weapon_info[i].name)) {
3240                         return i;
3241                 }
3242         }
3243
3244         return -1;
3245 }
3246
3247 // Group_id:  If you should quad lasers, they should all have the same group id.  
3248 // This will be used to optimize lighting, since each group only needs to cast one light.
3249 // Call this to get a new group id, then pass it to each weapon_create call for all the
3250 // weapons in the group.   Number will be between 0 and WEAPON_MAX_GROUP_IDS and will
3251 // get reused.
3252 int weapon_create_group_id()
3253 {
3254         static int current_id = 0;
3255
3256         int n = current_id;
3257         
3258         current_id++;
3259         if ( current_id >= WEAPON_MAX_GROUP_IDS )       {
3260                 current_id = 0;
3261         }
3262         return n;
3263 }
3264
3265
3266 void weapons_page_in()
3267 {
3268         int i, j, idx;
3269
3270         // Page in bitmaps for all weapons
3271         for (i=0; i<Num_weapon_types; i++ )     {
3272                 weapon_info *wip = &Weapon_info[i];
3273
3274                 wip->wi_flags &= (~WIF_THRUSTER);               // Assume no thrusters
3275                 
3276                 switch( wip->render_type )      {
3277                         case WRT_POF:
3278                                 {
3279                                         wip->model_num = model_load( wip->pofbitmap_name, 0, NULL );
3280
3281                                         polymodel *pm = model_get( wip->model_num );
3282
3283                                         // If it has a model, and the model pof has thrusters, then set
3284                                         // the flags
3285                                         if ( pm->n_thrusters > 0 )      {
3286                                                 //mprintf(( "Weapon %s has thrusters!\n", wip->name ));
3287                                                 wip->wi_flags |= WIF_THRUSTER;
3288                                         }
3289                 
3290                                         for (j=0; j<pm->n_textures; j++ )       {
3291                                                 int bitmap_num = pm->original_textures[j];
3292
3293                                                 if ( bitmap_num > -1 )  {
3294                                                         // if we're in Glide (and maybe later with D3D), use nondarkening textures
3295                                                         if(gr_screen.mode == GR_GLIDE){
3296                                                                 bm_page_in_nondarkening_texture( bitmap_num );
3297                                                         } else {
3298                                                                 bm_page_in_texture( bitmap_num );
3299                                                         }
3300                                                 }
3301                                         }
3302                                 }
3303                                 break;
3304
3305                         case WRT_LASER:
3306                                 {
3307                                         bm_page_in_texture( wip->laser_bitmap );
3308
3309                                         if(wip->laser_glow_bitmap >= 0){
3310                                                 bm_page_in_texture(wip->laser_glow_bitmap);
3311                                         }
3312                                 }
3313                                 break;
3314
3315                         default:
3316                                 Int3(); // Invalid weapon rendering type.
3317                 }
3318
3319                 // If this has an impact vclip page it in.
3320 //              if ( wip->impact_explosion_ani > -1 )   {
3321 //                      int nframes, fps;
3322 //                      bm_get_info( wip->impact_explosion_ani, NULL, NULL, NULL, &nframes, &fps );
3323 //                      bm_page_in_xparent_texture( wip->impact_explosion_ani, nframes );
3324 //              }
3325
3326                 // trail bitmaps
3327                 if ( (wip->wi_flags & WIF_TRAIL) && (wip->tr_info.bitmap > -1) )        {
3328                         bm_page_in_texture( wip->tr_info.bitmap );
3329                 }
3330
3331                 // if this is a beam weapon, page in its stuff
3332                 if(wip->wi_flags & WIF_BEAM){
3333                         // all beam sections
3334                         for(idx=0; idx<wip->b_info.beam_num_sections; idx++){
3335                                 if((idx < MAX_BEAM_SECTIONS) && (wip->b_info.sections[idx].texture >= 0)){
3336                                         bm_page_in_texture(wip->b_info.sections[idx].texture);
3337                                 }
3338                         }
3339
3340                         // muzzle glow
3341                         if(wip->b_info.beam_glow_bitmap >= 0){
3342                                 bm_page_in_texture(wip->b_info.beam_glow_bitmap);
3343                         }
3344
3345                         // particle ani
3346                         if(wip->b_info.beam_particle_ani >= 0){
3347                                 int nframes, fps;
3348                                 bm_get_info( wip->b_info.beam_particle_ani, NULL, NULL, NULL, &nframes, &fps );
3349                                 bm_page_in_texture( wip->b_info.beam_particle_ani, nframes );
3350                         }
3351                 }
3352         }
3353
3354         // explosion ani's
3355         for (i=0; i<Num_weapon_expl; i++) {
3356                 int bitmap_handle, nframes, fps;
3357
3358                 for (j=0; j<Weapon_expl_info[i].lod_count; j++) {
3359                         //load ani
3360                         bitmap_handle = bm_load_animation(Weapon_expl_info[i].lod[j].filename, &nframes, &fps, 1);
3361                         Weapon_expl_info[i].lod[j].bitmap_id = bitmap_handle;
3362                         Weapon_expl_info[i].lod[j].fps = fps;
3363                         Weapon_expl_info[i].lod[j].num_frames = nframes;
3364
3365                         // page it in
3366                         bm_page_in_xparent_texture(bitmap_handle, nframes);
3367                 }
3368         }
3369
3370         // Counter measures
3371         for (i=0; i<Num_cmeasure_types; i++ )   {
3372                 cmeasure_info *cmeasurep;
3373
3374                 cmeasurep = &Cmeasure_info[i];
3375         
3376                 cmeasurep->model_num = model_load( cmeasurep->pof_name, 0, NULL );
3377
3378                 polymodel *pm = model_get( cmeasurep->model_num );
3379
3380                 for (j=0; j<pm->n_textures; j++ )       {
3381                         int bitmap_num = pm->original_textures[j];
3382
3383                         if ( bitmap_num > -1 )  {
3384                                 bm_page_in_texture( bitmap_num );
3385                         }
3386                 }
3387                 Assert( cmeasurep->model_num > -1 );
3388         }
3389
3390 }
3391
3392 // call to get the "color" of the laser at the given moment (since glowing lasers can cycle colors)
3393 void weapon_get_laser_color(color *c, object *objp)
3394 {
3395         weapon *wep;
3396         weapon_info *winfo;
3397         float pct;
3398
3399         // sanity
3400         if(c == NULL){
3401                 return;
3402         }
3403
3404         // sanity
3405         Assert(objp->type == OBJ_WEAPON);
3406         Assert(objp->instance >= 0);
3407         Assert(Weapons[objp->instance].weapon_info_index >= 0);
3408         if((objp->type != OBJ_WEAPON) || (objp->instance < 0) || (Weapons[objp->instance].weapon_info_index < 0)){
3409                 return;
3410         }
3411         wep = &Weapons[objp->instance];
3412         winfo = &Weapon_info[wep->weapon_info_index];
3413
3414         // if we're a one-color laser
3415         if((winfo->laser_color_2.red == 0) && (winfo->laser_color_2.green == 0) && (winfo->laser_color_2.blue == 0)){
3416                 *c = winfo->laser_color_1;
3417         }
3418
3419         // lifetime pct
3420         pct = 1.0f - (wep->lifeleft / winfo->lifetime);
3421         if(pct > 0.5f){
3422                 pct = 0.5f;
3423         } else if (pct < 0.0f)
3424                 pct = 0.0f;
3425
3426         pct *= 2.0f;
3427         
3428         // otherwise interpolate between the colors
3429         gr_init_color( c, (int)((float)winfo->laser_color_1.red + (((float)winfo->laser_color_2.red - (float)winfo->laser_color_1.red) * pct)), 
3430                                                         (int)((float)winfo->laser_color_1.green + (((float)winfo->laser_color_2.green - (float)winfo->laser_color_1.green) * pct)), 
3431                                                         (int)((float)winfo->laser_color_1.blue + (((float)winfo->laser_color_2.blue - (float)winfo->laser_color_1.blue) * pct)) );
3432 }
3433
3434 // default weapon particle spew data
3435 int Weapon_particle_spew_count = 1;
3436 int Weapon_particle_spew_time = 25;
3437 float Weapon_particle_spew_vel = 0.4f;
3438 float Weapon_particle_spew_radius = 2.0f;
3439 float Weapon_particle_spew_lifetime = 0.15f;
3440 float Weapon_particle_spew_scale = 0.8f;
3441
3442 // for weapons flagged as particle spewers, spew particles. wheee
3443 void weapon_maybe_spew_particle(object *obj)
3444 {
3445         weapon *wp;
3446         int idx;
3447         vector direct, direct_temp, particle_pos;
3448         vector null_vec = ZERO_VECTOR;
3449         vector vel;
3450         float ang;
3451
3452         // check some stuff
3453         Assert(obj->type == OBJ_WEAPON);
3454         Assert(obj->instance >= 0);
3455         Assert(Weapons[obj->instance].weapon_info_index >= 0);
3456         Assert(Weapon_info[Weapons[obj->instance].weapon_info_index].wi_flags & WIF_PARTICLE_SPEW);
3457         
3458         wp = &Weapons[obj->instance];   
3459
3460         // if the weapon's particle timestamp has elapse`d
3461         if((wp->particle_spew_time == -1) || timestamp_elapsed(wp->particle_spew_time)){
3462                 // reset the timestamp
3463                 wp->particle_spew_time = timestamp(Weapon_particle_spew_time);
3464
3465                 // spew some particles
3466                 for(idx=0; idx<Weapon_particle_spew_count; idx++){
3467                         // get the backward vector of the weapon
3468                         direct = obj->orient.fvec;
3469                         vm_vec_negate(&direct);
3470
3471                         //      randomly perturb x, y and z
3472                         
3473                         // uvec
3474                         ang = fl_radian(frand_range(-90.0f, 90.0f));
3475                         vm_rot_point_around_line(&direct_temp, &direct, ang, &null_vec, &obj->orient.fvec);                     
3476                         direct = direct_temp;
3477                         vm_vec_scale(&direct, Weapon_particle_spew_scale);
3478
3479                         // rvec
3480                         ang = fl_radian(frand_range(-90.0f, 90.0f));
3481                         vm_rot_point_around_line(&direct_temp, &direct, ang, &null_vec, &obj->orient.rvec);                     
3482                         direct = direct_temp;
3483                         vm_vec_scale(&direct, Weapon_particle_spew_scale);
3484
3485                         // fvec
3486                         ang = fl_radian(frand_range(-90.0f, 90.0f));
3487                         vm_rot_point_around_line(&direct_temp, &direct, ang, &null_vec, &obj->orient.uvec);                     
3488                         direct = direct_temp;
3489                         vm_vec_scale(&direct, Weapon_particle_spew_scale);
3490
3491                         // get a velovity vector of some percentage of the weapon's velocity
3492                         vel = obj->phys_info.vel;
3493                         vm_vec_scale(&vel, Weapon_particle_spew_vel);
3494
3495                         // emit the particle
3496                         vm_vec_add(&particle_pos, &obj->pos, &direct);
3497                         particle_create(&particle_pos, &vel, Weapon_particle_spew_lifetime, Weapon_particle_spew_radius, PARTICLE_SMOKE);
3498                 }
3499         }
3500 }
3501
3502 // debug console functionality
3503 void pspew_display_dcf()
3504 {
3505         dc_printf("Particle spew settings\n\n");
3506         dc_printf("Particle spew count (pspew_count) : %d\n", Weapon_particle_spew_count);
3507         dc_printf("Particle spew time (pspew_time) : %d\n", Weapon_particle_spew_time);
3508         dc_printf("Particle spew velocity (pspew_vel) : %f\n", Weapon_particle_spew_vel);
3509         dc_printf("Particle spew size (pspew_size) : %f\n", Weapon_particle_spew_radius);
3510         dc_printf("Particle spew lifetime (pspew_life) : %f\n", Weapon_particle_spew_lifetime);
3511         dc_printf("Particle spew scale (psnew_scale) : %f\n", Weapon_particle_spew_scale);
3512 }
3513
3514 DCF(pspew_count, "Number of particles spewed at a time")
3515 {       
3516         dc_get_arg(ARG_INT);
3517         if(Dc_arg_type & ARG_INT){
3518                 Weapon_particle_spew_count = Dc_arg_int;
3519         }
3520
3521         pspew_display_dcf();
3522 }
3523
3524 DCF(pspew_time, "Time between particle spews")
3525 {       
3526         dc_get_arg(ARG_INT);
3527         if(Dc_arg_type & ARG_INT){
3528                 Weapon_particle_spew_time = Dc_arg_int;
3529         }
3530
3531         pspew_display_dcf();
3532 }
3533
3534 DCF(pspew_vel, "Relative velocity of particles (0.0 - 1.0)")
3535 {       
3536         dc_get_arg(ARG_FLOAT);
3537         if(Dc_arg_type & ARG_FLOAT){
3538                 Weapon_particle_spew_vel = Dc_arg_float;
3539         }
3540
3541         pspew_display_dcf();
3542 }
3543
3544 DCF(pspew_size, "Size of spewed particles")
3545 {       
3546         dc_get_arg(ARG_FLOAT);
3547         if(Dc_arg_type & ARG_FLOAT){
3548                 Weapon_particle_spew_radius = Dc_arg_float;
3549         }
3550
3551         pspew_display_dcf();
3552 }
3553
3554 DCF(pspew_life, "Lifetime of spewed particles")
3555 {       
3556         dc_get_arg(ARG_FLOAT);
3557         if(Dc_arg_type & ARG_FLOAT){
3558                 Weapon_particle_spew_lifetime = Dc_arg_float;
3559         }
3560
3561         pspew_display_dcf();
3562 }
3563
3564 DCF(pspew_scale, "How far away particles are from the weapon path")
3565 {       
3566         dc_get_arg(ARG_FLOAT);
3567         if(Dc_arg_type & ARG_FLOAT){
3568                 Weapon_particle_spew_scale = Dc_arg_float;
3569         }
3570
3571         pspew_display_dcf();
3572 }
3573
3574 // return a scale factor for damage which should be applied for 2 collisions
3575 float weapon_get_damage_scale(weapon_info *wip, object *wep, object *target)
3576 {
3577         weapon *wp;     
3578         int from_player = 0;
3579         float total_scale = 1.0f;
3580         float hull_pct;
3581         int is_big_damage_ship = 0;
3582
3583         // sanity
3584         if((wip == NULL) || (wep == NULL) || (target == NULL)){
3585                 return 1.0f;
3586         }
3587
3588         // don't scale any damage if its not a weapon   
3589         if((wep->type != OBJ_WEAPON) || (wep->instance < 0) || (wep->instance >= MAX_WEAPONS)){
3590                 return 1.0f;
3591         }
3592         wp = &Weapons[wep->instance];
3593
3594         // was the weapon fired by the player
3595         from_player = 0;
3596         if((wep->parent >= 0) && (wep->parent < MAX_OBJECTS) && (Objects[wep->parent].flags & OF_PLAYER_SHIP)){
3597                 from_player = 1;
3598         }
3599                 
3600         // if this is a lockarm weapon, and it was fired unlocked
3601         if((wip->wi_flags & WIF_LOCKARM) && !(wp->weapon_flags & WF_LOCKED_WHEN_FIRED)){                
3602                 total_scale *= 0.1f;
3603         }
3604         
3605         // if the hit object was a ship
3606         if(target->type == OBJ_SHIP){
3607                 ship *shipp;
3608                 ship_info *sip;
3609
3610                 // get some info on the ship
3611                 Assert((target->instance >= 0) && (target->instance < MAX_SHIPS));
3612                 if((target->instance < 0) || (target->instance >= MAX_SHIPS)){
3613                         return total_scale;
3614                 }
3615                 shipp = &Ships[target->instance];
3616                 sip = &Ship_info[Ships[target->instance].ship_info_index];
3617
3618                 // get hull pct of the ship currently
3619                 hull_pct = target->hull_strength / sip->initial_hull_strength;
3620
3621                 // if it has hit a supercap ship and is not a supercap class weapon
3622                 if((sip->flags & SIF_SUPERCAP) && !(wip->wi_flags & WIF_SUPERCAP)){
3623                         // if the supercap is around 3/4 damage, apply nothing
3624                         if(hull_pct <= 0.75f){
3625                                 return 0.0f;
3626                         } else {
3627                                 total_scale *= SUPERCAP_DAMAGE_SCALE;
3628                         }
3629                 }
3630
3631                 // determine if this is a big damage ship
3632                 is_big_damage_ship = (sip->flags & SIF_BIG_DAMAGE);
3633
3634                 // if this is a large ship, and is being hit by flak
3635                 if(is_big_damage_ship && (wip->wi_flags & WIF_FLAK)){
3636                         total_scale *= FLAK_DAMAGE_SCALE;
3637                 }
3638                 
3639                 // if the player is firing small weapons at a big ship
3640                 if( from_player && is_big_damage_ship && !(wip->wi_flags & (WIF_HURTS_BIG_SHIPS)) ){
3641
3642                         // if its a laser weapon
3643                         if(wip->subtype == WP_LASER){
3644                                 total_scale *= 0.01f;
3645                         } else {
3646                                 total_scale *= 0.05f;
3647                         }
3648                 }
3649
3650                 // if the weapon is a small weapon being fired at a big ship
3651                 if( is_big_damage_ship && !(wip->wi_flags & (WIF_HURTS_BIG_SHIPS)) ){
3652                         if(hull_pct > 0.1f){
3653                                 total_scale *= hull_pct;
3654                         } else {
3655                                 return 0.0f;
3656                         }
3657                 }
3658         }
3659         
3660         return total_scale;
3661 }
3662
3663 int weapon_get_expl_handle(int weapon_expl_index, vector *pos, float size)
3664 {
3665         weapon_expl_info *wei = &Weapon_expl_info[weapon_expl_index];
3666
3667         if (wei->lod_count == 1) {
3668                 return wei->lod[0].bitmap_id;
3669         }
3670
3671         // now we have to do some work
3672         vertex v;
3673         int x, y, w, h, bm_size;
3674         int must_stop = 0;
3675         int best_lod = 1;
3676         int behind = 0;
3677
3678         // start the frame
3679         extern float Viewer_zoom;
3680         extern int G3_count;
3681
3682         if(!G3_count){
3683                 g3_start_frame(1);
3684                 must_stop = 1;
3685         }
3686         g3_set_view_matrix(&Eye_position, &Eye_matrix, Viewer_zoom);
3687
3688         // get extents of the rotated bitmap
3689         g3_rotate_vertex(&v, pos);
3690
3691         // if vertex is behind, find size if in front, then drop down 1 LOD
3692         if (v.codes & CC_BEHIND) {
3693                 float dist = vm_vec_dist_quick(&Eye_position, pos);
3694                 vector temp;
3695
3696                 behind = 1;
3697                 vm_vec_scale_add(&temp, &Eye_position, &Eye_matrix.fvec, dist);
3698                 g3_rotate_vertex(&v, &temp);
3699
3700                 // if still behind, bail and go with default
3701                 if (v.codes & CC_BEHIND) {
3702                         behind = 0;
3703                 }
3704         }
3705
3706         if (!g3_get_bitmap_dims(wei->lod[0].bitmap_id, &v, size, &x, &y, &w, &h, &bm_size)) {
3707                 if (Detail.hardware_textures == 4) {
3708                         // straight LOD
3709                         if(w <= bm_size/8){
3710                                 best_lod = 3;
3711                         } else if(w <= bm_size/2){
3712                                 best_lod = 2;
3713                         } else if(w <= 1.3f*bm_size){
3714                                 best_lod = 1;
3715                         } else {
3716                                 best_lod = 0;
3717                         }
3718                 } else {
3719                         // less aggressive LOD for lower detail settings
3720                         if(w <= bm_size/8){
3721                                 best_lod = 3;
3722                         } else if(w <= bm_size/3){
3723                                 best_lod = 2;
3724                         } else if(w <= (1.15f*bm_size)){
3725                                 best_lod = 1;
3726                         } else {
3727                                 best_lod = 0;
3728                         }               
3729                 }
3730         }
3731
3732         // if it's behind, bump up LOD by 1
3733         if (behind) {
3734                 best_lod++;
3735         }
3736
3737         // end the frame
3738         if(must_stop){
3739                 g3_end_frame();
3740         }
3741
3742         best_lod = min(best_lod, wei->lod_count - 1);
3743         return wei->lod[best_lod].bitmap_id;
3744 }