LCOV - code coverage report
Current view: top level - source/simulation2/helpers - LongPathfinder.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 40 57 70.2 %
Date: 2026-12-03 01:19:39 Functions: 1 1 100.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #ifndef INCLUDED_LONGPATHFINDER
      19             : #define INCLUDED_LONGPATHFINDER
      20             : 
      21             : #include "Pathfinding.h"
      22             : 
      23             : #include "lib/code_generation.h"
      24             : #include "lib/debug.h"
      25             : #include "simulation2/helpers/Grid.h"
      26             : #include "simulation2/helpers/PathGoal.h"
      27             : #include "simulation2/helpers/Position.h"
      28             : #include "simulation2/helpers/PriorityQueue.h"
      29             : 
      30             : #include <atomic>
      31             : #include <map>
      32             : #include <memory>
      33             : #include <vector>
      34             : 
      35             : /**
      36             :  * Represents the 2D coordinates of a tile.
      37             :  * The i/j components are packed into a single std::uint32_t, since we usually use these
      38             :  * objects for equality comparisons and the VC2010 optimizer doesn't seem to automatically
      39             :  * compare two std::uint16_ts in a single operation.
      40             :  * TODO: maybe VC2012 will?
      41             :  */
      42             : struct TileID
      43             : {
      44             :     TileID() { }
      45             : 
      46        9549 :     TileID(std::uint16_t i, std::uint16_t j) : data((i << 16) | j) { }
      47             : 
      48           0 :     bool operator==(const TileID& b) const
      49             :     {
      50           0 :         return data == b.data;
      51             :     }
      52             : 
      53             :     /// Returns lexicographic order over (i,j)
      54        1848 :     bool operator<(const TileID& b) const
      55             :     {
      56        1848 :         return data < b.data;
      57             :     }
      58             : 
      59        2851 :     std::uint16_t i() const { return data >> 16; }
      60        2851 :     std::uint16_t j() const { return data & 0xFFFF; }
      61             : 
      62             : private:
      63             :     std::uint32_t data;
      64             : };
      65             : 
      66             : /**
      67             :  * Tile data for A* computation.
      68             :  * (We store an array of one of these per terrain tile, so it ought to be optimised for size)
      69             :  */
      70      524800 : struct PathfindTile
      71             : {
      72             : public:
      73             :     enum {
      74             :         STATUS_UNEXPLORED = 0,
      75             :         STATUS_OPEN = 1,
      76             :         STATUS_CLOSED = 2
      77             :     };
      78             : 
      79        8596 :     bool IsUnexplored() const { return GetStatus() == STATUS_UNEXPLORED; }
      80           0 :     bool IsOpen() const { return GetStatus() == STATUS_OPEN; }
      81           0 :     bool IsClosed() const { return GetStatus() == STATUS_CLOSED; }
      82        8596 :     void SetStatusOpen() { SetStatus(STATUS_OPEN); }
      83        2852 :     void SetStatusClosed() { SetStatus(STATUS_CLOSED); }
      84             : 
      85             :     // Get pi,pj coords of predecessor to this tile on best path, given i,j coords of this tile
      86        1928 :     inline int GetPredI(int i) const { return i + GetPredDI(); }
      87        1928 :     inline int GetPredJ(int j) const { return j + GetPredDJ(); }
      88             : 
      89        1902 :     inline PathCost GetCost() const { return g; }
      90        9550 :     inline void SetCost(PathCost cost) { g = cost; }
      91             : 
      92             : private:
      93             :     PathCost g; // cost to reach this tile
      94             :     std::uint32_t data; // 2-bit status; 15-bit PredI; 15-bit PredJ; packed for storage efficiency
      95             : 
      96             : public:
      97        8596 :     inline std::uint8_t GetStatus() const
      98             :     {
      99        8596 :         return data & 3;
     100             :     }
     101             : 
     102        3806 :     inline void SetStatus(std::uint8_t s)
     103             :     {
     104        3806 :         ASSERT(s < 4);
     105        3806 :         data &= ~3;
     106        3806 :         data |= (s & 3);
     107             :     }
     108             : 
     109        3830 :     int GetPredDI() const
     110             :     {
     111        3830 :         return static_cast<std::int32_t>(data) >> 17;
     112             :     }
     113             : 
     114        3830 :     int GetPredDJ() const
     115             :     {
     116        3830 :         return (static_cast<std::int32_t>(data) << 15) >> 17;
     117             :     }
     118             : 
     119             :     // Set the pi,pj coords of predecessor, given i,j coords of this tile
     120        9550 :     inline void SetPred(int pi, int pj, int i, int j)
     121             :     {
     122        9550 :         int di = pi - i;
     123        9550 :         int dj = pj - j;
     124        9550 :         ASSERT(-16384 <= di && di < 16384);
     125        9550 :         ASSERT(-16384 <= dj && dj < 16384);
     126        9550 :         data &= 3;
     127         954 :         data |= ((static_cast<std::uint32_t>(di) & 0x7FFF) << 17) |
     128        8596 :             ((static_cast<std::uint32_t>(dj) & 0x7FFF) << 2);
     129             :     }
     130             : };
     131             : 
     132             : struct CircularRegion
     133             : {
     134             :     CircularRegion(entity_pos_t x, entity_pos_t z, entity_pos_t r) : x(x), z(z), r(r) {}
     135             :     entity_pos_t x, z, r;
     136             : };
     137             : 
     138             : typedef PriorityQueueHeap<TileID, PathCost, PathCost> PriorityQueue;
     139             : typedef SparseGrid<PathfindTile> PathfindTileGrid;
     140             : 
     141             : class JumpPointCache;
     142             : 
     143        1907 : struct PathfinderState
     144             : {
     145             :     std::uint32_t steps; // number of algorithm iterations
     146             : 
     147             :     PathGoal goal;
     148             : 
     149             :     std::uint16_t iGoal, jGoal; // goal tile
     150             : 
     151             :     pass_class_t passClass;
     152             : 
     153             :     PriorityQueue open;
     154             :     // (there's no explicit closed list; it's encoded in PathfindTile)
     155             : 
     156             :     PathfindTileGrid* tiles;
     157             :     Grid<NavcellData>* terrain;
     158             : 
     159             :     PathCost hBest; // heuristic of closest discovered tile to goal
     160             :     std::uint16_t iBest, jBest; // closest tile
     161             : 
     162             :     const JumpPointCache* jpc;
     163             : };
     164             : 
     165             : class TerrainTextureOverlay;
     166             : 
     167             : class HierarchicalPathfinder;
     168             : 
     169             : class LongPathfinder
     170             : {
     171             : public:
     172             :     LongPathfinder();
     173             :     ~LongPathfinder();
     174             : 
     175             :     void SetDebugOverlay(bool enabled);
     176             : 
     177         954 :     void SetDebugPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass)
     178             :     {
     179         954 :         if (!m_Debug.Overlay)
     180             :             return;
     181             : 
     182           0 :         SAFE_DELETE(m_Debug.Grid);
     183           0 :         delete m_Debug.Path;
     184           0 :         m_Debug.Path = new WaypointPath();
     185           0 :         ComputePath(hierPath, x0, z0, goal, passClass, *m_Debug.Path);
     186           0 :         m_Debug.PassClass = passClass;
     187             :     }
     188             : 
     189           9 :     void Reload(Grid<NavcellData>* passabilityGrid)
     190             :     {
     191           9 :         m_Grid = passabilityGrid;
     192           9 :         ASSERT(passabilityGrid->m_H == passabilityGrid->m_W);
     193           9 :         m_GridSize = passabilityGrid->m_W;
     194             : 
     195           9 :         m_JumpPointCache.clear();
     196             :     }
     197             : 
     198           0 :     void Update(Grid<NavcellData>* passabilityGrid)
     199             :     {
     200           0 :         m_Grid = passabilityGrid;
     201           0 :         ASSERT(passabilityGrid->m_H == passabilityGrid->m_W);
     202           0 :         ASSERT(m_GridSize == passabilityGrid->m_H);
     203             : 
     204           0 :         m_JumpPointCache.clear();
     205             :     }
     206             : 
     207             :     /**
     208             :      * Compute a tile-based path from the given point to the goal, and return the set of waypoints.
     209             :      * The waypoints correspond to the centers of horizontally/vertically adjacent tiles
     210             :      * along the path.
     211             :      */
     212             :     void ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal,
     213             :         pass_class_t passClass, WaypointPath& path) const;
     214             : 
     215             :     /**
     216             :      * Compute a tile-based path from the given point to the goal, excluding the regions
     217             :      * specified in excludedRegions (which are treated as impassable) and return the set of waypoints.
     218             :      * The waypoints correspond to the centers of horizontally/vertically adjacent tiles
     219             :      * along the path.
     220             :      */
     221             :     void ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal,
     222             :         pass_class_t passClass, std::vector<CircularRegion> excludedRegions, WaypointPath& path);
     223             : 
     224           0 :     void GetDebugData(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const
     225             :     {
     226           0 :         GetDebugDataJPS(steps, time, grid);
     227           0 :     }
     228             : 
     229             :     Grid<NavcellData>* m_Grid;
     230             :     std::uint16_t m_GridSize;
     231             : 
     232             :     // Debugging - output from last pathfind operation.
     233          11 :     struct Debug
     234             :     {
     235             :         /**
     236             :          *  Atomic - used to toggle debugging.
     237             :          *
     238             :          * Terrain overlay for pathfinder debugging.
     239             :          * Renders a representation of the most recent pathfinding operation.
     240             :          */
     241             :         std::atomic<TerrainTextureOverlay*> Overlay = nullptr;
     242             :         // Mutable - set by ComputeJPSPath (thus possibly from different threads).
     243             :         // Synchronized via mutex if necessary.
     244             :         mutable PathfindTileGrid* Grid = nullptr;
     245             :         mutable std::uint32_t Steps;
     246             :         mutable double Time;
     247             :         mutable PathGoal Goal;
     248             : 
     249             :         WaypointPath* Path = nullptr;
     250             :         pass_class_t PassClass;
     251             :     } m_Debug;
     252             : 
     253             : private:
     254             :     PathCost CalculateHeuristic(int i, int j, int iGoal, int jGoal) const;
     255             :     void ProcessNeighbour(int pi, int pj, int i, int j, PathCost pg, PathfinderState& state) const;
     256             : 
     257             :     /**
     258             :      * JPS algorithm helper functions
     259             :      * @param detectGoal is not used if m_UseJPSCache is true
     260             :      */
     261             :     void AddJumpedHoriz(int i, int j, int di, PathCost g, PathfinderState& state, bool detectGoal) const;
     262             :     int HasJumpedHoriz(int i, int j, int di, PathfinderState& state, bool detectGoal) const;
     263             :     void AddJumpedVert(int i, int j, int dj, PathCost g, PathfinderState& state, bool detectGoal) const;
     264             :     int HasJumpedVert(int i, int j, int dj, PathfinderState& state, bool detectGoal) const;
     265             :     void AddJumpedDiag(int i, int j, int di, int dj, PathCost g, PathfinderState& state) const;
     266             : 
     267             :     /**
     268             :      * See LongPathfinder.cpp for implementation details
     269             :      * TODO: cleanup documentation
     270             :      */
     271             :     void ComputeJPSPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal, pass_class_t passClass, WaypointPath& path) const;
     272             :     void GetDebugDataJPS(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const;
     273             : 
     274             :     // Helper functions for ComputePath
     275             : 
     276             :     /**
     277             :      * Given a path with an arbitrary collection of waypoints, updates the
     278             :      * waypoints to be nicer.
     279             :      * If @param maxDist is non-zero, path waypoints will be espaced by at most @param maxDist.
     280             :      * In that case the distance between (x0, z0) and the first waypoint will also be made less than maxDist.
     281             :      */
     282             :     void ImprovePathWaypoints(WaypointPath& path, pass_class_t passClass, entity_pos_t maxDist, entity_pos_t x0, entity_pos_t z0) const;
     283             : 
     284             :     /**
     285             :      * Generate a passability map, stored in the 16th bit of navcells, based on passClass,
     286             :      * but with a set of impassable circular regions.
     287             :      */
     288             :     void GenerateSpecialMap(pass_class_t passClass, std::vector<CircularRegion> excludedRegions);
     289             : 
     290             :     bool m_UseJPSCache;
     291             :     // Mutable may be used here as caching does not change the external const-ness of the Long Range pathfinder.
     292             :     // This is thread-safe as it is order independent (no change in the output of the function for a given set of params).
     293             :     // Obviously, this means that the cache should actually be a cache and not return different results
     294             :     // from what would happen if things hadn't been cached.
     295             :     mutable std::map<pass_class_t, std::shared_ptr<JumpPointCache>> m_JumpPointCache;
     296             : };
     297             : 
     298             : #endif // INCLUDED_LONGPATHFINDER

Generated by: LCOV version 1.16