Commit Graph

45 Commits

Author SHA1 Message Date
RoosterDragon
6c96405ab2 Fix CS1573 2023-02-24 22:00:25 +02:00
abcdefg30
5bf7fe852c Remove the copyright year numbers 2023-01-11 11:58:54 +02:00
RoosterDragon
d8ebb96077 HPF handles searches from unreachable source cells into cut off areas.
If a path search is performed by the HierarchicalPathFinder when the source cell is unreachable location, a path is still allowed and starts from one of the cells adjacent to the location. If moving into one of these cells results in the actor moving into an isolated area that cannot reach the target this would previously crash as no abstract path could be found. Now we handle such locations by giving them a unreachable cost so the path search will not attempt to explore them.

Imagine a map split into two by a one tile wide line of impassable cliffs. If an actor is on top of these cliffs it is allowed to path because it can "jump off" the cliff and move into the cell immediately either side of it. However it is important which side it chooses to jump into, as one it has moved off the cliff it loses access to the other side. The previous error came about because the path might try and search on the side that couldn't reach the target location. Now we avoid that being considered.
2022-12-20 09:47:24 +13:00
RoosterDragon
a85ac26367 Pathing considers reachability of source cells consistently.
Using the local pathfinder, you could not find a path to an unreachable destination cell, but it was possible to find a path from an unreachable source cell if there was a reachable cells adjacent to it.

The hierarchical pathfinder did not have this behaviour and considering an unreachable source cell to block attempts to find a path.

Now, we unify the pathfinders to use a consistent behaviour, allowing paths from unreachable source cells to be found.
2022-11-13 19:59:36 +01:00
RoosterDragon
7e67889294 Fix a crash when trying to pathfind from unusable custom movement layers.
If a path search is attempted from a location outside the map, then PathSearch will filter these out to prevent any crashes. The path search will result in no path. However if the location is within the map but on a custom movement layer that the locomotor cannot use, this currently crashes. To fix this we apply a similar filtering logic to ignore any source locations that cannot be used, and so the path search will result in no path for these as well.
2022-09-10 15:24:25 +02:00
RoosterDragon
2599cb26d8 Allow custom cost to exclude source locations in path searches.
During the refactoring to introduce HierarchicalPathFinder, custom costs were no longer applied to source locations. The logic being that if we are already in the source location, then there should be no cost added to it to get there - we are already there!

Path searches support the ability to go from multiple sources to a single target, but the reverse is not supported. Some callers that require a search from a single source to one of multiple targets perform their search in reverse, swapping the source and targets so they can run the search, then reversing the path they are given so things are the correct way around again. For callers that also use a custom cost like the harvester code that do this in order to find free refineries, they might want the custom cost to be applied to the source location. The harvester code uses this to filter out overloaded refineries. It wants to search from a harvester to multiple refineries, and thus reverses this in order to perform the path search. Without the custom cost being applied to the "source" locations, this filtering logic never gets applied.

To fix this, we now apply the custom cost to source locations. If the custom cost provides an invalid path, then the source location is excluded entirely. Although this seems unintuitive on its own, this allows searches done "in reverse" to work again.
2022-08-13 11:58:45 +03:00
RoosterDragon
df858e06d6 Fix HierarchicalPathFinder failing to consider multiple source locations.
When asked to find a path from multiple source locations, the abstract search is used to determine which source locations are viable. Source locations that cannot be reached on the abstract graph are excluded from the local path search. As we know the locations are unreachable, this prevents the local path search from expanding over the entire search space in an attempt to find these unreachable locations, preventing wasted effort.

In order to determine these reachable locations, the abstract search is expanded successively trying to reach each source location each time. However, this failed to account for a property of the ExpandToTarget for which a comment is now added. If the location was found previously, then expanding to try and find it again will fail. If the source locations were close together, it was likely that the initial expansions of the search space would have included them, and thus they would not be found on a later expansion. This would mean these locations would incorrectly be thought unreachable.

To fix this, we check if the location has already been explored (has CellStatus.Closed in the graph). If so we can check the cost to determine if it is reachable.
2022-08-13 11:58:45 +03:00
RoosterDragon
93998dc4a7 Add a PathFinderOverlay to visualize path searches.
Activated with the '/path-debug' chat command, this displays the explored search space and costs when searching for paths. It supports custom movement layers, bi-directional searches as well as visualizing searches over the abstract graph of the HierarchicalPathFinder. The most recent search among selected units is shown.
2022-08-03 23:12:42 +02:00
RoosterDragon
5a8f91aa21 Add a hierarchical path finder to improve pathfinding performance.
Replaces the existing bi-directional search between points used by the pathfinder with a guided hierarchical search. The old search was a standard A* search with a heuristic of advancing in straight line towards the target. This heuristic performs well if a mostly direct path to the target exists, it performs poorly it the path has to navigate around blockages in the terrain. The hierarchical path finder maintains a simplified, abstract graph. When a path search is performed it uses this abstract graph to inform the heuristic. Instead of moving blindly towards the target, it will instead steer around major obstacles, almost as if it had been provided a map which ensures it can move in roughly the right direction. This allows it to explore less of the area overall, improving performance.

When a path needs to steer around terrain on the map, the hierarchical path finder is able to greatly improve on the previous performance. When a path is able to proceed in a straight line, no performance benefit will be seen. If the path needs to steer around actors on the map instead of terrain (e.g. trees, buildings, units) then the same poor pathfinding performance as before will be observed.
2022-08-03 23:12:42 +02:00
Vapre
8c042a243e PathSearch, make TargetPredicate a readonly private field. 2022-07-04 20:34:23 +02:00
RoosterDragon
c9ee902510 Fix issues preventing suboptimal path searches.
Two different issues were causing a path search to not explore cells in order of the cheapest estimated route first. This meant the search could sometimes miss a cheaper route and return a suboptimal path.

- PriorityQueue had a bug which would cause it to not check some elements when restoring the heap property of its internal data structure. Failing to do this would invalidate the heap property, meaning it would not longer return the items in correct priority order. Additional tests ensure this is covered.
- When a path search encountered the same cell again with a lower cost, it would not update the priority queue with the new cost. This meant the cell was not explored early enough as it was in the queue with its original, higher cost. Exploring other paths might close off surrounding cells, preventing the cell with the lower cost from progressing. Instead we now add a duplicate with the lower cost to ensure it gets explored at the right time. We remove the duplicate with the higher cost in CanExpand by checking for already Closed cells.
2022-06-07 15:47:02 +02:00
abcdefg30
6a31b1f9f3 Update the copyright header year 2022-05-28 00:35:10 -05:00
RoosterDragon
e22b6de4e8 Rename PathGraph to MapPathGraph.
Move PathCostForInvalidPath and MovementCostForUnreachableCell constants into a new static class, PathGraph.
2022-04-27 23:19:59 +02:00
RoosterDragon
d2935672ca Fix the shape of the IPathFinder interface, ensure all path searches use it.
Some path searches, using PathSearch, were created directly at the callsite rather than using the pathfinder trait. This means some searches did not not benefit from the performance checks done in the pathfinder trait. It also means the pathfinder trait was not responsible for all pathing done in the game. Fix this with the following changes:
- Create a sensible shape for the IPathFinder interface and promote it to a trait interface, allowing theoretical replacements of the implementation. Ensure none of the concrete classes in OpenRA.Mods.Common.Pathfinder are exposed in the interface to ensure this is possible.
- Update the PathFinder class to implement the interface, and update several callsites manually running pathfinding code to instead call the IPathFinder interface.
- Overall, this allows any implementation of the IPathFinder interface to intercept and control all path searching performed by the game. Previously some searches would not have used it, and no alternate implementations were possible as the existing implementation was hardcoded into the interface shape.

Additionally:
- Move the responsibility of finding paths on completed path searches from pathfinder to path search, which is a more sensible location.
- Clean up the pathfinder pre-search optimizations.
2022-04-18 11:18:43 +01:00
RoosterDragon
d67f696bd0 Move BlockedByActor, IPositionableInfo, IPositionable to Mods.Common.
Actor previously cached targetable locations for static actors as an optimization. As we can no longer reference the IPositionable interface, move this optimization to HitShape instead. Although we lose some of the efficiency of caching the final result on the actor, we gain some by allowing HitShape to cache the results as long as they have not changed. So instead of being limited to static actors, we can extend the caching to currently stationary actor.
2022-02-11 23:35:08 +01:00
RoosterDragon
6dc189b7d1 Rearrange various API surfaces related to pathfinding.
The existing APIs surfaces for pathfinding are in a wonky shape. We rearrange various responsibilities to better locations and simplify some abstractions that aren't providing value.

- IPathSearch, BasePathSearch and PathSearch are combined into only PathSearch. Its role is now to run a search space over a graph, maintaining the open queue and evaluating the provided heuristic function. The builder-like methods (WithHeuristic, Reverse, FromPoint, etc) are removed in favour of optional parameters in static creation methods. This removes confusion between the builder-aspect and the search function itself. It also becomes responsible for applying the heuristic weight to the heuristic. This fixes an issue where an externally provided heuristic ignored the weighting adjustment, as previously the weight was baked into the default heuristic only.
- Reduce the IGraph interface to the concepts of nodes and edges. Make it non-generic as it is specifically for pathfinding, and rename to IPathGraph accordingly. This is sufficient for a PathSearch to perform a search over any given IGraph. The various customization options are concrete properties of PathGraph only.
- PathFinder does not need to deal with disposal of the search/graph, that is the caller's responsibility.
- Remove CustomBlock from PathGraph as it was unused.
- Remove FindUnitPathToRange as it was unused.
- Use PathFinder.NoPath as the single helper to represent no/empty paths.
2022-01-30 11:47:52 +01:00
penev92
ab09ce21b4 Changed code to use object initializers everywhere 2022-01-23 13:14:57 +01:00
penev92
2f6f214bac Removed a bunch of explicit access modifiers 2022-01-09 18:58:37 +01:00
RoosterDragon
8c627aa185 Clean up PathSearch
- Remove functionality for tracking cells considered during the search, as nothing relies on this.
- Rename various parameters in the expand function to closer match naming of fields used in CellInfo, intended to improve clarity.
2021-11-21 12:03:16 +01:00
RoosterDragon
290ed17c9d Adjust some naming and order of parameters in CellInfo
- Make Status the first field.
- Rename EstimatedTotal to EstimatedTotalCost to make it clearer it has the same unit as the CostSoFar field.
- Rename PreviousPos to PreviousNode as node terminology is a better match for usage.
2021-11-20 12:13:42 +01:00
RoosterDragon
19760b04bd Allow the default value of a CellInfo to be an Unvisited location.
In CellInfoLayerPool, instead of having to store a layer with the default values, we know we can just clear the pooled layer in order to reset it. This saves on memory, and also makes resetting marginally faster.

In PathSearch, we need to amend a check to ensure a cell info is not Unvisited before we check on its cost.
2021-10-23 15:43:47 +02:00
penev92
8ba6d13b2f Removed unused using directives 2021-10-15 13:12:33 +02:00
RoosterDragon
df9398a871 Use named pathfinding constants.
- Rename CostForInvalidCell to PathCostForInvalidPath
- Add MovementCostForUnreachableCell
- Update usages of int.MaxValue and short.Maxvalue to use named constants where relevant.
- Update costs on ICustomMovementLayer to return short, for consistency with costs from Locomotor.
- Rename some methods to distinguish between path/movement cost.
2021-10-10 17:09:38 +02:00
Andre Mohren
6810469634 Updated copyright years. 2021-06-29 18:33:21 -05:00
teinarss
4a1e4f3e16 Use expression body syntax 2021-03-07 13:00:52 +00:00
teinarss
19b02875c7 Use Tuple syntax 2020-08-15 10:37:10 +01:00
Andre Mohren
006a87692a Removed unused imports. 2020-07-28 18:22:51 +02:00
abcdefg30
23b3c237b7 Update the year numbers in all license headers to 2020 2020-01-05 17:00:34 +00:00
RoosterDragon
04912ea996 Expose a setting for Weighted A*
Replace Constants.CellCost and Constants.DiagonalCellCost with a dynamically calculated value based on the lowest cost terrain to traverse. Using a fixed value meant the pathfinder heuristics would be incorrect.

In the four default mods, the minimum cost is in fact 100, not 125. This increase would essentially allow the pathfinder to return suboptimal paths up to 25% longer in the worst case, but it would be quicker to do so.

This is exactly what Weighted A* does - overestimate the heuristic by some factor in order to speed up the search by checking fewer routes. This makes the heuristic inadmissible and it may now return suboptimal paths, but their worst case length is bounded by the weight. A weight of 125% will never produce paths more than 25% longer than the shortest, optimal, path.

We set the default weight to 25% to effectively maintain the existing, suboptimal, behaviour due to the choice of the old constant - in future it may prove a useful tuning knob for performance.
2019-11-15 13:05:41 +01:00
tovl
4a609bbee8 Allow units to give way when path is blocked by oncoming unit. 2019-09-15 17:51:34 +01:00
teinarss
2ddf9fa826 Using Locomotor instead of Info for pathfinding 2019-07-26 15:54:22 +02:00
abcdefg30
cadbd0d9ab Change the year number in all cs headers from 2018 to 2019 2019-01-26 23:15:21 +01:00
reaperrr
81343926b6 Split Locomotor trait from Mobile
Add GrantConditionOn*Layer traits

This allows to
- drop some booleans from Locomotor
- drop a good part of the subterranean- and jumpjet-specific code/hacks from Mobile
- grant more than 1 condition per layer type (via multiple traits)
- easily add more traits of this kind for other layers
2018-05-03 10:49:21 +02:00
Arular101
8a60918841 Update copyright notice year to 2018 2018-01-17 00:47:34 +01:00
Taryn Hill
43317e0f5d Update copyright notice year to 2017 2016-12-31 23:46:13 -06:00
Paul Chote
e71225496b Clarify GPL version. 2016-02-21 16:30:48 +00:00
Paul Chote
b396965fd9 Update licence header year. 2016-02-21 16:27:31 +00:00
RoosterDragon
b0619a3e25 Added comments in performance sensitive code. 2015-12-13 16:24:54 +00:00
RoosterDragon
519be4374c Fixed pooling of layers used for pathfinding.
The previous implementation:
- Was failing to dispose of pooled layers.
- Was using a finalizer to allow undisposed layers to be reused.

This means all pooled layers are kept alive indefinitely until the map changes. If the finalizer is slow for any reason then the pathfiinder will allocate new layers when the pool runs out. Since these new layers are eventually stuffed back into the pool when the finalizer does run, this can theoretically leak unbounded memory until the pool goes out of scope. In practice it would leak tens of megabytes.

The new implementation ensures layers are disposed and pooled correctly to allow proper memory reuse. It also introduces some safeguards against memory leaks:
- A cap is set on the number of pooled layers. If more concurrent layers are needed than this, then the excess layers will not be pooled but instead be allowed to be garbage collected.
- No finalizer. An implementation that fails to call dispose simply allows the layer to be garbage collected instead.
2015-09-16 21:25:46 +01:00
RoosterDragon
ac55c5bf09 Fix pathfinding using PriorityQueue incorrectly.
By providing a comparer that could change over time (as estimated costs on the graph were updated), this meant the priority queue could have its heap property invalidated and thus not maintain a correct ordering. Instead we store elements into the queue with their estimations at the time. This preserves the heap property and thus ensures the queue returns properly ordered results, although it may contain out of date estimations.

This also improves performance. The fixed comparer need not perform expensive lookups into the graph, but can instead use the readily available value. This speeds up adds and removes on the queue significantly.
2015-09-01 17:29:36 +01:00
David Jiménez
787609d51e Improved the performance and intelligence of resource harvesting by
refactoring the Harvesters' pathfinding. Now they in first place assess
which is the closest resource inside their search area and then a path is
calculated

Changed the way harvesters find resources by always trying to find the
closest resource to their refinery.

Changed the strategy of finding to find resources in Annulus.
2015-07-22 02:31:26 +02:00
David Jiménez
044b51742f Remove plumbing for trait unit tests. 2015-05-01 16:24:14 +12:00
David Jiménez
6d96a43341 Fixes #7955. Improves pathfinder performance a bit. 2015-04-15 23:43:14 +02:00
David Jiménez
ea32c20450 Changed the harvester heuristic so that now takes into account the distance from the initial search location. This makes harvesters somewhat more "intelligent" and gather nearer resources. Also solved several regressions introduced in the recent changes in the Pathfinder 2015-03-12 12:28:34 +01:00
David Jiménez
54ae572303 - 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
2015-03-03 20:11:11 +01:00