Add sleep to game loop

This should ensure that the program does not hog up an entire CPU core just to get the current time.
This commit is contained in:
CuriouslyCurious 2025-12-15 17:54:36 +01:00
parent ae7723b0d2
commit b8969cde39
No known key found for this signature in database
GPG key ID: 5C1280AAD1EFE605
2 changed files with 15 additions and 1 deletions

View file

@ -613,6 +613,7 @@ public abstract class GameShell extends Applet implements Runnable, FocusListene
long lastUpdateTime = 0; long lastUpdateTime = 0;
long lastDrawTime = 0; long lastDrawTime = 0;
long nextUpdate = 0;
while (killTime == 0L) { while (killTime == 0L) {
if (GameShell.killTime > MonotonicClock.currentTimeMillis()) { if (GameShell.killTime > MonotonicClock.currentTimeMillis()) {
break; break;
@ -621,6 +622,14 @@ public abstract class GameShell extends Applet implements Runnable, FocusListene
long currentTime = System.nanoTime(); long currentTime = System.nanoTime();
updateDelta = currentTime - lastUpdateTime; updateDelta = currentTime - lastUpdateTime;
renderDelta = currentTime - lastDrawTime;
nextUpdate = Math.min(FIXED_UPDATE_RATE_NS - updateDelta, VARIABLE_RENDER_RATE_NS - renderDelta);
// Convert from ns to ms
nextUpdate /= 1_000_000;
ThreadUtils.sleep(nextUpdate);
// Game update
if (updateDelta >= FIXED_UPDATE_RATE_NS) { if (updateDelta >= FIXED_UPDATE_RATE_NS) {
logicCycles = timer.count(minimumDelay, (int) FIXED_UPDATE_RATE); logicCycles = timer.count(minimumDelay, (int) FIXED_UPDATE_RATE);
for (int cycle = 0; cycle < logicCycles; ++cycle) { for (int cycle = 0; cycle < logicCycles; ++cycle) {
@ -630,7 +639,7 @@ public abstract class GameShell extends Applet implements Runnable, FocusListene
flush(signLink, canvas); flush(signLink, canvas);
} }
renderDelta = currentTime - lastDrawTime; // Render update
if (renderDelta >= VARIABLE_RENDER_RATE_NS) { if (renderDelta >= VARIABLE_RENDER_RATE_NS) {
this.mainInputLoop(); this.mainInputLoop();
this.mainRedrawWrapper(); this.mainRedrawWrapper();

View file

@ -5,6 +5,11 @@ import org.openrs2.deob.annotation.OriginalMember;
import org.openrs2.deob.annotation.Pc; import org.openrs2.deob.annotation.Pc;
public class ThreadUtils { public class ThreadUtils {
/**
* Sleeps the current thread for a set amount of milliseconds.
*
* @param arg0. Time in milliseconds to sleep for.
*/
@OriginalMember(owner = "client!sk", name = "a", descriptor = "(JI)V") @OriginalMember(owner = "client!sk", name = "a", descriptor = "(JI)V")
public static void sleep(@OriginalArg(0) long arg0) { public static void sleep(@OriginalArg(0) long arg0) {
if (arg0 <= 0L) { if (arg0 <= 0L) {