Files
bworld/tools/importer/resources.ts
T
2026-10-15 11:45:12 -03:00

346 lines
14 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// where things are in a java mod's resources, and what they're called in bworld. a resource location like
// "create:block/cogwheel" (or "block/stone", which is minecraft's) becomes the id "create:block_cogwheel": bworld ids
// have no folders, so the path's folders are joined with _, the same way check_mods names textures in subfolders
import { ID_PATTERN, type TagRegistry } from "$/common/mod_data.ts";
import { registered_ids } from "$/common/mod_check.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { dirname, relative, resolve, SEPARATOR } from "@std/path";
export interface Location {
namespace: string;
path: string;
}
// bare is the namespace of a location written without one: minecraft's, in a mod's resources
export function parse_location(value: string, bare = "minecraft"): Location {
const colon = value.indexOf(":");
return colon < 0
? { namespace: bare, path: value }
: { namespace: value.slice(0, colon), path: value.slice(colon + 1) };
}
export function location_string({ namespace, path }: Location): string {
return `${namespace}:${path}`;
}
// rewrites applied to a location before it becomes an id, longest match first: { "minecraft:block/": "bworld:" } turns
// minecraft's block textures into the base game's, which are named the same. a key without a trailing / only matches
// that location exactly
export type Remap = Record<string, string>;
export interface Remaps {
textures: Remap;
models: Remap;
// blocks, items, entities and biomes, where tags and recipes name them
ids: Remap;
tags: Remap;
// patterns (regular expressions) for locations to leave out of every kind, like a mod's blocks for content bworld
// doesn't have: "crimson" leaves out create:crimson_window, its models and its textures
skip?: string[];
}
export const DEFAULT_REMAPS: Remaps = {
textures: { "minecraft:block/": "bworld:", "minecraft:item/": "bworld:" },
models: template_remaps(),
// the base game's blocks and items are named like minecraft's, and its tags too. forge's shared tags were renamed
// c, which is what bworld calls them
ids: { "minecraft:": "bworld:" },
tags: { "minecraft:": "bworld:", "forge:": "c:" },
};
// minecraft's template models (cube_all, stairs, walls, panes, ...) are the base game's in models/templates, which are
// named after their files
function template_remaps(): Remap {
const dir = new URL("../../mods/bworld/models/templates/", import.meta.url);
return Object.fromEntries(
[...Deno.readDirSync(dir)].filter((entry) => entry.name.endsWith(".json")).map((entry) => {
const name = entry.name.slice(0, -".json".length);
return [`minecraft:block/${name}`, `bworld:${name}`];
}),
);
}
export function remap_location(location: string, remap: Remap = {}, bare = "minecraft"): Location {
const full = location_string(parse_location(location, bare));
for (const from of Object.keys(remap).sort((a, b) => b.length - a.length)) {
const prefix = from.endsWith("/") || from.endsWith(":");
if (prefix ? full.startsWith(from) : full === from) {
return parse_location(remap[from] + full.slice(from.length));
}
}
return parse_location(full);
}
export function to_id(location: string, remap: Remap = {}, bare = "minecraft"): string {
const { namespace, path } = remap_location(location, remap, bare);
return `${namespace}:${path.replaceAll("/", "_")}`;
}
export function is_valid_id(id: string): boolean {
return ID_PATTERN.test(id);
}
// what a mod's resources are in: assets/ for what clients draw, data/ for tags, recipes and the rest
const TOPS = ["assets", "data"];
// a folder of one kind of resource (models, textures, ...) for one namespace: assets/<namespace>/<kind>, or
// data/<namespace>/<kind>. some kinds' folder was renamed between versions, like recipes to recipe, so a kind can be
// several names
export interface ResourceRoot {
namespace: string;
dir: string;
// not in a mod's assets/ but a loose folder, like blockbench's exports. what it names without a namespace is its
// own, not minecraft's: a texture "gear" next to a model is that model's texture
loose?: boolean;
}
// the roots of a kind inside a folder: every assets/<namespace>/<kind> under it (only namespace's, when it's given), or
// the folder itself when it's one or is inside one. a folder that's none of those is a root of the given namespace
export function find_roots(input: string, kind: string | string[], namespace?: string): ResourceRoot[] {
const dir = resolve(input);
const enclosing = enclosing_root(dir, kind);
if (enclosing) return [enclosing];
const roots: ResourceRoot[] = [];
for (const top of TOPS.flatMap((name) => find_dirs(dir, name))) {
for (const entry of read_dir(top)) {
for (const name of [kind].flat()) {
if (entry.isDirectory && is_dir(`${top}/${entry.name}/${name}`)) {
roots.push({ namespace: entry.name, dir: `${top}/${entry.name}/${name}` });
}
}
}
}
if (roots.length === 0) return namespace ? [{ namespace, dir, loose: true }] : [];
return namespace ? roots.filter((root) => root.namespace === namespace) : roots;
}
// a file to convert and the root it's in
export interface InputFile {
root: ResourceRoot;
file: string;
}
// what to convert: one file, or every file with the extension in a folder's roots of a kind. a file outside any
// assets/ folder is the namespace's, or the mod's that output is in
export function input_files(
input: string,
kind: string | string[],
extension: string,
namespace?: string,
output?: string,
): InputFile[] {
if (is_file(input)) {
const enclosing = enclosing_root(input, kind);
if (enclosing) return [{ root: enclosing, file: resolve(input) }];
const loose = namespace ?? (output && mod_namespace(output));
if (!loose) throw new Error(`can't tell ${input}'s namespace: pass --namespace, or an --output in a mod`);
return [{ root: { namespace: loose, dir: dirname(resolve(input)), loose: true }, file: resolve(input) }];
}
const roots = find_roots(input, kind, namespace);
if (roots.length === 0) {
const name = [kind].flat()[0];
throw new Error(`no ${name} in ${input}: pass --namespace when it isn't inside assets/<namespace>/${name}`);
}
const full = resolve(input);
return roots.flatMap((root) => {
const inside = full === root.dir || full.startsWith(root.dir + SEPARATOR);
return walk_files(inside ? full : root.dir, extension).map((file) => ({ root, file }));
});
}
// the assets/<namespace>/<kind> folder a path is in, if it's in one
export function enclosing_root(path: string, kind: string | string[]): ResourceRoot | undefined {
const parts = resolve(path).split(SEPARATOR);
for (let i = parts.length - 1; i >= 2; i--) {
if ([kind].flat().includes(parts[i]) && TOPS.includes(parts[i - 2])) {
return { namespace: parts[i - 1], dir: parts.slice(0, i + 1).join(SEPARATOR) };
}
}
return undefined;
}
// a file's location inside its root: assets/create/models/block/cogwheel.json is create:block/cogwheel
export function location_of(root: ResourceRoot, file: string, extension: string): Location {
const path = relative(root.dir, resolve(file)).split(SEPARATOR).join("/");
return { namespace: root.namespace, path: path.slice(0, -extension.length) };
}
// every file with the extension under a folder, as full paths
export function walk_files(dir: string, extension: string): string[] {
const files: string[] = [];
for (const entry of read_dir(dir)) {
const path = `${dir}/${entry.name}`;
if (entry.isDirectory) files.push(...walk_files(path, extension));
else if (entry.name.endsWith(extension)) files.push(path);
}
return files;
}
function find_dirs(dir: string, name: string): string[] {
const found: string[] = [];
for (const entry of read_dir(dir)) {
if (!entry.isDirectory) continue;
const path = `${dir}/${entry.name}`;
if (entry.name === name) found.push(path);
else found.push(...find_dirs(path, name));
}
return found;
}
function read_dir(dir: string): Deno.DirEntry[] {
try {
return [...Deno.readDirSync(dir)].sort((a, b) => a.name.localeCompare(b.name));
} catch (e) {
if (e instanceof Deno.errors.NotFound || e instanceof Deno.errors.NotADirectory) return [];
throw e;
}
}
// the id of the mod a path is in, from the manifest.json of the nearest folder up that has one
export function mod_namespace(path: string): string | undefined {
return mod_of(path)?.id;
}
function mod_of(path: string): { id: string; dir: string } | undefined {
for (let dir = dirname(resolve(path)); dir !== dirname(dir); dir = dirname(dir)) {
if (!is_file(`${dir}/manifest.json`)) continue;
const id = JSON.parse(Deno.readTextFileSync(`${dir}/manifest.json`)).id;
return typeof id === "string" ? { id, dir } : undefined;
}
return undefined;
}
// what the mods next to the one output is in have, by registry: their blocks, items, entities and biomes, and the
// tags their files define. undefined when output isn't in a mod
export interface Known {
ids: Record<TagRegistry, Set<string>>;
tags: Record<TagRegistry, Set<string>>;
}
export function known_in(output: string): Known | undefined {
const mod = mod_of(`${output}/x`);
if (!mod) return undefined;
const mods = load_and_check(dirname(mod.dir));
const tags: Known["tags"] = { blocks: new Set(), items: new Set(), entities: new Set(), biomes: new Set() };
for (const { json } of mods.flatMap((mod) => mod.tags)) tags[json.registry].add(json.id);
return { ids: registered_ids(mods), tags };
}
export function is_file(path: string): boolean {
try {
return Deno.statSync(path).isFile;
} catch {
return false;
}
}
function is_dir(path: string): boolean {
try {
return Deno.statSync(path).isDirectory;
} catch {
return false;
}
}
export interface ImportOptions {
// the file (for one input file) or folder to write
output?: string;
// the namespace of an input outside assets/<namespace>/, or the only one to take from a folder with several
namespace?: string;
// more folders to look things up in, like parent models from another mod
parents?: string[];
remaps?: Remaps;
// fields blocks get by id, over the placeholders, like their components or how long they take to mine. java sets
// those in code, so a mod's import keeps them in a table, like mods/create/import/blocks.json
blocks?: Record<string, Record<string, unknown>>;
}
// one file an import makes: text to write, or a file to copy
export interface Written {
location: string;
id: string;
// where it goes, undefined to print it
file?: string;
text?: string;
copy?: string;
}
export interface ImportReport {
written: Written[];
skipped: { location: string; reason: string }[];
errors: { location: string; problems: string[] }[];
warnings: { location: string; warning: string }[];
}
// whether the remaps leave a location out, which is reported as skipped
export function skips(location: string, remaps: Remaps, report: ImportReport): boolean {
const pattern = skip_pattern(location, remaps);
if (pattern !== undefined) report.skipped.push({ location, reason: `the remaps skip "${pattern}"` });
return pattern !== undefined;
}
// the skip pattern a location matches, if any
export function skip_pattern(location: string, remaps: Remaps): string | undefined {
return remaps.skip?.find((pattern) => new RegExp(pattern).test(location));
}
export function empty_report(): ImportReport {
return { written: [], skipped: [], errors: [], warnings: [] };
}
// two locations that would become the same id are an error, since one would overwrite the other. claim returns false
// for the second, after reporting it
export function id_claims(report: ImportReport) {
const owners = new Map<string, string>();
return (id: string, location: string) => {
const owner = owners.get(id);
if (owner === undefined) {
owners.set(id, location);
return true;
}
report.errors.push({
location,
problems: [`its id ${id} is the same as ${owner}'s, so give one of them another with --remap`],
});
return false;
};
}
export function write_report(report: ImportReport) {
for (const { file, text, copy } of report.written) {
if (file === undefined) continue;
Deno.mkdirSync(dirname(file), { recursive: true });
if (copy !== undefined) Deno.copyFileSync(copy, file);
else Deno.writeTextFileSync(file, text ?? "");
}
}
// how wide deno fmt lets a line be, with a tab as 4 columns, see deno.json
const LINE_WIDTH = 120;
const TAB_WIDTH = 4;
// json in the style of the repo's data files, the way deno fmt leaves it: tabs, and short lists and objects of plain
// values on one line when the whole line fits. indent is the line it starts on, after prefix (like a key) on that line
export function format_json(value: unknown, indent = "", prefix = 0): string {
if (value === null || typeof value !== "object") return JSON.stringify(value);
const entries = Array.isArray(value)
? value.map((v) => format_json(v, indent + "\t"))
: Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => {
const key = `${JSON.stringify(k)}: `;
return key + format_json(v, indent + "\t", key.length);
});
const [open, close] = Array.isArray(value) ? ["[", "]"] : ["{", "}"];
if (entries.length === 0) return open + close;
const flat = Object.values(value).every((v) =>
v === null || typeof v !== "object" || (Array.isArray(v) && v.every((x) => x === null || typeof x !== "object"))
);
const one_line = Array.isArray(value) ? `[${entries.join(", ")}]` : `{ ${entries.join(", ")} }`;
// and a comma after it
const width = indent.length * TAB_WIDTH + prefix + one_line.length + 1;
if (flat && !one_line.includes("\n") && width <= LINE_WIDTH) return one_line;
return `${open}\n${entries.map((e) => indent + "\t" + e).join(",\n")}\n${indent}${close}`;
}