Files
bworld/common/utils.ts
T
2026-11-05 23:06:37 -03:00

307 lines
11 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { ID_MASK, STATE_SHIFT } from "./constants.ts";
import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "./everything_registry.ts";
import { block_item_texture, cube_face_texture } from "./block_models.ts";
import { FULL_SHAPE, type Shape } from "./block_shapes.ts";
import type { FluidRules } from "./fluids.ts";
import { type ItemStack, sell_value } from "./inventory.ts";
import type { SharedContext } from "./mod_api/shared.ts";
import type { FluidInCell } from "./physics.ts";
import { list_matches } from "./tags.ts";
import { is_object } from "./schema.ts";
export function point_inside_rec(
point_x: number,
point_y: number,
rec_x: number,
rec_y: number,
rec_w: number,
rec_h: number,
) {
return point_x > rec_x &&
point_x < rec_x + rec_w &&
point_y > rec_y &&
point_y < rec_y + rec_h;
}
export function distance_point_rectangle(px: number, py: number, sqx: number, sqy: number, sqw: number, sqh: number) {
const x0 = sqx;
const y0 = sqy;
const x1 = sqx + sqw;
const y1 = sqy + sqh;
const cx = Math.max(x0, Math.min(px, x1));
const cy = Math.max(y0, Math.min(py, y1));
const dx = px - cx;
const dy = py - cy;
return Math.sqrt(dx * dx + dy * dy);
}
// -pi to pi
export function wrap_angle(angle: number) {
angle %= Math.PI * 2;
if (angle >= Math.PI) angle -= Math.PI * 2;
if (angle < -Math.PI) angle += Math.PI * 2;
return angle;
}
// the hex sha-256 of bytes
export async function sha256(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
export function distance_point_point(ax: number, ay: number, az: number, bx: number, by: number, bz: number) {
const dx = ax - bx;
const dy = ay - by;
const dz = az - bz;
return dx * dx + dy * dy + dz * dz;
}
export function register_block_item(block: BlockRegistry) {
// cubes are drawn from the block's textures, anything else as a sprite
const texture_id = block_item_texture(block) ?? cube_face_texture(block, "side");
const item: ItemRegistry = { texture_id, block_id: block.id };
if (block.name !== undefined) item.name = block.name;
EverythingRegistry.register<ItemRegistry>("items", block.id, item);
}
// the texture a stack is drawn with: one of its data_textures when its data has that key set, or its texture
export function item_texture(
item: ItemStack,
info = EverythingRegistry.get<ItemRegistry>("items", item.type_id),
): string {
if (!info) return "cubi:missing";
const data = item.data as Record<string, unknown> | undefined;
for (const [key, texture] of Object.entries(info.data_textures ?? {})) {
if (data?.[key]) return texture;
}
return typeof info.texture_id === "function" ? info.texture_id(item) : info.texture_id;
}
// what players see an item called: its name, or one made from its id
export function display_name(item_id: string): string {
return EverythingRegistry.get<ItemRegistry>("items", item_id)?.name || name_from_id(item_id);
}
// ctx.items for shared scripts, and the part of the client's that's the same. fluids are this side's rules, which
// price full fluid containers
export function shared_items_api(mod: string, fluids: FluidRules): SharedContext["items"] {
const known = (id: string) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`[${mod}] unknown item ${id}`);
return item;
};
return {
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
name: (id) => (known(id), display_name(id)),
components: (id) => structuredClone(known(id).components ?? {}),
sell_value: (id, data) => (known(id), sell_value(id, data, fluids)),
};
}
// a name for what didn't give one, so bworld:iron_ingot is "Iron Ingot"
export function name_from_id(id: string): string {
const words = (id.split(":")[1] ?? id).split("_").filter((word) => word.length > 0);
return words.map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
}
// whether two stacks' or fluids' data are the same, whatever order their keys are in. no data is the same as {}, and a
// key set to undefined as one that isn't there, the way they'd be once saved or sent
export function same_data(a: unknown, b: unknown): boolean {
return (is_empty_data(a) && is_empty_data(b)) || same_json(a, b);
}
function is_empty_data(value: unknown) {
return value === undefined || (is_object(value) && defined_keys(value).length === 0);
}
function same_json(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (Array.isArray(a) || Array.isArray(b)) {
return Array.isArray(a) && Array.isArray(b) && a.length === b.length &&
a.every((value, i) => same_json(value, b[i]));
}
if (!is_object(a) || !is_object(b)) return false;
const keys = defined_keys(a);
return keys.length === defined_keys(b).length && keys.every((key) => same_json(a[key], b[key]));
}
function defined_keys(value: Record<string, unknown>) {
return Object.keys(value).filter((key) => value[key] !== undefined);
}
export function get_state_value(value: number, block_info: BlockRegistry, name: string) {
if (!block_info.states) {
return undefined;
}
if (!block_info.compiled_states) {
compile_block_states(block_info);
}
const state_bits = value >>> STATE_SHIFT;
const s = block_info.compiled_states!.find((s) => s.name === name)!;
return (state_bits & s.mask) >>> s.shift;
}
// every state of a block value by name, like { age: 7 }
export function block_states(value: number, block_info: BlockRegistry): Record<string, number> {
if (!block_info.states) return {};
if (!block_info.compiled_states) compile_block_states(block_info);
const state_bits = value >>> STATE_SHIFT;
const states: Record<string, number> = {};
for (const s of block_info.compiled_states!) states[s.name] = (state_bits & s.mask) >>> s.shift;
return states;
}
export function set_state_value(value: number, block_info: BlockRegistry, name: string, new_value: number) {
if (!block_info.states) {
return undefined;
}
if (!block_info.compiled_states) {
compile_block_states(block_info);
}
const id = value & ID_MASK;
let state_bits = value >>> 16;
const s = block_info.compiled_states!.find((s) => s.name === name)!;
state_bits = (state_bits & ~s.mask) | (new_value << s.shift);
// >>> 0 keeps it unsigned when the top state bit is set
return ((state_bits << 16) | id) >>> 0;
}
// a block's numeric id with its states at their defaults, what placing it should store
export function default_block_value(nid: number, block_info: BlockRegistry | undefined): number {
let value = nid;
for (const state of block_info?.states ?? []) {
value = set_state_value(value, block_info!, state.name, state.default) ?? value;
}
return value;
}
export function block_value(nid: number, state: number): number {
return ((state << STATE_SHIFT) | nid) >>> 0;
}
function compile_block_states(block_info: BlockRegistry) {
if (!block_info.states) {
return;
}
let offset = 0;
block_info.compiled_states = block_info.states.map((s) => {
const shift = offset;
const mask = ((1 << s.bits) - 1) << shift;
offset += s.bits;
return { name: s.name, mask, shift };
});
}
// whether a block can be at a spot with below under it, see place_on
export function can_stand_on(block: BlockRegistry | undefined, below: string): boolean {
return !block?.place_on || list_matches("blocks", block.place_on, below);
}
// where a block placed by clicking a face of another goes: into the clicked block when it can be replaced (like water),
// like minecraft, otherwise next to it
export function placement_target(
x: number,
y: number,
z: number,
offset: { x: number; y: number; z: number },
clicked: BlockRegistry | undefined,
) {
return clicked?.replaceable ? { x, y, z } : { x: x + offset.x, y: y + offset.y, z: z + offset.z };
}
// whether a player can place block where current is now, with below under it. current is undefined for air,
// current_value is its value with its states
export function can_place(
block: BlockRegistry | undefined,
current: BlockRegistry | undefined,
current_value: number,
below: string,
): boolean {
if (!block) return false;
const into = current?.id ?? "cubi:air";
const replaceable = !current || current.replaceable === true;
const in_ok = block.place_in ? list_matches("blocks", block.place_in, into) : replaceable;
// one that's only ever waterlogged goes into a source of its fluid and nothing else
const source_ok = !block.waterlogged_only ||
(current !== undefined && current.id === block.waterloggable &&
(get_state_value(current_value, current, "level") ?? 0) === 0);
return in_ok && source_ok && can_stand_on(block, below);
}
// whether an entity's collision box, centered on x and z with its feet at y, overlaps the block at bx, by, bz. only
// the block's boxes count when given its shape, so a slab's empty half doesn't
export function box_overlaps_block(
entity: { x: number; y: number; z: number; width: number; height: number },
bx: number,
by: number,
bz: number,
shape: Shape = FULL_SHAPE,
): boolean {
const half = entity.width / 2;
return shape.some((box) =>
entity.x + half > bx + box[0] && entity.x - half < bx + box[3] &&
entity.y + entity.height > by + box[1] && entity.y < by + box[4] &&
entity.z + half > bz + box[2] && entity.z - half < bz + box[5]
);
}
// numeric so looking chunks up doesnt allocate a string every time, fine for |x|, |z| < 32768
export function chunk_key(x: number, z: number) {
return (x + 32768) * 65536 + (z + 32768);
}
// whether a block value is a waterloggable block holding its fluid
export function is_waterlogged(value: number, block: BlockRegistry | undefined): boolean {
return block?.waterloggable !== undefined && get_state_value(value, block, "waterlogged") === 1;
}
// the fluid in a cell with this block value: the block itself, or the fluid it's waterlogged with. undefined for
// none. what entities swim in, see in_water in physics.ts
export function fluid_block(value: number, block: BlockRegistry | undefined): BlockRegistry | undefined {
if (block?.fluid) return block;
if (!is_waterlogged(value, block)) return undefined;
return EverythingRegistry.get<BlockRegistry>("blocks", block!.waterloggable!);
}
// the fluid in a cell and how high it is, for fluids pushing things (see push_by_fluid in physics.ts). a waterlogged
// block holds a source
export function fluid_in_cell(value: number, block: BlockRegistry | undefined): FluidInCell | undefined {
if (block?.fluid) {
const level = get_state_value(value, block, "level") ?? 0;
return { id: block.id, height: fluid_height(level, block.fluid.range) };
}
const fluid = fluid_block(value, block);
return fluid && { id: fluid.id, height: 1 };
}
// a waterloggable block placed where a source of its fluid is holds it, like minecraft's getStateForPlacement.
// value is what it's placed as, current_value and current what's there now
export function waterlog_placement(
value: number,
block: BlockRegistry,
current_value: number,
current: BlockRegistry | undefined,
): number {
if (!block.waterloggable || current?.id !== block.waterloggable) return value;
if ((get_state_value(current_value, current, "level") ?? 0) !== 0) return value;
return set_state_value(value, block, "waterlogged", 1)!;
}