Loot tables
This commit is contained in:
+4
-2
@@ -28,6 +28,7 @@ import {
|
||||
validate_tag,
|
||||
} from "./mod_data.ts";
|
||||
import type { ModData } from "./mod_loader.ts";
|
||||
import { type LootTableJson, validate_loot_table } from "./loot.ts";
|
||||
import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
|
||||
import { ENGINE_GLOBAL } from "./hooks.ts";
|
||||
|
||||
@@ -63,7 +64,7 @@ export class BmodError extends Error {
|
||||
|
||||
// the zip's layout:
|
||||
// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip
|
||||
// data.json every block, model, item, recipe, ore, entity, entity model, effect and tag
|
||||
// data.json every block, model, item, recipe, ore, entity, entity model, effect, tag and loot table
|
||||
// scripts/<side>.js
|
||||
// textures/<name>.png the texture <mod id>:<name>
|
||||
// textures/<name>.json its animation, if it has one
|
||||
@@ -161,10 +162,11 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
|
||||
) as EntityModelJson[],
|
||||
effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[],
|
||||
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
|
||||
loot_tables: checked(raw_data.loot_tables, "loot_tables", validate_loot_table, problems) as LootTableJson[],
|
||||
};
|
||||
// a mod only registers ids in its own namespace
|
||||
const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models];
|
||||
for (const { id } of [...registered, ...data.effects]) {
|
||||
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!]) {
|
||||
if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
|
||||
}
|
||||
|
||||
|
||||
@@ -132,6 +132,8 @@ export interface BlockRegistry {
|
||||
// the lowest tool tier it drops for when requires_tool, like minecraft's incorrect_for_*_tool tags. 0 when not set
|
||||
tool_tier?: number;
|
||||
drop_table?: string;
|
||||
// what it drops when broken, see common/loot.ts. drop_table is one of an item instead
|
||||
loot_table?: string;
|
||||
|
||||
states?: BlockStateDefinition[];
|
||||
// a different model or textures for some states, by conditions like "age=7". the first match wins
|
||||
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
// 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 { 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;
|
||||
}
|
||||
|
||||
function is_object(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export interface ServerContext {
|
||||
blocks: BlockApi;
|
||||
recipes: RecipeApi;
|
||||
tags: TagApi;
|
||||
loot: LootApi;
|
||||
menus: MenuRegistry;
|
||||
ui: ServerUi;
|
||||
net: ServerNet;
|
||||
@@ -388,6 +389,47 @@ export interface RecipeApi {
|
||||
list(type: Id): any[];
|
||||
}
|
||||
|
||||
// loot tables, see docs/modding/resources/loot_tables.md
|
||||
|
||||
// what's happening when a table is rolled. its built in conditions read block, tool and killed_by_player, mods'
|
||||
// conditions and functions get all of it
|
||||
export interface LootContext {
|
||||
// where it happens, like the broken block or the fishing hook
|
||||
position?: Position;
|
||||
// the block being broken. its states are read from the world when not given
|
||||
block?: { id: Id; x: number; y: number; z: number; states?: Record<string, number> };
|
||||
// what it's done with, like the tool breaking the block or the fishing rod
|
||||
tool?: ItemStack;
|
||||
// who did it: broke the block, fished, killed the mob
|
||||
player?: Player;
|
||||
// the mob that died
|
||||
entity?: EntityRef;
|
||||
// a player killed it, for the "killed_by_player" condition
|
||||
killed_by_player?: boolean;
|
||||
}
|
||||
|
||||
// a condition's or function's json, with its "condition" or "function" id and whatever params it has
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type LootParams = Record<string, any>;
|
||||
|
||||
export interface LootApi {
|
||||
exists(id: Id): boolean;
|
||||
// what rolling the table gives, stacks split to fit a slot. throws for a table that doesn't exist
|
||||
roll(id: Id, context?: LootContext): ItemStack[];
|
||||
// rolls the table into the container's empty slots, at random like minecraft's chests. returns what didn't fit
|
||||
fill(container: Container, id: Id, context?: LootContext): ItemStack[];
|
||||
// a condition tables can use by its id, in the mod's namespace. only during setup
|
||||
register_condition(id: Id, condition: (params: LootParams, context: LootContext) => boolean): void;
|
||||
// a function tables can use by its id: the item changed, or undefined to take it away. only during setup
|
||||
register_function(
|
||||
id: Id,
|
||||
fn: (item: ItemStack, params: LootParams, context: LootContext) => ItemStack | undefined,
|
||||
): void;
|
||||
// changes what a table gives every time it's rolled, or every table's with "*", like neoforge's global loot
|
||||
// modifiers. return the new items, or change the list. only during setup
|
||||
modify(table: Id | "*", fn: (items: ItemStack[], context: LootContext, table: Id) => ItemStack[] | void): void;
|
||||
}
|
||||
|
||||
// forms, not built yet: menus whose screens the engine provides, see docs/modding_plan.md
|
||||
|
||||
export interface ActionForm {
|
||||
|
||||
+21
-1
@@ -18,6 +18,7 @@ import { PLAYER_PARTS } from "./everything_registry.ts";
|
||||
import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts";
|
||||
import { resolve_tags } from "./tags.ts";
|
||||
import type { TextureJson } from "./texture_animation.ts";
|
||||
import { loot_references, type LootTableJson } from "./loot.ts";
|
||||
import { BIOMES } from "./worldgen/overworld.ts";
|
||||
|
||||
export interface ModReport {
|
||||
@@ -41,6 +42,7 @@ export interface LoadedMod {
|
||||
entity_models: { file: string; json: EntityModelJson }[];
|
||||
effects: { file: string; json: EffectJson }[];
|
||||
tags: { file: string; json: TagJson }[];
|
||||
loot_tables: { file: string; json: LootTableJson }[];
|
||||
textures: string[];
|
||||
// absolute paths by texture id
|
||||
texture_files: Map<string, string>;
|
||||
@@ -87,6 +89,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
const effect_owners = new Map<string, string[]>();
|
||||
const tag_owners = new Map<TagRegistry, Set<string>>();
|
||||
const liquids = new Set<string>();
|
||||
const loot_tables = new Set<string>();
|
||||
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
|
||||
|
||||
const textures = new Set<string>(engine_textures);
|
||||
@@ -109,6 +112,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
entity_model_jsons.set(json.id, json);
|
||||
}
|
||||
for (const { json } of mod.effects) add(effect_owners, json.id, mod.id);
|
||||
for (const { json } of mod.loot_tables ?? []) loot_tables.add(json.id);
|
||||
for (const { json } of mod.tags) {
|
||||
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
|
||||
tag_owners.get(json.registry)!.add(json.id);
|
||||
@@ -138,7 +142,11 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
};
|
||||
|
||||
// block and item ids can be #tags, like in recipes and place_on
|
||||
const uses = (file: string, id: string, what: "block" | "item" | "texture" | "model" | "entity model") => {
|
||||
const uses = (
|
||||
file: string,
|
||||
id: string,
|
||||
what: "block" | "item" | "texture" | "model" | "entity model" | "loot table",
|
||||
) => {
|
||||
check_namespace(file, id);
|
||||
if (id.startsWith("#") && (what === "block" || what === "item")) {
|
||||
if (!tag_owners.get(what === "block" ? "blocks" : "items")?.has(id.slice(1))) {
|
||||
@@ -150,6 +158,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
if (!entity_model_owners.has(id)) errors.push(`${file}: entity model ${id} doesn't exist`);
|
||||
} else if (what === "texture") {
|
||||
if (!textures.has(id)) warnings.push(`${file}: texture ${id} doesn't exist, it will show as missing`);
|
||||
} else if (what === "loot table") {
|
||||
if (!loot_tables.has(id)) errors.push(`${file}: loot table ${id} doesn't exist`);
|
||||
} else if (!(what === "block" ? block_owners : item_owners).has(id)) {
|
||||
errors.push(`${file}: ${what} ${id} doesn't exist`);
|
||||
}
|
||||
@@ -167,6 +177,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
}
|
||||
}
|
||||
if (json.drops) uses(file, json.drops, "item");
|
||||
if (json.loot_table) uses(file, json.loot_table, "loot table");
|
||||
if (json.waterloggable) {
|
||||
uses(file, json.waterloggable, "block");
|
||||
if (block_owners.has(json.waterloggable) && !liquids.has(json.waterloggable)) {
|
||||
@@ -251,6 +262,15 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
}
|
||||
if (json.model !== undefined) uses(file, json.model, "entity model");
|
||||
uses(file, json.texture, "texture");
|
||||
if (json.loot_table) uses(file, json.loot_table, "loot table");
|
||||
}
|
||||
for (const { file, json } of mod.loot_tables ?? []) {
|
||||
const refs = loot_references(json);
|
||||
for (const id of refs.items) uses(file, id, "item");
|
||||
for (const id of refs.tags) uses(file, id, "item");
|
||||
for (const id of refs.tables) uses(file, id, "loot table");
|
||||
// mods' conditions and functions are registered by scripts, the server checks them when it starts
|
||||
for (const id of refs.custom) check_namespace(file, id);
|
||||
}
|
||||
for (const { file, json } of mod.effects) {
|
||||
if ((effect_owners.get(json.id)?.length ?? 0) > 1) {
|
||||
|
||||
@@ -79,6 +79,8 @@ export interface BlockJson {
|
||||
item_display?: { surface: number };
|
||||
// makes it a liquid, see LiquidProperties. range is 7 when not set
|
||||
liquid?: Partial<LiquidProperties>;
|
||||
// what it drops when broken, see common/loot.ts. drops is the shorthand for one of an item
|
||||
loot_table?: string;
|
||||
// the liquid it can hold, see BlockRegistry.waterloggable
|
||||
waterloggable?: string;
|
||||
// only placed into a source of it, see BlockRegistry.waterlogged_only
|
||||
@@ -152,6 +154,8 @@ export interface EntityJson {
|
||||
// protection from physical and from arcane damage, not used yet
|
||||
physical_shielding?: number;
|
||||
arcane_shielding?: number;
|
||||
// what it drops when it dies, see common/loot.ts
|
||||
loot_table?: string;
|
||||
}
|
||||
|
||||
// a status effect, like neoforge's MobEffect. what it does over time comes from components scripts register, see
|
||||
@@ -301,6 +305,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
|
||||
if (block.tool_tier) json.mining.tier = block.tool_tier;
|
||||
}
|
||||
if (block.drop_table !== undefined) json.drops = block.drop_table;
|
||||
if (block.loot_table !== undefined) json.loot_table = block.loot_table;
|
||||
if (!has_item) json.item = false;
|
||||
if (block.interactive) json.interactive = true;
|
||||
if (!!block.replaceable !== !!block.liquid) json.replaceable = !!block.replaceable;
|
||||
@@ -351,6 +356,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
|
||||
if (json.mining.tier) block.tool_tier = json.mining.tier;
|
||||
}
|
||||
if (json.drops !== undefined) block.drop_table = json.drops;
|
||||
if (json.loot_table !== undefined) block.loot_table = json.loot_table;
|
||||
if (json.interactive) block.interactive = true;
|
||||
if (json.replaceable ?? json.liquid) block.replaceable = true;
|
||||
if (json.place_on) block.place_on = json.place_on;
|
||||
@@ -661,6 +667,12 @@ export function validate_block(json: unknown): Problems {
|
||||
}
|
||||
}
|
||||
if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops"));
|
||||
if (json.loot_table !== undefined) {
|
||||
if (!(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table))) {
|
||||
problems.push('loot_table must be a loot table id, like "my_mod:blocks/thing"');
|
||||
}
|
||||
if (json.drops !== undefined) problems.push("drops and loot_table can't both be set, drops is one item");
|
||||
}
|
||||
if (json.item_display !== undefined) {
|
||||
const surface = is_object(json.item_display) ? json.item_display.surface : undefined;
|
||||
if (typeof surface !== "number" || surface < 0 || surface > 16) {
|
||||
@@ -1005,6 +1017,11 @@ export function validate_entity(json: unknown): Problems {
|
||||
if (json.behavior !== undefined && !["animal", "monster", "scripted"].includes(json.behavior as string)) {
|
||||
problems.push('behavior must be "animal", "monster" or "scripted"');
|
||||
}
|
||||
if (
|
||||
json.loot_table !== undefined && !(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table))
|
||||
) {
|
||||
problems.push('loot_table must be a loot table id, like "my_mod:entities/thing"');
|
||||
}
|
||||
for (const key of ["width", "height"]) {
|
||||
if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) {
|
||||
problems.push(`${key} must be a number of blocks above 0, at most 16`);
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
TagRegistry,
|
||||
} from "./mod_data.ts";
|
||||
import { resolve_tags, Tags } from "./tags.ts";
|
||||
import type { LootTableJson } from "./loot.ts";
|
||||
import { register_block_item } from "./utils.ts";
|
||||
import type { ModelJson } from "./block_models.ts";
|
||||
|
||||
@@ -40,6 +41,8 @@ export interface ModData {
|
||||
effects: EffectJson[];
|
||||
// tag files, see common/tags.ts
|
||||
tags: TagJson[];
|
||||
// see common/loot.ts. missing from mods packed before there were loot tables
|
||||
loot_tables?: LootTableJson[];
|
||||
}
|
||||
|
||||
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
|
||||
@@ -117,6 +120,9 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
|
||||
for (const json of data.effects) {
|
||||
EverythingRegistry.register<EffectJson>("effects", json.id, json);
|
||||
}
|
||||
for (const json of data.loot_tables ?? []) {
|
||||
EverythingRegistry.register<LootTableJson>("loot_tables", json.id, json);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new ModLoadError(id, (e as Error).message);
|
||||
}
|
||||
|
||||
@@ -86,6 +86,13 @@ export function get_state_value(value: number, block_info: BlockRegistry, 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;
|
||||
|
||||
Reference in New Issue
Block a user