UNPKG

@geckos.io/snapshot-interpolation

Version:

A Snapshot Interpolation library for Real-Time Multiplayer Games

66 lines 2.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Vault = void 0; /** A save place to store your snapshots. */ class Vault { constructor() { this._vault = []; this._vaultSize = 120; } /** Get a Snapshot by its ID. */ getById(id) { var _a; return (_a = this._vault.filter(snapshot => snapshot.id === id)) === null || _a === void 0 ? void 0 : _a[0]; } /** Clear this Vault */ clear() { this._vault = []; } get(time, closest) { var _a; // zero index is the newest snapshot const sorted = this._vault.sort((a, b) => b.time - a.time); if (typeof time === 'undefined') return sorted[0]; for (let i = 0; i < sorted.length; i++) { const snap = sorted[i]; if (snap.time <= time) { const snaps = { older: sorted[i], newer: sorted[i - 1] }; if (closest) { const older = Math.abs(time - snaps.older.time); const newer = Math.abs(time - ((_a = snaps.newer) === null || _a === void 0 ? void 0 : _a.time)); if (isNaN(newer)) return snaps.older; else if (newer <= older) return snaps.older; else return snaps.newer; } return snaps; } } return; } /** Add a snapshot to the vault. */ add(snapshot) { if (this._vault.length > this._vaultSize - 1) { // remove the oldest snapshot this._vault.sort((a, b) => a.time - b.time).shift(); } this._vault.push(snapshot); } /** Get the current capacity (size) of the vault. */ get size() { return this._vault.length; } /** Set the max capacity (size) of the vault. */ setMaxSize(size) { this._vaultSize = size; } /** Get the max capacity (size) of the vault. */ getMaxSize() { return this._vaultSize; } } exports.Vault = Vault; //# sourceMappingURL=vault.js.map