]> icculus.org git repositories - taylor/freespace2.git/blob - src/physics/physics.cpp
ryan's struct patch for gcc 2.95
[taylor/freespace2.git] / src / physics / physics.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/Physics/Physics.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Physics stuff
16  *
17  * $Log$
18  * Revision 1.4  2002/06/17 06:33:10  relnev
19  * ryan's struct patch for gcc 2.95
20  *
21  * Revision 1.3  2002/06/09 04:41:25  relnev
22  * added copyright header
23  *
24  * Revision 1.2  2002/05/03 13:34:33  theoddone33
25  * More stuff compiles
26  *
27  * Revision 1.1.1.1  2002/05/03 03:28:10  root
28  * Initial import.
29  *
30  * 
31  * 5     8/13/99 10:49a Andsager
32  * Knossos and HUGE ship warp out.  HUGE ship warp in.  Stealth search
33  * modes dont collide big ships.
34  * 
35  * 4     7/03/99 5:50p Dave
36  * Make rotated bitmaps draw properly in padlock views.
37  * 
38  * 3     5/11/99 10:16p Andsager
39  * First pass on engine wash effect.  Rotation (control input), damage,
40  * shake.  
41  * 
42  * 2     10/07/98 10:53a Dave
43  * Initial checkin.
44  * 
45  * 1     10/07/98 10:50a Dave
46  * 
47  * 125   8/26/98 4:00p Johnson
48  * Removed max velocity assert so the new huge cap ship can warp in
49  * safely.
50  * 
51  * 124   5/18/98 5:01p Comet
52  * don't do displacement checks in multiplayer
53  * 
54  * 123   4/06/98 2:38p Duncan
55  * AL: Fix potential negative sqrt due to numerical inaccuracy
56  * 
57  * 122   3/25/98 1:30p Andsager
58  * comment out physics assert
59  * 
60  * 121   3/23/98 9:48a Andsager
61  * comment out printf
62  * 
63  * 120   3/22/98 4:11p Andsager
64  * Remove global Freespace_running
65  * 
66  * 119   3/20/98 5:15p Andsager
67  * Revised calculation of rotation, shake, and velocity in response to
68  * shockwave since capital ships were seen  to shake.
69  * 
70  * 118   3/19/98 1:06p Andsager
71  * Fix bug checking excessive velocity with accelerated time.
72  * 
73  * 117   3/17/98 5:43p Andsager
74  * Modify physics checks for very slow frame rates.
75  * 
76  * 116   3/17/98 9:54a Andsager
77  * Temporary take out Int3()s in velocity checks
78  * 
79  * 115   3/17/98 9:51a Allender
80  * temporarily commented out Int3 that was causing pain
81  * 
82  * 114   3/16/98 6:07p Johnson
83  * DA:  check that ship velocity does not get too high from collisons
84  * 
85  * 113   3/16/98 4:39p Adam
86  * change Dave's asserts so that displacement checks don't get used when
87  * not "in mission"
88  * 
89  * 112   3/16/98 1:11p Andsager
90  * Turn on velocity, displacement limit checks
91  * 
92  * 111   3/12/98 5:21p Andsager
93  * Optimize physics for lasers and dumbfire missiles
94  * 
95  * 110   3/09/98 2:10p Andsager
96  * Put in checks for debris (other) with excessive velocity.
97  * 
98  * 109   3/09/98 12:59p Mike
99  * Put error checking in physics code to detect NANs.
100  * 
101  * 108   3/09/98 12:13a Andsager
102  * Add code to help find jumps in position.
103  * 
104  * 107   3/03/98 10:39a Andsager
105  * Fixed erroneous mprintf for log term in physics_apply_shock
106  * 
107  * 106   2/11/98 4:52p Mike
108  * Better attacking by ships.
109  * Fix stupidity in AI classes, which were in backward order!
110  * 
111  * 105   2/03/98 6:01p Andsager
112  * Fix excessive rotvel in debris_create.  Check using physics function
113  * check_rotvel_limit.
114  * 
115  * 104   2/03/98 10:45a Mike
116  * Comment out mprintf that could occur very often.
117  * 
118  * 103   1/29/98 2:38p Andsager
119  * Fix bug in physics_apply_shock so that large ships have a smaller
120  * effect from shockwaves.
121  * 
122  * 102   1/23/98 11:31a Andsager
123  * Added I_body_inv to phys_init.  Needed for shockwaves hitting ships in
124  * descent style physics.
125  * 
126  * 101   1/23/98 9:02a John
127  * Took out Dave's debugging Int3 since they aren't finding what he
128  * thought they would and they broke Testcode and pofview.
129  * 
130  * 100   1/22/98 5:10p Mike
131  * Fix bug with player's damp getting stuck off.
132  * 
133  * 99    1/20/98 3:13p Allender
134  * check for Player_obj being valid before doing some other andsager
135  * sanity check in physics_sim_vel
136  * 
137  * 98    1/20/98 10:08a Andsager
138  * Remove uninitialized viariable warnings.
139  * 
140  * 97    1/19/98 3:46p Allender
141  * fixed problem where a previous changed caused optimized builds to
142  * break.  Don't do a quick out on velcoity_ramp() anymore
143  * 
144  * 96    1/19/98 12:00p Dave
145  * DA:  Revise instantaneous velocity debug check to work with
146  * multiplayer.
147  * 
148  * 95    1/16/98 3:03p Andsager
149  * Fix debug info from int3() on player death.
150  * 
151  * 94    1/16/98 2:54p Andsager
152  * Fix debug info.
153  * 
154  * 93    1/16/98 2:34p Andsager
155  * Added debug code to find instantaneous acceleration.
156  * 
157  * 92    1/16/98 12:14p Andsager
158  * Add error checking for the current brief stage
159  * 
160  * 91    12/29/97 5:10p Allender
161  * fixed problems with speed not being reported properly in multiplayer
162  * games.  Made read_flying_controls take frametime as a parameter.  More
163  * ship/weapon select stuff
164  * 
165  * 90    12/29/97 12:58p Johnson
166  * don't debug rotational velocity when Fred is running
167  * 
168  * 89    12/08/97 10:29a Andsager
169  * Remove shockwave physics parameters from weapon_area_apply_blast and
170  * move into physics
171  * 
172  * 88    12/05/97 3:31p Andsager
173  * Added view shake if hit by a weapon or collisoin.
174  * 
175  * 87    12/03/97 5:47p Andsager
176  * Changed reduced damping following collision or weapon to run off time
177  * stamp. 
178  * 
179  * 86    11/24/97 1:54p Dan
180  * Mike: Comment out Assert() in physics, debug_rotvel().
181  * 
182  * 85    11/24/97 8:46a Andsager
183  * Added rotational velocity caps and debug info.
184  * 
185  * 84    11/20/97 4:01p Mike
186  * Prevent divide overflow.
187  * 
188  * 83    11/20/97 12:34a Mike
189  * Make ships coast to a stop when their engines have been destroyed.
190  * Tricky because code doesn't use damp in forward dimension.
191  * 
192  * 82    11/19/97 5:57p Mike
193  * Hmm, undid all my changes, except for the crucial removal of a blank
194  * between "physics_sim" and the open paren.
195  * 
196  * 81    11/19/97 1:26a Andsager
197  * Made shockwaves work again, including shake.
198  * 
199  * 80    11/17/97 5:15p Andsager
200  * 
201  * 79    11/13/97 6:01p Andsager
202  * Improve comment in physic_collide_whack
203  * 
204  * 78    11/13/97 5:41p Andsager
205  * Decreased the rotational whack after getting hit by lasers and
206  * missiles.
207  * 
208  * 77    10/29/97 5:01p Andsager
209  * fixed bug in collision physics (physics_collide_whack)
210  * 
211  * 76    9/16/97 5:28p Andsager
212  * calculate velocity in physics_sim_vel
213  * 
214  * 75    9/11/97 5:25p Mike
215  * Fix ! vs. & precedence bug in physics_sim_vel().
216  * 
217  * 74    9/09/97 10:14p Andsager
218  * 
219  * 73    9/04/97 5:09p Andsager
220  * implement physics using moment of inertia and mass (from BSPgen).
221  * Added to phys_info struct.  Updated ship_info, polymodel structs.
222  * Updated weapon ($Mass and $Force) and ship ($Mass -> $Density) tables
223  * 
224  * 72    9/03/97 5:43p Andsager
225  * fixed bug calculating ramp velocity after getting whacked
226  * 
227  * 71    9/02/97 4:19p Mike
228  * Comment out code at end of physics_apply_whack() that made ships nearly
229  * stop.
230  * 
231  * 70    8/29/97 10:13a Allender
232  * work on server/client prediction code -- doesn't work too well.  Made
233  * all clients simulate their own orientation with the server giving
234  * corrections every so often.
235  * 
236  * 69    8/25/97 2:41p Andsager
237  * collision code also changes ramp velocity to take account of collison.
238  * some optimization of collision physics.
239  * 
240  * 68    8/19/97 9:56a John
241  * new thruster effect fairly functional
242  * 
243  * 67    8/18/97 6:26p Andsager
244  * preliminary version of collision physics
245  * 
246  * 66    8/17/97 9:19p Andsager
247  * improvement to collision physics
248  * 
249  * 65    8/13/97 12:16p Andsager
250  * intermediate level checkin for use with collision with extended objects
251  * 
252  * 64    8/05/97 3:13p Andsager
253  * improved comments to apply_whack
254  * 
255  * 63    8/05/97 10:18a Lawrance
256  * my_rand() being used temporarily instead of rand()
257  * 
258  * 62    7/31/97 12:44p Andsager
259  * 
260  * 61    7/25/97 5:05p John
261  * fixed a potential bug in ramp_velocity when delta dist becomes 0, a
262  * bunch of sideways 8 thingys appear :-)
263  * 
264  * 
265  * 60    7/25/97 1:04p Andsager
266  * Modified physics flag PF_REDUCED_DAMP for damping when object is hit.
267  * Flag is now set in physics_apply_whack/shock and turned off in
268  * physics_sim_vel.  Weapons should not directly set this flag.
269  * 
270  * 59    7/25/97 9:07a Andsager
271  * modified apply_whack
272  * 
273  * 58    7/23/97 5:10p Andsager
274  * Enhanced shockwave effect with shake based on blast force.  
275  * 
276  * 57    7/22/97 2:40p Andsager
277  * shockwaves now cause proper rotation of ships
278  * 
279  * 56    7/21/97 4:12p Mike
280  * Two ships move as one while docked, including physics whacks.  Spin of
281  * objects when killed based on speed.
282  * 
283  * 55    7/21/97 2:19p John
284  * made descent-style physics work for testcode. fixed bug in the
285  * velocity_ramp code with t==0.0f
286  * 
287  * 54    7/17/97 8:02p Lawrance
288  * improve comments to physics_apply_whack()
289  * 
290  * 53    7/16/97 4:42p Mike
291  * Make afterburner shake viewer, not ship.
292  * Shake for limited time.
293  * Add timestamp_until() function to timer library.
294  * 
295  * 52    7/16/97 11:53a Andsager
296  * 
297  * 51    7/16/97 11:06a Andsager
298  * Allow damping on z to support shockwaves
299  * 
300  * 50    7/15/97 12:28p Andsager
301  * commented out some debug code.
302  * 
303  * 49    7/15/97 12:25p Andsager
304  * More integration with new physics.
305  * 
306  * 48    7/15/97 12:03p Andsager
307  * New physics stuff
308  * 
309  * 47    7/11/97 11:54a John
310  * added rotated 3d bitmaps.
311  * 
312  * 46    6/25/97 12:22p Mike
313  * Diminish bashing into of objects.  Make ships flying waypoints fly in
314  * formation.
315  * 
316  * 45    6/17/97 10:59p Mike
317  * Comment out irritating mprintf().
318  * 
319  * 44    6/11/97 4:27p Mike
320  * Balance the whack ships take when they get hit.
321  * 
322  * 43    4/17/97 10:02a Lawrance
323  * allow ship shaking for ABURN_DECAY_TIME after afterburners cut out
324  * 
325  * 42    4/16/97 10:48p Mike
326  * Afterburner shake.
327  * Made afterburner engagement a bit in physics flags, removed from ship
328  * flags, removed a parameter to physics_read_flying_controls().
329  * 
330  * 41    4/11/97 3:17p Mike
331  * Modify physics_sim() to use non quick version of vm_vec_mag().  Quick
332  * version was causing cumulative errors in velocity of homing missiles.
333  * 
334  * 40    4/10/97 3:20p Mike
335  * Change hull damage to be like shields.
336  * 
337  * 39    4/04/97 11:08a Adam
338  * played with banking values
339  * 
340  * 38    4/04/97 12:19a Mike
341  * Make ships bank when they turn.
342  * 
343  * 37    3/04/97 3:10p Mike
344  * Intermediate checkin: Had to resolve some build errors.  Working on two
345  * docked ships moving as one.
346  * 
347  * 36    2/25/97 7:39p Lawrance
348  * added afterburner_on flag to physics_read_flying_controls() to account
349  * for afterburner effects
350  * 
351  * 35    2/05/97 6:02p Hoffoss
352  * Added heading rotation around universal Y axis to Fred when controlling
353  * the camera.
354  * 
355  * 34    2/05/97 9:15a Mike
356  * Partial implementation of new docking system, integrated so I could
357  * update on John's new turret code.
358  * 
359  * 33    1/20/97 7:58p John
360  * Fixed some link errors with testcode.
361  * 
362  * $NoKeywords: $
363  */
364
365 #include <stdio.h>
366 #include <stdlib.h>
367 #include <string.h>
368 #include <math.h>
369
370 #include "physics.h"
371 #include "floating.h"
372 #include "player.h"
373 #include "freespace.h"
374 #include "linklist.h"
375 #include "timer.h"
376 #include "key.h"
377
378 // defines for physics functions
379 #define MAX_TURN_LIMIT  0.2618f         // about 15 degrees
380
381 #define ROT_DEBUG
382 #define ROTVEL_TOL              0.1                     // Amount of rotvel is decreased if over cap
383 #define ROTVEL_CAP              14.0                    // Rotational velocity cap for live objects
384 #define DEAD_ROTVEL_CAP 16.3                    // Rotational velocity cap for dead objects
385
386 #define MAX_SHIP_SPEED          300             // Maximum speed allowed after whack or shockwave
387 #define RESET_SHIP_SPEED        240             // Speed that a ship is reset to after exceeding MAX_SHIP_SPEED
388
389 #define SW_ROT_FACTOR                   5               // increase in rotational time constant in shockwave
390 #define SW_BLAST_DURATION               2000    // maximum duration of shockwave
391 #define REDUCED_DAMP_FACTOR     10              // increase in side_slip and acceleration time constants (scaled according to reduced damp time)
392 #define REDUCED_DAMP_VEL                30              // change in velocity at which reduced_damp_time is 2000 ms
393 #define REDUCED_DAMP_TIME               2000    // ms (2.0 sec)
394 #define WEAPON_SHAKE_TIME               500     //      ms (0.5 sec)    viewer shake time after hit by weapon (implemented via afterburner shake)
395 #define SPECIAL_WARP_T_CONST    0.651   // special warp time constant (loose 99 % of excess speed in 3 sec)
396
397 #define PHYS_DEBUG                                              // check if (vel > 500) or (displacement in one frame > 350)
398
399 void update_reduced_damp_timestamp( physics_info *pi, float impulse );
400
401 void physics_init( physics_info * pi )
402 {
403         memset( pi, 0, sizeof(physics_info) );
404
405         pi->mass = 10.0f;                                       // This ship weighs 10 units
406         pi->side_slip_time_const = 0.05f;                                       
407         pi->rotdamp = 0.1f;
408
409         pi->max_vel.xyz.x = 100.0f;             //sideways
410         pi->max_vel.xyz.y = 100.0f;             //up/down
411         pi->max_vel.xyz.z = 100.0f;             //forward
412         pi->max_rear_vel = 100.0f;      //backward -- controlled seperately
413
414         pi->max_rotvel.xyz.x = 2.0f;            //pitch 
415         pi->max_rotvel.xyz.y = 1.0f;            //heading
416         pi->max_rotvel.xyz.z = 2.0f;            //bank
417
418         pi->prev_ramp_vel.xyz.x = 0.0f;
419         pi->prev_ramp_vel.xyz.y = 0.0f;
420         pi->prev_ramp_vel.xyz.z = 0.0f;
421
422         pi->desired_vel.xyz.x = 0.0f;
423         pi->desired_vel.xyz.y = 0.0f;
424         pi->desired_vel.xyz.z = 0.0f;
425
426         pi->slide_accel_time_const=pi->side_slip_time_const;    // slide using max_vel.xyz.x & .xyz.y
427         pi->slide_decel_time_const=pi->side_slip_time_const;    // slide using max_vel.xyz.x & .xyz.y
428
429         pi->afterburner_decay = 1;      
430         pi->forward_thrust = 0.0f;
431
432         pi->flags = 0;
433
434         // default values for moment of inetaia
435         vm_vec_make( &pi->I_body_inv.v.rvec, 1e-5f, 0.0f, 0.0f );
436         vm_vec_make( &pi->I_body_inv.v.uvec, 0.0f, 1e-5f, 0.0f );
437         vm_vec_make( &pi->I_body_inv.v.fvec, 0.0f, 0.0f, 1e-5f );
438
439 }
440
441
442 //==========================================================================
443 // apply_physics - This does correct physics independent of frame rate.
444 //
445 // Given:
446 //    damping = damping factor.  Setting this to zero make the object instantly
447 //              go to the target velocity.  Increasing it makes the object ramp
448 //              up or down to the target velocity.
449 //    desired_vel = the target velocity
450 //    initial_vel = velocity at last call
451 //    t = elapsed time since last call
452 //
453 // Returns:
454 //    new_vel = current velocity
455 //    delta_pos = delta position (framevec)
456 // You can extend this to 3d by calling it 3 times, once for each x,y,z component.
457
458 void apply_physics( float damping, float desired_vel, float initial_vel, float t, float * new_vel, float * delta_pos )
459 {
460         if ( damping < 0.0001f )        {
461                 if ( delta_pos )
462                         *delta_pos = desired_vel*t;
463                 if ( new_vel )
464                         *new_vel = desired_vel;
465         } else {
466                 float dv, e;
467                 dv = initial_vel - desired_vel;
468                 e = (float)exp( -t/damping );
469                 if ( delta_pos )
470                         *delta_pos = (1.0f - e)*dv*damping + desired_vel*t;
471                 if ( new_vel )
472                         *new_vel = dv*e + desired_vel;
473         }
474 }
475
476
477
478 float Physics_viewer_bank = 0.0f;
479 int Physics_viewer_direction = PHYSICS_VIEWER_FRONT;
480 static physics_info * Viewer_physics_info = NULL;
481
482 // If you would like Physics_viewer_bank to be tracked (Which is needed
483 // for rotating 3d bitmaps) call this and pass it a pointer to the
484 // viewer's physics info.
485 void physics_set_viewer( physics_info * p, int dir )
486 {
487         if ( (Viewer_physics_info != p) || (Physics_viewer_direction != dir) )  {
488                 Viewer_physics_info = p;
489                 Physics_viewer_bank = 0.0f;
490                 Physics_viewer_direction = dir;
491         }
492 }
493
494
495
496 //      -----------------------------------------------------------------------------------------------------------
497 // add rotational velocity & acceleration
498
499
500
501 void physics_sim_rot(matrix * orient, physics_info * pi, float sim_time )
502 {
503         angles  tangles;
504         vector  new_vel;
505         matrix  tmp;
506         float           shock_amplitude;
507         float           rotdamp;
508         float           shock_fraction_time_left;
509
510         Assert(is_valid_matrix(orient));
511         Assert(is_valid_vec(&pi->rotvel));
512         Assert(is_valid_vec(&pi->desired_rotvel));
513
514         // Handle special case of shockwave
515         shock_amplitude = 0.0f;
516         if ( pi->flags & PF_IN_SHOCKWAVE ) {
517                 if ( timestamp_elapsed(pi->shockwave_decay) ) {
518                         pi->flags &= ~PF_IN_SHOCKWAVE;
519                         rotdamp = pi->rotdamp;
520                 } else {
521                         shock_fraction_time_left = timestamp_until( pi->shockwave_decay ) / (float) SW_BLAST_DURATION;
522                         rotdamp = pi->rotdamp + pi->rotdamp * (SW_ROT_FACTOR - 1) * shock_fraction_time_left;
523                         shock_amplitude = pi->shockwave_shake_amp * shock_fraction_time_left;
524                 }
525         } else {
526                 rotdamp = pi->rotdamp;
527         }
528
529         // Do rotational physics with given damping
530         apply_physics( rotdamp, pi->desired_rotvel.xyz.x, pi->rotvel.xyz.x, sim_time, &new_vel.xyz.x, NULL );
531         apply_physics( rotdamp, pi->desired_rotvel.xyz.y, pi->rotvel.xyz.y, sim_time, &new_vel.xyz.y, NULL );
532         apply_physics( rotdamp, pi->desired_rotvel.xyz.z, pi->rotvel.xyz.z, sim_time, &new_vel.xyz.z, NULL );
533
534         /*
535 #ifdef ROT_DEBUG
536         if (check_rotvel_limit( pi )) {
537                 nprintf(("Physics", "rotvel reset in physics_sim_rot\n"));
538         }
539 #endif
540 */
541         Assert(is_valid_vec(&new_vel));
542
543         pi->rotvel = new_vel;
544
545         tangles.p = pi->rotvel.xyz.x*sim_time;
546         tangles.h = pi->rotvel.xyz.y*sim_time;
547         tangles.b = pi->rotvel.xyz.z*sim_time;
548
549         // If this is the viewer_object, keep track of the
550         // changes in banking so that rotated bitmaps look correct.
551         // This is used by the g3_draw_rotated_bitmap function.
552         if ( pi == Viewer_physics_info )        {
553                 switch(Physics_viewer_direction){
554                 case PHYSICS_VIEWER_FRONT:                              
555                         Physics_viewer_bank -= tangles.b;
556                         break;
557
558                 case PHYSICS_VIEWER_UP:
559                         Physics_viewer_bank -= tangles.h;
560                         break;
561
562                 case PHYSICS_VIEWER_REAR:
563                         Physics_viewer_bank += tangles.b;
564                         break;
565
566                 case PHYSICS_VIEWER_LEFT:
567                         Physics_viewer_bank += tangles.p;
568                         break;
569
570                 case PHYSICS_VIEWER_RIGHT:
571                         Physics_viewer_bank -= tangles.p;
572                         break;
573
574                 default:
575                         Physics_viewer_bank -= tangles.b;
576                         break;
577                 }
578
579                 if ( Physics_viewer_bank < 0.0f ){
580                         Physics_viewer_bank += 2.0f * PI;
581                 }
582
583                 if ( Physics_viewer_bank > 2.0f * PI ){
584                         Physics_viewer_bank -= 2.0f * PI;
585                 }
586         }
587
588 /*      //      Make ship shake due to afterburner.
589         if (pi->flags & PF_AFTERBURNER_ON || !timestamp_elapsed(pi->afterburner_decay) ) {
590                 float   max_speed;
591
592                 max_speed = vm_vec_mag_quick(&pi->max_vel);
593                 tangles.p += (float) (rand()-RAND_MAX/2)/RAND_MAX * pi->speed/max_speed/64.0f;
594                 tangles.h += (float) (rand()-RAND_MAX/2)/RAND_MAX * pi->speed/max_speed/64.0f;
595                 if ( pi->flags & PF_AFTERBURNER_ON ) {
596                         pi->afterburner_decay = timestamp(ABURN_DECAY_TIME);
597                 }
598         }
599 */
600
601         // Make ship shake due to shockwave, decreasing in amplitude at the end of the shockwave
602         if ( pi->flags & PF_IN_SHOCKWAVE ) {
603                 tangles.p += (float) (myrand()-RAND_MAX/2)/RAND_MAX * shock_amplitude;
604                 tangles.h += (float) (myrand()-RAND_MAX/2)/RAND_MAX * shock_amplitude;
605         }
606
607
608         vm_angles_2_matrix(&pi->last_rotmat, &tangles );
609         vm_matrix_x_matrix( &tmp, orient, &pi->last_rotmat );
610         *orient = tmp;
611
612         vm_orthogonalize_matrix(orient);
613                 
614 }
615
616 //      -----------------------------------------------------------------------------------------------------------
617 // add rotational velocity & acceleration
618
619 void physics_sim_rot_editor(matrix * orient, physics_info * pi, float sim_time)
620 {
621         angles  tangles;
622         vector  new_vel;
623         matrix  tmp;
624         angles  t1, t2;
625
626         apply_physics( pi->rotdamp, pi->desired_rotvel.xyz.x, pi->rotvel.xyz.x, sim_time, 
627                                                                  &new_vel.xyz.x, NULL );
628
629         apply_physics( pi->rotdamp, pi->desired_rotvel.xyz.y, pi->rotvel.xyz.y, sim_time, 
630                                                                  &new_vel.xyz.y, NULL );
631
632         apply_physics( pi->rotdamp, pi->desired_rotvel.xyz.z, pi->rotvel.xyz.z, sim_time, 
633                                                                  &new_vel.xyz.z, NULL );
634         
635         pi->rotvel = new_vel;
636
637         tangles.p = pi->rotvel.xyz.x*sim_time;
638         tangles.h = pi->rotvel.xyz.y*sim_time;
639         tangles.b = pi->rotvel.xyz.z*sim_time;
640
641         t1 = t2 = tangles;
642         t1.h = 0.0f;  t1.b = 0.0f;
643         t2.p = 0.0f; t2.b = 0.0f;
644
645         // put in p & b like normal
646         vm_angles_2_matrix(&pi->last_rotmat, &t1 );
647         vm_matrix_x_matrix( &tmp, orient, &pi->last_rotmat );
648         
649         // Put in heading separately
650         vm_angles_2_matrix(&pi->last_rotmat, &t2 );
651         vm_matrix_x_matrix( orient, &pi->last_rotmat, &tmp );
652
653         vm_orthogonalize_matrix(orient);
654                 
655 }
656
657 // Adds velocity to position
658 // finds velocity and displacement in local coords
659 void physics_sim_vel(vector * position, physics_info * pi, float sim_time, matrix *orient)
660 {
661         vector local_disp;              // displacement in this frame
662         vector local_v_in;              // velocity in local coords at the start of this frame
663         vector local_desired_vel;       // desired velocity in local coords
664         vector local_v_out;             // velocity in local coords following this frame
665         vector damp;
666
667         //      Maybe clear the reduced_damp flag.
668         //      This fixes the problem of the player getting near-instantaneous acceleration under unknown circumstances.
669         //      The larger problem is probably that PF_USE_VEL is getting stuck set.
670         if ((pi->flags & PF_REDUCED_DAMP) && (timestamp_elapsed(pi->reduced_damp_decay))) {
671                 pi->flags &= ~PF_REDUCED_DAMP;
672         }
673
674         // Set up damping constants based on special conditions
675         // ie. shockwave, collision, weapon, dead
676         if (pi->flags & PF_DEAD_DAMP) {
677                 // side_slip_time_const is already quite large and now needs to be applied in all directions
678                 vm_vec_make( &damp, pi->side_slip_time_const, pi->side_slip_time_const, pi->side_slip_time_const );
679
680         } else if (pi->flags & PF_REDUCED_DAMP) {
681                 // case of shock, weapon, collide, etc.
682                 if ( timestamp_elapsed(pi->reduced_damp_decay) ) {
683                         vm_vec_make( &damp, pi->side_slip_time_const, pi->side_slip_time_const, 0.0f );
684                 } else {
685                         // damp is multiplied by fraction and not fraction^2, gives better collision separation
686                         float reduced_damp_fraction_time_left = timestamp_until( pi->reduced_damp_decay ) / (float) REDUCED_DAMP_TIME;
687                         damp.xyz.x = pi->side_slip_time_const * ( 1 + (REDUCED_DAMP_FACTOR-1) * reduced_damp_fraction_time_left );
688                         damp.xyz.y = pi->side_slip_time_const * ( 1 + (REDUCED_DAMP_FACTOR-1) * reduced_damp_fraction_time_left );
689                         damp.xyz.z = pi->side_slip_time_const * reduced_damp_fraction_time_left * REDUCED_DAMP_FACTOR;
690                 }
691         } else {
692                 // regular damping
693                 vm_vec_make( &damp, pi->side_slip_time_const, pi->side_slip_time_const, 0.0f );
694         }
695
696         // Note: CANNOT maintain a *local velocity* since a rotation can occur in this frame. 
697         // thus the local velocity of in the next frame can be different (this would require rotate to change local vel
698         // and this is not desired
699
700         // get local components of current velocity
701         vm_vec_rotate (&local_v_in, &pi->vel, orient);
702
703         // get local components of desired velocity
704         vm_vec_rotate (&local_desired_vel, &pi->desired_vel, orient);
705
706         // find updated LOCAL velocity and position in the local x direction
707         apply_physics (damp.xyz.x, local_desired_vel.xyz.x, local_v_in.xyz.x, sim_time, &local_v_out.xyz.x, &local_disp.xyz.x);
708
709         // find updated LOCAL velocity and position in the local y direction
710         apply_physics (damp.xyz.y, local_desired_vel.xyz.y, local_v_in.xyz.y, sim_time, &local_v_out.xyz.y, &local_disp.xyz.y);
711
712         // find updated LOCAL velocity and position in the local z direction
713         // for player ship, damp should normally be zero, but may be altered in a shockwave
714         //  in death, shockwave,etc. we want damping time const large for all 3 axes
715         // warp in test - make excessive speed drop exponentially from max allowed
716         // become (0.01x in 3 sec)
717
718         int special_warp_in = FALSE;
719         float excess = local_v_in.xyz.z - pi->max_vel.xyz.z;
720         if (excess > 5 && (pi->flags & PF_SPECIAL_WARP_IN)) {
721                 special_warp_in = TRUE;
722                 float exp_factor = float(exp(-sim_time / SPECIAL_WARP_T_CONST));
723                 local_v_out.xyz.z = pi->max_vel.xyz.z + excess * exp_factor;
724                 local_disp.xyz.z = (pi->max_vel.xyz.z * sim_time) + excess * (float(SPECIAL_WARP_T_CONST) * (1.0f - exp_factor));
725         } else if (pi->flags & PF_SPECIAL_WARP_OUT) {
726                 float exp_factor = float(exp(-sim_time / SPECIAL_WARP_T_CONST));
727                 vector temp;
728                 vm_vec_rotate(&temp, &pi->prev_ramp_vel, orient);
729                 float deficeit = temp.xyz.z - local_v_in.xyz.z;
730                 local_v_out.xyz.z = local_v_in.xyz.z + deficeit * (1.0f - exp_factor);
731                 local_disp.xyz.z = (local_v_in.xyz.z * sim_time) + deficeit * (sim_time - (float(SPECIAL_WARP_T_CONST) * (1.0f - exp_factor)));
732         } else {
733                 apply_physics (damp.xyz.z, local_desired_vel.xyz.z, local_v_in.xyz.z, sim_time, &local_v_out.xyz.z, &local_disp.xyz.z);
734         }
735
736         // maybe turn off special warp in flag
737         if ((pi->flags & PF_SPECIAL_WARP_IN) && (excess < 5)) {
738                 pi->flags &= ~(PF_SPECIAL_WARP_IN);
739         }
740
741         // update world position from local to world coords using orient
742         vector world_disp;
743         vm_vec_unrotate (&world_disp, &local_disp, orient);
744 #ifdef PHYS_DEBUG
745         // check for  excess velocity or translation
746         // GET DaveA.
747         if ( (Game_mode & GM_IN_MISSION) && (Game_mode & GM_NORMAL) ) {
748                 // Assert( (sim_time > 0.5f) || (vm_vec_mag_squared(&pi->vel) < 500*500) );
749                 // Assert( (sim_time > 0.5f) || (vm_vec_mag_squared(&world_disp) < 350*350) );
750         }
751 #endif
752         vm_vec_add2 (position, &world_disp);
753
754         // update world velocity
755         vm_vec_unrotate(&pi->vel, &local_v_out, orient);
756
757         if (special_warp_in) {
758                 vm_vec_rotate(&pi->prev_ramp_vel, &pi->vel, orient);
759         }
760 }
761
762 //      -----------------------------------------------------------------------------------------------------------
763 // Simulate a physics object for this frame
764 void physics_sim(vector* position, matrix* orient, physics_info* pi, float sim_time)
765 {
766         // check flag which tells us whether or not to do velocity translation
767         if (pi->flags & PF_CONST_VEL) {
768                 vm_vec_scale_add2(position, &pi->vel, sim_time);
769         } else {
770                 physics_sim_vel(position, pi, sim_time, orient);
771
772                 physics_sim_rot(orient, pi, sim_time);
773
774                 pi->speed = vm_vec_mag(&pi->vel);                                                       //      Note, cannot use quick version, causes cumulative error, increasing speed.
775                 pi->fspeed = vm_vec_dot(&orient->v.fvec, &pi->vel);             // instead of vector magnitude -- use only forward vector since we are only interested in forward velocity
776         }
777
778 }
779
780 //      -----------------------------------------------------------------------------------------------------------
781 // Simulate a physics object for this frame.  Used by the editor.  The difference between
782 // this function and physics_sim() is that this one uses a heading change to rotate around
783 // the universal Y axis, rather than the local orientation's Y axis.  Banking is also ignored.
784 void physics_sim_editor(vector *position, matrix * orient, physics_info * pi, float sim_time )
785 {
786         physics_sim_vel(position, pi, sim_time, orient);
787         physics_sim_rot_editor(orient, pi, sim_time);
788         pi->speed = vm_vec_mag_quick(&pi->vel);
789         pi->fspeed = vm_vec_dot(&orient->v.fvec, &pi->vel);             // instead of vector magnitude -- use only forward vector since we are only interested in forward velocity
790 }
791
792 // function to predict an object's position given the delta time and an objects physics info
793 void physics_predict_pos(physics_info *pi, float delta_time, vector *predicted_pos)
794 {
795         apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.x, pi->vel.xyz.x, delta_time, 
796                                                                  NULL, &predicted_pos->xyz.x );
797
798         apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.y, pi->vel.xyz.y, delta_time, 
799                                                                  NULL, &predicted_pos->xyz.y );
800
801         apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.z, pi->vel.xyz.z, delta_time, 
802                                                                  NULL, &predicted_pos->xyz.z );
803 }
804
805 // function to predict an object's velocity given the parameters
806 void physics_predict_vel(physics_info *pi, float delta_time, vector *predicted_vel)
807 {
808         if (pi->flags & PF_CONST_VEL) {
809                 predicted_vel = &pi->vel;
810         } else {
811                 apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.x, pi->vel.xyz.x, delta_time, 
812                                                                          &predicted_vel->xyz.x, NULL );
813
814                 apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.y, pi->vel.xyz.y, delta_time, 
815                                                                          &predicted_vel->xyz.y, NULL );
816
817                 apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.z, pi->vel.xyz.z, delta_time, 
818                                                                          &predicted_vel->xyz.z, NULL );
819         }
820 }
821
822 // function to predict position and velocity of an object
823 void physics_predict_pos_and_vel(physics_info *pi, float delta_time, vector *predicted_vel, vector *predicted_pos)
824 {
825
826         apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.x, pi->vel.xyz.x, delta_time, 
827                               &predicted_vel->xyz.x, &predicted_pos->xyz.x );
828
829         apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.y, pi->vel.xyz.y, delta_time, 
830                               &predicted_vel->xyz.y, &predicted_pos->xyz.y );
831
832         apply_physics( pi->side_slip_time_const, pi->desired_vel.xyz.z, pi->vel.xyz.z, delta_time, 
833                               &predicted_vel->xyz.z, &predicted_pos->xyz.z );
834 }
835
836 // physics_read_flying_controls() 
837 //
838 // parmeters:  *orient  ==>
839 //                                      *pi             ==>
840 //                                      *ci             ==> 
841 //      Adam: Uncomment-out this define to enable banking while turning.
842 #define BANK_WHEN_TURN
843
844
845
846 // function looks at the flying controls and the current velocity to determine a goal velocity
847 // function determines velocity in object's reference frame and goal velocity in object's reference frame
848 void physics_read_flying_controls( matrix * orient, physics_info * pi, control_info * ci, float sim_time, vector *wash_rot)
849 {
850         vector goal_vel;                // goal velocity in local coords, *not* accounting for ramping of velcity
851         float ramp_time_const;          // time constant for velocity ramping
852
853         float velocity_ramp (float v_in, float v_goal, float time_const, float t);
854
855 //      if ( keyd_pressed[KEY_LSHIFT] ) {
856 //              keyd_pressed[KEY_LSHIFT] = 0;
857 //              Int3();
858 //      }
859
860         ci->forward += (ci->forward_cruise_percent / 100.0f);
861
862 //      mprintf(("ci->forward == %7.3f\n", ci->forward));
863
864         // give control imput to cause rotation in engine wash
865         extern int Wash_on;
866         if ( wash_rot && Wash_on ) {
867                 ci->pitch += wash_rot->xyz.x;
868                 ci->bank += wash_rot->xyz.z;
869                 ci->heading += wash_rot->xyz.y;
870         }
871
872         if (ci->pitch > 1.0f ) ci->pitch = 1.0f;
873         else if (ci->pitch < -1.0f ) ci->pitch = -1.0f;
874
875         if (ci->vertical > 1.0f ) ci->vertical = 1.0f;
876         else if (ci->vertical < -1.0f ) ci->vertical = -1.0f;
877
878         if (ci->heading > 1.0f ) ci->heading = 1.0f;
879         else if (ci->heading < -1.0f ) ci->heading = -1.0f;
880
881         if (ci->sideways > 1.0f  ) ci->sideways = 1.0f;
882         else if (ci->sideways < -1.0f  ) ci->sideways = -1.0f;
883
884         if (ci->bank > 1.0f ) ci->bank = 1.0f;
885         else if (ci->bank < -1.0f ) ci->bank = -1.0f;
886
887         if ( pi->flags & PF_AFTERBURNER_ON )
888                 ci->forward = 1.0f;
889
890         if (ci->forward > 1.0f ) ci->forward = 1.0f;
891         else if (ci->forward < -1.0f ) ci->forward = -1.0f;
892
893         pi->desired_rotvel.xyz.x = ci->pitch * pi->max_rotvel.xyz.x;
894         pi->desired_rotvel.xyz.y = ci->heading * pi->max_rotvel.xyz.y;
895
896         float   delta_bank;
897
898 #ifdef BANK_WHEN_TURN
899         //      To change direction of bank, negate the whole expression.
900         //      To increase magnitude of banking, decrease denominator.
901         //      Adam: The following statement is all the math for banking while turning.
902         delta_bank = - (ci->heading * pi->max_rotvel.xyz.y)/2.0f;
903 #else
904         delta_bank = 0.0f;
905 #endif
906
907         pi->desired_rotvel.xyz.z = ci->bank * pi->max_rotvel.xyz.z + delta_bank;
908         pi->forward_thrust = ci->forward;
909
910         if ( pi->flags & PF_AFTERBURNER_ON ) {
911                 goal_vel.xyz.x = ci->sideways*pi->afterburner_max_vel.xyz.x;
912                 goal_vel.xyz.y = ci->vertical*pi->afterburner_max_vel.xyz.y;
913                 goal_vel.xyz.z = ci->forward* pi->afterburner_max_vel.xyz.z;
914         }
915         else {
916                 goal_vel.xyz.x = ci->sideways*pi->max_vel.xyz.x;
917                 goal_vel.xyz.y = ci->vertical*pi->max_vel.xyz.y;
918                 goal_vel.xyz.z = ci->forward* pi->max_vel.xyz.z;
919         }
920
921         if ( goal_vel.xyz.z < -pi->max_rear_vel ) 
922                 goal_vel.xyz.z = -pi->max_rear_vel;
923
924
925         if ( pi->flags & PF_ACCELERATES )       {
926                 //
927                 // Determine *resultant* DESIRED VELOCITY (desired_vel) accounting for RAMPING of velocity
928                 // Use LOCAL coordinates
929                 // if slide_enabled, ramp velocity for x and y, otherwise set goal (0)
930                 //    always ramp velocity for z
931                 // 
932
933                 // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast.
934                 // Scale according to reduced_damp_time_expansion.
935                 float reduced_damp_ramp_time_expansion;
936                 if ( pi->flags & PF_REDUCED_DAMP ) {
937                         float reduced_damp_fraction_time_left = timestamp_until( pi->reduced_damp_decay ) / (float) REDUCED_DAMP_TIME;
938                         reduced_damp_ramp_time_expansion = 1.0f + (REDUCED_DAMP_FACTOR-1) * reduced_damp_fraction_time_left;
939                 } else {
940                         reduced_damp_ramp_time_expansion = 1.0f;
941                 }
942
943 //      if ( !use_descent && (Player_obj->phys_info.forward_accel_time_const < 0.1) && !(Ships[Player_obj->instance].flags & SF_DYING) && (Player_obj->type != OBJ_OBSERVER) )
944 //                      Int3(); // Get dave A
945
946                 if (pi->flags & PF_SLIDE_ENABLED)  {
947                         // determine the local velocity
948                         // deterimine whether accelerating or decleration toward goal for x
949                         if ( goal_vel.xyz.x > 0.0f )  {
950                                 if ( goal_vel.xyz.x >= pi->prev_ramp_vel.xyz.x ) 
951                                         ramp_time_const = pi->slide_accel_time_const;
952                                 else
953                                         ramp_time_const = pi->slide_decel_time_const;
954                         } else  {  // goal_vel.xyz.x <= 0.0
955                                 if ( goal_vel.xyz.x <= pi->prev_ramp_vel.xyz.x )
956                                         ramp_time_const = pi->slide_accel_time_const;
957                                 else
958                                         ramp_time_const = pi->slide_decel_time_const;
959                         }
960                         // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast
961                         if ( pi->flags & PF_REDUCED_DAMP ) {
962                                 ramp_time_const *= reduced_damp_ramp_time_expansion;
963                         }
964                         pi->prev_ramp_vel.xyz.x = velocity_ramp(pi->prev_ramp_vel.xyz.x, goal_vel.xyz.x, ramp_time_const, sim_time);
965
966                         // deterimine whether accelerating or decleration toward goal for y
967                         if ( goal_vel.xyz.y > 0.0f )  {
968                                 if ( goal_vel.xyz.y >= pi->prev_ramp_vel.xyz.y ) 
969                                         ramp_time_const = pi->slide_accel_time_const;
970                                 else
971                                         ramp_time_const = pi->slide_decel_time_const;
972                         } else  {  // goal_vel.xyz.y <= 0.0
973                                 if ( goal_vel.xyz.y <= pi->prev_ramp_vel.xyz.y )
974                                         ramp_time_const = pi->slide_accel_time_const;
975                                 else
976                                         ramp_time_const = pi->slide_decel_time_const;
977                         }
978                         // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast
979                         if ( pi->flags & PF_REDUCED_DAMP ) {
980                                 ramp_time_const *= reduced_damp_ramp_time_expansion;
981                         }
982                         pi->prev_ramp_vel.xyz.y = velocity_ramp( pi->prev_ramp_vel.xyz.y, goal_vel.xyz.y, ramp_time_const, sim_time);
983                 } else  {
984                         // slide not enabled
985                         pi->prev_ramp_vel.xyz.x = 0.0f;
986                         pi->prev_ramp_vel.xyz.y = 0.0f;
987                 }
988
989                 // find ramp velocity in the forward direction
990                 if ( goal_vel.xyz.z >= pi->prev_ramp_vel.xyz.z )  {
991                         if ( pi->flags & PF_AFTERBURNER_ON )
992                                 ramp_time_const = pi->afterburner_forward_accel_time_const;
993                         else
994                                 ramp_time_const = pi->forward_accel_time_const;
995                 } else
996                         ramp_time_const = pi->forward_decel_time_const;
997
998                 // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast
999                 if ( pi->flags & PF_REDUCED_DAMP ) {
1000                         ramp_time_const *= reduced_damp_ramp_time_expansion;
1001                 }
1002                 pi->prev_ramp_vel.xyz.z = velocity_ramp( pi->prev_ramp_vel.xyz.z, goal_vel.xyz.z, ramp_time_const, sim_time);
1003
1004
1005                 // this translates local desired velocities to world velocities
1006
1007                 vm_vec_zero(&pi->desired_vel);
1008                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.rvec, pi->prev_ramp_vel.xyz.x );
1009                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.uvec, pi->prev_ramp_vel.xyz.y );
1010                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.fvec, pi->prev_ramp_vel.xyz.z );
1011         } else  // object does not accelerate  (PF_ACCELERATES not set)
1012                 pi->desired_vel = pi->vel;
1013 }
1014
1015
1016
1017 //      ----------------------------------------------------------------
1018 //      Do *dest = *delta unless:
1019 //                              *delta is pretty small
1020 //              and     they are of different signs.
1021 void physics_set_rotvel_and_saturate(float *dest, float delta)
1022 {
1023         /*
1024         if ((delta ^ *dest) < 0) {
1025                 if (abs(delta) < F1_0/8) {
1026                         // mprintf((0, "D"));
1027                         *dest = delta/4;
1028                 } else
1029                         // mprintf((0, "d"));
1030                         *dest = delta;
1031         } else {
1032                 // mprintf((0, "!"));
1033                 *dest = delta;
1034         }
1035         */
1036         *dest = delta;
1037 }
1038
1039
1040 // ----------------------------------------------------------------------------
1041 // physics_apply_whack applies an instaneous whack on an object changing
1042 // both the objects velocity and the rotational velocity based on the impulse
1043 // being applied.  
1044 //
1045 //      input:  impulse         =>              impulse vector ( force*time = impulse = change in momentum (mv) )
1046 //                              pos                     =>              vector from center of mass to location of where the force acts
1047 //                              pi                              =>              pointer to phys_info struct of object getting whacked
1048 //                              orient          =>              orientation matrix (needed to set rotational impulse in body coords)
1049 //                              mass                    =>              mass of the object (may be different from pi.mass if docked)
1050 //
1051 #define WHACK_LIMIT     0.001f
1052 #define ROTVEL_WHACK_CONST 0.12
1053 void physics_apply_whack(vector *impulse, vector *pos, physics_info *pi, matrix *orient, float mass)
1054 {
1055         vector  local_torque, torque;
1056 //      vector  npos;
1057
1058         //      Detect null vector.
1059         if ((fl_abs(impulse->xyz.x) <= WHACK_LIMIT) && (fl_abs(impulse->xyz.y) <= WHACK_LIMIT) && (fl_abs(impulse->xyz.z) <= WHACK_LIMIT))
1060                 return;
1061
1062         // first do the rotational velocity
1063         // calculate the torque on the body based on the point on the
1064         // object that was hit and the momentum being applied to the object
1065
1066         vm_vec_crossprod(&torque, pos, impulse);
1067         vm_vec_rotate ( &local_torque, &torque, orient );
1068
1069         vector delta_rotvel;
1070         vm_vec_rotate( &delta_rotvel, &local_torque, &pi->I_body_inv );
1071         vm_vec_scale ( &delta_rotvel, (float) ROTVEL_WHACK_CONST );
1072         vm_vec_add2( &pi->rotvel, &delta_rotvel );
1073
1074 #ifdef ROT_DEBUG
1075         if (check_rotvel_limit( pi )) {
1076                 nprintf(("Physics", "rotvel reset in physics_apply_whack\n"));
1077         }
1078 #endif
1079
1080         //mprintf(("Whack: %7.3f %7.3f %7.3f\n", pi->rotvel.xyz.x, pi->rotvel.xyz.y, pi->rotvel.xyz.z));
1081
1082         // instant whack on the velocity
1083         // reduce damping on all axes
1084         pi->flags |= PF_REDUCED_DAMP;
1085         update_reduced_damp_timestamp( pi, vm_vec_mag(impulse) );
1086
1087         // find time for shake from weapon to end
1088         int dtime = timestamp_until(pi->afterburner_decay);
1089         if (dtime < WEAPON_SHAKE_TIME) {
1090                 pi->afterburner_decay = timestamp( WEAPON_SHAKE_TIME );
1091         }
1092
1093         vm_vec_scale_add2( &pi->vel, impulse, 1.0f / pi->mass );
1094         if (!(pi->flags & PF_USE_VEL) && (vm_vec_mag_squared(&pi->vel) > MAX_SHIP_SPEED*MAX_SHIP_SPEED)) {
1095                 // Get DaveA
1096                 nprintf(("Physics", "speed reset in physics_apply_whack [speed: %f]\n", vm_vec_mag(&pi->vel)));
1097 //              Int3();
1098                 vm_vec_normalize(&pi->vel);
1099                 vm_vec_scale(&pi->vel, (float)RESET_SHIP_SPEED);
1100         }
1101         vm_vec_rotate( &pi->prev_ramp_vel, &pi->vel, orient );          // set so velocity will ramp starting from current speed
1102                                                                                                                                                                         // ramped velocity is now affected by collision
1103 }
1104
1105 // function generates a velocity ramp with a given time constant independent of frame rate
1106 // uses an exponential approach to desired velocity and a cheat when close to improve closure speed
1107 float velocity_ramp (float v_in, float v_goal, float ramp_time_const, float t)
1108 {
1109         float delta_v;
1110         float decay_factor;
1111         float dist;
1112
1113         // JAS: If no time elapsed, change nothing
1114         if ( t==0.0f )
1115                 return v_in;
1116
1117         delta_v = v_goal - v_in;
1118         dist = (float)fl_abs(delta_v);
1119
1120         // hack to speed up closure when close to goal
1121         if (dist < ramp_time_const/3)
1122                 ramp_time_const = dist / 3;
1123
1124         // Rather than get a divide by zero, just go to the goal
1125         if ( ramp_time_const < 0.0001f )        {
1126                 return v_goal;
1127         }
1128
1129         // determine decay factor  (ranges from 0 for short times to 1 for long times)
1130         // when decay factor is near 0, the velocity in nearly unchanged
1131         // when decay factor in near 1, the velocity approaches goal
1132         decay_factor = (float)exp(- t / ramp_time_const);
1133
1134         return (v_in + delta_v * (1.0f - decay_factor) );
1135 }
1136
1137
1138 // ----------------------------------------------------------------------------
1139 // physics_apply_shock applies applies a shockwave to an object.  This causes a velocity impulse and 
1140 // and a rotational impulse.  This is different than physics_apply_whack since a shock wave is a pressure
1141 // wave which acts over the *surface* of the object, not a point.
1142 //
1143 // inputs:      direction_vec           =>              a position vector whose direction is from the center of the shock wave to the object
1144 //                              pressure                                =>              the pressure of the shock wave at the object
1145 //                              pi                                              =>              physics_info structure
1146 //                              orient                          =>              matrix orientation of the object
1147 //                              min                                     =>              vector of minimum values of the bounding box
1148 //                              max                                     =>              vector of maximum values of the bounding box
1149 //                              radius                          =>              bounding box radius of the object, used for scaling rotation
1150 //
1151 // outputs:     makes changes to physics_info structure rotvel and vel variables
1152 //                              
1153 #define STD_PRESSURE            1000            // amplitude of standard shockwave blasts
1154 #define MIN_RADIUS                      10                      // radius within which full rotvel and shake applied
1155 #define MAX_RADIUS                      50                      // radius at which no rotvel or shake applied
1156 #define MAX_ROTVEL                      0.4             // max rotational velocity
1157 #define MAX_SHAKE                       0.1             // max rotational amplitude of shake
1158 #define MAX_VEL                         8                       // max vel from shockwave 
1159 void physics_apply_shock(vector *direction_vec, float pressure, physics_info *pi, matrix *orient, vector *min, vector *max, float radius)
1160 {
1161         vector normal;
1162         vector local_torque, temp_torque, torque;
1163         vector impact_vec;
1164         vector area;
1165         vector sin;
1166
1167         if (radius > MAX_RADIUS) {
1168                 return;
1169         }
1170
1171         vm_vec_normalize_safe ( direction_vec );
1172
1173         area.xyz.x = (max->xyz.y - min->xyz.z) * (max->xyz.z - min->xyz.z);
1174         area.xyz.y = (max->xyz.x - min->xyz.x) * (max->xyz.z - min->xyz.z);
1175         area.xyz.z = (max->xyz.x - min->xyz.x) * (max->xyz.y - min->xyz.y);
1176
1177         normal.xyz.x = vm_vec_dotprod( direction_vec, &orient->v.rvec );
1178         normal.xyz.y = vm_vec_dotprod( direction_vec, &orient->v.uvec );
1179         normal.xyz.z = vm_vec_dotprod( direction_vec, &orient->v.fvec );
1180
1181         sin.xyz.x = fl_sqrt( fl_abs(1.0f - normal.xyz.x*normal.xyz.x) );
1182         sin.xyz.y = fl_sqrt( fl_abs(1.0f - normal.xyz.y*normal.xyz.y) );
1183         sin.xyz.z = fl_sqrt( fl_abs(1.0f - normal.xyz.z*normal.xyz.z) );        
1184
1185         vm_vec_make( &torque, 0.0f, 0.0f, 0.0f );
1186
1187         // find the torque exerted due to the shockwave hitting each face
1188         //  model the effect of the shockwave as if the shockwave were a plane of projectiles,
1189         //  all moving in the direction direction_vec.  then find the torque as the cross prod
1190         //  of the force (pressure * area * normal * sin * scale * mass)
1191         //  normal takes account the fraction of the surface exposed to the shockwave
1192         //  the sin term is not technically needed but "feels" better
1193         //  scale factors out the increase in area with larger objects
1194         //  more massive objects get less rotation
1195
1196         // find torque due to forces on the right/left face
1197         if ( normal.xyz.x < 0.0f )              // normal < 0, hits the right face
1198                 vm_vec_copy_scale( &impact_vec, &orient->v.rvec, max->xyz.x * pressure * area.xyz.x *  normal.xyz.x * sin.xyz.x / pi->mass );
1199         else                                                            // normal > 0, hits the left face
1200                 vm_vec_copy_scale( &impact_vec, &orient->v.rvec, min->xyz.x * pressure * area.xyz.x * -normal.xyz.x * sin.xyz.x / pi->mass );
1201
1202         vm_vec_crossprod( &temp_torque, &impact_vec, direction_vec );
1203         vm_vec_add2( &torque, &temp_torque );
1204
1205         // find torque due to forces on the up/down face
1206         if ( normal.xyz.y < 0.0f )
1207                 vm_vec_copy_scale( &impact_vec, &orient->v.uvec, max->xyz.y * pressure * area.xyz.y *  normal.xyz.y * sin.xyz.y / pi->mass );
1208         else
1209                 vm_vec_copy_scale( &impact_vec, &orient->v.uvec, min->xyz.y * pressure * area.xyz.y * -normal.xyz.y * sin.xyz.y / pi->mass );
1210
1211         vm_vec_crossprod( &temp_torque, &impact_vec, direction_vec );
1212         vm_vec_add2( &torque, &temp_torque );
1213
1214         // find torque due to forces on the forward/backward face
1215         if ( normal.xyz.z < 0.0f )
1216                 vm_vec_copy_scale( &impact_vec, &orient->v.fvec, max->xyz.z * pressure * area.xyz.z *  normal.xyz.z * sin.xyz.z / pi->mass );
1217         else
1218                 vm_vec_copy_scale( &impact_vec, &orient->v.fvec, min->xyz.z * pressure * area.xyz.z * -normal.xyz.z * sin.xyz.z / pi->mass );
1219
1220         vm_vec_crossprod( &temp_torque, &impact_vec, direction_vec );
1221         vm_vec_add2( &torque, &temp_torque );
1222
1223         // compute delta rotvel, scale according to blast and radius
1224         float scale;
1225         vector delta_rotvel;
1226         vm_vec_rotate( &local_torque, &torque, orient );
1227         vm_vec_copy_normalize(&delta_rotvel, &local_torque);
1228         if (radius < MIN_RADIUS) {
1229                 scale = 1.0f;
1230         } else {
1231                 scale = (MAX_RADIUS - radius)/(MAX_RADIUS-MIN_RADIUS);
1232         }
1233         vm_vec_scale(&delta_rotvel, (float)(MAX_ROTVEL*(pressure/STD_PRESSURE)*scale));
1234         // nprintf(("Physics", "rotvel scale %f\n", (MAX_ROTVEL*(pressure/STD_PRESSURE)*scale)));
1235         vm_vec_add2(&pi->rotvel, &delta_rotvel);
1236
1237         // set shockwave shake amplitude, duration, flag
1238         pi->shockwave_shake_amp = (float)(MAX_SHAKE*(pressure/STD_PRESSURE)*scale);
1239         pi->shockwave_decay = timestamp( SW_BLAST_DURATION );
1240         pi->flags |= PF_IN_SHOCKWAVE;
1241
1242         // set reduced translational damping, set flags
1243         float velocity_scale = (float)MAX_VEL*scale;
1244         pi->flags |= PF_REDUCED_DAMP;
1245         update_reduced_damp_timestamp( pi, velocity_scale*pi->mass );
1246         vm_vec_scale_add2( &pi->vel, direction_vec, velocity_scale );
1247         vm_vec_rotate(&pi->prev_ramp_vel, &pi->vel, orient);    // set so velocity will ramp starting from current speed
1248
1249         // check that kick from shockwave is not too large
1250         if (!(pi->flags & PF_USE_VEL) && (vm_vec_mag_squared(&pi->vel) > MAX_SHIP_SPEED*MAX_SHIP_SPEED)) {
1251                 // Get DaveA
1252                 nprintf(("Physics", "speed reset in physics_apply_shock [speed: %f]\n", vm_vec_mag(&pi->vel)));
1253 //              Int3();
1254                 vm_vec_normalize(&pi->vel);
1255                 vm_vec_scale(&pi->vel, (float)RESET_SHIP_SPEED);
1256         }
1257
1258 #ifdef ROT_DEBUG
1259         if (check_rotvel_limit( pi )) {
1260                 nprintf(("Physics", "rotvel reset in physics_apply_shock\n"));
1261         }
1262 #endif
1263
1264                                                                                                                                                                 // ramped velocity is now affected by collision
1265 }
1266
1267 // ----------------------------------------------------------------------------
1268 // physics_collide_whack applies an instaneous whack on an object changing
1269 // both the objects velocity and the rotational velocity based on the impulse
1270 // being applied.  
1271 //
1272 //      input:  impulse                                 =>              impulse vector ( force*time = impulse = change in momentum (mv) )
1273 //                              world_delta_rotvel      =>              change in rotational velocity (already calculated)
1274 //                              pi                                                      =>              pointer to phys_info struct of object getting whacked
1275 //                              orient                                  =>              orientation matrix (needed to set rotational impulse in body coords)
1276 //
1277
1278 // Warning:  Do not change ROTVEL_COLLIDE_WHACK_CONST.  This will mess up collision physics.
1279 // If you need to change the rotation, change  COLLISION_ROTATION_FACTOR in collide_ship_ship.
1280 #define ROTVEL_COLLIDE_WHACK_CONST 1.0
1281 void physics_collide_whack( vector *impulse, vector *world_delta_rotvel, physics_info *pi, matrix *orient )
1282 {
1283         vector  body_delta_rotvel;
1284
1285         //      Detect null vector.
1286         if ((fl_abs(impulse->xyz.x) <= WHACK_LIMIT) && (fl_abs(impulse->xyz.y) <= WHACK_LIMIT) && (fl_abs(impulse->xyz.z) <= WHACK_LIMIT))
1287                 return;
1288
1289         vm_vec_rotate( &body_delta_rotvel, world_delta_rotvel, orient );
1290 //      vm_vec_scale( &body_delta_rotvel, (float)       ROTVEL_COLLIDE_WHACK_CONST );
1291         vm_vec_add2( &pi->rotvel, &body_delta_rotvel );
1292
1293 #ifdef ROT_DEBUG
1294         if (check_rotvel_limit( pi )) {
1295                 nprintf(("Physics", "rotvel reset in physics_collide_whack\n"));
1296         }
1297 #endif
1298
1299         update_reduced_damp_timestamp( pi, vm_vec_mag(impulse) );
1300
1301         // find time for shake from weapon to end
1302         int dtime = timestamp_until(pi->afterburner_decay);
1303         if (dtime < WEAPON_SHAKE_TIME) {
1304                 pi->afterburner_decay = timestamp( WEAPON_SHAKE_TIME );
1305         }
1306
1307         pi->flags |= PF_REDUCED_DAMP;
1308         vm_vec_scale_add2( &pi->vel, impulse, 1.0f / pi->mass );
1309         // check that collision does not give ship too much speed
1310         // reset if too high
1311         if (!(pi->flags & PF_USE_VEL) && (vm_vec_mag_squared(&pi->vel) > MAX_SHIP_SPEED*MAX_SHIP_SPEED)) {
1312                 // Get DaveA
1313                 nprintf(("Physics", "speed reset in physics_collide_whack [speed: %f]\n", vm_vec_mag(&pi->vel)));
1314 //              Int3();
1315                 vm_vec_normalize(&pi->vel);
1316                 vm_vec_scale(&pi->vel, (float)RESET_SHIP_SPEED);
1317         }
1318         vm_vec_rotate( &pi->prev_ramp_vel, &pi->vel, orient );          // set so velocity will ramp starting from current speed
1319                                                                                                                                                                         // ramped velocity is now affected by collision
1320         // rotate previous ramp velocity (in model coord) to be same as vel (in world coords)
1321 }
1322
1323
1324 int check_rotvel_limit( physics_info *pi )
1325 {
1326         if ( 0 == pi->flags )           // weapon
1327                 return 0;
1328
1329         if ( Fred_running )
1330                 return 0;
1331
1332         int change_made = 0;
1333         if ( !(pi->flags & PF_DEAD_DAMP) ) {
1334                 // case of normal, live ship
1335                 // -- Commented out by MK: Assert( vm_vec_mag_squared(&pi->max_rotvel) > ROTVEL_TOL );
1336                 // Assert( (pi->max_rotvel.xyz.x <= ROTVEL_CAP) && (pi->max_rotvel.xyz.y <= ROTVEL_CAP) && (pi->max_rotvel.xyz.z <= ROTVEL_CAP) );
1337                 //              Warning(LOCATION,"Excessive rotvel (wx: %f, wy: %f, wz:%f)\n", pi->rotvel.xyz.x, pi->rotvel.xyz.y, pi->rotvel.xyz.z);
1338                 if ( fl_abs(pi->rotvel.xyz.x) > pi->max_rotvel.xyz.x ) {
1339                         pi->rotvel.xyz.x = (pi->rotvel.xyz.x / fl_abs(pi->rotvel.xyz.x)) * (pi->max_rotvel.xyz.x - (float) ROTVEL_TOL);
1340                         change_made = 1;
1341                 }
1342                 if ( fl_abs(pi->rotvel.xyz.y) > pi->max_rotvel.xyz.y ) {
1343                         pi->rotvel.xyz.y = (pi->rotvel.xyz.y / fl_abs(pi->rotvel.xyz.y)) * (pi->max_rotvel.xyz.y - (float) ROTVEL_TOL);
1344                         change_made = 1;
1345                 }
1346                 if ( fl_abs(pi->rotvel.xyz.z) > pi->max_rotvel.xyz.z ) {
1347                         pi->rotvel.xyz.z = (pi->rotvel.xyz.z / fl_abs(pi->rotvel.xyz.z)) * (pi->max_rotvel.xyz.z - (float) ROTVEL_TOL);
1348                         change_made = 1;
1349                 }
1350         } else { 
1351                 // case of dead ship
1352                 if ( fl_abs(pi->rotvel.xyz.x) > DEAD_ROTVEL_CAP ) {
1353                         pi->rotvel.xyz.x = (pi->rotvel.xyz.x / fl_abs(pi->rotvel.xyz.x)) * (float) (DEAD_ROTVEL_CAP - ROTVEL_TOL);
1354                         change_made = 1;
1355                 }
1356                 if ( fl_abs(pi->rotvel.xyz.y) > DEAD_ROTVEL_CAP ) {
1357                         pi->rotvel.xyz.y = (pi->rotvel.xyz.y / fl_abs(pi->rotvel.xyz.y)) * (float) (DEAD_ROTVEL_CAP - ROTVEL_TOL);
1358                         change_made = 1;
1359                 }
1360                 if ( fl_abs(pi->rotvel.xyz.z) > DEAD_ROTVEL_CAP ) {
1361                         pi->rotvel.xyz.z = (pi->rotvel.xyz.z / fl_abs(pi->rotvel.xyz.z)) * (float) (DEAD_ROTVEL_CAP - ROTVEL_TOL);
1362                         change_made = 1;
1363                 }
1364         }
1365         return change_made;
1366 }
1367
1368 // ----------------------------------------------------------------------------
1369 // update_reduced_damp_timestamp()
1370 //
1371 void update_reduced_damp_timestamp( physics_info *pi, float impulse )
1372 {
1373
1374         // Compute duration of reduced damp from present
1375         // Compare with current value and increase if greater, otherwise ignore
1376         int reduced_damp_decay_time;
1377         reduced_damp_decay_time = (int) (REDUCED_DAMP_TIME * impulse / (REDUCED_DAMP_VEL * pi->mass));
1378         if ( reduced_damp_decay_time > REDUCED_DAMP_TIME )
1379                 reduced_damp_decay_time = REDUCED_DAMP_TIME;
1380
1381         // Reset timestamp if larger than current (if any)
1382         if ( timestamp_valid( pi->reduced_damp_decay ) ) {
1383                 int time_left = timestamp_until( pi->reduced_damp_decay );
1384                 if ( time_left > 0 ) {
1385                         // increment old time, but apply cap
1386                         int new_time = reduced_damp_decay_time + time_left;
1387                         if ( new_time < REDUCED_DAMP_TIME ) {
1388                                 pi->reduced_damp_decay = timestamp( new_time );
1389                         }
1390                 } else {
1391                         pi->reduced_damp_decay = timestamp( reduced_damp_decay_time );
1392                 }
1393         } else {
1394                 // set if not valid
1395                 pi->reduced_damp_decay = timestamp( reduced_damp_decay_time );
1396         }
1397
1398 }
1399