Shared state between client and server

This commit is contained in:
2026-10-03 18:45:07 -03:00
parent 63e6248f9f
commit 7417bfd5f1
24 changed files with 656 additions and 193 deletions
+15 -5
View File
@@ -4,7 +4,8 @@ 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, default_block_value, placement_target } from "$/common/utils.ts";
import { box_overlaps_block, can_place, placement_target } 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";
import { RemoteEntity } from "./entity/remote_entity.ts";
@@ -42,6 +43,7 @@ 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.destroy_progress = 0;
this.destroy_time = 0;
@@ -74,13 +76,21 @@ export class MultiPlayerGameMode {
const place_block = place_id !== undefined
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
: undefined;
// with the states the server will give it, see BlockRules.placement_value
const value = place_block &&
block_rules.placement_value(place_block, this.client.player.yaw, {
...target,
face: hit.face,
hit: hit.hit,
});
const placeable = place_id !== undefined && can_place(
place_block,
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
below_id,
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block));
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, value!));
if (!block_info.interactive && place_id && placeable) {
level.add_block({ ...target, id: place_id });
level.add_block({ ...target, id: place_id }, value! >>> 16);
predict_neighbors(target.x, target.y, target.z);
const slot = this.#held_slot();
slot.amount = slot.amount! - 1;
}
@@ -118,8 +128,8 @@ export class MultiPlayerGameMode {
// whether a mob's or player's collision box overlaps the block, the server doesn't let solid blocks go there. mobs
// are the mod entities that aren't scripted, players are this one and the others
#occupied(x: number, y: number, z: number, block: BlockRegistry) {
const shape = collision_shape_at(block, default_block_value(0, block));
#occupied(x: number, y: number, z: number, block: BlockRegistry, value: number) {
const shape = collision_shape_at(block, value);
for (const entity of this.client.level.entities.values()) {
const json = entity instanceof RemoteEntity
? EverythingRegistry.get<EntityJson>("entities", entity.type)
+89 -1
View File
@@ -5,7 +5,10 @@ import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/e
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "$/common/mod_api/client.ts";
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
import { type Bmod, read_bmod } from "$/common/bmod.ts";
import { display_name } from "$/common/utils.ts";
import { display_name, get_state_value, set_state_value } from "$/common/utils.ts";
import { BlockRules } from "$/common/block_rules.ts";
import { covers_face, EMPTY_SHAPE, FULL_SHAPE } from "$/common/block_shapes.ts";
import type { SharedContext, SharedWorld } from "$/common/mod_api/shared.ts";
import { tag_api } from "$/common/tags.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { Client } from "./client.ts";
@@ -38,6 +41,59 @@ export function receive_mod_message(channel: string, data: unknown) {
}
}
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts
export let block_rules = new BlockRules(run_mod);
// whether shared scripts are being set up, the only time they can register rules
let rules_setup = false;
function run_mod<T>(mod: string, what: string, fn: () => T): T | undefined {
try {
return fn();
} catch (e) {
console.error(`[${mod}] ${what} threw:`, e);
return undefined;
}
}
// the world shared rules see on this client: what it shows. what they change is a guess the server corrects
const rules_world: SharedWorld = {
get_block(x, y, z) {
const nid = client?.level.get_block(x, y, z);
if (nid === undefined) return undefined;
if (nid === AIR) return AIR_ID;
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
},
get_state(x, y, z, name) {
const level = client?.level;
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("blocks", level.get_block(x, y, z));
if (!info?.states?.some((state) => state.name === name)) return undefined;
return get_state_value(level!.get_block_value(x, y, z), info, name);
},
set_state(x, y, z, name, value) {
const level = client?.level;
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("blocks", level.get_block(x, y, z));
if (!info?.states?.some((state) => state.name === name)) return false;
const old_value = level!.get_block_value(x, y, z);
const new_value = set_state_value(old_value, info, name, value);
if (new_value === undefined) return false;
if (new_value !== old_value) {
level!.add_block({ x, y, z, id: info.id }, new_value >>> 16);
predict_neighbors(x, y, z);
}
return true;
},
is_face_sturdy(x, y, z, face) {
const shape = client?.level.collision_shape(x, y, z) ?? false;
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
},
};
// this client changed the block at x y z ahead of the server, the blocks beside it change with it the way they will
// on the server
export function predict_neighbors(x: number, y: number, z: number) {
block_rules.notify_neighbors(rules_world.get_block, x, y, z);
}
// the loaded mods' recipes, and their names by id
let recipe_book = new RecipeBook();
const mod_names = new Map<string, string>();
@@ -77,6 +133,19 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
mod_names.clear();
for (const listing of listings) mod_names.set(listing.id, listing.name);
// every mod's shared rules first, so client scripts can count on any mod's being there
block_rules = new BlockRules(run_mod);
rules_setup = true;
for (const [i, bmod] of bmods.entries()) {
if (!bmod.scripts.shared) continue;
const module = await import(script_url(bmod.scripts.shared));
if (typeof module.setup !== "function") {
throw new ModLoadError(bmod.manifest.id, "the shared script doesn't export a setup function");
}
await module.setup(shared_context(listings[i]));
}
rules_setup = false;
for (const [i, bmod] of bmods.entries()) {
if (!bmod.scripts.client) continue;
const module = await import(script_url(bmod.scripts.client));
@@ -91,6 +160,25 @@ function script_url(code: string) {
return code_url(new TextEncoder().encode(code));
}
function shared_context(listing: ModListing): SharedContext {
const mod = listing.id;
return {
mod: { id: mod, version: listing.version },
side: "client",
tags: tag_api(),
world: rules_world,
components: {
register_block(id, rules) {
if (!id.startsWith(`${mod}:`)) {
throw new Error(`[${mod}] component ${id} must be in the namespace "${mod}"`);
}
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
block_rules.register(mod, id, rules);
},
},
};
}
function client_context(listing: ModListing): ClientContext {
const mod = listing.id;
const not_yet = (name: string, where: string) =>