Files
bworld/common/utils.ts
T
2026-10-12 15:09:22 -03:00

242 lines
8.7 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, ItemRegistry, liquid_height } 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 { ItemStack } from "./inventory.ts";
import type { LiquidInCell } from "./physics.ts";
import { list_matches } from "./tags.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);
}
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 "engine: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, so bworld:iron_ingot is "Iron Ingot"
export function display_name(item_id: string): string {
const name = EverythingRegistry.get<ItemRegistry>("items", item_id)?.name;
if (name) return name;
const words = (item_id.split(":")[1] ?? item_id).split("_").filter((word) => word.length > 0);
return words.map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
}
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> {
return Object.fromEntries(
(block_info.states ?? []).map((s) => [s.name, get_state_value(value, block_info, s.name)!]),
);
}
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 ?? "bworld: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 liquid 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 liquid
export function is_waterlogged(value: number, block: BlockRegistry | undefined): boolean {
return block?.waterloggable !== undefined && get_state_value(value, block, "waterlogged") === 1;
}
// the liquid in a cell with this block value: the block itself, or the liquid it's waterlogged with. undefined for
// none. what entities swim in, see in_water in physics.ts
export function liquid_block(value: number, block: BlockRegistry | undefined): BlockRegistry | undefined {
if (block?.liquid) return block;
if (!is_waterlogged(value, block)) return undefined;
return EverythingRegistry.get<BlockRegistry>("blocks", block!.waterloggable!);
}
// the liquid in a cell and how high it is, for liquids pushing things (see push_by_liquid in physics.ts). a waterlogged
// block holds a source
export function liquid_in_cell(value: number, block: BlockRegistry | undefined): LiquidInCell | undefined {
if (block?.liquid) {
const level = get_state_value(value, block, "level") ?? 0;
return { id: block.id, height: liquid_height(level, block.liquid.range) };
}
const liquid = liquid_block(value, block);
return liquid && { id: liquid.id, height: 1 };
}
// a waterloggable block placed where a source of its liquid 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)!;
}