Verdigris wire and lever

This commit is contained in:
2026-10-22 13:43:57 -03:00
parent 0d80e85dec
commit 6af6c52673
24 changed files with 3191 additions and 733 deletions
+41
View File
@@ -0,0 +1,41 @@
{
"format_version": 1,
"block": {
"id": "bworld:lever",
"textures": { "lever": "bworld:lever", "base": "bworld:cobblestone" },
"model": "bworld:lever",
"render_layer": "cutout",
"collision": false,
"interactive": true,
"mining": { "toughness": 0.5 },
"drops": "bworld:lever",
"states": [
{ "name": "face", "bits": 2, "default": 0 },
{ "name": "facing", "bits": 2, "default": 0 },
{ "name": "powered", "bits": 1, "default": 0 }
],
"variants": {
"powered=1": { "model": "bworld:lever_on" },
"face=0,facing=1": { "y": 90 },
"face=0,facing=2": { "y": 180 },
"face=0,facing=3": { "y": 270 },
"face=1,facing=0": { "x": 90 },
"face=1,facing=1": { "x": 90, "y": 90 },
"face=1,facing=2": { "x": 90, "y": 180 },
"face=1,facing=3": { "x": 90, "y": 270 },
"face=2,facing=0": { "x": 180, "y": 180 },
"face=2,facing=1": { "x": 180, "y": 270 },
"face=2,facing=2": { "x": 180 },
"face=2,facing=3": { "x": 180, "y": 90 }
},
"components": {
"bworld:verdigris_source": {
"power": 15,
"when": "powered",
"facing": { "face": "face", "facing": "facing" },
"strong": ["back"]
},
"bworld:lever": {}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"format_version": 1,
"block": {
"id": "bworld:verdigris_block",
"textures": "bworld:verdigris_block",
"mining": {
"toughness": 5,
"tool": "pickaxe",
"requires_tool": true
},
"drops": "bworld:verdigris_block",
"components": {
"bworld:verdigris_source": { "power": 15 }
}
}
}
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
{
"format_version": 1,
"item": {
"id": "bworld:verdigris",
"texture": "bworld:verdigris",
"places": "bworld:verdigris_wire"
}
}
@@ -0,0 +1,97 @@
{
"format_version": 1,
"loot_table": {
"pools": [
{
"conditions": [
{
"condition": "block_state",
"states": {
"north": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"east": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"south": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"west": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"top": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"bottom": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
}
]
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"format_version": 1,
"model": {
"id": "bworld:lever",
"elements": [
{
"from": [5, 0, 4],
"to": [11, 3, 12],
"faces": {
"top": {
"texture": "#base"
},
"bottom": {
"texture": "#base"
},
"north": {
"texture": "#base"
},
"south": {
"texture": "#base"
},
"west": {
"texture": "#base"
},
"east": {
"texture": "#base"
}
}
},
{
"from": [7, 1, 7],
"to": [9, 11, 9],
"rotation": {
"origin": [8, 1, 8],
"axis": "x",
"angle": -45
},
"faces": {
"top": {
"texture": "#lever",
"uv": [7, 6, 9, 8]
},
"north": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"south": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"west": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"east": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
}
}
}
]
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"format_version": 1,
"model": {
"id": "bworld:lever_on",
"elements": [
{
"from": [5, 0, 4],
"to": [11, 3, 12],
"faces": {
"top": {
"texture": "#base"
},
"bottom": {
"texture": "#base"
},
"north": {
"texture": "#base"
},
"south": {
"texture": "#base"
},
"west": {
"texture": "#base"
},
"east": {
"texture": "#base"
}
}
},
{
"from": [7, 1, 7],
"to": [9, 11, 9],
"rotation": {
"origin": [8, 1, 8],
"axis": "x",
"angle": 45
},
"faces": {
"top": {
"texture": "#lever",
"uv": [7, 6, 9, 8]
},
"north": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"south": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"west": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"east": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
}
}
}
]
}
}
@@ -1,26 +0,0 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_corner",
"elements": [
{
"from": [7, 0, 0],
"to": [9, 0.25, 7],
"faces": {
"top": {
"texture": "#wire"
}
}
},
{
"from": [7, 0, 0],
"to": [9, 16, 0.25],
"faces": {
"south": {
"texture": "#wire"
}
}
}
]
}
}
@@ -1,26 +0,0 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_corner_east",
"elements": [
{
"from": [9, 0, 7],
"to": [16, 0.25, 9],
"faces": {
"top": {
"texture": "#wire"
}
}
},
{
"from": [15.75, 0, 7],
"to": [16, 16, 9],
"faces": {
"west": {
"texture": "#wire"
}
}
}
]
}
}
@@ -1,7 +1,7 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_edge",
"id": "bworld:verdigris_wire_out",
"elements": [
{
"from": [7, 0, -0.25],
@@ -1,7 +1,7 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_edge_east",
"id": "bworld:verdigris_wire_out_east",
"elements": [
{
"from": [9, 0, 7],
+2
View File
@@ -7,6 +7,7 @@ import { register_curios } from "./curios.ts";
import { register_effects } from "./effects.ts";
import { register_fishing } from "./fishing.ts";
import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts";
import { register_verdigris } from "./verdigris/server.ts";
export function setup(ctx: ServerContext) {
register_hoeable(ctx);
@@ -25,6 +26,7 @@ export function setup(ctx: ServerContext) {
register_curios(ctx);
register_effects(ctx);
register_growable_block(ctx);
register_verdigris(ctx);
}
// right clicking with a type of tool turns the block into another, like any hoe on grass
+2
View File
@@ -5,11 +5,13 @@
// server and on every client, so players see a fence join or a trapdoor turn the moment they place it, and a trapdoor
// or a door open the moment they click it
import type { SharedBlock, SharedContext } from "bworld/shared";
import { register_verdigris_rules } from "./verdigris/shared.ts";
export function setup(ctx: SharedContext) {
register_fence(ctx);
register_trapdoor(ctx);
register_door(ctx);
register_verdigris_rules(ctx);
}
// the sides a fence connects on, and the face of the block there it connects to
+33
View File
@@ -0,0 +1,33 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the blocks that make and use signals, see "Blocks" in REDSTONE.md. what they give out is their bworld:verdigris_source
// params, this is what makes their states change
import type { BlockRef, Face, Position, ServerContext } from "bworld/server";
import { type FacingParam, front_of, OPPOSITE, step } from "./sides.ts";
// a lever's face and facing states, see FacingParam
const LEVER_FACING: FacingParam = { face: "face", facing: "facing" };
// switched on and off by right clicking it, and it breaks when what it's on goes
export function register_lever(ctx: ServerContext) {
ctx.components.register_block("bworld:lever", {
on_interact(block) {
const powered = ctx.world.get_state(block.x, block.y, block.z, "powered");
ctx.world.set_state(block.x, block.y, block.z, "powered", powered ? 0 : 1);
return true;
},
on_neighbor_change(block, _params, neighbor) {
const front = front_of(LEVER_FACING, (name) => ctx.world.get_state(block.x, block.y, block.z, name));
breaks_without(ctx, block, OPPOSITE[front], neighbor);
},
});
}
// breaks a block that hangs from the block toward face when the neighbor that changed is that block and its face isn't
// something to attach to anymore
function breaks_without(ctx: ServerContext, block: BlockRef, face: Face, neighbor: Position) {
const [x, y, z] = step(block.x, block.y, block.z, face);
if (neighbor.x !== x || neighbor.y !== y || neighbor.z !== z) return;
if (!ctx.world.is_face_sturdy(x, y, z, OPPOSITE[face])) ctx.world.break_block(block.x, block.y, block.z);
}
+93
View File
@@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// which faces of its cell a wire covers and what it joins, see "Joining" in REDSTONE.md. a wire cell covers some of its
// six faces, each lying on the block on that side, and the wire on two faces that meet joins at that edge. a face's
// other directions lead out of the cell, and its arm_ states say which of those it joins. the shared rule sets them the
// same on the server and clients, and works out a join between two cells the same from either end
import type { Face } from "bworld/shared";
import { AIR, type BlockReader, connects, WIRE } from "./signals.ts";
import { DIRECTIONS, FACES, OPPOSITE, step } from "./sides.ts";
// how many arm_ states a wire has, so how many ways out of its cell its faces can have between them
export const MAX_ARMS = 6;
// whether the wire at x y z covers face of its cell. false when there's no wire
export function covers(world: BlockReader, x: number, y: number, z: number, face: Face) {
return world.get_block(x, y, z) === WIRE && world.get_state(x, y, z, face) === 1;
}
// the faces of its cell the wire at x y z covers, in FACES' order
export function faces_of(world: BlockReader, x: number, y: number, z: number): Face[] {
return world.get_block(x, y, z) === WIRE ? FACES.filter((face) => world.get_state(x, y, z, face) === 1) : [];
}
// the ways out of a cell covering faces: each face's directions toward faces it doesn't cover, which can lead to
// another cell. in FACES' order, then DIRECTIONS', which is the order of the arm_ states
export function ways_out(faces: readonly Face[]): [Face, Face][] {
return faces.flatMap((face) =>
DIRECTIONS[face].filter((direction) => !faces.includes(direction)).map((direction): [Face, Face] => [
face,
direction,
])
);
}
// whether one wire cell can cover all of faces: its ways out have to fit in its arm_ states. that leaves out two
// opposite faces with nothing joining them, and three or four faces all the way around the cell
export function can_cover(faces: readonly Face[]) {
return faces.length > 0 && ways_out(faces).length <= MAX_ARMS;
}
// what the wire on face of the cell at x y z joins toward direction, out of its cell: the same face of the next cell
// ("straight"), the next face of the block it lies on, around that block's edge ("edge"), or a block that makes or
// takes power ("block"). wire doesn't block the way around an edge, only the faces it covers matter
export type WayOut = "straight" | "edge" | "block";
export function joins_out(
world: BlockReader,
x: number,
y: number,
z: number,
face: Face,
direction: Face,
): WayOut | undefined {
const next = step(x, y, z, direction);
const id = world.get_block(...next);
if (id === undefined) return undefined;
if (id === WIRE) {
if (covers(world, ...next, face)) return "straight";
} else if (id !== AIR) {
return connects(world, ...next, id, OPPOSITE[direction]) ? "block" : undefined;
}
return covers(world, ...around_edge(x, y, z, face, direction), OPPOSITE[direction]) ? "edge" : undefined;
}
// the cell past the edge of the block the wire on face lies on, toward direction: where the wire on that block's next
// face is
export function around_edge(x: number, y: number, z: number, face: Face, direction: Face) {
return step(...step(x, y, z, face), direction);
}
// the wire cell a way out joins, undefined when it joins a block that isn't wire or nothing
export function joined_cell(world: BlockReader, x: number, y: number, z: number, face: Face, direction: Face) {
const way = joins_out(world, x, y, z, face, direction);
if (way === "straight") return step(x, y, z, direction);
if (way === "edge") return around_edge(x, y, z, face, direction);
return undefined;
}
// the arm_ states of a wire cell at x y z covering faces, from what's around it
export function arms_of(world: BlockReader, x: number, y: number, z: number, faces: readonly Face[]) {
const arms: Record<string, number> = {};
for (let i = 0; i < MAX_ARMS; i++) arms[`arm_${i}`] = 0;
ways_out(faces).forEach(([face, direction], i) => {
arms[`arm_${i}`] = joins_out(world, x, y, z, face, direction) ? 1 : 0;
});
return arms;
}
// a wire cell's face states for faces, all six
export function face_states(faces: readonly Face[]) {
return Object.fromEntries(FACES.map((face) => [face, faces.includes(face) ? 1 : 0]));
}
+121
View File
@@ -0,0 +1,121 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// verdigris's components, see REDSTONE.md: the wire, which works out its net's power whenever something around it
// changes, sources, and the devices
import type { BlockRef, Face, Position, ServerContext } from "bworld/server";
import { register_lever } from "./devices.ts";
import { arms_of, around_edge, can_cover, covers, face_states, faces_of, MAX_ARMS } from "./joins.ts";
import { type BlockReader, source_lookup, strong_sides } from "./signals.ts";
import { DIRECTIONS, FACES, OPPOSITE, step } from "./sides.ts";
import { type SignalWorld, tell_around_below, update_net, wire_at } from "./wires.ts";
// a wire's states that are its shape: the faces it covers and its arms. its power changing isn't
const SHAPE_STATES = [...FACES, ...Array.from({ length: MAX_ARMS }, (_, i) => `arm_${i}`)];
export function register_verdigris(ctx: ServerContext) {
const world = signal_world(ctx);
ctx.components.register_block("bworld:verdigris_wire", {
on_create(block) {
tell_around_edges(world, block);
update_net(world, block.x, block.y, block.z);
},
on_break(block) {
const wire = wire_at(world, block.x, block.y, block.z);
tell_around_edges(world, block);
if (wire && wire.power > 0) tell_around_below(world, wire);
},
on_neighbor_change(block, _params, neighbor) {
if (lose_face(ctx, world, block, neighbor)) return;
update_net(world, block.x, block.y, block.z);
},
// it covered another face, or its rule joined or let go of something, which can join two nets or split one
on_state_change(block, _params, before) {
const changed = SHAPE_STATES.some((name) =>
ctx.world.get_state(block.x, block.y, block.z, name) !== before[name]
);
if (changed) update_net(world, block.x, block.y, block.z);
},
});
// the engine tells the blocks beside a source when it changes. these tell the blocks around the solid blocks its
// strong sides power, which nothing else would. on_state_change tells them for the sides it had and has, in case it
// turned
ctx.components.register_block("bworld:verdigris_source", {
on_create: (block) => tell_through(world, block, strong_sides(world, block.x, block.y, block.z, block.id)),
on_break: (block) => tell_through(world, block, strong_sides(world, block.x, block.y, block.z, block.id)),
on_state_change(block, _params, before) {
const was: BlockReader = {
...world,
get_state: (x, y, z, name) =>
x === block.x && y === block.y && z === block.z ? before[name] : world.get_state(x, y, z, name),
};
const sides = new Set([
...strong_sides(was, block.x, block.y, block.z, block.id),
...strong_sides(world, block.x, block.y, block.z, block.id),
]);
tell_through(world, block, [...sides]);
},
});
register_lever(ctx);
}
// the wires on the next faces of the blocks a wire lies on, which it joins or could join around their edges. they aren't
// among the six blocks beside it the engine tells
function tell_around_edges(world: SignalWorld, block: BlockRef) {
const faces = faces_of(world, block.x, block.y, block.z);
for (const face of faces) {
for (const direction of DIRECTIONS[face]) {
if (faces.includes(direction)) continue;
const [x, y, z] = around_edge(block.x, block.y, block.z, face, direction);
if (covers(world, x, y, z, OPPOSITE[direction])) world.neighbor_changed(x, y, z, block);
}
}
}
// the face of a wire that lay on the block that changed, when that block's face isn't something to lie on anymore: the
// wire comes off it and drops it, or breaks when what's left can't be one cell. whether it did
function lose_face(ctx: ServerContext, world: SignalWorld, block: BlockRef, neighbor: Position) {
const faces = faces_of(world, block.x, block.y, block.z);
const face = faces.find((face) => {
const [x, y, z] = step(block.x, block.y, block.z, face);
return x === neighbor.x && y === neighbor.y && z === neighbor.z;
});
if (!face || ctx.world.is_face_sturdy(neighbor.x, neighbor.y, neighbor.z, OPPOSITE[face])) return false;
const left = faces.filter((other) => other !== face);
if (!can_cover(left)) {
ctx.world.break_block(block.x, block.y, block.z);
return true;
}
ctx.world.drop_item(block.x, block.y, block.z, { id: "bworld:verdigris", count: 1 });
const states = { ...face_states(left), ...arms_of(world, block.x, block.y, block.z, left) };
for (const [name, value] of Object.entries(states)) ctx.world.set_state(block.x, block.y, block.z, name, value);
return true;
}
// the blocks around each solid block toward those faces of the block, powered through it
function tell_through(world: SignalWorld, block: BlockRef, faces: readonly Face[]) {
for (const face of faces) {
const [sx, sy, sz] = step(block.x, block.y, block.z, face);
const id = world.get_block(sx, sy, sz);
if (id === undefined || !world.solid(id)) continue;
for (const around of FACES) {
if (around === OPPOSITE[face]) continue;
world.neighbor_changed(...step(sx, sy, sz, around), { x: sx, y: sy, z: sz });
}
}
}
function signal_world(ctx: ServerContext): SignalWorld {
return {
// a chunk that was never generated holds nothing anyone built, and reading it would generate it
get_block: (x, y, z) => ctx.world.is_loaded(x, z) ? ctx.world.get_block(x, y, z) : undefined,
get_state: (x, y, z, name) => ctx.world.get_state(x, y, z, name),
source: source_lookup(ctx.blocks),
solid: (id) => ctx.blocks.solid(id),
set_power: (x, y, z, power) => ctx.world.set_state(x, y, z, "power", power, { update_neighbors: false }),
neighbor_changed: (x, y, z, from) => ctx.world.neighbor_changed(x, y, z, from),
};
}
+61
View File
@@ -0,0 +1,61 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// verdigris placement and joins, see REDSTONE.md. rules, so a player sees a wire join or a lever turn to the wall the
// moment they place it. power, delays and clicks are the server's, see server.ts
import type { BlockPlacement, Face, SharedContext } from "bworld/shared";
import { arms_of, can_cover, face_states, faces_of } from "./joins.ts";
import { type BlockReader, source_lookup } from "./signals.ts";
import { FACES, OPPOSITE, step } from "./sides.ts";
export function register_verdigris_rules(ctx: SharedContext) {
const world = join_reader(ctx);
// lies on the face it's placed against, joined to what's around it. placed into a cell that has wire already, the
// wire there covers that face too, keeping its power
ctx.components.register_block("bworld:verdigris_wire", {
state_for_placement(placement) {
const face = hangs_from(ctx, placement);
if (!face) return false;
const { x, y, z } = placement;
const covered = faces_of(world, x, y, z);
const faces = FACES.filter((other) => other === face || covered.includes(other));
if (covered.includes(face) || !can_cover(faces)) return false;
const power = covered.length > 0 ? world.get_state(x, y, z, "power") ?? 0 : 0;
return { ...face_states(faces), ...arms_of(world, x, y, z, faces), power };
},
on_neighbor_change(block) {
const { x, y, z } = block;
for (const [name, arm] of Object.entries(arms_of(world, x, y, z, faces_of(world, x, y, z)))) {
ctx.world.set_state(x, y, z, name, arm);
}
},
});
// on a floor, on a wall pointing out of it, or on a ceiling. on a floor or ceiling, facing faces the player
ctx.components.register_block("bworld:lever", {
state_for_placement(placement): Record<string, number> | false {
const side = hangs_from(ctx, placement);
if (!side) return false;
if (side === "bottom") return { face: 0 };
if (side === "top") return { face: 2 };
return { face: 1, facing: FACES.indexOf(OPPOSITE[side]) };
},
});
}
// the face toward the block a wire or lever placed there hangs from: the one it's placed against, if that block's face
// is something to attach to
function hangs_from(ctx: SharedContext, placement: BlockPlacement): Face | undefined {
const side = OPPOSITE[placement.face];
const [x, y, z] = step(placement.x, placement.y, placement.z, side);
return ctx.world.is_face_sturdy(x, y, z, placement.face) ? side : undefined;
}
function join_reader(ctx: SharedContext): BlockReader {
return {
get_block: (x, y, z) => ctx.world.get_block(x, y, z),
get_state: (x, y, z, name) => ctx.world.get_state(x, y, z, name),
source: source_lookup(ctx.blocks),
};
}
+41 -3
View File
@@ -17,9 +17,47 @@ export const FACE_OFFSETS: Readonly<Record<Face, readonly [number, number, numbe
bottom: [0, -1, 0],
};
// the 4 directions along a wire lying on the block toward each face, as join_0 to join_3 number them. they're the same
// on every face: a floor wire's north, east, south and west, turned the way the floor turns onto that face, so a wire
// is drawn the same few pieces turned by its side. on a wall 0 is always down and 2 up
export const OPPOSITE: Readonly<Record<Face, Face>> = {
north: "south",
east: "west",
south: "north",
west: "east",
top: "bottom",
bottom: "top",
};
// the block toward face from x y z
export function step(x: number, y: number, z: number, face: Face): [number, number, number] {
const [dx, dy, dz] = FACE_OFFSETS[face];
return [x + dx, y + dy, z + dz];
}
// which way a block points, from its states: the name of a facing state, read as FACES' values with 2 bits or 3, or
// a face and facing state for blocks on a floor, wall or ceiling, like a lever. face 0 is the floor, where it points
// up, 1 a wall, where it points the way facing says, and 2 the ceiling, where it points down
export type FacingParam = string | { face: string; facing: string };
export function front_of(facing: FacingParam, state: (name: string) => number | undefined): Face {
if (typeof facing === "string") return FACES[state(facing) ?? 0];
const on = state(facing.face) ?? 0;
return on === 0 ? "top" : on === 2 ? "bottom" : FACES[state(facing.facing) ?? 0];
}
// a block's sides as components name them: faces, or front, back and sides, the four around the way it points
export type SideName = Face | "front" | "back" | "sides";
export function named_sides(names: readonly SideName[], front: Face | undefined): Face[] {
return names.flatMap((name): readonly Face[] => {
if (name === "front") return front ? [front] : [];
if (name === "back") return front ? [OPPOSITE[front]] : [];
if (name === "sides") return front ? FACES.filter((face) => face !== front && face !== OPPOSITE[front]) : [];
return [name];
});
}
// the 4 directions along a wire on each face of its cell, in the order its arm_ states take them (see ways_out in
// joins.ts). they're the same on every face: a floor's north, east, south and west, turned the way the floor turns
// onto that face, so a wire is drawn the same few pieces turned by face. on a wall 0 is always down and 2 up
export const DIRECTIONS: Readonly<Record<Face, readonly [Face, Face, Face, Face]>> = {
north: ["bottom", "west", "top", "east"],
east: ["bottom", "north", "top", "south"],
+115
View File
@@ -0,0 +1,115 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the power blocks give each other, see "How Power Works" in REDSTONE.md. every signal is a block state, so this only
// reads states, through a small world instead of ctx so it runs the same in shared scripts, server scripts and tests
import type { Face, Id } from "bworld/shared";
import { FACES, type FacingParam, front_of, named_sides, OPPOSITE, type SideName, step } from "./sides.ts";
export const WIRE = "bworld:verdigris_wire";
export const AIR = "bworld:air";
export const MAX_POWER = 15;
// a bworld:verdigris_source's params, the block json's: something that gives power out of some of its sides
export interface SourceParams {
// the state holding the power it gives, 0 to 15, or always this much
power: string | number;
// a 1 bit state it only gives power while it's 1
when?: string;
facing?: FacingParam;
// the sides it gives power out of, every side when not set
out?: SideName[];
// the ones of those that also power a solid block there
strong?: SideName[];
// the sides wire joins, out when not set
connects?: SideName[];
}
export interface BlockReader {
// undefined where there's nothing to read, like a chunk that was never generated
get_block(x: number, y: number, z: number): Id | undefined;
get_state(x: number, y: number, z: number, name: string): number | undefined;
// its bworld:verdigris_source params, undefined for a block that isn't one
source(id: Id): SourceParams | undefined;
}
export interface SignalReader extends BlockReader {
// whether it's solid for power: a block that's powered and passes it on, see ctx.blocks.solid
solid(id: Id): boolean;
}
// blocks' bworld:verdigris_source params from ctx.blocks, looked up once per block, since components don't change
export function source_lookup(blocks: { components(id: Id): Record<Id, unknown> }) {
const params = new Map<Id, SourceParams | undefined>();
return (id: Id): SourceParams | undefined => {
if (id === AIR) return undefined;
if (!params.has(id)) {
params.set(id, blocks.components(id)["bworld:verdigris_source"] as SourceParams | undefined);
}
return params.get(id);
};
}
// the faces a source's list of sides names, for the source at x y z
function sides_of(
world: BlockReader,
x: number,
y: number,
z: number,
params: SourceParams,
names?: SideName[],
): readonly Face[] {
if (!names) return FACES;
const front = params.facing === undefined
? undefined
: front_of(params.facing, (name) => world.get_state(x, y, z, name));
return named_sides(names, front);
}
// the power the source at x y z gives out of its side toward face, strong or not
function gives(world: BlockReader, x: number, y: number, z: number, params: SourceParams, face: Face, strong: boolean) {
if (params.when !== undefined && !world.get_state(x, y, z, params.when)) return 0;
const sides = strong ? params.strong ?? [] : params.out;
if (!sides_of(world, x, y, z, params, sides).includes(face)) return 0;
const power = typeof params.power === "number" ? params.power : world.get_state(x, y, z, params.power) ?? 0;
return Math.min(power, MAX_POWER);
}
// the power the block at x y z gives out of its side toward face. 0 for a block that isn't a source
export function output(world: BlockReader, x: number, y: number, z: number, id: Id, face: Face) {
const params = world.source(id);
return params ? gives(world, x, y, z, params, face, false) : 0;
}
// what output gives that also powers a solid block there
export function strong_output(world: BlockReader, x: number, y: number, z: number, id: Id, face: Face) {
const params = world.source(id);
return params ? gives(world, x, y, z, params, face, true) : 0;
}
// the faces of the source at x y z that power a solid block there, as its states are now
export function strong_sides(world: BlockReader, x: number, y: number, z: number, id: Id): readonly Face[] {
const params = world.source(id);
return params?.strong ? sides_of(world, x, y, z, params, params.strong) : [];
}
// whether wire joins the side toward face of the block at x y z: a source's connects
export function connects(world: BlockReader, x: number, y: number, z: number, id: Id, face: Face) {
const params = world.source(id);
return params !== undefined && sides_of(world, x, y, z, params, params.connects ?? params.out).includes(face);
}
// the power a solid block gets from the strong sides pointing into it. wire powers it too, but not for wire: a net
// would hold itself on through any block it lies on
export function solid_power(world: SignalReader, x: number, y: number, z: number, id: Id) {
if (!world.solid(id)) return 0;
let most = 0;
for (const face of FACES) {
const [nx, ny, nz] = step(x, y, z, face);
const beside = world.get_block(nx, ny, nz);
if (beside === undefined || beside === WIRE) continue;
most = Math.max(most, strong_output(world, nx, ny, nz, beside, OPPOSITE[face]));
if (most === MAX_POWER) break;
}
return most;
}
+137
View File
@@ -0,0 +1,137 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// wire nets, see "Power" in REDSTONE.md: a wire cell and every wire cell it reaches through its joins are one net, and
// they all have the same power, the most any block gives into any of them. a cell's faces always join each other, so
// it's one piece of one net. walked again on every change for now. the net index that keeps walks between changes
// comes later
import type { Face } from "bworld/shared";
import { faces_of, joined_cell, joins_out, ways_out } from "./joins.ts";
import { type BlockReader, MAX_POWER, output, type SignalReader, solid_power } from "./signals.ts";
import { FACES, OPPOSITE, step } from "./sides.ts";
export interface SignalWorld extends SignalReader {
// sets a wire's power without telling the blocks around it, see ServerWorld.set_state's update_neighbors
set_power(x: number, y: number, z: number, power: number): void;
// see ServerWorld.neighbor_changed
neighbor_changed(x: number, y: number, z: number, from: { x: number; y: number; z: number }): void;
}
export interface Wire {
readonly x: number;
readonly y: number;
readonly z: number;
// the faces of its cell it covers
readonly faces: readonly Face[];
// the ways out of its cell it joins, each a face and a direction, see ways_out
readonly out: readonly [Face, Face][];
readonly power: number;
}
const key = (x: number, y: number, z: number) => `${x} ${y} ${z}`;
// the wire at x y z, undefined when there's none
export function wire_at(world: BlockReader, x: number, y: number, z: number): Wire | undefined {
const faces = faces_of(world, x, y, z);
if (faces.length === 0) return undefined;
return {
x,
y,
z,
faces,
out: ways_out(faces).filter((_, i) => world.get_state(x, y, z, `arm_${i}`) === 1),
power: world.get_state(x, y, z, "power") ?? 0,
};
}
// every wire in the net of the wire at x y z, nothing when there's no wire there
export function walk(world: BlockReader, x: number, y: number, z: number): Wire[] {
const seen = new Set([key(x, y, z)]);
const queue: [number, number, number][] = [[x, y, z]];
const wires: Wire[] = [];
while (queue.length > 0) {
const wire = wire_at(world, ...queue.pop()!);
if (!wire) continue;
wires.push(wire);
for (const [face, direction] of wire.out) {
const next = joined_cell(world, wire.x, wire.y, wire.z, face, direction);
if (!next || seen.has(key(...next))) continue;
seen.add(key(...next));
queue.push(next);
}
}
return wires;
}
// the blocks a wire's faces lie on
function below(wire: Wire) {
return wire.faces.map((face) => ({ face, at: step(wire.x, wire.y, wire.z, face) }));
}
// the power going into a wire: from each block it lies on, a source's output on that side or a solid block's power,
// and from the blocks that aren't wire it joins
export function wire_input(world: SignalReader, wire: Wire) {
let most = 0;
for (const { face, at } of below(wire)) {
const id = world.get_block(...at);
if (id !== undefined) {
most = Math.max(most, output(world, ...at, id, OPPOSITE[face]), solid_power(world, ...at, id));
}
if (most === MAX_POWER) return most;
}
for (const [face, direction] of wire.out) {
if (joins_out(world, wire.x, wire.y, wire.z, face, direction) !== "block") continue;
const [nx, ny, nz] = step(wire.x, wire.y, wire.z, direction);
most = Math.max(most, output(world, nx, ny, nz, world.get_block(nx, ny, nz)!, OPPOSITE[direction]));
if (most === MAX_POWER) return most;
}
return most;
}
// works out the power of the net the wire at x y z is in, and sets it on each of its wires that doesn't have it. then
// each block the net gives power to is told once: the blocks its wires join, the blocks they lie on and the blocks
// around those, which are powered through them
export function update_net(world: SignalWorld, x: number, y: number, z: number) {
const wires = walk(world, x, y, z);
let power = 0;
for (const wire of wires) {
power = Math.max(power, wire_input(world, wire));
if (power === MAX_POWER) break;
}
if (wires.every((wire) => wire.power === power)) return;
for (const wire of wires) {
if (wire.power !== power) world.set_power(wire.x, wire.y, wire.z, power);
}
const told = new Set(wires.map((wire) => key(wire.x, wire.y, wire.z)));
const tell = (at: [number, number, number], from: { x: number; y: number; z: number }) => {
if (told.has(key(...at))) return;
told.add(key(...at));
world.neighbor_changed(...at, from);
};
for (const wire of wires) {
for (const [face, direction] of wire.out) {
if (joins_out(world, wire.x, wire.y, wire.z, face, direction) === "block") {
tell(step(wire.x, wire.y, wire.z, direction), wire);
}
}
for (const { at } of below(wire)) {
tell(at, wire);
for (const face of FACES) tell(step(...at, face), { x: at[0], y: at[1], z: at[2] });
}
}
}
// the blocks around the blocks a wire lies on, told when it's gone with power, since nothing else tells them they're
// no longer powered through
export function tell_around_below(world: SignalWorld, wire: Wire) {
for (const { at } of below(wire)) {
const from = { x: at[0], y: at[1], z: at[2] };
world.neighbor_changed(...at, wire);
for (const face of FACES) {
const around = step(...at, face);
if (around[0] !== wire.x || around[1] !== wire.y || around[2] !== wire.z) {
world.neighbor_changed(...around, from);
}
}
}
}
+99 -2
View File
@@ -2,17 +2,23 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { resolve, toFileUrl } from "@std/path";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { load_and_check, load_order } from "$/tools/check_mods.ts";
import { mod_data } from "$/common/mod_check.ts";
import type { ServerModSource } from "$/server/game/load_mods.ts";
import { GameServer } from "$/server/game/game_server.ts";
import { start_game } from "$/server/game/load_mods.ts";
import { apply_config } from "$/server/load_bmods.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { AIR_ID, PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import type { SavedChunk, SavedChunks, WorldSave } from "$/server/game/saves.ts";
import { BlockRules } from "$/common/block_rules.ts";
import { collision_shape_at, covers_face, is_solid } from "$/common/block_shapes.ts";
import { tag_api } from "$/common/tags.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
import type { Face, SharedWorld } from "$/common/mod_api/shared.ts";
import { setup as setup_shared } from "$/mods/bworld/scripts/shared.ts";
// the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only
// mods/ is kept, since tests change the temporary folders they make between games
@@ -184,3 +190,94 @@ export const container_items = (messages: Msg[], container: string) =>
// what the open menu's data last was among messages
export const menu_data = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_data")?.data;
// a box of blocks, by the lowest and highest of each coordinate in it
export interface Area {
x: [number, number];
y: [number, number];
z: [number, number];
}
// every block in the area, as id and state bits
function blocks_in(area: Area, get: (x: number, y: number, z: number) => [string, number]) {
const out: string[] = [];
for (let x = area.x[0]; x <= area.x[1]; x++) {
for (let y = area.y[0]; y <= area.y[1]; y++) {
for (let z = area.z[0]; z <= area.z[1]; z++) out.push(`${x} ${y} ${z} ${get(x, y, z).join(" ")}`);
}
}
return out;
}
export function server_blocks(game: GameServer, area: Area) {
return blocks_in(area, (x, y, z) => [game.world.get_block_id(x, y, z), game.world.get_block_value(x, y, z) >>> 16]);
}
// a client: its copy of the area, and the bworld shared script's rules running on it the way client/mods.ts does
export function client_of(game: GameServer, area: Area) {
const copy = new Map<string, [string, number]>();
for (const line of server_blocks(game, area)) {
const [x, y, z, id, state] = line.split(" ");
copy.set(`${x} ${y} ${z}`, [id, Number(state)]);
}
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(), (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) {
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
const block = info(id);
return block?.states?.some((s) => s.name === name) ? get_state_value(state << 16, block, name) : undefined;
},
set_state(x, y, z, name, value) {
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
const block = info(id);
if (!block?.states?.some((s) => s.name === name)) return false;
const changed = set_state_value(state << 16, block, name, value)! >>> 16;
if (changed !== state) {
copy.set(`${x} ${y} ${z}`, [id, changed]);
rules.notify_neighbors(x, y, z);
}
return true;
},
is_face_sturdy(x, y, z, face: Face) {
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
const block = info(id);
return block !== undefined && covers_face(collision_shape_at(block, state << 16), face);
},
biome_at: () => undefined,
season_at: () => undefined,
};
setup_shared({
mod: { id: "bworld", version: "test" },
side: "client",
tags: tag_api(),
blocks: {
exists: (id) => info(id) !== undefined,
components: (id) => structuredClone(info(id)!.components ?? {}),
solid: (id) => id !== AIR_ID && is_solid(info(id)!),
},
world,
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
});
return {
// what game_mode does when this client places held against face of x y z, at hit
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(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, sneaking: false }, yaw);
},
break(x: number, y: number, z: number) {
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
rules.notify_neighbors(x, y, z);
},
blocks: () => blocks_in(area, (x, y, z) => at(x, y, z)!),
};
}
+11 -100
View File
@@ -4,107 +4,18 @@
// 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, is_solid } from "$/common/block_shapes.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { tag_api } from "$/common/tags.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
import type { Face, SharedWorld } from "$/common/mod_api/shared.ts";
import { setup as setup_shared } from "$/mods/bworld/scripts/shared.ts";
import { test_game } from "./helpers.ts";
import { get_state_value } from "$/common/utils.ts";
import type { Face } from "$/common/mod_api/shared.ts";
import { type Area, client_of, server_blocks, test_game } from "./helpers.ts";
type Game = Awaited<ReturnType<typeof test_game>>;
const AREA = { x: [-3, 3], y: [99, 101], z: [-3, 3] };
// every block in the area, as id and state bits
function blocks_in(get: (x: number, y: number, z: number) => [string, number]) {
const out: string[] = [];
for (let x = AREA.x[0]; x <= AREA.x[1]; x++) {
for (let y = AREA.y[0]; y <= AREA.y[1]; y++) {
for (let z = AREA.z[0]; z <= AREA.z[1]; z++) out.push(`${x} ${y} ${z} ${get(x, y, z).join(" ")}`);
}
}
return out;
}
const AREA: Area = { x: [-3, 3], y: [99, 101], z: [-3, 3] };
function state(t: Game, x: number, y: number, z: number, name: string) {
return get_state_value(t.game.world.get_block_value(x, y, z), t.game.world.get_block_info(x, y, z)!, name);
}
function server_blocks(t: Game) {
return blocks_in((x, y, z) => [t.game.world.get_block_id(x, y, z), t.game.world.get_block_value(x, y, z) >>> 16]);
}
// a client: its copy of the area, and the bworld shared script's rules running on it the way client/mods.ts does
function client_of(t: Game) {
const copy = new Map<string, [string, number]>();
for (const line of server_blocks(t)) {
const [x, y, z, id, state] = line.split(" ");
copy.set(`${x} ${y} ${z}`, [id, Number(state)]);
}
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(), (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) {
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
const block = info(id);
return block?.states?.some((s) => s.name === name) ? get_state_value(state << 16, block, name) : undefined;
},
set_state(x, y, z, name, value) {
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
const block = info(id);
if (!block?.states?.some((s) => s.name === name)) return false;
const changed = set_state_value(state << 16, block, name, value)! >>> 16;
if (changed !== state) {
copy.set(`${x} ${y} ${z}`, [id, changed]);
rules.notify_neighbors(x, y, z);
}
return true;
},
is_face_sturdy(x, y, z, face: Face) {
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
const block = info(id);
return block !== undefined && covers_face(collision_shape_at(block, state << 16), face);
},
biome_at: () => undefined,
season_at: () => undefined,
};
setup_shared({
mod: { id: "bworld", version: "test" },
side: "client",
tags: tag_api(),
blocks: {
exists: (id) => info(id) !== undefined,
components: (id) => structuredClone(info(id)!.components ?? {}),
solid: (id) => id !== AIR_ID && is_solid(info(id)!),
},
world,
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
});
return {
// what game_mode does when this client places held against face of x y z, at hit
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(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, sneaking: false }, yaw);
},
break(x: number, y: number, z: number) {
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
rules.notify_neighbors(x, y, z);
},
blocks: () => blocks_in((x, y, z) => at(x, y, z)!),
};
}
// alice on a stone floor at y 99, south of 0 100 0, holding id
async function setup(id: string, yaw = 0) {
const t = await test_game("mods");
@@ -128,11 +39,11 @@ Deno.test("a client places a fence joined to the fences and walls beside it, the
t.game.set_block(-1, 100, 0, "bworld:oak_fence");
t.game.set_block(0, 100, -1, "bworld:stone");
t.game.set_block(1, 100, 0, "bworld:oak_leaves");
const client = client_of(t);
const client = client_of(t.game, AREA);
client.place("bworld:oak_fence", 0, 100, 0, 0, "top", [0.5, 1, 0.5]);
use(0, 99, 0, "top", [0.5, 1, 0.5]);
assertEquals(client.blocks(), server_blocks(t));
assertEquals(client.blocks(), server_blocks(t.game, AREA));
// it joined the fence and the stone, and the fence joined it back
assertEquals(state(t, 0, 100, 0, "west"), 1);
assertEquals(state(t, 0, 100, 0, "north"), 1);
@@ -141,21 +52,21 @@ Deno.test("a client places a fence joined to the fences and walls beside it, the
// breaking it lets go of the one beside it, on both
client.break(0, 100, 0);
t.send(1, { type: "break_block", x: 0, y: 100, z: 0 });
assertEquals(client.blocks(), server_blocks(t));
assertEquals(client.blocks(), server_blocks(t.game, AREA));
assertEquals(state(t, -1, 100, 0, "east"), 0);
});
Deno.test("a client places a trapdoor turned and in the half the server puts it", async () => {
const { t, use } = await setup("bworld:oak_trapdoor", Math.PI / 2);
t.game.set_block(0, 100, 0, "bworld:stone");
const client = client_of(t);
const client = client_of(t.game, AREA);
// on the upper half of the stone's east side, and on top of the floor facing alice, who looks west
client.place("bworld:oak_trapdoor", 1, 100, 0, Math.PI / 2, "east", [1, 0.8, 0.5]);
use(0, 100, 0, "east", [1, 0.8, 0.5]);
client.place("bworld:oak_trapdoor", 0, 100, 2, Math.PI / 2, "top", [0.5, 1, 0.5]);
use(0, 99, 2, "top", [0.5, 1, 0.5]);
assertEquals(client.blocks(), server_blocks(t));
assertEquals(client.blocks(), server_blocks(t.game, AREA));
assertEquals(state(t, 1, 100, 0, "half"), 1);
assertEquals(state(t, 0, 100, 2, "facing"), 1);
});
@@ -163,12 +74,12 @@ Deno.test("a client places a trapdoor turned and in the half the server puts it"
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);
const client = client_of(t.game, AREA);
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(client.blocks(), server_blocks(t.game, AREA));
assertEquals(state(t, 0, 100, 0, "open"), open);
}
// alice still has all of hers
+373 -76
View File
@@ -1,30 +1,40 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// verdigris wire, see REDSTONE.md: how it's drawn on every side it can lie on
// verdigris wire, see REDSTONE.md: how it's drawn on the faces of its cell, how it joins, and its nets' power
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
import { bake_block, type BakedQuad, FACE_INDEX, type ModelJson } from "$/common/block_models.ts";
import { block_shape } from "$/common/block_shapes.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import type { Face } from "$/common/mod_api/shared.ts";
import { default_block_value, set_state_value } from "$/common/utils.ts";
import { DIRECTIONS, FACE_OFFSETS, FACES } from "$/mods/bworld/scripts/verdigris/sides.ts";
import { test_game } from "./helpers.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { block_states, default_block_value, set_state_value } from "$/common/utils.ts";
import type { WorldSave } from "$/server/game/saves.ts";
import { can_cover, joined_cell, ways_out } from "$/mods/bworld/scripts/verdigris/joins.ts";
import type { BlockReader } from "$/mods/bworld/scripts/verdigris/signals.ts";
import { DIRECTIONS, FACE_OFFSETS, FACES, OPPOSITE } from "$/mods/bworld/scripts/verdigris/sides.ts";
import { wire_at } from "$/mods/bworld/scripts/verdigris/wires.ts";
import { type Area, client_of, server_blocks, test_game } from "./helpers.ts";
// how far it stands off the face it lies on, in blocks
const HEIGHT = 0.25 / 16;
const OPPOSITE: Record<Face, Face> = {
north: "south",
south: "north",
east: "west",
west: "east",
top: "bottom",
bottom: "top",
};
const WIRE = "bworld:verdigris_wire";
// every set of faces one wire cell can cover
function coverable(): Face[][] {
const sets: Face[][] = [];
for (let set = 1; set < 1 << FACES.length; set++) {
const faces = FACES.filter((_, i) => set & (1 << i));
if (can_cover(faces)) sets.push(faces);
}
return sets;
}
const covering = (faces: Face[]) => Object.fromEntries(faces.map((face) => [face, 1]));
async function wire() {
await test_game("mods");
const block = EverythingRegistry.get<BlockRegistry>("blocks", "bworld:verdigris_wire")!;
const block = EverythingRegistry.get<BlockRegistry>("blocks", WIRE)!;
const models = Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
const value = (states: Record<string, number>) => {
let value = default_block_value(0, block);
@@ -52,13 +62,26 @@ function range(quad: BakedQuad, face: Face) {
return [Math.min(...reach), Math.max(...reach)];
}
// lying on the block toward side: flat at the wire's height off it, facing away from it
function lies_on(quad: BakedQuad, side: Face) {
const [low, high] = range(quad, side);
return quad.face === FACE_INDEX[OPPOSITE[side]] && Math.abs(low - (1 - HEIGHT)) < 1e-6 &&
// lying on face of the cell: flat at the wire's height off it, facing away from it
function lies_on(quad: BakedQuad, face: Face) {
const [low, high] = range(quad, face);
return quad.face === FACE_INDEX[OPPOSITE[face]] && Math.abs(low - (1 - HEIGHT)) < 1e-6 &&
Math.abs(high - (1 - HEIGHT)) < 1e-6;
}
// the quad lying on face from the cell's middle toward direction, to its edge or a little past. undefined if none
function arm(quads: BakedQuad[], face: Face, direction: Face) {
const found = quads.filter((quad) => lies_on(quad, face) && range(quad, direction)[0] > 0.5);
assert(found.length <= 1);
if (found[0]) {
for (const across of DIRECTIONS[face].filter((d) => d !== direction && d !== OPPOSITE[direction])) {
const [low, high] = range(found[0], across);
assert(low > 0.4 && high < 0.6, `on ${face} toward ${direction}: no wider than the wire`);
}
}
return found[0];
}
// the part of its texture a point on a face facing that way would show on a whole block, like a face's default uv
function block_uv(face: number, [x, y, z]: number[]): [number, number] {
const uvs: [number, number][] = [
@@ -72,78 +95,352 @@ function block_uv(face: number, [x, y, z]: number[]): [number, number] {
return [uvs[face][0] * 16, uvs[face][1] * 16];
}
Deno.test("a wire on each side draws its middle there, and joins toward each of that side's directions", async () => {
Deno.test("a wire draws its middle on each face it covers, and its faces meet where they meet in the cell", async () => {
const { quads } = await wire();
FACES.forEach((side, s) => {
const alone = quads({ side: s });
assertEquals(alone.length, 1, `on ${side} it's only its middle`);
assert(lies_on(alone[0], side), side);
for (const face of FACES) {
const alone = quads({ [face]: 1 });
assertEquals(alone.length, 1, `on ${face} it's only its middle`);
assert(lies_on(alone[0], face), face);
for (const direction of DIRECTIONS[face]) {
// each runs to the edge between them, and no further
const both = quads({ [face]: 1, [direction]: 1 });
assertEquals(both.length, 4, `${face} and ${direction}`);
assertAlmostEquals(range(arm(both, face, direction)!, direction)[1], 1, 1e-6);
assertAlmostEquals(range(arm(both, direction, face)!, face)[1], 1, 1e-6);
}
}
});
DIRECTIONS[side].forEach((direction, i) => {
const where = `on ${side}, joining ${direction}`;
const [straight, edge, corner] = [1, 2, 3].map((join) =>
quads({ side: s, [`join_${i}`]: join }).filter((quad) =>
!lies_on(quad, side) || range(quad, direction)[1] > 0.6
)
);
// on the wire's side, from its middle out to the cell's edge that way
const arm = straight.find((quad) => lies_on(quad, side))!;
assert(arm, where);
assertEquals(straight.length, 1, where);
const [from, to] = range(arm, direction);
assert(from > 0.5 && Math.abs(to - 1) < 1e-6, `${where}: ${from} to ${to}`);
for (const across of DIRECTIONS[side].filter((d) => d !== direction && d !== OPPOSITE[direction])) {
const [low, high] = range(arm, across);
assert(low > 0.4 && high < 0.6, `${where}: no wider than the wire`);
}
// over an edge, a little past it to meet the wire around the corner
assertEquals(edge.length, 1, where);
assertAlmostEquals(range(edge[0], direction)[1], 1 + HEIGHT, 1e-6, where);
// into a corner, then up the face it runs into, all the way across the cell
assertEquals(corner.length, 2, where);
const bend = corner.find((quad) => !lies_on(quad, side))!;
assertEquals(bend.face, FACE_INDEX[OPPOSITE[direction]], where);
assertAlmostEquals(range(bend, direction)[0], 1 - HEIGHT, 1e-6, where);
assertEquals(range(bend, side).map((v) => Math.round(v * 1e6) / 1e6), [0, 1], where);
Deno.test("each arm_ state draws the way out of the cell its faces give it, a little past the edge", async () => {
const { quads } = await wire();
for (const faces of coverable()) {
const without = quads(covering(faces));
ways_out(faces).forEach(([face, direction], i) => {
const where = `${faces} arm_${i}`;
const with_arm = quads({ ...covering(faces), [`arm_${i}`]: 1 });
assertEquals(with_arm.length, without.length + 1, where);
assertEquals(arm(without, face, direction), undefined, where);
assertAlmostEquals(range(arm(with_arm, face, direction)!, direction)[1], 1 + HEIGHT, 1e-6, where);
});
});
}
});
Deno.test("the wire's texture lies the way it would on a whole block's faces, so it lines up from wire to wire", async () => {
const { quads } = await wire();
FACES.forEach((side, s) => {
for (let i = 0; i < 4; i++) {
for (const join of [1, 2, 3]) {
for (const quad of quads({ side: s, [`join_${i}`]: join })) {
corners(quad).forEach((point, k) => {
const [u, v] = block_uv(quad.face, point);
const where = `on ${side}, join_${i}=${join}, corner ${point}`;
assertAlmostEquals(quad.uvs[k * 2], u, 1e-6, where);
assertAlmostEquals(quad.uvs[k * 2 + 1], v, 1e-6, where);
});
}
}
for (const faces of coverable()) {
const arms = Object.fromEntries(ways_out(faces).map((_, i) => [`arm_${i}`, 1]));
for (const quad of quads({ ...covering(faces), ...arms })) {
corners(quad).forEach((point, k) => {
const [u, v] = block_uv(quad.face, point);
assertAlmostEquals(quad.uvs[k * 2], u, 1e-6, `${faces}, corner ${point}`);
assertAlmostEquals(quad.uvs[k * 2 + 1], v, 1e-6, `${faces}, corner ${point}`);
});
}
});
}
});
Deno.test("a cell covers faces that join each other, as many as its arm_ states fit", () => {
assert(can_cover(["bottom"]));
assert(can_cover(["bottom", "north"]));
assert(can_cover(["bottom", "north", "east"]));
assert(can_cover(FACES));
assert(!can_cover([]));
// opposite faces have nothing joining them, and around the cell there are too many ways out
assert(!can_cover(["bottom", "top"]));
assert(!can_cover(["bottom", "north", "top"]));
assert(!can_cover(["north", "east", "south", "west"]));
});
Deno.test("a wire shows its powered texture while it has power, and can be pointed at", async () => {
const { block, quads } = await wire();
assertEquals(new Set(quads({ join_0: 3 }).map((quad) => quad.texture)), new Set(["bworld:verdigris_wire"]));
assertEquals(
new Set(quads({ join_0: 3, power: 7 }).map((quad) => quad.texture)),
new Set(["bworld:verdigris_wire_on"]),
);
// a plate around its middle, on whichever side it lies
FACES.forEach((side, s) => {
const shape = block_shape(block, { side: s, join_0: 0, join_1: 0, join_2: 0, join_3: 0, power: 0 });
assertEquals(shape.length, 1, side);
const lit = (power: number) => new Set(quads({ bottom: 1, north: 1, power }).map((quad) => quad.texture));
assertEquals(lit(0), new Set(["bworld:verdigris_wire"]));
assertEquals(lit(7), new Set(["bworld:verdigris_wire_on"]));
// a plate around its middle on each face it covers
for (const face of FACES) {
const states = Object.fromEntries(block.states!.map((state) => [state.name, state.name === face ? 1 : 0]));
const shape = block_shape(block, states);
assertEquals(shape.length, 1, face);
const box = shape[0];
const extent = (face: Face) => {
const reach = [toward(box.slice(0, 3), face), toward(box.slice(3), face)];
const extent = (to: Face) => {
const reach = [toward(box.slice(0, 3), to), toward(box.slice(3), to)];
return [Math.min(...reach), Math.max(...reach)];
};
assertEquals(extent(side).map((v) => Math.round(v * 16)), [15, 16], side);
for (const across of DIRECTIONS[side]) assertEquals(extent(across).map((v) => Math.round(v * 16)), [3, 13]);
});
assertEquals(extent(face).map((v) => Math.round(v * 16)), [15, 16], face);
for (const across of DIRECTIONS[face]) assertEquals(extent(across).map((v) => Math.round(v * 16)), [3, 13]);
}
});
type Pos = [number, number, number];
const AREA: Area = { x: [-6, 6], y: [99, 104], z: [-6, 6] };
// alice on a stone floor at y 99, with air above it to build in
async function builder(save?: WorldSave) {
const t = await test_game("mods", save);
t.join(1, "alice");
if (!save) {
for (let x = AREA.x[0]; x <= AREA.x[1]; x++) {
for (let z = AREA.z[0]; z <= AREA.z[1]; z++) {
t.game.set_block(x, 99, z, "bworld:stone");
for (let y = 100; y <= AREA.y[1]; y++) t.game.set_block(x, y, z, AIR_ID);
}
}
}
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
const player = t.game.players()[0];
// alice uses id, or whatever she's holding, on face of the block at x y z, from right by it
const use = (id: string | undefined, x: number, y: number, z: number, face: Face) => {
if (id) {
t.send(1, { type: "chat", text: `/give ${id}` });
const slot = player.inventory.to_synced_data().findIndex((item) => item?.id === id);
t.send(1, { type: "select_slot", slot });
}
t.game.teleport(player, x + 0.5, y + 1, z + 0.5);
t.send(1, { type: "use_block", x, y, z, face, hit: [0.5, 0.5, 0.5] });
};
const states = (x: number, y: number, z: number) =>
block_states(t.game.world.get_block_value(x, y, z), t.game.world.get_block_info(x, y, z)!);
const id = (x: number, y: number, z: number) => t.game.world.get_block_id(x, y, z);
const power = (...at: Pos) => states(...at).power;
// the world the way the wire's own code reads it
const reader: BlockReader = {
get_block: id,
get_state: (x, y, z, name) => states(x, y, z)[name],
source: (block) =>
EverythingRegistry.get<BlockRegistry>("blocks", block)?.components?.["bworld:verdigris_source"] as never,
};
const covers = (...at: Pos) => FACES.filter((face) => states(...at)[face] === 1);
// the wire cells the wire at x y z joins
const joins = (...at: Pos) =>
(wire_at(reader, ...at)?.out ?? []).flatMap(([face, direction]) => {
const cell = joined_cell(reader, ...at, face, direction);
return cell ? [cell.join(" ")] : [];
});
return { t, use, states, id, power, covers, joins };
}
type Builder = Awaited<ReturnType<typeof builder>>;
// every wire cell these join joins them back
function joined_both_ways(b: Builder, wires: Pos[]) {
for (const at of wires) {
assertEquals(b.id(...at), WIRE, `${at}`);
for (const other of b.joins(...at)) {
const [x, y, z] = other.split(" ").map(Number);
assert(b.joins(x, y, z).includes(at.join(" ")), `${other} doesn't join ${at} back`);
}
}
}
// the wire from a floor up a wall onto a ceiling: one on the floor at z 2, then the cell at z 1 on the floor and the
// south face of a column at 0 100 0, one more up the column, the cell under the ceiling there on the column and the
// ceiling, and one on the ceiling above z 2. a lever on the floor joins the first
async function floor_wall_ceiling() {
const b = await builder();
for (const [x, y, z] of [[0, 100, 0], [0, 101, 0], [0, 102, 0], [0, 103, 1], [0, 103, 2]]) {
b.t.game.set_block(x, y, z, "bworld:stone");
}
b.use("bworld:verdigris", 0, 99, 2, "top");
b.use("bworld:verdigris", 0, 99, 1, "top");
b.use("bworld:verdigris", 0, 100, 0, "south");
b.use("bworld:verdigris", 0, 101, 0, "south");
b.use("bworld:verdigris", 0, 102, 0, "south");
b.use("bworld:verdigris", 0, 103, 1, "bottom");
b.use("bworld:verdigris", 0, 103, 2, "bottom");
b.use("bworld:lever", 0, 99, 3, "top");
const wires: Pos[] = [[0, 100, 2], [0, 100, 1], [0, 101, 1], [0, 102, 1], [0, 102, 2]];
return { ...b, wires, lever: [0, 100, 3] as Pos };
}
Deno.test("wire placed on another face of a cell with wire joins it there, up a wall and onto a ceiling", async () => {
const b = await floor_wall_ceiling();
assertEquals(b.covers(0, 100, 1), ["north", "bottom"]);
assertEquals(b.covers(0, 102, 1), ["north", "top"]);
joined_both_ways(b, b.wires);
assertEquals(b.joins(0, 100, 1).sort(), ["0 100 2", "0 101 1"]);
assertEquals(b.joins(0, 102, 1).sort(), ["0 101 1", "0 102 2"]);
// a cell can't cover a floor and a ceiling with nothing joining them
b.t.game.set_block(-3, 101, -3, "bworld:stone");
b.use("bworld:verdigris", -3, 99, -3, "top");
b.use("bworld:verdigris", -3, 101, -3, "bottom");
assertEquals(b.covers(-3, 100, -3), ["bottom"]);
});
Deno.test("a wire goes over the edge of a block to the wire on its next face, while nothing's in the way", async () => {
const b = await builder();
// on top of a block, over its north edge, down its north face, and on along the floor
b.t.game.set_block(3, 100, 1, "bworld:stone");
b.use("bworld:verdigris", 3, 100, 1, "top");
b.use("bworld:verdigris", 3, 100, 1, "north");
b.use("bworld:verdigris", 3, 99, 0, "top");
b.use("bworld:verdigris", 3, 99, -1, "top");
assertEquals(b.covers(3, 100, 0), ["south", "bottom"]);
joined_both_ways(b, [[3, 101, 1], [3, 100, 0], [3, 100, -1]]);
assertEquals(b.joins(3, 101, 1), ["3 100 0"]);
assertEquals(b.joins(3, 100, 0).sort(), ["3 100 -1", "3 101 1"]);
// filling the cell the edge goes around lets go of it at both ends
b.t.game.set_block(3, 101, 0, "bworld:stone");
assertEquals([b.joins(3, 101, 1), b.joins(3, 100, 0)], [[], ["3 100 -1"]]);
});
Deno.test("a player sees a wire join the moment they place it, the way the server joins it", async () => {
const b = await builder();
b.t.game.set_block(0, 100, 0, "bworld:stone");
b.t.game.set_block(0, 101, 0, "bworld:stone");
b.t.game.set_block(3, 100, 1, "bworld:stone");
b.use("bworld:verdigris", 0, 99, 1, "top");
b.use("bworld:verdigris", 0, 101, 0, "south");
b.use("bworld:verdigris", 3, 100, 1, "top");
const client = client_of(b.t.game, AREA);
const place = (at: Pos, clicked: Pos, face: Face) => {
client.place(WIRE, ...at, 0, face, [0.5, 0.5, 0.5]);
b.use("bworld:verdigris", ...clicked, face);
};
// beside one on the floor
place([0, 100, 2], [0, 99, 2], "top");
assertEquals(client.blocks(), server_blocks(b.t.game, AREA));
// onto the wall of the cell with the floor wire, joining that and the wire up the wall
place([0, 100, 1], [0, 100, 0], "south");
assertEquals(b.covers(0, 100, 1), ["north", "bottom"]);
assertEquals(b.joins(0, 101, 1), ["0 100 1"]);
assertEquals(client.blocks(), server_blocks(b.t.game, AREA));
// over an edge the wire it joins isn't beside it, so the server tells that one, and sends what it became
b.t.game.tick();
b.t.take(1);
place([3, 100, 0], [3, 100, 1], "north");
const differs = client.blocks().filter((line, i) => line !== server_blocks(b.t.game, AREA)[i]);
assertEquals(differs.map((line) => line.split(" ").slice(0, 3).join(" ")), ["3 101 1"]);
const sent = b.t.take(1).find((m) => m.type === "set_block" && m.x === 3 && m.y === 101 && m.z === 1);
assertEquals(sent?.state, b.t.game.world.get_block_value(3, 101, 1) >>> 16);
});
Deno.test("a lever's power goes all the way along a net, and the net goes off with it", async () => {
const b = await floor_wall_ceiling();
assertEquals(b.wires.map((at) => b.power(...at)), [0, 0, 0, 0, 0]);
b.use(undefined, ...b.lever, "top");
assertEquals(b.states(...b.lever).powered, 1);
assertEquals(b.wires.map((at) => b.power(...at)), [15, 15, 15, 15, 15]);
// the stone they lie on was powered by them, but that doesn't hold them on
b.use(undefined, ...b.lever, "top");
assertEquals(b.wires.map((at) => b.power(...at)), [0, 0, 0, 0, 0]);
});
Deno.test("a wire takes power from what it lies on, and two nets on one block don't power each other", async () => {
const b = await builder();
// a lever on the side of a block powers it, and the wires on its top and underneath through it
b.t.game.set_block(-3, 101, -3, "bworld:stone");
b.use("bworld:verdigris", -3, 101, -3, "top");
b.use("bworld:verdigris", -3, 101, -3, "bottom");
b.use("bworld:lever", -3, 101, -3, "east");
b.use(undefined, -2, 101, -3, "top");
assertEquals([b.power(-3, 102, -3), b.power(-3, 100, -3)], [15, 15]);
// a wire on a verdigris block, and one joined to one
b.t.game.set_block(3, 101, 3, "bworld:verdigris_block");
b.use("bworld:verdigris", 3, 101, 3, "top");
assertEquals(b.power(3, 102, 3), 15);
b.t.game.set_block(3, 101, -4, "bworld:stone");
b.t.game.set_block(4, 102, -4, "bworld:verdigris_block");
b.use("bworld:verdigris", 3, 101, -4, "top");
b.use("bworld:verdigris", 3, 101, -4, "bottom");
assertEquals(b.power(3, 102, -4), 15);
// the wire under that block isn't powered by the net on top of it, which only wire powers it with
assertEquals(b.power(3, 100, -4), 0);
b.t.game.set_block(4, 102, -4, AIR_ID);
assertEquals(b.power(3, 102, -4), 0);
});
// five wires in a row on the floor at z 5, from x -2 to 2, and a lever at the west end, switched on
async function powered_row(save?: WorldSave) {
const b = await builder(save);
const wires: Pos[] = [-2, -1, 0, 1, 2].map((x) => [x, 100, 5]);
if (!save) {
for (const [x] of wires) b.use("bworld:verdigris", x, 99, 5, "top");
b.use("bworld:lever", -3, 99, 5, "top");
b.use(undefined, -3, 100, 5, "top");
}
return { ...b, wires, lever: [-3, 100, 5] as Pos };
}
Deno.test("breaking a wire in the middle of a net leaves the half cut off from the lever without power", async () => {
const b = await powered_row();
assertEquals(b.wires.map((at) => b.power(...at)), [15, 15, 15, 15, 15]);
b.t.game.set_block(0, 100, 5, AIR_ID);
assertEquals([-2, -1, 1, 2].map((x) => b.power(x, 100, 5)), [15, 15, 0, 0]);
});
Deno.test("each wire is sent once when its net's power changes, and not at all when a block beside it is placed", async () => {
const b = await powered_row();
const sent_wires = () =>
b.t.take(1).filter((m) => m.type === "set_block" && m.id === WIRE).map((m) => `${m.x} ${m.z}`);
b.t.game.tick();
b.t.take(1);
b.use(undefined, ...b.lever, "top");
assertEquals(sent_wires().sort(), b.wires.map(([x, , z]) => `${x} ${z}`).sort());
b.use(undefined, ...b.lever, "top");
b.t.take(1);
b.t.game.set_block(0, 100, 6, "bworld:stone");
b.t.game.set_block(1, 101, 5, "bworld:stone");
assertEquals(sent_wires(), []);
assertEquals(b.wires.map((at) => b.power(...at)), [15, 15, 15, 15, 15]);
});
Deno.test("a world saved and loaded has the same nets", async () => {
const b = await powered_row();
const saved = b.t.game.save();
const again = await powered_row(saved);
assertEquals(again.wires.map((at) => again.power(...at)), [15, 15, 15, 15, 15]);
again.use(undefined, ...again.lever, "top");
assertEquals(again.wires.map((at) => again.power(...at)), [0, 0, 0, 0, 0]);
});
Deno.test("wire comes off a face whose block goes, and drops one verdigris for each face it covered", async () => {
const b = await builder();
const verdigris = () =>
b.t.game.item_entities().filter((e) => e.item.type_id === "bworld:verdigris").reduce(
(n, e) => n + e.item.amount,
0,
);
// on a floor and the wall beside it in one cell
b.t.game.set_block(5, 100, 4, "bworld:stone");
b.use("bworld:verdigris", 5, 99, 5, "top");
b.use("bworld:verdigris", 5, 100, 4, "south");
assertEquals(b.covers(5, 100, 5), ["north", "bottom"]);
b.t.game.set_block(5, 100, 4, AIR_ID);
assertEquals(b.covers(5, 100, 5), ["bottom"]);
assertEquals(verdigris(), 1);
b.t.game.set_block(5, 99, 5, AIR_ID);
assertEquals(b.id(5, 100, 5), AIR_ID);
assertEquals(verdigris(), 2);
// broken by hand, a cell drops what it covered
b.t.game.set_block(-5, 100, 4, "bworld:stone");
b.use("bworld:verdigris", -5, 99, 5, "top");
b.use("bworld:verdigris", -5, 100, 4, "south");
b.t.game.destroy_block(-5, 100, 5);
assertEquals(verdigris(), 4);
});
Deno.test("a wire or lever only goes on something to attach to, and a lever breaks when it goes", async () => {
const b = await builder();
// on a wall it points out of the wall, on a floor or ceiling it lies or hangs there
b.t.game.set_block(5, 101, -5, "bworld:stone");
b.use("bworld:lever", 5, 101, -5, "south");
assertEquals([b.states(5, 101, -4).face, b.states(5, 101, -4).facing], [1, FACES.indexOf("south")]);
b.use("bworld:lever", 5, 101, -5, "bottom");
assertEquals(b.states(5, 100, -5).face, 2);
b.use("bworld:lever", 4, 99, -5, "top");
assertEquals(b.states(4, 100, -5).face, 0);
b.t.game.set_block(5, 101, -5, AIR_ID);
assertEquals([b.id(5, 101, -4), b.id(5, 100, -5)], [AIR_ID, AIR_ID]);
assertEquals(b.id(4, 100, -5), "bworld:lever");
// a fence's top isn't something to lie on
b.t.game.set_block(-5, 100, -5, "bworld:oak_fence");
b.use("bworld:verdigris", -5, 100, -5, "top");
assertEquals(b.id(-5, 101, -5), AIR_ID);
});
+40 -32
View File
@@ -1,9 +1,11 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// writes the verdigris wire's look: its pieces as models, and the block's parts, which put each piece on every side a
// wire can lie on, pointing each way that side's directions go (DIRECTIONS in sides.ts). that's a part per side,
// direction and kind of join, too many to keep right by hand. run it after changing anything here or the directions:
// writes the verdigris wire's look: its pieces as models, and the block's parts, which put each piece on every face of
// its cell it can cover, pointing each way that face's directions go (DIRECTIONS in sides.ts). a way out of the cell
// is an arm_ state whose meaning depends on which faces the cell covers (ways_out in joins.ts), so there's a part for
// each of those for every set of faces a cell can cover, too many to keep right by hand. run it after changing
// anything here, the directions or the ways out:
//
// deno run -A tools/verdigris_wire_model.ts
//
@@ -12,6 +14,7 @@
import { model_shape } from "$/common/block_shapes.ts";
import type { ModelElementJson, ModelFace } from "$/common/block_models.ts";
import type { Face } from "$/common/mod_api/shared.ts";
import { can_cover, ways_out } from "$/mods/bworld/scripts/verdigris/joins.ts";
import { DIRECTIONS, FACE_OFFSETS, FACES } from "$/mods/bworld/scripts/verdigris/sides.ts";
const MODELS = "mods/bworld/models";
@@ -23,22 +26,18 @@ const [A, B] = [8 - WIDTH / 2, 8 + WIDTH / 2];
// what's outlined when the wire is pointed at: a plate around its middle, since the pieces are too thin to aim at
const CENTER_SHAPE = [[3, 0, 3, 13, 1, 13]];
const face = { texture: "#wire" };
const wire_face = { texture: "#wire" };
// a floor wire's pieces. the ones that point a way point north. their faces take their texture from where they are,
// so they have no uv
// the pieces of the wire on a cell's floor. the ones that point a way point north. their faces take their texture from
// where they are, so they have no uv
const PIECES: Record<string, ModelElementJson[]> = {
// always there, so the arms meet
center: [{ from: [A, 0, A], to: [B, HEIGHT, B], faces: { top: face } }],
// join 1, straight on: to the edge of its cell
arm: [{ from: [A, 0, 0], to: [B, HEIGHT, A], faces: { top: face } }],
// join 2, over an edge: a little past it, to meet the wire around the corner on the block's other face
edge: [{ from: [A, 0, -HEIGHT], to: [B, HEIGHT, A], faces: { top: face } }],
// join 3, into a corner: then up the face it runs into, to the wire on that face in the cell above
corner: [
{ from: [A, 0, 0], to: [B, HEIGHT, A], faces: { top: face } },
{ from: [A, 0, 0], to: [B, 16, HEIGHT], faces: { south: face } },
],
center: [{ from: [A, 0, A], to: [B, HEIGHT, B], faces: { top: wire_face } }],
// to the edge of its cell, where it meets the wire on the cell's face that way
arm: [{ from: [A, 0, 0], to: [B, HEIGHT, A], faces: { top: wire_face } }],
// a way out of its cell it joins: a little past the edge, so going around the edge of the block it lies on it meets
// the wire on that block's next face, and straight on it meets the next cell's
out: [{ from: [A, 0, -HEIGHT], to: [B, HEIGHT, A], faces: { top: wire_face } }],
};
// the faces a quarter turn clockwise seen from above takes each face to
@@ -62,7 +61,7 @@ function pointing_east(elements: ModelElementJson[]): ModelElementJson[] {
}
const models: Record<string, ModelElementJson[]> = { ...PIECES };
for (const name of ["arm", "edge", "corner"]) models[`${name}_east`] = pointing_east(PIECES[name]);
for (const name of ["arm", "out"]) models[`${name}_east`] = pointing_east(PIECES[name]);
type Vec = readonly [number, number, number];
const cross = (
@@ -75,10 +74,10 @@ function shape_key(boxes: readonly (readonly number[])[]) {
return JSON.stringify(boxes.map((box) => box.map((v) => Math.round(v * 1e6) / 1e6)).sort());
}
// the boxes a floor piece pointing north has on a wire lying on the block toward side, pointing toward direction: turned
// around the middle of the block so down goes to side and north to direction. clamped to the block, like model_shape
function placed(elements: ModelElementJson[], side: Face, direction: Face) {
const down = FACE_OFFSETS[side];
// the boxes a floor piece pointing north has on the wire covering face of its cell, pointing toward direction: turned
// around the middle of the block so down goes to face and north to direction. clamped to the block, like model_shape
function placed(elements: ModelElementJson[], face: Face, direction: Face) {
const down = FACE_OFFSETS[face];
const north = FACE_OFFSETS[direction];
const east = cross(down, north);
const turn = ([x, y, z]: readonly number[]) =>
@@ -91,8 +90,8 @@ function placed(elements: ModelElementJson[], side: Face, direction: Face) {
}
// the model and turns that put a piece there, the piece pointing north if it can, then its copy pointing east
function placement(piece: string, side: Face, direction: Face) {
const wanted = placed(PIECES[piece], side, direction);
function placement(piece: string, face: Face, direction: Face) {
const wanted = placed(PIECES[piece], face, direction);
for (const name of piece === "center" ? [piece] : [piece, `${piece}_east`]) {
for (const x of [0, 90, 180, 270]) {
for (const y of [0, 90, 180, 270]) {
@@ -101,19 +100,28 @@ function placement(piece: string, side: Face, direction: Face) {
}
}
}
throw new Error(`no turn puts the ${piece} on the ${side} pointing ${direction}`);
throw new Error(`no turn puts the ${piece} on the ${face} pointing ${direction}`);
}
const JOINS = [[1, "arm"], [2, "edge"], [3, "corner"]] as const;
const parts: Record<string, unknown>[] = [];
FACES.forEach((side, s) => {
parts.push({ when: `side=${s}`, ...placement("center", side, DIRECTIONS[side][0]), shape: CENTER_SHAPE });
DIRECTIONS[side].forEach((direction, i) => {
for (const [join, piece] of JOINS) {
parts.push({ when: `side=${s},join_${i}=${join}`, ...placement(piece, side, direction) });
}
for (const covered of FACES) {
parts.push({ when: `${covered}=1`, ...placement("center", covered, DIRECTIONS[covered][0]), shape: CENTER_SHAPE });
}
// two faces that meet inside the cell join at their edge
for (const covered of FACES) {
for (const direction of DIRECTIONS[covered]) {
parts.push({ when: `${covered}=1,${direction}=1`, ...placement("arm", covered, direction) });
}
}
// the ways out of the cell it joins, for every set of faces a cell can cover
for (let set = 1; set < 1 << FACES.length; set++) {
const faces = FACES.filter((_, i) => set & (1 << i));
if (!can_cover(faces)) continue;
const covering = FACES.map((covered) => `${covered}=${faces.includes(covered) ? 1 : 0}`).join(",");
ways_out(faces).forEach(([covered, direction], i) => {
parts.push({ when: `${covering},arm_${i}=1`, ...placement("out", covered, direction) });
});
});
}
const written: string[] = [];
const write = (path: string, json: unknown) => {