Fix delta time calculation

This commit is contained in:
Andras Schmelczer 2023-07-15 13:29:06 +01:00
parent bde0ad8f25
commit 379ee14739
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
2 changed files with 36 additions and 33 deletions

View file

@ -143,9 +143,8 @@ export class GameServer extends CommandReceiver {
private timeSinceLastPointUpdate = 0; private timeSinceLastPointUpdate = 0;
private handlePhysics() { private handlePhysics() {
const delta = this.deltaTimeCalculator.getNextDeltaTimeInSeconds(); const delta = this.deltaTimeCalculator.getNextDeltaTimeInSeconds({ setAsBase: true });
if (delta > settings.targetPhysicsDeltaTimeInSeconds) { this.deltaTimes.push(delta);
this.deltaTimeCalculator.getNextDeltaTimeInSeconds(true);
this.handleStats(); this.handleStats();
@ -172,10 +171,12 @@ export class GameServer extends CommandReceiver {
this.players.stepCommunication(delta); this.players.stepCommunication(delta);
this.objects.resetRemoteCalls(); this.objects.resetRemoteCalls();
this.deltaTimes.push(this.deltaTimeCalculator.getNextDeltaTimeInSeconds()); const physicsDelta = this.deltaTimeCalculator.getNextDeltaTimeInSeconds();
}
setImmediate(this.handlePhysics.bind(this)); setTimeout(
this.handlePhysics.bind(this),
Math.max(0, settings.targetPhysicsDeltaTimeInSeconds - physicsDelta) * 1000,
);
} }
private handleStats() { private handleStats() {
@ -184,9 +185,9 @@ export class GameServer extends CommandReceiver {
if (this.deltaTimes.length > framesBetweenDeltaTimeCalculation) { if (this.deltaTimes.length > framesBetweenDeltaTimeCalculation) {
this.deltaTimes.sort((a, b) => a - b); this.deltaTimes.sort((a, b) => a - b);
console.info( console.info(
`Median physics time: ${this.deltaTimes[ `Median physics time: ${(
Math.floor(framesBetweenDeltaTimeCalculation / 2) this.deltaTimes[Math.floor(framesBetweenDeltaTimeCalculation / 2)] * 1000
].toFixed(2)} ms`, ).toFixed(2)} ms`,
); );
console.info( console.info(
'Tail times: ', 'Tail times: ',

View file

@ -1,7 +1,9 @@
export class DeltaTimeCalculator { export class DeltaTimeCalculator {
private previousTime: [number, number] = process.hrtime(); private previousTime: [number, number] = process.hrtime();
public getNextDeltaTimeInSeconds(setAsBase = false): number { public getNextDeltaTimeInSeconds(
{ setAsBase = false }: { setAsBase: boolean } = { setAsBase: false },
): number {
const [seconds, nanoSeconds] = process.hrtime(this.previousTime); const [seconds, nanoSeconds] = process.hrtime(this.previousTime);
if (setAsBase) { if (setAsBase) {
this.previousTime = process.hrtime(); this.previousTime = process.hrtime();