Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add timer limiter to keep steps per update managable. #510

Merged
merged 1 commit into from
Dec 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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