// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // the json formats from docs/modding/, and converting them to and from the engine's registry entries. // the mod loader uses the from_json direction, tests use both to check nothing is lost import * as z from "zod"; import { is_tint_color, type TintColor } from "./worldgen/biome_colors.ts"; import { type BlockRegistry, type BlockStateDefinition, EverythingRegistry, FLUID_DEFAULTS, FLUID_LEVEL, type FluidContainerProperties, type FluidProperties, type FoodProperties, type ItemLayer, type ItemRegistry, MAX_FLUID_RANGE, RENDER_LAYERS, type RenderLayer, type ToolProperties, WATERLOGGED, type WornProperties, } from "./everything_registry.ts"; import type { BlockPart, BlockVariant, ModelDisplay, ModelFileJson } from "./block_models.ts"; import { expand_items, list_matches } from "./tags.ts"; import { GAME_VERSION } from "./constants.ts"; import type { PlayOptions } from "./mod_api/shared.ts"; import { by_kind, color, find_problems, id, id_or_tag, ID_PATTERN, is_object, json_object, loot_table_id, type Problems, TAG_ID_PATTERN, text, vec3, } from "./schema.ts"; export const FORMAT_VERSION = 1; export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/; export const RESERVED_NAMESPACES = ["cubi"]; // the namespace for tags every mod shares, like neoforge's. no mod owns it export const SHARED_TAG_NAMESPACE = "c"; export const TAG_REGISTRIES = ["blocks", "items", "entities", "biomes"] as const; export type TagRegistry = typeof TAG_REGISTRIES[number]; // a data file, with what it holds under key next to the format it's in, like { "format_version": 1, "block": { ... } } export function data_file(key: string, contents: z.ZodType) { return z.object({ format_version: z.literal(FORMAT_VERSION), [key]: contents }); } type BlockTextures = BlockRegistry["textures"]; // the pieces the formats here are made of, past the ones in schema.ts // how far a model turns const right_angle = z.literal([0, 90, 180, 270]); // what a block's tint draws its textures in, see TintColor const tint_color = z.custom(is_tint_color, 'must be "grass", "foliage", "water" or a color like "#80a755"'); // a texture id, or texture variables mapped to ids const textures = z.union([id, z.record(z.string(), id)], "must be a texture id or { variable: texture id }"); const stack = z.object({ id, count: z.int().min(1) }); // what a block's or entity's sounds start with, like "my_mod:wood" for my_mod:wood/break const sound_prefix = z.string('must be a sound id like "my_mod:wood"').regex(TAG_ID_PATTERN); // the manifest of the mod in the folder folder_name, which is its id const manifest_schema = (folder_name: string) => z.object({ format_version: z.literal(FORMAT_VERSION), id: z.string("must be 1-32 characters of a-z, 0-9 and _").regex(NAMESPACE_PATTERN) .refine((id) => id === folder_name, `must match the folder name "${folder_name}"`), name: text, description: z.string().optional(), version: z.string("must be semver, like 1.0.0").regex(/^\d+\.\d+\.\d+/), authors: z.array(z.string()).optional(), game_version: z.string().optional(), // imports cubi/engine to reach into the engine and hook its methods. needs game_version within one minor version engine_access: z.boolean().optional(), dependencies: z.array(z.object({ id: z.string(), version: z.string() })).optional(), // the mod's script, whose exports are its phases, see common/mod_loader.ts's PHASES main: z.string().optional(), credits: z.string().optional(), }).superRefine((manifest, ctx) => { const problem = manifest.engine_access ? engine_version_problem(manifest.game_version) : undefined; if (problem) ctx.addIssue({ code: "custom", message: problem }); }); export type ManifestJson = z.infer>; export interface BlockJson { id: string; name?: string; textures: BlockTextures; model?: string; variants?: Record; render_layer?: RenderLayer; cull_same?: boolean; tint?: { color: TintColor; textures?: string[] }; light_emission?: number; light_opacity?: number; // replaced by render_layer, true means translucent transparent?: boolean; alpha?: number; collision?: boolean; shape?: number[][]; collision_shape?: number[][]; parts?: BlockPart[]; item_model?: string; mining?: { toughness: number; tool?: string; requires_tool?: boolean; tier?: number }; drops?: string; item?: boolean; interactive?: boolean; scrollable?: boolean; sounds?: string; replaceable?: boolean; place_on?: string[]; place_in?: string[]; states?: BlockStateDefinition[]; components?: Record; item_display?: { surface: number }; // makes it a fluid, see FluidProperties. range is 7 when not set fluid?: Partial; // what it drops when broken, see common/loot.ts. drops is the shorthand for one of an item loot_table?: string; // the fluid it can hold, see BlockRegistry.waterloggable waterloggable?: string; // only placed into a source of it, see BlockRegistry.waterlogged_only waterlogged_only?: boolean; } // boxes in pixels: [[x1, y1, z1, x2, y2, z2], ...], each corner from 0 to 16 (y to top) and the second past the first function boxes(top: number) { const pixel = z.number().min(0).max(16); const height = z.number().min(0).max(top); const box = z.tuple([pixel, height, pixel, pixel, height, pixel], "must be a box, [x1, y1, z1, x2, y2, z2]") .refine(([x1, y1, z1, x2, y2, z2]) => x1 <= x2 && y1 <= y2 && z1 <= z2, "can't end before it starts"); return z.array(box, "must be a list of boxes in pixels, like [[0, 0, 0, 16, 8, 16]]").min(1); } const shape = boxes(16); // what entities bump into can be taller than the block, like a fence const collision_shape = boxes(24); const variant = z.object({ model: id.optional(), textures: textures.optional(), x: right_angle.optional(), y: right_angle.optional(), uvlock: z.boolean().optional(), shape: shape.optional(), collision_shape: collision_shape.optional(), }); const part = variant.extend({ when: z.string().optional(), model: id }); // a whole number of light, from none to full const light = z.int().min(0).max(15); const block_fields = z.object({ id, name: text.optional(), textures, model: id.optional(), // keys are conditions on the block's states, like "age=3" variants: z.record(z.string(), variant).optional(), render_layer: z.enum(RENDER_LAYERS).optional(), cull_same: z.boolean().optional(), tint: z.object({ color: tint_color, // texture variables, like ["top"] textures: z.array(z.string()).optional(), }).optional(), light_emission: light.optional(), light_opacity: light.optional(), transparent: z.boolean().optional(), alpha: z.number().min(0).max(1).optional(), collision: z.boolean().optional(), shape: shape.optional(), collision_shape: collision_shape.optional(), parts: z.array(part).min(1).optional(), item_model: id.optional(), // toughness is in seconds mining: z.object({ toughness: z.number().min(0), tool: z.string().optional(), requires_tool: z.boolean().optional(), tier: z.int().min(0).optional(), }).optional(), drops: id.optional(), item: z.boolean().optional(), interactive: z.boolean().optional(), scrollable: z.boolean().optional(), // what it sounds like: /break, /place, /step and /hit, see BLOCK_SOUNDS sounds: sound_prefix.optional(), replaceable: z.boolean().optional(), place_on: z.array(id_or_tag).min(1).optional(), place_in: z.array(id_or_tag).min(1).optional(), states: z.array(z.object({ name: z.string(), bits: z.int().min(1), default: z.int().min(0) })).optional(), components: json_object.optional(), // the height in pixels items lie on item_display: z.object({ surface: z.number().min(0).max(16) }).optional(), fluid: z.strictObject({ range: z.int().min(1).max(MAX_FLUID_RANGE).optional(), ticks: z.int().min(1).optional(), renewable: z.boolean().optional(), }, "must be { range, ticks, renewable }, or {}").optional(), loot_table: loot_table_id.optional(), waterloggable: id.optional(), waterlogged_only: z.boolean().optional(), }); const block_schema: z.ZodType = block_fields.superRefine(check_block); // what a fluid's and a plain cube's textures can be, past being ids const fluid_textures = z.union([z.string(), z.strictObject({ still: z.string(), flowing: z.string().optional() })]); const cube_textures = z.union([ z.string(), z.object({ top: z.string(), bottom: z.string(), side: z.string() }), z.object({ front: z.string(), side: z.string() }), ]); // what a block's fields mean for each other function check_block(block: z.infer, ctx: z.RefinementCtx) { const problem = (path: PropertyKey[], message: string) => ctx.addIssue({ code: "custom", path, message }); const states = block.states ?? []; const names = new Set(states.map((state) => state.name)); // a condition like "age=3,facing=1" on the block's states, for a variant or a part const check_condition = (path: PropertyKey[], condition: string) => { for (const term of condition === "" ? [] : condition.split(",")) { const [name, value] = term.split("=").map((side) => side.trim()); if (!names.has(name)) problem(path, `names ${name}, which isn't one of this block's states`); else if (!/^\d+$/.test(value ?? "")) problem(path, `must give ${name} a number, like ${name}=1`); } }; for (const condition of Object.keys(block.variants ?? {})) check_condition(["variants", condition], condition); block.parts?.forEach((part, i) => { if (part.when !== undefined) check_condition(["parts", i, "when"], part.when); }); if (block.fluid) { // a fluid is drawn by the engine, so it has no model of its own, and its level is a state it gets if (!fluid_textures.safeParse(block.textures).success) { problem(["textures"], "must be a texture id or { still, flowing } for a fluid"); } for (const key of ["model", "variants", "parts", "shape", "collision_shape", "item_model"] as const) { if (block[key] !== undefined) problem([key], "isn't for fluids, the engine draws them"); } if (names.has(FLUID_LEVEL.name)) { problem(["states"], `can't have "${FLUID_LEVEL.name}", a fluid gets that state of its own`); } if (block.waterloggable !== undefined) problem(["waterloggable"], "isn't for fluids"); } else if (block.parts === undefined && (block.model ?? "cubi:cube") === "cubi:cube") { if (!cube_textures.safeParse(block.textures).success) { problem(["textures"], "must be a texture id, { top, bottom, side } or { front, side }"); } } if (block.waterloggable !== undefined && names.has(WATERLOGGED.name)) { problem(["states"], `can't have "${WATERLOGGED.name}", a waterloggable block gets that state of its own`); } if (block.waterlogged_only && block.waterloggable === undefined) { problem(["waterlogged_only"], "needs waterloggable, the fluid it's placed into"); } // a block's states fit in 16 bits, with the one it gets for being a fluid or waterloggable const added = block.fluid ? FLUID_LEVEL : block.waterloggable !== undefined ? WATERLOGGED : undefined; const bits = states.reduce((sum, state) => sum + state.bits, added?.bits ?? 0); if (bits > 16) problem(["states"], `use ${bits} bits${added ? ` with ${added.name}` : ""}, the most is 16`); if (block.drops !== undefined && block.loot_table !== undefined) { problem(["drops"], "can't be set with loot_table, drops is the shorthand for a loot table of one item"); } } // the names block models' json uses, see block_models.ts. they live here because the schemas below need them as this // file loads, and block_models.ts imports this file (through utils.ts and biome_colors.ts) before its own are set export type ModelFace = "top" | "bottom" | "north" | "south" | "west" | "east"; export const MODEL_FACES: ModelFace[] = ["top", "bottom", "north", "south", "west", "east"]; // where items are shown: in slots, held in first person, dropped, and on blocks with item_display export const DISPLAY_CONTEXTS = ["gui", "firstperson_righthand", "ground", "fixed"] as const; export type DisplayContext = typeof DISPLAY_CONTEXTS[number]; const model_face = z.object({ texture: z.string(), uv: z.tuple([z.number(), z.number(), z.number(), z.number()], "must be [u1, v1, u2, v2] in pixels").optional(), rotation: right_angle.optional(), cullface: z.enum(MODEL_FACES).optional(), }); const model_element = z.object({ from: vec3, to: vec3, rotation: z.object({ origin: vec3, axis: z.enum(["x", "y", "z"]), angle: z.number().min(-180).max(180), rescale: z.boolean().optional(), }).optional(), shade: z.boolean().optional(), faces: z.partialRecord(z.enum(MODEL_FACES), model_face), }); const display_transform = z.strictObject({ rotation: vec3.optional(), translation: vec3.optional(), scale: vec3.optional(), }); const model_schema: z.ZodType = z.object({ id, parent: id.optional(), textures: z.record( z.string(), z.union([z.string().startsWith("#"), id], 'must be a texture id, or a variable like "#side"'), ).optional(), elements: z.array(model_element).optional(), display: z.partialRecord(z.enum(DISPLAY_CONTEXTS), display_transform).optional(), }).refine( // a model can leave its elements to its parent, or be one that only gives defaults to its children (model) => model.elements || model.parent || model.textures || model.display, "a model needs elements, a parent, or textures or display for models that use it as theirs", ); const ore_schema = z.object({ id, // a block, a "#tag" of blocks, or a list of those replaces: z.union([id_or_tag, z.array(id_or_tag).min(1)]), min_y: z.number(), max_y: z.number(), scale: z.number(), threshold: z.number(), }).refine((ore) => ore.min_y <= ore.max_y, { path: ["min_y"], message: "can't be above max_y" }); export type OreJson = z.infer; // mobs that spawn on their own, like neoforge's add_spawns biome modifier and undergarden's biome spawners. only // monsters for now: in the dark near players, like minecraft's NaturalSpawner const spawn_schema = z.object({ entity: id, // how often it's picked over the other spawns where both can spawn weight: z.int().min(0), // how many spawn together min_count: z.int().min(1), max_count: z.int().min(1), // only in these biomes, every biome when not set biomes: z.array(id).optional(), // the chance each spawn that passed every other check goes ahead, like undergarden's 1 in 10 for its rotspawn. 1 // when not set chance: z.number().positive().max(1).optional(), }).refine((spawn) => spawn.min_count <= spawn.max_count, { path: ["min_count"], message: "can't be above max_count" }); export type SpawnJson = z.infer; export interface ItemJson { id: string; // without one it isn't a new item, it fills in the item of the mod's block with this id, see add_to_block_item texture?: string; // data key -> texture, see ItemRegistry.data_textures data_textures?: Record; // see ItemRegistry.model model?: string; // see ItemRegistry.entity entity?: string; // tier and speed default to 0 and 2 tool?: Omit & Partial; places?: string; max_stack?: number; base_sell_value?: number; food?: FoodProperties; // how it looks worn on a player worn?: WornProperties; // see ItemRegistry.targets_fluids targets_fluids?: boolean; fluid_container?: FluidContainerProperties; layers?: ItemLayer[]; name?: string; lore?: string; components?: Record; } const item_schema: z.ZodType = z.object({ id, texture: id.optional(), data_textures: z.record(z.string(), id).optional(), model: id.optional(), entity: id.optional(), tool: z.object({ type: z.string(), durability: z.int().min(1), tier: z.int().min(0).optional(), speed: z.number().positive().optional(), }).optional(), places: id.optional(), max_stack: z.int().min(1).optional(), base_sell_value: z.int().min(0).optional(), food: z.object({ nutrition: z.int().min(0), saturation_modifier: z.number().min(0), always_edible: z.boolean().optional(), returns: id.optional(), }).optional(), // an entity model and a texture worn: z.strictObject({ model: id, texture: id, slim_model: id.optional(), slim_texture: id.optional(), }, "must be { model, texture }, an entity model and a texture").optional(), targets_fluids: z.boolean().optional(), fluid_container: z.strictObject({ capacity: z.int().min(1), full_max_stack: z.int().min(1).optional(), }).optional(), layers: z.array(z.strictObject({ texture: id, tint: z.custom( (value) => value === "fluid" || is_tint_color(value), 'must be "fluid", "grass", "foliage", "water" or a color like "#80a755"', ).optional(), })).optional(), name: text.optional(), lore: text.optional(), components: json_object.optional(), }); const ENTITY_BEHAVIORS = ["animal", "monster", "scripted", "object"]; // a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera. // an object without a model is drawn as the item it holds const entity_schema = z.object({ id, // an entity model, see EntityModelJson model: id.optional(), // only an object can go without one texture: id.optional(), // "animal" (the default) wanders around, panics when hurt and looks at players. "monster" goes after players it // sees and whoever hurts it, and despawns far from players, like minecraft's zombies. "scripted" stays where // scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook. "object" lies // around like a dropped item, holding one, without ai or health (see ItemRegistry.entity). any other id is a // behavior a mod's script registers behavior: z.custom( (value) => ENTITY_BEHAVIORS.includes(value as string) || id.safeParse(value).success, 'must be "animal", "monster", "scripted", "object" or a behavior id like "my_mod:thing"', ).optional(), // what natural spawning counts it as, see entity_category category: z.enum(["monster", "creature"]).optional(), // its collision box in blocks, width is for both x and z width: z.number().positive().max(16), height: z.number().positive().max(16), max_health: z.number().min(0).optional(), // minecraft's per tick speed, 0.25 for most animals movement_speed: z.number().min(0).optional(), // whether it jumps, onto blocks in its way and up its path, true when not set. one that doesn't still steps up its // step height, and swims up in water. see PATHFINDING.md jumps: z.boolean().optional(), // how many blocks it drops on its way, 3 when not set. 0 never walks off an edge, so it keeps out of pits max_fall: z.number().int().min(0).optional(), // what its hits do, for monsters. 2 when not set, like minecraft's attack_damage: z.number().min(0).optional(), // protection from physical and from arcane damage, not used yet physical_shielding: z.number().min(0).optional(), arcane_shielding: z.number().min(0).optional(), // what it drops when it dies, see common/loot.ts loot_table: loot_table_id.optional(), // what it sounds like: /hurt, /death, /step and /ambient, see ENTITY_SOUNDS sounds: sound_prefix.optional(), // how much bigger it's drawn than its model (or its texture, or its item), 1 when not set. its box stays the same scale: z.number().positive().optional(), }).refine((entity) => entity.texture !== undefined || entity.behavior === "object", { path: ["texture"], message: "is needed unless it's an object", }); export type EntityJson = z.infer; // like minecraft's MobCategory: monsters can spawn on their own and go away when no player is near, creatures stay. // monster behavior makes one a monster unless it says otherwise export function entity_category(json: EntityJson): "monster" | "creature" { return json.category ?? (json.behavior === "monster" ? "monster" : "creature"); } // like minecraft's MobEffectCategory, "neutral" when not set const effect_category = z.enum(["beneficial", "harmful", "neutral"]); export type EffectCategory = z.infer; // a status effect, like neoforge's MobEffect. what it does over time comes from components scripts register, see // docs/modding/entities/effects.md const effect_schema = z.object({ id, category: effect_category.optional(), // happens once when added instead of lasting, like instant health. its components' on_tick runs once instant: z.boolean().optional(), // a texture, shown at the top of the inventory screen while the player has it icon: id.optional(), // attribute modifiers while it's on, for level 1. each level adds that much again, like minecraft's speed modifiers: z.array(z.object({ attribute: id, amount: z.number(), operation: z.enum(["add_value", "add_multiplied_base", "add_multiplied_total"]), })).optional(), components: json_object.optional(), }); export type EffectJson = z.infer; // a kind of fluid, like neoforge's FluidType: what it is apart from any block, container or amount. a block flows in // the world with its own "fluid" field, which is another thing const fluid_schema = z.object({ id, // what players see, from the id when not set like an item's name: text.optional(), // for whatever shows it, like a layer tinted "fluid" on a full container color, // what a box of it is drawn with, tinted by its color, like neoforge's still texture. cubi:missing when not set texture: z.string().optional(), // what 1000 mB of it is worth when sold in a fluid container, like an item's base_sell_value base_sell_value: z.int().min(0).optional(), }); export type FluidJson = z.infer; const uv_pair = z.tuple([z.number(), z.number()]); // where one face of a cube is in the texture, from uv to uv + uv_size. a negative size flips it const face_uv = z.object({ uv: uv_pair, uv_size: uv_pair }); // a cube's faces, by the way they face. one that isn't here isn't drawn const face_uvs = z.object({ north: face_uv.optional(), east: face_uv.optional(), south: face_uv.optional(), west: face_uv.optional(), up: face_uv.optional(), down: face_uv.optional(), }); export type FaceUvs = z.infer; // a box from origin to origin + size. its uv is either [u, v], where a box's texture starts laid out like minecraft's // box uv (see the renderer's FACES), or where each face is const entity_cube = z.object({ origin: vec3, size: vec3, uv: z.union([uv_pair, face_uvs]), // grows the box this many pixels each way without moving its texture inflate: z.number().optional(), // what rotation turns the box around, inside its bone pivot: vec3.optional(), // degrees around x, y then z rotation: vec3.optional(), }); export type EntityCubeJson = z.infer; const entity_bone = z.object({ name: z.string(), parent: z.string().optional(), // what it turns around pivot: vec3, // degrees around x, y then z rotation: vec3.optional(), cubes: z.array(entity_cube), }); export type EntityBoneJson = z.infer; // a bedrock entity model (models/.geo.json) with only what the engine uses. positions and sizes are in // texture pixels, 16 to a block, and the model faces -z with its feet at 0 const entity_model_schema = z.object({ id, // the size its uvs are laid out for, the texture is stretched to it texture_width: z.int().min(1), texture_height: z.int().min(1), // how it's placed where it's shown as an item, from the geometry's item_display_transforms display: z.partialRecord(z.enum(DISPLAY_CONTEXTS), display_transform).optional(), // parents come before their children bones: z.array(entity_bone).superRefine((bones, ctx) => { const names = new Set(); bones.forEach((bone, i) => { const problem = (message: string) => ctx.addIssue({ code: "custom", path: [i], message }); if (names.has(bone.name)) problem(`there are two bones named ${bone.name}`); if (bone.parent !== undefined && !names.has(bone.parent)) { problem(`parent ${bone.parent} must be a bone before it`); } names.add(bone.name); }); }), }); export type EntityModelJson = z.infer; // a channel's value at a time in seconds. pre is what it comes into the keyframe at and post what it leaves at, the // same unless it jumps there. smooth is catmullrom to and from it, linear otherwise const clip_keyframe = z.object({ time: z.number().min(0), pre: vec3, post: vec3, smooth: z.boolean() }); export type ClipKeyframe = z.infer; const clip_channel = z.array(clip_keyframe).min(1).refine( (keyframes) => keyframes.every((keyframe, i) => i === 0 || keyframes[i - 1].time <= keyframe.time), "keyframes must be in time order", ); // an entity model animation (one of those in animations/.animation.json) with only what the engine uses, see // docs/modding/entities/index.md#clips. values are as bedrock has them, mirrored on x from the engine's like models: rotation in degrees, // added to a bone's own, position in pixels, and scale multiplying const clip_schema = z.object({ id: z.string('must be a clip id like "my_mod:thing/walk"').regex(TAG_ID_PATTERN), // seconds length: z.number().min(0), loop: z.boolean(), bones: z.record( z.string(), z.object({ rotation: clip_channel.optional(), position: clip_channel.optional(), scale: clip_channel.optional(), }), ), }); export type ClipJson = z.infer; // which volume slider a sound follows, each under the player's master volume. see docs/modding/resources/sounds.md export const SOUND_CATEGORIES = ["music", "ambient", "blocks", "entities", "players", "ui"] as const; export type SoundCategory = typeof SOUND_CATEGORIES[number]; // a path in a mod's sounds/ without .ogg, like jester/stomp_1, and a sound's name in sounds.json export const SOUND_PATH_PATTERN = /^[a-z0-9_]+(\/[a-z0-9_]+)*$/; // one of the sounds in a mod's sounds.json, with its id: the key "jester/step" in dangerous_business's is // dangerous_business:jester/step const sound_schema = z.object({ id: z.string('must be a sound id like "my_mod:thing/step"').regex(TAG_ID_PATTERN), // paths in the mod's own sounds/, one picked at random each time it plays files: z.array( z.string('must be a path in sounds/ without .ogg, like "thing/step_1"').regex(SOUND_PATH_PATTERN), ).min(1), // at most 1, plays multiply it. 1 when not given volume: z.number().min(0).max(1).optional(), // 1 when not given pitch: z.number().gt(0).optional(), // how far away it's heard at volume 1, in blocks. 16 when not given range: z.number().gt(0).optional(), // only the master volume when not given category: z.enum(SOUND_CATEGORIES).optional(), }); export type SoundJson = z.infer; export function validate_sound(json: unknown): Problems { return find_problems(sound_schema, json); } // the sounds the engine plays for a block or an entity whose json has "sounds", each after its prefix and a /. a sound // that isn't defined isn't played export const BLOCK_SOUNDS = ["break", "place", "step", "hit"] as const; export const ENTITY_SOUNDS = ["hurt", "death", "step", "ambient"] as const; // the id of the sound prefix has for kind, undefined when it has none export function sound_of(prefix: string | undefined, kind: string): string | undefined { const id = `${prefix}/${kind}`; return prefix !== undefined && EverythingRegistry.get("sounds", id) ? id : undefined; } // how far away a sound is heard at volume 1 when its definition doesn't say const DEFAULT_SOUND_RANGE = 16; // how far a sound played at volume is heard: its range, further for a louder one, like twice as far at volume 2 export function sound_range(json: SoundJson, volume = 1) { return (json.range ?? DEFAULT_SOUND_RANGE) * Math.max(1, (json.volume ?? 1) * volume); } // a mod playing sound with options: its definition, or an error saying what's wrong with them export function sound_to_play(sound: unknown, options: PlayOptions = {}): SoundJson { const json = typeof sound === "string" ? EverythingRegistry.get("sounds", sound) : undefined; if (!json) throw new Error(`unknown sound ${sound}`); const { volume = 1, pitch = 1 } = options; if (typeof volume !== "number" || !(volume >= 0) || !Number.isFinite(volume)) { throw new Error(`a sound's volume must be 0 or more`); } if (typeof pitch !== "number" || !(pitch > 0) || !Number.isFinite(pitch)) { throw new Error(`a sound's pitch must be more than 0`); } return json; } // whether a file starts the way every ogg does, so a wav or mp3 renamed to .ogg is caught when the mod is checked // instead of failing to play export function is_ogg(bytes: Uint8Array): boolean { return bytes.length >= 4 && bytes[0] === 0x4f && bytes[1] === 0x67 && bytes[2] === 0x67 && bytes[3] === 0x53; } // something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must const tag_entry = z.union( [id_or_tag, z.object({ id: id_or_tag, required: z.boolean().optional() })], 'must be an id, a "#tag", or { id, required }', ); export type TagEntryJson = z.infer; // a tag file, tags///.json, with the registry and id its path gives it. like neoforge's, // every mod's file for the same tag is merged, in load order const tag_schema = z.object({ registry: z.enum(TAG_REGISTRIES), id: z.string('must be a tag id like "my_mod:things" or "c:ingots/iron"').regex(TAG_ID_PATTERN), values: z.array(tag_entry), // drops what mods before this one put in the tag replace: z.boolean().optional(), // takes these out again, if they're in it remove: z.array(tag_entry).optional(), }); export type TagJson = z.infer; // an item a recipe takes: its id, a "#tag" of items, or a list of those any of which fits, like every kind of planks const item_choice = z.union([id_or_tag, z.array(id_or_tag).min(1)], 'must be an item id, a "#tag", or a list of them'); export type ItemChoice = z.infer; // the ids and #tags a choice lists, without looking inside the tags export function choice_list(choice: ItemChoice): string[] { return typeof choice === "string" ? [choice] : choice; } // every item that fits a choice, with its tags' items, once each. the tags must be loaded export function choice_ids(choice: ItemChoice): string[] { return expand_items(choice_list(choice)); } export function choice_matches(choice: ItemChoice, id: string): boolean { return list_matches("items", choice_list(choice), id); } const shaped_recipe = z.object({ type: z.literal("shaped"), // up to 3 by 3, a space is an empty slot pattern: z.array(z.string().min(1).max(3)).min(1).max(3), key: z.record(z.string(), item_choice), result: stack, }).superRefine((recipe, ctx) => { for (const letter of new Set(recipe.pattern.join("").replaceAll(" ", ""))) { if (!(letter in recipe.key)) { ctx.addIssue({ code: "custom", path: ["key"], message: `needs "${letter}", which pattern uses` }); } } }); export interface ModRecipeJson { type: `${string}:${string}`; [field: string]: unknown; } export type RecipeJson = z.infer | ModRecipeJson; const engine_recipes = new Map([ ["shaped", shaped_recipe], ]); // a mod's own types, like "bworld:cooking" for its cooking pot, are only stored by the engine. the mod parses them, // with ctx.recipes.register_type const recipe_schema = by_kind( "type", (type) => engine_recipes.get(type) ?? (ID_PATTERN.test(type) ? json_object : undefined), 'must be "shaped" or a mod\'s own type like "bworld:cooking"', ); // a recipe type a mod made up, as opposed to the engine's shaped export function is_mod_recipe(recipe: RecipeJson): recipe is ModRecipeJson { return recipe.type.includes(":"); } // the problems with an item or a stack in a mod's own recipe type, like the engine's own types' fields have, see // RecipeReader export function item_problems(json: unknown): Problems { return find_problems(id, json); } export function stack_problems(json: unknown): Problems { return find_problems(stack, json); } export function choice_problems(json: unknown): Problems { return find_problems(item_choice, json); } // the crafting grid's format, see server/game/crafting.ts export interface GridRecipe { width: number; height: number; pattern: (ItemChoice | undefined)[]; result: { id: string; count: number }; } // blocks export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJson { const json: BlockJson = { id: block.id, textures: block.textures }; if (block.name !== undefined) json.name = block.name; if (block.model !== undefined) json.model = block.model; if (block.variants !== undefined) json.variants = block.variants; if (block.render_layer && block.render_layer !== "solid") json.render_layer = block.render_layer; if (block.cull_same !== undefined) json.cull_same = block.cull_same; if (block.tint !== undefined) json.tint = block.tint; if (block.light_emission !== undefined) json.light_emission = block.light_emission; if (block.light_opacity !== undefined) json.light_opacity = block.light_opacity; if (block.alpha !== undefined) json.alpha = block.alpha; // fluids are without collision and replaceable unless they say otherwise if (block.has_collision === !!block.fluid) json.collision = block.has_collision; if (block.shape !== undefined) json.shape = block.shape; if (block.collision_shape !== undefined) json.collision_shape = block.collision_shape; if (block.parts !== undefined) json.parts = block.parts; if (block.item_model !== undefined) json.item_model = block.item_model; if (block.toughness !== undefined) { json.mining = { toughness: block.toughness }; if (block.tool_to_break !== undefined) json.mining.tool = block.tool_to_break; if (block.requires_tool) json.mining.requires_tool = true; if (block.tool_tier) json.mining.tier = block.tool_tier; } if (block.drop_table !== undefined) json.drops = block.drop_table; if (block.loot_table !== undefined) json.loot_table = block.loot_table; if (!has_item) json.item = false; if (block.interactive) json.interactive = true; if (block.sounds !== undefined) json.sounds = block.sounds; if (block.scrollable) json.scrollable = true; if (!!block.replaceable !== !!block.fluid) json.replaceable = !!block.replaceable; if (block.place_on) json.place_on = block.place_on; if (block.place_in) json.place_in = block.place_in; // a fluid's level state and a waterloggable block's waterlogged state are its own, added when it loads const added = block.fluid || block.waterloggable; const states = added ? block.states?.slice(0, -1) : block.states; if (states && (states.length > 0 || !added)) json.states = states; if (block.waterloggable) json.waterloggable = block.waterloggable; if (block.waterlogged_only) json.waterlogged_only = true; if (block.components) json.components = block.components; if (block.item_display) json.item_display = block.item_display; if (block.fluid) { // only what isn't the default const fluid = block.fluid; json.fluid = Object.fromEntries( Object.entries(fluid).filter(([key, value]) => FLUID_DEFAULTS[key as keyof FluidProperties] !== value), ); } return json; } export function block_from_json(json: BlockJson): { block: BlockRegistry; has_item: boolean } { const block: BlockRegistry = { id: json.id, textures: json.textures, has_collision: json.collision ?? !json.fluid, }; if (json.name !== undefined) block.name = json.name; if (json.model !== undefined) block.model = json.model; if (json.variants !== undefined) block.variants = json.variants; if (json.shape !== undefined) block.shape = json.shape; if (json.collision_shape !== undefined) block.collision_shape = json.collision_shape; if (json.parts !== undefined) block.parts = json.parts; if (json.item_model !== undefined) block.item_model = json.item_model; const render_layer = json.render_layer ?? (json.transparent ? "translucent" : undefined); if (render_layer && render_layer !== "solid") block.render_layer = render_layer; if (json.cull_same !== undefined) block.cull_same = json.cull_same; if (json.tint !== undefined) block.tint = json.tint; if (json.light_emission !== undefined) block.light_emission = json.light_emission; if (json.light_opacity !== undefined) block.light_opacity = json.light_opacity; if (json.alpha !== undefined) block.alpha = json.alpha; if (json.mining) { block.toughness = json.mining.toughness; block.requires_tool = json.mining.requires_tool ?? false; if (json.mining.tool !== undefined) block.tool_to_break = json.mining.tool; if (json.mining.tier) block.tool_tier = json.mining.tier; } if (json.drops !== undefined) block.drop_table = json.drops; if (json.loot_table !== undefined) block.loot_table = json.loot_table; if (json.interactive) block.interactive = true; if (json.scrollable) block.scrollable = true; if (json.sounds !== undefined) block.sounds = json.sounds; if (json.replaceable ?? json.fluid) block.replaceable = true; if (json.place_on) block.place_on = json.place_on; if (json.place_in) block.place_in = json.place_in; if (json.states) block.states = json.states; if (json.components) block.components = json.components; if (json.item_display) block.item_display = json.item_display; if (json.fluid) { block.fluid = { ...FLUID_DEFAULTS, ...json.fluid }; // last, so the block's own states keep their bits block.states = [...block.states ?? [], { ...FLUID_LEVEL }]; } if (json.waterlogged_only) block.waterlogged_only = true; if (json.waterloggable) { block.waterloggable = json.waterloggable; // last too, see WATERLOGGED block.states = [...block.states ?? [], { ...WATERLOGGED }]; } return { block, has_item: json.item ?? true }; } // items that aren't the item form of a block export function item_to_json(id: string, item: ItemRegistry): ItemJson { if (typeof item.texture_id !== "string") { throw new Error(`${id} picks its texture with a function, which json can't hold`); } const json: ItemJson = { id, texture: item.texture_id }; if (item.data_textures !== undefined) json.data_textures = item.data_textures; if (item.model !== undefined) json.model = item.model; if (item.entity !== undefined) json.entity = item.entity; if (item.tool !== undefined) json.tool = item.tool; if (item.block_id !== undefined) json.places = item.block_id; if (item.max_stack !== undefined) json.max_stack = item.max_stack; if (item.base_sell_value !== undefined) json.base_sell_value = item.base_sell_value; if (item.food !== undefined) json.food = item.food; if (item.worn !== undefined) json.worn = item.worn; if (item.targets_fluids !== undefined) json.targets_fluids = item.targets_fluids; if (item.fluid_container !== undefined) json.fluid_container = item.fluid_container; if (item.layers !== undefined) json.layers = item.layers; if (item.name !== undefined) json.name = item.name; if (item.lore !== undefined) json.lore = item.lore; if (item.components) json.components = item.components; return json; } export function item_from_json(json: ItemJson): ItemRegistry { if (json.texture === undefined) throw new Error(`${json.id} has no texture and isn't a block's item`); return { texture_id: json.texture, ...item_fields(json) }; } // an item json without a texture: what it sets replaces what the block's item has, the rest stays export function add_to_block_item(json: ItemJson, item: ItemRegistry) { Object.assign(item, item_fields(json)); } // everything but the texture function item_fields(json: ItemJson): Partial { const item: Partial = {}; if (json.data_textures !== undefined) item.data_textures = json.data_textures; if (json.model !== undefined) item.model = json.model; if (json.entity !== undefined) item.entity = json.entity; if (json.tool !== undefined) item.tool = { tier: 0, speed: 2, ...json.tool }; if (json.places !== undefined) item.block_id = json.places; if (json.max_stack !== undefined) item.max_stack = json.max_stack; if (json.base_sell_value !== undefined) item.base_sell_value = json.base_sell_value; if (json.food !== undefined) item.food = json.food; if (json.worn !== undefined) item.worn = json.worn; if (json.targets_fluids !== undefined) item.targets_fluids = json.targets_fluids; if (json.fluid_container !== undefined) item.fluid_container = json.fluid_container; if (json.layers !== undefined) item.layers = json.layers; if (json.name !== undefined) item.name = json.name; if (json.lore !== undefined) item.lore = json.lore; if (json.components) item.components = json.components; return item; } // shaped recipes <-> the grid format export function grid_recipe_to_json(recipe: GridRecipe): RecipeJson { const key: Record = {}; // by the choice as json, so equal lists share a letter const letters = new Map(); for (const choice of recipe.pattern) { if (choice === undefined || letters.has(JSON.stringify(choice))) continue; const letter = pick_letter(choice_list(choice)[0].replace("#", ""), new Set(letters.values())); letters.set(JSON.stringify(choice), letter); key[letter] = choice; } const pattern: string[] = []; for (let y = 0; y < recipe.height; y++) { let row = ""; for (let x = 0; x < recipe.width; x++) { const choice = recipe.pattern[y * recipe.width + x]; row += choice === undefined ? " " : letters.get(JSON.stringify(choice)); } pattern.push(row); } return { type: "shaped", pattern, key, result: recipe.result }; } export function grid_recipe_from_json(json: Extract): GridRecipe { const height = json.pattern.length; const width = Math.max(...json.pattern.map((row) => row.length)); const pattern: (ItemChoice | undefined)[] = []; for (const row of json.pattern) { for (let x = 0; x < width; x++) { const letter = row[x] ?? " "; pattern.push(letter === " " ? undefined : json.key[letter]); } } return { width, height, pattern, result: json.result }; } // a readable letter for an item in a pattern: its first letter if free, like P for planks function pick_letter(id: string, taken: Set) { const name = id.split(":")[1].split("/").at(-1)!.toUpperCase(); for (const letter of [...name, ..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"]) { if (/[A-Z]/.test(letter) && !taken.has(letter)) { return letter; } } throw new Error(`Ran out of letters for ${id}`); } // validation. every function returns a list of problems, empty when it's fine, see find_problems export function validate_manifest(json: unknown, folder_name: string): Problems { return find_problems(manifest_schema(folder_name), json); } // engine access isn't a stable api: a mod using it names one minor version of the game, like "~0.4.0" or "0.4.2", and // loading it on another is an error. game is the version it's loading on export function engine_version_problem(range: unknown, game = GAME_VERSION): string | undefined { const [major, minor, patch] = game.split(".").map(Number); const match = typeof range === "string" ? range.match(/^(~?)(\d+)\.(\d+)\.(\d+)$/) : null; if (!match) { return `engine_access needs game_version to be one minor version, like "~${major}.${minor}.0"`; } const [, tilde, m, n, p] = match; const fits = Number(m) === major && Number(n) === minor && (tilde ? Number(p) <= patch : Number(p) === patch); if (!fits) return `uses engine_access for game_version ${range}, this is the game's ${game}`; } export function validate_block(json: unknown): Problems { return find_problems(block_schema, json); } export function validate_model(json: unknown): Problems { return find_problems(model_schema, json); } export function validate_item(json: unknown): Problems { return find_problems(item_schema, json); } export function validate_recipe(json: unknown): Problems { return find_problems(recipe_schema, json); } export function validate_ore(json: unknown): Problems { return find_problems(ore_schema, json); } export function validate_spawn(json: unknown): Problems { return find_problems(spawn_schema, json); } export function validate_entity(json: unknown): Problems { return find_problems(entity_schema, json); } export function validate_effect(json: unknown): Problems { return find_problems(effect_schema, json); } export function validate_fluid(json: unknown): Problems { return find_problems(fluid_schema, json); } export function validate_entity_model(json: unknown): Problems { return find_problems(entity_model_schema, json); } // a models/.geo.json, as blockbench exports it for bedrock, to an EntityModelJson. its first geometry is used export function entity_model_from_geo(json: unknown, id: string): { model?: EntityModelJson; problems: Problems } { const geometry = is_object(json) && Array.isArray(json["minecraft:geometry"]) ? json["minecraft:geometry"][0] : undefined; if (!is_object(geometry) || !is_object(geometry.description)) { return { problems: ['must be a bedrock model: { "minecraft:geometry": [{ "description": ..., "bones": [...] }] }'], }; } const bones = Array.isArray(geometry.bones) ? geometry.bones : []; const display = geo_display(geometry.item_display_transforms); const model = { id, texture_width: geometry.description.texture_width, texture_height: geometry.description.texture_height, ...(display === undefined ? {} : { display }), bones: bones.map((bone) => { if (!is_object(bone)) return bone; const { name, parent, pivot, rotation } = bone; const cubes = Array.isArray(bone.cubes) ? bone.cubes : []; return { name, ...(parent === undefined ? {} : { parent }), pivot: pivot ?? [0, 0, 0], ...(rotation === undefined ? {} : { rotation }), cubes: cubes.map((cube) => { if (!is_object(cube)) return cube; const { origin, size, uv, inflate, pivot, rotation } = cube; return { origin, size, uv, ...(inflate === undefined ? {} : { inflate }), ...(rotation === undefined ? {} : { pivot: pivot ?? [0, 0, 0], rotation }), }; }), }; }), }; const problems = validate_entity_model(model); return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems }; } // the places a geometry's item_display_transforms has that items are shown in, with what of each the engine uses. their // rotation_pivot, scale_pivot and fit_to_frame are left out function geo_display(transforms: unknown): ModelDisplay | undefined { if (!is_object(transforms)) return undefined; const display: Record = {}; for (const context of DISPLAY_CONTEXTS) { const transform = transforms[context]; if (!is_object(transform)) continue; const { rotation, translation, scale } = transform; display[context] = { ...(rotation === undefined ? {} : { rotation }), ...(translation === undefined ? {} : { translation }), ...(scale === undefined ? {} : { scale }), }; } return Object.keys(display).length > 0 ? display as ModelDisplay : undefined; } export function validate_clip(json: unknown): Problems { return find_problems(clip_schema, json); } // what a bedrock animation can have that clips leave to an animator's code const ANIMATOR_FIELDS = [ "anim_time_update", "blend_weight", "start_delay", "loop_delay", "override_previous_animation", "sound_effects", "particle_effects", "timeline", ]; // an animations/.animation.json, as blockbench exports it for bedrock, to its clips. each is / and the // last part of its name, so animation.jester.walk in dangerous_business:jester is dangerous_business:jester/walk. // warnings are what it has that clips don't use export function clips_from_bedrock( json: unknown, file_id: string, ): { clips: ClipJson[]; problems: Problems; warnings: Problems } { const problems: Problems = []; const warnings: Problems = []; if (!is_object(json) || !is_object(json.animations)) { problems.push('must be a bedrock animation file: { "animations": { "animation.thing.walk": { ... } } }'); return { clips: [], problems, warnings }; } const clips: ClipJson[] = []; for (const [name, animation] of Object.entries(json.animations)) { const problem = (message: string) => problems.push(`${name}: ${message}`); const id = `${file_id}/${name.split(".").at(-1)!.toLowerCase()}`; if (clips.some((clip) => clip.id === id)) { problem(`its id ${id} is another animation's too`); continue; } if (!is_object(animation)) { problem("must be an object"); continue; } for (const field of ANIMATOR_FIELDS) { if (field in animation) warnings.push(`${name}: ${field} isn't used, an animator does that in code`); } if (![undefined, true, false, "hold_on_last_frame"].includes(animation.loop as string)) { problem('loop must be true, false or "hold_on_last_frame"'); } const length = animation.animation_length; if (length !== undefined && (typeof length !== "number" || length < 0)) { problem("animation_length must be a number of seconds"); } const bones: ClipJson["bones"] = {}; let last = 0; for (const [bone, channels] of Object.entries(is_object(animation.bones) ? animation.bones : {})) { if (!is_object(channels)) { problem(`${bone} must be an object of channels`); continue; } const read: ClipJson["bones"][string] = {}; for (const [channel, value] of Object.entries(channels)) { if (channel !== "rotation" && channel !== "position" && channel !== "scale") { warnings.push(`${name}: ${bone}'s ${channel} isn't used`); continue; } const keyframes = read_channel(value, (message) => problem(`${bone} ${channel}: ${message}`)); if (!keyframes) continue; read[channel] = keyframes; last = Math.max(last, keyframes.at(-1)!.time); } bones[bone] = read; } const clip = { id, length: typeof length === "number" ? length : last, loop: animation.loop === true, bones }; for (const message of validate_clip(clip)) problem(message); clips.push(clip); } return { clips: problems.length === 0 ? clips : [], problems, warnings }; } // a channel: one value for the whole clip, or keyframes by time in seconds function read_channel(value: unknown, problem: (message: string) => void): ClipKeyframe[] | undefined { const single = !is_object(value) || "pre" in value || "post" in value || "vector" in value; if (single) { const keyframe = read_keyframe(0, value, problem); return keyframe && [keyframe]; } const keyframes: ClipKeyframe[] = []; for (const [time, keyframe_value] of Object.entries(value)) { const seconds = Number(time); if (time.trim() === "" || !(seconds >= 0)) { problem(`${time} isn't a time in seconds`); return undefined; } const keyframe = read_keyframe(seconds, keyframe_value, (message) => problem(`at ${time}: ${message}`)); if (!keyframe) return undefined; keyframes.push(keyframe); } if (keyframes.length === 0) { problem("has no keyframes"); return undefined; } return keyframes.sort((a, b) => a.time - b.time); } // a value, { "pre": value, "post": value, "lerp_mode": ... } with either of pre and post, or geckolib's older // { "vector": value, "easing": ... } function read_keyframe(time: number, value: unknown, problem: (message: string) => void): ClipKeyframe | undefined { if (!is_object(value)) { const vector = read_vector(value, problem); return vector && { time, pre: vector, post: vector, smooth: false }; } const lerp = "vector" in value ? value.easing : value.lerp_mode; if (lerp !== undefined && lerp !== "linear" && lerp !== "catmullrom") { problem(`${"vector" in value ? "easing" : "lerp_mode"} ${JSON.stringify(lerp)} isn't supported`); return undefined; } if ("vector" in value) { const vector = read_vector(value.vector, problem); return vector && { time, pre: vector, post: vector, smooth: lerp === "catmullrom" }; } if (value.pre === undefined && value.post === undefined) { problem("needs pre or post"); return undefined; } const pre = read_vector(value.pre ?? value.post, problem); const post = read_vector(value.post ?? value.pre, problem); return pre && post && { time, pre, post, smooth: lerp === "catmullrom" }; } // [x, y, z], or one number for all three. numbers can be written as text, but not expressions, which are code function read_vector(value: unknown, problem: (message: string) => void): [number, number, number] | undefined { if (!Array.isArray(value)) { const number = read_number(value, problem); return number === undefined ? undefined : [number, number, number]; } if (value.length !== 3) { problem("must be [x, y, z] or a number"); return undefined; } const numbers = value.map((part) => read_number(part, problem)); return numbers.every((number) => number !== undefined) ? numbers as [number, number, number] : undefined; } function read_number(value: unknown, problem: (message: string) => void): number | undefined { const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value; if (typeof number === "number" && Number.isFinite(number)) return number; problem( typeof value === "string" ? `${JSON.stringify(value)} is an expression, which clips can't run: an animator does that in code` : "must be [x, y, z] or a number", ); return undefined; } // a tag file's contents, with the registry and id its path gives it export function validate_tag(json: unknown): Problems { return find_problems(tag_schema, json); }