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