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