From 355e7a21ca4bd144919a5bfaca0a0f98e8d0d560 Mon Sep 17 00:00:00 2001 From: Paula Date: Mon, 12 Oct 2026 17:22:50 -0300 Subject: [PATCH] Importer --- CLAUDE.md | 1 + CREATE.md | 548 +++++++++++++++++++++++++++++++ deno.json | 1 + tests/importer_test.ts | 134 ++++++++ tools/importer.ts | 210 ++++++++++++ tools/importer/models.ts | 165 ++++++++++ tools/importer/resources.ts | 155 +++++++++ tools/importer/vanilla_models.ts | 128 ++++++++ 8 files changed, 1342 insertions(+) create mode 100644 CREATE.md create mode 100644 tests/importer_test.ts create mode 100644 tools/importer.ts create mode 100644 tools/importer/models.ts create mode 100644 tools/importer/resources.ts create mode 100644 tools/importer/vanilla_models.ts diff --git a/CLAUDE.md b/CLAUDE.md index 0307d43..ae5d20d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,6 +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 ``` Tests load mods straight from `mods/` through `test_game` in `tests/helpers.ts`, so they don't need a build. Run diff --git a/CREATE.md b/CREATE.md new file mode 100644 index 0000000..aab11db --- /dev/null +++ b/CREATE.md @@ -0,0 +1,548 @@ +# Create + +A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics, processing, logistics, fluids, +redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as +possible, and to stay fast on both the server and the client when a world has thousands of moving parts. + +Nothing here is built yet. Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts +about bworld from its source. + +## Sources + +| Copy | Version | Used for | +| -------------------- | ------- | -------------------------------------------------------------------------------------------------------------------- | +| `ports/create1.21.1` | 6.0.11 | **All code and data**: mechanics, numbers, recipes, tags, worldgen, ponder scripts | +| `ports/create1.19.3` | 0.5.0.j | **Textures, models, blockstates, sounds and ponder scenes** from its `assets/` and `src/generated/resources/assets/` | + +0.5.0.j shipped with only an MIT `LICENSE`, so its assets are used under that, with the MIT notice in +`mods/create/CREDITS.md`. 6.0.11's `assets/` folder isn't in the copy and isn't used. + +**Keep the art removable.** Everything from 0.5.0.j's assets is written by the importer (below) into +`mods/create/textures/` and `mods/create/models/`, and nothing else in the mod depends on a specific file being there. +Removing the art is then deleting those two folders and re-running the importer with `--no-assets`. That writes +placeholder models (a plain cube, or the block's shape) and a placeholder texture, and the mod still loads and plays. + +**Content newer than 0.5.0.j has no art to take**, so it needs new art either way. These are the blocks and items 6.0.11 +registers that 0.5.0.j doesn't: the package logistics (`packager`, `repackager`, `package_frogport`, `stock_ticker`, +`stock_link`, `redstone_requester`, `factory_gauge`, `package_filter`, `item_hatch`, `chain_conveyor`, cardboard and its +blocks and armor, table cloths, `shopping_list`), `large_water_wheel`, `elevator_pulley`, `elevator_contact`, +`contraption_controls`, `mechanical_roller`, the copycats, `clipboard`, `desk_bell`, `pulse_timer`, metal doors and +scaffolding, `andesite_alloy_block`, `industrial_iron_block`, `weathered_iron_block`, `experience_block`, netherite +diving gear. The importer lists them in its report. + +## How Big Create Is + +6.0.11 is 2017 Java files, about 275,000 lines. By part: + +| Part | Lines | What | +| --------------------------- | ------ | ------------------------------------------------------------------------------- | +| `content/kinetics` | 36,000 | Shafts, cogs, gearboxes, generators, belts, and the machines that use rotation | +| `infrastructure` | 33,000 | Config, datagen, ponder scenes, commands | +| `content/trains` | 30,000 | Tracks, the track graph, signals, stations, schedules, train entities | +| `content/logistics` | 30,000 | Funnels, tunnels, chutes, depots, vaults, filters, and 6.0's packages | +| `content/contraptions` | 27,000 | Moving block structures: bearings, pistons, pulleys, gantries, actors | +| `content/equipment` | 17,000 | Wrench, goggles, potato cannon, backtank, toolbox, symmetry wand | +| `content/redstone` | 12,000 | Links, nixie tubes, display links, threshold switch, diodes | +| `content/fluids` | 12,000 | Pipes, pumps, tanks, spouts, drains, hose pulley, boilers | +| `compat` | 10,000 | Other mods. Only the JEI part matters, for the recipe viewer | +| `content/decoration` | 7,000 | Palettes, copycats, girders, sliding doors, placards | +| `content/schematics` | 7,000 | Schematic table, schematicannon | +| `content/processing` | 5,000 | Basin, blaze burner, sequenced assembly, the processing recipe base | +| `foundation`, `api`, `impl` | 40,000 | Block entity behaviours, connected textures, GUI, networking, rendering helpers | + +Data in 6.0.11: 188 blocks and 60 items registered one by one (plus generated families like palettes), and 1881 recipes +in 19 types. Art in 0.5.0.j: 1043 generated and 573 hand-made block models, 1006 textures, 92 connected texture sheets, +153 ponder scenes. + +A straight line-by-line translation would be most of a year of work and would carry over things bworld doesn't need, +like datagen, mixins, compat and Forge plumbing. The plan below is built to avoid that. + +## Strategy + +Six rules that keep the work small: + +1. **Import data, don't hand-write it.** One tool converts Create's models, textures, blockstates, recipes, tags, loot, + names and worldgen into bworld's formats, and reports what it couldn't convert. Hundreds of blocks then cost the same + as one, and re-running it after a fix redoes all of them. This replaces Create's datagen entirely. +2. **Port Create's architecture onto bworld's, not its classes.** Create builds every machine from a few shared pieces + (block entity behaviours, a rotation network, processing recipes, instance types). Each piece becomes one bworld + piece, and then the machines are mostly data plus a little code (see [Architecture](#architecture)). +3. **Put general features in the engine, once.** Block capabilities, fluids, redstone, instanced rendering and moving + block structures are things any mod could use. They go in the engine shaped like NeoForge's (check `ports/neoforge`), + and Create is their first user. +4. **Change-driven server work.** Rotation, pipes and belts are networks that only recompute when something in them + changes. Blocks that have nothing to do don't tick. +5. **GPU-driven animation.** A turning part is uploaded once with its axis, speed and offset, and the vertex shader + turns it from the time, like Create's `rotating` instance type. Nothing is sent or computed per frame for something + that turns at a steady speed. +6. **Playable in phases.** Each phase ends with something to use in a world and tests passing, in an order where every + phase only needs the ones before it. + +## The Importer + +A generic tool for any Minecraft Java mod, `tools/importer.ts`, not one for Create. It converts one kind of resource at +a time, from a single file or a whole folder: + +```sh +deno run -A tools/importer.ts model MODEL.json --output PATH # one model, printed without --output +deno run -A tools/importer.ts model path/to/resources --output DIR # every assets//models in it +``` + +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. + +**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 +pure function of the location, so every kind agrees on ids without sharing state: a blockstate pointing at a model +writes the same id the model was written with. Two locations that join to the same id are an error, fixed with +`--remap`. + +**Remaps** are prefix rules, longest first: `{ "textures": { "minecraft:block/": "bworld:" }, "models": {} }`. Mapping +Minecraft's block and item textures to the base game's of the same name is the default. A mod's remap file is where its +vanilla ids go, and later kinds add sections for items, blocks and fluids. + +**Kinds:** + +| 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 | | +| `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 | | +| `tag` | `data/*/tags/**.json` | `tags/`, `c:` tags merged with bworld's | | +| `loot` | `data/*/loot_table(s)/**.json` | `drops`, or loot tables | | +| `worldgen` | `data/*/worldgen/**.json` | `worldgen/`: ores, and features where bworld has them | | +| `sound` | `assets/*/sounds.json`, `sounds/**.ogg` | sounds, once the engine has them (S8) | | +| `mod` | all of the above | a whole mod folder with a manifest, and one report | | + +Block properties (shape, tool, toughness) aren't in any data file: Java mods set them in code. `mod` writes a block for +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. + +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. + +**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. + +**Vanilla ids in recipes.** Create's recipes use 447 distinct Minecraft ids, like dyes, `minecraft:cobblestone` and +`minecraft:netherrack`. The remap file maps each to a bworld id or to `null`. A recipe with a `null` or unmapped id is +skipped and listed in the report, so the table can grow over time and the report always says how much of Create is +missing because bworld lacks something. + +## Architecture + +How each of Create's shared pieces lands in bworld: + +| Create | bworld | +| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SmartBlockEntity` and its `BlockEntityBehaviour`s | A block with several components. Each behaviour (filtering, scroll value, inventory, fluid tank, transported items) is one reusable `create:` component with params | +| `lazyTick` (every N ticks) | A counter in the component, or `on_second` | +| `sendData` / `getUpdateTag` | Client-visible tile data (R1) | +| `BlockEntityRenderer` and Flywheel `Visual`s | Block visuals (R2) drawing instances (R3) | +| `AllPartialModels` | Models in `models/` used by visuals, not blocks (R4) | +| `AllInstanceTypes`: rotating, scrolling, scrolling transformed, fluid | Engine instance types (R3) | +| `RotationPropagator`, `KineticNetwork` | `scripts/kinetics/` | +| NeoForge capabilities (`IItemHandler`, `IFluidHandler`) | Block capabilities (S1, S2) | +| `ProcessingRecipe` and its 19 types | Custom recipe types parsed in one place (`scripts/recipes/`) | +| `AbstractContraptionEntity`, `Contraption` | Engine block structure entities (S6) and the mod's assembly code | +| `AllPackets` | Mod channels | +| Menus and screens | Menus and screens, which bworld has | +| `AllConfigs` | `mods/create/config.json`, read in `setup` (S12) | +| Registrate, datagen | The importer | +| Mixins | Engine hooks, only where an engine feature isn't worth adding | +| Ponder | A scene player (P13) | +| `compat/jei` | Recipe viewer categories (R11) | + +Server code is laid out by subsystem, each a folder with no `ctx` in its core logic so tests can call it directly: + +``` +mods/create/scripts/ + server.ts shared.ts client.ts worldgen.ts + kinetics/ connections, spreading, stress, generators + processing/ press, mixer, millstone, crushing, saw, fan, deployer, crafter, basin, burner, sequenced assembly + logistics/ belts, funnels, tunnels, chutes, depots, arm, vaults, filters, packages + fluids/ pipes, pumps, tanks, spouts, drains, hose pulley, boilers + redstone/ links, nixie tubes, display links, diodes, observers + contraptions/ assembly, movement, actors, controls + trains/ track graph, signals, stations, schedules, train movement + equipment/ wrench, goggles, potato cannon, backtank, toolbox, symmetry wand + recipes/ parsing every Create recipe type + visuals/ client visuals for each block that moves +``` + +## Engine Work + +Everything here is general, and none of it mentions Create. Each line says which phase first needs it. + +### Rendering + +**R1. Client-visible tile data** (P1). A component marks part of a block's tile data for clients, sent with the chunk +and again when it changes. Like NeoForge's `getUpdateTag`, but per field, so a fast-changing field doesn't resend the +rest. The display item (`set_block_item`, `ClientLevel.block_items`) moves onto it, so there's one way to sync block +data. + +**R2. Block visuals** (P1). `ctx.render.register_visual(block_id, factory)` in client scripts. A visual is created when +its chunk is meshed, updated when the block's client data or states change, and deleted with the block or chunk, like +Flywheel's `Visual`. Most visuals only create instances and update them on change. A visual that has to animate on the +CPU (a crank easing in, a press head) asks for a per-frame callback, like `DynamicVisual`. The engine keeps visuals per +chunk and skips whole chunks outside the frustum. + +**R3. Instanced drawing** (P1). A WebGPU pipeline that draws one model many times from an instance buffer, the thing +bworld has none of today (`client/renderer/core.ts` only batches vertices). The instance types, matching Create's: + +| Type | Per instance | Shader | +| ------------- | ------------------------------------------ | ----------------------------------------------------------------------- | +| `transformed` | a matrix, light, tint | moves the model | +| `rotating` | position, axis, rpm, offset, light, tint | turns the model around its axis by `ticks × rpm × 0.3 + offset` degrees | +| `scrolling` | position, rotation, uv scroll speed, light | scrolls the texture coordinates, for belts | +| `fluid` | box, fluid texture, fill, light | a box of a fluid's texture, for tanks and pipes | + +Instances are grouped by model and type, and each group is one draw call. Light is packed per instance from the block's +light, updated when that light changes. `rotating` is the important one: thousands of shafts at a steady speed cost +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: + +- `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; +- item models from model JSON (3D items in the hand and the GUI, with `display` transforms), since Create's wrench, + goggles and potato cannon aren't flat sprites. + +**R6. Connected textures** (P2). Create's casings, windows and vaults pick a tile from a sheet depending on which +neighbours are the same block (`foundation/block/connected/`: rectangle, horizontal, vertical and omni). It's done in +the chunk mesher, from a `connected` field on a block's textures that names the sheet and the kind. Generic: any mod's +glass can use it. + +**R7. Block structure rendering** (P7). A contraption's blocks are meshed once by the chunk worker, as a small chunk of +their own, and drawn with the contraption's matrix each frame. Its moving parts (a drill on it, a bearing's shaft) are +instances drawn relative to it. A block change on it remeshes only it. + +**R8. Render time** (P1). World ticks plus the partial tick, as a shader uniform and for client scripts. + +**R9. Particles** (P3). A simple GPU particle system: sprite, velocity, gravity, lifetime. Used for rotation indicators, +crushing, fan processing, steam, fluid splashes. Optional for gameplay, so it can come late. + +**R10. In-world text and boxes** (P3). Create's value boxes (the number on a scroll value, filter slots on a block's +side) and goggles' overlay. A small API for drawing a label or an item at a point in the world, and a HUD element API, +which is in bworld's types but throws today. + +**R11. 3D in GUIs** (P3). Drawing a model or block in a screen, turned and animated, for the recipe viewer's Create +categories (a press pressing over its recipe, like `compat/jei`), goggles and ponder. + +### Server and Gameplay + +**S0. Ticking only what ticks** (P1). `GameServer.tick` walks every tile in the world to find the ones that tick +([game_server.ts:376](server/game/game_server.ts#L376)). With thousands of Create blocks with tile data, that's the +first thing to fix. Keep a set of ticking tiles per chunk, updated when tiles are added or removed, and let a component +turn ticking off and on for one block (`block.set_ticking(false)`, like returning no ticker in NeoForge). A shaft has +tile data and never ticks. A press only ticks while pressing. + +**S1. Block capabilities** (P3). `ctx.capabilities.register_block("items", block_id, (block, side) => handler)` and +`ctx.world.capability("items", x, y, z, side)`, like NeoForge's `BlockCapability`. Handlers insert, extract, report +slots, and simulate. Chests and furnaces get them in `mods/bworld`. Funnels, chutes, arms, deployers, belts and vaults +all move items only through this. + +**S2. Fluids** (P5). A fluid registry (bworld's liquids are fluids, plus mods' own like Create's honey and chocolate), +fluid stacks with amounts in millibuckets, a `"fluids"` capability, and fluid containers in items (buckets, bottles). + +**S3. Redstone** (P6, or earlier for clutches). A signal API in the engine (each block side has a power level 0 to 15, +`get_signal`, `has_neighbor_signal`, updates to neighbours) and the basic blocks in `mods/bworld`: lever, button, dust, +torch, repeater, comparator, lamp. Create reads and makes signals in about 40 blocks, and bworld has no redstone at all +today. + +**S4. Machines acting on the world** (P3). + +- `liquid_flow(x, y, z)` (wraps `common/physics.ts`), for water wheels and fans. +- Item entities in a box, which can be changed and removed, for the press, fans and belts picking items up. +- Pushing entities, for fans. +- Breaking a block over time with progress shown, and its drops, for drills and saws. +- A fake player using an item on a block, for the deployer (`DeployerFakePlayer`). + +**S5. Scripted entities** (P7). Mods can define an entity's behaviour in server scripts (tick, data, interaction) and +how it's drawn in client scripts. Needed for the contraption entity, seats, potato cannon projectiles, trains and +packages. + +**S6. Block structure entities** (P7). An entity that carries a grid of blocks with their states and tile data, moved +and turned as a whole: assembled from the world and put back, saved, and synced. Players and mobs stand on it and bump +into it as it moves (Create's `ContraptionCollider`, about 1000 lines, is the hardest part), and they can point at and +use its blocks. Generic: boats with decks, falling structures and elevators would all use it. + +**S7. Player API additions** (P1). `sneaking` on players, placements and interactions. Reach from an attribute, for the +extendo grip. Item use events (use, release, using for some time) for the potato cannon and wands. + +**S8. Sound** (P3). Web Audio, positional, with sound events defined in data. bworld has no sound at all yet. Create's +whistles, presses, cranks and trains want it, but nothing breaks without it. + +**S9. More recipe types in bworld** (P0). `shapeless` crafting (Create's cogwheels and many others), stonecutting +(palettes have hundreds of stonecutting recipes, and the mechanical saw uses them), and smoking and blasting for fans. + +**S10. Block shape families in bworld** (P10). Stairs, slabs and walls don't exist in bworld yet, and Create's palettes +are mostly those. They're components with placement rules in `mods/bworld`, like the fence and trapdoor. + +**S11. Layered ore features** (P2). Create's striated ores are bands of stone types, not blobs. A worldgen feature in +`mods/create/scripts/worldgen.ts`, or a data feature if STRUCTURES.md's data features exist by then. Zinc is a plain ore +in `ores.json`. + +**S12. Mod config** (P1). A mod's `config.json`, overridable per server, read in `setup`. Create's stress values, speed +limits and processing times live there, and tests can set them. + +**S13. NBT** (P11). Reading and writing structure NBT, shared with STRUCTURES.md's `common/nbt.ts`, for schematics and +ponder scenes. + +**S14. Uploading files** (P11). A client sending a file to the server in pieces over a mod channel, for schematics. + +## Recipes + +All 19 of Create's types, plus the vanilla types its data uses: + +| Type | Count | Made by | Phase | +| ----------------------------------------------------- | ----- | ------------------------------------------- | ----------------------- | +| `crafting` (shaped/shapeless) | 369 | crafting grid | P0 | +| `stonecutting` | 327 | stonecutter (S9), mechanical saw | P3 | +| `smelting`, `blasting`, `smoking`, `campfire_cooking` | 64 | furnace, fans | P3 | +| `pressing` | 43 | mechanical press | P3 | +| `milling` | 246 | millstone | P3 | +| `crushing` | 211 | crushing wheels | P3 | +| `cutting` | 32 | mechanical saw | P3 | +| `splashing`, `haunting` | 73 | encased fan through water or soul fire | P3 | +| `deploying` | 167 | deployer | P3 | +| `item_application` | 8 | using an item on a block | P3 | +| `sandpaper_polishing` | 1 | sand paper | P3 | +| `mixing`, `compacting` | 21 | mixer and press over a basin | P3 (items), P5 (fluids) | +| `mechanical_crafting` | 4 | mechanical crafters | P3 | +| `sequenced_assembly` | 3 | belts with presses, deployers, spouts, saws | P4 | +| `filling`, `emptying` | 24 | spout, item drain | P5 | +| `toolbox_dyeing`, `item_copying`, `conversion` | — | built-in, special | P9 | + +Create's own types stay in Create's format inside bworld's envelope: + +```json +{ + "format_version": 1, + "recipe": { + "type": "create:pressing", + "ingredients": [{ "tag": "c:ingots/iron" }], + "results": [{ "id": "create:iron_sheet" }] + } +} +``` + +`scripts/recipes/` parses all of them in one place: ingredients as `{ item }`, `{ tag }`, lists of those, or sized fluid +ingredients; results as `{ id, count, chance }` or fluid stacks; `processing_time` and `heat_requirement`. It checks +each type's input and output limits, which come from each recipe class's `getMaxInputCount` and `getMaxOutputCount`. The +recipe viewer gets one reader for this shape, so every Create type shows with no per-type code, and animated categories +(R11) are added per machine on top. + +## Kinetics + +The core of everything, so its rules are written out here. + +**What turns.** One component, `create:kinetic`, with params for which state holds the axis (`axis`, `facing`, +`horizontal_facing`), which ends have an axle, whether it's a small or large cog, and its stress impact. Generators add +`create:generator` with a capacity. Special connections (gearbox, chain drive, belt, speed controller) are named +handlers in `kinetics/connections.ts`. + +**Connections**, with the ratio speed is multiplied by on the way across: + +| Pair | Where | Ratio | +| -------------------- | --------------------------------------------------------------------------------- | ------------------------ | +| Axle to axle | Face neighbours along the axis, both with an axle toward each other | 1 | +| Small cog, small cog | Face neighbours, same axis, not along it | −1 | +| Large cog to small | Same axis, level along it, ±1 on both other axes | −2 (−0.5 the other way) | +| Large cog, large cog | Different axes, ±1 along both their axes, 0 on the third | ±1 by the offsets' signs | +| Gearbox | Turns each side, reversing by side, see `getAxisModifier` in `RotationPropagator` | ±1 | +| Chain drive | Along a line of chain drives, with the adjustable one's ratio | per block | +| Belt | Every segment of a belt turns with its two ends | 1 | + +A large cog also looks at the 12 blocks diagonal to it along an edge. Cog placement rules (no large cog face to face +with any cog off its axis) and the axis a cog picks when placed are in `CogWheelBlock`. + +**Spreading.** When a kinetic block is placed or a generator's speed changes, its speed spreads to what it's connected +to. If a neighbour already turns the other way, or the speed passes 256 rpm, the changed block breaks. A faster +neighbour takes over this block, and a faster block takes over its neighbour's tree. In a loop, a speed that doesn't +match breaks the block. Removing a block clears the tree it was the source of and spreads again from what's left powered +at its edge. Both walks use a queue, not recursion. Rules from `RotationPropagator`. + +**Stress.** A network's capacity is the sum of each generator's capacity × |rpm|, and its stress the sum of each block's +impact × |rpm|. When stress is more than capacity, every block in it acts still and is drawn still. The network is found +by walking connections when something changes, never per tick. Values come from `BlockStressValues` and config defaults, +into `config.json`. + +**What the client gets.** Each kinetic block's rpm and whether its network is overstressed, in client data (R1). Its +visual makes a `rotating` instance with the axis, rpm and an offset that keeps cog teeth meshed. The offset is 22.5° +when the block's coordinates on the two axes that aren't its axis add up to an even number, otherwise 11.25° for large +cogs and 0 for the rest. A speed change updates one instance, and nothing else happens per frame. + +**Chunk borders.** Tile data keeps speeds across unloading. Create tracks unloaded members' stress separately +(`KineticNetwork`'s unloaded stress). Do the same, so a network across an unloaded chunk counts right. + +## Phases + +Each phase ends with every test passing and something to see and use in a world. Engine work (R and S) is listed where +it's first needed. + +### P0: Importer and Skeleton + +- S9 (`shapeless`, stonecutting), R5. +- The importer's other kinds, up to `mod`, and Create's remap file and block table in `mods/create/import/`. +- `mods/create` with every block and item imported, static models, names, recipes that only need crafting, tags. + +Check: every Create block can be placed and looks right standing still, crafting recipes work, and the report lists +what's missing. + +### P1: Kinetics + +- S0, S7, S12, R1, R2, R3 (`transformed` and `rotating`), R4, R8. +- Shaft, cogwheel, large cogwheel, gearbox, vertical gearbox, encased shafts and cogs, clutch and gearshift (with a + placeholder signal until S3), chain drive and adjustable chain gearshift, rotation speed controller, speedometer and + stressometer. +- Generators: hand crank, valve handle, water wheel, large water wheel, creative motor. +- Kinetic network, stress and overstress. + +Check: a water wheel drives a long shaft line through gearboxes and cog ratios, all turning smoothly on the GPU, and +1000 shafts cost nothing per frame and only a little per tick. + +### P2: Materials and World + +- S11, R6. +- Zinc ore, striated stone bands, andesite alloy, brass (made in P3's mixer), casings with connected textures. + +Check: new worlds have zinc and Create's stones, and casings join up. + +### P3: Processing + +- S1, S4, S8, R9, R10, R11, and stonecutting, smoking and blasting from S9. +- Mechanical press, millstone, crushing wheels, mechanical saw, encased fan with its processing (washing, smoking, + blasting, haunting from `AllFanProcessingTypes`), deployer, mechanical crafters, item application, sand paper, depot, + basin, mixer and compacting (items only), blaze burner and its heat. +- Recipe viewer: Create's recipe format, catalysts, and animated categories. + +Check: ores go through crushing, washing and smelting into more ingots than a furnace alone gives, and brass is mixed in +a heated basin. + +### P4: Logistics + +- R3's `scrolling` type. +- Belts. A belt is a line of segments, and only its controller (its first segment) ticks, moving every item on it + (`BeltInventory`), like `BeltBlockEntity.isController`. Items on belts are instances drawn by the controller's visual. +- Funnels, brass and andesite tunnels, chutes and smart chutes, mechanical arm, item vaults (multiblock), filters and + attribute filters, sequenced assembly on belts. + +Check: a sorting line with funnels, filters and an arm, and a precision mechanism made by sequenced assembly. + +### P5: Fluids + +- S2, R3's `fluid` type. +- Fluid pipes, encased and glass pipes, mechanical pump, fluid tanks (multiblock), spout, item drain, hose pulley, + portable fluid interface, basins with fluids, mixing and compacting with fluids, filling and emptying. +- Pipes are networks found by walking pipes from a pump when something changes (`FluidPropagator`, `FluidNetwork`). + Fluid only moves while a pump runs, and a network with no running pump doesn't tick. +- Steam engine and boilers on tanks (`BoilerData`), which are fluids plus heat plus kinetics. + +Check: a steam engine on a tank boiler, fed by a pump from water and heated by blaze burners, drives a factory. + +### P6: Redstone + +- S3, in `mods/bworld` first. +- Redstone link, nixie tube, display link and display board, threshold switch, smart observer, analog lever, pulse + repeater, extender and timer, powered latch and toggle latch, contact, desk bell, sequenced gearshift. Clutch and + gearshift switch to real signals. + +Check: a factory that stops when a vault is full and shows its count on a display board. + +### P7: Contraptions + +- S5, S6, R7. +- Mechanical bearing, windmill bearing with sails, clockwork bearing, mechanical piston, rope pulley, elevator pulley + and contacts, gantry carriage, linear and radial chassis, super glue, contraption controls. +- Actors, which act as their contraption moves (`AllMovementBehaviours`): drill, saw, harvester, plough, roller, + deployer, seats, storage, portable interfaces. +- Minecart contraptions need minecarts and rails, which bworld doesn't have. They wait until bworld has them, and the + cart assembler with them. + +Check: a windmill turns, a drill on a piston mines a wall, and a player rides an elevator. + +### P8: Trains + +- Train tracks and curved tracks, which are drawn as meshes made along their curves, not blocks. +- The track graph (`TrackGraph`, `GlobalRailwayManager`), saved with the world, and train movement along it. +- Bogeys, stations, assembly, signals and edge groups, schedules, train controls and HUD, train observers, displays. +- A train is a block structure entity (S6) that follows the graph instead of moving freely. + +Check: a scheduled train runs between two stations through signals. + +### P9: Equipment + +- Wrench (turning blocks, and picking them up with sneaking), goggles and the overlay (R10), extendo grip, potato + cannon, symmetry wand, toolbox, copper backtank and diving gear (air under water), clipboard, blueprint, worldshaper, + and Create's armor. + +### P10: Decoration + +- S10. +- Palettes (stone types in cut, polished, bricks, small bricks, layered and pillar, each as block, stairs, slab and + wall), windows and panes (connected glass), girders and brackets, scaffolding, ladders, bars, doors, sliding and + framed doors, placards, table cloths, copycats. +- Copycats show another block's texture in their own shape, which needs a model built from tile data. They come last. + +### P11: Schematics + +- S13, S14. +- Schematic and quill, schematic table with uploads, schematicannon placing from a schematic with its fuel and + materials. + +### P12: Package Logistics (6.0) + +- Packager, repackager, frogport, chain conveyor, stock link and ticker, redstone requester, factory gauge, shop table + cloths, cardboard. +- All new art, see [Sources](#sources). + +### P13: Ponder + +- A scene player: a small world from a scene's NBT, drawn in a screen (R11), with Create's scene scripts + (`infrastructure/ponder/scenes/`) ported to run its steps. 0.5.0.j has 153 scene files. +- The `W` key over an item opens its scenes. + +## Tests + +`tests/create/`, a file per subsystem, with `test_game` from `tests/helpers.ts`. Each phase's check becomes tests: + +- **Rules from plain functions:** connection ratios, recipe parsing, belt item movement, pipe flow. +- **Machines in a world:** an input goes in, the right output comes out, and nothing happens without power. +- **Networks:** placing and breaking in the middle of a line; two generators fighting; overstress. +- **Performance:** a tick with 10,000 shafts, and a frame's instance updates, stay under a budget. These are benchmarks + (`deno bench`), not tests, so a slow machine doesn't fail CI. + +Following CLAUDE.md, tests check behaviour and not tuned numbers, except where the number is the point, like a 2:1 cog +ratio. Recipes come from the imported data, so tests use Create's recipes instead of copying them. + +## Open Questions + +- **Minecraft content Create assumes:** blazes (the blaze burner captures one), soul fire (haunting), the Nether and the + End (crushing and haunting recipes), minecarts and rails (cart contraptions, controller rails), honey and chocolate as + 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 + moving earlier? +- **6.0's package logistics:** new art for about 20 blocks. Port them, or leave Create at 0.5's logistics? diff --git a/deno.json b/deno.json index 4d9d2ae..859a780 100644 --- a/deno.json +++ b/deno.json @@ -4,6 +4,7 @@ "serve:client": "deno run --allow-net --allow-read jsr:@std/http/file-server build", "server": "deno run --unstable-worker-options --allow-net --allow-read --allow-write --allow-env server/main.ts", "new-mod": "deno run --allow-read --allow-write tools/new_mod.ts", + "import": "deno run --allow-read --allow-write tools/importer.ts", "check-mods": "deno run --allow-read --allow-run tools/check_mods.ts", "pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts", "test": "deno test --allow-read --allow-write --allow-run --allow-net tests/", diff --git a/tests/importer_test.ts b/tests/importer_test.ts new file mode 100644 index 0000000..53efa20 --- /dev/null +++ b/tests/importer_test.ts @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { assert, assertEquals, assertStringIncludes } 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"; + +// a java mod's resources in a temporary folder: { "block/gear": {...} } is assets//models/block/gear.json +function resources(models: Record, namespace = "gears"): string { + const root = Deno.makeTempDirSync(); + for (const [path, json] of Object.entries(models)) { + const file = `${root}/assets/${namespace}/models/${path}.json`; + Deno.mkdirSync(file.slice(0, file.lastIndexOf("/")), { recursive: true }); + Deno.writeTextFileSync(file, JSON.stringify(json)); + } + return root; +} + +function convert(models: Record, 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; +} + +const GEAR = { + credit: "Made with Blockbench", + texture_size: [32, 32], + textures: { "0": "gears:block/gear", particle: "gears:block/gear" }, + elements: [{ + name: "hub", + from: [4, 0, 4], + to: [12, 4, 12], + rotation: { angle: 22.5, axis: "y", origin: [8, 8, 8] }, + faces: { + up: { uv: [0, 0, 8, 8], texture: "#0", cullface: "up" }, + down: { uv: [0, 0, 8, 8], texture: "#0", cullface: "down", tintindex: 0 }, + north: { uv: [0, 8, 8, 12], texture: "#0", rotation: 90 }, + }, + }], +}; + +Deno.test("a java block model becomes a bworld model that passes its checks", () => { + const model = convert({ "block/gear": GEAR }, "block/gear"); + 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; + 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", () => { + 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); +}); + +Deno.test("vanilla parents like cube_all and stairs convert without minecraft's files", () => { + 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); + // minecraft's block textures are taken to be the base game's of the same name + assertEquals(cube.textures?.all, "bworld:stone"); + + 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); +}); + +Deno.test("a folder converts into the same folders, with models that are only parents left out", () => { + const root = resources({ + "block/gear": GEAR, + "block/large/gear": { parent: "gears:block/gear" }, + "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"]) { + const json = JSON.parse(Deno.readTextFileSync(`${output}/${path}.json`)); + assertEquals(json.format_version, 1); + assertEquals(validate_model(json.model), []); + } +}); + +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" }, + "block/tilted": { + ...GEAR, + elements: [{ ...GEAR.elements[0], rotation: { angle: 30, axis: "x", origin: [8, 8, 8] } }], + }, + // these two would both be gears:block_a_b + "block/a/b": GEAR, + "block/a_b": GEAR, + }); + const output = Deno.makeTempDirSync(); + const report = import_models(root, { output }); + assertEquals(report.skipped.map(({ location }) => location).sort(), ["gears:block/obj", "gears:item/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); +}); + +Deno.test("--remap renames locations before they become ids", () => { + const root = resources({ "block/gear": GEAR }); + 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; + assertEquals(model.id, "cogs:big_gear"); + assertEquals(model.textures, { "0": "cogs:gear" }); +}); diff --git a/tools/importer.ts b/tools/importer.ts new file mode 100644 index 0000000..912c5ea --- /dev/null +++ b/tools/importer.ts @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// converts a minecraft java mod's resources into bworld's formats, one kind at a time: +// deno run -A tools/importer.ts model MODEL.json --output PATH +// deno run -A tools/importer.ts model path/to/resources --output mods/example/models +// a folder can be a whole mod's resources (every assets//models in it), one assets//models, or a +// folder inside one. see USAGE for the options +import { dirname, join, resolve, SEPARATOR } from "@std/path"; +import { convert_model, type ModelSource } from "./importer/models.ts"; +import { + DEFAULT_REMAPS, + enclosing_root, + find_roots, + format_json, + location_of, + location_string, + parse_location, + type Remaps, + type ResourceRoot, + walk_files, +} from "./importer/resources.ts"; + +const USAGE = `deno run -A tools/importer.ts [options] + +kinds: + model java block models to bworld models + +options: + --output PATH the file (for one model) or the folder to write. one model without it is printed + --namespace NS the namespace, when the input isn't inside assets//models + --parents FOLDER another folder to find parent models in, like another mod's resources. can be repeated + --remap FILE json that renames locations before they become ids, longest match first: + { "textures": { "minecraft:block/": "bworld:" }, "models": {} } + minecraft's block and item textures become bworld's of the same name unless it says otherwise`; + +export interface ImportOptions { + output?: string; + namespace?: string; + parents?: string[]; + remaps?: Remaps; +} + +export interface ImportReport { + written: { location: string; id: string; file?: string; text: string }[]; + // models with no boxes of their own, only there for others to use as a parent + parents: string[]; + skipped: { location: string; reason: string }[]; + errors: { location: string; problems: string[] }[]; + warnings: { location: string; warning: string }[]; +} + +export function import_models(input: string, options: ImportOptions = {}): ImportReport { + const remaps = options.remaps ?? DEFAULT_REMAPS; + const single = is_file(input); + const roots = single ? file_root(input, options.namespace) : find_roots(input, "models", options.namespace); + if (roots.length === 0) { + throw new Error(`no models in ${input}: pass --namespace when it isn't inside assets//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 | undefined>(); + const read: ModelSource = (location) => { + if (cache.has(location)) return cache.get(location); + const { namespace, path } = parse_location(location); + let json: Record | 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(); + for (const { root, file } of files) { + const where = location_of(root, file, ".json"); + const location = location_string(where); + const result = convert_model(location, read, remaps); + if (result.kind === "parent") report.parents.push(location); + else if (result.kind === "skipped") report.skipped.push({ location, reason: result.reason }); + else if (result.kind === "error") report.errors.push({ location, problems: result.problems }); + else { + const other = locations.get(result.id); + if (other) { + const problem = + `its id ${result.id} is the same as ${other}'s, so give one of them another with --remap`; + report.errors.push({ location, problems: [problem] }); + continue; + } + locations.set(result.id, location); + for (const warning of result.warnings) report.warnings.push({ location, warning }); + const output = single + ? options.output + : join(options.output!, ...(several_namespaces ? [where.namespace] : []), `${where.path}.json`); + report.written.push({ location, id: result.id, file: output, text: format_json(result.json) + "\n" }); + } + } + for (const { file, text } of report.written) { + if (file === undefined) continue; + Deno.mkdirSync(dirname(file), { recursive: true }); + Deno.writeTextFileSync(file, text); + } + return report; +} + +function file_root(file: string, namespace?: string): ResourceRoot[] { + const root = enclosing_root(file, "models"); + if (root) return [root]; + if (!namespace) throw new Error(`can't tell ${file}'s namespace: pass --namespace`); + return [{ namespace, dir: dirname(resolve(file)) }]; +} + +function inside(path: string, root: ResourceRoot) { + const full = resolve(path); + return full === root.dir || full.startsWith(root.dir + SEPARATOR); +} + +function is_file(path: string) { + try { + return Deno.statSync(path).isFile; + } catch { + return false; + } +} + +function parse_args(args: string[]) { + const positional: string[] = []; + const options: ImportOptions & { parents: string[] } = { parents: [] }; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const value = () => { + const next = args[++i]; + if (next === undefined) throw new Error(`${arg} needs a value`); + return next; + }; + if (arg === "--output") options.output = value(); + else if (arg === "--namespace") options.namespace = value(); + else if (arg === "--parents") options.parents.push(value()); + else if (arg === "--remap") { + const remap = JSON.parse(Deno.readTextFileSync(value())); + options.remaps = { + textures: { ...DEFAULT_REMAPS.textures, ...remap.textures }, + models: { ...DEFAULT_REMAPS.models, ...remap.models }, + }; + } else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`); + else positional.push(arg); + } + return { positional, options }; +} + +function print_report(report: ImportReport) { + if (report.written.length === 1 && report.written[0].file === undefined) { + console.log(report.written[0].text.trimEnd()); + } + for (const { location, reason } of report.skipped) console.error(`skipped ${location}: ${reason}`); + for (const { location, problems } of report.errors) { + for (const problem of problems) console.error(`error in ${location}: ${problem}`); + } + // the same warning on many models is one line + const warnings = new Map(); + for (const { location, warning } of report.warnings) { + warnings.set(warning, [...(warnings.get(warning) ?? []), location]); + } + for (const [warning, locations] of warnings) { + const which = locations.length === 1 ? locations[0] : `${locations.length} models`; + console.error(`warning: ${warning} (${which})`); + } + console.error( + `${report.written.length} converted, ${report.parents.length} only parents, ${report.skipped.length} skipped, ` + + `${report.errors.length} with errors`, + ); +} + +if (import.meta.main) { + if (Deno.args.includes("--help") || Deno.args.includes("-h")) { + console.log(USAGE); + Deno.exit(0); + } + try { + const { positional: [kind, input], options } = parse_args(Deno.args); + if (!kind || !input) { + console.error(USAGE); + Deno.exit(2); + } + if (kind !== "model") throw new Error(`"${kind}" isn't a kind that can be imported yet, see --help`); + const report = import_models(input, options); + print_report(report); + if (report.errors.length > 0) Deno.exit(1); + } catch (e) { + console.error((e as Error).message); + Deno.exit(1); + } +} diff --git a/tools/importer/models.ts b/tools/importer/models.ts new file mode 100644 index 0000000..cd72e93 --- /dev/null +++ b/tools/importer/models.ts @@ -0,0 +1,165 @@ +// 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"; +import { FORMAT_VERSION } from "$/common/mod_data.ts"; +import { is_valid_id, location_string, parse_location, type Remaps, to_id } 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: "skipped"; reason: string } + | { kind: "error"; problems: string[] }; + +const FACE_NAMES: Record = { + down: "bottom", + up: "top", + north: "north", + south: "south", + west: "west", + east: "east", +}; +const ANGLES = [-45, -22.5, 0, 22.5, 45]; + +interface Flat { + textures: Record; + elements?: unknown[]; + loader?: string; + render_type?: string; + not_boxes?: string; +} + +class ImportError extends Error {} + +export function convert_model(location: string, read: ModelSource, remaps: Remaps): ModelResult { + let flat: Flat; + try { + flat = flatten(location_string(parse_location(location)), read, []); + } catch (e) { + if (e instanceof ImportError) return { kind: "error", problems: [e.message] }; + throw e; + } + if (flat.not_boxes) return { kind: "skipped", reason: flat.not_boxes }; + if (flat.loader) return { kind: "skipped", reason: `it uses the "${flat.loader}" loader` }; + if (!flat.elements || flat.elements.length === 0) return { kind: "parent" }; + + const problems: string[] = []; + const warnings = new Set(); + if (flat.render_type) warnings.add(`render_type "${flat.render_type}" was left out, set the block's render layer`); + const texture = (value: string, where: string) => { + if (value.startsWith("#")) return value; + const id = to_id(value, remaps.textures); + if (!is_valid_id(id)) problems.push(`${where}: "${value}" doesn't make a valid texture id (${id})`); + return id; + }; + + const elements = flat.elements.map((element, i) => + convert_element(element, `elements[${i}]`, texture, problems, warnings) + ); + + // only the variables faces reach, so particle textures and ones children overrode don't come along + const textures: Record = {}; + const pending = elements.flatMap((element) => Object.values(element.faces).map((face) => face!.texture)); + for (let reference = pending.pop(); reference !== undefined; reference = pending.pop()) { + const name = reference.slice(1); + if (!reference.startsWith("#") || name in textures || flat.textures[name] === undefined) continue; + textures[name] = texture(flat.textures[name], `textures.${name}`); + pending.push(textures[name]); + } + + const id = to_id(location, remaps.models); + if (!is_valid_id(id)) problems.push(`"${location}" doesn't make a valid model id (${id})`); + if (problems.length > 0) return { kind: "error", problems }; + const model: ModelJson = Object.keys(textures).length > 0 ? { id, textures, elements } : { id, elements }; + return { kind: "model", id, json: { format_version: FORMAT_VERSION, model }, warnings: [...warnings] }; +} + +// a model with its parents' textures and elements merged in, like minecraft's BlockModel does when it bakes: the child's +// textures win, and its elements replace its parent's when it has any +function flatten(location: string, read: ModelSource, chain: string[]): Flat { + if (chain.includes(location)) throw new ImportError(`its parents loop: ${[...chain, location].join(" -> ")}`); + if (NOT_BOXES[location]) return { textures: {}, not_boxes: `${NOT_BOXES[location]} (${location})` }; + const json = VANILLA_MODELS[location] ?? read(location); + if (!json) { + throw new ImportError( + chain.length === 0 ? `${location} wasn't found` : `its parent ${location} wasn't found, pass --parents`, + ); + } + const parent: Flat = typeof json.parent === "string" + ? flatten(location_string(parse_location(json.parent)), read, [...chain, location]) + : { textures: {} }; + return { + textures: { ...parent.textures, ...(json.textures as Record | undefined) }, + elements: Array.isArray(json.elements) ? json.elements : parent.elements, + loader: typeof json.loader === "string" ? json.loader : parent.loader, + render_type: typeof json.render_type === "string" ? json.render_type : parent.render_type, + not_boxes: parent.not_boxes, + }; +} + +function convert_element( + json: unknown, + where: string, + texture: (value: string, where: string) => string, + problems: string[], + warnings: Set, +): ModelElementJson { + const element = (json ?? {}) as Record; + const point = (key: string) => { + const value = element[key]; + if (Array.isArray(value) && value.length === 3 && value.every((v) => typeof v === "number")) { + return value as [number, number, number]; + } + problems.push(`${where}.${key} must be [x, y, z]`); + return [0, 0, 0] as [number, number, number]; + }; + const out = { from: point("from"), to: point("to") } as ModelElementJson; + + const rotation = element.rotation as Record | undefined; + if (rotation && rotation.angle !== 0) { + if (!ANGLES.includes(rotation.angle as number)) { + problems.push(`${where}.rotation: an angle of ${rotation.angle} isn't one of ${ANGLES.join(", ")}`); + } + out.rotation = { + origin: rotation.origin as [number, number, number], + axis: rotation.axis as "x" | "y" | "z", + angle: rotation.angle as number, + ...(rotation.rescale === true ? { rescale: true } : {}), + }; + } + if (element.shade === false) out.shade = false; + if (element.light_emission !== undefined) warnings.add("light_emission on elements was left out"); + + out.faces = {}; + for (const [side, value] of Object.entries((element.faces ?? {}) as Record>)) { + const name = FACE_NAMES[side]; + if (!name) { + problems.push(`${where}.faces: "${side}" isn't a side`); + continue; + } + if (typeof value.texture !== "string") { + problems.push(`${where}.faces.${side} has no texture`); + continue; + } + const face: ModelFaceJson = { texture: texture(value.texture, `${where}.faces.${side}`) }; + if (Array.isArray(value.uv)) face.uv = value.uv as [number, number, number, number]; + if (typeof value.rotation === "number" && value.rotation !== 0) face.rotation = value.rotation; + if (typeof value.cullface === "string") { + // java also takes "bottom" for down + const cullface = FACE_NAMES[value.cullface] ?? (value.cullface === "bottom" ? "bottom" : undefined); + if (cullface) face.cullface = cullface; + else problems.push(`${where}.faces.${side}.cullface: "${value.cullface}" isn't a side`); + } + if (value.tintindex !== undefined) warnings.add("tintindex on faces was left out"); + out.faces[name] = face; + } + return out; +} diff --git a/tools/importer/resources.ts b/tools/importer/resources.ts new file mode 100644 index 0000000..817379c --- /dev/null +++ b/tools/importer/resources.ts @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// where things are in a java mod's resources, and what they're called in bworld. a resource location like +// "create:block/cogwheel" (or "block/stone", which is minecraft's) becomes the id "create:block_cogwheel": bworld ids +// have no folders, so the path's folders are joined with _, the same way check_mods names textures in subfolders +import { ID_PATTERN } from "$/common/mod_data.ts"; +import { relative, resolve, SEPARATOR } from "@std/path"; + +export interface Location { + namespace: string; + path: string; +} + +export function parse_location(value: string): Location { + const colon = value.indexOf(":"); + return colon < 0 + ? { namespace: "minecraft", path: value } + : { namespace: value.slice(0, colon), path: value.slice(colon + 1) }; +} + +export function location_string({ namespace, path }: Location): string { + return `${namespace}:${path}`; +} + +// rewrites applied to a location before it becomes an id, longest match first: { "minecraft:block/": "bworld:" } turns +// minecraft's block textures into the base game's, which are named the same. a key without a trailing / only matches +// that location exactly +export type Remap = Record; + +export interface Remaps { + textures: Remap; + models: Remap; +} + +export const DEFAULT_REMAPS: Remaps = { + textures: { "minecraft:block/": "bworld:", "minecraft:item/": "bworld:" }, + models: {}, +}; + +export function to_id(location: string, remap: Remap = {}): string { + 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; + } + } + const { namespace, path } = parse_location(mapped); + return `${namespace}:${path.replaceAll("/", "_")}`; +} + +export function is_valid_id(id: string): boolean { + return ID_PATTERN.test(id); +} + +// a folder of one kind of resource (models, textures, ...) for one namespace: assets// +export interface ResourceRoot { + namespace: string; + dir: string; +} + +// the roots of a kind inside a folder: every assets// 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 +export function find_roots(input: string, kind: string, namespace?: string): ResourceRoot[] { + const dir = resolve(input); + const enclosing = enclosing_root(dir, kind); + if (enclosing) return [enclosing]; + const roots: ResourceRoot[] = []; + for (const assets of find_dirs(dir, "assets")) { + for (const entry of read_dir(assets)) { + if (entry.isDirectory && is_dir(`${assets}/${entry.name}/${kind}`)) { + roots.push({ namespace: entry.name, dir: `${assets}/${entry.name}/${kind}` }); + } + } + } + if (roots.length === 0 && namespace) roots.push({ namespace, dir }); + return roots; +} + +// the assets// folder a path is in, if it's in one +export function enclosing_root(path: string, kind: string): ResourceRoot | undefined { + const parts = resolve(path).split(SEPARATOR); + for (let i = parts.length - 1; i >= 2; i--) { + if (parts[i] === kind && parts[i - 2] === "assets") { + return { namespace: parts[i - 1], dir: parts.slice(0, i + 1).join(SEPARATOR) }; + } + } + return undefined; +} + +// a file's location inside its root: assets/create/models/block/cogwheel.json is create:block/cogwheel +export function location_of(root: ResourceRoot, file: string, extension: string): Location { + const path = relative(root.dir, resolve(file)).split(SEPARATOR).join("/"); + return { namespace: root.namespace, path: path.slice(0, -extension.length) }; +} + +// every file with the extension under a folder, as full paths +export function walk_files(dir: string, extension: string): string[] { + const files: string[] = []; + for (const entry of read_dir(dir)) { + const path = `${dir}/${entry.name}`; + if (entry.isDirectory) files.push(...walk_files(path, extension)); + else if (entry.name.endsWith(extension)) files.push(path); + } + return files; +} + +function find_dirs(dir: string, name: string): string[] { + const found: string[] = []; + for (const entry of read_dir(dir)) { + if (!entry.isDirectory) continue; + const path = `${dir}/${entry.name}`; + if (entry.name === name) found.push(path); + else found.push(...find_dirs(path, name)); + } + return found; +} + +function read_dir(dir: string): Deno.DirEntry[] { + try { + return [...Deno.readDirSync(dir)].sort((a, b) => a.name.localeCompare(b.name)); + } catch (e) { + if (e instanceof Deno.errors.NotFound || e instanceof Deno.errors.NotADirectory) return []; + throw e; + } +} + +function is_dir(path: string): boolean { + try { + return Deno.statSync(path).isDirectory; + } catch { + return false; + } +} + +// 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); + const entries = Array.isArray(value) + ? value.map((v) => format_json(v, indent + "\t")) + : Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => + `${JSON.stringify(k)}: ${format_json(v, indent + "\t")}` + ); + const [open, close] = Array.isArray(value) ? ["[", "]"] : ["{", "}"]; + if (entries.length === 0) return open + close; + const flat = Object.values(value).every((v) => + v === null || typeof v !== "object" || (Array.isArray(v) && v.every((x) => x === null || typeof x !== "object")) + ); + const one_line = Array.isArray(value) ? `[${entries.join(", ")}]` : `{ ${entries.join(", ")} }`; + if (flat && !one_line.includes("\n") && indent.length * 4 + one_line.length <= 100) return one_line; + return `${open}\n${entries.map((e) => indent + "\t" + e).join(",\n")}\n${indent}${close}`; +} diff --git a/tools/importer/vanilla_models.ts b/tools/importer/vanilla_models.ts new file mode 100644 index 0000000..fb506ef --- /dev/null +++ b/tools/importer/vanilla_models.ts @@ -0,0 +1,128 @@ +// 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", +};