Files
bworld/common/loot.ts
T
2026-10-13 11:57:43 -03:00

453 lines
17 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// loot tables, like minecraft's: what something gives when it's broken, killed, fished or opened, as data. a table
// has pools, each rolled some number of times, each roll picking one of the pool's entries by weight. conditions
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
// conditions and functions (ctx.loot in server scripts), which are ids in their namespace.
// see docs/modding/resources/loot_tables.md
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
import { list_matches, Tags } from "./tags.ts";
import { is_object, TAG_ID_PATTERN } from "./mod_data.ts";
// a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's
// constant, uniform and binomial number providers
export type NumberProvider = number | { min: number; max: number } | { n: number; p: number };
export interface LootCondition {
condition: string;
[param: string]: unknown;
}
export interface LootFunction {
function: string;
[param: string]: unknown;
}
export interface LootEntry {
// "item" when not given
type?: "item" | "tag" | "loot_table" | "empty";
// for "item"
item?: string;
// for "item", the count it gives, 1 when not given. the same as a set_count function first
count?: NumberProvider;
// for "tag": one item of the tag at random, like "#bworld:logs"
tag?: string;
// for "loot_table": what rolling that table gives
table?: string;
// how likely it is picked against the pool's other entries, 1 when not given
weight?: number;
conditions?: LootCondition[];
functions?: LootFunction[];
}
export interface LootPool {
// how many times one of its entries is picked, 1 when not given
rolls?: NumberProvider;
conditions?: LootCondition[];
entries: LootEntry[];
functions?: LootFunction[];
}
export interface LootTableJson {
// from its file: loot_tables/<path>.json in a mod is <mod>:<path>
id: string;
pools: LootPool[];
conditions?: LootCondition[];
functions?: LootFunction[];
}
// an item a table gives
export interface LootItem {
id: string;
count: number;
data?: unknown;
}
// what the built in conditions read from what's happening. more is there for mods' conditions and functions, like
// the player, see LootContext in mod_api/server.ts
export interface BaseLootContext {
// the block being broken, with its states
block?: { id: string; states?: Record<string, number> };
// what it's done with, like the tool breaking the block or the fishing rod
tool?: { id: string };
// a player killed the entity it's for
killed_by_player?: boolean;
}
// a mod's condition: whether it holds, from its params (the condition's json) and what's happening
export type LootConditionFn<C> = (params: LootCondition, context: C) => boolean;
// a mod's function: the item changed, or undefined to take it away
export type LootFunctionFn<C> = (item: LootItem, params: LootFunction, context: C) => LootItem | undefined;
export interface LootEnvironment<C extends BaseLootContext> {
conditions?: ReadonlyMap<string, LootConditionFn<C>>;
functions?: ReadonlyMap<string, LootFunctionFn<C>>;
// 0 to 1, Math.random when not given
random?: () => number;
}
export const LOOT_CONDITIONS = [
"random_chance",
"match_tool",
"block_state",
"killed_by_player",
"inverted",
"any_of",
"all_of",
] as const;
export const LOOT_FUNCTIONS = ["set_count", "limit_count", "set_data"] as const;
const ENTRY_TYPES = ["item", "tag", "loot_table", "empty"];
// tables in tables in tables: past this it's taken as a loop and gives nothing more
const MAX_DEPTH = 16;
export class LootError extends Error {
constructor(message: string) {
super(message);
this.name = "LootError";
}
}
// rolls a registered table: every item it gives, in the order its pools gave them
export function roll_loot<C extends BaseLootContext>(
id: string,
context: C,
env: LootEnvironment<C> = {},
): LootItem[] {
return roll_table(id, context, { random: Math.random, ...env }, 0);
}
type Env<C extends BaseLootContext> = LootEnvironment<C> & { random: () => number };
function roll_table<C extends BaseLootContext>(id: string, context: C, env: Env<C>, depth: number): LootItem[] {
const table = EverythingRegistry.get<LootTableJson>("loot_tables", id);
if (!table) throw new LootError(`loot table ${id} doesn't exist`);
if (depth > MAX_DEPTH) throw new LootError(`loot table ${id} is in itself, through its loot_table entries`);
if (!all(table.conditions, context, env)) return [];
const items: LootItem[] = [];
for (const pool of table.pools) {
if (!all(pool.conditions, context, env)) continue;
const rolls = number(pool.rolls ?? 1, env);
for (let i = 0; i < rolls; i++) {
const entry = pick(pool.entries.filter((e) => all(e.conditions, context, env)), env);
if (!entry) continue;
for (const item of entry_items(entry, context, env, depth)) {
const done = apply_all(apply_all(item, entry.functions, context, env), pool.functions, context, env);
if (done) items.push(done);
}
}
}
return items.flatMap((item) => apply_all(item, table.functions, context, env) ?? []).filter((item) =>
item.count > 0
);
}
// one of them by weight, undefined for none
function pick<T extends { weight?: number }>(entries: T[], env: { random: () => number }): T | undefined {
const total = entries.reduce((sum, entry) => sum + (entry.weight ?? 1), 0);
if (total <= 0) return undefined;
let left = env.random() * total;
for (const entry of entries) {
left -= entry.weight ?? 1;
if (left < 0) return entry;
}
return entries.at(-1);
}
function entry_items<C extends BaseLootContext>(entry: LootEntry, context: C, env: Env<C>, depth: number): LootItem[] {
switch (entry.type ?? "item") {
case "item":
return [{ id: entry.item!, count: number(entry.count ?? 1, env) }];
case "tag": {
const items = Tags.get("items", entry.tag!);
const id = items[Math.floor(env.random() * items.length)];
return id === undefined ? [] : [{ id, count: number(entry.count ?? 1, env) }];
}
case "loot_table":
return roll_table(entry.table!, context, env, depth + 1);
default:
return [];
}
}
export function number(provider: NumberProvider, env: { random: () => number }): number {
if (typeof provider === "number") return provider;
if ("min" in provider) return provider.min + Math.floor(env.random() * (provider.max - provider.min + 1));
let count = 0;
for (let i = 0; i < provider.n; i++) if (env.random() < provider.p) count++;
return count;
}
function all<C extends BaseLootContext>(conditions: LootCondition[] | undefined, context: C, env: Env<C>): boolean {
return (conditions ?? []).every((condition) => holds(condition, context, env));
}
function holds<C extends BaseLootContext>(condition: LootCondition, context: C, env: Env<C>): boolean {
switch (condition.condition) {
case "random_chance":
return env.random() < (condition.chance as number);
case "match_tool": {
const id = context.tool?.id;
if (!id) return false;
const items = condition.items as string[] | undefined;
if (items && !list_matches("items", items, id)) return false;
const tool = EverythingRegistry.get<ItemRegistry>("items", id)?.tool;
if (condition.tool !== undefined && tool?.type !== condition.tool) return false;
if (condition.min_tier !== undefined && (tool?.tier ?? -1) < (condition.min_tier as number)) return false;
return true;
}
case "block_state": {
const block = context.block;
if (!block) return false;
if (condition.block !== undefined && block.id !== condition.block) return false;
return Object.entries(condition.states as Record<string, StateMatch>).every(([name, match]) => {
const value = block.states?.[name];
if (value === undefined) return false;
if (typeof match === "number") return value === match;
return value >= (match.min ?? -Infinity) && value <= (match.max ?? Infinity);
});
}
case "killed_by_player":
return context.killed_by_player === true;
case "inverted":
return !holds(condition.term as LootCondition, context, env);
case "any_of":
return (condition.terms as LootCondition[]).some((term) => holds(term, context, env));
case "all_of":
return (condition.terms as LootCondition[]).every((term) => holds(term, context, env));
}
const custom = env.conditions?.get(condition.condition);
if (!custom) throw new LootError(`loot condition ${condition.condition} isn't registered`);
return custom(condition, context);
}
type StateMatch = number | { min?: number; max?: number };
function apply_all<C extends BaseLootContext>(
item: LootItem | undefined,
functions: LootFunction[] | undefined,
context: C,
env: Env<C>,
): LootItem | undefined {
for (const fn of functions ?? []) {
if (!item) return undefined;
item = apply(item, fn, context, env);
}
return item;
}
function apply<C extends BaseLootContext>(
item: LootItem,
fn: LootFunction,
context: C,
env: Env<C>,
): LootItem | undefined {
if (!all(fn.conditions as LootCondition[] | undefined, context, env)) return item;
switch (fn.function) {
case "set_count": {
const count = number(fn.count as NumberProvider, env);
return { ...item, count: fn.add ? item.count + count : count };
}
case "limit_count": {
const min = (fn.min as number | undefined) ?? 0;
const max = (fn.max as number | undefined) ?? Infinity;
return { ...item, count: Math.min(Math.max(item.count, min), max) };
}
case "set_data":
return { ...item, data: structuredClone(fn.data) };
}
const custom = env.functions?.get(fn.function);
if (!custom) throw new LootError(`loot function ${fn.function} isn't registered`);
return custom(item, fn, context);
}
// checking a table's json
type Problems = string[];
export function validate_loot_table(json: unknown): Problems {
if (!is_object(json)) return ["loot_table must be an object"];
const problems: Problems = [];
if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) {
problems.push("its file name must be a-z, 0-9 and _, in folders");
}
problems.push(...validate_conditions(json.conditions, "conditions"));
problems.push(...validate_functions(json.functions, "functions"));
if (!Array.isArray(json.pools)) return [...problems, "pools must be a list"];
json.pools.forEach((pool, i) => {
const where = `pools[${i}]`;
if (!is_object(pool)) return problems.push(`${where} must be { rolls, entries }`);
if (pool.rolls !== undefined) problems.push(...validate_number(pool.rolls, `${where}.rolls`));
problems.push(...validate_conditions(pool.conditions, `${where}.conditions`));
problems.push(...validate_functions(pool.functions, `${where}.functions`));
if (!Array.isArray(pool.entries) || pool.entries.length === 0) {
return problems.push(`${where}.entries must be a list of entries`);
}
pool.entries.forEach((entry, j) => problems.push(...validate_entry(entry, `${where}.entries[${j}]`)));
});
return problems;
}
function validate_entry(entry: unknown, where: string): Problems {
if (!is_object(entry)) return [`${where} must be { type, item, weight }`];
const problems: Problems = [];
const type = entry.type ?? "item";
if (typeof type !== "string" || !ENTRY_TYPES.includes(type)) {
problems.push(`${where}.type must be one of ${ENTRY_TYPES.join(", ")}`);
}
const field = { item: "item", tag: "tag", loot_table: "table" }[type as string];
if (field && typeof entry[field] !== "string") problems.push(`${where}.${field} is needed for a "${type}" entry`);
if (type === "tag" && typeof entry.tag === "string" && !entry.tag.startsWith("#")) {
problems.push(`${where}.tag must be a #tag, like "#bworld:logs"`);
}
if (entry.count !== undefined) problems.push(...validate_number(entry.count, `${where}.count`));
if (entry.weight !== undefined && (typeof entry.weight !== "number" || entry.weight < 0)) {
problems.push(`${where}.weight must be a number, 0 or more`);
}
problems.push(...validate_conditions(entry.conditions, `${where}.conditions`));
problems.push(...validate_functions(entry.functions, `${where}.functions`));
return problems;
}
export function validate_number(value: unknown, where: string): Problems {
const whole = (n: unknown) => Number.isInteger(n) && (n as number) >= 0;
if (whole(value)) return [];
if (is_object(value) && whole(value.min) && whole(value.max) && (value.max as number) >= (value.min as number)) {
return [];
}
if (
is_object(value) && whole(value.n) && typeof value.p === "number" && value.p >= 0 && value.p <= 1
) return [];
return [`${where} must be a whole number, { min, max } or { n, p }`];
}
function validate_conditions(list: unknown, where: string): Problems {
if (list === undefined) return [];
if (!Array.isArray(list)) return [`${where} must be a list`];
return list.flatMap((condition, i) => validate_condition(condition, `${where}[${i}]`));
}
function validate_condition(condition: unknown, where: string): Problems {
if (!is_object(condition) || typeof condition.condition !== "string") {
return [`${where} must be { "condition": ... }`];
}
const name = condition.condition;
switch (name) {
case "random_chance": {
const chance = condition.chance;
return typeof chance === "number" && chance >= 0 && chance <= 1
? []
: [`${where}.chance must be from 0 to 1`];
}
case "match_tool": {
const problems: Problems = [];
const items = condition.items;
if (items !== undefined && !(Array.isArray(items) && items.every((i) => typeof i === "string"))) {
problems.push(`${where}.items must be a list of item ids and #tags`);
}
if (condition.tool !== undefined && typeof condition.tool !== "string") {
problems.push(`${where}.tool must be a tool type, like "axe"`);
}
if (condition.min_tier !== undefined && !Number.isInteger(condition.min_tier)) {
problems.push(`${where}.min_tier must be a whole number`);
}
return problems;
}
case "block_state": {
const states = condition.states;
const ok = is_object(states) && Object.values(states).every((match) =>
Number.isInteger(match) ||
(is_object(match) && (match.min === undefined || Number.isInteger(match.min)) &&
(match.max === undefined || Number.isInteger(match.max)))
);
return ok ? [] : [`${where}.states must map states to a number or { min, max }, like { "age": 7 }`];
}
case "killed_by_player":
return [];
case "inverted":
return validate_condition(condition.term, `${where}.term`);
case "any_of":
case "all_of":
return Array.isArray(condition.terms)
? condition.terms.flatMap((term, i) => validate_condition(term, `${where}.terms[${i}]`))
: [`${where}.terms must be a list of conditions`];
}
return name.includes(":") ? [] : [
`${where}: ${name} isn't a loot condition. the engine's are ${LOOT_CONDITIONS.join(", ")}, a mod's has its id`,
];
}
function validate_functions(list: unknown, where: string): Problems {
if (list === undefined) return [];
if (!Array.isArray(list)) return [`${where} must be a list`];
return list.flatMap((fn, i) => {
const at = `${where}[${i}]`;
if (!is_object(fn) || typeof fn.function !== "string") return [`${at} must be { "function": ... }`];
const problems = validate_conditions(fn.conditions, `${at}.conditions`);
switch (fn.function) {
case "set_count":
problems.push(...validate_number(fn.count, `${at}.count`));
if (fn.add !== undefined && typeof fn.add !== "boolean") {
problems.push(`${at}.add must be true or false`);
}
break;
case "limit_count":
for (const key of ["min", "max"]) {
if (fn[key] !== undefined && !Number.isInteger(fn[key])) {
problems.push(`${at}.${key} must be a whole number`);
}
}
break;
case "set_data":
if (fn.data === undefined) problems.push(`${at}.data is needed`);
break;
default:
if (!fn.function.includes(":")) {
problems.push(
`${at}: ${fn.function} isn't a loot function. the engine's are ${
LOOT_FUNCTIONS.join(", ")
}, a mod's has its id`,
);
}
}
return problems;
});
}
// what a table refers to, for check-mods: items, item #tags, other tables, and mods' conditions and functions
export function loot_references(table: LootTableJson) {
const refs = { items: [] as string[], tags: [] as string[], tables: [] as string[], custom: [] as string[] };
const conditions = (list: LootCondition[] | undefined) => {
for (const condition of list ?? []) {
if (condition.condition.includes(":")) refs.custom.push(condition.condition);
if (condition.condition === "match_tool") {
for (const id of (condition.items as string[] | undefined) ?? []) {
(id.startsWith("#") ? refs.tags : refs.items).push(id);
}
}
if (condition.term) conditions([condition.term as LootCondition]);
if (condition.terms) conditions(condition.terms as LootCondition[]);
}
};
const functions = (list: LootFunction[] | undefined) => {
for (const fn of list ?? []) {
if (fn.function.includes(":")) refs.custom.push(fn.function);
conditions(fn.conditions as LootCondition[] | undefined);
}
};
conditions(table.conditions);
functions(table.functions);
for (const pool of table.pools) {
conditions(pool.conditions);
functions(pool.functions);
for (const entry of pool.entries) {
conditions(entry.conditions);
functions(entry.functions);
if ((entry.type ?? "item") === "item") refs.items.push(entry.item!);
if (entry.type === "tag") refs.tags.push(entry.tag!);
if (entry.type === "loot_table") refs.tables.push(entry.table!);
}
}
return refs;
}