Files
bworld/client/level/block_predictions.ts
2026-10-12 15:09:22 -03:00

72 lines
2.5 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what this client changed ahead of the server, like minecraft's BlockStatePredictionHandler. each break_block and
// use_block gets a sequence number, and the server sends block_ack with it once it's handled it, after the set_blocks
// it caused. until then, what the server says about a block a guess changed is kept here instead of shown, so the
// answer to an older click can't undo a newer guess, like a trapdoor clicked twice flickering open again
// a block as the server sends it, see set_block
export interface ServerBlock {
x: number;
y: number;
z: number;
id: string;
state: number;
}
export class BlockPredictions {
// the last sequence number handed out
#seq = 0;
// whether a guess is running, see start
#predicting = false;
// the blocks guesses changed, by "x,y,z": the newest guess that changed it, and what the server last said is there
#server = new Map<string, { seq: number; block: ServerBlock }>();
// a guess is starting: the blocks it changes are kept track of until end. returns its sequence number, for the
// message that tells the server what the player did
start(): number {
this.#seq++;
this.#predicting = true;
return this.#seq;
}
end() {
this.#predicting = false;
}
// this client is about to change the block at x y z, which is what current gives now. the first guess to change it
// keeps that as what the server said, later ones only make it wait for their ack too
retain(x: number, y: number, z: number, current: () => ServerBlock) {
if (!this.#predicting) return;
const key = `${x},${y},${z}`;
const known = this.#server.get(key);
if (known) {
known.seq = this.#seq;
} else {
this.#server.set(key, { seq: this.#seq, block: current() });
}
}
// the server says x y z is id with state. returns true when a guess about it is waiting for its ack, then it's kept
// for then instead of shown
from_server(x: number, y: number, z: number, id: string, state: number): boolean {
const known = this.#server.get(`${x},${y},${z}`);
if (!known) return false;
known.block = { x, y, z, id, state };
return true;
}
// the server handled everything up to seq: the blocks only those guesses changed, as the server says they are now,
// to show instead of the guesses
ack(seq: number): ServerBlock[] {
const done: ServerBlock[] = [];
for (const [key, { seq: newest, block }] of this.#server) {
if (newest > seq) continue;
this.#server.delete(key);
done.push(block);
}
return done;
}
}