FINDPATH.CPP 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. //
  2. // Copyright 2020 Electronic Arts Inc.
  3. //
  4. // TiberianDawn.DLL and RedAlert.dll and corresponding source code is free
  5. // software: you can redistribute it and/or modify it under the terms of
  6. // the GNU General Public License as published by the Free Software Foundation,
  7. // either version 3 of the License, or (at your option) any later version.
  8. // TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed
  9. // in the hope that it will be useful, but with permitted additional restrictions
  10. // under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT
  11. // distributed with this program. You should have received a copy of the
  12. // GNU General Public License along with permitted additional restrictions
  13. // with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection
  14. /* $Header: /CounterStrike/FINDPATH.CPP 1 3/03/97 10:24a Joe_bostic $ */
  15. /***********************************************************************************************
  16. *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
  17. ***********************************************************************************************
  18. * *
  19. * Project Name : Command & Conquer *
  20. * *
  21. * File Name : FINDPATH.CPP *
  22. * *
  23. * Programmer : Joe L. Bostic *
  24. * *
  25. * Start Date : September 10, 1993 *
  26. * *
  27. * Last Update : May 25, 1995 [PWG] *
  28. * *
  29. * The path algorithm works by following a LOS path to the target. If it *
  30. * collides with an impassable spot, it uses an Edge following routine to *
  31. * get around it. The edge follower moves along the edge in a clockwise or *
  32. * counter clockwise fashion until finding the destination spot. The *
  33. * destination is determined by Find_Path. It is the first passable that *
  34. * can be reached (so it will handle the doughnut case, where there is *
  35. * a passable in the center of an unreachable area). *
  36. * *
  37. *---------------------------------------------------------------------------------------------*
  38. * Functions: *
  39. * Clear_Path_Overlap -- clears the path overlap list *
  40. * Find_Path -- Find a path from point a to point b. *
  41. * Find_Path_Cell -- Finds a given cell on a specified path *
  42. * Follow_Edge -- Follow an edge to get around an impassable spot. *
  43. * FootClass::Unravel_Loop -- Unravels a loop in the movement path *
  44. * Get_New_XY -- Get the new x,y based on current position and direction. *
  45. * Optimize_Moves -- Optimize the move list. *
  46. * Set_Path_Overlap -- Sets the overlap bit for given cell *
  47. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  48. #include "function.h"
  49. //#include <string.h>
  50. /*
  51. ** When an edge search is started, it can be performed CLOCKwise or
  52. ** COUNTERCLOCKwise direction.
  53. */
  54. #define CLOCK (FacingType)1 // Clockwise.
  55. #define COUNTERCLOCK (FacingType)-1 // Counterclockwise.
  56. /*
  57. ** If defined, diagonal moves are allowed, else no diagonals.
  58. */
  59. #define DIAGONAL
  60. /*
  61. ** This is the marker to signify the end of the path list.
  62. */
  63. #define END FACING_NONE
  64. /*
  65. ** "- 1" test for bit manipulation.
  66. */
  67. #define TEST
  68. /*
  69. ** If memory is more important than speed, set this define to
  70. ** true. It will then perform intermediate optimizations to get the most
  71. ** milage out of a limited movement list staging area. If this value
  72. ** is true then it figures paths a bit more intelligently.
  73. */
  74. #define SAVEMEM true
  75. /*
  76. ** Modify this macro so that given two cell values, it will return
  77. ** a value between 0 and 7, with 0 being North and moving
  78. ** clockwise (just like map degrees).
  79. */
  80. #define CELL_FACING(a, b) Dir_Facing(::Direction((a), (b)))
  81. /*-------------------------------------------------------------------------*/
  82. /*
  83. ** Cells values are really indexes into the 'map'. The following value is
  84. ** the X width of the map.
  85. */
  86. #define MODULO MAP_CELL_W
  87. /*
  88. ** Maximum lookahead cells. Twice this value in bytes will be
  89. ** reserved on the stack. The smaller this number, the faster the processing.
  90. */
  91. #define MAX_MLIST_SIZE 300
  92. #define THREAT_THRESHOLD 5
  93. #define MAX_PATH_EDGE_FOLLOW 400
  94. #ifdef NEVER
  95. typedef enum {
  96. FACING_N, // North
  97. FACING_NE, // North-East
  98. FACING_E, // East
  99. FACING_SE, // South-East
  100. FACING_S, // South
  101. FACING_SW, // South-West
  102. FACING_W, // West
  103. FACING_NW, // North-West
  104. FACING_COUNT // Total of 8 directions (0..7).
  105. } FacingType;
  106. #endif
  107. /*-------------------------------------------------------------------------*/
  108. //static bool DrawPath;
  109. inline FacingType Opposite(FacingType face)
  110. {
  111. return( (FacingType) (face ^ 4));
  112. }
  113. inline static FacingType Next_Direction(FacingType facing, FacingType dir)
  114. {
  115. facing = facing + dir;
  116. #ifndef DIAGONAL
  117. facing = (FacingType)(facing & 0x06);
  118. #endif
  119. return(facing);
  120. }
  121. /*=========================================================================*/
  122. /* Define a couple of variables which are private to the module they are */
  123. /* declared in. */
  124. /*=========================================================================*/
  125. static unsigned long MainOverlap[MAP_CELL_TOTAL/32]; // overlap list for the main path
  126. static unsigned long LeftOverlap[MAP_CELL_TOTAL/32]; // overlap list for the left path
  127. static unsigned long RightOverlap[MAP_CELL_TOTAL/32]; // overlap list for the right path
  128. //static CELL MoveMask = 0;
  129. static CELL DestLocation;
  130. static CELL StartLocation;
  131. /***************************************************************************
  132. * Point_Relative_To_Line -- Relation between a point and a line *
  133. * *
  134. * If a point is on a line then the following function holds true: *
  135. * (x - x2)(z1 - z2) = (z - z2)(x1 - x2) given x,z a point on the *
  136. * line (x1,z1),(x2,z2). *
  137. * If the right side is > then the left side then the point is on one *
  138. * side of the line and if the right side is < the the left side, then*
  139. * the point is on the other side of the line. By subtracting one side*
  140. * from the other we can determine on what side (if any) the point is on*
  141. * by testing the side of the resulting subtraction. *
  142. * *
  143. * INPUT: *
  144. * int x - x pos of point. *
  145. * int z - z pos of point. *
  146. * int x1 - x pos of first end of line segment. *
  147. * int z1 - z pos of first end of line segment. *
  148. * int x1 - x pos of second end of line segment. *
  149. * int z1 - z pos of second end of line segment. *
  150. * *
  151. * OUTPUT: *
  152. * Assuming (x1,z1) is north, (x2,z2) is south: *
  153. * 0 : point is on line. *
  154. * > 0 : point is east of line. *
  155. * < 0 : point is west of line. *
  156. * *
  157. * WARNINGS: *
  158. * Remember that int means that assumes 16 bits of precision. *
  159. * *
  160. * HISTORY: *
  161. * 10/28/1994 SKB : Created. *
  162. *=========================================================================*/
  163. int Point_Relative_To_Line(int x, int z, int x1, int z1, int x2, int z2)
  164. {
  165. return((((long)x - (long)x2) * ((long)z1 - (long)z2)) - (((long)z - (long)z2) * ((long)x1 - (long)x2)));
  166. }
  167. /***************************************************************************
  168. * FootClass::Unravel_Loop -- Unravels a loop in the movement path *
  169. * *
  170. * While in the midst of the Follow Edge logic, it is possible (due to the *
  171. * fact that we support diagonal movement) to begin looping around a *
  172. * column of some type. The Unravel loop function will scan backward *
  173. * through the list and fixup the path to try to prevent the loop. *
  174. * *
  175. * INPUT: path - pointer to the generated path so we can pull the *
  176. * commands out of it. *
  177. * cell - the cell we tried to enter that generated the *
  178. * double overlap condition. *
  179. * dir - the direction we tried to enter from when we *
  180. * generated the double overlap condition *
  181. * startx - the start x position of this path segment *
  182. * starty - the start y position of this path segment *
  183. * destx - the dest x position for this path segment *
  184. * desty - the dest y position for this path segment *
  185. * *
  186. * OUTPUT: TRUE - loop has been successfully unravelled *
  187. * FALSE - loop can not be unravelled so abort follow edge *
  188. * *
  189. * WARNINGS: none *
  190. * *
  191. * HISTORY: *
  192. * 05/25/1995 PWG : Created. *
  193. *=========================================================================*/
  194. bool FootClass::Unravel_Loop(PathType * path, CELL &cell, FacingType &dir, int sx, int sy, int dx, int dy, MoveType threshhold)
  195. {
  196. /*
  197. ** Walk back to the actual cell before we advanced our position
  198. */
  199. FacingType curr_dir = dir;
  200. CELL curr_pos = Adjacent_Cell(cell, Opposite(curr_dir));
  201. int idx = path->Length; // start at the last position
  202. FacingType * list = &path->Command[idx-1]; // point to the last command
  203. int checkx;
  204. int checky;
  205. int last_was_line = false;
  206. /*
  207. ** loop backward through the list searching for a point that is
  208. ** on the line. If the point was a diagonal move then adjust
  209. ** it.
  210. */
  211. while (idx) {
  212. checkx = Cell_X(curr_pos);
  213. checky = Cell_Y(curr_pos);
  214. if (!Point_Relative_To_Line(checkx, checky, sx, sy, dx, dy) || last_was_line) {
  215. /*
  216. ** We have now found a point on the line. Now we must check to see
  217. ** if we left the line on a diagonal. If we did then we need to fix
  218. ** it up.
  219. */
  220. if (curr_dir & 1 && curr_pos != path->LastFixup) {
  221. cell = curr_pos;
  222. dir = *(list-1);
  223. path->Length = idx;
  224. path->LastFixup = curr_pos;
  225. return(true);
  226. }
  227. last_was_line = !last_was_line;
  228. }
  229. /*
  230. ** Since this cell will not be in the list, then pull out its cost
  231. */
  232. path->Cost -= Passable_Cell(curr_pos, *list, -1, threshhold);
  233. /*
  234. ** Remove this cells flag from the overlap list for the path
  235. */
  236. #ifdef TEST
  237. path->Overlap[curr_pos >> 5] &= ~(1 << ((curr_pos & 31)));
  238. #else
  239. path->Overlap[curr_pos >> 5] &= ~(1 << ((curr_pos & 31) - 1));
  240. #endif
  241. /*
  242. ** Adjust to the next list position and direction.
  243. */
  244. curr_dir = *list--;
  245. curr_pos = Adjacent_Cell(curr_pos, Opposite(curr_dir));
  246. idx--;
  247. }
  248. /*
  249. ** If we can't modify the list to eliminate the problem, then we have
  250. ** a larger problem in that we have deleted all of the cells in the
  251. ** list.
  252. */
  253. return(false);
  254. }
  255. /***************************************************************************
  256. * Register_Cell -- registers a cell on our path and check for backtrack *
  257. * *
  258. * This function adds a new cell to our path. If the cell has already *
  259. * been recorded as part of our path, then this function moves back down *
  260. * the list truncating it at the point we registered that cell. This *
  261. * function will eliminate all backtracking from the list. *
  262. * *
  263. * INPUT: long * list - the list to set the overlap bit for *
  264. * CELL cell - the cell to mark on the overlap list *
  265. * *
  266. * OUTPUT: BOOL - TRUE if bit has been set, FALSE if bit already set *
  267. * *
  268. * HISTORY: *
  269. * 05/23/1995 PWG : Created. *
  270. *=========================================================================*/
  271. bool FootClass::Register_Cell(PathType * path, CELL cell, FacingType dir, int cost, MoveType threshhold)
  272. {
  273. FacingType * list;
  274. int pos = cell >> 5;
  275. #ifdef TEST
  276. int bit = (cell & 31);
  277. #else
  278. int bit = (cell & 31) - 1;
  279. #endif
  280. /*
  281. ** See if this point has already been registered as on the list. If so
  282. ** we need to truncate the list back to this point and register the
  283. ** new direction.
  284. */
  285. if (path->Overlap[pos] & (1 << bit)) {
  286. /*
  287. ** If this is not a case of immediate back tracking then handle
  288. ** by searching the list to see what we find. However is this is
  289. ** an immediate back track, then pop of the last direction
  290. ** and unflag the cell we are in (not the cell we are moving to).
  291. ** Note: That we do not check for a zero length cell because we
  292. ** could not have a duplicate unless there are cells in the list.
  293. */
  294. if (path->Command[path->Length - 1] == Opposite(dir)) {
  295. CELL pos = Adjacent_Cell(cell, Opposite(dir));
  296. #ifdef TEST
  297. path->Overlap[pos >> 5] &= ~(1 << ((pos & 31)));
  298. #else
  299. path->Overlap[pos >> 5] &= ~(1 << ((pos & 31) - 1));
  300. #endif
  301. path->Length--;
  302. } else {
  303. /*
  304. ** If this overlap is in the same place as we had our last overlap
  305. ** then we are in a loop condition. We need to signify that we
  306. ** cannot register this cell.
  307. */
  308. if (path->LastOverlap == cell) {
  309. return(false);
  310. } else {
  311. path->LastOverlap = cell;
  312. }
  313. CELL pos = path->Start;
  314. int newlen = 0;
  315. int idx = 0;
  316. list = path->Command;
  317. /*
  318. ** Note that the cell has to be in this list, so theres no sense
  319. ** in checking whether we found it (famous last words).
  320. **
  321. ** PWG 8/16/95 - However there is no sense searching the list if
  322. ** the cell we have overlapped on is the cell we
  323. ** started in.
  324. */
  325. if (pos != cell) {
  326. while (idx < path->Length) {
  327. pos = Adjacent_Cell(pos, *list);
  328. if (pos == cell) {
  329. idx++;
  330. list++;
  331. break;
  332. }
  333. idx++;
  334. list++;
  335. }
  336. newlen = idx;
  337. }
  338. /*
  339. ** Now we are pointing at the next command in the list. From here on
  340. ** out we need to unmark the fact that we have entered these cells and
  341. ** adjust the cost of our path to reflect that we have not entered
  342. ** then.
  343. */
  344. while (idx < path->Length) {
  345. pos = Adjacent_Cell(pos, *list);
  346. path->Cost -= Passable_Cell(pos, *list, -1, threshhold);
  347. #ifdef TEST
  348. path->Overlap[pos >> 5] &= ~(1 << ((pos & 31)));
  349. #else
  350. path->Overlap[pos >> 5] &= ~(1 << ((pos & 31) - 1));
  351. #endif
  352. idx++;
  353. list++;
  354. }
  355. path->Length = newlen;
  356. }
  357. } else {
  358. /*
  359. ** Now we need to register the new direction, updating the cell structure
  360. ** and the cost.
  361. */
  362. int cpos = path->Length++;
  363. path->Command[cpos] = dir; // save of the direction we moved
  364. path->Cost += cost; // figure new cost for cell
  365. path->Overlap[pos] |= (1 << bit); // mark the we have entered point
  366. }
  367. return(true);
  368. }
  369. /***********************************************************************************************
  370. * Find_Path -- Find a path from point a to point b. *
  371. * *
  372. * INPUT: int source x,y, int destination x,y, char *final moves *
  373. * array to store moves, int maximum moves we may attempt *
  374. * *
  375. * OUTPUT: int number of moves it took (IMPOSSIBLE_MOVES if we could *
  376. * not reach the destination *
  377. * *
  378. * WARNINGS: This algorithm assumes that the target is NOT situated *
  379. * inside an impassable. If this case may arise, the do-while *
  380. * statement inside the inner while (true) must be changed *
  381. * to include a check to se if the next_x,y is equal to the *
  382. * dest_x,y. If it is, then return(IMPOSSIBLE_MOVES). *
  383. * *
  384. * HISTORY: *
  385. * 07/08/1991 CY : Created. *
  386. *=============================================================================================*/
  387. PathType * FootClass::Find_Path(CELL dest, FacingType * final_moves, int maxlen, MoveType threshhold)
  388. {
  389. CELL source = Coord_Cell(Coord); // Source expressed as cell
  390. static PathType path; // Main path control.
  391. CELL next; // Next cell to enter
  392. CELL startcell; // Cell we started in
  393. FacingType direction; // Working direction of look ahead.
  394. FacingType newdir; // Tentative facing value.
  395. bool left=false, // Was leftward path legal?
  396. right=false; // Was rightward path legal?
  397. int len; // Length of detour command list.
  398. int unit_threat; // Calculated unit threat rating
  399. int cost; // Cost to enter the square
  400. FacingType moves_left[MAX_MLIST_SIZE+2], // Counterclockwise move list.
  401. moves_right[MAX_MLIST_SIZE+2]; // Clockwise move list.
  402. PathType pleft,pright; // Path control structures.
  403. PathType * which; // Which path to actually use.
  404. int threat = 0; //
  405. int threat_stage = 0; //These weren't initialized. ST - 1/8/2019 12:03PM
  406. /*
  407. ** If we have been provided an illegal place to store our final moves
  408. ** then forget it.
  409. */
  410. if (!final_moves) return(NULL);
  411. BStart(BENCH_FINDPATH);
  412. PathCount++;
  413. if (Team && Team->Class->IsRoundAbout) {
  414. unit_threat = (Team) ? Team->Risk : Risk();
  415. threat_stage = 0;
  416. threat = 0;
  417. } else {
  418. unit_threat = threat = -1;
  419. }
  420. StartLocation = source;
  421. DestLocation = dest;
  422. /*
  423. ** Initialize the path structure so that we can keep track of the
  424. ** path.
  425. */
  426. path.Start = source;
  427. path.Cost = 0;
  428. path.Length = 0;
  429. path.Command = final_moves;
  430. path.Command[0] = END;
  431. path.Overlap = MainOverlap;
  432. path.LastOverlap = -1;
  433. path.LastFixup = -1;
  434. memset(path.Overlap, 0, sizeof(MainOverlap));
  435. /*
  436. ** Clear the over lap list and then make sure that our starting position is marked
  437. ** on the overlap list. (Otherwise the harvesters will drive in circles... )
  438. */
  439. #ifdef TEST
  440. path.Overlap[source >> 5] |= (1 << ((source & 31)));
  441. #else
  442. path.Overlap[source >> 5] |= (1 << ((source & 31) - 1));
  443. #endif
  444. startcell = source;
  445. /*
  446. ** Account for trailing end of list command, so reduce the maximum
  447. ** allowed legal commands to reflect this.
  448. */
  449. maxlen--;
  450. /*
  451. ** As long as there is room to put commands in the movement command list,
  452. ** then put commands in it. We build the path using the following
  453. ** methodology.
  454. **
  455. ** 1. Scan through the desired straight line path until we either hit an
  456. ** impassable or have created a valid path.
  457. **
  458. ** 2. If we have hit an impassable, walk through the impassable to make
  459. ** sure that there is a passable on the other side. If there is not
  460. ** and we can not change the impassable, then this list is dead.
  461. **
  462. ** 3. Walk around the impassable on both the left and right edges and
  463. ** take the shorter of the two paths.
  464. **
  465. ** 4. Taking the new location as our start location start again with
  466. ** step #1.
  467. */
  468. while (path.Length < maxlen) {
  469. top_of_list:
  470. /*
  471. ** Have we reached the destination already? If so abort any further
  472. ** command building.
  473. */
  474. if (startcell == dest) {
  475. break;
  476. }
  477. /*
  478. ** Find the absolute correct direction to reach the next straight
  479. ** line cell and what cell it is.
  480. */
  481. direction = CELL_FACING(startcell, dest);
  482. next = Adjacent_Cell(startcell, direction);
  483. /*
  484. ** If we can move here, then make this our next move.
  485. */
  486. cost = Passable_Cell(next, direction, threat, threshhold);
  487. if (cost) {
  488. Register_Cell(&path, next, direction, cost, threshhold);
  489. } else {
  490. /*
  491. ** If the impassable location is actually the destination,
  492. ** then stop here and consider this "good enough".
  493. */
  494. if (next == dest) break;
  495. /*
  496. ** We could not move to the next cell, so follow through the
  497. ** impassable until we find a passable spot that can be reached.
  498. ** Once we find a passable, figure out the shortest path to it.
  499. ** Since we have variable passable conditions this is not as
  500. ** simple as it used to be. The limiter loop below allows us to
  501. ** step through ten doughnuts before we give up.
  502. */
  503. for (int limiter = 0; limiter < 5; limiter++) {
  504. /*
  505. ** Get the next passable position by zipping through the
  506. ** impassable positions until a passable position is found
  507. ** or the destination is reached.
  508. */
  509. for (;;) {
  510. /*
  511. ** Move one step closer toward destination.
  512. */
  513. newdir = CELL_FACING(next, dest);
  514. next = Adjacent_Cell(next, newdir);
  515. /*
  516. ** If the cell is passable then we have been completely
  517. ** successful. If the cell is not passable then continue.
  518. */
  519. if (Passable_Cell(next, FACING_NONE, threat, threshhold)) {
  520. // if ((Passable_Cell(next, FACING_NONE, threat, threshhold)) || (next == dest)) {
  521. break;
  522. }
  523. /*
  524. ** If we reached destination while in this loop, we
  525. ** know that either the destination is impassible (if
  526. ** we are ignoring) or that we need to up our threat
  527. ** tolerance and try again.
  528. */
  529. if (next == dest) {
  530. if (threat != -1) {
  531. switch (threat_stage++) {
  532. case 0:
  533. threat = unit_threat >> 1;
  534. break;
  535. case 1:
  536. threat += unit_threat;
  537. break;
  538. case 2:
  539. threat = -1;
  540. break;
  541. }
  542. goto top_of_list;
  543. }
  544. goto end_of_list;
  545. }
  546. }
  547. /*
  548. ** Try to find a path to the passable position by following
  549. ** the edge of the blocking object in both CLOCKwise and
  550. ** COUNTERCLOCKwise fashions.
  551. */
  552. int follow_len = maxlen + (maxlen >> 1);
  553. Mem_Copy(&path, &pleft, sizeof(PathType));
  554. pleft.Command = &moves_left[0];
  555. pleft.Overlap = LeftOverlap;
  556. Mem_Copy(path.Command, pleft.Command, path.Length);
  557. Mem_Copy(path.Overlap, pleft.Overlap, sizeof(LeftOverlap));
  558. // MBL 09.30.2019: We hit a runtime bounds crash where END (-1 / 0xFF) was being poked into +1 just past the end of the moves_right[] array;
  559. // The FacingType moves_left[] and moves_right[] arrays already have MAX_MLIST_SIZE+2 as their size, which may have been a previous attempted fix;
  560. // We are now passing MAX_MLIST_SIZE, since the sizeof calculations included the +2 buffering;
  561. #if 0
  562. left = Follow_Edge(startcell, next, &pleft, COUNTERCLOCK, direction, threat, threat_stage, sizeof(moves_left)/sizeof(moves_left[0]), threshhold);
  563. // left = Follow_Edge(startcell, next, &pleft, COUNTERCLOCK, direction, threat, threat_stage, follow_len, threshhold);
  564. #endif
  565. left = Follow_Edge(startcell, next, &pleft, COUNTERCLOCK, direction, threat, threat_stage, MAX_MLIST_SIZE, threshhold);
  566. if (left) {
  567. follow_len = min(maxlen, pleft.Length + (pleft.Length >> 1));
  568. }
  569. Mem_Copy(&path, &pright, sizeof(PathType));
  570. pright.Command = &moves_right[0];
  571. pright.Overlap = RightOverlap;
  572. Mem_Copy(path.Command, pright.Command, path.Length);
  573. Mem_Copy(path.Overlap, pright.Overlap, sizeof(RightOverlap));
  574. // MBL 09.30.2019: We hit a runtime bounds crash where END (-1 / 0xFF) was being poked into +1 just past the end of the moves_right[] array;
  575. // The FacingType moves_left[] and moves_right[] arrays already have MAX_MLIST_SIZE+2 as their size, which may have been a previous attempted fix;
  576. // We are now passing MAX_MLIST_SIZE, since the sizeof calculations included the +2 buffering;
  577. #if 0
  578. right = Follow_Edge(startcell, next, &pright, CLOCK, direction, threat, threat_stage, sizeof(moves_right)/sizeof(moves_right[0]), threshhold);
  579. // right = Follow_Edge(startcell, next, &pright, CLOCK, direction, threat, threat_stage, follow_len, threshhold);
  580. #endif
  581. right = Follow_Edge(startcell, next, &pright, CLOCK, direction, threat, threat_stage, MAX_MLIST_SIZE, threshhold);
  582. /*
  583. ** If we could find a path, break from this loop. Otherwise this
  584. ** means that we have found a "hole" of passable terrain that
  585. ** cannot be reached by normal means. Scan forward looking for
  586. ** the other side of the "doughnut".
  587. */
  588. if (left || right) break;
  589. /*
  590. ** If no path can be found to the intermediate cell, then
  591. ** presume we have found a doughnut of some sort. Scan
  592. ** forward until the next impassable is found and then
  593. ** process this loop again.
  594. */
  595. do {
  596. /*
  597. ** If we reached destination while in this loop, we
  598. ** know that either the destination is impassible (if
  599. ** we are ignoring) or that we need to up our threat
  600. ** tolerance and try again.
  601. */
  602. if (next == dest) {
  603. if (threat != -1) {
  604. switch (threat_stage++) {
  605. case 0:
  606. threat = unit_threat >> 1;
  607. break;
  608. case 1:
  609. threat += unit_threat;
  610. break;
  611. case 2:
  612. threat = -1;
  613. break;
  614. }
  615. goto top_of_list;
  616. }
  617. goto end_of_list;
  618. }
  619. newdir = CELL_FACING(next, dest);
  620. next = Adjacent_Cell(next, newdir);
  621. } while (Passable_Cell(next, newdir, threat, threshhold));
  622. }
  623. if (!left && !right) break;
  624. /*
  625. ** We found a path around the impassable locations, so figure out
  626. ** which one was the smallest and copy those moves into the
  627. ** path.Command array.
  628. */
  629. which = &pleft;
  630. if (right) {
  631. which = &pright;
  632. if (left) {
  633. if (pleft.Length < pright.Length) {
  634. which = &pleft;
  635. } else {
  636. which = &pright;
  637. }
  638. }
  639. }
  640. /*
  641. ** Record as much as possible of the shorter of the two
  642. ** paths. The trailing EOL command is not copied because
  643. ** this may not be the end of the find path logic.
  644. */
  645. len = which->Length;
  646. len = min(len, maxlen);
  647. if (len > 0) {
  648. memcpy(&path.Overlap[0], &which->Overlap[0], sizeof(LeftOverlap));
  649. memcpy(&path.Command[0], &which->Command[0], len * sizeof(FacingType));
  650. path.Length = len;
  651. path.Cost = which->Cost;
  652. path.LastOverlap = -1;
  653. path.LastFixup = -1;
  654. } else {
  655. break;
  656. }
  657. }
  658. startcell = next;
  659. }
  660. end_of_list:
  661. /*
  662. ** Poke in the stop command.
  663. */
  664. if (path.Length < maxlen) {
  665. path.Command[path.Length++] = END;
  666. }
  667. /*
  668. ** Optimize the move list but only necessary if
  669. ** diagonal moves are allowed.
  670. */
  671. #ifdef DIAGONAL
  672. Optimize_Moves(&path, threshhold);
  673. #endif
  674. BEnd(BENCH_FINDPATH);
  675. return(&path);
  676. }
  677. /***********************************************************************************************
  678. * Follow_Edge -- Follow an edge to get around an impassable spot. *
  679. * *
  680. * INPUT: start -- cell to head from *
  681. * *
  682. * target -- Target cell to head to. *
  683. * *
  684. * path -- Pointer to path list structure. *
  685. * *
  686. * search -- Direction of search (1=clock, -1=counterclock). *
  687. * *
  688. * olddir -- Facing impassible direction from start. *
  689. * *
  690. * callback -- Function pointer for determining if a cell is *
  691. * passable or not. *
  692. * *
  693. * OUTPUT: bool: Could a path be found to the desired cell? *
  694. * *
  695. * WARNINGS: none *
  696. * *
  697. * HISTORY: *
  698. * 07/08/1991 CY : Created. *
  699. * 06/01/1992 JLB : Optimized & commented. *
  700. *=============================================================================================*/
  701. bool FootClass::Follow_Edge(CELL start, CELL target, PathType * path, FacingType search, FacingType olddir, int threat, int , int max_cells, MoveType threshhold)
  702. {
  703. FacingType newdir; // Direction of facing before surrounding cell check.
  704. CELL oldcell, // Current cell.
  705. newcell; // Tentative new cell.
  706. int cost; // Working cost value.
  707. int startx;
  708. int starty;
  709. int online=true;
  710. int targetx;
  711. int targety;
  712. int oldval = 0;
  713. int cellcount=0;
  714. int forceout = false;
  715. FacingType firstdir = (FacingType)-1;
  716. CELL firstcell = -1;
  717. bool stepped_off_line = false;
  718. startx = Cell_X(start);
  719. starty = Cell_Y(start);
  720. targetx = Cell_X(target);
  721. targety = Cell_Y(target);
  722. if (!path) return(false);
  723. path->LastOverlap = -1;
  724. path->LastFixup = -1;
  725. #ifndef DIAGONAL
  726. /*
  727. ** The edge following algorithm doesn't "do" diagonals. Force initial facing
  728. ** to be an even 90 degree value. Adjust it in the direction it should be
  729. ** rotating.
  730. */
  731. if (olddir & 0x01) {
  732. olddir = Next_Direction(olddir, search);
  733. }
  734. #endif
  735. newdir = Next_Direction(olddir, search);
  736. oldcell = start;
  737. newcell = Adjacent_Cell(oldcell, newdir);
  738. /*
  739. ** Continue until we find our target, find our original starting spot,
  740. ** or run out of moves.
  741. */
  742. while (path->Length < max_cells) {
  743. /*
  744. ** Look in all the adjacent cells to determine a passable one that
  745. ** most closely matches the desired direction (working in the specified
  746. ** direction).
  747. */
  748. newdir = olddir;
  749. for (;;) {
  750. bool forcefail; // Is failure forced?
  751. forcefail = false;
  752. #ifdef DIAGONAL
  753. /*
  754. ** Rotate 45/90 degrees in desired direction.
  755. */
  756. newdir = Next_Direction(newdir, search);
  757. /*
  758. ** If facing a diagonal we must check the next 90 degree location
  759. ** to make sure that we don't walk right by the destination. This
  760. ** will happen if the destination it is at the corner edge of an
  761. ** impassable that we are moving around.
  762. */
  763. if (newdir & FACING_NE) {
  764. CELL checkcell; // Non-diagonal check cell.
  765. //int x,y;
  766. checkcell = Adjacent_Cell(oldcell, Next_Direction(newdir, search));
  767. if (checkcell == target) {
  768. /*
  769. ** This only works if in fact, it is possible to move to the
  770. ** cell from the current location.
  771. */
  772. cost = Passable_Cell(checkcell, Next_Direction(newdir, search), threat, threshhold);
  773. if (cost) {
  774. /*
  775. ** YES! The destination is at the corner of an impassable, so
  776. ** set the direction to point directly at it and then the
  777. ** scanning will terminate later.
  778. */
  779. newdir = Next_Direction(newdir, search);
  780. newcell = Adjacent_Cell(oldcell, newdir);
  781. break;
  782. }
  783. }
  784. /*
  785. ** Perform special diagonal check. If the edge follower would cross the
  786. ** diagonal or fall on the diagonal line from the source, then consider
  787. ** that cell impassible. Otherwise, the find path algorithm will fail
  788. ** when there are two impassible locations located on a diagonal
  789. ** that is lined up between the source and destination location.
  790. **
  791. ** P.S. It might help if you check the right cell rather than using
  792. ** the value that just happened to be in checkcell.
  793. */
  794. checkcell = Adjacent_Cell(oldcell, newdir);
  795. int checkx = Cell_X(checkcell);
  796. int checky = Cell_Y(checkcell);
  797. int checkval = Point_Relative_To_Line(checkx, checky, startx, starty, targetx, targety);
  798. if (checkval && !online) {
  799. forcefail = ((checkval ^ oldval) < 0);
  800. } else {
  801. forcefail = false;
  802. }
  803. /*
  804. ** The only exception to the above is when we are directly backtracking
  805. ** because we could be trying to escape from a culdesack!
  806. */
  807. if (forcefail && path->Length > 0 && (FacingType)(newdir ^ 4) == path->Command[path->Length - 1]) {
  808. forcefail = false;
  809. }
  810. }
  811. #else
  812. newdir = Next_Direction(newdir, search*2);
  813. #endif
  814. /*
  815. ** If we have just checked the same heading we started with,
  816. ** we are surrounded by impassable characters and we exit.
  817. */
  818. if (newdir == olddir) {
  819. return(false);
  820. }
  821. /*
  822. ** Get the new cell.
  823. */
  824. newcell = Adjacent_Cell(oldcell, newdir);
  825. /*
  826. ** If we found a passable position, this is where we should move.
  827. */
  828. if (!forcefail && ((cost = Passable_Cell(newcell, newdir, threat, threshhold)) != 0)) {
  829. break;
  830. } else {
  831. if (newcell == target) {
  832. forceout = true;
  833. break;
  834. }
  835. }
  836. }
  837. /*
  838. ** Record the direction.
  839. */
  840. if (!forceout) {
  841. /*
  842. ** Mark the cell because this is where we need to be. If register
  843. ** cell fails then the list has been shortened and we need to adjust
  844. ** the new direction.
  845. */
  846. if (!Register_Cell(path, newcell, newdir, cost, threshhold)) {
  847. /*
  848. ** The only reason we could not register a cell is that we are in
  849. ** a looping situation. So we need to try and unravel the loop if
  850. ** we can.
  851. */
  852. if (!Unravel_Loop(path, newcell, newdir, startx, starty, targetx, targety, threshhold)) {
  853. return(false);
  854. }
  855. /*
  856. ** Since we need to eliminate a diagonal we must pretend the upon
  857. ** attaining this square, we were moving turned further in the
  858. ** search direction then we really were.
  859. */
  860. newdir = Next_Direction(newdir, (FacingType)(search*2));
  861. }
  862. /*
  863. ** Find out which side of the line this cell is on. If it is on
  864. ** a side, then store off that side.
  865. */
  866. int newx = Cell_X(newcell);
  867. int newy = Cell_Y(newcell);
  868. int val = Point_Relative_To_Line(newx, newy, startx, starty, targetx, targety);
  869. if (val) {
  870. oldval = val;
  871. online = false;
  872. } else {
  873. online = true;
  874. }
  875. cellcount++;
  876. if (cellcount == MAX_PATH_EDGE_FOLLOW) {
  877. return(false);
  878. }
  879. }
  880. /*
  881. ** If we have found the target spot, we are done.
  882. */
  883. if (newcell == target) {
  884. path->Command[path->Length] = END;
  885. return(true);
  886. }
  887. /*
  888. ** If we make a full circle back to our original spot, get out.
  889. */
  890. if (newcell == firstcell && newdir == firstdir) {
  891. return(false);
  892. }
  893. if (firstcell == -1) {
  894. firstcell = newcell;
  895. firstdir = newdir;
  896. }
  897. /*
  898. ** Because we moved, our facing is now incorrect. We want to face toward
  899. ** the impassable edge we are following (well, not actually toward, but
  900. ** a little past so that we can turn corners). We have to turn 45/90 degrees
  901. ** more than expected in anticipation of the pending 45/90 degree turn at
  902. ** the start of this loop.
  903. */
  904. #ifdef DIAGONAL
  905. olddir = Next_Direction(newdir, (FacingType)(-(int)search*3));
  906. #else
  907. olddir = Next_Direction(newdir, (FacingType)(-(int)search*4));
  908. #endif
  909. oldcell = newcell;
  910. }
  911. /*
  912. ** The maximum search path is exhausted... abort with a failure.
  913. */
  914. return(false);
  915. }
  916. /***********************************************************************************************
  917. * Optimize_Moves -- Optimize the move list. *
  918. * *
  919. * INPUT: char *moves to optimize *
  920. * *
  921. * OUTPUT: none (list is optimized) *
  922. * *
  923. * WARNINGS: EMPTY moves are used to hold the place of eliminated *
  924. * commands. Also, NEVER call this routine with a list that *
  925. * contains illegal commands. The list MUST be terminated *
  926. * with a EOL command *
  927. * *
  928. * HISTORY: *
  929. * 07/08/1991 CY : Created. *
  930. * 06/01/1992 JLB : Optimized and commented. *
  931. *=============================================================================================*/
  932. #define EMPTY (FacingType)-2
  933. int FootClass::Optimize_Moves(PathType * path, MoveType threshhold)
  934. //int Optimize_Moves(PathType *path, int (*callback)(CELL, FacingType), int threshold)
  935. {
  936. /*
  937. ** Facing command pair adjustment table. Compare the facing difference between
  938. ** the two commands. 0 means no optimization is possible. 3 means backtracking
  939. ** so eliminate both commands. Any other value adjusts the first command facing.
  940. */
  941. #ifdef DIAGONAL
  942. static FacingType _trans[FACING_COUNT] = {(FacingType)0, (FacingType)0, (FacingType)1, (FacingType)2, (FacingType)3, (FacingType)-2, (FacingType)-1, (FacingType)0}; // Smoothing.
  943. #else
  944. static FacingType _trans[FACING_COUNT] = {(FacingType)0, (FacingType)0, (FacingType)0, (FacingType)2, (FacingType)3, (FacingType)-2, (FacingType)0, (FacingType)0};
  945. #endif
  946. FacingType * cmd1, // Floating first command pointer.
  947. * cmd2, // Floating second command pointer.
  948. newcmd; // Calculated new optimized command.
  949. FacingType newdir; // Tentative new direction for smoothing.
  950. CELL cell; // Working cell (as it moves along path).
  951. /*
  952. ** Abort if there is any illegal parameter.
  953. */
  954. if (!path || !path->Command) return(0);
  955. /*
  956. ** Optimization loop -- start scanning with the
  957. ** first pair of commands (if there are at least two
  958. ** in the command list).
  959. */
  960. path->Command[path->Length] = END; // Force end of list.
  961. if (path->Length == 0) return(0);
  962. cell = path->Start;
  963. if (path->Length > 1) {
  964. cmd2 = path->Command + 1;
  965. while (*cmd2 != END) {
  966. /*
  967. ** Set the cmd1 pointer to point to the valid command closest, but
  968. ** previous to cmd2. Be sure not to go previous to the head of the
  969. ** command list.
  970. */
  971. cmd1 = cmd2-1;
  972. while (*cmd1 == EMPTY && cmd1 != path->Command) {
  973. cmd1--;
  974. }
  975. /*
  976. ** If there isn't any valid previous command, then bump the
  977. ** cmd pointers to the next command pair and continue...
  978. */
  979. if (*cmd1 == EMPTY) {
  980. cmd2++;
  981. continue;
  982. }
  983. /*
  984. ** Fetch precalculated command change value. 0 means leave
  985. ** command set alone, 3 means backtrack and eliminate two
  986. ** commands. Any other value is new direction and eliminate
  987. ** one command.
  988. */
  989. newcmd = (FacingType)(*cmd2 - *cmd1);
  990. if (newcmd < FACING_N) newcmd = (FacingType)(newcmd + FACING_COUNT);
  991. newcmd = _trans[newcmd];
  992. /*
  993. ** Check for backtracking. If this occurs, then eliminate the
  994. ** two commands. This is the easiest optimization.
  995. */
  996. if (newcmd == FACING_SE) {
  997. *cmd1 = EMPTY;
  998. *cmd2++ = EMPTY;
  999. continue;
  1000. }
  1001. /*
  1002. ** If an optimization code was found the process it. The command is a facing
  1003. ** offset to more directly travel toward the immediate destination cell.
  1004. */
  1005. if (newcmd) {
  1006. /*
  1007. ** Optimizations differ when dealing with diagonals. Especially when dealing
  1008. ** with diagonals of 90 degrees. In such a case, 90 degree optimizations can
  1009. ** only be optimized if the intervening cell is passable. The distance travelled
  1010. ** is the same, but the path is less circuitous.
  1011. */
  1012. if (*cmd1 & FACING_NE) {
  1013. /*
  1014. ** Diagonal optimizations are always only 45
  1015. ** degree adjustments.
  1016. */
  1017. newdir = Next_Direction(*cmd1, (newcmd < FACING_N) ? (FacingType)-1 : (FacingType)1);
  1018. /*
  1019. ** Diagonal 90 degree changes can be smoothed, although
  1020. ** the path isn't any shorter.
  1021. */
  1022. if (ABS((int)newcmd) == 1) {
  1023. if (Passable_Cell(Adjacent_Cell(cell, newdir), newdir, -1, threshhold)) {
  1024. *cmd2 = newdir;
  1025. *cmd1 = newdir;
  1026. }
  1027. // BOB 16.12.92
  1028. cell = Adjacent_Cell(cell, *cmd1);
  1029. cmd2++;
  1030. continue;
  1031. }
  1032. } else {
  1033. newdir = Next_Direction(*cmd1, newcmd);
  1034. }
  1035. /*
  1036. ** Allow shortening turn only on right angle moves that are based on
  1037. ** 90 degrees. Always allow 135 degree optimizations.
  1038. */
  1039. *cmd2 = newdir;
  1040. *cmd1 = EMPTY;
  1041. /*
  1042. ** Backup what it thinks is the current cell.
  1043. */
  1044. while (*cmd1 == EMPTY && cmd1 != path->Command) {
  1045. cmd1--;
  1046. }
  1047. if (*cmd1 != EMPTY) {
  1048. cell = Adjacent_Cell(cell, Next_Direction(*cmd1, FACING_S));
  1049. } else {
  1050. cell = path->Start;
  1051. }
  1052. continue;
  1053. }
  1054. /*
  1055. ** Since we could not make an optimization, we move our
  1056. ** head pointer forward.
  1057. */
  1058. cell = Adjacent_Cell(cell, *cmd1);
  1059. cmd2++;
  1060. }
  1061. }
  1062. /*
  1063. ** Pack the command list to remove any EMPTY command entries.
  1064. */
  1065. cmd1 = path->Command;
  1066. cmd2 = path->Command;
  1067. cell = path->Start;
  1068. path->Cost = 0;
  1069. path->Length = 0;
  1070. while (*cmd2 != END) {
  1071. if (*cmd2 != EMPTY) {
  1072. cell = Adjacent_Cell(cell, *cmd2);
  1073. path->Cost+= Passable_Cell(cell, *cmd2, -1, threshhold);
  1074. path->Length++;
  1075. *cmd1++ = *cmd2;
  1076. }
  1077. cmd2++;
  1078. }
  1079. path->Length++;
  1080. *cmd1 = END;
  1081. return(path->Length);
  1082. }
  1083. CELL FootClass::Safety_Point(CELL src, CELL dst, int start, int max)
  1084. {
  1085. FacingType dir;
  1086. CELL next;
  1087. int lp;
  1088. dir = (FacingType)(CELL_FACING(src, dst) ^ 4) - 1;
  1089. /*
  1090. ** Loop through the different acceptable distances.
  1091. */
  1092. for (int dist = start; dist < max; dist ++) {
  1093. /*
  1094. ** Move to the starting location.
  1095. */
  1096. next = dst;
  1097. for (lp = 0; lp < dist; lp ++) {
  1098. next = Adjacent_Cell(next, dir);
  1099. }
  1100. if (dir & 1) {
  1101. /*
  1102. ** If our direction is diagonal than we need to check
  1103. ** only one side which is as long as both of the old sides
  1104. ** together.
  1105. */
  1106. for (lp = 0; lp < dist << 1; lp ++) {
  1107. next = Adjacent_Cell(next, dir + 3);
  1108. if (!Can_Enter_Cell(next)) {
  1109. return(next);
  1110. }
  1111. }
  1112. } else {
  1113. /*
  1114. ** If our direction is not diagonal than we need to check two
  1115. ** sides so that we are checking a corner like location.
  1116. */
  1117. for (lp = 0; lp < dist; lp ++) {
  1118. next = Adjacent_Cell(next, dir + 2);
  1119. if (!Can_Enter_Cell(next)) {
  1120. return(next);
  1121. }
  1122. }
  1123. for (lp = 0; lp < dist; lp ++) {
  1124. next = Adjacent_Cell(next, dir + 4);
  1125. if (!Can_Enter_Cell(next)) {
  1126. return(next);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. return(-1);
  1132. }
  1133. int FootClass::Passable_Cell(CELL cell, FacingType face, int threat, MoveType threshhold)
  1134. {
  1135. MoveType move = Can_Enter_Cell(cell, face);
  1136. if (move < MOVE_MOVING_BLOCK && Distance(Cell_Coord(cell)) > 0x0100) threshhold = MOVE_MOVING_BLOCK;
  1137. if (move > threshhold) return(0);
  1138. if (Session.Type == GAME_NORMAL) {
  1139. if (threat != -1) {
  1140. if (::Distance(Cell_Coord(cell), Cell_Coord(DestLocation)) > (THREAT_THRESHOLD * CELL_LEPTON_W)) {
  1141. // if (Map.Cell_Distance(cell, DestLocation) > THREAT_THRESHOLD) {
  1142. if (Map.Cell_Threat(cell, Owner()) > threat)
  1143. return(0);
  1144. }
  1145. }
  1146. }
  1147. static int _value[MOVE_COUNT] = {
  1148. 1, // MOVE_OK
  1149. 1, // MOVE_CLOAK
  1150. 3, // MOVE_MOVING_BLOCK
  1151. 8, // MOVE_DESTROYABLE
  1152. 10, // MOVE_TEMP
  1153. 0 // MOVE_NO
  1154. };
  1155. return(_value[move]);
  1156. }