Files
bworld/tools/importer/models.ts
T
2026-10-12 17:39:48 -03:00

236 lines
9.7 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// java block models (assets/<namespace>/models/**.json) to bworld's models/. the formats are close: what changes is
// that parents are flattened into each model, faces are top and bottom instead of up and down, ids lose their folders,
// and what bworld has no use for (blockbench's names, display transforms, particle textures) is left out
import type { ModelElementJson, ModelFace, ModelFaceJson, ModelJson } from "$/common/block_models.ts";
import { FORMAT_VERSION } from "$/common/mod_data.ts";
import { join } from "@std/path";
import {
DEFAULT_REMAPS,
empty_report,
find_roots,
format_json,
id_claims,
type ImportOptions,
type ImportReport,
input_files,
is_file,
is_valid_id,
location_of,
location_string,
parse_location,
type Remaps,
to_id,
write_report,
} from "./resources.ts";
import { NOT_BOXES, VANILLA_MODELS } from "./vanilla_models.ts";
// reads a java model by location ("create:block/cogwheel"), undefined when there's none
export type ModelSource = (location: string) => Record<string, unknown> | undefined;
export type ModelResult =
| { kind: "model"; id: string; json: { format_version: number; model: ModelJson }; warnings: string[] }
// only there to be a parent, like minecraft's block/block
| { kind: "parent" }
| { kind: "skipped"; reason: string }
| { kind: "error"; problems: string[] };
const FACE_NAMES: Record<string, ModelFace> = {
down: "bottom",
up: "top",
north: "north",
south: "south",
west: "west",
east: "east",
};
const ANGLES = [-45, -22.5, 0, 22.5, 45];
interface Flat {
textures: Record<string, string>;
elements?: unknown[];
loader?: string;
render_type?: string;
not_boxes?: string;
}
class ImportError extends Error {}
// converts one model, or every model in a folder. parents can be anywhere in the same roots or in options.parents, not
// only in what's being converted
export function import_models(input: string, options: ImportOptions = {}): ImportReport {
const remaps = options.remaps ?? DEFAULT_REMAPS;
const single = is_file(input);
if (!single && options.output === undefined) throw new Error("--output is needed to convert a folder");
const files = input_files(input, "models", ".json", options.namespace);
const lookup = [
...new Set(files.map(({ root }) => root)),
...(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);
const file = lookup.filter((root) => root.namespace === namespace).map((root) => `${root.dir}/${path}.json`)
.find(is_file);
let json: Record<string, unknown> | undefined;
if (file) {
try {
json = JSON.parse(Deno.readTextFileSync(file));
} catch (e) {
throw new Error(`${file} isn't valid json: ${(e as Error).message}`);
}
}
cache.set(location, json);
return json;
};
const several_namespaces = new Set(files.map(({ root }) => root.namespace)).size > 1;
const report = empty_report();
const claim = id_claims(report);
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 if (claim(result.id, location)) {
for (const warning of result.warnings) report.warnings.push({ location, warning });
// a model's id is inside it, so its file can keep the folders it had
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" });
}
}
write_report(report);
return report;
}
export function convert_model(location: string, read: ModelSource, remaps: Remaps): ModelResult {
let flat: Flat;
try {
flat = flatten(location_string(parse_location(location)), read, []);
} catch (e) {
if (e instanceof ImportError) return { kind: "error", problems: [e.message] };
throw e;
}
if (flat.not_boxes) return { kind: "skipped", reason: flat.not_boxes };
if (flat.loader) return { kind: "skipped", reason: `it uses the "${flat.loader}" loader` };
if (!flat.elements || flat.elements.length === 0) return { kind: "parent" };
const problems: string[] = [];
const warnings = new Set<string>();
if (flat.render_type) warnings.add(`render_type "${flat.render_type}" was left out, set the block's render layer`);
const texture = (value: string, where: string) => {
if (value.startsWith("#")) return value;
const id = to_id(value, remaps.textures);
if (!is_valid_id(id)) problems.push(`${where}: "${value}" doesn't make a valid texture id (${id})`);
return id;
};
const elements = flat.elements.map((element, i) =>
convert_element(element, `elements[${i}]`, texture, problems, warnings)
);
// only the variables faces reach, so particle textures and ones children overrode don't come along
const textures: Record<string, string> = {};
const pending = elements.flatMap((element) => Object.values(element.faces).map((face) => face!.texture));
for (let reference = pending.pop(); reference !== undefined; reference = pending.pop()) {
const name = reference.slice(1);
if (!reference.startsWith("#") || name in textures || flat.textures[name] === undefined) continue;
textures[name] = texture(flat.textures[name], `textures.${name}`);
pending.push(textures[name]);
}
const id = to_id(location, remaps.models);
if (!is_valid_id(id)) problems.push(`"${location}" doesn't make a valid model id (${id})`);
if (problems.length > 0) return { kind: "error", problems };
const model: ModelJson = Object.keys(textures).length > 0 ? { id, textures, elements } : { id, elements };
return { kind: "model", id, json: { format_version: FORMAT_VERSION, model }, warnings: [...warnings] };
}
// a model with its parents' textures and elements merged in, like minecraft's BlockModel does when it bakes: the child's
// textures win, and its elements replace its parent's when it has any
function flatten(location: string, read: ModelSource, chain: string[]): Flat {
if (chain.includes(location)) throw new ImportError(`its parents loop: ${[...chain, location].join(" -> ")}`);
if (NOT_BOXES[location]) return { textures: {}, not_boxes: `${NOT_BOXES[location]} (${location})` };
const json = VANILLA_MODELS[location] ?? read(location);
if (!json) {
throw new ImportError(
chain.length === 0 ? `${location} wasn't found` : `its parent ${location} wasn't found, pass --parents`,
);
}
const parent: Flat = typeof json.parent === "string"
? flatten(location_string(parse_location(json.parent)), read, [...chain, location])
: { textures: {} };
return {
textures: { ...parent.textures, ...(json.textures as Record<string, string> | undefined) },
elements: Array.isArray(json.elements) ? json.elements : parent.elements,
loader: typeof json.loader === "string" ? json.loader : parent.loader,
render_type: typeof json.render_type === "string" ? json.render_type : parent.render_type,
not_boxes: parent.not_boxes,
};
}
function convert_element(
json: unknown,
where: string,
texture: (value: string, where: string) => string,
problems: string[],
warnings: Set<string>,
): ModelElementJson {
const element = (json ?? {}) as Record<string, unknown>;
const point = (key: string) => {
const value = element[key];
if (Array.isArray(value) && value.length === 3 && value.every((v) => typeof v === "number")) {
return value as [number, number, number];
}
problems.push(`${where}.${key} must be [x, y, z]`);
return [0, 0, 0] as [number, number, number];
};
const out = { from: point("from"), to: point("to") } as ModelElementJson;
const rotation = element.rotation as Record<string, unknown> | undefined;
if (rotation && rotation.angle !== 0) {
if (!ANGLES.includes(rotation.angle as number)) {
problems.push(`${where}.rotation: an angle of ${rotation.angle} isn't one of ${ANGLES.join(", ")}`);
}
out.rotation = {
origin: rotation.origin as [number, number, number],
axis: rotation.axis as "x" | "y" | "z",
angle: rotation.angle as number,
...(rotation.rescale === true ? { rescale: true } : {}),
};
}
if (element.shade === false) out.shade = false;
if (element.light_emission !== undefined) warnings.add("light_emission on elements was left out");
out.faces = {};
for (const [side, value] of Object.entries((element.faces ?? {}) as Record<string, Record<string, unknown>>)) {
const name = FACE_NAMES[side];
if (!name) {
problems.push(`${where}.faces: "${side}" isn't a side`);
continue;
}
if (typeof value.texture !== "string") {
problems.push(`${where}.faces.${side} has no texture`);
continue;
}
const face: ModelFaceJson = { texture: texture(value.texture, `${where}.faces.${side}`) };
if (Array.isArray(value.uv)) face.uv = value.uv as [number, number, number, number];
if (typeof value.rotation === "number" && value.rotation !== 0) face.rotation = value.rotation;
if (typeof value.cullface === "string") {
// java also takes "bottom" for down
const cullface = FACE_NAMES[value.cullface] ?? (value.cullface === "bottom" ? "bottom" : undefined);
if (cullface) face.cullface = cullface;
else problems.push(`${where}.faces.${side}.cullface: "${value.cullface}" isn't a side`);
}
if (value.tintindex !== undefined) warnings.add("tintindex on faces was left out");
out.faces[name] = face;
}
return out;
}