Calculate FPS
This commit is contained in:
parent
9d8c975776
commit
52799a6bf0
2 changed files with 34 additions and 5 deletions
|
|
@ -1,7 +1,16 @@
|
|||
export class DeltaTimeCalculator {
|
||||
private previousTime: DOMHighResTimeStamp | null = null;
|
||||
import { clamp } from './clamp';
|
||||
import { exponentialDecay } from './exponential-decay';
|
||||
|
||||
constructor(private readonly maxDeltaTimeInSeconds: number = 1 / 30) {
|
||||
export class DeltaTimeCalculator {
|
||||
private static FPS_EXPONENTIAL_DECAY_STRENGTH = 0.1;
|
||||
|
||||
private previousTime: DOMHighResTimeStamp | null = null;
|
||||
private deltaTimeAccumulator: number | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly maxDeltaTimeInSeconds: number = 1 / 30,
|
||||
private readonly minDeltaTimeInSeconds: number = 1 / 240
|
||||
) {
|
||||
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
|
||||
}
|
||||
|
||||
|
|
@ -14,8 +23,15 @@ export class DeltaTimeCalculator {
|
|||
|
||||
const delta = currentTime - this.previousTime;
|
||||
this.previousTime = currentTime;
|
||||
return 1 / 60;
|
||||
return Math.min(delta / 1000, this.maxDeltaTimeInSeconds);
|
||||
const deltaInSeconds = delta / 1000;
|
||||
|
||||
this.deltaTimeAccumulator = exponentialDecay({
|
||||
accumulator: this.deltaTimeAccumulator ?? deltaInSeconds,
|
||||
nextValue: deltaInSeconds,
|
||||
biasOfNextValue: DeltaTimeCalculator.FPS_EXPONENTIAL_DECAY_STRENGTH,
|
||||
});
|
||||
|
||||
return clamp(delta / 1000, this.minDeltaTimeInSeconds, this.maxDeltaTimeInSeconds);
|
||||
}
|
||||
|
||||
private handleVisibilityChange() {
|
||||
|
|
@ -23,4 +39,8 @@ export class DeltaTimeCalculator {
|
|||
this.previousTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
public get fps() {
|
||||
return 1 / this.deltaTimeAccumulator;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
9
src/utils/exponential-decay.ts
Normal file
9
src/utils/exponential-decay.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export const exponentialDecay = ({
|
||||
accumulator,
|
||||
nextValue,
|
||||
biasOfNextValue,
|
||||
}: {
|
||||
accumulator: number;
|
||||
nextValue: number;
|
||||
biasOfNextValue: number;
|
||||
}) => accumulator * (1 - biasOfNextValue) + nextValue * biasOfNextValue;
|
||||
Loading…
Add table
Add a link
Reference in a new issue