From 79ff6f9ad5d4b71917ce15c9202e2c041063f2e1 Mon Sep 17 00:00:00 2001 From: Paula Date: Sat, 10 Oct 2026 14:21:27 -0300 Subject: [PATCH] Predict interactions with blocks --- client/game_mode.ts | 52 ++++++++++++++++++----- client/level/block_predictions.ts | 68 +++++++++++++++++++++++++++++++ client/level/client_level.ts | 33 ++++++++++++++- client/packet_listener.ts | 3 ++ common/block_rules.ts | 23 ++++++++++- common/mod_api/shared.ts | 12 ++++++ common/protocol.ts | 12 ++++-- docs/modding/blocks/components.md | 64 ++++++++++++++++++----------- docs/modding/concepts/events.md | 5 ++- docs/modding/concepts/sides.md | 28 +++++++------ mods/bworld/scripts/server.ts | 12 ------ mods/bworld/scripts/shared.ts | 10 ++++- server/game/game_server.ts | 19 ++++++++- tests/block_predictions_test.ts | 64 +++++++++++++++++++++++++++++ tests/shared_rules_test.ts | 23 ++++++++++- 15 files changed, 355 insertions(+), 73 deletions(-) create mode 100644 client/level/block_predictions.ts create mode 100644 tests/block_predictions_test.ts diff --git a/client/game_mode.ts b/client/game_mode.ts index bc79332..9862308 100644 --- a/client/game_mode.ts +++ b/client/game_mode.ts @@ -4,7 +4,7 @@ import type { Client } from "./client.ts"; import type { BlockHitResult } from "./level/client_level.ts"; import type { Container } from "$/common/inventory.ts"; import { AIR_ID } from "$/common/protocol.ts"; -import { box_overlaps_block, can_place, placement_target, waterlog_placement } from "$/common/utils.ts"; +import { box_overlaps_block, can_place, liquid_block, placement_target, waterlog_placement } from "$/common/utils.ts"; import { block_rules, predict_neighbors } from "./mods.ts"; import { collision_shape_at } from "$/common/block_shapes.ts"; import type { EntityJson } from "$/common/mod_data.ts"; @@ -47,9 +47,11 @@ export class MultiPlayerGameMode { if (this.destroy_progress >= this.destroy_time) { // show it right away, the server decides drops and corrects us if it disagrees - this.client.level.break_block(hit.x, hit.y, hit.z); - predict_neighbors(hit.x, hit.y, hit.z); - this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z }); + this.#predict((seq) => { + this.client.level.break_block(hit.x, hit.y, hit.z); + predict_neighbors(hit.x, hit.y, hit.z); + this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z, seq }); + }); this.destroy_progress = 0; this.destroy_time = 0; } @@ -63,26 +65,42 @@ export class MultiPlayerGameMode { // right click on a block use_item_on(hit: BlockHitResult) { - const level = this.client.level; // the server checks that the block isn't going inside the player with where it is now, like this does this.client.player.send_position_now(); - this.client.connection.send({ type: "use_block", x: hit.x, y: hit.y, z: hit.z, face: hit.face, hit: hit.hit }); + this.#predict((seq) => { + const { x, y, z, face } = hit; + this.client.connection.send({ type: "use_block", x, y, z, face, hit: hit.hit, seq }); + this.#guess_use(hit); + }); + } + + // what using a block will do, shown right away + #guess_use(hit: BlockHitResult) { + const level = this.client.level; + + // the shared rules' on_interact, like a trapdoor opening, shows right away. the server runs them too and corrects + // this if it disagrees. when they do something nothing is placed, like on the server + // an item aimed at liquids, like a bucket, uses the liquid in a waterlogged block instead, like on the server + const block_info = EverythingRegistry.get_by_id("blocks", hit.block)!; + const held = this.held_item(); + const value = level.get_block_value(hit.x, hit.y, hit.z); + const used = (held?.targets_liquids && liquid_block(value, block_info)) || block_info; + const interaction = { face: hit.face, hit: hit.hit }; + if (block_rules.interact(used, hit.x, hit.y, hit.z, interaction, this.client.player.yaw)) return; // guess that it places the held block, unless the block does something when used. the same rules as the server: // into the clicked block when it's replaceable, and only where place_in and place_on allow - const block_info = EverythingRegistry.get_by_id("blocks", hit.block)!; const target = placement_target(hit.x, hit.y, hit.z, FACE_OFFSETS[hit.face], block_info); const current = level.get_block(target.x, target.y, target.z); const below = level.get_block(target.x, target.y - 1, target.z); const below_id = EverythingRegistry.get_by_id("blocks", below)?.id ?? AIR_ID; - const held = this.held_item(); // items with components might do something else on the server, like on_use const place_id = held?.components ? undefined : held?.block_id; const place_block = place_id !== undefined ? EverythingRegistry.get("blocks", place_id) : undefined; // with the states the server will give it, see BlockRules.placement_value, and holding the liquid it goes into - const value = place_block && + const place_value = place_block && waterlog_placement( block_rules.placement_value(place_block, this.client.player.yaw, { ...target, @@ -98,9 +116,9 @@ export class MultiPlayerGameMode { current === AIR ? undefined : EverythingRegistry.get_by_id("blocks", current), level.get_block_value(target.x, target.y, target.z), below_id, - ) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, value!)); + ) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!)); if (!block_info.interactive && place_id && placeable) { - level.add_block({ ...target, id: place_id }, value! >>> 16); + level.add_block({ ...target, id: place_id }, place_value! >>> 16); predict_neighbors(target.x, target.y, target.z); const slot = this.#held_slot(); slot.amount = slot.amount! - 1; @@ -151,6 +169,18 @@ export class MultiPlayerGameMode { return false; } + // runs guess with the blocks it changes kept track of, like minecraft's startPrediction. what the server says about + // them waits until it answers the message guess sends with seq, see client/level/block_predictions.ts + #predict(guess: (seq: number) => void) { + const predictions = this.client.level.predictions; + const seq = predictions.start(); + try { + guess(seq); + } finally { + predictions.end(); + } + } + #held_slot() { const inventories = this.client.player.inventories; return inventories.inventory.get_slot(inventories.hotbar_selected); diff --git a/client/level/block_predictions.ts b/client/level/block_predictions.ts new file mode 100644 index 0000000..c158d92 --- /dev/null +++ b/client/level/block_predictions.ts @@ -0,0 +1,68 @@ +// 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(); + + // 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; + } +} diff --git a/client/level/client_level.ts b/client/level/client_level.ts index 5f5fb15..5179953 100644 --- a/client/level/client_level.ts +++ b/client/level/client_level.ts @@ -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("blocks"); @@ -259,6 +262,7 @@ export class ClientLevel { } const [nid, info] = EverythingRegistry.get_full("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; diff --git a/client/packet_listener.ts b/client/packet_listener.ts index a359a73..46b826b 100644 --- a/client/packet_listener.ts +++ b/client/packet_listener.ts @@ -175,6 +175,9 @@ export class ClientPacketListener { case "set_block": level.apply_change(message.x, message.y, message.z, message.id, message.state); break; + case "block_ack": + level.ack_predictions(message.seq); + break; case "set_block_item": level.set_block_item( message.x, diff --git a/common/block_rules.ts b/common/block_rules.ts index e176d5f..1f61367 100644 --- a/common/block_rules.ts +++ b/common/block_rules.ts @@ -1,7 +1,7 @@ // the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on // clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own // BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with -import type { BlockPlacement, BlockRules as Rules, SharedWorld } from "./mod_api/shared.ts"; +import type { BlockInteraction, BlockPlacement, BlockRules as Rules, SharedWorld } from "./mod_api/shared.ts"; import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts"; import { default_block_value, set_state_value } from "./utils.ts"; @@ -75,6 +75,27 @@ export class BlockRules { return value; } + // a player right clicked the block at x y z: its rules' on_interact, every one of them. returns whether any did + // something. what they change goes through the side's world, so on a client it's a guess the server corrects + interact( + block: BlockRegistry, + x: number, + y: number, + z: number, + interaction: Omit, + yaw: number, + ): boolean { + const at = { x, y, z, id: block.id }; + const full: BlockInteraction = { ...interaction, facing: horizontal_facing(yaw) }; + let handled = false; + for (const { mod, id, rules, params } of this.#of(block)) { + if (!rules.on_interact) continue; + handled = this.run(mod, `${id} on_interact`, () => rules.on_interact!(at, params, full)) === true || + handled; + } + return handled; + } + // tells the blocks beside x y z it changed, so they can change with it like a fence joining it: their rules' // on_neighbor_change. the world's set_state calls this again for what they change, until nothing changes notify_neighbors(get_block: SharedWorld["get_block"], x: number, y: number, z: number) { diff --git a/common/mod_api/shared.ts b/common/mod_api/shared.ts index 167225d..ea9f4dd 100644 --- a/common/mod_api/shared.ts +++ b/common/mod_api/shared.ts @@ -97,6 +97,14 @@ export interface BlockPlacement extends Position { readonly facing: "north" | "east" | "south" | "west"; } +// a player right clicking face of a block, at hit (0 to 1 on each axis of the block), like minecraft's BlockHitResult. +// facing is the way the player looks, along the ground +export interface BlockInteraction { + readonly face: Face; + readonly hit: readonly [number, number, number]; + readonly facing: "north" | "east" | "south" | "west"; +} + // P is the component's params from the block json // deno-lint-ignore no-explicit-any export interface BlockRules

{ @@ -106,4 +114,8 @@ export interface BlockRules

{ // a block next to it (on any of the 6 sides) was placed, broken or changed its states, like minecraft's // updateShape. neighbor is where, and what's there now on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void; + // a player right clicks it, like minecraft's useWithoutItem: changes only its states and its neighbors', which + // the clicking client shows right away instead of waiting for the server. return true if it did something, then + // nothing is placed. the server runs the server script's on_interact too + on_interact?(block: SharedBlock, params: P, interaction: BlockInteraction): boolean | void; } diff --git a/common/protocol.ts b/common/protocol.ts index da98938..98d80db 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 19; +export const PROTOCOL_VERSION = 20; export interface PlayerInfo { id: string; @@ -101,7 +101,8 @@ export type ClientMessage = teleport?: number; swimming?: boolean; } - | { type: "break_block"; x: number; y: number; z: number } + // seq numbers what this client guessed for it, the server answers with block_ack. see client/level/block_predictions.ts + | { type: "break_block"; x: number; y: number; z: number; seq?: number } // the player started hitting a block, for on_click | { type: "hit_block"; x: number; y: number; z: number } // left click on an entity, by id @@ -111,8 +112,8 @@ export type ClientMessage = // right click without looking at a block, for items' on_use | { type: "use_item" } // right click on a block: interact with it, or place the held block against `face`. hit is where on the block it - // clicked, 0 to 1 on each axis, like minecraft's click location - | { type: "use_block"; x: number; y: number; z: number; face: Faces; hit?: [number, number, number] } + // clicked, 0 to 1 on each axis, like minecraft's click location. seq is like break_block's + | { type: "use_block"; x: number; y: number; z: number; face: Faces; hit?: [number, number, number]; seq?: number } | { type: "select_slot"; slot: number } // a slot of the open menu, or of menu 0 when none is. shift moves the stack to the other part of the menu instead, // like minecraft's quick move. clicks for a menu that isn't open any more are ignored @@ -208,6 +209,9 @@ export type ServerMessage = // to the players who have the chunk, including the one who caused it, which corrects anything their client // predicted wrong | { type: "set_block"; x: number; y: number; z: number; id: string; state?: number } + // the break_block or use_block with this seq is handled, and so is every one before it. the set_blocks it caused + // came first, and what they said about blocks this client guessed shows now + | { type: "block_ack"; seq: number } // the item a block shows, see BlockRegistry.item_display. to the players who have the chunk, after it and whenever // it changes. null when it shows nothing any more | { type: "set_block_item"; x: number; y: number; z: number; item: ItemData | null } diff --git a/docs/modding/blocks/components.md b/docs/modding/blocks/components.md index e27d529..34bf32e 100644 --- a/docs/modding/blocks/components.md +++ b/docs/modding/blocks/components.md @@ -75,10 +75,10 @@ this component, and `dt` is in seconds. ## Rules -A component's rules decide a block's states from where it's placed and what's around it. They're registered in the mod's -[shared script](../concepts/sides.md#shared-scripts) instead, under the same id, because clients run them too: that's -how a player sees a fence join its neighbors the moment they place it, instead of a moment later when the server -answers. A component can have rules, handlers, or both, and a block can list one that only has rules. +A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're +registered in the mod's [shared script](../concepts/sides.md#shared-scripts) instead, under the same id, because clients +run them too: that's how a player sees a fence join its neighbors the moment they place it, instead of a moment later +when the server answers. A component can have rules, handlers, or both, and a block can list one that only has rules. ```ts import type { SharedContext } from "bworld/shared"; @@ -87,14 +87,16 @@ export function setup(ctx: SharedContext) { ctx.components.register_block("copper_tools:pipe", { state_for_placement(placement, params) {/* ... */}, on_neighbor_change(block, params, neighbor) {/* ... */}, + on_interact(block, params, interaction) {/* ... */}, }); } ``` -| Rule | Called when | Returns | -| --------------------------------------------- | ---------------------------------------------------------------------- | ----------------------- | -| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with | -| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | | +| Rule | Called when | Returns | +| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------- | +| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with | +| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | | +| `on_interact(block, params, interaction)` | A player right clicks it. | `true` if it did something | Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in a shared script has `get_block`, `get_state`, `set_state`, `is_face_sturdy`, `biome_at` and `season_at` (see @@ -133,8 +135,22 @@ after. Both are in `mods/bworld/scripts/shared.ts`. ### Interacting -When a player right clicks a block, every component's `on_interact` runs. If any of them returns `true`, the click was -handled and nothing else happens. Otherwise the held item is used or placed, as if the block had no components. +When a player right clicks a block, every component's `on_interact` runs: the rules' first, then the handlers'. If any +of them returns `true`, the click was handled and nothing else happens. Otherwise the held item is used or placed, as if +the block had no components. + +A rule's `on_interact` also runs on the clicking player's client, so they see what it does right away instead of waiting +for the server, like a trapdoor opening. It's for clicks that only change states with `ctx.world.set_state`, like +Minecraft's `useWithoutItem`: anything that needs the server, like opening a screen, giving items or tile data, goes in +the handler. `interaction` is `{ face, hit, facing }`: the face that was clicked, where on it (from 0 to 1 on each +axis), and the way the player looks along the ground. The trapdoor's is in `mods/bworld/scripts/shared.ts`: + +```ts +on_interact(block) { + const open = ctx.world.get_state(block.x, block.y, block.z, "open") ?? 0; + return ctx.world.set_state(block.x, block.y, block.z, "open", open ? 0 : 1); +}, +``` Give a block `"interactive": true` when right clicking it always does something, like opening a screen. Otherwise clients guess that the click places the held block and show it for a moment before the server corrects them. @@ -155,19 +171,19 @@ catch up. If it's further behind than that, it skips the rest and logs a warning `mods/bworld/scripts/server.ts` registers these, and any mod that depends on `bworld` can use them: -| Component | Params | What it does | -| ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. | -| `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it with a `base_sell_value` for coins. | -| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. | -| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. | -| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. | -| `bworld:farmland` | none | Watered with the watering can, dries out every morning. | -| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. | -| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. | -| `bworld:water_source` | none | Refills the watering can. | -| `bworld:fishable` | none | The fishing rod's hook floats on it and fish bite there when it lands in it. | -| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (its rules are in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. | -| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. | +| Component | Params | What it does | +| ----------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. | +| `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it with a `base_sell_value` for coins. | +| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. | +| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. | +| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. | +| `bworld:farmland` | none | Watered with the watering can, dries out every morning. | +| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. | +| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. | +| `bworld:water_source` | none | Refills the watering can. | +| `bworld:fishable` | none | The fishing rod's hook floats on it and fish bite there when it lands in it. | +| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. | +| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. | Item components work the same way, see [Items](../items/index.md#item-components). diff --git a/docs/modding/concepts/events.md b/docs/modding/concepts/events.md index 04554cd..6973206 100644 --- a/docs/modding/concepts/events.md +++ b/docs/modding/concepts/events.md @@ -61,8 +61,9 @@ showed. These events fire for **every** player's actions, since they all go thro ### Order Handlers run in the order they subscribed, and mods' `setup` functions run in [load order](registries.md#loading). For -`block_interact`, the before event runs first, then the block's own components' `on_interact`. If no component handled -the click and the held item has no `on_use`, the held block is placed, which fires `block_place`. +`block_interact`, the before event runs first, then the block's own components' `on_interact`, rules before handlers. If +no component handled the click and the held item has no `on_use`, the held block is placed, which fires `block_place`. +Cancelling it undoes what the clicking player's client guessed, like a trapdoor it showed opening. ## Errors diff --git a/docs/modding/concepts/sides.md b/docs/modding/concepts/sides.md index 4c97227..a15570a 100644 --- a/docs/modding/concepts/sides.md +++ b/docs/modding/concepts/sides.md @@ -9,11 +9,13 @@ Clients send what the player is _trying_ to do: "break the block at x, y, z", "u slot 3". The server checks it (reach, the item being held, container rules), runs mod logic, and sends back what happened. -For responsiveness, the client guesses the result of breaking and placing blocks and shows it right away, with the -states the server will give them: it runs the same [shared scripts](#shared-scripts) the server does. When the server -disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is undone. -Blocks with `"interactive": true` tell the client not to guess, since right clicking them does something other than -placing. +For responsiveness, the client guesses the result of breaking, placing and right clicking blocks and shows it right +away, with the states the server will give them: it runs the same [shared scripts](#shared-scripts) the server does. +When the server disagrees, like when a before event cancels a placement, it sends that player the real block and the +guess is undone. Like Minecraft, each click is numbered and the server says when it's done with it: until then the +client keeps showing its guess, so the server's answer to an earlier click can't flicker a block a newer one changed, +like a trapdoor clicked twice. Blocks with `"interactive": true` tell the client not to guess a placement, since right +clicking them does something else. ``` server process browser @@ -85,19 +87,21 @@ export function setup(ctx: SharedContext) { ctx.components.register_block("copper_tools:pipe", { state_for_placement(placement) {/* ... */}, on_neighbor_change(block, params, neighbor) {/* ... */}, + on_interact(block, params, interaction) {/* ... */}, }); } ``` Shared scripts hold a block component's rules, the code Minecraft runs on both sides: what states a block is placed with -(`state_for_placement`) and how it changes with the blocks beside it (`on_neighbor_change`). See -[Block Components](../blocks/components.md#placing). The server script registers the rest of the same component, like -its `on_interact`, under the same id. +(`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it +changes (`on_interact`, like a trapdoor opening). See [Block Components](../blocks/components.md#rules). The server +script registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the +same id. -On the server they run on the real world. On a client they run on what that client shows, when its player places or -breaks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and the -server's answer replaces it a moment later, so a shared script that gives a different answer on a client only costs a -flicker. `ctx.side` says which one it's running on. +On the server they run on the real world. On a client they run on what that client shows, when its player places, breaks +or right clicks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and +the server's answer replaces it a moment later, so a shared script that gives a different answer on a client only costs +a flicker. `ctx.side` says which one it's running on. `setup` runs before the server or client script on each side, for every mod first, so their scripts can count on any mod's rules being there. Rules can only be registered during `setup`, and `ctx.world` only works in them. diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index ca10494..e1a0d83 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -10,7 +10,6 @@ export function setup(ctx: ServerContext) { register_shipping_bin(ctx, storage_menu); register_furnace(ctx); register_smithing_table(ctx); - register_trapdoor(ctx); register_farming(ctx); register_fishing(ctx); register_buckets(ctx); @@ -32,17 +31,6 @@ function register_hoeable(ctx: ServerContext) { }); } -// a trapdoor opens and closes when right clicked, like a wooden one in minecraft. how it's placed is in shared.ts -function register_trapdoor(ctx: ServerContext) { - ctx.components.register_block("bworld:trapdoor", { - on_interact(block) { - const open = ctx.world.get_state(block.x, block.y, block.z, "open") ?? 0; - ctx.world.set_state(block.x, block.y, block.z, "open", open ? 0 : 1); - return true; - }, - }); -} - // the container a block keeps its items in, made the first time it's needed. blocks placed before tile data // existed don't have one yet function block_container(ctx: ServerContext, block: BlockRef, size: number): Container { diff --git a/mods/bworld/scripts/shared.ts b/mods/bworld/scripts/shared.ts index b108bcc..1862da7 100644 --- a/mods/bworld/scripts/shared.ts +++ b/mods/bworld/scripts/shared.ts @@ -1,5 +1,6 @@ // the base game's block rules: how blocks are placed and how they change with the blocks beside them. they run on the -// server and on every client, so players see a fence join or a trapdoor turn the moment they place it +// server and on every client, so players see a fence join or a trapdoor turn the moment they place it, and a trapdoor +// open the moment they click it import type { SharedBlock, SharedContext } from "bworld/shared"; export function setup(ctx: SharedContext) { @@ -47,9 +48,14 @@ const FACINGS = ["north", "east", "south", "west"]; // placed against the side of a block, a trapdoor hangs from that block, in the half of the side that was clicked. // placed on top of a block it lies in the bottom half, and under one in the top half, swinging open away from the -// player, like minecraft's TrapDoorBlock +// player, like minecraft's TrapDoorBlock. it opens and closes when right clicked, like a wooden one, here so the +// player who clicks sees it move right away function register_trapdoor(ctx: SharedContext) { ctx.components.register_block("bworld:trapdoor", { + on_interact(block) { + const open = ctx.world.get_state(block.x, block.y, block.z, "open") ?? 0; + return ctx.world.set_state(block.x, block.y, block.z, "open", open ? 0 : 1); + }, state_for_placement(placement): Record { if (placement.face !== "top" && placement.face !== "bottom") { return { facing: FACINGS.indexOf(placement.face), half: placement.hit[1] > 0.5 ? 1 : 0 }; diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 93a53b1..2873a8c 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -873,6 +873,7 @@ export class GameServer { if (is_block_position(message.x, message.y, message.z)) { this.#break_block(player, message.x, message.y, message.z); } + this.#ack(player, message.seq); break; case "hit_block": if (is_block_position(message.x, message.y, message.z)) { @@ -899,6 +900,7 @@ export class GameServer { : [0.5, 0.5, 0.5]; this.#use_block(player, message.x, message.y, message.z, message.face, hit); } + this.#ack(player, message.seq); break; case "select_slot": if (is_int(message.slot) && message.slot >= 0 && message.slot < 9) { @@ -1044,11 +1046,14 @@ export class GameServer { const before_interact = { ...interact, cancel: false }; this.mods.before.block_interact.emit(before_interact); if (before_interact.cancel) { + // the client may have guessed the shared rules' on_interact, or a placement + this.#correct(player, x, y, z); this.#correct(player, tx, ty, tz); return; } - let handled = false; + // the shared rules first, the ones the client guessed, then the server script's + let handled = this.mods.rules.interact(used, x, y, z, { face, hit: [hit[0], hit[1], hit[2]] }, player.yaw); for (const { mod, id: component_id, component, params } of this.mods.components_of(used.id)) { if (component.on_interact) { handled = run_guarded(mod, `${component_id} on_interact`, () => @@ -1058,7 +1063,9 @@ export class GameServer { } if (handled) { this.mods.after.block_interact.emit(interact); - // the client didn't guess a placement for interactive blocks, but it might have for others + // the client guessed the shared rules' on_interact from what it sees, which might not be what's here. it didn't + // guess a placement for interactive blocks, but it might have for others + this.#correct(player, x, y, z); this.#correct(player, tx, ty, tz); return; } @@ -1848,6 +1855,14 @@ export class GameServer { } // tell the player what's really at a position, undoing anything their client guessed + // the client's break_block or use_block with seq is handled, after the set_blocks it caused, even when it's + // ignored: the client holds back what the server says about the blocks it guessed until this comes + #ack(player: ServerPlayer, seq: unknown) { + if (is_int(seq) && seq > 0) { + this.#send(player, { type: "block_ack", seq }); + } + } + #correct(player: ServerPlayer, x: number, y: number, z: number) { if (y < 0 || y >= CHUNK_HEIGHT || !player.chunks.has_block(x, z)) { return; diff --git a/tests/block_predictions_test.ts b/tests/block_predictions_test.ts new file mode 100644 index 0000000..6f36a71 --- /dev/null +++ b/tests/block_predictions_test.ts @@ -0,0 +1,64 @@ +// what a client guesses about blocks waits for the server's block_ack before the server's word replaces it, like +// minecraft's BlockStatePredictionHandler, so clicking fast doesn't flicker. see client/level/block_predictions.ts +import { assertEquals } from "@std/assert"; +import { BlockPredictions } from "$/client/level/block_predictions.ts"; +import { test_game } from "./helpers.ts"; + +const CLOSED = { x: 0, y: 100, z: 0, id: "bworld:oak_trapdoor", state: 0 }; +const OPEN = { ...CLOSED, state: 4 }; + +Deno.test("what the server says about a guessed block waits for the ack of the newest guess that changed it", () => { + const predictions = new BlockPredictions(); + // a trapdoor clicked open, then closed again before the server answers + const first = predictions.start(); + predictions.retain(0, 100, 0, () => CLOSED); + predictions.end(); + const second = predictions.start(); + predictions.retain(0, 100, 0, () => OPEN); + predictions.end(); + + // the answer to the first click opens it, but the second is still on its way + assertEquals(predictions.from_server(0, 100, 0, OPEN.id, OPEN.state), true); + assertEquals(predictions.ack(first), []); + // and the answer to the second closes it, which shows now + assertEquals(predictions.from_server(0, 100, 0, CLOSED.id, CLOSED.state), true); + assertEquals(predictions.ack(second), [CLOSED]); + assertEquals(predictions.from_server(0, 100, 0, OPEN.id, OPEN.state), false); +}); + +Deno.test("a guess the server says nothing about goes back to what it said before, once acked", () => { + const predictions = new BlockPredictions(); + const seq = predictions.start(); + predictions.retain(0, 100, 0, () => CLOSED); + predictions.end(); + assertEquals(predictions.ack(seq), [CLOSED]); +}); + +Deno.test("changes outside a guess aren't kept track of", () => { + const predictions = new BlockPredictions(); + predictions.retain(0, 100, 0, () => CLOSED); + assertEquals(predictions.from_server(0, 100, 0, OPEN.id, OPEN.state), false); + assertEquals(predictions.ack(1), []); +}); + +Deno.test("the server acks a use_block or break_block after the set_blocks it caused, even one it ignores", async () => { + const { game, join, take, send } = await test_game("mods"); + join(1, "alice"); + send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: 0, pitch: 0 }); + game.set_block(0, 99, 0, "bworld:stone"); + game.set_block(0, 100, 0, "bworld:oak_trapdoor"); + // until alice's client has the chunk, nothing in it is sent there + while (!game.players()[0].chunks.has_block(0, 0)) game.tick(); + take(1); + + send(1, { type: "use_block", x: 0, y: 100, z: 0, face: "south", hit: [0.5, 0.5, 1], seq: 1 }); + const types = take(1).map((m) => m.type).filter((type) => type === "set_block" || type === "block_ack"); + assertEquals(types.at(-1), "block_ack"); + assertEquals(types.includes("set_block"), true); + + send(1, { type: "break_block", x: 0, y: 1000, z: 0, seq: 2 }); + assertEquals(take(1).filter((m) => m.type === "block_ack"), [{ type: "block_ack", seq: 2 }]); + // without a seq, from a client that doesn't guess, there's nothing to ack + send(1, { type: "break_block", x: 0, y: 100, z: 0 }); + assertEquals(take(1).filter((m) => m.type === "block_ack"), []); +}); diff --git a/tests/shared_rules_test.ts b/tests/shared_rules_test.ts index b097642..7e70867 100644 --- a/tests/shared_rules_test.ts +++ b/tests/shared_rules_test.ts @@ -1,5 +1,5 @@ -// shared scripts' block rules run on clients too, so what a client shows the moment it places or breaks a block is -// what the server ends up with +// shared scripts' block rules run on clients too, so what a client shows the moment it places, breaks or right clicks +// a block is what the server ends up with import { assertEquals } from "@std/assert"; import { BlockRules } from "$/common/block_rules.ts"; import { collision_shape_at, covers_face } from "$/common/block_shapes.ts"; @@ -85,6 +85,10 @@ function client_of(t: Game) { copy.set(`${x} ${y} ${z}`, [id, value >>> 16]); rules.notify_neighbors(world.get_block, x, y, z); }, + // what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something + interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) { + return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit }, yaw); + }, break(x: number, y: number, z: number) { copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]); rules.notify_neighbors(world.get_block, x, y, z); @@ -147,3 +151,18 @@ Deno.test("a client places a trapdoor turned and in the half the server puts it" assertEquals(state(t, 1, 100, 0, "half"), 1); assertEquals(state(t, 0, 100, 2, "facing"), 1); }); + +Deno.test("a client opens and closes a trapdoor right away, the same as the server, without placing anything", async () => { + const { t, use } = await setup("bworld:oak_trapdoor"); + t.game.set_block(0, 100, 0, "bworld:oak_trapdoor"); + const client = client_of(t); + + for (const open of [1, 0]) { + assertEquals(client.interact(0, 100, 0, 0, "south", [0.5, 0.5, 1]), true); + use(0, 100, 0, "south", [0.5, 0.5, 1]); + assertEquals(client.blocks(), server_blocks(t)); + assertEquals(state(t, 0, 100, 0, "open"), open); + } + // alice still has all of hers + assertEquals(t.game.players()[0].inventory.get_slot(0).amount, 64); +});