diff --git a/CREATE.md b/CREATE.md index a3e41a2..62f8f57 100644 --- a/CREATE.md +++ b/CREATE.md @@ -89,9 +89,9 @@ deno run -A tools/importer.ts model path/to/resources --output DIR # every as ``` A folder can be a mod's whole resources, one `assets//models`, or a folder inside one, and the output keeps -the same folders. `--parents FOLDER` adds other resources to find parent models in (another mod, or vanilla's), and -`--remap FILE` renames locations before they become ids. Every kind reports what it converted, what it skipped and why, -and what's wrong, and exits with an error when anything is. +the same folders. `--parents FOLDER` adds other resources to follow parents through (to tell sprites and OBJ models +apart), and `--remap FILE` renames locations before they become ids. Every kind reports what it converted, what it +skipped and why, and what's wrong, and exits with an error when anything is. **Ids.** A resource location becomes a bworld id by joining its folders with `_`, the same rule `check-mods` uses for textures in subfolders: `create:block/cogwheel` is `create:block_cogwheel`, for its model and its texture alike. It's a @@ -107,7 +107,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 | +| `model` | `assets/*/models/**.json` | `models/`, parents kept, faces renamed, Blockbench extras dropped | Built | | `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 | | @@ -122,16 +122,19 @@ Block properties (shape, tool, toughness) aren't in any data file: Java mods set each blockstate with placeholder properties, and a per-mod table fills them in. For Create that table is `mods/create/import/blocks.json`. -**What `model` does today.** It flattens `parent` chains into each model (the child's textures win, its elements replace -its parent's), and knows the vanilla parents most mods use without Minecraft's files: `block/block`, `cube`, `cube_all`, -`cube_column`, `cube_column_horizontal`, `cube_bottom_top`, `orientable`, slabs, stairs, walls and glass panes -(`tools/importer/vanilla_models.ts`, written as boxes, not copied). It drops Blockbench's extras, `display`, `particle` -and texture variables no face reaches. It skips item sprites (`item/generated`) and `loader` models (OBJ, composite), -and says why. +**What `model` does today.** It keeps `parent`, since the engine merges parents in when it loads (see +[Parents](docs/modding/resources/models.md#parents)), and remaps it like any id. Minecraft's template parents (`cube`, +`cube_all`, `cube_column`, `orientable`, slabs, stairs, walls, glass panes) become the base game's models of the same +name in `mods/bworld/models/templates/`, and the default remap is read from that folder. A parent that holds nothing +bworld uses, like `block/block` or a mod's own root of display transforms, is left out. It drops Blockbench's extras and +`display`, keeps every texture variable (some models draw faces with `#particle`), skips item sprites (`item/generated`) +and `loader` models (OBJ, composite) anywhere up a model's parents, and says why. -Run over Create 0.5.0.j's 2237 model files it converts 2099, all passing `validate_model`. The rest are 78 item sprites, -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. +Run over Create 0.5.0.j's 2237 model files it converts 2105, and with its textures they make a mod `check-mods` accepts. +The rest are 79 item sprites, 50 OBJ or composite models and 5 display-only roots, and 3 name clashes were fixed with +one remap line. Merged the way the game merges them, the 2099 models with boxes come out identical to flattening them, +and the files are 1.5 MB instead of 3.4 MB. 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 @@ -224,9 +227,8 @@ nothing per frame. See `ports/sodium` for how to keep buffer updates cheap. **R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU buffer, and turned for whatever axis it's used on. -**R5. The model format** (P0). What Create's models use that bworld's don't support yet: +**R5. The model format** (P0). What Create's models use that bworld's don't support yet (`parent` is built): -- `parent` (or the importer flattens it, which is simpler; decide in P0); - `x` turns in variants and parts, not just `y`; - `uvlock`; - element `rotation` at every 22.5° step on all three axes; @@ -548,7 +550,6 @@ ratio. Recipes come from the imported data, so tests use Create's recipes instea fluids, dyes. Add them to bworld, substitute them in Create's remap file, or drop what needs them? - **Unloaded chunks:** blocks only tick within 6 chunks of a player. Do factories need a way to stay loaded, like chunk loaders, or is "near a player" fine for bworld? -- **`parent` in models:** support it in the engine (R5), which other mods would use, or flatten it in the importer? - **Contraption collision:** port `ContraptionCollider`'s approach, or write a simpler one for bworld's physics (`common/physics.ts`) that handles turning structures differently? - **Trains before or after contraptions:** trains reuse S6, but they're also the most-loved part of Create. Is P8 worth diff --git a/common/block_models.ts b/common/block_models.ts index eac5a1f..c5acff3 100644 --- a/common/block_models.ts +++ b/common/block_models.ts @@ -39,13 +39,78 @@ export interface ModelElementJson { faces: Partial>; } -export interface ModelJson { +// a model as a mod writes it in models/. it can start from a parent, like minecraft's: it gets the parent's elements +// unless it has its own, and the parent's texture defaults under its own. one with no elements is only there to be a +// parent, or draws nothing +export interface ModelFileJson { id: string; + parent?: string; // defaults for texture variables, can point at other variables ("top": "#side") textures?: Record; + elements?: ModelElementJson[]; +} + +// a model with its parents merged in, which is what blocks are drawn with. see resolve_models +export interface ModelJson { + id: string; + textures?: Record; elements: ModelElementJson[]; } +// mods' models with their parents merged in. a parent is another of these, or one existing finds (a model of a mod +// loaded before, or a built-in one). a model whose parent doesn't exist or whose parents loop keeps only what it has +// itself, and gets a problem +export function resolve_models( + models: ModelFileJson[], + existing: (id: string) => ModelJson | undefined, +): { models: ModelJson[]; problems: { id: string; problem: string }[] } { + const files = new Map(models.map((model) => [model.id, model])); + const problems: { id: string; problem: string }[] = []; + // a model in a loop is resolved without its parent, so resolving never goes round one + const looped = new Set(); + for (const { id } of models) { + const loop = parent_loop(id, (other) => files.get(other)?.parent); + if (loop) { + looped.add(id); + problems.push({ id, problem: `its parents loop: ${loop.join(" -> ")}` }); + } + } + const resolved = new Map(); + const resolve = (id: string): ModelJson | undefined => { + const file = files.get(id); + if (!file) return existing(id); + const done = resolved.get(id); + if (done) return done; + let parent: ModelJson | undefined; + if (file.parent !== undefined && !looped.has(id)) { + parent = resolve(file.parent); + // a parent of this mod that has a problem of its own still resolves, so this is only for missing ones + if (!parent) problems.push({ id, problem: `its parent ${file.parent} doesn't exist` }); + } + const textures = { ...parent?.textures, ...file.textures }; + const model: ModelJson = { + id, + ...(Object.keys(textures).length > 0 ? { textures } : {}), + elements: file.elements ?? parent?.elements ?? [], + }; + resolved.set(id, model); + return model; + }; + return { models: models.map(({ id }) => resolve(id)!), problems }; +} + +// the parents from a model back round to it, when its parents loop. parent_of gives a model's parent, if it has one +export function parent_loop(id: string, parent_of: (id: string) => string | undefined): string[] | undefined { + const chain = [id]; + for (let next = parent_of(id); next !== undefined; next = parent_of(next)) { + if (next === id) return [...chain, id]; + // a loop further up, which isn't this model's to report + if (chain.includes(next)) return undefined; + chain.push(next); + } + return undefined; +} + // a model a block uses, and the textures it fills in export interface BlockVariant { model?: string; diff --git a/common/bmod.ts b/common/bmod.ts index 63414a3..27f7641 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -4,7 +4,7 @@ // .bmod files: a built mod in one zip, what servers load from server_mods/ and send to players. see // docs/modding/gettingstarted/modfiles.md. the same code reads them on the server and in the browser, so it only works on bytes import { unzipSync, zipSync } from "fflate"; -import type { ModelJson } from "./block_models.ts"; +import type { ModelFileJson } from "./block_models.ts"; import { MAX_ANIMATED_TEXTURE_SIZE, MAX_TEXTURE_SIZE } from "./constants.ts"; import { type BlockJson, @@ -164,7 +164,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { const data: ModData = { blocks: checked(raw_data.blocks, "blocks", validate_block, problems) as BlockJson[], - models: checked(raw_data.models, "models", validate_model, problems) as ModelJson[], + models: checked(raw_data.models, "models", validate_model, problems) as ModelFileJson[], items: checked(raw_data.items, "items", validate_item, problems) as ItemJson[], recipes: checked(raw_data.recipes, "recipes", validate_recipe, problems) as RecipeJson[], ores: checked(raw_data.ores, "ores", validate_ore, problems) as OreJson[], diff --git a/common/mod_check.ts b/common/mod_check.ts index 09d28e4..7081bb5 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -18,7 +18,7 @@ import { type TagRegistry, } from "./mod_data.ts"; import { PLAYER_PARTS } from "./everything_registry.ts"; -import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts"; +import { BUILTIN_MODELS, type ModelFileJson, parent_loop } from "./block_models.ts"; import { resolve_tags } from "./tags.ts"; import type { TextureJson } from "./texture_animation.ts"; import { loot_references, type LootTableJson } from "./loot.ts"; @@ -49,7 +49,7 @@ export interface LoadedMod { report: ModReport; manifest?: Record; blocks: { file: string; json: BlockJson }[]; - models: { file: string; json: ModelJson }[]; + models: { file: string; json: ModelFileJson }[]; items: { file: string; json: ItemJson }[]; recipes: { file: string; json: RecipeJson }[]; ores: { file: string; json: OreJson }[]; @@ -105,6 +105,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable(); const item_owners = new Map(); const model_owners = new Map(); + const model_parents = new Map(); const entity_owners = new Map(); const entity_jsons = new Map(); const entity_model_owners = new Map(); @@ -136,7 +137,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable model_parents.get(id)); + if (loop) errors.push(`${file}: model ${json.id}'s parents loop: ${loop.join(" -> ")}`); + } + for (const element of json.elements ?? []) { for (const face of Object.values(element.faces)) { if (face && !face.texture.startsWith("#")) uses(file, face.texture, "texture"); } diff --git a/common/mod_data.ts b/common/mod_data.ts index 9d6d2d6..8caf119 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -775,8 +775,16 @@ function validate_shape(shape: unknown, where: string, top = 16): Problems { export function validate_model(json: unknown): Problems { if (!is_object(json)) return ["model must be an object"]; const problems = validate_id(json.id, "id"); + if (json.parent !== undefined) problems.push(...validate_id(json.parent, "parent")); if (json.textures !== undefined) problems.push(...validate_textures(json.textures, "textures", true)); - if (!Array.isArray(json.elements) || json.elements.length === 0) { + // a model can leave its elements to its parent, or be one that only gives texture defaults to its children + if (json.elements === undefined) { + if (json.parent === undefined && json.textures === undefined) { + problems.push("a model needs elements, a parent, or textures for models that use it as theirs"); + } + return problems; + } + if (!Array.isArray(json.elements)) { problems.push("elements must be a list of boxes"); return problems; } diff --git a/common/mod_loader.ts b/common/mod_loader.ts index f0089df..b6cc862 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -29,13 +29,13 @@ import { type BiomeJson, register_biome } from "./worldgen/biomes.ts"; import type { BiomeSourceJson, DensityFunctionJson, NoiseJson, NoiseSettingsJson } from "./worldgen/data.ts"; import type { FeatureJson } from "./worldgen/features.ts"; import { register_block_item } from "./utils.ts"; -import type { ModelJson } from "./block_models.ts"; +import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts"; // everything a mod's json files hold, merged into one file by the build (build/mods///data.json) export interface ModData { blocks: BlockJson[]; - // block models, see common/block_models.ts - models: ModelJson[]; + // block models as mods write them, parents not merged in yet. see common/block_models.ts + models: ModelFileJson[]; items: ItemJson[]; recipes: RecipeJson[]; ores: OreJson[]; @@ -107,7 +107,15 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe for (const { id, data } of mods) { try { - for (const model of data.models) { + // parents are this mod's or an earlier one's, which are already registered with theirs merged in + const { models, problems } = resolve_models( + data.models, + (model_id) => find_model(model_id, {}) ?? EverythingRegistry.get("models", model_id), + ); + if (problems.length > 0) { + throw new Error(problems.map(({ id, problem }) => `model ${id}: ${problem}`).join("\n")); + } + for (const model of models) { EverythingRegistry.register("models", model.id, model); } for (const json of data.blocks) { diff --git a/docs/modding/resources/models.md b/docs/modding/resources/models.md index 0dbd3a0..1d89cae 100644 --- a/docs/modding/resources/models.md +++ b/docs/modding/resources/models.md @@ -65,6 +65,7 @@ on every face, since `top` and `bottom` default to `#side`. | Field | Meaning | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | The model's id, in the mod's namespace. | +| `parent` | Another model this one starts from, see [Parents](#parents). | | `textures` | Defaults for texture variables. Values are texture ids or other variables, like `"#side"`. | | `elements[].from`, `to` | Opposite corners of the box, `[x, y, z]` in pixels. | | `elements[].rotation` | `{ origin, axis, angle, rescale }`: turns the box around `origin` on `x`, `y` or `z` by -45, -22.5, 0, 22.5 or 45 degrees. `rescale` stretches it back to the block's width. | @@ -77,6 +78,44 @@ on every face, since `top` and `bottom` default to `#side`. Faces are only drawn from the front, so a flat plane that should be seen from both sides needs a face each way. +## Parents + +A model can start from another with `parent`, like Minecraft's. It gets the parent's elements unless it has its own, and +the parent's texture defaults, with its own winning. A parent can have a parent too. `models/brass_gear.json` reuses a +gear's shape with other textures: + +```json +{ + "format_version": 1, + "model": { + "id": "copper_tools:brass_gear", + "parent": "copper_tools:gear", + "textures": { "teeth": "copper_tools:brass" } + } +} +``` + +A parent can be the mod's own model, a built-in one, or one from a mod it depends on. A model with no `elements` is only +there to be a parent, or to give its children texture defaults. Parents are merged in once, when the game loads, so a +model with a parent draws exactly as if it had everything written out. `check-mods` reports a parent that doesn't exist +and parents that loop. + +The base game has Minecraft's template models in `mods/bworld/models/templates/`, with the same names and texture +variables: `bworld:cube`, `cube_all`, `cube_column`, `cube_column_horizontal`, `cube_bottom_top`, `orientable`, +`orientable_with_bottom`, `slab`, `slab_top`, `stairs`, `inner_stairs`, `outer_stairs`, the `template_wall_*` and +`template_glass_pane_*` models, and `wall_inventory`. A pillar from a log's textures: + +```json +{ + "format_version": 1, + "model": { + "id": "copper_tools:pillar", + "parent": "bworld:cube_column", + "textures": { "end": "copper_tools:pillar_top", "side": "copper_tools:pillar" } + } +} +``` + ## Shapes A block's shape is the boxes it's made of, like Minecraft's `VoxelShape`. It's what players point at, so they can look diff --git a/mods/bworld/models/templates/cube.json b/mods/bworld/models/templates/cube.json new file mode 100644 index 0000000..892ed55 --- /dev/null +++ b/mods/bworld/models/templates/cube.json @@ -0,0 +1,20 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:cube", + "elements": [ + { + "from": [0, 0, 0], + "to": [16, 16, 16], + "faces": { + "bottom": { "texture": "#down", "cullface": "bottom" }, + "top": { "texture": "#up", "cullface": "top" }, + "north": { "texture": "#north", "cullface": "north" }, + "south": { "texture": "#south", "cullface": "south" }, + "west": { "texture": "#west", "cullface": "west" }, + "east": { "texture": "#east", "cullface": "east" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/cube_all.json b/mods/bworld/models/templates/cube_all.json new file mode 100644 index 0000000..005c689 --- /dev/null +++ b/mods/bworld/models/templates/cube_all.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:cube_all", + "parent": "bworld:cube", + "textures": { + "down": "#all", + "up": "#all", + "north": "#all", + "south": "#all", + "west": "#all", + "east": "#all" + } + } +} diff --git a/mods/bworld/models/templates/cube_bottom_top.json b/mods/bworld/models/templates/cube_bottom_top.json new file mode 100644 index 0000000..1a5cc22 --- /dev/null +++ b/mods/bworld/models/templates/cube_bottom_top.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:cube_bottom_top", + "parent": "bworld:cube", + "textures": { + "down": "#bottom", + "up": "#top", + "north": "#side", + "south": "#side", + "west": "#side", + "east": "#side" + } + } +} diff --git a/mods/bworld/models/templates/cube_column.json b/mods/bworld/models/templates/cube_column.json new file mode 100644 index 0000000..ddd78ce --- /dev/null +++ b/mods/bworld/models/templates/cube_column.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:cube_column", + "parent": "bworld:cube", + "textures": { + "down": "#end", + "up": "#end", + "north": "#side", + "south": "#side", + "west": "#side", + "east": "#side" + } + } +} diff --git a/mods/bworld/models/templates/cube_column_horizontal.json b/mods/bworld/models/templates/cube_column_horizontal.json new file mode 100644 index 0000000..800f346 --- /dev/null +++ b/mods/bworld/models/templates/cube_column_horizontal.json @@ -0,0 +1,20 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:cube_column_horizontal", + "elements": [ + { + "from": [0, 0, 0], + "to": [16, 16, 16], + "faces": { + "bottom": { "texture": "#side", "rotation": 180, "cullface": "bottom" }, + "top": { "texture": "#side", "cullface": "top" }, + "north": { "texture": "#end", "cullface": "north" }, + "south": { "texture": "#end", "cullface": "south" }, + "west": { "texture": "#side", "rotation": 270, "cullface": "west" }, + "east": { "texture": "#side", "rotation": 90, "cullface": "east" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/inner_stairs.json b/mods/bworld/models/templates/inner_stairs.json new file mode 100644 index 0000000..c35b595 --- /dev/null +++ b/mods/bworld/models/templates/inner_stairs.json @@ -0,0 +1,42 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:inner_stairs", + "elements": [ + { + "from": [0, 0, 0], + "to": [16, 8, 16], + "faces": { + "bottom": { "texture": "#bottom", "cullface": "bottom" }, + "top": { "texture": "#top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "east" } + } + }, + { + "from": [8, 8, 0], + "to": [16, 16, 16], + "faces": { + "top": { "texture": "#top", "cullface": "top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side" }, + "east": { "texture": "#side", "cullface": "east" } + } + }, + { + "from": [0, 8, 8], + "to": [8, 16, 16], + "faces": { + "top": { "texture": "#top", "cullface": "top" }, + "north": { "texture": "#side" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/orientable.json b/mods/bworld/models/templates/orientable.json new file mode 100644 index 0000000..1c76d29 --- /dev/null +++ b/mods/bworld/models/templates/orientable.json @@ -0,0 +1,8 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:orientable", + "parent": "bworld:orientable_with_bottom", + "textures": { "bottom": "#top" } + } +} diff --git a/mods/bworld/models/templates/orientable_with_bottom.json b/mods/bworld/models/templates/orientable_with_bottom.json new file mode 100644 index 0000000..13f5122 --- /dev/null +++ b/mods/bworld/models/templates/orientable_with_bottom.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:orientable_with_bottom", + "parent": "bworld:cube", + "textures": { + "down": "#bottom", + "up": "#top", + "north": "#front", + "south": "#side", + "west": "#side", + "east": "#side" + } + } +} diff --git a/mods/bworld/models/templates/outer_stairs.json b/mods/bworld/models/templates/outer_stairs.json new file mode 100644 index 0000000..1d4aaf7 --- /dev/null +++ b/mods/bworld/models/templates/outer_stairs.json @@ -0,0 +1,31 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:outer_stairs", + "elements": [ + { + "from": [0, 0, 0], + "to": [16, 8, 16], + "faces": { + "bottom": { "texture": "#bottom", "cullface": "bottom" }, + "top": { "texture": "#top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "east" } + } + }, + { + "from": [8, 8, 8], + "to": [16, 16, 16], + "faces": { + "top": { "texture": "#top", "cullface": "top" }, + "north": { "texture": "#side" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side" }, + "east": { "texture": "#side", "cullface": "east" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/slab.json b/mods/bworld/models/templates/slab.json new file mode 100644 index 0000000..d8289dd --- /dev/null +++ b/mods/bworld/models/templates/slab.json @@ -0,0 +1,20 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:slab", + "elements": [ + { + "from": [0, 0, 0], + "to": [16, 8, 16], + "faces": { + "bottom": { "texture": "#bottom", "cullface": "bottom" }, + "top": { "texture": "#top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "east" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/slab_top.json b/mods/bworld/models/templates/slab_top.json new file mode 100644 index 0000000..4da7c6a --- /dev/null +++ b/mods/bworld/models/templates/slab_top.json @@ -0,0 +1,20 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:slab_top", + "elements": [ + { + "from": [0, 8, 0], + "to": [16, 16, 16], + "faces": { + "bottom": { "texture": "#bottom" }, + "top": { "texture": "#top", "cullface": "top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "east" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/stairs.json b/mods/bworld/models/templates/stairs.json new file mode 100644 index 0000000..2afc80f --- /dev/null +++ b/mods/bworld/models/templates/stairs.json @@ -0,0 +1,31 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:stairs", + "elements": [ + { + "from": [0, 0, 0], + "to": [16, 8, 16], + "faces": { + "bottom": { "texture": "#bottom", "cullface": "bottom" }, + "top": { "texture": "#top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "east" } + } + }, + { + "from": [8, 8, 0], + "to": [16, 16, 16], + "faces": { + "top": { "texture": "#top", "cullface": "top" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side" }, + "east": { "texture": "#side", "cullface": "east" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_glass_pane_noside.json b/mods/bworld/models/templates/template_glass_pane_noside.json new file mode 100644 index 0000000..eb9e561 --- /dev/null +++ b/mods/bworld/models/templates/template_glass_pane_noside.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_glass_pane_noside", + "elements": [ + { + "from": [7, 0, 7], + "to": [9, 16, 9], + "faces": { + "north": { "texture": "#pane" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_glass_pane_noside_alt.json b/mods/bworld/models/templates/template_glass_pane_noside_alt.json new file mode 100644 index 0000000..008a703 --- /dev/null +++ b/mods/bworld/models/templates/template_glass_pane_noside_alt.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_glass_pane_noside_alt", + "elements": [ + { + "from": [7, 0, 7], + "to": [9, 16, 9], + "faces": { + "east": { "texture": "#pane" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_glass_pane_post.json b/mods/bworld/models/templates/template_glass_pane_post.json new file mode 100644 index 0000000..8c15164 --- /dev/null +++ b/mods/bworld/models/templates/template_glass_pane_post.json @@ -0,0 +1,16 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_glass_pane_post", + "elements": [ + { + "from": [7, 0, 7], + "to": [9, 16, 9], + "faces": { + "bottom": { "texture": "#edge", "cullface": "bottom" }, + "top": { "texture": "#edge", "cullface": "top" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_glass_pane_side.json b/mods/bworld/models/templates/template_glass_pane_side.json new file mode 100644 index 0000000..db24e81 --- /dev/null +++ b/mods/bworld/models/templates/template_glass_pane_side.json @@ -0,0 +1,19 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_glass_pane_side", + "elements": [ + { + "from": [7, 0, 0], + "to": [9, 16, 7], + "faces": { + "bottom": { "texture": "#edge", "cullface": "bottom" }, + "top": { "texture": "#edge", "cullface": "top" }, + "north": { "texture": "#edge", "cullface": "north" }, + "west": { "texture": "#pane" }, + "east": { "texture": "#pane" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_glass_pane_side_alt.json b/mods/bworld/models/templates/template_glass_pane_side_alt.json new file mode 100644 index 0000000..7682e73 --- /dev/null +++ b/mods/bworld/models/templates/template_glass_pane_side_alt.json @@ -0,0 +1,19 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_glass_pane_side_alt", + "elements": [ + { + "from": [7, 0, 9], + "to": [9, 16, 16], + "faces": { + "bottom": { "texture": "#edge", "cullface": "bottom" }, + "top": { "texture": "#edge", "cullface": "top" }, + "south": { "texture": "#edge", "cullface": "south" }, + "west": { "texture": "#pane" }, + "east": { "texture": "#pane" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_wall_post.json b/mods/bworld/models/templates/template_wall_post.json new file mode 100644 index 0000000..d34efa2 --- /dev/null +++ b/mods/bworld/models/templates/template_wall_post.json @@ -0,0 +1,20 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_wall_post", + "elements": [ + { + "from": [4, 0, 4], + "to": [12, 16, 12], + "faces": { + "bottom": { "texture": "#wall", "cullface": "bottom" }, + "top": { "texture": "#wall", "cullface": "top" }, + "north": { "texture": "#wall" }, + "south": { "texture": "#wall" }, + "west": { "texture": "#wall" }, + "east": { "texture": "#wall" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_wall_side.json b/mods/bworld/models/templates/template_wall_side.json new file mode 100644 index 0000000..f2e14f5 --- /dev/null +++ b/mods/bworld/models/templates/template_wall_side.json @@ -0,0 +1,19 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_wall_side", + "elements": [ + { + "from": [5, 0, 0], + "to": [11, 14, 8], + "faces": { + "bottom": { "texture": "#wall", "cullface": "bottom" }, + "top": { "texture": "#wall" }, + "north": { "texture": "#wall", "cullface": "north" }, + "west": { "texture": "#wall" }, + "east": { "texture": "#wall" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/template_wall_side_tall.json b/mods/bworld/models/templates/template_wall_side_tall.json new file mode 100644 index 0000000..9a56a61 --- /dev/null +++ b/mods/bworld/models/templates/template_wall_side_tall.json @@ -0,0 +1,19 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:template_wall_side_tall", + "elements": [ + { + "from": [5, 0, 0], + "to": [11, 16, 8], + "faces": { + "bottom": { "texture": "#wall", "cullface": "bottom" }, + "top": { "texture": "#wall", "cullface": "top" }, + "north": { "texture": "#wall", "cullface": "north" }, + "west": { "texture": "#wall" }, + "east": { "texture": "#wall" } + } + } + ] + } +} diff --git a/mods/bworld/models/templates/wall_inventory.json b/mods/bworld/models/templates/wall_inventory.json new file mode 100644 index 0000000..20c382a --- /dev/null +++ b/mods/bworld/models/templates/wall_inventory.json @@ -0,0 +1,32 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:wall_inventory", + "elements": [ + { + "from": [4, 0, 4], + "to": [12, 16, 12], + "faces": { + "bottom": { "texture": "#wall", "cullface": "bottom" }, + "top": { "texture": "#wall", "cullface": "top" }, + "north": { "texture": "#wall" }, + "south": { "texture": "#wall" }, + "west": { "texture": "#wall" }, + "east": { "texture": "#wall" } + } + }, + { + "from": [5, 0, 0], + "to": [11, 13, 16], + "faces": { + "bottom": { "texture": "#wall" }, + "top": { "texture": "#wall" }, + "north": { "texture": "#wall", "cullface": "north" }, + "south": { "texture": "#wall", "cullface": "south" }, + "west": { "texture": "#wall" }, + "east": { "texture": "#wall" } + } + } + ] + } +} diff --git a/tests/importer_test.ts b/tests/importer_test.ts index 526fc93..18c3441 100644 --- a/tests/importer_test.ts +++ b/tests/importer_test.ts @@ -3,7 +3,7 @@ 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 type { ModelFileJson } from "$/common/block_models.ts"; import { import_models } from "$/tools/importer/models.ts"; import { convert_mcmeta, import_textures } from "$/tools/importer/textures.ts"; @@ -18,7 +18,7 @@ function resources(models: Record, namespace = "gears"): string return root; } -function convert(models: Record, path: string): ModelJson { +function convert(models: Record, path: string): ModelFileJson { const root = resources(models); const report = import_models(`${root}/assets/gears/models/${path}.json`); assertEquals(report.errors, []); @@ -47,65 +47,66 @@ Deno.test("a java block model becomes a bworld model that passes its checks", () assertEquals(validate_model(model), []); // folders are joined into the id, the way textures in subfolders are named assertEquals(model.id, "gears:block_gear"); - assertEquals(model.textures, { "0": "gears:block_gear" }); - const [hub] = model.elements; + // particle comes along too, since some models draw faces with it + assertEquals(model.textures, { "0": "gears:block_gear", particle: "gears:block_gear" }); + const [hub] = model.elements!; assertEquals(Object.keys(hub.faces).sort(), ["bottom", "north", "top"]); assertEquals(hub.faces.top, { texture: "#0", uv: [0, 0, 8, 8], cullface: "top" }); assertEquals(hub.faces.north?.rotation, 90); assertEquals(hub.rotation, { origin: [8, 8, 8], axis: "y", angle: 22.5 }); }); -Deno.test("a model gets its parents' elements and textures, its own textures winning", () => { +Deno.test("a model keeps its parent, which bworld merges in when it loads", () => { const model = convert({ "block/gear": GEAR, "block/gear_brass": { parent: "gears:block/gear", textures: { "0": "gears:block/brass_gear" } }, }, "block/gear_brass"); - assertEquals(model.textures, { "0": "gears:block_brass_gear" }); - assertEquals(model.elements.length, GEAR.elements.length); + assertEquals(model, { + id: "gears:block_gear_brass", + parent: "gears:block_gear", + textures: { "0": "gears:block_brass_gear" }, + }); }); -Deno.test("vanilla parents like cube_all and stairs convert without minecraft's files", () => { +Deno.test("minecraft's template parents become the base game's, and others need a remap", () => { const cube = convert( { "block/casing": { parent: "minecraft:block/cube_all", textures: { all: "block/stone" } } }, "block/casing", ); - assertEquals(validate_model(cube), []); - assertEquals(Object.keys(cube.elements[0].faces).length, 6); + assertEquals(cube.parent, "bworld:cube_all"); // minecraft's block textures are taken to be the base game's of the same name assertEquals(cube.textures?.all, "bworld:stone"); + assertEquals(convert({ "block/steps": { parent: "block/stairs" } }, "block/steps").parent, "bworld:stairs"); - const stairs = convert({ - "block/stairs": { - parent: "block/stairs", - textures: { top: "gears:block/a", bottom: "gears:block/a", side: "gears:block/a" }, - }, - }, "block/stairs"); - assertEquals(validate_model(stairs), []); - assert(stairs.elements.length > 1); + const root = resources({ "block/stand": { parent: "block/lectern" } }); + const report = import_models(`${root}/assets/gears/models/block/stand.json`); + assertStringIncludes(report.errors[0].problems[0], "--remap"); }); -Deno.test("a folder converts into the same folders, with models that are only parents left out", () => { +Deno.test("a folder converts into the same folders, models only there to be parents included", () => { const root = resources({ "block/gear": GEAR, "block/large/gear": { parent: "gears:block/gear" }, + // block/block only holds display transforms, so this keeps its textures and nothing else "block/template": { parent: "block/block", textures: { "0": "gears:block/gear" } }, }); const output = Deno.makeTempDirSync(); const report = import_models(root, { output }); assertEquals(report.errors, []); - assertEquals(report.parents, ["gears:block/template"]); - for (const path of ["block/gear", "block/large/gear"]) { + for (const path of ["block/gear", "block/large/gear", "block/template"]) { const json = JSON.parse(Deno.readTextFileSync(`${output}/${path}.json`)); assertEquals(json.format_version, 1); assertEquals(validate_model(json.model), []); } + assertEquals(JSON.parse(Deno.readTextFileSync(`${output}/block/template.json`)).model.parent, undefined); }); Deno.test("models that can't be converted are reported, not written", () => { const root = resources({ "block/obj": { loader: "forge:obj", model: "gears:models/block/thing.obj" }, "item/ingot": { parent: "item/generated", textures: { layer0: "gears:item/ingot" } }, - "block/orphan": { parent: "gears:block/nowhere" }, + // a sprite's child is a sprite too + "item/shiny_ingot": { parent: "gears:item/ingot" }, "block/tilted": { ...GEAR, elements: [{ ...GEAR.elements[0], rotation: { angle: 30, axis: "x", origin: [8, 8, 8] } }], @@ -116,9 +117,12 @@ Deno.test("models that can't be converted are reported, not written", () => { }); const output = Deno.makeTempDirSync(); const report = import_models(root, { output }); - assertEquals(report.skipped.map(({ location }) => location).sort(), ["gears:block/obj", "gears:item/ingot"]); + assertEquals(report.skipped.map(({ location }) => location).sort(), [ + "gears:block/obj", + "gears:item/ingot", + "gears:item/shiny_ingot", + ]); const errors = Object.fromEntries(report.errors.map(({ location, problems }) => [location, problems.join(" ")])); - assertStringIncludes(errors["gears:block/orphan"], "gears:block/nowhere"); assertStringIncludes(errors["gears:block/tilted"], "30"); assertStringIncludes(errors["gears:block/a_b"] ?? errors["gears:block/a/b"], "--remap"); assertEquals(report.written.length, 1); @@ -131,7 +135,7 @@ Deno.test("--remap renames locations before they become ids", () => { }); const model = JSON.parse(report.written[0].text!).model; assertEquals(model.id, "cogs:big_gear"); - assertEquals(model.textures, { "0": "cogs:gear" }); + assertEquals(model.textures, { "0": "cogs:gear", particle: "cogs:gear" }); }); // a png with only the header, which is all that's read to size it diff --git a/tests/model_parents_test.ts b/tests/model_parents_test.ts new file mode 100644 index 0000000..9f5ec75 --- /dev/null +++ b/tests/model_parents_test.ts @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { assert, assertEquals } from "@std/assert"; +import { BUILTIN_MODELS, type ModelJson, resolve_models, resolve_texture } from "$/common/block_models.ts"; +import { EverythingRegistry } from "$/common/everything_registry.ts"; +import { load_and_check } from "$/tools/check_mods.ts"; +import { create_mod } from "$/tools/new_mod.ts"; +import { copy_dir, test_game } from "./helpers.ts"; + +const BOX = { from: [0, 0, 0], to: [16, 8, 16], faces: { top: { texture: "#top" } } } as ModelJson["elements"][0]; + +Deno.test("a model gets its parent's elements and textures, with its own textures and elements winning", () => { + const { models, problems } = resolve_models([ + { id: "a:base", textures: { top: "a:stone", side: "a:stone" }, elements: [BOX] }, + { id: "a:brass", parent: "a:base", textures: { top: "a:brass" } }, + { id: "a:tall", parent: "a:brass", elements: [BOX, BOX] }, + ], () => undefined); + assertEquals(problems, []); + const [, brass, tall] = models; + assertEquals(brass, { id: "a:brass", textures: { top: "a:brass", side: "a:stone" }, elements: [BOX] }); + // its parent's parent counts too + assertEquals(tall.textures, { top: "a:brass", side: "a:stone" }); + assertEquals(tall.elements.length, 2); +}); + +Deno.test("a parent can be another mod's model or a built-in one", () => { + const earlier: Record = { "base:slab": { id: "base:slab", elements: [BOX] } }; + const { models, problems } = resolve_models([ + { id: "a:slab", parent: "base:slab", textures: { top: "a:top" } }, + { id: "a:cross", parent: "engine:cross" }, + ], (id) => BUILTIN_MODELS[id] ?? earlier[id]); + assertEquals(problems, []); + assertEquals(models[0].elements, [BOX]); + assertEquals(models[1].elements, BUILTIN_MODELS["engine:cross"].elements); +}); + +Deno.test("a missing parent and parents that loop are problems, and the models still resolve", () => { + const { models, problems } = resolve_models([ + { id: "a:orphan", parent: "a:nowhere", elements: [BOX] }, + { id: "a:one", parent: "a:two" }, + { id: "a:two", parent: "a:one" }, + ], () => undefined); + assertEquals(models.length, 3); + assertEquals(models[0].elements, [BOX]); + assertEquals(problems.map(({ id }) => id).sort(), ["a:one", "a:orphan", "a:two"]); + assert(problems.find(({ id }) => id === "a:one")!.problem.includes("loop")); +}); + +// mods/bworld and a mod made from the template, with models added to it +function mods_with(models: Record) { + const dir = Deno.makeTempDirSync({ prefix: "bworld_parents_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + create_mod("copper_tools", "Copper Tools", dir); + Deno.mkdirSync(`${dir}/copper_tools/models`, { recursive: true }); + for (const [name, model] of Object.entries(models)) { + Deno.writeTextFileSync(`${dir}/copper_tools/models/${name}.json`, JSON.stringify({ format_version: 1, model })); + } + return dir; +} + +Deno.test("a mod's model can use the base game's templates as its parent", async () => { + const dir = mods_with({ + pillar: { id: "copper_tools:pillar", parent: "bworld:cube_column", textures: { end: "bworld:oak_log_top" } }, + }); + await test_game(dir); + const model = EverythingRegistry.get("models", "copper_tools:pillar")!; + assertEquals(Object.keys(model.elements[0].faces).length, 6); + // the cube's six variables lead through cube_column's to the textures a block gives + const faces = model.elements[0].faces; + assertEquals(resolve_texture(faces.top!.texture, { side: "a:bark" }, model), "bworld:oak_log_top"); + assertEquals(resolve_texture(faces.north!.texture, { side: "a:bark" }, model), "a:bark"); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("check-mods reports a parent that doesn't exist and parents that loop", () => { + const dir = mods_with({ + orphan: { id: "copper_tools:orphan", parent: "copper_tools:nowhere" }, + one: { id: "copper_tools:one", parent: "copper_tools:two" }, + two: { id: "copper_tools:two", parent: "copper_tools:one" }, + }); + const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n"); + assert(errors.includes("model copper_tools:nowhere doesn't exist"), errors); + assert(errors.includes("copper_tools:one's parents loop"), errors); + Deno.removeSync(dir, { recursive: true }); +}); diff --git a/tools/importer.ts b/tools/importer.ts index 268db39..3eba444 100644 --- a/tools/importer.ts +++ b/tools/importer.ts @@ -25,7 +25,7 @@ options: --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//, 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 + --parents FOLDER another folder to follow parent models through, 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`; @@ -71,9 +71,8 @@ function print_report(report: ImportReport) { 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( - `${converted} converted, ${parents}${report.skipped.length} skipped, ${report.errors.length} with errors`, + `${converted} converted, ${report.skipped.length} skipped, ${report.errors.length} with errors`, ); } diff --git a/tools/importer/models.ts b/tools/importer/models.ts index d7a5ba6..a567bf1 100644 --- a/tools/importer/models.ts +++ b/tools/importer/models.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// java block models (assets//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"; +// java block models (assets//models/**.json) to bworld's models/. the formats are close: faces are top and +// bottom instead of up and down, ids lose their folders, a parent keeps being a parent (bworld merges them when it +// loads, see resolve_models), and what bworld has no use for (blockbench's names, display transforms) is left out +import type { ModelElementJson, ModelFace, ModelFaceJson, ModelFileJson } from "$/common/block_models.ts"; import { FORMAT_VERSION } from "$/common/mod_data.ts"; import { join } from "@std/path"; import { @@ -25,15 +25,12 @@ import { 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 | 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: "model"; id: string; json: { format_version: number; model: ModelFileJson }; warnings: string[] } | { kind: "skipped"; reason: string } | { kind: "error"; problems: string[] }; @@ -47,18 +44,30 @@ const FACE_NAMES: Record = { }; const ANGLES = [-45, -22.5, 0, 22.5, 45]; -interface Flat { - textures: Record; - elements?: unknown[]; - loader?: string; - render_type?: string; - not_boxes?: string; +// item models that are a flat sprite or drawn by code, not boxes, and so is anything that has one as a parent +const NOT_BOXES: Record = { + "minecraft:item/generated": "an item sprite", + "minecraft:item/handheld": "an item sprite", + "minecraft:item/barrier": "an item sprite", + "minecraft:builtin/generated": "an item sprite", + "minecraft:builtin/entity": "drawn by code", +}; +// minecraft's roots, which hold nothing a bworld model can use: block/block is only display transforms +const EMPTY_PARENTS = ["minecraft:block/block", "minecraft:block/air"]; + +// whether a model holds nothing a bworld model can use, all the way up its parents, like block/block or a mod's own +// root of display transforms. a model with one as its parent leaves it out, since it isn't written +function is_empty(location: string, read: ModelSource, seen = new Set()): boolean { + if (EMPTY_PARENTS.includes(location)) return true; + const json = read(location); + if (!json || seen.has(location) || json.elements !== undefined) return false; + if (Object.keys((json.textures ?? {}) as Record).length > 0) return false; + seen.add(location); + return typeof json.parent !== "string" || is_empty(location_string(parse_location(json.parent)), read, seen); } -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 +// converts one model, or every model in a folder. other models are only read to tell whether a model is really a +// sprite or made by code: its parents can be anywhere in the same roots or in options.parents export function import_models(input: string, options: ImportOptions = {}): ImportReport { const remaps = options.remaps ?? DEFAULT_REMAPS; const single = is_file(input); @@ -93,8 +102,7 @@ export function import_models(input: string, options: ImportOptions = {}): Impor 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 }); + 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 }); @@ -110,20 +118,16 @@ export function import_models(input: string, options: ImportOptions = {}): Impor } 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 json = read(location_string(parse_location(location))); + if (!json) return { kind: "error", problems: [`${location} wasn't found`] }; + const made = made_by(location, read); + if (made) return { kind: "skipped", reason: made }; const problems: string[] = []; const warnings = new Set(); - if (flat.render_type) warnings.add(`render_type "${flat.render_type}" was left out, set the block's render layer`); + if (typeof json.render_type === "string") { + warnings.add(`render_type "${json.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); @@ -131,48 +135,52 @@ export function convert_model(location: string, read: ModelSource, remaps: Remap return id; }; - const elements = flat.elements.map((element, i) => - convert_element(element, `elements[${i}]`, texture, problems, warnings) + let parent: string | undefined; + if (typeof json.parent === "string") { + const from = location_string(parse_location(json.parent)); + if (!is_empty(from, read)) { + parent = to_id(from, remaps.models); + if (parent.startsWith("minecraft:")) { + problems.push(`its parent ${from} is minecraft's, and no --remap names a bworld model for it`); + } + } + } + // every variable comes along, since it may be filling in a parent's faces. even "particle": some models draw with it + const textures = Object.fromEntries( + Object.entries((json.textures ?? {}) as Record) + .map(([name, value]) => [name, texture(value, `textures.${name}`)]), ); - - // only the variables faces reach, so particle textures and ones children overrode don't come along - const textures: Record = {}; - 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 elements = Array.isArray(json.elements) + ? json.elements.map((element, i) => convert_element(element, `elements[${i}]`, texture, problems, warnings)) + : undefined; + if (parent === undefined && elements === undefined && Object.keys(textures).length === 0) { + return { kind: "skipped", reason: "it has nothing a bworld model holds, like only display transforms" }; } 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 }; + const model: ModelFileJson = { + id, + ...(parent !== undefined ? { parent } : {}), + ...(Object.keys(textures).length > 0 ? { textures } : {}), + ...(elements !== undefined ? { 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`, - ); +// why a model isn't boxes bworld can draw, going up its parents: an item sprite, or one a loader makes (obj files, +// composites). undefined for boxes, or when its parents can't be followed, which check-mods then reports +function made_by(location: string, read: ModelSource): string | undefined { + const seen = new Set(); + for (let at: string | undefined = location_string(parse_location(location)); at && !seen.has(at);) { + seen.add(at); + if (NOT_BOXES[at]) return `${NOT_BOXES[at]} (${at})`; + const json = read(at); + if (typeof json?.loader === "string") return `it uses the "${json.loader}" loader`; + at = typeof json?.parent === "string" ? location_string(parse_location(json.parent)) : undefined; } - 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 | 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, - }; + return undefined; } function convert_element( diff --git a/tools/importer/resources.ts b/tools/importer/resources.ts index 7022605..57a4aae 100644 --- a/tools/importer/resources.ts +++ b/tools/importer/resources.ts @@ -35,9 +35,21 @@ export interface Remaps { export const DEFAULT_REMAPS: Remaps = { textures: { "minecraft:block/": "bworld:", "minecraft:item/": "bworld:" }, - models: {}, + models: template_remaps(), }; +// 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 = {}): Location { const full = location_string(parse_location(location)); for (const from of Object.keys(remap).sort((a, b) => b.length - a.length)) { @@ -192,15 +204,13 @@ export interface Written { 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: [] }; + 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 diff --git a/tools/importer/vanilla_models.ts b/tools/importer/vanilla_models.ts deleted file mode 100644 index fb506ef..0000000 --- a/tools/importer/vanilla_models.ts +++ /dev/null @@ -1,128 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// the vanilla parent models mods build on, so their models convert without minecraft's own files: cubes, slabs, -// stairs, walls and panes. each is boxes with texture variables for the children to fill in. faces leave out uv, which -// then comes from where the face is on the block, as it does in java -type Side = "down" | "up" | "north" | "south" | "west" | "east"; -type Faces = Partial>; -type Model = Record; - -const SIDES: Side[] = ["down", "up", "north", "south", "west", "east"]; - -// a box whose faces are given as "#texture", with "!" in front for one hidden by a solid neighbor on that side -function box(from: number[], to: number[], faces: Faces, rotations: Partial> = {}) { - return { - from, - to, - faces: Object.fromEntries( - Object.entries(faces).map(([side, texture]) => [side, { - texture: texture.replace("!", ""), - ...(texture.startsWith("!") ? { cullface: side } : {}), - ...(rotations[side as Side] ? { rotation: rotations[side as Side] } : {}), - }]), - ), - }; -} - -const all = (texture: (side: Side) => string): Faces => Object.fromEntries(SIDES.map((side) => [side, texture(side)])); -const sides = (top: string, bottom: string, side: string) => - all((s) => s === "up" ? top : s === "down" ? bottom : side); - -// a full cube's faces, all hidden by solid neighbors -const cube_faces = all((side) => `!#${side}`); -const slab = box([0, 0, 0], [16, 8, 16], { ...all((side) => `!#side`), down: "!#bottom", up: "#top" }); -// the stairs' step is the back (east) half, the way they face with no turn -const step = (from: number[], to: number[], culled: Side[]) => - box(from, to, { - ...Object.fromEntries( - (["up", "north", "south", "west", "east"] as Side[]).map(( - side, - ) => [side, side === "up" ? "#top" : "#side"]), - ), - ...Object.fromEntries(culled.map((side) => [side, side === "up" ? "!#top" : "!#side"])), - }); -const wall_post = box([4, 0, 4], [12, 16, 12], { ...all(() => "#wall"), down: "!#wall", up: "!#wall" }); -const wall_side = (height: number) => - box([5, 0, 0], [11, height, 8], { - down: "!#wall", - up: height === 16 ? "!#wall" : "#wall", - north: "!#wall", - west: "#wall", - east: "#wall", - }); - -export const VANILLA_MODELS: Record = { - "minecraft:block/block": {}, - "minecraft:block/air": {}, - "minecraft:block/cube": { elements: [box([0, 0, 0], [16, 16, 16], cube_faces)] }, - "minecraft:block/cube_all": { parent: "block/cube", textures: all(() => "#all") }, - "minecraft:block/cube_column": { parent: "block/cube", textures: sides("#end", "#end", "#side") }, - "minecraft:block/cube_bottom_top": { parent: "block/cube", textures: sides("#top", "#bottom", "#side") }, - "minecraft:block/orientable_with_bottom": { - parent: "block/cube", - textures: { ...sides("#top", "#bottom", "#side"), north: "#front" }, - }, - "minecraft:block/orientable": { parent: "block/orientable_with_bottom", textures: { bottom: "#top" } }, - // a column lying along north to south, its sides turned so their grain runs the same way - "minecraft:block/cube_column_horizontal": { - elements: [box( - [0, 0, 0], - [16, 16, 16], - { down: "!#side", up: "!#side", north: "!#end", south: "!#end", west: "!#side", east: "!#side" }, - { down: 180, west: 270, east: 90 }, - )], - }, - "minecraft:block/slab": { elements: [slab] }, - "minecraft:block/slab_top": { - elements: [box([0, 8, 0], [16, 16, 16], { ...all(() => "!#side"), down: "#bottom", up: "!#top" })], - }, - "minecraft:block/stairs": { elements: [slab, step([8, 8, 0], [16, 16, 16], ["up", "north", "south", "east"])] }, - "minecraft:block/inner_stairs": { - elements: [ - slab, - step([8, 8, 0], [16, 16, 16], ["up", "north", "south", "east"]), - step([0, 8, 8], [8, 16, 16], ["up", "south", "west"]), - ], - }, - "minecraft:block/outer_stairs": { elements: [slab, step([8, 8, 8], [16, 16, 16], ["up", "south", "east"])] }, - "minecraft:block/template_wall_post": { elements: [wall_post] }, - "minecraft:block/template_wall_side": { elements: [wall_side(14)] }, - "minecraft:block/template_wall_side_tall": { elements: [wall_side(16)] }, - "minecraft:block/wall_inventory": { - elements: [ - wall_post, - box([5, 0, 0], [11, 13, 16], { ...all(() => "#wall"), north: "!#wall", south: "!#wall" }), - ], - }, - "minecraft:block/template_glass_pane_post": { - elements: [box([7, 0, 7], [9, 16, 9], { down: "!#edge", up: "!#edge" })], - }, - "minecraft:block/template_glass_pane_side": { - elements: [ - box([7, 0, 0], [9, 16, 7], { down: "!#edge", up: "!#edge", north: "!#edge", west: "#pane", east: "#pane" }), - ], - }, - "minecraft:block/template_glass_pane_side_alt": { - elements: [ - box([7, 0, 9], [9, 16, 16], { - down: "!#edge", - up: "!#edge", - south: "!#edge", - west: "#pane", - east: "#pane", - }), - ], - }, - "minecraft:block/template_glass_pane_noside": { elements: [box([7, 0, 7], [9, 16, 9], { north: "#pane" })] }, - "minecraft:block/template_glass_pane_noside_alt": { elements: [box([7, 0, 7], [9, 16, 9], { east: "#pane" })] }, -}; - -// item models that are a flat sprite or drawn by code, not boxes -export const NOT_BOXES: Record = { - "minecraft:item/generated": "an item sprite", - "minecraft:item/handheld": "an item sprite", - "minecraft:item/barrier": "an item sprite", - "minecraft:builtin/generated": "an item sprite", - "minecraft:builtin/entity": "drawn by code", -};