- Introduced Unit Testing capabilities to the PathFinder trait and algorithm.

Introduced also a small Unit test project to prove it.

- Separated caching capabilities from PathFinder class to increase cohesion and maintainability.
Refactored the pathfinding algorithm by extracting methods based on responsibilities like
calculating costs and reordering functions. These changes should provide a in average a small increase in
pathfinding performance and maintainability.

- Optimized the pathfinder algorithm to reuse calculations like the
MovementCost and heuristics.

- Introduced base classes, IPathSearch and IPriorityQueue interfaces,
and restructured code to ease readability and testability

- Renamed the PathFinder related classes to more appropriate names. Made the
traits rely on the interface IPathfinder instead of concrete PathFinder
implementation.

- Massive performance improvements

- Solved error with harvesters' Heuristic

- Updated the heuristic to ease redability and adjustability. D can be
adjusted to offer best paths by decreasing and more performance by
increasing it

- Refactored the CellLayer<CellInfo> creation in its own Singleton class

- Extracted the graph abstraction onto an IGraph interface, making the
Pathfinder agnostic to the definition of world and terrain. This
abstraction can help in the future to be able to cache graphs for similar
classes and their costs, speeding up the pathfinder and being able to feed
the A* algorithm with different types of graphs like Hierarchical graphs
This commit is contained in:
David Jiménez
2015-02-20 08:59:07 +01:00
parent 8659a3e71e
commit 54ae572303
28 changed files with 1727 additions and 667 deletions

View File

@@ -12,9 +12,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using OpenRA;
using OpenRA.Primitives;
using OpenRA.Support;
using OpenRA.Mods.Common.Pathfinder;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
@@ -22,222 +20,221 @@ namespace OpenRA.Mods.Common.Traits
[Desc("Calculates routes for mobile units based on the A* search algorithm.", " Attach this to the world actor.")]
public class PathFinderInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new PathFinder(init.World); }
public object Create(ActorInitializer init)
{
return new PathFinderCacheDecorator(new PathFinder(init.World), new PathCacheStorage(init.World));
}
}
public class PathFinder
public interface IPathFinder
{
/// <summary>
/// Calculates a path for the actor from source to destination
/// </summary>
/// <returns>A path from start to target</returns>
List<CPos> FindUnitPath(CPos source, CPos target, IActor self);
List<CPos> FindUnitPathToRange(CPos source, SubCell srcSub, WPos target, WRange range, IActor self);
/// <summary>
/// Calculates a path given a search specification
/// </summary>
List<CPos> FindPath(IPathSearch search);
/// <summary>
/// Calculates a path given two search specifications, and
/// then returns a path when both search intersect each other
/// TODO: This should eventually disappear
/// </summary>
List<CPos> FindBidiPath(IPathSearch fromSrc, IPathSearch fromDest);
}
public class PathFinder : IPathFinder
{
const int MaxPathAge = 50; /* x 40ms ticks */
static readonly List<CPos> EmptyPath = new List<CPos>(0);
readonly IWorld world;
readonly World world;
public PathFinder(World world) { this.world = world; }
class CachedPath
public PathFinder(IWorld world)
{
public CPos From;
public CPos To;
public List<CPos> Result;
public int Tick;
public Actor Actor;
this.world = world;
}
List<CachedPath> cachedPaths = new List<CachedPath>();
public List<CPos> FindUnitPath(CPos from, CPos target, Actor self)
public List<CPos> FindUnitPath(CPos source, CPos target, IActor self)
{
using (new PerfSample("Pathfinder"))
var mi = self.Info.Traits.Get<IMobileInfo>();
// If a water-land transition is required, bail early
var domainIndex = world.WorldActor.TraitOrDefault<DomainIndex>();
if (domainIndex != null)
{
var cached = cachedPaths.FirstOrDefault(p => p.From == from && p.To == target && p.Actor == self);
if (cached != null)
{
Log.Write("debug", "Actor {0} asked for a path from {1} tick(s) ago", self.ActorID, world.WorldTick - cached.Tick);
if (world.WorldTick - cached.Tick > MaxPathAge)
cachedPaths.Remove(cached);
return new List<CPos>(cached.Result);
}
var mi = self.Info.Traits.Get<MobileInfo>();
// If a water-land transition is required, bail early
var domainIndex = self.World.WorldActor.TraitOrDefault<DomainIndex>();
if (domainIndex != null)
{
var passable = mi.GetMovementClass(world.TileSet);
if (!domainIndex.IsPassable(from, target, (uint)passable))
return EmptyPath;
}
var fromPoint = PathSearch.FromPoint(world, mi, self, target, from, true)
.WithIgnoredActor(self);
var fromPointReverse = PathSearch.FromPoint(world, mi, self, from, target, true)
.WithIgnoredActor(self)
.Reverse();
var pb = FindBidiPath(
fromPoint,
fromPointReverse);
CheckSanePath2(pb, from, target);
cachedPaths.RemoveAll(p => world.WorldTick - p.Tick > MaxPathAge);
cachedPaths.Add(new CachedPath { From = from, To = target, Actor = self, Result = pb, Tick = world.WorldTick });
return new List<CPos>(pb);
var passable = mi.GetMovementClass(world.TileSet);
if (!domainIndex.IsPassable(source, target, (uint)passable))
return EmptyPath;
}
var pb = FindBidiPath(
PathSearch.FromPoint(world, mi, self, target, source, true),
PathSearch.FromPoint(world, mi, self, source, target, true).Reverse());
CheckSanePath2(pb, source, target);
return pb;
}
public List<CPos> FindUnitPathToRange(CPos src, SubCell srcSub, WPos target, WRange range, Actor self)
public List<CPos> FindUnitPathToRange(CPos source, SubCell srcSub, WPos target, WRange range, IActor self)
{
using (new PerfSample("Pathfinder"))
var mi = self.Info.Traits.Get<MobileInfo>();
var targetCell = world.Map.CellContaining(target);
var rangeSquared = range.Range * range.Range;
// Correct for SubCell offset
target -= world.Map.OffsetOfSubCell(srcSub);
// Select only the tiles that are within range from the requested SubCell
// This assumes that the SubCell does not change during the path traversal
var tilesInRange = world.Map.FindTilesInCircle(targetCell, range.Range / 1024 + 1)
.Where(t => (world.Map.CenterOfCell(t) - target).LengthSquared <= rangeSquared
&& mi.CanEnterCell(self.World as World, self as Actor, t));
// See if there is any cell within range that does not involve a cross-domain request
// Really, we only need to check the circle perimeter, but it's not clear that would be a performance win
var domainIndex = world.WorldActor.TraitOrDefault<DomainIndex>();
if (domainIndex != null)
{
var mi = self.Info.Traits.Get<MobileInfo>();
var targetCell = self.World.Map.CellContaining(target);
var rangeSquared = range.Range * range.Range;
var passable = mi.GetMovementClass(world.TileSet);
tilesInRange = new List<CPos>(tilesInRange.Where(t => domainIndex.IsPassable(source, t, (uint)passable)));
if (!tilesInRange.Any())
return EmptyPath;
}
// Correct for SubCell offset
target -= self.World.Map.OffsetOfSubCell(srcSub);
var path = FindBidiPath(
PathSearch.FromPoints(world, mi, self, tilesInRange, source, true),
PathSearch.FromPoint(world, mi, self, source, targetCell, true).Reverse());
// Select only the tiles that are within range from the requested SubCell
// This assumes that the SubCell does not change during the path traversal
var tilesInRange = world.Map.FindTilesInCircle(targetCell, range.Range / 1024 + 1)
.Where(t => (world.Map.CenterOfCell(t) - target).LengthSquared <= rangeSquared &&
mi.CanEnterCell(self.World, self, t));
return path;
}
// See if there is any cell within range that does not involve a cross-domain request
// Really, we only need to check the circle perimeter, but it's not clear that would be a performance win
var domainIndex = self.World.WorldActor.TraitOrDefault<DomainIndex>();
if (domainIndex != null)
public List<CPos> FindPath(IPathSearch search)
{
var dbg = world.WorldActor.TraitOrDefault<PathfinderDebugOverlay>();
if (dbg != null && dbg.Visible)
search.Debug = true;
List<CPos> path = null;
while (!search.OpenQueue.Empty)
{
var p = search.Expand();
if (search.IsTarget(p))
{
var passable = mi.GetMovementClass(world.TileSet);
tilesInRange = new List<CPos>(tilesInRange.Where(t => domainIndex.IsPassable(src, t, (uint)passable)));
if (!tilesInRange.Any())
return EmptyPath;
path = MakePath(search.Graph, p);
break;
}
}
var path = FindBidiPath(
PathSearch.FromPoints(world, mi, self, tilesInRange, src, true),
PathSearch.FromPoint(world, mi, self, src, targetCell, true).Reverse());
if (dbg != null && dbg.Visible)
dbg.AddLayer(search.Considered, search.MaxCost, search.Owner);
search.Graph.Dispose();
if (path != null)
return path;
}
// no path exists
return EmptyPath;
}
public List<CPos> FindPath(PathSearch search)
// Searches from both ends toward each other. This is used to prevent blockings in case we find
// units in the middle of the path that prevent us to continue.
public List<CPos> FindBidiPath(IPathSearch fromSrc, IPathSearch fromDest)
{
using (new PerfSample("Pathfinder"))
List<CPos> path = null;
var dbg = world.WorldActor.TraitOrDefault<PathfinderDebugOverlay>();
if (dbg != null && dbg.Visible)
{
using (search)
fromSrc.Debug = true;
fromDest.Debug = true;
}
while (!fromSrc.OpenQueue.Empty && !fromDest.OpenQueue.Empty)
{
// make some progress on the first search
var p = fromSrc.Expand();
if (fromDest.Graph[p].Status == CellStatus.Closed &&
fromDest.Graph[p].CostSoFar < int.MaxValue)
{
List<CPos> path = null;
while (!search.Queue.Empty)
{
var p = search.Expand(world);
if (search.Heuristic(p) == 0)
{
path = MakePath(search.CellInfo, p);
break;
}
}
var dbg = world.WorldActor.TraitOrDefault<PathfinderDebugOverlay>();
if (dbg != null)
dbg.AddLayer(search.Considered.Select(p => new Pair<CPos, int>(p, search.CellInfo[p].MinCost)), search.MaxCost, search.Owner);
if (path != null)
return path;
path = MakeBidiPath(fromSrc, fromDest, p);
break;
}
// no path exists
return EmptyPath;
// make some progress on the second search
var q = fromDest.Expand();
if (fromSrc.Graph[q].Status == CellStatus.Closed &&
fromSrc.Graph[q].CostSoFar < int.MaxValue)
{
path = MakeBidiPath(fromSrc, fromDest, q);
break;
}
}
if (dbg != null && dbg.Visible)
{
dbg.AddLayer(fromSrc.Considered, fromSrc.MaxCost, fromSrc.Owner);
dbg.AddLayer(fromDest.Considered, fromDest.MaxCost, fromDest.Owner);
}
fromSrc.Graph.Dispose();
fromDest.Graph.Dispose();
if (path != null)
return path;
return EmptyPath;
}
static List<CPos> MakePath(CellLayer<CellInfo> cellInfo, CPos destination)
// Build the path from the destination. When we find a node that has the same previous
// position than itself, that node is the source node.
static List<CPos> MakePath(IGraph<CellInfo> cellInfo, CPos destination)
{
var ret = new List<CPos>();
var pathNode = destination;
var currentNode = destination;
while (cellInfo[pathNode].Path != pathNode)
while (cellInfo[currentNode].PreviousPos != currentNode)
{
ret.Add(pathNode);
pathNode = cellInfo[pathNode].Path;
ret.Add(currentNode);
currentNode = cellInfo[currentNode].PreviousPos;
}
ret.Add(pathNode);
ret.Add(currentNode);
CheckSanePath(ret);
return ret;
}
// Searches from both ends toward each other
public List<CPos> FindBidiPath(PathSearch fromSrc, PathSearch fromDest)
static List<CPos> MakeBidiPath(IPathSearch a, IPathSearch b, CPos confluenceNode)
{
using (new PerfSample("Pathfinder"))
{
using (fromSrc)
using (fromDest)
{
List<CPos> path = null;
while (!fromSrc.Queue.Empty && !fromDest.Queue.Empty)
{
/* make some progress on the first search */
var p = fromSrc.Expand(world);
if (fromDest.CellInfo[p].Seen &&
fromDest.CellInfo[p].MinCost < float.PositiveInfinity)
{
path = MakeBidiPath(fromSrc, fromDest, p);
break;
}
/* make some progress on the second search */
var q = fromDest.Expand(world);
if (fromSrc.CellInfo[q].Seen &&
fromSrc.CellInfo[q].MinCost < float.PositiveInfinity)
{
path = MakeBidiPath(fromSrc, fromDest, q);
break;
}
}
var dbg = world.WorldActor.TraitOrDefault<PathfinderDebugOverlay>();
if (dbg != null)
{
dbg.AddLayer(fromSrc.Considered.Select(p => new Pair<CPos, int>(p, fromSrc.CellInfo[p].MinCost)), fromSrc.MaxCost, fromSrc.Owner);
dbg.AddLayer(fromDest.Considered.Select(p => new Pair<CPos, int>(p, fromDest.CellInfo[p].MinCost)), fromDest.MaxCost, fromDest.Owner);
}
if (path != null)
return path;
}
return EmptyPath;
}
}
static List<CPos> MakeBidiPath(PathSearch a, PathSearch b, CPos p)
{
var ca = a.CellInfo;
var cb = b.CellInfo;
var ca = a.Graph;
var cb = b.Graph;
var ret = new List<CPos>();
var q = p;
while (ca[q].Path != q)
var q = confluenceNode;
while (ca[q].PreviousPos != q)
{
ret.Add(q);
q = ca[q].Path;
q = ca[q].PreviousPos;
}
ret.Add(q);
ret.Reverse();
q = p;
while (cb[q].Path != q)
q = confluenceNode;
while (cb[q].PreviousPos != q)
{
q = cb[q].Path;
q = cb[q].PreviousPos;
ret.Add(q);
}
@@ -246,22 +243,22 @@ namespace OpenRA.Mods.Common.Traits
}
[Conditional("SANITY_CHECKS")]
static void CheckSanePath(List<CPos> path)
static void CheckSanePath(IList<CPos> path)
{
if (path.Count == 0)
return;
var prev = path[0];
for (var i = 0; i < path.Count; i++)
foreach (var cell in path)
{
var d = path[i] - prev;
var d = cell - prev;
if (Math.Abs(d.X) > 1 || Math.Abs(d.Y) > 1)
throw new InvalidOperationException("(PathFinder) path sanity check failed");
prev = path[i];
prev = cell;
}
}
[Conditional("SANITY_CHECKS")]
static void CheckSanePath2(List<CPos> path, CPos src, CPos dest)
static void CheckSanePath2(IList<CPos> path, CPos src, CPos dest)
{
if (path.Count == 0)
return;
@@ -272,35 +269,4 @@ namespace OpenRA.Mods.Common.Traits
throw new InvalidOperationException("(PathFinder) sanity check failed: doesn't come from src");
}
}
public struct CellInfo
{
public int MinCost;
public CPos Path;
public bool Seen;
public CellInfo(int minCost, CPos path, bool seen)
{
MinCost = minCost;
Path = path;
Seen = seen;
}
}
public struct PathDistance : IComparable<PathDistance>
{
public readonly int EstTotal;
public readonly CPos Location;
public PathDistance(int estTotal, CPos location)
{
EstTotal = estTotal;
Location = location;
}
public int CompareTo(PathDistance other)
{
return Math.Sign(EstTotal - other.EstTotal);
}
}
}