Files
bworld/tools/importer.ts
T
2026-10-12 17:22:50 -03:00

211 lines
8.0 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// converts a minecraft java mod's resources into bworld's formats, one kind at a time:
// deno run -A tools/importer.ts model MODEL.json --output PATH
// deno run -A tools/importer.ts model path/to/resources --output mods/example/models
// a folder can be a whole mod's resources (every assets/<namespace>/models in it), one assets/<namespace>/models, or a
// folder inside one. see USAGE for the options
import { dirname, join, resolve, SEPARATOR } from "@std/path";
import { convert_model, type ModelSource } from "./importer/models.ts";
import {
DEFAULT_REMAPS,
enclosing_root,
find_roots,
format_json,
location_of,
location_string,
parse_location,
type Remaps,
type ResourceRoot,
walk_files,
} from "./importer/resources.ts";
const USAGE = `deno run -A tools/importer.ts <kind> <file or folder> [options]
kinds:
model java block models to bworld models
options:
--output PATH the file (for one model) or the folder to write. one model without it is printed
--namespace NS the namespace, when the input isn't inside assets/<namespace>/models
--parents FOLDER another folder to find parent models in, like another mod's resources. can be repeated
--remap FILE json that renames locations before they become ids, longest match first:
{ "textures": { "minecraft:block/": "bworld:" }, "models": {} }
minecraft's block and item textures become bworld's of the same name unless it says otherwise`;
export interface ImportOptions {
output?: string;
namespace?: string;
parents?: string[];
remaps?: Remaps;
}
export interface ImportReport {
written: { location: string; id: string; file?: string; text: string }[];
// models with no boxes of their own, only there for others to use as a parent
parents: string[];
skipped: { location: string; reason: string }[];
errors: { location: string; problems: string[] }[];
warnings: { location: string; warning: string }[];
}
export function import_models(input: string, options: ImportOptions = {}): ImportReport {
const remaps = options.remaps ?? DEFAULT_REMAPS;
const single = is_file(input);
const roots = single ? file_root(input, options.namespace) : find_roots(input, "models", options.namespace);
if (roots.length === 0) {
throw new Error(`no models in ${input}: pass --namespace when it isn't inside assets/<namespace>/models`);
}
if (!single && options.output === undefined) throw new Error("--output is needed to convert a folder");
// parents can be anywhere in the same roots, or in --parents, not only in what's being converted
const lookup = [...roots, ...(options.parents ?? []).flatMap((dir) => find_roots(dir, "models"))];
const cache = new Map<string, Record<string, unknown> | undefined>();
const read: ModelSource = (location) => {
if (cache.has(location)) return cache.get(location);
const { namespace, path } = parse_location(location);
let json: Record<string, unknown> | undefined;
for (const root of lookup.filter((root) => root.namespace === namespace)) {
const file = `${root.dir}/${path}.json`;
if (!is_file(file)) continue;
try {
json = JSON.parse(Deno.readTextFileSync(file));
} catch (e) {
throw new Error(`${file} isn't valid json: ${(e as Error).message}`);
}
break;
}
cache.set(location, json);
return json;
};
const files = single
? [{ root: roots[0], file: resolve(input) }]
: roots.flatMap((root) =>
walk_files(inside(input, root) ? resolve(input) : root.dir, ".json").map((file) => ({ root, file }))
);
const several_namespaces = new Set(files.map(({ root }) => root.namespace)).size > 1;
const report: ImportReport = { written: [], parents: [], skipped: [], errors: [], warnings: [] };
const locations = new Map<string, string>();
for (const { root, file } of files) {
const where = location_of(root, file, ".json");
const location = location_string(where);
const result = convert_model(location, read, remaps);
if (result.kind === "parent") report.parents.push(location);
else if (result.kind === "skipped") report.skipped.push({ location, reason: result.reason });
else if (result.kind === "error") report.errors.push({ location, problems: result.problems });
else {
const other = locations.get(result.id);
if (other) {
const problem =
`its id ${result.id} is the same as ${other}'s, so give one of them another with --remap`;
report.errors.push({ location, problems: [problem] });
continue;
}
locations.set(result.id, location);
for (const warning of result.warnings) report.warnings.push({ location, warning });
const output = single
? options.output
: join(options.output!, ...(several_namespaces ? [where.namespace] : []), `${where.path}.json`);
report.written.push({ location, id: result.id, file: output, text: format_json(result.json) + "\n" });
}
}
for (const { file, text } of report.written) {
if (file === undefined) continue;
Deno.mkdirSync(dirname(file), { recursive: true });
Deno.writeTextFileSync(file, text);
}
return report;
}
function file_root(file: string, namespace?: string): ResourceRoot[] {
const root = enclosing_root(file, "models");
if (root) return [root];
if (!namespace) throw new Error(`can't tell ${file}'s namespace: pass --namespace`);
return [{ namespace, dir: dirname(resolve(file)) }];
}
function inside(path: string, root: ResourceRoot) {
const full = resolve(path);
return full === root.dir || full.startsWith(root.dir + SEPARATOR);
}
function is_file(path: string) {
try {
return Deno.statSync(path).isFile;
} catch {
return false;
}
}
function parse_args(args: string[]) {
const positional: string[] = [];
const options: ImportOptions & { parents: string[] } = { parents: [] };
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const value = () => {
const next = args[++i];
if (next === undefined) throw new Error(`${arg} needs a value`);
return next;
};
if (arg === "--output") options.output = value();
else if (arg === "--namespace") options.namespace = value();
else if (arg === "--parents") options.parents.push(value());
else if (arg === "--remap") {
const remap = JSON.parse(Deno.readTextFileSync(value()));
options.remaps = {
textures: { ...DEFAULT_REMAPS.textures, ...remap.textures },
models: { ...DEFAULT_REMAPS.models, ...remap.models },
};
} else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
else positional.push(arg);
}
return { positional, options };
}
function print_report(report: ImportReport) {
if (report.written.length === 1 && report.written[0].file === undefined) {
console.log(report.written[0].text.trimEnd());
}
for (const { location, reason } of report.skipped) console.error(`skipped ${location}: ${reason}`);
for (const { location, problems } of report.errors) {
for (const problem of problems) console.error(`error in ${location}: ${problem}`);
}
// the same warning on many models is one line
const warnings = new Map<string, string[]>();
for (const { location, warning } of report.warnings) {
warnings.set(warning, [...(warnings.get(warning) ?? []), location]);
}
for (const [warning, locations] of warnings) {
const which = locations.length === 1 ? locations[0] : `${locations.length} models`;
console.error(`warning: ${warning} (${which})`);
}
console.error(
`${report.written.length} converted, ${report.parents.length} only parents, ${report.skipped.length} skipped, ` +
`${report.errors.length} with errors`,
);
}
if (import.meta.main) {
if (Deno.args.includes("--help") || Deno.args.includes("-h")) {
console.log(USAGE);
Deno.exit(0);
}
try {
const { positional: [kind, input], options } = parse_args(Deno.args);
if (!kind || !input) {
console.error(USAGE);
Deno.exit(2);
}
if (kind !== "model") throw new Error(`"${kind}" isn't a kind that can be imported yet, see --help`);
const report = import_models(input, options);
print_report(report);
if (report.errors.length > 0) Deno.exit(1);
} catch (e) {
console.error((e as Error).message);
Deno.exit(1);
}
}