]> icculus.org git repositories - btb/d2x.git/blob - main/aipath.c
Import of d2x-0.0.8
[btb/d2x.git] / main / aipath.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.  
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 #include <conf.h>
15 #include <stdio.h>              //      for printf()
16 #include <stdlib.h>             // for rand() and qsort()
17 #include <string.h>             // for memset()
18
19 #include "inferno.h"
20 #include "mono.h"
21 #include "fix.h"
22 #include "vecmat.h"
23 #include "gr.h"
24 #include "3d.h"
25
26 #include "object.h"
27 #include "error.h"
28 #include "ai.h"
29 #include "robot.h"
30 #include "fvi.h"
31 #include "physics.h"
32 #include "wall.h"
33 #include "player.h"
34 #include "fireball.h"
35 #include "game.h"
36 #include "maths.h"
37
38 #ifdef EDITOR
39 #include "editor\editor.h"
40 #endif
41
42 #define PARALLAX        0               //      If !0, then special debugging for Parallax eyes enabled.
43
44 //      Length in segments of avoidance path
45 #define AVOID_SEG_LENGTH        7
46
47 #define PATH_VALIDATION 0
48
49 //      LINT:  Function prototypes
50 int validate_path(int debug_flag, point_seg* psegs, int num_points);
51 void validate_all_paths(void);
52 void ai_path_set_orient_and_vel(object *objp, vms_vector* goal_point, int player_visibility, vms_vector *vec_to_player);
53 void maybe_ai_path_garbage_collect(void);
54
55 void ai_path_garbage_collect(void);
56
57 //      ------------------------------------------------------------------------
58 void create_random_xlate(byte *xt)
59 {
60         int     i;
61
62         for (i=0; i<MAX_SIDES_PER_SEGMENT; i++)
63                 xt[i] = i;
64
65         for (i=0; i<MAX_SIDES_PER_SEGMENT; i++) {
66                 int     j = (d_rand()*MAX_SIDES_PER_SEGMENT)/(RAND_MAX);
67                 byte    temp_byte;
68                 Assert((j >= 0) && (j < MAX_SIDES_PER_SEGMENT));
69
70                 temp_byte = xt[j];
71                 xt[j] = xt[i];
72                 xt[i] = temp_byte;
73         }
74
75 }
76
77 //      -----------------------------------------------------------------------------------------------------------
78 //      Insert the point at the center of the side connecting two segments between the two points.
79 // This is messy because we must insert into the list.  The simplest (and not too slow) way to do this is to start
80 // at the end of the list and go backwards.
81 void insert_center_points(point_seg *psegs, int *num_points)
82 {
83         int     i, j, last_point;
84         int     count=*num_points;
85
86         last_point = *num_points-1;
87
88         for (i=last_point; i>0; i--) {
89                 int                     connect_side, temp_segnum;
90                 vms_vector      center_point, new_point;
91
92                 psegs[2*i] = psegs[i];
93                 connect_side = find_connect_side(&Segments[psegs[i].segnum], &Segments[psegs[i-1].segnum]);
94                 Assert(connect_side != -1);     //      Impossible!  These two segments must be connected, they were created by create_path_points (which was created by mk!)
95                 if (connect_side == -1)                 //      Try to blow past the assert, this should at least prevent a hang.
96                         connect_side = 0;
97                 compute_center_point_on_side(&center_point, &Segments[psegs[i-1].segnum], connect_side);
98                 vm_vec_sub(&new_point, &psegs[i-1].point, &center_point);
99                 new_point.x /= 16;
100                 new_point.y /= 16;
101                 new_point.z /= 16;
102                 vm_vec_sub(&psegs[2*i-1].point, &center_point, &new_point);
103                 temp_segnum = find_point_seg(&psegs[2*i-1].point, psegs[2*i].segnum);
104                 if (temp_segnum == -1) {
105                         mprintf((1, "Warning: point not in ANY segment in aipath.c/insert_center_points.\n"));
106                         psegs[2*i-1].point = center_point;
107                         find_point_seg(&psegs[2*i-1].point, psegs[2*i].segnum);
108                 }
109
110                 psegs[2*i-1].segnum = psegs[2*i].segnum;
111                 count++;
112         }
113
114         //      Now, remove unnecessary center points.
115         //      A center point is unnecessary if it is close to the line between the two adjacent points.
116         //      MK, OPTIMIZE!  Can get away with about half the math since every vector gets computed twice.
117         for (i=1; i<count-1; i+=2) {
118                 vms_vector      temp1, temp2;
119                 fix                     dot;
120
121                 dot = vm_vec_dot(vm_vec_sub(&temp1, &psegs[i].point, &psegs[i-1].point), vm_vec_sub(&temp2, &psegs[i+1].point, &psegs[i].point));
122
123                 if (dot * 9/8 > fixmul(vm_vec_mag(&temp1), vm_vec_mag(&temp2)))
124                         psegs[i].segnum = -1;
125
126         }
127
128         //      Now, scan for points with segnum == -1
129         j = 0;
130         for (i=0; i<count; i++)
131                 if (psegs[i].segnum != -1)
132                         psegs[j++] = psegs[i];
133
134         *num_points = j;
135 }
136
137 #ifdef EDITOR
138 int     Safety_flag_override = 0;
139 int     Random_flag_override = 0;
140 int     Ai_path_debug=0;
141 #endif
142
143 //      -----------------------------------------------------------------------------------------------------------
144 //      Move points halfway to outside of segment.
145 void move_towards_outside(point_seg *psegs, int *num_points, object *objp, int rand_flag)
146 {
147         int     i;
148         point_seg       new_psegs[200];
149
150         Assert(*num_points < 200);
151
152         for (i=1; i<*num_points-1; i++) {
153                 int                     new_segnum;
154                 fix                     segment_size;
155                 int                     segnum;
156                 vms_vector      a, b, c, d, e;
157                 vms_vector      goal_pos;
158                 int                     count;
159                 int                     temp_segnum;
160
161                 // -- psegs[i].segnum = find_point_seg(&psegs[i].point, psegs[i].segnum);
162                 temp_segnum = find_point_seg(&psegs[i].point, psegs[i].segnum);
163                 Assert(temp_segnum != -1);
164                 psegs[i].segnum = temp_segnum;
165                 segnum = psegs[i].segnum;
166
167                 vm_vec_sub(&a, &psegs[i].point, &psegs[i-1].point);
168                 vm_vec_sub(&b, &psegs[i+1].point, &psegs[i].point);
169                 vm_vec_sub(&c, &psegs[i+1].point, &psegs[i-1].point);
170                 //      I don't think we can use quick version here and this is _very_ rarely called. --MK, 07/03/95
171                 vm_vec_normalize_quick(&a);
172                 vm_vec_normalize_quick(&b);
173                 if (abs(vm_vec_dot(&a, &b)) > 3*F1_0/4 ) {
174                         if (abs(a.z) < F1_0/2) {
175                                 if (rand_flag) {
176                                         e.x = (d_rand()-16384)/2;
177                                         e.y = (d_rand()-16384)/2;
178                                         e.z = abs(e.x) + abs(e.y) + 1;
179                                         vm_vec_normalize_quick(&e);
180                                 } else {
181                                         e.x = 0;
182                                         e.y = 0;
183                                         e.z = F1_0;
184                                 }
185                         } else {
186                                 if (rand_flag) {
187                                         e.y = (d_rand()-16384)/2;
188                                         e.z = (d_rand()-16384)/2;
189                                         e.x = abs(e.y) + abs(e.z) + 1;
190                                         vm_vec_normalize_quick(&e);
191                                 } else {
192                                         e.x = F1_0;
193                                         e.y = 0;
194                                         e.z = 0;
195                                 }
196                         }
197                 } else {
198                         vm_vec_cross(&d, &a, &b);
199                         vm_vec_cross(&e, &c, &d);
200                         vm_vec_normalize_quick(&e);
201                 }
202
203 if (vm_vec_mag_quick(&e) < F1_0/2)
204         Int3();
205
206 //mprintf((0, "(%i) Moving to side: %6.3f %6.3f %6.3f\n", i, f2fl(e.x), f2fl(e.y), f2fl(e.z)));
207
208                 segment_size = vm_vec_dist_quick(&Vertices[Segments[segnum].verts[0]], &Vertices[Segments[segnum].verts[6]]);
209                 if (segment_size > F1_0*40)
210                         segment_size = F1_0*40;
211
212                 vm_vec_scale_add(&goal_pos, &psegs[i].point, &e, segment_size/4);
213
214                 count = 3;
215                 while (count) {
216                         fvi_query       fq;
217                         fvi_info                hit_data;
218                         int                     hit_type;
219         
220                         fq.p0                                           = &psegs[i].point;
221                         fq.startseg                             = psegs[i].segnum;
222                         fq.p1                                           = &goal_pos;
223                         fq.rad                                  = objp->size;
224                         fq.thisobjnum                   = objp-Objects;
225                         fq.ignore_obj_list      = NULL;
226                         fq.flags                                        = 0;
227         
228                         hit_type = find_vector_intersection(&fq, &hit_data);
229         
230                         if (hit_type == HIT_NONE)
231                                 count = 0;
232                         else {
233                                 if ((count == 3) && (hit_type == HIT_BAD_P0))
234                                         Int3();
235                                 goal_pos.x = (fq.p0->x + hit_data.hit_pnt.x)/2;
236                                 goal_pos.y = (fq.p0->y + hit_data.hit_pnt.y)/2;
237                                 goal_pos.z = (fq.p0->z + hit_data.hit_pnt.z)/2;
238                                 count--;
239                                 if (count == 0) {       //      Couldn't move towards outside, that's ok, sometimes things can't be moved.
240                                         goal_pos = psegs[i].point;
241                                 }
242                         }
243                 }
244
245                 //      Only move towards outside if remained inside segment.
246                 new_segnum = find_point_seg(&goal_pos, psegs[i].segnum);
247                 if (new_segnum == psegs[i].segnum) {
248                         new_psegs[i].point = goal_pos;
249                         new_psegs[i].segnum = new_segnum;
250                 } else {
251                         new_psegs[i].point = psegs[i].point;
252                         new_psegs[i].segnum = psegs[i].segnum;
253                 }
254
255         }
256
257         for (i=1; i<*num_points-1; i++)
258                 psegs[i] = new_psegs[i];
259 }
260
261
262 //      -----------------------------------------------------------------------------------------------------------
263 //      Create a path from objp->pos to the center of end_seg.
264 //      Return a list of (segment_num, point_locations) at psegs
265 //      Return number of points in *num_points.
266 //      if max_depth == -1, then there is no maximum depth.
267 //      If unable to create path, return -1, else return 0.
268 //      If random_flag !0, then introduce randomness into path by looking at sides in random order.  This means
269 //      that a path between two segments won't always be the same, unless it is unique.
270 //      If safety_flag is set, then additional points are added to "make sure" that points are reachable.  I would
271 //      like to say that it ensures that the object can move between the points, but that would require knowing what
272 //      the object is (which isn't passed, right?) and making fvi calls (slow, right?).  So, consider it the more_or_less_safe_flag.
273 //      If end_seg == -2, then end seg will never be found and this routine will drop out due to depth (probably called by create_n_segment_path).
274 int create_path_points(object *objp, int start_seg, int end_seg, point_seg *psegs, short *num_points, int max_depth, int random_flag, int safety_flag, int avoid_seg)
275 {
276         int             cur_seg;
277         int             sidenum;
278         int             qtail = 0, qhead = 0;
279         int             i;
280         byte            visited[MAX_SEGMENTS];
281         seg_seg seg_queue[MAX_SEGMENTS];
282         short           depth[MAX_SEGMENTS];
283         int             cur_depth;
284         byte            random_xlate[MAX_SIDES_PER_SEGMENT];
285         point_seg       *original_psegs = psegs;
286         int             l_num_points;
287
288 // -- mprintf((0, "cpp: frame = %4i obj %3i, psegs = %5i\n", FrameCount, objp-Objects, psegs-Point_segs));
289 #if PATH_VALIDATION
290         validate_all_paths();
291 #endif
292
293 if ((objp->type == OBJ_ROBOT) && (objp->ctype.ai_info.behavior == AIB_RUN_FROM)) {
294         random_flag = 1;
295         avoid_seg = ConsoleObject->segnum;
296         // Int3();
297 }
298
299         if (max_depth == -1)
300                 max_depth = MAX_PATH_LENGTH;
301
302         l_num_points = 0;
303 //random_flag = Random_flag_override; //!! debug!!
304 //safety_flag = Safety_flag_override; //!! debug!!
305
306 //      for (i=0; i<=Highest_segment_index; i++) {
307 //              visited[i] = 0;
308 //              depth[i] = 0;
309 //      }
310         memset(visited, 0, sizeof(visited[0])*(Highest_segment_index+1));
311         memset(depth, 0, sizeof(depth[0])*(Highest_segment_index+1));
312
313         //      If there is a segment we're not allowed to visit, mark it.
314         if (avoid_seg != -1) {
315                 Assert(avoid_seg <= Highest_segment_index);
316                 if ((start_seg != avoid_seg) && (end_seg != avoid_seg)) {
317                         visited[avoid_seg] = 1;
318                         depth[avoid_seg] = 0;
319                 } else
320                         ; // -- mprintf((0, "Start/End/Avoid = %i %i %i\n", start_seg, end_seg, avoid_seg));
321         }
322
323         if (random_flag)
324                 create_random_xlate(random_xlate);
325
326         cur_seg = start_seg;
327         visited[cur_seg] = 1;
328         cur_depth = 0;
329
330         while (cur_seg != end_seg) {
331                 segment *segp = &Segments[cur_seg];
332
333                 if (random_flag)
334                         if (d_rand() < 8192)
335                                 create_random_xlate(random_xlate);
336
337                 // mprintf((0, "\n"));
338                 for (sidenum = 0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
339
340                         int     snum = sidenum;
341
342                         if (random_flag)
343                                 snum = random_xlate[sidenum];
344
345                         if (IS_CHILD(segp->children[snum]) && ((WALL_IS_DOORWAY(segp, snum) & WID_FLY_FLAG) || (ai_door_is_openable(objp, segp, snum)))) {
346                                 int                     this_seg = segp->children[snum];
347                                 Assert(this_seg != -1);
348                                 if (((cur_seg == avoid_seg) || (this_seg == avoid_seg)) && (ConsoleObject->segnum == avoid_seg)) {
349                                         vms_vector      center_point;
350
351                                         fvi_query       fq;
352                                         fvi_info                hit_data;
353                                         int                     hit_type;
354         
355                                         compute_center_point_on_side(&center_point, segp, snum);
356
357                                         fq.p0                                           = &objp->pos;
358                                         fq.startseg                             = objp->segnum;
359                                         fq.p1                                           = &center_point;
360                                         fq.rad                                  = objp->size;
361                                         fq.thisobjnum                   = objp-Objects;
362                                         fq.ignore_obj_list      = NULL;
363                                         fq.flags                                        = 0;
364
365                                         hit_type = find_vector_intersection(&fq, &hit_data);
366                                         if (hit_type != HIT_NONE) {
367                                                 // -- mprintf((0, "hit_type = %i, object = %i\n", hit_type, hit_data.hit_object));
368                                                 goto dont_add;
369                                         }
370                                 }
371
372                                 if (!visited[this_seg]) {
373                                         seg_queue[qtail].start = cur_seg;
374                                         seg_queue[qtail].end = this_seg;
375                                         visited[this_seg] = 1;
376                                         depth[qtail++] = cur_depth+1;
377                                         if (depth[qtail-1] == max_depth) {
378                                                 // mprintf((0, "\ndepth == max_depth == %i\n", max_depth));
379                                                 end_seg = seg_queue[qtail-1].end;
380                                                 goto cpp_done1;
381                                         }       // end if (depth[...
382                                 }       // end if (!visited...
383                         }       // if (WALL_IS_DOORWAY(...
384 dont_add: ;
385                 }       //      for (sidenum...
386
387                 if (qhead >= qtail) {
388                         //      Couldn't get to goal, return a path as far as we got, which probably acceptable to the unparticular caller.
389                         end_seg = seg_queue[qtail-1].end;
390                         break;
391                 }
392
393                 cur_seg = seg_queue[qhead].end;
394                 cur_depth = depth[qhead];
395                 qhead++;
396
397 cpp_done1: ;
398         }       //      while (cur_seg ...
399
400         //      Set qtail to the segment which ends at the goal.
401         while (seg_queue[--qtail].end != end_seg)
402                 if (qtail < 0) {
403                         // mprintf((0, "\nNo path!\n"));
404                         // printf("UNABLE TO FORM PATH");
405                         // Int3();
406                         *num_points = l_num_points;
407                         return -1;
408                 }
409
410         #ifdef EDITOR
411         // -- N_selected_segs = 0;
412         #endif
413 //printf("Object #%3i, start: %3i ", objp-Objects, psegs-Point_segs);
414         while (qtail >= 0) {
415                 int     parent_seg, this_seg;
416
417                 this_seg = seg_queue[qtail].end;
418                 parent_seg = seg_queue[qtail].start;
419                 Assert((this_seg >= 0) && (this_seg <= Highest_segment_index));
420                 psegs->segnum = this_seg;
421 //printf("%3i ", this_seg);
422                 compute_segment_center(&psegs->point,&Segments[this_seg]);
423                 psegs++;
424                 l_num_points++;
425                 #ifdef EDITOR
426                 // -- Selected_segs[N_selected_segs++] = this_seg;
427                 #endif
428
429                 if (parent_seg == start_seg)
430                         break;
431
432                 while (seg_queue[--qtail].end != parent_seg)
433                         Assert(qtail >= 0);
434         }
435
436         Assert((start_seg >= 0) && (start_seg <= Highest_segment_index));
437         psegs->segnum = start_seg;
438 //printf("%3i\n", start_seg);
439         compute_segment_center(&psegs->point,&Segments[start_seg]);
440         psegs++;
441         l_num_points++;
442
443 #if PATH_VALIDATION
444         validate_path(1, original_psegs, l_num_points);
445 #endif
446
447         //      Now, reverse point_segs in place.
448         for (i=0; i< l_num_points/2; i++) {
449                 point_seg               temp_point_seg = *(original_psegs + i);
450                 *(original_psegs + i) = *(original_psegs + l_num_points - i - 1);
451                 *(original_psegs + l_num_points - i - 1) = temp_point_seg;
452         }
453 #if PATH_VALIDATION
454         validate_path(2, original_psegs, l_num_points);
455 #endif
456
457         //      Now, if safety_flag set, then insert the point at the center of the side connecting two segments
458         //      between the two points.  This is messy because we must insert into the list.  The simplest (and not too slow)
459         //      way to do this is to start at the end of the list and go backwards.
460         if (safety_flag) {
461                 if (psegs - Point_segs + l_num_points + 2 > MAX_POINT_SEGS) {
462                         //      Ouch!  Cannot insert center points in path.  So return unsafe path.
463 //                      Int3(); // Contact Mike:  This is impossible.
464 //                      force_dump_ai_objects_all("Error in create_path_points");
465                         mprintf((0, "Resetting all paths because of safety_flag.\n"));
466                         ai_reset_all_paths();
467                         *num_points = l_num_points;
468                         return -1;
469                 } else {
470                         // int  old_num_points = l_num_points;
471                         insert_center_points(original_psegs, &l_num_points);
472                         // mprintf((0, "Saved %i/%i points.\n", 2*old_num_points - l_num_points - 1, old_num_points-1));
473                 }
474         }
475
476 #if PATH_VALIDATION
477         validate_path(3, original_psegs, l_num_points);
478 #endif
479
480 // -- MK, 10/30/95 -- This code causes apparent discontinuities in the path, moving a point
481 //      into a new segment.  It is not necessarily bad, but it makes it hard to track down actual
482 //      discontinuity problems.
483         if (objp->type == OBJ_ROBOT)
484                 if (Robot_info[objp->id].companion)
485                         move_towards_outside(original_psegs, &l_num_points, objp, 0);
486
487 #if PATH_VALIDATION
488         validate_path(4, original_psegs, l_num_points);
489 #endif
490
491         *num_points = l_num_points;
492         return 0;
493 }
494
495 int     Last_buddy_polish_path_frame;
496
497 //      -------------------------------------------------------------------------------------------------------
498 //      polish_path
499 //      Takes an existing path and makes it nicer.
500 //      Drops as many leading points as possible still maintaining direct accessibility
501 //      from current position to first point.
502 //      Will not shorten path to fewer than 3 points.
503 //      Returns number of points.
504 //      Starting position in psegs doesn't change.
505 //      Changed, MK, 10/18/95.  I think this was causing robots to get hung up on walls.
506 //                              Only drop up to the first three points.
507 int polish_path(object *objp, point_seg *psegs, int num_points)
508 {
509         int     i, first_point=0;
510
511         if (num_points <= 4)
512                 return num_points;
513
514         //      Prevent the buddy from polishing his path twice in one frame, which can cause him to get hung up.  Pretty ugly, huh?
515         if (Robot_info[objp->id].companion)
516         {
517                 if (FrameCount == Last_buddy_polish_path_frame)
518                         return num_points;
519                 else
520                         Last_buddy_polish_path_frame = FrameCount;
521         }
522
523         // -- MK: 10/18/95: for (i=0; i<num_points-3; i++) {
524         for (i=0; i<2; i++) {
525                 fvi_query       fq;
526                 fvi_info                hit_data;
527                 int                     hit_type;
528         
529                 fq.p0                                           = &objp->pos;
530                 fq.startseg                             = objp->segnum;
531                 fq.p1                                           = &psegs[i].point;
532                 fq.rad                                  = objp->size;
533                 fq.thisobjnum                   = objp-Objects;
534                 fq.ignore_obj_list      = NULL;
535                 fq.flags                                        = 0;
536
537                 hit_type = find_vector_intersection(&fq, &hit_data);
538         
539                 if (hit_type == HIT_NONE)
540                         first_point = i+1;
541                 else
542                         break;          
543         }
544
545         if (first_point) {
546                 //      Scrunch down all the psegs.
547                 for (i=first_point; i<num_points; i++)
548                         psegs[i-first_point] = psegs[i];
549         }
550
551         return num_points - first_point;
552 }
553
554 #ifndef NDEBUG
555 //      -------------------------------------------------------------------------------------------------------
556 //      Make sure that there are connections between all segments on path.
557 //      Note that if path has been optimized, connections may not be direct, so this function is useless, or worse.
558 //      Return true if valid, else return false.
559 int validate_path(int debug_flag, point_seg *psegs, int num_points)
560 {
561 #if PATH_VALIDATION
562         int             i, curseg;
563
564         curseg = psegs->segnum;
565         if ((curseg < 0) || (curseg > Highest_segment_index)) {
566                 mprintf((0, "Path beginning at index %i, length=%i is bogus!\n", psegs-Point_segs, num_points));
567                 Int3();         //      Contact Mike: Debug trap for elusive, nasty bug.
568                 return 0;
569         }
570
571 if (debug_flag == 999)
572         mprintf((0, "That's curious...\n"));
573
574 if (num_points == 0)
575         return 1;
576
577 // printf("(%i) Validating path at psegs=%i, num_points=%i, segments = %3i ", debug_flag, psegs-Point_segs, num_points, psegs[0].segnum);
578         for (i=1; i<num_points; i++) {
579                 int     sidenum;
580                 int     nextseg = psegs[i].segnum;
581
582                 if ((nextseg < 0) || (nextseg > Highest_segment_index)) {
583                         mprintf((0, "Path beginning at index %i, length=%i is bogus!\n", psegs-Point_segs, num_points));
584                         Int3();         //      Contact Mike: Debug trap for elusive, nasty bug.
585                         return 0;
586                 }
587
588 // printf("%3i ", nextseg);
589                 if (curseg != nextseg) {
590                         for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++)
591                                 if (Segments[curseg].children[sidenum] == nextseg)
592                                         break;
593
594                         // Assert(sidenum != MAX_SIDES_PER_SEGMENT);    //      Hey, created path is not contiguous, why!?
595                         if (sidenum == MAX_SIDES_PER_SEGMENT) {
596                                 mprintf((0, "Path beginning at index %i, length=%i is bogus!\n", psegs-Point_segs, num_points));
597                                 // printf("BOGUS");
598                                 Int3();
599                                 return 0;
600                         }
601                         curseg = nextseg;
602                 }
603         }
604 //printf("\n");
605 #endif
606         return 1;
607
608 }
609 #endif
610
611 #ifndef NDEBUG
612 //      -----------------------------------------------------------------------------------------------------------
613 void validate_all_paths(void)
614 {
615
616 #if PATH_VALIDATION
617         int     i;
618
619         for (i=0; i<=Highest_object_index; i++) {
620                 if (Objects[i].type == OBJ_ROBOT) {
621                         object          *objp = &Objects[i];
622                         ai_static       *aip = &objp->ctype.ai_info;
623                         //ai_local              *ailp = &Ai_local_info[i];
624
625                         if (objp->control_type == CT_AI) {
626                                 if ((aip->hide_index != -1) && (aip->path_length > 0))
627                                         if (!validate_path(4, &Point_segs[aip->hide_index], aip->path_length)) {
628                                                 Int3(); //      This path is bogus!  Who corrupted it!  Danger! Danger!
629                                                                         //      Contact Mike, he caused this mess.
630                                                 //force_dump_ai_objects_all("Error in validate_all_paths");
631                                                 aip->path_length=0;     //      This allows people to resume without harm...
632                                         }
633                         }
634                 }
635         }
636 #endif
637
638 }
639 #endif
640
641 // -- //        -------------------------------------------------------------------------------------------------------
642 // -- //        Creates a path from the objects current segment (objp->segnum) to the specified segment for the object to
643 // -- //        hide in Ai_local_info[objnum].goal_segment.
644 // -- //        Sets    objp->ctype.ai_info.hide_index,         a pointer into Point_segs, the first point_seg of the path.
645 // -- //                        objp->ctype.ai_info.path_length,                length of path
646 // -- //                        Point_segs_free_ptr                             global pointer into Point_segs array
647 // -- void create_path(object *objp)
648 // -- {
649 // --   ai_static       *aip = &objp->ctype.ai_info;
650 // --   ai_local                *ailp = &Ai_local_info[objp-Objects];
651 // --   int                     start_seg, end_seg;
652 // -- 
653 // --   start_seg = objp->segnum;
654 // --   end_seg = ailp->goal_segment;
655 // -- 
656 // --   if (end_seg == -1)
657 // --           create_n_segment_path(objp, 3, -1);
658 // -- 
659 // --   if (end_seg == -1) {
660 // --           ; //mprintf((0, "Object %i, hide_segment = -1, not creating path.\n", objp-Objects));
661 // --   } else {
662 // --           create_path_points(objp, start_seg, end_seg, Point_segs_free_ptr, &aip->path_length, -1, 0, 0, -1);
663 // --           aip->hide_index = Point_segs_free_ptr - Point_segs;
664 // --           aip->cur_path_index = 0;
665 // -- #if PATH_VALIDATION
666 // --           validate_path(5, Point_segs_free_ptr, aip->path_length);
667 // -- #endif
668 // --           Point_segs_free_ptr += aip->path_length;
669 // --           if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
670 // --                   //Int3();       //      Contact Mike: This is curious, though not deadly. /eip++;g
671 // --                   //force_dump_ai_objects_all("Error in create_path");
672 // --                   ai_reset_all_paths();
673 // --           }
674 // --           aip->PATH_DIR = 1;              //      Initialize to moving forward.
675 // --           aip->SUBMODE = AISM_HIDING;             //      Pretend we are hiding, so we sit here until bothered.
676 // --   }
677 // -- 
678 // --   maybe_ai_path_garbage_collect();
679 // -- 
680 // -- }
681
682 //      -------------------------------------------------------------------------------------------------------
683 //      Creates a path from the objects current segment (objp->segnum) to the specified segment for the object to
684 //      hide in Ai_local_info[objnum].goal_segment.
685 //      Sets    objp->ctype.ai_info.hide_index,         a pointer into Point_segs, the first point_seg of the path.
686 //                      objp->ctype.ai_info.path_length,                length of path
687 //                      Point_segs_free_ptr                             global pointer into Point_segs array
688 //      Change, 10/07/95: Used to create path to ConsoleObject->pos.  Now creates path to Believed_player_pos.
689 void create_path_to_player(object *objp, int max_length, int safety_flag)
690 {
691         ai_static       *aip = &objp->ctype.ai_info;
692         ai_local                *ailp = &Ai_local_info[objp-Objects];
693         int                     start_seg, end_seg;
694
695 //mprintf((0, "Creating path to player.\n"));
696         if (max_length == -1)
697                 max_length = MAX_DEPTH_TO_SEARCH_FOR_PLAYER;
698
699         ailp->time_player_seen = GameTime;                      //      Prevent from resetting path quickly.
700         ailp->goal_segment = Believed_player_seg;
701
702         start_seg = objp->segnum;
703         end_seg = ailp->goal_segment;
704
705         // mprintf((0, "Creating path for object #%i, from segment #%i to #%i\n", objp-Objects, start_seg, end_seg));
706
707         if (end_seg == -1) {
708                 ; //mprintf((0, "Object %i, hide_segment = -1, not creating path.\n", objp-Objects));
709         } else {
710                 create_path_points(objp, start_seg, end_seg, Point_segs_free_ptr, &aip->path_length, max_length, 1, safety_flag, -1);
711                 aip->path_length = polish_path(objp, Point_segs_free_ptr, aip->path_length);
712                 aip->hide_index = Point_segs_free_ptr - Point_segs;
713                 aip->cur_path_index = 0;
714                 Point_segs_free_ptr += aip->path_length;
715                 if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
716                         //Int3();       //      Contact Mike: This is stupid.  Should call maybe_ai_garbage_collect before the add.
717                         //force_dump_ai_objects_all("Error in create_path_to_player");
718                         ai_reset_all_paths();
719                         return;
720                 }
721 //              Assert(Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 < MAX_POINT_SEGS);
722                 aip->PATH_DIR = 1;              //      Initialize to moving forward.
723                 // -- UNUSED! aip->SUBMODE = AISM_GOHIDE;               //      This forces immediate movement.
724                 ailp->mode = AIM_FOLLOW_PATH;
725                 ailp->player_awareness_type = 0;                //      If robot too aware of player, will set mode to chase
726                 // mprintf((0, "Created %i segment path to player.\n", aip->path_length));
727         }
728
729         maybe_ai_path_garbage_collect();
730
731 }
732
733 //      -------------------------------------------------------------------------------------------------------
734 //      Creates a path from the object's current segment (objp->segnum) to segment goalseg.
735 void create_path_to_segment(object *objp, int goalseg, int max_length, int safety_flag)
736 {
737         ai_static       *aip = &objp->ctype.ai_info;
738         ai_local                *ailp = &Ai_local_info[objp-Objects];
739         int                     start_seg, end_seg;
740
741         if (max_length == -1)
742                 max_length = MAX_DEPTH_TO_SEARCH_FOR_PLAYER;
743
744         ailp->time_player_seen = GameTime;                      //      Prevent from resetting path quickly.
745         ailp->goal_segment = goalseg;
746
747         start_seg = objp->segnum;
748         end_seg = ailp->goal_segment;
749
750         if (end_seg == -1) {
751                 ;
752         } else {
753                 create_path_points(objp, start_seg, end_seg, Point_segs_free_ptr, &aip->path_length, max_length, 1, safety_flag, -1);
754                 aip->hide_index = Point_segs_free_ptr - Point_segs;
755                 aip->cur_path_index = 0;
756                 Point_segs_free_ptr += aip->path_length;
757                 if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
758                         ai_reset_all_paths();
759                         return;
760                 }
761
762                 aip->PATH_DIR = 1;              //      Initialize to moving forward.
763                 // -- UNUSED! aip->SUBMODE = AISM_GOHIDE;               //      This forces immediate movement.
764                 ailp->player_awareness_type = 0;                //      If robot too aware of player, will set mode to chase
765         }
766
767         maybe_ai_path_garbage_collect();
768
769 }
770
771 //      -------------------------------------------------------------------------------------------------------
772 //      Creates a path from the objects current segment (objp->segnum) to the specified segment for the object to
773 //      hide in Ai_local_info[objnum].goal_segment
774 //      Sets    objp->ctype.ai_info.hide_index,         a pointer into Point_segs, the first point_seg of the path.
775 //                      objp->ctype.ai_info.path_length,                length of path
776 //                      Point_segs_free_ptr                             global pointer into Point_segs array
777 void create_path_to_station(object *objp, int max_length)
778 {
779         ai_static       *aip = &objp->ctype.ai_info;
780         ai_local                *ailp = &Ai_local_info[objp-Objects];
781         int                     start_seg, end_seg;
782
783         if (max_length == -1)
784                 max_length = MAX_DEPTH_TO_SEARCH_FOR_PLAYER;
785
786         ailp->time_player_seen = GameTime;                      //      Prevent from resetting path quickly.
787
788         start_seg = objp->segnum;
789         end_seg = aip->hide_segment;
790
791         //1001: mprintf((0, "Back to station for object #%i, from segment #%i to #%i\n", objp-Objects, start_seg, end_seg));
792
793         if (end_seg == -1) {
794                 ; //mprintf((0, "Object %i, hide_segment = -1, not creating path.\n", objp-Objects));
795         } else {
796                 create_path_points(objp, start_seg, end_seg, Point_segs_free_ptr, &aip->path_length, max_length, 1, 1, -1);
797                 aip->path_length = polish_path(objp, Point_segs_free_ptr, aip->path_length);
798                 aip->hide_index = Point_segs_free_ptr - Point_segs;
799                 aip->cur_path_index = 0;
800
801                 Point_segs_free_ptr += aip->path_length;
802                 if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
803                         //Int3();       //      Contact Mike: Stupid.
804                         //force_dump_ai_objects_all("Error in create_path_to_station");
805                         ai_reset_all_paths();
806                         return;
807                 }
808 //              Assert(Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 < MAX_POINT_SEGS);
809                 aip->PATH_DIR = 1;              //      Initialize to moving forward.
810                 // aip->SUBMODE = AISM_GOHIDE;          //      This forces immediate movement.
811                 ailp->mode = AIM_FOLLOW_PATH;
812                 ailp->player_awareness_type = 0;
813         }
814
815
816         maybe_ai_path_garbage_collect();
817
818 }
819
820
821 //      -------------------------------------------------------------------------------------------------------
822 //      Create a path of length path_length for an object, stuffing info in ai_info field.
823 void create_n_segment_path(object *objp, int path_length, int avoid_seg)
824 {
825         ai_static       *aip=&objp->ctype.ai_info;
826         ai_local                *ailp = &Ai_local_info[objp-Objects];
827
828 //mprintf((0, "Creating %i segment path.\n", path_length));
829
830         if (create_path_points(objp, objp->segnum, -2, Point_segs_free_ptr, &aip->path_length, path_length, 1, 0, avoid_seg) == -1) {
831                 Point_segs_free_ptr += aip->path_length;
832                 while ((create_path_points(objp, objp->segnum, -2, Point_segs_free_ptr, &aip->path_length, --path_length, 1, 0, -1) == -1)) {
833                         //mprintf((0, "R"));
834                         Assert(path_length);
835                 }
836         }
837
838         aip->hide_index = Point_segs_free_ptr - Point_segs;
839         aip->cur_path_index = 0;
840 #if PATH_VALIDATION
841         validate_path(8, Point_segs_free_ptr, aip->path_length);
842 #endif
843         Point_segs_free_ptr += aip->path_length;
844         if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
845                 //Int3();       //      Contact Mike: This is curious, though not deadly. /eip++;g
846                 //force_dump_ai_objects_all("Error in crete_n_segment_path 2");
847                 ai_reset_all_paths();
848         }
849
850         aip->PATH_DIR = 1;              //      Initialize to moving forward.
851         // -- UNUSED! aip->SUBMODE = -1;                //      Don't know what this means.
852         ailp->mode = AIM_FOLLOW_PATH;
853
854         //      If this robot is visible (player_visibility is not available) and it's running away, move towards outside with
855         //      randomness to prevent a stream of bots from going away down the center of a corridor.
856         if (Ai_local_info[objp-Objects].previous_visibility) {
857                 if (aip->path_length) {
858                         int     t_num_points = aip->path_length;
859                         move_towards_outside(&Point_segs[aip->hide_index], &t_num_points, objp, 1);
860                         aip->path_length = t_num_points;
861                 }
862         }
863         //mprintf((0, "\n"));
864
865         maybe_ai_path_garbage_collect();
866
867 }
868
869 //      -------------------------------------------------------------------------------------------------------
870 void create_n_segment_path_to_door(object *objp, int path_length, int avoid_seg)
871 {
872         create_n_segment_path(objp, path_length, avoid_seg);
873 }
874
875 extern int Connected_segment_distance;
876
877 #define Int3_if(cond) if (!cond) Int3();
878
879 //      ----------------------------------------------------------------------------------------------------
880 void move_object_to_goal(object *objp, vms_vector *goal_point, int goal_seg)
881 {
882         ai_static       *aip = &objp->ctype.ai_info;
883         int                     segnum;
884
885         if (aip->path_length < 2)
886                 return;
887
888         Assert(objp->segnum != -1);
889
890         // mprintf((0, "[%i -> %i]\n", objp-Objects, goal_seg));
891
892 #ifndef NDEBUG
893         if (objp->segnum != goal_seg)
894                 if (find_connect_side(&Segments[objp->segnum], &Segments[goal_seg]) == -1) {
895                         fix     dist;
896                         dist = find_connected_distance(&objp->pos, objp->segnum, goal_point, goal_seg, 30, WID_FLY_FLAG);
897                         if (Connected_segment_distance > 2) {   //      This global is set in find_connected_distance
898                                 // -- Int3();
899                                 mprintf((1, "Warning: Object %i hopped across %i segments, a distance of %7.3f.\n", objp-Objects, Connected_segment_distance, f2fl(dist)));
900                         }
901                 }
902 #endif
903
904         Assert(aip->path_length >= 2);
905
906         if (aip->cur_path_index <= 0) {
907                 if (aip->behavior == AIB_STATION) {
908                         // mprintf((0, "Object #%i, creating path back to station.\n", objp-Objects));
909                         create_path_to_station(objp, 15);
910                         return;
911                 }
912                 aip->cur_path_index = 1;
913                 aip->PATH_DIR = 1;
914         } else if (aip->cur_path_index >= aip->path_length - 1) {
915                 if (aip->behavior == AIB_STATION) {
916                         // mprintf((0, "Object #%i, creating path back to station.\n", objp-Objects));
917                         create_path_to_station(objp, 15);
918                         if (aip->path_length == 0) {
919                                 ai_local                *ailp = &Ai_local_info[objp-Objects];
920                                 ailp->mode = AIM_STILL;
921                         }
922                         return;
923                 }
924                 Assert(aip->path_length != 0);
925                 aip->cur_path_index = aip->path_length-2;
926                 aip->PATH_DIR = -1;
927         } else
928                 aip->cur_path_index += aip->PATH_DIR;
929
930         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
931
932         objp->pos = *goal_point;
933         segnum = find_object_seg(objp);
934         if (segnum != goal_seg)
935                 mprintf((1, "Object #%i goal supposed to be in segment #%i, but in segment #%i\n", objp-Objects, goal_seg, segnum));
936
937         if (segnum == -1) {
938                 Int3(); //      Oops, object is not in any segment.
939                                         // Contact Mike: This is impossible.
940                 //      Hack, move object to center of segment it used to be in.
941                 compute_segment_center(&objp->pos, &Segments[objp->segnum]);
942         } else
943                 obj_relink(objp-Objects, segnum);
944 }
945
946 // -- too much work -- //       ----------------------------------------------------------------------------------------------------------
947 // -- too much work -- //       Return true if the object the companion wants to kill is reachable.
948 // -- too much work -- int attack_kill_object(object *objp)
949 // -- too much work -- {
950 // -- too much work --  object          *kill_objp;
951 // -- too much work --  fvi_info                hit_data;
952 // -- too much work --  int                     fate;
953 // -- too much work --  fvi_query       fq;
954 // -- too much work -- 
955 // -- too much work --  if (Escort_kill_object == -1)
956 // -- too much work --          return 0;
957 // -- too much work -- 
958 // -- too much work --  kill_objp = &Objects[Escort_kill_object];
959 // -- too much work -- 
960 // -- too much work --  fq.p0                                           = &objp->pos;
961 // -- too much work --  fq.startseg                             = objp->segnum;
962 // -- too much work --  fq.p1                                           = &kill_objp->pos;
963 // -- too much work --  fq.rad                                  = objp->size;
964 // -- too much work --  fq.thisobjnum                   = objp-Objects;
965 // -- too much work --  fq.ignore_obj_list      = NULL;
966 // -- too much work --  fq.flags                                        = 0;
967 // -- too much work -- 
968 // -- too much work --  fate = find_vector_intersection(&fq,&hit_data);
969 // -- too much work -- 
970 // -- too much work --  if (fate == HIT_NONE)
971 // -- too much work --          return 1;
972 // -- too much work --  else
973 // -- too much work --          return 0;
974 // -- too much work -- }
975
976 //      ----------------------------------------------------------------------------------------------------------
977 //      Optimization: If current velocity will take robot near goal, don't change velocity
978 void ai_follow_path(object *objp, int player_visibility, int previous_visibility, vms_vector *vec_to_player)
979 {
980         ai_static               *aip = &objp->ctype.ai_info;
981
982         vms_vector      goal_point, new_goal_point;
983         fix                     dist_to_goal;
984         robot_info      *robptr = &Robot_info[objp->id];
985         int                     forced_break, original_dir, original_index;
986         fix                     dist_to_player;
987         int                     goal_seg;
988         ai_local                *ailp = &Ai_local_info[objp-Objects];
989         fix                     threshold_distance;
990
991
992 // mprintf((0, "Obj %i, dist=%6.1f index=%i len=%i seg=%i pos = %6.1f %6.1f %6.1f.\n", objp-Objects, f2fl(vm_vec_dist_quick(&objp->pos, &ConsoleObject->pos)), aip->cur_path_index, aip->path_length, objp->segnum, f2fl(objp->pos.x), f2fl(objp->pos.y), f2
993
994         if ((aip->hide_index == -1) || (aip->path_length == 0))
995         {
996                 if (ailp->mode == AIM_RUN_FROM_OBJECT) {
997                         create_n_segment_path(objp, 5, -1);
998                         //--Int3_if((aip->path_length != 0));
999                         ailp->mode = AIM_RUN_FROM_OBJECT;
1000                 } else {
1001                         // -- mprintf((0, "Object %i creating path for no apparent reason.\n", objp-Objects));
1002                         create_n_segment_path(objp, 5, -1);
1003                         //--Int3_if((aip->path_length != 0));
1004                 }
1005         }
1006
1007         if ((aip->hide_index + aip->path_length > Point_segs_free_ptr - Point_segs) && (aip->path_length>0)) {
1008                 Int3(); //      Contact Mike: Bad.  Path goes into what is believed to be free space.
1009                 //      This is debugging code.  Figure out why garbage collection
1010                 //      didn't compress this object's path information.
1011                 ai_path_garbage_collect();
1012                 //force_dump_ai_objects_all("Error in ai_follow_path");
1013                 ai_reset_all_paths();
1014         }
1015
1016         if (aip->path_length < 2) {
1017                 if ((aip->behavior == AIB_SNIPE) || (ailp->mode == AIM_RUN_FROM_OBJECT)) {
1018                         if (ConsoleObject->segnum == objp->segnum) {
1019                                 create_n_segment_path(objp, AVOID_SEG_LENGTH, -1);                      //      Can't avoid segment player is in, robot is already in it! (That's what the -1 is for) 
1020                                 //--Int3_if((aip->path_length != 0));
1021                         } else {
1022                                 create_n_segment_path(objp, AVOID_SEG_LENGTH, ConsoleObject->segnum);
1023                                 //--Int3_if((aip->path_length != 0));
1024                         }
1025                         if (aip->behavior == AIB_SNIPE) {
1026                                 if (robptr->thief)
1027                                         ailp->mode = AIM_THIEF_ATTACK;  //      It gets bashed in create_n_segment_path
1028                                 else
1029                                         ailp->mode = AIM_SNIPE_FIRE;    //      It gets bashed in create_n_segment_path
1030                         } else {
1031                                 ailp->mode = AIM_RUN_FROM_OBJECT;       //      It gets bashed in create_n_segment_path
1032                         }
1033                 } else if (robptr->companion == 0) {
1034                         ailp->mode = AIM_STILL;
1035                         aip->path_length = 0;
1036                         return;
1037                 }
1038         }
1039
1040         //--Int3_if(((aip->PATH_DIR == -1) || (aip->PATH_DIR == 1)));
1041         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1042
1043         goal_point = Point_segs[aip->hide_index + aip->cur_path_index].point;
1044         goal_seg = Point_segs[aip->hide_index + aip->cur_path_index].segnum;
1045         dist_to_goal = vm_vec_dist_quick(&goal_point, &objp->pos);
1046
1047         if (Player_is_dead)
1048                 dist_to_player = vm_vec_dist_quick(&objp->pos, &Viewer->pos);
1049         else
1050                 dist_to_player = vm_vec_dist_quick(&objp->pos, &ConsoleObject->pos);
1051
1052         //      Efficiency hack: If far away from player, move in big quantized jumps.
1053         if (!(player_visibility || previous_visibility) && (dist_to_player > F1_0*200) && !(Game_mode & GM_MULTI)) {
1054                 if (dist_to_goal < F1_0*2) {
1055                         move_object_to_goal(objp, &goal_point, goal_seg);
1056                         return;
1057                 } else {
1058                         robot_info      *robptr = &Robot_info[objp->id];
1059                         fix     cur_speed = robptr->max_speed[Difficulty_level]/2;
1060                         fix     distance_travellable = fixmul(FrameTime, cur_speed);
1061
1062                         // int  connect_side = find_connect_side(objp->segnum, goal_seg);
1063                         //      Only move to goal if allowed to fly through the side.
1064                         //      Buddy-bot can create paths he can't fly, waiting for player.
1065                         // -- bah, this isn't good enough, buddy will fail to get through any door! if (WALL_IS_DOORWAY(&Segments]objp->segnum], connect_side) & WID_FLY_FLAG) {
1066                         if (!Robot_info[objp->id].companion && !Robot_info[objp->id].thief) {
1067                                 if (distance_travellable >= dist_to_goal) {
1068                                         move_object_to_goal(objp, &goal_point, goal_seg);
1069                                 } else {
1070                                         fix     prob = fixdiv(distance_travellable, dist_to_goal);
1071         
1072                                         int     rand_num = d_rand();
1073                                         if ( (rand_num >> 1) < prob) {
1074                                                 move_object_to_goal(objp, &goal_point, goal_seg);
1075                                         }
1076                                 }
1077                                 return;
1078                         }
1079                 }
1080
1081         }
1082
1083         //      If running from player, only run until can't be seen.
1084         if (ailp->mode == AIM_RUN_FROM_OBJECT) {
1085                 if ((player_visibility == 0) && (ailp->player_awareness_type == 0)) {
1086                         fix     vel_scale;
1087
1088                         vel_scale = F1_0 - FrameTime/2;
1089                         if (vel_scale < F1_0/2)
1090                                 vel_scale = F1_0/2;
1091
1092                         vm_vec_scale(&objp->mtype.phys_info.velocity, vel_scale);
1093
1094                         return;
1095                 } else if (!(FrameCount ^ ((objp-Objects) & 0x07))) {           //      Done 1/8 frames.
1096                         //      If player on path (beyond point robot is now at), then create a new path.
1097                         point_seg       *curpsp = &Point_segs[aip->hide_index];
1098                         int                     player_segnum = ConsoleObject->segnum;
1099                         int                     i;
1100
1101                         //      This is probably being done every frame, which is wasteful.
1102                         for (i=aip->cur_path_index; i<aip->path_length; i++) {
1103                                 if (curpsp[i].segnum == player_segnum) {
1104                                         if (player_segnum != objp->segnum) {
1105                                                 create_n_segment_path(objp, AVOID_SEG_LENGTH, player_segnum);
1106                                         } else {
1107                                                 create_n_segment_path(objp, AVOID_SEG_LENGTH, -1);
1108                                         }
1109                                         Assert(aip->path_length != 0);
1110                                         ailp->mode = AIM_RUN_FROM_OBJECT;       //      It gets bashed in create_n_segment_path
1111                                         break;
1112                                 }
1113                         }
1114                         if (player_visibility) {
1115                                 ailp->player_awareness_type = 1;
1116                                 ailp->player_awareness_time = F1_0;
1117                         }
1118                 }
1119         }
1120
1121         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1122
1123         if (aip->cur_path_index < 0) {
1124                 aip->cur_path_index = 0;
1125         } else if (aip->cur_path_index >= aip->path_length) {
1126                 if (ailp->mode == AIM_RUN_FROM_OBJECT) {
1127                         create_n_segment_path(objp, AVOID_SEG_LENGTH, ConsoleObject->segnum);
1128                         ailp->mode = AIM_RUN_FROM_OBJECT;       //      It gets bashed in create_n_segment_path
1129                         Assert(aip->path_length != 0);
1130                 } else {
1131                         aip->cur_path_index = aip->path_length-1;
1132                 }
1133         }
1134
1135         goal_point = Point_segs[aip->hide_index + aip->cur_path_index].point;
1136
1137         //      If near goal, pick another goal point.
1138         forced_break = 0;               //      Gets set for short paths.
1139         original_dir = aip->PATH_DIR;
1140         original_index = aip->cur_path_index;
1141         threshold_distance = fixmul(vm_vec_mag_quick(&objp->mtype.phys_info.velocity), FrameTime)*2 + F1_0*2;
1142
1143         new_goal_point = Point_segs[aip->hide_index + aip->cur_path_index].point;
1144
1145         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1146
1147         while ((dist_to_goal < threshold_distance) && !forced_break) {
1148
1149                 //      Advance to next point on path.
1150                 aip->cur_path_index += aip->PATH_DIR;
1151
1152                 //      See if next point wraps past end of path (in either direction), and if so, deal with it based on mode.
1153                 if ((aip->cur_path_index >= aip->path_length) || (aip->cur_path_index < 0)) {
1154
1155                         //mprintf((0, "Object %i reached end of the line!\n", objp-Objects));
1156                         //      If mode = hiding, then stay here until get bonked or hit by player.
1157                         // --   if (ailp->mode == AIM_BEHIND) {
1158                         // --           ailp->mode = AIM_STILL;
1159                         // --           return;         // Stay here until bonked or hit by player.
1160                         // --   } else
1161
1162                         //      Buddy bot.  If he's in mode to get away from player and at end of line,
1163                         //      if player visible, then make a new path, else just return.
1164                         if (robptr->companion) {
1165                                 if (Escort_special_goal == ESCORT_GOAL_SCRAM)
1166                                 {
1167                                         if (player_visibility) {
1168                                                 create_n_segment_path(objp, 16 + d_rand() * 16, -1);
1169                                                 aip->path_length = polish_path(objp, &Point_segs[aip->hide_index], aip->path_length);
1170                                                 Assert(aip->path_length != 0);
1171                                                 // -- mprintf((0, "Buddy: Creating new path!\n"));
1172                                                 ailp->mode = AIM_WANDER;        //      Special buddy mode.
1173                                                 //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1174                                                 return;
1175                                         } else {
1176                                                 ailp->mode = AIM_WANDER;        //      Special buddy mode.
1177                                                 vm_vec_zero(&objp->mtype.phys_info.velocity);
1178                                                 vm_vec_zero(&objp->mtype.phys_info.rotvel);
1179                                                 // -- mprintf((0, "Buddy: I'm hidden!\n"));
1180                                                 //!!Assert((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length));
1181                                                 return;
1182                                         }
1183                                 }
1184                         }
1185
1186                         if (aip->behavior == AIB_FOLLOW) {
1187                                 // mprintf((0, "AIB_FOLLOW: Making new path.\n"));
1188                                 create_n_segment_path(objp, 10, ConsoleObject->segnum);
1189                                 //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1190                         } else if (aip->behavior == AIB_STATION) {
1191                                 // mprintf((0, "Object %i reached end of line, creating path back to station.\n", objp-Objects));
1192                                 create_path_to_station(objp, 15);
1193                                 if ((aip->hide_segment != Point_segs[aip->hide_index+aip->path_length-1].segnum) || (aip->path_length == 0)) {
1194                                         ailp->mode = AIM_STILL;
1195                                 } else {
1196                                         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1197                                 }
1198                                 return;
1199                         } else if (ailp->mode == AIM_FOLLOW_PATH) {
1200                                 create_path_to_player(objp, 10, 1);
1201                                 if (aip->hide_segment != Point_segs[aip->hide_index+aip->path_length-1].segnum) {
1202                                         ailp->mode = AIM_STILL;
1203                                         return;
1204                                 } else {
1205                                         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1206                                 }
1207                         } else if (ailp->mode == AIM_RUN_FROM_OBJECT) {
1208                                 create_n_segment_path(objp, AVOID_SEG_LENGTH, ConsoleObject->segnum);
1209                                 ailp->mode = AIM_RUN_FROM_OBJECT;       //      It gets bashed in create_n_segment_path
1210                                 if (aip->path_length < 1) {
1211                                         create_n_segment_path(objp, AVOID_SEG_LENGTH, ConsoleObject->segnum);
1212                                         ailp->mode = AIM_RUN_FROM_OBJECT;       //      It gets bashed in create_n_segment_path
1213                                         if (aip->path_length < 1) {
1214                                                 aip->behavior = AIB_NORMAL;
1215                                                 ailp->mode = AIM_STILL;
1216                                                 return;
1217                                         }
1218                                 }
1219                                 //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1220                         } else {
1221                                 //      Reached end of the line.  First see if opposite end point is reachable, and if so, go there.
1222                                 //      If not, turn around.
1223                                 int                     opposite_end_index;
1224                                 vms_vector      *opposite_end_point;
1225                                 fvi_info                hit_data;
1226                                 int                     fate;
1227                                 fvi_query       fq;
1228
1229                                 // See which end we're nearer and look at the opposite end point.
1230                                 if (abs(aip->cur_path_index - aip->path_length) < aip->cur_path_index) {
1231                                         //      Nearer to far end (ie, index not 0), so try to reach 0.
1232                                         opposite_end_index = 0;
1233                                 } else {
1234                                         //      Nearer to 0 end, so try to reach far end.
1235                                         opposite_end_index = aip->path_length-1;
1236                                 }
1237
1238                                 //--Int3_if(((opposite_end_index >= 0) && (opposite_end_index < aip->path_length)));
1239
1240                                 opposite_end_point = &Point_segs[aip->hide_index + opposite_end_index].point;
1241
1242                                 fq.p0                                           = &objp->pos;
1243                                 fq.startseg                             = objp->segnum;
1244                                 fq.p1                                           = opposite_end_point;
1245                                 fq.rad                                  = objp->size;
1246                                 fq.thisobjnum                   = objp-Objects;
1247                                 fq.ignore_obj_list      = NULL;
1248                                 fq.flags                                        = 0;                            //what about trans walls???
1249
1250                                 fate = find_vector_intersection(&fq,&hit_data);
1251
1252                                 if (fate != HIT_WALL) {
1253                                         //      We can be circular!  Do it!
1254                                         //      Path direction is unchanged.
1255                                         aip->cur_path_index = opposite_end_index;
1256                                 } else {
1257                                         aip->PATH_DIR = -aip->PATH_DIR;
1258                                         aip->cur_path_index += aip->PATH_DIR;
1259                                 }
1260                                 //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1261                         }
1262                         break;
1263                 } else {
1264                         new_goal_point = Point_segs[aip->hide_index + aip->cur_path_index].point;
1265                         goal_point = new_goal_point;
1266                         dist_to_goal = vm_vec_dist_quick(&goal_point, &objp->pos);
1267                         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1268                 }
1269
1270                 //      If went all the way around to original point, in same direction, then get out of here!
1271                 if ((aip->cur_path_index == original_index) && (aip->PATH_DIR == original_dir)) {
1272                         create_path_to_player(objp, 3, 1);
1273                         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1274                         forced_break = 1;
1275                 }
1276                 //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1277         }       //      end while
1278
1279         //      Set velocity (objp->mtype.phys_info.velocity) and orientation (objp->orient) for this object.
1280         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1281         ai_path_set_orient_and_vel(objp, &goal_point, player_visibility, vec_to_player);
1282         //--Int3_if(((aip->cur_path_index >= 0) && (aip->cur_path_index < aip->path_length)));
1283
1284 }
1285
1286 typedef struct {
1287         short   path_start, objnum;
1288 } obj_path;
1289
1290 int path_index_compare(obj_path *i1, obj_path *i2)
1291 {
1292         if (i1->path_start < i2->path_start)
1293                 return -1;
1294         else if (i1->path_start == i2->path_start)
1295                 return 0;
1296         else
1297                 return 1;
1298 }
1299
1300 //      ----------------------------------------------------------------------------------------------------------
1301 //      Set orientation matrix and velocity for objp based on its desire to get to a point.
1302 void ai_path_set_orient_and_vel(object *objp, vms_vector *goal_point, int player_visibility, vms_vector *vec_to_player)
1303 {
1304         vms_vector      cur_vel = objp->mtype.phys_info.velocity;
1305         vms_vector      norm_cur_vel;
1306         vms_vector      norm_vec_to_goal;
1307         vms_vector      cur_pos = objp->pos;
1308         vms_vector      norm_fvec;
1309         fix                     speed_scale;
1310         fix                     dot;
1311         robot_info      *robptr = &Robot_info[objp->id];
1312         fix                     max_speed;
1313
1314         //      If evading player, use highest difficulty level speed, plus something based on diff level
1315         max_speed = robptr->max_speed[Difficulty_level];
1316         if ((Ai_local_info[objp-Objects].mode == AIM_RUN_FROM_OBJECT) || (objp->ctype.ai_info.behavior == AIB_SNIPE))
1317                 max_speed = max_speed*3/2;
1318
1319         vm_vec_sub(&norm_vec_to_goal, goal_point, &cur_pos);
1320         vm_vec_normalize_quick(&norm_vec_to_goal);
1321
1322         norm_cur_vel = cur_vel;
1323         vm_vec_normalize_quick(&norm_cur_vel);
1324
1325         norm_fvec = objp->orient.fvec;
1326         vm_vec_normalize_quick(&norm_fvec);
1327
1328         dot = vm_vec_dot(&norm_vec_to_goal, &norm_fvec);
1329
1330         //      If very close to facing opposite desired vector, perturb vector
1331         if (dot < -15*F1_0/16) {
1332                 //mprintf((0, "Facing away from goal, abruptly turning\n"));
1333                 norm_cur_vel = norm_vec_to_goal;
1334         } else {
1335                 norm_cur_vel.x += norm_vec_to_goal.x/2;
1336                 norm_cur_vel.y += norm_vec_to_goal.y/2;
1337                 norm_cur_vel.z += norm_vec_to_goal.z/2;
1338         }
1339
1340         vm_vec_normalize_quick(&norm_cur_vel);
1341
1342         //      Set speed based on this robot type's maximum allowed speed and how hard it is turning.
1343         //      How hard it is turning is based on the dot product of (vector to goal) and (current velocity vector)
1344         //      Note that since 3*F1_0/4 is added to dot product, it is possible for the robot to back up.
1345
1346         //      Set speed and orientation.
1347         if (dot < 0)
1348                 dot /= -4;
1349
1350         //      If in snipe mode, can move fast even if not facing that direction.
1351         if (objp->ctype.ai_info.behavior == AIB_SNIPE)
1352                 if (dot < F1_0/2)
1353                         dot = (dot + F1_0)/2;
1354
1355         speed_scale = fixmul(max_speed, dot);
1356         vm_vec_scale(&norm_cur_vel, speed_scale);
1357         objp->mtype.phys_info.velocity = norm_cur_vel;
1358
1359         if ((Ai_local_info[objp-Objects].mode == AIM_RUN_FROM_OBJECT) || (robptr->companion == 1) || (objp->ctype.ai_info.behavior == AIB_SNIPE)) {
1360                 if (Ai_local_info[objp-Objects].mode == AIM_SNIPE_RETREAT_BACKWARDS) {
1361                         if ((player_visibility) && (vec_to_player != NULL))
1362                                 norm_vec_to_goal = *vec_to_player;
1363                         else
1364                                 vm_vec_negate(&norm_vec_to_goal);
1365                 }
1366                 ai_turn_towards_vector(&norm_vec_to_goal, objp, robptr->turn_time[NDL-1]/2);
1367         } else
1368                 ai_turn_towards_vector(&norm_vec_to_goal, objp, robptr->turn_time[Difficulty_level]);
1369
1370 }
1371
1372 int     Last_frame_garbage_collected = 0;
1373
1374 //      ----------------------------------------------------------------------------------------------------------
1375 //      Garbage colledion -- Free all unused records in Point_segs and compress all paths.
1376 void ai_path_garbage_collect(void)
1377 {
1378         int     free_path_index = 0;
1379         int     num_path_objects = 0;
1380         int     objnum;
1381         int     objind;
1382         obj_path                object_list[MAX_OBJECTS];
1383
1384 #ifndef NDEBUG
1385         force_dump_ai_objects_all("***** Start ai_path_garbage_collect *****");
1386 #endif
1387
1388         // -- mprintf((0, "Garbage collection frame %i, last frame %i!  Old free index = %i ", FrameCount, Last_frame_garbage_collected, Point_segs_free_ptr - Point_segs));
1389
1390         Last_frame_garbage_collected = FrameCount;
1391
1392 #if PATH_VALIDATION
1393         validate_all_paths();
1394 #endif
1395         //      Create a list of objects which have paths of length 1 or more.
1396         for (objnum=0; objnum <= Highest_object_index; objnum++) {
1397                 object  *objp = &Objects[objnum];
1398
1399                 if ((objp->type == OBJ_ROBOT) && ((objp->control_type == CT_AI) || (objp->control_type == CT_MORPH))) {
1400                         ai_static       *aip = &objp->ctype.ai_info;
1401
1402                         if (aip->path_length) {
1403                                 object_list[num_path_objects].path_start = aip->hide_index;
1404                                 object_list[num_path_objects++].objnum = objnum;
1405                         }
1406                 }
1407         }
1408
1409         qsort(object_list, num_path_objects, sizeof(object_list[0]), 
1410                         (int (*)(void const *,void const *))path_index_compare);
1411
1412         for (objind=0; objind < num_path_objects; objind++) {
1413                 object          *objp;
1414                 ai_static       *aip;
1415                 int                     i;
1416                 int                     old_index;
1417
1418                 objnum = object_list[objind].objnum;
1419                 objp = &Objects[objnum];
1420                 aip = &objp->ctype.ai_info;
1421                 old_index = aip->hide_index;
1422
1423                 aip->hide_index = free_path_index;
1424                 for (i=0; i<aip->path_length; i++)
1425                         Point_segs[free_path_index++] = Point_segs[old_index++];
1426         }
1427
1428         Point_segs_free_ptr = &Point_segs[free_path_index];
1429
1430         // mprintf((0, "new = %i\n", free_path_index));
1431 //printf("After garbage collection, free index = %i\n", Point_segs_free_ptr - Point_segs);
1432 #ifndef NDEBUG
1433         {
1434         int i;
1435
1436         force_dump_ai_objects_all("***** Finish ai_path_garbage_collect *****");
1437
1438         for (i=0; i<=Highest_object_index; i++) {
1439                 ai_static       *aip = &Objects[i].ctype.ai_info;
1440
1441                 if ((Objects[i].type == OBJ_ROBOT) && (Objects[i].control_type == CT_AI))
1442                         if ((aip->hide_index + aip->path_length > Point_segs_free_ptr - Point_segs) && (aip->path_length>0))
1443                                 Int3();         //      Contact Mike: Debug trap for nasty, elusive bug.
1444         }
1445
1446         validate_all_paths();
1447         }
1448 #endif
1449
1450 }
1451
1452 //      -----------------------------------------------------------------------------
1453 //      Do garbage collection if not been done for awhile, or things getting really critical.
1454 void maybe_ai_path_garbage_collect(void)
1455 {
1456         if (Point_segs_free_ptr - Point_segs > MAX_POINT_SEGS - MAX_PATH_LENGTH) {
1457                 if (Last_frame_garbage_collected+1 >= FrameCount) {
1458                         //      This is kind of bad.  Garbage collected last frame or this frame.
1459                         //      Just destroy all paths.  Too bad for the robots.  They are memory wasteful.
1460                         ai_reset_all_paths();
1461                         mprintf((1, "Warning: Resetting all paths.  Point_segs buffer nearly exhausted.\n"));
1462                 } else {
1463                         //      We are really close to full, but didn't just garbage collect, so maybe this is recoverable.
1464                         mprintf((1, "Warning: Almost full garbage collection being performed: "));
1465                         ai_path_garbage_collect();
1466                         mprintf((1, "Free records = %i/%i\n", MAX_POINT_SEGS - (Point_segs_free_ptr - Point_segs), MAX_POINT_SEGS));
1467                 }
1468         } else if (Point_segs_free_ptr - Point_segs > 3*MAX_POINT_SEGS/4) {
1469                 if (Last_frame_garbage_collected + 16 < FrameCount) {
1470                         ai_path_garbage_collect();
1471                 }
1472         } else if (Point_segs_free_ptr - Point_segs > MAX_POINT_SEGS/2) {
1473                 if (Last_frame_garbage_collected + 256 < FrameCount) {
1474                         ai_path_garbage_collect();
1475                 }
1476         }
1477 }
1478
1479 //      -----------------------------------------------------------------------------
1480 //      Reset all paths.  Do garbage collection.
1481 //      Should be called at the start of each level.
1482 void ai_reset_all_paths(void)
1483 {
1484         int     i;
1485
1486         for (i=0; i<=Highest_object_index; i++)
1487                 if (Objects[i].control_type == CT_AI) {
1488                         Objects[i].ctype.ai_info.hide_index = -1;
1489                         Objects[i].ctype.ai_info.path_length = 0;
1490                 }
1491
1492         ai_path_garbage_collect();
1493
1494 }
1495
1496 //      ---------------------------------------------------------------------------------------------------------
1497 //      Probably called because a robot bashed a wall, getting a bunch of retries.
1498 //      Try to resume path.
1499 void attempt_to_resume_path(object *objp)
1500 {
1501         //int                           objnum = objp-Objects;
1502         ai_static               *aip = &objp->ctype.ai_info;
1503 //      int                             goal_segnum, object_segnum,
1504         int                             abs_index, new_path_index;
1505
1506         // mprintf((0, "Object %i trying to resume path at index %i\n", objp-Objects, aip->cur_path_index));
1507
1508         if ((aip->behavior == AIB_STATION) && (Robot_info[objp->id].companion != 1))
1509                 if (d_rand() > 8192) {
1510                         ai_local                        *ailp = &Ai_local_info[objp-Objects];
1511
1512                         aip->hide_segment = objp->segnum;
1513 //Int3();
1514                         ailp->mode = AIM_STILL;
1515                         mprintf((1, "Note: Bashing hide segment of robot %i to current segment because he's lost.\n", objp-Objects));
1516                 }
1517
1518 //      object_segnum = objp->segnum;
1519         abs_index = aip->hide_index+aip->cur_path_index;
1520 //      goal_segnum = Point_segs[abs_index].segnum;
1521
1522 //      if (object_segnum == goal_segnum)
1523 //              mprintf((0, "Very peculiar, goal segnum = object's segnum = %i.\n", goal_segnum));
1524
1525         new_path_index = aip->cur_path_index - aip->PATH_DIR;
1526
1527         if ((new_path_index >= 0) && (new_path_index < aip->path_length)) {
1528                 // mprintf((0, "Trying path index of %i\n", new_path_index));
1529                 aip->cur_path_index = new_path_index;
1530         } else {
1531                 //      At end of line and have nowhere to go.
1532                 // mprintf((0, "At end of line and can't get to goal.  Creating new path.  Frame %i\n", FrameCount));
1533                 move_towards_segment_center(objp);
1534                 create_path_to_station(objp, 15);
1535         }
1536
1537 }
1538
1539 //      ----------------------------------------------------------------------------------------------------------
1540 //                                      DEBUG FUNCTIONS FOLLOW
1541 //      ----------------------------------------------------------------------------------------------------------
1542
1543 #ifdef EDITOR
1544 int     Test_size = 1000;
1545
1546 void test_create_path_many(void)
1547 {
1548         point_seg       point_segs[200];
1549         short                   num_points;
1550
1551         int                     i;
1552
1553         for (i=0; i<Test_size; i++) {
1554                 Cursegp = &Segments[(d_rand() * (Highest_segment_index + 1)) / RAND_MAX];
1555                 Markedsegp = &Segments[(d_rand() * (Highest_segment_index + 1)) / RAND_MAX];
1556                 create_path_points(&Objects[0], Cursegp-Segments, Markedsegp-Segments, point_segs, &num_points, -1, 0, 0, -1);
1557         }
1558
1559 }
1560
1561 void test_create_path(void)
1562 {
1563         point_seg       point_segs[200];
1564         short                   num_points;
1565
1566         create_path_points(&Objects[0], Cursegp-Segments, Markedsegp-Segments, point_segs, &num_points, -1, 0, 0, -1);
1567
1568 }
1569
1570 void show_path(int start_seg, int end_seg, point_seg *psp, short length)
1571 {
1572         printf("[%3i:%3i (%3i):] ", start_seg, end_seg, length);
1573
1574         while (length--)
1575                 printf("%3i ", psp[length].segnum);
1576
1577         printf("\n");
1578 }
1579
1580 //      For all segments in mine, create paths to all segments in mine, print results.
1581 void test_create_all_paths(void)
1582 {
1583         int     start_seg, end_seg;
1584         short   resultant_length;
1585
1586         Point_segs_free_ptr = Point_segs;
1587
1588         for (start_seg=0; start_seg<=Highest_segment_index-1; start_seg++) {
1589                 // -- mprintf((0, "."));
1590                 if (Segments[start_seg].segnum != -1) {
1591                         for (end_seg=start_seg+1; end_seg<=Highest_segment_index; end_seg++) {
1592                                 if (Segments[end_seg].segnum != -1) {
1593                                         create_path_points(&Objects[0], start_seg, end_seg, Point_segs_free_ptr, &resultant_length, -1, 0, 0, -1);
1594                                         show_path(start_seg, end_seg, Point_segs_free_ptr, resultant_length);
1595                                 }
1596                         }
1597                 }
1598         }
1599 }
1600
1601 //--anchor--int Num_anchors;
1602 //--anchor--int Anchor_distance = 3;
1603 //--anchor--int End_distance = 1;
1604 //--anchor--int Anchors[MAX_SEGMENTS];
1605
1606 //--anchor--int get_nearest_anchor_distance(int segnum)
1607 //--anchor--{
1608 //--anchor--    short   resultant_length, minimum_length;
1609 //--anchor--    int     anchor_index;
1610 //--anchor--
1611 //--anchor--    minimum_length = 16383;
1612 //--anchor--
1613 //--anchor--    for (anchor_index=0; anchor_index<Num_anchors; anchor_index++) {
1614 //--anchor--            create_path_points(&Objects[0], segnum, Anchors[anchor_index], Point_segs_free_ptr, &resultant_length, -1, 0, 0, -1);
1615 //--anchor--            if (resultant_length != 0)
1616 //--anchor--                    if (resultant_length < minimum_length)
1617 //--anchor--                            minimum_length = resultant_length;
1618 //--anchor--    }
1619 //--anchor--
1620 //--anchor--    return minimum_length;
1621 //--anchor--
1622 //--anchor--}
1623 //--anchor--
1624 //--anchor--void create_new_anchor(int segnum)
1625 //--anchor--{
1626 //--anchor--    Anchors[Num_anchors++] = segnum;
1627 //--anchor--}
1628 //--anchor--
1629 //--anchor--//  A set of anchors is within N units of all segments in the graph.
1630 //--anchor--//  Anchor_distance = how close anchors can be.
1631 //--anchor--//  End_distance = how close you can be to the end.
1632 //--anchor--void test_create_all_anchors(void)
1633 //--anchor--{
1634 //--anchor--    int     nearest_anchor_distance;
1635 //--anchor--    int     segnum,i;
1636 //--anchor--
1637 //--anchor--    Num_anchors = 0;
1638 //--anchor--
1639 //--anchor--    for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1640 //--anchor--            if (Segments[segnum].segnum != -1) {
1641 //--anchor--                    nearest_anchor_distance = get_nearest_anchor_distance(segnum);
1642 //--anchor--                    if (nearest_anchor_distance > Anchor_distance)
1643 //--anchor--                            create_new_anchor(segnum);
1644 //--anchor--            }
1645 //--anchor--    }
1646 //--anchor--
1647 //--anchor--    //      Set selected segs.
1648 //--anchor--    for (i=0; i<Num_anchors; i++)
1649 //--anchor--            Selected_segs[i] = Anchors[i];
1650 //--anchor--    N_selected_segs = Num_anchors;
1651 //--anchor--
1652 //--anchor--}
1653 //--anchor--
1654 //--anchor--int Test_path_length = 5;
1655 //--anchor--
1656 //--anchor--void test_create_n_segment_path(void)
1657 //--anchor--{
1658 //--anchor--    point_seg       point_segs[200];
1659 //--anchor--    short                   num_points;
1660 //--anchor--
1661 //--anchor--    create_path_points(&Objects[0], Cursegp-Segments, -2, point_segs, &num_points, Test_path_length, 0, 0, -1);
1662 //--anchor--}
1663
1664 short   Player_path_length=0;
1665 int     Player_hide_index=-1;
1666 int     Player_cur_path_index=0;
1667 int     Player_following_path_flag=0;
1668
1669 //      ------------------------------------------------------------------------------------------------------------------
1670 //      Set orientation matrix and velocity for objp based on its desire to get to a point.
1671 void player_path_set_orient_and_vel(object *objp, vms_vector *goal_point)
1672 {
1673         vms_vector      cur_vel = objp->mtype.phys_info.velocity;
1674         vms_vector      norm_cur_vel;
1675         vms_vector      norm_vec_to_goal;
1676         vms_vector      cur_pos = objp->pos;
1677         vms_vector      norm_fvec;
1678         fix                     speed_scale;
1679         fix                     dot;
1680         fix                     max_speed;
1681
1682         max_speed = Robot_info[objp->id].max_speed[Difficulty_level];
1683
1684         vm_vec_sub(&norm_vec_to_goal, goal_point, &cur_pos);
1685         vm_vec_normalize_quick(&norm_vec_to_goal);
1686
1687         norm_cur_vel = cur_vel;
1688         vm_vec_normalize_quick(&norm_cur_vel);
1689
1690         norm_fvec = objp->orient.fvec;
1691         vm_vec_normalize_quick(&norm_fvec);
1692
1693         dot = vm_vec_dot(&norm_vec_to_goal, &norm_fvec);
1694         if (Ai_local_info[objp-Objects].mode == AIM_SNIPE_RETREAT_BACKWARDS) {
1695                 dot = -dot;
1696         }
1697
1698         //      If very close to facing opposite desired vector, perturb vector
1699         if (dot < -15*F1_0/16) {
1700                 //mprintf((0, "Facing away from goal, abruptly turning\n"));
1701                 norm_cur_vel = norm_vec_to_goal;
1702         } else {
1703                 norm_cur_vel.x += norm_vec_to_goal.x/2;
1704                 norm_cur_vel.y += norm_vec_to_goal.y/2;
1705                 norm_cur_vel.z += norm_vec_to_goal.z/2;
1706         }
1707
1708         vm_vec_normalize_quick(&norm_cur_vel);
1709
1710         //      Set speed based on this robot type's maximum allowed speed and how hard it is turning.
1711         //      How hard it is turning is based on the dot product of (vector to goal) and (current velocity vector)
1712         //      Note that since 3*F1_0/4 is added to dot product, it is possible for the robot to back up.
1713
1714         //      Set speed and orientation.
1715         if (dot < 0)
1716                 dot /= 4;
1717
1718         speed_scale = fixmul(max_speed, dot);
1719         vm_vec_scale(&norm_cur_vel, speed_scale);
1720         objp->mtype.phys_info.velocity = norm_cur_vel;
1721         ai_turn_towards_vector(&norm_vec_to_goal, objp, F1_0);
1722
1723 }
1724
1725 //      ----------------------------------------------------------------------------------------------------------
1726 //      Optimization: If current velocity will take robot near goal, don't change velocity
1727 void player_follow_path(object *objp)
1728 {
1729         vms_vector      goal_point;
1730         fix                     dist_to_goal;
1731         int                     count, forced_break, original_index;
1732         int                     goal_seg;
1733         fix                     threshold_distance;
1734
1735         if (!Player_following_path_flag)
1736                 return;
1737
1738         if (Player_hide_index == -1)
1739                 return;
1740
1741         if (Player_path_length < 2)
1742                 return;
1743
1744         goal_point = Point_segs[Player_hide_index + Player_cur_path_index].point;
1745         goal_seg = Point_segs[Player_hide_index + Player_cur_path_index].segnum;
1746         Assert((goal_seg >= 0) && (goal_seg <= Highest_segment_index));
1747         dist_to_goal = vm_vec_dist_quick(&goal_point, &objp->pos);
1748
1749         if (Player_cur_path_index < 0)
1750                 Player_cur_path_index = 0;
1751         else if (Player_cur_path_index >= Player_path_length)
1752                 Player_cur_path_index = Player_path_length-1;
1753
1754         goal_point = Point_segs[Player_hide_index + Player_cur_path_index].point;
1755
1756         count=0;
1757
1758         //      If near goal, pick another goal point.
1759         forced_break = 0;               //      Gets set for short paths.
1760         //original_dir = 1;
1761         original_index = Player_cur_path_index;
1762         threshold_distance = fixmul(vm_vec_mag_quick(&objp->mtype.phys_info.velocity), FrameTime)*2 + F1_0*2;
1763
1764         while ((dist_to_goal < threshold_distance) && !forced_break) {
1765
1766 // --           if (count > 1)
1767 // --                   mprintf((0, "."));
1768
1769                 //      ----- Debug stuff -----
1770                 if (count++ > 20) {
1771                         mprintf((1,"Problem following path for player.  Aborting.\n"));
1772                         break;
1773                 }
1774
1775                 //      Advance to next point on path.
1776                 Player_cur_path_index += 1;
1777
1778                 //      See if next point wraps past end of path (in either direction), and if so, deal with it based on mode.
1779                 if ((Player_cur_path_index >= Player_path_length) || (Player_cur_path_index < 0)) {
1780                         Player_following_path_flag = 0;
1781                         forced_break = 1;
1782                 }
1783
1784                 //      If went all the way around to original point, in same direction, then get out of here!
1785                 if (Player_cur_path_index == original_index) {
1786                         mprintf((0, "Forcing break because player path wrapped, count = %i.\n", count));
1787                         Player_following_path_flag = 0;
1788                         forced_break = 1;
1789                 }
1790
1791                 goal_point = Point_segs[Player_hide_index + Player_cur_path_index].point;
1792                 dist_to_goal = vm_vec_dist_quick(&goal_point, &objp->pos);
1793
1794         }       //      end while
1795
1796         //      Set velocity (objp->mtype.phys_info.velocity) and orientation (objp->orient) for this object.
1797         player_path_set_orient_and_vel(objp, &goal_point);
1798
1799 }
1800
1801
1802 //      ------------------------------------------------------------------------------------------------------------------
1803 //      Create path for player from current segment to goal segment.
1804 void create_player_path_to_segment(int segnum)
1805 {
1806         object          *objp = ConsoleObject;
1807
1808         Player_path_length=0;
1809         Player_hide_index=-1;
1810         Player_cur_path_index=0;
1811         Player_following_path_flag=0;
1812
1813         if (create_path_points(objp, objp->segnum, segnum, Point_segs_free_ptr, &Player_path_length, 100, 0, 0, -1) == -1)
1814                 mprintf((0, "Unable to form path of length %i for myself\n", 100));
1815
1816         Player_following_path_flag = 1;
1817
1818         Player_hide_index = Point_segs_free_ptr - Point_segs;
1819         Player_cur_path_index = 0;
1820         Point_segs_free_ptr += Player_path_length;
1821         if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
1822                 //Int3();       //      Contact Mike: This is curious, though not deadly. /eip++;g
1823                 ai_reset_all_paths();
1824         }
1825
1826 }
1827
1828 int     Player_goal_segment = -1;
1829
1830 void check_create_player_path(void)
1831 {
1832         if (Player_goal_segment != -1)
1833                 create_player_path_to_segment(Player_goal_segment);
1834
1835         Player_goal_segment = -1;
1836 }
1837
1838 #endif
1839
1840 //      ----------------------------------------------------------------------------------------------------------
1841 //                                      DEBUG FUNCTIONS ENDED
1842 //      ----------------------------------------------------------------------------------------------------------
1843