Import textures

This commit is contained in:
2026-10-12 17:39:48 -03:00
parent 355e7a21ca
commit e5baeab193
7 changed files with 419 additions and 152 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ deno task check-mods # validate and typecheck every mod in mods/
deno task build # pack mods and build the client, then keeps rebuilding on changes
deno task server # start a server with the mods from the last build
deno fmt # format (tabs, 120 columns), applies to JSON too
deno task import model IN --output OUT # convert a java mod's resources (a file or a folder), see tools/importer.ts
deno task import KIND IN --output OUT # convert a java mod's models or textures (a file or a folder)
```
Tests load mods straight from `mods/` through `test_game` in `tests/helpers.ts`, so they don't need a build. Run
+9 -1
View File
@@ -108,7 +108,7 @@ vanilla ids go, and later kinds add sections for items, blocks and fluids.
| Kind | Java | bworld | Status |
| ------------ | -------------------------------------------- | ------------------------------------------------------------------------- | ------ |
| `model` | `assets/*/models/**.json` | `models/`, parents flattened in, faces renamed, Blockbench extras dropped | Built |
| `texture` | `assets/*/textures/**.png` and `.png.mcmeta` | `textures/`, with animations | |
| `texture` | `assets/*/textures/**.png` and `.png.mcmeta` | `textures/`, with animations | Built |
| `blockstate` | `assets/*/blockstates/*.json` | `variants` or `parts` on `blocks/*.json`, string states made numeric | |
| `lang` | `assets/*/lang/en_us.json` | item and block names | |
| `recipe` | `data/*/recipe(s)/**.json` | `recipes/`: vanilla types to bworld's, a mod's own types kept as they are | |
@@ -133,6 +133,14 @@ Run over Create 0.5.0.j's 2237 model files it converts 2099, all passing `valida
50 OBJ or composite models, 9 that are only parents, and 3 name clashes fixed with one remap line. 26 vanilla textures
they use (pistons, redstone torches, rails) aren't in bworld yet.
**What `texture` does today.** It copies PNGs keeping their folders, since bworld already names a texture in a subfolder
by joining the folders with `_`, which is the same id the converted models use. A `.png.mcmeta` becomes the `.json` next
to the png, keeping only its `animation` section: bworld reads the same format. It checks every texture against the
limits a `.bmod` checks, skips Minecraft's own textures (the remap points at bworld's), and needs `--namespace` when a
folder holds textures of more than one mod, since a texture's namespace comes from the mod it ends up in. For Create
0.5.0.j it copies 989 textures and 11 animations, and skips the six 512×512 title screen panoramas. Its textures and
models together make a mod `check-mods` accepts, with warnings only for the 27 missing textures.
**For Create**, `mods/create/import/` keeps the remap file and the block table. Re-running the import is one command,
and hand-written files are never in the folders it writes.
+80 -4
View File
@@ -1,10 +1,11 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { assert, assertEquals, assertStringIncludes } from "@std/assert";
import { assert, assertEquals, assertStringIncludes, assertThrows } from "@std/assert";
import { validate_model } from "$/common/mod_data.ts";
import type { ModelJson } from "$/common/block_models.ts";
import { import_models } from "$/tools/importer.ts";
import { import_models } from "$/tools/importer/models.ts";
import { convert_mcmeta, import_textures } from "$/tools/importer/textures.ts";
// a java mod's resources in a temporary folder: { "block/gear": {...} } is assets/<namespace>/models/block/gear.json
function resources(models: Record<string, unknown>, namespace = "gears"): string {
@@ -21,7 +22,7 @@ function convert(models: Record<string, unknown>, path: string): ModelJson {
const root = resources(models);
const report = import_models(`${root}/assets/gears/models/${path}.json`);
assertEquals(report.errors, []);
return JSON.parse(report.written[0].text).model;
return JSON.parse(report.written[0].text!).model;
}
const GEAR = {
@@ -128,7 +129,82 @@ Deno.test("--remap renames locations before they become ids", () => {
const report = import_models(`${root}/assets/gears/models/block/gear.json`, {
remaps: { textures: { "gears:block/": "cogs:" }, models: { "gears:block/gear": "cogs:big_gear" } },
});
const model = JSON.parse(report.written[0].text).model;
const model = JSON.parse(report.written[0].text!).model;
assertEquals(model.id, "cogs:big_gear");
assertEquals(model.textures, { "0": "cogs:gear" });
});
// a png with only the header, which is all that's read to size it
function png(width: number, height: number): Uint8Array {
const bytes = new Uint8Array(33);
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52]);
const view = new DataView(bytes.buffer);
view.setUint32(16, width);
view.setUint32(20, height);
return bytes;
}
// textures in a temporary resources folder: { "gears:block/gear": [16, 16] }, with a .png.mcmeta when given
function textures(files: Record<string, { size: [number, number]; mcmeta?: unknown }>): string {
const root = Deno.makeTempDirSync();
for (const [location, { size, mcmeta }] of Object.entries(files)) {
const [namespace, path] = location.split(":");
const file = `${root}/assets/${namespace}/textures/${path}.png`;
Deno.mkdirSync(file.slice(0, file.lastIndexOf("/")), { recursive: true });
Deno.writeFileSync(file, png(...size));
if (mcmeta !== undefined) Deno.writeTextFileSync(`${file}.mcmeta`, JSON.stringify(mcmeta));
}
return root;
}
Deno.test("textures keep their folders, so bworld names them like the models that use them", () => {
const root = textures({
"gears:block/gear": { size: [16, 16] },
"gears:block/belt/scroll": {
size: [16, 64],
mcmeta: { animation: { frametime: 2, interpolate: true }, villager: { hat: "full" } },
},
});
const output = Deno.makeTempDirSync();
const report = import_textures(root, { output });
assertEquals(report.errors, []);
assertEquals(report.written.filter(({ copy }) => copy).map(({ id }) => id).sort(), [
"gears:block_belt_scroll",
"gears:block_gear",
]);
assertEquals(Deno.readFileSync(`${output}/block/gear.png`), png(16, 16));
// the animation is the same format, only renamed, and what bworld can't use is left out
const animation = JSON.parse(Deno.readTextFileSync(`${output}/block/belt/scroll.json`));
assertEquals(animation, { animation: { frametime: 2, interpolate: true } });
assertEquals(report.warnings.length, 1);
});
Deno.test("textures bworld can't use are reported, and minecraft's aren't copied", () => {
const root = textures({
"gears:gui/panorama": { size: [512, 512] },
// 3 rows of 16 don't split into 16×32 frames
"gears:block/uneven": { size: [16, 48], mcmeta: { animation: { height: 32 } } },
"minecraft:block/stone": { size: [16, 16] },
});
const output = Deno.makeTempDirSync();
const report = import_textures(root, { output });
assertEquals(report.skipped.map(({ location }) => location).sort(), [
"gears:gui/panorama",
"minecraft:block/stone",
]);
assertEquals(report.errors.map(({ location }) => location), ["gears:block/uneven"]);
assertEquals(report.written, []);
});
Deno.test("a folder with two mods' textures needs --namespace to pick one", () => {
const root = textures({ "gears:block/gear": { size: [16, 16] }, "belts:block/belt": { size: [16, 16] } });
const output = Deno.makeTempDirSync();
assertThrows(() => import_textures(root, { output }), Error, "--namespace");
const report = import_textures(root, { output, namespace: "belts" });
assertEquals(report.written.map(({ id }) => id), ["belts:block_belt"]);
});
Deno.test("an animation that doesn't fit its png is an error, not a broken texture", () => {
const { problems } = convert_mcmeta({ animation: { frames: [0, 5] } }, { width: 16, height: 32 });
assert(problems.length > 0);
});
+25 -135
View File
@@ -3,143 +3,33 @@
// 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";
// deno run -A tools/importer.ts texture path/to/resources --output mods/example/textures
// a folder can be a whole mod's resources (every assets/<namespace>/<kind> in it), one assets/<namespace>/<kind>, or a
// folder inside one. each kind is in tools/importer/, see USAGE for the options
import { import_models } from "./importer/models.ts";
import { DEFAULT_REMAPS, type ImportOptions, type ImportReport } from "./importer/resources.ts";
import { import_textures } from "./importer/textures.ts";
const KINDS: Record<string, (input: string, options: ImportOptions) => ImportReport> = {
model: import_models,
texture: import_textures,
};
const USAGE = `deno run -A tools/importer.ts <kind> <file or folder> [options]
kinds:
model java block models to bworld models
texture textures, with their .png.mcmeta animations
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
--output PATH the file (for one input file) or the folder to write. one model without it is printed
--namespace NS the namespace, when the input isn't inside assets/<namespace>/, or the only one to take from a
folder with several
--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: [] };
@@ -166,25 +56,24 @@ function parse_args(args: string[]) {
}
function print_report(report: ImportReport) {
if (report.written.length === 1 && report.written[0].file === undefined) {
console.log(report.written[0].text.trimEnd());
}
const [first] = report.written;
if (report.written.length === 1 && first.file === undefined) console.log(first.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
// the same warning about many files 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(`warning: ${warning} (${locations.length === 1 ? locations[0] : `${locations.length} files`})`);
}
const converted = new Set(report.written.map(({ location }) => location)).size;
const parents = report.parents.length > 0 ? `${report.parents.length} only parents, ` : "";
console.error(
`${report.written.length} converted, ${report.parents.length} only parents, ${report.skipped.length} skipped, ` +
`${report.errors.length} with errors`,
`${converted} converted, ${parents}${report.skipped.length} skipped, ${report.errors.length} with errors`,
);
}
@@ -199,8 +88,9 @@ if (import.meta.main) {
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);
const run = KINDS[kind];
if (!run) throw new Error(`"${kind}" isn't a kind that can be imported yet: ${Object.keys(KINDS).join(", ")}`);
const report = run(input, options);
print_report(report);
if (report.errors.length > 0) Deno.exit(1);
} catch (e) {
+71 -1
View File
@@ -6,7 +6,25 @@
// 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 { is_valid_id, location_string, parse_location, type Remaps, to_id } from "./resources.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
@@ -39,6 +57,58 @@ interface Flat {
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 {
+104 -10
View File
@@ -5,7 +5,7 @@
// "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 } from "$/common/mod_data.ts";
import { relative, resolve, SEPARATOR } from "@std/path";
import { dirname, relative, resolve, SEPARATOR } from "@std/path";
export interface Location {
namespace: string;
@@ -38,17 +38,19 @@ export const DEFAULT_REMAPS: Remaps = {
models: {},
};
export function to_id(location: string, remap: Remap = {}): string {
export function remap_location(location: string, remap: Remap = {}): Location {
const full = location_string(parse_location(location));
let mapped = full;
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) {
mapped = remap[from] + full.slice(from.length);
break;
return parse_location(remap[from] + full.slice(from.length));
}
}
const { namespace, path } = parse_location(mapped);
return parse_location(full);
}
export function to_id(location: string, remap: Remap = {}): string {
const { namespace, path } = remap_location(location, remap);
return `${namespace}:${path.replaceAll("/", "_")}`;
}
@@ -62,8 +64,8 @@ export interface ResourceRoot {
dir: string;
}
// the roots of a kind inside a folder: every assets/<namespace>/<kind> under it, 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, if there is one
// 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, namespace?: string): ResourceRoot[] {
const dir = resolve(input);
const enclosing = enclosing_root(dir, kind);
@@ -76,8 +78,32 @@ export function find_roots(input: string, kind: string, namespace?: string): Res
}
}
}
if (roots.length === 0 && namespace) roots.push({ namespace, dir });
return roots;
if (roots.length === 0) return namespace ? [{ namespace, dir }] : [];
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
export function input_files(input: string, kind: string, extension: string, namespace?: string): InputFile[] {
if (is_file(input)) {
const root = enclosing_root(input, kind) ?? (namespace && { namespace, dir: dirname(resolve(input)) });
if (!root) throw new Error(`can't tell ${input}'s namespace: pass --namespace`);
return [{ root, file: resolve(input) }];
}
const roots = find_roots(input, kind, namespace);
if (roots.length === 0) {
throw new Error(`no ${kind} in ${input}: pass --namespace when it isn't inside assets/<namespace>/${kind}`);
}
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
@@ -128,6 +154,14 @@ function read_dir(dir: string): Deno.DirEntry[] {
}
}
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;
@@ -136,6 +170,66 @@ function is_dir(path: string): boolean {
}
}
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;
}
// 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[];
// 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 empty_report(): ImportReport {
return { written: [], parents: [], 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 ?? "");
}
}
// json in the style of the repo's data files: tabs, and short lists and objects of plain values on one line
export function format_json(value: unknown, indent = ""): string {
if (value === null || typeof value !== "object") return JSON.stringify(value);
+129
View File
@@ -0,0 +1,129 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// java textures (assets/<namespace>/textures/**.png) to a bworld mod's textures/. bworld names a texture in a subfolder
// by joining the folders with _, like resources.ts does for every id, so the folders stay as they are and models
// converted from the same mod find their textures. a .png.mcmeta becomes the .json next to the png: bworld reads the
// same animation format
import { join } from "@std/path";
import { png_size, texture_size_problem } from "$/common/bmod.ts";
import { type TextureJson, validate_texture_json } from "$/common/texture_animation.ts";
import {
DEFAULT_REMAPS,
empty_report,
format_json,
id_claims,
type ImportOptions,
type ImportReport,
input_files,
is_file,
is_valid_id,
location_of,
location_string,
remap_location,
to_id,
write_report,
} from "./resources.ts";
const ANIMATION_FIELDS = ["frametime", "interpolate", "frames", "width", "height"];
export type MetaResult = { json?: TextureJson; warnings: string[]; problems: string[] };
// a .png.mcmeta's animation, for a png of the size, or no json for one with no animation. the other sections (blur and
// clamping, a gui's nine-slice scaling) have nothing in bworld to go to
export function convert_mcmeta(mcmeta: unknown, size: { width: number; height: number }): MetaResult {
if (mcmeta === null || typeof mcmeta !== "object" || Array.isArray(mcmeta)) {
return { warnings: [], problems: ["the .mcmeta must be an object"] };
}
const warnings = Object.keys(mcmeta).filter((key) => key !== "animation")
.map((key) => `the .mcmeta's "${key}" section was left out`);
const animation = (mcmeta as Record<string, unknown>).animation as Record<string, unknown> | undefined;
if (animation === undefined) return { warnings, problems: [] };
for (const key of Object.keys(animation ?? {})) {
if (!ANIMATION_FIELDS.includes(key)) warnings.push(`the animation's "${key}" was left out`);
}
const json = {
animation: Object.fromEntries(
Object.entries(animation ?? {}).filter(([key]) => ANIMATION_FIELDS.includes(key)),
),
};
const problems = validate_texture_json(json, size);
return problems.length > 0 ? { warnings, problems } : { json: json as TextureJson, warnings, problems };
}
// copies one texture, or every texture in a folder, with their animations. minecraft's own textures aren't copied:
// models refer to them through the remap, which by default makes them the base game's
export function import_textures(input: string, options: ImportOptions = {}): ImportReport {
if (options.output === undefined) throw new Error("--output is needed for textures");
const remaps = options.remaps ?? DEFAULT_REMAPS;
const single = is_file(input);
const report = empty_report();
const claim = id_claims(report);
const files = input_files(input, "textures", ".png", options.namespace);
// a texture gets its namespace from the mod it's in, so two namespaces' textures can't share one folder
const namespaces = [...new Set(files.map(({ root }) => root.namespace))].filter((ns) => ns !== "minecraft");
if (namespaces.length > 1) {
throw new Error(`${input} has textures of ${namespaces.join(", ")}: pick one with --namespace`);
}
for (const { root, file } of files) {
const location = location_string(location_of(root, file, ".png"));
if (root.namespace === "minecraft") {
report.skipped.push({
location,
reason: "minecraft's own textures aren't copied, the remap points at bworld's",
});
continue;
}
const id = to_id(location, remaps.textures);
if (!is_valid_id(id)) {
report.errors.push({ location, problems: [`it doesn't make a valid texture id (${id})`] });
continue;
}
const size = png_size(Deno.readFileSync(file));
if (!size) {
report.errors.push({ location, problems: ["it isn't a png"] });
continue;
}
let json: TextureJson | undefined;
if (is_file(`${file}.mcmeta`)) {
let mcmeta: unknown;
try {
mcmeta = JSON.parse(Deno.readTextFileSync(`${file}.mcmeta`));
} catch (e) {
report.errors.push({ location, problems: [`its .mcmeta isn't valid json: ${(e as Error).message}`] });
continue;
}
const result = convert_mcmeta(mcmeta, size);
if (result.problems.length > 0) {
report.errors.push({ location, problems: result.problems });
continue;
}
for (const warning of result.warnings) report.warnings.push({ location, warning });
json = result.json;
}
// the limits a .bmod checks, like a title screen's 512×512 panorama being too big
const too_big = texture_size_problem(size, json);
if (too_big) {
report.skipped.push({ location, reason: `it ${too_big}` });
continue;
}
if (!claim(id, location)) continue;
// where it goes is what names it, so a remapped texture goes where its new name says
const png = single
? options.output
: join(options.output, `${remap_location(location, remaps.textures).path}.png`);
report.written.push({ location, id, file: png, copy: file });
if (json) {
report.written.push({
location,
id,
file: png.replace(/\.png$/, "") + ".json",
text: format_json(json) + "\n",
});
}
}
write_report(report);
return report;
}