well, first of all this is not a jPCT question, it's about the strange behaviour of my animation loop on some rare machines. i have no idea why and when that happens, maybe you may have
i've taken the animation loop below from a book about Java games and slightly modified
as you can see, the main idea is to keep updates per second constant (as much as the desired fps = 1 / period). it works reasonably well on most machines (including my slow one) but on some rare ones, updates per second increases unexpectedly up to 2-3 times.
i've no idea how that can happen ? i can only blame window's system clock granularity or sleep time inaccuracies (even with sleep time inaccuracies that loop shouldnt expected to run faster ??)
so do you have any ideas why this may happen ?
thx
edit: the mentioned book by Andrew Davison can be found online at
http://fivedots.coe.psu.ac.th/~ad/jg/
long beforeTime, afterTime, timeDiff, sleepTime;
long overSleepTime = 0;
int noDelays = 0;
long excess = 0;
running = true;
while(running) {
try {
beforeTime = System.nanoTime();
gameUpdate();
if (! paused)
gameRender();
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (period - timeDiff) - overSleepTime;
if (sleepTime > 0) { // some time left in this cycle
try {
Thread.sleep(sleepTime/1000000L); // nano -> ms
} catch(InterruptedException ex) {}
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
} else { // sleepTime <= 0; frame took longer than period
excess -= sleepTime; // store excess time value
overSleepTime = 0L;
if (++noDelays >= KConfig.noDelaysPerYield) {
Thread.yield(); // give another thread a chance to run
noDelays = 0;
}
} // if-else (sleepTime > 0)
/* If rendering is taking too long, update the game state without rendering it, to get the updates/sec nearer to the required FPS. */
int skips = 0;
while (running && (excess > period) && (skips < KConfig.maxFrameSkips)) {
excess -= period;
skips++;
gameUpdate(); // update state but don't render
}
} catch (Throwable t) {
logger.warning("exception in timer thread {0}", t);
}
} // while running
r a f t