如何在我的空游戏中计算FPS?

时间:2012-07-31 11:05:06

标签: java android game-engine frame-rate game-loop

为了创建游戏循环,我跟着this excellent tutorial。但是我认为显示FPS的下一个教程有点不确定,所以我试着单独进行。我对我所做的trackFps()方法充满信心;在计算帧之间的时间差之后调用它,每次运行时测量预测的FPS,将那些预测的FPS值存储在ArrayList中,然后每秒一次将这些预测的FPS加起来并除以添加到的值的数量。获得平均FPS。

当我使用调试器运行它时,它运行正常,但是当我通过它时,我得到以下异常:

FATAL EXCEPTION: Thread-11
java.lang.IndexOutOfBoundsException: Invalid index 26, size is 6
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
at java.util.ArrayList.get(ArrayList.java:311)
at biz.hireholly.engine.GameLoop.trackFps(GameLoop.java:120)
at biz.hireholly.engine.GameLoop.run(GameLoop.java:73)

这是非常明确的解释,发生在这一行fps += fpsStore.get(fpsTrackCount-1);上。但我看不出fpsTrackCount变量如何高达26,它应该只与ArrayList fpsStore中存储的变量数一样高。

有人会查看我的GameLoop课程,特别是底部的trackFps()方法吗?我会提供整件事。它评论很多,但它并不多,对你们中的一些人应该非常熟悉。

GameLoop(包含用于计算底部FPS的trackFps()方法):

package biz.hireholly.engine;

import android.graphics.Canvas;
import android.view.SurfaceHolder;
import java.util.ArrayList;


/**
 * The GameLoop is a thread that will ensure updating and drawing is done at set intervals.
 * The thread will sleep when it has updated/rendered quicker than needed to reach the desired fps.
 * The loop is designed to skip drawing if the update/draw cycle is taking to long, up to a MAX_FRAME_SKIPS.
 * The Canvas object is created and managed to some extent in the game loop,
 * this is so that we can prevent multiple objects trying to draw to it simultaneously.
 * Note that the gameloop has a reference to the gameview and vice versa.
 */

public class GameLoop extends Thread {

    private static final String TAG = GameLoop.class.getSimpleName();
    //desired frames per second
    private final static int MAX_FPS = 30;
    //maximum number of drawn frames to be skipped if drawing took too long last cycle
    private final static int MAX_FRAME_SKIPS = 5;
    //ideal time taken to update & draw
    private final static int CYCLE_PERIOD = 1000 / MAX_FPS;

    private SurfaceHolder surfaceHolder;
    //the gameview actually handles inputs and draws to the surface
    private GameView gameview;

    private boolean running;
    private long beginTime = 0; // time when cycle began
    private long timeDifference = 0; // time it took for the cycle to execute
    private int sleepTime = 0; // milliseconds to sleep (<0 if drawing behind schedule) 
    private int framesSkipped = 0; // number of render frames skipped

    private double lastFps = 0; //The last FPS tracked, the number displayed onscreen
    private int fpsTrackCount = 1; // number we'll divide the fpsSTore by to get average
    private ArrayList<Double> fpsStore = new ArrayList<Double>(); //For the previous fps values
    private long lastTimeFpsCalculated = System.currentTimeMillis(); //used in trackFps

    public GameLoop(SurfaceHolder holder, GameView gameview) {
        super();
        this.surfaceHolder = holder;
        this.gameview = gameview;
    }

    public void setRunning(boolean running) {
        this.running = running;     
    }
    @Override
    public void run(){

        Canvas c;

        while (running) {
            c = null;
            //try locking canvas, so only we can edit pixels on surface
            try{
                c = this.surfaceHolder.lockCanvas();
                //sync so nothing else can modify while were using it
                synchronized (surfaceHolder){ 

                    beginTime = System.currentTimeMillis();
                    framesSkipped = 0; //reset frame skips

                    this.gameview.update();
                    this.gameview.draw(c);

                    //calculate how long cycle took
                    timeDifference = System.currentTimeMillis() - beginTime;
                    //good time to trackFps?
                    trackFps();

                    //calculate potential sleep time
                    sleepTime = (int)(CYCLE_PERIOD - timeDifference);

                    //sleep for remaining cycle
                    if (sleepTime >0){
                        try{
                            Thread.sleep(sleepTime); //saves battery! :)
                        } catch (InterruptedException e){}
                    }
                    //if sleepTime negative then we're running behind
                    while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS){
                        //update without rendering to catch up
                        this.gameview.update();
                        //skip as many frame renders as needed to get back into
                        //positive sleepTime and continue as normal
                        sleepTime += CYCLE_PERIOD;
                        framesSkipped++;
                    }

                }

            } finally{
                //finally executes regardless of exception, 
                //so surface is not left in an inconsistent state
                if (c != null){
                    surfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }

    }

    /* Calculates the average fps every second */
    private void trackFps(){
        long currentTime = System.currentTimeMillis();

        if(timeDifference != 0){
            fpsStore.add((double)(1000 / timeDifference));
        }
        //If a second has past since last time average was calculated,
        // it's time to calculate a new average fps to display
        if ((currentTime - 1000) > lastTimeFpsCalculated){
            int fps = 0;
            int toDivideBy = fpsTrackCount;
            while ((fpsStore !=  null) && (fpsTrackCount > 0 )){
                fps += fpsStore.get(fpsTrackCount-1);
                fpsTrackCount--;
            }
            lastFps = fps / toDivideBy;
            lastTimeFpsCalculated = System.currentTimeMillis();
            fpsTrackCount = 1;
            fpsStore.clear();
        }
        else{   
        fpsTrackCount++;
        }
    }
    /* So That it can be drawn in the gameview */
    public String getFps() {
        return String.valueOf(lastFps);
    }

}

3 个答案:

答案 0 :(得分:2)

好吧,让我们先来看看......

java.lang.IndexOutOfBoundsException: Invalid index 26, size is 6
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
at java.util.ArrayList.get(ArrayList.java:311)
at biz.hireholly.engine.GameLoop.trackFps(GameLoop.java:120)

所以在trackFPS的某个地方,get()是荒谬的超出界限......

private void trackFps()
{
    long currentTime = System.currentTimeMillis();

    if(timeDifference != 0)
    {
        fpsStore.add((double)(1000 / timeDifference));
    }
    //If a second has past since last time average was calculated,
    // it's time to calculate a new average fps to display
    if ((currentTime - 1000) > lastTimeFpsCalculated)
    {
        int fps = 0;
        int toDivideBy = fpsTrackCount;
        while ((fpsStore !=  null || !fpsStore.isEmpty()) && (fpsTrackCount > 0 ) && (fpsTrackCount < fpsStore.getCount()))
        {
            //synchronized(this) {
            fps += fpsStore.get(fpsTrackCount-1);
            fpsStore.remove(fpsTrackCount-1);  //otherwise we'll get stuck because of getCount condition
            fpsTrackCount--;
            //}
        }
        lastFps = fps / toDivideBy;
        lastTimeFpsCalculated = System.currentTimeMillis();
        //fpsTrackCount = 1;
        //fpsStore.clear();
        Log.d("trackFPS()", "fpsTrackCount = "+fpsTrackCount+"\tfpsStore.size() = "+fpsStore.size()+"\t"+fpsStore.toString());
    }
    else   
        fpsTrackCount++;
}

给它一个旋转。如果效果不好,请尝试取消注释sync'd块。

至于你的另一个问题,关于TextDrawable,我看了你的GameView ......

这是我在SurfaceChanged()

中所做的事情
  fps = new TextDrawable();
  fps.setText("HELLO");

现在,你为什么不把它移到SurfaceCreated()?也许你会得到很多surfaceChanged()回调,但由于你没有Logcat调用,所以不知道它? :)它是唯一从我能看到的TextDrawable实例化的地方。

答案 1 :(得分:1)

您还可以在Android Play商店中使用应用来测量FPS。最近发布的一款非常好的应用是GameBench。它不仅可以捕获FPS,还可以捕获屏幕截图,这样您就可以了解FPS下降时的情况。它还提供CPU使用率,在某些设备中也提供GPU使用率。我相信你会发现它很有用。

链接是this

答案 2 :(得分:-4)

我认为这段代码应该适合你

cputhrottle=(int) System.currentTimeMillis();
cputhrottle = (int)System.currentTimeMillis() - cputhrottle;cputhrottle=33-cputhrottle;

每秒30帧对你有用