This repository has been archived on 2021-02-20. You can view files and clone it, but cannot push or open issues or pull requests.
shapez.io/src/js/game/dynamic_tickrate.js

101 lines
3.0 KiB
JavaScript
Raw Normal View History

2020-05-18 12:53:01 +02:00
import { GameRoot } from "./root";
import { createLogger } from "../core/logging";
import { globalConfig } from "../core/config";
import { performanceNow, Math_min, Math_round, Math_max } from "../core/builtins";
import { round3Digits } from "../core/utils";
const logger = createLogger("dynamic_tickrate");
export class DynamicTickrate {
/**
*
* @param {GameRoot} root
*/
constructor(root) {
this.root = root;
this.currentTickStart = null;
this.capturedTicks = [];
this.averageTickDuration = 0;
this.setTickRate(60);
2020-05-18 12:53:01 +02:00
}
/**
* Sets the tick rate to N updates per second
* @param {number} rate
*/
setTickRate(rate) {
logger.log("Applying tick-rate of", rate);
this.currentTickRate = rate;
this.deltaMs = 1000.0 / this.currentTickRate;
this.deltaSeconds = 1.0 / this.currentTickRate;
}
/**
* Increases the tick rate marginally
*/
increaseTickRate() {
this.setTickRate(Math_round(Math_min(globalConfig.maximumTickRate, this.currentTickRate * 1.2)));
2020-05-18 12:53:01 +02:00
}
/**
* Decreases the tick rate marginally
*/
decreaseTickRate() {
this.setTickRate(Math_round(Math_max(globalConfig.minimumTickRate, this.currentTickRate * 0.8)));
2020-05-18 12:53:01 +02:00
}
/**
* Call whenever a tick began
*/
beginTick() {
assert(this.currentTickStart === null, "BeginTick called twice");
this.currentTickStart = performanceNow();
if (this.capturedTicks.length > this.currentTickRate * 2) {
2020-05-18 12:53:01 +02:00
// Take only a portion of the ticks
this.capturedTicks.sort();
this.capturedTicks.splice(0, 10);
this.capturedTicks.splice(this.capturedTicks.length - 11, 10);
let average = 0;
for (let i = 0; i < this.capturedTicks.length; ++i) {
average += this.capturedTicks[i];
}
average /= this.capturedTicks.length;
// Calculate tick duration to cover X% of the frame
const ticksPerFrame = this.currentTickRate / 60;
const maxFrameDurationMs = 8;
const maxTickDuration = maxFrameDurationMs / ticksPerFrame;
// const maxTickDuration = (1000 / this.currentTickRate) * 0.75;
logger.log(
"Average time per tick:",
round3Digits(average) + "ms",
"allowed are",
maxTickDuration
);
this.averageTickDuration = average;
if (average < maxTickDuration) {
this.increaseTickRate();
} else {
this.decreaseTickRate();
}
this.capturedTicks = [];
}
}
/**
* Call whenever a tick ended
*/
endTick() {
assert(this.currentTickStart !== null, "EndTick called without BeginTick");
const duration = performanceNow() - this.currentTickStart;
this.capturedTicks.push(duration);
this.currentTickStart = null;
}
}