Implement tags !
This commit is contained in:
+4
-1
@@ -12,6 +12,7 @@ import {
|
||||
type ManifestJson,
|
||||
type OreJson,
|
||||
type RecipeJson,
|
||||
type TagJson,
|
||||
validate_block,
|
||||
validate_entity,
|
||||
validate_entity_model,
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
validate_model,
|
||||
validate_ore,
|
||||
validate_recipe,
|
||||
validate_tag,
|
||||
} from "./mod_data.ts";
|
||||
import type { ModData } from "./mod_loader.ts";
|
||||
|
||||
@@ -53,7 +55,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 and entity model
|
||||
// data.json every block, model, item, recipe, ore, entity, entity model and tag
|
||||
// scripts/<side>.js
|
||||
// textures/<name>.png the texture <mod id>:<name>
|
||||
// credits.md
|
||||
@@ -144,6 +146,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
|
||||
validate_entity_model,
|
||||
problems,
|
||||
) as EntityModelJson[],
|
||||
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
|
||||
};
|
||||
// a mod only registers ids in its own namespace
|
||||
for (const { id } of [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models]) {
|
||||
|
||||
@@ -135,10 +135,11 @@ export interface BlockRegistry {
|
||||
interactive?: boolean;
|
||||
// placing a block into it replaces it, like water
|
||||
replaceable?: boolean;
|
||||
// the blocks it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when the block
|
||||
// under it becomes something else. anything when not set
|
||||
// the blocks (ids or #tags) it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when
|
||||
// the block under it becomes something else. anything when not set
|
||||
place_on?: string[];
|
||||
// the blocks it can be placed into, replacing them, like rice into water. air and replaceable blocks when not set
|
||||
// the blocks (ids or #tags) it can be placed into, replacing them, like rice into water. air and replaceable blocks
|
||||
// when not set
|
||||
place_in?: string[];
|
||||
// custom components from mods and their params, the server runs them
|
||||
components?: Record<string, unknown>;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// what client scripts get, see docs/modding/gui/index.md
|
||||
import type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
|
||||
import type { Id, ItemStack, KeyCode, ModInfo, Position, TagApi } from "./shared.ts";
|
||||
|
||||
export type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
|
||||
export type { Id, ItemStack, KeyCode, ModInfo, Position, TagApi, TagRegistry } from "./shared.ts";
|
||||
|
||||
export interface ClientContext {
|
||||
mod: ModInfo;
|
||||
@@ -30,6 +30,8 @@ export interface ClientContext {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
list(type?: Id): any[];
|
||||
};
|
||||
// every mod's block, item and entity tags
|
||||
tags: TagApi;
|
||||
log(...args: unknown[]): void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// what server scripts get, see docs/modding/
|
||||
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
|
||||
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position, TagApi } from "./shared.ts";
|
||||
import type { ArgumentType, CommandNode } from "../commands.ts";
|
||||
|
||||
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
|
||||
|
||||
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
|
||||
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position, TagApi, TagRegistry } from "./shared.ts";
|
||||
|
||||
export interface ServerContext {
|
||||
mod: ModInfo;
|
||||
@@ -17,6 +17,7 @@ export interface ServerContext {
|
||||
containers: ContainerApi;
|
||||
items: ItemApi;
|
||||
recipes: RecipeApi;
|
||||
tags: TagApi;
|
||||
ui: ServerUi;
|
||||
net: ServerNet;
|
||||
storage: ModStorage;
|
||||
|
||||
@@ -10,6 +10,23 @@ export interface ItemStack {
|
||||
data?: unknown;
|
||||
}
|
||||
|
||||
// the registries tags are for, see docs/modding/resources/tags.md
|
||||
export type TagRegistry = "blocks" | "items" | "entities";
|
||||
|
||||
// every mod's tags, the same on the server and every client. tags can be written with or without their #
|
||||
export interface TagApi {
|
||||
// whether any mod defines the tag and it loaded
|
||||
exists(registry: TagRegistry, tag: Id): boolean;
|
||||
// whether id is in the tag, like has("items", "bworld:planks", "bworld:birch_planks"). false for a tag nobody defines
|
||||
has(registry: TagRegistry, tag: Id, id: Id): boolean;
|
||||
// every id in the tag, including its tags' ids, in the order they were added. empty for a tag nobody defines
|
||||
get(registry: TagRegistry, tag: Id): Id[];
|
||||
// every tag id is in
|
||||
of(registry: TagRegistry, id: Id): Id[];
|
||||
// the items a recipe's item choice stands for, once each: an item id or "#tag", or a list of those
|
||||
expand(choice: Id | Id[]): Id[];
|
||||
}
|
||||
|
||||
export interface ModInfo {
|
||||
readonly id: string;
|
||||
readonly version: string;
|
||||
|
||||
+57
-7
@@ -2,14 +2,18 @@
|
||||
// and the server (on .bmod files) all use it
|
||||
import {
|
||||
type BlockJson,
|
||||
choice_ids,
|
||||
choice_list,
|
||||
type EntityJson,
|
||||
type EntityModelJson,
|
||||
type ItemJson,
|
||||
type OreJson,
|
||||
type RecipeJson,
|
||||
SHARED_TAG_NAMESPACE,
|
||||
type TagJson,
|
||||
type TagRegistry,
|
||||
} from "./mod_data.ts";
|
||||
import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts";
|
||||
import { resolve_tags } from "./tags.ts";
|
||||
|
||||
export interface ModReport {
|
||||
id: string;
|
||||
@@ -29,6 +33,7 @@ export interface LoadedMod {
|
||||
ores: { file: string; json: OreJson }[];
|
||||
entities: { file: string; json: EntityJson }[];
|
||||
entity_models: { file: string; json: EntityModelJson }[];
|
||||
tags: { file: string; json: TagJson }[];
|
||||
textures: string[];
|
||||
// absolute paths by texture id
|
||||
texture_files: Map<string, string>;
|
||||
@@ -68,6 +73,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
const model_owners = new Map<string, string[]>();
|
||||
const entity_owners = new Map<string, string[]>();
|
||||
const entity_model_owners = new Map<string, string[]>();
|
||||
const tag_owners = new Map<TagRegistry, 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);
|
||||
@@ -81,6 +87,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
for (const { json } of mod.models) add(model_owners, json.id, mod.id);
|
||||
for (const { json } of mod.entities) add(entity_owners, json.id, mod.id);
|
||||
for (const { json } of mod.entity_models) add(entity_model_owners, json.id, mod.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);
|
||||
}
|
||||
for (const texture of mod.textures) textures.add(texture);
|
||||
}
|
||||
|
||||
@@ -95,12 +105,24 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
if (!mod_ids.has(dep)) errors.push(`manifest.json: depends on "${dep}", which isn't installed`);
|
||||
}
|
||||
|
||||
const uses = (file: string, id: string, what: "block" | "item" | "texture" | "model" | "entity model") => {
|
||||
const namespace = id.split(":")[0];
|
||||
// the shared tag namespace belongs to no mod, so using it needs no dependency
|
||||
const check_namespace = (file: string, id: string) => {
|
||||
const tag = id.startsWith("#");
|
||||
const namespace = id.replace("#", "").split(":")[0];
|
||||
if (tag && namespace === SHARED_TAG_NAMESPACE) return;
|
||||
if (namespace !== mod.id && namespace !== "engine" && !dependencies.has(namespace)) {
|
||||
warnings.push(`${file}: uses ${id} but doesn't list "${namespace}" in dependencies`);
|
||||
}
|
||||
if (what === "model") {
|
||||
};
|
||||
|
||||
// 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") => {
|
||||
check_namespace(file, id);
|
||||
if (id.startsWith("#") && (what === "block" || what === "item")) {
|
||||
if (!tag_owners.get(what === "block" ? "blocks" : "items")?.has(id.slice(1))) {
|
||||
errors.push(`${file}: ${what} tag ${id} doesn't exist`);
|
||||
}
|
||||
} else if (what === "model") {
|
||||
if (!BUILTIN_MODELS[id] && !model_owners.has(id)) errors.push(`${file}: model ${id} doesn't exist`);
|
||||
} else if (what === "entity model") {
|
||||
if (!entity_model_owners.has(id)) errors.push(`${file}: entity model ${id} doesn't exist`);
|
||||
@@ -152,15 +174,15 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
for (const { file, json } of mod.recipes) {
|
||||
switch (json.type) {
|
||||
case "shaped":
|
||||
for (const id of Object.values(json.key).flatMap(choice_ids)) uses(file, id, "item");
|
||||
for (const id of Object.values(json.key).flatMap(choice_list)) uses(file, id, "item");
|
||||
uses(file, json.result.id, "item");
|
||||
break;
|
||||
case "furnace":
|
||||
for (const id of choice_ids(json.input)) uses(file, id, "item");
|
||||
for (const id of choice_list(json.input)) uses(file, id, "item");
|
||||
uses(file, json.output.id, "item");
|
||||
break;
|
||||
case "fuel":
|
||||
for (const id of choice_ids(json.item)) uses(file, id, "item");
|
||||
for (const id of choice_list(json.item)) uses(file, id, "item");
|
||||
break;
|
||||
case "smithing":
|
||||
uses(file, json.tool, "item");
|
||||
@@ -186,5 +208,33 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
errors.push(`${file}: entity model ${json.id} is defined more than once`);
|
||||
}
|
||||
}
|
||||
// whether what a tag holds exists is up to resolve_tags below, since entries can be optional
|
||||
for (const { file, json } of mod.tags) {
|
||||
check_namespace(file, `#${json.id}`);
|
||||
for (const entry of json.values) {
|
||||
if (typeof entry === "string" || entry.required !== false) {
|
||||
check_namespace(file, typeof entry === "string" ? entry : entry.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tags merge in load order. when there's no order, mods depending on each other in a circle is its own error
|
||||
let ordered = mods;
|
||||
try {
|
||||
ordered = load_order(mods);
|
||||
} catch {
|
||||
// checked by the caller
|
||||
}
|
||||
const owners: Record<TagRegistry, Map<string, string[]>> = {
|
||||
blocks: block_owners,
|
||||
items: item_owners,
|
||||
entities: entity_owners,
|
||||
};
|
||||
const { problems } = resolve_tags(
|
||||
ordered.flatMap((mod) => mod.tags.map(({ file, json }) => ({ mod: mod.id, file, json }))),
|
||||
(registry, id) => (registry === "blocks" && id === "bworld:air") || owners[registry].has(id),
|
||||
);
|
||||
const by_id = new Map(mods.map((mod) => [mod.id, mod]));
|
||||
for (const { mod, file, message } of problems) by_id.get(mod)!.report.errors.push(`${file}: ${message}`);
|
||||
}
|
||||
|
||||
+80
-9
@@ -11,11 +11,18 @@ import {
|
||||
type ToolProperties,
|
||||
} from "./everything_registry.ts";
|
||||
import { type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts";
|
||||
import { expand_items, list_matches } from "./tags.ts";
|
||||
|
||||
export const FORMAT_VERSION = 1;
|
||||
export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/;
|
||||
export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/;
|
||||
export const RESERVED_NAMESPACES = ["bworld", "engine"];
|
||||
// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md
|
||||
export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/;
|
||||
// the namespace for tags every mod shares, like neoforge's and fabric's. no mod owns it
|
||||
export const SHARED_TAG_NAMESPACE = "c";
|
||||
export const TAG_REGISTRIES = ["blocks", "items", "entities"] as const;
|
||||
export type TagRegistry = typeof TAG_REGISTRIES[number];
|
||||
|
||||
type BlockTextures = BlockRegistry["textures"];
|
||||
|
||||
@@ -135,13 +142,38 @@ export interface EntityCubeJson {
|
||||
inflate?: number;
|
||||
}
|
||||
|
||||
// an item a recipe takes: its id, or a list of ids any of which fits, like every kind of planks
|
||||
// something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must
|
||||
export type TagEntryJson = string | { id: string; required?: boolean };
|
||||
|
||||
// a tag file, tags/<registry>/<namespace>/<path>.json, with the registry and id its path gives it. like neoforge's,
|
||||
// every mod's file for the same tag is merged, in load order
|
||||
export interface TagJson {
|
||||
registry: TagRegistry;
|
||||
id: string;
|
||||
values: TagEntryJson[];
|
||||
// drops what mods before this one put in the tag
|
||||
replace?: boolean;
|
||||
// takes these out again, if they're in it
|
||||
remove?: TagEntryJson[];
|
||||
}
|
||||
|
||||
// an item a recipe takes: its id, a "#tag" of items, or a list of those any of which fits, like every kind of planks
|
||||
export type ItemChoice = string | string[];
|
||||
|
||||
export function choice_ids(choice: ItemChoice): string[] {
|
||||
// the ids and #tags a choice lists, without looking inside the tags
|
||||
export function choice_list(choice: ItemChoice): string[] {
|
||||
return typeof choice === "string" ? [choice] : choice;
|
||||
}
|
||||
|
||||
// every item that fits a choice, with its tags' items, once each. the tags must be loaded
|
||||
export function choice_ids(choice: ItemChoice): string[] {
|
||||
return expand_items(choice_list(choice));
|
||||
}
|
||||
|
||||
export function choice_matches(choice: ItemChoice, id: string): boolean {
|
||||
return list_matches("items", choice_list(choice), id);
|
||||
}
|
||||
|
||||
export type RecipeJson =
|
||||
| {
|
||||
type: "shaped";
|
||||
@@ -285,7 +317,7 @@ export function grid_recipe_to_json(recipe: GridRecipe): RecipeJson {
|
||||
const letters = new Map<string, string>();
|
||||
for (const choice of recipe.pattern) {
|
||||
if (choice === undefined || letters.has(JSON.stringify(choice))) continue;
|
||||
const letter = pick_letter(choice_ids(choice)[0], new Set(letters.values()));
|
||||
const letter = pick_letter(choice_list(choice)[0].replace("#", ""), new Set(letters.values()));
|
||||
letters.set(JSON.stringify(choice), letter);
|
||||
key[letter] = choice;
|
||||
}
|
||||
@@ -318,7 +350,7 @@ export function grid_recipe_from_json(json: Extract<RecipeJson, { type: "shaped"
|
||||
|
||||
// a readable letter for an item in a pattern: its first letter if free, like P for planks
|
||||
function pick_letter(id: string, taken: Set<string>) {
|
||||
const name = id.split(":")[1].toUpperCase();
|
||||
const name = id.split(":")[1].split("/").at(-1)!.toUpperCase();
|
||||
for (const letter of [...name, ..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"]) {
|
||||
if (/[A-Z]/.test(letter) && !taken.has(letter)) {
|
||||
return letter;
|
||||
@@ -458,9 +490,9 @@ export function validate_block(json: unknown): Problems {
|
||||
const list = json[key];
|
||||
if (list === undefined) continue;
|
||||
if (!Array.isArray(list) || list.length === 0) {
|
||||
problems.push(`${key} must be a list of block ids`);
|
||||
problems.push(`${key} must be a list of block ids or #tags`);
|
||||
} else {
|
||||
for (const id of list) problems.push(...validate_id(id, key));
|
||||
for (const id of list) problems.push(...validate_id_or_tag(id, key));
|
||||
}
|
||||
}
|
||||
if (json.states !== undefined) {
|
||||
@@ -775,11 +807,50 @@ function validate_vec3(value: unknown, field: string): Problems {
|
||||
: [`${field} must be [x, y, z]`];
|
||||
}
|
||||
|
||||
// an item id, or a list of them any of which fits
|
||||
// an item id or #tag, or a list of them any of which fits
|
||||
function validate_choice(value: unknown, field: string): Problems {
|
||||
if (!Array.isArray(value)) return validate_id(value, field);
|
||||
if (!Array.isArray(value)) return validate_id_or_tag(value, field);
|
||||
if (value.length === 0) return [`${field} must list at least one item`];
|
||||
return value.flatMap((id) => validate_id(id, field));
|
||||
return value.flatMap((id) => validate_id_or_tag(id, field));
|
||||
}
|
||||
|
||||
function validate_id_or_tag(value: unknown, field: string): Problems {
|
||||
if (typeof value === "string" && value.startsWith("#")) {
|
||||
return TAG_ID_PATTERN.test(value.slice(1)) ? [] : [`${field} must be a tag like "#my_mod:things"`];
|
||||
}
|
||||
return validate_id(value, field);
|
||||
}
|
||||
|
||||
// a tag file's contents, with the registry and id its path gives it
|
||||
export function validate_tag(json: unknown): Problems {
|
||||
if (!is_object(json)) return ["tag must be an object"];
|
||||
const problems: Problems = [];
|
||||
if (!TAG_REGISTRIES.includes(json.registry as TagRegistry)) {
|
||||
problems.push(`registry must be one of ${TAG_REGISTRIES.join(", ")}`);
|
||||
}
|
||||
if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) {
|
||||
problems.push('id must be a tag id like "my_mod:things" or "c:ingots/iron"');
|
||||
}
|
||||
if (json.replace !== undefined && typeof json.replace !== "boolean") problems.push("replace must be true or false");
|
||||
for (const key of ["values", "remove"]) {
|
||||
const list = json[key];
|
||||
if (list === undefined && key === "remove") continue;
|
||||
if (!Array.isArray(list)) {
|
||||
problems.push(`${key} must be a list of ids and #tags`);
|
||||
continue;
|
||||
}
|
||||
for (const entry of list) {
|
||||
if (is_object(entry)) {
|
||||
problems.push(...validate_id_or_tag(entry.id, `${key}[].id`));
|
||||
if (entry.required !== undefined && typeof entry.required !== "boolean") {
|
||||
problems.push(`${key}[].required must be true or false`);
|
||||
}
|
||||
} else {
|
||||
problems.push(...validate_id_or_tag(entry, key));
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// optional text players see
|
||||
|
||||
+27
-5
@@ -14,7 +14,10 @@ import {
|
||||
ModRecipeJson,
|
||||
OreJson,
|
||||
RecipeJson,
|
||||
TagJson,
|
||||
TagRegistry,
|
||||
} from "./mod_data.ts";
|
||||
import { resolve_tags, Tags } from "./tags.ts";
|
||||
import { register_block_item } from "./utils.ts";
|
||||
import type { ModelJson } from "./block_models.ts";
|
||||
|
||||
@@ -28,6 +31,8 @@ export interface ModData {
|
||||
ores: OreJson[];
|
||||
entities: EntityJson[];
|
||||
entity_models: EntityModelJson[];
|
||||
// tag files, see common/tags.ts
|
||||
tags: TagJson[];
|
||||
}
|
||||
|
||||
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
|
||||
@@ -61,14 +66,17 @@ export class ModLoadError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// registers every mod's blocks, items, entities and recipes, in the order given (dependencies first)
|
||||
// whether a block, item or entity is registered, for tags. air isn't a registered block, but tags can hold it
|
||||
export function is_registered(registry: TagRegistry, id: string): boolean {
|
||||
return (registry === "blocks" && id === "bworld:air") || EverythingRegistry.get(registry, id) !== undefined;
|
||||
}
|
||||
|
||||
// registers every mod's blocks, items, entities, tags and recipes, in the order given (dependencies first). tags load
|
||||
// once every mod's content has, since a tag can hold anything, and recipes after them, since they can use tags
|
||||
export function register_mod_data(mods: { id: string; data: ModData }[]): RecipeBook {
|
||||
const recipes = new RecipeBook();
|
||||
|
||||
for (const { id, data } of mods) {
|
||||
const fail = (message: string): never => {
|
||||
throw new ModLoadError(id, message);
|
||||
};
|
||||
try {
|
||||
for (const model of data.models) {
|
||||
EverythingRegistry.register<ModelJson>("models", model.id, model);
|
||||
@@ -90,9 +98,23 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
|
||||
EverythingRegistry.register<EntityJson>("entities", json.id, json);
|
||||
}
|
||||
} catch (e) {
|
||||
fail((e as Error).message);
|
||||
throw new ModLoadError(id, (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
const { tags, problems } = resolve_tags(
|
||||
mods.flatMap(({ id, data }) =>
|
||||
data.tags.map((json) => ({ mod: id, file: `tags/${json.registry}/${json.id}`, json }))
|
||||
),
|
||||
is_registered,
|
||||
);
|
||||
if (problems.length > 0) throw new ModLoadError(problems[0].mod, `${problems[0].file}: ${problems[0].message}`);
|
||||
Tags.load(tags);
|
||||
|
||||
for (const { id, data } of mods) {
|
||||
const fail = (message: string): never => {
|
||||
throw new ModLoadError(id, message);
|
||||
};
|
||||
for (const recipe of data.recipes) {
|
||||
recipes.all.push(recipe);
|
||||
if (is_mod_recipe(recipe)) {
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
// tags: named lists of blocks, items or entities that mods add to, like neoforge's. see docs/modding/resources/tags.md.
|
||||
// resolve_tags works them out from every mod's tag files, the same way on the server, clients and in check-mods
|
||||
import type { TagEntryJson, TagJson, TagRegistry } from "./mod_data.ts";
|
||||
import type { TagApi } from "./mod_api/shared.ts";
|
||||
|
||||
export interface TagSource {
|
||||
mod: string;
|
||||
// where the tag came from, for problems
|
||||
file: string;
|
||||
json: TagJson;
|
||||
}
|
||||
|
||||
export interface TagProblem {
|
||||
mod: string;
|
||||
file: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// ids by tag id, by registry. each list in the order its ids were added
|
||||
export type ResolvedTags = Map<TagRegistry, Map<string, string[]>>;
|
||||
|
||||
interface Entry {
|
||||
id: string;
|
||||
tag: boolean;
|
||||
required: boolean;
|
||||
remove: boolean;
|
||||
source: TagSource;
|
||||
}
|
||||
|
||||
function parse_entry(json: TagEntryJson, remove: boolean, source: TagSource): Entry {
|
||||
const raw = typeof json === "string" ? json : json.id;
|
||||
const tag = raw.startsWith("#");
|
||||
// like neoforge, what's removed never has to exist
|
||||
const required = !remove && (typeof json === "string" || json.required !== false);
|
||||
return { id: tag ? raw.slice(1) : raw, tag, required, remove, source };
|
||||
}
|
||||
|
||||
// merges the tag files, sources in load order, and resolves the tags inside tags. like neoforge, a later file with
|
||||
// replace drops the entries before it, and values and removes apply in order, so a later mod can add back what an
|
||||
// earlier one removed. a tag with a required entry that doesn't exist, or that contains itself, doesn't load and is a
|
||||
// problem. exists says whether a block, item or entity is registered
|
||||
export function resolve_tags(
|
||||
sources: TagSource[],
|
||||
exists: (registry: TagRegistry, id: string) => boolean,
|
||||
): { tags: ResolvedTags; problems: TagProblem[] } {
|
||||
const entries = new Map<TagRegistry, Map<string, Entry[]>>();
|
||||
for (const source of sources) {
|
||||
const { registry, id, values, replace, remove } = source.json;
|
||||
if (!entries.has(registry)) entries.set(registry, new Map());
|
||||
const by_tag = entries.get(registry)!;
|
||||
const list = replace ? [] : by_tag.get(id) ?? [];
|
||||
list.push(...values.map((json) => parse_entry(json, false, source)));
|
||||
list.push(...(remove ?? []).map((json) => parse_entry(json, true, source)));
|
||||
by_tag.set(id, list);
|
||||
}
|
||||
|
||||
const problems: TagProblem[] = [];
|
||||
const problem = (entry: Entry, message: string) =>
|
||||
problems.push({ mod: entry.source.mod, file: entry.source.file, message });
|
||||
|
||||
const tags: ResolvedTags = new Map();
|
||||
for (const [registry, by_tag] of entries) {
|
||||
// undefined while resolving, null once it failed
|
||||
const resolved = new Map<string, Set<string> | null | undefined>();
|
||||
|
||||
const resolve = (id: string, path: string[]): Set<string> | null => {
|
||||
const done = resolved.get(id);
|
||||
if (done !== undefined) return done;
|
||||
resolved.set(id, undefined);
|
||||
const ids = new Set<string>();
|
||||
let failed = false;
|
||||
for (const entry of by_tag.get(id)!) {
|
||||
const apply = (member: string) => entry.remove ? ids.delete(member) : ids.add(member);
|
||||
if (!entry.tag) {
|
||||
if (exists(registry, entry.id)) apply(entry.id);
|
||||
else if (entry.required) {
|
||||
problem(entry, `#${id} needs ${entry.id}, which doesn't exist`);
|
||||
failed = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!by_tag.has(entry.id)) {
|
||||
if (entry.required) {
|
||||
problem(entry, `#${id} needs #${entry.id}, which no mod defines`);
|
||||
failed = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (resolved.has(entry.id) && resolved.get(entry.id) === undefined) {
|
||||
const start = path.indexOf(entry.id);
|
||||
const circle = [...(start === -1 ? [] : path.slice(start)), id, entry.id].map((t) => `#${t}`);
|
||||
problem(entry, `tags contain each other in a circle: ${circle.join(" -> ")}`);
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
const inner = resolve(entry.id, [...path, id]);
|
||||
// what went wrong inside is its own problem
|
||||
if (inner === null) {
|
||||
if (!entry.remove) failed = true;
|
||||
continue;
|
||||
}
|
||||
for (const member of inner) apply(member);
|
||||
}
|
||||
const result = failed ? null : ids;
|
||||
resolved.set(id, result);
|
||||
return result;
|
||||
};
|
||||
|
||||
const out = new Map<string, string[]>();
|
||||
for (const id of by_tag.keys()) {
|
||||
const ids = resolve(id, []);
|
||||
if (ids) out.set(id, [...ids]);
|
||||
}
|
||||
tags.set(registry, out);
|
||||
}
|
||||
return { tags, problems };
|
||||
}
|
||||
|
||||
// the loaded mods' tags, set by register_mod_data in common/mod_loader.ts
|
||||
export class Tags {
|
||||
static #tags: ResolvedTags = new Map();
|
||||
static #sets = new Map<TagRegistry, Map<string, Set<string>>>();
|
||||
// tags by member, made the first time something asks
|
||||
static #of: Map<TagRegistry, Map<string, string[]>> | undefined;
|
||||
|
||||
static load(tags: ResolvedTags) {
|
||||
this.#tags = tags;
|
||||
this.#sets = new Map(
|
||||
[...tags].map((
|
||||
[registry, by_tag],
|
||||
) => [registry, new Map([...by_tag].map(([id, ids]) => [id, new Set(ids)]))]),
|
||||
);
|
||||
this.#of = undefined;
|
||||
}
|
||||
|
||||
// whether a tag loaded. with or without its #
|
||||
static exists(registry: TagRegistry, tag: string): boolean {
|
||||
return this.#tags.get(registry)?.has(strip(tag)) ?? false;
|
||||
}
|
||||
|
||||
// false when the tag doesn't exist
|
||||
static has(registry: TagRegistry, tag: string, id: string): boolean {
|
||||
return this.#sets.get(registry)?.get(strip(tag))?.has(id) ?? false;
|
||||
}
|
||||
|
||||
// empty when the tag doesn't exist
|
||||
static get(registry: TagRegistry, tag: string): string[] {
|
||||
return this.#tags.get(registry)?.get(strip(tag)) ?? [];
|
||||
}
|
||||
|
||||
// every tag id is in, in the order the tags were first defined
|
||||
static of(registry: TagRegistry, id: string): string[] {
|
||||
if (!this.#of) {
|
||||
this.#of = new Map();
|
||||
for (const [reg, by_tag] of this.#tags) {
|
||||
const by_member = new Map<string, string[]>();
|
||||
for (const [tag, ids] of by_tag) {
|
||||
for (const member of ids) by_member.set(member, [...(by_member.get(member) ?? []), tag]);
|
||||
}
|
||||
this.#of.set(reg, by_member);
|
||||
}
|
||||
}
|
||||
return this.#of.get(registry)?.get(id) ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
function strip(tag: string) {
|
||||
return tag.startsWith("#") ? tag.slice(1) : tag;
|
||||
}
|
||||
|
||||
// whether id is one of a list of ids and #tags, like a recipe's choice or a block's place_on
|
||||
export function list_matches(registry: TagRegistry, list: readonly string[], id: string): boolean {
|
||||
return list.some((entry) => entry.startsWith("#") ? Tags.has(registry, entry, id) : entry === id);
|
||||
}
|
||||
|
||||
// every item a list of item ids and #tags stands for, once each
|
||||
export function expand_items(list: readonly string[]): string[] {
|
||||
return [...new Set(list.flatMap((id) => id.startsWith("#") ? Tags.get("items", id) : [id]))];
|
||||
}
|
||||
|
||||
// ctx.tags for server and client scripts. everything it returns is a copy
|
||||
export function tag_api(): TagApi {
|
||||
const registry = (name: string): TagRegistry => {
|
||||
if (name !== "blocks" && name !== "items" && name !== "entities") {
|
||||
throw new Error(`tags are for "blocks", "items" or "entities", not ${JSON.stringify(name)}`);
|
||||
}
|
||||
return name;
|
||||
};
|
||||
return {
|
||||
exists: (reg, tag) => Tags.exists(registry(reg), tag),
|
||||
has: (reg, tag, id) => Tags.has(registry(reg), tag, id),
|
||||
get: (reg, tag) => [...Tags.get(registry(reg), tag)],
|
||||
of: (reg, id) => [...Tags.of(registry(reg), id)],
|
||||
expand: (choice) => expand_items([choice].flat()),
|
||||
};
|
||||
}
|
||||
+3
-2
@@ -2,6 +2,7 @@ import { ID_MASK, STATE_SHIFT } from "./constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
|
||||
import { block_item_texture, cube_face_texture } from "./block_models.ts";
|
||||
import type { ItemStack } from "./inventory.ts";
|
||||
import { list_matches } from "./tags.ts";
|
||||
|
||||
export function point_inside_rec(
|
||||
point_x: number,
|
||||
@@ -134,7 +135,7 @@ function compile_block_states(block_info: BlockRegistry) {
|
||||
|
||||
// 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 || block.place_on.includes(below);
|
||||
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),
|
||||
@@ -158,7 +159,7 @@ export function can_place(
|
||||
if (!block) return false;
|
||||
const into = current?.id ?? "bworld:air";
|
||||
const replaceable = !current || current.replaceable === true;
|
||||
const in_ok = block.place_in ? block.place_in.includes(into) : replaceable;
|
||||
const in_ok = block.place_in ? list_matches("blocks", block.place_in, into) : replaceable;
|
||||
return in_ok && can_stand_on(block, below);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user