]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/shipfx.cpp
ryan's struct patch for gcc 2.95
[taylor/freespace2.git] / src / ship / shipfx.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Ship/ShipFX.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Routines for ship effects (as in special)
16  *
17  * $Log$
18  * Revision 1.4  2002/06/17 06:33:11  relnev
19  * ryan's struct patch for gcc 2.95
20  *
21  * Revision 1.3  2002/06/09 04:41:26  relnev
22  * added copyright header
23  *
24  * Revision 1.2  2002/05/07 03:16:52  theoddone33
25  * The Great Newline Fix
26  *
27  * Revision 1.1.1.1  2002/05/03 03:28:10  root
28  * Initial import.
29  *
30  * 
31  * 51    9/13/99 4:53p Andsager
32  * 
33  * 50    9/13/99 10:09a Andsager
34  * Add debug console commands to lower model render detail and fireball
35  * LOD for big ship explosiosns.
36  * 
37  * 49    9/08/99 10:44p Andsager
38  * Make HUGE ships not die when warping out, after warp effect started.
39  * 
40  * 48    9/06/99 10:16p Andsager
41  * Modify big ship explosions.  Less frequent fireballs, fewer particles,
42  * larger fireballs
43  * 
44  * 47    9/05/99 11:10a Andsager
45  * Fix up which split ship get debris pieces.  Dont render debris pieces
46  * for split ships until they are near clip plane.
47  * 
48  * 46    9/02/99 12:55a Mikek
49  * Scale engine wash by speed.
50  * 
51  * 45    9/01/99 10:15a Dave
52  * 
53  * 44    8/31/99 10:13p Andsager
54  * Add Knossos warp effect fireball
55  * 
56  * 43    8/23/99 11:09a Andsager
57  * Round 2 of Knossos explosion
58  * 
59  * 42    8/20/99 2:16p Andsager
60  * Make only supercaps slow down extra fast after warping in.
61  * 
62  * 41    8/20/99 1:42p Andsager
63  * Frist pass on Knossos explosion.
64  * 
65  * 40    8/19/99 4:36p Andsager
66  * Cleaned up special_warpout
67  * 
68  * 39    8/16/99 10:04p Andsager
69  * Add special-warp-dist and special-warpout-name sexp for Knossos device
70  * warpout.
71  * 
72  * 38    8/16/99 2:01p Andsager
73  * Knossos warp-in warp-out.
74  * 
75  * 37    8/13/99 10:49a Andsager
76  * Knossos and HUGE ship warp out.  HUGE ship warp in.  Stealth search
77  * modes dont collide big ships.
78  * 
79  * 36    8/05/99 2:06a Dave
80  * Whee.
81  * 
82  * 35    7/18/99 12:32p Dave
83  * Randomly oriented shockwaves.
84  * 
85  * 34    7/09/99 12:52a Andsager
86  * Modify engine wash (1) less damage (2) only at a closer range (3) no
87  * damage when engine is disabled
88  * 
89  * 33    7/06/99 10:45a Andsager
90  * Modify engine wash to work on any ship that is not small.  Add AWACS
91  * ask for help.
92  * 
93  * 32    7/02/99 9:55p Dave
94  * Player engine wash sound.
95  * 
96  * 31    7/02/99 4:31p Dave
97  * Much more sophisticated lightning support.
98  * 
99  * 30    7/01/99 4:23p Dave
100  * Full support for multiple linked ambient engine sounds. Added "big
101  * damage" flag.
102  * 
103  * 29    7/01/99 11:44a Dave
104  * Updated object sound system to allow multiple obj sounds per ship.
105  * Added hit-by-beam sound. Added killed by beam sound.
106  * 
107  * 28    6/17/99 12:06p Andsager
108  * Add a fireball for each live debris piece.
109  * 
110  * 27    6/14/99 3:21p Andsager
111  * Allow collisions between ship and its debris.  Fix up collision pairs
112  * when large ship is warping out.
113  * 
114  * 26    5/27/99 12:14p Andsager
115  * Some fixes for live debris when more than one subsys on ship with live
116  * debris.  Set subsys strength (when 0) blows off subsystem.
117  * sexp_hits_left_subsystem works for SUBSYSTEM_UNKNOWN.
118  * 
119  * 25    5/26/99 11:46a Dave
120  * Added ship-blasting lighting and made the randomization of lighting
121  * much more customizable.
122  * 
123  * 24    5/25/99 10:05a Andsager
124  * Fix assert with wing warping out with no warp effect.
125  * 
126  * 23    5/24/99 5:45p Dave
127  * Added detail levels to the nebula, with a decent speedup. Split nebula
128  * lightning into its own section.
129  * 
130  * 22    5/21/99 5:03p Andsager
131  * Add code to display engine wash death.  Modify ship_kill_packet
132  * 
133  * 21    5/19/99 11:09a Andsager
134  * Turn on engine wash.  Check every 1/4 sec.
135  * 
136  * 20    5/18/99 1:30p Dave
137  * Added muzzle flash table stuff.
138  * 
139  * 19    5/17/99 10:33a Dave
140  * Fixed warning.
141  * 
142  * 18    5/11/99 10:16p Andsager
143  * First pass on engine wash effect.  Rotation (control input), damage,
144  * shake.  
145  * 
146  * 17    5/09/99 6:00p Dave
147  * Lots of cool new effects. E3 build tweaks.
148  * 
149  * 16    4/28/99 11:13p Dave
150  * Temporary checkin of artillery code.
151  * 
152  * 15    3/29/99 6:17p Dave
153  * More work on demo system. Got just about everything in except for
154  * blowing ships up, secondary weapons and player death/warpout.
155  * 
156  * 14    3/28/99 5:58p Dave
157  * Added early demo code. Make objects move. Nice and framerate
158  * independant, but not much else. Don't use yet unless you're me :)
159  * 
160  * 13    3/23/99 2:29p Andsager
161  * Fix shockwaves for kamikazi and Fred defined.  Collect together
162  * shockwave_create_info struct.
163  * 
164  * 12    3/20/99 3:03p Andsager
165  * Fix get_model_cross_section_at_z() from getting invalid index .
166  * 
167  * 11    3/19/99 9:51a Dave
168  * Checkin to repair massive source safe crash. Also added support for
169  * pof-style nebulae, and some new weapons code.
170  * 
171  * 10    2/26/99 4:14p Dave
172  * Put in the ability to have multiple shockwaves for ships.
173  * 
174  * 9     1/29/99 12:47a Dave
175  * Put in sounds for beam weapon. A bunch of interface screens (tech
176  * database stuff).
177  * 
178  * 8     1/28/99 9:10a Andsager
179  * Particles increased in width, life, number.  Max particles increased
180  * 
181  * 7     1/27/99 9:56a Dave
182  * Temporary checkin of beam weapons for Dan to make cool sounds.
183  * 
184  * 6     1/11/99 12:42p Andsager
185  * Add live debris - debris which is created from a destroyed subsystem,
186  * when the ship is still alive
187  * 
188  * 5     11/18/98 10:29a Johnson
189  * fix assert in shipfx_remove_submodel_ship_sparks.  submodel may not
190  * have spark and be destroyed.
191  * 
192  * 4     11/17/98 4:27p Andsager
193  * Stop sparks from emitting from destroyed subobjects
194  * 
195  * 3     10/20/98 1:39p Andsager
196  * Make so sparks follow animated ship submodels.  Modify
197  * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
198  * submodel_num.  Add submodel_num to multiplayer hit packet.
199  * 
200  * 2     10/07/98 10:53a Dave
201  * Initial checkin.
202  * 
203  * 1     10/07/98 10:51a Dave
204  * 
205  *
206  * $NoKeywords: $
207  */
208
209 #include "pstypes.h"
210 #include "systemvars.h"
211 #include "ship.h"
212 #include "fireballs.h"
213 #include "debris.h"
214 #include "hudtarget.h"
215 #include "shipfx.h"
216 #include "multi.h"
217 #include "gamesnd.h"
218 #include "timer.h"
219 #include "3d.h"                 // needed for View_position, which is used when playing a 3D sound
220 #include "multi.h"
221 #include "multiutil.h"
222 #include "hud.h"
223 #include "fvi.h"
224 #include "gamesequence.h"
225 #include "lighting.h"
226 #include "linklist.h"
227 #include "particle.h"
228 #include "multimsgs.h"
229 #include "multiutil.h"
230 #include "bmpman.h"
231 #include "freespace.h"
232 #include "muzzleflash.h"
233 #include "demo.h"
234 #include "shiphit.h"
235 #include "neblightning.h"
236 #include "objectsnd.h"
237
238 #ifndef NDEBUG
239 extern float flFrametime;
240 extern int Framecount;
241 #endif
242
243 #define SHIP_CANNON_BITMAP                      "argh"
244 int Ship_cannon_bitmap = -1;
245
246 int Player_engine_wash_loop = -1;
247
248 void shipfx_remove_submodel_ship_sparks(ship *shipp, int submodel_num)
249 {
250         Assert(submodel_num != -1);
251
252         // maybe no active sparks on submodel
253         if (shipp->num_hits == 0) {
254                 return;
255         }
256         
257         for (int spark_num=0; spark_num<shipp->num_hits; spark_num++) {
258                 if (shipp->sparks[spark_num].submodel_num == submodel_num) {
259                         shipp->sparks[spark_num].end_time = timestamp(1);
260                 }
261         }
262 }
263
264 // Check if subsystem has live debris and create
265 // DKA: 5/26/99 make velocity of debris scale according to size of debris subobject (at least for large subobjects)
266 void shipfx_subsystem_mabye_create_live_debris(object *ship_obj, ship *ship_p, ship_subsys *subsys, vector *exp_center, float exp_mag)
267 {
268         // initializations
269         polymodel *pm = model_get(ship_p->modelnum);
270         int submodel_num = subsys->system_info->subobj_num;
271         submodel_instance_info *sii = &subsys->submodel_info_1;
272
273         object *live_debris_obj;
274         int i, num_live_debris, live_debris_submodel;
275
276         // get number of live debris objects to create
277         num_live_debris = pm->submodel[submodel_num].num_live_debris;
278         if (num_live_debris <= 0) {
279                 return;
280         }
281
282         ship_model_start(ship_obj);
283
284         // copy angles
285         angles copy_angs = pm->submodel[submodel_num].angs;
286         angles zero_angs = {0.0f, 0.0f, 0.0f};
287
288         // make sure the axis point is set
289         if ( !sii->axis_set ) {
290                 model_init_submodel_axis_pt(sii, ship_p->modelnum, submodel_num);
291         }
292
293         // get the rotvel
294         vector model_axis, world_axis, rotvel, world_axis_pt;
295         void model_get_rotating_submodel_axis(vector *model_axis, vector *world_axis, int modelnum, int submodel_num, object *obj);
296         model_get_rotating_submodel_axis(&model_axis, &world_axis, ship_p->modelnum, submodel_num, ship_obj);
297         vm_vec_copy_scale(&rotvel, &world_axis, sii->cur_turn_rate);
298
299         model_find_world_point(&world_axis_pt, &sii->pt_on_axis, ship_p->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
300
301         matrix m_rot;   // rotation for debris orient about axis
302         vm_quaternion_rotate(&m_rot, vm_vec_mag((vector*)&sii->angs), &model_axis);
303
304
305         // create live debris pieces
306         for (i=0; i<num_live_debris; i++) {
307                 live_debris_submodel = pm->submodel[submodel_num].live_debris[i];
308                 vector start_world_pos, start_model_pos, end_world_pos;
309
310                 // get start world pos
311                 vm_vec_zero(&start_world_pos);
312                 model_find_world_point(&start_world_pos, &pm->submodel[live_debris_submodel].offset, ship_p->modelnum, live_debris_submodel, &ship_obj->orient, &ship_obj->pos );
313
314                 // convert to model coord of underlying submodel
315                 // set angle to zero
316                 pm->submodel[submodel_num].angs = zero_angs;
317                 world_find_model_point(&start_model_pos, &start_world_pos, pm, submodel_num, &ship_obj->orient, &ship_obj->pos);
318
319                 // rotate from submodel coord to world coords
320                 // reset angle to current angle
321                 pm->submodel[submodel_num].angs = copy_angs;
322                 model_find_world_point(&end_world_pos, &start_model_pos, ship_p->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
323
324                 // create fireball here.
325                 fireball_create(&end_world_pos, FIREBALL_EXPLOSION_MEDIUM, OBJ_INDEX(ship_obj), pm->submodel[live_debris_submodel].rad);
326
327                 // create debris
328                 live_debris_obj = debris_create(ship_obj, ship_p->modelnum, live_debris_submodel, &end_world_pos, exp_center, 1, exp_mag);
329
330                 // only do if debris is created
331                 if (live_debris_obj) {
332                         // get radial velocity of debris
333                         vector delta_x, radial_vel;
334                         vm_vec_sub(&delta_x, &end_world_pos, &world_axis_pt);
335                         vm_vec_crossprod(&radial_vel, &rotvel, &delta_x);
336
337                         if (Ship_info[ship_p->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
338                                 // set velocity to cross center of knossos device
339                                 vector rand_vec, vec_to_center;
340
341                                 float vel_mag = vm_vec_mag_quick(&radial_vel) * 1.3f * (0.9f + 0.2f*frand());
342                                 vm_vec_normalized_dir(&vec_to_center, &world_axis_pt, &end_world_pos);
343                                 vm_vec_rand_vec_quick(&rand_vec);
344                                 vm_vec_scale_add2(&vec_to_center, &rand_vec, 0.2f);
345                                 vm_vec_scale_add2(&live_debris_obj->phys_info.vel, &vec_to_center, vel_mag);
346
347                         } else {
348                                 // Get rotation of debris object
349                                 matrix copy = live_debris_obj->orient;
350                                 vm_matrix_x_matrix(&live_debris_obj->orient, &copy, &m_rot);
351
352                                 // Add radial velocity (at least as large as exp velocity)
353                                 vector temp_vel;        // explosion velocity with ship_obj velocity removed
354                                 vm_vec_sub(&temp_vel, &live_debris_obj->phys_info.vel, &ship_obj->phys_info.vel);
355
356                                 // find magnitudes of radial and temp velocity
357                                 float vel_mag = vm_vec_mag(&temp_vel);
358                                 float rotvel_mag = vm_vec_mag(&radial_vel);
359
360                                 if (rotvel_mag > 0.1) {
361                                         float scale = (1.2f + 0.2f * frand()) * vel_mag / rotvel_mag;
362                                         // always add *at least* rotvel
363                                         if (scale < 1) {
364                                                 scale = 1.0f;
365                                         }
366
367                                         if (exp_mag > 1) {      // whole ship going down
368                                                 scale = exp_mag;
369                                         }
370
371                                         if (Ship_info[ship_p->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
372                                                 scale = 1.0f;
373                                         }
374
375                                         vm_vec_scale_add2(&live_debris_obj->phys_info.vel, &radial_vel, scale);
376                                 }
377
378                                 // scale up speed of debris if ship_obj > 125, but not for knossos
379                                 if (ship_obj->radius > 250 && !(Ship_info[ship_p->ship_info_index].flags & SIF_KNOSSOS_DEVICE)) {
380                                         vm_vec_scale(&live_debris_obj->phys_info.vel, ship_obj->radius/250.0f);
381                                 }
382                         }
383                 }
384         }
385
386         ship_model_stop(ship_obj);
387 }
388
389 void set_ship_submodel_as_blown_off(ship *shipp, char *name)
390 {
391         int found =     FALSE;
392
393         // go through list of ship subsystems and find name
394         ship_subsys     *pss = NULL;
395         for (pss=GET_FIRST(&shipp->subsys_list); pss!=END_OF_LIST(&shipp->subsys_list); pss=GET_NEXT(pss)) {
396                 if ( stricmp(pss->system_info->name, name) == 0) {
397                         found = TRUE;
398                         break;
399                 }
400         }
401
402         // set its blown off flag to TRUE
403         Assert(found);
404         if (found) {
405                 pss->submodel_info_1.blown_off = 1;
406         }
407 }
408
409
410 // Create debris for ship submodel which has live debris (at ship death)
411 // when ship submodel has not already been blown off (and hence liberated live debris)
412 void shipfx_maybe_create_live_debris_at_ship_death( object *ship_obj )
413 {
414         // if ship has live debris, detonate that subsystem now
415         // search for any live debris
416
417         ship *shipp = &Ships[ship_obj->instance];
418         polymodel *pm = model_get(shipp->modelnum);
419
420         int live_debris_submodel = -1;
421         for (int idx=0; idx<pm->num_debris_objects; idx++) {
422                 if (pm->submodel[pm->debris_objects[idx]].is_live_debris) {
423                         live_debris_submodel = pm->debris_objects[idx];
424
425                         // get submodel that produces live debris
426                         int model_get_parent_submodel_for_live_debris( int model_num, int live_debris_model_num );
427                         int parent = model_get_parent_submodel_for_live_debris( shipp->modelnum, live_debris_submodel);
428                         Assert(parent != -1);
429
430                         // set model values only once (esp blown off)
431                         ship_model_start(ship_obj);
432
433                         // check if already blown off  (ship model set)
434                         if ( !pm->submodel[parent].blown_off ) {
435                 
436                                 // get ship_subsys for live_debris
437                                 // Go through all subsystems and look for submodel the subsystems with "parent" submodel.
438                                 ship_subsys     *pss = NULL;
439                                 for ( pss = GET_FIRST(&shipp->subsys_list); pss != END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
440                                         if (pss->system_info->subobj_num == parent) {
441                                                 break;
442                                         }
443                                 }
444
445                                 Assert (pss != NULL);
446                                 if (pss != NULL) {
447                                         vector exp_center, tmp = {0.0f, 0.0f, 0.0f};
448                                         model_find_world_point(&exp_center, &tmp, shipp->modelnum, parent, &ship_obj->orient, &ship_obj->pos );
449
450                                         // if not blown off, blow it off
451                                         shipfx_subsystem_mabye_create_live_debris(ship_obj, shipp, pss, &exp_center, 3.0f);
452
453                                         // now set subsystem as blown off, so we only get one copy
454                                         pm->submodel[parent].blown_off = 1;
455                                         set_ship_submodel_as_blown_off(&Ships[ship_obj->instance], pss->system_info->name);
456                                 }
457                         }
458                 }
459         }
460
461         // clean up
462         ship_model_stop(ship_obj);
463
464 }
465
466 void shipfx_blow_off_subsystem(object *ship_obj,ship *ship_p,ship_subsys *subsys, vector *exp_center)
467 {
468         vector subobj_pos;
469
470         model_subsystem *psub = subsys->system_info;
471
472         get_subsystem_world_pos(ship_obj, subsys, &subobj_pos);
473
474 /*
475         if ( psub->turret_gun_sobj > -1 )
476                 debris_create( ship_obj, ship_p->modelnum, psub->turret_gun_sobj, &subobj_pos, exp_center, 0, 1.0f );
477
478         if ( psub->subobj_num > -1 )
479                 debris_create( ship_obj, ship_p->modelnum, psub->subobj_num, &subobj_pos, exp_center, 0, 1.0f );
480 */
481         // get rid of sparks on submodel that is destroyed
482         shipfx_remove_submodel_ship_sparks(ship_p, psub->subobj_num);
483
484         // create debris shards
485         shipfx_blow_up_model(ship_obj, ship_p->modelnum, psub->subobj_num, 50, &subobj_pos );
486
487         // create live debris objects, if any
488         // TODO:  some MULITPLAYER implcations here!!
489         shipfx_subsystem_mabye_create_live_debris(ship_obj, ship_p, subsys, exp_center, 1.0f);
490
491         // create first fireball
492         fireball_create( &subobj_pos, FIREBALL_EXPLOSION_MEDIUM, OBJ_INDEX(ship_obj), psub->radius );
493 }
494
495
496 void shipfx_blow_up_hull(object *obj, int model, vector *exp_center)
497 {
498         int i;
499         polymodel * pm;
500         ushort sig_save;
501
502
503         pm = model_get(model);
504         if (!pm) return;
505
506         // in multiplayer, send a debris_hull_create packet.  Save/restore the debris signature
507         // when in misison only (since we can create debris pieces before mission starts)
508         sig_save = 0;
509         if ( (Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_IN_MISSION) ) {
510                 sig_save = multi_get_next_network_signature( MULTI_SIG_DEBRIS );
511                 multi_set_network_signature( (ushort)(Ships[obj->instance].arrival_distance), MULTI_SIG_DEBRIS );
512         }
513
514         bool try_live_debris = true;
515         for (i=0; i<pm->num_debris_objects; i++ )       {
516                 if (! pm->submodel[pm->debris_objects[i]].is_live_debris) {
517                         vector tmp = {0.0f, 0.0f, 0.0f };               
518                         model_find_world_point(&tmp, &pm->submodel[pm->debris_objects[i]].offset, model, 0, &obj->orient, &obj->pos );
519                         debris_create( obj, model, pm->debris_objects[i], &tmp, exp_center, 1, 3.0f );
520                 } else {
521                         if ( try_live_debris ) {
522                                 // only create live debris once
523                                 // this creates *all* the live debris for *all* the currently live subsystems.
524                                 try_live_debris = false;
525                                 shipfx_maybe_create_live_debris_at_ship_death(obj);
526                         }
527                 }
528         }
529
530         // restore the ship signature to it's original value.
531         if ( (Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_IN_MISSION) ) {
532                 multi_set_network_signature( sig_save, MULTI_SIG_DEBRIS );
533         }
534 }
535
536
537 // Creates "ndebris" pieces of debris on random verts of the the "submodel" in the 
538 // ship's model.
539 void shipfx_blow_up_model(object *obj,int model, int submodel, int ndebris, vector *exp_center )
540 {
541         int i;
542
543         // if in a multiplayer game -- seed the random number generator with a value that will be the same
544         // on all clients in the game -- the net_signature of the object works nicely -- since doing so should
545         // ensure that all pieces of debris will get scattered in same direction on all machines
546         if ( Game_mode & GM_MULTIPLAYER )
547                 srand( obj->net_signature );
548
549         // made a change to allow anyone but multiplayer client to blow up hull.  Clients will do it when
550         // they get the create packet
551         if ( submodel == 0 ) {
552                 shipfx_blow_up_hull(obj,model, exp_center );
553         }
554
555         for (i=0; i<ndebris; i++ )      {
556                 vector pnt1, pnt2;
557
558                 // Gets two random points on the surface of a submodel
559                 submodel_get_two_random_points(model, submodel, &pnt1, &pnt2 );
560
561                 vector tmp, outpnt;
562
563                 vm_vec_avg( &tmp, &pnt1, &pnt2 );
564                 model_find_world_point(&outpnt, &tmp, model,submodel, &obj->orient, &obj->pos );
565
566                 debris_create( obj, -1, -1, &outpnt, exp_center, 0, 1.0f );
567         }
568 }
569
570
571 // =================================================
572 //          SHIP WARP IN EFFECT CODE
573 // =================================================
574
575
576 // Given an ship, find the radius of it as viewed from the front.
577 static float shipfx_calculate_effect_radius( object *objp )
578 {
579         float w,h,rad;
580         ship *shipp = &Ships[objp->instance];
581
582         polymodel *pm = model_get( shipp->modelnum );
583
584         w = pm->maxs.xyz.x - pm->mins.xyz.x;
585         h = pm->maxs.xyz.y - pm->mins.xyz.y;
586         
587         if ( w > h )    {
588                 rad = w / 2.0f;
589         } else {
590                 rad = h / 2.0f;
591         }
592
593         object *docked_objp = ai_find_docked_object( objp );
594
595         //      If ship is docked then center wormhold about their center and make radius large enough.
596         if ( docked_objp ) {
597                 ship *docked_shipp = &Ships[docked_objp->instance];
598                 
599                 pm = model_get( docked_shipp->modelnum );
600                 
601                 w = pm->maxs.xyz.x - pm->mins.xyz.x;
602                 h = pm->maxs.xyz.y - pm->mins.xyz.y;
603                 
604                 if ( w > h )    {
605                         rad += w / 2.0f;
606                 } else {
607                         rad += h / 2.0f;
608                 }
609         }
610         return rad*3.0f;
611 }
612
613 // How long the stage 1 & stage 2 of warp in effect lasts.
614 // There are different times for small, medium, and large ships.
615 // The appropriate values are picked depending on the ship's
616 // radius.
617 #define SHIPFX_WARP_DELAY       (2.0f)          // time for warp effect to ramp up before ship moves into it.
618
619 // Give object objp, calculate how long it should take the
620 // ship to go through the warp effect and how fast the ship
621 // should go.   For reference,  capital ship of 2780m 
622 // should take 7 seconds to fly through.   Fighters of 30, 
623 // should take 1.5 seconds to fly through.
624
625 #define LARGEST_RAD 1390.0f 
626 #define LARGEST_RAD_TIME 7.0f
627
628 #define SMALLEST_RAD 15.0f
629 #define SMALLEST_RAD_TIME 1.5f
630
631
632 static float shipfx_calculate_warp_time( object * objp )
633 {
634         // Find rad_percent from 0 to 1, 0 being smallest ship, 1 being largest
635         float rad_percent = (objp->radius-SMALLEST_RAD) / (LARGEST_RAD-SMALLEST_RAD);
636         if ( rad_percent < 0.0f ) {
637                 rad_percent = 0.0f;
638         } else if ( rad_percent > 1.0f )        {
639                 rad_percent = 1.0f;
640         }
641         float rad_time = rad_percent*(LARGEST_RAD_TIME-SMALLEST_RAD_TIME) + SMALLEST_RAD_TIME;
642
643         return rad_time;
644 }
645
646 // calculate warp speed
647 float shipfx_calculate_warp_speed(object *objp)
648 {
649         float length;
650
651         Assert(objp->type == OBJ_SHIP);
652         if (objp->type != OBJ_SHIP) {
653                 length = 2.0f * objp->radius;
654         } else {
655                 length = ship_get_length(&Ships[objp->instance]);
656         }
657         return length / shipfx_calculate_warp_time(objp);
658 }
659
660
661 // This is called to actually warp this object in
662 // after all the flashy fx are done, or if the flashy 
663 // fx don't work for some reason.
664 void shipfx_actually_warpin(    ship *shipp, object *objp )
665 {
666         shipp->flags &= (~SF_ARRIVING_STAGE_1);
667         shipp->flags &= (~SF_ARRIVING_STAGE_2);
668
669         // let physics in on it too.
670         objp->phys_info.flags &= (~PF_WARP_IN);
671 }
672
673 // JAS - code to start the ship doing the warp in effect
674 // This also starts the animating 3d effect playing.
675 // There are two modes, stage 1 and stage 2.   Stage 1 is
676 // when the ship just invisibly waits for a certain time
677 // period after the effect starts, and then stage 2 begins,
678 // where the ships flies through the effect at a set
679 // velocity so it gets through in a certain amount of
680 // time.
681 void shipfx_warpin_start( object *objp )
682 {
683         ship *shipp;
684         float effect_time, effect_radius;
685         
686         shipp = &Ships[objp->instance];
687
688         if ( shipp->flags & SF_ARRIVING )       {
689                 mprintf(( "Ship is already arriving!\n" ));
690                 return;
691         }
692
693         // post a warpin event
694         if(Game_mode & GM_DEMO_RECORD){
695                 demo_POST_warpin(objp->signature, shipp->flags);
696         }
697
698         // if there is no arrival warp, then skip the whole thing
699         if ( shipp->flags & SF_NO_ARRIVAL_WARP )        {
700                 shipfx_actually_warpin(shipp,objp);
701                 return;
702         }
703         
704         // VALIDATE special_warp_objnum
705         if (shipp->special_warp_objnum >= 0) {
706                         
707                 int ref_objnum = shipp->special_warp_objnum;
708                 int valid_reference_ship = FALSE;
709
710                 // Validate reference_objnum
711                 if ((ref_objnum >= 0) && (ref_objnum < MAX_OBJECTS)) {
712                         object *sp_objp = &Objects[ref_objnum];
713                         if (sp_objp->type == OBJ_SHIP) {
714                                 if (Ship_info[Ships[sp_objp->instance].ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
715                                         valid_reference_ship = TRUE;
716                                 }
717                         }
718                 }
719
720                 if (valid_reference_ship != TRUE) {
721                         shipp->special_warp_objnum = -1;
722                 }
723         }
724
725         // only move warp effect pos if not special warp in.
726         if (shipp->special_warp_objnum >= 0) {
727                 Assert(!(Game_mode & GM_MULTIPLAYER));
728                 polymodel *pm;
729                 pm = model_get(shipp->modelnum);
730                 vm_vec_scale_add(&shipp->warp_effect_pos, &objp->pos, &objp->orient.v.fvec, -pm->mins.xyz.z);
731         } else {
732                 vm_vec_scale_add( &shipp->warp_effect_pos, &objp->pos, &objp->orient.v.fvec, objp->radius );
733         }
734         
735         // The ending zero mean this is a warp-in effect
736         if ( !(shipp->flags & SF_INITIALLY_DOCKED) ) {
737                 int warp_objnum;
738
739                 // Effect time is 'SHIPFX_WARP_DELAY' (1.5 secs) seconds to start, 'shipfx_calculate_warp_time' 
740                 // for ship to go thru, and 'SHIPFX_WARP_DELAY' (1.5 secs) to go away.
741                 effect_time = shipfx_calculate_warp_time(objp) + SHIPFX_WARP_DELAY + SHIPFX_WARP_DELAY;
742                 effect_radius = shipfx_calculate_effect_radius(objp);
743
744                 // maybe special warpin
745                 if (shipp->special_warp_objnum >= 0) {
746                         // cap radius to size of knossos
747                         effect_radius = min(effect_radius, 0.8f*Objects[shipp->special_warp_objnum].radius);
748                         warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_KNOSSOS_EFFECT, shipp->special_warp_objnum, effect_radius, 0, NULL, effect_time, shipp->ship_info_index);
749                 } else {
750                         warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_WARP_EFFECT, OBJ_INDEX(objp), effect_radius, 0, NULL, effect_time, shipp->ship_info_index);
751                 }
752                 if (warp_objnum < 0 )   {       // JAS: This must always be created, if not, just warp the ship in
753                         shipfx_actually_warpin(shipp,objp);
754                         return;
755                 }
756
757                 shipp->warp_effect_fvec = Objects[warp_objnum].orient.v.fvec;
758                 // maybe negate if special warp effect
759                 if (shipp->special_warp_objnum >= 0) {
760                         if (vm_vec_dotprod(&shipp->warp_effect_fvec, &objp->orient.v.fvec) < 0) {
761                                 vm_vec_negate(&shipp->warp_effect_fvec);
762                         }
763                 }
764
765
766                 shipp->final_warp_time = timestamp(fl2i(SHIPFX_WARP_DELAY*1000.0f));
767                 shipp->flags |= SF_ARRIVING_STAGE_1;
768
769                 // see if this ship is docked with anything, and if so, make docked ship be "arriving"
770                 /*
771                 if ( Ai_info[shipp->ai_index].dock_objnum != -1 ) {
772                         Ships[Ai_info[shipp->ai_index].dock_objnum].final_warp_time = timestamp(fl2i(warp_time*1000.0f));
773                         Ships[Ai_info[shipp->ai_index].dock_objnum].flags |= SF_ARRIVING_STAGE_1;
774                 }
775                 */
776         }
777 }
778
779 void shipfx_warpin_frame( object *objp, float frametime )
780 {
781         ship *shipp;
782
783         shipp = &Ships[objp->instance];
784
785         if ( shipp->flags & SF_DYING ) return;
786
787         if ( shipp->flags & SF_ARRIVING_STAGE_1 )       {
788                 if ( timestamp_elapsed(shipp->final_warp_time) ) {
789
790                         // let physics know the ship is going to warp in.
791                         objp->phys_info.flags |= PF_WARP_IN;
792
793                         // done doing stage 1 of warp, so go on to stage 2
794                         shipp->flags &= (~SF_ARRIVING_STAGE_1);
795                         shipp->flags |= SF_ARRIVING_STAGE_2;
796
797                         float warp_time = shipfx_calculate_warp_time(objp);
798                         float speed = shipfx_calculate_warp_speed(objp);                        // How long it takes to move through warp effect
799
800                         // Make ship move at velocity so that it moves two radius's in warp_time seconds.
801                         vector vel;
802                         vel = objp->orient.v.fvec;
803                         vm_vec_scale( &vel, speed );
804                         objp->phys_info.vel = vel;
805                         objp->phys_info.desired_vel = vel;
806                         objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
807                         objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
808                         objp->phys_info.prev_ramp_vel.xyz.z = speed;
809                         objp->phys_info.forward_thrust = 0.0f;          // How much the forward thruster is applied.  0-1.
810
811                         shipp->final_warp_time = timestamp(fl2i(warp_time*1000.0f));
812
813                         /*
814                         // see if this ship is docked with anything, and if so, make docked ship be "arriving"
815                         if ( Ai_info[shipp->ai_index].dock_objnum != -1 ) {
816                                 Ships[Ai_info[shipp->ai_index].dock_objnum].flags &= (~SF_ARRIVING_STAGE_1);
817                                 Ships[Ai_info[shipp->ai_index].dock_objnum].flags |= SF_ARRIVING_STAGE_2;
818                                 Ships[Ai_info[shipp->ai_index].dock_objnum].final_warp_time = timestamp(fl2i(warp_time*1000.0f));
819                         }
820                         */
821                 } 
822         } else if ( shipp->flags & SF_ARRIVING_STAGE_2 )        {
823                 if ( timestamp_elapsed(shipp->final_warp_time) ) {
824                         // done doing stage 2 of warp, so turn off arriving flag
825                         shipfx_actually_warpin(shipp,objp);
826
827                         // notify physics to slow down
828                         if (Ship_info[shipp->ship_info_index].flags & SIF_SUPERCAP) {
829                                 // let physics know this is a special warp in
830                                 objp->phys_info.flags |= PF_SPECIAL_WARP_IN;
831                         }
832                 }
833         }
834
835 }
836  
837 // This is called to actually warp this object out
838 // after all the flashy fx are done, or if the flashy 
839 // fx don't work for some reason.  OR to skip the flashy
840 // fx.
841 void shipfx_actually_warpout( ship *shipp, object *objp )
842 {
843         // Once we get through effect, make the ship go away
844
845         if ( objp == Player_obj )       {
846                 // Normally, this will never get called for the player. If it
847                 // does, it is because some error (like the warpout effect
848                 // couldn't start) so go ahead an warp the player out.
849                 // All this does is set the event to go to debriefing, the
850                 // same thing that happens after the player warp out effect
851                 // ends.
852                 gameseq_post_event( GS_EVENT_DEBRIEF ); // proceed to debriefing
853         } else {
854                 object *docked_objp;
855                 
856                 // Code for objects except player ship warping out
857                 objp->flags |= OF_SHOULD_BE_DEAD;
858                 // check to see if departing ship is docked with anything and if so, mark that object
859                 // gone as well
860                 docked_objp = ai_find_docked_object( objp );
861                 if ( docked_objp ) {
862                         docked_objp->flags |= OF_SHOULD_BE_DEAD;
863                 }
864
865                 ship_departed( objp->instance );
866                 if ( docked_objp ){
867                         ship_departed( docked_objp->instance );
868                 }
869         }
870 }
871
872 // compute_special_warpout_stuff();
873 int compute_special_warpout_stuff(object *objp, float *speed, float *warp_time, vector *warp_pos)
874 {
875         object  *sp_objp = NULL;
876         ship            *shipp;
877         int             valid_refenence_ship = FALSE, ref_objnum;
878         vector  facing_normal, vec_to_knossos;
879         float           dist_to_plane;
880
881         // knossos warpout only valid in single player
882         if (Game_mode & GM_MULTIPLAYER) {
883                 mprintf(("special warpout only for single player\n"));
884                 return -1;
885         }
886
887         // find special warp ship reference
888         valid_refenence_ship = FALSE;
889         ref_objnum = Ships[objp->instance].special_warp_objnum;
890
891         // Validate reference_objnum
892         if ((ref_objnum >= 0) && (ref_objnum < MAX_OBJECTS)) {
893                 sp_objp = &Objects[ref_objnum];
894                 if (sp_objp->type == OBJ_SHIP) {
895                         shipp = &Ships[sp_objp->instance];
896                         if (Ship_info[shipp->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
897                                 valid_refenence_ship = TRUE;
898                         }
899                 }
900         }
901         
902         if (!valid_refenence_ship) {
903                 Int3();
904                 mprintf(("special warpout reference ship not found\n"));
905                 return -1;
906         }
907
908         // get facing normal from knossos
909         vm_vec_sub(&vec_to_knossos, &sp_objp->pos, &objp->pos);
910         facing_normal = sp_objp->orient.v.fvec;
911         if (vm_vec_dotprod(&vec_to_knossos, &sp_objp->orient.v.fvec) > 0) {
912                 vm_vec_negate(&facing_normal);
913         }
914
915         // find position to play the warp ani..
916         dist_to_plane = fvi_ray_plane(warp_pos, &sp_objp->pos, &facing_normal, &objp->pos, &objp->orient.v.fvec, 0.0f);
917
918         // calculate distance to warpout point.
919         polymodel *pm = model_get(Ships[objp->instance].modelnum);
920         dist_to_plane += pm->mins.xyz.z;
921
922         if (dist_to_plane < 0) {
923                 mprintf(("warpout started too late\n"));
924                 return -1;
925         }
926
927         // validate angle
928         float max_warpout_angle = 0.707f;       // 45 degree half-angle cone for small ships
929         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
930                 max_warpout_angle = 0.866f;     // 30 degree half-angle cone for BIG or HUGE
931         }
932
933         if (-vm_vec_dotprod(&objp->orient.v.fvec, &facing_normal) < max_warpout_angle) {        // within allowed angle
934                 Int3();
935                 mprintf(("special warpout angle exceeded\n"));
936                 return -1;
937         }
938
939         // Calculate speed needed to get 
940         *speed = shipfx_calculate_warp_speed(objp);
941         
942         // Calculate how long to fly through the effect.  Not to get to the effect, just through it.
943         *warp_time = shipfx_calculate_warp_time(objp);
944         *warp_time += dist_to_plane / *speed;
945
946         return 0;
947 }
948
949
950 void compute_warpout_stuff(object *objp, float *speed, float *warp_time, vector *warp_pos)
951 {
952         // If we're warping through the knossos, do something different.
953         if (Ships[objp->instance].special_warp_objnum >= 0) {
954                 if (compute_special_warpout_stuff(objp, speed, warp_time, warp_pos) != -1) {
955                         return;
956                 } else {
957                         mprintf(("Invalid special warp\n"));
958                 }
959         }
960
961         object  *docked_objp = ai_find_docked_object( objp );
962         vector  center_pos = objp->pos;
963         float           radius, ship_move_dist, warp_dist;
964
965         radius = objp->radius;
966
967         //      If ship is docked then center wormhold about their center and make radius large enough.
968         if ( docked_objp ) {
969                 vm_vec_avg(&center_pos, &objp->pos, &docked_objp->pos);
970                 radius += docked_objp->radius;
971         }
972
973         // Calculate how long to fly through the effect.  Not to get to the effect, just through it.
974         *warp_time = shipfx_calculate_warp_time(objp);
975
976         // Pick some speed at which we want to go through the warp effect.  
977         // This is determined by shipfx_calculate_warp_time specifying how long
978         // it should take to go through the effect, or 2R.
979         *speed = shipfx_calculate_warp_speed(objp);
980
981         if ( objp == Player_obj )       {
982                 *speed = 0.8f*objp->phys_info.max_vel.xyz.z;
983         }
984
985         // Now we know our speed. Figure out how far the warp effect will be from here.  
986         ship_move_dist = (*speed * SHIPFX_WARP_DELAY) + radius*1.5f;            // We want to get to 1.5R away from effect
987         if ( ship_move_dist < radius*1.5f ) {
988                 ship_move_dist = radius*1.5f;
989         }
990
991         // If this is a huge ship, set the distance to the length of the ship
992         if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
993                 ship_move_dist = 0.5f * ship_get_length(&Ships[objp->instance]);
994         }
995
996         // Acount for time to get to warp effect, before we actually go through it.
997         *warp_time += ship_move_dist / *speed;
998
999         warp_dist = ship_move_dist;
1000         // allow for off center
1001         if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
1002                 polymodel *pm = model_get(Ships[objp->instance].modelnum);
1003                 warp_dist -= pm->mins.xyz.z;
1004         }
1005
1006         vm_vec_scale_add( warp_pos, &center_pos, &objp->orient.v.fvec, warp_dist );
1007 }
1008
1009 // JAS - code to start the ship doing the warp out effect
1010 // This puts the ship into a mode specified by SF_DEPARTING
1011 // where it flies forward for a set time period at a set
1012 // velocity, then disappears when that time is reached.  This
1013 // also starts the animating 3d effect playing.
1014 void shipfx_warpout_start( object *objp )
1015 {
1016         float warp_time;
1017         ship *shipp;
1018         shipp = &Ships[objp->instance];
1019
1020         if (    shipp->flags & SF_DEPART_WARP ) {
1021                 mprintf(( "Ship is already departing!\n" ));
1022                 return;
1023         }
1024
1025         // if we're dying return
1026         if ( shipp->flags & SF_DYING ) {
1027                 return;
1028         }
1029
1030         // if we're HUGE, keep alive - set guardian
1031         if (Ship_info[shipp->ship_info_index].flags & SIF_HUGE_SHIP) {
1032                 objp->flags |= OF_GUARDIAN;
1033         }
1034
1035         // post a warpin event
1036         if(Game_mode & GM_DEMO_RECORD){
1037                 demo_POST_warpout(objp->signature, shipp->flags);
1038         }
1039
1040         // don't send ship depart packets for player ships
1041         if ( (MULTIPLAYER_MASTER) && !(objp->flags & OF_PLAYER_SHIP) ){
1042                 send_ship_depart_packet( objp );
1043         }
1044
1045         // don't do departure wormhole if ship flag is set which indicates no effect
1046         if ( shipp->flags & SF_NO_DEPARTURE_WARP ) {
1047                 // DKA 5/25/99 If he's going to warpout, set it.  
1048                 // Next line fixes assert in wing cleanup code when no warp effect.
1049                 shipp->flags |= SF_DEPART_WARP;
1050
1051                 shipfx_actually_warpout(shipp, objp);
1052                 return;
1053         }
1054
1055         if ( objp == Player_obj )       {
1056                 HUD_printf(XSTR( "Subspace node activated", 498) );
1057         }
1058
1059         float   speed, effect_time, effect_radius;
1060         vector  warp_pos;
1061         // warp time from compute warpout stuff includes time to get up to warp_pos
1062         compute_warpout_stuff(objp, &speed, &warp_time, &warp_pos);
1063         shipp->warp_effect_pos = warp_pos;
1064
1065         // The ending one means this is a warp-out effect
1066         int warp_objnum;
1067         // Effect time is 'SHIPFX_WARP_DELAY' (1.5 secs) seconds to start, 'shipfx_calculate_warp_time' 
1068         // for ship to go thru, and 'SHIPFX_WARP_DELAY' (1.5 secs) to go away.
1069         // effect_time = shipfx_calculate_warp_time(objp) + SHIPFX_WARP_DELAY + SHIPFX_WARP_DELAY;
1070         effect_time = warp_time + SHIPFX_WARP_DELAY;
1071         effect_radius = shipfx_calculate_effect_radius(objp);
1072
1073         // maybe special warpout
1074         if (shipp->special_warp_objnum >= 0) {
1075                 // cap radius to size of knossos
1076                 effect_radius = min(effect_radius, 0.8f*Objects[shipp->special_warp_objnum].radius);
1077                 warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_KNOSSOS_EFFECT, shipp->special_warp_objnum, effect_radius, 1, NULL, effect_time, shipp->ship_info_index);
1078         } else {
1079                 warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_WARP_EFFECT, OBJ_INDEX(objp), effect_radius, 1, NULL, effect_time, shipp->ship_info_index);
1080         }
1081         if (warp_objnum < 0 )   {       // JAS: This must always be created, if not, just warp the ship in
1082                 shipfx_actually_warpout(shipp,objp);
1083                 return;
1084         }
1085
1086         shipp->warp_effect_fvec = Objects[warp_objnum].orient.v.fvec;
1087         // maybe negate if special warp effect
1088         if (shipp->special_warp_objnum >= 0) {
1089                 if (vm_vec_dotprod(&shipp->warp_effect_fvec, &objp->orient.v.fvec) > 0) {
1090                         vm_vec_negate(&shipp->warp_effect_fvec);
1091                 }
1092         }
1093
1094         // Make the warp effect stage 1 last SHIP_WARP_TIME1 seconds.
1095         if ( objp == Player_obj )       {
1096                 warp_time = fireball_lifeleft(&Objects[warp_objnum]);
1097                 shipp->final_warp_time = timestamp(fl2i(warp_time*1000.0f));
1098         } else {
1099                 shipp->final_warp_time = timestamp(fl2i(warp_time*2.0f*1000.0f));
1100         }
1101         shipp->flags |= SF_DEPART_WARP;
1102
1103 //      mprintf(( "Warp time = %.4f , effect time = %.4f ms\n", warp_time*1000.0f, effect_time ));
1104
1105         // This is a hack to make the ship go at the right speed to go from it's current position to the warp_effect_pos;
1106         
1107         // Set ship's velocity to 'speed'
1108         // This should actually be an AI that flies from the current
1109         // position through 'shipp->warp_effect_pos' in 'warp_time'
1110         // and keeps going 
1111         if ( objp != Player_obj )       {
1112                 vector vel;
1113                 vel = objp->orient.v.fvec;
1114                 vm_vec_scale( &vel, speed );
1115                 objp->phys_info.vel = vel;
1116                 objp->phys_info.desired_vel = vel;
1117                 objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
1118                 objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
1119                 objp->phys_info.prev_ramp_vel.xyz.z = speed;
1120                 objp->phys_info.forward_thrust = 1.0f;          // How much the forward thruster is applied.  0-1.
1121
1122                 // special case for HUGE ships
1123                 if (Ship_info[shipp->ship_info_index].flags & SIF_HUGE_SHIP) {
1124 //                      objp->phys_info.flags |= PF_SPECIAL_WARP_OUT;
1125                 }
1126         }
1127
1128 }
1129
1130 void shipfx_warpout_frame( object *objp, float frametime )
1131 {
1132         ship *shipp;
1133         shipp = &Ships[objp->instance];
1134
1135         if ( shipp->flags & SF_DYING ) return;
1136
1137         vector tempv;
1138         float warp_pos; // position of warp effect in object's frame of reference
1139
1140         vm_vec_sub( &tempv, &objp->pos, &shipp->warp_effect_pos );
1141         warp_pos = -vm_vec_dot( &tempv, &shipp->warp_effect_fvec );
1142
1143
1144         // Find the closest point on line from center of wormhole
1145         vector pos;
1146         float dist;
1147
1148         fvi_ray_plane(&pos,&objp->pos,&shipp->warp_effect_fvec,&shipp->warp_effect_pos, &shipp->warp_effect_fvec, 0.0f );
1149         dist = vm_vec_dist( &pos, &objp->pos );
1150
1151 //      mprintf(( "Warp pos = %.1f, rad=%.1f, center dist = %.1f\n", warp_pos, objp->radius, dist ));
1152
1153         if ( objp == Player_obj )       {
1154                 // Code for player warpout frame
1155
1156                 if ( (Player->control_mode==PCM_WARPOUT_STAGE2) && (warp_pos > objp->radius) )  {
1157                         gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_DONE_STAGE2 );
1158                 }
1159
1160                 if ( timestamp_elapsed(shipp->final_warp_time) ) {
1161
1162                         // Something went wrong... oh well, warp him out anyway.
1163                         if ( Player->control_mode != PCM_WARPOUT_STAGE3 )       {
1164                                 mprintf(( "Hmmm... player ship warpout time elapsed, but he wasn't in warp stage 3.\n" ));
1165                         }
1166
1167                         gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_DONE );
1168                         ship_departed( objp->instance );                                                                // mark log entry for the player
1169                 }
1170
1171         } else {
1172                 // Code for all non-player ships warpout frame
1173
1174                 int timed_out = timestamp_elapsed(shipp->final_warp_time);
1175                 if ( timed_out )        {
1176 //                      mprintf(("Frame %i: Ship %s missed departue cue.\n", Framecount, shipp->ship_name ));
1177                         int     delta_ms = timestamp_until(shipp->final_warp_time);
1178                         if (delta_ms > 1000.0f * frametime ) {
1179                                 nprintf(("AI", "Frame %i: Ship %s missed departue cue by %7.3f seconds.\n", Framecount, shipp->ship_name, - (float) delta_ms/1000.0f));
1180                         }
1181                 }
1182
1183                 // MWA 10/21/97 -- added shipp->flags & SF_NO_DEPARTURE_WARP part of next if statement.  For ships
1184                 // that don't get a wormhole effect, I wanted to drop into this code immediately.
1185                 if ( (warp_pos > objp->radius)  || (shipp->flags & SF_NO_DEPARTURE_WARP) || timed_out ) {
1186                         shipfx_actually_warpout( shipp, objp );
1187                 } 
1188         }
1189 }
1190
1191
1192 //==================================================
1193 // Stuff for keeping track of which ships are in
1194 // whose shadows.
1195
1196
1197 // Given point p0, in object's frame of reference, find if 
1198 // it can see the sun.
1199 int shipfx_point_in_shadow( vector *p0, matrix *src_orient, vector *src_pos, float radius )
1200 {
1201         mc_info mc;
1202         object *objp;
1203         ship_obj *so;
1204         ship *shipp;
1205         int n_lights;
1206         int idx;
1207
1208         vector rp0, rp1;
1209
1210         vector light_dir;
1211
1212         // Move rp0 into world coordinates      
1213         vm_vec_unrotate(&rp0, p0, src_orient);
1214         vm_vec_add2(&rp0, src_pos);
1215
1216         // get the # of global lights
1217         n_lights = light_get_global_count();
1218         
1219         for(idx=0; idx<n_lights; idx++){
1220                 // get the light dir for this light
1221                 light_get_global_dir(&light_dir, idx);
1222
1223                 // Find rp1
1224                 vm_vec_scale_add( &rp1, &rp0, &light_dir, 10000.0f );
1225
1226                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) )    {
1227                         objp = &Objects[so->objnum];
1228                         shipp = &Ships[objp->instance];
1229
1230                         mc.model_num = shipp->modelnum;
1231                         mc.orient = &objp->orient;
1232                         mc.pos = &objp->pos;
1233                         mc.p0 = &rp0;
1234                         mc.p1 = &rp1;
1235                         mc.flags = MC_CHECK_MODEL;      
1236
1237                         if ( model_collide(&mc) ){
1238                                 return 1;
1239                         }
1240                 }
1241         }
1242
1243         // not in shadow
1244         return 0;
1245 }
1246
1247
1248 // Given an ship see if it is in a shadow.
1249 int shipfx_in_shadow( object * src_obj )
1250 {
1251         mc_info mc;
1252         object *objp;
1253         ship_obj *so;
1254         ship *shipp;
1255         int n_lights;
1256         int idx;
1257
1258         vector rp0, rp1;
1259         vector light_dir;
1260
1261         rp0 = src_obj->pos;
1262         
1263         // get the # of global lights
1264         n_lights = light_get_global_count();
1265
1266         for(idx=0; idx<n_lights; idx++){
1267                 // get the direction for this light
1268                 light_get_global_dir(&light_dir, idx);
1269
1270                 // Find rp1
1271                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) )    {
1272                         objp = &Objects[so->objnum];
1273
1274                         if ( src_obj != objp )  {
1275                                 shipp = &Ships[objp->instance];
1276
1277                                 vm_vec_scale_add( &rp1, &rp0, &light_dir, objp->radius*10.0f );
1278
1279                                 mc.model_num = shipp->modelnum;
1280                                 mc.orient = &objp->orient;
1281                                 mc.pos = &objp->pos;
1282                                 mc.p0 = &rp0;
1283                                 mc.p1 = &rp1;
1284                                 mc.flags = MC_CHECK_MODEL;      
1285
1286         //                      mc.flags |= MC_CHECK_SPHERELINE;
1287         //                      mc.radius = src_obj->radius;
1288
1289                                 if ( model_collide(&mc) )       {
1290                                         return 1;
1291                                 }
1292                         }
1293                 }
1294         }
1295
1296         // not in shadow
1297         return 0;
1298 }
1299
1300 // Given world point see if it is in a shadow.
1301 int shipfx_eye_in_shadow( vector *eye_pos, object * src_obj, int sun_n )
1302 {
1303         mc_info mc;
1304         object *objp;
1305         ship_obj *so;
1306         ship *shipp;    
1307
1308         vector rp0, rp1;
1309         vector light_dir;
1310
1311         rp0 = *eye_pos; 
1312         
1313         // get the light dir
1314         if(!light_get_global_dir(&light_dir, sun_n)){
1315                 return 0;
1316         }
1317
1318         // Find rp1
1319         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) )    {
1320                 objp = &Objects[so->objnum];
1321
1322                 if ( src_obj != objp )  {
1323                         shipp = &Ships[objp->instance];
1324
1325                         vm_vec_scale_add( &rp1, &rp0, &light_dir, objp->radius*10.0f );
1326
1327                         ship_model_start(objp);
1328
1329                         mc.model_num = shipp->modelnum;
1330                         mc.orient = &objp->orient;
1331                         mc.pos = &objp->pos;
1332                         mc.p0 = &rp0;
1333                         mc.p1 = &rp1;
1334                         mc.flags = MC_CHECK_MODEL;      
1335
1336         //                      mc.flags |= MC_CHECK_SPHERELINE;
1337         //                      mc.radius = src_obj->radius;
1338
1339                         int hit = model_collide(&mc);
1340
1341                         ship_model_stop(objp);
1342
1343                         if (hit) {
1344                                 return 1;
1345                         }
1346                 }
1347         }
1348
1349         // Check all the big hull debris pieces.
1350         debris  *db = Debris;
1351
1352         int i;
1353         for ( i = 0; i < MAX_DEBRIS_PIECES; i++, db++ ) {
1354                 if ( !(db->flags & DEBRIS_USED) || !db->is_hull ){
1355                         continue;
1356                 }
1357
1358                 objp = &Objects[db->objnum];
1359
1360                 vm_vec_scale_add( &rp1, &rp0, &light_dir, objp->radius*10.0f );
1361
1362                 mc.model_num = db->model_num;   // Fill in the model to check
1363                 mc.submodel_num = db->submodel_num;
1364                 model_clear_instance( mc.model_num );
1365                 mc.orient = &objp->orient;                                      // The object's orient
1366                 mc.pos = &objp->pos;                                                    // The object's position
1367                 mc.p0 = &rp0;                           // Point 1 of ray to check
1368                 mc.p1 = &rp1;                                   // Point 2 of ray to check
1369                 mc.flags = (MC_CHECK_MODEL | MC_SUBMODEL);
1370
1371                 if (model_collide(&mc)) {
1372                         return 1;
1373                 }
1374         }       
1375
1376         // not in shadow
1377         return 0;
1378 }
1379
1380 //=====================================================================================
1381 // STUFF FOR DOING SHIP GUN FLASHES
1382 //=====================================================================================
1383
1384 #define MAX_FLASHES     128                     // How many flashes total
1385 #define FLASH_LIFE_PRIMARY              0.25f                   // How long flash lives
1386 #define FLASH_LIFE_SECONDARY    0.50f                   // How long flash lives
1387
1388
1389 typedef struct ship_flash {
1390         int     objnum;                                 // object number of parent ship
1391         int     obj_signature;                  // signature of that object
1392         int     light_num;                              // which light in the model this uses
1393         float   life;                                           // how long this should be around
1394         float max_life;                         // how long this has been around.
1395 } ship_flash;
1396
1397 int Ship_flash_inited = 0;
1398 int Ship_flash_highest = -1;
1399 ship_flash Ship_flash[MAX_FLASHES];
1400
1401 // Resets the ship flash stuff. Call before each level.
1402 void shipfx_flash_init()
1403 {
1404         int i;
1405         
1406         for (i=0; i<MAX_FLASHES; i++ )  {
1407                 Ship_flash[i].objnum = -1;                      // mark as unused
1408         }
1409         Ship_flash_highest = -1;
1410         Ship_flash_inited = 1;  
1411 }
1412
1413
1414 // Given that a ship fired a weapon, light up the model
1415 // accordingly.
1416 void shipfx_flash_create(object *objp, ship * shipp, vector *gun_pos, vector *gun_dir, int is_primary, int weapon_info_index)
1417 {
1418         int i;
1419         int objnum = OBJ_INDEX(objp);
1420
1421         Assert(Ship_flash_inited);
1422
1423         polymodel *pm = model_get( shipp->modelnum );
1424         int closest_light = -1;
1425         float d, closest_dist = 0.0f;
1426
1427         // ALWAYS do this - since this is called once per firing
1428         // if this is a cannon type weapon, create a muzzle flash
1429         // HACK - let the flak guns do this on their own since they fire so quickly
1430         if((Weapon_info[weapon_info_index].wi_flags & WIF_MFLASH) && !(Weapon_info[weapon_info_index].wi_flags & WIF_FLAK)){
1431                 // spiffy new flash stuff
1432                 mflash_create(gun_pos, gun_dir, Weapon_info[weapon_info_index].muzzle_flash);           
1433         }
1434
1435         if ( pm->num_lights < 1 ) return;
1436
1437         for (i=0; i<pm->num_lights; i++ )       {
1438                 d = vm_vec_dist( &pm->lights[i].pos, gun_pos );
1439         
1440                 if ( pm->lights[i].type == BSP_LIGHT_TYPE_WEAPON ) {
1441                         if ( (closest_light==-1) || (d<closest_dist) )  {
1442                                 closest_light = i;
1443                                 closest_dist = d;
1444                         }
1445                 }
1446         }
1447
1448         if ( closest_light == -1 ) return;
1449
1450         int first_slot = -1;
1451
1452         for (i=0; i<=Ship_flash_highest; i++ )  {
1453                 if ( (first_slot==-1) && (Ship_flash[i].objnum < 0) )   {
1454                         first_slot = i;
1455                 }
1456
1457                 if ( (Ship_flash[i].objnum == objnum) && (Ship_flash[i].obj_signature==objp->signature) )       {
1458                         if ( Ship_flash[i].light_num == closest_light ) {
1459                                 // This is already flashing!
1460                                 Ship_flash[i].life = 0.0f;
1461                                 if ( is_primary )       {
1462                                         Ship_flash[i].max_life = FLASH_LIFE_PRIMARY;
1463                                 } else {
1464                                         Ship_flash[i].max_life = FLASH_LIFE_SECONDARY;
1465                                 }
1466                                 return;
1467                         }
1468                 }
1469         }
1470
1471         if ( first_slot == -1 ) {
1472                 if ( Ship_flash_highest < MAX_FLASHES-1 )       {
1473                         Ship_flash_highest++;
1474                         first_slot = Ship_flash_highest;
1475                 } else {
1476                         //mprintf(( "SHIP_FLASH: Out of flash spots!\n" ));
1477                         return;         // out of flash slots
1478                 }
1479         }
1480
1481         Assert( Ship_flash[first_slot].objnum == -1 );
1482
1483         Ship_flash[first_slot].objnum = objnum;
1484         Ship_flash[first_slot].obj_signature = objp->signature;
1485         Ship_flash[first_slot].life = 0.0f;             // Start it up
1486         if ( is_primary )       {
1487                 Ship_flash[first_slot].max_life = FLASH_LIFE_PRIMARY;
1488         } else {
1489                 Ship_flash[first_slot].max_life = FLASH_LIFE_SECONDARY;
1490         }
1491         Ship_flash[first_slot].light_num = closest_light;               
1492 }
1493
1494 // Sets the flash lights in the model used by this
1495 // ship to the appropriate values.  There might not
1496 // be any flashes linked to this ship in which
1497 // case this function does nothing.
1498 void shipfx_flash_light_model( object *objp, ship * shipp )
1499 {
1500         int i, objnum = OBJ_INDEX(objp);
1501         polymodel *pm = model_get( shipp->modelnum );
1502
1503         for (i=0; i<=Ship_flash_highest; i++ )  {
1504                 if ( (Ship_flash[i].objnum == objnum) && (Ship_flash[i].obj_signature==objp->signature) )       {
1505                         float v = (Ship_flash[i].max_life - Ship_flash[i].life)/Ship_flash[i].max_life;
1506
1507                         pm->lights[Ship_flash[i].light_num].value += v / 255.0f;
1508                 }
1509         }
1510
1511 }
1512
1513 // Does whatever processing needs to be done each frame.
1514 void shipfx_flash_do_frame(float frametime)
1515 {
1516         ship_flash *sf;
1517         int kill_it = 0;
1518         int i;
1519
1520         for (i=0, sf = &Ship_flash[0]; i<=Ship_flash_highest; i++, sf++ )       {
1521                 if ( sf->objnum > -1 )  {
1522                         if ( Objects[sf->objnum].signature != sf->obj_signature )       {
1523                                 kill_it = 1;
1524                         }
1525                         sf->life += frametime;
1526                         if ( sf->life >= sf->max_life ) kill_it = 1;
1527
1528                         if (kill_it) {
1529                                 sf->objnum = -1;
1530                                 if ( i == Ship_flash_highest )  {
1531                                         while( (Ship_flash_highest>0) && (Ship_flash[Ship_flash_highest].objnum == -1) )        {
1532                                                 Ship_flash_highest--;
1533                                         }
1534                                 }
1535                         }       
1536                 }
1537         }       
1538
1539 }
1540
1541 float Particle_width = 1.2f;
1542 DCF(particle_width, "Multiplier for angular width of the particle spew")
1543 {
1544         if ( Dc_command ) {
1545                 dc_get_arg(ARG_FLOAT);
1546                 if ( (Dc_arg_float >= 0 ) && (Dc_arg_float <= 5) ) {
1547                         Particle_width = Dc_arg_float;
1548                 } else {
1549                         dc_printf( "Illegal value for particle width. (Must be from 0-5) \n\n");
1550                 }
1551         }
1552 }
1553
1554 float Particle_number = 1.2f;
1555 DCF(particle_num, "Multiplier for the number of particles created")
1556 {
1557         if ( Dc_command ) {
1558                 dc_get_arg(ARG_FLOAT);
1559                 if ( (Dc_arg_float >= 0 ) && (Dc_arg_float <= 5) ) {
1560                         Particle_number = Dc_arg_float;
1561                 } else {
1562                         dc_printf( "Illegal value for particle num. (Must be from 0-5) \n\n");
1563                 }
1564         }
1565 }
1566
1567 float Particle_life = 1.2f;
1568 DCF(particle_life, "Multiplier for the lifetime of particles created")
1569 {
1570         if ( Dc_command ) {
1571                 dc_get_arg(ARG_FLOAT);
1572                 if ( (Dc_arg_float >= 0 ) && (Dc_arg_float <= 5) ) {
1573                         Particle_life = Dc_arg_float;
1574                 } else {
1575                         dc_printf( "Illegal value for particle life. (Must be from 0-5) \n\n");
1576                 }
1577         }
1578 }
1579
1580 // Make sparks fly off of ship n.
1581 // sn = spark number to spark, corrosponding to element in
1582 //      ship->hitpos array.  If this isn't -1, it is a just
1583 //      got hit by weapon spark, otherwise pick one randomally.
1584 void shipfx_emit_spark( int n, int sn )
1585 {
1586         int create_spark = 1;
1587         object * obj;
1588         vector outpnt;
1589         ship *shipp = &Ships[n];
1590         float ship_radius, spark_scale_factor;
1591         
1592         if ( shipp->num_hits <= 0 )
1593                 return;
1594
1595         // get radius of ship
1596         ship_radius = model_get_radius(Ship_info[shipp->ship_info_index].modelnum);
1597
1598         // get spark_scale_factor -- how much to increase ship sparks, based on radius
1599         if (ship_radius > 40) {
1600                 spark_scale_factor = 1.0f;
1601         } else if (ship_radius > 20) {
1602                 spark_scale_factor = (ship_radius - 20.0f) / 20.0f;
1603         } else {
1604                 spark_scale_factor = 0.0f;
1605         }
1606
1607         float spark_time_scale  = 1.0f + spark_scale_factor * (Particle_life   - 1.0f);
1608         float spark_width_scale = 1.0f + spark_scale_factor * (Particle_width  - 1.0f);
1609         float spark_num_scale   = 1.0f + spark_scale_factor * (Particle_number - 1.0f);
1610
1611         obj = &Objects[shipp->objnum];
1612         ship_info* si = &Ship_info[shipp->ship_info_index];
1613
1614         float hull_percent = obj->hull_strength / si->initial_hull_strength;
1615         if (hull_percent < 0.001) {
1616                 hull_percent = 0.001f;
1617         }
1618         float fraction = 0.1f * obj->radius / hull_percent;
1619         if (fraction > 1.0f) {
1620                 fraction = 1.0f;
1621         }
1622
1623         int spark_num;
1624         if ( sn == -1 ) {
1625                 spark_num = myrand() % shipp->num_hits;
1626         } else {
1627                 spark_num = sn;
1628         }
1629
1630         // don't display sparks that have expired
1631         if ( timestamp_elapsed(shipp->sparks[spark_num].end_time) ) {
1632                 return;
1633         }
1634
1635         // get spark position
1636         if (shipp->sparks[spark_num].submodel_num != -1) {
1637                 ship_model_start(obj);
1638                 model_find_world_point(&outpnt, &shipp->sparks[spark_num].pos, shipp->modelnum, shipp->sparks[spark_num].submodel_num, &obj->orient, &obj->pos);
1639                 ship_model_stop(obj);
1640         } else {
1641                 // rotate sparks correctly with current ship orient
1642                 vm_vec_unrotate(&outpnt, &shipp->sparks[spark_num].pos, &obj->orient);
1643                 vm_vec_add2(&outpnt,&obj->pos);
1644         }
1645
1646         if ( shipp->flags & (SF_ARRIVING|SF_DEPART_WARP) ) {
1647                 vector tmp;
1648                 vm_vec_sub( &tmp, &outpnt, &shipp->warp_effect_pos );
1649                 if ( vm_vec_dot( &tmp, &shipp->warp_effect_fvec ) < 0.0f )      {
1650                         // if in front of warp plane, don't create.
1651                         create_spark = 0;
1652                 }
1653         }
1654
1655         if ( create_spark )     {
1656
1657                 particle_emitter        pe;
1658
1659                 pe.pos = outpnt;                                // Where the particles emit from
1660
1661                 if ( shipp->flags & (SF_ARRIVING|SF_DEPART_WARP) ) {
1662                         // No velocity if going through warp.
1663                         pe.vel = vmd_zero_vector;
1664                 } else {
1665                         // Initial velocity of all the particles.
1666                         // 0.0f = 0% of parent's.
1667                         // 1.0f = 100% of parent's.
1668                         vm_vec_copy_scale( &pe.vel, &obj->phys_info.vel, 0.7f );
1669                 }
1670
1671                 // TODO: add velocity from rotation if submodel is rotating
1672                 // v_rot = w x r
1673
1674                 // r = outpnt - model_find_world_point(0)
1675
1676                 // w = model_find_world_dir(
1677                 // model_find_world_dir(&out_dir, &in_dir, model_num, submodel_num, &objorient, &objpos);
1678
1679                 vector tmp_norm, tmp_vel;
1680                 vm_vec_sub( &tmp_norm, &outpnt, &obj->pos );
1681                 vm_vec_normalize_safe(&tmp_norm);
1682
1683                 tmp_vel = obj->phys_info.vel;
1684                 if ( vm_vec_normalize_safe(&tmp_vel) > 1.0f )   {
1685                         vm_vec_scale_add2(&tmp_norm,&tmp_vel, -2.0f);
1686                         vm_vec_normalize_safe(&tmp_norm);
1687                 }
1688                                 
1689                 pe.normal = tmp_norm;                   // What normal the particle emit around
1690                 pe.normal_variance = 0.3f;              //      How close they stick to that normal 0=good, 1=360 degree
1691                 pe.min_rad = 0.20f;                             // Min radius
1692                 pe.max_rad = 0.50f;                             // Max radius
1693
1694                 // first time through - set up end time and make heavier initially
1695                 if ( sn > -1 )  {
1696                         // Sparks for first time at this spot
1697                         if (si->flags & SIF_FIGHTER) {
1698                                 if (hull_percent > 0.6f) {
1699                                         // sparks only once when hull > 60%
1700                                         float spark_duration = (float)pow(2.0f, -5.0f*(hull_percent-1.3f)) * (1.0f + 0.6f*(frand()-0.5f));      // +- 30%
1701                                         shipp->sparks[spark_num].end_time = timestamp( (int) (1000.0f * spark_duration) );
1702                                 } else {
1703                                         // spark never ends when hull < 60% (~277 hr)
1704                                         shipp->sparks[spark_num].end_time = timestamp( 100000000 );
1705                                 }
1706                         }
1707
1708                         if ( D3D_enabled ) {
1709                                 pe.num_low  = 25;                               // Lowest number of particles to create (hardware)
1710                                 pe.num_high = 30;                               // Highest number of particles to create (hardware)
1711                         } else {
1712                                 pe.num_low  = 5;                                // Lowest number of particles to create (software)
1713                                 pe.num_high = 7;                                // Highest number of particles to create (software)
1714                         }
1715                         pe.normal_variance = 1.0f;      //      How close they stick to that normal 0=good, 1=360 degree
1716                         pe.min_vel = 2.0f;                              // How fast the slowest particle can move
1717                         pe.max_vel = 12.0f;                             // How fast the fastest particle can move
1718                         pe.min_life = 0.05f;                            // How long the particles live
1719                         pe.max_life = 0.55f;                            // How long the particles live
1720
1721                         particle_emit( &pe, PARTICLE_FIRE, 0 );
1722                 } else {
1723
1724                         pe.min_rad = 0.7f;                              // Min radius
1725                         pe.max_rad = 1.3f;                              // Max radius
1726                         if ( D3D_enabled ) {
1727                                 pe.num_low  = int (20 * spark_num_scale);               // Lowest number of particles to create (hardware)
1728                                 pe.num_high = int (50 * spark_num_scale);               // Highest number of particles to create (hardware)
1729                         } else {
1730                                 pe.num_low  = 2;                        // Lowest number of particles to create (software)
1731                                 pe.num_high = 8;                // Highest number of particles to create (software)
1732                         }
1733                         pe.normal_variance = 0.2f * spark_width_scale;          //      How close they stick to that normal 0=good, 1=360 degree
1734                         pe.min_vel = 3.0f;                              // How fast the slowest particle can move
1735                         pe.max_vel = 12.0f;                             // How fast the fastest particle can move
1736                         pe.min_life = 0.35f*2.0f * spark_time_scale;            // How long the particles live
1737                         pe.max_life = 0.75f*2.0f * spark_time_scale;            // How long the particles live
1738                         
1739                         particle_emit( &pe, PARTICLE_SMOKE, 0 );
1740                 }
1741         }
1742
1743         // Select time to do next spark
1744 //      Ships[n].next_hit_spark = timestamp_rand(100,500);
1745         shipp->next_hit_spark = timestamp_rand(50,100);
1746 }
1747
1748
1749
1750 //=====================================================================================
1751 // STUFF FOR DOING LARGE SHIP EXPLOSIONS
1752 //=====================================================================================
1753
1754 int     Bs_exp_fire_low = 1;
1755 float   Bs_exp_fire_time_mult = 1.0f;
1756
1757 DCF_BOOL(bs_exp_fire_low, Bs_exp_fire_low)
1758 DCF(bs_exp_fire_time_mult, "Multiplier time between fireball in big ship explosion")
1759 {
1760         if ( Dc_command ) {
1761                 dc_get_arg(ARG_FLOAT);
1762                 if ( (Dc_arg_float >= 0.1 ) && (Dc_arg_float <= 5) ) {
1763                         Bs_exp_fire_time_mult = Dc_arg_float;
1764                 } else {
1765                         dc_printf( "Illegal value for bs_exp_fire_time_mult. (Must be from 0.1-5) \n\n");
1766                 }
1767         }
1768 }
1769
1770 #define MAX_SPLIT_SHIPS         3               // How many can explode at once.  Each one is about 1K.
1771
1772 #define DEBRIS_NONE                     0
1773 #define DEBRIS_DRAW                     1
1774 #define DEBRIS_FREE                     2
1775
1776 typedef struct clip_ship {
1777         object*                 parent_obj;
1778         float                   length_left;    // uncomsumed length
1779         matrix                  orient;
1780         physics_info    phys_info;
1781         vector                  local_pivot;                                                            // world center of mass position of half ship
1782         vector                  model_center_disp_to_orig_center;       // displacement from half ship center to original model center
1783         vector                  clip_plane_norm;                                                        // clip plane normal (local [0,0,1] or [0,0,-1])
1784         float                           cur_clip_plane_pt;                                              // displacement from half ship clip plane to original model center
1785         float                           explosion_vel;
1786         ubyte                           draw_debris[MAX_DEBRIS_OBJECTS];
1787         int                             next_fireball;
1788 } clip_ship;
1789
1790 typedef struct split_ship {
1791         int                             used;                                   // 0 if not used, 1 if used
1792         clip_ship               front_ship;
1793         clip_ship               back_ship;
1794         int                             explosion_flash_timestamp;
1795         int                             explosion_flash_started;
1796         int                             sound_handle[NUM_SUB_EXPL_HANDLES];
1797 } split_ship;
1798
1799
1800 static split_ship Split_ships[MAX_SPLIT_SHIPS];
1801 static int Split_ships_inited = 0;
1802
1803 static void split_ship_init_system()
1804 {
1805         int i;
1806         for (i=0; i<MAX_SPLIT_SHIPS; i++ )      {
1807                 Split_ships[i].used = 0;
1808         }
1809         Split_ships_inited = 1;
1810 }
1811
1812 static void maybe_fireball_wipe(clip_ship* half_ship, int* sound_handle);
1813 static void split_ship_init( ship* shipp, split_ship* split_ship )
1814 {
1815         object* parent_ship_obj = &Objects[shipp->objnum];
1816         matrix* orient = &parent_ship_obj->orient;
1817         for (int ii=0; ii<NUM_SUB_EXPL_HANDLES; ii++) {
1818                 split_ship->sound_handle[ii] = shipp->sub_expl_sound_handle[ii];
1819         }
1820
1821         // play 3d sound for shockwave explosion
1822         snd_play_3d( &Snds[SND_SHOCKWAVE_EXPLODE], &parent_ship_obj->pos, &View_position, 0.0f, NULL, 0, 1.0f, SND_PRIORITY_SINGLE_INSTANCE, NULL, 3.0f );
1823
1824         // initialize both ships
1825         split_ship->front_ship.parent_obj = parent_ship_obj;
1826         split_ship->back_ship.parent_obj  = parent_ship_obj;
1827         split_ship->explosion_flash_timestamp = timestamp((int)(0.00075f*parent_ship_obj->radius));
1828         split_ship->explosion_flash_started = 0;
1829         split_ship->front_ship.orient = *orient;
1830         split_ship->back_ship.orient  = *orient;
1831         split_ship->front_ship.next_fireball = timestamp_rand(0, 100);
1832         split_ship->back_ship.next_fireball  = timestamp_rand(0, 100);
1833
1834         split_ship->front_ship.clip_plane_norm = vmd_z_vector;
1835         vm_vec_copy_scale(&split_ship->back_ship.clip_plane_norm, &vmd_z_vector, -1.0f);
1836
1837         // find the point at which the ship splits (relative to its pivot)
1838         polymodel* pm = model_get(shipp->modelnum);
1839         float init_clip_plane_dist;
1840         if (pm->num_split_plane > 0) {
1841                 int index = rand()%pm->num_split_plane;
1842                 init_clip_plane_dist = pm->split_plane[index];
1843         } else {
1844                 init_clip_plane_dist = 0.5f * (0.5f - frand())*pm->core_radius;
1845         }
1846
1847         split_ship->back_ship.cur_clip_plane_pt =  init_clip_plane_dist;
1848         split_ship->front_ship.cur_clip_plane_pt = init_clip_plane_dist;
1849
1850         float dist;
1851         dist = (split_ship->front_ship.cur_clip_plane_pt+pm->maxs.xyz.z)/2.0f;
1852         vm_vec_copy_scale(&split_ship->front_ship.local_pivot, &orient->v.fvec, dist);
1853         vm_vec_make(&split_ship->front_ship.model_center_disp_to_orig_center, 0.0f, 0.0f, -dist);
1854         dist = (split_ship->back_ship.cur_clip_plane_pt +pm->mins.xyz.z)/2.0f;
1855         vm_vec_copy_scale(&split_ship->back_ship.local_pivot, &orient->v.fvec, dist);
1856         vm_vec_make(&split_ship->back_ship.model_center_disp_to_orig_center, 0.0f, 0.0f, -dist);
1857         vm_vec_add2(&split_ship->front_ship.local_pivot, &parent_ship_obj->pos );
1858         vm_vec_add2(&split_ship->back_ship.local_pivot,  &parent_ship_obj->pos );
1859         
1860         // find which debris pieces are in the front and back split ships
1861         for (int i=0; i<pm->num_debris_objects; i++ )   {
1862                 vector temp_pos = {0.0f, 0.0f, 0.0f};
1863                 vector tmp = {0.0f, 0.0f, 0.0f };               
1864                 vector tmp1 = pm->submodel[pm->debris_objects[i]].offset;
1865                 // tmp is world position,  temp_pos is world_pivot,  tmp1 is offset from world_pivot (in ship local coord)
1866                 model_find_world_point(&tmp, &tmp1, shipp->modelnum, -1, &vmd_identity_matrix, &temp_pos );
1867                 if (tmp.xyz.z > init_clip_plane_dist) {
1868                         split_ship->front_ship.draw_debris[i] = DEBRIS_DRAW;
1869                         split_ship->back_ship.draw_debris[i]  = DEBRIS_NONE;
1870                 } else {
1871                         split_ship->front_ship.draw_debris[i] = DEBRIS_NONE;
1872                         split_ship->back_ship.draw_debris[i]  = DEBRIS_DRAW;
1873                 }
1874         }
1875
1876         /*
1877         // set the remaining debris slots to not draw
1878         for (i=pm->num_debris_objects; i<MAX_DEBRIS_OBJECTS; i++) {
1879                 split_ship->front_ship.draw_debris[i] = DEBRIS_NONE;
1880                 split_ship->back_ship.draw_debris[i]  = DEBRIS_NONE;
1881         } */
1882
1883         // set up physics 
1884         physics_init( &split_ship->front_ship.phys_info );
1885         physics_init( &split_ship->back_ship.phys_info );
1886         split_ship->front_ship.phys_info.flags  |= (PF_ACCELERATES | PF_DEAD_DAMP);
1887         split_ship->back_ship.phys_info.flags |= (PF_ACCELERATES | PF_DEAD_DAMP);
1888         split_ship->front_ship.phys_info.side_slip_time_const = 10000.0f;
1889         split_ship->back_ship.phys_info.side_slip_time_const =  10000.0f;
1890         split_ship->front_ship.phys_info.rotdamp = 10000.0f;
1891         split_ship->back_ship.phys_info.rotdamp =  10000.0f;
1892
1893         // set up explosion vel and relative velocities (assuming mass depends on length)
1894         float front_length = pm->maxs.xyz.z - split_ship->front_ship.cur_clip_plane_pt;
1895         float back_length  = split_ship->back_ship.cur_clip_plane_pt - pm->mins.xyz.z;
1896         float ship_length = front_length + back_length;
1897         split_ship->front_ship.length_left = front_length;
1898         split_ship->back_ship.length_left  = back_length;
1899
1900         float expl_length_scale = (ship_length - 200.0f) / 2000.0f;
1901         // s_r_f effects speed of "wipe" and rotvel
1902         float speed_reduction_factor = (1.0f + 0.001f*parent_ship_obj->radius);
1903         float explosion_time = (3.0f + expl_length_scale + (frand()-0.5f)) * speed_reduction_factor;
1904         float long_length = max(front_length, back_length);
1905         float expl_vel = long_length / explosion_time;
1906         split_ship->front_ship.explosion_vel = expl_vel;
1907         split_ship->back_ship.explosion_vel  = -expl_vel;
1908
1909         float rel_vel = (0.6f + 0.2f*frand()) * expl_vel * speed_reduction_factor;
1910         float front_vel = rel_vel * back_length / ship_length;
1911         float back_vel = -rel_vel * front_length / ship_length;
1912         // mprintf(("rel_vel %.1f, expl_vel %.1f\n", rel_vel, expl_vel));
1913
1914         // set up rotational vel
1915         vector rotvel;
1916         vm_vec_rand_vec_quick(&rotvel);
1917         rotvel.xyz.z = 0.0f;
1918         vm_vec_normalize(&rotvel);
1919         vm_vec_scale(&rotvel, 0.15f / speed_reduction_factor);
1920         split_ship->front_ship.phys_info.rotvel = rotvel;
1921         vm_vec_copy_scale(&split_ship->back_ship.phys_info.rotvel, &rotvel, -(front_length*front_length)/(back_length*back_length));
1922         split_ship->front_ship.phys_info.rotvel.xyz.z = parent_ship_obj->phys_info.rotvel.xyz.z;
1923         split_ship->back_ship.phys_info.rotvel.xyz.z  = parent_ship_obj->phys_info.rotvel.xyz.z;
1924
1925
1926         // modify vel of each split ship based on rotvel of parent ship obj
1927         vector temp_rotvel = parent_ship_obj->phys_info.rotvel;
1928         temp_rotvel.xyz.z = 0.0f;
1929         vector vel_from_rotvel;
1930         vm_vec_crossprod(&vel_from_rotvel, &temp_rotvel, &split_ship->front_ship.local_pivot);
1931         //      vm_vec_scale_add2(&split_ship->front_ship.phys_info.vel, &vel_from_rotvel, 0.5f);
1932         vm_vec_crossprod(&vel_from_rotvel, &temp_rotvel, &split_ship->back_ship.local_pivot);
1933         //      vm_vec_scale_add2(&split_ship->back_ship.phys_info.vel, &vel_from_rotvel, 0.5f);
1934
1935         // set up velocity and make initial fireballs and particles
1936         split_ship->front_ship.phys_info.vel = parent_ship_obj->phys_info.vel;
1937         split_ship->back_ship.phys_info.vel  = parent_ship_obj->phys_info.vel;
1938         maybe_fireball_wipe(&split_ship->front_ship, (int*)&split_ship->sound_handle);
1939         maybe_fireball_wipe(&split_ship->back_ship,  (int*)&split_ship->sound_handle);
1940         vm_vec_scale_add2(&split_ship->front_ship.phys_info.vel, &orient->v.fvec, front_vel);
1941         vm_vec_scale_add2(&split_ship->back_ship.phys_info.vel,  &orient->v.fvec, back_vel);
1942
1943         // HANDLE LIVE DEBRIS - blow off if not already gone
1944         shipfx_maybe_create_live_debris_at_ship_death( parent_ship_obj );
1945 }
1946
1947
1948 static void half_ship_render_ship_and_debris(clip_ship* half_ship,ship *shipp)
1949 {
1950         Assert( Split_ships_inited );
1951
1952         polymodel *pm = model_get(shipp->modelnum);
1953
1954         // get rotated clip plane normal and world coord of original ship center
1955         vector orig_ship_world_center, clip_plane_norm, model_clip_plane_pt, debris_clip_plane_pt;
1956         vm_vec_unrotate(&clip_plane_norm, &half_ship->clip_plane_norm, &half_ship->orient);
1957         vm_vec_unrotate(&orig_ship_world_center, &half_ship->model_center_disp_to_orig_center, &half_ship->orient);
1958         vm_vec_add2(&orig_ship_world_center, &half_ship->local_pivot);
1959
1960         // *out_pivot = orig_ship_world_center;
1961
1962         // get debris clip plane pt and draw debris
1963         vm_vec_unrotate(&debris_clip_plane_pt, &half_ship->model_center_disp_to_orig_center, &half_ship->orient);
1964         vm_vec_add2(&debris_clip_plane_pt, &half_ship->local_pivot);
1965         g3_start_user_clip_plane( &debris_clip_plane_pt, &clip_plane_norm);
1966
1967         // set up render flags
1968         uint render_flags = MR_NORMAL;
1969
1970         for (int i=0; i<pm->num_debris_objects; i++ )   {
1971                 // draw DEBRIS_FREE in test only
1972                 if (half_ship->draw_debris[i] == DEBRIS_DRAW) {
1973                         vector temp_pos = orig_ship_world_center;
1974                         vector tmp = {0.0f, 0.0f, 0.0f};
1975                         vector tmp1 = pm->submodel[pm->debris_objects[i]].offset;
1976
1977                         // determine if explosion front has past debris piece
1978                         // 67 ~ dist expl moves in 2 frames -- maybe fraction works better
1979                         int is_live_debris = pm->submodel[pm->debris_objects[i]].is_live_debris;
1980                         int create_debris = 0;
1981                         // front ship
1982                         if (half_ship->explosion_vel > 0) {
1983                                 if (half_ship->cur_clip_plane_pt > tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].max.xyz.z - 0.1f*half_ship->explosion_vel) {
1984                                         create_debris = 1;
1985                                 }
1986                                 // is the debris visible
1987 //                              if (half_ship->cur_clip_plane_pt > tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].min.xyz.z - 0.5f*half_ship->explosion_vel) {
1988 //                                      render_debris = 1;
1989 //                              }
1990                         // back ship
1991                         } else {
1992                                 if (half_ship->cur_clip_plane_pt < tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].min.xyz.z - 0.1f*half_ship->explosion_vel) {
1993                                         create_debris = 1;
1994                                 }
1995                                 // is the debris visible
1996 //                              if (half_ship->cur_clip_plane_pt < tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].max.xyz.z - 0.5f*half_ship->explosion_vel) {
1997 //                                      render_debris = 1;
1998 //                              }
1999                         }
2000
2001                         // Draw debris, but not live debris
2002                         if ( !is_live_debris ) {
2003                                 model_find_world_point(&tmp, &tmp1, shipp->modelnum, -1, &half_ship->orient, &temp_pos);
2004                                 submodel_render(shipp->modelnum, pm->debris_objects[i], &half_ship->orient, &tmp, render_flags);
2005                         }
2006
2007                         // make free piece of debris
2008                         if ( create_debris ) {
2009                                 half_ship->draw_debris[i] = DEBRIS_FREE;                // mark debris to not render with model
2010                                 vector center_to_debris, debris_vel, radial_vel;
2011                                 // check if last debris piece, ie, debris_count == 0
2012                                 int debris_count = 0;
2013                                 for (int j=0; j<pm->num_debris_objects; j++ ) {
2014                                         if (half_ship->draw_debris[j] == DEBRIS_DRAW) {
2015                                                 debris_count++;
2016                                         }
2017                                 } 
2018                                 // do debris create here, but not for live debris
2019                                 // debris vel (1) split ship vel (2) split ship rotvel (3) random
2020                                 if ( !is_live_debris ) {
2021                                         object* debris_obj;
2022                                         debris_obj = debris_create(half_ship->parent_obj, shipp->modelnum, pm->debris_objects[i], &tmp, &half_ship->local_pivot, 1, 1.0f);
2023                                         // AL: make sure debris_obj isn't NULL!
2024                                         if ( debris_obj ) {
2025                                                 vm_vec_scale(&debris_obj->phys_info.rotvel, 4.0f);
2026                                                 debris_obj->orient = half_ship->orient;
2027                                                 // if (debris_count > 0) {
2028                                                         //mprintf(( "base rotvel %.1f, debris rotvel mag %.2f\n", vm_vec_mag(&half_ship->phys_info.rotvel), vm_vec_mag(&debris_obj->phys_info.rotvel) ));
2029                                                         vm_vec_sub(&center_to_debris, &tmp, &half_ship->local_pivot);
2030                                                         vm_vec_crossprod(&debris_vel, &center_to_debris, &half_ship->phys_info.rotvel);
2031                                                         vm_vec_add2(&debris_vel, &half_ship->phys_info.vel);
2032                                                         vm_vec_copy_normalize(&radial_vel, &center_to_debris);
2033                                                         float radial_mag = 10.0f + 30.0f*frand();
2034                                                         vm_vec_scale_add2(&debris_vel, &radial_vel, radial_mag);
2035                                                         debris_obj->phys_info.vel = debris_vel;
2036                                                 /* } else {
2037                                                         debris_obj->phys_info.vel = half_ship->phys_info.vel;
2038                                                         debris_obj->phys_info.rotvel = half_ship->phys_info.rotvel;
2039                                                 } */
2040                                         }
2041                                 }
2042                         }
2043                 }
2044         }
2045
2046         // get model clip plane pt and draw model
2047         vector temp;
2048         vm_vec_make(&temp, 0.0f, 0.0f, half_ship->cur_clip_plane_pt);
2049         vm_vec_unrotate(&model_clip_plane_pt, &temp, &half_ship->orient);
2050         vm_vec_add2(&model_clip_plane_pt, &orig_ship_world_center);
2051         g3_start_user_clip_plane( &model_clip_plane_pt, &clip_plane_norm );
2052         model_render(shipp->modelnum, &half_ship->orient, &orig_ship_world_center, render_flags);
2053 }
2054
2055 void shipfx_large_blowup_level_init()
2056 {
2057         split_ship_init_system();
2058
2059         if(Ship_cannon_bitmap != -1){
2060                 bm_unload(Ship_cannon_bitmap);
2061                 Ship_cannon_bitmap = bm_load(SHIP_CANNON_BITMAP);
2062         }
2063 }
2064
2065 // Returns 0 if couldn't init
2066 int shipfx_large_blowup_init(ship *shipp)
2067 {
2068
2069         if ( !Split_ships_inited )      {
2070                 split_ship_init_system();
2071         }
2072
2073         int i;
2074         for (i=0; i<MAX_SPLIT_SHIPS; i++ )      {
2075                 if ( Split_ships[i].used == 0 ) {
2076                         break;
2077                 }
2078         }
2079
2080         if ( i >= MAX_SPLIT_SHIPS )     {
2081                 mprintf(( "Not enough split ship slots!! See John!\n" ));
2082                 Int3();
2083                 return 0;
2084         }
2085
2086         Split_ships[i].used = 1;
2087         shipp->large_ship_blowup_index = i;
2088
2089         split_ship_init(shipp, &Split_ships[i] );
2090         
2091         return 1;
2092 }
2093
2094 // ----------------------------------------------------------------------------
2095 // uses list of model z values with constant increment to find the radius of the 
2096 // cross section at the current model z value
2097 float get_model_cross_section_at_z(float z, polymodel* pm)
2098 {
2099         if (pm->num_xc < 2) {
2100                 return 0.0f;
2101         }
2102
2103         float index, increment;
2104         increment = (pm->xc[pm->num_xc-1].z - pm->xc[0].z) / (float)(pm->num_xc - 1);
2105         index = (z - pm->xc[0].z) / increment;
2106
2107         if (index < 0.5f) {
2108                 return pm->xc[0].radius;
2109         } else if (index > (pm->num_xc - 1.0f - 0.5f)) {
2110                 return pm->xc[pm->num_xc-1].radius;
2111         } else {
2112                 int floor_index = (int)floor(index);
2113                 int ceil_index  = (int)ceil(index);
2114                 return max(pm->xc[ceil_index].radius, pm->xc[floor_index].radius);
2115         }
2116 }
2117
2118 // returns how long sound has been playing
2119 int get_sound_time_played(int snd_id, int handle)
2120 {
2121         if (handle == -1) {
2122                 return 100000;
2123         }
2124
2125         int bits_per_sample, frequency;
2126         snd_get_format(snd_id, &bits_per_sample, &frequency);
2127         int time_left = snd_time_remaining(handle, bits_per_sample, frequency);
2128         int duration = snd_get_duration(snd_id);
2129         
2130         return (duration - time_left);
2131 }
2132
2133 // sound manager for big ship sub explosions sounds.
2134 // forces playing of sub-explosion sounds.  keeps track of active sounds, plays them for >= 750 ms
2135 // when sound has played >= 750, sound is stopped and new instance is started 
2136 void do_sub_expl_sound(float radius, vector* sound_pos, int* sound_handle)
2137 {
2138         int sound_index, handle;
2139         // multiplier for range (near and far distances) to apply attenuation
2140         float sound_range = 1.0f + 0.0043f*radius;
2141
2142         int handle_index = rand()%NUM_SUB_EXPL_HANDLES;
2143         //mprintf(("handle_index %d\n", *handle_index));
2144
2145         // sound_index = get_sub_explosion_sound_index(handle_index);
2146         sound_index = SND_SHIP_EXPLODE_1;
2147         handle = sound_handle[handle_index];
2148
2149
2150         // mprintf(("dist to sound %.1f snd_indx: %d, h1: %d, h2: %d\n", vm_vec_dist(&Player_obj->pos, sound_pos), next_sound_index, sound_handle[0], sound_handle[1]));
2151
2152         if (handle == -1) {
2153                 // if no handle, get one
2154                 sound_handle[handle_index] = snd_play_3d( &Snds[sound_index], sound_pos, &View_position, 0.0f, NULL, 0, 0.6f, SND_PRIORITY_MUST_PLAY, NULL, sound_range );
2155         } else if (!snd_is_playing(handle)) {
2156                 // if sound not playing and old, get new one
2157                 // I don't think will happen with SND_PRIORITY_MUST_PLAY
2158                 if (get_sound_time_played(Snds[sound_index].id, handle) > 400) {
2159                         //mprintf(("sound not playing %d, time_played %d, stopped\n", handle, get_sound_time_played(Snds[sound_index].id, handle)));
2160                         snd_stop(sound_handle[handle_index]);
2161                         sound_handle[handle_index] = snd_play_3d( &Snds[sound_index], sound_pos, &View_position, 0.0f, NULL, 0, 0.6f, SND_PRIORITY_MUST_PLAY, NULL, sound_range );
2162                 }
2163         } else if (get_sound_time_played(Snds[sound_index].id, handle) > 750) {
2164                 //mprintf(("time %f, cur sound %d time_played %d num sounds %d\n", f2fl(Missiontime), handle_index, get_sound_time_played(Snds[sound_index].id, handle), snd_num_playing() ));
2165                 sound_handle[handle_index] = snd_play_3d( &Snds[sound_index], sound_pos, &View_position, 0.0f, NULL, 0, 0.6f, SND_PRIORITY_MUST_PLAY, NULL, sound_range );
2166         }
2167 }
2168
2169 // maybe create a fireball along model clip plane
2170 // also maybe plays explosion sound
2171 static void maybe_fireball_wipe(clip_ship* half_ship, int* sound_handle)
2172 {
2173         // maybe make fireball to cover wipe.
2174         if ( timestamp_elapsed(half_ship->next_fireball) ) {
2175                 if ( half_ship->length_left > 0.2f*fl_abs(half_ship->explosion_vel) )   {
2176
2177                         polymodel* pm = model_get(Ships[half_ship->parent_obj->instance].modelnum);
2178
2179                         vector model_clip_plane_pt, orig_ship_world_center, temp;
2180
2181                         vm_vec_unrotate(&orig_ship_world_center, &half_ship->model_center_disp_to_orig_center, &half_ship->orient);
2182                         vm_vec_add2(&orig_ship_world_center, &half_ship->local_pivot);
2183
2184                         vm_vec_make(&temp, 0.0f, 0.0f, half_ship->cur_clip_plane_pt);
2185                         vm_vec_unrotate(&model_clip_plane_pt, &temp, &half_ship->orient);
2186                         vm_vec_add2(&model_clip_plane_pt, &orig_ship_world_center);
2187                         vm_vec_rand_vec_quick(&temp);
2188                         vm_vec_scale(&temp, 0.1f*frand());
2189                         vm_vec_add2(&model_clip_plane_pt, &temp);
2190
2191                         float rad = get_model_cross_section_at_z(half_ship->cur_clip_plane_pt, pm);
2192                         if (rad < 1) {
2193                                 rad = half_ship->parent_obj->radius * frand_range(0.4f, 0.6f);
2194                         } else {
2195                                 // make fireball radius (1.5 +/- .1) * model_cross_section value
2196                                 rad *= frand_range(1.4f, 1.6f);
2197                         }
2198
2199                         rad *= 1.5f;
2200                         rad = min(rad, half_ship->parent_obj->radius);
2201
2202                         // mprintf(("xc %.1f model %.1f\n", rad, half_ship->parent_obj->radius*0.25));
2203                         int fireball_type = FIREBALL_EXPLOSION_LARGE1 + rand()%FIREBALL_NUM_LARGE_EXPLOSIONS;
2204                         int low_res_fireballs = Bs_exp_fire_low;
2205                         fireball_create(&model_clip_plane_pt, fireball_type, OBJ_INDEX(half_ship->parent_obj), rad, 0, &half_ship->parent_obj->phys_info.vel, 0.0f, -1, NULL, low_res_fireballs);
2206
2207                         // start the next fireball up (3-4 per frame) + 30%
2208                         int time_low, time_high;
2209                         time_low = int(650 * Bs_exp_fire_time_mult);
2210                         time_high = int(900 * Bs_exp_fire_time_mult);
2211                         half_ship->next_fireball = timestamp_rand(time_low, time_high);
2212
2213                         // do sound
2214                         do_sub_expl_sound(half_ship->parent_obj->radius, &model_clip_plane_pt, sound_handle);
2215
2216                         // do particles
2217                         particle_emitter        pe;
2218
2219                         pe.num_low = 40;                                        // Lowest number of particles to create
2220                         pe.num_high = 80;                               // Highest number of particles to create
2221                         pe.pos = model_clip_plane_pt;   // Where the particles emit from
2222                         pe.vel = half_ship->phys_info.vel;              // Initial velocity of all the particles
2223
2224 #ifdef FS2_DEMO
2225                         float range = 1.0f + 0.002f*half_ship->parent_obj->radius * 5.0f;
2226 #else 
2227                         float range = 1.0f + 0.002f*half_ship->parent_obj->radius;
2228 #endif
2229
2230 #ifdef FS2_DEMO
2231                         pe.min_life = 2.0f*range;                               // How long the particles live
2232                         pe.max_life = 10.0f*range;                              // How long the particles live
2233 #else
2234                         pe.min_life = 0.5f*range;                               // How long the particles live
2235                         pe.max_life = 6.0f*range;                               // How long the particles live
2236 #endif
2237                         pe.normal = vmd_x_vector;               // What normal the particle emit around
2238                         pe.normal_variance = 2.0f;              //      How close they stick to that normal 0=on normal, 1=180, 2=360 degree
2239                         pe.min_vel = 0.0f;                              // How fast the slowest particle can move
2240                         pe.max_vel = half_ship->explosion_vel;                          // How fast the fastest particle can move
2241
2242 #ifdef FS2_DEMO
2243                         float scale = half_ship->parent_obj->radius * 0.02f;
2244 #else
2245                         float scale = half_ship->parent_obj->radius * 0.01f;
2246 #endif
2247                         pe.min_rad = 0.5f*scale;                                // Min radius
2248                         pe.max_rad = 1.5f*scale;                                // Max radius
2249
2250                         particle_emit( &pe, PARTICLE_SMOKE2, 0, range );
2251
2252                 } else {
2253                         // time out forever
2254                         half_ship->next_fireball = timestamp(-1);
2255                 }
2256         }
2257 }
2258
2259
2260 // Returns 1 when explosion is done
2261 int shipfx_large_blowup_do_frame(ship *shipp, float frametime)
2262 {
2263         // DAVE:  I made this not do any movement just to try to get things working...
2264         // return 0;
2265
2266         Assert( Split_ships_inited );
2267         Assert( shipp->large_ship_blowup_index > -1 );
2268
2269         split_ship *the_split_ship = &Split_ships[shipp->large_ship_blowup_index];
2270         Assert( the_split_ship->used );         // Get John
2271
2272         // Do fireballs, particles, shockwave here
2273         // Note parent ship is still valid, vel and pos updated in obj_move_all
2274
2275         if ( timestamp_elapsed(the_split_ship->explosion_flash_timestamp) ) {
2276                 if ( !the_split_ship->explosion_flash_started ) {
2277                         object* objp = &Objects[shipp->objnum];
2278                         if (objp->flags & OF_WAS_RENDERED) {
2279                                 float excess_dist = vm_vec_dist(&Player_obj->pos, &objp->pos) - 2.0f*objp->radius - Player_obj->radius;
2280                                 float intensity = 1.0f - 0.1f*excess_dist / objp->radius;
2281
2282                                 if (intensity > 1) {
2283                                         intensity = 1.0f;
2284                                 }
2285
2286                                 if (intensity > 0.1f) {
2287                                         // big_explosion_flash(intensity);
2288                                 }
2289                         }
2290                         the_split_ship->explosion_flash_started = 1;
2291                 }
2292         }
2293
2294         physics_sim(&the_split_ship->front_ship.local_pivot, &the_split_ship->front_ship.orient, &the_split_ship->front_ship.phys_info, frametime);
2295         physics_sim(&the_split_ship->back_ship.local_pivot,  &the_split_ship->back_ship.orient,  &the_split_ship->back_ship.phys_info,  frametime);
2296         the_split_ship->front_ship.length_left -= the_split_ship->front_ship.explosion_vel*frametime;
2297         the_split_ship->back_ship.length_left  += the_split_ship->back_ship.explosion_vel *frametime;
2298         the_split_ship->front_ship.cur_clip_plane_pt += the_split_ship->front_ship.explosion_vel*frametime;
2299         the_split_ship->back_ship.cur_clip_plane_pt  += the_split_ship->back_ship.explosion_vel *frametime;
2300
2301         float length_left = max( the_split_ship->front_ship.length_left, the_split_ship->back_ship.length_left );
2302
2303         //      mprintf(( "Blowup frame, dist = %.1f \n", length_left ));
2304
2305         if ( length_left < 0 )  {
2306                 the_split_ship->used = 0;
2307                 return 1;
2308         }
2309
2310         maybe_fireball_wipe(&the_split_ship->front_ship, (int*)&the_split_ship->sound_handle);
2311         maybe_fireball_wipe(&the_split_ship->back_ship,  (int*)&the_split_ship->sound_handle);
2312         return 0;
2313 }
2314
2315 void shipfx_large_blowup_render(ship* shipp)
2316 {
2317 // This actually renders the original model like it should render.
2318 //      object *objp = &Objects[shipp->objnum];
2319 //      model_render( shipp->modelnum, &objp->orient, &objp->pos, MR_NORMAL );
2320 //      return;
2321
2322         Assert( Split_ships_inited );
2323         Assert( shipp->large_ship_blowup_index > -1 );
2324
2325         split_ship *the_split_ship = &Split_ships[shipp->large_ship_blowup_index];
2326         Assert( the_split_ship->used );         // Get John
2327
2328         // vector front_global_pivot, back_global_pivot;
2329
2330         if (the_split_ship->front_ship.length_left > 0) {
2331                 half_ship_render_ship_and_debris(&the_split_ship->front_ship,shipp);
2332         }
2333
2334         if (the_split_ship->back_ship.length_left > 0) {
2335                 half_ship_render_ship_and_debris(&the_split_ship->back_ship,shipp);
2336         }
2337
2338         g3_stop_user_clip_plane();                      
2339 }
2340
2341
2342 // ================== DO THE ELECTRIC ARCING STUFF =====================
2343 // Creates any new ones, moves old ones.
2344
2345 #define MAX_ARC_LENGTH_PERCENTAGE 0.25f
2346
2347 #define MAX_EMP_ARC_TIMESTAMP            (150.0f)
2348
2349 void shipfx_do_damaged_arcs_frame( ship *shipp )
2350 {
2351         int i;
2352         int should_arc;
2353         object *obj = &Objects[shipp->objnum];
2354         ship_info * sip = &Ship_info[shipp->ship_info_index];
2355
2356         should_arc = 1;
2357
2358         float damage = obj->hull_strength / sip->initial_hull_strength; 
2359
2360         if (damage < 0) {
2361                 damage = 0.0f;
2362         }
2363
2364         // don't draw an arc based on damage
2365         if ( damage > 0.30f )   {
2366                 // Don't do spark.
2367                 should_arc = 0;
2368         }
2369
2370         // we should draw an arc
2371         if( shipp->emp_intensity > 0.0f){
2372                 should_arc = 1;
2373         }
2374
2375         // Kill off old sparks
2376         for(i=0; i<MAX_SHIP_ARCS; i++){
2377                 if(timestamp_valid(shipp->arc_timestamp[i]) && timestamp_elapsed(shipp->arc_timestamp[i])){                     
2378                         shipp->arc_timestamp[i] = timestamp(-1);
2379                 }
2380         }
2381
2382         // if we shouldn't draw an arc, return
2383         if(!should_arc){
2384                 return;
2385         }
2386
2387         if (!timestamp_valid(shipp->arc_next_time))     {
2388                 // start the next fireball up in the next 10 seconds or so... 
2389                 int freq;
2390                 
2391                 // if the emp effect is active
2392                 if(shipp->emp_intensity > 0.0f){
2393                         freq = fl2i(MAX_EMP_ARC_TIMESTAMP);
2394                 }
2395                 // otherwise if we're arcing based upon damage
2396                 else {
2397                         freq = fl2i((damage+0.1f)*5000.0f);
2398                 }
2399
2400                 // set the next arc time
2401                 shipp->arc_next_time = timestamp_rand(freq*2,freq*4);
2402         }
2403
2404         if ( timestamp_elapsed(shipp->arc_next_time) )  {
2405
2406                 shipp->arc_next_time = timestamp(-1);           // invalid, so it gets restarted next frame
2407
2408                 //mprintf(( "Creating new ship arc!\n" ));
2409
2410                 int n, n_arcs = ((rand()>>5) % 3)+1;            // Create 1-3 sparks
2411
2412                 vector v1, v2, v3, v4;
2413                 submodel_get_two_random_points( shipp->modelnum, -1, &v1, &v2 );
2414                 submodel_get_two_random_points( shipp->modelnum, -1, &v3, &v4 );
2415
2416                 // For large ships, cap the length to be 25% of max radius
2417                 if ( obj->radius > 200.0f )     {
2418                         float max_dist = obj->radius * MAX_ARC_LENGTH_PERCENTAGE;
2419                         
2420                         vector tmp;
2421                         float d;
2422
2423                         // Cap arc 2->1
2424                         vm_vec_sub( &tmp, &v1, &v2 );
2425                         d = vm_vec_mag_quick( &tmp );
2426                         if ( d > max_dist )     {
2427                                 vm_vec_scale_add( &v1, &v2, &tmp, max_dist / d );
2428                         }
2429
2430                         // Cap arc 2->3
2431                         vm_vec_sub( &tmp, &v3, &v2 );
2432                         d = vm_vec_mag_quick( &tmp );
2433                         if ( d > max_dist )     {
2434                                 vm_vec_scale_add( &v3, &v2, &tmp, max_dist / d );
2435                         }
2436
2437
2438                         // Cap arc 2->4
2439                         vm_vec_sub( &tmp, &v4, &v2 );
2440                         d = vm_vec_mag_quick( &tmp );
2441                         if ( d > max_dist )     {
2442                                 vm_vec_scale_add( &v4, &v2, &tmp, max_dist / d );
2443                         }
2444                         
2445                 }
2446                 
2447                 n = 0;
2448
2449 //              int a = 100, b = 1000;
2450                 float factor = 1.0f + 0.0025f*obj->radius;
2451                 int a = (int) (factor*100.0f);
2452                 int b = (int) (factor*1000.0f);
2453                 int lifetime = (myrand()%((b)-(a)+1))+(a);
2454
2455                 // Create the arc effects
2456                 for (i=0; i<MAX_SHIP_ARCS; i++ )        {
2457                         if ( !timestamp_valid( shipp->arc_timestamp[i] ) )      {
2458                                 //shipp->arc_timestamp[i] = timestamp_rand(400,1000);   // live up to a second
2459                                 shipp->arc_timestamp[i] = timestamp(lifetime);  // live up to a second
2460
2461                                 switch( n )     {
2462                                 case 0:
2463                                         shipp->arc_pts[i][0] = v1;
2464                                         shipp->arc_pts[i][1] = v2;
2465                                         break;
2466                                 case 1:
2467                                         shipp->arc_pts[i][0] = v2;
2468                                         shipp->arc_pts[i][1] = v3;
2469                                         break;
2470
2471                                 case 2:
2472                                         shipp->arc_pts[i][0] = v2;
2473                                         shipp->arc_pts[i][1] = v4;
2474                                         break;
2475
2476                                 default:
2477                                         Int3();
2478                                 }
2479
2480                                 // determine what kind of arc to create
2481                                 if(shipp->emp_intensity > 0.0f){
2482                                         shipp->arc_type[i] = MARC_TYPE_EMP;
2483                                 } else {
2484                                         shipp->arc_type[i] = MARC_TYPE_NORMAL;
2485                                 }
2486                                         
2487                                 n++;
2488                                 if ( n == n_arcs )
2489                                         break;  // Don't need to create anymore
2490                         }
2491         
2492                         // rotate v2 out of local coordinates into world.
2493                         // Use v2 since it is used in every bolt.  See above switch().
2494                         vector snd_pos;
2495                         vm_vec_unrotate(&snd_pos, &v2, &obj->orient);
2496                         vm_vec_add2(&snd_pos, &obj->pos );
2497
2498                         //Play a sound effect
2499                         if ( lifetime > 750 )   {
2500                                 // 1.00 second effect
2501                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_05], &snd_pos, &View_position, obj->radius );
2502                         } else if ( lifetime >  500 )   {
2503                                 // 0.75 second effect
2504                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_04], &snd_pos, &View_position, obj->radius );
2505                         } else if ( lifetime >  250 )   {
2506                                 // 0.50 second effect
2507                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_03], &snd_pos, &View_position, obj->radius );
2508                         } else if ( lifetime >  100 )   {
2509                                 // 0.25 second effect
2510                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_02], &snd_pos, &View_position, obj->radius );
2511                         } else {
2512                                 // 0.10 second effect
2513                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_01], &snd_pos, &View_position, obj->radius );
2514                         }
2515                 }
2516         }
2517
2518         // maybe move arc points around
2519         for (i=0; i<MAX_SHIP_ARCS; i++ )        {
2520                 if ( timestamp_valid( shipp->arc_timestamp[i] ) )       {
2521                         if ( !timestamp_elapsed( shipp->arc_timestamp[i] ) )    {                                                       
2522                                 // Maybe move a vertex....  20% of the time maybe?
2523                                 int mr = myrand();
2524                                 if ( mr < RAND_MAX/5 )  {
2525                                         vector v1, v2;
2526                                         submodel_get_two_random_points( shipp->modelnum, -1, &v1, &v2 );
2527
2528                                         vector static_one;
2529
2530                                         if ( mr % 2 )   {
2531                                                 static_one = shipp->arc_pts[i][0];
2532                                         } else {
2533                                                 static_one = shipp->arc_pts[i][1];
2534                                         }
2535
2536                                         // For large ships, cap the length to be 25% of max radius
2537                                         if ( obj->radius > 200.0f )     {
2538                                                 float max_dist = obj->radius * MAX_ARC_LENGTH_PERCENTAGE;
2539                                                 
2540                                                 vector tmp;
2541                                                 float d;
2542
2543                                                 // Cap arc 2->1
2544                                                 vm_vec_sub( &tmp, &v1, &static_one );
2545                                                 d = vm_vec_mag_quick( &tmp );
2546                                                 if ( d > max_dist )     {
2547                                                         vm_vec_scale_add( &v1, &static_one, &tmp, max_dist / d );
2548                                                 }
2549                                         }
2550
2551                                         shipp->arc_pts[i][mr % 2] = v1;
2552                                 }
2553                         }
2554                 }
2555         }
2556 }
2557
2558 int l_cruiser_count = 1;
2559 int l_big_count = 2;
2560 int l_huge_count = 3;
2561 float l_max_radius = 3000.0f;
2562 void shipfx_do_lightning_frame( ship *shipp )
2563 {
2564         /*
2565         ship_info *sip;
2566         object *objp;
2567         int stamp, count;
2568         vector v1, v2, n1, n2, temp, temp2;
2569         bolt_info binfo;
2570
2571         // sanity checks
2572         Assert(shipp != NULL);
2573         if(shipp == NULL){
2574                 return;
2575         } 
2576         Assert(shipp->ship_info_index >= 0);
2577         if(shipp->ship_info_index < 0){
2578                 return;
2579         }       
2580         Assert(shipp->objnum >= 0);
2581         if(shipp->objnum < 0){
2582                 return;
2583         }       
2584
2585         // get some pointers
2586         sip = &Ship_info[shipp->ship_info_index];
2587         objp = &Objects[shipp->objnum]; 
2588
2589         // if this is not a nebula mission, don't do anything
2590         if(!(The_mission.flags & MISSION_FLAG_FULLNEB)){
2591                 shipp->lightning_stamp = -1;
2592                 return;
2593         }
2594         
2595         // if this not a cruiser or big ship
2596         if(!((sip->flags & SIF_CRUISER) || (sip->flags & SIF_BIG_SHIP) || (sip->flags & SIF_HUGE_SHIP))){
2597                 shipp->lightning_stamp = -1;
2598                 return;
2599         }
2600
2601         // determine stamp and count values
2602         if(sip->flags & SIF_CRUISER){
2603                 stamp = (int)((float)(Nebl_cruiser_min + ((Nebl_cruiser_max - Nebl_cruiser_min) * Nebl_intensity)) * frand_range(0.8f, 1.1f));
2604                 count = l_cruiser_count;
2605         } 
2606         else {
2607                 if(sip->flags & SIF_HUGE_SHIP){
2608                         stamp = (int)((float)(Nebl_supercap_min + ((Nebl_supercap_max - Nebl_supercap_min) * Nebl_intensity)) * frand_range(0.8f, 1.1f));
2609                         count = l_huge_count;
2610                 } else {
2611                         stamp = (int)((float)(Nebl_cap_min + ((Nebl_cap_max - Nebl_cap_min) * Nebl_intensity)) * frand_range(0.8f, 1.1f));
2612                         count = l_big_count;
2613                 }
2614         }
2615
2616         // if his timestamp is unset
2617         if(shipp->lightning_stamp == -1){
2618                 shipp->lightning_stamp = timestamp(stamp);
2619                 return;
2620         }
2621         // if his timestamp is currently unelapsed
2622         if(!timestamp_elapsed(shipp->lightning_stamp)){
2623                 return;
2624         }
2625
2626         mprintf(("SHIP BOLT\n"));
2627
2628         // restamp him first
2629         shipp->lightning_stamp = timestamp(stamp);
2630
2631         // ah, now we can create some lightning bolts
2632         count = (int)frand_range(0.0f, (float)count);
2633         while(count > 0){
2634                 // get 2 points on the hull of the ship
2635                 submodel_get_two_random_points(shipp->modelnum, 0, &v1, &v2, &n1, &n2);         
2636
2637                 // make up to 2 bolts
2638                 if(objp->radius > l_max_radius){
2639                         vm_vec_scale_add(&temp2, &v1, &n1, l_max_radius);
2640                 } else {
2641                         vm_vec_scale_add(&temp2, &v1, &n1, objp->radius);
2642                 }
2643                 vm_vec_unrotate(&temp, &temp2, &objp->orient);
2644                 vm_vec_add2(&temp, &objp->pos);
2645                 vm_vec_unrotate(&temp2, &v1, &objp->orient);
2646                 vm_vec_add2(&temp2, &objp->pos);
2647
2648                 // create the bolt
2649                 binfo.start = temp;
2650                 binfo.strike = temp2;
2651                 binfo.num_strikes = 3;
2652                 binfo.noise = 0.045f;
2653                 binfo.life = 375;
2654                 binfo.delay = (int)frand_range(0.0f, 1600.0f);
2655                 nebl_bolt(&binfo);
2656                 count--;
2657         
2658                 // done
2659                 if(count <= 0){
2660                         break;
2661                 }
2662
2663                 // one more             
2664                 if(objp->radius > l_max_radius){
2665                         vm_vec_scale_add(&temp2, &v2, &n2, l_max_radius);
2666                 } else {
2667                         vm_vec_scale_add(&temp2, &v2, &n2, objp->radius);
2668                 }
2669                 vm_vec_unrotate(&temp, &temp2, &objp->orient);
2670                 vm_vec_add2(&temp, &objp->pos);
2671                 vm_vec_unrotate(&temp2, &v2, &objp->orient);
2672                 vm_vec_add2(&temp2, &objp->pos);
2673
2674                 // create the bolt
2675                 binfo.start = temp;
2676                 binfo.strike = temp2;
2677                 binfo.num_strikes = 3;
2678                 binfo.noise = 0.045f;
2679                 binfo.life = 375;
2680                 binfo.delay = (int)frand_range(0.0f, 1600.0f);
2681                 nebl_bolt(&binfo);              
2682                 count--;
2683         }
2684         */
2685 }
2686
2687 // do all shockwaves for a ship blowing up
2688 void shipfx_do_shockwave_stuff(ship *shipp, shockwave_create_info *sci)
2689 {
2690         ship_info *sip;
2691         object *objp;
2692         polymodel *pm;
2693         vector temp, dir, shockwave_pos;
2694         vector head = vmd_zero_vector;
2695         vector tail = vmd_zero_vector;  
2696         float len, step, cur;
2697         int idx;
2698
2699         // sanity checks
2700         Assert(shipp != NULL);
2701         if(shipp == NULL){
2702                 return;
2703         } 
2704         Assert(shipp->ship_info_index >= 0);
2705         if(shipp->ship_info_index < 0){
2706                 return;
2707         }       
2708         Assert(shipp->objnum >= 0);
2709         if(shipp->objnum < 0){
2710                 return;
2711         }
2712         Assert(sci != NULL);
2713         if (sci == NULL) {
2714                 return;
2715         }
2716
2717         // get some pointers
2718         sip = &Ship_info[shipp->ship_info_index];
2719         objp = &Objects[shipp->objnum]; 
2720
2721         Assert(sip->shockwave_count > 0);
2722         if(sip->shockwave_count <= 0){
2723                 return;
2724         }
2725
2726         // get vectors at the head and tail of the object, dead center          
2727         pm = model_get(shipp->modelnum);
2728         if(pm == NULL){
2729                 return;
2730         }
2731         head.xyz.x = pm->submodel[0].offset.xyz.x;
2732         head.xyz.y = pm->submodel[0].offset.xyz.y;
2733         head.xyz.z = pm->maxs.xyz.z;
2734
2735         tail.xyz.x = pm->submodel[0].offset.xyz.x;
2736         tail.xyz.y = pm->submodel[0].offset.xyz.y;
2737         tail.xyz.z = pm->mins.xyz.z;
2738
2739         // transform the vectors into world coords
2740         vm_vec_unrotate(&temp, &head, &objp->orient);
2741         vm_vec_add(&head, &temp, &objp->pos);
2742         vm_vec_unrotate(&temp, &tail, &objp->orient);
2743         vm_vec_add(&tail, &temp, &objp->pos);
2744
2745         // now create as many shockwaves as needed
2746         vm_vec_sub(&dir, &head, &tail);
2747         len = vm_vec_mag(&dir);
2748         step = 1.0f / ((float)sip->shockwave_count + 1.0f);
2749         cur = step;
2750         for(idx=0; idx<sip->shockwave_count; idx++){
2751                 // get the shockwave position           
2752                 temp = dir;
2753                 vm_vec_scale(&temp, cur);
2754                 vm_vec_add(&shockwave_pos, &tail, &temp);
2755
2756                 // if knossos device, make shockwave in center
2757                 if (Ship_info[shipp->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
2758                         shockwave_pos = Objects[shipp->objnum].pos;
2759                 }
2760
2761                 // create the shockwave
2762                 shockwave_create_info sci2;
2763                 sci2.blast = (sci->blast / (float)sip->shockwave_count) * frand_range(0.75f, 1.25f);
2764                 sci2.damage = (sci->damage / (float)sip->shockwave_count) * frand_range(0.75f, 1.25f);
2765                 sci2.inner_rad = sci->inner_rad;
2766                 sci2.outer_rad = sci->outer_rad;
2767                 sci2.speed = sci->speed * frand_range(0.75f, 1.25f);
2768                 sci2.rot_angle = frand_range(0.0f, 359.0f);
2769
2770                 shockwave_create(shipp->objnum, &shockwave_pos, &sci2, SW_SHIP_DEATH, (int)frand_range(0.0f, 350.0f));
2771                 // shockwave_create(shipp->objnum, &objp->pos, sip->shockwave_speed, sip->inner_rad, sip->outer_rad, sip->damage, sip->blast, SW_SHIP_DEATH);
2772
2773                 // next shockwave
2774                 cur += step;
2775         }
2776 }
2777
2778 int Wash_on = 1;
2779 DCF_BOOL(engine_wash, Wash_on);
2780 #define ENGINE_WASH_CHECK_INTERVAL              250     // (4x sec)
2781 // Do engine wash effect for ship
2782 // Assumes length of engine wash is greater than radius of engine wash hemisphere
2783 void engine_wash_ship_process(ship *shipp)
2784 {
2785         int idx, j;             
2786         object *objp, *ship_objp, *max_ship_intensity_objp;
2787         int started_with_no_wash = shipp->wash_intensity <= 0 ? 1 : 0;
2788
2789         if (!Wash_on) {
2790                 return;
2791         }
2792
2793         Assert(shipp != NULL);
2794         Assert(shipp->objnum >= 0);
2795         objp = &Objects[shipp->objnum];
2796         ship_obj *so;
2797         ship_objp = NULL;
2798
2799         vector world_thruster_pos, world_thruster_norm, apex, thruster_to_ship, apex_to_ship, temp;
2800         float dist_sqr, inset_depth, dot_to_ship, max_ship_intensity;
2801         polymodel *pm;
2802
2803         float max_wash_dist, half_angle, radius_mult;
2804
2805         // if this is not a fighter or bomber, we don't care
2806         if ((objp->type != OBJ_SHIP) || !(Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ) {
2807                 return;
2808         }
2809
2810         // is it time to check for engine wash 
2811         int time_to_next_hit = timestamp_until(shipp->wash_timestamp);
2812         if (time_to_next_hit < 0) {
2813                 if (time_to_next_hit < -ENGINE_WASH_CHECK_INTERVAL) {
2814                         time_to_next_hit = 0;
2815                 }
2816
2817                 // keep interval constant independent of framerate
2818                 shipp->wash_timestamp = timestamp(ENGINE_WASH_CHECK_INTERVAL + time_to_next_hit);
2819
2820                 // initialize wash params
2821                 shipp->wash_intensity = 0.0f;
2822                 vm_vec_zero(&shipp->wash_rot_axis);
2823                 max_ship_intensity_objp = NULL;
2824                 max_ship_intensity = 0;
2825         } else {
2826                 return;
2827         }
2828
2829         // only do damage if we're within half of the max wash distance
2830         int do_damage = 0;
2831
2832         // go thru Ship_used_list and check if we're in wash from CAP or SUPERCAP (SIF_HUGE)
2833         for (so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so)) {
2834                 ship_objp = &Objects[so->objnum];
2835
2836                 // don't do small ships
2837                 if ( (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP) ) {
2838                         continue;
2839                 }
2840
2841                 pm = model_get(Ships[ship_objp->instance].modelnum);
2842                 float ship_intensity = 0;
2843
2844                 // if engines disabled, no engine wash
2845                 if (ship_get_subsystem_strength(&Ships[ship_objp->instance], SUBSYSTEM_ENGINE) < 0.01) {
2846                         continue;
2847                 }
2848
2849                 float   speed_scale;
2850                 if (ship_objp->phys_info.speed > 20.0f)
2851                         speed_scale = 1.0f;
2852                 else
2853                         speed_scale = ship_objp->phys_info.speed/20.0f;
2854
2855                 for (idx = 0; idx < pm->n_thrusters; idx++) {
2856                         thruster_bank *bank = &pm->thrusters[idx];
2857
2858                         // check if thruster bank has engine wash
2859                         if (bank->wash_info_index < 0) {
2860                                 // if huge, give default engine wash
2861                                 if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
2862                                         bank->wash_info_index = 0;
2863                                         nprintf(("wash", "Adding default engine wash to ship %s", Ship_info[Ships[ship_objp->instance].ship_info_index].name));
2864                                 } else {
2865                                         continue;
2866                                 }
2867                         }
2868
2869                         engine_wash_info *ewp = &Engine_wash_info[bank->wash_info_index];
2870                         half_angle = ewp->angle;
2871                         radius_mult = ewp->radius_mult;
2872
2873                         for (j=0; j<bank->num_slots; j++) {
2874                                 // get world pos of thruster
2875                                 vm_vec_unrotate(&world_thruster_pos, &bank->pnt[j], &ship_objp->orient);
2876                                 vm_vec_add2(&world_thruster_pos, &ship_objp->pos);
2877                                 
2878                                 // get world norm of thruster;
2879                                 vm_vec_unrotate(&world_thruster_norm, &bank->norm[j], &ship_objp->orient);
2880
2881                                 // get vector from thruster to ship
2882                                 vm_vec_sub(&thruster_to_ship, &objp->pos, &world_thruster_pos);
2883
2884                                 // check if on back side of thruster
2885                                 dot_to_ship = vm_vec_dotprod(&thruster_to_ship, &world_thruster_norm);
2886                                 if (dot_to_ship > 0) {
2887
2888                                         // get max wash distance
2889                                         max_wash_dist = max(ewp->length, bank->radius[j]*ewp->radius_mult);
2890
2891                                         // check if within dist range
2892                                         dist_sqr = vm_vec_mag_squared(&thruster_to_ship);
2893                                         if (dist_sqr < max_wash_dist*max_wash_dist) {
2894
2895                                                 // check if inside the sphere
2896                                                 if (dist_sqr < radius_mult*radius_mult*bank->radius[j]*bank->radius[j]) {
2897                                                         vm_vec_crossprod(&temp, &world_thruster_norm, &thruster_to_ship);
2898                                                         vm_vec_scale_add2(&shipp->wash_rot_axis, &temp, dot_to_ship / dist_sqr);
2899 //                                                      shipp->wash_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2900                                                         ship_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2901                                                         if (!do_damage) {
2902                                                                 if (dist_sqr < 0.25 * max_wash_dist * max_wash_dist) {
2903                                                                         do_damage = 1;
2904                                                                 }
2905                                                         }
2906                                                 } else {
2907                                                         // check if inside cone - first fine apex of cone
2908                                                         inset_depth = float(bank->radius[j] / tan(half_angle));
2909                                                         vm_vec_scale_add(&apex, &world_thruster_pos, &world_thruster_norm, -inset_depth);
2910                                                         vm_vec_sub(&apex_to_ship, &objp->pos, &apex);
2911                                                         vm_vec_normalize(&apex_to_ship);
2912
2913                                                         // check if inside cone angle
2914                                                         if (vm_vec_dotprod(&apex_to_ship, &world_thruster_norm) > cos(half_angle)) {
2915                                                                 vm_vec_crossprod(&temp, &world_thruster_norm, &thruster_to_ship);
2916                                                                 vm_vec_scale_add2(&shipp->wash_rot_axis, &temp, dot_to_ship / dist_sqr);
2917 //                                                              shipp->wash_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2918                                                                 ship_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2919                                                                 if (!do_damage) {
2920                                                                         if (dist_sqr < 0.25 * max_wash_dist * max_wash_dist) {
2921                                                                                 do_damage = 1;
2922                                                                         }
2923                                                                 }
2924                                                         }
2925                                                 }
2926                                         }
2927                                 }
2928                         }
2929                 }
2930                 shipp->wash_intensity += ship_intensity * speed_scale;
2931                 if (ship_intensity > max_ship_intensity) {
2932                         max_ship_intensity = ship_intensity;
2933                         max_ship_intensity_objp = ship_objp;
2934                 }
2935         }
2936
2937         // apply damage at rate of 1%/sec
2938         if (shipp->wash_intensity > 0) {
2939                 Assert(max_ship_intensity_objp != NULL);
2940
2941                 nprintf(("wash", "Wash intensity %.2f\n", shipp->wash_intensity));
2942
2943                 float damage;
2944                 if (!do_damage) {
2945                         damage = 0;
2946                 } else {
2947                         damage = (0.001f * 0.003f * ENGINE_WASH_CHECK_INTERVAL * Ship_info[shipp->ship_info_index].initial_hull_strength * shipp->wash_intensity);
2948                 }
2949
2950                 ship_apply_wash_damage(&Objects[shipp->objnum], max_ship_intensity_objp, damage);
2951
2952                 // if we had no wash before now, add the wash object sound
2953                 if(started_with_no_wash){
2954                         if(shipp != Player_ship){
2955                                 obj_snd_assign(shipp->objnum, SND_ENGINE_WASH, &vmd_zero_vector, 1);
2956                         } else {                                
2957                                 Player_engine_wash_loop = snd_play_looping( &Snds[SND_ENGINE_WASH], 0.0f , -1, -1, 1.0f);
2958                         }
2959                 }
2960         } 
2961         // if we've got no wash, kill any wash object sounds from this guy
2962         else {
2963                 if(shipp != Player_ship){
2964                         obj_snd_delete(shipp->objnum, SND_ENGINE_WASH);
2965                 } else {
2966                         snd_stop(Player_engine_wash_loop);
2967                         Player_engine_wash_loop = -1;
2968                 }
2969         }
2970 }
2971
2972 // engine wash level init
2973 void shipfx_engine_wash_level_init()
2974 {
2975         Player_engine_wash_loop = -1;
2976 }
2977
2978 // pause engine wash sounds
2979 void shipfx_stop_engine_wash_sound()
2980 {
2981         if(Player_engine_wash_loop != -1){
2982                 snd_stop(Player_engine_wash_loop);
2983                 Player_engine_wash_loop = -1;
2984         }
2985 }