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