Neighbor Updates as a Queue

This commit is contained in:
2026-10-20 13:40:44 -03:00
parent 0af35d1e17
commit 77cd327f94
9 changed files with 348 additions and 138 deletions
+136 -23
View File
@@ -2,23 +2,28 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// the server's side of a block hearing about changes: its components' on_neighbor_change, after the shared rules, and
// on_state_change when its own states change
import { assertEquals } from "@std/assert";
// on_state_change when its own states change. blocks hear of changes through a queue, once the change is done
import { assert, assertEquals } from "@std/assert";
import { AIR_ID } from "$/common/protocol.ts";
import { MAX_NEIGHBOR_UPDATES } from "$/common/block_rules.ts";
import { get_state_value } from "$/common/utils.ts";
import type { GameServer } from "$/server/game/game_server.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
const at = ({ x, y, z }: { x: number; y: number; z: number }) => x + " " + y + " " + z;
ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block, _params, neighbor) {
const seen = ctx.world.get_state(block.x, block.y, block.z, "seen");
log(["neighbor", neighbor.id, neighbor.x, neighbor.y, neighbor.z, seen]);
log(["neighbor", at(block), neighbor.id, at(neighbor), seen]);
},
on_state_change(block, _params, before) {
const { x, y, z } = block;
log(["state", before, { seen: ctx.world.get_state(x, y, z, "seen"), count: ctx.world.get_state(x, y, z, "count") }]);
const now = { seen: ctx.world.get_state(x, y, z, "seen"), count: ctx.world.get_state(x, y, z, "count") };
log(["state", at(block), before, now]);
},
});
// hangs from the block above and falls when it's gone, which only a server handler can do
@@ -29,20 +34,50 @@ export function setup(ctx: ServerContext) {
}
},
});
// tells the block two to the east when it's broken, which isn't beside it
ctx.components.register_block("testmod:tether", {
on_break(block) { ctx.world.neighbor_changed(block.x + 2, block.y, block.z, block); },
});
ctx.commands.register("state", {
description: "", usage: "",
run([x, y, z, name, value]) { ctx.world.set_state(Number(x), Number(y), Number(z), name, Number(value)); },
run([x, y, z, name, value, quiet]) {
const options = quiet === "quiet" ? { update_neighbors: false } : undefined;
ctx.world.set_state(Number(x), Number(y), Number(z), name, Number(value), options);
},
});
ctx.commands.register("tell", {
description: "", usage: "",
run(args) {
const [x, y, z, fx, fy, fz] = args.map(Number);
ctx.world.neighbor_changed(x, y, z, { x: fx, y: fy, z: fz });
},
});
}
`;
// marks the watcher once anything beside it changes
const SHARED_SCRIPT = `
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
// marks the watcher once anything beside it changes
ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); },
});
// passes a count back and forth with a relay beside it, one higher each time, up to 10000
ctx.components.register_block("testmod:relay", {
on_neighbor_change(block, _params, neighbor) {
if (neighbor.id !== "testmod:relay") return;
const theirs = ctx.world.get_state(neighbor.x, neighbor.y, neighbor.z, "count")!;
const mine = ctx.world.get_state(block.x, block.y, block.z, "count")!;
if (theirs >= mine && theirs < 10000) ctx.world.set_state(block.x, block.y, block.z, "count", theirs + 1);
},
});
// flips whenever anything beside it changes, so two side by side never stop
ctx.components.register_block("testmod:flipper", {
on_neighbor_change(block) {
const on = ctx.world.get_state(block.x, block.y, block.z, "on")!;
ctx.world.set_state(block.x, block.y, block.z, "on", 1 - on);
},
});
}
`;
@@ -60,18 +95,22 @@ function test_mods() {
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
});
const block = (id: string, extra: Record<string, unknown>) => ({
format_version: 1,
block: { id, textures: "bworld:stone", mining: { toughness: 1 }, ...extra },
});
write(
"blocks/watcher.json",
block("testmod:watcher", {
states: [{ name: "seen", bits: 1, default: 0 }, { name: "count", bits: 4, default: 0 }],
components: { "testmod:watcher": {} },
}),
);
write("blocks/lantern.json", block("testmod:lantern", { components: { "testmod:lantern": {} } }));
const block = (name: string, states: unknown[] = []) =>
write(`blocks/${name}.json`, {
format_version: 1,
block: {
id: `testmod:${name}`,
textures: "bworld:stone",
mining: { toughness: 1 },
states,
components: { [`testmod:${name}`]: {} },
},
});
block("watcher", [{ name: "seen", bits: 1, default: 0 }, { name: "count", bits: 4, default: 0 }]);
block("lantern");
block("tether");
block("relay", [{ name: "count", bits: 14, default: 0 }]);
block("flipper", [{ name: "on", bits: 1, default: 0 }]);
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
return dir;
@@ -94,6 +133,10 @@ async function setup() {
return { game, log, command, cleanup };
}
function state(game: GameServer, x: number, y: number, z: number, name: string) {
return get_state_value(game.world.get_block_value(x, y, z), game.world.get_block_info(x, y, z)!, name);
}
Deno.test("a component's on_neighbor_change runs after the block's rules, and can change the world", async () => {
const { game, log, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher");
@@ -101,12 +144,12 @@ Deno.test("a component's on_neighbor_change runs after the block's rules, and ca
game.set_block(1, 100, 0, "bworld:stone");
assertEquals(log(), [
["state", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
["state", "0 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
// the rule had marked it already
["neighbor", "bworld:stone", 1, 100, 0, 1],
["neighbor", "0 100 0", "bworld:stone", "1 100 0", 1],
]);
game.set_block(1, 100, 0, AIR_ID);
assertEquals(log(), [["neighbor", AIR_ID, 1, 100, 0, 1]], "the block that changed is what's there now");
assertEquals(log(), [["neighbor", "0 100 0", AIR_ID, "1 100 0", 1]], "the block that changed is what's there now");
game.set_block(3, 101, 0, "bworld:stone");
game.set_block(3, 100, 0, "testmod:lantern");
@@ -123,13 +166,13 @@ Deno.test("on_state_change gets the states from before, when a script or a rule
log();
command("/state 0 100 0 count 3");
assertEquals(log(), [["state", { seen: 0, count: 0 }, { seen: 0, count: 3 }]]);
assertEquals(log(), [["state", "0 100 0", { seen: 0, count: 0 }, { seen: 0, count: 3 }]]);
command("/state 0 100 0 count 3");
assertEquals(log(), [], "setting a state to what it is changes nothing");
// a rule
game.set_block(0, 101, 0, "bworld:stone");
assertEquals(log()[0], ["state", { seen: 0, count: 3 }, { seen: 1, count: 3 }]);
assertEquals(log()[0], ["state", "0 100 0", { seen: 0, count: 3 }, { seen: 1, count: 3 }]);
// replacing it is a new block, not a state change
game.set_block(0, 100, 0, "testmod:watcher");
@@ -137,3 +180,73 @@ Deno.test("on_state_change gets the states from before, when a script or a rule
assertEquals(game.world.get_block_value(0, 100, 0) >>> 16, 0);
cleanup();
});
Deno.test("a script can tell any block of a change, and one told in on_break hears once the block is gone", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(2, 100, 0, "testmod:watcher");
game.set_block(0, 100, 0, "testmod:tether");
log();
game.set_block(0, 100, 0, AIR_ID);
assertEquals(log(), [
// its rule and its component heard
["state", "2 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
["neighbor", "2 100 0", AIR_ID, "0 100 0", 1],
]);
// right away, when nothing else is changing
command("/tell 2 100 0 2 100 5");
assertEquals(log(), [["neighbor", "2 100 0", "bworld:air", "2 100 5", 1]]);
cleanup();
});
Deno.test("update_neighbors false changes a state without telling anyone, but on_state_change runs", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher");
game.set_block(1, 100, 0, "testmod:watcher");
log();
command("/state 0 100 0 count 5 quiet");
assertEquals(log(), [["state", "0 100 0", { seen: 1, count: 0 }, { seen: 1, count: 5 }]]);
command("/state 0 100 0 count 6");
assert(
log().some((event) =>
JSON.stringify(event) === JSON.stringify(["neighbor", "1 100 0", "testmod:watcher", "0 100 0", 1])
),
);
cleanup();
});
Deno.test("a chain of 10000 changes, each setting off the next, runs to the end", async () => {
const { game, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:relay");
game.set_block(1, 100, 0, "testmod:relay");
const counts = [state(game, 0, 100, 0, "count")!, state(game, 1, 100, 0, "count")!];
assertEquals(Math.max(...counts), 10000);
assertEquals(Math.min(...counts), 9999);
cleanup();
});
Deno.test("blocks that keep setting each other off are stopped, and the server says where", async () => {
const { game, log, cleanup } = await setup();
const warn = console.warn;
const warnings: string[] = [];
console.warn = (...args: unknown[]) => warnings.push(args.join(" "));
try {
game.set_block(0, 100, 0, "testmod:flipper");
game.set_block(1, 100, 0, "testmod:flipper");
} finally {
console.warn = warn;
}
assertEquals(warnings.length, 1);
assert(warnings[0].includes(String(MAX_NEIGHBOR_UPDATES)), warnings[0]);
const [x, y, z] = warnings[0].match(/at (-?\d+) (-?\d+) (-?\d+)/)!.slice(1).map(Number);
assert(Math.abs(x - 0.5) <= 1.5 && Math.abs(y - 100) <= 1 && Math.abs(z) <= 1, "beside the flippers");
// the next change goes as usual
game.set_block(0, 100, 3, "testmod:watcher");
log();
game.set_block(1, 100, 3, "bworld:stone");
assertEquals(log().length, 2);
cleanup();
});
+4 -4
View File
@@ -46,7 +46,7 @@ function client_of(t: Game) {
const at = (x: number, y: number, z: number) => copy.get(`${x} ${y} ${z}`);
const info = (id: string) => EverythingRegistry.get<BlockRegistry>("blocks", id);
const rules = new BlockRules((_mod, _what, fn) => fn());
const rules = new BlockRules((_mod, _what, fn) => fn(), (x, y, z) => at(x, y, z)?.[0]);
const world: SharedWorld = {
get_block: (x, y, z) => at(x, y, z)?.[0],
get_state(x, y, z, name) {
@@ -61,7 +61,7 @@ function client_of(t: Game) {
const changed = set_state_value(state << 16, block, name, value)! >>> 16;
if (changed !== state) {
copy.set(`${x} ${y} ${z}`, [id, changed]);
rules.notify_neighbors(world.get_block, x, y, z);
rules.notify_neighbors(x, y, z);
}
return true;
},
@@ -90,7 +90,7 @@ function client_of(t: Game) {
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false });
copy.set(`${x} ${y} ${z}`, [id, value! >>> 16]);
rules.notify_neighbors(world.get_block, x, y, z);
rules.notify_neighbors(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]) {
@@ -98,7 +98,7 @@ function client_of(t: Game) {
},
break(x: number, y: number, z: number) {
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
rules.notify_neighbors(world.get_block, x, y, z);
rules.notify_neighbors(x, y, z);
},
blocks: () => blocks_in((x, y, z) => at(x, y, z)!),
};