Predict interactions with blocks

This commit is contained in:
2026-10-10 14:21:27 -03:00
parent 7fe9c15b67
commit 79ff6f9ad5
15 changed files with 355 additions and 73 deletions
+32 -1
View File
@@ -29,6 +29,7 @@ import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "$/common/block_models.ts";
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.ts";
import type { ItemStack } from "$/common/inventory.ts";
import { BlockPredictions } from "./block_predictions.ts";
export interface Block {
id: string;
@@ -119,6 +120,8 @@ export class ClientLevel {
view_distance: number;
// the chunk the server says the player is in
center: { x: number; z: number } | undefined;
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
predictions = new BlockPredictions();
workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
@@ -259,6 +262,7 @@ export class ClientLevel {
}
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
this.#retain(block.x, block.y, block.z);
const lx = block.x - block_chunk_x * CHUNK_SIZE;
const lz = block.z - block_chunk_z * CHUNK_SIZE;
@@ -375,6 +379,8 @@ export class ClientLevel {
return;
}
this.#retain(x, y, z);
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const ly = y;
@@ -451,8 +457,33 @@ export class ClientLevel {
return [x, y, z];
}
// set a block the server told us about. the server only sends them for chunks this client has
// set a block the server told us about. the server only sends them for chunks this client has. a block this
// client guessed waits for the server's ack instead, see BlockPredictions
apply_change(x: number, y: number, z: number, id: string, state = 0) {
if (this.predictions.from_server(x, y, z, id, state)) {
return;
}
this.#set_from_server(x, y, z, id, state);
}
// the server handled this client's guesses up to seq, what it said about the blocks they changed shows now
ack_predictions(seq: number) {
for (const { x, y, z, id, state } of this.predictions.ack(seq)) {
this.#set_from_server(x, y, z, id, state);
}
}
// while guessing, keeps what's at x y z before the guess changes it, as the server would say it
#retain(x: number, y: number, z: number) {
this.predictions.retain(x, y, z, () => {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
const id = nid === AIR ? AIR_ID : this.#blocks[nid]?.id ?? AIR_ID;
return { x, y, z, id, state: value >>> 16 };
});
}
#set_from_server(x: number, y: number, z: number, id: string, state: number) {
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!chunk) {
return;