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