]> icculus.org git repositories - taylor/freespace2.git/blob - src/object/collideshipweapon.cpp
Initial revision
[taylor/freespace2.git] / src / object / collideshipweapon.cpp
1 /*
2  * $Logfile: /Freespace2/code/Object/CollideShipWeapon.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Routines to detect collisions and do physics, damage, etc for weapons and ships
8  *
9  * $Log$
10  * Revision 1.1  2002/05/03 03:28:10  root
11  * Initial revision
12  *
13  * 
14  * 13    8/30/99 11:06a Andsager
15  * Fix bug preventing ship_apply_whack()
16  * 
17  * 12    8/16/99 11:58p Andsager
18  * Disable collision on proximity for ships with SIF_DONT_COLLIDE_INVIS
19  * hulls.
20  * 
21  * 11    7/22/99 7:18p Dave
22  * Fixed excessive multiplayer collision whacks.
23  * 
24  * 10    6/30/99 5:53p Dave
25  * Put in new anti-camper code.
26  * 
27  * 9     6/25/99 3:37p Jasons
28  * Whoops. Only send pain packet for WP_LASER subtypes.
29  * 
30  * 8     6/21/99 7:24p Dave
31  * netplayer pain packet. Added type E unmoving beams.
32  * 
33  * 7     6/01/99 8:35p Dave
34  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
35  * awacs-set-radius sexpression.
36  * 
37  * 6     4/23/99 12:01p Johnson
38  * Added SIF_HUGE_SHIP
39  * 
40  * 5     3/10/99 6:50p Dave
41  * Changed the way we buffer packets for all clients. Optimized turret
42  * fired packets. Did some weapon firing optimizations.
43  * 
44  * 4     1/12/99 5:45p Dave
45  * Moved weapon pipeline in multiplayer to almost exclusively client side.
46  * Very good results. Bandwidth goes down, playability goes up for crappy
47  * connections. Fixed object update problem for ship subsystems.
48  * 
49  * 3     10/20/98 1:39p Andsager
50  * Make so sparks follow animated ship submodels.  Modify
51  * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
52  * submodel_num.  Add submodel_num to multiplayer hit packet.
53  * 
54  * 2     10/07/98 10:53a Dave
55  * Initial checkin.
56  * 
57  * 1     10/07/98 10:50a Dave
58  * 
59  * 21    4/13/98 2:14p Mike
60  * Countermeasure balance testing for Jim.
61  * 
62  * 20    4/01/98 1:48p Allender
63  * major changes to ship collision in multiplayer.  Clients now do own
64  * ship/ship collisions (with their own ship only)  Modifed the hull
65  * update packet to be sent quicker when object is target of player.
66  * 
67  * 19    3/31/98 5:18p John
68  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
69  * bunch of debug stuff out of player file.  Made model code be able to
70  * unload models and malloc out only however many models are needed.
71  *  
72  * 
73  * 18    3/25/98 1:33p Andsager
74  * Comment out assert
75  * 
76  * 17    3/16/98 5:17p Mike
77  * Fix arm time.  Make missiles not explode in first second.
78  * 
79  * 16    3/14/98 5:02p Lawrance
80  * Support arbitrary wings in the wingman status gauge
81  * 
82  * 15    2/23/98 4:30p Mike
83  * Make homing missiles detonate after they pass up their target.  Make
84  * countermeasures less effective.
85  * 
86  * 14    2/10/98 5:02p Andsager
87  * Big ship:weapon collision use flag SIF_BIG_SHIP or SIF_CAPITAL
88  * 
89  * 13    2/10/98 2:57p Jasen
90  * Andsager: predict speed when big ship has zero acceleration (ie,
91  * instalation)
92  * 
93  * 12    2/09/98 1:19p Andsager
94  * 
95  * 11    2/01/98 2:53p Mike
96  * Much better time returned by hud_ai_get_dock_time or whatever it's
97  * called.
98  * 
99  * 10    1/24/98 3:21p Lawrance
100  * Add flashing when hit, and correct association with the wingman status
101  * gauge.
102  * 
103  * 9     1/14/98 1:43p Lawrance
104  * Puncture weapons don't pass through shields any more.
105  * 
106  * 8     1/13/98 8:09p John
107  * Removed the old collision system that checked all pairs.   Added code
108  * to disable collisions and particles.
109  * 
110  * 7     11/18/97 6:00p Lawrance
111  * modify how hud_shield_quadrant_hit() gets called
112  * 
113  * 6     11/08/97 11:08p Lawrance
114  * implement new "mini-shield" view that sits near bottom of reticle
115  * 
116  * 5     11/07/97 4:36p Mike
117  * Change how ships determine they're under attack by dumbfire weapons.
118  * 
119  * 4     10/27/97 8:35a John
120  * code for new player warpout sequence
121  * 
122  * 3     9/18/97 4:08p John
123  * Cleaned up & restructured ship damage stuff.
124  * 
125  * 2     9/17/97 5:12p John
126  * Restructured collision routines.  Probably broke a lot of stuff.
127  * 
128  * 1     9/17/97 2:14p John
129  * Initial revision
130  *
131  * $NoKeywords: $
132  */
133
134 #include "objcollide.h"
135 #include "model.h"
136 #include "shiphit.h"
137 #include "player.h"
138 #include "hudshield.h"
139 #include "hud.h"
140 #include "hudwingmanstatus.h"
141 #include "timer.h"
142 #include "freespace.h"
143 #include "multi.h"
144 #include "multiutil.h"
145 #include "multimsgs.h"
146
147
148 extern float ai_endangered_time(object *ship_objp, object *weapon_objp);
149 int check_inside_radius_for_big_ships( object *ship, object *weapon, obj_pair *pair );
150 float estimate_ship_speed_upper_limit( object *ship, float time );
151 extern float flFrametime;
152
153
154 //      If weapon_obj is likely to hit ship_obj sooner than current aip->danger_weapon_objnum,
155 //      then update danger_weapon_objnum.
156 void update_danger_weapon(object *ship_obj, object *weapon_obj)
157 {
158         ai_info *aip;
159
160         Assert(ship_obj->type == OBJ_SHIP);
161
162         aip = &Ai_info[Ships[ship_obj->instance].ai_index];
163
164         if (aip->danger_weapon_objnum == -1) {
165                 aip->danger_weapon_objnum = weapon_obj-Objects;
166                 aip->danger_weapon_signature = weapon_obj->signature;
167         } else if (aip->danger_weapon_signature == Objects[aip->danger_weapon_objnum].signature) {
168                 float   danger_old_time, danger_new_time;
169
170                 danger_old_time = ai_endangered_time(ship_obj, &Objects[aip->danger_weapon_objnum]);
171                 danger_new_time = ai_endangered_time(ship_obj, weapon_obj);
172
173                 if (danger_new_time < danger_old_time) {
174                         aip->danger_weapon_objnum = weapon_obj-Objects;
175                         aip->danger_weapon_signature = weapon_obj->signature;
176                 }
177         }
178 }
179
180 // function to actually deal with weapon-ship hit stuff.  separated from check_collision routine below
181 // because of multiplayer reasons.
182 void ship_weapon_do_hit_stuff(object *ship_obj, object *weapon_obj, vector *world_hitpos, vector *hitpos, int quadrant_num, int submodel_num)
183 {
184         weapon  *wp = &Weapons[weapon_obj->instance];
185         weapon_info     *wip = &Weapon_info[wp->weapon_info_index];
186         ship *shipp = &Ships[ship_obj->instance];       
187         float damage;
188         vector force;           
189
190         // Apply hit & damage & stuff to weapon
191         weapon_hit(weapon_obj, ship_obj,  world_hitpos);
192
193         damage = wip->damage;
194
195         // deterine whack whack
196         float           blast = wip->mass;
197         vm_vec_copy_scale(&force, &weapon_obj->phys_info.vel, blast );  
198
199         // send player pain packet
200         if ( (MULTIPLAYER_MASTER) && !(shipp->flags & SF_DYING) ){
201                 int np_index = multi_find_player_by_object(ship_obj);
202
203                 // if this is a player ship
204                 if((np_index >= 0) && (np_index != MY_NET_PLAYER_NUM) && (wip->subtype == WP_LASER)){
205                         send_player_pain_packet(&Net_players[np_index], wp->weapon_info_index, wip->damage * weapon_get_damage_scale(wip, weapon_obj, ship_obj), &force, hitpos);
206                 }
207         }       
208
209         ship_apply_local_damage(ship_obj, weapon_obj, world_hitpos, damage, quadrant_num, CREATE_SPARKS, submodel_num);
210
211         // let the hud shield gauge know when Player or Player target is hit
212         hud_shield_quadrant_hit(ship_obj, quadrant_num);
213
214         // Let wingman status gauge know a wingman ship was hit
215         if ( (Ships[ship_obj->instance].wing_status_wing_index >= 0) && ((Ships[ship_obj->instance].wing_status_wing_pos >= 0)) ) {
216                 hud_wingman_status_start_flash(shipp->wing_status_wing_index, shipp->wing_status_wing_pos);
217         }
218
219         // Apply a wack.  This used to be inside of ship_hit... duh! Ship_hit
220         // is to apply damage, not physics, so I moved it here.
221         // don't apply whack for multiplayer_client from laser - will occur with pain packet
222         if( !((wip->subtype == WP_LASER) && MULTIPLAYER_CLIENT) ) {             
223                 // apply a whack                
224                 ship_apply_whack( &force, hitpos, ship_obj );
225         }
226 }
227
228 extern int Framecount;
229
230 int ship_weapon_check_collision(object * ship_obj, object * weapon_obj, float time_limit = 0.0f, int *next_hit=NULL)
231 {
232         mc_info mc;
233         int     num;
234         ship    *shipp;
235         weapon  *wp = &Weapons[weapon_obj->instance];
236         weapon_info     *wip = &Weapon_info[wp->weapon_info_index];
237
238         Assert( ship_obj->type == OBJ_SHIP );
239         Assert( weapon_obj->type == OBJ_WEAPON );
240
241         num = ship_obj->instance;
242         Assert( num >= 0 );
243         Assert( Ships[num].objnum == OBJ_INDEX(ship_obj));
244
245         shipp = &Ships[num];
246
247         // Make ships that are warping in not get collision detection done
248         if ( shipp->flags & SF_ARRIVING ) return 0;
249
250         // if one object is a capital, only check player and player weapons with
251         // the capital -- too slow for now otherwise.
252 //      if ( Polygon_models[Ships[num].modelnum].use_grid && !( (other_obj == Player_obj) || (&Objects[other_obj->parent] == Player_obj)) )
253 //              return 0;
254
255         //      If either of these objects doesn't get collision checks, abort.
256         if (!(Ship_info[shipp->ship_info_index].flags & SIF_DO_COLLISION_CHECK))
257                 return 0;
258
259         //      Return information for AI to detect incoming fire.
260         //      Could perhaps be done elsewhere at lower cost --MK, 11/7/97
261         float   dist = vm_vec_dist_quick(&ship_obj->pos, &weapon_obj->pos);
262         if (dist < weapon_obj->phys_info.speed) {
263                 update_danger_weapon(ship_obj, weapon_obj);
264         }
265         
266         ship_model_start(ship_obj);
267
268         int     valid_hit_occured = 0;                          // If this is set, then hitpos is set
269         int     do_model_check = 1;                                     // Assume we need to check the model
270         int     quadrant_num = -1;
271
272         //      total time is flFrametime + time_limit (time_limit used to predict collisions into the future)
273         vector weapon_end_pos;
274         vm_vec_scale_add( &weapon_end_pos, &weapon_obj->pos, &weapon_obj->phys_info.vel, time_limit );
275
276         memset(&mc, -1, sizeof(mc_info));
277         mc.model_num = shipp->modelnum;                 // Fill in the model to check
278         mc.orient = &ship_obj->orient;                  // The object's orient
279         mc.pos = &ship_obj->pos;                                        // The object's position
280         mc.p0 = &weapon_obj->last_pos;                  // Point 1 of ray to check
281         mc.p1 = &weapon_end_pos;                                        // Point 2 of ray to check
282
283         polymodel *pm = model_get( shipp->modelnum );
284
285         // Check the shields for an impact if necessary
286 #ifndef NDEBUG
287         if (!(ship_obj->flags & OF_NO_SHIELDS) && New_shield_system && (pm->shield.ntris > 0)) {
288 #else
289         if (!(ship_obj->flags & OF_NO_SHIELDS) &&  (pm->shield.ntris > 0)) {
290 #endif
291
292                 mc.flags = MC_CHECK_SHIELD;
293
294                 if ( model_collide(&mc) )       {
295                         quadrant_num = get_quadrant(&mc.hit_point);
296                         //      Note: This code is obviously stupid. We want to add the shield point if there is shield to hit, but:
297                         //              1. We want the size/color of the hit effect to indicate shield damage done.  (Ie, for already-weak shield, smaller effect.)
298                         //              2. Currently (8/9/97), apply_damage_to_shield() passes lefer damage to hull, which might not make sense.  If
299                         //                      wouldn't have collided with hull, shouldn't do damage.  Once this is fixed, the code below needs to cast the
300                         //                      vector through to the hull if there is leftover damage.
301                         if (!(shipp->flags & SF_DYING) && ship_is_shield_up(ship_obj,quadrant_num) ) {
302
303                                 // AL 1-14-97: "Puncture" doesn't mean penetrate shield anymore, it means that it punctures
304                                 //                                      hull do inflict maximum subsystem damage
305 /*
306                                 if ( Weapon_info[Weapons[other_obj->instance].weapon_info_index].wi_flags & WIF_PUNCTURE )      {
307                                         // If this weapon punctures the shield, then do
308                                         // the hit effect, but act like a shield collision never occurred.
309                                         quadrant_num = -1;      // ignore shield hit
310                                         add_shield_point(obj-Objects, mc.shield_hit_tri, &mc.hit_point);
311                                 } else {
312 */
313                                 valid_hit_occured = 1;
314                                 // shield effect
315                                 add_shield_point(ship_obj-Objects, mc.shield_hit_tri, &mc.hit_point);
316                                 do_model_check = 0;     // since we hit the shield, no need to check the model
317
318                         } else {
319                                 quadrant_num = -1;      // ignore shield hit
320                         }
321                 }
322         } 
323
324         // Check the model for an impact if necessary
325         if ( do_model_check )   {                       
326                 mc.flags = MC_CHECK_MODEL;                      // flags
327
328                 if (model_collide(&mc)) {
329                         valid_hit_occured = 1;
330                 }
331         }
332
333         //nprintf(("AI", "Frame %i, Hit tri = %i\n", Framecount, mc.shield_hit_tri));
334         ship_model_stop(ship_obj);
335
336         // deal with predictive collisions.  Find their actual hit time and see if they occured in current frame
337         if (next_hit && valid_hit_occured) {
338                 // find hit time
339                 *next_hit = (int) (1000.0f * (mc.hit_dist*(flFrametime + time_limit) - flFrametime) );
340                 if (*next_hit > 0)
341                         // if hit occurs outside of this frame, do not do damage 
342                         return 1;
343         }
344
345         if ( valid_hit_occured )        {
346                 ship_weapon_do_hit_stuff(ship_obj, weapon_obj, &mc.hit_point_world, &mc.hit_point, quadrant_num, mc.hit_submodel);
347         } else if ((Missiontime - wp->creation_time > F1_0/2) && (wip->wi_flags & WIF_HOMING) && (wp->homing_object == ship_obj)) {
348                 if (dist < wip->inner_radius) {
349                         vector  vec_to_ship;
350
351                         vm_vec_normalized_dir(&vec_to_ship, &ship_obj->pos, &weapon_obj->pos);
352
353                         if (vm_vec_dot(&vec_to_ship, &weapon_obj->orient.fvec) < 0.0f) {
354                                 // check if we're colliding against "invisible" ship
355                                 if (!(Ship_info[shipp->ship_info_index].flags & SIF_DONT_COLLIDE_INVIS)) {
356                                         wp->lifeleft = 0.001f;
357                                         if (ship_obj == Player_obj)
358                                                 nprintf(("Jim", "Frame %i: Weapon %i set to detonate, dist = %7.3f.\n", Framecount, weapon_obj-Objects, dist));
359                                         valid_hit_occured = 1;
360                                 }
361                         }
362
363                 }
364         }
365
366         
367         return valid_hit_occured;
368 }
369
370
371 // Checks ship-weapon collisions.  pair->a is ship and pair->b is weapon.
372 // Returns 1 if all future collisions between these can be ignored
373 int collide_ship_weapon( obj_pair * pair )
374 {
375         int             did_hit;
376         object *ship = pair->a;
377         object *weapon = pair->b;
378         
379         Assert( ship->type == OBJ_SHIP );
380         Assert( weapon->type == OBJ_WEAPON );
381
382         // Don't check collisions for player if past first warpout stage.
383         if ( Player->control_mode > PCM_WARPOUT_STAGE1) {
384                 if ( ship == Player_obj )
385                         return 0;
386         }
387
388         // Cull lasers within big ship spheres by casting a vector forward for (1) exit sphere or (2) lifetime of laser
389         // If it does hit, don't check the pair until about 200 ms before collision.  
390         // If it does not hit and is within error tolerance, cull the pair.
391
392         if ( (Ship_info[Ships[ship->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) && (Weapon_info[Weapons[weapon->instance].weapon_info_index].subtype == WP_LASER) ) {
393 //      if (  (ship->radius > 50) && (Weapon_info[Weapons[weapon->instance].weapon_info_index].subtype == WP_LASER) ) {
394                 // Check when within ~1.1 radii.  
395                 // This allows good transition between sphere checking (leaving the laser about 200 ms from radius) and checking
396                 // within the sphere with little time between.  There may be some time for "small" big ships
397                 if ( vm_vec_dist_squared(&ship->pos, &weapon->pos) < (1.2f*ship->radius*ship->radius) ) {
398                         return check_inside_radius_for_big_ships( ship, weapon, pair );
399                 }
400         }
401
402
403 //      demo_do_rand_test();
404         did_hit = ship_weapon_check_collision( ship, weapon );
405 //      demo_do_rand_test();
406         if ( !did_hit ) {
407                 // Since we didn't hit, check to see if we can disable all future collisions
408                 // between these two.
409                 return weapon_will_never_hit( weapon, ship, pair );
410         }
411
412         return 0;
413 }
414
415 // ----------------------------------------------------------------------------
416 // upper limit estimate ship speed at end of time
417 float estimate_ship_speed_upper_limit( object *ship, float time ) 
418 {
419         float exponent;
420         float delta_v;
421         float factor;
422
423         delta_v = Ship_info[Ships[ship->instance].ship_info_index].max_vel.z - ship->phys_info.speed;
424         if (ship->phys_info.forward_accel_time_const == 0) {
425                 return ship->phys_info.speed;
426         }
427         exponent = time / ship->phys_info.forward_accel_time_const;
428         //Assert( exponent >= 0);
429
430
431         factor = 1.0f - (float)exp( -exponent );
432         return ship->phys_info.speed + factor*delta_v;
433 }
434
435 // maximum error allowed in detecting collisions between laser and big ship inside the radius
436 // this is set for a 150 m radius ship.  For ships with larger radius, the error scales according
437 // to the ration of radii, but is never less than 2 m
438 #define ERROR_STD       2       
439
440 // ----------------------------------------------------------------------------                                                 
441 // check_inside_radius_for_big_ships()                                                  
442 // when inside radius of big ship, check if we can cull collision pair
443 // determine the time when pair should next be checked
444 // return 1 if pair can be culled
445 // return 0 if pair can not be culled
446 int check_inside_radius_for_big_ships( object *ship, object *weapon, obj_pair *pair )
447 {
448         vector error_vel;               // vel perpendicular to laser
449         float error_vel_mag;    // magnitude of error_vel
450         float time_to_max_error, time_to_exit_sphere;
451         float ship_speed_at_exit_sphere, error_at_exit_sphere;  
452         float max_error = (float) ERROR_STD / 150.0f * ship->radius;
453         if (max_error < 2)
454                 max_error = 2.0f;
455
456         time_to_exit_sphere = (ship->radius + vm_vec_dist(&ship->pos, &weapon->pos)) / (weapon->phys_info.max_vel.z - ship->phys_info.max_vel.z);
457         ship_speed_at_exit_sphere = estimate_ship_speed_upper_limit( ship, time_to_exit_sphere );
458         // update estimated time to exit sphere
459         time_to_exit_sphere = (ship->radius + vm_vec_dist(&ship->pos, &weapon->pos)) / (weapon->phys_info.max_vel.z - ship_speed_at_exit_sphere);
460         vm_vec_scale_add( &error_vel, &ship->phys_info.vel, &weapon->orient.fvec, -vm_vec_dotprod(&ship->phys_info.vel, &weapon->orient.fvec) );
461         error_vel_mag = vm_vec_mag_quick( &error_vel );
462         error_vel_mag += 0.5f * (ship->phys_info.max_vel.z - error_vel_mag)*(time_to_exit_sphere/ship->phys_info.forward_accel_time_const);
463         // error_vel_mag is now average velocity over period
464         error_at_exit_sphere = error_vel_mag * time_to_exit_sphere;
465         time_to_max_error = max_error / error_at_exit_sphere * time_to_exit_sphere;
466
467         // find the minimum time we can safely check into the future.
468         // limited by (1) time to exit sphere (2) time to weapon expires
469         // if ship_weapon_check_collision comes back with a hit_time > error limit, ok
470         // if ship_weapon_check_collision comes finds no collision, next check time based on error time
471         float limit_time;               // furthest time to check (either lifetime or exit sphere)
472         if ( time_to_exit_sphere < Weapons[weapon->instance].lifeleft ) {
473                 limit_time = time_to_exit_sphere;
474         } else {
475                 limit_time = Weapons[weapon->instance].lifeleft;
476         }
477
478         // Note:  when estimated hit time is less than 200 ms, look at every frame
479         int hit_time;   // estimated time of hit in ms
480
481         // modify ship_weapon_check_collision to do damage if hit_time is negative (ie, hit occurs in this frame)
482         if ( ship_weapon_check_collision( ship, weapon, limit_time, &hit_time ) ) {
483                 // hit occured in while in sphere
484                 if (hit_time < 0) {
485                         // hit occured in the frame
486                         return 1;
487                 } else if (hit_time > 200) {
488                         pair->next_check_time = timestamp(hit_time - 200);
489                         return 0;
490                         // set next check time to time - 200
491                 } else {
492                         // set next check time to next frame
493                         pair->next_check_time = 1;
494                         return 0;
495                 }
496         } else {
497                 if (limit_time > time_to_max_error) {
498                 // no hit, but beyond error tolerance
499                         if (1000*time_to_max_error > 200) {
500                                 pair->next_check_time = timestamp( (int)(1000*time_to_max_error) - 200 );
501                         } else {
502                                 pair->next_check_time = 1;
503                         }
504                         return 0;
505                 } else {
506                         // no hit and within error tolerance
507                         return 1;
508                 }
509         }
510 }