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