Skip to content

Commit

Permalink
Add timer limiter to keep steps per update managable. (#510)
Browse files Browse the repository at this point in the history
Closes #489, #504

Co-authored-by: David Souther <[email protected]>
  • Loading branch information
DavidSouther and David Souther authored Dec 2, 2024
1 parent 002568c commit 564ee90
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions simulator/src/timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ export const MAX_STEPS = 1000;

const clock = Clock.get();

const BUDGET = 8; // ms allowed per tick

export abstract class Timer {
frame() {
this.tick();
Expand All @@ -26,8 +28,24 @@ export abstract class Timer {

abstract toggle(): void;

steps = 1; // How many steps to take per update
speed = 1000; // how often to update, in ms
_steps = 1; // How many steps to take per update
_steps_actual = 1;
get steps() {
return this._steps;
}
set steps(value: number) {
this._steps = value;
this._steps_actual = value;
}

_speed = 60; // how often to update, in ms
get speed() {
return this._speed;
}
set speed(value: number) {
this._speed = value;
}

get running() {
return this.#running;
}
Expand All @@ -45,15 +63,19 @@ export abstract class Timer {
this.#sinceLastFrame += delta;
if (this.#sinceLastFrame > this.speed) {
let done = false;
// let steps = Math.min(this.steps, MAX_STEPS);
let steps = this.steps;
const timingLabel = `Timing ${steps} steps`;
console.time(timingLabel);
while (!done && steps--) {
// done = await this.tick();
let steps = Math.min(this._steps, this._steps_actual);

const startTime = performance.now();
while (!done && steps-- > 0) {
done = await this.tick();
}
console.timeEnd(timingLabel);
const endTime = performance.now();

// Dynamically adjust steps to stay within BUDGET ms per update, to avoid blocking the main thread.
const duration = endTime - startTime;
this._steps_actual *= BUDGET / duration;
this._steps_actual = Math.ceil(this._steps_actual);

this.finishFrame();
if (done) {
this.stop();
Expand Down

0 comments on commit 564ee90

Please sign in to comment.