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