Skip to content

Implement accumulator pattern for precise frame rate limiting #16484

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

Merged
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
22 changes: 16 additions & 6 deletions packages/dev/core/src/Engines/abstractEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,7 @@ export abstract class AbstractEngine {
protected _maxFPS: number | undefined;
protected _minFrameTime: number;
protected _lastFrameTime: number = 0;
protected _renderAccumulator: number = 0;

/**
* Skip frame rendering but keep the frame heartbeat (begin/end frame).
Expand All @@ -919,21 +920,30 @@ export abstract class AbstractEngine {
return;
}

this._minFrameTime = 1000 / (value + 1); // We need to provide a bit of leeway to ensure we don't go under because of vbl sync
this._minFrameTime = 1000 / value;
}

protected _isOverFrameTime(timestamp?: number): boolean {
if (!timestamp) {
if (!timestamp || this._maxFPS === undefined) {
return false;
}

const elapsedTime = timestamp - this._lastFrameTime;
if (this._maxFPS === undefined || elapsedTime >= this._minFrameTime) {
this._lastFrameTime = timestamp;
return false;
this._lastFrameTime = timestamp;

this._renderAccumulator += elapsedTime;

if (this._renderAccumulator < this._minFrameTime) {
return true;
}

return true;
this._renderAccumulator -= this._minFrameTime;

if (this._renderAccumulator > this._minFrameTime) {
this._renderAccumulator = this._minFrameTime;
}

return false;
}

protected _processFrame(timestamp?: number) {
Expand Down