Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Pathfinding On Android


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
9 replies to this topic

#1 SillyCow   Members   -  Reputation: 885

Like
0Likes
Like

Posted 02 June 2012 - 12:16 AM

I am making an RTS game on Android. For path-finding I have tried several approaches:
1. BFS
2. A* with a simple distance heuristic.

A* gives me slightly better performance then BFS (My maps are pretty maze shaped).

Both are not performing as well as I would like (This is a single core ARM CPU running JAVA, not an Intel 3Ghz running C).

Right now the implementation is very naive. In a game logic frame, a unit can ask for a path, and that path is calculated synchronously (Thereby halting the game logic).

I am looking for ways to improve the performance.

My current thoughts lean towards:
1. Find a better A* heuristic
2. Split up the path finding over several logic frames.
3. Improve trivial A* to multi-tiered A*(Pre-calculate all paths between super-nodes, and add minor path adjustments)
4. Find a way to recycle old unit path calculations. (Unit A calculated path to unit B, Unit B moved : Unit A should recycle some of it's old path).
5. Unit clustering (Seems really hard, I was hoping to avoid this one...)

Any suggestions as to what I should try, and how?

My new android game : Enemies of the Crown

My previous android game : Killer Bees


Sponsor:

#2 Álvaro   Crossbones+   -  Reputation: 13671

Like
1Likes
Like

Posted 02 June 2012 - 06:49 AM

Make sure your implementation doesn't allocate any memory in a tight loop, since that would kill performance.

If you have multiple units going to the same destination, you can compute the distance from any square to the target square with a pretty simple algorithm:
  • Start with an array marked with 0 at the target and infinity (or just a very large number) everywhere else.
  • Loop over the array from top to bottom, from left to right, and update the distance to each location to be the minimum of the distance to a neighbor plus distance from that neighbor to goal (using the current estimate read from the array).
  • Do the same loop, but from bottom to top, from right to left. (This is a small optimization that will speed things up a lot if you have long straight corridors).
  • As long as something has been changed, go to 2.
Now just recover the paths by traveling from the unit's location to the neighbor with the lowest distance (well, not exactly, but you can fill in the details).

Actually, depending on your map, the simple algorithm described above might work extremely well even for one unit.

If everything else fails, code it up in C.

Edited by alvaro, 02 June 2012 - 06:50 AM.


#3 SillyCow   Members   -  Reputation: 885

Like
0Likes
Like

Posted 02 June 2012 - 03:11 PM

Make sure your implementation doesn't allocate any memory in a tight loop, since that would kill performance.

If you have multiple units going to the same destination, you can compute the distance from any square to the target square with a pretty simple algorithm:

  • Start with an array marked with 0 at the target and infinity (or just a very large number) everywhere else.
  • Loop over the array from top to bottom, from left to right, and update the distance to each location to be the minimum of the distance to a neighbor plus distance from that neighbor to goal (using the current estimate read from the array).
  • Do the same loop, but from bottom to top, from right to left. (This is a small optimization that will speed things up a lot if you have long straight corridors).
  • As long as something has been changed, go to 2.
Now just recover the paths by traveling from the unit's location to the neighbor with the lowest distance (well, not exactly, but you can fill in the details).

Actually, depending on your map, the simple algorithm described above might work extremely well even for one unit.

Sounds like a good clustering plan, But I am not sure that I have alot of units attacking the same target.


If everything else fails, code it up in C.

Don't like going native in android. I like staying in Java where I can. If I am stingy with my "new"s (avoid mallocs) is there any big performance boost?

My new android game : Enemies of the Crown

My previous android game : Killer Bees


#4 Álvaro   Crossbones+   -  Reputation: 13671

Like
0Likes
Like

Posted 02 June 2012 - 07:37 PM

Don't like going native in android. I like staying in Java where I can. If I am stingy with my "new"s (avoid mallocs) is there any big performance boost?


As usual with performance questions, there is only one way to really know: Code it up and measure the difference. But I would certainly expect a good boost from removing all dynamic memory allocation in the inner loop.

#5 wodinoneeye   Members   -  Reputation: 861

Like
0Likes
Like

Posted 09 June 2012 - 10:05 PM

Depending on your map mechanism you should be able to do a hierarchical path-finder that can save on a great deal of processing.

---

You can also save paths from a previous pathfind and if you are outside of a critical distance you pathfind from the last known target position to its new position (indicating its still reachable)meanwhile you are following the save path til you get close.

Once you are within the 'critical distance' you do the normal pathfinding every cycle (or frequently)
--------------------------------------------Ratings are Opinion, not Fact

#6 SillyCow   Members   -  Reputation: 885

Like
0Likes
Like

Posted 10 June 2012 - 11:35 AM

Depending on your map mechanism you should be able to do a hierarchical path-finder that can save on a great deal of processing.


I have the usual RTS tile map, where buildings are occasionally added as obstacles. Can you suggest a good hierarchical algorithm?

My new android game : Enemies of the Crown

My previous android game : Killer Bees


#7 ApochPiQ   Moderators   -  Reputation: 16079

Like
2Likes
Like

Posted 11 June 2012 - 01:15 PM

I would suggest posting your current Java implementation first. Let's see if we can trivially optimize it before worrying about complex algorithm-level changes. If your simple A* code isn't fast enough, adding complexity to the algorithm is not guaranteed to give you any real gains.

For reference, unless your maps are millions of nodes, you should be able to do pathing in near real-time on most contemporary Android devices (i.e. fast enough that a synchronous path lookup is on the order of milliseconds and doesn't have terrible gameplay effects as long as you aren't calling it with some insane frequency).

#8 SillyCow   Members   -  Reputation: 885

Like
0Likes
Like

Posted 11 June 2012 - 03:15 PM

I would suggest posting your current Java implementation first. Let's see if we can trivially optimize it before worrying about complex algorithm-level changes. If your simple A* code isn't fast enough, adding complexity to the algorithm is not guaranteed to give you any real gains.


Code below.
One PathFinder object is used throughout the entire game (init with "new"s happens at load time). The reason it is an object is that I might want to multi-thread it later. "Big Pathfinding" from one side of the screen to the next on a Nexus S (Single core 1GHz) takes several milliseconds per unit. Right now a pathfinding request is atomic (no yields). The map size is tens of thousands of nodes, but I would like to make it eventually larger.

A big problem I have found is that if a node is temporarily blocked (surrounded by units), but has a short path to it, The algorithm ends up scanning the entire map (until it has reached it's maximum scan limit) .

Note about the code:
1. I call the map a "game board" so anything with "board" in it is referring to parts of the map.
2. PathNode is a custom linked list node shared between several linked lists. (The shared part of two paths has only one instance).
3. This is currently an inner class belonging to a logic engine, so some members such as m_Board are defined out of scope.

class PathFinder {
		PathNode[][] m_Paths;
		public PathFinder(Board board) {
			m_Paths = new PathNode[board.m_Extents.p[0]][board.m_Extents.p[1]];
			for (int y = 0; y < board.getExtents().p[1]; y++) {
				for (int x = 0; x < board.getExtents().p[0]; x++) {
					m_Paths[x][y] = new PathNode(board.getNode(x, y), null);
				}
			}
		}
		PathNode getPathNode(BoardNode n) {
			return m_Paths[n.m_Position.p[0]][n.m_Position.p[1]];
		}
		class PathNode {
			public PathNode(BoardNode node, PathNode path) {
				this.node = node;
				this.path = path;
				this.distance = (path != null) ? path.distance + 1 : 0;
			}
			public void set(PathNode path) {
				this.path = path;
				this.distance = (path != null) ? path.distance + 1 : 0;
			}
			final BoardNode node;
			PathNode path;
			int distance;
			int marked = -1;
			private LinkedList<BoardNode> toList() {
				LinkedList<BoardNode> ret = new LinkedList<BoardNode>();
				Stack<BoardNode> rev = new Stack();
				PathNode currentPathNode = this;
				while (currentPathNode != null) {
					rev.push(currentPathNode.node);
					currentPathNode = currentPathNode.path;
				}
				while (!rev.empty()) {
					ret.add(rev.pop());
				}
				return ret;
			}
		}
		/**
		 * Scan for path to target node
		 * @param sourceNode
		 * @param targetNode
		 * @return
		 */
		public LinkedList<BoardNode> scanPath(BoardNode sourceNode, BoardNode targetNode, int scanLimit) {
			if (sourceNode == targetNode) {
				return null;
			}
			markIteration++;

			SortedQueue<Integer, PathNode> toScan = new SortedQueue<Integer, PathNode>();
			//Set<BoardNode> markedNodes = new HashSet<BoardNode>();
			{
				//initialize first node to scan:
				PathNode initNode = getPathNode(sourceNode);
				initNode.marked = markIteration;
				initNode.set(null);
				toScan.add(0, initNode);
			}
			//markedNodes.add(sourceNode);
			int closestDistance = Integer.MAX_VALUE;
			PathNode bestPath = null;
			IntVector v = new IntVector(2);
			IntVector tempVect = new IntVector(2);
			for (int scanSteps = 0;
					!toScan.isEmpty() && scanSteps < scanLimit;
					scanSteps++) {
				PathNode currentPath = toScan.poll();
				for (v.p[0] = -1; v.p[0] <= 1; v.p[0]++) {
					for (v.p[1] = -1; v.p[1] <= 1; v.p[1]++) {
						//eliminate 0  and diagonals with XOR:
						if ((v.p[0] != 0) ^ (v.p[1] != 0)) {
							tempVect.set(currentPath.node.m_Position);
							tempVect.add(v);
							if (m_Board.hasNode(tempVect)) {
								BoardNode n = m_Board.getNode(tempVect);
								PathNode pathToNode = getPathNode(n);
								if (n == targetNode || ((n.m_Entity == null || !n.m_Entity.isObsticle()) && (pathToNode.marked != markIteration))) {
									//Check for height differences
									if (Math.abs(n.getHeight() - currentPath.node.getHeight()) <= 1) {
										//Add node to scan queue
										pathToNode.set((currentPath.node != sourceNode) ? currentPath : null);
										pathToNode.marked = markIteration;
										tempVect.sub(targetNode.m_Position);
										int distance = tempVect.squaredLength();
										if (distance < closestDistance) {
											closestDistance = distance;
											bestPath = pathToNode;
										}
										if (n == targetNode) {
											//Success. return path targetNode (including the targetNode itself)
											return pathToNode.toList();
										}
										toScan.add(tempVect.manhattenDistance() + pathToNode.distance, pathToNode);
									}
								}
							}
						}
					}
				}
			}
			//Failed to find path, return closest node instead
			if (bestPath == null) {
				return null;
			}
			return bestPath.toList();
		}
	}

Edited by SillyCow, 11 June 2012 - 03:23 PM.

My new android game : Enemies of the Crown

My previous android game : Killer Bees


#9 PantherBoy   Members   -  Reputation: 163

Like
0Likes
Like

Posted 20 July 2012 - 05:06 PM

Spreading the pathfinding calculations over multiple frames can also be an easy win

#10 SillyCow   Members   -  Reputation: 885

Like
0Likes
Like

Posted 21 July 2012 - 03:35 AM

Spreading the pathfinding calculations over multiple frames can also be an easy win


Already doing that. It's still not as fast as i would like it to be once I have many units.

My new android game : Enemies of the Crown

My previous android game : Killer Bees





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS