• 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
Sparkon

Multithreaded pathfinding

12 posts in this topic

Hello guys... i'm now working on the pathfinding of my game, and since pathfinding can really slow down the game i had three ideas :
1) i update the game (rendering) at 60 fps ( example ), i update my physics at 60/2 and since pathfinding does not require to be updated many times a second i was gonna update it once every 60 frames
2) multi-threading
3) splitting pathfinding algorithms over multiple frames

I've read that multithreading is used often when dealing with pathfinding or similar, but i've got only some basic knowledge about multi-threading (C++)
The 1) IMHO is a good idea... but it can still slow down my program in THAT frame i update the pathfinding.
The 3) seems the best idea for me... splitting a N number of paths to find over N threads, but i have really no good idea how to implement it.

i was looking for some hints & tips from people with more experience. My game is pretty simple, but the AI is the most important part (it's for learning mainly). And for pathfinding i'm using different algorithms for different purposes ( DFS,BFS,Dijkstra,A*). i've already implemented most of them and even the DFS that "is supposed to be the faster" really slow the program down.

P.S. if you have any good article i'd be glad to read it ! Edited by Sparkon
0

Share this post


Link to post
Share on other sites
I would spend some time on this idea:
0) Make your pathfinding code as fast as possible.

I don't know anything about how you code, but I have seen enough horror stories to suspect that there is a decent chance you are doing something needlessly slow in your code. I am thinking of something like allocating dynamic memory whenever a node gets visited, or that type of thing.

I would only pursue one of the other options after I have satisfied myself that there isn't much to be gained from improving the single-threaded pathfinding code.
1

Share this post


Link to post
Share on other sites
Before you start to multithread, make sure your algoritms are working properly and efficiently with extensive tests.

Then reduce the times it is run, why would it be needed to run at a fixed timestep?
Only times the path changes is if the goal changes or the terrain changes.

Then you can simplify the terrain to have less nodes to search.

DFS is not "supposed to be faster", only in very special cases.

You probably want A*, specially if you have an easy way to estimate distance left to goal, dijkstra's is useful if you can't. Edited by Olof Hedman
1

Share this post


Link to post
Share on other sites
Ahah Alvaro hopefully i havn't done it yet.
Anyway i'm already trying to optmize that. To get all the nodes in the map i've used flood fill... I'll try to reduce the number of nodes. I've got one node every 15 pixels ( except for walls or non-walkable areas ) that roughly are 8k nodes per map. I'm realizing that maybe they are too many nodes.
The entire map is around 1920x1080. Do you think that are too many ?
0

Share this post


Link to post
Share on other sites
That doesn't sound much to me... thats just a grid of approx 90x90 nodes.

If the map is relatively open and interconnected, an A* shouldn't have to visit much more then a few hundred in average, and that is when navigating from one end of the map to the other. If start and end is relatively close to eachother, you will just visit a handful of nodes, should be very fast.

DFS will in average visit half the nodes, even when start and end is just next to each other (if you are unlucky and start searching the wrong direction, you might have to visit _every_ node before you find the goal in your neighbor node...)

I think there might be something funky in your A*
unless you have a very high number of agents pathfinding...

Another optimization is to have different levels of pathfindning, a coarse one to find (for example) the "rooms" to visit, and then a finer to navigate through each "room". Edited by Olof Hedman
0

Share this post


Link to post
Share on other sites
[quote name='Olof Hedman' timestamp='1350923359' post='4992806']
That doesn't sound much to me... thats just a grid of approx 90x90 nodes.

If the map is relatively open and interconnected, an A* shouldn't have to visit much more then a few hundred in average, and that is when navigating from one end of the map to the other. If start and end is relatively close to eachother, you will just visit a handful of nodes, should be very fast.

DFS will in average visit half the nodes, even when start and end is just next to each other (if you are unlucky and start searching the wrong direction, you might have to visit _every_ node before you find the goal in your neighbor node...)

I think there might be something funky in your A*
unless you have a very high number of agents pathfinding...

Another optimization is to have different levels of pathfindning, a coarse one to find (for example) the "rooms" to visit, and then a finer to navigate through each "room".
[/quote]

A* definitively faster than DFS ( i'm finishing A* "benchmarks" ). DFS takes 1 second in the worst case
0

Share this post


Link to post
Share on other sites
Sounds to me like that inner loop can be optimized, if you only test 8 nodes per millisecond. (assuming modern PC)
Remember, adding threads will only increase capacity by the number of cores you have.
Optimizing your inner loop could give you 100x improvement in some cases [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] (not saying you could in this case)

What is your heuristic for A*? if its euclidian distance to goal, you could try squared distance, just as good but a lot faster.

There are also more advanced ones to handle dead ends better if your map have lots of those, you could check this out for example: [url="http://www.ru.is/faculty/yngvi/pdf/BjornssonH06.pdf"]http://www.ru.is/fac...jornssonH06.pdf[/url]

Though, when you've exhausted all algorithmic improvements and optimizations, at least it IS easily parallelized.
For multithreading, you should remember that you can't run more threads then cores in parellel, so you should divide n paths per thread where n = number of paths / number of cores.
some kind of thread pool that you dispatch work to, seems like a popular architecture for those things, but I must admit I don't have much experience in that. Edited by Olof Hedman
0

Share this post


Link to post
Share on other sites
[quote name='Olof Hedman' timestamp='1350926931' post='4992824']
Sounds to me like that inner loop can be optimized, if you only test 8 nodes per millisecond. (assuming modern PC)
Remember, adding threads will only increase capacity by the number of cores you have.
Optimizing your inner loop could give you 100x improvement in some cases [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] (not saying you could in this case)

What is your heuristic for A*? if its euclidian distance to goal, you could try squared distance, just as good but a lot faster.

There are also more advanced ones to handle dead ends better if your map have lots of those, you could check this out for example: [url="http://www.ru.is/faculty/yngvi/pdf/BjornssonH06.pdf"]http://www.ru.is/fac...jornssonH06.pdf[/url]

Though, when you've exhausted all algorithmic improvements and optimizations, at least it IS easily parallelized, and your assumption of 1 path per thread sounds very good.
[/quote]

For the DFS ( that is causing me most of the trouble ) to get from node 10 to 600 ( it's doing the worst path possible ) with ~15k recursion in the inner loop and ~8400 nodes and ~32600 edges ( only 4 directions ) it takes 1 seconds. Here is my code for the DFS ( for this algorithm i'm following a book )
[code]
void GraphSearch::DFSearch(int sourceID,int targetID,std::vector<int>& path)
{
// creating containers
std::stack<const MapEdge*> stack;
std::vector<int> visitedNodes(pNodes_->size(),node::NODE_UNVISITED); // creating the container here is quite slow, but DFS still takes 1 sec
std::vector<MapEdge*> connectingNodes;
sf::Clock clock;
float timeElapsed = 0;
int deep = 0;
MapEdge dummyStart(sourceID,sourceID,10);
stack.push(&dummyStart);
while(!stack.empty())
{
timeElapsed += clock.restart().asSeconds();
deep += 1;
const MapEdge* next = stack.top();
stack.pop();
if (next->To() == targetID)
{
std::cout << "Time elapsed " << timeElapsed
<< " on : " << deep << " recursions" << std::endl;
return;
}
path[next->To()] = next->From();
visitedNodes[next->To()] = node::NODE_VISITED;
connectingNodes.clear();
FindConnectingNodes(next->To(),connectingNodes); // this might be the problem since i'm looping through 32k edges * 15k recursions
std::size_t s = connectingNodes.size();
for(int i = 0;i <s;++i)
{
if (visitedNodes[connectingNodes[i]->To()] == node::NODE_UNVISITED)
stack.push(connectingNodes[i]);
}
}
}
[/code]

edit : yes the FindConnectingNodes is definitively a problem, i've just given a run with VerySleepy and i've found out that is the most expensive call. something like 20% of the whole program ( windows call included) Edited by Sparkon
0

Share this post


Link to post
Share on other sites
Hi Sparkon,

are you sure, that you need to do all the calculation every time?

I don't know which game you are building exactly, but there might be a way to use precalculated A* for example.

See [url="http://www.gamedev.net/page/books/index.html/_/technical/game-programming-9/advanced-game-programming-a-gamedevnet-collection-r723"]http://www.gamedev.net/page/books/index.html/_/technical/game-programming-9/advanced-game-programming-a-gamedevnet-collection-r723[/url]

e. g. if you have many rooms and the player moves in the building as does the enemy (AI). You could calculate the routes between the room at buildtime. Than you just lookup position (enemy room) and destination (player room) and have the best way. You can even have seperate calculations for different conditions like locked doors, spawned health packs etc.

As soon as player and enemy are in the same room you can use nearly any pathfinding algorithm for the 'last mile'.

-- GWDev Edited by GWDev
0

Share this post


Link to post
Share on other sites
[quote name='GWDev' timestamp='1350930031' post='4992835']
Hi Sparkon,

are you sure, that you need to do all the calculation every time?

I don't know which game you are building exactly, but there might be a way to use precalculated A* for example.

See [url="http://www.gamedev.net/page/books/index.html/_/technical/game-programming-9/advanced-game-programming-a-gamedevnet-collection-r723"]http://www.gamedev.n...collection-r723[/url]

e. g. if you have many rooms and the player moves in the building as does the enemy (AI). You could calculate the routes between the room at buildtime. Than you just lookup position (enemy room) and destination (player room) and have the best way. You can even have seperate calculations for different conditions like locked doors, spawned health packs etc.

As soon as player and enemy are in the same room you can use nearly any pathfinding algorithm for the 'last mile'.

-- GWDev
[/quote]

yes... i'll probably do as you suggest.

Olof Hedman i fixed the code now it's extremely faster, i'll try to improve it more before going with multi-threading :P
0

Share this post


Link to post
Share on other sites
Yeah, your datastructure is definitely a problem.

A common, and very fast way, let the nodes be cells in an array, like pixels in a bitmap, and just mark cells as "unpassable" for walls and such.
Then finding neighbours is as easy as adding or substracting to the index of the current node.

Edit: didn't see the last post :) Glad to see you've improved it. Edited by Olof Hedman
0

Share this post


Link to post
Share on other sites
Much depends on what is dynamic (which effects continuing validity of a path that is found) .

If nothing impacts a path once it is built then the calculated paths dont need to be redone over and over

If the things that impact the path validity move less than once a second (or alot less), then re-calculating the paths much faster than that is a waste.
(You may even be able to detect IF something on the map changed each 'turn' and if it hasnt, then the previously calculated paths can be reused0

When the target is far away. you mau be able to continue to reuse the old calculated path (or only recaclulate it infrequently) until you get close enuf or get stuck on something dynamic. (You may have to find any factors/cases where it DOES matter to recalculate faster).


Usually when you are very close (terminal guidance) to the target is when you need to recalculate very frequently (which usually has to be handled specially anyway)

If you have alot of dynamic elements (things that block paths change alot) then there also can be processing variations that can reuse/patch a saved path data (so as to not require full recalculation).

----

Multi-threading can be useful when you have cores to spare- (and see [b]Processor[/b] [b]affinity[/b] to help that along) especially when you have many objects that need pathfinding done for them (but with the usual issues of handling any map dynamic changes ).

For huge maps (and long paths) - hierarchical pathfinding can be very important Edited by wodinoneeye
0

Share this post


Link to post
Share on other sites
[quote name='Olof Hedman' timestamp='1350932601' post='4992858']
Yeah, your datastructure is definitely a problem.

A common, and very fast way, let the nodes be cells in an array, like pixels in a bitmap, and just mark cells as "unpassable" for walls and such.
Then finding neighbours is as easy as adding or substracting to the index of the current node.

Edit: didn't see the last post [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] Glad to see you've improved it.
[/quote]

yeah the flagged 'grid' border eliminates the costly edge coordinate tests


I helped someone long ago with every optimzation possible and even went so far as ditching the 2D array, using a single dimensional array/memory block and pointer math +/- 1 for the X axiz and +/- a precaclulated map width for the Y (I forget if we did byte addressing directly to get rid of the pointer multiply altogether- though I do recall an 8 grid direction array with all the single value offsets precalculated) .

The pointers also helped with the open/closed list (one offset value to point to the map data) . Along with other things like using a HeapQ and smallest datas possible to minimize cache misses (which was far more significant than word alignment issues).

It was amazing how much faster we got it to run (and we were using large maps 1K x 1K where you needed the performance) Edited by wodinoneeye
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