public void FindPath_ThrowsIfGraphNotBuilt() { var solver = new PathSolver <Point, PathTestOption>(_testMap); PathResult <Point> pathResult = null; Assert.ThrowsException <PathfindingException>(() => pathResult = solver.FindPath(_startPt, _reachableEndPt, PathTestOption.Normal)); }
public void TestViablePath() { var roads = new TestRoads(); Assert.AreEqual(1, roads.seg_0_0_10_0.AIRoutes.Length); Assert.AreEqual(1, roads.seg_40_0_50_0.AIRoutes.Length); Assert.AreEqual(3, roads.seg_0_0_10_0.AIRoutes[0].Paths.Length); Assert.AreEqual(3, roads.seg_40_0_50_0.AIRoutes[0].Paths.Length); var routeSolver = new RouteSolver(roads.seg_0_0_10_0.AIRoutes, roads.seg_40_0_50_0.AIRoutes); while (!routeSolver.IsComplete) { routeSolver.Iterate(); } Assert.IsTrue(routeSolver.IsSuccess); var route = routeSolver.Solution; var pathSolver = new PathSolver(roads.seg_0_0_10_0.AIRoutes[0].Paths, roads.seg_40_0_50_0.AIRoutes[0].Paths, route); while (!pathSolver.IsComplete) { pathSolver.Iterate(); } Assert.IsTrue(pathSolver.IsSuccess); }
public void FindPathManyRooms() { Room[] rooms = LoadFromFile(); PrintWorld(rooms, Path <TileNode> .EMPTY); TileNode start = null, goal = null; foreach (Room r in rooms) { GameTypes.IntPoint localStart = r.WorldToLocalPoint(new GameTypes.IntPoint(-8, 1)); GameTypes.IntPoint localGoal = r.WorldToLocalPoint(new GameTypes.IntPoint(17, 6)); if (r.GetTileType(localStart) == TileType.FLOOR) { start = r.GetTile(localStart); } if (r.GetTileType(localGoal) == TileType.FLOOR) { goal = r.GetTile(localGoal); } } Assert.NotNull(start); Assert.NotNull(goal); PathSolver <TileNode> solver = new PathSolver <TileNode>(); MultiRoomNetwork roomNetwork = new MultiRoomNetwork(rooms); var foundPath = solver.FindPath(start, goal, roomNetwork); Assert.AreEqual(PathStatus.FOUND_GOAL, foundPath.status); PrintWorld(rooms, foundPath); }
public List <PathSolver.PathFinderNode> Search(Position Start, Position End) { try { lock (_mapObjects) { if (Grid.GetLength(0) == 0 || Grid.GetLength(1) == 0) { return(null); } if (!Client.MapLoaded) { return(null); } nodes = new PathSolver.PathNode[Width, Height]; for (short y = 0; y < Height; y++) { for (short x = 0; x < Width; x++) { nodes[x, y] = new PathSolver.PathNode() { HasReactor = false, IsBlock = this[x, y] == 1, Steps = 0, IsDoor = false }; } } foreach (var obj in MapObjects) { if (obj.Type == MapObjectType.Monster || obj.Type == MapObjectType.Aisling || obj.Type == MapObjectType.NPC) { nodes[obj.ServerPosition.X, obj.ServerPosition.Y].IsBlock = true; } } SetPassable(Start); SetPassable(End); nodes[Start.X, Start.Y].IsBlock = false; nodes[End.X, End.Y].IsBlock = false; var usingpath = PathSolver.FindPath(ref nodes, Start, End); return(usingpath); } } catch { return(null); } }
public PathSolver getPathSolver() { if (pathSolver == null) { pathSolver = new PathSolver(width, height, regions, terrainTypes); } return(pathSolver); }
static void Main(string[] args) { // Create the map we'll use for this program. Since StarMap implements IPathGraph, it can answer // questions PathSolver asks about connections and distances between stars. var maxJumpDist = _shipTypes.Select((ship) => ship.MaxJumpDistance).Max(); var starMap = CreateMap(maxJumpDist); // Create a PathSolver instance that we'll use. The first type parameter, string, is what // we'll use to identify nodes in the graph. The second, ShipCharacteristics, is the type of // caller data that we will pass to FindPath, and it will subsequently pass to Cost and EstimatedCost. // In this example, what type of spaceship we're plotting a path for. var solver = new PathSolver <string, ShipCharacteristics>(starMap); // Pre-build PathSolver's internal data. We have to give it one or more seed points - nodes that // we know exist. One is sufficient as long as all of the others are reachable from it. solver.BuildAdjacencyGraph("A"); // Show the user the star map. foreach (var row in _asciiMap) { Console.WriteLine(row); } // Prompt for input about what paths to plot. string startStar; string endStar; Console.Write("Enter starting star: "); var startStarInput = Console.ReadLine(); if (startStarInput.Length > 0) { startStar = startStarInput.ToUpper().Substring(0, 1); } else { return; } Console.Write("Enter destination star: "); var endStarInput = Console.ReadLine(); if (endStarInput.Length > 0) { endStar = endStarInput.ToUpper().Substring(0, 1); } else { return; } // Find a path for each type of spaceship, and display it to the user. Console.WriteLine($"--{startStar} to {endStar}--"); foreach (var ship in _shipTypes) { WritePath(starMap, solver, startStar, endStar, ship); } }
public void FindPath_ThrowsIfEmptyDestinationList() { var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(_startPt); PathResult <Point> pathResult = null; var destList = new List <Point>(); Assert.ThrowsException <PathfindingException>(() => pathResult = solver.FindPath(_startPt, destList, PathTestOption.Normal)); }
public void FindPath_ThrowsIfDestNodeNotInGraph() { var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(_startPt); PathResult <Point> pathResult = null; var ptOutsideOfGraph = new Point(-1, -1); Assert.ThrowsException <PathfindingException>(() => pathResult = solver.FindPath(_startPt, ptOutsideOfGraph, PathTestOption.Normal)); }
void Awake() { gameRules = GameObject.FindGameObjectWithTag("GameManager").GetComponent <Manager_Game>().GameRules; CreateGrid(); solver = new PathSolver(); requestHandler = new PathRequestHandler(); solver.Init(this); requestHandler.Init(solver); }
public void FindPath_ZeroLengthPathToSelf() { var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); var solution = solver.FindPath(_startPt, _startPt, PathTestOption.Normal); Assert.IsTrue(solution.PathCost == 0); Assert.IsNotNull(solution.Path); Assert.IsTrue(solution.Path.Count == 0); StringAssert.Contains(solution.PerformanceSummary(), "Zero-length path"); }
public void PerformanceSummary_HasInfo() { var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); var solution = solver.FindPath(_startPt, _reachableEndPt, PathTestOption.Normal); var summary = solver.PerformanceSummary(); Assert.IsNotNull(summary); StringAssert.Contains(summary, "pathCount=1;"); }
public void FindPath_NoPathToUnreachable() { // In this case, _startPt and _unreachableEndPt are disconnected in the adjacency graph. var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); var solution = solver.FindPath(_startPt, _unreachableEndPt, PathTestOption.Normal); Assert.IsTrue(solution.PathCost == double.PositiveInfinity); Assert.IsNull(solution.Path); StringAssert.Contains(solution.PerformanceSummary(), "Path not found"); }
public void FindPath_NoPathIfAllInfiniteCosts() { // In this case, the start and end points are connected in the adjacency graph, but all possible paths // have an infinite cost. PathSolver treats that as unreachable. var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); var solution = solver.FindPath(_startPt, _reachableEndPt, PathTestOption.InfiniteCost); Assert.IsTrue(solution.PathCost == double.PositiveInfinity); Assert.IsNull(solution.Path); StringAssert.Contains(solution.PerformanceSummary(), "Path not found"); }
private void TestPaths(IAIPath[] from, TestPath[] to, TestRoute[] route) { var solver = new PathSolver(from, to, route); while (solver.Iterate()) { } Assert.IsTrue(solver.IsComplete); Assert.IsTrue(solver.IsSuccess); r.HighlightRoute(route); r.HighlightRoute(solver.Solution.OfType <TestPath>()); }
public void FindPath_GoodPathToReachable() { var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); var solution = solver.FindPath(_startPt, _reachableEndPt, PathTestOption.Normal); Assert.IsTrue(solution.PathCost >= _testMap.EstimatedCost(_startPt, _reachableEndPt, PathTestOption.Normal)); Assert.IsNotNull(solution.Path); Assert.IsTrue(solution.Path.Count > 0); Assert.IsTrue(solution.Path[solution.Path.Count - 1] == _reachableEndPt); Assert.IsFalse(solution.Path.Contains(_startPt)); Assert.IsTrue(solution.NodesReprocessedCount == 0); StringAssert.Contains(solution.PerformanceSummary(), $"Path from {_startPt}"); }
public void FindPath_GoodPathEvenWithOverestimate() { // If we give PathSolver a bad estimate, we should still get a path, but it won't always be optimal. // NodesReprocessedCount can only be > 0 in this case. var solver = new PathSolver <Point, PathTestOption>(_testMap); solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); var solution = solver.FindPath(_startPt, _reachableEndPt, PathTestOption.OverEstimateRemainingDistance); Assert.IsNotNull(solution.Path); Assert.IsTrue(solution.Path.Count > 0); Assert.IsTrue(solution.Path[solution.Path.Count - 1] == _reachableEndPt); Assert.IsFalse(solution.Path.Contains(_startPt)); Assert.IsTrue(solution.NodesReprocessedCount > 0); StringAssert.Contains(solution.PerformanceSummary(), $"Path from {_startPt}"); }
public void ClearAdjacencyGraph_InvalidatesOldNodes() { var solver = new PathSolver <Point, PathTestOption>(_testMap); // Build a graph based on all three points. solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); // Clear the graph, and then rebuild it with just one point. solver.ClearAdjacencyGraph(); solver.BuildAdjacencyGraph(_startPt); // Try to find a path to _unreachableEndPt. PathSolver should complain that it doesn't know about that point. PathResult <Point> pathResult = null; Assert.ThrowsException <PathfindingException>(() => pathResult = solver.FindPath(_startPt, _unreachableEndPt, PathTestOption.Normal)); }
private static void Demo() { // Create a tile map. In this case we're doing it from hard-coded strings, but it // would be trivial to get it from a file instead. var map = new Map(_demoMapStrings); // Create an instace of an IPathGraph. This is a class that the caller provides // that answers which tiles are adjacent to which, and what the cost is to move from // one to the next. var tileGraph = new TileGraph(map); // Create a PathSolver instance. The first type parameter here is Point2D. It's whatever // we're using to identify nodes (tile in this case). The second one - int here - is a dummy // type since we don't care about callerData/passthrough values in this example. var solver = new PathSolver <Point2D, int>(tileGraph); var allImportantPoints = _demoGoalPts.Concat(_demoStartPts); // Pre-build the PathSolver's data structures. We're telling it to build a graph of all of the points // reachable from the ones we give it here. solver.BuildAdjacencyGraph(allImportantPoints); // Create a path and draw the map for each point in _demoStartPts. foreach (var startPt in _demoStartPts) { // Find the shortest path from startPt to any of points listed in _interestingGoals. Of course, // you could just give it one ending point. The third parameter, 0 here, is unused in this example. var pathResult = solver.FindPath(startPt, _demoGoalPts, 0); // Write the map out as a grid characters, with a couple extra bits: // O is the starting point for our path. // X is one of the ending points for our path. // . is a tile we moved through on the path. var startPtsArray = new Point2D[] { startPt }; var mapStrings = map.RowStrings(pathResult.Path, startPtsArray, _demoGoalPts); Console.WriteLine(); foreach (var mapRow in mapStrings) { Console.WriteLine(mapRow); } // Write performance info. Console.WriteLine(pathResult.PerformanceSummary()); } }
public List <PathSolver.PathFinderNode> Search(Position Start, Position End) { lock (_mapObjects) { if (Grid.GetLength(0) == 0 || Grid.GetLength(1) == 0) { return(null); } if (!Client.MapLoaded) { return(null); } var usingpath = PathSolver.FindPath(Grid, Start, End); return(usingpath); } }
/// <summary> /// Plot a path between the given stars for a particular ship type, and write that path out to the console. /// </summary> private static void WritePath(StarMap map, PathSolver <string, ShipCharacteristics> solver, string fromStar, string toStar, ShipCharacteristics ship) { // Find the best path between our stars. The third parameter here, ship, gets passed through // to StarMap's Cost and EstimatedCost methods. var pathInfo = solver.FindPath(fromStar, toStar, ship); if (pathInfo.Path == null) { Console.WriteLine($"{ship.ShipClass}: no path found from {fromStar} to {toStar}"); return; } // Write out a string indicating each step in the path and its cost. var buff = new System.Text.StringBuilder(); buff.Append(ship.ShipClass).Append(": ").Append(fromStar); string currentStar = fromStar; int i = 0; while (i < pathInfo.Path.Count) { string nextStar = pathInfo.Path[i]; var cost = map.Cost(currentStar, nextStar, ship); buff.AppendFormat(" -({0:N1})-> ", cost); buff.Append(nextStar); i += 1; currentStar = nextStar; } Console.WriteLine(buff.ToString()); // Write out debug/performance stats. Console.WriteLine(" " + pathInfo.PerformanceSummary()); }
public void Init() { for (int x = 0; x < Constants.EDGE_WIDTH; x++) { for (int y = 0; y < Constants.EDGE_HEIGHT; y++) { m_routeMap[x, y] = new IsoPathGrid { EntityID = 0, X = x, Y = y, }; m_entityCount[x, y] = 0; } } m_buildingMap = new int[Constants.WIDTH, Constants.HEIGHT]; for (int i = 0; i < (int)OwnerType.Count; i++) { m_entities[i] = new List <TileEntity>(); } m_entityHash.Clear(); m_entitiesToAdd.Clear(); m_entitiesToRemove.Clear(); m_aStar = new PathSolver <IMoveGrid, IsoPathGrid, AStarUserContext>(m_routeMap); m_dijkstra = new Dijkstra(); m_wallLinker = new object(); m_wallLinkerId = m_wallLinker.GetHashCode(); _cacheWorkerHouse = null; m_guardAreaMap = null; }
/// <summary> /// Search for a whole lot of paths using a large map. /// </summary> private static void Benchmark() { // Build the necessary pieces (as above in Demo()). var map = new Map(_benchmarkMapStrings); var tileGraph = new TileGraph(map); var solver = new PathSolver <Point2D, int>(tileGraph); // Init the solver's graph. (This step is included in solver.LifetimeSolutionTimeMS, by the way.) solver.BuildAdjacencyGraph(_benchmarkPts); // Solve a path for every combination of 1 starting point and 2 destination points. (So if P is the number of // points, then we're solving P*(P-1)*(P-2)/2 paths.) for (var startIdx = 0; startIdx < _benchmarkPts.Length; ++startIdx) { var startPt = _benchmarkPts[startIdx]; for (var endIdx1 = 0; endIdx1 < _benchmarkPts.Length; ++endIdx1) { if (endIdx1 == startIdx) { continue; } for (var endIdx2 = endIdx1 + 1; endIdx2 < _benchmarkPts.Length; ++endIdx2) { if (endIdx2 == startIdx) { continue; } var endPts = new[] { _benchmarkPts[endIdx1], _benchmarkPts[endIdx2] }; var pathResult = solver.FindPath(startPt, endPts, 0); } } } // Write out a summary of the PathSolver's lifetime statistics. Console.WriteLine(solver.PerformanceSummary()); }
/// <summary> /// 更新paths,并取下一个node位置 /// </summary> /// <param name="currentX"></param> /// <param name="currentY"></param> public void findUpdatedPath(int currentX, int currentY) { PathSolver <MyPathNode, System.Object> aStar = new PathSolver <MyPathNode, System.Object>(Game.grid); IEnumerable <MyPathNode> path = aStar.Search(new Vector2(currentX, currentY), new Vector2(endGridPosition.x, endGridPosition.y), null); int x = 0; if (path != null) { foreach (MyPathNode node in path) { if (x == 1) { nextNode = node; break; } x++; } foreach (GameObject g in GameObject.FindGameObjectsWithTag("GridBox")) { if (g.GetComponent <Renderer>().material.color != Color.red && g.GetComponent <Renderer>().material.color == myColor) { g.GetComponent <Renderer>().material.color = Color.white; } } foreach (MyPathNode node in path) { GameObject.Find(node.X + "," + node.Y).GetComponent <Renderer>().material.color = myColor; } } }
public void Init(PathSolver pathfinding) { solver = pathfinding; instance = this; }
public void Setup() { solver = new PathSolver <SampleNode>(); }
public void BasicUsage() { { RelayTwo relay = new RelayTwo(); relay.CreateTable(Room.TABLE_NAME); RoomRunner roomRunner = new RoomRunner(relay); foreach (string s in roomRunner.Preload()) { ; } Room r1 = roomRunner.CreateRoom <Room>("r1"); Room r2 = roomRunner.CreateRoom <Room>("r2"); PointTileNode door1 = null; PointTileNode door2 = null; for (int i = 0; i < 100; i++) { int x = i % 10; int y = i / 10; if (x == 9 && y == 9) { door1 = new PointTileNode(new IntPoint(9, 9), r1); r1.AddTile(door1); } else { r1.AddTile(new PointTileNode(new IntPoint(x, y), r1)); } } for (int i = 0; i < 100; i++) { int x = i % 10; int y = i / 10; if (x == 0 && y == 0) { door2 = new PointTileNode(new IntPoint(0, 0), r2); r2.AddTile(door2); } else { r2.AddTile(new PointTileNode(new IntPoint(x, y), r2)); } } r1.worldPosition = new IntPoint(50, 0); door1.teleportTarget = door2; door2.teleportTarget = door1; relay.SaveAll("room_test.json"); } { RelayTwo relay = new RelayTwo("room_test.json"); RoomRunner roomRunner = new RoomRunner(relay); foreach (string s in roomRunner.Preload()) { ; } Room r1 = roomRunner.GetRoom("r1"); Room r2 = roomRunner.GetRoom("r2"); r1.GetTile(9, 9).teleportTarget = r2.GetTile(0, 0); r2.worldPosition = new IntPoint(0, 0); PointTileNode start = r1.GetTile(new IntPoint(0, 5)); PointTileNode goal = r2.GetTile(new IntPoint(9, 5)); D.isNull(start); D.isNull(goal); PathSolver <PointTileNode> pathSolver = new PathSolver <PointTileNode>(); Path <PointTileNode> path = pathSolver.FindPath(start, goal, roomRunner); Assert.AreEqual(PathStatus.FOUND_GOAL, path.status); Console.WriteLine("path resolved using " + path.pathSearchTestCount + " node tests"); Console.WriteLine("path tile count " + path.nodes.Length); } }
public Form1() { InitializeComponent(); int[,] biomeMap; var popCenters = buildData(out biomeMap); var field = new TerrainType() { cost = 10f, name = "field" }; var wood = new TerrainType() { cost = 2f, name = "wood" }; var town = new TerrainType() { cost = 1.5f, name = "town" }; World world = new World(biomeMap, new List <TerrainType>() { field, wood, town }); Console.WriteLine("built world"); pathfinding = world.getPathSolver(); Console.WriteLine("built pathFinding"); //pictureBox.Image = world.image; //pictureBox.Image=world.(); var road = new RoadType() { weightRequirement = 0, cost = 1f }; var highway = new RoadType() { weightRequirement = 5f, cost = 1f }; var roads = new List <RoadType> { road, highway }; var popCenter1 = new PopulationCentre(new MyMath.Point(10, 10), 100); var popCenter2 = new PopulationCentre(new MyMath.Point(74, 3), 30); var popCenter3 = new PopulationCentre(new MyMath.Point(230, 100), 70); var popCenter4 = new PopulationCentre(new MyMath.Point(200, 250), 30); var pops = new List <PopulationCentre>() { popCenter1, popCenter3, popCenter4 }; pathfinding.AddRoads(popCenters, roads); //var path = pathfinding.getPath(new MyMath.Point(3, 3), new MyMath.Point(95, 53)); var g = Graphics.FromImage(pictureBox.Image); foreach (var segment in pathfinding.roadNetwork.roadSegments) { Color c = Color.Gray; if ((segment.roadType as RoadType).weightRequirement != 0) { c = Color.Purple; } g.DrawLines(new Pen(c, 1), segment.ConvertAll(x => new PointF(x.x, x.y)).ToArray()); } pictureBox.Image.Save("roadMap.png"); var meshes = world.getMeshes(); /*foreach(var v in pathfinding.navigationNodes()) * { * * g.FillRectangle(new SolidBrush(Color.Red), (float)v.x, (float)v.y, 1, 1); * * }*/ }