2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
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
10 * $Logfile: /Freespace2/code/Ship/AiCode.cpp $
15 * AI code that does interesting stuff
18 * Revision 1.11 2006/04/26 19:45:22 taylor
19 * fix a FS1 docked speed issue, should keep it in line with the original now
21 * Revision 1.10 2005/03/29 02:18:47 taylor
22 * Various 64-bit platform fixes
23 * Fix compiler errors with MAKE_FS1 and fix gr_set_bitmap() too
24 * Make sure that turrets can fire at asteroids for FS1 (needed for a couple missions)
25 * Streaming audio support (big thanks to Pierre Willenbrock!!)
26 * Removed dependance on strings.tbl for FS1 since we don't actually need it now
28 * Revision 1.9 2004/09/20 01:31:44 theoddone33
31 * Revision 1.8 2003/08/03 16:10:30 taylor
32 * cleanup; compile warning fixes
34 * Revision 1.7 2003/05/25 02:30:43 taylor
37 * Revision 1.6 2002/07/13 19:47:02 theoddone33
38 * Fix some more warnings
40 * Change demo building, edit Makefile if you want the demo.
42 * Revision 1.5 2002/06/17 06:33:10 relnev
43 * ryan's struct patch for gcc 2.95
45 * Revision 1.4 2002/06/09 04:41:26 relnev
46 * added copyright header
48 * Revision 1.3 2002/06/01 07:12:34 relnev
49 * a few NDEBUG updates.
51 * removed a few warnings.
53 * Revision 1.2 2002/05/03 13:34:33 theoddone33
56 * Revision 1.1.1.1 2002/05/03 03:28:10 root
60 * 107 9/15/99 4:42a Mikek
61 * Make any big ship attacking Colossus, or Colossus attacking any large
62 * ship not use big cruiser movement code.
64 * 106 9/15/99 3:28a Jimb
65 * Make all big ships in sm3-08 not do cruiser chase code when attacking
66 * Colossus. Added so Beast doesn't swerve away from Colossus.
68 * 105 9/14/99 4:18p Andsager
69 * hack for mission sm3-08 to abort cruiser_chase as sathanas is about to
70 * begin circling colossus.
72 * 104 9/08/99 10:44p Andsager
73 * Make HUGE ships not die when warping out, after warp effect started.
75 * 103 9/03/99 11:40p Mikek
76 * Comment out an annoying nprintf().
78 * 102 9/01/99 11:26p Dave
79 * Fixed release build warnings.
81 * 101 9/01/99 9:12p Mikek
82 * Make it a boatload harder to become a traitor from hitting a large
85 * 100 9/01/99 4:01p Andsager
86 * Make sure BIG|HUGE ships do not respond to shockwaves
88 * 99 9/01/99 10:09a Dave
91 * 98 8/31/99 4:24p Andsager
92 * Reduce collisions when attacking big ships.
94 * 97 8/31/99 7:33a Mikek
95 * Improvements in formation flying, less silly behavior, especially when
96 * leader is moving very slowly.
98 * 96 8/31/99 5:48a Mikek
99 * Making ships not overshoot so much in formation flying. Intermediate
102 * 95 8/30/99 12:03a Mikek
103 * Make guard behavior much less annoying. Guarders don't get quite so
104 * close and they try to avoid striking the target they are guarding.
106 * 94 8/29/99 4:18p Andsager
107 * New "burst" limit for friendly damage. Also credit more damage done
108 * against large friendly ships.
110 * 93 8/28/99 7:29p Dave
111 * Fixed wingmen persona messaging. Make sure locked turrets don't count
112 * towards the # attacking a player.
114 * 92 8/26/99 10:46p Andsager
115 * Apply shockwave damage to lethality.
117 * 91 8/26/99 8:52p Dave
118 * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
120 * 90 8/26/99 5:14p Andsager
122 * 89 8/24/99 8:55p Dave
123 * Make sure nondimming pixels work properly in tech menu.
125 * 88 8/23/99 6:21p Jefff
126 * added "no traitor" option to missions (and fred)
128 * 87 8/20/99 3:36p Andsager
129 * Make sure we don;t miss stealth sweep points.
131 * 86 8/16/99 8:21a Andsager
134 * 85 8/16/99 8:19a Andsager
135 * Add project_point_onto_bbox() to fvi and include in aicode
137 * 84 8/15/99 1:30p Dave
138 * Removed some bounding box code because of link errors. Assuming needed
139 * function just needs to get checked in by DaveA.
141 * 83 8/15/99 11:59a Andsager
142 * For targing big/huge ships, find nearest distance to bbox, not center.
144 * 82 8/13/99 2:20p Andsager
145 * Add speed modification to chances turret will find stealth ship
147 * 81 8/13/99 10:49a Andsager
148 * Knossos and HUGE ship warp out. HUGE ship warp in. Stealth search
149 * modes dont collide big ships.
151 * 80 8/10/99 5:02p Andsager
152 * Fix bug where AI gets stuck in SM_EVADE_WEAPON with no target.
154 * 79 8/10/99 11:58a Andsager
155 * Allow turrets to sometimes see stealth.
157 * 78 7/31/99 2:57p Dave
158 * Scaled flak aim and jitter by weapon subsystem strength.
160 * 77 7/27/99 10:33p Andsager
161 * improve ai for attacking stealth. reduced jitter in aim. reduced
162 * error in position when avoiding. skill level support for attacking
163 * stealth. Made target error same for team vs. team.
165 * 76 7/27/99 10:49a Andsager
166 * Make turret fire rate independent of team for HUGE turrets, and also
167 * for mult team vs. team.
169 * 75 7/26/99 12:14p Andsager
170 * Apply cap to how much slower a transport flies with cargo. Remove
171 * limit on waypoint speed for training. Enemy ai get stealth exact pos
174 * 74 7/20/99 1:49p Dave
175 * Peter Drake build. Fixed some release build warnings.
177 * 73 7/19/99 2:13p Dave
178 * Added some new strings for Heiko.
180 * 72 7/19/99 12:02p Andsager
181 * Allow AWACS on any ship subsystem. Fix sexp_set_subsystem_strength to
182 * only blow up subsystem if its strength is > 0
184 * 71 7/15/99 9:20a Andsager
185 * FS2_DEMO initial checkin
187 * 70 7/14/99 1:44p Andsager
188 * modify ai_guard for BIG ships to circle around the long axis
190 * 69 7/09/99 5:54p Dave
191 * Seperated cruiser types into individual types. Added tons of new
192 * briefing icons. Campaign screen.
194 * 68 7/08/99 4:32p Andsager
195 * fix bug with turret-tagged-only
197 * 67 7/08/99 12:06p Andsager
198 * Add turret-tagged-only and turret-tagged-clear sexp.
200 * 66 7/02/99 3:49p Andsager
201 * Remove debug code. Allow targeting of stealth from any weapon it
204 * 65 7/02/99 2:01p Andsager
205 * Fix bug where big ship tries to evade dumpfire weapon.
207 * 64 7/02/99 10:58a Andsager
208 * Put in big ship - big ship attack mode. Modify stealth sweep ai.
210 * 63 6/30/99 5:53p Dave
211 * Put in new anti-camper code.
213 * 62 6/28/99 3:22p Anoop
214 * Fix turret optimization, where ship may not have any valid subsystems
217 * 61 6/25/99 5:56p Andsager
218 * First real pass on stealth ai.
220 * 60 6/25/99 3:08p Dave
221 * Multiple flyby sounds.
223 * 59 6/25/99 1:12p Danw
224 * DKA: Make sure big ship has subsystems before trying to target them.
226 * 58 6/25/99 10:56a Johnson
227 * Fixed dumb ai code.
229 * 57 6/24/99 5:15p Dave
230 * Make sure stride is always at least one for checking turret subsystem
233 * 56 6/24/99 4:59p Dave
234 * Significant speedups to turret firing.
236 * 55 6/23/99 5:51p Andsager
237 * Add waypoint-cap-speed. Checkin stealth ai - inactive.
239 * 54 6/16/99 10:21a Dave
240 * Added send-message-list sexpression.
242 * 53 6/15/99 9:25a Andsager
243 * Make guard and dynamic chase (who hit you) work with stealth
245 * 52 6/14/99 3:21p Andsager
246 * Allow collisions between ship and its debris. Fix up collision pairs
247 * when large ship is warping out.
249 * 51 6/14/99 10:45a Dave
250 * Made beam weapons specify accuracy by skill level in the weapons.tbl
252 * 50 6/03/99 8:11a Andsager
254 * 49 6/02/99 5:41p Andsager
255 * Reduce range of secondary weapons not fired from turrets in nebula.
256 * Reduce range of beams fired from turrrets in nebula
258 * 48 6/02/99 3:23p Andsager
259 * Make AI aware of team visibility. Allow player targeting with team
260 * visibility info. Make stealth ships not targetable by AI in nebula
263 * 47 6/02/99 12:52p Andsager
264 * Added team-wide ship visibility. Implemented for player.
266 * 46 6/01/99 8:35p Dave
267 * Finished lockarm weapons. Added proper supercap weapons/damage. Added
268 * awacs-set-radius sexpression.
270 * 45 5/28/99 5:35p Andsager
271 * Make ai nebula aware
273 * 44 5/24/99 9:55a Dave
274 * Fixed stream weapon ai firing problem. ick.
276 * 43 5/20/99 7:00p Dave
277 * Added alternate type names for ships. Changed swarm missile table
280 * 42 5/18/99 1:30p Dave
281 * Added muzzle flash table stuff.
283 * 41 5/12/99 2:55p Andsager
284 * Implemented level 2 tag as priority in turret object selection
286 * 40 5/12/99 10:42a Andsager
287 * Fix turret bug allowing HUGE turrets to fire at fighters
289 * 39 5/06/99 11:46a Andsager
290 * Bug fixes. Don't get into illegal strafe submode. Don't choose turret
291 * enemy objnum for beam protected.
293 * 38 5/03/99 10:50p Andsager
294 * Make Asteroid_obj_list. Change get_nearest_turret_objnum() to use
295 * Asteroid_obj_list, Ship_obj_list and Missile_obj_list vs.
298 * 37 4/29/99 2:29p Dave
299 * Made flak work much better in multiplayer.
301 * 36 4/28/99 11:36p Dave
302 * Tweaked up subspace missile strike a bit,
304 * 35 4/28/99 3:11p Andsager
305 * Stagger turret weapon fire times. Make turrets smarter when target is
306 * protected or beam protected. Add weaopn range to weapon info struct.
308 * 34 4/26/99 10:58a Andsager
309 * Add OF_BEAM_PROTECTED flag to keep object from being targeted for zing.
311 * 33 4/23/99 12:12p Andsager
312 * Modify wing positions when player is wing leader to prevent some
315 * 32 4/23/99 12:01p Johnson
316 * Added SIF_HUGE_SHIP
318 * 31 4/22/99 11:06p Dave
319 * Final pass at beam weapons. Solidified a lot of stuff. All that remains
320 * now is to tweak and fix bugs as they come up. No new beam weapon
323 * 30 4/20/99 6:39p Dave
324 * Almost done with artillery targeting. Added support for downloading
325 * images on the PXO screen.
327 * 29 4/20/99 3:40p Andsager
328 * Changes to big ship ai. Uses bounding box as limit where to fly to
331 * 28 4/16/99 5:54p Dave
332 * Support for on/off style "stream" weapons. Real early support for
333 * target-painting lasers.
335 * 27 4/02/99 9:55a Dave
336 * Added a few more options in the weapons.tbl for beam weapons. Attempt
337 * at putting "pain" packets into multiplayer.
339 * 26 3/28/99 5:58p Dave
340 * Added early demo code. Make objects move. Nice and framerate
341 * independant, but not much else. Don't use yet unless you're me :)
343 * 25 3/19/99 9:51a Dave
344 * Checkin to repair massive source safe crash. Also added support for
345 * pof-style nebulae, and some new weapons code.
347 * 24 3/08/99 7:03p Dave
348 * First run of new object update system. Looks very promising.
350 * 23 3/05/99 3:55p Anoop
351 * Handle some asserts properly.
353 * 22 3/04/99 6:09p Dave
354 * Added in sexpressions for firing beams and checking for if a ship is
357 * 21 3/02/99 9:25p Dave
358 * Added a bunch of model rendering debug code. Started work on fixing
359 * beam weapon wacky firing.
361 * 20 2/25/99 2:32p Anoop
362 * (Alan). Fixed ai path following code for AI_BAY_EMERGE. Put in sanity
363 * check so that when the last point on the path is reached, it finishes.
365 * 19 2/19/99 2:11p Anoop
366 * Put in some nice handling code for wacky support ship problems (like no
369 * 18 2/17/99 2:11p Dave
370 * First full run of squad war. All freespace and tracker side stuff
373 * 17 2/11/99 5:22p Andsager
374 * Fixed bugs, generalized block Sexp_variables
376 * 16 1/29/99 5:07p Dave
377 * Fixed multiplayer stuff. Put in multiplayer support for rapid fire
380 * 15 1/29/99 2:25p Andsager
381 * Added turret_swarm_missiles
383 * 14 1/27/99 9:56a Dave
384 * Temporary checkin of beam weapons for Dan to make cool sounds.
386 * 13 1/24/99 11:37p Dave
387 * First full rev of beam weapons. Very customizable. Removed some bogus
388 * Int3()'s in low level net code.
390 * 12 1/21/99 10:44a Dave
391 * More beam weapon stuff. Put in warmdown time.
393 * 11 1/12/99 5:45p Dave
394 * Moved weapon pipeline in multiplayer to almost exclusively client side.
395 * Very good results. Bandwidth goes down, playability goes up for crappy
396 * connections. Fixed object update problem for ship subsystems.
398 * 10 1/08/99 2:08p Dave
399 * Fixed software rendering for pofview. Super early support for AWACS and
402 * 9 12/23/98 2:53p Andsager
403 * Added ship activation and gas collection subsystems, removed bridge
405 * 8 11/12/98 12:13a Dave
406 * Tidied code up for multiplayer test. Put in network support for flak
409 * 7 11/05/98 5:55p Dave
410 * Big pass at reducing #includes
412 * 6 10/26/98 9:42a Dave
413 * Early flak gun support.
415 * 5 10/23/98 3:51p Dave
416 * Full support for tstrings.tbl and foreign languages. All that remains
417 * is to make it active in Fred.
419 * 4 10/20/98 1:39p Andsager
420 * Make so sparks follow animated ship submodels. Modify
421 * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
422 * submodel_num. Add submodel_num to multiplayer hit packet.
424 * 3 10/13/98 9:29a Dave
425 * Started neatening up freespace.h. Many variables renamed and
426 * reorganized. Added AlphaColors.[h,cpp]
428 * 2 10/07/98 10:53a Dave
431 * 1 10/07/98 10:51a Dave
437 // This module contains the actual AI code that does interesting stuff
438 // to objects. The code in Ai.cpp is just for bookeeping, allocating
439 // ai slots and linking them to ships.
443 #include "linklist.h"
452 #include "floating.h"
454 #include "freespace.h"
456 #include "missiongoals.h"
457 #include "missionlog.h"
462 #include "hudmessage.h"
463 #include "missionmessage.h"
464 #include "cmeasure.h"
465 #include "staticrand.h"
466 #include "multimsgs.h"
467 #include "afterburner.h"
472 #include "multiutil.h"
474 #include "objcollide.h"
475 #include "asteroid.h"
477 #include "missiontraining.h"
478 #include "gamesequence.h"
480 #include "localize.h"
485 #include "multi_team.h"
490 #pragma optimize("", off)
491 #pragma auto_inline(off)
494 #define UNINITIALIZED_VALUE -99999.9f
496 #define INSTRUCTOR_SHIP_NAME NOX("instructor")
498 #define AICODE_SMALL_MAGNITUDE 0.001f // cosider a vector NULL if mag is less than this
500 #define NEXT_REARM_TIMESTAMP (60*1000) // Ships will re-request rearm, typically, after this long.
502 #define BEAM_NEBULA_RANGE_REDUCE_FACTOR 0.8
504 // AIM_CHASE submode defines
506 #define SM_SF_AHEAD 0
507 #define SM_SF_BEHIND 1
511 #define SM_SS_SET_GOAL -1
523 const char *Mode_text[MAX_AI_BEHAVIORS] = {
547 // Submode text is only valid for CHASE mode.
548 const char *Submode_text[] = {
569 const char *Strafe_submode_text[5] = {
579 // Used for global ignore of objects. If an object appears in the Ignore_objects array,
580 // no one will attack it.
581 #define MAX_IGNORE_OBJECTS 16
587 ignore_object Ignore_objects[MAX_IGNORE_OBJECTS];
590 typedef struct eval_enemy_obj_struct {
591 int turret_parent_objnum; // parent of turret
592 float weapon_travel_dist; // max targeting range of turret weapon
594 int weapon_system_ok; // is the weapon subsystem of turret ship ok
595 int big_only_flag; // turret fires only at big and huge ships
598 ship_subsys *turret_subsys;
602 float nearest_attacker_dist; // nearest ship
603 int nearest_attacker_objnum;
605 float nearest_homing_bomb_dist; // nearest homing bomb
606 int nearest_homing_bomb_objnum;
608 float nearest_bomb_dist; // nearest non-homing bomb
609 int nearest_bomb_objnum;
611 float nearest_dist; // nearest ship attacking this turret
613 } eval_enemy_obj_struct;
621 waypoint_list Waypoint_lists[MAX_WAYPOINT_LISTS];
623 // How close a turret has to be point at its target before it
624 // can fire. If the dot of the gun normal and the vector from gun
625 // to target is greater than this, the turret fires. The smaller
626 // the sloppier the shooting.
627 #define AICODE_TURRET_DUMBFIRE_ANGLE (0.8f)
628 #define AICODE_TURRET_HEATSEEK_ANGLE (0.7f)
629 #define AICODE_TURRET_MAX_TIME_IN_RANGE (5.0f)
631 #define REARM_SOUND_DELAY (3*F1_0) // Amount of time to delay rearm/repair after mode start
632 #define REARM_BREAKOFF_DELAY (3*F1_0) // Amount of time to wait after fully rearmed to breakoff.
634 #define MIN_DIST_TO_WAYPOINT_GOAL 5.0f
635 #define MAX_GUARD_DIST 250.0f
636 #define BIG_GUARD_RADIUS 500.0f
638 #define MAX_EVADE_TIME (15 * 1000) // Max time to evade a weapon.
640 // defines for repair ship stuff.
641 #define MAX_REPAIR_SPEED 25.0f
642 #define MAX_UNDOCK_ABORT_SPEED 2.0f
644 // defines for EMP effect stuff
645 #define MAX_EMP_INACCURACY 50.0f
647 // defines for stealth
648 #define MAX_STEALTH_INACCURACY 50.0f // at max view dist
649 #define STEALTH_MAX_VIEW_DIST 400 // dist at which 1) stealth no longer visible 2) firing inaccuracy is greatest
650 #define STEALTH_VIEW_CONE_DOT 0.707 // (half angle of 45 degrees)
653 ai_class Ai_classes[MAX_AI_CLASSES];
654 int Ai_firing_enabled = 1;
657 int AI_FrameCount = 0;
658 int Ship_info_inited = 0;
659 int AI_watch_object = 0; // Debugging, object to spew debug info for.
660 int Num_waypoint_lists = 0;
661 int Mission_all_attack = 0; // !0 means all teams attack all teams.
663 const char *Skill_level_names(int level, int translate)
665 const char *str = NULL;
667 #if NUM_SKILL_LEVELS != 5
668 #error Number of skill levels is wrong!
674 str = XSTR("Very Easy", 469);
677 str = XSTR("Easy", 470);
680 str = XSTR("Medium", 471);
683 str = XSTR("Hard", 472);
686 str = XSTR("Insane", 473);
694 str = NOX("Very Easy");
716 #define DELAY_TARGET_TIME (12*1000) // time in milliseconds until a ship can target a new enemy after an order.
718 // Make enemy ships turn more slowly at lower skill levels.
719 float Turn_time_skill_level_scale[NUM_SKILL_LEVELS] = {3.0f, 2.2f, 1.6f, 1.3f, 1.0f};
721 // Maximum number of simultaneous homing weapons on player based on skill level.
722 int Max_allowed_player_homers[NUM_SKILL_LEVELS] = {2, 3, 4, 7, 99};
724 // Number of ships that can attack another ship at a given skill level.
725 int Skill_level_max_attackers[NUM_SKILL_LEVELS] = {2, 3, 4, 5, 99};
727 // How long until next predict position.
728 fix Skill_level_delay[NUM_SKILL_LEVELS] = {2*F1_0, 3*F1_0/2, 4*F1_0/3, F1_0/2, 0};
730 // AI ships link primary weapons if energy levels greater than the following amounts:
731 float Link_energy_levels_always[NUM_SKILL_LEVELS] = {100.0f, 80.0f, 60.0f, 40.0f, 20.0f}; // always link
732 float Link_energy_levels_maybe[NUM_SKILL_LEVELS] = {90.0f, 60.0f, 40.0f, 20.0f, 10.0f}; // link if hull strength low
734 // Seconds to add to time it takes to get enemy in range. Only for player's enemies.
735 float In_range_time[NUM_SKILL_LEVELS] = {2.0f, 1.4f, 0.75f, 0.0f, -1.0f};
737 // No matter what, a random unit vector gets scaled by this amount in firing at an enemy.
738 // Note that for shorter in-range times, these values get scaled, so a value of 0.5f is meaningful.
739 float Aiming_error[NUM_SKILL_LEVELS] = {3.0f, 2.2f, 1.3f, 0.7f, 0.2f};
741 // Chance a countermeasure will be fired based on skill level.
742 float Cmeasure_fire_chance[NUM_SKILL_LEVELS] = {0.2f, 0.3f, 0.5f, 0.9f, 1.1f}; // Note, this gets scaled by ai_class
744 float Shield_manage_delays[NUM_SKILL_LEVELS] = {5.0f, 4.0f, 2.5f, 1.2f, 0.1f};
746 // accuracy we feed into the beam weapons based upon skill system
747 // float Beam_accuracy[NUM_SKILL_LEVELS] = {2.0f, 1.5f, 1.0f, 0.7f, 0.4f};
749 extern float Ship_fire_delay_scale_hostile[NUM_SKILL_LEVELS];
750 extern float Ship_fire_delay_scale_friendly[NUM_SKILL_LEVELS];
752 pnode Path_points[MAX_PATH_POINTS];
753 pnode *Ppfp; // Free pointer in path points.
757 char *Ai_class_names[MAX_AI_CLASSES];
759 // global for rearm status for teams
760 int Ai_friendly_rearm_timestamp, Ai_hostile_rearm_timestamp, Ai_neutral_rearm_timestamp, Ai_traitor_rearm_timestamp, Ai_unknown_rearm_timestamp;
762 // globals for dealing with when to fire huge secondary weapons
763 #define MAX_HUGE_SECONDARY_INFO 10
772 huge_fire_info Ai_huge_fire_info[MAX_HUGE_SECONDARY_INFO];
774 int Ai_last_arrive_path; // index of ship_bay path used by last arrival from a fighter bay
776 // forward declarations
777 int ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index);
778 void create_model_exit_path(object *pl_objp, object *mobjp, int path_num, int count=1);
779 void copy_xlate_model_path_points(object *objp, model_path *mp, int dir, int count, int path_num, pnode *pnp, int randomize_pnt=-1);
781 // ai_set_rearm_status takes a team (friendly, hostile, neutral) and a time. This function
782 // sets the timestamp used to tell is it is a good time for this team to rearm. Once the timestamp
783 // is no longer valid, then rearming is not a "good time"
784 // not safe. Called from sexpression code.
785 void ai_set_rearm_status( int team, int time )
787 SDL_assert( time >= 0 );
791 Ai_friendly_rearm_timestamp = timestamp( time * 1000 );
794 Ai_hostile_rearm_timestamp = timestamp( time * 1000 );
797 Ai_neutral_rearm_timestamp = timestamp( time * 1000 );
800 Ai_traitor_rearm_timestamp = timestamp( time * 1000 );
803 Ai_traitor_rearm_timestamp = timestamp( time * 1000 );
811 // int ai_good_time_to_rearm returns true(1) or false(0) if it is "safe" for the given
812 // object to rearm. "safe" is currently defined by the mission designer using the good/bad
813 // time to rearm sexpressions. This status is currently team based. This function could
814 // be easily expended to further the definition of "safe"
815 int ai_good_time_to_rearm( object *objp )
819 SDL_assert(objp->type == OBJ_SHIP);
820 team = Ships[objp->instance].team;
825 status = timestamp_valid(Ai_friendly_rearm_timestamp);
828 status = timestamp_valid(Ai_hostile_rearm_timestamp);
831 status = timestamp_valid(Ai_neutral_rearm_timestamp);
834 status = timestamp_valid(Ai_traitor_rearm_timestamp);
837 status = timestamp_valid(Ai_unknown_rearm_timestamp);
847 // functions to deal with letting the ai know about good times to fire powerful secondary
850 // this function is entry point from sexpression code to set internal data for use by ai code.
851 void ai_good_secondary_time( int team, int weapon_index, int max_fire_count, char *shipname )
855 // find an open slot to put this data
856 for ( i = 0; i < MAX_HUGE_SECONDARY_INFO; i++ ) {
857 if ( Ai_huge_fire_info[i].weapon_index == -1 )
861 SDL_assert( i < MAX_HUGE_SECONDARY_INFO ); // we've run out of room
863 Ai_huge_fire_info[i].weapon_index = weapon_index;
864 Ai_huge_fire_info[i].team = team;
865 Ai_huge_fire_info[i].max_fire_count = max_fire_count;
867 Ai_huge_fire_info[i].shipname = ai_get_goal_ship_name( shipname, &index );
870 // function called internally to the ai code to tell whether or not weapon_num can be fired
871 // from firer_objp at target_objp. This function will resolve the team for the firer.
873 // -1 -- when conditions don't allow firer to fire weapon_num on target_objp
874 // >=0 -- when conditions allow firer to fire. Return value is max number of weapon_nums
875 // which can be fired on target_objp
876 int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
878 int i, firer_team, target_signature;
880 huge_fire_info *hfi = NULL;
882 SDL_assert( firer_objp->type == OBJ_SHIP );
883 firer_ship = &Ships[firer_objp->instance];
884 firer_team = firer_ship->team;
886 // get target object's signature and try to find it in the list.
887 target_signature = target_objp->signature;
888 for ( i = 0; i < MAX_HUGE_SECONDARY_INFO; i++ ) {
889 int ship_index, signature;
891 hfi = &Ai_huge_fire_info[i];
892 if ( hfi->weapon_index == -1 )
895 ship_index = ship_name_lookup( hfi->shipname );
896 if ( ship_index == -1 )
899 signature = Objects[Ships[ship_index].objnum].signature;
901 // sigatures, weapon_index, and team must match
902 if ( (signature == target_signature) && (hfi->weapon_index == weapon_num) && (hfi->team == firer_team) )
906 // return -1 if not found
907 if ( i == MAX_HUGE_SECONDARY_INFO )
910 // otherwise, we can return the max number of weapons we can fire against target_objps
912 return hfi->max_fire_count;
915 // function to clear out secondary firing infomration between levels
916 void ai_init_secondary_info()
920 // clear out the data for dealing with when ai ships can fire huge secondary weapons
921 for (i = 0; i < MAX_HUGE_SECONDARY_INFO; i++ ) {
922 Ai_huge_fire_info[i].weapon_index = -1;
923 Ai_huge_fire_info[i].team = -1;
924 Ai_huge_fire_info[i].max_fire_count = -1;
925 Ai_huge_fire_info[i].shipname = NULL;
930 // Garbage collect the Path_points buffer.
931 // Scans all objects, looking for used Path_points records.
932 // Compresses Path_points buffer, updating aip->path_start and aip->path_cur indices.
933 // Updates Ppfp to point to first free record.
934 // This function is fairly fast. Its worst-case running time is proportional to
935 // 3*MAX_PATH_POINTS + MAX_OBJECTS
936 // Things to do to optimize this function:
937 // 1. if (t != 0) xlt++; can be replaced by xlt += t; assuming t can only be 0 or 1.
938 // 2. When pp_xlate is getting stuffed the first time, note highest index and use that
939 // instead of MAX_PATH_POINTS in following two for loops.
940 void garbage_collect_path_points()
943 int pp_xlate[MAX_PATH_POINTS];
947 // Scan all objects and create Path_points xlate table.
948 for (i=0; i<MAX_PATH_POINTS; i++)
951 // in pp_xlate, mark all used Path_point records
952 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
953 A = &Objects[so->objnum];
954 ship *shipp = &Ships[A->instance];
955 if (shipp->ai_index != -1) {
956 ai_info *aip = &Ai_info[shipp->ai_index];
958 if ((aip->path_length > 0) && (aip->path_start > -1)) {
960 for (i=aip->path_start; i<aip->path_start + aip->path_length; i++) {
961 SDL_assert(pp_xlate[i] == 0); // If this is not 0, then two paths use this point!
968 // Now, stuff xlate index in pp_xlate. This is the number to translate any path_start
969 // or path_cur index to.
971 for (i=0; i<MAX_PATH_POINTS; i++) {
979 // Update global Path_points free pointer.
980 Ppfp = &Path_points[xlt];
982 // Now, using pp_xlate, fixup all aip->path_cur and aip->path_start indices
983 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
984 A = &Objects[so->objnum];
985 ship *shipp = &Ships[A->instance];
986 if (shipp->ai_index != -1) {
987 ai_info *aip = &Ai_info[shipp->ai_index];
989 if ((aip->path_length > 0) && (aip->path_start > -1)) {
990 SDL_assert(aip->path_start < MAX_PATH_POINTS);
991 aip->path_start = pp_xlate[aip->path_start];
993 SDL_assert((aip->path_cur >= 0) && (aip->path_cur < MAX_PATH_POINTS));
994 aip->path_cur = pp_xlate[aip->path_cur];
999 // Now, compress the buffer.
1000 for (i=0; i<MAX_PATH_POINTS; i++)
1001 if (i != pp_xlate[i])
1002 Path_points[pp_xlate[i]] = Path_points[i];
1006 // Hash two values together, return result.
1007 // Hash function: curval shifted right circular by one, newval xored in.
1008 int hash(unsigned int curval, int newval)
1010 int addval = curval & 1;
1014 curval |= 0x80000000;
1020 // Hash some information in an object together.
1021 // On 2/20/97, the information is position and orientation.
1022 int create_object_hash(object *objp)
1025 unsigned int hashval = 0;
1028 ip = (int *) &objp->orient;
1030 for (i=0; i<9; i++) {
1031 hashval = hash(hashval, *ip);
1035 ip = (int *) &objp->pos;
1037 for (i=0; i<3; i++) {
1038 hashval = hash(hashval, *ip);
1045 // Stuff a list of NUM_SKILL_LEVELS floats at *plist.
1046 void parse_float_list(float *plist)
1050 for (i=0; i<NUM_SKILL_LEVELS; i++) {
1051 stuff_float(&plist[i]);
1055 void parse_ai_class()
1057 ai_class *aicp = &Ai_classes[Num_ai_classes];
1059 required_string("$Name:");
1060 stuff_string(aicp->name, F_NAME, NULL);
1062 Ai_class_names[Num_ai_classes] = aicp->name;
1064 required_string("$accuracy:");
1065 parse_float_list(aicp->ai_accuracy);
1067 required_string("$evasion:");
1068 parse_float_list(aicp->ai_evasion);
1070 required_string("$courage:");
1071 parse_float_list(aicp->ai_courage);
1073 required_string("$patience:");
1074 parse_float_list(aicp->ai_patience);
1079 // open localization
1082 read_file_text("ai.tbl");
1088 required_string("#AI Classes");
1090 while (required_string_either("#End", "$Name:")) {
1091 SDL_assert( Num_ai_classes < MAX_AI_CLASSES);
1098 // close localization
1102 static int ai_inited = 0;
1104 //========================= BOOK-KEEPING FUNCTIONS =======================
1106 // Called once at game start-up
1110 // Do the first time initialization stuff here
1113 } catch (parse_error_t rval) {
1114 Error(LOCATION, "Error parsing 'ai.tbl'\r\nError code = %i.\r\n", (int)rval);
1125 // this inits the ai. You should be able to call this between
1126 // levels to reset everything.
1127 void ai_level_init()
1131 // Do the stuff to reset all ai stuff here
1132 for (i=0; i<MAX_AI_INFO ; i++) {
1133 Ai_info[i].shipnum = -1;
1135 Ai_goal_signature = 0;
1136 Ai_friendly_rearm_timestamp = timestamp(-1);
1137 Ai_hostile_rearm_timestamp = timestamp(-1);
1138 Ai_neutral_rearm_timestamp = timestamp(-1);
1139 Ai_traitor_rearm_timestamp = timestamp(-1);
1141 // clear out the stuff needed for AI firing powerful secondary weapons
1142 ai_init_secondary_info();
1144 Ai_last_arrive_path=0;
1148 // -----------------------------------------------------------------------------
1149 // Check if object is a stealth ship
1150 int is_object_stealth_ship(object* objp)
1152 if (objp->type == OBJ_SHIP) {
1153 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_STEALTH) {
1162 // -----------------------------------------------------------------------------
1163 // Init necessary ai info for new stealth target
1164 void init_ai_stealth_info(ai_info *aip, object *stealth_objp)
1166 SDL_assert(is_object_stealth_ship(stealth_objp));
1168 // set necessary ai info for new stealth target
1169 aip->stealth_last_pos = stealth_objp->pos;
1170 aip->stealth_velocity = stealth_objp->phys_info.vel;
1171 aip->stealth_last_visible_stamp = timestamp();
1174 // -----------------------------------------------------------------------------
1175 // Check whether Pl_objp can see a stealth ship object
1176 #define STEALTH_INVISIBLE 0
1177 #define STEALTH_VISIBLE 1
1178 #define STEALTH_FULLY_TARGETABLE 2
1180 float get_skill_stealth_dist_scaler()
1182 // return dist scaler based on skill level
1183 switch (Game_skill_level) {
1184 case 0: // very easy
1206 float get_skill_stealth_dot_scaler()
1208 // return multiplier on dot based on skill level
1209 switch (Game_skill_level) {
1210 case 0: // very easy
1232 int ai_is_stealth_visible(object *viewer_objp, object *stealth_objp)
1234 vector vec_to_stealth;
1235 float dot_to_stealth, dist_to_stealth, max_stealth_dist;
1237 SDL_assert(stealth_objp->type == OBJ_SHIP);
1238 SDL_assert(viewer_objp->type == OBJ_SHIP);
1240 // check if stealth ship
1241 SDL_assert(Ship_info[Ships[stealth_objp->instance].ship_info_index].flags & SIF_STEALTH);
1243 // check if in neb and below awac level for visible
1244 if ( !ship_is_visible_by_team(stealth_objp->instance, Ships[viewer_objp->instance].team) ) {
1245 vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &viewer_objp->pos);
1246 dist_to_stealth = vm_vec_mag_quick(&vec_to_stealth);
1247 dot_to_stealth = vm_vec_dotprod(&viewer_objp->orient.v.fvec, &vec_to_stealth) / dist_to_stealth;
1249 // get max dist at which stealth is visible
1250 max_stealth_dist = get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST;
1252 // now check if within view frustrum
1253 float needed_dot_to_stealth;
1254 if (dist_to_stealth < 100) {
1255 needed_dot_to_stealth = 0.0f;
1257 needed_dot_to_stealth = get_skill_stealth_dot_scaler() * float(STEALTH_VIEW_CONE_DOT) * (dist_to_stealth / max_stealth_dist);
1259 if (dot_to_stealth > needed_dot_to_stealth) {
1260 if (dist_to_stealth < max_stealth_dist) {
1261 return STEALTH_VISIBLE;
1265 // not within frustrum
1266 return STEALTH_INVISIBLE;
1269 // visible by awacs level
1270 return STEALTH_FULLY_TARGETABLE;
1275 // Compute dot product of direction vector and forward vector.
1276 // Direction vector is vector from one object to other object.
1277 // Forward vector is the forward vector of the ship.
1278 // If from_dot == NULL, don't fill it in.
1279 float compute_dots(object *objp, object *other_objp, float *to_dot, float *from_dot)
1284 dist = vm_vec_normalized_dir(&v2o, &other_objp->pos, &objp->pos);
1286 *to_dot = vm_vec_dot(&objp->orient.v.fvec, &v2o);
1288 if (from_dot != NULL)
1289 *from_dot = - vm_vec_dot(&other_objp->orient.v.fvec, &v2o);
1294 // -----------------------------------------------------------------------------
1295 // update estimated stealth info
1296 // this is a "cheat" update
1297 // error increases with time not seen, true distance away, dot to enemey
1298 // this is done only if we can not see the stealth target
1299 // need to infer its position either by weapon fire pos or last know pos
1300 void update_ai_stealth_info_with_error(ai_info *aip/*, int no_error*/)
1303 object *stealth_objp;
1305 float error_time_mult, error_dist_mult, error_dot_mult, error_mult;
1306 float pos_error, vel_error;
1307 vector error_vec, vec_to_stealth;
1308 float dist_to_stealth, dot_to_stealth;
1309 float delta_time, delta_capped;
1312 // make sure I am targeting a stealth ship
1313 SDL_assert( is_object_stealth_ship(&Objects[aip->target_objnum]) );
1314 stealth_objp = &Objects[aip->target_objnum];
1317 // ship = &Objects[Ships[aip->shipnum].objnum];
1319 // if update is due to weapon fire, get exact stealth position
1321 aip->stealth_last_pos = stealth_objp->pos;
1322 aip->stealth_velocity = stealth_objp->phys_info.vel;
1323 aip->stealth_last_visible_stamp = timestamp();
1327 // get time since last seen
1328 delta_time = 0.001f * (timestamp() - aip->stealth_last_visible_stamp);
1330 // we don't want our "cheat" guess to more off than what we would get from extrapolating from last visible
1331 // only update if stealth info is "old"
1332 if ( (delta_time) < 0.5 ) {
1336 // find vec_to_stealth and dist
1337 vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &ship->pos);
1338 dist_to_stealth = vm_vec_normalize_quick(&vec_to_stealth);
1339 dot_to_stealth = vm_vec_dotprod(&vec_to_stealth, &ship->orient.v.fvec);
1342 delta_capped = delta_time;
1343 if (delta_time > 5.0) {
1344 delta_capped = 5.0f;
1347 // erorr_time_mult (for 0-5) -> (1-6)
1348 error_time_mult = (1.0f + delta_capped);
1350 // error_dot_mult (-1 to 1) -> (1-3)
1351 error_dot_mult = (2 - dot_to_stealth);
1353 // error_dist_mult (0-1000+) -> (1-4)
1354 error_dist_mult = dist_to_stealth * 4.0f * 0.001f;
1355 if (error_dist_mult < 1) {
1356 error_dist_mult = 1.0f;
1357 } else if (error_dist_mult > 4) {
1358 error_dist_mult = 4.0f;
1361 // multiply error out
1362 error_mult = error_time_mult * error_dot_mult * error_dist_mult;
1364 float base_pos_error = 10;
1365 float base_vel_error = 2;
1367 // find the position and velocity error magnitude;
1368 pos_error = base_pos_error * error_mult;
1369 vel_error = base_vel_error * error_mult;
1371 // get an error that changes slowly over time
1372 static_randvec( ((int)aip ^ (Missiontime >> 18)) & 7, &error_vec);
1373 vm_vec_zero(&error_vec);
1375 // update pos and vel with error
1376 vm_vec_scale_add(&aip->stealth_velocity, &stealth_objp->phys_info.vel, &error_vec, vel_error);
1378 // revise last "known" position to arrive at last pos with given error
1379 vm_vec_scale_add(&aip->stealth_last_pos, &stealth_objp->pos, &error_vec, pos_error);
1380 vm_vec_scale_add2(&aip->stealth_last_pos, &aip->stealth_velocity, -(0.001f * delta_time));
1384 // Update danger_weapon_objnum and signature in ai_info to say this weapon is to be avoided.
1385 void ai_update_danger_weapon(int attacked_objnum, int weapon_objnum)
1387 object *objp, *weapon_objp;
1389 float old_dist, new_dist;
1390 float old_dot, new_dot;
1391 object *old_weapon_objp = NULL;
1393 if ((attacked_objnum == -1) || (weapon_objnum == -1)) {
1397 objp = &Objects[attacked_objnum];
1399 // AL 2-24-98: If this isn't a ship, we don't need to worry about updating weapon_objnum (ie it would be
1400 // an asteroid or bomb).
1401 if ( objp->type != OBJ_SHIP ) {
1405 weapon_objp = &Objects[weapon_objnum];
1407 aip = &Ai_info[Ships[objp->instance].ai_index];
1409 // if my taraget is a stealth ship and is not visible
1410 if (aip->target_objnum >= 0) {
1411 if ( is_object_stealth_ship(&Objects[aip->target_objnum]) ) {
1412 if ( ai_is_stealth_visible(objp, &Objects[aip->target_objnum]) == STEALTH_INVISIBLE ) {
1413 // and the weapon is coming from that stealth ship
1414 if (weapon_objp->parent == aip->target_objnum) {
1415 // update my position estimate for stealth ship
1416 update_ai_stealth_info_with_error(aip/*, 1*/);
1422 if (aip->danger_weapon_objnum != -1) {
1423 old_weapon_objp = &Objects[aip->danger_weapon_objnum];
1424 if ((old_weapon_objp->type == OBJ_WEAPON) && (old_weapon_objp->signature == aip->danger_weapon_signature)) {
1427 aip->danger_weapon_objnum = -1;
1431 new_dist = compute_dots(weapon_objp, objp, &new_dot, NULL);
1433 if (aip->danger_weapon_objnum == -1) {
1434 if (new_dist < 1500.0f) {
1435 if (new_dot > 0.5f) {
1436 aip->danger_weapon_objnum = weapon_objnum;
1437 aip->danger_weapon_signature = weapon_objp->signature;
1441 SDL_assert(old_weapon_objp != NULL);
1442 old_dist = compute_dots(old_weapon_objp, objp, &old_dot, NULL);
1444 if (old_dot < 0.5f) {
1445 aip->danger_weapon_objnum = -1;
1449 if ((new_dot > 0.5f) && (new_dot > old_dot-0.01f)) {
1450 if (new_dist < old_dist) {
1451 aip->danger_weapon_objnum = weapon_objnum;
1452 aip->danger_weapon_signature = weapon_objp->signature;
1458 // If rvec != NULL, use it to match bank by calling vm_matrix_interpolate.
1459 // (rvec defaults to NULL)
1460 void ai_turn_towards_vector(vector *dest, object *objp,
1461 float frametime, float turn_time, vector *slide_vec, vector *rel_pos, float bank_override, int flags, vector *rvec)
1463 //matrix goal_orient;
1465 vector vel_in, vel_out, desired_fvec, src;
1468 vector vel_limit, acc_limit;
1471 // Don't allow a ship to turn if it has no engine strength.
1472 // AL 3-12-98: objp may not always be a ship!
1473 if ( objp->type == OBJ_SHIP ) {
1474 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f)
1478 //nprintf(("AI", "Ship %s turning towards point %7.3f %7.3f %7.3f\n", Ships[objp->instance].ship_name, dest->x, dest->y, dest->z));
1479 pip = &objp->phys_info;
1481 vel_in = pip->rotvel;
1482 curr_orient = objp->orient;
1483 delta_time = flFrametime;
1485 SDL_assert(turn_time > 0.0f);
1487 // Scale turn_time based on skill level and team.
1488 if (!(flags & AITTV_FAST)){
1489 if (objp->type == OBJ_SHIP){
1490 if (Ships[objp->instance].team != Ships[Player_obj->instance].team){
1491 turn_time *= Turn_time_skill_level_scale[Game_skill_level];
1496 // Set max turn rate.
1497 vel_limit.xyz.x = 2*PI/turn_time;
1498 vel_limit.xyz.y = 2*PI/turn_time;
1499 vel_limit.xyz.z = 2*PI/turn_time;
1501 // Set rate at which ship can accelerate to its rotational velocity.
1502 // For now, weapons just go much faster.
1503 acc_limit = vel_limit;
1504 if (objp->type == OBJ_WEAPON)
1505 vm_vec_scale(&acc_limit, 8.0f);
1509 if (rel_pos != NULL) {
1511 vm_vec_unrotate(&gun_point, rel_pos, &objp->orient);
1512 vm_vec_add2(&src, &gun_point);
1515 vm_vec_normalized_dir(&desired_fvec, dest, &src);
1517 // Since ship isn't necessarily moving in the direction it's pointing, sometimes it's better
1518 // to be moving towards goal rather than just pointing. So, if slide_vec is !NULL, try to
1519 // make ship move towards goal, not point at goal.
1520 if (slide_vec != NULL) {
1521 vm_vec_add2(&desired_fvec, slide_vec);
1522 vm_vec_normalize(&desired_fvec);
1525 // Should be more general case here. Currently, anything that is not a weapon will bank when it turns.
1526 if (objp->type == OBJ_WEAPON)
1528 else if ((bank_override) && (Ships[objp->instance].team & opposing_team_mask(Player_ship->team))) { // Theoretically, this will only happen for Shivans.
1529 delta_bank = bank_override;
1530 //nprintf(("AI", "%i: %7.3f\n", Framecount, bank_override));
1532 delta_bank = vm_vec_dot(&curr_orient.v.rvec, &objp->last_orient.v.rvec);
1533 delta_bank = 100.0f * (1.0f - delta_bank);
1534 if (vm_vec_dot(&objp->last_orient.v.fvec, &objp->orient.v.rvec) < 0.0f)
1535 delta_bank = -delta_bank;
1537 //nprintf(("AI", "%s: Frame %i: delta bank = %7.3f\n", Ships[objp->instance].ship_name, Framecount, delta_bank));
1540 // Dave Andsager: The non-indented lines here are debug code to help you track down the problem in the physics
1541 // that is causing ships to inexplicably rotate very far. If you hit the Int3(), set the next statement to be
1542 // the one marked "HERE". (Do this clicking the cursor there, then right clicking. Choose the right option.)
1543 // This will allow you to rerun vm_forward_interpolate() with the values that caused the error.
1544 // Note, you'll need to enable the Int3() about ten lines below.
1546 vector tvec = objp->orient.v.fvec;
1548 matrix objp_orient_copy;
1550 vel_in_copy = vel_in;
1551 objp_orient_copy = objp->orient;
1553 vel_in = vel_in_copy; // HERE
1554 objp->orient = objp_orient_copy;
1557 matrix out_orient, goal_orient;
1559 vm_vector_2_matrix(&goal_orient, &desired_fvec, NULL, rvec);
1560 vm_matrix_interpolate(&goal_orient, &curr_orient, &vel_in, delta_time, &out_orient, &vel_out, &vel_limit, &acc_limit);
1561 objp->orient = out_orient;
1563 vm_forward_interpolate(&desired_fvec, &curr_orient, &vel_in, delta_time, delta_bank, &objp->orient, &vel_out, &vel_limit, &acc_limit);
1566 if (!((objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[objp->instance].weapon_info_index].subtype == WP_MISSILE))) {
1567 if (delta_time < 0.25f && vm_vec_dot(&objp->orient.v.fvec, &tvec) < 0.1f)
1568 Int3(); // Get Andsager. A ship has turned too far in one frame.
1572 pip->rotvel = vel_out;
1575 void init_ship_info()
1579 if (Ship_info_inited)
1582 for (i=0; i<MAX_SHIP_TYPES; i++) {
1583 Ship_info[i].min_speed = - Ship_info[i].max_rear_vel;
1584 Ship_info[i].max_accel = Ship_info[i].max_vel.xyz.z;
1587 Ship_info_inited = 1;
1591 // Set aip->target_objnum to objnum
1592 // Update aip->previous_target_objnum.
1593 // If new target (objnum) is different than old target, reset target_time.
1594 int set_target_objnum(ai_info *aip, int objnum)
1597 char old_name[32], new_name[32];
1599 if (!timestamp_elapsed(aip->ok_to_target_timestamp))
1600 return aip->target_objnum;
1602 if (Player_ship && (Ships[aip->shipnum].team == Player_ship->team)) {
1603 if (aip->target_objnum == -1)
1604 strcpy(old_name, "none");
1606 strcpy(old_name, Ships[Objects[aip->target_objnum].instance].ship_name);
1609 strcpy(new_name, "none");
1611 strcpy(new_name, Ships[Objects[objnum].instance].ship_name);
1613 nprintf(("AI", "Ship %s changing target from %s to %s\n", Ships[aip->shipnum].ship_name, old_name, new_name));
1617 // AL 2-25-97: Ensure that a protected ship isn't being set as a target (for non-players only)
1619 if ( objnum >= 0 ) {
1620 if ( !(Objects[Ships[aip->shipnum].objnum].flags & OF_PLAYER_SHIP) ) {
1621 if ( Objects[objnum].flags & OF_PROTECTED ) {
1622 // AL 2-26-97: removing Int3() until issue with setting OF_PROTECTED in ai_set_attack_subsystem()
1623 //Int3(); // this should not happen
1624 return aip->target_objnum; // don't change targets
1630 if ((aip != Player_ai) && (!timestamp_elapsed(aip->ok_to_target_timestamp))) {
1631 return aip->target_objnum;
1634 if (aip->target_objnum == objnum) {
1635 aip->previous_target_objnum = aip->target_objnum;
1637 aip->previous_target_objnum = aip->target_objnum;
1639 // ignore this assert if a multiplayer observer
1640 if((Game_mode & GM_MULTIPLAYER) && (aip == Player_ai) && (Player_obj->type == OBJ_OBSERVER)){
1642 SDL_assert(objnum != Ships[aip->shipnum].objnum); // make sure not targeting self
1645 // if stealth target, init ai_info for stealth
1646 if ( (objnum > 0) && is_object_stealth_ship(&Objects[objnum]) ) {
1647 init_ai_stealth_info(aip, &Objects[objnum]);
1650 aip->target_objnum = objnum;
1651 aip->target_time = 0.0f;
1652 aip->target_signature = Objects[objnum].signature;
1653 // clear targeted subsystem
1654 set_targeted_subsys(aip, NULL, -1);
1657 return aip->target_objnum;
1660 int ai_select_primary_weapon(object *objp, object *other_objp, int flags);
1662 // Make new_subsys the targeted subsystem of ship *aip.
1663 ship_subsys *set_targeted_subsys(ai_info *aip, ship_subsys *new_subsys, int parent_objnum)
1665 SDL_assert(aip != NULL);
1667 aip->last_subsys_target = aip->targeted_subsys;
1668 aip->targeted_subsys = new_subsys;
1669 aip->targeted_subsys_parent = parent_objnum;
1672 // Make new_subsys target
1673 if (new_subsys->system_info->type == SUBSYSTEM_ENGINE) {
1674 if ( aip != Player_ai ) {
1675 ai_select_primary_weapon(&Objects[Ships[aip->shipnum].objnum], &Objects[parent_objnum], WIF_PUNCTURE);
1676 ship_primary_changed(&Ships[aip->shipnum]); // AL: maybe send multiplayer information when AI ship changes primaries
1680 if ( aip == Player_ai ) {
1681 hud_lock_reset(0.5f);
1685 // Cleanup any subsys path information if it exists
1686 ai_big_subsys_path_cleanup(aip);
1689 return aip->targeted_subsys;
1692 // called to init the data for single ai object. At this point,
1693 // the ship and the object and the ai_info are are correctly
1694 // linked together. Ai_info[ai_index].shipnum is the only valid field
1696 // This is called right when the object is parsed, so you can't assume much
1697 // has been initialized. For example, wings, waypoints, goals are probably
1698 // not yet loaded. --MK, 10/8/96
1699 void ai_object_init(object * obj, int ai_index)
1702 SDL_assert(ai_index >= 0 && ai_index < MAX_AI_INFO);
1704 aip = &Ai_info[ai_index];
1706 aip->type = 0; // 0 means not in use.
1707 aip->wing = -1; // Member of what wing? -1 means none.
1708 aip->ai_class = Ship_info[Ships[obj->instance].ship_info_index].ai_class;
1709 aip->behavior = AIM_NONE;
1712 // If *aip is docked, set max acceleration to A->mass/(A->mass + B->mass) where A is *aip and B is dock object
1713 void adjust_accel_for_docking(ai_info *aip)
1715 if (aip->dock_objnum != -1) {
1716 object *obj2p = &Objects[aip->dock_objnum];
1719 obj1p = &Objects[Ships[aip->shipnum].objnum];
1721 if (obj2p->signature == aip->dock_signature) {
1724 ratio = obj1p->phys_info.mass / (obj1p->phys_info.mass + obj2p->phys_info.mass);
1726 // put cap on how much ship can slow down
1728 // FS1 can go slower, perhaps down to 0, but I'll cap it at .25 just in case
1729 if (ratio < 0.25f) {
1738 if (AI_ci.forward > ratio) {
1739 AI_ci.forward = ratio;
1745 // -------------------------------------------------------------------
1746 void accelerate_ship(ai_info *aip, float accel)
1748 aip->prev_accel = accel;
1749 AI_ci.forward = accel;
1750 adjust_accel_for_docking(aip);
1753 // --------------------------------------------------------------------------
1754 void change_acceleration(ai_info *aip, float delta_accel)
1758 if (delta_accel < 0.0f) {
1759 if (aip->prev_accel > 0.0f)
1760 aip->prev_accel = 0.0f;
1761 } else if (aip->prev_accel < 0.0f)
1762 aip->prev_accel = 0.0f;
1764 new_accel = aip->prev_accel + delta_accel * flFrametime;
1766 if (new_accel > 1.0f)
1768 else if (new_accel < -1.0f)
1771 aip->prev_accel = new_accel;
1773 AI_ci.forward = new_accel;
1774 adjust_accel_for_docking(aip);
1777 void set_accel_for_target_speed(object *objp, float tspeed)
1782 aip = &Ai_info[Ships[objp->instance].ai_index];
1784 max_speed = Ships[objp->instance].current_max_speed;
1786 AI_ci.forward = tspeed/max_speed;
1787 aip->prev_accel = AI_ci.forward;
1789 adjust_accel_for_docking(aip);
1792 // Stuff perim_point with a point on the perimeter of the sphere defined by object *objp
1793 // on the vector from the center of *objp through the point *vp.
1794 void project_point_to_perimeter(vector *perim_point, vector *pos, float radius, vector *vp)
1799 vm_vec_sub(&v1, vp, pos);
1800 mag = vm_vec_mag(&v1);
1803 Warning(LOCATION, "projectable point is at center of sphere.");
1804 (void) vm_vec_make(&v1, 0.0f, radius, 0.0f);
1806 vm_vec_normalize(&v1);
1807 vm_vec_scale(&v1, 1.1f * radius + 10.0f);
1810 vm_vec_add2(&v1, pos);
1814 // Stuff tan1 with tangent point on sphere. tan1 is point nearer to *p1
1815 // *p0 is point through which tangents pass.
1816 // *centerp is center of sphere.
1817 // *p1 is another point in space to define the plane in which tan1, tan2 reside.
1818 // radius is the radius of the sphere.
1819 // Note, this is a very approximate function just for AI.
1820 // Note also: On 12/26/96, p1 is used to define the plane perpendicular to that which
1821 // contains the tangent point.
1822 void get_tangent_point(vector *tan1, vector *p0, vector *centerp, vector *p1, float radius)
1824 vector dest_vec, v2c, perp_vec, temp_vec, v2;
1827 // Detect condition of point inside sphere.
1828 if (vm_vec_dist(p0, centerp) < radius)
1829 project_point_to_perimeter(tan1, centerp, radius, p0);
1831 vm_vec_normalized_dir(&v2c, centerp, p0);
1833 // Compute perpendicular vector using p0, centerp, p1
1834 vm_vec_normal(&temp_vec, p0, centerp, p1);
1835 vm_vec_sub(&v2, centerp, p0);
1836 vm_vec_cross(&perp_vec, &temp_vec, &v2);
1838 vm_vec_normalize(&perp_vec);
1840 dist = vm_vec_dist_quick(p0, centerp);
1841 ratio = dist / radius;
1844 vm_vec_scale_add(&dest_vec, &perp_vec, &v2c, ratio-1.0f);
1846 vm_vec_scale_add(&dest_vec, &v2c, &perp_vec, (1.0f + 1.0f/ratio));
1848 vm_vec_scale_add(tan1, p0, &dest_vec, dist + radius);
1852 // --------------------------------------------------------------------------
1853 // Given an object and a point, turn towards the point, resulting in
1854 // approach behavior.
1855 void turn_towards_point(object *objp, vector *point, vector *slide_vec, float bank_override)
1858 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
1860 // check if in formation and if not leader, don't change rotvel.xyz.z (bank to match leader elsewhere)
1861 if (aip->ai_flags & AIF_FORMATION) {
1862 if (&Objects[aip->goal_objnum] != objp) {
1863 float rotvel_z = objp->phys_info.rotvel.xyz.z;
1864 ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1865 objp->phys_info.rotvel.xyz.z = rotvel_z;
1869 ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1873 // --------------------------------------------------------------------------
1874 // Given an object and a point, turn away from the point, resulting in avoidance behavior.
1875 // Note: Turn away at full speed, not scaled down by skill level.
1876 void turn_away_from_point(object *objp, vector *point, float bank_override)
1878 vector opposite_point;
1880 vm_vec_sub(&opposite_point, &objp->pos, point);
1881 vm_vec_add2(&opposite_point, &objp->pos);
1883 ai_turn_towards_vector(&opposite_point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, bank_override, AITTV_FAST);
1887 // --------------------------------------------------------------------------
1888 // Given an object and a point, turn tangent to the point, resulting in
1889 // a circling behavior.
1890 // Make object *objp turn around the point *point with a radius of radius.
1891 // Note that this isn't the same as following a circle of radius radius with
1892 // center *point, but it should be adequate.
1893 // Note that if you want to circle an object without hitting it, you should use
1894 // about twice that object's radius for radius, else you'll certainly bump into it.
1895 // Return dot product to goal point.
1896 float turn_towards_tangent(object *objp, vector *point, float radius)
1898 vector vec_to_point;
1900 vector perp_point; // point radius away from *point on vector to objp->pos
1901 vector up_vec, perp_vec;
1903 vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1904 vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1905 vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1907 vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1908 if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1909 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, radius);
1911 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, -radius);
1914 // Ai_info[Ships[objp->instance].ai_index].goal_point = goal_point;
1915 turn_towards_point(objp, &goal_point, NULL, 0.0f);
1919 vm_vec_normalized_dir(&v2g, &goal_point, &objp->pos);
1920 return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1923 float turn_toward_tangent_with_axis(object *objp, object *center_objp, float radius)
1925 vector r_vec, theta_vec;
1926 vector center_vec, vec_on_cylinder, sph_r_vec;
1929 // find closest z of center objp
1930 vm_vec_sub(&sph_r_vec, &objp->pos, ¢er_objp->pos);
1931 center_obj_z = vm_vec_dotprod(&sph_r_vec, ¢er_objp->orient.v.fvec);
1933 // find pt on axis with closest z
1934 vm_vec_scale_add(¢er_vec, ¢er_objp->pos, ¢er_objp->orient.v.fvec, center_obj_z);
1937 vm_vec_sub(&r_vec, &objp->pos, ¢er_vec);
1938 // float r_mag = vm_vec_normalize_quick(&r_vec);
1939 // mprintf(("cur_r: %.1f, desired_r: %.1f\n", r_mag, radius));
1940 SDL_assert( (vm_vec_dotprod(&r_vec, ¢er_objp->orient.v.fvec) < 0.0001));
1942 // get theta vec - perp to r_vec and z_vec
1943 vm_vec_crossprod(&theta_vec, ¢er_objp->orient.v.fvec, &r_vec);
1946 float mag = vm_vec_normalize(&theta_vec);
1947 SDL_assert(mag > 0.9999 && mag < 1.0001);
1951 vm_vec_crossprod(&temp, &r_vec, &theta_vec);
1954 float dot = vm_vec_dotprod(&temp, ¢er_objp->orient.v.fvec);
1955 SDL_assert( dot >0.9999 && dot < 1.0001);
1958 // find pt on clylinder with closest z
1959 vm_vec_scale_add(&vec_on_cylinder, ¢er_vec, &r_vec, radius);
1961 vector goal_pt, v2g;
1962 vm_vec_scale_add(&goal_pt, &vec_on_cylinder, &theta_vec, radius);
1964 // Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pt;
1965 turn_towards_point(objp, &goal_pt, NULL, 0.0f);
1967 vm_vec_normalized_dir(&v2g, &goal_pt, &objp->pos);
1968 return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1971 // Returns a point radius units away from *point that *objp should turn towards to orbit *point
1972 void get_tangent_point(vector *goal_point, object *objp, vector *point, float radius)
1974 vector vec_to_point;
1975 vector perp_point; // point radius away from *point on vector to objp->pos
1976 vector up_vec, perp_vec;
1978 vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1979 vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1980 vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1981 vm_vec_normalize(&perp_vec);
1983 vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1985 if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1986 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, radius);
1988 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, -radius);
1992 int Player_attacking_enabled = 1;
1994 // -----------------------------------------------------------------------------
1995 // Determine whether an object is targetable within a nebula
1996 int object_is_targetable(object *target, ship *viewer)
1998 int stealth_ship = 0;
2000 // if target is ship, check if visible by team
2001 if (target->type == OBJ_SHIP) {
2002 stealth_ship = (Ship_info[Ships[target->instance].ship_info_index].flags & SIF_STEALTH);
2003 if ( ship_is_visible_by_team(target->instance, viewer->team) == 1) {
2008 // for AI partially targetable works as fully targetable, except for stealth ship
2010 // if not team targetable, check if within frustrum
2011 if ( ai_is_stealth_visible(&Objects[viewer->objnum], target) == STEALTH_VISIBLE ) {
2018 // if not fully targetable by team, check awacs level with viewer
2019 // allow targeting even if only only partially targetable to player
2020 float radar_return = awacs_get_level(target, viewer);
2021 if ( radar_return > 0.4 ) {
2028 // Return number of enemies attacking object objnum
2030 // AL 10.26.97: Also include turrets on large ships when couting enemies attacking
2031 int num_enemies_attacking(int objnum)
2041 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2042 objp = &Objects[so->objnum];
2043 SDL_assert(objp->instance != -1);
2044 sp = &Ships[objp->instance];
2046 if (Ai_info[sp->ai_index].target_objnum == objnum)
2049 // consider turrets that may be attacking objnum (but only turrets on SIF_BIG_SHIP ships)
2050 if ( Ship_info[sp->ship_info_index].flags & SIF_BIG_SHIP ) {
2052 // loop through all the subsystems, check if turret has objnum as a target
2053 ssp = GET_FIRST(&sp->subsys_list);
2054 while ( ssp != END_OF_LIST( &sp->subsys_list ) ) {
2056 if ( ssp->system_info->type == SUBSYSTEM_TURRET ) {
2057 if ( (ssp->turret_enemy_objnum == objnum) && (ssp->current_hits > 0) ) {
2061 ssp = GET_NEXT( ssp );
2069 // Get the team to fire on given an object.
2070 int get_enemy_team_mask(int objnum)
2072 int my_team, enemy_team_mask;
2074 my_team = Ships[Objects[objnum].instance].team;
2076 if (Mission_all_attack) {
2077 // All teams attack all teams.
2080 enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2083 enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2086 enemy_team_mask = TEAM_FRIENDLY | TEAM_HOSTILE | TEAM_TRAITOR;
2089 enemy_team_mask = TEAM_HOSTILE;
2092 enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2095 enemy_team_mask = TEAM_HOSTILE;
2096 Int3(); // Illegal value for team!
2102 enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2105 enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2108 enemy_team_mask = TEAM_FRIENDLY | TEAM_TRAITOR;
2111 enemy_team_mask = TEAM_HOSTILE;
2114 enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2117 enemy_team_mask = TEAM_HOSTILE;
2118 Int3(); // Illegal value for team!
2123 return enemy_team_mask;
2126 // Scan all the ships in *objp's wing.
2127 // Return the lowest maximum speed of a ship in the wing.
2128 // Current maximum speed (based on energy settings) is shipp->current_max_speed
2129 float get_wing_lowest_max_speed(object *objp)
2133 float lowest_max_speed;
2138 SDL_assert(objp->type == OBJ_SHIP);
2139 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
2140 shipp = &Ships[objp->instance];
2141 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
2142 aip = &Ai_info[shipp->ai_index];
2144 wingnum = aip->wing;
2146 lowest_max_speed = shipp->current_max_speed;
2148 if ( wingnum == -1 )
2149 return lowest_max_speed;
2151 SDL_assert(wingnum >= 0);
2153 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2154 o = &Objects[so->objnum];
2155 ship *oshipp = &Ships[o->instance];
2156 ai_info *oaip = &Ai_info[oshipp->ai_index];
2158 if ((oaip->mode == AIM_WAYPOINTS) && (oaip->wing == wingnum)) {
2159 // Note: If a ship in the wing has a super low max speed, probably its engines are disabled. So, fly along and
2160 // ignore the poor guy.
2161 float cur_max = oshipp->current_max_speed;
2163 if (oaip->ai_flags & AIF_DOCKED) {
2164 if (oaip->dock_objnum > -1)
2165 if (Objects[oaip->dock_objnum].type == OBJ_SHIP)
2166 cur_max *= o->phys_info.mass/(o->phys_info.mass + Objects[oaip->dock_objnum].phys_info.mass);
2169 if ((oshipp->current_max_speed > 5.0f) && (cur_max < lowest_max_speed)) {
2170 lowest_max_speed = cur_max;
2175 return lowest_max_speed;
2179 // Tell everyone to ignore object objnum.
2180 void set_global_ignore_object(int objnum)
2184 SDL_assert(Objects[objnum].type == OBJ_SHIP);
2186 nprintf(("AI", "Telling everyone to ignore object %s\n", Ships[Objects[objnum].instance].ship_name));
2188 for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2189 if (Ignore_objects[i].objnum == -1) {
2190 Ignore_objects[i].objnum = objnum;
2191 Ignore_objects[i].signature = Objects[objnum].signature;
2196 if (i == MAX_IGNORE_OBJECTS) {
2197 // Couldn't find a free slot, but maybe one of these objects has died.
2198 for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2199 int o = Ignore_objects[i].objnum;
2200 if (Objects[o].type != OBJ_SHIP)
2201 break; // Not a ship, so use this slot.
2202 if (Objects[o].signature != Ignore_objects[i].signature)
2203 break; // Signatures don't match, so use this slot.
2206 if (i != MAX_IGNORE_OBJECTS) {
2207 Ignore_objects[i].objnum = objnum;
2208 Ignore_objects[i].signature = Objects[objnum].signature;
2210 nprintf(("Warning", "Ignore_objects buffer full. Stealing a slot to ignore object #%i\n"));
2215 r = objnum % MAX_IGNORE_OBJECTS;
2217 Ignore_objects[r].objnum = objnum;
2218 Ignore_objects[r].signature = Objects[objnum].signature;
2225 // Determine if object objnum is supposed to be ignored by object with ai_info *aip.
2227 // TRUE if objnum is aip->ignore_objnum (and signatures match)
2228 // or objnum is in ignore wing
2230 int is_ignore_object(ai_info *aip, int objnum)
2233 /* // First, scan all objects in global array of objects to be ignored.
2234 for (int i=0; i<MAX_IGNORE_OBJECTS; i++)
2235 if (Ignore_objects[i].objnum != -1)
2236 if (objnum == Ignore_objects[i].objnum)
2237 if (Objects[Ignore_objects[i].objnum].signature == Ignore_objects[i].signature)
2241 // Didn't find in global list. Now check
2242 if (aip->ignore_objnum == UNUSED_OBJNUM)
2243 return 0; // Not ignoring anything.
2244 else if (aip->ignore_objnum >= 0) { // This means it's ignoring an object, not a wing.
2245 if (aip->ignore_objnum == objnum) {
2246 if (Objects[aip->ignore_objnum].signature == aip->ignore_signature) {
2249 aip->ignore_objnum = UNUSED_OBJNUM;
2255 } else { // Ignoring a wing.
2256 Int3(); // Should never happen. I thought I removed this behavior! -- MK, 5/17/98
2258 /* int ignore_wingnum = -(aip->ignore_objnum + 1);
2260 SDL_assert(ignore_wingnum < MAX_WINGS);
2261 SDL_assert(aip->shipnum >= 0);
2262 return (Ships[Objects[objnum].instance].wingnum == ignore_wingnum);
2266 // -----------------------------------------------------------------------------
2268 // given a ship with bounding box and a point, find the closest point on the bbox
2269 int get_nearest_bbox_point(object *ship_obj, vector *start, vector *box_pt)
2271 vector temp, rf_start;
2273 pm = model_get(Ship_info[Ships[ship_obj->instance].ship_info_index].modelnum);
2275 // get start in ship rf
2276 vm_vec_sub(&temp, start, &ship_obj->pos);
2277 vm_vec_rotate(&rf_start, &temp, &ship_obj->orient);
2280 int inside = project_point_onto_bbox(&pm->mins, &pm->maxs, &rf_start, &temp);
2282 // get box_pt in world rf
2283 vm_vec_unrotate(box_pt, &temp, &ship_obj->orient);
2284 vm_vec_add2(box_pt, &ship_obj->pos);
2290 typedef struct eval_nearest_objnum {
2293 int enemy_team_mask;
2299 int check_danger_weapon_objnum;
2300 } eval_nearest_objnum;
2303 void evaluate_object_as_nearest_objnum(eval_nearest_objnum *eno)
2306 ship_subsys *attacking_subsystem;
2308 aip = &Ai_info[Ships[Objects[eno->objnum].instance].ai_index];
2310 attacking_subsystem = aip->targeted_subsys;
2312 if ((attacking_subsystem != NULL) || !(eno->trial_objp->flags & OF_PROTECTED)) {
2313 if ( OBJ_INDEX(eno->trial_objp) != eno->objnum ) {
2315 if (!Player_attacking_enabled && (eno->trial_objp == Player_obj))
2318 // If only supposed to attack ship in a specific wing, don't attack other ships.
2319 if ((eno->enemy_wing != -1) && (Ships[eno->trial_objp->instance].wingnum != eno->enemy_wing))
2322 // Don't keep firing at a ship that is in its death throes.
2323 if (Ships[eno->trial_objp->instance].flags & SF_DYING)
2326 if (is_ignore_object(aip, ((eno->trial_objp)-Objects)))
2329 if (eno->trial_objp->flags & OF_PROTECTED)
2332 if (Ships[eno->trial_objp->instance].flags & SF_ARRIVING)
2335 ship_info *sip = &Ship_info[Ships[eno->trial_objp->instance].ship_info_index];
2337 if (sip->flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2340 if (Ships[eno->trial_objp->instance].team & eno->enemy_team_mask) {
2344 // Allow targeting of stealth in nebula by his firing at me
2345 // This is done for a specific ship, not generally.
2346 if ( !eno->check_danger_weapon_objnum ) {
2347 // check if can be targeted if inside nebula
2348 if ( !object_is_targetable(eno->trial_objp, &Ships[Objects[eno->objnum].instance]) ) {
2349 // check if stealth ship is visible, but not "targetable"
2350 if ( !((sip->flags & SIF_STEALTH) && ai_is_stealth_visible(&Objects[eno->objnum], eno->trial_objp)) ) {
2356 // if objnum is BIG or HUGE, find distance to bbox
2357 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
2359 // check if inside bbox
2360 int inside = get_nearest_bbox_point(eno->trial_objp, &Objects[eno->objnum].pos, &box_pt);
2365 dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &box_pt);
2368 dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &eno->trial_objp->pos);
2371 // Make it more likely that fighters (or bombers) will be picked as an enemy by scaling up distance for other types.
2372 if ((Ship_info[Ships[eno->trial_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))) {
2376 num_attacking = num_enemies_attacking(eno->trial_objp-Objects);
2377 if ((sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) || (num_attacking < eno->max_attackers)) {
2378 if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))){
2379 dist *= (float) (num_attacking+2)/2.0f; // prevents lots of ships from attacking same target
2382 if (eno->trial_objp->flags & OF_PLAYER_SHIP){
2383 dist *= 1.0f + (NUM_SKILL_LEVELS - Game_skill_level - 1)/NUM_SKILL_LEVELS; // Favor attacking non-players based on skill level.
2386 if (dist < eno->nearest_dist) {
2387 eno->nearest_dist = dist;
2388 eno->nearest_objnum = eno->trial_objp-Objects;
2398 // Given an object and an enemy team, return the index of the nearest enemy object.
2399 // Unless aip->targeted_subsys != NULL, don't allow to attack objects
2400 // with OF_PROTECTED bit set.
2401 // Ship must be within range "range".
2402 // Don't attack a ship that already has at least max_attackers attacking it.
2403 int get_nearest_objnum(int objnum, int enemy_team_mask, int enemy_wing, float range, int max_attackers)
2405 object *danger_weapon_objp;
2409 // initialize eno struct
2410 eval_nearest_objnum eno;
2411 eno.enemy_team_mask = enemy_team_mask;
2412 eno.enemy_wing = enemy_wing;
2413 eno.max_attackers = max_attackers;
2414 eno.objnum = objnum;
2416 eno.nearest_dist = range;
2417 eno.nearest_objnum = -1;
2418 eno.check_danger_weapon_objnum = 0;
2420 // go through the list of all ships and evaluate as potential targets
2421 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2422 eno.trial_objp = &Objects[so->objnum];
2423 evaluate_object_as_nearest_objnum(&eno);
2427 // check if danger_weapon_objnum has will show a stealth ship
2428 aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2429 if (aip->danger_weapon_objnum >= 0) {
2430 danger_weapon_objp = &Objects[aip->danger_weapon_objnum];
2432 if (danger_weapon_objp->signature == aip->danger_weapon_signature) {
2433 SDL_assert(danger_weapon_objp->type == OBJ_WEAPON);
2434 // check if parent is a ship
2435 if (danger_weapon_objp->parent >= 0) {
2436 if ( is_object_stealth_ship(&Objects[danger_weapon_objp->parent]) ) {
2437 // check if stealthy
2438 if ( ai_is_stealth_visible(&Objects[objnum], &Objects[danger_weapon_objp->parent]) != STEALTH_FULLY_TARGETABLE ) {
2439 // check if weapon is laser
2440 if (Weapon_info[Weapons[danger_weapon_objp->instance].weapon_info_index].subtype == WP_LASER) {
2441 // check stealth ship by its laser fire
2442 eno.check_danger_weapon_objnum = 1;
2443 eno.trial_objp = &Objects[danger_weapon_objp->parent];
2444 evaluate_object_as_nearest_objnum(&eno);
2452 // If only looking for target in certain wing and couldn't find anything in
2453 // that wing, look for any object.
2454 if ((eno.nearest_objnum == -1) && (enemy_wing != -1)) {
2455 return get_nearest_objnum(objnum, enemy_team_mask, -1, range, max_attackers);
2458 return eno.nearest_objnum;
2461 // Given an object and an enemy team, return the index of the nearest enemy object.
2462 // Unlike find_enemy or find_nearest_objnum, this doesn't care about things like the protected flag or number
2463 // of enemies attacking.
2464 // It is used to find the nearest enemy to determine things like whether to rearm.
2465 int find_nearby_hostile(int objnum, int enemy_team_mask, float range, int *count)
2472 nearest_objnum = -1;
2473 nearest_dist = range;
2477 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2478 objp = &Objects[so->objnum];
2480 if ( OBJ_INDEX(objp) != objnum ) {
2481 if (Ships[objp->instance].flags & SF_DYING)
2484 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2487 if (Ships[objp->instance].team & enemy_team_mask) {
2490 dist = vm_vec_dist_quick(&Objects[objnum].pos, &objp->pos) - objp->radius*0.75f;
2495 if (dist < nearest_dist) {
2496 nearest_dist = dist;
2497 nearest_objnum = objp-Objects;
2504 return nearest_objnum;
2507 // return !0 if objp can be considered for a turret target, 0 otherwise
2508 // input: objp => object that turret is considering as an enemy
2509 // turret_parent => object index for ship that turret sits on
2510 int valid_turret_enemy(object *objp, object *turret_parent)
2512 if ( objp == turret_parent ) {
2516 if ( objp->type == OBJ_ASTEROID ) {
2520 if ( objp->type == OBJ_SHIP ) {
2522 shipp = &Ships[objp->instance];
2524 // don't fire at ships with protected bit set!!!
2525 if ( objp->flags & OF_PROTECTED ) {
2529 if ( !(Ship_info[shipp->ship_info_index].flags & SIF_DO_COLLISION_CHECK)) {
2533 if (shipp->flags & SF_ARRIVING) {
2540 if ( objp->type == OBJ_WEAPON ) {
2541 if ( Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_BOMB ) {
2542 if ( obj_team(turret_parent) != Weapons[objp->instance].team ) {
2551 // return 1 if objp is in fov of the specified turret, tp. Otherwise return 0.
2552 // dist = distance from turret to center point of object
2553 int object_in_turret_fov(object *objp, model_subsystem *tp, vector *tvec, vector *tpos, float dist)
2557 vm_vec_normalized_dir(&v2e, &objp->pos, tpos);
2558 dot = vm_vec_dot(&v2e, tvec);
2560 dot += objp->radius / (dist + objp->radius);
2562 if ( dot >= tp->turret_fov ) {
2569 // return 1 if bomb_objp is headed towards ship_objp
2570 int bomb_headed_towards_ship(object *bomb_objp, object *ship_objp)
2573 vector bomb_to_ship_vector;
2575 vm_vec_normalized_dir(&bomb_to_ship_vector, &ship_objp->pos, &bomb_objp->pos);
2576 dot = vm_vec_dot(&bomb_objp->orient.v.fvec, &bomb_to_ship_vector);
2585 // nubmer of live turrets with target_objnum
2586 int num_turrets_attacking(object *turret_parent, int target_objnum)
2591 shipp = &Ships[turret_parent->instance];
2593 SDL_assert(turret_parent->type == OBJ_SHIP);
2594 SDL_assert(Objects[target_objnum].type == OBJ_SHIP);
2596 for (ss=GET_FIRST(&shipp->subsys_list); ss!=END_OF_LIST(&shipp->subsys_list); ss=GET_NEXT(ss)) {
2597 // check if subsys is alive
2598 if (ss->current_hits <= 0.0f) {
2602 // check if it's a turret
2603 if (ss->system_info->type != SUBSYSTEM_TURRET) {
2607 // if the turret is locked
2608 if(ss->weapons.flags & SW_FLAG_TURRET_LOCK){
2612 // check if turret is targeting target_objnum
2613 if (ss->turret_enemy_objnum == target_objnum) {
2621 float Lethality_range_const = 2.0f;
2622 DCF(lethality_range, "N for modifying range: 1 / (1+N) at 100")
2624 dc_get_arg(ARG_FLOAT);
2625 Lethality_range_const = Dc_arg_float;
2628 float Player_lethality_bump[NUM_SKILL_LEVELS] = {
2629 // 0.0f, 5.0f, 10.0f, 25.0f, 40.0f
2630 0.0f, 0.0f, 0.0f, 0.0f, 0.0f
2633 // evaluate obj as posssible target for turret
2634 void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
2636 object *turret_parent_obj = &Objects[eeo->turret_parent_objnum];
2638 model_subsystem *tp = eeo->turret_subsys->system_info;
2641 // Don't look for bombs when weapon system is not ok
2642 if (objp->type == OBJ_WEAPON && !eeo->weapon_system_ok) {
2646 if ( !valid_turret_enemy(objp, turret_parent_obj) ) {
2651 if (!Player_attacking_enabled && (objp == Player_obj)) {
2656 if ( objp->type == OBJ_SHIP ) {
2657 shipp = &Ships[objp->instance];
2659 // check on enemy team
2660 if ( !(shipp->team & eeo->enemy_team_mask) ) {
2664 // check if protected
2665 if (objp->flags & OF_PROTECTED) {
2669 // check if beam protected
2670 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2671 if (objp->flags & OF_BEAM_PROTECTED) {
2676 if (eeo->big_only_flag) {
2677 if (!(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2682 // check if turret flagged to only target tagged ships
2683 if ( (eeo->turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && !ship_is_tagged(objp) ) {
2687 // check if valid target in nebula
2688 if ( !object_is_targetable(objp, &Ships[Objects[eeo->turret_parent_objnum].instance]) ) {
2689 // BYPASS ocassionally for stealth
2690 int try_anyway = FALSE;
2691 if ( is_object_stealth_ship(objp) ) {
2692 float turret_stealth_find_chance = 0.5f;
2693 float speed_mod = -0.1f + vm_vec_mag_quick(&objp->phys_info.vel) / 70.0f;
2694 if (frand() > (turret_stealth_find_chance + speed_mod)) {
2708 // modify dist for BIG|HUGE, getting closest point on bbox, if not inside
2709 dist = vm_vec_dist_quick(eeo->tpos, &objp->pos) - objp->radius;
2714 // check if object is a bomb attacking the turret parent
2715 // check if bomb is homing on the turret parent ship
2716 if (objp->type == OBJ_WEAPON) {
2717 if ( Weapons[objp->instance].homing_object == &Objects[eeo->turret_parent_objnum] ) {
2718 if ( dist < eeo->nearest_homing_bomb_dist ) {
2719 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2720 eeo->nearest_homing_bomb_dist = dist;
2721 eeo->nearest_homing_bomb_objnum = OBJ_INDEX(objp);
2724 // if not homing, check if bomb is flying towards ship
2725 } else if ( bomb_headed_towards_ship(objp, &Objects[eeo->turret_parent_objnum]) ) {
2726 if ( dist < eeo->nearest_bomb_dist ) {
2727 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2728 eeo->nearest_bomb_dist = dist;
2729 eeo->nearest_bomb_objnum = OBJ_INDEX(objp);
2733 } // end weapon section
2735 // maybe recalculate dist for big or huge ship
2736 // if (shipp && (Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2737 // fvi_ray_boundingbox(min, max, start, direction, hit);
2738 // dist = vm_vec_dist_quick(hit, tvec);
2741 // check for nearest attcker
2742 if ( (shipp) && (dist < eeo->weapon_travel_dist) ) {
2743 ai_info *aip = &Ai_info[shipp->ai_index];
2745 // modify distance based on number of turrets from my ship attacking enemy (add 10% per turret)
2746 // dist *= (num_enemies_attacking(OBJ_INDEX(objp))+2)/2; // prevents lots of ships from attacking same target
2747 int num_att_turrets = num_turrets_attacking(turret_parent_obj, OBJ_INDEX(objp));
2748 dist *= (1.0f + 0.1f*num_att_turrets);
2750 // return if we're over the cap
2751 int max_turrets = 3 + Game_skill_level * Game_skill_level;
2752 if (num_att_turrets > max_turrets) {
2756 // modify distance based on lethality of objp to my ship
2757 float active_lethality = aip->lethality;
2758 if (objp->flags & OF_PLAYER_SHIP) {
2759 active_lethality += Player_lethality_bump[Game_skill_level];
2762 dist /= (1.0f + 0.01f*Lethality_range_const*active_lethality);
2764 // Make level 2 tagged ships more likely to be targeted
2765 if (shipp->level2_tag_left > 0.0f) {
2769 // check if objp is targeting the turret's ship, or if objp has just hit the turret's ship
2770 if ( aip->target_objnum == eeo->turret_parent_objnum || aip->last_objsig_hit == Objects[eeo->turret_parent_objnum].signature ) {
2771 // A turret will always target a ship that is attacking itself... self-preservation!
2772 if ( aip->targeted_subsys == eeo->turret_subsys ) {
2773 dist *= 0.5f; // highest priority
2777 // maybe update nearest attacker
2778 if ( dist < eeo->nearest_attacker_dist ) {
2779 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2780 // nprintf(("AI", "Nearest enemy = %s, dist = %7.3f, dot = %6.3f, fov = %6.3f\n", Ships[objp->instance].ship_name, dist, vm_vec_dot(&v2e, tvec), tp->turret_fov));
2781 eeo->nearest_attacker_dist = dist;
2782 eeo->nearest_attacker_objnum = OBJ_INDEX(objp);
2785 } // end ship section
2788 // check if object is an asteroid attacking the turret parent - taylor
2789 if (objp->type == OBJ_ASTEROID) {
2790 if ( eeo->turret_parent_objnum == asteroid_collide_objnum(objp) ) {
2791 // give priority to the closest asteroid *impact* (ms intervals)
2792 dist *= 0.9f + (0.01f * asteroid_time_to_impact(objp));
2794 if (dist < eeo->nearest_dist ) {
2795 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2796 eeo->nearest_dist = dist;
2797 eeo->nearest_objnum = OBJ_INDEX(objp);
2801 } // end asteroid selection
2805 // return 0 only if objnum is beam protected and turret is beam turret
2806 int is_target_beam_valid(ship_subsys *turret_subsys, int objnum)
2808 // check if turret has beam weapon
2809 model_subsystem *tp = turret_subsys->system_info;
2811 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2812 if (Objects[objnum].flags & OF_BEAM_PROTECTED) {
2816 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_HUGE) {
2817 if (Objects[objnum].type == OBJ_SHIP && !(Ship_info[Ships[Objects[objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
2827 // Given an object and an enemy team, return the index of the nearest enemy object.
2830 // turret_parent_objnum => parent objnum for the turret
2831 // turret_subsys => pointer to system_info for the turret subsystem
2832 // enemy_team_mask => OR'ed TEAM_ flags for the enemy of the turret parent ship
2833 // tpos => position of turret (world coords)
2834 // tvec => forward vector of turret (world coords)
2835 // current_enemy => objnum of current turret target
2836 int get_nearest_turret_objnum(int turret_parent_objnum, ship_subsys *turret_subsys, int enemy_team_mask, vector *tpos, vector *tvec, int current_enemy, int big_only_flag)
2838 float weapon_travel_dist;
2839 int weapon_system_ok;
2841 model_subsystem *tp;
2842 eval_enemy_obj_struct eeo;
2844 // list of stuff to go thru
2848 tp = turret_subsys->system_info;
2849 weapon_travel_dist = SDL_min(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
2851 // Set flag based on strength of weapons subsystem. If weapons subsystem is destroyed, don't let turrets fire at bombs
2852 weapon_system_ok = 0;
2853 if ( ship_get_subsystem_strength( &Ships[Objects[turret_parent_objnum].instance], SUBSYSTEM_WEAPONS ) > 0 ) {
2854 weapon_system_ok = 1;
2857 // Initialize eeo struct.
2858 eeo.turret_parent_objnum = turret_parent_objnum;
2859 eeo.weapon_system_ok = weapon_system_ok;
2860 eeo.weapon_travel_dist = weapon_travel_dist;
2861 eeo.big_only_flag = big_only_flag;
2862 eeo.enemy_team_mask = enemy_team_mask;
2863 eeo.current_enemy = current_enemy;
2866 eeo.turret_subsys = turret_subsys;
2868 eeo.nearest_attacker_dist = 99999.0f;
2869 eeo.nearest_attacker_objnum = -1;
2871 eeo.nearest_homing_bomb_dist = 99999.0f;
2872 eeo.nearest_homing_bomb_objnum = -1;
2874 eeo.nearest_bomb_dist = 99999.0f;
2875 eeo.nearest_bomb_objnum = -1;
2877 eeo.nearest_dist = 99999.0f;
2878 eeo.nearest_objnum = -1;
2882 for( mo = GET_FIRST(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
2883 objp = &Objects[mo->objnum];
2884 evaluate_obj_as_target(objp, &eeo);
2887 if ( eeo.nearest_homing_bomb_objnum != -1 ) { // highest priority is an incoming homing bomb
2888 return eeo.nearest_homing_bomb_objnum;
2889 } else if ( eeo.nearest_bomb_objnum != -1 ) { // next highest priority is an incoming dumbfire bomb
2890 return eeo.nearest_bomb_objnum;
2895 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2896 objp = &Objects[so->objnum];
2897 evaluate_obj_as_target(objp, &eeo);
2900 SDL_assert(eeo.nearest_attacker_objnum < 0 || is_target_beam_valid(turret_subsys, eeo.nearest_attacker_objnum));
2901 // next highest priority is attacking ship
2902 if ( eeo.nearest_attacker_objnum != -1 ) { // next highest priority is an attacking ship
2903 return eeo.nearest_attacker_objnum;
2907 #if !(defined(FS2_DEMO) || defined(FS1_DEMO))
2909 // Asteroid_obj_list
2910 for( ao = GET_FIRST(&Asteroid_obj_list); ao != END_OF_LIST(&Asteroid_obj_list); ao = GET_NEXT(ao) ) {
2911 objp = &Objects[ao->objnum];
2912 evaluate_obj_as_target(objp, &eeo);
2916 return eeo.nearest_objnum; // lowest priority is the closest enemy objnum
2919 // Return timestamp until a ship can find an enemy.
2920 // Yes, no parameters. Based solely on skill level.
2921 int get_enemy_timestamp()
2923 return (NUM_SKILL_LEVELS - Game_skill_level) * ( (myrand() % 500) + 500);
2926 // -------------------------------------------------------------------
2927 // Return objnum if enemy found, else return -1;
2928 // Don't attack a ship that already has at least max_attackers attacking it.
2929 int find_enemy(int objnum, float range, int max_attackers)
2931 int enemy_team_mask;
2933 enemy_team_mask = get_enemy_team_mask(objnum);
2935 // if target_objnum != -1, use that as goal.
2936 ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2937 if (timestamp_elapsed(aip->choose_enemy_timestamp)) {
2938 aip->choose_enemy_timestamp = timestamp(get_enemy_timestamp());
2939 if (aip->target_objnum != -1) {
2940 int target_objnum = aip->target_objnum;
2942 // DKA don't undo object as target in nebula missions.
2943 // This could cause attack on ship on fringe on nebula to stop if attackee moves our of nebula range. (BAD)
2944 if (Objects[target_objnum].signature == aip->target_signature) {
2945 if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2946 if (!(Objects[target_objnum].flags & OF_PROTECTED)) {
2947 // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2948 return target_objnum;
2952 aip->target_objnum = -1;
2953 aip->target_signature = -1;
2956 return get_nearest_objnum(objnum, enemy_team_mask, aip->enemy_wing, range, max_attackers);
2958 aip->target_objnum = -1;
2959 aip->target_signature = -1;
2965 int Use_parent_target = 0;
2966 DCF_BOOL(use_parent_target, Use_parent_target)
2968 // -------------------------------------------------------------------
2969 // Return objnum if enemy found, else return -1;
2972 // turret_subsys => pointer to turret subsystem
2973 // objnum => parent objnum for the turret
2974 // tpos => position of turret (world coords)
2975 // tvec => forward vector of turret (world coords)
2976 // current_enemy => objnum of current turret target
2977 int find_turret_enemy(ship_subsys *turret_subsys, int objnum, vector *tpos, vector *tvec, int current_enemy, float fov, int big_only_flag = 0)
2979 int enemy_team_mask, enemy_objnum;
2980 model_subsystem *tp;
2983 tp = turret_subsys->system_info;
2984 enemy_team_mask = get_enemy_team_mask(objnum);
2986 // If a small ship and target_objnum != -1, use that as goal.
2987 ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2988 sip = &Ship_info[Ships[Objects[objnum].instance].ship_info_index];
2990 if ((sip->flags & SIF_SMALL_SHIP) && (aip->target_objnum != -1)) {
2991 int target_objnum = aip->target_objnum;
2993 if (Objects[target_objnum].signature == aip->target_signature) {
2994 if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2995 if ( !(Objects[target_objnum].flags & OF_PROTECTED) ) { // check this flag as well.
2996 // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2997 return target_objnum;
3001 aip->target_objnum = -1;
3002 aip->target_signature = -1;
3004 // Not small or small with target objnum
3006 // maybe use aip->target_objnum as next target
3007 if ((frand() < 0.8f) && (aip->target_objnum != -1) && Use_parent_target) {
3009 //check if aip->target_objnum is valid target
3010 int target_flags = Objects[aip->target_objnum].flags;
3011 if ( target_flags & OF_PROTECTED ) {
3012 // AL 2-27-98: why is a protected ship being targeted?
3013 set_target_objnum(aip, -1);
3017 // maybe use ship target_objnum if valid for turret
3018 // check for beam weapon and beam protected
3019 if ( !((target_flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) ) {
3020 if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
3021 // check for huge weapon and huge ship
3022 if ( !big_only_flag || (Ship_info[Ships[Objects[aip->target_objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
3023 // check for tagged only and tagged ship
3024 if ( (turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && ship_is_tagged(&Objects[aip->target_objnum]) ) {
3025 // select new target if aip->target_objnum is out of field of view
3028 /*dist =*/ vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, tpos);
3029 dot = vm_vec_dot(&v2e, tvec);
3030 // MODIFY FOR ATTACKING BIG SHIP
3031 // dot += (0.5f * Objects[aip->target_objnum].radius / dist);
3033 return aip->target_objnum;
3042 enemy_objnum = get_nearest_turret_objnum(objnum, turret_subsys, enemy_team_mask, tpos, tvec, current_enemy, big_only_flag);
3043 if ( enemy_objnum >= 0 ) {
3044 SDL_assert( !((Objects[enemy_objnum].flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) );
3045 if ( Objects[enemy_objnum].flags & OF_PROTECTED ) {
3047 enemy_objnum = aip->target_objnum;
3051 return enemy_objnum;
3054 // If issued an order to a ship that's awaiting repair, abort that process.
3055 // However, do not abort process for an object that is currently being repaired -- let it finish.
3056 void ai_set_goal_maybe_abort_dock(object *objp, ai_info *aip)
3058 if (aip->ai_flags & AIF_AWAITING_REPAIR) {
3061 if (aip->dock_objnum == -1) {
3064 repair_obj = &Objects[aip->dock_objnum];
3066 ai_do_objects_repairing_stuff( objp, repair_obj, REPAIR_INFO_ABORT );
3068 aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP); // Might request again after 30 seconds.
3071 void force_avoid_player_check(object *objp, ai_info *aip)
3073 if (Ships[objp->instance].team == Player_ship->team){
3074 aip->avoid_check_timestamp = timestamp(0); // Force a check for collision next frame.
3078 // --------------------------------------------------------------------------
3079 // Set *attacked as object to attack for object *attacker
3080 // If attacked == NULL, then attack any enemy object.
3081 // Attack point *rel_pos on object. This is for supporting attacking subsystems.
3082 void ai_attack_object(object *attacker, object *attacked, int priority, ship_subsys *ssp)
3086 SDL_assert(attacker != NULL);
3087 SDL_assert(attacker->instance != -1);
3088 SDL_assert(Ships[attacker->instance].ai_index != -1);
3090 aip = &Ai_info[Ships[attacker->instance].ai_index];
3091 force_avoid_player_check(attacker, aip);
3093 aip->ok_to_target_timestamp = timestamp(0); // Guarantee we can target.
3095 // if (!SDL_strncasecmp(Ships[attacker->instance].ship_name, NOX("Kami"), 4)) {
3096 // aip->ai_flags |= AIF_KAMIKAZE;
3097 // aip->ai_flags |= AIF_NO_DYNAMIC;
3100 if (attacker == attacked) {
3101 Int3(); // Bogus! Who tried to get me to attack myself! Trace out and fix!
3105 // Only set to chase if a fighter or bomber, otherwise just return.
3106 if (!(Ship_info[Ships[attacker->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
3107 // nprintf(("AI","Note: AI ship %s refusing to set AI mode to AIM_CHASE\n", Ships[attacker->instance].ship_name));
3109 nprintf(("AI", "AI ship %s is large ship ordered to attack %s\n", Ships[attacker->instance].ship_name, (attacked) ? Ships[attacked->instance].ship_name : "<none>"));
3112 // This is how "engage enemy" gets processed
3113 if (attacked == NULL) {
3114 aip->choose_enemy_timestamp = timestamp(0);
3116 set_target_objnum(aip, find_enemy(attacker-Objects, 99999.9f, 4));
3118 // check if we can see atacked in nebula
3119 if (aip->target_objnum != attacked - Objects) {
3120 aip->aspect_locked_time = 0.0f;
3122 set_target_objnum(aip, attacked - Objects);
3125 ai_set_goal_maybe_abort_dock(attacker, aip);
3126 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME); // No dynamic targeting for 7 seconds.
3128 if (is_ignore_object(aip, aip->target_objnum)) {
3129 aip->ignore_objnum = UNUSED_OBJNUM;
3132 aip->mode = AIM_CHASE;
3133 aip->submode = SM_ATTACK; // AL 12-15-97: need to set submode? I got an assert() where submode was bogus
3134 // for AIM_CHASE... it may have been not set correctly here
3136 set_targeted_subsys(aip, NULL, -1);
3137 if (aip->target_objnum != -1) {
3138 //nprintf(("AI", "Unprotecting ship %s\n", Ships[Objects[aip->target_objnum].instance].ship_name));
3139 Objects[aip->target_objnum].flags &= ~OF_PROTECTED; // If ship had been protected, unprotect it.
3142 Int3(); // Not supported yet!
3146 // --------------------------------------------------------------------------
3147 // Set *attacked as object to attack for object *attacker
3148 // Attack point *rel_pos on object. This is for supporting attacking subsystems.
3149 void ai_attack_wing(object *attacker, int wingnum, int priority)
3153 SDL_assert(attacker != NULL);
3154 SDL_assert(attacker->instance != -1);
3155 SDL_assert(Ships[attacker->instance].ai_index != -1);
3157 aip = &Ai_info[Ships[attacker->instance].ai_index];
3159 aip->enemy_wing = wingnum;
3160 aip->mode = AIM_CHASE;
3161 aip->submode = SM_ATTACK; // AL 12-15-97: need to set submode? I got an assert() where submode was bogus
3162 // for AIM_CHASE... it may have been not set correctly here
3164 aip->ok_to_target_timestamp = timestamp(0); // Guarantee we can target.
3166 int count = Wings[wingnum].current_count;
3170 index = (int) (frand() * count);
3175 set_target_objnum(aip, Ships[Wings[wingnum].ship_index[index]].objnum);
3177 ai_set_goal_maybe_abort_dock(attacker, aip);
3178 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME); // No dynamic targeting for 7 seconds.
3182 // --------------------------------------------------------------------------
3183 // Set *evaded as object for *evader to evade.
3184 void ai_evade_object(object *evader, object *evaded, int priority)
3188 SDL_assert(evader != NULL);
3189 SDL_assert(evaded != NULL);
3190 SDL_assert(evader->instance != -1);
3191 SDL_assert(Ships[evader->instance].ai_index != -1);
3193 if (evaded == evader) {
3194 Int3(); // Bogus! Who tried to get me to evade myself! Trace out and fix!
3198 aip = &Ai_info[Ships[evader->instance].ai_index];
3200 set_target_objnum(aip, evaded - Objects);
3201 aip->mode = AIM_EVADE;
3205 // Ignore some object without changing mode.
3206 void ai_ignore_object(object *ignorer, object *ignored, int priority)
3210 SDL_assert(ignorer != NULL);
3211 SDL_assert(ignored != NULL);
3212 SDL_assert(ignorer->instance != -1);
3213 SDL_assert(Ships[ignorer->instance].ai_index != -1);
3214 SDL_assert(ignorer != ignored);
3216 aip = &Ai_info[Ships[ignorer->instance].ai_index];
3218 // MK, 5/17/98, removing ignoring of wings.
3219 // It's too confusing. It often causes mysterious behavior in which fighters unexpectedly refuse to attack anything.
3220 /* if (Ships[ignored->instance].wingnum > -1) {
3223 wingnum = Ships[ignored->instance].wingnum;
3224 aip->ignore_objnum = -(wingnum+1);
3225 // set protected bit for each ship in a wing
3226 // MK, 4/23/98: Only set for fighters if they are the original "ignored" object
3227 for (i = 0; i < Wings[wingnum].current_count; i++ ) {
3230 objp = &Objects[Ships[Wings[wingnum].ship_index[i]].objnum];
3231 if (objp != ignored) {
3232 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))
3236 Objects[Ships[Wings[wingnum].ship_index[i]].objnum].flags |= OF_PROTECTED;
3241 aip->ignore_objnum = ignored - Objects;
3242 aip->ignore_signature = ignored->signature;
3243 aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3244 ignored->flags |= OF_PROTECTED; // set protected bit of ignored ship.
3249 // Ignore some object without changing mode.
3250 void ai_ignore_wing(object *ignorer, int wingnum, int priority)
3254 SDL_assert(ignorer != NULL);
3255 SDL_assert(ignorer->instance != -1);
3256 SDL_assert(Ships[ignorer->instance].ai_index != -1);
3257 SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
3259 aip = &Ai_info[Ships[ignorer->instance].ai_index];
3261 aip->ignore_objnum = -(wingnum +1);
3262 aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3266 // Add a path point in the global buffer Path_points.
3267 // modify_index = index in Path_points at which to store path point.
3268 // If modify_index == -1, then create a new point.
3269 // If a new point is created (ie, modify_index == -1), then Ppfp is updated.
3270 void add_path_point(vector *pos, int path_num, int path_index, int modify_index)
3274 if (modify_index == -1) {
3275 SDL_assert(Ppfp-Path_points < MAX_PATH_POINTS-1);
3279 SDL_assert((modify_index >= 0) && (modify_index < MAX_PATH_POINTS-1));
3280 pnp = &Path_points[modify_index];
3284 pnp->path_num = path_num;
3285 pnp->path_index = path_index;
3288 // Given two points on a sphere, the center of the sphere and the radius, return a
3289 // point on the vector through the midpoint of the chord on the sphere.
3290 void bisect_chord(vector *p0, vector *p1, vector *centerp, float radius)
3295 vm_vec_add(&tvec, p0, p1);
3296 vm_vec_sub2(&tvec, centerp);
3297 vm_vec_sub2(&tvec, centerp);
3298 if (vm_vec_mag_quick(&tvec) < 0.1f) {
3299 vm_vec_sub(&tvec, p0, p1);
3300 if (fl_abs(tvec.xyz.x) <= fl_abs(tvec.xyz.z)){
3301 tvec.xyz.x = -tvec.xyz.z;
3303 tvec.xyz.y = -tvec.xyz.x;
3307 vm_vec_normalize(&tvec);
3308 vm_vec_scale(&tvec, radius);
3309 vm_vec_add(&new_pnt, centerp, &tvec);
3311 add_path_point(&new_pnt, -1, -1, -1);
3314 // Create a path from the current position to a goal position.
3315 // The current position is in the current object and the goal position is
3316 // in the goal object.
3317 // It is ok to intersect the current object, but not the goal object.
3318 // This function is useful for creating a path to an initial point near a large
3321 // input: subsys_path: optional param (default 0), indicates this is a path to a subsystem
3322 void create_path_to_point(vector *curpos, vector *goalpos, object *curobjp, object *goalobjp, int subsys_path)
3324 // If can't cast vector to goalpos, then create an intermediate point.
3325 if (pp_collide(curpos, goalpos, goalobjp, curobjp->radius)) {
3329 // If this is a path to a subsystem, use SUBSYS_PATH_DIST as the radius for the object you are
3330 // trying to avoid. This is needed since subsystem paths extend out to SUBSYS_PATH_DIST, and we
3331 // want ships to reach their path destination without flying to points that sit on the radius of
3333 radius = goalobjp->radius;
3335 if ( SUBSYS_PATH_DIST > goalobjp->radius ) {
3336 radius = SUBSYS_PATH_DIST;
3340 // The intermediate point is at the intersection of:
3341 // tangent to *goalobjp sphere at point *goalpos
3342 // tangent to *goalobjp sphere through point *curpos in plane defined by *curpos, *goalpos, goalobjp->pos
3343 // Note, there are two tangents through *curpos, unless *curpos is on the
3344 // sphere. The tangent that causes the nearer intersection (to *goalpos) is chosen.
3345 get_tangent_point(&tan1, curpos, &goalobjp->pos, goalpos, radius);
3347 // If we can't reach tan1 from curpos, insert a new point.
3348 if (pp_collide(&tan1, curpos, goalobjp, curobjp->radius))
3349 bisect_chord(curpos, &tan1, &goalobjp->pos, radius);
3351 add_path_point(&tan1, -1, -1, -1);
3353 // If we can't reach goalpos from tan1, insert a new point.
3354 if (pp_collide(goalpos, &tan1, goalobjp, curobjp->radius))
3355 bisect_chord(goalpos, &tan1, &goalobjp->pos, radius);
3360 // Given an object and a model path, globalize the points on the model
3361 // and copy into the global path list.
3362 // If pnp != NULL, then modify, in place, the path points. This is used to create new
3363 // globalized points when the base object has moved.
3364 // input: randomize_pnt => optional parameter (default value -1), add random vector in sphere to this path point
3365 void copy_xlate_model_path_points(object *objp, model_path *mp, int dir, int count, int path_num, pnode *pnp, int randomize_pnt)
3370 int pp_index; // index in Path_points at which to store point, if this is a modify-in-place (pnp ! NULL)
3371 int start_index, finish_index;
3373 // nprintf(("AI", "Creating path for object %s in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
3375 // Initialize pp_index.
3376 // If pnp == NULL, that means we're creating new points. If not NULL, then modify in place.
3378 pp_index = -1; // This tells add_path_point to create a new point.
3380 pp_index = 0; // pp_index will get assigned to index in Path_points to reuse.
3382 vm_copy_transpose_matrix(&m, &objp->orient);
3386 finish_index = SDL_min(count, mp->nverts);
3388 SDL_assert(dir == -1); // direction must be up by 1 or down by 1 and it's neither!
3389 start_index = mp->nverts-1;
3390 finish_index = SDL_max(-1, mp->nverts-1-count);
3394 for (i=start_index; i != finish_index; i += dir) {
3395 // Globalize the point.
3396 vm_vec_rotate(&v1, &mp->verts[i].pos, &m);
3397 vm_vec_add2(&v1, &objp->pos);
3399 if ( randomize_pnt == i ) {
3401 static_randvec(OBJ_INDEX(objp), &v_rand);
3402 vm_vec_scale(&v_rand, 30.0f);
3403 vm_vec_add2(&v1, &v_rand);
3407 pp_index = pnp-Path_points + offset;
3409 add_path_point(&v1, path_num, i, pp_index);
3415 // For pl_objp, create a path along path path_num into mobjp.
3416 // The tricky part of this problem is creating the entry to the first point on the
3417 // predefined path. The points on this entry path are based on the location of Pl_objp
3418 // relative to the start of the path.
3421 // subsys_path: optional param (default 0), indicating this is a path to a subsystem
3422 void create_model_path(object *pl_objp, object *mobjp, int path_num, int subsys_path)
3424 ship *shipp = &Ships[pl_objp->instance];
3425 ai_info *aip = &Ai_info[shipp->ai_index];
3427 ship_info *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3428 polymodel *pm = model_get(osip->modelnum);
3430 pnode *ppfp_start = Ppfp;
3434 SDL_assert(path_num >= 0);
3436 // Do garbage collection if necessary.
3437 if (Ppfp-Path_points + 64 > MAX_PATH_POINTS) {
3438 garbage_collect_path_points();
3442 aip->path_start = Ppfp - Path_points;
3443 SDL_assert(path_num < pm->n_paths);
3445 mp = &pm->paths[path_num];
3447 SDL_assert(Ppfp-Path_points + mp->nverts + 4 < MAX_PATH_POINTS);
3449 vm_copy_transpose_matrix(&m, &mobjp->orient);
3450 vm_vec_rotate(&gp0, &mp->verts[0].pos, &m);
3451 vm_vec_add2(&gp0, &mobjp->pos);
3453 if (pp_collide(&pl_objp->pos, &gp0, mobjp, pl_objp->radius)) {
3454 vector perim_point1;
3455 vector perim_point2;
3457 perim_point2 = pl_objp->pos;
3459 // If object that wants to dock is inside bounding sphere of object it wants to dock with, make it fly out.
3460 // Assume it can fly "straight" out to the bounding sphere.
3461 if (vm_vec_dist_quick(&pl_objp->pos, &mobjp->pos) < mobjp->radius) {
3462 project_point_to_perimeter(&perim_point2, &mobjp->pos, mobjp->radius, &pl_objp->pos);
3463 add_path_point(&perim_point2, path_num, -1, -1);
3466 // If last point on pre-defined path is inside bounding sphere, create a new point on the surface of the sphere.
3467 if (vm_vec_dist_quick(&mobjp->pos, &gp0) < mobjp->radius) {
3468 project_point_to_perimeter(&perim_point1, &mobjp->pos, mobjp->radius, &gp0);
3469 create_path_to_point(&perim_point2, &perim_point1, pl_objp, mobjp, subsys_path);
3470 add_path_point(&perim_point1, path_num, -1, -1);
3471 } else { // The predefined path extends outside the sphere. Create path to that point.
3472 create_path_to_point(&perim_point2, &gp0, pl_objp, mobjp, subsys_path);
3476 // AL 12-31-97: If following a subsystem path, add random vector to second last path point
3477 if ( subsys_path ) {
3478 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL, mp->nverts-2);
3480 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL);
3483 aip->path_cur = aip->path_start;
3484 aip->path_dir = PD_FORWARD;
3485 aip->path_objnum = mobjp-Objects;
3486 aip->mp_index = path_num;
3487 aip->path_length = Ppfp - ppfp_start;
3488 aip->path_next_check_time = timestamp(1);
3490 aip->path_goal_obj_hash = create_object_hash(&Objects[aip->path_objnum]);
3492 aip->path_next_create_time = timestamp(1000); // OK to try to create one second later
3493 aip->path_create_pos = pl_objp->pos;
3494 aip->path_create_orient = pl_objp->orient;
3496 aip->ai_flags &= ~AIF_USE_EXIT_PATH; // ensure this flag is cleared
3499 // For pl_objp, create a path along path path_num into mobjp.
3500 // The tricky part of this problem is creating the entry to the first point on the
3501 // predefined path. The points on this entry path are based on the location of pl_objp
3502 // relative to the start of the path.
3503 void create_model_exit_path(object *pl_objp, object *mobjp, int path_num, int count)
3505 ship *shipp = &Ships[pl_objp->instance];
3506 ai_info *aip = &Ai_info[shipp->ai_index];
3508 ship_info *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3509 polymodel *pm = model_get(osip->modelnum);
3511 pnode *ppfp_start = Ppfp;
3513 aip->path_start = Ppfp - Path_points;
3514 SDL_assert(path_num < pm->n_paths);
3516 mp = &pm->paths[path_num];
3518 SDL_assert(Ppfp-Path_points + mp->nverts + 4 < MAX_PATH_POINTS);
3520 copy_xlate_model_path_points(mobjp, mp, -1, count, path_num, NULL);
3522 aip->path_cur = aip->path_start;
3523 aip->path_dir = PD_FORWARD;
3524 aip->path_objnum = mobjp-Objects;
3525 aip->mp_index = path_num;
3526 aip->path_length = Ppfp - ppfp_start;
3527 aip->path_next_check_time = timestamp(1);
3529 aip->ai_flags |= AIF_USE_EXIT_PATH; // mark as exit path, referenced in maybe
3532 // Return true if the vector from curpos to goalpos intersects with any ship other than the ignore objects.
3534 int pp_collide_any(vector *curpos, vector *goalpos, float radius, object *ignore_objp1, object *ignore_objp2, int big_only_flag)
3538 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
3539 object *objp = &Objects[so->objnum];
3541 if (big_only_flag) {
3542 if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
3546 if ((objp != ignore_objp1) && (objp != ignore_objp2)) {
3547 if (pp_collide(curpos, goalpos, objp, radius))
3548 return OBJ_INDEX(objp);
3555 // Used to create docking paths and other pre-defined paths through ships.
3556 // Creates a path in absolute space.
3557 // Create a path into the object objnum.
3560 // pl_objp: object that will use the path
3561 // objnum: Object to find path to.
3562 // path_num: model path index to use
3563 // exit_flag: true means this is an exit path in the model
3564 // subsys_path: optional param (default 0) that indicates this is a path to a subsystem
3566 // ai_info struct in Pl_objp gets stuffed with information to enable Pl_objp to fly the path.
3567 void ai_find_path(object *pl_objp, int objnum, int path_num, int exit_flag, int subsys_path)
3569 ai_info *aip = &Ai_info[Ships[pl_objp->instance].ai_index];
3571 SDL_assert(path_num >= 0);
3573 // This is test code, find an object with paths.
3575 object *objp = &Objects[objnum];
3577 if (objp->type == OBJ_SHIP) {
3579 polymodel *pm = model_get( Ships[objp->instance].modelnum );
3580 SDL_assert(pm->n_paths > path_num);
3582 aip->goal_objnum = objp-Objects;
3583 aip->goal_signature = objp->signature;
3585 create_model_exit_path(pl_objp, objp, path_num);
3587 create_model_path(pl_objp, objp, path_num, subsys_path);
3594 extern int vector_object_collision(vector *start_pos, vector *end_pos, object *objp, float radius_scale);
3596 // Maybe make *objp avoid a player object.
3597 // For now, 4/6/98, only check Player_obj.
3598 // If player collision would occur, set AIF_AVOIDING_SMALL_SHIP bit in ai_flags.
3599 // Set aip->avoid_goal_point
3600 int maybe_avoid_player(object *objp, vector *goal_pos)
3603 vector cur_pos, new_goal_pos;
3604 object *player_objp;
3605 vector n_vec_to_goal, n_vec_to_player;
3607 aip = &Ai_info[Ships[objp->instance].ai_index];
3609 if (!timestamp_elapsed(aip->avoid_check_timestamp))
3612 player_objp = Player_obj;
3616 // How far two ships could be apart and still collide within one second.
3617 speed_time = player_objp->phys_info.speed + objp->phys_info.speed;
3621 obj_obj_dist = vm_vec_dist_quick(&player_objp->pos, &objp->pos);
3623 if (obj_obj_dist > speed_time*2.0f)
3626 cur_pos = objp->pos;
3628 new_goal_pos = *goal_pos;
3630 float dist = vm_vec_normalized_dir(&n_vec_to_goal, goal_pos, &objp->pos);
3631 vm_vec_normalized_dir(&n_vec_to_player, &player_objp->pos, &objp->pos);
3633 if (dist > speed_time*2.0f) {
3634 vm_vec_scale_add(&new_goal_pos, &objp->pos, &n_vec_to_goal, 200.0f);
3637 if (vector_object_collision(&objp->pos, &new_goal_pos, player_objp, 1.5f)) {
3638 aip->ai_flags |= AIF_AVOIDING_SMALL_SHIP;
3642 vm_vec_sub(&avoid_vec, &n_vec_to_goal, &n_vec_to_player);
3643 if (vm_vec_mag_quick(&avoid_vec) < 0.01f) {
3644 vm_vec_copy_scale(&avoid_vec, &objp->orient.v.rvec, frand()-0.5f);
3645 vm_vec_scale_add2(&avoid_vec, &objp->orient.v.uvec, frand()-0.5f);
3646 vm_vec_normalize(&avoid_vec);
3649 vm_vec_normalize(&avoid_vec);
3650 vm_vec_crossprod(&tvec1, &n_vec_to_goal, &avoid_vec);
3651 vm_vec_crossprod(&avoid_vec, &tvec1, &n_vec_to_player);
3654 // Now, avoid_vec is a vector perpendicular to the vector to the player and the direction *objp
3655 // should fly in to avoid the player while still approaching its goal.
3656 vm_vec_scale_add(&aip->avoid_goal_point, &player_objp->pos, &avoid_vec, 400.0f);
3658 aip->avoid_check_timestamp = timestamp(1000);
3662 aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
3663 aip->avoid_check_timestamp = timestamp((int) (obj_obj_dist/200.0f) + 500);
3669 // Make object *still_objp enter AIM_STILL mode.
3670 // Make it point at view_pos.
3671 void ai_stay_still(object *still_objp, vector *view_pos)
3676 SDL_assert(still_objp->type == OBJ_SHIP);
3677 SDL_assert((still_objp->instance >= 0) && (still_objp->instance < MAX_OBJECTS));
3679 shipp = &Ships[still_objp->instance];
3680 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
3682 aip = &Ai_info[shipp->ai_index];
3684 aip->mode = AIM_STILL;
3686 // If view_pos not NULL, point at that point. Else, point at a point directly in front of ship. Ie, don't turn.
3687 if (view_pos != NULL)
3688 aip->goal_point = *view_pos;
3690 vm_vec_scale_add(&aip->goal_point, &still_objp->pos, &still_objp->orient.v.fvec, 100.0f);
3693 // code which is called from ai_dock_with_object and ai_dock to set flags and apprioriate variable
3694 // when two objects have completed docking. used because we can dock object initially at misison load
3695 // time (meaning that ai_dock() might never get called). docker has docked with dockee (i.e. docker
3696 // would be a freighter and dockee would be a cargo).
3697 void ai_do_objects_docked_stuff(object *docker, object *dockee)
3699 ai_info *aip, *other_aip;
3701 aip = &Ai_info[Ships[docker->instance].ai_index];
3702 other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3704 // set the flags and dock_objnum for both objects
3705 aip->ai_flags |= AIF_DOCKED;
3706 aip->dock_objnum = OBJ_INDEX(dockee);
3707 other_aip->ai_flags |= AIF_DOCKED;
3708 other_aip->dock_objnum = OBJ_INDEX(docker);
3709 aip->dock_signature = dockee->signature;
3710 other_aip->dock_signature = docker->signature;
3712 // add multiplayer hook here to deal with docked objects. We need to only send information
3713 // about the object that is docking. Both flags will get updated.
3714 if ( MULTIPLAYER_MASTER )
3715 send_ai_info_update_packet( docker, AI_UPDATE_DOCK );
3719 // code which is called when objects become undocked. Equivalent of above function.
3720 // dockee might not be valid since this code can get called to cleanup after a ship
3722 void ai_do_objects_undocked_stuff( object *docker, object *dockee )
3724 ai_info *aip, *other_aip;
3726 // add multiplayer hook here to deal with undocked objects. Do it before we
3727 // do anything else. We don't need to send info for both objects, since we can find
3728 // it be dock_objnum
3729 if ( MULTIPLAYER_MASTER )
3730 send_ai_info_update_packet( docker, AI_UPDATE_UNDOCK );
3732 aip = &Ai_info[Ships[docker->instance].ai_index];
3734 // set the flags and dock_objnum for both objects
3735 aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3736 aip->dock_objnum = -1;
3738 if ( dockee != NULL ) {
3739 other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3740 other_aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3741 other_aip->dock_objnum = -1;
3747 // --------------------------------------------------------------------------
3748 // Interface from goals code to AI.
3749 // Cause *docker to dock with *dockee.
3750 // priority is priority of goal from goals code.
3752 // AIDO_DOCK set goal of docking
3753 // AIDO_DOCK_NOW immediately dock, used for ships that need to be docked at mission start
3754 // AIDO_UNDOCK set goal of undocking
3755 void ai_dock_with_object(object *docker, object *dockee, int priority, int dock_type, int docker_index, int dockee_index)
3758 ai_info *dockee_aip;
3760 SDL_assert(docker != NULL);
3761 SDL_assert(dockee != NULL);
3762 SDL_assert(docker->instance != -1);
3763 SDL_assert(Ships[docker->instance].ai_index != -1);
3764 SDL_assert(Ships[dockee->instance].ai_index != -1);
3765 SDL_assert( docker_index != -1 );
3766 SDL_assert( dockee_index != -1 );
3768 aip = &Ai_info[Ships[docker->instance].ai_index];
3770 if ((aip->ai_flags & AIF_DOCKED) && (dock_type == AIDO_DOCK)) {
3772 // int docker_index2, dockee_index2;
3774 SDL_assert(aip->dock_objnum > -1);
3775 // dockee2 = &Objects[aip->dock_objnum];
3776 // docker_index2 = aip->dock_index;
3777 // dockee_index2 = aip->dockee_index;
3778 // MWA -- 2/9/98. use the goal code to undock the ships since goals might need to get removed
3779 // and that code will do it properly. I'd actually be surprised if we got into this code anymore
3780 // since the outer layer goal code should deal with this issue....but who knows...
3781 ai_add_goal_ship_internal( aip, AI_GOAL_UNDOCK, NULL, -1, -1, 0 );
3784 //ai_dock_with_object(docker, dockee2, priority, AIDO_UNDOCK, docker_index2, dockee_index2);
3785 nprintf(("AI", "Ship %s told to dock with %s, but it was already docked with %s.\n", Ships[docker->instance].ship_name, Ships[dockee->instance].ship_name, Ships[Objects[aip->dock_objnum].instance].ship_name));
3786 nprintf(("AI", "...so ship %s will now undock.\n", Ships[docker->instance].ship_name));
3790 dockee_aip = &Ai_info[Ships[dockee->instance].ai_index];
3792 aip->goal_objnum = dockee - Objects;
3793 aip->goal_signature = dockee->signature;
3795 aip->mode = AIM_DOCK;
3797 switch (dock_type) {
3799 aip->submode = AIS_DOCK_0;
3802 aip->submode = AIS_DOCK_3A;
3805 aip->submode = AIS_UNDOCK_0;
3808 Int3(); // Bogus dock_type.
3811 aip->submode_start_time = Missiontime;
3812 aip->dock_index = docker_index;
3813 aip->dockee_index = dockee_index;
3815 dockee_aip->dock_index = dockee_index;
3816 dockee_aip->dockee_index = docker_index;
3818 // get the path number to the docking point on the dockee. Each docking point contains a list
3819 // of paths that the point can be reached by. Pick the first path in the path list for now.
3820 // We only want to do this stuff if we are docking!!! Be sure to set the path index
3821 if ((dock_type == AIDO_DOCK) || (dock_type == AIDO_DOCK_NOW)) {
3823 polymodel *pm = model_get( Ships[dockee->instance].modelnum );
3824 SDL_assert( pm->docking_bays[dockee_index].num_spline_paths > 0 );
3827 // only set the dock path index if we are docking. undocking will assume that dock_path_index
3828 // already set from some other docking command
3829 aip->dock_path_index = dockee_index;
3830 dockee_aip->dock_path_index = docker_index;
3833 if (dock_type != AIDO_DOCK_NOW) {
3835 // Note: Second parameter is dock path index. This should be specified as an
3836 // _input_ to this function and passed through. The path index should be already
3837 // set for the undock function
3838 path_num = ai_return_path_num_from_dockbay(dockee, dockee_index);
3839 ai_find_path(docker, dockee-Objects, path_num, 0);
3840 // ai_find_path(dockee-Objects, dockee_index, 0);
3842 dock_orient_and_approach(docker, dockee, DOA_DOCK_STAY);
3843 //aip->dock_objnum = OBJ_INDEX(dockee);
3844 ai_do_objects_docked_stuff( docker, dockee );
3849 // Cause a ship to fly its waypoints.
3851 // WPF_REPEAT Set -> repeat waypoints.
3852 void ai_start_waypoints(object *objp, int waypoint_list_index, int wp_flags)
3856 SDL_assert(waypoint_list_index < Num_waypoint_lists);
3858 //nprintf(("AI", "Frame %i: Ship %s instructed to fly waypoint list #%i\n", AI_FrameCount, Ships[objp->instance].ship_name, waypoint_list_index));
3859 aip = &Ai_info[Ships[objp->instance].ai_index];
3861 if ( (aip->mode == AIM_WAYPOINTS) && (aip->wp_index == waypoint_list_index) )
3864 aip->ai_flags |= AIF_FORMATION_WING;
3865 aip->ai_flags &= ~AIF_FORMATION_OBJECT;
3866 aip->wp_list = waypoint_list_index;
3868 aip->wp_flags = wp_flags;
3869 aip->mode = AIM_WAYPOINTS;
3871 SDL_assert(aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC);
3874 // Make *objp stay within dist units of *other_objp
3875 void ai_do_stay_near(object *objp, object *other_objp, float dist)
3879 SDL_assert(objp != other_objp); // Bogus! Told to stay near self.
3880 SDL_assert(objp->type == OBJ_SHIP);
3881 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
3883 aip = &Ai_info[Ships[objp->instance].ai_index];
3885 aip->mode = AIM_STAY_NEAR;
3887 aip->stay_near_distance = dist;
3888 aip->goal_objnum = other_objp-Objects;
3889 aip->goal_signature = other_objp->signature;
3893 // Make object *objp form on wing of object *goal_objp
3894 void ai_form_on_wing(object *objp, object *goal_objp)
3900 // objp == goal_objp sometimes in multiplayer when someone leaves a game -- make a simple
3901 // out for this case.
3902 if ( Game_mode & GM_MULTIPLAYER ) {
3903 if ( objp == goal_objp ) {
3908 SDL_assert(objp != goal_objp); // Bogus! Told to form on own's wing!
3910 shipp = &Ships[objp->instance];
3911 sip = &Ship_info[shipp->ship_info_index];
3913 // Only fighters or bombers allowed to form on wing.
3914 if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
3915 nprintf(("AI", "Warning: Ship %s tried to form on player's wing, but not fighter or bomber.\n", shipp->ship_name));
3919 aip = &Ai_info[Ships[objp->instance].ai_index];
3921 aip->ai_flags &= ~AIF_FORMATION_WING;
3922 aip->ai_flags |= AIF_FORMATION_OBJECT;
3924 aip->goal_objnum = goal_objp-Objects;
3925 ai_set_goal_maybe_abort_dock(objp, aip);
3926 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME*4); // Super extra long time until can target another ship.
3930 // Given an object and an object on whose wing to form, return slot to use.
3932 // This function is called per object in formation per frame. Should store slot in ai_info struct.
3933 int ai_formation_object_get_slotnum(int objnum, object *objp)
3935 int slotnum = 1; // Note: Slot #0 means leader, which isn't someone who was told to form-on-wing.
3938 for ( o = GET_FIRST(&obj_used_list); o != END_OF_LIST(&obj_used_list); o = GET_NEXT(o) ) {
3941 else if (o->type == OBJ_SHIP)
3942 if (Ai_info[Ships[o->instance].ai_index].ai_flags & AIF_FORMATION_OBJECT)
3943 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == objnum)
3947 SDL_assert(o != END_OF_LIST(&obj_used_list)); // Didn't find objp in list of used ships. Impossible!
3952 #define BIGNUM 100000.0f
3956 // Given an attacker's position and a target's position and velocity, compute the time of
3957 // intersection of a weapon fired by the attacker with speed weapon_speed.
3958 // Return this value. Return value of 0.0f means no collision is possible.
3959 float compute_collision_time(vector *targpos, vector *targvel, vector *attackpos, float weapon_speed)
3961 vector vec_to_target;
3966 vm_vec_sub(&vec_to_target, targpos, attackpos);
3967 pos_dot_vel = vm_vec_dot(&vec_to_target, targvel);
3968 vel_sqr = vm_vec_dot(targvel, targvel) - weapon_speed*weapon_speed;
3969 discrim = pos_dot_vel*pos_dot_vel - vel_sqr*vm_vec_dot(&vec_to_target, &vec_to_target);
3971 if (discrim > 0.0f) {
3972 float t1, t2, t_solve;
3974 t1 = (-pos_dot_vel + fl_sqrt(discrim)) / vel_sqr;
3975 t2 = (-pos_dot_vel - fl_sqrt(discrim)) / vel_sqr;
3981 if ((t2 > 0.0f) && (t2 < t_solve))
3984 if (t_solve < BIGNUM-1.0f) {
3985 return t_solve + Debug_k * flFrametime;
3993 // --------------------------------------------------------------------------
3994 // If far away, use player's speed.
3995 // If in between, lerp between player and laser speed
3996 // If close, use laser speed.
3997 // Want to know how much time it will take to get to the enemy.
3998 // This function doesn't account for the fact that by the time the player
3999 // (or his laser) gets to the current enemy position, the enemy will have moved.
4000 // This is dealt with in polish_predicted_enemy_pos.
4001 float compute_time_to_enemy(float dist_to_enemy, object *pobjp, object *eobjp)
4003 float time_to_enemy;
4004 float pl_speed = pobjp->phys_info.speed;
4005 float max_laser_distance, max_laser_speed;
4006 int bank_num, weapon_num;
4007 ship *shipp = &Ships[pobjp->instance];
4009 bank_num = shipp->weapons.current_primary_bank;
4010 weapon_num = shipp->weapons.primary_bank_weapons[bank_num];
4011 max_laser_speed = Weapon_info[weapon_num].max_speed;
4012 max_laser_distance = max_laser_speed * Weapon_info[weapon_num].lifetime;
4014 // If pretty far away, use player's speed to predict position, else
4015 // use laser's speed because when close, we care more about hitting
4016 // with a laser than about causing ship:ship rendezvous.
4017 if (dist_to_enemy > 1.5 * max_laser_distance) {
4018 if (pl_speed > 0.0f)
4019 time_to_enemy = dist_to_enemy/pl_speed;
4021 time_to_enemy = 1.0f;
4022 } else if (dist_to_enemy > 1.1*max_laser_distance) {
4023 if (pl_speed > 0.1f) {
4026 scale = (float) ((dist_to_enemy - max_laser_distance) / max_laser_distance);
4028 time_to_enemy = (float) (dist_to_enemy/(pl_speed * scale + max_laser_speed * (1.0f - scale)));
4030 time_to_enemy = 2.0f;
4032 time_to_enemy = (float) (dist_to_enemy/max_laser_speed);
4034 // return time_to_enemy * (1.0f + Ai_info[Ships[pobjp->instance].ai_index].lead_scale);
4035 return time_to_enemy + flFrametime;
4038 // Stuff *dot and *tts.
4039 // *dot is always computed. If dot is less than zero, the magnitude is
4040 // incorrect, not having been divided by distance.
4041 // If *dot is > 0.0f, then tts is computed. This is the time it will take object
4042 // *objp to get to *pos, assuming it moves right at it.
4043 void fds_aux(float *dot, float *tts, vector *pos, float dtime, object *objp)
4047 vm_vec_sub(&v2s, pos, &objp->pos);
4048 *dot = vm_vec_dot(&v2s, &objp->orient.v.fvec);
4053 dist = vm_vec_dist(&objp->pos, pos);
4060 if (objp->phys_info.speed > 0.1f)
4061 *tts = dist / objp->phys_info.speed;
4063 *tts = dist * 100.0f;
4068 // Return index of weapon that could hit object *sobjp within dtime seconds.
4069 // Actual time until impact returned in *atime.
4070 int find_danger_weapon(object *sobjp, float dtime, float *atime, float dot_threshhold)
4072 object *objp, *best_objp = NULL;
4073 float best_tts = 1000.0f;
4075 for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
4076 if ((objp->type == OBJ_WEAPON) && (sobjp-Objects != objp->parent)) {
4078 // vector psp; // Predicted ship position.
4080 // Get dot and time to current ship position.
4081 fds_aux(&dot, &tts, &sobjp->pos, dtime, objp);
4083 // If dot and tts are in plausible range, do more expensive stuff.
4085 // float dot_from_sobjp;
4088 vm_vec_normalized_dir(&v2e, &objp->pos, &sobjp->pos);
4089 // dot_from_sobjp = vm_vec_dot(&sobjp->orient.v.fvec, &v2e);
4090 // if (dot_from_sobjp >= dot_threshhold)
4092 if (tts < best_tts) {
4103 if (best_objp != NULL)
4104 return best_objp-Objects;
4110 // --------------------------------------------------------------------------
4111 void ai_set_positions(object *pl_objp, object *en_objp, ai_info *aip, vector *player_pos, vector *enemy_pos)
4113 *player_pos = pl_objp->pos;
4115 if (aip->next_predict_pos_time > Missiontime) {
4116 *enemy_pos = aip->last_predicted_enemy_pos;
4118 *enemy_pos = en_objp->pos;
4120 aip->next_predict_pos_time = Missiontime + Skill_level_delay[Game_skill_level];
4121 aip->last_predicted_enemy_pos = *enemy_pos;
4127 // --------------------------------------------------------------------------
4128 int find_nearest_waypoint(object *objp)
4131 float dist, min_dist, dot;
4136 wp_listnum = Ai_info[Ships[objp->instance].ai_index].wp_list;
4137 SDL_assert(wp_listnum > 0);
4138 wpl = &Waypoint_lists[wp_listnum];
4140 min_dist = 999999.0f;
4143 for (i=0; i<wpl->count; i++) {
4144 dist = vm_vec_dist_quick(&objp->pos, &wpl->waypoints[i]);
4145 dot = vm_vec_dot_to_point(&objp->orient.v.fvec, &objp->pos, &wpl->waypoints[i]);
4146 dist = (float) (dist * (1.25 - dot));
4147 if (dist < min_dist) {
4153 SDL_assert(min_ind != -1);
4158 // Given an ai_info struct, by reading current goal and path information,
4159 // extract base path information and return in pmp and pmpv.
4160 // Return true if found, else return false.
4161 // false means the current point is not on the original path.
4162 int get_base_path_info(int path_cur, int goal_objnum, model_path **pmp, mp_vert **pmpv)
4164 pnode *pn = &Path_points[path_cur];
4165 ship_info *sip = &Ship_info[Ships[Objects[goal_objnum].instance].ship_info_index];
4166 polymodel *pm = model_get(sip->modelnum);
4167 //static int debug_last_index = -1; // no longer used
4171 if (pn->path_num != -1) {
4172 *pmp = &pm->paths[pn->path_num];
4173 if (pn->path_index != -1)
4174 *pmpv = &(*pmp)->verts[pn->path_index];
4180 /* if (debug_last_index != *pmpv-(*pmp)->verts) {
4181 debug_last_index = *pmpv-(*pmp)->verts;
4182 nprintf(("AI", "Point %i has %i turrets: ", *pmpv-(*pmp)->verts, (*pmpv)->nturrets));
4183 for (int i=0; i<(*pmpv)->nturrets; i++) {
4184 nprintf(("AI", "%i ", (*pmpv)->turret_ids[i]));
4186 nprintf(("AI", "\n"));
4192 // Modify, in place, the points in a global model path.
4193 // Only modify those points that are defined in the model path. Don't modify the
4194 // leadin points, such as those that are necessary to get the model on the path.
4195 void modify_model_path_points(object *objp)
4197 ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
4198 object *mobjp = &Objects[aip->path_objnum];
4199 ship_info *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
4200 polymodel *pm = model_get(osip->modelnum);
4204 SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
4206 pnp = &Path_points[aip->path_start];
4207 while ((pnp->path_index == -1) && (pnp-Path_points - aip->path_start < aip->path_length))
4210 path_num = pnp->path_num;
4211 SDL_assert((path_num >= 0) && (path_num < pm->n_paths));
4213 SDL_assert(pnp->path_index != -1); // If this is -1, that means we never found the model path points
4216 if ( aip->ai_flags & AIF_USE_EXIT_PATH ) {
4220 copy_xlate_model_path_points(mobjp, &pm->paths[path_num], dir, pm->paths[path_num].nverts, path_num, pnp);
4223 // Return an indication of the distance between two matrices.
4224 // This is the sum of the distances of their dot products from 1.0f.
4225 float ai_matrix_dist(matrix *mat1, matrix *mat2)
4229 t = 1.0f - vm_vec_dot(&mat1->v.fvec, &mat2->v.fvec);
4230 t += 1.0f - vm_vec_dot(&mat1->v.uvec, &mat2->v.uvec);
4231 t += 1.0f - vm_vec_dot(&mat1->v.rvec, &mat2->v.rvec);
4237 // Paths are created in absolute space, so a moving object needs to have model paths within it recreated.
4238 // This uses the hash functions which means the slightest movement will cause a recreate, though the timestamp
4239 // prevents this from happening too often.
4240 // force_recreate_flag TRUE means to recreate regardless of timestamp.
4241 // Returns TRUE if path recreated.
4242 float maybe_recreate_path(object *objp, ai_info *aip, int force_recreate_flag)
4246 SDL_assert(&Ai_info[Ships[objp->instance].ai_index] == aip);
4248 if ((aip->mode == AIM_BAY_EMERGE) || (aip->mode == AIM_BAY_DEPART))
4249 if ((OBJ_INDEX(objp) % 4) == (Framecount % 4))
4250 force_recreate_flag = 1;
4252 // If no path, that means we don't need one.
4253 if (aip->path_start == -1)
4256 // AL 11-12-97: If AIF_USE_STATIC_PATH is set, don't try to recreate. This is needed when ships
4257 // emerge from fighter bays. We don't need to recreate the path.. and in case the
4258 // parent ship dies, we still want to be able to continue on the path
4259 if ( aip->ai_flags & AIF_USE_STATIC_PATH )
4262 if (force_recreate_flag || timestamp_elapsed(aip->path_next_create_time)) {
4265 path_objp = &Objects[aip->path_objnum];
4267 if ((hashval = create_object_hash(path_objp)) != aip->path_goal_obj_hash) {
4270 dist = vm_vec_dist_quick(&path_objp->pos, &aip->path_create_pos);
4271 dist += ai_matrix_dist(&path_objp->orient, &aip->path_create_orient) * 25.0f;
4273 if (force_recreate_flag || (dist > 2.0f)) {
4274 aip->path_next_create_time = timestamp(1000); // Update again in as little as 1000 milliseconds, ie 1 second.
4275 aip->path_goal_obj_hash = hashval;
4276 modify_model_path_points(objp);
4278 aip->path_create_pos = path_objp->pos;
4279 aip->path_create_orient = path_objp->orient;
4289 // Set acceleration for ai_dock().
4290 void set_accel_for_docking(object *objp, ai_info *aip, float dot, float dot_to_next, float dist_to_next, float dist_to_goal, ship_info *sip)
4292 float prev_dot_to_goal = aip->prev_dot_to_goal;
4294 aip->prev_dot_to_goal = dot;
4296 if (objp->phys_info.speed < 0.0f) {
4297 accelerate_ship(aip, 1.0f/32.0f);
4298 } else if ((prev_dot_to_goal-dot) > 0.01) {
4299 if (prev_dot_to_goal > dot + 0.05f) {
4300 accelerate_ship(aip, 0.0f);
4302 change_acceleration(aip, -1.0f); // -1.0f means subtract off flFrametime from acceleration value in 0.0..1.0
4305 if ((aip->mode == AIM_DOCK) && (dist_to_next < 150.0f) && (aip->path_start + aip->path_length - 2 == aip->path_cur)) {
4306 set_accel_for_target_speed(objp, sip->max_speed * SDL_max(dist_to_next/500.0f, 1.0f));
4307 //mprintf(("dist = %7.3f, speed = %7.3f\n", dist_to_next, objp->phys_info.speed));
4308 } else if ((dot_to_next >= dot * .9) || (dist_to_next > 100.0f)) {
4309 if (dist_to_goal > 200.0f)
4310 set_accel_for_target_speed(objp, sip->max_speed * (dot + 1.0f) / 2.0f);
4314 xdot = (dot_to_next + dot)/2.0f;
4318 // AL: if following a path not in dock mode, move full speed
4319 if (( aip->mode != AIM_DOCK ) && (dot > 0.9f)) {
4320 set_accel_for_target_speed(objp, sip->max_speed*dot*dot*dot);
4322 if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4323 //nprintf(("AI", "Target speed = %7.3f\n", dist_to_goal/8.0f));
4324 set_accel_for_target_speed(objp, dist_to_goal/8.0f + 2.0f);
4326 set_accel_for_target_speed(objp, sip->max_speed * (2*xdot + 0.25f)/4.0f);
4333 xdot = SDL_max(dot_to_next, 0.1f);
4334 if ( aip->mode != AIM_DOCK ) {
4335 set_accel_for_target_speed(objp, sip->max_speed);
4338 if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4339 speed = dist_to_goal/8.0f + 2.0f;
4340 } else if (dist_to_goal < 4*objp->radius + 50.0f) {
4341 speed = dist_to_goal/4.0f + 4.0f;
4343 speed = sip->max_speed * (3*xdot + 1.0f)/4.0f;
4345 if (aip->mode == AIM_DOCK) {
4346 speed = speed * 2.0f + 1.0f;
4347 if (aip->goal_objnum != -1) {
4348 speed += Objects[aip->goal_objnum].phys_info.speed;
4352 set_accel_for_target_speed(objp, speed);
4358 // --------------------------------------------------------------------------
4359 // Follow a path associated with a large object, such as a capital ship.
4360 // The points defined on the path are in the object's reference frame.
4361 // The object of interest is goal_objnum.
4362 // The paths are defined in the model. The path of interest is wp_list.
4363 // The next goal point in the path is wp_index.
4364 // wp_flags contain special information specific to the path.
4366 // The path vertices are defined by model_path structs:
4367 // typedef struct model_path {
4368 // char name[MAX_NAME_LEN]; // name of the subsystem. Probably displayed on HUD
4373 // The polymodel struct for the object contains the following:
4375 // model_path *paths;
4377 // Returns distance to goal point.
4381 float dot, dist_to_goal, dist_to_next, dot_to_next;
4382 ship *shipp = &Ships[Pl_objp->instance];
4383 ship_info *sip = &Ship_info[shipp->ship_info_index];
4386 float mag;//, prev_dot_to_goal;
4387 vector temp_vec, *slop_vec;
4389 vector *cvp, *nvp, next_vec, gcvp, gnvp; // current and next vertices in global coordinates.
4391 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4393 SDL_assert(aip->goal_objnum != -1);
4394 SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
4396 gobjp = &Objects[aip->goal_objnum];
4399 polymodel *pm = model_get( Ships[gobjp->instance].modelnum );
4400 SDL_assert(pm->n_paths > 0);
4403 if (aip->path_start == -1) {
4405 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
4406 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
4407 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
4410 // nprintf(("AI", "Frame: %i, Path index = %i/%i\n", AI_FrameCount, aip->path_cur-aip->path_start, aip->path_length));
4412 maybe_recreate_path(Pl_objp, aip, 0);
4414 num_points = aip->path_length;
4416 // Set cvp and nvp as pointers to current and next vertices of interest on path.
4417 cvp = &Path_points[aip->path_cur].pos;
4418 if ((aip->path_cur + aip->path_dir - aip->path_start < num_points) || (aip->path_cur + aip->path_dir < aip->path_start))
4419 nvp = &Path_points[aip->path_cur + aip->path_dir].pos;
4421 // If this is 0, then path length must be 1 which means we have no direction!
4422 SDL_assert((aip->path_cur - aip->path_dir >= aip->path_start) && (aip->path_cur - aip->path_dir - aip->path_start < num_points));
4423 // Cleanup for above SDL_assert() which we hit too near release. -- MK, 5/24/98.
4424 if (aip->path_cur - aip->path_dir - aip->path_start >= num_points) {
4425 if (aip->path_dir == 1)
4426 aip->path_cur = aip->path_start;
4428 aip->path_cur = aip->path_start + num_points - 1;
4432 vm_vec_sub(&delvec, cvp, &Path_points[aip->path_cur - aip->path_dir].pos);
4433 vm_vec_normalize(&delvec);
4434 vm_vec_scale_add(&next_vec, cvp, &delvec, 10.0f);
4438 // Interrupt if can't get to current goal point. Debug only.
4439 /* if (pp_collide(&Pl_objp->pos, cvp, gobjp, Pl_objp->radius)) {
4443 // See if can reach next point (as opposed to current point)
4444 // However, don't do this if docking and next point is last point.
4445 // That is, we don't want to pursue the last point under control of the
4446 // path code. In docking, this is a special hack.
4447 if ((aip->mode != AIM_DOCK) || ((aip->path_cur-aip->path_start) < num_points - 2)) {
4448 if ((aip->path_cur + aip->path_dir > aip->path_start) && (aip->path_cur + aip->path_dir < aip->path_start + num_points-2)) {
4449 if ( timestamp_elapsed(aip->path_next_check_time)) {
4450 aip->path_next_check_time = timestamp( 3000 );
4451 if (!pp_collide(&Pl_objp->pos, nvp, gobjp, 1.1f * Pl_objp->radius)) {
4453 aip->path_cur += aip->path_dir;
4454 nvp = &Path_points[aip->path_cur].pos;
4455 //nprintf(("AI", "Reach: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4464 dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &gcvp);
4465 dist_to_next = vm_vec_dist_quick(&Pl_objp->pos, &gnvp);
4466 // Can't use fvec, need to use velocity vector because we aren't necessarily
4467 // moving in the direction we're facing.
4469 // if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4470 if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4472 vm_vec_zero(&nvel_vec);
4474 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4476 // If moving not-very-slowly and sliding, then try to slide at goal, rather than
4480 nvel_vec = Pl_objp->orient.v.fvec;
4481 else if (mag > 5.0f) {
4483 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4484 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4485 slop_vec = &temp_vec;
4486 vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4490 if (dist_to_goal > 0.1f)
4491 ai_turn_towards_vector(&gcvp, Pl_objp, flFrametime, sip->srotation_time, slop_vec, NULL, 0.0f, 0);
4493 // Code to control speed is MUCH less forgiving in path following than in waypoint
4494 // following. Must be very close to path or might hit objects.
4495 // prev_dot_to_goal = aip->prev_dot_to_goal;
4496 dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gcvp);
4497 dot_to_next = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gnvp);
4499 set_accel_for_docking(Pl_objp, aip, dot, dot_to_next, dist_to_next, dist_to_goal, sip);
4500 aip->prev_dot_to_goal = dot;
4502 //mprintf(("Goal index = %i, dist = %7.3f, dot = %7.3f\n", wp_index, dist_to_goal, dot));
4504 // If moving at a non-tiny velocity, detect attaining path point by its being close to
4505 // line between previous and current object location.
4506 if ((dist_to_goal < MIN_DIST_TO_WAYPOINT_GOAL) || (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f)) {
4507 vector nearest_point;
4508 float r, min_dist_to_goal;
4510 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, &gcvp);
4512 // Set min_dist_to_goal = how close must be to waypoint to pick next one.
4513 // If docking and this is the second last waypoint, must be very close.
4514 if ((aip->mode == AIM_DOCK) && (aip->path_cur >= aip->path_length-2))
4515 min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL;
4517 min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius;
4519 if ( (vm_vec_dist_quick(&Pl_objp->pos, &gcvp) < min_dist_to_goal) ||
4520 (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, &gcvp) < (MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius)))) {
4521 aip->path_cur += aip->path_dir;
4522 //nprintf(("AI", " Near: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4523 if (((aip->path_cur - aip->path_start) > (num_points+1)) || (aip->path_cur < aip->path_start)) {
4524 SDL_assert(aip->mode != AIM_DOCK); // If docking, should never get this far, getting to last point handled outside ai_path()
4525 aip->path_dir = -aip->path_dir;
4526 // aip->path_cur += aip->path_dir;
4531 return dist_to_goal;
4534 void update_min_max(float val, float *min, float *max)
4538 else if (val > *max)
4542 // Stuff bounding box of all enemy objects within "range" units of object *my_objp.
4543 // Stuff ni min_vec and max_vec.
4544 // Return value: Number of enemy objects in bounding box.
4545 int get_enemy_team_range(object *my_objp, float range, int enemy_team_mask, vector *min_vec, vector *max_vec)
4551 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
4552 objp = &Objects[so->objnum];
4553 if (Ships[objp->instance].team & enemy_team_mask) {
4554 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER | SIF_CRUISER | SIF_CAPITAL | SIF_SUPERCAP | SIF_DRYDOCK | SIF_CORVETTE | SIF_AWACS | SIF_GAS_MINER))
4555 if (vm_vec_dist_quick(&my_objp->pos, &objp->pos) < range) {
4557 *min_vec = objp->pos;
4558 *max_vec = objp->pos;
4561 update_min_max(objp->pos.xyz.x, &min_vec->xyz.x, &max_vec->xyz.x);
4562 update_min_max(objp->pos.xyz.y, &min_vec->xyz.y, &max_vec->xyz.y);
4563 update_min_max(objp->pos.xyz.z, &min_vec->xyz.z, &max_vec->xyz.z);
4573 // Pick a relatively safe spot for objp to fly to.
4575 // Finds a spot away from any enemy within a bounding box.
4576 // Doesn't verify that "safe spot" is not near some other enemy.
4577 void ai_safety_pick_spot(object *objp)
4580 int enemy_team_mask;
4581 vector min_vec, max_vec;
4582 vector vec_to_center, center;
4585 objnum = OBJ_INDEX(objp);
4587 enemy_team_mask = get_enemy_team_mask(objnum);
4589 if (get_enemy_team_range(objp, 1000.0f, enemy_team_mask, &min_vec, &max_vec)) {
4590 vm_vec_avg(¢er, &min_vec, &max_vec);
4591 vm_vec_normalized_dir(&vec_to_center, ¢er, &objp->pos);
4593 vm_vec_scale_add(&goal_pos, ¢er, &vec_to_center, 2000.0f);
4595 vm_vec_scale_add(&goal_pos, &objp->pos, &objp->orient.v.fvec, 100.0f);
4597 Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pos;
4600 // Fly to desired safe point.
4601 // Returns distance to that point.
4602 float ai_safety_goto_spot(object *objp)
4610 sip = &Ship_info[Ships[objp->instance].ship_info_index];
4612 aip = &Ai_info[Ships[objp->instance].ai_index];
4613 dist = vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
4614 dot = vm_vec_dot(&vec_to_goal, &objp->orient.v.fvec);
4616 dot_val = (1.1f + dot) / 2.0f;
4617 if (dist > 200.0f) {
4618 set_accel_for_target_speed(objp, sip->max_speed * dot_val);
4620 set_accel_for_target_speed(objp, sip->max_speed * dot_val * (dist/200.0f + 0.2f));
4625 void ai_safety_circle_spot(object *objp)
4631 sip = &Ship_info[Ships[objp->instance].ship_info_index];
4633 goal_point = Ai_info[Ships[objp->instance].ai_index].goal_point;
4634 dot = turn_towards_tangent(objp, &goal_point, 250.0f); // Increased from 50 to 250 to make circling not look so wacky.
4636 set_accel_for_target_speed(objp, 0.5f * (1.0f + dot) * sip->max_speed/4.0f);
4638 // float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
4639 // nprintf(("AI", "Ship %s circling %7.3f %7.3f %7.3f. Distance = %7.3f\n", Ships[Pl_objp->instance].ship_name, goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z, dist));
4643 // --------------------------------------------------------------------------
4648 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4650 switch (aip->submode) {
4652 ai_safety_pick_spot(Pl_objp);
4653 aip->submode = AISS_2;
4654 aip->submode_start_time = Missiontime;
4656 case AISS_1a: // Pick a safe point because we just got whacked!
4660 if (ai_safety_goto_spot(Pl_objp) < 25.0f) {
4661 aip->submode = AISS_3;
4662 aip->submode_start_time = Missiontime;
4666 ai_safety_circle_spot(Pl_objp);
4669 Int3(); // Illegal submode for ai_safety();
4674 // --------------------------------------------------------------------------
4675 // make Pl_objp fly waypoints.
4679 vector *wp_cur, *wp_next;
4680 float dot, dist_to_goal;//, dot_to_next;
4681 ship *shipp = &Ships[Pl_objp->instance];
4682 ship_info *sip = &Ship_info[shipp->ship_info_index];
4687 float prev_dot_to_goal;
4691 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4693 wp_index = aip->wp_index;
4695 if (wp_index == -1) {
4696 ai_start_waypoints(Pl_objp, 0, WPF_REPEAT);
4697 wp_index = aip->wp_index;
4701 wpl = &Waypoint_lists[Ai_info[Ships[Pl_objp->instance].ai_index].wp_list];
4703 SDL_assert(wpl->count); // What? Is this zero? Probably wp_index never got initialized!
4705 wp_cur = &wpl->waypoints[wp_index];
4706 wp_next = &wpl->waypoints[(wp_index+1) % wpl->count];
4708 dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, wp_cur);
4710 // Can't use fvec, need to use velocity vector because we aren't necessarily
4711 // moving in the direction we're facing.
4712 // AL 23-3-98: Account for very small velocities by checking result of vm_vec_mag().
4713 // If we don't vm_vec_copy_normalize() will think it is normalizing a null vector.
4714 // if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4715 if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4717 vm_vec_zero(&nvel_vec);
4719 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4722 // If moving not-very-slowly and sliding, then try to slide at goal, rather than
4726 nvel_vec = Pl_objp->orient.v.fvec;
4727 } else if (mag > 5.0f) {
4729 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4730 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4731 slop_vec = &temp_vec;
4732 vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4736 // If a wing leader, take turns more slowly, based on size of wing.
4739 if (Ai_info[Ships[Pl_objp->instance].ai_index].wing >= 0) {
4740 scale = Wings[Ai_info[Ships[Pl_objp->instance].ai_index].wing].current_count;
4741 scale = (int) ((scale+1)/2);
4746 if (dist_to_goal > 0.1f) {
4747 ai_turn_towards_vector(wp_cur, Pl_objp, flFrametime, sip->srotation_time*3.0f*scale, slop_vec, NULL, 0.0f, 0);
4750 prev_dot_to_goal = aip->prev_dot_to_goal;
4751 dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_cur);
4752 /*dot_to_next =*/ vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_next);
4753 aip->prev_dot_to_goal = dot;
4755 // If there is no next point on the path, don't care about dot to next.
4756 // if (wp_index + 1 >= wpl->count) {
4757 // dot_to_next = dot;
4760 // nprintf(("AI", "Wp #%i, dot = %6.3f, next dot = %6.3f, dist = %7.2f\n", wp_index, dot, dot_to_next, dist_to_goal));
4762 if (Pl_objp->phys_info.speed < 0.0f) {
4763 accelerate_ship(aip, 1.0f/32);
4764 } else if (prev_dot_to_goal > dot+0.01f) {
4765 // We are further from pointing at our goal this frame than last frame, so slow down.
4766 set_accel_for_target_speed(Pl_objp, Pl_objp->phys_info.speed * 0.95f);
4767 } else if (dist_to_goal < 100.0f) {
4768 float slew_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4769 if (fl_abs(slew_dot) < 0.9f) {
4770 accelerate_ship(aip, 0.0f);
4771 } else if (dot < 0.88f + 0.1f*(100.0f - dist_to_goal)/100.0f) {
4772 accelerate_ship(aip, 0.0f);
4774 accelerate_ship(aip, 0.5f * dot * dot);
4778 if (dist_to_goal < 250.0f) {
4779 dot1 = dot*dot*dot; // Very important to be pointing towards goal when nearby. Note, cubing preserves sign.
4788 if (dist_to_goal > 100.0f + Pl_objp->radius * 2) {
4794 if (sip->flags & SIF_SMALL_SHIP) {
4795 set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/5.0f);
4797 set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/10.0f);
4801 // Make sure not travelling too fast for someone to keep up.
4802 float max_allowed_speed = 9999.9f;
4804 if (shipp->wingnum != -1) {
4805 max_allowed_speed = 0.9f * get_wing_lowest_max_speed(Pl_objp);
4808 // check if waypoint speed cap is set and adjust max speed
4809 if (aip->waypoint_speed_cap > 0) {
4810 max_allowed_speed = (float) aip->waypoint_speed_cap;
4813 if (aip->prev_accel * shipp->current_max_speed > max_allowed_speed) {
4814 accelerate_ship(aip, max_allowed_speed / shipp->current_max_speed);
4817 if (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f) {
4818 vector nearest_point;
4821 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, wp_cur);
4823 if ( (vm_vec_dist_quick(&Pl_objp->pos, wp_cur) < (MIN_DIST_TO_WAYPOINT_GOAL + fl_sqrt(Pl_objp->radius) + vm_vec_dist_quick(&Pl_objp->pos, &Pl_objp->last_pos))) ||
4824 (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, wp_cur) < (MIN_DIST_TO_WAYPOINT_GOAL + fl_sqrt(Pl_objp->radius))))) {
4826 if (wp_index >= wpl->count) {
4827 if (aip->wp_flags & WPF_REPEAT) {
4832 // when not repeating waypoints -- mark the goal as done and put and entry into the mission log
4833 // we must be careful when dealing with wings. A ship in a wing might be completing
4834 // a waypoint for for the entire wing, or it might be completing a goal for itself. If
4835 // for itself and in a wing, treat the completion as we would a ship
4837 if ( Ships[Pl_objp->instance].wingnum != -1 ) {
4840 // I don't think that you can fly waypoints as dynamic goals!!!
4841 // -- This is legal, just stupid. -- SDL_assert( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) );
4843 // Clean up from above SDL_assert, just in case we ship without fixing it. (Encountered by JimB on 2/9/98)
4844 if ( (aip->active_goal == AI_GOAL_NONE) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC) ) {
4845 aip->mode = AIM_NONE;
4846 Int3(); // Look at the ship, find out of it's supposed to be flying waypoints. -- MK.
4849 type = aip->goals[aip->active_goal].type;
4850 if ( (type == AIG_TYPE_EVENT_WING) || (type == AIG_TYPE_PLAYER_WING) ) {
4857 // if the ship is not in a wing, remove the goal and continue on
4858 if ( treat_as_ship ) {
4859 ai_mission_goal_complete( aip ); // this call should reset the AI mode
4860 mission_log_add_entry(LOG_WAYPOINTS_DONE, Ships[Pl_objp->instance].ship_name, wpl->name, -1 );
4862 // this ship is in a wing. We must mark the goal as being completed for all ships
4863 // in the wing. We will also mark an entry in the log that the wing completed the goal
4864 // not the individual ship.
4865 ai_mission_wing_goal_complete( Ships[Pl_objp->instance].wingnum, &(aip->goals[aip->active_goal]) );
4866 mission_log_add_entry( LOG_WAYPOINTS_DONE, Wings[Ships[Pl_objp->instance].wingnum].name, wpl->name, -1 );
4868 //wp_index = wpl->count-1;
4872 aip->wp_index = wp_index;
4877 // Make Pl_objp avoid En_objp
4878 // Not like evading. This is for avoiding a collision!
4879 // Note, use sliding if available.
4882 // To avoid an object, turn towards right or left vector until facing away from object.
4883 // To choose right vs. left, pick one that is further from center of avoid object.
4884 // Keep turning away from until pointing away from ship.
4885 // Stay in avoid mode until at least 3 enemy ship radii away.
4888 // If inside sphere, zero speed and turn towards outside.
4889 // If outside sphere, inside 2x sphere, set speed percent of max to:
4890 // SDL_max(away_dot, (dist-rad)/rad)
4891 // where away_dot is dot(Pl_objp->v.fvec, vec_En_objp_to_Pl_objp)
4893 vector vec_to_enemy;
4896 ship *shipp = &Ships[Pl_objp->instance];
4897 ship_info *sip = &Ship_info[shipp->ship_info_index];
4898 ai_info *aip = &Ai_info[shipp->ai_index];
4899 vector player_pos, enemy_pos;
4901 // if we're avoiding a stealth ship, then we know where he is, update with no error
4902 if ( is_object_stealth_ship(En_objp) ) {
4903 update_ai_stealth_info_with_error(aip/*, 1*/);
4906 ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
4907 vm_vec_sub(&vec_to_enemy, &enemy_pos, &Pl_objp->pos);
4909 dist = vm_vec_normalize(&vec_to_enemy);
4910 away_dot = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
4912 if ((sip->max_vel.xyz.x > 0.0f) || (sip->max_vel.xyz.y > 0.0f)) {
4913 if (vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_to_enemy) > 0.0f) {
4914 AI_ci.sideways = -1.0f;
4916 AI_ci.sideways = 1.0f;
4918 if (vm_vec_dot(&Pl_objp->orient.v.uvec, &vec_to_enemy) > 0.0f) {
4919 AI_ci.vertical = -1.0f;
4921 AI_ci.vertical = 1.0f;
4925 //nprintf(("AI", "Frame %i: Sliding: %s %s\n", Framecount, AI_ci.sideways < 0 ? "left" : "right", AI_ci.vertical < 0 ? "down" : "up" ));
4926 // nprintf(("AI", "away_dot = %6.3f, dist = %7.2f, dist/radsum = %6.3f\n", away_dot, dist, dist/(Pl_objp->radius + En_objp->radius)));
4928 // If in front of enemy, turn away from it.
4929 // If behind enemy, try to get fully behind it.
4930 if (away_dot < 0.0f) {
4931 turn_away_from_point(Pl_objp, &enemy_pos, Pl_objp->phys_info.speed);
4935 vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);
4936 turn_towards_point(Pl_objp, &goal_pos, NULL, Pl_objp->phys_info.speed);
4940 float radsum = Pl_objp->radius + En_objp->radius;
4943 accelerate_ship(aip, SDL_max(away_dot, 0.2f));
4944 else if (dist < 2*radsum)
4945 accelerate_ship(aip, SDL_max(away_dot, (dist - radsum) / radsum)+0.2f);
4947 accelerate_ship(aip, 1.0f);
4951 // Maybe it's time to resume the previous AI mode in aip->previous_mode.
4952 // Each type of previous_mode has its own criteria on when to resume.
4953 // Return true if previous mode was resumed.
4954 int maybe_resume_previous_mode(object *objp, ai_info *aip)
4956 // Only (maybe) resume previous goal if current goal is dynamic.
4957 if (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC)
4960 if (aip->mode == AIM_EVADE_WEAPON) {
4961 if (timestamp_elapsed(aip->mode_time) || (((aip->nearest_locked_object == -1) || (Objects[aip->nearest_locked_object].type != OBJ_WEAPON)) && (aip->danger_weapon_objnum == -1))) {
4962 SDL_assert(aip->previous_mode != AIM_EVADE_WEAPON);
4963 aip->mode = aip->previous_mode;
4964 aip->submode = aip->previous_submode;
4965 aip->submode_start_time = Missiontime;
4966 aip->active_goal = AI_GOAL_NONE;
4967 aip->mode_time = -1; // Means do forever.
4970 } else if ( aip->previous_mode == AIM_GUARD) {
4971 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
4975 guard_objp = &Objects[aip->guard_objnum];
4976 dist = vm_vec_dist_quick(&guard_objp->pos, &objp->pos);
4978 // If guarding ship is far away from guardee and enemy is far away from guardee,
4979 // then stop chasing and resume guarding.
4980 if (dist > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4981 if ((En_objp != NULL) && (En_objp->type == OBJ_SHIP)) {
4982 if (vm_vec_dist_quick(&guard_objp->pos, &En_objp->pos) > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4983 SDL_assert(aip->previous_mode == AIM_GUARD);
4984 aip->mode = aip->previous_mode;
4985 aip->submode = AIS_GUARD_PATROL;
4986 aip->active_goal = AI_GOAL_NONE;
4998 // Call this function if you want something to happen on average every N quarters of a second.
4999 // The truth value returned by this function will be the same for any given quarter second interval.
5000 // The value "num" is only passed in to get asynchronous behavior for different objects.
5001 // modulus == 1 will always return true.
5002 // modulus == 2 will return true half the time.
5003 // modulus == 16 will return true for one quarter second interval every four seconds.
5004 int static_rand_timed(int num, int modulus)
5011 t = Missiontime >> 18; // Get time in quarters of a second
5014 return !(t % modulus);
5018 // Maybe fire afterburner based on AI class
5019 int ai_maybe_fire_afterburner(object *objp, ai_info *aip)
5021 if (aip->ai_class == 0)
5022 return 0; // Lowest level never aburners away
5024 // Maybe don't afterburner because of a potential collision with the player.
5025 // If not multiplayer, near player and player in front, probably don't afterburner.
5026 if (!(Game_mode & GM_MULTIPLAYER)) {
5027 if (Ships[objp->instance].team == Player_ship->team) {
5030 dist = vm_vec_dist_quick(&objp->pos, &Player_obj->pos) - Player_obj->radius - objp->radius;
5031 if (dist < 150.0f) {
5035 vm_vec_normalized_dir(&v2p, &Player_obj->pos, &objp->pos);
5036 dot = vm_vec_dot(&v2p, &objp->orient.v.fvec);
5039 if (dot * dist > 50.0f)
5046 if (aip->ai_class >= Num_ai_classes-2)
5047 return 1; // Highest two levels always aburner away.
5049 return static_rand_timed(objp-Objects, Num_ai_classes - aip->ai_class);
5054 // Maybe engage afterburner after being hit by an object.
5055 void maybe_afterburner_after_ship_hit(object *objp, ai_info *aip, object *en_objp)
5057 // Only do if facing a little away.
5058 if (en_objp != NULL) {
5061 vm_vec_normalized_dir(&v2e, &en_objp->pos, &objp->pos);
5062 if (vm_vec_dot(&v2e, &objp->orient.v.fvec) > -0.5f)
5066 if (!( objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5067 if (ai_maybe_fire_afterburner(objp, aip)) {
5068 afterburners_start(objp);
5069 aip->afterburner_stop_time = Missiontime + F1_0/2;
5074 // Return true if object *objp is an instructor.
5075 // Is an instructor if name begins INSTRUCTOR_SHIP_NAME else not.
5076 int is_instructor(object *objp)
5078 return !SDL_strncasecmp(Ships[objp->instance].ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME));
5081 // Evade the weapon aip->danger_weapon_objnum
5082 // If it's not valid, do a quick out.
5083 // Evade by accelerating hard.
5084 // If necessary, turn hard left or hard right.
5087 object *weapon_objp = NULL;
5088 object *unlocked_weapon_objp = NULL, *locked_weapon_objp = NULL;
5089 vector weapon_pos, player_pos, goal_point;
5090 vector vec_from_enemy;
5091 float dot_from_enemy, dot_to_enemy;
5093 ship *shipp = &Ships[Pl_objp->instance];
5094 ai_info *aip = &Ai_info[shipp->ai_index];
5096 if (is_instructor(Pl_objp))
5099 // Make sure we're actually being attacked.
5100 // Favor locked objects.
5101 if (aip->nearest_locked_object != -1) {
5102 if (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)
5103 locked_weapon_objp = &Objects[aip->nearest_locked_object];
5106 if (aip->danger_weapon_objnum != -1) {
5107 if (Objects[aip->danger_weapon_objnum].signature == aip->danger_weapon_signature) {
5108 unlocked_weapon_objp = &Objects[aip->danger_weapon_objnum];
5110 aip->danger_weapon_objnum = -1; // Signatures don't match, so no longer endangered.
5114 if (locked_weapon_objp != NULL) {
5115 if (unlocked_weapon_objp != NULL) {
5116 if (vm_vec_dist_quick(&locked_weapon_objp->pos, &Pl_objp->pos) < 1.5f * vm_vec_dist_quick(&unlocked_weapon_objp->pos, &Pl_objp->pos))
5117 weapon_objp = locked_weapon_objp;
5119 weapon_objp = unlocked_weapon_objp;
5121 weapon_objp = locked_weapon_objp;
5122 } else if (unlocked_weapon_objp != NULL)
5123 weapon_objp = unlocked_weapon_objp;
5125 if (aip->mode == AIM_EVADE_WEAPON)
5126 maybe_resume_previous_mode(Pl_objp, aip);
5130 SDL_assert(weapon_objp != NULL);
5132 if (weapon_objp->type != OBJ_WEAPON) {
5133 if (aip->mode == AIM_EVADE_WEAPON)
5134 maybe_resume_previous_mode(Pl_objp, aip);
5138 weapon_pos = weapon_objp->pos;
5139 player_pos = Pl_objp->pos;
5141 // Make speed based on skill level, varying at highest skill level, which is harder to hit.
5142 accelerate_ship(aip, 1.0f);
5144 dist = vm_vec_normalized_dir(&vec_from_enemy, &player_pos, &weapon_pos);
5146 dot_to_enemy = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_from_enemy);
5147 dot_from_enemy = vm_vec_dot(&weapon_objp->orient.v.fvec, &vec_from_enemy);
5148 //nprintf(("AI", "dot from enemy = %7.3f\n", dot_from_enemy));
5150 // If shot is incoming...
5151 if (dot_from_enemy < 0.3f) {
5152 if (weapon_objp == unlocked_weapon_objp)
5153 aip->danger_weapon_objnum = -1;
5155 } else if (dot_from_enemy > 0.7f) {
5156 if (dist < 200.0f) {
5157 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5158 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
5159 //nprintf(("AI", "Frame %i, turning on afterburner.\n", AI_FrameCount));
5160 afterburners_start(Pl_objp);
5161 aip->afterburner_stop_time = Missiontime + F1_0/2;
5166 // If we're sort of pointing towards it...
5167 if ((dot_to_enemy < -0.5f) || (dot_to_enemy > 0.5f)) {
5170 // Turn hard left or right, depending on which gets out of way quicker.
5171 rdot = vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_from_enemy);
5173 if ((rdot < -0.5f) || (rdot > 0.5f))
5174 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, -200.0f);
5176 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 200.0f);
5178 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
5184 // Use sliding and backwards moving to face enemy.
5185 // (Coded 2/20/98. Works fine, but it's hard to see how to integrate it into the AI system.
5186 // Typically ships are moving so fast that a little sliding isn't enough to gain an advantage.
5187 // It's currently used to avoid collisions and could be used to evade weapon fire, but the latter
5188 // would be frustrating, I think.
5189 // This function is currently not called.)
5190 void slide_face_ship()
5194 sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
5196 // If can't slide, return.
5197 if ((sip->max_vel.xyz.x == 0.0f) && (sip->max_vel.xyz.y == 0.0f))
5201 float dot_from_enemy;
5202 vector vec_from_enemy, vec_to_goal;
5207 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
5209 dist = vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
5211 ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
5213 dot_from_enemy = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
5215 if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > 0.0f)
5220 if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.uvec) > 0.0f)
5225 vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.rvec, right * 200.0f);
5226 vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.uvec, up * 200.0f);
5228 vm_vec_normalized_dir(&vec_to_goal, &goal_pos, &Pl_objp->pos);
5230 if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.rvec) > 0.0f)
5231 AI_ci.sideways = 1.0f;
5233 AI_ci.sideways = -1.0f;
5235 if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.uvec) > 0.0f)
5236 AI_ci.vertical = 1.0f;
5238 AI_ci.vertical = -1.0f;
5240 if (dist < 200.0f) {
5241 if (dot_from_enemy < 0.7f)
5242 accelerate_ship(aip, -1.0f);
5244 accelerate_ship(aip, dot_from_enemy + 0.5f);
5246 if (dot_from_enemy < 0.7f) {
5247 accelerate_ship(aip, 0.2f);
5249 accelerate_ship(aip, 1.0f);
5254 // General code for handling one ship evading another.
5255 // Problem: This code is also used for avoiding an impending collision.
5256 // In such a case, it is not good to go to max speed, which is often good
5257 // for a certain kind of evasion.
5260 vector player_pos, enemy_pos, goal_point;
5261 vector vec_from_enemy;
5262 float dot_from_enemy;
5264 ship *shipp = &Ships[Pl_objp->instance];
5265 ship_info *sip = &Ship_info[shipp->ship_info_index];
5266 ai_info *aip = &Ai_info[shipp->ai_index];
5267 float bank_override = 0.0f;
5269 ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
5271 // Make speed based on skill level, varying at highest skill level, which is harder to hit.
5272 if (Game_skill_level == NUM_SKILL_LEVELS-1) {
5276 rand_int = static_rand(Pl_objp-Objects);
5277 accel_val = (float) (((Missiontime^rand_int) >> 14) & 0x0f)/32.0f + 0.5f;
5278 accelerate_ship(aip, accel_val);
5279 //nprintf(("AI", "Accel value = %7.3f\n", accel_val));
5281 accelerate_ship(aip, (float) (Game_skill_level+2) / (NUM_SKILL_LEVELS+1));
5283 if ((Missiontime - aip->submode_start_time > F1_0/2) && (sip->afterburner_fuel_capacity > 0.0f)) {
5284 float percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
5285 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
5286 afterburners_start(Pl_objp);
5287 aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
5291 vm_vec_sub(&vec_from_enemy, &player_pos, &enemy_pos);
5293 dist = vm_vec_normalize(&vec_from_enemy);
5294 dot_from_enemy = vm_vec_dot(&En_objp->orient.v.fvec, &vec_from_enemy);
5296 if (dist > 250.0f) {
5298 // If far away from enemy, circle, going to nearer of point far off left or right wing
5299 vm_vec_scale_add(&gp1, &enemy_pos, &En_objp->orient.v.rvec, 250.0f);
5300 vm_vec_scale_add(&gp2, &enemy_pos, &En_objp->orient.v.rvec, -250.0f);
5301 if (vm_vec_dist_quick(&gp1, &Pl_objp->pos) < vm_vec_dist_quick(&gp2, &Pl_objp->pos))
5305 } else if (dot_from_enemy < 0.1f) {
5306 // If already close to behind, goal is to get completely behind.
5307 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.fvec, -1000.0f);
5308 } else if (dot_from_enemy > 0.9f) {
5309 // If enemy pointing almost right at self, and self pointing close to enemy, turn away from
5310 vector vec_to_enemy;
5313 vm_vec_sub(&vec_to_enemy, &enemy_pos, &player_pos);
5315 vm_vec_normalize(&vec_to_enemy);
5316 dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
5317 if (dot_to_enemy > 0.75f) {
5318 // Used to go to En_objp's right vector, but due to banking while turning, that
5319 // caused flying in an odd spiral.
5320 vm_vec_scale_add(&goal_point, &enemy_pos, &Pl_objp->orient.v.rvec, 1000.0f);
5322 bank_override = Pl_objp->phys_info.speed;
5324 bank_override = Pl_objp->phys_info.speed; // In enemy's sights, not pointing at him, twirl away.
5325 // nprintf(("Mike", " Do sumpin' else."));
5330 if (aip->ai_evasion > myrand()*100.0f/32767.0f) {
5333 float psrandval; // some value close to zero to choose whether to turn right or left.
5335 psrandval = (float) (((Missiontime >> 14) & 0x0f) - 8); // Value between -8 and 7
5336 psrandval = psrandval/16.0f; // Value between -1/2 and 1/2 (approx)
5338 // If not close to behind, turn towards his right or left vector, whichever won't cross his path.
5339 if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > psrandval) {
5345 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, scale);
5347 temp = ((Missiontime >> 16) & 0x07);
5348 temp = ((temp * (temp+1)) % 16)/2 - 4;
5349 if ((psrandval == 0) && (temp == 0))
5352 scale = 200.0f * temp;
5354 vm_vec_scale_add2(&goal_point, &En_objp->orient.v.uvec, scale);
5356 // No evasion this frame, but continue with previous turn.
5357 // Reason: If you don't, you lose rotational momentum. Turning every other frame,
5358 // and not in between results in a very slow turn because of loss of momentum.
5359 if ((aip->prev_goal_point.xyz.x != 0.0f) || (aip->prev_goal_point.xyz.y != 0.0f) || (aip->prev_goal_point.xyz.z != 0.0f))
5360 goal_point = aip->prev_goal_point;
5362 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, 100.0f);
5366 // nprintf(("Mike", "Goal point = %7.1f %7.1f %7.1f\n", goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z));
5367 turn_towards_point(Pl_objp, &goal_point, NULL, bank_override);
5369 aip->prev_goal_point = goal_point;
5372 // --------------------------------------------------------------------------
5373 // Fly in a manner making it difficult for opponent to attack.
5380 // -------------------------------------------------------------------
5381 // Refine predicted enemy position because enemy will move while we move
5382 // towards predicted enemy position.
5383 // last_delta_vec is stuffed with size of polishing in last step. This small amount
5384 // can be used to perturb the predicted position to make firing not be exact.
5385 // This function will almost always undershoot actual position, assuming both ships
5386 // are moving at constant speed. But with even one polishing step, the error should
5387 // be under 1%. The number of polishing steps is specified in the parameter num_polish_steps.
5388 void polish_predicted_enemy_pos(vector *predicted_enemy_pos, object *pobjp, object *eobjp, float dist_to_enemy, vector *last_delta_vec, int num_polish_steps) // Not used:, float time_to_enemy)
5391 vector player_pos = pobjp->pos;
5392 vector enemy_pos = *predicted_enemy_pos;
5393 physics_info *en_physp = &eobjp->phys_info;
5394 float time_to_enemy;
5395 vector last_predicted_enemy_pos = *predicted_enemy_pos;
5397 vm_vec_zero(last_delta_vec);
5399 for (iteration=0; iteration < num_polish_steps; iteration++) {
5400 dist_to_enemy = vm_vec_dist_quick(predicted_enemy_pos, &player_pos);
5401 time_to_enemy = compute_time_to_enemy(dist_to_enemy, pobjp, eobjp);
5402 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, time_to_enemy);
5403 vm_vec_sub(last_delta_vec, predicted_enemy_pos, &last_predicted_enemy_pos);
5404 last_predicted_enemy_pos= *predicted_enemy_pos;
5410 Relevant variables are:
5411 best_dot_to_enemy best dot product to enemy in last BEST_DOT_TIME seconds
5412 best_dot_to_time time at which best dot occurred
5413 best_dot_from_enemy best dot product for enemy to player in last BEST_DOT_TIME seconds
5414 best_dot_from_time time at which best dot occurred
5415 submode_start_time time at which we entered the current submode
5416 previous_submode previous submode, get it?
5418 CONTINUOUS_TURN vector_id {0..3 = right, -right, up, -up}
5424 float G_collision_time;
5425 vector G_predicted_pos, G_fire_pos;
5428 void show_firing_diag()
5435 if (G_collision_time == 0.0f)
5438 mprintf(("Fired from %5.1f, %5.1f %5.1f at time = %5.1f, predict collision in %5.2f seconds at %5.1f %5.1f %5.1f\n",
5439 Pl_objp->pos.xyz.x, Pl_objp->pos.xyz.y, Pl_objp->pos.xyz.z, (float) Missiontime/1000.0f, G_collision_time, G_predicted_pos.xyz.x, G_predicted_pos.xyz.y, G_predicted_pos.xyz.z));
5440 vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5441 dot = vm_vec_dot(&v2t, &Pl_objp->orient.v.fvec);
5442 mprintf(("Dot of v.fvec and vector to predicted position = %10.7f (%7.3f degrees)\n", dot, acos(dot)*180.0f/3.141592654f));
5444 vm_vec_scale_add(&pos1, &En_objp->pos, &En_objp->phys_info.vel, G_collision_time);
5445 vm_vec_scale_add(&pos2, &G_fire_pos, &Pl_objp->orient.v.fvec, G_collision_time*300.0f);
5446 dist = vm_vec_dist(&pos1, &pos2);
5448 mprintf(("Enemy, laser pos, distance: [%5.1f %5.1f %5.1f] [%5.1f %5.1f %5.1f] %6.2f\n", pos1.xyz.x, pos1.xyz.y, pos1.xyz.z, pos2.xyz.x, pos2.xyz.y, pos2.xyz.z, dist));
5453 // flags & WIF_PUNCTURE
5454 // Then Select a Puncture weapon.
5456 // Select Any ol' weapon.
5457 // Returns primary_bank index.
5458 int ai_select_primary_weapon(object *objp, object *other_objp, int flags)
5460 ship *shipp = &Ships[objp->instance];
5461 ship_weapon *swp = &shipp->weapons;
5463 //SDL_assert( other_objp != NULL );
5464 SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5466 if (flags & WIF_PUNCTURE) {
5467 if (swp->current_primary_bank >= 0) {
5470 bank_index = swp->current_primary_bank;
5472 if (Weapon_info[swp->primary_bank_weapons[bank_index]].wi_flags & WIF_PUNCTURE) {
5473 //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[bank_index]].name));
5474 return swp->current_primary_bank;
5477 for (int i=0; i<swp->num_primary_banks; i++) {
5478 int weapon_info_index;
5480 weapon_info_index = swp->primary_bank_weapons[i];
5482 if (weapon_info_index > -1){
5483 if (Weapon_info[weapon_info_index].wi_flags & WIF_PUNCTURE) {
5484 swp->current_primary_bank = i;
5485 //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5491 // AL 26-3-98: If we couldn't find a puncture weapon, pick first available weapon if one isn't active
5492 if ( swp->current_primary_bank < 0 ) {
5493 if ( swp->num_primary_banks > 0 ) {
5494 swp->current_primary_bank = 0;
5498 } else { // Don't need to be using a puncture weapon.
5499 if (swp->current_primary_bank >= 0) {
5500 if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)){
5501 return swp->current_primary_bank;
5504 for (int i=0; i<swp->num_primary_banks; i++) {
5505 if (swp->primary_bank_weapons[i] > -1) {
5506 if (!(Weapon_info[swp->primary_bank_weapons[i]].wi_flags & WIF_PUNCTURE)) {
5507 swp->current_primary_bank = i;
5508 nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5513 // Wasn't able to find a non-puncture weapon. Stick with what we have.
5516 SDL_assert( swp->current_primary_bank != -1 ); // get Alan or Allender
5518 return swp->current_primary_bank;
5521 // --------------------------------------------------------------------------
5522 // Maybe link primary weapons.
5523 void set_primary_weapon_linkage(object *objp)
5528 shipp = &Ships[objp->instance];
5529 aip = &Ai_info[shipp->ai_index];
5531 shipp->flags &= ~SF_PRIMARY_LINKED;
5533 if (Num_weapons > (int) (MAX_WEAPONS * 0.75f)) {
5534 if (shipp->flags & SF_PRIMARY_LINKED) {
5535 nprintf(("AI", "Frame %i, ship %s: Unlinking primaries.\n", Framecount, shipp->ship_name));
5537 shipp->flags &= ~SF_PRIMARY_LINKED;
5538 return; // If low on slots, don't link.
5541 shipp->flags &= ~SF_PRIMARY_LINKED;
5543 // AL: ensure target is a ship!
5544 if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
5545 // If trying to destroy a big ship (i.e., not disable/disarm), always unleash all weapons
5546 if ( ship_get_SIF(&Ships[Objects[aip->target_objnum].instance]) & SIF_BIG_SHIP) {
5547 if ( aip->targeted_subsys == NULL ) {
5548 shipp->flags |= SF_PRIMARY_LINKED;
5549 shipp->flags |= SF_SECONDARY_DUAL_FIRE;
5555 // AL 2-11-98: If ship has a disarm or disable goal, don't link unless both weapons are
5557 if ( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) ) {
5558 if ( aip->goals[aip->active_goal].ai_mode & (AI_GOAL_DISABLE_SHIP|AI_GOAL_DISARM_SHIP) ) {
5560 swp = &shipp->weapons;
5561 // only continue if both primaries are puncture weapons
5562 if ( swp->num_primary_banks == 2 ) {
5563 if ( !(Weapon_info[swp->primary_bank_weapons[0]].wi_flags & WIF_PUNCTURE) )
5565 if ( !(Weapon_info[swp->primary_bank_weapons[1]].wi_flags & WIF_PUNCTURE) )
5571 // Don't want all ships always linking weapons at start, so asynchronize.
5572 if (Missiontime < i2f(30))
5574 else if (Missiontime < i2f(120)) {
5575 int r = static_rand((Missiontime >> 17) ^ OBJ_INDEX(objp));
5580 if (shipp->weapon_energy > Link_energy_levels_always[Game_skill_level]) {
5581 shipp->flags |= SF_PRIMARY_LINKED;
5582 } else if (shipp->weapon_energy > Link_energy_levels_maybe[Game_skill_level]) {
5583 if (objp->hull_strength < Ship_info[shipp->ship_info_index].initial_hull_strength/3.0f)
5584 shipp->flags |= SF_PRIMARY_LINKED;
5588 // --------------------------------------------------------------------------
5589 // Fire the current primary weapon.
5590 // *objp is the object to fire from.
5591 void ai_fire_primary_weapon(object *objp)
5593 ship *shipp = &Ships[objp->instance];
5594 ship_weapon *swp = &shipp->weapons;
5598 SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5600 aip = &Ai_info[shipp->ai_index];
5602 // If low on slots, fire a little less often.
5603 if (Num_weapons > (int) (0.9f * MAX_WEAPONS)) {
5604 if (frand() > 0.5f) {
5605 nprintf(("AI", "Frame %i, %s not fire.\n", Framecount, shipp->ship_name));
5610 if (!Ai_firing_enabled){
5614 if (aip->target_objnum != -1){
5615 enemy_objp = &Objects[aip->target_objnum];
5620 if ( (swp->current_primary_bank < 0) || (swp->current_primary_bank >= swp->num_primary_banks) || timestamp_elapsed(aip->primary_select_timestamp)) {
5622 // AL 2-11-98: If attacking any subsystem (not just engines), use disrupter weapon
5623 // if ((aip->targeted_subsys != NULL) && (aip->targeted_subsys->system_info->type == SUBSYSTEM_ENGINE)) {
5624 if ( aip->targeted_subsys != NULL ) {
5625 flags = WIF_PUNCTURE;
5627 ai_select_primary_weapon(objp, enemy_objp, flags);
5628 ship_primary_changed(shipp); // AL: maybe send multiplayer information when AI ship changes primaries
5629 aip->primary_select_timestamp = timestamp(5 * 1000); // Maybe change primary weapon five seconds from now.
5632 // If pointing nearly at predicted collision point of target, bash orientation to be perfectly pointing.
5636 // if (!IS_VEC_NULL(&G_predicted_pos)) {
5637 if (!( vm_vec_mag_quick(&G_predicted_pos) < AICODE_SMALL_MAGNITUDE )) {
5638 if ( !vm_vec_cmp(&G_predicted_pos, &G_fire_pos) ) {
5639 nprintf(("Warning", "Avoid NULL vector assert.. why are G_predicted_pos and G_fire_pos the same?\n"));
5641 vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5642 dot = vm_vec_dot(&v2t, &objp->orient.v.fvec);
5643 if (dot > .998629534f){ // if within 3.0 degrees of desired heading, bash
5644 vm_vector_2_matrix(&objp->orient, &v2t, &objp->orient.v.uvec, NULL);
5649 // Make sure not firing at a protected ship unless firing at a live subsystem.
5650 // Note: This happens every time the ship tries to fire, perhaps every frame.
5651 // Should be wrapped in a timestamp, same one that enables it to fire, but that is complicated
5652 // by multiple banks it can fire from.
5653 if (aip->target_objnum != -1) {
5654 object *tobjp = &Objects[aip->target_objnum];
5655 if (tobjp->flags & OF_PROTECTED) {
5656 if (aip->targeted_subsys != NULL) {
5659 type = aip->targeted_subsys->system_info->type;
5660 if (ship_get_subsystem_strength(&Ships[tobjp->instance], type) == 0.0f) {
5661 aip->target_objnum = -1;
5665 aip->target_objnum = -1;
5671 // If enemy is protected, not firing a puncture weapon and enemy's hull is low, don't fire.
5672 if ((enemy_objp != NULL) && (enemy_objp->flags & OF_PROTECTED)) {
5673 // AL: 3-6-98: Check if current_primary_bank is valid
5674 if ((enemy_objp->hull_strength < 750.0f) &&
5675 ((aip->targeted_subsys == NULL) || (enemy_objp->hull_strength < aip->targeted_subsys->current_hits + 50.0f)) &&
5676 (swp->current_primary_bank >= 0) ) {
5677 if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)) {
5678 //nprintf(("AI", "Ship %s not firing at protected ship %s because not using disruptor.\n", Ships[objp->instance].ship_name, Ships[enemy_objp->instance].ship_name));
5679 swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(1000);
5685 num_attacking = num_enemies_attacking(enemy_objp-Objects);
5686 if (enemy_objp->hull_strength / num_attacking < 200.0f) {
5687 if (frand() < 0.75f) {
5688 nprintf(("AI", "Ship %s not firing at protected ship %s because too many attacking.\n", Ships[objp->instance].ship_name, Ships[enemy_objp->instance].ship_name));
5689 swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(500);
5697 set_primary_weapon_linkage(objp);
5699 // I think this will properly solve the problem
5700 // fire non-streaming weapons
5701 ship_fire_primary(objp, 0);
5703 // fire streaming weapons
5704 shipp->flags |= SF_TRIGGER_DOWN;
5705 ship_fire_primary(objp, 1);
5706 shipp->flags &= ~SF_TRIGGER_DOWN;
5709 // --------------------------------------------------------------------------
5710 // Return number of nearby enemy fighters.
5711 // threshold is the distance within which a ship is considered near.
5713 // input: enemy_team_mask => teams that are considered as an enemy
5714 // pos => world position to measure ship distances from
5715 // threshold => max distance from pos to be considered "near"
5717 // exit: number of ships within threshold units of pos
5718 int num_nearby_fighters(int enemy_team_mask, vector *pos, float threshold)
5724 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5726 ship_objp = &Objects[so->objnum];
5728 if (Ships[ship_objp->instance].team & enemy_team_mask) {
5729 if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) {
5730 if (vm_vec_dist_quick(pos, &ship_objp->pos) < threshold)
5739 // --------------------------------------------------------------------------
5740 // Select secondary weapon to fire.
5741 // Currently, 1/16/98:
5742 // If 0 secondary weapons available, return -1
5743 // If 1 available, use it.
5744 // If 2 or more, if the current weapon is one of them, stick with it, otherwise choose a random one.
5745 // priority1 and priority2 are Weapon_info[] bitmasks such as WIF_HOMING_ASPECT. If any weapon has any bit in priority1
5746 // set, that weapon will be selected. If not, apply to priority2. If neither, return -1, meaning no weapon selected.
5747 // Note, priorityX have default values of -1, meaning if not set, they will match any weapon.
5751 // Favor aspect seekers when attacking small ships faraway.
5752 // Favor rapid fire dumbfire when attacking a large ship.
5753 // Ignore heat seekers because we're not sure how they'll work.
5754 void ai_select_secondary_weapon(object *objp, ship_weapon *swp, int priority1 = -1, int priority2 = -1)
5756 int num_weapon_types;
5757 int weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
5762 initial_bank = swp->current_secondary_bank;
5764 // Ignore bombs unless one of the priorities asks for them to be selected.
5765 if (WIF_HUGE & (priority1 | priority2))
5768 ignore_mask = WIF_HUGE;
5770 if (!(WIF_BOMBER_PLUS & (priority1 | priority2)))
5771 ignore_mask |= WIF_BOMBER_PLUS;
5774 for (i=0; i<MAX_WEAPON_TYPES; i++) {
5775 weapon_id_list[i] = -1;
5776 weapon_bank_list[i] = -1;
5780 // Stuff weapon_bank_list with bank index of available weapons.
5781 num_weapon_types = get_available_secondary_weapons(objp, weapon_id_list, weapon_bank_list);
5783 int priority2_index = -1;
5785 for (i=0; i<num_weapon_types; i++) {
5788 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5789 if (!(wi_flags & ignore_mask)) { // Maybe bombs are illegal.
5790 if (wi_flags & priority1) {
5791 swp->current_secondary_bank = weapon_bank_list[i]; // Found first priority, return it.
5793 } else if (wi_flags & priority2)
5794 priority2_index = weapon_bank_list[i]; // Found second priority, but might still find first priority.
5798 // If didn't find anything above, then pick any secondary weapon.
5799 if (i == num_weapon_types) {
5800 swp->current_secondary_bank = priority2_index; // Assume we won't find anything.
5801 if (priority2_index == -1) {
5802 for (i=0; i<num_weapon_types; i++) {
5805 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5806 if (!(wi_flags & ignore_mask)) { // Maybe bombs are illegal.
5807 if (swp->secondary_bank_ammo[i] > 0) {
5808 swp->current_secondary_bank = i;
5816 // If switched banks, force reacquisition of aspect lock.
5817 if (swp->current_secondary_bank != initial_bank) {
5818 ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
5820 aip->aspect_locked_time = 0.0f;
5821 aip->current_target_is_locked = 0;
5825 ship_secondary_changed(&Ships[objp->instance]); // AL: let multiplayer know if secondary bank has changed
5826 // nprintf(("AI", "Ship %s selected weapon %s\n", Ships[objp->instance].ship_name, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
5829 // Return number of objects homing on object *target_objp
5830 int compute_num_homing_objects(object *target_objp)
5835 for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
5836 if (objp->type == OBJ_WEAPON) {
5837 if (Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_HOMING) {
5838 if (Weapons[objp->instance].homing_object == target_objp) {
5848 // Object *firing_objp just fired weapon weapon_index (index in Weapon_info).
5849 // If it's a shockwave weapon, tell your team about it!
5850 void ai_maybe_announce_shockwave_weapon(object *firing_objp, int weapon_index)
5852 if ((firing_objp->type == OBJ_SHIP) && (Weapon_info[weapon_index].shockwave_speed > 0.0f)) {
5854 int firing_ship_team;
5856 firing_ship_team = Ships[firing_objp->instance].team;
5858 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5859 object *A = &Objects[so->objnum];
5860 SDL_assert(A->type == OBJ_SHIP);
5862 if (Ships[A->instance].team == firing_ship_team) {
5863 ai_info *aip = &Ai_info[Ships[A->instance].ai_index];
5864 // AL 1-5-98: only avoid shockwave if not docked or repairing
5865 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
5866 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_WEAPON;
5873 // Return total payload of all incoming missiles.
5874 float compute_incoming_payload(object *target_objp)
5877 float payload = 0.0f;
5879 for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
5882 objp = &Objects[mo->objnum];
5883 SDL_assert(objp->type == OBJ_WEAPON);
5884 if (Weapons[objp->instance].homing_object == target_objp) {
5885 payload += Weapon_info[Weapons[objp->instance].weapon_info_index].damage;
5892 // --------------------------------------------------------------------------
5893 // Return true if OK for *aip to fire its current weapon at its current target.
5894 // Only reason this function returns false is:
5895 // weapon is a homer
5896 // targeted at player
5897 // OR: player has too many homers targeted at him
5898 // Missiontime in that dead zone in which can't fire at this player
5899 // Note: If player is attacking a ship, that ship is allowed to fire at player. Otherwise, we get in a situation in which
5900 // player is attacking a large ship, but that large ship is not defending itself with missiles.
5901 int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip)
5904 object *tobjp = &Objects[target_objnum];
5906 if (target_objnum > -1) {
5907 // AL 3-4-98: Ensure objp target is a ship first
5908 if ( tobjp->type == OBJ_SHIP ) {
5910 // should not get this far. check if ship is protected from beam and weapon is type beam
5911 if ( (wip->wi_flags & WIF_BEAM) && (tobjp->flags & OF_BEAM_PROTECTED) ) {
5915 if (Ship_info[Ships[tobjp->instance].ship_info_index].flags & SIF_SMALL_SHIP) {
5916 num_homers = compute_num_homing_objects(&Objects[target_objnum]);
5920 // If player, maybe fire based on Skill_level and number of incoming weapons.
5921 // If non-player, maybe fire based on payload of incoming weapons.
5922 if (wip->wi_flags & WIF_HOMING) {
5923 if ((target_objnum > -1) && (tobjp->flags & OF_PLAYER_SHIP)) {
5924 if (Ai_info[Ships[tobjp->instance].ai_index].target_objnum != objnum) {
5925 // Don't allow AI ships to fire at player for fixed periods of time based on skill level.
5926 // With 5 skill levels, at Very Easy, they fire in 1/7 of every 10 second interval.
5927 // At Easy, 2/7...at Expert, 5/7
5928 int t = ((Missiontime /(65536*10)) ^ target_objnum ^ 0x01) % (NUM_SKILL_LEVELS+2);
5929 if (t > Game_skill_level) {
5930 //nprintf(("AI", "Not OK to fire homer at time thing %i\n", t));
5934 //nprintf(("AI", " IS OK to fire homer at time thing %i ***\n", t));
5936 if (wip->wi_flags & WIF_SWARM)
5937 swarmers = 2; // Note, always want to be able to fire swarmers if no currently incident homers.
5938 if (Max_allowed_player_homers[Game_skill_level] < num_homers + swarmers) {
5941 } else if (num_homers > 3) {
5942 float incoming_payload;
5944 incoming_payload = compute_incoming_payload(&Objects[target_objnum]);
5946 if (incoming_payload > tobjp->hull_strength) {
5956 // --------------------------------------------------------------------------
5957 // Fire a secondary weapon.
5958 // Maybe choose to fire a different one.
5959 // priority1 and priority2 are optional parameters with defaults = -1
5960 int ai_fire_secondary_weapon(object *objp, int priority1, int priority2)
5968 if (!Ai_firing_enabled)
5972 SDL_assert( objp != NULL );
5973 SDL_assert(objp->type == OBJ_SHIP);
5974 shipp = &Ships[objp->instance];
5975 swp = &shipp->weapons;
5977 // Select secondary weapon.
5978 current_bank = swp->current_secondary_bank; //ai_select_secondary_weapon(objp, swp, priority1, priority2);
5980 //nprintf(("AI", "Frame %i: Current bank = %i, ammo remaining = %i\n", Framecount, current_bank, swp->secondary_bank_ammo[current_bank]));
5981 if (current_bank == -1) {
5985 SDL_assert(current_bank < shipp->weapons.num_secondary_banks);
5987 weapon_info *wip = &Weapon_info[shipp->weapons.secondary_bank_weapons[current_bank]];
5989 if ((wip->wi_flags & WIF_HOMING_ASPECT) && (!Ai_info[shipp->ai_index].current_target_is_locked)) {
5990 //nprintf(("AI", "Not firing secondary weapon because not aspect locked.\n"));
5991 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
5992 } else if ((wip->wi_flags & WIF_BOMB) || (vm_vec_dist_quick(&objp->pos, &En_objp->pos) > 50.0f)) {
5993 // This might look dumb, firing a bomb even if closer than 50 meters, but the reason is, if you're carrying
5994 // bombs, delivering them is probably more important than surviving.
5997 aip = &Ai_info[shipp->ai_index];
5999 // Note, maybe don't fire if firing at player and any homers yet fired.
6000 // Decreasing chance to fire the more homers are incoming on player.
6001 if (check_ok_to_fire(OBJ_INDEX(objp), aip->target_objnum, wip)) {
6002 if (ship_fire_secondary(objp)) {
6004 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6005 //nprintf(("AI", "Frane %i: Ship %s fired secondary %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->secondary_bank_weapons[current_bank]].name));
6009 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6016 // Return true if it looks like obj1, if continuing to move along current vector, will
6017 // collide with obj2.
6018 int might_collide_with_ship(object *obj1, object *obj2, float dot_to_enemy, float dist_to_enemy, float duration)
6020 if (obj1->phys_info.speed * duration + 2*(obj1->radius + obj2->radius) > dist_to_enemy)
6021 if (dot_to_enemy > 0.8f - 2*(obj1->radius + obj2->radius)/dist_to_enemy)
6022 return objects_will_collide(obj1, obj2, duration, 2.0f);
6025 // CONDITION 1, dist_to_enemy < o1_rad + o2_rad + (obj1.speed + obj2.speed) * time + 50
6031 // --------------------------------------------------------------------------
6032 // Return true if ship *objp firing a laser believes it will hit a teammate.
6033 int might_hit_teammate(object *firing_objp)
6039 team = Ships[firing_objp->instance].team;
6041 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6042 objp = &Objects[so->objnum];
6043 if (Ships[objp->instance].team == team) {
6047 vm_vec_sub(&vec_to_objp, &firing_objp->pos, &objp->pos);
6048 dist = vm_vec_mag_quick(&vec_to_objp);
6049 dot = vm_vec_dot(&firing_objp->orient.v.fvec, &vec_to_objp)/dist;
6050 if (might_collide_with_ship(firing_objp, objp, dot, dist, 2.0f))
6059 //int Team_not_fire_count=0, Team_hit_count = 0;
6061 void render_all_ship_bay_paths(object *objp)
6064 ship *sp = &Ships[objp->instance];
6068 pm = model_get(sp->modelnum);
6069 vector global_path_point;
6070 vertex v, prev_vertex;
6072 if ( pm->ship_bay == NULL )
6075 for ( i = 0; i < pm->ship_bay->num_paths; i++ ) {
6076 mp = &pm->paths[pm->ship_bay->paths[i]];
6078 for ( j = 0; j < mp->nverts; j++ ) {
6079 vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6080 vm_vec_add2(&global_path_point, &objp->pos);
6081 g3_rotate_vertex(&v, &global_path_point);
6085 gr_set_color(0, color, 0);
6087 if ( j == mp->nverts-1 ) {
6088 gr_set_color(255, 0, 0);
6091 g3_draw_sphere( &v, 1.5f);
6094 g3_draw_line(&v, &prev_vertex);
6102 // debug function to show all path points associated with an object
6103 void render_all_subsys_paths(object *objp)
6106 ship *sp = &Ships[objp->instance];
6110 pm = model_get(sp->modelnum);
6111 vector global_path_point;
6112 vertex v, prev_vertex;
6114 if ( pm->ship_bay == NULL )
6117 for ( i = 0; i < pm->n_paths; i++ ) {
6119 for ( j = 0; j < mp->nverts; j++ ) {
6120 vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6121 vm_vec_add2(&global_path_point, &objp->pos);
6122 g3_rotate_vertex(&v, &global_path_point);
6126 gr_set_color(0, color, 0);
6128 if ( j == mp->nverts-1 ) {
6129 gr_set_color(255, 0, 0);
6132 g3_draw_sphere( &v, 1.5f);
6135 g3_draw_line(&v, &prev_vertex);
6142 void render_path_points(object *objp)
6144 ship *shipp = &Ships[objp->instance];
6145 ai_info *aip = &Ai_info[shipp->ai_index];
6149 render_all_subsys_paths(objp);
6150 render_all_ship_bay_paths(objp);
6152 if (aip->goal_objnum < 0)
6155 dobjp = &Objects[aip->goal_objnum];
6156 pm = model_get(Ships[dobjp->instance].modelnum);
6157 vector dock_point, global_dock_point;
6160 ship_model_start(&Objects[aip->goal_objnum]);
6162 dock_point = pm->docking_bays[0].pnt[0];
6163 model_find_world_point(&global_dock_point, &dock_point, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6164 g3_rotate_vertex(&v, &global_dock_point);
6165 gr_set_color(255, 255, 255);
6166 g3_draw_sphere( &v, 1.5f);
6169 if (aip->path_start != -1) {
6171 pnode *pp = &Path_points[aip->path_start];
6172 int num_points = aip->path_length;
6175 for (i=0; i<num_points; i++) {
6178 g3_rotate_vertex( &v0, &pp->pos );
6180 gr_set_color(0, 128, 96);
6182 g3_draw_line(&v0, &prev_vertex);
6184 if (pp-Path_points == aip->path_cur)
6185 gr_set_color(255,255,0);
6187 g3_draw_sphere( &v0, 4.5f);
6189 // Connect all the turrets that can fire upon this point to this point.
6190 /* if (0) { //pp->path_index != -1) {
6194 get_base_path_info(pp->path_index, aip->goal_objnum, &pmp, &pmpv);
6196 if (pmpv->nturrets) {
6197 for (int j = 0; j<pmpv->nturrets; j++) {
6202 ssp = ship_get_indexed_subsys(&Ships[Objects[aip->goal_objnum].instance], pmpv->turret_ids[j]);
6204 model_find_world_point(&turret_pos, &ssp->system_info->pnt, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6206 g3_rotate_vertex(&v1, &turret_pos);
6207 gr_set_color(255, 255, 0);
6208 g3_draw_line(&v0, &v1);
6209 g3_draw_sphere( &v1, 1.5f);
6220 ship_model_stop(&Objects[aip->goal_objnum]);
6223 // Return the distance that the current AI weapon will travel
6224 float ai_get_weapon_dist(ship_weapon *swp)
6226 int bank_num, weapon_num;
6228 bank_num = swp->current_primary_bank;
6229 weapon_num = swp->primary_bank_weapons[bank_num];
6231 // If weapon_num is illegal, return a reasonable value. A valid weapon
6232 // will get selected when this ship tries to fire.
6233 if (weapon_num == -1) {
6238 return Weapon_info[weapon_num].max_speed * Weapon_info[weapon_num].lifetime;
6241 float ai_get_weapon_speed(ship_weapon *swp)
6243 int bank_num, weapon_num;
6245 bank_num = swp->current_primary_bank;
6249 weapon_num = swp->primary_bank_weapons[bank_num];
6251 if (weapon_num == -1) {
6256 return Weapon_info[weapon_num].max_speed;
6259 // Compute the predicted position of a ship to be fired upon from a turret.
6260 // This is based on position of firing gun, enemy object, weapon speed and skill level constraints.
6261 // Return value in *predicted_enemy_pos.
6262 // Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6263 // *pobjp object firing the weapon
6264 // *eobjp object being fired upon
6265 void set_predicted_enemy_pos_turret(vector *predicted_enemy_pos, vector *gun_pos, object *pobjp, vector *enemy_pos, vector *enemy_vel, float weapon_speed, float time_enemy_in_range)
6267 ship *shipp = &Ships[pobjp->instance];
6270 //weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6272 if (weapon_speed < 1.0f)
6273 weapon_speed = 1.0f;
6277 // Make it take longer for enemies to get player's allies in range based on skill level.
6278 if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team)
6279 range_time += In_range_time[Game_skill_level];
6281 //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6283 if (time_enemy_in_range < range_time) {
6286 dist = vm_vec_dist_quick(&pobjp->pos, enemy_pos);
6287 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, time_enemy_in_range * dist/weapon_speed);
6289 float collision_time, scale;
6291 ai_info *aip = &Ai_info[shipp->ai_index];
6293 collision_time = compute_collision_time(enemy_pos, enemy_vel, gun_pos, weapon_speed);
6295 if (collision_time == 0.0f){
6296 collision_time = 100.0f;
6299 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, collision_time);
6300 if (time_enemy_in_range > 2*range_time){
6301 scale = (1.0f - aip->ai_accuracy) * 4.0f;
6303 scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - time_enemy_in_range/(2*range_time)));
6306 static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6308 vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6309 G_collision_time = collision_time;
6310 G_fire_pos = *gun_pos;
6313 G_predicted_pos = *predicted_enemy_pos;
6316 // Compute the predicted position of a ship to be fired upon.
6317 // This is based on current position of firing object, enemy object, relative position of gun on firing object,
6318 // weapon speed and skill level constraints.
6319 // Return value in *predicted_enemy_pos.
6320 // Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6321 void set_predicted_enemy_pos(vector *predicted_enemy_pos, object *pobjp, object *eobjp, ai_info *aip)
6323 float weapon_speed, range_time;
6324 ship *shipp = &Ships[pobjp->instance];
6326 weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6327 weapon_speed = SDL_max(weapon_speed, 1.0f); // set not less than 1
6331 // Make it take longer for enemies to get player's allies in range based on skill level.
6332 // but don't bias team v. team missions
6333 if ( !((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) ) {
6334 if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team) {
6335 range_time += In_range_time[Game_skill_level];
6338 //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6340 if (aip->time_enemy_in_range < range_time) {
6343 dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6344 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, aip->time_enemy_in_range * dist/weapon_speed);
6346 float collision_time;
6347 vector gun_pos, pnt;
6348 polymodel *po = model_get( Ship_info[shipp->ship_info_index].modelnum );
6350 // Compute position of gun in absolute space and use that as fire position.
6351 if(po->gun_banks != NULL){
6352 pnt = po->gun_banks[0].pnt[0];
6354 pnt = Objects[shipp->objnum].pos;
6356 vm_vec_unrotate(&gun_pos, &pnt, &pobjp->orient);
6357 vm_vec_add2(&gun_pos, &pobjp->pos);
6359 collision_time = compute_collision_time(&eobjp->pos, &eobjp->phys_info.vel, &gun_pos, weapon_speed);
6361 if (collision_time == 0.0f) {
6362 collision_time = 100.0f;
6365 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, collision_time);
6368 G_collision_time = collision_time;
6369 G_fire_pos = gun_pos;
6372 // Now add error terms (1) regular aim (2) EMP (3) stealth
6376 // regular skill level error in aim
6377 if (aip->time_enemy_in_range > 2*range_time) {
6378 scale = (1.0f - aip->ai_accuracy) * 4.0f;
6380 scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - aip->time_enemy_in_range/(2*range_time)));
6383 // if this ship is under the effect of an EMP blast, throw his aim off a bit
6384 if (shipp->emp_intensity > 0.0f) {
6385 // never go lower than 1/2 of the EMP effect max, otherwise things aren't noticeable
6386 scale += (MAX_EMP_INACCURACY * (shipp->emp_intensity < 0.5f ? 0.5f : shipp->emp_intensity));
6387 mprintf(("AI miss scale factor (EMP) %f\n",scale));
6390 // if stealthy ship, throw his aim off, more when farther away and when dot is small
6391 if ( aip->ai_flags & AIF_STEALTH_PURSIUT ) {
6392 float dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6394 vm_vec_sub(&temp, &eobjp->pos, &pobjp->pos);
6395 vm_vec_normalize_quick(&temp);
6396 float dot = vm_vec_dotprod(&temp, &pobjp->orient.v.fvec);
6397 float st_err = 3.0f * (1.4f - dot) * (1.0f + dist / (get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST)) * (1 - aip->ai_accuracy);
6399 // mprintf(("error term: %.1f, total %.1f, dot %.3f\n", st_err, scale, dot));
6402 // get a random vector that changes slowly over time (1x / sec)
6403 static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6405 vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6408 G_predicted_pos = *predicted_enemy_pos;
6411 // Handler of submode for Chase. Go into a continuous turn for awhile.
6418 SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6419 sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6420 SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6421 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6423 // Make a continuous turn towards any combination of possibly negated
6424 // up and right vectors.
6425 tvec = Pl_objp->pos;
6427 if (aip->submode_parm0 & 0x01)
6428 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6429 if (aip->submode_parm0 & 0x02)
6430 vm_vec_sub2(&tvec, &Pl_objp->orient.v.rvec);
6431 if (aip->submode_parm0 & 0x04)
6432 vm_vec_add2(&tvec, &Pl_objp->orient.v.uvec);
6433 if (aip->submode_parm0 & 0x08)
6434 vm_vec_sub2(&tvec, &Pl_objp->orient.v.uvec);
6436 // Detect degenerate cases that cause tvec to be same as player pos.
6437 if (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
6438 aip->submode_parm0 &= 0x05;
6439 if (aip->submode_parm0 == 0)
6440 aip->submode_parm0 = 1;
6441 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6444 ai_turn_towards_vector(&tvec, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6445 accelerate_ship(aip, 1.0f);
6448 // ATTACK submode handler for chase mode.
6449 void ai_chase_eb(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
6452 float dot_to_enemy, dot_from_enemy;
6454 compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
6456 // If we're trying to slow down to get behind, then point to turn towards is different.
6457 _pep = *predicted_enemy_pos;
6458 if ((dot_to_enemy > dot_from_enemy + 0.1f) || (dot_to_enemy > 0.9f))
6459 vm_vec_scale_add(&_pep, &Pl_objp->pos, &En_objp->orient.v.fvec, 100.0f);
6461 ai_turn_towards_vector(&_pep, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6463 accelerate_ship(aip, 0.0f);
6466 // Return time until weapon_objp might hit ship_objp.
6467 // Assumes ship_objp is not moving.
6468 // Returns negative time if not going to hit.
6469 // This is a very approximate function, but is pretty fast.
6470 float ai_endangered_time(object *ship_objp, object *weapon_objp)
6472 float to_dot, from_dot, dist;
6474 dist = compute_dots(ship_objp, weapon_objp, &to_dot, &from_dot);
6476 // Note, this is bogus. It assumes only the weapon is moving.
6477 // Only proceed if weapon sort of pointing at object and object pointing towards or away from weapon
6478 // (Ie, if object moving at right angle to weapon, just continue for now...)
6479 if (weapon_objp->phys_info.speed < 1.0f)
6481 else if ((from_dot > 0.1f) && (dist/(from_dot*from_dot) < 48*ship_objp->radius)) //: don't require them to see it, they have instruments!: && (fl_abs(to_dot) > 0.5f))
6482 return dist / weapon_objp->phys_info.speed;
6487 // Return time until danger weapon could hit this ai object.
6488 // Return negative time if not endangered.
6489 float ai_endangered_by_weapon(ai_info *aip)
6491 object *weapon_objp;
6493 if (aip->danger_weapon_objnum == -1) {
6497 weapon_objp = &Objects[aip->danger_weapon_objnum];
6499 if (weapon_objp->signature != aip->danger_weapon_signature) {
6500 aip->danger_weapon_objnum = -1;
6504 return ai_endangered_time(&Objects[Ships[aip->shipnum].objnum], weapon_objp);
6507 // Return true if this ship is near full strength.
6508 int ai_near_full_strength(object *objp, ship_info *sip)
6510 return (objp->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp)/sip->shields > 0.8f);
6513 // Set acceleration while in attack mode.
6514 void attack_set_accel(ai_info *aip, float dist_to_enemy, float dot_to_enemy, float dot_from_enemy)
6518 if (En_objp->phys_info.speed > 1.0f)
6519 speed_ratio = Pl_objp->phys_info.speed/En_objp->phys_info.speed;
6523 // Sometimes, told to attack slowly. Allows to get in more hits.
6524 if (aip->ai_flags & AIF_ATTACK_SLOWLY) {
6525 if ((dist_to_enemy > 200.0f) && (dist_to_enemy < 800.0f)) {
6526 if ((dot_from_enemy < 0.9f) || ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
6527 //nprintf(("AI", " slowly "));
6528 accelerate_ship(aip, SDL_max(1.0f - (dist_to_enemy-200.0f)/600.0f, 0.1f));
6532 aip->ai_flags &= ~AIF_ATTACK_SLOWLY;
6535 if (dist_to_enemy > 200.0f + vm_vec_mag_quick(&En_objp->phys_info.vel) * dot_from_enemy + Pl_objp->phys_info.speed * speed_ratio) {
6536 //nprintf(("AI", "1"));
6537 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6538 if (dist_to_enemy > 800.0f) {
6539 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6544 shipp = &Ships[Pl_objp->instance];
6545 sip = &Ship_info[shipp->ship_info_index];
6547 if (sip->afterburner_fuel_capacity > 0.0f) {
6548 percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
6549 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
6550 afterburners_start(Pl_objp);
6551 aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
6558 accelerate_ship(aip, 1.0f);
6559 } else if ((Missiontime - aip->last_hit_time > F1_0*7)
6560 && (En_objp->phys_info.speed < 10.0f)
6561 && (dist_to_enemy > 25.0f)
6562 && (dot_to_enemy > 0.8f)
6563 && (dot_from_enemy < 0.8f)) {
6564 accelerate_ship(aip, 0.0f); // No one attacking us, so don't need to move.
6565 } else if ((dot_from_enemy < 0.25f) && (dot_to_enemy > 0.5f)) {
6566 set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed);
6567 } else if (Pl_objp->phys_info.speed < 15.0f) {
6568 accelerate_ship(aip, 1.0f);
6569 } else if (Pl_objp->phys_info.speed > En_objp->phys_info.speed - 1.0f) {
6570 if (dot_from_enemy > 0.75f)
6571 accelerate_ship(aip, 1.0f);
6573 set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed*0.75f + 3.0f);
6575 change_acceleration(aip, 0.5f);
6579 // Pl_objp (aip) tries to get behind En_objp.
6580 // New on 2/21/98: If this ship can move backwards and slide, maybe do that to get behind.
6581 void get_behind_ship(ai_info *aip, ship_info *sip, float dist_to_enemy)
6585 vector vec_from_enemy;
6587 vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
6589 vm_vec_scale_add(&new_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f); // Pick point 100 units behind.
6590 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6592 dot = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
6595 accelerate_ship(aip, 1.0f);
6597 accelerate_ship(aip, (dot + 1.0f)/2.0f);
6601 int avoid_player(object *objp, vector *goal_pos)
6603 maybe_avoid_player(Pl_objp, goal_pos);
6604 ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
6606 if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6607 ship_info *sip = &Ship_info[Ships[objp->instance].ship_info_index];
6609 if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6610 ai_turn_towards_vector(&aip->avoid_goal_point, objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6611 accelerate_ship(aip, 0.5f);
6619 // Determine if a cylinder of width radius from p0 to p1 will collide with big_objp.
6620 // If so, stuff *collision_point.
6621 int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6625 mc.model_num = Ships[big_objp->instance].modelnum; // Fill in the model to check
6626 mc.orient = &big_objp->orient; // The object's orient
6627 mc.pos = &big_objp->pos; // The object's position
6628 mc.p0 = p0; // Point 1 of ray to check
6630 mc.flags = MC_CHECK_MODEL | MC_CHECK_SPHERELINE | MC_SUBMODEL; // flags
6634 // Only check the 2nd lowest hull object
6635 polymodel *pm = model_get(Ships[big_objp->instance].modelnum);
6636 mc.submodel_num = pm->detail[0]; //pm->submodel->num_details-2];
6640 *collision_point = mc.hit_point_world;
6645 // Return true/false if *objp will collide with *big_objp
6646 // Stuff distance in *distance to collision point if *objp will collide with *big_objp within delta_time seconds.
6647 // Global collision point stuffed in *collision_point
6648 int will_collide_with_big_ship(object *objp, vector *goal_point, object *big_objp, vector *collision_point, float delta_time)
6653 radius = big_objp->radius + delta_time * objp->phys_info.speed;
6655 if (vm_vec_dist_quick(&big_objp->pos, &objp->pos) > radius) {
6659 if (goal_point == NULL) {
6660 vm_vec_scale_add(&end_pos, &objp->pos, &objp->phys_info.vel, delta_time); // Point 2 of ray to check
6662 end_pos = *goal_point;
6665 return will_collide_pp(&objp->pos, &end_pos, objp->radius, big_objp, collision_point);
6668 // Return true if *objp is expected to collide with a large ship.
6669 // Stuff global collision point in *collision_point.
6670 // If *goal_point is not NULL, use that as the point towards which *objp will be flying. Don't use *objp velocity
6671 // *ignore_objp will typically be the target this ship is pursuing, either to attack or guard. We don't want to avoid it.
6672 int will_collide_with_big_ship_all(object *objp, object *ignore_objp, vector *goal_point, vector *collision_point, float *distance, float delta_time)
6676 int collision_obj_index = -1;
6677 float min_dist = 999999.9f;
6679 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6680 big_objp = &Objects[so->objnum];
6682 if (big_objp == ignore_objp)
6685 if (Ship_info[Ships[big_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
6686 vector cur_collision_point;
6689 if (will_collide_with_big_ship(objp, goal_point, big_objp, &cur_collision_point, delta_time)) {
6691 cur_dist = vm_vec_dist(&cur_collision_point, &objp->pos);
6693 if (cur_dist < min_dist) {
6694 min_dist = cur_dist;
6695 *collision_point = cur_collision_point;
6696 collision_obj_index = OBJ_INDEX(big_objp);
6702 *distance = min_dist;
6703 return collision_obj_index;
6713 //int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6714 // Pick a point for *objp to fly towards to avoid a collision with *big_objp at *collision_point
6715 // Return result in *avoid_pos
6716 void mabs_pick_goal_point(object *objp, object *big_objp, vector *collision_point, vector *avoid_pos)
6722 vm_vec_normalized_dir(&v2b, collision_point, &objp->pos);
6723 vm_vector_2_matrix(&mat1, &v2b, NULL, NULL);
6727 // Try various scales, in 0.5f, 0.75f, 1.0f, 1.25f.
6728 // First try 0.5f to see if we can find a point that near the center of the target ship, which presumably
6729 // means less of a turn.
6730 // Try going as far as 1.25f * radius.
6732 for (s=0.5f; s<1.3f; s += 0.25f) {
6734 for (i=0; i<4; i++) {
6735 vector p = big_objp->pos;
6736 float ku = big_objp->radius*s + objp->radius * (OBJ_INDEX(objp) % 4)/4; // This objp->radius stuff to prevent ships from glomming together at one point
6737 float kr = big_objp->radius*s + objp->radius * ((OBJ_INDEX(objp) % 4) ^ 2)/4;
6742 vm_vec_scale_add2(&p, &mat1.v.uvec, ku);
6743 vm_vec_scale_add2(&p, &mat1.v.rvec, kr);
6745 goals[i].dist = vm_vec_dist_quick(&objp->pos, &p);
6746 goals[i].collide = will_collide_pp(&objp->pos, &p, objp->radius, big_objp, collision_point);
6747 if (!goals[i].collide)
6751 // If we found a point that doesn't collide, find the nearest one and make that the *avoid_pos.
6753 float min_dist = 9999999.9f;
6756 for (i=0; i<4; i++) {
6757 if (!goals[i].collide && (goals[i].dist < min_dist)) {
6758 min_dist = goals[i].dist;
6763 SDL_assert(i != -1);
6765 *avoid_pos = goals[min_index].pos;
6771 // Drat. We tried and tried and could not find a point that did not cause a collision.
6772 // Get this dump pilot far away from the problem ship.
6774 vm_vec_normalized_dir(&away_vec, &objp->pos, collision_point);
6775 vm_vec_scale_add(avoid_pos, &objp->pos, &away_vec, big_objp->radius*1.5f);
6779 // Return true if a large ship is being ignored.
6780 int maybe_avoid_big_ship(object *objp, object *ignore_objp, ai_info *aip, vector *goal_point, float delta_time)
6782 if (timestamp_elapsed(aip->avoid_check_timestamp)) {
6784 vector collision_point;
6786 if ((ship_num = will_collide_with_big_ship_all(Pl_objp, ignore_objp, goal_point, &collision_point, &distance, delta_time)) != -1) {
6787 aip->ai_flags |= AIF_AVOIDING_BIG_SHIP;
6788 mabs_pick_goal_point(objp, &Objects[ship_num], &collision_point, &aip->avoid_goal_point);
6789 float dist = vm_vec_dist_quick(&aip->avoid_goal_point, &objp->pos);
6790 aip->avoid_check_timestamp = timestamp(2000 + SDL_min(1000, (int) (dist * 2.0f))); // Delay until check again is based on distance to avoid point.
6791 aip->avoid_ship_num = ship_num;
6793 aip->ai_flags &= ~AIF_AVOIDING_BIG_SHIP;
6794 aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
6795 aip->avoid_ship_num = -1;
6796 aip->avoid_check_timestamp = timestamp(1500);
6800 if (aip->ai_flags & AIF_AVOIDING_BIG_SHIP) {
6801 ship_info *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6805 ai_turn_towards_vector(&aip->avoid_goal_point, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6806 vm_vec_normalized_dir(&v2g, &aip->avoid_goal_point, &Pl_objp->pos);
6807 float dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
6808 float d2 = (1.0f + dot) * (1.0f + dot);
6809 accelerate_ship(aip, d2/4.0f);
6816 // Set desired right vector for ships flying towards another ship.
6817 // Since this is governed only by vector to target, it causes ships to align bank and look less chaotic.
6818 void compute_desired_rvec(vector *rvec, vector *goal_pos, vector *cur_pos)
6822 vm_vec_normalized_dir(&v2e, goal_pos, cur_pos);
6823 rvec->xyz.x = v2e.xyz.z;
6825 rvec->xyz.z = -v2e.xyz.x;
6826 if (vm_vec_mag_squared(rvec) < 0.001f)
6830 // Handler for stealth find submode of Chase.
6831 void ai_stealth_find()
6836 vector new_pos, vec_to_enemy;
6837 float dist_to_enemy, dot_to_enemy, dot_from_enemy;
6839 SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6840 sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6841 SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6842 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6844 // get time since last seen
6845 int delta_time = (timestamp() - aip->stealth_last_visible_stamp);
6847 // if delta_time is really big, i'm real confused, start sweep
6848 if (delta_time > 10000) {
6849 aip->submode_parm0 = SM_SF_BAIL;
6852 // guestimate new position
6853 vm_vec_scale_add(&new_pos, &aip->stealth_last_pos, &aip->stealth_velocity, (delta_time * 0.001f));
6855 // if I think he's behind me, go to the goal point
6856 if ( aip->submode_parm0 == SM_SF_BEHIND ) {
6857 new_pos = aip->goal_point;
6860 // check for collision with big ships
6861 if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &new_pos, 10.0f)) {
6862 // reset ai submode to chase
6866 // if dist is near max and dot is close to 1, accel, afterburn
6867 vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6868 dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6869 dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6871 // if i think i should see him ahead and i don't, set goal pos and turn around, but only if I haven't seen him for a while
6872 if ( (delta_time > 800) && (aip->submode_parm0 == SM_SF_AHEAD) && (dot_to_enemy > .94) && (dist_to_enemy < get_skill_stealth_dist_scaler()*STEALTH_MAX_VIEW_DIST + 50) ) {
6874 vm_vec_scale_add(&aip->goal_point, &Pl_objp->pos, &Pl_objp->orient.v.fvec, -300.0f);
6875 aip->submode_parm0 = SM_SF_BEHIND;
6876 vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6877 dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6878 dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6881 if ( (dist_to_enemy > get_skill_stealth_dist_scaler()*STEALTH_MAX_VIEW_DIST) && (dot_to_enemy > 0.94f) ) { // 20 degree half angle
6883 accelerate_ship(aip, 1.0f);
6885 // engage afterburner
6886 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6887 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6888 afterburners_start(Pl_objp);
6889 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
6893 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6897 // If enemy more than 500 meters away, all ships flying there will tend to match bank.
6898 // They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
6899 // to interpolate a matrix rather than just a vector.
6900 if (dist_to_enemy > 500.0f) {
6902 compute_desired_rvec(&rvec, &new_pos, &Pl_objp->pos);
6903 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0, &rvec);
6905 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6908 dot_from_enemy = -vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec);
6910 attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
6913 // -----------------------------------------------------------------------------
6914 // try to find stealth ship by sweeping an area
6915 void ai_stealth_sweep()
6920 SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6921 sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6922 SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6923 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6926 vector forward, right, up;
6929 // time since stealth last seen
6930 lost_time = (timestamp() - aip->stealth_last_visible_stamp);
6932 // determine which pt to fly to in sweep by keeping track of parm0
6933 if (aip->submode_parm0 == SM_SS_SET_GOAL) {
6935 // don't make goal pt more than 2k from current pos
6936 vm_vec_scale_add(&goal_pt, &aip->stealth_last_pos, &aip->stealth_velocity, (0.001f * lost_time));
6938 // make box size based on speed of stealth and expected time to intercept (keep box in range 200-500)
6939 float box_size = vm_vec_mag_quick(&aip->stealth_velocity) * (0.001f * lost_time);
6940 box_size = SDL_min(200.0f, box_size);
6941 box_size = SDL_max(500.0f, box_size);
6942 aip->stealth_sweep_box_size = box_size;
6944 aip->goal_point = goal_pt;
6945 aip->submode_parm0 = SM_SS_BOX0;
6948 // GET UP, RIGHT, FORWARD FOR BOX based on stealth ship's velocity
6949 // if velocity changes in stealth mode, then ship is *seen*, and falls out of sweep mode
6950 // if stealth has no velocity make a velocity
6951 if ( vm_vec_mag_quick(&aip->stealth_velocity) < 1 ) {
6952 vm_vec_rand_vec_quick(&aip->stealth_velocity);
6955 // get "right" vector for box
6956 vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_y_vector);
6958 if ( vm_vec_mag_quick(&right) < 0.01 ) {
6959 vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_z_vector);
6962 vm_vec_normalize_quick(&right);
6964 // get forward for box
6965 vm_vec_copy_normalize_quick(&forward, &aip->stealth_velocity);
6968 vm_vec_crossprod(&up, &forward, &right);
6970 // lost far away ahead (do box)
6971 switch(aip->submode_parm0) {
6973 goal_pt = aip->goal_point;
6978 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
6979 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
6980 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6985 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
6986 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
6987 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6992 goal_pt = aip->goal_point;
6997 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
6998 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
6999 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7004 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
7005 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
7006 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7011 goal_pt = aip->goal_point;
7019 // when close to goal_pt, update next goal pt
7020 float dist_to_goal = vm_vec_dist(&goal_pt, &Pl_objp->pos);
7021 if (dist_to_goal < 15) {
7022 aip->submode_parm0++;
7025 // check for collision with big ship
7026 if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &goal_pt, 10.0f)) {
7027 // skip to the next pt on box
7028 aip->submode_parm0++;
7032 ai_turn_towards_vector(&goal_pt, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
7035 if (dist_to_goal < 100) {
7037 vm_vec_normalized_dir(&vec_to_goal, &goal_pt, &Pl_objp->pos);
7038 dot = vm_vec_dotprod(&vec_to_goal, &Pl_objp->orient.v.fvec);
7041 accelerate_ship(aip, 0.8f*dot);
7044 // ATTACK submode handler for chase mode.
7045 void ai_chase_attack(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
7048 float dot_to_enemy, dot_from_enemy; //, time_to_hit;
7049 float bank_override = 0.0f;
7051 if (avoid_player(Pl_objp, predicted_enemy_pos))
7054 compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
7056 polymodel *po = model_get( sip->modelnum );
7063 start_bank = Ships[aip->shipnum].weapons.current_primary_bank;
7064 if (po->n_guns && start_bank != -1 ) {
7065 rel_pos = &po->gun_banks[start_bank].pnt[0];
7069 // If ship moving slowly relative to its size, then don't attack its center point.
7070 // How far from center we attack is based on speed, size and distance to enemy
7071 if (En_objp->radius > En_objp->phys_info.speed) {
7072 static_randvec(Pl_objp-Objects, &randvec);
7073 scale = dist_to_enemy/(dist_to_enemy + En_objp->radius) * En_objp->radius;
7074 scale *= 0.5f * En_objp->radius/(En_objp->phys_info.speed + En_objp->radius); // scale downward by 1/2 to 1/4
7075 vm_vec_scale_add(&new_pos, predicted_enemy_pos, &randvec, scale);
7077 new_pos = *predicted_enemy_pos;
7079 if (dist_to_enemy < 250.0f) {
7080 if (dot_from_enemy > 0.7f) {
7081 bank_override = Pl_objp->phys_info.speed;
7085 // If enemy more than 500 meters away, all ships flying there will tend to match bank.
7086 // They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
7087 // to interpolate a matrix rather than just a vector.
7088 if (dist_to_enemy > 500.0f) {
7090 compute_desired_rvec(&rvec, predicted_enemy_pos, &Pl_objp->pos);
7091 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0, &rvec);
7093 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0);
7096 attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
7099 // EVADE_SQUIGGLE submode handler for chase mode.
7100 // Changed by MK on 5/5/97.
7101 // Used to evade towards a point off the right or up vector.
7102 // Now, evade straight away to try to get far away.
7103 // The squiggling should protect against laser fire.
7104 void ai_chase_es(ai_info *aip, ship_info *sip)
7109 float bank_override = 0.0f;
7111 tvec = Pl_objp->pos;
7113 timeslice = (Missiontime >> 16) & 0x0f;
7114 scale = ((Missiontime >> 16) & 0x0f) << 14;
7116 if (timeslice & 0x01)
7117 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale ^ 0x10000));
7118 if (timeslice & 0x02)
7119 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale));
7120 if (timeslice & 0x04)
7121 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale ^ 0x10000));
7122 if (timeslice & 0x08)
7123 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale));
7125 while (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
7126 tvec.xyz.x += frand();
7127 tvec.xyz.y += frand();
7130 bank_override = Pl_objp->phys_info.speed;
7132 ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7133 accelerate_ship(aip, 1.0f);
7136 // Trying to get away from opponent.
7137 void ai_chase_ga(ai_info *aip, ship_info *sip)
7139 // If not near end of this submode, evade squiggly. If near end, just fly straight for a bit
7141 float bank_override;
7142 vector vec_from_enemy;
7144 if (En_objp != NULL) {
7145 vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
7147 vec_from_enemy = Pl_objp->orient.v.fvec;
7149 static_randvec(Missiontime >> 15, &tvec);
7150 vm_vec_scale(&tvec, 100.0f);
7151 vm_vec_scale_add2(&tvec, &vec_from_enemy, 300.0f);
7152 vm_vec_add2(&tvec, &Pl_objp->pos);
7154 bank_override = Pl_objp->phys_info.speed;
7156 ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7158 accelerate_ship(aip, 2.0f);
7160 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
7161 if (!(Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
7162 float percent_left = 100.0f * Ships[Pl_objp->instance].afterburner_fuel / sip->afterburner_fuel_capacity;
7163 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
7164 afterburners_start(Pl_objp);
7165 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7167 afterburners_start(Pl_objp);
7168 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7174 // Make object *objp attack subsystem with ID = subnum.
7175 // Return true if found a subsystem to attack, else return false.
7176 // Note, can fail if subsystem exists, but has no hits.
7177 int ai_set_attack_subsystem(object *objp, int subnum)
7179 ship *shipp, *attacker_shipp;
7182 object *attacked_objp;
7184 SDL_assert(objp->type == OBJ_SHIP);
7185 SDL_assert(objp->instance >= 0);
7187 attacker_shipp = &Ships[objp->instance];
7188 SDL_assert(attacker_shipp->ai_index >= 0);
7190 aip = &Ai_info[attacker_shipp->ai_index];
7192 // MWA -- 2/27/98. Due to AL's changes, target_objnum is now not always valid (at least sometimes
7193 // in terms of goals). So, bail if we don't have a valid target.
7194 if ( aip->target_objnum == -1 )
7197 attacked_objp = &Objects[aip->target_objnum];
7198 shipp = &Ships[attacked_objp->instance]; // need to get our target's ship pointer!!!
7200 ssp = ship_get_indexed_subsys(shipp, subnum, &objp->pos);
7204 set_targeted_subsys(aip, ssp, aip->target_objnum);
7206 if (aip->ignore_objnum == aip->target_objnum)
7207 aip->ignore_objnum = UNUSED_OBJNUM;
7209 // -- Done at caller in ai_process_mission_orders -- attacked_objp->flags |= OF_PROTECTED;
7211 ai_set_goal_maybe_abort_dock(objp, aip);
7212 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7217 void ai_set_guard_vec(object *objp, object *guard_objp)
7222 aip = &Ai_info[Ships[objp->instance].ai_index];
7224 // Handle case of bogus call in which ship is told to guard self.
7225 SDL_assert(objp != guard_objp);
7226 if (objp == guard_objp) {
7227 vm_vec_rand_vec_quick(&aip->guard_vec);
7228 vm_vec_scale(&aip->guard_vec, 100.0f);
7232 // check if guard_objp is BIG
7233 radius = 5.0f * (objp->radius + guard_objp->radius) + 50.0f;
7234 if (radius > 300.0f) {
7235 radius = guard_objp->radius * 1.25f;
7238 vm_vec_sub(&aip->guard_vec, &objp->pos, &guard_objp->pos);
7240 if (vm_vec_mag(&aip->guard_vec) > 3.0f*radius) {
7241 // Far away, don't just use vector to object, causes clustering of guard ships.
7244 mag = vm_vec_copy_normalize(&tvec, &aip->guard_vec);
7245 vm_vec_rand_vec_quick(&rvec);
7246 vm_vec_scale_add2(&tvec, &rvec, 0.5f);
7247 vm_vec_copy_scale(&aip->guard_vec, &tvec, mag);
7250 vm_vec_normalize_quick(&aip->guard_vec);
7251 vm_vec_scale(&aip->guard_vec, radius);
7254 // Make object *objp guard object *other_objp.
7255 // To be called from the goals code.
7256 void ai_set_guard_wing(object *objp, int wingnum)
7260 int leader_objnum, leader_shipnum;
7262 SDL_assert(wingnum >= 0);
7264 SDL_assert(objp->type == OBJ_SHIP);
7265 SDL_assert(objp->instance >= 0);
7267 // shouldn't set the ai mode for the player
7268 if ( objp == Player_obj ) {
7272 shipp = &Ships[objp->instance];
7274 SDL_assert(shipp->ai_index >= 0);
7276 aip = &Ai_info[shipp->ai_index];
7277 force_avoid_player_check(objp, aip);
7279 ai_set_goal_maybe_abort_dock(objp, aip);
7280 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7282 // This function is called whenever a guarded ship is destroyed, so this code
7283 // prevents a ship from trying to guard a non-existent wing.
7284 if (Wings[wingnum].current_count < 1) {
7285 aip->guard_objnum = -1;
7286 aip->guard_wingnum = -1;
7287 aip->mode = AIM_NONE;
7289 leader_shipnum = Wings[wingnum].ship_index[0];
7290 leader_objnum = Ships[leader_shipnum].objnum;
7292 SDL_assert((leader_objnum >= 0) && (leader_objnum < MAX_OBJECTS));
7293 //SDL_assert(leader_objnum != objp-Objects); // Don't allow ships to guard themselves.
7294 if (leader_objnum == OBJ_INDEX(objp)) {
7295 //Int3(); // Seems illegal, but let's clean up. Get MikeK.
7299 aip->guard_wingnum = wingnum;
7300 aip->guard_objnum = leader_objnum;
7301 aip->guard_signature = Objects[leader_objnum].signature;
7302 aip->mode = AIM_GUARD;
7303 aip->submode = AIS_GUARD_STATIC;
7305 ai_set_guard_vec(objp, &Objects[leader_objnum]);
7309 // Make object *objp guard object *other_objp.
7310 // To be called from the goals code.
7311 void ai_set_evade_object(object *objp, object *other_objp)
7317 SDL_assert(objp->type == OBJ_SHIP);
7318 SDL_assert(objp->instance >= 0);
7320 shipp = &Ships[objp->instance];
7322 SDL_assert(shipp->ai_index >= 0);
7324 aip = &Ai_info[shipp->ai_index];
7326 other_objnum = OBJ_INDEX(other_objp);
7327 SDL_assert(other_objnum >= 0);
7329 SDL_assert(other_objnum != Ships[aip->shipnum].objnum); // make sure not targeting self
7330 aip->target_objnum = other_objnum;
7332 aip->mode = AIM_EVADE;
7335 // Make objp guard other_objp
7336 // If other_objp is a member of a wing, objp will guard that whole wing
7337 // UNLESS objp is also a member of the wing!
7338 void ai_set_guard_object(object *objp, object *other_objp)
7344 SDL_assert(objp->type == OBJ_SHIP);
7345 SDL_assert(objp->instance >= 0);
7346 SDL_assert(objp != other_objp);
7348 shipp = &Ships[objp->instance];
7350 SDL_assert(shipp->ai_index >= 0);
7352 aip = &Ai_info[shipp->ai_index];
7353 aip->avoid_check_timestamp = timestamp(1);
7355 // If ship to guard is in a wing, guard that whole wing.
7356 ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
7357 if ((other_aip->wing != -1) && (other_aip->wing != aip->wing)) {
7358 ai_set_guard_wing(objp, Ai_info[Ships[other_objp->instance].ai_index].wing);
7361 other_objnum = other_objp-Objects;
7363 aip->guard_objnum = other_objnum;
7364 aip->guard_signature = other_objp->signature;
7365 aip->guard_wingnum = -1;
7367 aip->mode = AIM_GUARD;
7368 aip->submode = AIS_GUARD_STATIC;
7370 SDL_assert(other_objnum >= 0); // Hmm, bogus object and we need its position for guard_vec.
7372 // vm_vec_sub(&aip->guard_vec, &objp->pos, &Objects[other_objnum].pos);
7373 ai_set_guard_vec(objp, &Objects[other_objnum]);
7375 ai_set_goal_maybe_abort_dock(objp, aip);
7376 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7380 // Update the aspect_locked_time field based on whether enemy is in view cone.
7381 // Also set/clear AIF_SEEK_LOCK.
7382 void update_aspect_lock_information(ai_info *aip, vector *vec_to_enemy, float dist_to_enemy, float enemy_radius)
7385 int num_weapon_types;
7386 int weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
7391 shipp = &Ships[aip->shipnum];
7392 swp = &shipp->weapons;
7394 // AL 3-7-98: This probably should never happen, but check to ensure that current_secondary_bank is valid
7395 if ( (swp->current_secondary_bank < 0) || (swp->current_secondary_bank > swp->num_secondary_banks) ) {
7399 num_weapon_types = get_available_secondary_weapons(Pl_objp, weapon_id_list, weapon_bank_list);
7401 wip = &Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]];
7403 if (num_weapon_types && (wip->wi_flags & WIF_HOMING_ASPECT)) {
7404 if (dist_to_enemy > 300.0f - SDL_min(enemy_radius, 100.0f))
7405 aip->ai_flags |= AIF_SEEK_LOCK;
7407 aip->ai_flags &= ~AIF_SEEK_LOCK;
7409 // Update locking information for aspect seeking missiles.
7410 aip->current_target_is_locked = 0;
7411 dot_to_enemy = vm_vec_dot(vec_to_enemy, &Pl_objp->orient.v.fvec);
7413 float needed_dot = 0.9f - 0.5f * enemy_radius/(dist_to_enemy + enemy_radius); // Replaced MIN_TRACKABLE_DOT with 0.9f
7414 if (dot_to_enemy > needed_dot) {
7415 aip->aspect_locked_time += flFrametime;
7416 // nprintf(("AI", "+ Lock time = %7.3f\n", aip->aspect_locked_time));
7417 if (aip->aspect_locked_time >= wip->min_lock_time) {
7418 aip->aspect_locked_time = wip->min_lock_time;
7419 aip->current_target_is_locked = 1;
7422 aip->aspect_locked_time -= flFrametime*2;
7423 // nprintf(("AI", "- Lock time = %7.3f\n", aip->aspect_locked_time));
7424 if (aip->aspect_locked_time < 0.0f)
7425 aip->aspect_locked_time = 0.0f;
7427 //nprintf(("AI", "dot = %7.3f, time = %7.3f\n", dot_to_enemy, aip->aspect_locked_time));
7430 aip->current_target_is_locked = 0;
7431 aip->aspect_locked_time = 0.0f; // Used to be this, why?: wip->min_lock_time;
7432 aip->ai_flags &= ~AIF_SEEK_LOCK;
7437 // We're in chase mode and we've recently collided with our target.
7438 // Fly away from it!
7439 void ai_chase_fly_away(object *objp, ai_info *aip)
7443 if (aip->ai_flags & AIF_TARGET_COLLISION) {
7444 aip->ai_flags &= ~AIF_TARGET_COLLISION; // Don't process this hit again next frame.
7445 aip->submode = SM_FLY_AWAY; // Focus on avoiding target
7446 aip->submode_start_time = Missiontime;
7449 if ((aip->target_objnum == -1) || (Objects[aip->target_objnum].signature != aip->target_signature)) {
7453 if (abort_flag || (Missiontime > aip->submode_start_time + F1_0)) {
7454 aip->last_attack_time = Missiontime;
7455 aip->submode = SM_ATTACK;
7456 aip->submode_start_time = Missiontime;
7461 vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, &objp->pos);
7463 dot = vm_vec_dot(&objp->orient.v.fvec, &v2e);
7465 accelerate_ship(aip, 1.0f);
7467 accelerate_ship(aip, 1.0f - dot);
7468 turn_away_from_point(objp, &Objects[aip->target_objnum].pos, 0.0f);
7472 // Return bank index of favored secondary weapon.
7473 // Return -1 if nothing favored.
7474 // "favored" means SEXPs have specified the weapon as being good to fire at en_objp.
7475 int has_preferred_secondary(object *objp, object *en_objp, ship_weapon *swp)
7477 // int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
7480 for (i=0; i<swp->num_secondary_banks; i++) {
7481 if (swp->secondary_bank_capacity[i] > 0) {
7482 if (swp->secondary_bank_ammo[i] > 0) {
7483 if (is_preferred_weapon(swp->secondary_bank_weapons[i], objp, en_objp) != -1){
7493 // Choose which secondary weapon to fire.
7494 // Note, this is not like ai_select_secondary_weapon(). "choose" means make a choice.
7495 // "select" means execute an order. Get it?
7496 // This function calls ai_select_secondary_weapon() with the characteristics it should search for.
7497 void ai_choose_secondary_weapon(object *objp, ai_info *aip, object *en_objp)
7499 float subsystem_strength = 0.0f;
7500 int is_big_ship, priority1, priority2;
7504 if ( en_objp->type == OBJ_SHIP ) {
7505 esip = &Ship_info[Ships[en_objp->instance].ship_info_index];
7510 swp = &Ships[objp->instance].weapons;
7512 // AL 3-5-98: do a quick out if the ship has no secondaries
7513 if ( swp->num_secondary_banks <= 0 ) {
7514 swp->current_secondary_bank = -1;
7518 int preferred_secondary = has_preferred_secondary(objp, en_objp, swp);
7520 if (preferred_secondary != -1) {
7521 if (swp->current_secondary_bank != preferred_secondary) {
7522 aip->current_target_is_locked = 0;
7523 aip->aspect_locked_time = 0.0f;
7524 swp->current_secondary_bank = preferred_secondary;
7526 //nprintf(("AI", "Favored secondary = %s\n", Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7527 aip->ai_flags |= AIF_UNLOAD_SECONDARIES;
7529 aip->ai_flags &= ~AIF_UNLOAD_SECONDARIES;
7530 if (aip->targeted_subsys) {
7531 subsystem_strength = aip->targeted_subsys->current_hits;
7535 is_big_ship = esip->flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP);
7541 priority1 = WIF_HUGE;
7542 priority2 = WIF_HOMING;
7543 } else if ( (esip != NULL) && (esip->flags & SIF_BOMBER) ) {
7544 priority1 = WIF_BOMBER_PLUS;
7545 priority2 = WIF_HOMING;
7546 } else if (subsystem_strength > 100.0f) {
7547 priority1 = WIF_PUNCTURE;
7548 priority2 = WIF_HOMING;
7550 priority1 = WIF_HOMING;
7554 ai_select_secondary_weapon(objp, swp, priority1, priority2);
7557 // nprintf(("AI", "Frame %i: Chose secondary %s\n", Framecount, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7560 // Return time, in seconds, at which this ship can next fire its current secondary weapon.
7561 float set_secondary_fire_delay(ai_info *aip, ship *shipp, weapon_info *swip)
7563 float t = swip->fire_wait; // Base delay for this weapon.
7564 if (shipp->team == Player_ship->team) {
7565 // On player's team, _lower_ skill level = faster firing
7566 t = t * (Game_skill_level+2) / (NUM_SKILL_LEVELS);
7567 } else { // Not on player's team, higher skill level = faster firing
7568 t = t * (NUM_SKILL_LEVELS - Game_skill_level+2) / (NUM_SKILL_LEVELS);
7571 t += (Num_ai_classes - aip->ai_class + 1) * 0.5f;
7572 t *= frand_range(0.8f, 1.2f);
7574 // For the missiles that fire fairly quickly, occasionally add an additional substantial delay.
7577 t = t * 2.0f + 2.0f;
7583 void ai_chase_big_approach_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7587 // head straight toward him and maybe circle later
7588 vm_vec_avg(goal_pos, &attack_objp->pos, &target_objp->pos);
7590 // get distance to goal
7591 dist_to_goal = vm_vec_dist(goal_pos, &attack_objp->pos);
7594 if (dist_to_goal > 400.0f) {
7597 *accel = dist_to_goal/400.0f;
7601 void ai_chase_big_circle_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7603 get_tangent_point(goal_pos, attack_objp, &target_objp->pos, attack_objp->radius + target_objp->radius + 100.0f);
7608 // get the current and desired horizontal separations between target
7609 void ai_chase_big_get_separations(object *attack_objp, object *target_objp, vector *horz_vec_to_target, float *desired_separation, float *cur_separation)
7611 float temp, r_target, r_attacker;
7613 vector vec_to_target;
7616 // get parameters of ships (as cylinders - radius and height)
7617 // get radius of attacker (for rotations about forward)
7618 pm = model_get(Ships[attack_objp->instance].modelnum);
7619 temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7620 r_attacker = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7621 r_attacker = SDL_max(temp, r_attacker);
7623 // get radius of target (for rotations about forward)
7624 pm = model_get(Ships[attack_objp->instance].modelnum);
7625 temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7626 r_target = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7627 r_target = SDL_max(temp, r_target);
7629 // find separation between cylinders [if parallel]
7630 vm_vec_sub(&vec_to_target, &attack_objp->pos, &target_objp->pos);
7632 // find the distance between centers along forward direction of ships
7633 perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7635 // subtract off perp component to get "horizontal" separation vector between cylinders [ASSUMING parallel]
7636 vm_vec_scale_add(horz_vec_to_target, &vec_to_target, &target_objp->orient.v.fvec, -perp_dist);
7637 *cur_separation = vm_vec_mag_quick(horz_vec_to_target);
7639 // choose "optimal" separation of 1000 + r_target + r_attacker
7640 *desired_separation = 1000 + r_target + r_attacker;
7643 void ai_chase_big_parallel_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7646 float separation, optimal_separation;
7647 vector horz_vec_to_target;
7650 float temp, r_target, r_attacker;
7653 // get parameters of ships (as cylinders - radius and height)
7654 // get radius of attacker (for rotations about forward)
7655 pm = model_get(Ships[attack_objp->instance].modelnum);
7656 temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7657 r_attacker = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7658 r_attacker = SDL_max(temp, r_attacker);
7660 // get radius of target (for rotations about forward)
7661 pm = model_get(Ships[attack_objp->instance].modelnum);
7662 temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7663 r_target = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7664 r_target = SDL_max(temp, r_target);
7667 // are we opposing (only when other ship is not moving)
7668 opposing = ( vm_vec_dotprod(&attack_objp->orient.v.fvec, &target_objp->orient.v.fvec) < 0 );
7670 ai_chase_big_get_separations(attack_objp, target_objp, &horz_vec_to_target, &optimal_separation, &separation);
7672 // choose dist (2000) so that we don't bash
7678 // set the goal pos as dist forward from target along target forward
7679 vm_vec_scale_add(goal_pos, &target_objp->pos, &target_objp->orient.v.fvec, dist);
7680 // then add horizontal separation
7681 vm_vec_scale_add2(goal_pos, &horz_vec_to_target, optimal_separation/separation);
7683 // find the distance between centers along forward direction of ships
7684 vector vec_to_target;
7685 vm_vec_sub(&vec_to_target, &target_objp->pos, &attack_objp->pos);
7686 float perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7688 float match_accel = target_objp->phys_info.vel.xyz.z / Ship_info[Ships[attack_objp->instance].ship_info_index].max_vel.xyz.z;
7689 float length_scale = attack_objp->radius;
7691 // if we're heading toward enemy ship, we want to keep going if we're ahead
7693 perp_dist = -perp_dist;
7696 if (perp_dist > 0) {
7697 // falling behind, so speed up
7698 *accel = match_accel + (1.0f - match_accel) / length_scale * (perp_dist);
7700 // up in front, so slow down
7701 *accel = match_accel - match_accel / length_scale * -perp_dist;
7702 *accel = SDL_max(0.0f, *accel);
7708 // Return *goal_pos for one cruiser to attack another (big ship).
7709 // Choose point fairly nearby that is not occupied by another cruiser.
7710 void ai_cruiser_chase_set_goal_pos(vector *goal_pos, object *pl_objp, object *en_objp)
7714 aip = &Ai_info[Ships[pl_objp->instance].ai_index];
7717 switch (aip->submode) {
7718 case SM_BIG_APPROACH:
7719 // do approach stuff;
7720 ai_chase_big_approach_set_goal(goal_pos, pl_objp, en_objp, &accel);
7725 ai_chase_big_circle_set_goal(goal_pos, pl_objp, en_objp, &accel);
7728 case SM_BIG_PARALLEL:
7729 // do parallel stuff
7730 ai_chase_big_parallel_set_goal(goal_pos, pl_objp, en_objp, &accel);
7735 int maybe_hack_cruiser_chase_abort()
7737 ship *shipp = &Ships[Pl_objp->instance];
7738 ship *eshipp = &Ships[En_objp->instance];
7739 ai_info *aip = &Ai_info[shipp->ai_index];
7741 // mission sm3-08, sathanos chasing collosus
7742 if ( SDL_strcasecmp(Mission_filename, "sm3-08.fs2") == 0 ) {
7743 if (( SDL_strcasecmp(eshipp->ship_name, "colossus") == 0 ) || ( SDL_strcasecmp(shipp->ship_name, "colossus") == 0 )) {
7744 // Changed so all big ships attacking the Colossus will not do the chase code.
7745 // Did this so Beast wouldn't swerve away from Colossus. -- MK, 9/14/99
7746 //if ( SDL_strcasecmp(shipp->ship_name, "Sathanas") == 0 ) {
7747 // do cool hack stuff here
7748 ai_clear_ship_goals( aip );
7749 aip->mode = AIM_NONE;
7758 // Make a big ship pursue another big ship.
7759 // (Note, called "ai_cruiser_chase" because we already have ai_chase_big() which means fighter chases big ship.
7760 void ai_cruiser_chase()
7762 ship_info *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7763 ship *shipp = &Ships[Pl_objp->instance];
7764 ai_info *aip = &Ai_info[shipp->ai_index];
7766 if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7767 Int3(); // Hmm, not a very big ship, how did we get in this function?
7768 aip->mode = AIM_NONE;
7772 if (En_objp->type != OBJ_SHIP) {
7777 if (En_objp->instance < 0) {
7785 eshipp = &Ships[En_objp->instance];
7786 esip = &Ship_info[eshipp->ship_info_index];
7788 if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7789 // Int3(); // Hmm, we're big and we're pursuing something other than a big ship?
7790 aip->mode = AIM_NONE;
7795 float turn_time = Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time;
7797 // kamikaze - ram and explode
7798 if (aip->ai_flags & AIF_KAMIKAZE) {
7799 ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
7800 accelerate_ship(aip, 1.0f);
7803 // really track down and chase
7805 // check valid submode
7806 SDL_assert( (aip->submode == SM_ATTACK) || (aip->submode == SM_BIG_APPROACH) || (aip->submode == SM_BIG_CIRCLE) || (aip->submode == SM_BIG_PARALLEL) );
7808 // just entering, approach enemy ship
7809 if (aip->submode == SM_ATTACK) {
7810 aip->submode = SM_BIG_APPROACH;
7815 vector *rvecp = NULL;
7817 switch (aip->submode) {
7818 case SM_BIG_APPROACH:
7819 // do approach stuff;
7820 ai_chase_big_approach_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7826 ai_chase_big_circle_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7830 case SM_BIG_PARALLEL:
7831 // do parallel stuff
7832 ai_chase_big_parallel_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7838 // now move as desired
7839 ai_turn_towards_vector(&goal_pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0, rvecp);
7840 accelerate_ship(aip, accel);
7843 // maybe switch to new mode
7844 vector vec_to_enemy;
7845 float dist_to_enemy;
7846 int moving = (En_objp->phys_info.vel.xyz.z > 0.5f);
7847 vm_vec_sub(&vec_to_enemy, &En_objp->pos, &Pl_objp->pos);
7848 dist_to_enemy = vm_vec_mag_quick(&vec_to_enemy);
7850 switch (aip->submode) {
7851 case SM_BIG_APPROACH:
7852 if ( dist_to_enemy < (Pl_objp->radius + En_objp->radius)*1.25f + 200.0f ) {
7855 // if within 90 degrees of en forward, go into parallel, otherwise circle
7856 if ( vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0 ) {
7857 aip->submode = SM_BIG_PARALLEL;
7862 if ( !maybe_hack_cruiser_chase_abort() ) {
7863 aip->submode = SM_BIG_CIRCLE;
7872 float desired_sep, cur_sep;
7873 // we're behind the enemy ship
7874 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7875 // and we're turning toward the enemy
7876 if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7878 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7879 // and the separation is > 0.9 desired
7880 if (cur_sep > 0.9 * desired_sep) {
7881 aip->submode = SM_BIG_PARALLEL;
7888 float desired_sep, cur_sep;
7889 // we're behind the enemy ship
7890 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7891 // and we're turning toward the enemy
7892 if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7894 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7895 //and the separation is [0.9 to 1.1] desired
7896 if ( (cur_sep > 0.9f * desired_sep) ) {
7897 aip->submode = SM_BIG_PARALLEL;
7903 // and we're turning toward the enemy
7904 if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) < 0) {
7906 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7907 //and the separation is [0.9 to 1.1] desired
7908 if ( (cur_sep > 0.9f * desired_sep) ) {
7909 aip->submode = SM_BIG_PARALLEL;
7916 case SM_BIG_PARALLEL:
7918 if ( vm_vec_dotprod(&Pl_objp->orient.v.fvec, &En_objp->orient.v.fvec) < 0 ) {
7919 // and the other ship is moving
7921 // and we no longer overlap
7922 if ( dist_to_enemy > (0.75 * (En_objp->radius + Pl_objp->radius)) ) {
7923 aip->submode = SM_BIG_APPROACH;
7932 // --------------------------------------------------------------------------
7933 // Make object Pl_objp chase object En_objp
7936 float dist_to_enemy;
7937 float dot_to_enemy, dot_from_enemy, real_dot_to_enemy;
7938 vector player_pos, enemy_pos, predicted_enemy_pos, real_vec_to_enemy, predicted_vec_to_enemy;
7939 ship_info *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7940 ship *shipp = &Ships[Pl_objp->instance];
7941 ship_weapon *swp = &shipp->weapons;
7942 ai_info *aip = &Ai_info[shipp->ai_index];
7943 int enemy_sip_flags;
7945 if (aip->mode != AIM_CHASE) {
7949 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7954 if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER | SIF_ESCAPEPOD))) {
7955 Warning(LOCATION, "Ship %s is not 'small', but is in chase mode.\nSwitching to AI=none.\n", shipp->ship_name);
7956 aip->mode = AIM_NONE;
7960 //nprintf(("AI", "%7s ", Submode_text[aip->submode]));
7962 if ( En_objp->type == OBJ_SHIP ) {
7963 enemy_sip_flags = Ship_info[Ships[En_objp->instance].ship_info_index].flags;
7965 enemy_sip_flags = 0;
7968 if ( enemy_sip_flags > 0 ) {
7969 if (enemy_sip_flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7975 // If collided with target_objnum last frame, avoid that ship.
7976 // This should prevent the embarrassing behavior of ships getting stuck on each other
7977 // as if they were magnetically attracted. -- MK, 11/13/97.
7978 if ((aip->ai_flags & AIF_TARGET_COLLISION) || (aip->submode == SM_FLY_AWAY)) {
7979 ai_chase_fly_away(Pl_objp, aip);
7983 ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
7984 dist_to_enemy = vm_vec_dist_quick(&player_pos, &enemy_pos);
7985 vm_vec_sub(&real_vec_to_enemy, &enemy_pos, &player_pos);
7987 vm_vec_normalize(&real_vec_to_enemy);
7989 real_dot_to_enemy = vm_vec_dot(&real_vec_to_enemy, &Pl_objp->orient.v.fvec);
7991 int is_stealthy_ship = 0;
7992 if ( (enemy_sip_flags > 0) && (enemy_sip_flags & SIF_STEALTH) ) {
7993 if ( ai_is_stealth_visible(Pl_objp, En_objp) != STEALTH_FULLY_TARGETABLE ) {
7994 is_stealthy_ship = 1;
7998 // Can only acquire lock on a target that isn't hidden from sensors
7999 if ( !(Ships[En_objp->instance].flags & SF_HIDDEN_FROM_SENSORS) && !is_stealthy_ship ) {
8000 update_aspect_lock_information(aip, &real_vec_to_enemy, dist_to_enemy, En_objp->radius);
8002 aip->current_target_is_locked = 0;
8003 aip->ai_flags &= ~AIF_SEEK_LOCK;
8006 // If seeking lock, try to point directly at ship, else predict position so lasers can hit it.
8007 // If just acquired target, or target is not in reasonable cone, don't refine believed enemy position.
8008 if ((real_dot_to_enemy < 0.25f) || (aip->target_time < 1.0f) || (aip->ai_flags & AIF_SEEK_LOCK)) {
8009 predicted_enemy_pos = enemy_pos;
8011 // Set predicted_enemy_pos.
8012 // See if attacking a subsystem.
8013 if (aip->targeted_subsys != NULL) {
8014 SDL_assert(En_objp->type == OBJ_SHIP);
8015 ship_info *esip = &Ship_info[Ships[En_objp->instance].ship_info_index];
8016 if (get_shield_strength(En_objp)/esip->shields < HULL_DAMAGE_THRESHOLD_PERCENT) {
8019 if (aip->targeted_subsys != NULL) {
8020 get_subsystem_pos(&enemy_pos, En_objp, aip->targeted_subsys);
8021 predicted_enemy_pos = enemy_pos;
8022 predicted_vec_to_enemy = real_vec_to_enemy;
8024 set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8025 set_target_objnum(aip, -1);
8027 // nprintf(("AI", "Attacking subsystem: rval = %i, pos = %7.3f %7.3f %7.3f\n", rval, predicted_enemy_pos.xyz.x, predicted_enemy_pos.xyz.y, predicted_enemy_pos.xyz.z));
8030 set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8031 // nprintf(("AI", "Attacking subsystem: pos = %7.3f %7.3f %7.3f\n", predicted_enemy_pos.xyz.x, predicted_enemy_pos.xyz.y, predicted_enemy_pos.xyz.z));
8034 set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8038 vm_vec_sub(&predicted_vec_to_enemy, &predicted_enemy_pos, &player_pos);
8040 vm_vec_normalize(&predicted_vec_to_enemy);
8042 dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &predicted_vec_to_enemy);
8043 dot_from_enemy= - vm_vec_dot(&En_objp->orient.v.fvec, &real_vec_to_enemy);
8046 // Set turn and acceleration based on submode.
8048 switch (aip->submode) {
8049 case SM_CONTINUOUS_TURN:
8053 case SM_STEALTH_FIND:
8057 case SM_STEALTH_SWEEP:
8062 case SM_SUPER_ATTACK:
8063 case SM_ATTACK_FOREVER:
8064 if (vm_vec_dist_quick(&Pl_objp->pos, &predicted_enemy_pos) > 100.0f + En_objp->radius * 2.0f) {
8065 if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &predicted_enemy_pos, 10.0f))
8069 ai_chase_attack(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8072 case SM_EVADE_SQUIGGLE:
8073 ai_chase_es(aip, sip);
8076 case SM_EVADE_BRAKE:
8077 ai_chase_eb(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8089 get_behind_ship(aip, sip, dist_to_enemy);
8092 case SM_GET_AWAY: // Used to get away from opponent to prevent endless circling.
8093 ai_chase_ga(aip, sip);
8096 case SM_EVADE_WEAPON:
8102 aip->last_attack_time = Missiontime;
8103 aip->submode = SM_ATTACK;
8104 aip->submode_start_time = Missiontime;
8108 // Maybe choose a new submode.
8110 if ( (aip->submode != SM_AVOID) && (aip->submode != SM_ATTACK_FOREVER) ) {
8111 // If a very long time since attacked, attack no matter what!
8112 if ( (aip->submode != SM_SUPER_ATTACK) && (aip->submode != SM_GET_AWAY) && !(aip->ai_flags & AIF_STEALTH_PURSIUT) ) {
8113 if (Missiontime - aip->last_attack_time > i2f(6)) {
8114 aip->submode = SM_SUPER_ATTACK;
8115 aip->submode_start_time = Missiontime;
8116 aip->last_attack_time = Missiontime;
8120 // If a collision is expected, pull out!
8121 // If enemy is pointing away and moving a bit, don't worry about collision detection.
8122 if ((dot_from_enemy > 0.5f) || (En_objp->phys_info.speed < 10.0f)) {
8123 if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 4.0f)) {
8124 if ((Missiontime - aip->last_hit_time > F1_0*4) && (dist_to_enemy < Pl_objp->radius*2 + En_objp->radius*2)) {
8125 accelerate_ship(aip, -1.0f);
8127 aip->submode = SM_AVOID;
8128 aip->submode_start_time = Missiontime;
8134 switch (aip->submode) {
8135 case SM_CONTINUOUS_TURN:
8136 if (Missiontime - aip->submode_start_time > i2f(3)) {
8137 aip->last_attack_time = Missiontime;
8138 aip->submode = SM_ATTACK;
8139 aip->submode_start_time = Missiontime;
8144 // if taraget is stealth and stealth not visible, then enter stealth find mode
8145 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8146 aip->submode = SM_STEALTH_FIND;
8147 aip->submode_start_time = Missiontime;
8148 aip->submode_parm0 = SM_SF_AHEAD;
8149 } else if (ai_near_full_strength(Pl_objp, sip) && (Missiontime - aip->last_hit_target_time > i2f(3)) && (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.5f)) {
8150 aip->submode = SM_SUPER_ATTACK;
8151 aip->submode_start_time = Missiontime;
8152 aip->last_attack_time = Missiontime;
8153 } else if ((Missiontime - aip->last_hit_target_time > i2f(6)) &&
8154 (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.2f) &&
8155 (frand() < (float) Game_skill_level/NUM_SKILL_LEVELS)) {
8156 aip->submode = SM_GET_AWAY;
8157 aip->submode_start_time = Missiontime;
8158 aip->last_hit_target_time = Missiontime;
8159 } else if ((enemy_sip_flags & SIF_SMALL_SHIP)
8160 && (dot_to_enemy < dot_from_enemy)
8161 && (En_objp->phys_info.speed > 15.0f)
8162 && (dist_to_enemy < 200.0f)
8163 && (dist_to_enemy > 50.0f)
8164 && (dot_to_enemy < 0.1f)
8165 && (Missiontime - aip->submode_start_time > i2f(2))) {
8166 aip->submode = SM_EVADE_BRAKE;
8167 aip->submode_start_time = Missiontime;
8168 } else if ((dot_to_enemy > 0.2f) && (dot_from_enemy > -0.2f) && (dot_from_enemy < 0.1f)) {
8169 aip->submode = SM_GET_BEHIND;
8170 aip->submode_start_time = Missiontime;
8171 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (dist_to_enemy < 150.0f) && (dot_from_enemy > dot_to_enemy + 0.5f + aip->ai_courage*.002)) {
8172 if ((Missiontime - aip->last_hit_target_time > i2f(5)) && (frand() < (float) (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS))) { aip->submode = SM_GET_AWAY;
8173 aip->submode_start_time = Missiontime;
8174 aip->last_hit_target_time = Missiontime;
8176 aip->submode = SM_EVADE_SQUIGGLE;
8177 aip->submode_start_time = Missiontime;
8179 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > F1_0*2)) {
8180 if ((dot_to_enemy < 0.8f) && (dot_from_enemy > dot_to_enemy)) {
8181 if (frand() > 0.5f) {
8182 aip->submode = SM_CONTINUOUS_TURN;
8183 aip->submode_parm0 = myrand() & 0x0f;
8184 aip->submode_start_time = Missiontime;
8186 aip->submode = SM_EVADE;
8187 aip->submode_start_time = Missiontime;
8190 aip->submode_start_time = Missiontime;
8194 aip->last_attack_time = Missiontime;
8198 case SM_EVADE_SQUIGGLE:
8199 if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > 300.0f)) {
8200 if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.0f) && (dot_from_enemy > 0.5f)) {
8201 aip->submode = SM_EVADE_BRAKE;
8202 aip->submode_start_time = Missiontime;
8204 aip->last_attack_time = Missiontime;
8205 aip->submode = SM_ATTACK;
8206 aip->submode_start_time = Missiontime;
8211 case SM_EVADE_BRAKE:
8212 if ((dist_to_enemy < 15.0f) || (En_objp->phys_info.speed < 10.0f)) {
8213 aip->submode = SM_AVOID;
8214 aip->submode_start_time = Missiontime;
8215 } else if ((dot_to_enemy > 0.9f) || ((dot_from_enemy > 0.9f) && (Missiontime - aip->submode_start_time > i2f(1)))) {
8216 aip->last_attack_time = Missiontime;
8217 aip->submode = SM_ATTACK;
8218 aip->submode_start_time = Missiontime;
8219 } else if (Missiontime - aip->submode_start_time > i2f(4)) {
8220 aip->last_attack_time = Missiontime;
8221 aip->submode = SM_ATTACK;
8222 aip->submode_start_time = Missiontime;
8227 // Modified by MK on 5/5/97 to keep trying to regain attack mode. It's what a human would do.
8228 if ((dot_to_enemy < 0.2f) && (dot_from_enemy < 0.8f) && (dist_to_enemy < 100.0f) && (En_objp->phys_info.speed > 15.0f)) {
8229 aip->last_attack_time = Missiontime;
8230 aip->submode = SM_EVADE_BRAKE;
8231 aip->submode_start_time = Missiontime;
8232 } else if (((dot_to_enemy > dot_from_enemy - 0.1f)
8233 && (Missiontime > aip->submode_start_time + i2f(1)))
8234 || (dist_to_enemy > 150.0f + 2*(Pl_objp->radius + En_objp->radius))) {
8235 aip->last_attack_time = Missiontime;
8236 aip->submode = SM_ATTACK;
8237 aip->submode_start_time = Missiontime;
8238 } else if (Missiontime - aip->submode_start_time > i2f(2))
8239 if (dot_from_enemy > 0.8f) {
8240 aip->submode = SM_EVADE_SQUIGGLE;
8241 aip->submode_start_time = Missiontime;
8246 case SM_SUPER_ATTACK:
8247 // if stealth and invisible, enter stealth find mode
8248 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8249 aip->submode = SM_STEALTH_FIND;
8250 aip->submode_start_time = Missiontime;
8251 aip->submode_parm0 = SM_SF_AHEAD;
8252 } else if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.8f) && (enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > i2f(5) )) {
8253 aip->ai_flags &= ~AIF_ATTACK_SLOWLY; // Just in case, clear here.
8255 switch (myrand() % 5) {
8257 aip->submode = SM_CONTINUOUS_TURN;
8258 aip->submode_start_time = Missiontime;
8261 aip->submode_start_time = Missiontime; // Stay in super attack mode
8265 if (frand() < (float) 0.5f * (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS)) {
8266 aip->submode = SM_GET_AWAY;
8267 aip->submode_start_time = Missiontime;
8269 aip->submode = SM_EVADE;
8270 aip->submode_start_time = Missiontime;
8274 if (dot_from_enemy + (NUM_SKILL_LEVELS - Game_skill_level) * 0.1f > dot_to_enemy) { // Less likely to GET_AWAY at lower skill levels.
8275 aip->submode = SM_EVADE;
8276 aip->submode_start_time = Missiontime;
8278 aip->submode = SM_GET_AWAY;
8279 aip->submode_start_time = Missiontime;
8283 Int3(); // Impossible!
8287 aip->last_attack_time = Missiontime;
8292 if ((dot_to_enemy > -0.2f) && (dist_to_enemy / (dot_to_enemy + 0.3f) < 100.0f)) {
8293 aip->submode_start_time = Missiontime;
8294 } else if (Missiontime - aip->submode_start_time > i2f(1)/2) {
8295 if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 3.0f)) {
8296 aip->submode_start_time = Missiontime;
8298 aip->submode = SM_GET_BEHIND;
8299 aip->submode_start_time = Missiontime;
8306 if ((dot_from_enemy < -0.7f) || (Missiontime - aip->submode_start_time > i2f(2))) {
8307 aip->submode = SM_ATTACK;
8308 aip->submode_start_time = Missiontime;
8309 aip->last_attack_time = Missiontime;
8314 if (Missiontime - aip->submode_start_time > i2f(2)) {
8317 rand_dist = ((Missiontime >> 17) & 0x03) * 100.0f + 200.0f; // Some value in 200..500
8318 if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > rand_dist) || (dot_from_enemy < 0.4f)) {
8319 aip->ai_flags |= AIF_ATTACK_SLOWLY;
8320 aip->submode = SM_ATTACK;
8321 aip->time_enemy_in_range = 2.0f; // Cheat. Presumably if they were running away from you, they were monitoring you!
8322 aip->submode_start_time = Missiontime;
8323 aip->last_attack_time = Missiontime;
8328 case SM_EVADE_WEAPON:
8329 if (aip->danger_weapon_objnum == -1) {
8330 aip->submode = SM_ATTACK;
8331 aip->submode_start_time = Missiontime;
8332 aip->last_attack_time = Missiontime;
8336 // Either change to SM_ATTACK or AIM_FIND_STEALTH
8337 case SM_STEALTH_FIND:
8338 // if time > 5 sec change mode to sweep
8339 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8340 aip->submode = SM_ATTACK;
8341 aip->submode_start_time = Missiontime;
8342 aip->last_attack_time = Missiontime;
8343 // sweep if I can't find in 5 sec or bail from find
8344 } else if ( ((Missiontime - aip->submode_start_time) > i2f(5)) || (aip->submode_parm0 == SM_SF_BAIL) ) {
8346 aip->submode = SM_STEALTH_SWEEP;
8347 aip->submode_start_time = Missiontime;
8348 aip->last_attack_time = Missiontime;
8349 aip->submode_parm0 = SM_SS_SET_GOAL;
8353 case SM_STEALTH_SWEEP:
8354 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8355 aip->submode = SM_ATTACK;
8356 aip->submode_start_time = Missiontime;
8357 aip->last_attack_time = Missiontime;
8358 } else if ( (timestamp() - aip->stealth_last_visible_stamp) < 5000 ) {
8359 // go back to find mode
8360 aip->submode = SM_STEALTH_FIND;
8361 aip->submode_start_time = Missiontime;
8362 aip->submode_parm0 = SM_SF_AHEAD;
8363 } else if ( /*(Missiontime - aip->submode_start_time) > i2f(30) || */ aip->submode_parm0 == SM_SS_DONE ) {
8364 // set target objnum = -1
8365 set_target_objnum(aip, -1);
8367 // set submode to attack
8368 aip->submode = SM_ATTACK;
8369 aip->submode_start_time = Missiontime;
8370 aip->last_attack_time = Missiontime;
8374 case SM_ATTACK_FOREVER: // Engines blown, just attack.
8379 aip->submode = SM_ATTACK;
8380 aip->last_attack_time = Missiontime;
8382 aip->submode_start_time = Missiontime;
8386 // Maybe fire primary weapon and update time_enemy_in_range
8388 //nprintf(("AI", "time_enemy_in_range = %7.3f, dot = %7.3f\n", aip->time_enemy_in_range, dot_to_enemy));
8390 if (aip->mode != AIM_EVADE) {
8391 if (dot_to_enemy > 0.95f - 0.5f * En_objp->radius/SDL_max(1.0f, En_objp->radius + dist_to_enemy)) {
8392 aip->time_enemy_in_range += flFrametime;
8394 // Chance of hitting ship is based on dot product of firing ship's forward vector with vector to ship
8395 // and also the size of the target relative to distance to target.
8396 if (dot_to_enemy > SDL_max(0.5f, 0.90f + aip->ai_accuracy/10.0f - En_objp->radius/SDL_max(1.0f,dist_to_enemy))) {
8401 temp_shipp = &Ships[Pl_objp->instance];
8402 tswp = &temp_shipp->weapons;
8403 if ( tswp->num_primary_banks > 0 ) {
8405 SDL_assert(tswp->current_primary_bank < tswp->num_primary_banks);
8406 weapon_info *pwip = &Weapon_info[tswp->primary_bank_weapons[tswp->current_primary_bank]];
8408 // Less likely to fire if far away and moving.
8409 scale = pwip->max_speed/(En_objp->phys_info.speed + pwip->max_speed);
8411 scale = (scale - 0.6f) * 1.5f;
8414 if (dist_to_enemy < pwip->max_speed * (1.0f + scale)) {
8415 ai_fire_primary_weapon(Pl_objp);
8418 // Don't fire secondaries at a protected ship.
8419 if (!(En_objp->flags & OF_PROTECTED)) {
8420 ai_choose_secondary_weapon(Pl_objp, aip, En_objp);
8421 int current_bank = tswp->current_secondary_bank;
8423 if (current_bank > -1) {
8424 weapon_info *swip = &Weapon_info[tswp->secondary_bank_weapons[current_bank]];
8426 if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8427 if (timestamp_until(swp->next_secondary_fire_stamp[current_bank]) > swip->fire_wait*1000.0f) {
8428 swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (swip->fire_wait*1000.0f));
8432 if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
8435 if (swip->wi_flags & WIF_BOMB)
8436 firing_range = swip->max_speed * swip->lifetime * 0.75f;
8438 firing_range = swip->max_speed * swip->lifetime * (Game_skill_level + 1 + aip->ai_class/2)/NUM_SKILL_LEVELS;
8440 // reduce firing range in nebula
8441 extern int Nebula_sec_range;
8442 if ((The_mission.flags & MISSION_FLAG_FULLNEB) && Nebula_sec_range) {
8443 firing_range *= 0.8f;
8446 // If firing a spawn weapon, distance doesn't matter.
8449 if (swip->wi_flags & WIF_SPAWN) {
8452 count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(Pl_objp)), &Pl_objp->pos, 1000.0f);
8456 else if (count >= 1) {
8457 float hull_percent = Pl_objp->hull_strength/sip->initial_hull_strength;
8459 if (hull_percent < 0.01f)
8460 hull_percent = 0.01f;
8462 if (frand() < 0.25f/(30.0f*hull_percent) * count) // With timestamp below, this means could fire in 30 seconds if one enemy.
8467 if (spawn_fire || (dist_to_enemy < firing_range)) {
8468 if (ai_fire_secondary_weapon(Pl_objp)) {
8469 // Only if weapon was fired do we specify time until next fire. If not fired, done in ai_fire_secondary...
8472 if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8473 t = swip->fire_wait;
8475 t = set_secondary_fire_delay(aip, temp_shipp, swip);
8477 //nprintf(("AI", "Next secondary to be fired in %7.3f seconds.\n", t));
8478 swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (t*1000.0f));
8481 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
8489 aip->time_enemy_in_range *= (1.0f - flFrametime);
8492 aip->time_enemy_in_range *= (1.0f - flFrametime);
8496 // Make the object *objp move so that the point *dp on the object moves towards the point *vp
8498 void dock_move_towards_point(object *objp, vector *dp, vector *vp, float speed_scale, float other_obj_speed = 0.0f)
8500 physics_info *pi = &objp->phys_info;
8501 float dist; // dist to goal
8502 vector v2g; // vector to goal
8503 vector abs_pnt; // location of dock point, ie objp->pos + db
8506 abs_pnt = objp->pos;
8508 vm_vec_add(&abs_pnt, &objp->pos, dp);
8510 dist = vm_vec_dist_quick(vp, &abs_pnt);
8514 dist = vm_vec_normalized_dir(&v2g, vp, &abs_pnt);
8515 speed = fl_sqrt(dist) * speed_scale;
8516 if (other_obj_speed < MAX_REPAIR_SPEED*0.75f)
8517 speed += other_obj_speed;
8519 speed += MAX_REPAIR_SPEED*0.75f;
8521 vm_vec_copy_scale(&pi->desired_vel, &v2g, speed);
8523 vm_vec_zero(&pi->desired_vel);
8526 // Set the orientation in the global reference frame for an object to attain
8527 // to dock with another object.
8528 // *dom resultant global matrix
8529 // *db_dest pointer to destination docking bay information
8530 // *db_src pointer to source docking bay information
8531 // *dorient pointer to global orientation of docking bay (ie, the dockee object's orient)
8532 // *sorient pointer to global orientation of docker
8533 void set_goal_dock_orient(matrix *dom, dock_bay *db_dest, dock_bay *db_src, matrix *dorient, matrix *sorient)
8538 // Compute the global orientation of the docker's (dest) docking bay.
8539 fvec = db_dest->norm[0];
8540 vm_vec_negate(&fvec);
8542 vm_vec_normalized_dir(&uvec, &db_dest->pnt[1], &db_dest->pnt[0]);
8543 vm_vector_2_matrix(&m1, &fvec, &uvec, NULL);
8545 vm_matrix_x_matrix(&m3, dorient, &m1);
8547 // Compute the matrix given by the source docking bay.
8548 // Pre-multiply the orientation of the source object (sorient) by the transpose
8549 // of the docking bay's orientation, ie unrotate the source object's matrix.
8550 fvec = db_src->norm[0];
8551 vm_vec_normalized_dir(&uvec, &db_src->pnt[1], &db_src->pnt[0]);
8552 vm_vector_2_matrix(&m2, &fvec, &uvec, NULL);
8555 vm_matrix_x_matrix(dom, &m3, &m2);
8558 #define DOCK_BACKUP_RETURN_VAL 99999.9f
8560 // Make objp dock with dobjp
8561 // Returns distance to goal, defined as distance between corresponding dock points, plus 10.0f * rotational velocity vector (DOA_DOCK only)
8562 // DOA_APPROACH means approach point aip->path_cur
8563 // DOA_DOCK means dock
8564 // DOA_UNDOCK_1 means undock, moving to point nearest dock bay
8565 // DOA_UNDOCK_2 means undock, moving to point nearest dock bay and facing away from ship
8566 // DOA_DOCK_STAY means rigidly maintain position in dock bay.
8567 float dock_orient_and_approach(object *objp, object *dobjp, int dock_mode)
8569 ship_info *sip0, *sip1;
8570 polymodel *pm0, *pm1;
8573 vector goal_point, docker_point;
8574 float fdist = UNINITIALIZED_VALUE;
8575 int docker_index, dockee_index; // index into docking_bays[] array for objects docking
8576 // docker is Pl_objp -- dockee is dobjp
8577 aip = &Ai_info[Ships[objp->instance].ai_index];
8579 // If dockee has moved much, then path will be recreated.
8580 // Might need to change state if moved too far.
8581 if ((dock_mode != DOA_DOCK_STAY) && (dock_mode != DOA_DOCK)) {
8582 if (maybe_recreate_path(objp, &Ai_info[Ships[objp->instance].ai_index], 0) > 5.0f) {
8583 /* if (dock_mode == DOA_APPROACH) {
8584 return DOCK_BACKUP_RETURN_VAL;
8585 } else if (dock_mode == DOA_DOCK) {
8586 return DOCK_BACKUP_RETURN_VAL;
8591 objp->phys_info.forward_thrust = 0.0f; // Kill thrust so we don't have a sputtering thruster.
8593 sip0 = &Ship_info[Ships[objp->instance].ship_info_index];
8594 sip1 = &Ship_info[Ships[dobjp->instance].ship_info_index];
8595 pm0 = model_get( sip0->modelnum );
8596 pm1 = model_get( sip1->modelnum );
8598 docker_index = aip->dock_index;
8599 dockee_index = aip->dockee_index;
8601 SDL_assert( docker_index >= 0 );
8602 SDL_assert( dockee_index >= 0 );
8604 SDL_assert(pm0->docking_bays[docker_index].num_slots == 2);
8605 SDL_assert(pm1->docking_bays[dockee_index].num_slots == 2);
8607 float speed_scale = 1.0f;
8608 if (sip0->flags & SIF_SUPPORT) {
8612 switch (dock_mode) {
8615 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8619 // Compute the desired global orientation matrix for the docker's station.
8620 // That is, the normal vector of the docking station must be the same as the
8621 // forward vector and the vector between its two points must be the uvec.
8622 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8624 // Compute new orientation matrix and update rotational velocity.
8625 vector w_in, w_out, vel_limit, acc_limit;
8626 float tdist, mdist, ss1;
8628 w_in = objp->phys_info.rotvel;
8629 vel_limit = objp->phys_info.max_rotvel;
8630 vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8632 if (sip0->flags & SIF_SUPPORT)
8633 vm_vec_scale(&acc_limit, 2.0f);
8635 // 1 at end of line prevent overshoot
8636 vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit, 1);
8637 objp->phys_info.rotvel = w_out;
8640 // Translate towards goal and note distance to goal.
8641 goal_point = Path_points[aip->path_cur].pos;
8642 mdist = ai_matrix_dist(&objp->orient, &dom);
8643 tdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8645 // If translation is badly lagging rotation, speed up translation.
8647 ss1 = tdist/(10.0f * mdist);
8653 // nprintf(("AI", "speed scale = %7.3f\n", ss1));
8654 speed_scale *= 1.0f + ss1;
8656 dock_move_towards_point(objp, NULL, &goal_point, speed_scale, dobjp->phys_info.speed);
8658 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8660 // Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8661 // nprintf(("AI", "matrix dist = %7.3f, threshold = %7.3f\n", mdist, 2*flFrametime));
8662 fdist += 2.0f * mdist;
8667 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8671 // Compute the desired global orientation matrix for the docker's station.
8672 // That is, the normal vector of the docking station must be the same as the
8673 // forward vector and the vector between its two points must be the uvec.
8674 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8676 // Compute distance between dock bay points.
8677 vector db0, db1, db2, db3;
8679 vm_vec_unrotate(&db0, &pm0->docking_bays[docker_index].pnt[0], &objp->orient);
8680 vm_vec_add2(&db0, &objp->pos);
8682 vm_vec_unrotate(&db1, &pm0->docking_bays[docker_index].pnt[1], &objp->orient);
8683 vm_vec_add2(&db1, &objp->pos);
8685 vm_vec_unrotate(&db2, &pm1->docking_bays[dockee_index].pnt[0], &dobjp->orient);
8686 vm_vec_add2(&db2, &dobjp->pos);
8688 vm_vec_unrotate(&db3, &pm1->docking_bays[dockee_index].pnt[1], &dobjp->orient);
8689 vm_vec_add2(&db3, &dobjp->pos);
8691 vm_vec_avg(&goal_point, &db2, &db3);
8693 vm_vec_avg(&docker_point, &db0, &db1);
8694 vm_vec_sub2(&docker_point, &objp->pos);
8696 if (dock_mode == DOA_DOCK) {
8698 vector w_in, w_out, vel_limit, acc_limit;
8700 fdist = vm_vec_dist_quick(vm_vec_avg(&t1, &db0, &db1), vm_vec_avg(&t2, &db2, &db3));
8702 // Compute new orientation matrix and update rotational velocity.
8703 w_in = objp->phys_info.rotvel;
8704 vel_limit = objp->phys_info.max_rotvel;
8705 vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8707 if (sip0->flags & SIF_SUPPORT)
8708 vm_vec_scale(&acc_limit, 2.0f);
8710 vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit);
8711 objp->phys_info.rotvel = w_out;
8714 // Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8715 fdist += 10.0f * vm_vec_mag_quick(&w_out);
8717 dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale, dobjp->phys_info.speed);
8719 SDL_assert(dock_mode == DOA_DOCK_STAY);
8722 vm_vec_sub(&temp, &goal_point, &docker_point);
8723 vm_vec_sub(&objp->pos, &goal_point, &docker_point);
8727 case DOA_UNDOCK_1: {
8728 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8733 // Move to point on dock path nearest to dock station.
8734 SDL_assert(aip->path_length >= 2);
8735 goal_point = Path_points[aip->path_start + aip->path_length-2].pos;
8737 vm_vec_zero(&docker_point);
8738 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8740 dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale);
8745 case DOA_UNDOCK_2: {
8747 // Move to point on dock path nearest to dock station and orient away from big ship.
8750 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8754 SDL_assert(aip->path_length >= 2);
8755 // if (aip->path_length >= 3)
8756 // desired_index = aip->path_length-3;
8758 desired_index = aip->path_length-2;
8760 goal_point = Path_points[aip->path_start + desired_index].pos;
8762 dock_move_towards_point(objp, NULL, &goal_point, speed_scale);
8764 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8767 case DOA_UNDOCK_3: {
8768 float dist, goal_dist;
8771 goal_dist = objp->radius + dobjp->radius + 25.0f;
8773 dist = vm_vec_normalized_dir(&away_vec, &objp->pos, &dobjp->pos);
8774 vm_vec_scale_add(&goal_point, &dobjp->pos, &away_vec, goal_dist);
8775 if (vm_vec_dist_quick(&goal_point, &dobjp->pos) < vm_vec_dist_quick(&objp->pos, &dobjp->pos))
8779 float turn_time = Ship_info[Ships[objp->instance].ship_info_index].srotation_time;
8780 ai_turn_towards_vector(&goal_point, objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
8782 dot = vm_vec_dot(&objp->orient.v.fvec, &away_vec);
8786 if (dist > goal_dist/2)
8787 accel *= 1.2f - 0.5f*goal_dist/dist;
8789 accelerate_ship(aip, accel);
8790 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8798 // For debug purposes, compute global orientation of both dock vectors and show
8799 // how close they are.
8802 vm_vec_unrotate(&d0, &pm0->docking_bays[docker_index].norm[0], &objp->orient);
8803 vm_vec_unrotate(&d1, &pm1->docking_bays[dockee_index].norm[0], &dobjp->orient);
8805 //nprintf(("AI", "or/app: dist = %7.3f/%7.3f, dot = %7.3f, global dot = %7.3f\n",
8806 // vm_vec_dist_quick(&goal_point, &objp->pos), fdist,
8807 // vm_vec_dot(&objp->orient.v.fvec, &dom.v.fvec),
8808 // vm_vec_dot(&d0, &d1)));
8811 // -- Note, A lot of callers don't care about fdist, so OK to return ERROR value: SDL_assert(fdist != UNINITIALIZED_VALUE);
8816 void debug_find_guard_object()
8818 ship *shipp = &Ships[Pl_objp->instance];
8821 for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
8822 if ((Pl_objp != objp) && (objp->type == OBJ_SHIP)) {
8823 if (objp->instance != -1) {
8824 if (Ships[objp->instance].team == shipp->team) {
8825 // nprintf(("AI", "Setting guard object for %s to %s\n", shipp->ship_name, Ships[objp->instance].ship_name));
8826 ai_set_guard_object(Pl_objp, objp);
8834 // Given an object number, return the number of ships attacking it.
8835 int num_ships_attacking(int objnum)
8841 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8842 objp = &Objects[so->objnum];
8843 if (objp->instance != -1) {
8845 aip = &Ai_info[Ships[objp->instance].ai_index];
8847 if ((aip->mode == AIM_CHASE) && (aip->target_objnum == objnum))
8848 if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team)
8856 // For all objects attacking object #objnum, remove the one that is farthest away.
8857 // Do this by resuming previous behavior, if any. If not, set target_objnum to -1.
8858 void remove_farthest_attacker(int objnum)
8860 object *objp, *objp2, *farthest_objp;
8862 float farthest_dist;
8864 objp2 = &Objects[objnum];
8866 farthest_dist = 9999999.9f;
8867 farthest_objp = NULL;
8869 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8870 objp = &Objects[so->objnum];
8871 if ( !(objp->flags & OF_PLAYER_SHIP)) {
8872 if (objp->instance != -1) {
8875 aip2 = &Ai_info[Ships[objp->instance].ai_index];
8877 if ((aip2->mode == AIM_CHASE) && (aip2->target_objnum == objnum)) {
8878 if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team) {
8881 dist = vm_vec_dist_quick(&objp->pos, &objp2->pos);
8882 if (dist < farthest_dist) {
8883 farthest_dist = dist;
8884 farthest_objp = objp;
8892 if (farthest_objp != NULL) {
8894 SDL_assert(farthest_objp->type == OBJ_SHIP);
8895 SDL_assert((farthest_objp->instance > -1) && (farthest_objp->instance < MAX_SHIPS));
8896 SDL_assert(Ships[farthest_objp->instance].ai_index > -1);
8898 aip = &Ai_info[Ships[farthest_objp->instance].ai_index];
8900 if (!maybe_resume_previous_mode(Pl_objp, aip)) {
8901 // If already ignoring something under player's orders, don't ignore current target.
8902 if ((aip->ignore_objnum == UNUSED_OBJNUM) || (aip->ai_flags & AIF_TEMPORARY_IGNORE)) {
8903 aip->ignore_objnum = aip->target_objnum;
8904 aip->ignore_signature = Objects[aip->target_objnum].signature;
8905 aip->ai_flags |= AIF_TEMPORARY_IGNORE;
8906 aip->ignore_expire_timestamp = timestamp(((myrand() % 10) + 20) * 1000); // OK to attack again in 20 to 24 seconds.
8908 aip->target_objnum = -1;
8909 ai_do_default_behavior(farthest_objp);
8914 // Maybe limit the number of attackers on attack_objnum. For now, only limit attackers
8915 // in attacked_objnum is the player
8916 // input: attacked_objnum => object index for ship we want to limit attacks on
8918 // exit: 1 => num attackers exceeds maximum, abort
8919 // 0 => removed the farthest attacker
8920 // -1 => nothing was done
8921 int ai_maybe_limit_attackers(int attacked_objnum)
8925 // limit the number of ships attacking the _player_ only
8926 // if ( attacked_objnum == OBJ_INDEX(Player_obj) ) {
8927 if ( Objects[attacked_objnum].flags & OF_PLAYER_SHIP) {
8929 num_attacking = num_ships_attacking(attacked_objnum);
8931 if (num_attacking == Skill_level_max_attackers[Game_skill_level]) {
8932 remove_farthest_attacker(attacked_objnum);
8934 } else if (num_attacking > Skill_level_max_attackers[Game_skill_level]) {
8937 //nprintf(("AI", "Num attacking player = %i\n", num_attacking));
8943 // Object being guarded by object *guard_objp was hit by object *hitter_objp
8944 void guard_object_was_hit(object *guard_objp, object *hitter_objp)
8949 aip = &Ai_info[Ships[guard_objp->instance].ai_index];
8951 if (guard_objp == hitter_objp) {
8952 // Int3(); // Bogus! Who tried to get me to attack myself! Trace out and fix!
8956 if (guard_objp->type == OBJ_GHOST || hitter_objp->type == OBJ_GHOST)
8959 if (aip->ai_flags & AIF_NO_DYNAMIC) // Not allowed to pursue dynamic goals. So, why are we guarding?
8962 SDL_assert( (hitter_objp->type == OBJ_SHIP) || (hitter_objp->type == OBJ_ASTEROID) || (hitter_objp->type == OBJ_WEAPON) );
8964 hitter_objnum = OBJ_INDEX(hitter_objp);
8966 if ( hitter_objp->type == OBJ_SHIP ) {
8967 // If the hitter object is the ignore object, don't attack it.
8968 if (is_ignore_object(aip, hitter_objp-Objects))
8971 // If hitter is on same team as me, don't attack him.
8972 if (Ships[guard_objp->instance].team == Ships[hitter_objp->instance].team)
8975 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
8976 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
8980 // dont attack if you can't see him
8981 if ( awacs_get_level(hitter_objp, &Ships[aip->shipnum], 1) < 1 ) {
8982 // if he's a stealth and visible, but not targetable, ok to attack.
8983 if ( is_object_stealth_ship(hitter_objp) ) {
8984 if ( ai_is_stealth_visible(guard_objp, hitter_objp) != STEALTH_VISIBLE ) {
8991 if (aip->target_objnum == -1) {
8992 aip->ok_to_target_timestamp = timestamp(0);
8995 if ((aip->submode == AIS_GUARD_PATROL) || (aip->submode == AIS_GUARD_STATIC)) {
8997 if ( hitter_objp->type == OBJ_SHIP ) {
8998 if (!(Ship_info[Ships[guard_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
9002 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9003 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9008 if (aip->target_objnum != hitter_objnum) {
9009 aip->aspect_locked_time = 0.0f;
9012 aip->ok_to_target_timestamp = timestamp(0);
9014 set_target_objnum(aip, hitter_objnum);
9015 //if (aip->target_objnum == -1) nprintf(("AI", "Frame %i: Attacking NONE\n",Framecount)); else nprintf(("AI", "Frame %i: Attacking %s\n", Framecount, Ships[Objects[aip->target_objnum].instance].ship_name));
9016 aip->previous_mode = AIM_GUARD;
9017 aip->previous_submode = aip->submode;
9018 aip->mode = AIM_CHASE;
9019 aip->submode = SM_ATTACK;
9020 aip->submode_start_time = Missiontime;
9021 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9022 } else if (aip->previous_mode == AIM_GUARD) {
9023 if (aip->target_objnum == -1) {
9025 if ( hitter_objp->type == OBJ_SHIP ) {
9026 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9027 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9032 set_target_objnum(aip, hitter_objnum);
9033 //if (aip->target_objnum == -1) nprintf(("AI", "Frame %i: Attacking NONE\n",Framecount)); else nprintf(("AI", "Frame %i: Attacking %s\n", Framecount, Ships[Objects[aip->target_objnum].instance].ship_name));
9034 aip->mode = AIM_CHASE;
9035 aip->submode = SM_ATTACK;
9036 aip->submode_start_time = Missiontime;
9037 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9039 int num_attacking_cur, num_attacking_new;
9041 num_attacking_cur = num_ships_attacking(aip->target_objnum);
9042 if (num_attacking_cur > 1) {
9043 num_attacking_new = num_ships_attacking(hitter_objnum);
9045 if (num_attacking_new < num_attacking_cur) {
9047 if ( hitter_objp->type == OBJ_SHIP ) {
9048 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9049 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9053 set_target_objnum(aip, hitter_objp-Objects);
9054 //if (aip->target_objnum == -1) nprintf(("AI", "Frame %i: Attacking NONE\n",Framecount)); else nprintf(("AI", "Frame %i: Attacking %s\n", Framecount, Ships[Objects[aip->target_objnum].instance].ship_name));
9055 aip->mode = AIM_CHASE;
9056 aip->submode = SM_ATTACK;
9057 aip->submode_start_time = Missiontime;
9058 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9065 // Ship object *hit_objp was hit by ship object *hitter_objp.
9066 // See if anyone is guarding hit_objp and, if so, do something useful.
9067 void maybe_update_guard_object(object *hit_objp, object *hitter_objp)
9072 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9073 objp = &Objects[so->objnum];
9074 if (objp->instance != -1) {
9076 aip = &Ai_info[Ships[objp->instance].ai_index];
9078 if ((aip->mode == AIM_GUARD) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
9079 if (aip->guard_objnum == hit_objp-Objects) {
9080 guard_object_was_hit(objp, hitter_objp);
9081 } else if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[hit_objp->instance].ai_index].wing)) {
9082 guard_object_was_hit(objp, hitter_objp);
9089 // Scan missile list looking for bombs homing on guarded_objp
9090 // return 1 if bomb is found (and targeted by guarding_objp), otherwise return 0
9091 int ai_guard_find_nearby_bomb(object *guarding_objp, object *guarded_objp)
9094 object *bomb_objp, *closest_bomb_objp=NULL;
9095 float dist, dist_to_guarding_obj,closest_dist_to_guarding_obj=999999.0f;
9099 for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
9100 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
9101 bomb_objp = &Objects[mo->objnum];
9103 wp = &Weapons[bomb_objp->instance];
9104 wip = &Weapon_info[wp->weapon_info_index];
9106 if ( !(wip->wi_flags & WIF_BOMB) ) {
9110 if ( wp->homing_object != guarded_objp ) {
9114 dist = vm_vec_dist_quick(&bomb_objp->pos, &guarded_objp->pos);
9116 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9117 dist_to_guarding_obj = vm_vec_dist_quick(&bomb_objp->pos, &guarding_objp->pos);
9118 if ( dist_to_guarding_obj < closest_dist_to_guarding_obj ) {
9119 closest_dist_to_guarding_obj = dist_to_guarding_obj;
9120 closest_bomb_objp = bomb_objp;
9125 if ( closest_bomb_objp ) {
9126 guard_object_was_hit(guarding_objp, closest_bomb_objp);
9133 // Scan enemy ships and see if one is near enough to guard object to be pursued.
9134 void ai_guard_find_nearby_ship(object *guarding_objp, object *guarded_objp)
9136 ship *guarding_shipp = &Ships[guarding_objp->instance];
9137 ai_info *guarding_aip = &Ai_info[guarding_shipp->ai_index];
9142 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9143 enemy_objp = &Objects[so->objnum];
9145 if (enemy_objp->instance < 0) {
9149 ship *eshipp = &Ships[enemy_objp->instance];
9151 // Don't attack a cargo container or other harmless ships
9152 if (!(Ship_info[eshipp->ship_info_index].flags & SIF_HARMLESS)) {
9153 if (guarding_shipp->team != eshipp->team) {
9154 dist = vm_vec_dist_quick(&enemy_objp->pos, &guarded_objp->pos);
9155 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9156 guard_object_was_hit(guarding_objp, enemy_objp);
9157 } else if ((dist < 3000.0f) && (Ai_info[eshipp->ai_index].target_objnum == guarding_aip->guard_objnum)) {
9158 //nprintf(("AI", "%i: Enemy %s targeting guard object (%s), %s will attack!!\n", Framecount, eshipp->ship_name, Ships[Objects[guarding_aip->guard_objnum].instance].ship_name, guarding_shipp->ship_name));
9159 guard_object_was_hit(guarding_objp, enemy_objp);
9166 // Scan for nearby asteroids. Favor asteroids which have their collide_objnum set to that of the
9167 // guarded ship. Also, favor asteroids that are closer to the guarding ship, since it looks cooler
9168 // when a ship blows up an asteroid then goes after the pieces that break off.
9169 void ai_guard_find_nearby_asteroid(object *guarding_objp, object *guarded_objp)
9173 object *closest_asteroid_objp=NULL, *danger_asteroid_objp=NULL, *asteroid_objp;
9174 float dist_to_self, closest_danger_asteroid_dist=999999.0f, closest_asteroid_dist=999999.0f;
9176 for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp != END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
9177 if ( asteroid_objp->type == OBJ_ASTEROID ) {
9178 // Attack asteroid if near guarded ship
9179 dist = vm_vec_dist_quick(&asteroid_objp->pos, &guarded_objp->pos);
9180 if ( dist < (MAX_GUARD_DIST + guarded_objp->radius)*2) {
9181 dist_to_self = vm_vec_dist_quick(&asteroid_objp->pos, &guarding_objp->pos);
9182 if ( OBJ_INDEX(guarded_objp) == asteroid_collide_objnum(asteroid_objp) ) {
9183 if( dist_to_self < closest_danger_asteroid_dist ) {
9184 danger_asteroid_objp=asteroid_objp;
9185 closest_danger_asteroid_dist=dist_to_self;
9188 if ( dist_to_self < closest_asteroid_dist ) {
9189 // only attack if moving slower than own max speed
9190 if ( vm_vec_mag_quick(&asteroid_objp->phys_info.vel) < guarding_objp->phys_info.max_vel.xyz.z ) {
9191 closest_asteroid_dist = dist_to_self;
9192 closest_asteroid_objp = asteroid_objp;
9199 if ( danger_asteroid_objp ) {
9200 guard_object_was_hit(guarding_objp, danger_asteroid_objp);
9201 } else if ( closest_asteroid_objp ) {
9202 guard_object_was_hit(guarding_objp, closest_asteroid_objp);
9206 // Scan potential harmful objects and see if one is near enough to guard object to be pursued.
9207 void ai_guard_find_nearby_object()
9209 ship *shipp = &Ships[Pl_objp->instance];
9210 ai_info *aip = &Ai_info[shipp->ai_index];
9214 guardobjp = &Objects[aip->guard_objnum];
9216 // highest priority is a bomb fired on guarded ship
9217 bomb_found = ai_guard_find_nearby_bomb(Pl_objp, guardobjp);
9219 if ( !bomb_found ) {
9220 // check for ships if there are no bombs fired at guarded ship
9221 ai_guard_find_nearby_ship(Pl_objp, guardobjp);
9223 // if not attacking anything, go for asteroid close to guarded ship
9224 if ( (aip->target_objnum == -1) && asteroid_count() ) {
9225 ai_guard_find_nearby_asteroid(Pl_objp, guardobjp);
9230 // gets closest point on extended axis of cylinder, r_vec, and radius of cylinder
9231 // returns z of axis_point in cyl_objp reference frame
9232 float get_cylinder_points(object *other_objp, object *cyl_objp, vector *axis_pt, vector *r_vec, float *radius)
9234 SDL_assert(other_objp->type == OBJ_SHIP);
9235 SDL_assert(cyl_objp->type == OBJ_SHIP);
9237 // get radius of cylinder
9238 polymodel *pm = model_get(Ships[cyl_objp->instance].modelnum);
9240 tempx = SDL_max(-pm->mins.xyz.x, pm->maxs.xyz.x);
9241 tempy = SDL_max(-pm->mins.xyz.y, pm->maxs.xyz.y);
9242 *radius = SDL_max(tempx, tempy);
9244 // get vec from cylinder to other_obj
9246 vm_vec_sub(&r_sph, &other_objp->pos, &cyl_objp->pos);
9248 // get point on axis and on cylinder
9249 // extended_cylinder_z is along extended cylinder
9250 // cylinder_z is capped within cylinder
9251 float extended_cylinder_z = vm_vec_dotprod(&r_sph, &cyl_objp->orient.v.fvec);
9253 // get pt on axis of extended cylinder
9254 vm_vec_scale_add(axis_pt, &cyl_objp->pos, &cyl_objp->orient.v.fvec, extended_cylinder_z);
9256 // get r_vec (pos - axis_pt) normalized
9257 vm_vec_normalized_dir(r_vec, &other_objp->pos, axis_pt);
9259 return extended_cylinder_z;
9262 // handler for guard behavior when guarding BIG ships
9263 // When someone has attacked guarded ship, then attack that ship.
9264 // To attack another ship, switch out of guard mode into chase mode.
9268 ship *shipp = &Ships[Pl_objp->instance];
9269 ai_info *aip = &Ai_info[shipp->ai_index];
9272 // sanity checks already done in ai_guard()
9273 guard_objp = &Objects[aip->guard_objnum];
9275 switch (aip->submode) {
9276 case AIS_GUARD_STATIC:
9277 case AIS_GUARD_PATROL:
9279 vector axis_pt, r_vec, theta_vec;
9280 float radius, extended_z;
9282 // get random [0 to 1] based on OBJNUM
9283 float objval = static_randf(Pl_objp-Objects);
9285 // get position relative to cylinder of guard_objp
9286 extended_z = get_cylinder_points(Pl_objp, guard_objp, &axis_pt, &r_vec, &radius);
9287 vm_vec_crossprod(&theta_vec, &guard_objp->orient.v.fvec, &r_vec);
9289 // half ships circle each way
9290 if (objval > 0.5f) {
9291 vm_vec_negate(&theta_vec);
9294 float min_guard_dist = radius + Pl_objp->radius + 50.0f;
9295 float desired_guard_dist = min_guard_dist + 0.5f * ((1.0f + objval) * MAX_GUARD_DIST);
9296 float max_guard_dist = min_guard_dist + 1.0f * ((1.0f + objval) * MAX_GUARD_DIST);
9299 float min_z, max_z, length;
9300 polymodel *pm = model_get(Ships[guard_objp->instance].modelnum);
9301 min_z = pm->mins.xyz.z;
9302 max_z = pm->maxs.xyz.z;
9303 length = max_z - min_z;
9306 // how often to choose new desired_z
9307 // 1*(64) sec < 2000, 2*(64) < 2-4000 3*(64) > 4-8000, etc (Missiontime >> 22 is 64 sec intervals)
9308 int time_choose = int(floor(log(length * 0.001) / log(2.0)));
9309 float desired_z = min_z + length * static_randf( (Pl_objp-Objects) ^ (Missiontime >> (22 + time_choose)) );
9311 // get r from guard_ship
9312 float cur_guard_rad = vm_vec_dist(&Pl_objp->pos, &axis_pt);
9314 // is ship within extents of cylinder of ship it is guarding
9315 int inside = (extended_z > min_z) && (extended_z < min_z + length);
9318 // maybe go into orbit mode
9319 if (cur_guard_rad < max_guard_dist) {
9320 if ( cur_guard_rad > min_guard_dist ) {
9323 vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, desired_guard_dist);
9324 vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9326 // move to where I can orbit
9327 if (extended_z < min_z) {
9328 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9330 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9332 vm_vec_scale_add2(&goal_pt, &r_vec, desired_guard_dist);
9333 vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9336 // too close for orbit mode
9338 // inside (fly straight out and return circle)
9339 vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, max_guard_dist);
9341 // outside (fly to edge and circle)
9342 if (extended_z < min_z) {
9343 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9345 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9347 vm_vec_scale_add2(&goal_pt, &r_vec, max_guard_dist);
9348 vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9352 if (Pl_objp->phys_info.fspeed > 0) {
9353 // modify goal_pt to take account moving guard objp
9354 float dist = vm_vec_dist_quick(&Pl_objp->pos, &goal_pt);
9355 float time = dist / Pl_objp->phys_info.fspeed;
9356 vm_vec_scale_add2(&goal_pt, &guard_objp->phys_info.vel, time);
9358 // now modify to move to desired z (at a max of 20 m/s)
9359 float delta_z = desired_z - extended_z;
9360 float v_z = delta_z * 0.2f;
9363 } else if (v_z > 20) {
9367 vm_vec_scale_add2(&goal_pt, &guard_objp->orient.v.fvec, v_z*time);
9371 // cast vector to center of guard_ship adjusted by desired_z
9372 float delta_z = desired_z - extended_z;
9373 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, delta_z);
9376 // try not to bump into things along the way
9377 if ( (cur_guard_rad > max_guard_dist) || (extended_z < min_z) || (extended_z > max_z) ) {
9378 if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9382 if (avoid_player(Pl_objp, &goal_pt)) {
9386 if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9391 // got the point, now let's go there
9392 ai_turn_towards_vector(&goal_pt, Pl_objp, flFrametime, Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time, NULL, NULL, 0.0f, 0);
9393 // aip->goal_point = goal_pt;
9394 accelerate_ship(aip, 1.0f);
9396 // Periodically, scan for a nearby ship to attack.
9397 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9398 ai_guard_find_nearby_object();
9403 case AIS_GUARD_ATTACK:
9404 // The guarded ship has been attacked. Do something useful!
9409 //Int3(); // Illegal submode for Guard mode.
9410 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9411 aip->submode = AIS_GUARD_PATROL;
9416 // Main handler for guard behavior.
9417 // When someone has attacked guarded ship, then attack that ship.
9418 // To attack another ship, switch out of guard mode into chase mode.
9421 ship *shipp = &Ships[Pl_objp->instance];
9422 ai_info *aip = &Ai_info[shipp->ai_index];
9424 float dist_to_guardobj;
9425 vector vec_to_guardobj;
9427 /* // Debug code, find an object to guard.
9428 int finding_guard_objnum = 0; // Debug code, to see if body of "if" below gets executed.
9429 if (aip->guard_objnum == -1) {
9430 finding_guard_objnum = 1;
9431 debug_find_guard_object();
9432 if (aip->guard_objnum == -1)
9436 if (aip->guard_objnum == -1) {
9437 aip->mode = AIM_NONE;
9441 SDL_assert(aip->guard_objnum != -1);
9443 guard_objp = &Objects[aip->guard_objnum];
9445 if (guard_objp == Pl_objp) {
9446 Int3(); // This seems illegal. Why is a ship guarding itself?
9447 aip->guard_objnum = -1;
9451 // check that I have someone to guard
9452 if (guard_objp->instance == -1) {
9456 // Not sure whether this should be impossible, or a reasonable cleanup condition.
9457 // For now (3/31/97), it's getting trapped by an SDL_assert, so clean it up.
9458 if (guard_objp->type != OBJ_SHIP) {
9459 aip->guard_objnum = -1;
9463 // handler for gurad object with BIG radius
9464 if (guard_objp->radius > BIG_GUARD_RADIUS) {
9472 float dist_to_goal_point, dot_to_goal_point, accel_scale;
9475 // get random [0 to 1] based on OBJNUM
9476 objval = static_randf(Pl_objp-Objects);
9478 switch (aip->submode) {
9479 case AIS_GUARD_STATIC:
9480 case AIS_GUARD_PATROL:
9482 dist_to_guardobj = vm_vec_normalized_dir(&vec_to_guardobj, &guard_objp->pos, &Pl_objp->pos);
9484 rel_vec = aip->guard_vec;
9485 vm_vec_add(&goal_point, &guard_objp->pos, &rel_vec);
9487 vm_vec_normalized_dir(&v2g, &goal_point, &Pl_objp->pos);
9488 dist_to_goal_point = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
9489 dot_to_goal_point = vm_vec_dot(&v2g, &Pl_objp->orient.v.fvec);
9490 accel_scale = (1.0f + dot_to_goal_point)/2.0f;
9492 // If far away, get closer
9493 if (dist_to_goal_point > MAX_GUARD_DIST + 1.5 * (Pl_objp->radius + guard_objp->radius)) {
9494 if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 5.0f)) {
9498 if (avoid_player(Pl_objp, &goal_point)) {
9502 // quite far away, so try to go straight to
9503 compute_desired_rvec(&rvec, &goal_point, &Pl_objp->pos);
9504 ai_turn_towards_vector(&goal_point, Pl_objp, flFrametime, Ship_info[shipp->ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, &rvec);
9506 accelerate_ship(aip, accel_scale * (0.25f + dist_to_goal_point/700.0f));
9508 if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 2.0f)) {
9512 // get max of guard_objp (1) normal speed (2) dock speed
9513 float speed = guard_objp->phys_info.speed;
9515 if (guard_objp->type == OBJ_SHIP) {
9516 ai_info *guard_aip = &Ai_info[Ships[guard_objp->instance].ai_index];
9518 if (guard_aip->dock_objnum != -1) {
9519 speed = SDL_max(speed, Objects[guard_aip->dock_objnum].phys_info.speed);
9523 // Deal with guarding a small object.
9524 // If going to guard_vec might cause a collision with guarded object, pick a new guard point.
9525 if (vm_vec_dot(&v2g, &vec_to_guardobj) > 0.8f) {
9526 if (dist_to_guardobj < dist_to_goal_point) {
9527 ai_set_guard_vec(Pl_objp, guard_objp); // OK to return here.
9532 if (speed > 10.0f) {
9533 // If goal ship is moving more than a tiny bit, don't orbit it, get near it.
9534 if (vm_vec_dist_quick(&goal_point, &Pl_objp->pos) > 40.0f) {
9535 if (vm_vec_dot(&Pl_objp->orient.v.fvec, &v2g) < 0.0f) {
9536 // Just slow down, don't turn.
9537 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point/10.0f);
9539 // Goal point is in front.
9541 // If close to goal point, don't change direction, just change speed.
9542 if (dist_to_goal_point > Pl_objp->radius + 10.0f) {
9543 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9546 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + (dist_to_goal_point-40.0f)/20.0f);
9549 if (dot_to_goal_point > 0.8f) {
9550 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9551 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + dist_to_goal_point*0.1f);
9553 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point*0.1f - 1.0f);
9556 // consider guard object STILL
9557 } else if (guard_objp->radius < 50.0f) {
9558 if (dist_to_goal_point > 15.0f) {
9559 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9560 set_accel_for_target_speed(Pl_objp, (dist_to_goal_point-10.0f)/2.0f);
9561 } else if (Pl_objp->phys_info.speed < 1.0f) {
9562 turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9565 } else if (dist_to_guardobj > MAX_GUARD_DIST + Pl_objp->radius + guard_objp->radius) {
9566 // Orbiting ship, too far away
9567 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.0f + objval/2) * guard_objp->radius);
9568 accelerate_ship(aip, (1.0f + dot)/2.0f);
9569 } else if (dist_to_guardobj < Pl_objp->radius + guard_objp->radius) {
9570 // Orbiting ship, got too close
9571 turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9572 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9573 change_acceleration(aip, 0.25f);
9575 accelerate_ship(aip, 0.5f + objval/4.0f);
9577 // Orbiting ship, about the right distance away.
9578 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.5f + objval/2.0f)*guard_objp->radius);
9579 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9580 set_accel_for_target_speed(Pl_objp, (0.5f * (1.0f + dot)) * (guard_objp->phys_info.speed + (dist_to_guardobj - guard_objp->radius - Pl_objp->radius)/10.0f));
9582 accelerate_ship(aip, 0.5f * (1.0f + dot) * (0.3f + objval/3.0f));
9586 // Periodically, scan for a nearby ship to attack.
9587 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9588 ai_guard_find_nearby_object();
9592 case AIS_GUARD_ATTACK:
9593 // The guarded ship has been attacked. Do something useful!
9598 //Int3(); // Illegal submode for Guard mode.
9599 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9600 aip->submode = AIS_GUARD_PATROL;
9606 // Return the object of the ship that the given object is docked
9607 // with. Currently, we know a ship is docked when his ai_mode is AIM_DOCK,
9608 // and his submode is AIS_DOCK_3. I suppose that this is likely to change though.
9609 // Also, the objnum that was is passed in may not be the object that actually
9610 // performed the docking maneuver. This code will account for that case.
9611 object *ai_find_docked_object( object *docker )
9615 // we are trying to find the dockee of docker. (Note that that these terms
9616 // are totally relative to what is passed in as a parameter.)
9618 // first thing to attempt is to check and see if this object is docked with something.
9619 SDL_assert( docker->type == OBJ_SHIP ); // this had probably better be a ship!!!
9620 aip = &Ai_info[Ships[docker->instance].ai_index];
9621 if ( !(aip->ai_flags & AIF_DOCKED) ) // flag not set if not docked with anything
9624 if ( aip->dock_objnum == -1 ) {
9625 Int3(); // mwa says this is wrong wrong wrong
9626 ai_do_objects_undocked_stuff( docker, NULL );
9630 return &Objects[aip->dock_objnum];
9635 // define for the points subtracted from score for a rearm started on a player.
9636 #define REPAIR_PENALTY 50
9639 // function to clean up ai flags, variables, and other interesting information
9640 // for a ship that was getting repaired. The how parameter is useful for multiplayer
9641 // only in that it tells us why the repaired ship is being cleaned up.
9642 void ai_do_objects_repairing_stuff( object *repaired_objp, object *repair_objp, int how )
9644 ai_info *aip, *repair_aip;
9647 SDL_assert( repaired_objp->type == OBJ_SHIP);
9648 aip = &Ai_info[Ships[repaired_objp->instance].ai_index];
9653 if(Game_mode & GM_MULTIPLAYER){
9654 p_index = multi_find_player_by_object(repaired_objp);
9657 if(repaired_objp == Player_obj){
9658 p_index = Player_num;
9663 case REPAIR_INFO_BEGIN:
9664 aip->ai_flags |= AIF_BEING_REPAIRED;
9665 aip->ai_flags &= ~AIF_AWAITING_REPAIR;
9666 stamp = timestamp(-1);
9668 // if this is a player ship, then subtract the repair penalty from this player's score
9669 if ( repaired_objp->flags & OF_PLAYER_SHIP ) {
9670 if ( !(Game_mode & GM_MULTIPLAYER) ) {
9671 Player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor()); // subtract the penalty
9676 // multiplayer game -- find the player, then subtract the score
9677 pnum = multi_find_player_by_object( repaired_objp );
9679 Net_players[pnum].player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());
9682 multi_team_maybe_add_score(-(int)(REPAIR_PENALTY * scoring_get_scale_factor()), Net_players[pnum].p_info.team);
9684 nprintf(("Network", "Couldn't find player for ship %s for repair penalty\n", Ships[repaired_objp->instance].ship_name));
9691 case REPAIR_INFO_BROKEN:
9692 aip->ai_flags &= ~AIF_BEING_REPAIRED;
9693 aip->ai_flags |= AIF_AWAITING_REPAIR;
9694 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9697 case REPAIR_INFO_END:
9698 // when only awaiting repair, and the repair is ended, then set dock_objnum to -1.
9699 if ( aip->ai_flags & AIF_AWAITING_REPAIR ){
9700 aip->dock_objnum = -1;
9702 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9703 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9706 case REPAIR_INFO_QUEUE:
9707 aip->ai_flags |= AIF_AWAITING_REPAIR;
9708 if ( aip == Player_ai ){
9709 hud_support_view_start();
9711 stamp = timestamp(-1);
9714 case REPAIR_INFO_ABORT:
9715 case REPAIR_INFO_KILLED:
9716 // 5/4/98 -- MWA -- Need to set dock objnum to -1 to let code know this guy who was getting
9717 // repaired (or queued for repair), isn't really going to be docked with anyone anymore.
9718 aip->dock_objnum = -1;
9719 aip->ai_flags &= ~AIF_DOCKED;
9720 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9721 if (repair_objp != NULL) {
9722 repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9723 repair_aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9726 if ( p_index >= 0 ) {
9727 hud_support_view_abort();
9729 // send appropriate message to player here
9730 if ( how == REPAIR_INFO_KILLED ){
9731 message_send_builtin_to_player( MESSAGE_SUPPORT_KILLED, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9734 message_send_builtin_to_player( MESSAGE_REPAIR_ABORTED, &Ships[repair_objp->instance], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9739 // add log entry if this is a player
9740 if ( repaired_objp->flags & OF_PLAYER_SHIP ){
9741 mission_log_add_entry(LOG_PLAYER_REARM_ABORT, Ships[repaired_objp->instance].ship_name, NULL);
9744 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9747 case REPAIR_INFO_COMPLETE:
9748 // clear the being repaired flag -- and
9749 if ( p_index >= 0 ) {
9750 SDL_assert( repair_objp );
9752 hud_support_view_stop();
9754 message_send_builtin_to_player(MESSAGE_REPAIR_DONE, &Ships[repair_objp->instance], MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, p_index, -1);
9756 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9759 case REPAIR_INFO_ONWAY:
9760 // need to set the dock_signature so that clients in multiplayer games rearm correctly
9761 SDL_assert( repair_objp );
9762 aip->dock_signature = repair_objp->signature;
9763 aip->dock_objnum = OBJ_INDEX(repair_objp);
9764 stamp = timestamp(-1);
9768 Int3(); // bogus type of repair info
9772 Ai_info[Ships[repair_objp->instance].ai_index].warp_out_timestamp = stamp;
9775 // repair_objp might be NULL is we are cleaning up this mode because of the support ship
9777 if ( repair_objp ) {
9778 aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9780 case REPAIR_INFO_ONWAY:
9781 SDL_assert( repaired_objp != NULL );
9782 aip->goal_objnum = OBJ_INDEX(repaired_objp);
9783 aip->ai_flags |= AIF_REPAIRING;
9786 case REPAIR_INFO_BROKEN:
9789 case REPAIR_INFO_END:
9790 case REPAIR_INFO_ABORT:
9791 case REPAIR_INFO_KILLED:
9792 if ( how == REPAIR_INFO_ABORT )
9793 aip->goal_objnum = -1;
9795 aip->ai_flags &= ~AIF_REPAIRING;
9798 case REPAIR_INFO_QUEUE:
9799 ai_add_rearm_goal( repaired_objp, repair_objp );
9802 case REPAIR_INFO_BEGIN:
9803 case REPAIR_INFO_COMPLETE:
9807 Int3(); // bogus type of repair info
9811 multi_maybe_send_repair_info( repaired_objp, repair_objp, how );
9814 // Cleanup AI stuff for when a ship was supposed to dock with another, but the ship
9815 // it was supposed to dock with is no longer valid.
9816 void ai_cleanup_dock_mode(ai_info *aip, ship *shipp)
9820 objp = &Objects[shipp->objnum];
9821 aip->mode = AIM_NONE;
9823 if (aip->ai_flags & AIF_REPAIRING) {
9824 SDL_assert( aip->goal_objnum != -1 );
9825 ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], &Objects[shipp->objnum], REPAIR_INFO_KILLED );
9826 } else if ( aip->ai_flags & AIF_BEING_REPAIRED ) {
9827 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9828 SDL_assert( aip->dock_objnum != -1 );
9829 ai_do_objects_repairing_stuff( &Objects[shipp->objnum], &Objects[aip->dock_objnum], REPAIR_INFO_KILLED );
9830 } else if ( aip->ai_flags & AIF_AWAITING_REPAIR ) {
9831 // need to find the support ship that has me as a goal_objnum
9832 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9833 // MWA -- 3/38/98 Check to see if this guy is queued for a support ship, or there is already
9834 // one in the mission
9835 if ( mission_is_repair_scheduled(objp) ) {
9836 mission_remove_scheduled_repair( objp ); // this function will notify multiplayer clients.
9838 if ( aip->dock_objnum != -1 )
9839 ai_do_objects_repairing_stuff( objp, &Objects[aip->dock_objnum], REPAIR_INFO_ABORT );
9841 ai_do_objects_repairing_stuff( objp, NULL, REPAIR_INFO_ABORT );
9845 if ( aip->ai_flags & AIF_DOCKED ) {
9848 SDL_assert( aip->dock_objnum != -1 );
9850 // if docked, and the dock_objnum is not undocking, force them to near last stage
9851 other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
9852 if ( (other_aip->mode == AIM_DOCK) && (other_aip->submode < AIS_UNDOCK_3) )
9853 other_aip->submode = AIS_UNDOCK_3;
9854 ai_do_objects_undocked_stuff( objp, &Objects[aip->dock_objnum] );
9859 // Make dockee_objp shake a bit due to docking.
9860 void ai_dock_shake(object *docker_objp, object *dockee_objp)
9867 scale = 0.25f; // Compute this based on mass and speed at time of docking.
9869 vm_vec_rand_vec_quick(&tangles);
9870 vm_vec_scale(&tangles, scale);
9872 ap = (angles *) &tangles;
9874 vm_angles_2_matrix(&rotmat, ap);
9875 vm_matrix_x_matrix( &tmp, &dockee_objp->orient, &rotmat );
9876 dockee_objp->orient = tmp;
9878 vm_orthogonalize_matrix(&dockee_objp->orient);
9880 dock_orient_and_approach(docker_objp, dockee_objp, DOA_DOCK_STAY);
9885 // Make Pl_objp point at aip->goal_point.
9891 SDL_assert(Pl_objp->type == OBJ_SHIP);
9892 SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_OBJECTS));
9894 shipp = &Ships[Pl_objp->instance];
9895 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
9897 aip = &Ai_info[shipp->ai_index];
9899 turn_towards_point(Pl_objp, &aip->goal_point, NULL, 0.0f);
9902 // Make *Pl_objp stay near another ship.
9908 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
9910 goal_objnum = aip->goal_objnum;
9912 if ((goal_objnum < 0) || (Objects[goal_objnum].type != OBJ_SHIP) || (Objects[goal_objnum].signature != aip->goal_signature)) {
9913 aip->mode = AIM_NONE;
9915 float dist, max_dist, scale;
9916 vector rand_vec, goal_pos, vec_to_goal;
9919 goal_objp = &Objects[goal_objnum];
9921 // Make not all ships pursue same point.
9922 static_randvec(Pl_objp-Objects, &rand_vec);
9924 // Make sure point is in front hemisphere (relative to Pl_objp's position.
9925 vm_vec_sub(&vec_to_goal, &goal_objp->pos, &Pl_objp->pos);
9926 if (vm_vec_dot(&rand_vec, &vec_to_goal) > 1.0f) {
9927 vm_vec_negate(&rand_vec);
9930 // Scale the random vector by an amount proportional to the distance from Pl_objp to the true goal.
9931 dist = vm_vec_dist_quick(&goal_objp->pos, &Pl_objp->pos);
9932 max_dist = aip->stay_near_distance;
9933 scale = dist - max_dist/2;
9937 vm_vec_scale_add(&goal_pos, &goal_objp->pos, &rand_vec, scale);
9939 if (max_dist < Pl_objp->radius + goal_objp->radius + 25.0f)
9940 max_dist = Pl_objp->radius + goal_objp->radius + 25.0f;
9942 if (dist > max_dist) {
9943 turn_towards_point(Pl_objp, &goal_pos, NULL, 0.0f);
9944 accelerate_ship(aip, dist / max_dist - 0.8f);
9951 // Warn player if dock path is obstructed.
9952 int maybe_dock_obstructed(object *cur_objp, object *goal_objp, int big_only_flag)
9954 vector *goalpos, *curpos;
9959 aip = &Ai_info[Ships[cur_objp->instance].ai_index];
9961 Ai_info[Ships[goal_objp->instance].ai_index].ai_flags &= ~AIF_REPAIR_OBSTRUCTED;
9963 if (goal_objp != Player_obj)
9966 curpos = &cur_objp->pos;
9967 radius = cur_objp->radius;
9968 goalpos = &Path_points[aip->path_cur].pos;
9969 collide_objnum = pp_collide_any(curpos, goalpos, radius, cur_objp, goal_objp, big_only_flag);
9971 if (collide_objnum != -1)
9972 Ai_info[Ships[goal_objp->instance].ai_index].ai_flags |= AIF_REPAIR_OBSTRUCTED;
9974 return collide_objnum;
9978 int Dock_path_warning_given = 0;
9980 // Docking behavior.
9981 // Approach a ship, follow path to docking platform, approach platform, after awhile,
9985 ship *shipp = &Ships[Pl_objp->instance];
9986 ai_info *aip = &Ai_info[shipp->ai_index];
9988 ship_info *sip = &Ship_info[shipp->ship_info_index];
9990 // Make sure object we're supposed to dock with still exists.
9991 if ((aip->goal_objnum == -1) || (Objects[aip->goal_objnum].signature != aip->goal_signature)) {
9992 ai_cleanup_dock_mode(aip, shipp);
9996 goal_objp = &Objects[aip->goal_objnum];
9998 // For docking submodes (ie, not undocking), follow path. Once at second last
9999 // point on path (point just before point on dock platform), orient into position.
10000 // For undocking, first mode pushes docked ship straight back from docking point
10001 // second mode turns ship and moves to point on docking radius
10002 switch (aip->submode) {
10004 // This mode means to find the path to the docking point.
10006 //aip->path_start = -1;
10007 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10009 if (!Dock_path_warning_given && (aip->path_length < 4)) {
10010 Warning( LOCATION, "Ship '%s' has only %i points on dock path. Docking will look strange. Contact Adam.", shipp->ship_name, aip->path_length );
10011 Dock_path_warning_given = 1; // This is on a mission-wide basis, but it's just a hack for now...
10014 aip->submode = AIS_DOCK_1;
10015 aip->path_start = -1;
10016 aip->submode_start_time = Missiontime;
10019 // This mode means to follow the path until just before the end.
10024 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp, 1)) != -1) {
10026 if ((r1 = maybe_avoid_big_ship(Pl_objp, goal_objp, aip, &goal_objp->pos, 7.0f)) != 0) {
10027 nprintf(("AI", "Support ship %s avoiding large ship %s\n", Ships[Pl_objp->instance].ship_name, Ships[Objects[r1].instance].ship_name));
10030 nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10031 accelerate_ship(aip, 0.0f);
10032 aip->submode = AIS_DOCK_0;
10036 /*dist =*/ ai_path();
10037 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10038 //nprintf(("AI", "Dock 1: Frame: %i, goal point = %i, dist = %7.3f\n", Framecount, aip->path_cur-aip->path_start, dist));
10040 if (aip->path_cur-aip->path_start >= aip->path_length-1) { // If got this far, advance no matter what.
10041 aip->submode = AIS_DOCK_2;
10042 aip->submode_start_time = Missiontime;
10044 SDL_assert(aip->path_cur-aip->path_start >= 0);
10045 } else if (aip->path_cur-aip->path_start >= aip->path_length-2) {
10046 if (Pl_objp->phys_info.speed > goal_objp->phys_info.speed + 1.5f) {
10047 set_accel_for_target_speed(Pl_objp, goal_objp->phys_info.speed);
10049 aip->submode = AIS_DOCK_2;
10050 aip->submode_start_time = Missiontime;
10056 // This mode means to drag oneself right to the second last point on the path.
10057 // Path code allows it to overshoot.
10062 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10063 nprintf(("AI", "Dock 2: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10064 accelerate_ship(aip, 0.0f);
10065 aip->submode = AIS_DOCK_1;
10067 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10068 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_APPROACH);
10069 SDL_assert(dist != UNINITIALIZED_VALUE);
10071 if (dist == DOCK_BACKUP_RETURN_VAL) {
10073 aip->submode = AIS_DOCK_1;
10074 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
10075 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
10076 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
10080 //nprintf(("AI", "Dock 2: dist = %7.3f\n", vm_vec_dist_quick(&Pl_objp->pos, &goal_point)));
10082 if (Objects[aip->goal_objnum].flags & OF_PLAYER_SHIP)
10083 tolerance = 6*flFrametime + 1.0f;
10085 tolerance = 4*flFrametime + 0.5f;
10087 if ( dist < tolerance) {
10088 aip->submode = AIS_DOCK_3;
10089 aip->submode_start_time = Missiontime;
10099 SDL_assert(aip->goal_objnum != -1);
10102 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10103 nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10104 accelerate_ship(aip, 0.0f);
10105 aip->submode = AIS_DOCK_2;
10108 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10109 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10110 SDL_assert(dist != UNINITIALIZED_VALUE);
10112 if (dist == DOCK_BACKUP_RETURN_VAL) {
10113 aip->submode = AIS_DOCK_2;
10117 //nprintf(("AI", "Dock 3: dist = %7.3f\n", dist));
10119 if (dist < 2*flFrametime * (1.0f + fl_sqrt(goal_objp->phys_info.speed))) {
10120 // - Removed by MK on 11/7/97, causes errors for ships docked at mission start: maybe_recreate_path(Pl_objp, aip, 1);
10121 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10122 SDL_assert(dist != UNINITIALIZED_VALUE);
10124 physics_ship_init(Pl_objp);
10126 ai_do_objects_docked_stuff( Pl_objp, goal_objp );
10128 if (aip->submode == AIS_DOCK_3) {
10129 snd_play_3d( &Snds[SND_DOCK_ATTACH], &Pl_objp->pos, &View_position );
10130 hud_maybe_flash_docking_text(Pl_objp);
10131 // ai_dock_shake(Pl_objp, goal_objp);
10133 if ((Pl_objp == Player_obj) || (goal_objp == Player_obj))
10134 joy_ff_docked(); // shake player's joystick a little
10137 // If this ship is repairing another ship...
10138 if (aip->ai_flags & AIF_REPAIRING) {
10139 aip->submode = AIS_DOCK_4; // Special rearming only dock mode.
10140 aip->submode_start_time = Missiontime;
10142 aip->submode = AIS_DOCK_4A;
10143 aip->submode_start_time = Missiontime;
10150 // Yes, we just sit here. We wait for further orders. No, it's not a bug.
10152 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10153 //nprintf(("AI", "."));
10154 if (aip->active_goal >= 0) {
10155 mission_log_add_entry(LOG_SHIP_DOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10157 if (aip->goals[aip->active_goal].ai_mode == AI_GOAL_DOCK) {
10158 ai_mission_goal_complete( aip ); // Note, this calls ai_set_default_behavior().
10160 } else { // Can happen for initially docked ships.
10161 ai_do_default_behavior( &Objects[Ships[aip->shipnum].objnum] ); // do the default behavior
10167 // This mode is only for rearming/repairing.
10168 // The ship that is performing the rearm enters this mode after it docks.
10169 SDL_assert((aip->goal_objnum >= -1) && (aip->goal_objnum < MAX_OBJECTS));
10171 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10172 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10173 SDL_assert(dist != UNINITIALIZED_VALUE);
10175 SDL_assert(goal_objp->type == OBJ_SHIP);
10176 ship *goal_shipp = &Ships[goal_objp->instance];
10177 ai_info *goal_aip = &Ai_info[goal_shipp->ai_index];
10179 //nprintf(("AI", "Dock 4: dist = %7.3f\n", dist));
10181 // Make sure repair has not broken off.
10182 if (dist > 5.0f) { // Oops, too far away!
10183 if ( goal_aip->ai_flags & AIF_BEING_REPAIRED )
10184 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BROKEN);
10186 if (dist > Pl_objp->radius*2 + goal_objp->radius*2) {
10187 // Got real far away from goal, so move back a couple modes and try again.
10188 aip->submode = AIS_DOCK_2;
10189 aip->submode_start_time = Missiontime;
10192 if ( goal_aip->ai_flags & AIF_AWAITING_REPAIR )
10193 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BEGIN );
10199 case AIS_UNDOCK_0: {
10201 // First stage of undocking.
10203 //nprintf(("AI", "Undock 0:\n"));
10205 aip->submode = AIS_UNDOCK_1;
10206 aip->submode_start_time = Missiontime;
10207 if (aip->dock_objnum == -1) {
10208 aip->submode = AIS_UNDOCK_3;
10211 // set up the path points for the undocking procedure. dock_path_index member should
10212 // have gotten set in the docking code.
10213 SDL_assert( aip->dock_path_index != -1 );
10214 path_num = ai_return_path_num_from_dockbay(goal_objp, aip->dock_path_index);
10215 ai_find_path(Pl_objp, goal_objp-Objects, path_num, 0);
10217 // Play a ship docking detach sound
10218 snd_play_3d( &Snds[SND_DOCK_DETACH], &Pl_objp->pos, &View_position );
10222 case AIS_UNDOCK_1: {
10223 // Using thrusters, exit from dock station to nearest next dock path point.
10226 //nprintf(("AI", "Undock 1: time in this mode = %7.3f\n", f2fl(Missiontime - aip->submode_start_time)));
10228 if (Missiontime - aip->submode_start_time < REARM_BREAKOFF_DELAY) {
10229 break; // Waiting for one second to elapse to let detach sound effect play out.
10231 else { // AL - added 05/16/97. Hack to play depart sound. Will probably take out.
10232 // Assumes that the submode_start_time is not used for AIS_UNDOCK_1 anymore
10233 if ( aip->submode_start_time != 0 )
10234 snd_play_3d( &Snds[SND_DOCK_DEPART], &Pl_objp->pos, &View_position );
10235 aip->submode_start_time = 0;
10238 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_1);
10239 SDL_assert(dist != UNINITIALIZED_VALUE);
10241 float dist_to_dock_obj = vm_vec_dist_quick(&Pl_objp->pos, &Objects[aip->goal_objnum].pos);
10243 // Move to within 0.1 units of second last point on path before orienting, or just plain far away from docked-to ship.
10244 // This allows undock to complete if first ship flies away.
10245 if ((dist < 2*flFrametime) || (dist_to_dock_obj > 2*Pl_objp->radius)) {
10246 aip->submode = AIS_UNDOCK_2;
10247 aip->submode_start_time = Missiontime;
10251 case AIS_UNDOCK_2: {
10253 //ai_info *other_aip;
10255 // get pointer to docked object's aip to reset flags, etc
10256 SDL_assert( aip->dock_objnum != -1 );
10257 //other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
10259 // Second stage of undocking.
10260 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_2);
10261 SDL_assert(dist != UNINITIALIZED_VALUE);
10264 //nprintf(("AI", "Undock 2: dist = %7.3f\n", dist));
10266 // If at goal point, or quite far away from dock object
10267 if ((dist < 2.0f) || (vm_vec_dist_quick(&Pl_objp->pos, &goal_objp->pos) > (Pl_objp->radius + goal_objp->radius)*2) || (goal_objp->phys_info.speed > MAX_UNDOCK_ABORT_SPEED) ) {
10268 // reset the dock flags. If rearm/repair, reset rearm repair flags for those ships as well.
10269 if ( sip->flags & SIF_SUPPORT ) {
10270 ai_do_objects_repairing_stuff( &Objects[aip->dock_objnum], Pl_objp, REPAIR_INFO_END );
10273 // clear out flags for AIF_DOCKED for both objects.
10274 ai_do_objects_undocked_stuff( Pl_objp, goal_objp );
10275 physics_ship_init(Pl_objp);
10276 aip->submode = AIS_UNDOCK_3; // The do-nothing mode, until another order is issued
10278 //aip->ai_flags &= ~AIF_DOCKED; // @MK, 9/18/97
10279 //other_aip->ai_flags &= ~AIF_DOCKED;
10280 //aip->dock_objnum = -1; // invalidate who obj is docked with
10281 //other_aip->dock_objnum = -1; // MWA 10/07/97 invalide docked objects dock_objnum value as well
10283 // don't add undock log entries for support ships.
10284 if ( !(sip->flags & SIF_SUPPORT) )
10285 mission_log_add_entry(LOG_SHIP_UNDOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10290 case AIS_UNDOCK_3: {
10291 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_3);
10292 SDL_assert(dist != UNINITIALIZED_VALUE);
10294 if (dist < Pl_objp->radius/2 + 5.0f) {
10295 aip->submode = AIS_UNDOCK_4;
10298 // possible that this flag hasn't been cleared yet. When aborting a rearm, this submode might
10299 // be entered directly.
10300 if ( (sip->flags & SIF_SUPPORT) && (aip->ai_flags & AIF_REPAIRING) ) {
10301 ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], Pl_objp, REPAIR_INFO_ABORT );
10306 case AIS_UNDOCK_4: {
10307 //ai_info *other_aip;
10309 // MWA 10/07/97 I'm slightly confused by the dual use of goal_objnum and dock_objnum. Seems to me
10310 // that goal_objnum and dock_objnum are the same through this whole docking/undocking process, although
10311 // I could be wrong. dock_objnum was reset in undock_2 submode so try to use goal_objnum here to
10312 // get other ships ai_info pointer
10313 //SDL_assert( aip->goal_objnum != -1 );
10314 //other_aip = &Ai_info[Ships[Objects[aip->goal_objnum].instance].ai_index];
10316 aip->mode = AIM_NONE;
10317 aip->dock_path_index = -1; // invalidate the docking path index
10319 // these flags should have been cleared long ago!
10320 // Get Allender if you hit one of these!!!!!
10321 // removed by allender on 2/16 since a ship may be docked with some other ship, but still be the
10322 // goal_objnum of this ship ending it's undocking mode.
10323 //SDL_assert( !(aip->ai_flags & AIF_DOCKED) );
10324 //SDL_assert( !(other_aip->ai_flags & AIF_DOCKED) );
10325 //SDL_assert( !(aip->ai_flags & AIF_REPAIRING) );
10326 //SDL_assert( !(other_aip->ai_flags & AIF_BEING_REPAIRED) );
10327 //SDL_assert( !(other_aip->ai_flags & AIF_AWAITING_REPAIR) );
10329 // only call mission goal complete if this was indeed an undock goal
10330 if ( aip->active_goal > -1 ) {
10331 if ( aip->goals[aip->active_goal].ai_mode == AI_GOAL_UNDOCK )
10332 ai_mission_goal_complete( aip ); // this call should reset the AI mode
10334 // aip->active_goal = -1; // this ensures that this ship might get new goal
10340 Int3(); // Error, bogus submode
10347 // Given an object and a turret on that object, return the global position and forward vector
10348 // of the turret. The gun normal is the unrotated gun normal, (the center of the FOV cone), not
10349 // the actual gun normal given using the current turret heading. But it _is_ rotated into the model's orientation
10350 // in global space.
10351 void ship_get_global_turret_info(object *objp, model_subsystem *tp, vector *gpos, vector *gvec)
10354 vm_copy_transpose_matrix(&m, &objp->orient);
10355 // vm_vec_rotate(gpos, &tp->turret_avg_firing_point, &m);
10356 vm_vec_rotate(gpos, &tp->pnt, &m);
10357 vm_vec_add2(gpos, &objp->pos);
10358 vm_vec_rotate(gvec, &tp->turret_norm, &m);
10361 // Given an object and a turret on that object, return the actual firing point of the gun
10362 // and its normal. This uses the current turret angles. We are keeping track of which
10363 // gun to fire next in the ship specific info for this turret subobject. Use this info
10364 // to determine which position to fire from next.
10366 // *gpos: absolute position of gun firing point
10367 // *gvec: vector fro *gpos to *targetp
10368 void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vector *gpos, vector *gvec, int use_angles, vector *targetp)
10371 model_subsystem *tp = ssp->system_info;
10373 ship_model_start(objp);
10375 gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
10377 model_find_world_point(gpos, gun_pos, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10380 model_find_world_dir(gvec, &tp->turret_norm, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10383 //vm_vec_add(&gun_pos2, gpos, gun_pos);
10384 vm_vec_normalized_dir(gvec, targetp, gpos);
10387 ship_model_stop(objp);
10390 // Rotate a turret towards an enemy.
10391 // Return TRUE if caller should use angles in subsequent rotations.
10392 // Some obscure model thing only John Slagel knows about.
10393 // Sets predicted enemy position.
10394 // If the turret (*ss) has a subsystem targeted, the subsystem is used as the predicted point.
10395 int aifft_rotate_turret(ship *shipp, int parent_objnum, ship_subsys *ss, object *objp, object *lep, vector *predicted_enemy_pos, vector *gvec)
10397 if (ss->turret_enemy_objnum != -1) {
10398 model_subsystem *tp = ss->system_info;
10399 vector gun_pos, gun_vec;
10400 float weapon_speed;
10401 float weapon_system_strength;
10403 // weapon_system_strength scales time enemy in range in 0..1. So, the lower this is, the worse the aiming will be.
10404 weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
10406 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gun_pos, &gun_vec);
10408 weapon_speed = Weapon_info[tp->turret_weapon_type].max_speed;
10409 float weapon_travel_dist = weapon_speed * Weapon_info[tp->turret_weapon_type].lifetime;
10411 vector enemy_point;
10412 if (ss->targeted_subsys != NULL) {
10413 if (ss->turret_enemy_objnum != -1) {
10414 vm_vec_unrotate(&enemy_point, &ss->targeted_subsys->system_info->pnt, &Objects[ss->turret_enemy_objnum].orient);
10415 vm_vec_add2(&enemy_point, &Objects[ss->turret_enemy_objnum].pos);
10418 if ((lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
10419 ai_big_pick_attack_point_turret(lep, ss, &gun_pos, &gun_vec, &enemy_point, tp->turret_fov, SDL_min(weapon_travel_dist, Weapon_info[tp->turret_weapon_type].weapon_range));
10421 enemy_point = lep->pos;
10425 set_predicted_enemy_pos_turret(predicted_enemy_pos, &gun_pos, objp, &enemy_point, &lep->phys_info.vel, weapon_speed, ss->turret_time_enemy_in_range * (weapon_system_strength + 1.0f)/2.0f);
10427 if (weapon_system_strength < 0.7f) {
10430 static_randvec(Missiontime >> 18, &rand_vec); // Return same random number for two seconds.
10431 // Add to predicted_enemy_pos value in .45 to 1.5x radius of enemy ship, so will often miss, but not by a huge amount.
10432 vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, (1.0f - weapon_system_strength)*1.5f * lep->radius);
10436 vm_vec_normalized_dir(&v2e, predicted_enemy_pos, &gun_pos);
10437 if (vm_vec_dot(&v2e, gvec) > tp->turret_fov) {
10438 model_rotate_gun(shipp->modelnum, ss->system_info, &Objects[parent_objnum].orient,
10439 &ss->submodel_info_1.angs, &ss->submodel_info_2.angs,
10440 &Objects[parent_objnum].pos, predicted_enemy_pos);
10447 // Determine if subsystem *enemy_subsysp is hittable from objp.
10448 // If so, return dot product of vector from point abs_gunposp to *enemy_subsysp
10449 float aifft_compute_turret_dot(object *objp, object *enemy_objp, vector *abs_gunposp, ship_subsys *turret_subsysp, ship_subsys *enemy_subsysp)
10452 vector subobj_pos, vector_out;
10454 vm_vec_unrotate(&subobj_pos, &enemy_subsysp->system_info->pnt, &enemy_objp->orient);
10455 vm_vec_add2(&subobj_pos, &enemy_objp->pos);
10457 if (ship_subsystem_in_sight(enemy_objp, enemy_subsysp, abs_gunposp, &subobj_pos, 1, &dot_out, &vector_out)) {
10458 vector turret_norm;
10460 vm_vec_rotate(&turret_norm, &turret_subsysp->system_info->turret_norm, &objp->orient);
10461 return vm_vec_dot(&turret_norm, &vector_out);
10467 #define MAX_AIFFT_TURRETS 60
10468 ship_subsys *aifft_list[MAX_AIFFT_TURRETS];
10469 float aifft_rank[MAX_AIFFT_TURRETS];
10470 int aifft_list_size = 0;
10471 int aifft_max_checks = 5;
10474 dc_get_arg(ARG_INT);
10475 aifft_max_checks = Dc_arg_int;
10479 // Pick a subsystem to attack on enemy_objp.
10480 // Only pick one if enemy_objp is a big ship or a capital ship.
10481 // Returns dot product from turret to subsystem in *dot_out
10482 ship_subsys *aifft_find_turret_subsys(object *objp, ship_subsys *ssp, object *enemy_objp, float *dot_out)
10486 ship_subsys *best_subsysp = NULL;
10489 SDL_assert(enemy_objp->type == OBJ_SHIP);
10491 eshipp = &Ships[enemy_objp->instance];
10492 esip = &Ship_info[eshipp->ship_info_index];
10494 float best_dot = 0.0f;
10495 *dot_out = best_dot;
10497 // Compute absolute gun position.
10498 vector abs_gun_pos;
10499 vm_vec_unrotate(&abs_gun_pos, &ssp->system_info->pnt, &objp->orient);
10500 vm_vec_add2(&abs_gun_pos, &objp->pos);
10502 // Only pick a turret to attack on large ships.
10503 if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
10504 return best_subsysp;
10506 // Make sure big or huge ship *actually* has subsystems (ie, knossos)
10507 if (esip->n_subsystems == 0) {
10508 return best_subsysp;
10511 // first build up a list subsystems to traverse
10513 aifft_list_size = 0;
10514 for ( pss = GET_FIRST(&eshipp->subsys_list); pss !=END_OF_LIST(&eshipp->subsys_list); pss = GET_NEXT(pss) ) {
10515 model_subsystem *psub = pss->system_info;
10517 // if we've reached max turrets bail
10518 if(aifft_list_size >= MAX_AIFFT_TURRETS){
10522 // Don't process destroyed objects
10523 if ( pss->current_hits <= 0.0f ){
10527 switch (psub->type) {
10528 case SUBSYSTEM_WEAPONS:
10529 aifft_list[aifft_list_size] = pss;
10530 aifft_rank[aifft_list_size++] = 1.4f;
10533 case SUBSYSTEM_TURRET:
10534 aifft_list[aifft_list_size] = pss;
10535 aifft_rank[aifft_list_size++] = 1.2f;
10538 case SUBSYSTEM_SENSORS:
10539 case SUBSYSTEM_ENGINE:
10540 aifft_list[aifft_list_size] = pss;
10541 aifft_rank[aifft_list_size++] = 1.0f;
10546 // DKA: 6/28/99 all subsystems can be destroyed.
10547 //SDL_assert(aifft_list_size > 0);
10548 if (aifft_list_size == 0) {
10549 return best_subsysp;
10552 // determine a stride value so we're not checking too many turrets
10553 int stride = aifft_list_size > aifft_max_checks ? aifft_list_size / aifft_max_checks : 1;
10557 int offset = (int)frand_range(0.0f, (float)(aifft_list_size % stride));
10559 for(idx=offset; idx<aifft_list_size; idx+=stride){
10560 dot = aifft_compute_turret_dot(objp, enemy_objp, &abs_gun_pos, ssp, aifft_list[idx]);
10562 if (dot* aifft_rank[idx] > best_dot) {
10563 best_dot = dot*aifft_rank[idx];
10564 best_subsysp = aifft_list[idx];
10568 SDL_assert(best_subsysp != &eshipp->subsys_list);
10570 *dot_out = best_dot;
10571 return best_subsysp;
10574 // Set active weapon for turret
10575 void ai_turret_select_default_weapon(ship_subsys *turret)
10579 twp = &turret->weapons;
10581 // If a primary weapon is available, select it
10582 if ( twp->num_primary_banks > 0 ) {
10583 turret->system_info->turret_weapon_type = twp->primary_bank_weapons[0];
10584 } else if ( twp->num_secondary_banks > 0 ) {
10585 turret->system_info->turret_weapon_type = twp->secondary_bank_weapons[0];
10589 // return !0 if the specified target should scan for a new target, otherwise return 0
10590 int turret_should_pick_new_target(ship_subsys *turret)
10592 // int target_type;
10594 if ( timestamp_elapsed(turret->turret_next_enemy_check_stamp) ) {
10601 if ( turret->turret_enemy_objnum == -1 ) {
10605 target_type = Objects[turret->turret_enemy_objnum].type;
10606 if ( (target_type != OBJ_SHIP) && (target_type != OBJ_ASTEROID) ) {
10614 // Set the next fire timestamp for a turret, based on weapon type and ai class
10615 void turret_set_next_fire_timestamp(ship_subsys *turret, ai_info *aip)
10620 weapon_id = turret->system_info->turret_weapon_type;
10622 wait = Weapon_info[weapon_id].fire_wait * 1000.0f;
10624 // make side even for team vs. team
10625 if ((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) {
10626 // flak guns need to fire more rapidly
10627 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10628 wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10629 wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10631 wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10632 wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10635 // flak guns need to fire more rapidly
10636 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10637 if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10638 wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10640 wait *= Ship_fire_delay_scale_hostile[Game_skill_level] * 0.5f;
10642 wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10644 } else if (Weapon_info[weapon_id].wi_flags & WIF_HUGE) {
10645 // make huge weapons fire independently of team
10646 wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10647 wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10649 // give team friendly an advantage
10650 if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10651 wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10653 wait *= Ship_fire_delay_scale_hostile[Game_skill_level];
10655 wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10659 // vary wait time +/- 10%
10660 wait *= frand_range(0.9f, 1.1f);
10661 turret->turret_next_fire_stamp = timestamp((int) wait);
10664 // Decide if a turret should launch an aspect seeking missile
10665 int turret_should_fire_aspect(ship_subsys *turret, float dot, int weapon_class)
10669 wip = &Weapon_info[weapon_class];
10671 if ( (dot > AICODE_TURRET_DUMBFIRE_ANGLE) && (turret->turret_time_enemy_in_range >= SDL_min(wip->min_lock_time,AICODE_TURRET_MAX_TIME_IN_RANGE)) ) {
10678 // Update how long current target has been in this turrets range
10679 void turret_update_enemy_in_range(ship_subsys *turret, float seconds)
10681 turret->turret_time_enemy_in_range += seconds;
10683 if ( turret->turret_time_enemy_in_range < 0.0f ) {
10684 turret->turret_time_enemy_in_range = 0.0f;
10687 if ( turret->turret_time_enemy_in_range > AICODE_TURRET_MAX_TIME_IN_RANGE ) {
10688 turret->turret_time_enemy_in_range = AICODE_TURRET_MAX_TIME_IN_RANGE;
10694 // Fire a weapon from a turret
10695 void turret_fire_weapon(ship_subsys *turret, int parent_objnum, vector *turret_pos, vector *turret_fvec, vector *predicted_pos = NULL)
10697 matrix turret_orient;
10698 int turret_weapon_class, weapon_objnum;
10699 ai_info *parent_aip;
10701 beam_fire_info fire_info;
10702 float flak_range = 0.0f;
10704 parent_aip = &Ai_info[Ships[Objects[parent_objnum].instance].ai_index];
10705 parent_ship = &Ships[Objects[parent_objnum].instance];
10706 turret_weapon_class = turret->system_info->turret_weapon_type;
10708 if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, &Weapon_info[turret_weapon_class])) {
10709 vm_vector_2_matrix(&turret_orient, turret_fvec, NULL, NULL);
10710 turret->turret_last_fire_direction = *turret_fvec;
10712 // set next fire timestamp for the turret
10713 turret_set_next_fire_timestamp(turret, parent_aip);
10715 // if this weapon is a beam weapon, handle it specially
10716 if(Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM){
10717 // if this beam isn't free to fire
10718 if (!(turret->weapons.flags & SW_FLAG_BEAM_FREE)) {
10719 Int3(); // should never get this far
10723 // stuff beam firing info
10724 memset(&fire_info, 0, sizeof(beam_fire_info));
10725 fire_info.accuracy = 1.0f;
10726 fire_info.beam_info_index = turret_weapon_class;
10727 fire_info.beam_info_override = NULL;
10728 fire_info.shooter = &Objects[parent_objnum];
10729 fire_info.target = &Objects[turret->turret_enemy_objnum];
10730 fire_info.target_subsys = NULL;
10731 fire_info.turret = turret;
10733 // fire a beam weapon
10734 beam_fire(&fire_info);
10737 // don't fire swarm, but set up swarm info
10738 if (Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM) {
10739 turret_swarm_set_up_info(parent_objnum, turret, turret_weapon_class);
10742 weapon_objnum = weapon_create( turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10743 weapon_set_tracking_info(weapon_objnum, parent_objnum, turret->turret_enemy_objnum, 1, turret->targeted_subsys);
10746 //nprintf(("AI", "Turret_time_enemy_in_range = %7.3f\n", ss->turret_time_enemy_in_range));
10747 if (weapon_objnum != -1) {
10748 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10749 // AL 1-6-97: Store pointer to turret subsystem
10750 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10752 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10753 // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10754 if ( parent_objnum != OBJ_INDEX(Player_obj) ) {
10755 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], turret_pos, &View_position );
10759 // if the gun is a flak gun
10760 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){
10761 // show a muzzle flash
10762 flak_muzzle_flash(turret_pos, turret_fvec, turret_weapon_class);
10764 // pick a firing range so that it detonates properly
10765 flak_pick_range(&Objects[weapon_objnum], predicted_pos, ship_get_subsystem_strength(parent_ship, SUBSYSTEM_WEAPONS));
10767 // determine what that range was
10768 flak_range = flak_get_range(&Objects[weapon_objnum]);
10771 // in multiplayer (and the master), then send a turret fired packet.
10772 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10775 subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10776 SDL_assert( subsys_index != -1 );
10777 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){
10778 send_flak_fired_packet( parent_objnum, subsys_index, weapon_objnum, flak_range );
10780 send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10786 float wait = 1000.0f * frand_range(0.9f, 1.1f);
10787 turret->turret_next_fire_stamp = timestamp((int) wait);
10791 void turret_swarm_fire_from_turret(ship_subsys *turret, int parent_objnum, int target_objnum, ship_subsys *target_subsys)
10793 int turret_weapon_class, weapon_objnum;
10794 matrix turret_orient;
10795 vector turret_pos, turret_fvec;
10797 // parent not alive, quick out.
10798 if (Objects[parent_objnum].type != OBJ_SHIP) {
10802 // change firing point
10803 ship_get_global_turret_gun_info(&Objects[parent_objnum], turret, &turret_pos, &turret_fvec, 1, NULL);
10804 turret->turret_next_fire_pos++;
10806 // get class [index into Weapon_info array
10807 turret_weapon_class = turret->system_info->turret_weapon_type;
10808 SDL_assert(Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM);
10810 // make turret_orient from turret_fvec -- turret->turret_last_fire_direction
10811 vm_vector_2_matrix(&turret_orient, &turret_fvec, NULL, NULL);
10813 // create weapon and homing info
10814 weapon_objnum = weapon_create(&turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10815 weapon_set_tracking_info(weapon_objnum, parent_objnum, target_objnum, 1, target_subsys);
10817 // do other cool stuff if weapon is created.
10818 if (weapon_objnum > -1) {
10819 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10820 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10823 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10824 // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10825 if ( parent_objnum != OBJ_INDEX(Player_obj) ) {
10826 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], &turret_pos, &View_position );
10830 // in multiplayer (and the master), then send a turret fired packet.
10831 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10834 subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10835 SDL_assert( subsys_index != -1 );
10836 send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10841 int Num_ai_firing = 0;
10842 int Num_find_turret_enemy = 0;
10843 int Num_turrets_fired = 0;
10844 // Given a turret tp and its parent parent_objnum, fire from the turret at its enemy.
10845 void ai_fire_from_turret(ship *shipp, ship_subsys *ss, int parent_objnum)
10847 float weapon_firing_range;
10849 object *lep; // Last enemy pointer
10850 model_subsystem *tp = ss->system_info;
10851 int use_angles, turret_weapon_class;
10852 vector predicted_enemy_pos;
10856 if (!Ai_firing_enabled) {
10860 if (ss->current_hits < 0.0f) {
10864 if ( ship_subsys_disrupted(ss) ){ // AL 1/19/98: Make sure turret isn't suffering disruption effects
10868 // Check turret free
10869 if (ss->weapons.flags & SW_FLAG_TURRET_LOCK) {
10873 // If beam weapon, check beam free
10874 if ( (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) && !(ss->weapons.flags & SW_FLAG_BEAM_FREE) ) {
10878 SDL_assert( shipp->objnum == parent_objnum );
10880 if ( tp->turret_weapon_type < 0 ){
10884 // Monitor number of calls to ai_fire_from_turret
10887 turret_weapon_class = tp->turret_weapon_type;
10889 // AL 09/14/97: ensure ss->turret_enemy_objnum != -1 before setting lep
10890 if ( (ss->turret_enemy_objnum >= 0 && ss->turret_enemy_objnum < MAX_OBJECTS) && (ss->turret_enemy_sig == Objects[ss->turret_enemy_objnum].signature)) {
10891 lep = &Objects[ss->turret_enemy_objnum];
10893 // MK -- here is where turret is targeting a bomb. I simply return for now. We should force
10894 // a target change -- or better yet, never pick a weapon when this turret has a "huge" weapon
10897 // we only care about targets which are ships.
10898 //if ( lep->type != OBJ_SHIP )
10901 // If targeted a small ship and have a huge weapon, don't fire. But this shouldn't happen, as a small ship should not get selected.
10902 if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HUGE ) {
10903 if ( lep->type != OBJ_SHIP ) {
10906 if ( !(Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
10911 // If targeting protected or beam protected ship, don't fire. Reset enemy objnum
10912 if (lep->type == OBJ_SHIP) {
10913 // Check if we're targeting a protected ship
10914 if (lep->flags & OF_PROTECTED) {
10915 ss->turret_enemy_objnum = -1;
10916 ss->turret_time_enemy_in_range = 0.0f;
10920 // Check if we're targeting a beam protected ship with a beam weapon
10921 if ( (lep->flags & OF_BEAM_PROTECTED) && (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) ) {
10922 ss->turret_enemy_objnum = -1;
10923 ss->turret_time_enemy_in_range = 0.0f;
10928 ss->turret_enemy_objnum = -1;
10932 SDL_assert((parent_objnum >= 0) && (parent_objnum < MAX_OBJECTS));
10933 objp = &Objects[parent_objnum];
10934 SDL_assert(objp->type == OBJ_SHIP);
10935 aip = &Ai_info[Ships[objp->instance].ai_index];
10937 // Use the turret info for all guns, not one gun in particular.
10939 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
10941 // Rotate the turret even if time hasn't elapsed, since it needs to turn to face its target.
10942 use_angles = aifft_rotate_turret(shipp, parent_objnum, ss, objp, lep, &predicted_enemy_pos, &gvec);
10944 if ( !timestamp_elapsed(ss->turret_next_fire_stamp)){
10948 // Don't try to fire beyond weapon_limit_range
10949 weapon_firing_range = SDL_min(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
10951 // if beam weapon in nebula and target not tagged, decrase firing range
10952 extern int Nebula_sec_range;
10953 if (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) {
10954 if ( !((shipp->tag_left > 0) || (shipp->level2_tag_left > 0)) ) {
10955 if (Nebula_sec_range) {
10956 weapon_firing_range *= float(BEAM_NEBULA_RANGE_REDUCE_FACTOR);
10961 if (ss->turret_enemy_objnum != -1) {
10962 float dist_to_enemy = vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius;
10963 if (dist_to_enemy > weapon_firing_range) {
10964 ss->turret_enemy_objnum = -1; // Force picking of new enemy.
10968 // Turret spawn weapons are a special case. They fire if there are enough enemies in the
10969 // immediate area (not necessarily in the turret fov).
10970 if ( Weapon_info[turret_weapon_class].wi_flags & WIF_SPAWN ) {
10971 int num_ships_nearby;
10972 num_ships_nearby = num_nearby_fighters(get_enemy_team_mask(parent_objnum), &gpos, 1500.0f);
10973 if (( num_ships_nearby >= 3 ) || ((num_ships_nearby >= 2) && (frand() < 0.1f))) {
10974 turret_fire_weapon(ss, parent_objnum, &gpos, &ss->turret_last_fire_direction);
10976 ss->turret_next_fire_stamp = timestamp(1000); // Regardless of firing rate, don't check whether should fire for awhile.
10981 // Maybe pick a new enemy.
10982 if ( turret_should_pick_new_target(ss) ) {
10983 Num_find_turret_enemy++;
10984 int objnum = find_turret_enemy(ss, parent_objnum, &gpos, &gvec, ss->turret_enemy_objnum, tp->turret_fov, Weapon_info[turret_weapon_class].wi_flags & WIF_HUGE);
10985 SDL_assert(objnum < 0 || is_target_beam_valid(ss, objnum));
10987 if (objnum != -1) {
10988 if (ss->turret_enemy_objnum == -1) {
10989 ss->turret_enemy_objnum = objnum;
10990 ss->turret_enemy_sig = Objects[objnum].signature;
10994 ss->turret_enemy_objnum = objnum;
10995 ss->turret_enemy_sig = Objects[objnum].signature;
10998 ss->turret_enemy_objnum = -1;
11001 if (ss->turret_enemy_objnum != -1) {
11003 lep = &Objects[ss->turret_enemy_objnum];
11004 if ( lep->type == OBJ_SHIP ) {
11005 ss->targeted_subsys = aifft_find_turret_subsys(objp, ss, lep, &dot);
11007 ss->turret_next_enemy_check_stamp = timestamp((int) (SDL_max(dot, 0.5f)*2000.0f) + 1000);
11009 ss->turret_next_enemy_check_stamp = timestamp((int) (2000.0f * frand_range(0.9f, 1.1f))); // Check every two seconds
11013 // If still don't have an enemy, return. Or, if enemy is protected, return.
11014 if (ss->turret_enemy_objnum != -1) {
11015 // Don't shoot at ship we're going to dock with.
11016 if (ss->turret_enemy_objnum == aip->dock_objnum) {
11017 ss->turret_enemy_objnum = -1;
11021 if (Objects[ss->turret_enemy_objnum].flags & OF_PROTECTED) {
11022 // This can happen if the enemy was selected before it became protected.
11023 ss->turret_enemy_objnum = -1;
11026 lep = &Objects[ss->turret_enemy_objnum];
11028 if (timestamp_until(ss->turret_next_fire_stamp) < 500) {
11029 ss->turret_next_fire_stamp = timestamp(500);
11034 if ( lep == NULL ){
11038 SDL_assert(ss->turret_enemy_objnum != -1);
11040 float dot = vm_vec_dot(&v2e, &gvec);
11042 if (dot > tp->turret_fov ) {
11043 // Ok, the turret is lined up... now line up a particular gun.
11044 int ok_to_fire = 0;
11045 float dist_to_enemy;
11047 // We're ready to fire... now get down to specifics, like where is the
11048 // actual gun point and normal, not just the one for whole turret.
11049 ship_get_global_turret_gun_info(&Objects[parent_objnum], ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
11050 ss->turret_next_fire_pos++;
11052 // Fire in the direction the turret is facing, not right at the target regardless of turret dir.
11053 vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
11054 dist_to_enemy = vm_vec_normalize(&v2e);
11055 dot = vm_vec_dot(&v2e, &gvec);
11057 // if the weapon is a flak gun, add some jitter to its aim so it fires in a "cone" to make a cool visual effect
11058 // and make them less lethal
11059 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){
11060 flak_jitter_aim(&v2e, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS));
11064 // dumbfire and nearly pointing at target.
11065 // heat seeking and target in a fairly wide cone.
11066 // aspect seeking and target is locked.
11067 turret_weapon_class = tp->turret_weapon_type;
11069 // if dumbfire (lasers and non-homing missiles)
11070 if ( !(Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING) ) {
11071 if ((dist_to_enemy < 75.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11072 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11075 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_HEAT ) { // if heat seekers
11076 if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_HEATSEEK_ANGLE )) {
11077 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11080 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_ASPECT ) { // if aspect seeker
11081 if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11082 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11084 if ( turret_should_fire_aspect(ss, dot, turret_weapon_class) ) {
11089 if ( ok_to_fire ) {
11090 Num_turrets_fired++;
11092 turret_fire_weapon(ss, parent_objnum, &gpos, &v2e, &predicted_enemy_pos);
11094 turret_update_enemy_in_range(ss, -4*Weapon_info[tp->turret_weapon_type].fire_wait);
11095 ss->turret_next_fire_stamp = timestamp(500);
11099 ss->turret_enemy_objnum = -1; // Reset enemy objnum, find a new one next frame.
11100 ss->turret_time_enemy_in_range = 0.0f;
11107 #define MAX_AI_DEBUG_RENDER_STUFF 100
11108 typedef struct ai_render_stuff {
11113 ai_render_stuff AI_debug_render_stuff[MAX_AI_DEBUG_RENDER_STUFF];
11115 int Num_AI_debug_render_stuff = 0;
11117 void ai_debug_render_stuff()
11119 vertex vert1, vert2;
11123 for (i=0; i<Num_AI_debug_render_stuff; i++) {
11127 model_subsystem *tp;
11129 ss = AI_debug_render_stuff[i].ss;
11130 tp = ss->system_info;
11132 parent_objnum = AI_debug_render_stuff[i].parent_objnum;
11134 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
11135 g3_rotate_vertex(&vert1, &gpos);
11136 vm_vec_scale_add(&gpos2, &gpos, &gvec, 20.0f);
11137 g3_rotate_vertex(&vert2, &gpos2);
11138 gr_set_color(0, 0, 255);
11139 g3_draw_sphere(&vert1, 2.0f);
11140 gr_set_color(255, 0, 255);
11141 g3_draw_sphere(&vert2, 2.0f);
11142 g3_draw_line(&vert1, &vert2);
11145 // draw from beta to its goal point
11146 /* for (i=0; i<6; i++) {
11147 ai_info *aip = &Ai_info[i];
11148 gr_set_color(0, 0, 255);
11149 g3_rotate_vertex(&vert1, &Objects[i].pos);
11150 g3_rotate_vertex(&vert2, &aip->goal_point);
11151 g3_draw_line(&vert1, &vert2);
11155 Num_AI_debug_render_stuff = 0;
11161 int Msg_count_4996 = 0;
11164 // --------------------------------------------------------------------------
11165 // Process subobjects of object objnum.
11166 // Deal with engines disabled.
11167 void process_subobjects(int objnum)
11169 model_subsystem *psub;
11171 object *objp = &Objects[objnum];
11172 ship *shipp = &Ships[objp->instance];
11173 ai_info *aip = &Ai_info[shipp->ai_index];
11174 ship_info *sip = &Ship_info[shipp->ship_info_index];
11176 for ( pss = GET_FIRST(&shipp->subsys_list); pss !=END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
11177 psub = pss->system_info;
11179 // Don't process destroyed objects
11180 if ( pss->current_hits <= 0.0f )
11183 switch (psub->type) {
11184 case SUBSYSTEM_TURRET:
11185 if ( psub->turret_num_firing_points > 0 ) {
11186 ai_fire_from_turret(shipp, pss, objnum);
11189 if (!Msg_count_4996) {
11190 Warning( LOCATION, "Ship '%s' has turrets with no guns!\nProbably a model problem, so get an artist!", shipp->ship_name );
11197 case SUBSYSTEM_ENGINE:
11198 case SUBSYSTEM_NAVIGATION:
11199 case SUBSYSTEM_COMMUNICATION:
11200 case SUBSYSTEM_WEAPONS:
11201 case SUBSYSTEM_SENSORS:
11202 case SUBSYSTEM_UNKNOWN:
11205 // next set of subsystems may rotation
11206 case SUBSYSTEM_RADAR:
11207 case SUBSYSTEM_SOLAR:
11209 case SUBSYSTEM_GAS_COLLECT:
11210 case SUBSYSTEM_ACTIVATION:
11214 Error(LOCATION, "Illegal subsystem type.\n");
11217 // do solar/radar/gas/activator rotation here
11218 if ( psub->flags & MSS_FLAG_ROTATES ) {
11219 if (psub->flags & MSS_FLAG_STEPPED_ROTATE ) {
11220 submodel_stepped_rotate(psub, &pss->submodel_info_1);
11222 submodel_rotate(psub, &pss->submodel_info_1 );
11228 // Deal with a ship with blown out engines.
11229 if (ship_get_subsystem_strength(shipp, SUBSYSTEM_ENGINE) == 0.0f) {
11230 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
11231 // AL: Only attack forever if not trying to depart to a docking bay. Need to have this in, since
11232 // a ship may get repaired... and it should still try to depart. Since docking bay departures
11233 // are not handled as goals, we don't want to leave the AIM_BAY_DEPART mode.
11234 if ( aip->mode != AIM_BAY_DEPART ) {
11235 ai_attack_object(objp, NULL, 99, NULL); // Regardless of current mode, enter attack mode.
11236 aip->submode = SM_ATTACK_FOREVER; // Never leave attack submode, don't avoid, evade, etc.
11244 // Given an object and the wing it's in, return its index in the wing list.
11245 // This defines its location in the wing formation.
11246 // If the object can't be found in the wing, return -1.
11247 // *objp object of interest
11248 // wingnum the wing *objp is in
11249 int get_wing_index(object *objp, int wingnum)
11254 SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11256 wingp = &Wings[wingnum];
11258 for (i=wingp->current_count-1; i>=0; i--)
11259 if ( objp->instance == wingp->ship_index[i] )
11262 return i; // Note, returns -1 if string not found.
11265 // Given a wing, return a pointer to the object of its leader.
11266 // Asserts if object not found.
11267 // Currently, the wing leader is defined as the first object in the wing.
11268 // wingnum Wing number in Wings array.
11269 // If wing leader is disabled, swap it with another ship.
11270 object * get_wing_leader(int wingnum)
11275 SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11277 wingp = &Wings[wingnum];
11279 SDL_assert(wingp->current_count != 0); // Make sure there is a leader
11281 ship_num = wingp->ship_index[0];
11283 // If this ship is disabled, try another ship in the wing.
11285 while (ship_get_subsystem_strength(&Ships[ship_num], SUBSYSTEM_ENGINE) == 0.0f) {
11287 if (n >= wingp->current_count)
11289 ship_num = wingp->ship_index[n];
11292 if (( n != 0) && (n != wingp->current_count)) {
11293 int t = wingp->ship_index[0];
11294 wingp->ship_index[0] = wingp->ship_index[n];
11295 wingp->ship_index[n] = t;
11298 return &Objects[Ships[ship_num].objnum];
11301 #define DEFAULT_WING_X_DELTA 1.0f
11302 #define DEFAULT_WING_Y_DELTA 0.25f
11303 #define DEFAULT_WING_Z_DELTA 0.75f
11304 #define DEFAULT_WING_MAG (fl_sqrt(DEFAULT_WING_X_DELTA*DEFAULT_WING_X_DELTA + DEFAULT_WING_Y_DELTA*DEFAULT_WING_Y_DELTA + DEFAULT_WING_Z_DELTA*DEFAULT_WING_Z_DELTA))
11305 // next constant is higher that MAX_SHIPS_IN_WINGS to deal with forming on player's wing
11306 #define MAX_FORMATION_ROWS 4
11308 // Given a position in a wing, return the desired location of the ship relative to the leader
11309 // *_delta_vec OUTPUT. delta vector based on wing_index
11310 // wing_index position in wing.
11311 void get_wing_delta(vector *_delta_vec, int wing_index)
11315 SDL_assert(wing_index >= 0);
11317 int k, row, column;
11319 int bank = wing_index / (MAX_FORMATION_ROWS*(MAX_FORMATION_ROWS+1)/2);
11320 wi0 = wing_index % (MAX_FORMATION_ROWS * (MAX_FORMATION_ROWS+1)/2);
11323 for (row=1; row<MAX_FORMATION_ROWS+1; row++) {
11330 column = wi0 - k + row + 1;
11332 _delta_vec->xyz.x = ((float) column - (float) row/2.0f) * DEFAULT_WING_X_DELTA/DEFAULT_WING_MAG;
11333 _delta_vec->xyz.y = ((float)row + (float)bank*2.25f) * DEFAULT_WING_Y_DELTA/DEFAULT_WING_MAG;
11334 _delta_vec->xyz.z = - ((float)row + 0.5f * (float) bank) * DEFAULT_WING_Z_DELTA/DEFAULT_WING_MAG;
11337 // Compute the largest radius of a ship in a *objp's wing.
11338 float gwlr_1(object *objp, ai_info *aip)
11340 int wingnum = aip->wing;
11345 SDL_assert(wingnum >= 0);
11347 max_radius = objp->radius;
11349 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11350 o = &Objects[so->objnum];
11351 if (Ai_info[Ships[o->instance].ai_index].wing == wingnum)
11352 if (o->radius > max_radius)
11353 max_radius = o->radius;
11359 // Compute the largest radius of a ship forming on *objp's wing.
11360 float gwlr_object_1(object *objp, ai_info *aip)
11366 max_radius = objp->radius;
11368 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11369 o = &Objects[so->objnum];
11370 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == OBJ_INDEX(objp))
11371 if (o->radius > max_radius)
11372 max_radius = o->radius;
11378 // For the wing that *objp is part of, return the largest ship radius in that wing.
11379 float get_wing_largest_radius(object *objp, int formation_object_flag)
11384 SDL_assert(objp->type == OBJ_SHIP);
11385 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
11386 shipp = &Ships[objp->instance];
11387 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11388 aip = &Ai_info[shipp->ai_index];
11390 if (formation_object_flag) {
11391 return gwlr_object_1(objp, aip);
11393 return gwlr_1(objp, aip);
11398 float Wing_y_scale = 2.0f;
11399 float Wing_scale = 1.0f;
11400 DCF(wing_y_scale, "")
11402 dc_get_arg(ARG_FLOAT);
11403 Wing_y_scale = Dc_arg_float;
11406 DCF(wing_scale, "")
11408 dc_get_arg(ARG_FLOAT);
11409 Wing_scale = Dc_arg_float;
11412 // Given a wing leader and a position in the wing formation, return the desired absolute location to fly to.
11413 // Returns result in *result_pos.
11414 void get_absolute_wing_pos(vector *result_pos, object *leader_objp, int wing_index, int formation_object_flag)
11416 vector wing_delta, rotated_wing_delta;
11417 float wing_spread_size;
11419 get_wing_delta(&wing_delta, wing_index); // Desired location in leader's reference frame
11421 wing_spread_size = SDL_max(50.0f, 3.0f * get_wing_largest_radius(leader_objp, formation_object_flag) + 15.0f);
11423 // for player obj (1) move ships up 20% (2) scale formation up 20%
11424 if (leader_objp->flags & OF_PLAYER_SHIP) {
11425 wing_delta.xyz.y *= Wing_y_scale;
11426 wing_spread_size *= Wing_scale;
11429 vm_vec_scale(&wing_delta, wing_spread_size * (1.0f + leader_objp->phys_info.speed/70.0f));
11431 vm_vec_unrotate(&rotated_wing_delta, &wing_delta, &leader_objp->orient); // Rotate into leader's reference.
11433 vm_vec_add(result_pos, &leader_objp->pos, &rotated_wing_delta); // goal_point is absolute 3-space point.
11437 int Debug_render_wing_phantoms;
11439 void render_wing_phantoms(object *objp)
11445 int wing_index; // Index in wing struct, defines 3-space location in wing.
11448 SDL_assert(objp->type == OBJ_SHIP);
11449 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11451 shipp = &Ships[objp->instance];
11452 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11454 aip = &Ai_info[shipp->ai_index];
11456 wingnum = aip->wing;
11461 wing_index = get_wing_index(objp, wingnum);
11463 // If this ship is NOT the leader, abort.
11464 if (wing_index != 0)
11467 for (i=0; i<32; i++)
11468 if (Debug_render_wing_phantoms & (1 << i)) {
11469 get_absolute_wing_pos(&goal_point, objp, i, 0);
11472 gr_set_color(255, 0, 128);
11473 g3_rotate_vertex(&vert, &goal_point);
11474 g3_draw_sphere(&vert, 2.0f);
11477 Debug_render_wing_phantoms = 0;
11481 void render_wing_phantoms_all()
11486 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11490 int wing_index; // Index in wing struct, defines 3-space location in wing.
11492 objp = &Objects[so->objnum];
11494 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11495 shipp = &Ships[objp->instance];
11496 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11498 aip = &Ai_info[shipp->ai_index];
11500 wingnum = aip->wing;
11505 wing_index = get_wing_index(objp, wingnum);
11507 // If this ship is NOT the leader, abort.
11508 if (wing_index != 0)
11511 render_wing_phantoms(objp);
11519 // Hook from goals code to AI.
11520 // Force a wing to fly in formation.
11521 // Sets AIF_FORMATION bit in ai_flags.
11522 // wingnum Wing to force to fly in formation
11523 void ai_fly_in_formation(int wingnum)
11529 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11530 objp = &Objects[so->objnum];
11531 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11533 shipp = &Ships[objp->instance];
11534 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11536 if (Ai_info[shipp->ai_index].wing == wingnum) {
11537 Ai_info[shipp->ai_index].ai_flags |= AIF_FORMATION_WING;
11538 Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_OBJECT;
11543 // Hook from goals code to AI.
11544 // Force a wing to abandon formation flying.
11545 // Clears AIF_FORMATION bit in ai_flags.
11546 // wingnum Wing to force to fly in formation
11547 void ai_disband_formation(int wingnum)
11553 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11554 objp = &Objects[so->objnum];
11555 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11557 shipp = &Ships[objp->instance];
11558 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11560 if (Ai_info[shipp->ai_index].wing == wingnum) {
11561 Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_WING;
11566 float Leader_chaos = 0.0f;
11567 int Chaos_frame = -1;
11569 // Return true if objp is flying in an erratic manner
11570 // Only true if objp is a player
11571 int formation_is_leader_chaotic(object *objp)
11573 if (Game_mode & GM_MULTIPLAYER)
11576 if (objp != Player_obj)
11579 if (Framecount != Chaos_frame) {
11583 speed_scale = 3.0f + objp->phys_info.speed * 0.1f;
11585 fdot = 5.0f * (1.0f - vm_vec_dot(&objp->orient.v.fvec, &objp->last_orient.v.fvec)) * flFrametime;
11586 udot = 8.0f * (1.0f - vm_vec_dot(&objp->orient.v.uvec, &objp->last_orient.v.uvec)) * flFrametime;
11588 Leader_chaos += fdot * speed_scale + udot * speed_scale;
11590 Leader_chaos *= (1.0f - flFrametime*0.2f);
11592 if (Leader_chaos < 0.0f)
11593 Leader_chaos = 0.0f;
11594 else if (Leader_chaos > 1.7f)
11595 Leader_chaos = 1.7f;
11597 //nprintf(("AI", "Frame %i: chaos = %7.4f\n", Framecount, Leader_chaos));
11599 Chaos_frame = Framecount;
11602 return (Leader_chaos > 1.0f);
11605 // Fly in formation.
11606 // Make Pl_objp assume its proper place in formation.
11607 // If the leader of the wing is doing something stupid, like fighting a battle,
11608 // then the poor sap wingmates will be in for a "world of hurt"
11609 // Return TRUE if we need to process this object's normal mode
11612 object *leader_objp;
11614 ai_info *aip, *laip;
11616 int wing_index; // Index in wing struct, defines 3-space location in wing.
11617 int player_wing; // index of the players wingnum
11618 vector goal_point, future_goal_point_5, future_goal_point_2, future_goal_point_x, future_goal_point_1000x, vec_to_goal, dir_to_goal;
11619 float dot_to_goal, dist_to_goal, leader_speed;
11621 SDL_assert(Pl_objp->type == OBJ_SHIP);
11622 SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_SHIPS));
11624 shipp = &Ships[Pl_objp->instance];
11626 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11628 aip = &Ai_info[shipp->ai_index];
11630 SDL_assert((aip->ai_flags & AIF_FORMATION) != AIF_FORMATION); // Make sure not both types of formation flying in effect.
11632 // Determine which kind of formation flying.
11633 // If tracking an object, not in waypoint mode:
11634 if (aip->ai_flags & AIF_FORMATION_OBJECT) {
11635 if ((aip->goal_objnum < 0) || (aip->goal_objnum >= MAX_OBJECTS)) {
11636 aip->ai_flags &= ~AIF_FORMATION_OBJECT;
11640 wing_index = ai_formation_object_get_slotnum(aip->goal_objnum, Pl_objp);
11641 leader_objp = &Objects[aip->goal_objnum];
11642 } else { // Formation flying in waypoint mode.
11643 SDL_assert(aip->ai_flags & AIF_FORMATION_WING);
11644 if (aip->mode != AIM_WAYPOINTS) {
11645 aip->ai_flags &= ~AIF_FORMATION_WING;
11649 wingnum = aip->wing;
11654 // disable formation flying for any ship in the players wing
11655 player_wing = Ships[Player_obj->instance].wingnum;
11656 if ( (player_wing != -1) && (wingnum == player_wing) )
11659 wing_index = get_wing_index(Pl_objp, wingnum);
11661 leader_objp = get_wing_leader(wingnum);
11665 // If docked with a ship in this wing, only the more massive one actually flies in formation.
11666 if (aip->dock_objnum != -1) {
11667 object *other_objp = &Objects[aip->dock_objnum];
11668 ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
11670 if (aip->wing == other_aip->wing) {
11671 if (Pl_objp->phys_info.mass < other_objp->phys_info.mass)
11673 else if (Pl_objp->phys_info.mass == other_objp->phys_info.mass) {
11674 if (Pl_objp->signature < other_objp->signature)
11680 SDL_assert(leader_objp != NULL);
11681 laip = &Ai_info[Ships[leader_objp->instance].ai_index];
11683 // Make sure we're really in this wing.
11684 if (wing_index == -1)
11687 // If this ship is the leader, abort, as he doesn't have to follow anyone.
11688 if (wing_index == 0) {
11689 // nprintf(("AI", "Hmm, wing leader %s in ai_formation for no good reason.\n", shipp->ship_name));
11693 if (aip->mode == AIM_WAYPOINTS) {
11694 aip->wp_list = laip->wp_list;
11695 if (laip->wp_index < Waypoint_lists[laip->wp_list].count)
11696 aip->wp_index = laip->wp_index;
11698 aip->wp_index = Waypoint_lists[laip->wp_list].count - 1;
11699 aip->wp_flags = laip->wp_flags;
11700 aip->wp_dir = laip->wp_dir;
11704 Debug_render_wing_phantoms |= (1 << wing_index);
11707 leader_speed = leader_objp->phys_info.speed;
11708 vector leader_vec = leader_objp->phys_info.vel;
11710 get_absolute_wing_pos(&goal_point, leader_objp, wing_index, aip->ai_flags & AIF_FORMATION_OBJECT);
11711 vm_vec_scale_add(&future_goal_point_5, &goal_point, &leader_vec, 10.0f);
11712 vm_vec_scale_add(&future_goal_point_2, &goal_point, &leader_vec, 5.0f);
11713 vm_vec_scale_add(&future_goal_point_x, &goal_point, &leader_objp->orient.v.fvec, 10.0f); // used when very close to destination
11714 vm_vec_scale_add(&future_goal_point_1000x, &goal_point, &leader_objp->orient.v.fvec, 1000.0f); // used when very close to destination
11716 // Now, get information telling this object how to turn and accelerate to get to its
11717 // desired location.
11718 vm_vec_sub(&vec_to_goal, &goal_point, &Pl_objp->pos);
11719 if ( vm_vec_mag_quick(&vec_to_goal) < AICODE_SMALL_MAGNITUDE )
11720 vec_to_goal.xyz.x += 0.1f;
11722 vm_vec_copy_normalize(&dir_to_goal, &vec_to_goal);
11723 //dot_to_goal = vm_vec_dot(&dir_to_goal, &leader_objp->orient.v.fvec);
11724 dot_to_goal = vm_vec_dot(&dir_to_goal, &Pl_objp->orient.v.fvec);
11725 dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &goal_point);
11726 float dist_to_goal_2 = vm_vec_dist_quick(&Pl_objp->pos, &future_goal_point_2);
11728 // nprintf(("AI", "dot = %7.3f, dist = %8.3f, speed = %7.3f, leader speed = %7.3f\n", dot_to_goal, dist_to_goal, Pl_objp->phys_info.speed, leader_objp->phys_info.speed));
11730 int chaotic_leader = 0;
11732 chaotic_leader = formation_is_leader_chaotic(leader_objp); // Set to 1 if leader is player and flying erratically. Causes ships to not aggressively pursue formation location.
11734 if (dist_to_goal > 500.0f) {
11735 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11736 accelerate_ship(aip, 1.0f);
11737 } else if (dist_to_goal > 200.0f) {
11738 if (dot_to_goal > -0.5f) {
11739 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11740 float range_speed = shipp->current_max_speed - leader_speed;
11741 if (range_speed > 0.0f)
11742 set_accel_for_target_speed(Pl_objp, leader_speed + range_speed * (dist_to_goal+100.0f)/500.0f);
11744 set_accel_for_target_speed(Pl_objp, shipp->current_max_speed);
11746 turn_towards_point(Pl_objp, &future_goal_point_5, NULL, 0.0f);
11747 if (leader_speed > 10.0f)
11748 set_accel_for_target_speed(Pl_objp, leader_speed *(1.0f + dot_to_goal));
11750 set_accel_for_target_speed(Pl_objp, 10.0f);
11756 vm_vec_normalized_dir(&v2f2, &future_goal_point_2, &Pl_objp->pos);
11757 dot_to_f2 = vm_vec_dot(&v2f2, &Pl_objp->orient.v.fvec);
11759 // Leader flying like a maniac. Don't try hard to form on wing.
11760 if (chaotic_leader) {
11761 turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11762 set_accel_for_target_speed(Pl_objp, SDL_min(leader_speed*0.8f, 20.0f));
11763 } else if (dist_to_goal > 75.0f) {
11764 turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11766 float range_speed = shipp->current_max_speed - leader_speed;
11767 if (range_speed > 0.0f)
11768 delta_speed = dist_to_goal_2/500.0f * range_speed;
11770 delta_speed = shipp->current_max_speed - leader_speed;
11771 if (dot_to_goal < 0.0f) {
11772 delta_speed = -delta_speed;
11773 if (-delta_speed > leader_speed/2)
11774 delta_speed = -leader_speed/2;
11777 if (leader_speed < 5.0f)
11778 if (delta_speed < 5.0f)
11779 delta_speed = 5.0f;
11781 float scale = dot_to_f2;
11787 set_accel_for_target_speed(Pl_objp, scale * (leader_speed + delta_speed));
11789 //nprintf(("AI", "Dot = %7.3f\n", dot_to_goal));
11791 if (leader_speed < 5.0f) {
11792 // Leader very slow. If not close to goal point, get very close. Note, keep trying to get close unless
11793 // moving very slowly, else momentum can carry far away from goal.
11795 if ((dist_to_goal > 10.0f) || ((Pl_objp->phys_info.speed > leader_speed + 2.5f) && (dot_to_goal > 0.5f))) {
11796 //nprintf(("MK", "(1) "));
11797 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11798 set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/10.0f);
11800 if (Pl_objp->phys_info.speed < 0.5f) {
11801 //nprintf(("MK", "(2) "));
11802 turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11804 //nprintf(("MK", "(3) "));
11806 set_accel_for_target_speed(Pl_objp, leader_speed);
11808 //nprintf(("MK", "dist: %7.3f, dot: %6.3f, speed: %7.3f\n", dist_to_goal, dot_to_goal, Pl_objp->phys_info.speed));
11809 } else if (dist_to_goal > 10.0f) {
11812 //future_goal_point_2;
11814 turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11816 if (dist_to_goal > 25.0f) {
11817 if (dot_to_goal < 0.3f)
11820 dv = dot_to_goal - 0.2f;
11822 set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/5.0f * dv);
11824 set_accel_for_target_speed(Pl_objp, leader_speed + 1.5f * dot_to_goal - 1.0f);
11827 if (Pl_objp->phys_info.speed < 0.1f)
11828 turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11830 turn_towards_point(Pl_objp, &future_goal_point_x, NULL, 0.0f);
11831 set_accel_for_target_speed(Pl_objp, 0.0f);
11837 // See how different this ship's bank is relative to wing leader
11838 float up_dot = vm_vec_dot(&leader_objp->orient.v.uvec, &Pl_objp->orient.v.uvec);
11839 if (up_dot < 0.996f) {
11842 vector angular_accel;
11844 vm_vec_copy_scale(&angular_accel, &Pl_objp->phys_info.max_rotvel, 0.2f);
11845 vm_matrix_interpolate(&leader_objp->orient, &Pl_objp->orient, &Pl_objp->phys_info.rotvel, flFrametime, &new_orient, &w_out, &Pl_objp->phys_info.max_rotvel, &angular_accel, 1);
11847 // nprintf(("AI", "Frame %d Bashing formation orient. Dot was %6.3f, becomes %6.3f\n", Framecount, up_dot, vm_vec_dot(&leader_objp->orient.v.uvec, &new_orient.v.uvec)));
11848 Pl_objp->orient = new_orient;
11849 Pl_objp->phys_info.rotvel = w_out;
11850 // Pl_objp->phys_info.desired_rotvel = w_out;
11852 Pl_objp->phys_info.rotvel.xyz.z = 0.0f;
11858 // Return index of object repairing object objnum.
11859 int find_repairing_objnum(int objnum)
11866 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11867 objp = &Objects[so->objnum];
11869 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11871 shipp = &Ships[objp->instance];
11872 sip = &Ship_info[shipp->ship_info_index];
11874 if (sip->flags & SIF_SUPPORT) {
11877 aip = &Ai_info[shipp->ai_index];
11879 if (aip->goal_objnum == objnum) {
11880 return objp-Objects;
11888 // If object *objp is being repaired, deal with it!
11889 void ai_do_repair_frame(object *objp, ai_info *aip, float frametime)
11891 if (Ships[objp->instance].team == TEAM_TRAITOR) {
11892 ai_abort_rearm_request(objp);
11896 if (aip->ai_flags & (AIF_BEING_REPAIRED | AIF_AWAITING_REPAIR)) {
11898 ai_info *repair_aip;
11900 dock_objnum = aip->dock_objnum; // find_repairing_objnum(objp-Objects);
11901 //SDL_assert(dock_objnum != -1);
11902 if (dock_objnum == -1)
11904 if (Objects[dock_objnum].signature != aip->dock_signature) {
11905 Int3(); // Curious -- object numbers match, but signatures do not.
11906 // Must mean original repair ship died and was replaced by current ship.
11910 repair_aip = &Ai_info[Ships[Objects[dock_objnum].instance].ai_index];
11911 //SDL_assert(repair_aip->mode == AIM_DOCK);
11913 if (aip->ai_flags & AIF_BEING_REPAIRED) {
11914 // SDL_assert(repair_aip->submode == AIS_DOCK_4);
11916 // Wait awhile into the mode to synchronize with sound effect.
11917 if (Missiontime - repair_aip->submode_start_time > REARM_SOUND_DELAY) {
11920 repaired = ship_do_rearm_frame( objp, frametime ); // hook to do missile rearming
11922 // See if fully repaired. If so, cause process to stop.
11923 if ( repaired && (repair_aip->submode == AIS_DOCK_4)) {
11925 repair_aip->submode = AIS_UNDOCK_0;
11926 repair_aip->submode_start_time = Missiontime;
11928 // if repairing player object -- tell him done with repair
11929 if ( !MULTIPLAYER_CLIENT ){
11930 ai_do_objects_repairing_stuff( objp, &Objects[dock_objnum], REPAIR_INFO_COMPLETE );
11934 } else if (aip->ai_flags & AIF_AWAITING_REPAIR) {
11935 // If this ship has been awaiting repair for 90+ seconds, abort.
11936 if ( !MULTIPLAYER_CLIENT ) {
11937 if ((Game_mode & GM_MULTIPLAYER) || (objp != Player_obj)) {
11938 if ((repair_aip->goal_objnum == OBJ_INDEX(objp)) && (timestamp_elapsed(aip->abort_rearm_timestamp))) {
11939 ai_abort_rearm_request(objp);
11940 aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);
11946 // AL 11-24-97: If this is the player ship, ensure the repair sound isn't playing. We need to
11947 // do this check, since this is a looping sound, and may continue on if rearm/repair
11948 // finishes abnormally once sound begins looping.
11949 if ( objp == Player_obj ) {
11950 player_stop_repair_sound();
11955 // Shell around dock_orient_and_approach to detect whether dock process should be aborted.
11956 // obj1 is the ship performing the repair.
11957 // obj2 is the ship being repaired.
11958 void call_doa(object *obj1, object *obj2, ship_info *sip1)
11960 if (sip1->flags & SIF_SUPPORT) {
11961 if (obj2->phys_info.speed > MAX_REPAIR_SPEED) {
11963 // call the ai_abort rearm request code
11964 ai_abort_rearm_request( obj2 );
11966 dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11968 if (Ship_info[Ships[obj1->instance].ship_info_index].flags & SIF_CARGO)
11969 dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11970 else if (Ship_info[Ships[obj2->instance].ship_info_index].flags & SIF_CARGO)
11971 dock_orient_and_approach(obj2, obj1, DOA_DOCK_STAY);
11973 //mprintf(("Warning: Not sure, but making %s [%s] move to stay docked with %s [%s]\n",
11974 // Ships[obj1->instance].ship_name, Ship_info[Ships[obj1->instance].ship_info_index].name, Ships[obj2->instance].ship_name, Ship_info[Ships[obj2->instance].ship_info_index].name));
11975 dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11982 // Maybe launch a countermeasure.
11983 // Also, detect a supposed homing missile that no longer exists.
11984 void ai_maybe_launch_cmeasure(object *objp, ai_info *aip)
11990 shipp = &Ships[objp->instance];
11991 sip = &Ship_info[shipp->ship_info_index];
11993 if (!(sip->flags & (SIF_SMALL_SHIP | SIF_TRANSPORT)))
11996 if (!shipp->cmeasure_count)
11999 if ( !timestamp_elapsed(shipp->cmeasure_fire_stamp) )
12002 // If not on player's team and Skill_level + ai_class is low, never fire a countermeasure. The ship is too dumb.
12003 if (shipp->team != Player_ship->team) {
12004 if (Game_skill_level + aip->ai_class < 4){
12009 if ((aip->nearest_locked_object != -1) && (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)) {
12010 object *weapon_objp;
12012 weapon_objp = &Objects[aip->nearest_locked_object];
12014 if ((dist = vm_vec_dist_quick(&objp->pos, &weapon_objp->pos)) < weapon_objp->phys_info.speed*2.0f) {
12016 aip->nearest_locked_distance = dist;
12017 // Verify that this object is really homing on us.
12021 // For ships on player's team, have constant, average chance to fire.
12022 // For enemies, increasing chance with higher skill level.
12023 if (shipp->team == Player_ship->team)
12024 fire_chance = Cmeasure_fire_chance[NUM_SKILL_LEVELS/2];
12026 fire_chance = Cmeasure_fire_chance[Game_skill_level];
12028 // Decrease chance to fire at lower ai class.
12029 fire_chance *= (float) aip->ai_class/Num_ai_classes;
12032 if (fire_chance < r) {
12033 //nprintf(("AI", "Not firing countermeasure due to skill level: %7.3f < %7.3f\n", fire_chance, r));
12034 shipp->cmeasure_fire_stamp = timestamp(CMEASURE_WAIT + (int) (fire_chance*2000)); // Wait 1/2 second (CMEASURE_WAIT) + additional delay to decrease chance of firing very soon.
12038 if (weapon_objp->type == OBJ_WEAPON) {
12039 if (weapon_objp->instance >= 0) {
12040 //nprintf(("AI", "Firing countermeasure at time t=%7.3f\n", f2fl(Missiontime)));
12041 ship_launch_countermeasure(objp);
12042 shipp->cmeasure_fire_stamp = timestamp(2*CMEASURE_WAIT);
12053 // --------------------------------------------------------------------------
12054 void ai_preprocess_ignore_objnum(object *objp, ai_info *aip)
12056 // if (aip->ignore_objnum == UNUSED_OBJNUM)
12059 if (aip->ai_flags & AIF_TEMPORARY_IGNORE) {
12060 if (timestamp_elapsed(aip->ignore_expire_timestamp)) {
12061 aip->ignore_objnum = UNUSED_OBJNUM;
12065 if (is_ignore_object(aip, aip->goal_objnum)) {
12066 aip->goal_objnum = -1;
12067 // AL 12-11-97: If in STRAFE mode, we need to ensure that target_objnum is also
12069 if ( aip->mode == AIM_STRAFE ) {
12070 aip->target_objnum = -1;
12074 if (is_ignore_object(aip, aip->target_objnum))
12075 aip->target_objnum = -1;
12079 void ai_safety_circle_spot()
12084 sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12086 goal_point = Ai_info[Ships[Pl_objp->instance].ai_index].goal_point;
12087 turn_towards_tangent(Pl_objp, &goal_point, 50.0f);
12089 set_accel_for_target_speed(Pl_objp, sip->max_speed/4.0f);
12091 // float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
12092 // nprintf(("AI", "Ship %s circling %7.3f %7.3f %7.3f. Distance = %7.3f\n", Ships[Pl_objp->instance].ship_name, goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z, dist));
12097 #define CHASE_CIRCLE_DIST 100.0f
12099 void ai_chase_circle(object *objp)
12101 float dist_to_goal;
12102 float target_speed;
12107 sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12109 target_speed = sip->max_speed/4.0f;
12110 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12112 SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f); // Supposedly detects bogus vector
12114 goal_point = aip->goal_point;
12116 if (aip->ignore_objnum == UNUSED_OBJNUM) {
12117 dist_to_goal = vm_vec_dist_quick(&aip->goal_point, &objp->pos);
12119 if (dist_to_goal > 2*CHASE_CIRCLE_DIST) {
12120 vector vec_to_goal;
12121 // Too far from circle goal, create a new goal point.
12122 vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
12123 vm_vec_scale_add(&aip->goal_point, &objp->pos, &vec_to_goal, CHASE_CIRCLE_DIST);
12126 goal_point = aip->goal_point;
12127 } else if (is_ignore_object(aip, aip->ignore_objnum)) {
12128 object *ignore_objp = &Objects[aip->ignore_objnum];
12133 dist = vm_vec_normalized_dir(&tvec1, &Pl_objp->pos, &ignore_objp->pos);
12135 if (dist < ignore_objp->radius*2 + 1500.0f) {
12136 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &tvec1, ignore_objp->radius*2 + 1400.0f);
12137 if (dist < ignore_objp->radius*2 + 1300.0f)
12138 target_speed = sip->max_speed * (1.25f - dist/(ignore_objp->radius*2 + 1500.0f));
12142 SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f); // Supposedly detects bogus vector
12144 turn_towards_tangent(Pl_objp, &goal_point, 10*objp->radius + 200.0f);
12146 set_accel_for_target_speed(Pl_objp, target_speed);
12150 #define SHIELD_BALANCE_RATE 0.2f // 0.1f -> takes 10 seconds to equalize shield.
12152 // Transfer shield energy to most recently hit section from others.
12153 void ai_transfer_shield(object *objp, int quadrant_num)
12156 float transfer_amount;
12157 float transfer_delta;
12159 float max_quadrant_strength;
12161 sip = &Ship_info[Ships[objp->instance].ship_info_index];
12162 max_quadrant_strength = sip->shields/MAX_SHIELD_SECTIONS;
12164 transfer_amount = 0.0f;
12165 transfer_delta = (SHIELD_BALANCE_RATE/2) * max_quadrant_strength;
12167 if (objp->shields[quadrant_num] + (MAX_SHIELD_SECTIONS-1)*transfer_delta > max_quadrant_strength)
12168 transfer_delta = (max_quadrant_strength - objp->shields[quadrant_num])/(MAX_SHIELD_SECTIONS-1);
12170 for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12171 if (i != quadrant_num) {
12172 if (objp->shields[i] >= transfer_delta) {
12173 objp->shields[i] -= transfer_delta;
12174 transfer_amount += transfer_delta;
12176 transfer_amount += objp->shields[i];
12177 objp->shields[i] = 0.0f;
12181 objp->shields[quadrant_num] += transfer_amount;
12184 void ai_balance_shield(object *objp)
12187 float shield_strength_avg;
12191 shield_strength_avg = get_shield_strength(objp)/MAX_SHIELD_SECTIONS;
12193 delta = SHIELD_BALANCE_RATE * shield_strength_avg;
12195 for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12196 if (objp->shields[i] < shield_strength_avg) {
12197 add_shield_strength(objp, delta);
12198 if (objp->shields[i] > shield_strength_avg)
12199 objp->shields[i] = shield_strength_avg;
12201 add_shield_strength(objp, -delta);
12202 if (objp->shields[i] < shield_strength_avg)
12203 objp->shields[i] = shield_strength_avg;
12207 // Manage the shield for this ship.
12208 // Try to max out the side that was most recently hit.
12209 void ai_manage_shield(object *objp, ai_info *aip)
12213 sip = &Ship_info[Ships[objp->instance].ship_info_index];
12215 if (timestamp_elapsed(aip->shield_manage_timestamp)) {
12218 // Scale time until next manage shield based on Skill_level.
12219 // Ships on player's team are treated as if Skill_level is average.
12220 if (Ships[objp->instance].team != Player_ship->team){
12221 delay = Shield_manage_delays[Game_skill_level];
12223 delay = Shield_manage_delays[NUM_SKILL_LEVELS/2];
12226 // Scale between 1x and 3x based on ai_class
12227 delay = delay + delay * (float) (3*(Num_ai_classes - aip->ai_class - 1) / (Num_ai_classes - 1));
12228 aip->shield_manage_timestamp = timestamp((int) (delay * 1000.0f));
12230 if (sip->flags & SIF_SMALL_SHIP) {
12231 if (Missiontime - aip->last_hit_time < F1_0*10)
12232 ai_transfer_shield(objp, aip->last_hit_quadrant);
12234 ai_balance_shield(objp);
12237 // nprintf(("AI", "Time: %7.3f Next: %7.3f, Shields: %7.3f %7.3f %7.3f %7.3f\n", f2fl(Missiontime), f2fl(Missiontime) + delay, objp->shields[0], objp->shields[1], objp->shields[2], objp->shields[3]));
12241 // See if object *objp should evade an incoming missile.
12242 // *aip is the ai_info pointer within *objp.
12243 void ai_maybe_evade_locked_missile(object *objp, ai_info *aip)
12247 shipp = &Ships[objp->instance];
12249 // Only small ships evade an incoming missile. Why would a capital ship try to swerve?
12250 if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12254 if (aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) { // If not allowed to pursue dynamic objectives, don't evade. Dumb? Maybe change. -- MK, 3/15/98
12258 if (aip->nearest_locked_object != -1) {
12259 object *missile_objp;
12261 missile_objp = &Objects[aip->nearest_locked_object];
12263 if (Weapons[missile_objp->instance].homing_object != objp) {
12264 //nprintf(("AI", "\nMissile lost home!"));
12265 aip->nearest_locked_object = -1;
12269 if ((missile_objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[missile_objp->instance].weapon_info_index].wi_flags & WIF_HOMING)) {
12270 float dist = vm_vec_dist_quick(&missile_objp->pos, &objp->pos);
12271 float dist2 = 4.0f * vm_vec_mag_quick(&missile_objp->phys_info.vel);
12272 if (dist < dist2) {
12273 switch (aip->mode) {
12274 // If in AIM_STRAFE mode, don't evade if parent of weapon is targeted ship.
12276 if ((missile_objp->parent != -1) && (missile_objp->parent == aip->target_objnum)) {
12279 ; // Alan -- If you want to handle incoming weapons from someone other than the ship
12280 // the strafing ship is attacking, do it here.
12284 // Don't always go into evade weapon mode. Usually, a countermeasure gets launched.
12285 // If low on countermeasures, more likely to try to evade. If 8+, never evade due to low cmeasures.
12286 if (((((Missiontime >> 18) ^ OBJ_INDEX(objp)) & 3) == 0) ||
12287 (objp->phys_info.speed < 40.0f) ||
12288 (frand() < 1.0f - (float) shipp->cmeasure_count/8.0f)) {
12289 if (aip->submode != SM_ATTACK_FOREVER) { // SM_ATTACK_FOREVER means engines blown.
12290 aip->submode = SM_EVADE_WEAPON;
12291 aip->submode_start_time = Missiontime;
12295 case AIM_DOCK: // Ships in dock mode can evade iif they are not currently repairing or docked.
12296 if (aip->ai_flags & (AIF_REPAIRING | AIF_DOCKED))
12299 // If in guard mode and far away from guard object, don't pursue guy that hit me.
12300 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12301 if (vm_vec_dist_quick(&objp->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12306 case AIM_GET_BEHIND:
12307 case AIM_STAY_NEAR:
12310 case AIM_WAYPOINTS:
12314 case AIM_BE_REARMED:
12316 case AIM_BAY_EMERGE:
12317 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12318 aip->previous_mode = aip->mode;
12319 aip->previous_submode = aip->submode;
12320 aip->mode = AIM_EVADE_WEAPON;
12322 aip->submode_start_time = Missiontime;
12323 aip->mode_time = timestamp(MAX_EVADE_TIME); // Max time to evade.
12324 //nprintf(("AI", "%s Evade weapon in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
12326 case AIM_EVADE_WEAPON: // Note: We don't want to change mode on another evasion, or previous_mode will get bashed.
12327 case AIM_PLAY_DEAD:
12328 case AIM_BAY_DEPART:
12329 case AIM_SENTRYGUN:
12334 Int3(); // Hey, what mode is it?
12339 aip->nearest_locked_object = -1;
12344 // Maybe evade a dumbfire weapon that was fired when Pl_objp was targeted.
12345 // Have an 80% chance of evading in a second
12346 void maybe_evade_dumbfire_weapon(ai_info *aip)
12348 // Only small ships evade an incoming missile. Why would a capital ship try to swerve?
12349 if (!(Ship_info[Ships[Pl_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12353 // Make sure in a mode in which we evade dumbfire weapons.
12354 switch (aip->mode) {
12356 if (aip->submode == SM_ATTACK_FOREVER) {
12360 // If in guard mode and far away from guard object, don't pursue guy that hit me.
12361 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12362 if (vm_vec_dist_quick(&Objects[Ships[aip->shipnum].objnum].pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12367 case AIM_STAY_NEAR:
12369 case AIM_GET_BEHIND:
12373 case AIM_WAYPOINTS:
12379 case AIM_PLAY_DEAD:
12380 case AIM_EVADE_WEAPON:
12381 case AIM_BAY_EMERGE:
12382 case AIM_BAY_DEPART:
12383 case AIM_SENTRYGUN:
12387 Int3(); // Bogus mode!
12391 if (is_instructor(&Objects[Ships[aip->shipnum].objnum]))
12392 return; // Instructor doesn't evade.
12394 float t = ai_endangered_by_weapon(aip);
12395 if ((t > 0.0f) && (t < 1.0f)) {
12396 // Check if this weapon is from a large ship Pl_objp is attacking... if so, enter strafe mode
12397 if ( ai_big_maybe_enter_strafe_mode(Pl_objp, aip->danger_weapon_objnum) ) {
12401 switch (aip->mode) {
12403 switch (aip->submode) {
12405 case SM_ATTACK_FOREVER:
12408 case SM_EVADE_WEAPON:
12411 if (ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
12412 //mprintf(("Ship %s entered super mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12413 aip->submode = SM_SUPER_ATTACK;
12414 aip->submode_start_time = Missiontime;
12415 aip->last_attack_time = Missiontime;
12417 //mprintf(("Ship %s entered dumbfire evade mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12418 aip->submode = SM_EVADE_WEAPON;
12419 aip->submode_start_time = Missiontime;
12426 case AIM_STAY_NEAR:
12428 case AIM_GET_BEHIND:
12432 case AIM_WAYPOINTS:
12434 if (!(aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) && (Ship_info[Ships[aip->shipnum].ship_info_index].flags & SIF_SMALL_SHIP)) {
12435 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12436 aip->previous_mode = aip->mode;
12437 aip->previous_submode = aip->submode;
12438 aip->mode = AIM_EVADE_WEAPON;
12440 aip->submode_start_time = Missiontime;
12441 aip->mode_time = timestamp(MAX_EVADE_TIME); // Evade for up to five seconds.
12447 case AIM_PLAY_DEAD:
12448 case AIM_EVADE_WEAPON:
12449 case AIM_BAY_EMERGE:
12450 case AIM_BAY_DEPART:
12451 case AIM_SENTRYGUN:
12454 Int3(); // Bogus mode!
12459 // determine what path to use when emerging from a fighter bay
12460 // input: pl_objp => pointer to object for ship that is arriving
12461 // pos => output parameter, it is the starting world pos for path choosen
12462 // v.fvec => output parameter, this is the forward vector that ship has when arriving
12464 // exit: -1 => path could not be located
12466 int ai_acquire_emerge_path(object *pl_objp, int parent_objnum, vector *pos, vector *fvec)
12468 int path_index, sb_path_index;
12469 ship *parent_sp = NULL;
12474 vector *next_point;
12476 aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12478 if ( parent_objnum == -1 ) {
12483 parent_sp = &Ships[Objects[parent_objnum].instance];
12485 SDL_assert(parent_sp != NULL);
12486 pm = model_get( parent_sp->modelnum );
12492 if ( sb->num_paths <= 0 )
12495 // try to find a bay path that is not taken
12496 sb_path_index = Ai_last_arrive_path++;
12498 if ( sb_path_index >= sb->num_paths ) {
12500 Ai_last_arrive_path=0;
12503 path_index = sb->paths[sb_path_index];
12504 if ( path_index == -1 )
12507 // create the path for pl_objp to follow
12508 create_model_exit_path(pl_objp, &Objects[parent_objnum], path_index, pm->paths[path_index].nverts);
12510 // Set this flag, so we don't bother recreating the path... we won't need to update the path
12511 // that has just been created.
12512 // aip->ai_flags |= AIF_USE_STATIC_PATH;
12514 // now return to the caller what the starting world pos and starting fvec for the ship will be
12515 SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
12516 pnp = &Path_points[aip->path_start];
12519 // calc the forward vector using the starting two points of the path
12520 pnp = &Path_points[aip->path_start+1];
12521 next_point = &pnp->pos;
12522 vm_vec_normalized_dir(fvec, next_point, pos);
12524 // record the parent objnum, since we'll need it once we're done with following the path
12525 aip->goal_objnum = parent_objnum;
12526 aip->goal_signature = Objects[parent_objnum].signature;
12527 aip->mode = AIM_BAY_EMERGE;
12528 aip->submode_start_time = Missiontime;
12530 // set up starting vel
12533 speed = Ship_info[Ships[pl_objp->instance].ship_info_index].max_speed;
12535 vm_vec_scale( &vel, speed );
12536 pl_objp->phys_info.vel = vel;
12537 pl_objp->phys_info.desired_vel = vel;
12538 pl_objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
12539 pl_objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
12540 pl_objp->phys_info.prev_ramp_vel.xyz.z = speed;
12541 pl_objp->phys_info.forward_thrust = 0.0f; // How much the forward thruster is applied. 0-1.
12546 // clean up path data used for emerging from a fighter bay
12547 void ai_emerge_bay_path_cleanup(ai_info *aip)
12549 aip->path_start = -1;
12550 aip->path_cur = -1;
12551 aip->path_length = 0;
12552 aip->mode = AIM_NONE;
12555 // handler for AIM_BAY_EMERGE
12556 void ai_bay_emerge()
12561 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12563 // if no path to follow, leave this mode
12564 if ( aip->path_start < 0 ) {
12565 aip->mode = AIM_NONE;
12569 // ensure parent ship is still alive
12570 if ( aip->goal_objnum < 0 ) {
12573 if ( !parent_died ) {
12574 if ( Objects[aip->goal_objnum].signature != aip->goal_signature ) {
12579 if ( !parent_died ) {
12580 SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
12581 if ( Ships[Objects[aip->goal_objnum].instance].flags & SF_DYING ) {
12586 if ( parent_died ) {
12587 ai_emerge_bay_path_cleanup(aip);
12591 // follow the path to the final point
12594 // New test: must have been in AI_EMERGE mode for at least 10 seconds, and be a minimum distance from the start point
12595 if ( ( (Missiontime - aip->submode_start_time) > 10*F1_0 ) && (vm_vec_dist_quick(&Pl_objp->pos, &Objects[aip->goal_objnum].pos) > 0.75f * Objects[aip->goal_objnum].radius)) {
12597 ai_emerge_bay_path_cleanup(aip);
12600 // 2-25-99: Need this check to fix an assert for supercap ships... maybe we'll only do this check for supercaps
12601 if (aip->path_cur > (aip->path_start+aip->path_length-1)) {
12602 ai_emerge_bay_path_cleanup(aip);
12606 // Select the closest depart path
12608 // input: aip => ai info pointer to ship seeking to depart
12609 // pm => pointer to polymodel for the ship contining the ship bay/depart paths
12611 // exit: >=0 => ship bay path index for depart path (ie index into sb->paths[])
12612 // -1 => no path could be found
12614 // NOTE: this function should only be used for calculating closest depart paths for ai mode
12615 // AI_BAY_DEPART. It tries to find the closest path that isn't already in use
12616 int ai_find_closest_depart_path(ai_info *aip, polymodel *pm)
12618 int i, j, best_path, best_free_path;
12619 float dist, min_dist, min_free_dist;
12626 best_free_path = best_path = -1;
12627 min_free_dist = min_dist = 1e20f;
12628 SDL_assert(aip->shipnum >= 0);
12629 source = &Objects[Ships[aip->shipnum].objnum].pos;
12631 for ( i = 0; i < sb->num_paths; i++ ) {
12634 mp = &pm->paths[sb->paths[i]];
12635 for ( j = 0; j < mp->nverts; j++ ) {
12636 dist = vm_vec_dist_squared(source, &mp->verts[j].pos);
12638 if ( dist < min_dist ) {
12643 // If this is a free path
12644 if ( !(sb->depart_flags & (1<<i)) ) {
12645 if ( dist < min_free_dist ) {
12646 min_free_dist = dist;
12647 best_free_path = i;
12653 if ( best_free_path >= 0 ) {
12654 return best_free_path;
12660 // determine what path to use when trying to depart to a fighter bay
12661 // NOTE: this should be called when AIM_BAY_DEPART mode is set
12663 // input: pl_objp => pointer to object for ship that is departing
12665 // exit: -1 => could not find depart path
12666 // 0 => found depart path
12667 int ai_acquire_depart_path(object *pl_objp, int parent_objnum)
12669 int objnum, path_index;
12675 aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12677 if ( parent_objnum == -1 ) {
12680 // for now just locate a captial ship on the same team:
12681 so = GET_FIRST(&Ship_obj_list);
12683 while(so != END_OF_LIST(&Ship_obj_list)){
12684 sp = &Ships[Objects[so->objnum].instance];
12685 if ( (Ship_info[sp->ship_info_index].flags & (SIF_HUGE_SHIP)) && (sp->team == Ships[pl_objp->instance].team) ) {
12686 objnum = so->objnum;
12692 objnum = parent_objnum;
12695 aip->path_start = -1;
12697 if ( objnum == -1 )
12700 pm = model_get( Ships[Objects[objnum].instance].modelnum );
12705 if ( sb->num_paths <= 0 )
12711 for ( i = 0; i < sb->num_paths; i++ ) {
12712 if ( !(sb->depart_flags & (1<<i)) ) {
12713 sb->depart_flags |= (1<<i);
12714 path_index = sb->paths[i];
12715 aip->submode_parm0 = i; // use mode-specific parameter to record ship bay path index
12721 // take the closest path we can find
12723 ship_bay_path = ai_find_closest_depart_path(aip, pm);
12725 if (ship_bay_path == -1) {
12729 path_index = sb->paths[ship_bay_path];
12730 aip->submode_parm0 = ship_bay_path;
12731 sb->depart_flags |= (1<<ship_bay_path);
12733 if ( path_index == -1 ) {
12737 SDL_assert(pm->n_paths > path_index);
12738 ai_find_path(pl_objp, objnum, path_index, 0);
12740 // Set this flag, so we don't bother recreating the path... we won't need to update the path
12741 // that has just been created.
12742 aip->ai_flags &= ~AIF_USE_STATIC_PATH;
12744 aip->goal_objnum = objnum;
12745 aip->goal_signature = Objects[objnum].signature;
12746 aip->mode = AIM_BAY_DEPART;
12748 Ships[pl_objp->instance].flags |= SF_DEPART_DOCKBAY;
12752 // handler for AIM_BAY_DEPART
12753 void ai_bay_depart()
12757 aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12759 // if no path to follow, leave this mode
12760 if ( aip->path_start < 0 ) {
12761 aip->mode = AIM_NONE;
12765 // check if parent ship still exists, if not abort depart
12766 if ( aip->goal_signature != Objects[aip->goal_objnum].signature ) {
12767 aip->mode = AIM_NONE;
12771 // follow the path to the final point
12774 // if the final point is reached, let default AI take over
12775 if ( aip->path_cur >= (aip->path_start+aip->path_length) ) {
12779 pm = model_get( Ships[Objects[aip->goal_objnum].instance].modelnum );
12781 if ( sb != NULL ) {
12782 sb->depart_flags &= ~(1<<aip->submode_parm0);
12785 // make ship disappear
12786 Pl_objp->flags |= OF_SHOULD_BE_DEAD;
12787 ship_departed( Pl_objp->instance );
12789 // clean up path stuff
12790 aip->path_start = -1;
12791 aip->path_cur = -1;
12792 aip->path_length = 0;
12793 aip->mode = AIM_NONE;
12797 // Handler for AIM_SENTRYGUN. This AI mode is for sentry guns only (ie floating turrets).
12798 void ai_sentrygun()
12800 // Nothing to do here. Turret firing is handled via process_subobjects().
12801 // If you want the sentry guns to do anything beyond firing their turrets at enemies, add it here!
12804 // --------------------------------------------------------------------------
12805 // Execute behavior given by aip->mode.
12806 void ai_execute_behavior(ai_info *aip)
12808 switch (aip->mode) {
12812 } else if (aip->submode == SM_EVADE_WEAPON) {
12814 // maybe reset submode
12815 if (aip->danger_weapon_objnum == -1) {
12816 aip->submode = SM_ATTACK;
12817 aip->submode_start_time = Missiontime;
12818 aip->last_attack_time = Missiontime;
12821 // Don't circle if this is the instructor.
12822 ship *shipp = &Ships[aip->shipnum];
12823 ship_info *sip = &Ship_info[shipp->ship_info_index];
12825 if (SDL_strncasecmp(shipp->ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME))) {
12826 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
12827 aip->mode = AIM_NONE;
12829 ai_chase_circle(Pl_objp);
12839 vm_vec_scale_add(&tvec, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 100.0f);
12840 turn_towards_point(Pl_objp, &tvec, NULL, 0.0f);
12841 accelerate_ship(aip, 0.5f);
12847 case AIM_STAY_NEAR:
12853 case AIM_WAYPOINTS:
12863 ai_big_ship(Pl_objp);
12867 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], 0);
12868 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
12875 case AIM_EVADE_WEAPON:
12880 SDL_assert(En_objp->type == OBJ_SHIP);
12881 ai_big_strafe(); // strafe a big ship
12883 aip->mode = AIM_NONE;
12886 case AIM_BAY_EMERGE:
12889 case AIM_BAY_DEPART:
12892 case AIM_SENTRYGUN:
12896 break; // Note, handled directly from ai_frame().
12898 Int3(); // This should never happen -- MK, 5/12/97
12902 if ( !(ship_get_SIF(aip->shipnum) & SIF_NOT_FLYABLE) ) {
12903 maybe_evade_dumbfire_weapon(aip);
12907 // Auxiliary function for maybe_request_support.
12908 // Return 1 if subsystem "type" is worthy of repair, else return 0.
12909 // Since subsystems cannot be repaired if they are at 0 strength, don't return 1 if subsystem is dead.
12910 int mrs_subsystem(ship *shipp, int type)
12914 t = ship_get_subsystem_strength(shipp, type);
12917 return (int) ((1.0f - t) * 3);
12923 // Return number of ships on *objp's team that are currently rearming.
12924 int num_allies_rearming(object *objp)
12930 team = Ships[objp->instance].team;
12932 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
12935 SDL_assert (so->objnum != -1);
12936 A = &Objects[so->objnum];
12938 if (Ships[A->instance].team == team) {
12939 if (Ai_info[Ships[A->instance].ai_index].ai_flags & (AIF_REPAIRING | AIF_AWAITING_REPAIR)) {
12949 // Maybe ship *objp should request support (rearm/repair).
12950 // If it does, return TRUE, else return FALSE.
12951 int maybe_request_support(object *objp)
12958 SDL_assert(objp->type == OBJ_SHIP);
12959 shipp = &Ships[objp->instance];
12960 aip = &Ai_info[shipp->ai_index];
12961 sip = &Ship_info[shipp->ship_info_index];
12963 if (!timestamp_elapsed(aip->next_rearm_request_timestamp))
12966 // Only fighters and bombers request support.
12967 if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER)))
12970 // A ship that is currently awaiting does not need support!
12971 if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
12974 if (!is_support_allowed(objp))
12977 //if (shipp->team != TEAM_FRIENDLY)
12980 // Compute a desire value.
12981 // Desire of 0 means no reason to request support.
12982 // 1 is slight, 2 more, etc. Maximum is around 20. Anything larger than 3 is pretty strong.
12985 // Set desire based on hull strength.
12986 // No: We no longer repair hull, so this would cause repeated repair requests.
12987 //desire += 6 - (int) ((objp->hull_strength/sip->initial_hull_strength) * 6.0f);
12989 // Set desire based on key subsystems.
12990 desire += 2*mrs_subsystem(shipp, SUBSYSTEM_ENGINE); // Note, disabled engine forces repair request, regardless of nearby enemies.
12991 desire += mrs_subsystem(shipp, SUBSYSTEM_COMMUNICATION);
12992 desire += mrs_subsystem(shipp, SUBSYSTEM_WEAPONS);
12993 desire += mrs_subsystem(shipp, SUBSYSTEM_SENSORS);
12995 // Set desire based on percentage of secondary weapons.
12996 ship_weapon *swp = &shipp->weapons;
12998 for ( int i = 0; i < swp->num_secondary_banks; i++ ) {
12999 if (swp->secondary_bank_start_ammo[i] > 0) {
13000 // float r = (float) swp->secondary_bank_ammo[i]*Weapon_info[swp->secondary_bank_weapons[i]].cargo_size/swp->secondary_bank_capacity[i];
13001 float r = (float) swp->secondary_bank_ammo[i]/swp->secondary_bank_start_ammo[i];
13002 desire += (int) ((1.0f - r) * 3.0f);
13006 // If no reason to repair, don't bother to see if it's safe to repair.
13011 // Compute danger threshold.
13012 // Balance this with desire and maybe request support.
13013 if (ai_good_time_to_rearm( objp )) {
13014 ai_issue_rearm_request(objp);
13016 } else if (num_allies_rearming(objp) < 2) {
13017 if (desire >= 8) { // guarantees disabled will cause repair request
13018 ai_issue_rearm_request(objp);
13019 } else if (desire >= 3) { // >= 3 means having a single subsystem fully blown will cause repair.
13021 int objnum = find_nearby_hostile(OBJ_INDEX(objp), get_enemy_team_mask(OBJ_INDEX(objp)), 2000.0f, &count);
13023 if ((objnum == -1) || (count < 2) || (vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos) > 3000.0f*count/desire)) {
13024 ai_issue_rearm_request(objp);
13027 //nprintf(("AI", "Would like to rearm, but enemy only %7.3f units away.\n", vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos)));
13036 void ai_set_mode_warp_out(object *objp, ai_info *aip)
13038 ai_abort_rearm_request(objp);
13039 if (aip->mode != AIM_WARP_OUT) {
13040 aip->mode = AIM_WARP_OUT;
13041 aip->submode = AIS_WARP_1;
13045 // Maybe warp ship out.
13046 // Shivan and HoL fighter/bomber warp out if their weapons subsystems have been destroyed.
13047 void ai_maybe_warp_out(object *objp)
13051 // don't do anything if in a training mission.
13052 if ( The_mission.game_type & MISSION_TYPE_TRAINING )
13055 SDL_assert(objp->type == OBJ_SHIP);
13057 shipp = &Ships[objp->instance];
13058 ai_info *aip = &Ai_info[shipp->ai_index];
13060 if (aip->mode == AIM_WARP_OUT)
13063 // If a support ship with no goals and low hull, warp out. Be sure that there are no pending goals
13064 // in the support ships ai_goal array. Just process this ships goals.
13065 ship_info *sip = &Ship_info[shipp->ship_info_index];
13066 if (sip->flags & SIF_SUPPORT) {
13067 if ( timestamp_elapsed(aip->warp_out_timestamp) ) {
13068 ai_process_mission_orders( OBJ_INDEX(objp), aip );
13069 if ( (aip->dock_objnum == -1) && (objp->hull_strength/sip->initial_hull_strength < 0.25f) ) {
13070 ai_set_mode_warp_out(objp, aip);
13075 // Friendly don't warp out, they'll eventually request support.
13076 if (shipp->team == TEAM_FRIENDLY)
13079 if (!(shipp->flags & SF_DEPARTING)) {
13080 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
13081 if (aip->warp_out_timestamp == 0) {
13082 //if (ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS) == 0.0f) {
13083 // aip->warp_out_timestamp = timestamp(((myrand() % 10) + 10) * 1000);
13085 } else if (timestamp_elapsed(aip->warp_out_timestamp)) {
13086 ai_set_mode_warp_out(objp, aip);
13092 // Warp this ship out.
13093 void ai_warp_out(object *objp)
13095 // if dying, don't warp out.
13096 if (Ships[objp->instance].flags & SF_DYING) {
13102 aip = &Ai_info[Ships[objp->instance].ai_index];
13104 switch (aip->submode) {
13106 aip->force_warp_time = timestamp(10*1000); // Try to avoid a collision for up to ten seconds.
13107 aip->submode = AIS_WARP_2;
13109 case AIS_WARP_2: // Make sure won't collide with any object.
13110 if (timestamp_elapsed(aip->force_warp_time) || !collide_predict_large_ship(objp, objp->radius*2.0f + 100.0f)) {
13111 aip->submode = AIS_WARP_3;
13113 // maybe recalculate collision pairs.
13114 if (ship_get_warp_speed(objp) > ship_get_max_speed(&Ships[objp->instance])) {
13115 // recalculate collision pairs
13116 OBJ_RECALC_PAIRS(objp);
13119 aip->force_warp_time = timestamp(4*1000); // Try to attain target speed for up to 4 seconds.
13122 vm_vec_scale_add(&goal_point, &objp->pos, &objp->orient.v.uvec, 100.0f);
13123 turn_towards_point(objp, &goal_point, NULL, 0.0f);
13124 accelerate_ship(aip, 0.0f);
13128 // Rampup desired_vel in here from current to desired velocity and set PF_USE_VEL. (not sure this is the right flag)
13129 // desired velocity is computed in shipfx_calculate_warp_time(). See shipfx#572 for sample code.
13130 float speed, goal_speed;
13131 float shipfx_calculate_warp_speed(object*);
13132 goal_speed = shipfx_calculate_warp_speed(objp);
13134 // HUGE ships go immediately to AIS_WARP_4
13135 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
13136 aip->submode = AIS_WARP_4;
13139 //compute_warpout_stuff(objp, &goal_speed, &warp_time, &warp_pos);
13140 //goal_speed = 80.0f;
13141 //set_accel_for_target_speed(objp, 40.0f);
13142 // DKA 8/11/99 objp->phys_info.flags |= PF_USE_VEL; This flag is set in object code if warping out and AIS_WARP >= 3, properly accounting for blown engines
13143 speed = goal_speed * flFrametime + objp->phys_info.speed * (1.0f - flFrametime);
13144 vm_vec_copy_scale(&objp->phys_info.vel, &objp->orient.v.fvec, speed);
13145 objp->phys_info.desired_vel = objp->phys_info.vel;
13146 // nprintf(("AI", "Frame %i, speed = %7.3f, goal = %7.3f\n", Framecount, vm_vec_mag_quick(&objp->phys_info.vel), goal_speed));
13147 if (timestamp_elapsed(aip->force_warp_time) || (fl_abs(objp->phys_info.speed - goal_speed) < 2.0f))
13148 aip->submode = AIS_WARP_4;
13151 shipfx_warpout_start(objp);
13152 aip->submode = AIS_WARP_5;
13158 Int3(); // Illegal submode for warping out.
13162 // Return object index of weapon that could produce a shockwave that should be known about to *objp.
13163 // Return nearest one.
13164 int ai_find_shockwave_weapon(object *objp, ai_info *aip)
13167 float nearest_dist = 999999.9f;
13168 int nearest_index = -1;
13170 for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
13175 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
13176 A = &Objects[mo->objnum];
13178 SDL_assert(A->type == OBJ_WEAPON);
13179 SDL_assert((A->instance >= 0) && (A->instance < MAX_WEAPONS));
13180 wp = &Weapons[A->instance];
13181 wip = &Weapon_info[wp->weapon_info_index];
13182 SDL_assert( wip->subtype == WP_MISSILE );
13184 if (wip->shockwave_speed > 0.0f) {
13187 dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13188 if (dist < nearest_dist) {
13189 nearest_dist = dist;
13190 nearest_index = mo->objnum;
13195 return nearest_index;
13199 #define EVADE_SHOCKWAVE_DAMAGE_THRESHOLD 100.0f
13201 // Tell all ships to avoid a big ship that is blowing up.
13202 // Only avoid if shockwave is fairly large.
13203 // OK to tell everyone to avoid. If they're too far away, that gets cleaned up in the frame interval.
13204 void ai_announce_ship_dying(object *dying_objp)
13206 float damage = ship_get_exp_damage(dying_objp);
13207 if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {
13210 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13211 if (Ship_info[Ships[Objects[so->objnum].instance].ship_info_index].flags & (SIF_SMALL_SHIP | SIF_FREIGHTER)) {
13214 aip = &Ai_info[Ships[Objects[so->objnum].instance].ai_index];
13216 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
13217 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_SHIP;
13225 // Return object index of weapon that could produce a shockwave that should be known about to *objp.
13226 // Return nearest one.
13227 int ai_find_shockwave_ship(object *objp, ai_info *aip)
13230 float nearest_dist = 999999.9f;
13231 int nearest_index = -1;
13233 for ( so = GET_NEXT(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13237 SDL_assert(so->objnum >= 0 && so->objnum < MAX_OBJECTS);
13238 A = &Objects[so->objnum];
13240 SDL_assert(A->type == OBJ_SHIP);
13241 SDL_assert((A->instance >= 0) && (A->instance < MAX_SHIPS));
13242 shipp = &Ships[A->instance];
13243 // Only look at objects in the process of dying.
13244 if (shipp->flags & SF_DYING) {
13245 float damage = ship_get_exp_damage(objp);
13247 if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) { // Only evade quite large blasts
13250 dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13251 if (dist < nearest_dist) {
13252 nearest_dist = dist;
13253 nearest_index = so->objnum;
13259 return nearest_index;
13263 int aas_1(object *objp, ai_info *aip, vector *safe_pos)
13265 // MAKE SURE safe_pos DOES NOT TAKE US TOWARD THE A SHIP WE'RE ATTACKING.
13266 if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_WEAPON) {
13267 // If we don't currently know of a weapon to avoid, try to find one.
13268 // If we can't find one, then clear the bit so we don't keep coming here.
13269 if (aip->shockwave_object == -1) {
13270 int shockwave_weapon = ai_find_shockwave_weapon(objp, aip);
13271 if (shockwave_weapon == -1) {
13272 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13275 aip->shockwave_object = shockwave_weapon;
13279 // OK, we have reason to believe we should avoid aip->shockwave_object.
13280 SDL_assert(aip->shockwave_object > -1);
13281 object *weapon_objp = &Objects[aip->shockwave_object];
13282 if (weapon_objp->type != OBJ_WEAPON) {
13283 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13284 aip->shockwave_object = -1;
13288 weapon *weaponp = &Weapons[weapon_objp->instance];
13289 weapon_info *wip = &Weapon_info[weaponp->weapon_info_index];
13290 object *target_ship_obj = NULL;
13292 if (wip->shockwave_speed == 0.0f) {
13293 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13294 aip->shockwave_object = -1;
13299 vector expected_pos; // Position at which we expect the weapon to detonate.
13302 danger_dist = wip->outer_radius;
13303 // Set predicted position of detonation.
13304 // If an aspect locked missile, assume it will detonate at the homing position.
13305 // If not, which is not possible in a default FreeSpace weapon, then predict it will detonate at some
13306 // time in the future, this time based on max lifetime and life left.
13307 if (wip->wi_flags & WIF_HOMING_ASPECT) {
13308 expected_pos = weaponp->homing_pos;
13309 // if (weaponp->homing_object && weaponp->homing_object->type == OBJ_SHIP) {
13310 // target_ship_obj = weaponp->homing_object;
13313 if (IS_VEC_NULL(&weaponp->homing_pos)) {
13315 if (weaponp->target_num != -1) {
13316 if (Objects[weaponp->target_num].type == OBJ_SHIP) {
13317 target_ship_obj = &Objects[weaponp->target_num];
13318 expected_pos = target_ship_obj->pos;
13328 if (wip->lifetime - weaponp->lifeleft > 5.0f) {
13331 time_scale = weaponp->lifeleft/2.0f;
13334 vm_vec_scale_add(&expected_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, time_scale);
13337 // See if too far away to care about shockwave.
13338 if (vm_vec_dist_quick(&objp->pos, &expected_pos) > danger_dist*2.0f) {
13339 //aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13342 // try to find a safe position
13343 vector vec_from_exp;
13345 vm_vec_sub(&vec_from_exp, &objp->pos, &expected_pos);
13346 float dot = vm_vec_dotprod(&vec_from_exp, &weapon_objp->orient.v.fvec);
13348 // if we're already on the other side of the explosion, don't try to fly behind it
13352 // Fly towards a point behind the weapon.
13353 vm_vec_scale_add(safe_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, -50000.0f*dir);
13355 // verify safe_pos will not make us collide with our target objnum, else try 2 other vecs
13356 // don't bang your head, else go
13357 // int go_safe = FALSE;
13358 int go_safe = TRUE;
13359 /* if (target_ship_obj) {
13360 if (pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius)) {
13361 // try up to 2 other random directions
13362 vector dir_vec, rand_vec;
13364 for (idx=0; idx<2; idx++) {
13365 vm_vec_rand_vec_quick(&rand_vec);
13366 vm_vec_scale_add(&dir_vec, &weapon_objp->orient.v.fvec, &rand_vec, 0.5f);
13367 vm_vec_scale_add(safe_pos, &weapon_objp->pos, &dir_vec, -50000.0f*dir);
13368 if ( !pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius) ) {
13373 } else { // direct path is safe
13376 } else { // no target_obj_ship
13383 // can't figure out a good way to go
13387 } else if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_SHIP) {
13388 if (aip->shockwave_object == -1) {
13389 int shockwave_ship = ai_find_shockwave_ship(objp, aip);
13390 if (shockwave_ship == -1) {
13391 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13394 aip->shockwave_object = shockwave_ship;
13398 SDL_assert(aip->shockwave_object > -1);
13399 object *ship_objp = &Objects[aip->shockwave_object];
13400 if (ship_objp == objp) {
13401 aip->shockwave_object = -1;
13405 if (ship_objp->type != OBJ_SHIP) {
13406 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13410 // Optimize note! Don't really have to normalize. We only need a point away from the blowing-up ship.
13413 vm_vec_normalized_dir(&safe_vec, &objp->pos, &ship_objp->pos);
13414 vm_vec_scale_add(safe_pos, &ship_objp->pos, &safe_vec, 50000.0f); // Fly away from the ship.
13416 float outer_rad = ship_get_exp_outer_rad(ship_objp);
13418 if (vm_vec_dist_quick(&objp->pos, &ship_objp->pos) > outer_rad*1.5f) {
13419 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13426 Int3(); // Illegal -- supposedly avoiding a shockwave, but neither ship nor weapon. What is it!?
13435 void rand_chance_test()
13445 for (frametime=0.02f; frametime<0.25f; frametime *= 1.25f) {
13448 nprintf(("AI", "%6.4f: ", frametime));
13449 for (chance=0.25f; chance<2.5f; chance += 0.25f) {
13452 for (i=0; i<100.0f/frametime; i++) {
13453 if (rand_chance(frametime, chance))
13456 nprintf(("AI", "%3i ", count));
13458 nprintf(("AI", "\n"));
13463 // --------------------------------------------------------------------------
13464 // Make object *objp avoid the nearest dangerous shockwave-producing weapon.
13465 // If it looks like there is no valid shockwave-producing weapon then clear the AIF_AVOID_SHOCKWAVE_WEAPON bit in ai_flags and return.
13466 // Return 1 if avoiding a shockwave, else return 0.
13467 int ai_avoid_shockwave(object *objp, ai_info *aip)
13471 //rand_chance_test();
13472 // BIG|HUGE do not respond to shockwaves
13473 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
13474 // don't come here again
13475 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE;
13479 // Don't all react right away.
13480 if (!(aip->ai_flags & AIF_AVOID_SHOCKWAVE_STARTED))
13481 if (!rand_chance(flFrametime, (float) aip->ai_class/4.0f + 0.25f)) // Chance to avoid in 1 second is 0.25 + ai_class/4
13484 if (!aas_1(objp, aip, &safe_pos)) {
13485 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13489 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13491 // OK, evade the shockwave!
13492 turn_towards_point(objp, &safe_pos, NULL, 0.0f);
13493 vector vec_to_safe_pos;
13496 vm_vec_normalized_dir(&vec_to_safe_pos, &safe_pos, &objp->pos);
13498 dot_to_goal = vm_vec_dot(&objp->orient.v.fvec, &vec_to_safe_pos);
13499 if (dot_to_goal < -0.5f)
13500 accelerate_ship(aip, 0.3f);
13502 accelerate_ship(aip, 1.0f + dot_to_goal);
13503 if (dot_to_goal > 0.2f) {
13504 if (!(objp->phys_info.flags & PF_AFTERBURNER_ON )) {
13505 afterburners_start(objp);
13506 aip->afterburner_stop_time = Missiontime + 2*F1_0;
13514 // Awaiting repair. Be useful.
13515 // Probably fly towards incoming repair ship.
13516 // Return true if this ship is close to being repaired, else return false.
13517 int ai_await_repair_frame(object *objp, ai_info *aip)
13519 if (!(aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)))
13522 if (aip->dock_objnum == -1)
13528 shipp = &Ships[Objects[aip->dock_objnum].instance];
13529 sip = &Ship_info[shipp->ship_info_index];
13531 aip->ai_flags &= ~AIF_FORMATION_OBJECT; // Prevents endless rotation.
13533 if (!(sip->flags & SIF_SUPPORT))
13537 object *repair_objp;
13539 repair_objp = &Objects[aip->dock_objnum];
13541 if (Ships[repair_objp->instance].team == TEAM_TRAITOR) {
13542 ai_abort_rearm_request(repair_objp);
13546 vm_vec_scale_add(&goal_point, &repair_objp->pos, &repair_objp->orient.v.uvec, -50.0f); // Fly towards point below repair ship.
13549 float dist = vm_vec_normalized_dir(&vtr, &goal_point, &objp->pos);
13550 float dot = vm_vec_dot(&vtr, &objp->orient.v.fvec);
13552 if (dist > 200.0f) {
13553 //nprintf(("AI", "%s flying towards %s for repair, dist = %7.3f\n", Ships[objp->instance].ship_name, &Ships[repair_objp->instance].ship_name, dist));
13554 accelerate_ship(aip, (0.9f + dot) * dist/1500.0f);
13555 turn_towards_point(objp, &goal_point, NULL, 0.0f);
13557 accelerate_ship(aip, 0.0f);
13558 //nprintf(("AI", "%s sitting still awaiting repair from %s, dist = %7.3f\n", Ships[objp->instance].ship_name, &Ships[repair_objp->instance].ship_name, dist));
13564 // Maybe cause this ship to self-destruct.
13565 // Currently, any small ship (SIF_SMALL_SHIP) that has been disabled will self-destruct after awhile.
13566 // Maybe should only do this if they are preventing their wing from re-entering.
13567 void ai_maybe_self_destruct(object *objp, ai_info *aip)
13569 // Friendly ships can be repaired, so no self-destruct.
13570 // In multiplayer, just don't self-destruct. I figured there would be a problem. -- MK, 3/19/98.
13571 if ((Ships[objp->instance].team == TEAM_FRIENDLY) || (Game_mode & GM_MULTIPLAYER))
13574 // Small ships in a wing blow themselves up after awhile if engine or weapons system has been destroyed.
13575 // Reason: Don't want them to prevent a re-emergence of the wing.
13576 // Note: Don't blow up if not in a wing for two reasons: One, won't affect re-emergence of waves and (1) disable the Dragon
13577 // mission would be broken.
13578 if ((Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP) && (Ships[objp->instance].wingnum != -1)) {
13579 if ((ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) ||
13580 (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_WEAPONS) <= 0.0f)) {
13581 if (aip->self_destruct_timestamp < 0)
13582 aip->self_destruct_timestamp = timestamp(90 * 1000); // seconds until self-destruct
13584 aip->self_destruct_timestamp = -1;
13587 if (aip->self_destruct_timestamp < 0) {
13591 if (timestamp_elapsed(aip->self_destruct_timestamp)) {
13592 ship_apply_local_damage( objp, objp, &objp->pos, objp->hull_strength*flFrametime + 1.0f, MISS_SHIELDS);
13597 // Determine if pl_objp needs a new target, called from ai_frame()
13598 int ai_need_new_target(object *pl_objp, int target_objnum)
13602 if ( target_objnum < 0 ) {
13606 objp = &Objects[target_objnum];
13608 if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) && (objp->type != OBJ_WEAPON) ) {
13612 if ( objp->type == OBJ_SHIP ) {
13613 if ( Ships[objp->instance].flags & SF_DYING ) {
13615 } else if (Ships[objp->instance].team == Ships[pl_objp->instance].team)
13622 // If *objp is recovering from a collision with a big ship, handle it.
13623 // Return true if recovering.
13624 int maybe_big_ship_collide_recover_frame(object *objp, ai_info *aip)
13629 if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1) {
13630 ai_turn_towards_vector(&aip->big_recover_pos_1, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, NULL);
13631 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_1, &objp->pos);
13632 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13633 accelerate_ship(aip, dot);
13635 // If close to desired point, or 15+ seconds since entered this mode, continue to next mode.
13636 if ((timestamp_until(aip->big_recover_timestamp) < -15*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13637 aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_1;
13638 aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13643 } else if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_2) {
13644 ai_turn_towards_vector(&aip->big_recover_pos_2, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, NULL);
13645 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_2, &objp->pos);
13646 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13647 accelerate_ship(aip, dot);
13649 // If close to desired point, or 30+ seconds since started avoiding collision, done avoiding.
13650 if ((timestamp_until(aip->big_recover_timestamp) < -30*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13651 aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13652 aip->ai_flags &= ~AIF_TARGET_COLLISION;
13658 if (aip->ai_flags & AIF_TARGET_COLLISION) {
13659 aip->ai_flags &= ~AIF_TARGET_COLLISION;
13664 void validate_mode_submode(ai_info *aip)
13666 switch (aip->mode) {
13668 // check valid submode
13669 switch (aip->submode) {
13670 case SM_CONTINUOUS_TURN:
13672 case SM_EVADE_SQUIGGLE:
13673 case SM_EVADE_BRAKE:
13675 case SM_SUPER_ATTACK:
13677 case SM_GET_BEHIND:
13679 case SM_EVADE_WEAPON:
13681 case SM_ATTACK_FOREVER:
13689 // check valid submode
13690 switch(aip->submode) {
13691 case AIS_STRAFE_ATTACK:
13692 case AIS_STRAFE_AVOID:
13693 case AIS_STRAFE_RETREAT1:
13694 case AIS_STRAFE_RETREAT2:
13695 case AIS_STRAFE_POSITION:
13704 // --------------------------------------------------------------------------
13705 // Process AI object "objnum".
13706 void ai_frame(int objnum)
13708 ship *shipp = &Ships[Objects[objnum].instance];
13709 ai_info *aip = &Ai_info[shipp->ai_index];
13712 // validate_mode_submode(aip);
13714 SDL_assert((aip->mode != AIM_WAYPOINTS) || (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC));
13716 // Set globals defining the current object and its enemy object.
13717 Pl_objp = &Objects[objnum];
13719 if (aip->mode == AIM_WARP_OUT) {
13720 ai_warp_out(Pl_objp);
13724 /* // HACK! TEST! REMOVE ME!
13725 if (Ship_info[shipp->ship_info_index].flags & SIF_BIG_SHIP)
13726 if (shipp->team == Player_ship->team)
13727 aip->mode = AIM_CHASE;
13730 // if (!SDL_strncasecmp(Ships[Pl_objp->instance].ship_name, "cancer", 6))
13731 // nprintf(("AI", "Ship %s: mode = %s, submode = %i\n", Ships[Pl_objp->instance].ship_name, Mode_text[aip->mode], aip->submode));
13733 ai_maybe_self_destruct(Pl_objp, aip);
13735 // if ( timestamp_elapsed(aip->goal_check_time) ) {
13736 ai_process_mission_orders( objnum, aip );
13737 // aip->goal_check_time = timestamp_rand(1000,2000);
13740 // Avoid a shockwave, if necessary. If a shockwave and rearming, stop rearming.
13741 if (aip->ai_flags & AIF_AVOID_SHOCKWAVE) {
13742 if (ai_avoid_shockwave(Pl_objp, aip)) {
13743 aip->ai_flags &= ~(AIF_BIG_SHIP_COLLIDE_RECOVER_1 | AIF_BIG_SHIP_COLLIDE_RECOVER_2);
13744 if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
13745 ai_abort_rearm_request(Pl_objp);
13749 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_STARTED;
13752 // moved call to ai_do_repair frame here from below because of the subsequent if statment returning
13753 // if the ship is getting repaired
13754 // If waiting to be repaired, just stop and sit.
13755 ai_do_repair_frame(Pl_objp, aip, flFrametime);
13756 if ((aip->ai_flags & AIF_AWAITING_REPAIR) || (aip->ai_flags & AIF_BEING_REPAIRED)) {
13757 if (ai_await_repair_frame(Pl_objp, aip))
13761 if (aip->mode == AIM_PLAY_DEAD)
13764 // If recovering from a collision with a big ship, don't continue.
13765 if (maybe_big_ship_collide_recover_frame(Pl_objp, aip))
13768 ai_preprocess_ignore_objnum(Pl_objp, aip);
13769 target_objnum = set_target_objnum(aip, aip->target_objnum);
13771 // nprintf(("AI", "Frame %i: Coords = %7.3f %7.3f %7.3f\n", AI_FrameCount, Pl_objp->pos.xyz.x, Pl_objp->pos.xyz.y, Pl_objp->pos.xyz.z));
13773 SDL_assert(objnum != target_objnum);
13775 ai_manage_shield(Pl_objp, aip);
13777 if ( maybe_request_support(Pl_objp) ) {
13778 if ( Ships[Pl_objp->instance].flags & SF_FROM_PLAYER_WING ) {
13779 ship_maybe_tell_about_rearm(shipp);
13783 ai_maybe_warp_out(Pl_objp);
13786 // If this ship is attacking an object's subsystems and someone else destroyed
13787 // the subsystem, it could continue attacking the ship. Need to invalidate the objnum.
13788 if (target_objnum >= 0)
13789 if (Objects[target_objnum].flags & OF_PROTECTED) {
13790 // if (aip->targeted_subsys != NULL)
13791 // ; //nprintf(("AI", "subsys hits = %7.3f\n", aip->targeted_subsys->current_hits));
13793 if ((aip->targeted_subsys == NULL) || (aip->targeted_subsys->current_hits <= 0.0f)) {
13794 target_objnum = -1;
13795 aip->target_objnum = -1;
13801 // Find an enemy if don't already have one.
13803 if ( ai_need_new_target(Pl_objp, target_objnum) ) {
13804 if ((aip->mode != AIM_EVADE_WEAPON) && (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
13805 aip->resume_goal_time = -1;
13806 aip->active_goal = AI_GOAL_NONE;
13807 } else if (aip->resume_goal_time == -1) {
13808 // AL 12-9-97: Don't allow cargo and navbuoys to set their aip->target_objnum
13809 if ( !(Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS) ) {
13810 target_objnum = find_enemy(objnum, MAX_ENEMY_DISTANCE, Skill_level_max_attackers[Game_skill_level]); // Attack up to 25K units away.
13811 if (target_objnum != -1) {
13812 if (aip->target_objnum != target_objnum)
13813 aip->aspect_locked_time = 0.0f;
13814 set_target_objnum(aip, target_objnum);
13815 En_objp = &Objects[target_objnum];
13819 } else if (target_objnum >= 0) {
13820 En_objp = &Objects[target_objnum];
13823 // set base stealth info each frame
13824 aip->ai_flags &= ~AIF_STEALTH_PURSIUT;
13825 if (En_objp && En_objp->type == OBJ_SHIP) {
13826 if (Ship_info[Ships[En_objp->instance].ship_info_index].flags & SIF_STEALTH) {
13827 int stealth_state = ai_is_stealth_visible(Pl_objp, En_objp);
13828 float dist = vm_vec_dist_quick(&En_objp->pos, &Pl_objp->pos);
13830 if (stealth_state != STEALTH_FULLY_TARGETABLE) {
13831 aip->ai_flags |= AIF_STEALTH_PURSIUT;
13834 if ( (stealth_state == STEALTH_FULLY_TARGETABLE) || (stealth_state == STEALTH_VISIBLE) ) {
13835 aip->stealth_last_visible_stamp = timestamp();
13836 aip->stealth_last_cheat_visible_stamp = aip->stealth_last_visible_stamp;
13837 aip->stealth_last_pos = En_objp->pos;
13838 aip->stealth_velocity = En_objp->phys_info.vel;
13839 } else if (dist < 100) {
13840 // get cheat timestamp
13841 aip->stealth_last_cheat_visible_stamp = timestamp();
13843 // set approximate pos and vel, with increasing error as time from last_visible_stamp increases
13844 update_ai_stealth_info_with_error(aip/*, 0*/);
13849 /* if ((Pl_objp != NULL) && (En_objp != NULL)) {
13854 // AL 12-10-97: ensure that cargo and navbuoys aip->target_objnum is always -1.
13855 if ( Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS ) {
13856 aip->target_objnum = -1;
13859 if ((En_objp != NULL) && (En_objp->pos.xyz.x == Pl_objp->pos.xyz.x) && (En_objp->pos.xyz.y == Pl_objp->pos.xyz.y) && (En_objp->pos.xyz.z == Pl_objp->pos.xyz.z)) {
13860 mprintf(("Warning: Object and its enemy have same position. Object #%i\n", Pl_objp-Objects));
13864 if (aip->mode == AIM_CHASE) {
13865 if (En_objp == NULL) {
13866 aip->active_goal = -1;
13870 // If there is a goal to resume and enough time has elapsed, resume the goal.
13871 if ((aip->resume_goal_time > 0) && (aip->resume_goal_time < Missiontime)) {
13872 aip->active_goal = AI_GOAL_NONE;
13873 aip->resume_goal_time = -1;
13874 target_objnum = find_enemy(objnum, 2000.0f, Skill_level_max_attackers[Game_skill_level]);
13875 if (target_objnum != -1) {
13876 if (aip->target_objnum != target_objnum) {
13877 aip->aspect_locked_time = 0.0f;
13879 set_target_objnum(aip, target_objnum);
13883 // check if targeted subsystem has been destroyed, if so, move onto another subsystem
13884 // if trying to disable or disarm the target
13885 if ((En_objp != NULL) && ( aip->targeted_subsys != NULL )) {
13886 SDL_assert(En_objp->type == OBJ_SHIP);
13887 if ( aip->targeted_subsys->current_hits <= 0.0f ) {
13890 if ( aip->goals[0].ai_mode == AI_GOAL_DISABLE_SHIP ) {
13891 subsys_type = SUBSYSTEM_ENGINE;
13892 } else if ( aip->goals[0].ai_mode == AI_GOAL_DISARM_SHIP ) {
13893 subsys_type = SUBSYSTEM_TURRET;
13898 if ( subsys_type != -1 ) {
13899 ship_subsys *new_subsys;
13900 new_subsys = ship_return_next_subsys(&Ships[En_objp->instance], subsys_type, &Pl_objp->pos);
13901 if ( new_subsys != NULL ) {
13902 set_targeted_subsys(aip, new_subsys, aip->target_objnum);
13904 // AL 12-16-97: no more subsystems to attack... reset targeting info
13905 aip->target_objnum = -1;
13906 set_targeted_subsys(aip, NULL, -1);
13909 // targeted subsys is destroyed, so stop attacking it
13910 set_targeted_subsys(aip, NULL, -1);
13915 ai_maybe_launch_cmeasure(Pl_objp, aip);
13916 ai_maybe_evade_locked_missile(Pl_objp, aip);
13918 aip->target_time += flFrametime;
13920 int in_formation = 0;
13921 if (aip->ai_flags & AIF_FORMATION) {
13922 in_formation = !ai_formation();
13925 if ( !in_formation ) {
13926 ai_execute_behavior(aip);
13929 process_subobjects(objnum);
13930 maybe_resume_previous_mode(Pl_objp, aip);
13932 if (Pl_objp->phys_info.flags & PF_AFTERBURNER_ON ) {
13933 if (Missiontime > aip->afterburner_stop_time) {
13934 //nprintf(("AI", "Frame %i, turning off afterburner.\n", AI_FrameCount));
13935 afterburners_stop(Pl_objp);
13938 // validate_mode_submode(aip);
13941 int Waypoints_created = 0;
13943 // Find the ship with the name *name in the Ship_info array.
13944 int find_ship_name(char *name)
13948 for (i=0; i<Num_ship_types; i++)
13949 if (!strcmp(Ship_info[i].name, name))
13955 void create_waypoints()
13959 // Waypoints_created = 1;
13961 if (Waypoints_created)
13964 for (j=0; j<Num_waypoint_lists; j++)
13965 for (i=0; i<Waypoint_lists[j].count; i++) {
13966 obj_create(OBJ_WAYPOINT, 0, j * 65536 + i, NULL,
13967 &Waypoint_lists[j].waypoints[i], 0.0f, OF_RENDERS);
13970 Waypoints_created = 1;
13973 int Last_ai_obj = -1;
13975 void ai_process( object * obj, int ai_index, float frametime )
13977 // if (Ships[obj->instance].flags & SF_DYING)
13978 // nprintf(("AI", "Frame: %i Ship %s is dying!\n", Framecount, Ships[obj->instance].ship_name));
13980 if (obj->flags & OF_SHOULD_BE_DEAD)
13983 // return if ship is dead, unless it's a big ship...then its turrets still fire, like I was quoted in a magazine. -- MK, 5/15/98.
13984 if ((Ships[obj->instance].flags & SF_DYING ) && !(Ship_info[Ships[obj->instance].ship_info_index].flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP))){
13988 int rfc = 1; // Assume will be Reading Flying Controls.
13990 SDL_assert( obj->type == OBJ_SHIP );
13991 SDL_assert( ai_index >= 0 );
13995 create_waypoints();
13997 AI_frametime = frametime;
13998 if (obj-Objects <= Last_ai_obj) {
14002 memset( &AI_ci, 0, sizeof(AI_ci) );
14004 ai_frame(obj-Objects);
14006 AI_ci.pitch = 0.0f;
14008 AI_ci.heading = 0.0f;
14010 // the ships maximum velocity now depends on the energy flowing to engines
14011 obj->phys_info.max_vel.xyz.z = Ships[obj->instance].current_max_speed;
14012 ai_info *aip = &Ai_info[Ships[obj->instance].ai_index];
14014 // In certain circumstances, the AI says don't fly in the normal way.
14015 // One circumstance is in docking and undocking, when the ship is moving
14016 // under thruster control.
14017 switch (aip->mode) {
14019 if ((aip->submode >= AIS_DOCK_2) && (aip->submode != AIS_UNDOCK_3))
14023 if (aip->submode >= AIS_WARP_3)
14027 // if (aip->submode == AIS_NONE_FORMATION)
14035 vector copy_desired_rotvel = obj->phys_info.rotvel;
14036 physics_read_flying_controls( &obj->orient, &obj->phys_info, &AI_ci, frametime);
14037 // if obj is in formation and not flight leader, don't update rotvel
14038 if (aip->ai_flags & AIF_FORMATION) {
14039 if (&Objects[aip->goal_objnum] != obj) {
14040 obj->phys_info.desired_rotvel = copy_desired_rotvel;
14041 obj->phys_info.rotvel = copy_desired_rotvel;
14046 Last_ai_obj = obj-Objects;
14049 // Initialize ai_info struct of object objnum.
14050 void init_ai_object(int objnum)
14052 int ship_index, ai_index;
14056 vector near_vec; // A vector nearby and mainly in front of this object.
14058 objp = &Objects[objnum];
14059 ship_index = objp->instance;
14060 ai_index = Ships[ship_index].ai_index;
14061 SDL_assert((ai_index >= 0) && (ai_index < MAX_AI_INFO));
14063 aip = &Ai_info[ai_index];
14065 ship_type = Ships[ship_index].ship_info_index;
14067 vm_vec_scale_add(&near_vec, &objp->pos, &objp->orient.v.fvec, 100.0f);
14068 vm_vec_scale_add2(&near_vec, &objp->orient.v.rvec, 10.0f);
14070 // Things that shouldn't have to get initialized, but initialize them just in case!
14072 aip->previous_mode = AIM_NONE;
14073 aip->mode_time = -1;
14074 aip->target_objnum = -1;
14075 aip->target_signature = -1;
14076 aip->previous_target_objnum = -1;
14077 aip->target_time = 0.0f;
14078 aip->enemy_wing = -1;
14079 aip->attacker_objnum = -1;
14080 aip->goal_objnum = -1;
14081 aip->goal_signature = -1;
14082 aip->guard_objnum = -1;
14083 aip->guard_signature = -1;
14084 aip->guard_wingnum = -1;
14085 aip->dock_signature = -1;
14087 aip->previous_submode = 0;
14088 aip->best_dot_to_enemy = -1.0f;
14089 aip->best_dot_from_enemy = -1.0f;
14090 aip->best_dot_to_time = 0;
14091 aip->best_dot_from_time = 0;
14092 aip->submode_start_time = 0;
14093 aip->submode_parm0 = 0;
14094 aip->active_goal = -1;
14095 aip->goal_check_time = timestamp(0);
14096 aip->last_predicted_enemy_pos = near_vec;
14097 aip->prev_goal_point = near_vec;
14098 aip->goal_point = near_vec;
14099 aip->time_enemy_in_range = 0.0f;
14100 aip->last_attack_time = 0;
14101 aip->last_hit_time = 0;
14102 aip->last_hit_quadrant = 0;
14103 aip->hitter_objnum = -1;
14104 aip->hitter_signature = -1;
14105 aip->resume_goal_time = -1;
14106 aip->prev_accel = 0.0f;
14107 aip->prev_dot_to_goal = 0.0f;
14109 aip->ignore_objnum = UNUSED_OBJNUM;
14110 aip->ignore_signature = -1;
14112 // aip->mode = AIM_NONE;
14114 // End of Things that shouldn't have to get initialized, but initialize them just in case!
14116 aip->ai_courage = Ai_classes[Ship_info[ship_type].ai_class].ai_courage[Game_skill_level];
14117 aip->ai_patience = Ai_classes[Ship_info[ship_type].ai_class].ai_patience[Game_skill_level];
14118 aip->ai_evasion = Ai_classes[Ship_info[ship_type].ai_class].ai_evasion[Game_skill_level];
14119 aip->ai_accuracy = Ai_classes[Ship_info[ship_type].ai_class].ai_accuracy[Game_skill_level];
14121 if (Num_waypoint_lists > 0) {
14122 aip->wp_index = -1;
14125 aip->wp_index = -1;
14129 aip->attacker_objnum = -1;
14130 aip->goal_signature = -1;
14132 Objects[objnum].phys_info.prev_fvec = Objects[objnum].orient.v.fvec;
14134 aip->last_predicted_enemy_pos.xyz.x = 0.0f; // Says this value needs to be recomputed!
14135 aip->time_enemy_in_range = 0.0f;
14137 aip->resume_goal_time = -1; // Say there is no goal to resume.
14139 aip->active_goal = -1;
14140 aip->path_start = -1;
14141 aip->path_goal_dist = -1;
14142 aip->path_length = 0;
14143 aip->path_subsystem_next_check = 1;
14144 aip->dock_path_index = -1;
14145 aip->dock_index = -1;
14146 aip->dock_objnum = -1;
14148 aip->danger_weapon_objnum = -1;
14149 aip->danger_weapon_signature = -1;
14151 aip->lead_scale = 0.0f;
14152 aip->last_hit_target_time = Missiontime;
14154 aip->nearest_locked_object = -1;
14155 aip->nearest_locked_distance = 99999.0f;
14157 aip->targeted_subsys = NULL;
14158 aip->last_subsys_target = NULL;
14159 aip->targeted_subsys_parent = -1;
14161 // The next two fields are used to time the rearming to allow useful sound effects for missile rearming
14162 aip->rearm_first_missile = TRUE; // flag to indicate that next missile to load is the first missile
14163 aip->rearm_release_delay = 0; // timestamp to delay the separation of docked ships after rearm
14165 aip->next_predict_pos_time = 0;
14167 aip->afterburner_stop_time = 0;
14168 aip->last_objsig_hit = -1; // object signature of the ship most recently hit by aip
14170 aip->path_next_create_time = timestamp(1);
14171 aip->path_create_pos = Objects[objnum].pos;
14172 aip->path_create_orient = Objects[objnum].orient;
14174 aip->ignore_expire_timestamp = timestamp(1);
14175 aip->warp_out_timestamp = 0;
14176 aip->next_rearm_request_timestamp = timestamp(1);
14177 aip->primary_select_timestamp = timestamp(1);
14178 aip->secondary_select_timestamp = timestamp(1);
14179 aip->scan_for_enemy_timestamp = timestamp(1);
14181 aip->choose_enemy_timestamp = timestamp(3*(NUM_SKILL_LEVELS-Game_skill_level) * ((rand_alt() % 500) + 500));
14183 aip->shockwave_object = -1;
14184 aip->shield_manage_timestamp = timestamp(1);
14185 aip->self_destruct_timestamp = -1; // This is a flag that we have not yet set this.
14186 aip->ok_to_target_timestamp = timestamp(1);
14187 aip->pick_big_attack_point_timestamp = timestamp(1);
14188 vm_vec_zero(&aip->big_attack_point);
14190 aip->avoid_check_timestamp = timestamp(1);
14192 aip->abort_rearm_timestamp = -1;
14195 aip->artillery_objnum = -1;
14196 aip->artillery_sig = -1;
14198 // waypoint speed cap
14199 aip->waypoint_speed_cap = -1;
14201 // set lethality to enemy team
14202 aip->lethality = 0.0f;
14205 void init_ai_objects()
14209 for (i=0; i<num_objects; i++){
14210 if (Objects[i].type == OBJ_SHIP){
14216 void init_ai_system()
14218 // MWA -- removed next line of code on 11/12/97. When a ship is created
14219 // it calls init_ai_object() on it's objnum. Doing this init at the point where
14220 // this function gets called messes things up.
14221 //init_ai_objects();
14223 Ppfp = Path_points;
14224 Waypoints_created = 0;
14226 Dock_path_warning_given = 0;
14228 /* for (int i=0; i<MAX_IGNORE_OBJECTS; i++) {
14229 Ignore_objects[i].objnum = -1;
14230 Ignore_objects[i].signature = -1;
14236 void ai_set_default_behavior(object *obj, int classnum)
14240 SDL_assert(obj != NULL);
14241 SDL_assert(obj->instance != -1);
14242 SDL_assert(Ships[obj->instance].ai_index != -1);
14244 aip = &Ai_info[Ships[obj->instance].ai_index];
14246 aip->behavior = classnum;
14250 void ai_do_default_behavior(object *obj)
14255 SDL_assert(obj != NULL);
14256 SDL_assert(obj->instance != -1);
14257 SDL_assert(Ships[obj->instance].ai_index != -1);
14259 aip = &Ai_info[Ships[obj->instance].ai_index];
14261 ship_flags = Ship_info[Ships[obj->instance].ship_info_index].flags;
14262 if (!is_instructor(obj) && (ship_flags & (SIF_FIGHTER | SIF_BOMBER))) {
14263 int enemy_objnum = find_enemy(OBJ_INDEX(obj), 1000.0f, Skill_level_max_attackers[Game_skill_level]);
14264 set_target_objnum(aip, enemy_objnum);
14265 aip->mode = AIM_CHASE;
14266 aip->submode = SM_ATTACK;
14267 } else if (ship_flags & (SIF_SUPPORT)) {
14268 aip->mode = AIM_SAFETY;
14269 aip->submode = AISS_1;
14270 aip->ai_flags &= ~(AIF_REPAIRING);
14271 } else if ( ship_flags & SIF_SENTRYGUN ) {
14272 aip->mode = AIM_SENTRYGUN;
14274 aip->mode = AIM_NONE;
14277 aip->submode_start_time = Missiontime;
14278 aip->active_goal = AI_GOAL_NONE;
14281 #define FRIENDLY_DAMAGE_THRESHOLD 50.0f // Display a message at this threshold. Note, this gets scaled by Skill_level
14283 // send the given message from objp. called from the maybe_process_friendly_hit
14284 // code below when a message must get send to the player when he fires on friendlies
14285 void process_friendly_hit_message( int message, object *objp )
14289 // no traitor in multiplayer
14290 if(Game_mode & GM_MULTIPLAYER){
14294 // don't send this message if a player ship was hit.
14295 if ( objp->flags & OF_PLAYER_SHIP ){
14299 // check if objp is a cargo contianer -- if so, then find a new ship to send the message
14300 index = objp->instance;
14301 if ( !(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ){
14305 // if the message is "oops" (the don't hit me message), always make come from Terran command
14306 if ( message == MESSAGE_OOPS ){
14311 message_send_builtin_to_player( message, &Ships[index], MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14313 message_send_builtin_to_player( message, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14317 extern void ship_set_subsystem_strength( ship *shipp, int type, float strength );
14319 // Object *objp_weapon, fired by *objp_hitter, hit object *objp_ship.
14320 void maybe_process_friendly_hit(object *objp_hitter, object *objp_hit, object *objp_weapon)
14322 // no turning traitor in multiplayer
14323 if ( Game_mode & GM_MULTIPLAYER ) {
14327 // ditto if mission says no traitors allowed
14328 if (The_mission.flags & MISSION_FLAG_NO_TRAITOR) {
14332 if ((objp_hitter == Player_obj) && (Player_ship->team == TEAM_FRIENDLY)) {
14334 // AL 12-4-97: It is possible the Player is a OBJ_GHOST at this point. If so, bail out.
14335 if ( objp_hitter->type != OBJ_SHIP ) {
14339 SDL_assert(objp_hitter->type == OBJ_SHIP);
14340 SDL_assert(objp_hit->type == OBJ_SHIP);
14341 SDL_assert(objp_weapon->type == OBJ_WEAPON);
14343 ship *shipp_hitter = &Ships[objp_hitter->instance];
14344 ship *shipp_hit = &Ships[objp_hit->instance];
14346 if (shipp_hitter->team != shipp_hit->team) {
14351 player *pp = &Players[Player_num];
14353 // wacky stuff here
14354 if (pp->friendly_hits != 0) {
14355 float time_since_last_hit = f2fl(Missiontime - pp->friendly_last_hit_time);
14356 if ((time_since_last_hit >= 0.0f) && (time_since_last_hit < 10000.0f)) {
14357 if (time_since_last_hit > 60.0f) {
14358 pp->friendly_hits = 0;
14359 pp->friendly_damage = 0.0f;
14360 } else if (time_since_last_hit > 2.0f) {
14361 pp->friendly_hits -= (int) time_since_last_hit/2;
14362 pp->friendly_damage -= time_since_last_hit;
14365 if (pp->friendly_damage < 0.0f) {
14366 pp->friendly_damage = 0.0f;
14369 if (pp->friendly_hits < 0) {
14370 pp->friendly_hits = 0;
14375 float damage; // Damage done by weapon. Gets scaled down based on size of ship.
14377 damage = Weapon_info[Weapons[objp_weapon->instance].weapon_info_index].damage;
14379 // wacky stuff here
14380 ship_info *sip = &Ship_info[Ships[objp_hit->instance].ship_info_index];
14381 if (sip->initial_hull_strength > 1000.0f) {
14382 float factor = sip->initial_hull_strength / 1000.0f;
14383 factor = SDL_min(100.0f, factor);
14387 // Don't penalize much at all for hitting cargo
14388 if (sip->flags & (SIF_CARGO | SIF_SENTRYGUN)) {
14392 // Hit ship, but not targeting it, so it's not so heinous, maybe an accident.
14393 if (Ai_info[shipp_hitter->ai_index].target_objnum != OBJ_INDEX(objp_hit)) {
14397 pp->friendly_last_hit_time = Missiontime;
14398 pp->friendly_hits++;
14400 // cap damage and number of hits done this frame
14401 float accredited_damage = SDL_min(MAX_BURST_DAMAGE, pp->damage_this_burst + damage) - pp->damage_this_burst;
14402 pp->friendly_damage += accredited_damage;
14403 pp->damage_this_burst += accredited_damage;
14405 // Done with adjustments to damage. Evaluate based on current friendly_damage
14406 nprintf(("AI", "Friendly damage: %.1f, threshold: %.1f, inc damage: %.1f, max burst: %d\n", pp->friendly_damage, FRIENDLY_DAMAGE_THRESHOLD * (1.0f + (float) (NUM_SKILL_LEVELS + 1 - Game_skill_level)/3.0f), pp->damage_this_burst, MAX_BURST_DAMAGE ));
14408 if (is_instructor(objp_hit)) {
14409 // it's not nice to hit your instructor
14410 if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD) {
14411 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_ATTACK, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14412 pp->last_warning_message_time = Missiontime;
14413 ship_set_subsystem_strength( Player_ship, SUBSYSTEM_WEAPONS, 0.0f);
14417 // Instructor warp out.
14418 ai_set_mode_warp_out(objp_hit, &Ai_info[Ships[objp_hit->instance].ai_index]);
14419 gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_START_FORCED ); // Force player to warp out.
14421 //ship_apply_global_damage( objp_hitter, objp_hit, NULL, 2*(get_shield_strength(objp_hitter) + Ship_info[shipp_hitter->ship_info_index].initial_hull_strength) );
14422 //ship_apply_global_damage( objp_hitter, objp_hit, NULL, 1.0f );
14423 } else if (Missiontime - pp->last_warning_message_time > F1_0*4) {
14424 // warning every 4 sec
14425 // use NULL as the message sender here since it is the Terran Command persona
14426 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_HIT, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14427 pp->last_warning_message_time = Missiontime;
14430 // not nice to hit your friends
14431 } else if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD * (1.0f + (float) (NUM_SKILL_LEVELS + 1 - Game_skill_level)/3.0f)) {
14432 process_friendly_hit_message( MESSAGE_HAMMER_SWINE, objp_hit );
14433 mission_goal_fail_all();
14434 ai_abort_rearm_request( Player_obj );
14436 Player_ship->team = TEAM_TRAITOR;
14438 } else if ((damage > frand()) && (Missiontime - pp->last_warning_message_time > F1_0*4) && (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD)) {
14439 // no closer than 4 sec intervals
14440 // Note: (damage > frand()) added on 12/9/97 by MK. Since damage is now scaled down for big ships, we could get too
14441 // many warnings. Kind of tedious. frand() returns a value in 0..1, so this won't affect legit hits.
14442 process_friendly_hit_message( MESSAGE_OOPS, objp_hit );
14443 pp->last_warning_message_time = Missiontime;
14448 // Maybe make ship with ai_info *aip attack hitter_objnum as a dynamic goal
14449 void maybe_set_dynamic_chase(ai_info *aip, int hitter_objnum)
14451 SDL_assert(Ship_info[Ships[aip->shipnum].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER));
14453 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
14454 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
14458 // only set as target if can be targeted.
14459 if (awacs_get_level(&Objects[hitter_objnum], &Ships[aip->shipnum], 1) < 1) {
14463 if (aip->target_objnum != hitter_objnum)
14464 aip->aspect_locked_time = 0.0f;
14465 set_target_objnum(aip, hitter_objnum);
14466 aip->resume_goal_time = Missiontime + i2f(20); // Only chase up to 20 seconds.
14467 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14469 set_targeted_subsys(aip, NULL, -1); // Say not attacking any particular subsystem.
14471 aip->previous_submode = aip->mode;
14472 aip->mode = AIM_CHASE;
14473 aip->submode = SM_ATTACK;
14477 // Return true if *objp has armed an aspect seeking bomb.
14478 // This function written so a ship with an important bomb to fire will willingly take hits in the face to fire its bomb.
14479 int firing_aspect_seeking_bomb(object *objp)
14485 shipp = &Ships[objp->instance];
14487 swp = &shipp->weapons;
14489 bank_index = swp->current_secondary_bank;
14491 if (bank_index != -1)
14492 if (swp->secondary_bank_ammo[bank_index] > 0) {
14493 if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_BOMB) {
14494 if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_HOMING_ASPECT) {
14503 // *objp collided with big ship *big_objp at global point *collide_pos
14504 // Make it fly away from the collision point.
14505 // collision_normal is NULL, when a collision is imminent and we just want to bug out.
14506 void big_ship_collide_recover_start(object *objp, object *big_objp, vector *collide_pos, vector *collision_normal)
14510 SDL_assert(objp->type == OBJ_SHIP);
14512 aip = &Ai_info[Ships[objp->instance].ai_index];
14514 if (!timestamp_elapsed(aip->big_recover_timestamp) && (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1))
14517 //nprintf(("AI", "Ship %s beginning to avoid ship %s at time %7.3f", Ships[objp->instance].ship_name, Ships[big_objp->instance].ship_name, f2fl(Missiontime)));
14518 if (collision_normal) {
14519 aip->big_recover_timestamp = timestamp(2000);
14520 aip->big_collision_normal = *collision_normal;
14521 // nprintf(("AI", " normal\n"));
14523 aip->big_recover_timestamp = timestamp(500);
14524 // nprintf(("AI", " no normal\n"));
14528 aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
14529 aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_1;
14532 // vm_vec_normalized_dir(&out_vec, &objp->pos, collide_pos);
14534 // big_recover_pos_1 is 100 m out along normal
14536 if (collision_normal) {
14537 direction = *collision_normal;
14539 vm_vec_copy_scale(&direction, &objp->orient.v.fvec, -1.0f);
14541 vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &direction, 100.0f);
14543 // go out 200 m from box closest box point
14544 get_world_closest_box_point_with_delta(&aip->big_recover_pos_2, big_objp, &aip->big_recover_pos_1, NULL, 300.0f);
14546 accelerate_ship(aip, 0.0f);
14548 if (vm_vec_dot(collision_normal, &objp->orient.v.fvec) > 0.5f) {
14549 // vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14550 // vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14551 // vm_vec_scale_add(&aip->big_recover_pos_2, &objp->pos, &out_vec, big_objp->radius*2.0f);
14552 accelerate_ship(aip, 2.0f);
14554 // vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14555 // vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14556 accelerate_ship(aip, 0.0f);
14560 float max_lethality = 0.0f;
14562 void ai_update_lethality(object *ship_obj, object *other_obj, float damage)
14564 SDL_assert(ship_obj->type == OBJ_SHIP);
14565 SDL_assert(other_obj->type == OBJ_WEAPON || other_obj->type == OBJ_SHOCKWAVE);
14566 int dont_count = FALSE;
14568 int parent = other_obj->parent;
14569 if (Objects[parent].type == OBJ_SHIP) {
14570 if (Objects[parent].signature == other_obj->parent_sig) {
14572 // check damage done to enemy team
14573 if (Ships[ship_obj->instance].team != Ships[Objects[parent].instance].team) {
14576 if (other_obj->type == OBJ_WEAPON) {
14577 weapon *wp = &Weapons[other_obj->instance];
14578 weapon_info *wif = &Weapon_info[wp->weapon_info_index];
14580 // if parent is BIG|HUGE, don't count beam
14581 if (Ship_info[Ships[Objects[parent].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
14582 if (wif->wi_flags & WIF_BEAM) {
14589 float lethality = 0.025f * damage; // 2 cyclops (@2000) put you at 100 lethality
14591 // increase lethality weapon's parent ship
14592 ai_info *aip = &Ai_info[Ships[Objects[parent].instance].ai_index];
14593 aip->lethality += lethality;
14594 aip->lethality = SDL_min(110.0f, aip->lethality);
14595 // if you hit, don;t be less than 0
14596 aip->lethality = SDL_max(0.0f, aip->lethality);
14598 // if (aip->lethality > max_lethality) {
14599 // max_lethality = aip->lethality;
14600 // mprintf(("new lethalilty high: %.1f\n", max_lethality));
14603 // if parent is player, show his lethality
14604 // if (Objects[parent].flags & OF_PLAYER_SHIP) {
14605 // mprintf(("Player lethality: %.1f\n", aip->lethality));
14614 // Object *objp_ship was hit by either weapon *objp_weapon or collided into by ship hit_objp at point *hitpos.
14615 void ai_ship_hit(object *objp_ship, object *hit_objp, vector *hitpos, int shield_quadrant, vector *hit_normal)
14617 int hitter_objnum = -2;
14618 object *objp_hitter = NULL;
14620 ai_info *aip, *hitter_aip;
14622 shipp = &Ships[objp_ship->instance];
14623 aip = &Ai_info[shipp->ai_index];
14625 if (objp_ship->flags & OF_PLAYER_SHIP)
14628 if ((aip->mode == AIM_WARP_OUT) || (aip->mode == AIM_PLAY_DEAD))
14631 if (hit_objp->type == OBJ_SHIP) {
14632 // If the object that this ship collided with is a big ship
14633 if (Ship_info[Ships[hit_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
14634 // And the current object is _not_ a big ship
14635 if (!(Ship_info[Ships[objp_ship->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
14636 // Recover from hitting a big ship. Note, if two big ships collide, they just pound away at each other. Oh well. Recovery looks dumb and it's very late.
14637 big_ship_collide_recover_start(objp_ship, hit_objp, hitpos, hit_normal);
14642 if (hit_objp->type == OBJ_WEAPON) {
14643 // Make sure the object that fired this weapon is still alive. If not, abort.
14644 // SDL_assert(hit_objp->parent >= 0);
14645 if(hit_objp->parent < 0){
14648 if ( hit_objp->parent_sig != Objects[hit_objp->parent].signature ){
14652 // Hit by a protected ship, don't attack it.
14653 if (Objects[hit_objp->parent].flags & OF_PROTECTED) {
14654 if ((Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) && (aip->target_objnum == -1)) {
14655 if (aip->mode == AIM_CHASE) {
14656 if (aip->submode != SM_EVADE_WEAPON) {
14657 aip->mode = AIM_CHASE;
14658 aip->submode = SM_EVADE_WEAPON;
14659 aip->submode_start_time = Missiontime;
14661 } else if (aip->mode != AIM_EVADE_WEAPON) {
14662 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14663 aip->previous_mode = aip->mode;
14664 aip->previous_submode = aip->submode;
14665 aip->mode = AIM_EVADE_WEAPON;
14667 aip->submode_start_time = Missiontime;
14668 aip->mode_time = timestamp(MAX_EVADE_TIME); // Evade for up to five seconds.
14675 hitter_objnum = hit_objp->parent;
14676 SDL_assert((hitter_objnum >= 0) && (hitter_objnum < MAX_OBJECTS));
14677 objp_hitter = &Objects[hitter_objnum];
14678 maybe_process_friendly_hit(objp_hitter, objp_ship, hit_objp); // Deal with player's friendly fire.
14680 if ( (shipp->team & TEAM_FRIENDLY) && !(Game_mode & GM_MULTIPLAYER) ) {
14681 ship_maybe_ask_for_help(shipp);
14683 } else if (hit_objp->type == OBJ_SHIP) {
14684 if (shipp->team == Ships[hit_objp->instance].team) // Don't have AI react to collisions between teammates.
14686 objp_hitter = hit_objp;
14687 hitter_objnum = hit_objp-Objects;
14689 Int3(); // Hmm, what kind of object hit this if not weapon or ship? Get MikeK.
14693 // Collided into a protected ship, don't attack it.
14694 if (hit_objp->flags & OF_PROTECTED)
14697 SDL_assert(objp_hitter != NULL);
14698 hitter_aip = &Ai_info[Ships[objp_hitter->instance].ai_index];
14699 hitter_aip->last_hit_target_time = Missiontime;
14701 // store the object signature of objp_ship into ai_info, since we want to track the last ship hit by 'hitter_objnum'
14702 hitter_aip->last_objsig_hit = objp_ship->signature;
14704 aip->last_hit_time = Missiontime;
14706 if (aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) // If not allowed to pursue dynamic objectives, don't evade. Dumb? Maybe change. -- MK, 3/15/98
14709 // If this ship is awaiting repair, abort!
14710 if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)) {
14711 ship_info *sip = &Ship_info[shipp->ship_info_index];
14713 if (objp_ship->hull_strength/sip->initial_hull_strength < 0.3f) {
14714 // No, only abort if hull below a certain level.
14715 aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP/2); // Might request again after 15 seconds.
14716 if ( !(objp_ship->flags & OF_PLAYER_SHIP) ) // mwa -- don't abort rearm for a player
14717 ai_abort_rearm_request(objp_ship);
14721 // If firing a bomb, ignore enemy fire so we can gain lock drop the bomb.
14722 // Only ignore fire if aspect_locked_time > 0.5f, as this means we're in range.
14723 if (firing_aspect_seeking_bomb(objp_ship)) {
14724 if ((aip->ai_flags & AIF_SEEK_LOCK) && (aip->aspect_locked_time > 0.1f))
14728 // If in AIM_STRAFE mode and got hit by target, maybe attack turret if appropriate
14729 if (aip->mode == AIM_STRAFE) {
14730 SDL_assert(hitter_objnum != -2);
14731 if (aip->target_objnum == hitter_objnum) {
14732 if ( hit_objp->type == OBJ_WEAPON ) {
14733 ai_big_strafe_maybe_attack_turret(objp_ship, hit_objp);
14739 ; // do nothing here, we'll attack this hitter if it is a fighter or bomber (this is handled
14740 // in code later in this function
14744 if (objp_ship == Player_obj)
14745 return; // We don't do AI for the player.
14747 maybe_update_guard_object(objp_ship, objp_hitter);
14749 // Big ships don't go any further.
14750 if (!(Ship_info[shipp->ship_info_index].flags & SIF_SMALL_SHIP))
14753 // If the hitter object is the ignore object, don't attack it.
14754 ship_info *sip = &Ship_info[shipp->ship_info_index];
14755 if ((is_ignore_object(aip, objp_hitter-Objects)) && (sip->flags & (SIF_BOMBER | SIF_FIGHTER))) {
14756 if (aip->mode == AIM_NONE) {
14757 aip->mode = AIM_CHASE; // This will cause the ship to move, if not attack.
14758 aip->submode = SM_EVADE;
14763 // Maybe abort based on mode.
14764 switch (aip->mode) {
14766 if (aip->submode == SM_ATTACK_FOREVER)
14769 if ( hit_objp->type == OBJ_WEAPON ) {
14770 if ( ai_big_maybe_enter_strafe_mode(objp_ship, OBJ_INDEX(hit_objp), 1) )
14775 // If in guard mode and far away from guard object, don't pursue guy that hit me.
14776 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
14777 if (vm_vec_dist_quick(&objp_ship->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
14782 case AIM_STAY_NEAR:
14783 // Note: Dealt with above, at very top. case AIM_PLAY_DEAD:
14786 case AIM_EVADE_WEAPON:
14788 case AIM_GET_BEHIND:
14794 case AIM_BAY_DEPART:
14795 case AIM_SENTRYGUN:
14797 case AIM_BAY_EMERGE:
14798 // If just leaving the docking bay, don't react to enemy fire... just keep flying away from docking bay
14799 if ( (Missiontime - aip->submode_start_time) < 5*F1_0 ) {
14803 case AIM_WAYPOINTS:
14804 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER))
14810 if ((aip->submode != AISS_1) || (Missiontime - aip->submode_start_time > i2f(1))) {
14811 aip->submode = AISS_1;
14812 aip->submode_start_time = Missiontime;
14820 Int3(); // Bogus mode!
14823 if (timestamp_elapsed(aip->ok_to_target_timestamp))
14824 aip->ai_flags &= ~AIF_FORMATION; // If flying in formation, bug out!
14826 aip->hitter_objnum = hitter_objnum;
14827 aip->hitter_signature = Objects[hitter_objnum].signature;
14829 // If the hitter is not on the same team as the hittee, do some stuff.
14830 if (shipp->team != Ships[objp_hitter->instance].team) {
14831 //nprintf(("AI", "Object %i attacking %i, who just hit him!\n", objp_ship-Objects, hitter_objnum));
14833 if ((hitter_objnum != aip->target_objnum) && (sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
14834 maybe_set_dynamic_chase(aip, hitter_objnum);
14835 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14837 if ((aip->mode == AIM_CHASE) && ((objp_ship->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp_ship)/sip->shields > 0.8f))) {
14838 switch (aip->submode) {
14840 case SM_SUPER_ATTACK:
14844 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
14845 maybe_set_dynamic_chase(aip, hitter_objnum);
14847 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14850 } else if (aip->mode == AIM_CHASE) {
14851 switch (aip->submode) {
14853 aip->submode = SM_EVADE;
14854 aip->submode_start_time = Missiontime;
14856 case SM_SUPER_ATTACK:
14857 if (Missiontime - aip->submode_start_time > i2f(1)) {
14858 aip->submode = SM_EVADE;
14859 aip->submode_start_time = Missiontime;
14862 case SM_EVADE_BRAKE:
14864 case SM_EVADE_SQUIGGLE:
14865 aip->submode = SM_EVADE;
14866 aip->submode_start_time = Missiontime;
14869 if (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) {
14870 maybe_set_dynamic_chase(aip, hitter_objnum);
14871 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14877 // AL 3-15-98: Prevent escape pods from entering chase mode
14878 if ( (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) ) {
14879 maybe_set_dynamic_chase(aip, hitter_objnum);
14881 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14887 // Ship shipnum has been destroyed.
14889 // the parameter 'method' is used to tell is this ship was destroyed or it departed normally.
14890 // This function will get called in either case, and there are things that should be done if
14891 // the ship actually gets destroyed which shouldn't get done if it departed.
14892 void ai_ship_destroy(int shipnum, int method)
14895 object *other_objp;
14900 SDL_assert((shipnum >= 0) && (shipnum < MAX_SHIPS));
14901 objnum = Ships[shipnum].objnum;
14902 dead_aip = &Ai_info[Ships[shipnum].ai_index];
14904 // if I was getting repaired, or awaiting repair, then cleanup the repair mode. When awaiting repair, the dock_objnum
14905 // is -1. When the support ship is on the way, the dock_objnum >= 0 (points to support ship).
14906 if ( dead_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14907 if ( dead_aip->dock_objnum >= 0 )
14908 ai_do_objects_repairing_stuff( &Objects[objnum], &Objects[dead_aip->dock_objnum], REPAIR_INFO_END);
14910 ai_do_objects_repairing_stuff( &Objects[objnum], NULL, REPAIR_INFO_END );
14913 // For all objects that had this ship as a target, wipe it out, forcing find of a new enemy.
14914 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
14915 other_objp = &Objects[so->objnum];
14916 SDL_assert(other_objp->instance != -1);
14918 shipp = &Ships[other_objp->instance];
14919 SDL_assert(shipp->ai_index != -1);
14921 ai_info *aip = &Ai_info[shipp->ai_index];
14924 // code commented out below is taken care of in ai_cleanup_dock_mode when gets called when the
14925 // support ship starts it's death roll.
14927 // If the destroyed ship was on its way to repair the current ship
14928 if (aip->dock_objnum == objnum) {
14930 // clean up the flags for any kind of docking mode. If aip was part of a goal of dock/undock
14931 // then it will get cleaned up by the goal code.
14932 ai_do_objects_undocked_stuff( other_objp, NULL );
14934 if ( aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14936 if ( method == SEF_DEPARTED ) {
14937 abort_reason = REPAIR_INFO_ABORT;
14939 abort_reason = REPAIR_INFO_KILLED;
14941 ai_do_objects_repairing_stuff( other_objp, NULL, abort_reason );
14945 if (aip->target_objnum == objnum) {
14946 set_target_objnum(aip, -1);
14947 // If this ship had a dynamic goal of chasing the dead ship, clear the dynamic goal.
14948 if (aip->resume_goal_time != -1)
14949 aip->active_goal = AI_GOAL_NONE;
14952 if (aip->goal_objnum == objnum) {
14953 aip->goal_objnum = -1;
14954 aip->goal_signature = -1;
14957 if (aip->guard_objnum == objnum) {
14958 aip->guard_objnum = -1;
14959 aip->guard_signature = -1;
14962 if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[Objects[objnum].instance].ai_index].wing)) {
14963 if (aip->guard_wingnum != aip->wing)
14964 ai_set_guard_wing(other_objp, aip->guard_wingnum);
14967 if (aip->hitter_objnum == objnum)
14968 aip->hitter_objnum = -1;
14975 // Interface function to goals code.
14976 // Make object *objp fly to point *vp and warp out.
14977 void ai_warp_out(object *objp, vector *vp)
14981 aip = &Ai_info[Ships[objp->instance].ai_index];
14983 if (aip->mode != AIM_WARP_OUT) {
14984 ai_set_mode_warp_out(objp, aip);
14991 dist = vm_vec_normalized_dir(&v2v, vp, &objp->pos);
14993 if (dist < objp->radius + 5.0f) {
14995 // Start the warp out effect
14996 shipfx_warpout_start(objp);
14999 dot = vm_vec_dot(&objp->orient.v.fvec, &v2v);
15001 aip = &Ai_info[Ships[objp->instance].ai_index];
15004 accelerate_ship(aip, 1.0f);
15006 accelerate_ship(aip, (3*dot + 1.0f)/4.0f);
15008 turn_towards_point(objp, vp, NULL, 0.0f);
15014 // Do stuff at start of deathroll.
15015 void ai_deathroll_start(object *ship_obj)
15018 ship *shipp, *other_ship;
15020 shipp = &Ships[ship_obj->instance];
15021 aip = &Ai_info[shipp->ai_index];
15023 // mark object we are docked with so we can do damage and separate during deathroll
15024 // keep dock_objnum_when_dead from being changed if already set (only allow to be set when -1)
15025 if (Ships[ship_obj->instance].dock_objnum_when_dead == -1) {
15026 Ships[ship_obj->instance].dock_objnum_when_dead = aip->dock_objnum;
15027 // set other_ship dock_objnum_when_dead, if other_ship exits.
15028 if (Ships[ship_obj->instance].dock_objnum_when_dead != -1) {
15029 other_ship = &Ships[Objects[aip->dock_objnum].instance];
15030 other_ship->dock_objnum_when_dead = shipp->objnum;
15034 ai_cleanup_dock_mode(aip, shipp);
15036 aip->mode = AIM_NONE;
15039 // Object *requester_objp tells rearm ship to abort rearm.
15040 // Returns true if it succeeded, else false.
15041 // To succeed means you were previously rearming.
15042 int ai_abort_rearm_request(object *requester_objp)
15044 ship *requester_shipp;
15045 ai_info *requester_aip;
15047 SDL_assert(requester_objp->type == OBJ_SHIP);
15048 if(requester_objp->type != OBJ_SHIP){
15051 SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));
15052 if((requester_objp->instance < 0) || (requester_objp->instance >= MAX_SHIPS)){
15055 requester_shipp = &Ships[requester_objp->instance];
15056 SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));
15057 if((requester_shipp->ai_index < 0) || (requester_shipp->ai_index >= MAX_AI_INFO)){
15060 requester_aip = &Ai_info[requester_shipp->ai_index];
15062 if (requester_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)){
15064 // dock_objnum is always valid once a rearm repair has been requested. It points to the
15065 // ship that is coming to repair me.
15066 if (requester_aip->dock_objnum != -1) {
15067 object *repair_objp;
15068 ai_info *repair_aip;
15070 repair_objp = &Objects[requester_aip->dock_objnum];
15071 repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
15073 // Make sure signatures match. This prevents nasty bugs in which an object
15074 // that was repairing another is destroyed and is replaced by another ship
15075 // before this code comes around.
15076 if (repair_objp->signature == requester_aip->dock_signature) {
15078 SDL_assert( repair_objp->type == OBJ_SHIP );
15080 // if support ship is in the process of undocking, don't do anything.
15081 if ( repair_aip->submode < AIS_UNDOCK_0 ) {
15082 ai_do_objects_repairing_stuff( requester_objp, repair_objp, REPAIR_INFO_ABORT );
15084 if ( repair_aip->submode == AIS_DOCK_4 )
15085 repair_aip->submode = AIS_UNDOCK_0;
15087 repair_aip->submode = AIS_UNDOCK_3;
15089 repair_aip->submode_start_time = Missiontime;
15091 nprintf(("AI", "Not aborting rearm since already undocking\n"));
15095 // setting these flags is the safe things to do. There may not be a corresponding repair
15096 // ship for this guys since a repair ship may be currently repairing someone else.
15097 ai_do_objects_repairing_stuff( requester_objp, NULL, REPAIR_INFO_ABORT );
15099 // try and remove this guy from an arriving support ship.
15100 mission_remove_scheduled_repair(requester_objp);
15104 } else if ( requester_aip->ai_flags & AIF_REPAIRING ) {
15105 // a support ship can request to abort when he is told to do something else (like warp out).
15106 // see if this support ships goal_objnum is valid. If so, then issue this ai_abort comment
15107 // for the ship that he is enroute to repair
15108 if ( requester_aip->goal_objnum != -1 ) {
15111 val = ai_abort_rearm_request( &Objects[requester_aip->goal_objnum] );
15119 // function which gets called from ai-issue_rearm_request and from code in missionparse.cpp
15120 // to actually issue the rearm goal (support_obj to rearm requester_obj);
15121 void ai_add_rearm_goal( object *requester_objp, object *support_objp )
15123 ship *support_shipp, *requester_shipp;
15124 ai_info *support_aip, *requester_aip;
15126 support_shipp = &Ships[support_objp->instance];
15127 requester_shipp = &Ships[requester_objp->instance];
15128 requester_aip = &Ai_info[requester_shipp->ai_index];
15130 SDL_assert( support_shipp->ai_index != -1 );
15131 support_aip = &Ai_info[support_shipp->ai_index];
15133 // if the requester is a player object, issue the order as the squadmate messaging code does. Doing so
15134 // ensures that the player get a higher priority!
15135 requester_aip->ai_flags |= AIF_AWAITING_REPAIR; // Tell that I'm awaiting repair.
15136 if ( requester_objp->flags & OF_PLAYER_SHIP )
15137 ai_add_ship_goal_player( AIG_TYPE_PLAYER_SHIP, AI_GOAL_REARM_REPAIR, -1, requester_shipp->ship_name, support_aip );
15139 ai_add_goal_ship_internal( support_aip, AI_GOAL_REARM_REPAIR, requester_shipp->ship_name, -1, -1 );
15143 // Object *requester_objp requests rearming.
15144 // Returns objnum of ship coming to repair requester on success
15145 // Success means you found someone to rearm you and you weren't previously rearming.
15146 int ai_issue_rearm_request(object *requester_objp)
15149 ship *requester_shipp;
15150 ai_info *requester_aip;
15152 SDL_assert(requester_objp->type == OBJ_SHIP);
15153 SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));
15154 requester_shipp = &Ships[requester_objp->instance];
15155 SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));
15156 requester_aip = &Ai_info[requester_shipp->ai_index];
15158 // Make sure not already awaiting repair.
15159 if (requester_aip->ai_flags & AIF_AWAITING_REPAIR) {
15160 nprintf(("AI", "Ship %s already awaiting rearm by ship %s.\n", requester_shipp->ship_name, &Ships[Objects[requester_aip->dock_objnum].instance].ship_name));
15164 if ( !is_support_allowed(requester_objp) )
15167 //nprintf(("AI", "Ship %s requesting rearming.\n", requester_shipp->ship_name));
15168 requester_aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP); // Might request again after this much time.
15170 // call ship_find_repair_ship to get a support ship. If none is found, then we will warp one in. This
15171 // function will return the next available ship which can repair requester
15172 objp = ship_find_repair_ship( requester_objp );
15173 ai_do_objects_repairing_stuff( requester_objp, objp, REPAIR_INFO_QUEUE );
15176 // MWA 5/14/98 -- moved next item into the ai_do_objects_repairing_stuff function so that clients
15177 // would properly update their hud support view
15178 //ai_add_rearm_goal( requester_objp, objp );
15179 return OBJ_INDEX(objp);
15182 // call to warp in repair ship!!!! for now, warp in any number of ships needed. Should cap it to
15183 // some reasonable max (or let support ships warp out). We should assume here that ship_find_repair_ship()
15184 // would have returned a valid object if there are too many support ships already in the mission
15185 mission_warp_in_support_ship( requester_objp );
15192 // make objp rearm and repair goal_objp
15193 void ai_rearm_repair( object *objp, object *goal_objp, int priority, int docker_index, int dockee_index )
15195 ai_info *aip, *goal_aip;
15197 aip = &Ai_info[Ships[objp->instance].ai_index];
15198 aip->goal_objnum = goal_objp-Objects;
15200 // nprintf(("AI", "Ship %s preparing to rearm ship %s.\n", shipp->ship_name, requester_shipp->ship_name));
15202 ai_dock_with_object(objp, goal_objp, priority, AIDO_DOCK, docker_index, dockee_index);
15203 aip->ai_flags |= AIF_REPAIRING; // Tell that repair guy is busy trying to repair someone.
15205 goal_aip = &Ai_info[Ships[goal_objp->instance].ai_index];
15206 goal_aip->dock_objnum = objp-Objects; // Tell which object is coming to repair.
15207 goal_aip->dock_signature = objp->signature;
15209 ai_do_objects_repairing_stuff( goal_objp, objp, REPAIR_INFO_ONWAY );
15211 goal_aip->abort_rearm_timestamp = timestamp(NEXT_REARM_TIMESTAMP*3/2);
15214 // Given a dockee object and the index of the dockbay for that object (ie the dockbay index
15215 // into polymodel->dockbays[] for the model associated with the object), return the index
15216 // of a path_num associated with than dockbay (this is an index into polymodel->paths[])
15217 int ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index)
15219 if ( dockbay_index < 0 || dockee_objp == NULL ) {
15220 Int3(); // should never happen
15224 if ( dockee_objp->type == OBJ_SHIP ) {
15228 pm = model_get( Ships[dockee_objp->instance].modelnum );
15231 SDL_assert(pm->n_docks > dockbay_index);
15232 SDL_assert(pm->docking_bays[dockbay_index].num_spline_paths > 0);
15233 SDL_assert(pm->docking_bays[dockbay_index].splines != NULL);
15234 if(pm->n_docks <= dockbay_index){
15237 if(pm->docking_bays[dockbay_index].num_spline_paths <= 0){
15240 if(pm->docking_bays[dockbay_index].splines == NULL){
15244 // We only need to return one path for the dockbay, so return the first
15245 path_num = pm->docking_bays[dockbay_index].splines[0];
15252 // Actually go ahead and fire the synaptics.
15253 void cheat_fire_synaptic(object *objp, ship *shipp, ai_info *aip)
15256 swp = &shipp->weapons;
15257 int current_bank = swp->current_secondary_bank;
15259 ai_select_secondary_weapon(objp, swp, WIF_SPAWN, 0);
15260 if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
15261 if (ship_fire_secondary(objp)) {
15262 nprintf(("AI", "ship %s cheat fired synaptic!\n", shipp->ship_name));
15263 swp->next_secondary_fire_stamp[current_bank] = timestamp(2500);
15268 // For the subspace mission (sm3-09a)
15270 // if they're sufficiently far into the mission
15271 // if they're near one or more enemies
15273 // fire a synaptic if they have one.
15274 void maybe_cheat_fire_synaptic(object *objp, ai_info *aip)
15276 // Only do in subspace missions.
15277 if ( The_mission.flags & MISSION_FLAG_SUBSPACE ) {
15281 shipp = &Ships[objp->instance];
15283 if (!(SDL_strncasecmp(shipp->ship_name, NOX("delta"), 5))) {
15284 num = shipp->ship_name[6] - '1';
15286 if ((num >= 0) && (num <= 3)) {
15287 time = Missiontime >> 16; // Convert to seconds.
15289 time -= 2*60; // Subtract off two minutes.
15292 int modulus = 17 + num*3;
15294 if ((time % modulus) < 2) {
15295 int count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(objp)), &objp->pos, 1500.0f);
15298 cheat_fire_synaptic(objp, shipp, aip);