• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
SillyCow

Pathfinding On Android

9 posts in this topic

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?
0

Share this post


Link to post
Share on other sites
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:[list]
[*]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.
[/list]
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
1

Share this post


Link to post
Share on other sites
[quote name='alvaro' timestamp='1338641358' post='4945561']
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:[list]
[*]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.
[/list]
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.
[/quote]
Sounds like a good clustering plan, But I am not sure that I have alot of units attacking the same target.


[quote name='alvaro' timestamp='1338641358' post='4945561']
If everything else fails, code it up in C.

[/quote]
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?
0

Share this post


Link to post
Share on other sites
[quote name='SillyCow' timestamp='1338671482' post='4945656']
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?
[/quote]

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.
0

Share this post


Link to post
Share on other sites
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)
0

Share this post


Link to post
Share on other sites
[quote]Depending on your map mechanism you should be able to do a hierarchical path-finder that can save on a great deal of processing.
[/quote]

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

Share this post


Link to post
Share on other sites
I would suggest posting your current Java implementation [i]first[/i]. 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).
2

Share this post


Link to post
Share on other sites
[quote name='ApochPiQ' timestamp='1339442152' post='4948255']
I would suggest posting your current Java implementation [i]first[/i]. 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.
[/quote]

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.

[CODE]
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();
}
}
[/CODE] Edited by SillyCow
0

Share this post


Link to post
Share on other sites
[quote name='PantherBoy' timestamp='1342825579' post='4961501']
Spreading the pathfinding calculations over multiple frames can also be an easy win
[/quote]

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0