Reputation: 323
Im making a 2D sandbox game(like terraria) with LibGDX. I have come across a issue though. I need the world to generated in another thread so the program can render the animated loading screen while it generates. I put the generation code in a new thread. When I run it, I receive this error:
Exception in thread "Thread-1" java.lang.RuntimeException: No OpenGL context found in the current thread.
Why is this happening and how can i fix it? When the generator runs it needs to create a Sprite which requires OpenGL, but it seems to not like running in a seperate thread. Any insights?
Upvotes: 1
Views: 1138
Reputation: 13571
Maybe it is possible to somehow create a GL context in a new thread (but I'm not sure since I haven't done this ever) but why the heck are you trying to achieve this in that way? :)
Instead of creating new thread to load assets / generate world just render some "loading" label/animation - anything you want and start to render world when it is done.
If you are trying to load some asset you should use AssetManager and it's update method to check if assets are loaded - something like
AssetManager assetManager = new AssetManager();
//load assets
...
//render method
if(assetManager.update())
{
//render world or even change screen to game screen
}
else
//render "loading"
If you are trying to generate a world just slice this operation for pieces (like generating squares N x N) and have a method to do this just add some control to check if operation is finished - it can be some enum, flag, method... So assuming that you have class WorldGenerator it would be something like
WorldGenerator worldGenerator;
//generate world
...
//render method
if(WorldGenerator.isGenerated())
{
//render world or even change screen to game screen
}
else
//render "loading"
//make a step of generation
Avoid multithreading as fire - especially in Libgdx there are really not many cases that you need this and almost every time it is well handled by framework
Upvotes: 1
Reputation: 323
OK solved.
Libgdx has a sweet util that can post code from a new thread into the main GL thread. Here is a example:
new Thread(new Runnable(){
@Override
public void run(){
//Here we are telling libgdx to connect a new runnable to the gl thread
Gdx.app.postRunnable(new Runnable(){
//Type thread code here. Will be seperate to main thread but part of it at the same time
}
}
});
Hope this helps :D
Upvotes: 2