将GLSurfaceView上下文传递给线程

时间:2011-10-29 12:57:03

标签: java android multithreading opengl-es openglcontext

我希望我的GL渲染器设置为“DIRTY”并使用线程来控制FPS但由于某种原因,requestRender调用似乎总是被跳过。我有一种感觉,这可能与线程没有得到正确的上下文有关。是否有人知道将GLSurfaceView上下文传递给其他线程的良好做法?

这是我的主题:

public class GameLoop extends Thread {


    private GLSurfaceView myGLSurfaceView;
    private final static int maxFPS = 30;
    private final static int maxFrameSkips = 5;
    private final static int framePeriod = 1000 / maxFPS;

    public static boolean running;
    public final static String TAG = "input";

    public GameLoop(){
        myGLSurfaceView = MyLaunchActivity.getMyGLSurfaceView();
    }

@Override
public void run() {

    running = MyLaunchActivity.getRunning();
    long beginTime;
    long timeDiff;
    int sleepTime;
    int framesSkipped;


    sleepTime = 0;
    while (running) {
        running = MyLaunchActivity.getRunning();
        //Log.d(TAG, "gameRunning");
        beginTime = System.currentTimeMillis();
        framesSkipped = 0;
        GameLogic.update();
        myGLSurfaceView.requestRender();
        //Log.d(TAG, "rendered");
        timeDiff = System.currentTimeMillis() - beginTime;
        sleepTime = (int)(framePeriod - timeDiff);

        if (sleepTime > 0) {
            try{
                Thread.sleep(sleepTime);
                //Log.d(TAG, "sleeping" + String.valueOf(sleepTime));
            }catch(InterruptedException e){}
        }

        while(sleepTime < 0 && framesSkipped < maxFrameSkips){
            GameLogic.update();
            sleepTime += framePeriod;
            framesSkipped++;
            Log.d(TAG, "Frames Skipped");
        }




}
}


}

这是我的表面视图的构造函数......

 public MyGLSurfaceView(Context context, AttributeSet attrs){
    super(context, attrs);
            myGLSurfaceRenderer = new MyGLSurfaceRenderer();
    setRenderer(myGLSurfaceRenderer);
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
            Log.d(TAG, "GLSurfaceViewed");

}

1 个答案:

答案 0 :(得分:1)

myGLSurfaceView = MyLaunchActivity.getMyGLSurfaceView();

有关您的代码的一些问题:

  • 如何设置上下文?
  • 在初始化MyLaunchActivity.getMyGLSurfaceView()返回的MyGLSurfaceView后,您是否检查过是否创建了GameLoop对象?

您可以做的第一件事是在run()方法中为Exception添加一个catch子句,以查看是否有任何问题可以解释为什么不调用该方法。