I want to pass my renderer some values from another class. After the renderer has calculated the values, I have a mutex in a helper class that should tell me that the renderer has finished calculating so I can continue with these new values. I can pass the renderer the values without problems, but I can’t figure out how to get them back. I currently use some static variables, but after they are changed by the renderer, they seem to get lost. They aren’t visible in my other class.
Example:
A class
public class View extends SurfaceView{
private void doSomething(){
glSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
//..
renderer.calculate(stack);
}
});
}
private void doAnotherThing(){
//Never happens:
if(Helper.hasCalculated){
/...
}
}
}
In my renderer:
public class MyRenderer implements GLSurfaceView.Renderer{
private void calculate(Stack stack){
Helper.hasCalculated = true
}
}
My helper class:
public class Helper{
public static volatile boolean hasCalculated = false;
}
hasCalculated is definitely set to true in the renderer, but my other class always sees it as false. Any idea why? My best guess is that it’s because its in another thread, but how would I solve that? If there is a cleaner and safer approach, I’d be happy to hear him.
You can keep hold of your renderer as a variable in your activity (don’t just do
mGLView.setRenderer(new MyRenderer());as a lot of people do, but ratherMyRenderer myRenderer = new MyRenderer(); mGLView.setRenderer(myRenderer);). Then you can communicate with your renderer easily through method calls. The problem then just comes down to cross-thread communication. I’ve put two examples below, one with communication between a non-UI thread, the GL thread and the main UI thread. The second example is just for communication between the GL thread and UI threadThen in renderer
I’ve used flags in the renderer example above, but it would be fairly simple to turn that into a queue, if, say, you wanted to tell the renderer “load this array of models”. Since you have to load the models (or at least textures) in the GL thread using the GL handle, you can have other classes and threads do your logic and have just the GL stuff done in the GL thread
Alternatively, if you just want to update the UI thread after your calculation is done, rather than interact with any other threads:
and then from anywhere: