From 4fad43d9cc39c4f52cb73c1aea7bf01880060a2e Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 25 Oct 2026 12:41:46 -0300 Subject: [PATCH] Validators using zod --- common/block_models.ts | 7 +- common/bmod.ts | 3 +- common/loot.ts | 267 +++---- common/mod_check.ts | 4 +- common/mod_data.ts | 1278 ++++++++++++--------------------- common/schema.ts | 141 ++++ common/texture_animation.ts | 92 +-- common/worldgen/biomes.ts | 117 +-- common/worldgen/data.ts | 574 ++++++--------- common/worldgen/features.ts | 353 ++++----- deno.json | 3 +- deno.lock | 17 +- server/load_bmods.ts | 8 +- tests/bmod_test.ts | 4 +- tests/liquid_test.ts | 12 +- tests/mod_entity_test.ts | 23 +- tests/mod_tools_test.ts | 6 +- tests/model_parents_test.ts | 2 +- tests/tags_test.ts | 8 +- tools/check_mods.ts | 91 +-- tools/importer/models.ts | 11 +- tools/importer/resources.ts | 3 +- tools/importer/tags.ts | 3 +- tools/verdigris_wire_model.ts | 3 +- 24 files changed, 1242 insertions(+), 1788 deletions(-) create mode 100644 common/schema.ts diff --git a/common/block_models.ts b/common/block_models.ts index dbb0fa5..318e5e3 100644 --- a/common/block_models.ts +++ b/common/block_models.ts @@ -7,9 +7,7 @@ import { type BlockRegistry, type BlockTextures, liquid_textures } from "./everything_registry.ts"; import { tint_without_biome } from "./worldgen/biome_colors.ts"; import { get_state_value } from "./utils.ts"; - -export type ModelFace = "top" | "bottom" | "north" | "south" | "west" | "east"; -export const MODEL_FACES: ModelFace[] = ["top", "bottom", "north", "south", "west", "east"]; +import { type DisplayContext, MODEL_FACES, type ModelFace } from "./mod_data.ts"; export interface ModelFaceJson { // a texture variable like "#side", or a texture id @@ -47,9 +45,6 @@ export interface DisplayTransform { scale?: [number, number, number]; } -// 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]; export type ModelDisplay = Partial>; // a model as a mod writes it in models/. it can start from a parent, like minecraft's: it gets the parent's elements diff --git a/common/bmod.ts b/common/bmod.ts index d7b6ffc..109cc3d 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -11,8 +11,6 @@ import { type EffectJson, type EntityJson, type EntityModelJson, - ID_PATTERN, - is_object, type ItemJson, type ManifestJson, type OreJson, @@ -31,6 +29,7 @@ import { validate_spawn, validate_tag, } from "./mod_data.ts"; +import { ID_PATTERN, is_object } from "./schema.ts"; import type { ModData } from "./mod_loader.ts"; import { type LootTableJson, validate_loot_table } from "./loot.ts"; import { type BiomeJson, validate_biome } from "./worldgen/biomes.ts"; diff --git a/common/loot.ts b/common/loot.ts index b60d169..48ccdcf 100644 --- a/common/loot.ts +++ b/common/loot.ts @@ -6,9 +6,19 @@ // decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own // conditions and functions (ctx.loot in server scripts), which are ids in their namespace. // see docs/modding/resources/loot_tables.md +import * as z from "zod"; import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts"; import { list_matches, Tags } from "./tags.ts"; -import { is_object, TAG_ID_PATTERN } from "./mod_data.ts"; +import { + by_kind, + find_problems, + id, + id_or_tag, + json_object, + loot_table_id, + type Problems, + TAG_ID_PATTERN, +} from "./schema.ts"; // a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's // constant, uniform and binomial number providers @@ -87,17 +97,6 @@ export interface LootEnvironment { random?: () => number; } -export const LOOT_CONDITIONS = [ - "random_chance", - "match_tool", - "block_state", - "killed_by_player", - "inverted", - "any_of", - "all_of", -] as const; -export const LOOT_FUNCTIONS = ["set_count", "limit_count", "set_data"] as const; -const ENTRY_TYPES = ["item", "tag", "loot_table", "empty"]; // tables in tables in tables: past this it's taken as a loop and gives nothing more const MAX_DEPTH = 16; @@ -263,155 +262,105 @@ function apply( // checking a table's json -type Problems = string[]; +const whole = z.int().min(0); + +const number_provider: z.ZodType = z.union([ + whole, + z.object({ min: whole, max: whole }).refine(({ min, max }) => min <= max, { + path: ["max"], + message: "can't be below min", + }), + z.object({ n: whole, p: z.number().min(0).max(1) }), +], "must be a whole number, { min, max } or { n, p }"); + +const conditions = z.array(z.lazy(() => loot_condition)); + +// the engine's conditions, by name +const CONDITIONS = new Map([ + ["random_chance", z.object({ chance: z.number().min(0).max(1) })], + [ + "match_tool", + z.object({ items: z.array(id_or_tag).optional(), tool: z.string().optional(), min_tier: z.int().optional() }), + ], + [ + "block_state", + z.object({ + block: id.optional(), + states: z.record( + z.string(), + z.union( + [z.int(), z.object({ min: z.int().optional(), max: z.int().optional() })], + 'must be a number or { min, max }, like { "age": 7 }', + ), + ), + }), + ], + ["killed_by_player", z.object({})], + ["inverted", z.object({ term: z.lazy(() => loot_condition) })], + ["any_of", z.object({ terms: conditions })], + ["all_of", z.object({ terms: conditions })], +]); + +// any other condition is a mod's own, by its id. the server checks a script registered it when it starts +const loot_condition: z.ZodType = by_kind( + "condition", + (name) => CONDITIONS.get(name) ?? (name.includes(":") ? json_object : undefined), + `must be one of ${[...CONDITIONS.keys()].join(", ")}, or a mod's own condition's id`, +); + +// every function can have conditions +const loot_function_base = z.object({ conditions: conditions.optional() }); + +// the engine's functions, by name +const FUNCTIONS = new Map([ + ["set_count", loot_function_base.extend({ count: number_provider, add: z.boolean().optional() })], + ["limit_count", loot_function_base.extend({ min: z.int().optional(), max: z.int().optional() })], + ["set_data", loot_function_base.extend({ data: z.unknown() })], +]); + +// any other function is a mod's own, like conditions +const loot_function: z.ZodType = by_kind( + "function", + (name) => FUNCTIONS.get(name) ?? (name.includes(":") ? loot_function_base : undefined), + `must be one of ${[...FUNCTIONS.keys()].join(", ")}, or a mod's own function's id`, +); + +const functions = z.array(loot_function); + +// every entry can have these +const loot_entry_base = z.object({ + weight: z.number().min(0).optional(), + conditions: conditions.optional(), + functions: functions.optional(), +}); + +const loot_entry: z.ZodType = z.discriminatedUnion("type", [ + loot_entry_base.extend({ type: z.literal("item").optional(), item: id, count: number_provider.optional() }), + loot_entry_base.extend({ + type: z.literal("tag"), + tag: z.string('must be a #tag, like "#bworld:logs"').refine((tag) => + tag.startsWith("#") && TAG_ID_PATTERN.test(tag.slice(1)) + ), + count: number_provider.optional(), + }), + loot_entry_base.extend({ type: z.literal("loot_table"), table: loot_table_id }), + loot_entry_base.extend({ type: z.literal("empty") }), +]); + +const loot_table_schema: z.ZodType = z.object({ + id: z.string("its file name must be a-z, 0-9 and _, in folders").regex(TAG_ID_PATTERN), + pools: z.array(z.object({ + rolls: number_provider.optional(), + conditions: conditions.optional(), + entries: z.array(loot_entry).min(1), + functions: functions.optional(), + })), + conditions: conditions.optional(), + functions: functions.optional(), +}); export function validate_loot_table(json: unknown): Problems { - if (!is_object(json)) return ["loot_table must be an object"]; - const problems: Problems = []; - if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) { - problems.push("its file name must be a-z, 0-9 and _, in folders"); - } - problems.push(...validate_conditions(json.conditions, "conditions")); - problems.push(...validate_functions(json.functions, "functions")); - if (!Array.isArray(json.pools)) return [...problems, "pools must be a list"]; - json.pools.forEach((pool, i) => { - const where = `pools[${i}]`; - if (!is_object(pool)) return problems.push(`${where} must be { rolls, entries }`); - if (pool.rolls !== undefined) problems.push(...validate_number(pool.rolls, `${where}.rolls`)); - problems.push(...validate_conditions(pool.conditions, `${where}.conditions`)); - problems.push(...validate_functions(pool.functions, `${where}.functions`)); - if (!Array.isArray(pool.entries) || pool.entries.length === 0) { - return problems.push(`${where}.entries must be a list of entries`); - } - pool.entries.forEach((entry, j) => problems.push(...validate_entry(entry, `${where}.entries[${j}]`))); - }); - return problems; -} - -function validate_entry(entry: unknown, where: string): Problems { - if (!is_object(entry)) return [`${where} must be { type, item, weight }`]; - const problems: Problems = []; - const type = entry.type ?? "item"; - if (typeof type !== "string" || !ENTRY_TYPES.includes(type)) { - problems.push(`${where}.type must be one of ${ENTRY_TYPES.join(", ")}`); - } - const field = { item: "item", tag: "tag", loot_table: "table" }[type as string]; - if (field && typeof entry[field] !== "string") problems.push(`${where}.${field} is needed for a "${type}" entry`); - if (type === "tag" && typeof entry.tag === "string" && !entry.tag.startsWith("#")) { - problems.push(`${where}.tag must be a #tag, like "#bworld:logs"`); - } - if (entry.count !== undefined) problems.push(...validate_number(entry.count, `${where}.count`)); - if (entry.weight !== undefined && (typeof entry.weight !== "number" || entry.weight < 0)) { - problems.push(`${where}.weight must be a number, 0 or more`); - } - problems.push(...validate_conditions(entry.conditions, `${where}.conditions`)); - problems.push(...validate_functions(entry.functions, `${where}.functions`)); - return problems; -} - -export function validate_number(value: unknown, where: string): Problems { - const whole = (n: unknown) => Number.isInteger(n) && (n as number) >= 0; - if (whole(value)) return []; - if (is_object(value) && whole(value.min) && whole(value.max) && (value.max as number) >= (value.min as number)) { - return []; - } - if ( - is_object(value) && whole(value.n) && typeof value.p === "number" && value.p >= 0 && value.p <= 1 - ) return []; - return [`${where} must be a whole number, { min, max } or { n, p }`]; -} - -function validate_conditions(list: unknown, where: string): Problems { - if (list === undefined) return []; - if (!Array.isArray(list)) return [`${where} must be a list`]; - return list.flatMap((condition, i) => validate_condition(condition, `${where}[${i}]`)); -} - -function validate_condition(condition: unknown, where: string): Problems { - if (!is_object(condition) || typeof condition.condition !== "string") { - return [`${where} must be { "condition": ... }`]; - } - const name = condition.condition; - switch (name) { - case "random_chance": { - const chance = condition.chance; - return typeof chance === "number" && chance >= 0 && chance <= 1 - ? [] - : [`${where}.chance must be from 0 to 1`]; - } - case "match_tool": { - const problems: Problems = []; - const items = condition.items; - if (items !== undefined && !(Array.isArray(items) && items.every((i) => typeof i === "string"))) { - problems.push(`${where}.items must be a list of item ids and #tags`); - } - if (condition.tool !== undefined && typeof condition.tool !== "string") { - problems.push(`${where}.tool must be a tool type, like "axe"`); - } - if (condition.min_tier !== undefined && !Number.isInteger(condition.min_tier)) { - problems.push(`${where}.min_tier must be a whole number`); - } - return problems; - } - case "block_state": { - const states = condition.states; - const ok = is_object(states) && Object.values(states).every((match) => - Number.isInteger(match) || - (is_object(match) && (match.min === undefined || Number.isInteger(match.min)) && - (match.max === undefined || Number.isInteger(match.max))) - ); - return ok ? [] : [`${where}.states must map states to a number or { min, max }, like { "age": 7 }`]; - } - case "killed_by_player": - return []; - case "inverted": - return validate_condition(condition.term, `${where}.term`); - case "any_of": - case "all_of": - return Array.isArray(condition.terms) - ? condition.terms.flatMap((term, i) => validate_condition(term, `${where}.terms[${i}]`)) - : [`${where}.terms must be a list of conditions`]; - } - return name.includes(":") ? [] : [ - `${where}: ${name} isn't a loot condition. the engine's are ${LOOT_CONDITIONS.join(", ")}, a mod's has its id`, - ]; -} - -function validate_functions(list: unknown, where: string): Problems { - if (list === undefined) return []; - if (!Array.isArray(list)) return [`${where} must be a list`]; - return list.flatMap((fn, i) => { - const at = `${where}[${i}]`; - if (!is_object(fn) || typeof fn.function !== "string") return [`${at} must be { "function": ... }`]; - const problems = validate_conditions(fn.conditions, `${at}.conditions`); - switch (fn.function) { - case "set_count": - problems.push(...validate_number(fn.count, `${at}.count`)); - if (fn.add !== undefined && typeof fn.add !== "boolean") { - problems.push(`${at}.add must be true or false`); - } - break; - case "limit_count": - for (const key of ["min", "max"]) { - if (fn[key] !== undefined && !Number.isInteger(fn[key])) { - problems.push(`${at}.${key} must be a whole number`); - } - } - break; - case "set_data": - if (fn.data === undefined) problems.push(`${at}.data is needed`); - break; - default: - if (!fn.function.includes(":")) { - problems.push( - `${at}: ${fn.function} isn't a loot function. the engine's are ${ - LOOT_FUNCTIONS.join(", ") - }, a mod's has its id`, - ); - } - } - return problems; - }); + return find_problems(loot_table_schema, json); } // what a table refers to, for check-mods: items, item #tags, other tables, and mods' conditions and functions diff --git a/common/mod_check.ts b/common/mod_check.ts index d635fca..bda7160 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -406,12 +406,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable, refs); + noise_settings_refs(json, refs); check_worldgen("noise settings", file, json.id, refs); } for (const { file, json } of mod.biome_sources ?? []) { const refs = new_refs(); - biome_source_refs(json as unknown as Record, refs); + biome_source_refs(json, refs); check_worldgen("biome source", file, json.id, refs); // what its rules look at, in every generator that uses it const users = all_noise_settings.filter((settings) => settings.biome_source === (json.extends ?? json.id)); diff --git a/common/mod_data.ts b/common/mod_data.ts index d23d5b4..23e1a6e 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -3,6 +3,7 @@ // 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, @@ -19,44 +20,74 @@ import { WATERLOGGED, type WornProperties, } from "./everything_registry.ts"; -import { - type BlockPart, - type BlockVariant, - DISPLAY_CONTEXTS, - type DisplayContext, - MODEL_FACES, - type ModelFace, -} from "./block_models.ts"; +import type { BlockPart, BlockVariant, ModelFileJson } from "./block_models.ts"; import { expand_items, list_matches } from "./tags.ts"; import { GAME_VERSION } from "./constants.ts"; +import { + by_kind, + 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 ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/; export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/; export const RESERVED_NAMESPACES = ["bworld", "engine"]; -// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md -export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/; // 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"]; -export interface ManifestJson { - format_version: number; - id: string; - name: string; - description?: string; - version: string; - authors?: string[]; - game_version?: string; - // imports bworld/engine to reach into the engine and hook its methods. needs game_version within one minor version - engine_access?: boolean; - dependencies?: { id: string; version: string }[]; - scripts?: { server?: string; client?: string; worldgen?: string; shared?: string }; - credits?: string; -} +// 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]); +// 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) }); + +// 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 bworld/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(), + scripts: z.strictObject({ + server: z.string().optional(), + client: z.string().optional(), + worldgen: z.string().optional(), + shared: z.string().optional(), + }).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; @@ -98,30 +129,225 @@ export interface BlockJson { waterlogged_only?: boolean; } -export interface OreJson { - id: string; - replaces: string; - min_y: number; - max_y: number; - scale: number; - threshold: number; +// 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: z.custom(is_tint_color, 'must be "grass", "foliage", "water" or a color like "#80a755"'), + // 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(), + 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(), + liquid: z.strictObject({ + range: z.int().min(1).max(MAX_LIQUID_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 liquid's and a plain cube's textures can be, past being ids +const liquid_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.liquid) { + // a liquid is drawn by the engine, so it has no model of its own, and its level is a state it gets + if (!liquid_textures.safeParse(block.textures).success) { + problem(["textures"], "must be a texture id or { still, flowing } for a liquid"); + } + for (const key of ["model", "variants", "parts", "shape", "collision_shape", "item_model"] as const) { + if (block[key] !== undefined) problem([key], "isn't for liquids, the engine draws them"); + } + if (names.has(LIQUID_LEVEL.name)) { + problem(["states"], `can't have "${LIQUID_LEVEL.name}", a liquid gets that state of its own`); + } + if (block.waterloggable !== undefined) problem(["waterloggable"], "isn't for liquids"); + } else if (block.parts === undefined && (block.model ?? "engine:cube") === "engine: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 liquid it's placed into"); + } + // a block's states fit in 16 bits, with the one it gets for being a liquid or waterloggable + const added = block.liquid ? LIQUID_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, + replaces: id, + 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 -export interface SpawnJson { - entity: string; +const spawn_schema = z.object({ + entity: id, // how often it's picked over the other spawns where both can spawn - weight: number; + weight: z.int().min(0), // how many spawn together - min_count: number; - max_count: number; + min_count: z.int().min(1), + max_count: z.int().min(1), // only in these biomes, every biome when not set - biomes?: string[]; + 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?: number; -} + 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; @@ -146,98 +372,162 @@ export interface ItemJson { components?: Record; } +const item_schema: z.ZodType = z.object({ + id, + texture: id.optional(), + data_textures: z.record(z.string(), id).optional(), + model: 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_liquids: z.boolean().optional(), + name: text.optional(), + lore: text.optional(), + components: json_object.optional(), +}); + // a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera -export interface EntityJson { - id: string; +const entity_schema = z.object({ + id, // an entity model, see EntityModelJson - model?: string; - texture: string; + model: id.optional(), + texture: id, // "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 - behavior?: "animal" | "monster" | "scripted"; + behavior: z.enum(["animal", "monster", "scripted"]).optional(), // its collision box in blocks, width is for both x and z - width: number; - height: number; - max_health?: number; + 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?: number; + movement_speed: z.number().min(0).optional(), // what its hits do, for monsters. 2 when not set, like minecraft's - attack_damage?: number; + attack_damage: z.number().min(0).optional(), // protection from physical and from arcane damage, not used yet - physical_shielding?: number; - arcane_shielding?: number; + 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?: string; -} + loot_table: loot_table_id.optional(), +}); + +export type EntityJson = z.infer; + +// 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 -export interface EffectJson { - id: string; - // like minecraft's MobEffectCategory, "neutral" when not set - category?: EffectCategory; +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?: boolean; + instant: z.boolean().optional(), // a texture, shown at the top of the inventory screen while the player has it - icon?: string; + icon: id.optional(), // attribute modifiers while it's on, for level 1. each level adds that much again, like minecraft's speed - modifiers?: { attribute: string; amount: number; operation: EffectModifierOperation }[]; - components?: Record; -} + 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 EffectCategory = "beneficial" | "harmful" | "neutral"; -export type EffectModifierOperation = "add_value" | "add_multiplied_base" | "add_multiplied_total"; +export type EffectJson = z.infer; -type Vec3 = [number, number, number]; +// a box from origin to origin + size, textured like minecraft's box uv: see the renderer's FACES +const entity_cube = z.object({ + origin: vec3, + size: vec3, + uv: z.tuple([z.number(), z.number()], "must be [u, v], per face uvs aren't supported"), + // grows the box this many pixels each way without moving its texture + inflate: z.number().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 -export interface EntityModelJson { - id: string; +const entity_model_schema = z.object({ + id, // the size its uvs are laid out for, the texture is stretched to it - texture_width: number; - texture_height: number; + texture_width: z.int().min(1), + texture_height: z.int().min(1), // parents come before their children - bones: EntityBoneJson[]; -} + 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 interface EntityBoneJson { - name: string; - parent?: string; - // what it turns around - pivot: Vec3; - // degrees around x, y then z - rotation?: Vec3; - cubes: EntityCubeJson[]; -} - -// a box from origin to origin + size, textured like minecraft's box uv: see the renderer's FACES -export interface EntityCubeJson { - origin: Vec3; - size: Vec3; - uv: [number, number]; - // grows the box this many pixels each way without moving its texture - inflate?: number; -} +export type EntityModelJson = z.infer; // something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must -export type TagEntryJson = string | { id: string; required?: boolean }; +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 -export interface TagJson { - registry: TagRegistry; - id: string; - values: TagEntryJson[]; +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?: boolean; + replace: z.boolean().optional(), // takes these out again, if they're in it - remove?: TagEntryJson[]; -} + 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 -export type ItemChoice = string | string[]; +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[] { @@ -253,32 +543,66 @@ export function choice_matches(choice: ItemChoice, id: string): boolean { return list_matches("items", choice_list(choice), id); } -export type RecipeJson = - | { - type: "shaped"; - pattern: string[]; - key: Record; - result: { id: string; count: number }; +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` }); + } } - | { type: "furnace"; input: ItemChoice; output: { id: string; count: number }; cook_time: number } - | { type: "fuel"; item: ItemChoice; burn_time: number } - // upgrades a tool at a smithing table, with some of a material and maybe one more item - | { - type: "smithing"; - tool: string; - material: { id: string; count: number }; - addition?: string; - result: string; - } - // a mod's own recipe type, like "farmersdelight:cooking" for its cooking pot. the engine only stores these, the mod's - // server script reads them with ctx.recipes.list and checks the rest - | ModRecipeJson; +}); + +// cook_time and burn_time are in ticks +const furnace_recipe = z.object({ + type: z.literal("furnace"), + input: item_choice, + output: stack, + cook_time: z.int().min(1), +}); + +const fuel_recipe = z.object({ type: z.literal("fuel"), item: item_choice, burn_time: z.int().min(1) }); + +// upgrades a tool at a smithing table, with some of a material and maybe one more item +const smithing_recipe = z.object({ + type: z.literal("smithing"), + tool: id, + material: stack, + addition: id.optional(), + result: id, +}); export interface ModRecipeJson { type: `${string}:${string}`; [field: string]: unknown; } +export type RecipeJson = + | z.infer + | z.infer + | z.infer + | z.infer + | ModRecipeJson; + +const engine_recipes = new Map([ + ["shaped", shaped_recipe], + ["furnace", furnace_recipe], + ["fuel", fuel_recipe], + ["smithing", smithing_recipe], +]); + +// a mod's own types, like "farmersdelight:cooking" for its cooking pot, are only stored by the engine. the mod's server +// script reads them with ctx.recipes.list and checks them +const recipe_schema = by_kind( + "type", + (type) => engine_recipes.get(type) ?? (ID_PATTERN.test(type) ? json_object : undefined), + 'must be "shaped", "furnace", "fuel", "smithing" or a mod\'s own type like "farmersdelight:cooking"', +); + // a recipe type a mod made up, as opposed to the engine's shaped, furnace, fuel and smithing export function is_mod_recipe(recipe: RecipeJson): recipe is ModRecipeJson { return recipe.type.includes(":"); @@ -493,57 +817,10 @@ function pick_letter(id: string, taken: Set) { throw new Error(`Ran out of letters for ${id}`); } -// validation. every function returns a list of problems, empty when it's fine - -type Problems = string[]; +// 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 { - const problems: Problems = []; - if (!is_object(json)) return ["manifest.json must be an object"]; - - if (json.format_version !== FORMAT_VERSION) { - problems.push(`format_version must be ${FORMAT_VERSION}`); - } - if (typeof json.id !== "string" || !NAMESPACE_PATTERN.test(json.id)) { - problems.push("id must be 1-32 characters of a-z, 0-9 and _"); - } else if (json.id !== folder_name) { - problems.push(`id "${json.id}" must match the folder name "${folder_name}"`); - } - if (typeof json.name !== "string" || json.name.length === 0) problems.push("name is required"); - if (typeof json.version !== "string" || !/^\d+\.\d+\.\d+/.test(json.version)) { - problems.push("version must be semver, like 1.0.0"); - } - if (json.engine_access !== undefined && typeof json.engine_access !== "boolean") { - problems.push("engine_access must be true or false"); - } - if (json.engine_access === true) { - const problem = engine_version_problem(json.game_version); - if (problem) problems.push(problem); - } - if (json.dependencies !== undefined) { - if (!Array.isArray(json.dependencies)) { - problems.push("dependencies must be a list"); - } else { - for (const dep of json.dependencies) { - if (!is_object(dep) || typeof dep.id !== "string" || typeof dep.version !== "string") { - problems.push("each dependency needs an id and a version range"); - } - } - } - } - if (json.scripts !== undefined) { - if (!is_object(json.scripts)) { - problems.push("scripts must be an object"); - } else { - for (const [side, path] of Object.entries(json.scripts)) { - if (!["server", "client", "worldgen", "shared"].includes(side)) { - problems.push(`unknown script "${side}"`); - } - if (typeof path !== "string") problems.push(`scripts.${side} must be a path`); - } - } - } - return 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 @@ -561,616 +838,39 @@ export function engine_version_problem(range: unknown, game = GAME_VERSION): str } export function validate_block(json: unknown): Problems { - if (!is_object(json)) return ["block must be an object"]; - const problems = validate_id(json.id, "id"); - if (json.model !== undefined) problems.push(...validate_id(json.model, "model")); - const is_cube = json.parts === undefined && (json.model === undefined || json.model === "engine:cube"); - const textures = json.textures; - if (json.liquid !== undefined) { - problems.push(...validate_liquid(json)); - } else if (is_cube) { - const texture_ok = typeof textures === "string" || - (is_object(textures) && - (["top", "bottom", "side"].every((k) => typeof textures[k] === "string") || - ["front", "side"].every((k) => typeof textures[k] === "string"))); - if (!texture_ok) problems.push("textures must be a texture id, { top, bottom, side } or { front, side }"); - } else { - problems.push(...validate_textures(textures, "textures")); - } - if (json.variants !== undefined) { - if (!is_object(json.variants)) { - problems.push('variants must map conditions like "age=3" to { model, textures, y }'); - } else { - const names = new Set(Array.isArray(json.states) ? json.states.map((s) => is_object(s) ? s.name : "") : []); - for (const [condition, variant] of Object.entries(json.variants)) { - const where = `variants["${condition}"]`; - for (const part of condition === "" ? [] : condition.split(",")) { - const [name, value] = part.split("=").map((p) => p.trim()); - if (!names.has(name) || !/^\d+$/.test(value ?? "")) { - problems.push(`${where}: "${part}" must be a state of this block and a number, like age=3`); - } - } - if (!is_object(variant)) { - problems.push(`${where} must be { model, textures, y, shape }`); - continue; - } - if (variant.model !== undefined) problems.push(...validate_id(variant.model, `${where}.model`)); - if (variant.textures !== undefined) { - problems.push(...validate_textures(variant.textures, `${where}.textures`)); - } - for (const axis of ["x", "y"]) { - if (variant[axis] !== undefined && ![0, 90, 180, 270].includes(variant[axis] as number)) { - problems.push(`${where}.${axis} must be 0, 90, 180 or 270`); - } - } - if (variant.uvlock !== undefined && typeof variant.uvlock !== "boolean") { - problems.push(`${where}.uvlock must be true or false`); - } - if (variant.shape !== undefined) problems.push(...validate_shape(variant.shape, `${where}.shape`)); - if (variant.collision_shape !== undefined) { - problems.push(...validate_shape(variant.collision_shape, `${where}.collision_shape`, 24)); - } - } - } - } - if (json.shape !== undefined) problems.push(...validate_shape(json.shape, "shape")); - if (json.collision_shape !== undefined) { - problems.push(...validate_shape(json.collision_shape, "collision_shape", 24)); - } - if (json.item_model !== undefined) problems.push(...validate_id(json.item_model, "item_model")); - if (json.parts !== undefined) { - if (!Array.isArray(json.parts) || json.parts.length === 0) { - problems.push("parts must be a list of { when, model, y }"); - } else { - const names = new Set(Array.isArray(json.states) ? json.states.map((s) => is_object(s) ? s.name : "") : []); - json.parts.forEach((part, i) => { - const where = `parts[${i}]`; - if (!is_object(part)) { - problems.push(`${where} must be { when, model, y }`); - return; - } - problems.push(...validate_id(part.model, `${where}.model`)); - if (part.when !== undefined) { - const parts = typeof part.when === "string" ? part.when.split(",") : [undefined]; - for (const condition of part.when === "" ? [] : parts) { - const [name, value] = (condition ?? "").split("=").map((p) => p.trim()); - if (!names.has(name) || !/^\d+$/.test(value ?? "")) { - problems.push( - `${where}.when: "${condition}" must be a state of this block and a number, like north=1`, - ); - } - } - } - if (part.textures !== undefined) { - problems.push(...validate_textures(part.textures, `${where}.textures`)); - } - for (const axis of ["x", "y"]) { - if (part[axis] !== undefined && ![0, 90, 180, 270].includes(part[axis] as number)) { - problems.push(`${where}.${axis} must be 0, 90, 180 or 270`); - } - } - if (part.uvlock !== undefined && typeof part.uvlock !== "boolean") { - problems.push(`${where}.uvlock must be true or false`); - } - if (part.shape !== undefined) problems.push(...validate_shape(part.shape, `${where}.shape`)); - if (part.collision_shape !== undefined) { - problems.push(...validate_shape(part.collision_shape, `${where}.collision_shape`, 24)); - } - }); - } - } - if (json.render_layer !== undefined && !RENDER_LAYERS.includes(json.render_layer as RenderLayer)) { - problems.push(`render_layer must be one of ${RENDER_LAYERS.join(", ")}`); - } - for (const key of ["light_emission", "light_opacity"]) { - const value = json[key]; - if (value !== undefined && (!Number.isInteger(value) || (value as number) < 0 || (value as number) > 15)) { - problems.push(`${key} must be a whole number from 0 to 15`); - } - } - problems.push(...validate_text(json.name, "name")); - for (const key of ["cull_same", "transparent", "collision", "item", "interactive", "scrollable", "replaceable"]) { - if (json[key] !== undefined && typeof json[key] !== "boolean") problems.push(`${key} must be true or false`); - } - if (json.tint !== undefined) { - const tint = json.tint; - if (!is_object(tint) || !is_tint_color(tint.color)) { - problems.push('tint.color must be "grass", "foliage", "water" or a color like "#80a755"'); - } else if ( - tint.textures !== undefined && - !(Array.isArray(tint.textures) && tint.textures.every((name) => typeof name === "string")) - ) { - problems.push('tint.textures must be a list of texture variables, like ["top"]'); - } - } - if (json.alpha !== undefined && (typeof json.alpha !== "number" || json.alpha < 0 || json.alpha > 1)) { - problems.push("alpha must be between 0 and 1"); - } - if (json.mining !== undefined) { - if (!is_object(json.mining) || typeof json.mining.toughness !== "number" || json.mining.toughness < 0) { - problems.push("mining.toughness must be a number of seconds"); - } else if (json.mining.tier !== undefined && !is_whole(json.mining.tier)) { - problems.push("mining.tier must be a whole number of 0 or more"); - } - } - if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops")); - if (json.loot_table !== undefined) { - if (!(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table))) { - problems.push('loot_table must be a loot table id, like "my_mod:blocks/thing"'); - } - if (json.drops !== undefined) problems.push("drops and loot_table can't both be set, drops is one item"); - } - if (json.item_display !== undefined) { - const surface = is_object(json.item_display) ? json.item_display.surface : undefined; - if (typeof surface !== "number" || surface < 0 || surface > 16) { - problems.push("item_display.surface must be the height in pixels items lie on, from 0 to 16"); - } - } - for (const key of ["place_on", "place_in"]) { - const list = json[key]; - if (list === undefined) continue; - if (!Array.isArray(list) || list.length === 0) { - problems.push(`${key} must be a list of block ids or #tags`); - } else { - for (const id of list) problems.push(...validate_id_or_tag(id, key)); - } - } - if (json.states !== undefined) { - const states = json.states; - if (!Array.isArray(states)) { - problems.push("states must be a list"); - } else { - const bits = states.reduce((sum, s) => sum + (is_object(s) && typeof s.bits === "number" ? s.bits : 0), 0); - if (bits > 16) problems.push(`states use ${bits} bits, the most is 16`); - if (json.waterloggable !== undefined && bits + WATERLOGGED.bits > 16) { - problems.push(`its states and waterlogged use more than 16 bits`); - } - } - } - if (json.waterloggable !== undefined) { - problems.push(...validate_id(json.waterloggable, "waterloggable")); - if (json.liquid !== undefined) problems.push("a liquid can't be waterloggable"); - const states = Array.isArray(json.states) ? json.states : []; - if (states.some((state) => is_object(state) && state.name === WATERLOGGED.name)) { - problems.push(`a waterloggable block gets a "${WATERLOGGED.name}" state of its own`); - } - } - if (json.waterlogged_only !== undefined) { - if (typeof json.waterlogged_only !== "boolean") problems.push("waterlogged_only must be true or false"); - else if (json.waterlogged_only && json.waterloggable === undefined) { - problems.push("waterlogged_only needs waterloggable, the liquid it's placed into"); - } - } - return problems; -} - -// a liquid is drawn by the engine, so it has no model of its own, and its level is a state it gets -function validate_liquid(json: Record): Problems { - const problems: Problems = []; - const liquid = json.liquid; - if (!is_object(liquid)) return ["liquid must be { range, ticks, renewable }, or {}"]; - for (const key of Object.keys(liquid)) { - if (!(key in LIQUID_DEFAULTS)) problems.push(`liquid.${key} isn't a liquid property`); - } - if (liquid.ticks !== undefined && (!Number.isInteger(liquid.ticks) || (liquid.ticks as number) < 1)) { - problems.push("liquid.ticks must be a whole number of 1 or more"); - } - if (liquid.renewable !== undefined && typeof liquid.renewable !== "boolean") { - problems.push("liquid.renewable must be true or false"); - } - const range = liquid.range; - if ( - range !== undefined && - (!Number.isInteger(range) || (range as number) < 1 || (range as number) > MAX_LIQUID_RANGE) - ) { - problems.push(`liquid.range must be a whole number from 1 to ${MAX_LIQUID_RANGE}`); - } - const textures = json.textures; - const texture_ok = typeof textures === "string" || - (is_object(textures) && typeof textures.still === "string" && - (textures.flowing === undefined || typeof textures.flowing === "string") && - Object.keys(textures).every((key) => key === "still" || key === "flowing")); - if (!texture_ok) problems.push("a liquid's textures must be a texture id or { still, flowing }"); - for (const key of ["model", "variants", "parts", "shape", "collision_shape", "item_model"]) { - if (json[key] !== undefined) problems.push(`a liquid can't have ${key}, the engine draws it`); - } - const states = Array.isArray(json.states) ? json.states : []; - if (states.some((state) => is_object(state) && state.name === LIQUID_LEVEL.name)) { - problems.push(`a liquid gets a "${LIQUID_LEVEL.name}" state of its own`); - } - const bits = states.reduce((sum, s) => sum + (is_object(s) && typeof s.bits === "number" ? s.bits : 0), 0); - if (bits + LIQUID_LEVEL.bits > 16) problems.push(`its states and its level use more than 16 bits`); - return problems; -} - -// 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 validate_shape(shape: unknown, where: string, top = 16): Problems { - const is_box = (box: unknown) => - Array.isArray(box) && box.length === 6 && - box.every((v, i) => typeof v === "number" && v >= 0 && v <= (i % 3 === 1 ? top : 16)) && - box[0] <= box[3] && box[1] <= box[4] && box[2] <= box[5]; - if (!Array.isArray(shape) || shape.length === 0 || !shape.every(is_box)) { - const most = top === 16 ? "" : `, up to ${top} high`; - return [`${where} must be a list of boxes in pixels${most}, like [[0, 0, 0, 16, 8, 16]]`]; - } - return []; + return find_problems(block_schema, json); } export function validate_model(json: unknown): Problems { - if (!is_object(json)) return ["model must be an object"]; - const problems = validate_id(json.id, "id"); - if (json.parent !== undefined) problems.push(...validate_id(json.parent, "parent")); - if (json.textures !== undefined) problems.push(...validate_textures(json.textures, "textures", true)); - if (json.display !== undefined) problems.push(...validate_display(json.display)); - // a model can leave its elements to its parent, or be one that only gives defaults to its children - if (json.elements === undefined) { - if (json.parent === undefined && json.textures === undefined && json.display === undefined) { - problems.push("a model needs elements, a parent, or textures or display for models that use it as theirs"); - } - return problems; - } - if (!Array.isArray(json.elements)) { - problems.push("elements must be a list of boxes"); - return problems; - } - json.elements.forEach((element, i) => { - const where = `elements[${i}]`; - if (!is_object(element)) { - problems.push(`${where} must be { from, to, faces }`); - return; - } - for (const key of ["from", "to"]) { - const point = element[key]; - if (!Array.isArray(point) || point.length !== 3 || !point.every((v) => typeof v === "number")) { - problems.push(`${where}.${key} must be [x, y, z] in pixels`); - } - } - const rotation = element.rotation; - if (rotation !== undefined) { - if ( - !is_object(rotation) || !["x", "y", "z"].includes(rotation.axis as string) || - typeof rotation.angle !== "number" || Math.abs(rotation.angle) > 180 || !Array.isArray(rotation.origin) - ) { - problems.push( - `${where}.rotation must be { origin, axis: x, y or z, angle: degrees from -180 to 180 }`, - ); - } - } - if (element.shade !== undefined && typeof element.shade !== "boolean") { - problems.push(`${where}.shade must be true or false`); - } - if (!is_object(element.faces)) { - problems.push(`${where}.faces must map sides to { texture }`); - return; - } - for (const [side, face] of Object.entries(element.faces)) { - if (!MODEL_FACES.includes(side as ModelFace)) { - problems.push(`${where}.faces: "${side}" isn't one of ${MODEL_FACES.join(", ")}`); - } - if (!is_object(face) || typeof face.texture !== "string") { - problems.push(`${where}.faces.${side} needs a texture, like "#side"`); - continue; - } - if (face.uv !== undefined && (!Array.isArray(face.uv) || face.uv.length !== 4)) { - problems.push(`${where}.faces.${side}.uv must be [u1, v1, u2, v2] in pixels`); - } - if (face.rotation !== undefined && ![0, 90, 180, 270].includes(face.rotation as number)) { - problems.push(`${where}.faces.${side}.rotation must be 0, 90, 180 or 270`); - } - if (face.cullface !== undefined && !MODEL_FACES.includes(face.cullface as ModelFace)) { - problems.push(`${where}.faces.${side}.cullface isn't one of ${MODEL_FACES.join(", ")}`); - } - } - }); - return problems; -} - -function validate_display(display: unknown): Problems { - if (!is_object(display)) return [`display must map ${DISPLAY_CONTEXTS.join(", ")} to transforms`]; - const problems: Problems = []; - for (const [context, transform] of Object.entries(display)) { - if (!DISPLAY_CONTEXTS.includes(context as DisplayContext)) { - problems.push(`display: "${context}" isn't one of ${DISPLAY_CONTEXTS.join(", ")}`); - } else if (!is_object(transform)) { - problems.push(`display.${context} must be { rotation, translation, scale }`); - } else { - for (const [key, value] of Object.entries(transform)) { - if (!["rotation", "translation", "scale"].includes(key)) { - problems.push(`display.${context}: "${key}" isn't rotation, translation or scale`); - } else if (!Array.isArray(value) || value.length !== 3 || !value.every((v) => typeof v === "number")) { - problems.push(`display.${context}.${key} must be [x, y, z]`); - } - } - } - } - return problems; -} - -// a texture id, or texture variables mapped to ids. a model's own defaults may also point at variables ("#side") -function validate_textures(value: unknown, field: string, allow_variables = false): Problems { - if (typeof value === "string") return validate_id(value, field); - if (!is_object(value)) return [`${field} must be a texture id or { variable: texture id }`]; - return Object.entries(value).flatMap(([name, id]) => - allow_variables && typeof id === "string" && id.startsWith("#") ? [] : validate_id(id, `${field}.${name}`) - ); -} - -function is_whole(value: unknown): value is number { - return Number.isInteger(value) && (value as number) >= 0; + return find_problems(model_schema, json); } export function validate_item(json: unknown): Problems { - if (!is_object(json)) return ["item must be an object"]; - const problems = validate_id(json.id, "id"); - if (json.texture !== undefined) problems.push(...validate_id(json.texture, "texture")); - if (json.data_textures !== undefined) { - if (!is_object(json.data_textures)) problems.push("data_textures must be { data key: texture id }"); - else { - for (const [key, id] of Object.entries(json.data_textures)) { - problems.push(...validate_id(id, `data_textures.${key}`)); - } - } - } - if (json.model !== undefined) problems.push(...validate_id(json.model, "model")); - if (json.places !== undefined) problems.push(...validate_id(json.places, "places")); - problems.push(...validate_text(json.name, "name"), ...validate_text(json.lore, "lore")); - if (json.max_stack !== undefined && (!Number.isInteger(json.max_stack) || (json.max_stack as number) < 1)) { - problems.push("max_stack must be a positive whole number"); - } - if (json.base_sell_value !== undefined && !is_whole(json.base_sell_value)) { - problems.push("base_sell_value must be a whole number of 0 or more"); - } - if (json.targets_liquids !== undefined && typeof json.targets_liquids !== "boolean") { - problems.push("targets_liquids must be true or false"); - } - if (json.tool !== undefined) { - const tool = json.tool; - if (!is_object(tool) || typeof tool.type !== "string") { - problems.push('tool must be { type, durability }, like "pickaxe"'); - } else { - if (!is_whole(tool.durability) || tool.durability < 1) { - problems.push("tool.durability must be a positive whole number"); - } - if (tool.tier !== undefined && !is_whole(tool.tier)) { - problems.push("tool.tier must be a whole number of 0 or more"); - } - if (tool.speed !== undefined && (typeof tool.speed !== "number" || tool.speed <= 0)) { - problems.push("tool.speed must be a positive number"); - } - } - } - if (json.food !== undefined) { - const food = json.food; - if ( - !is_object(food) || !Number.isInteger(food.nutrition) || (food.nutrition as number) < 0 || - typeof food.saturation_modifier !== "number" || food.saturation_modifier < 0 - ) { - problems.push("food must be { nutrition, saturation_modifier }, nutrition a whole number"); - } else { - if (food.always_edible !== undefined && typeof food.always_edible !== "boolean") { - problems.push("food.always_edible must be true or false"); - } - if (food.returns !== undefined) problems.push(...validate_id(food.returns, "food.returns")); - } - } - if (json.worn !== undefined) { - const worn = json.worn; - if (!is_object(worn)) { - problems.push("worn must be { model, texture }, an entity model and a texture"); - } else { - problems.push(...validate_id(worn.model, "worn.model"), ...validate_id(worn.texture, "worn.texture")); - for (const field of ["slim_model", "slim_texture"]) { - if (worn[field] !== undefined) problems.push(...validate_id(worn[field], `worn.${field}`)); - } - for (const field of Object.keys(worn)) { - if (!["model", "texture", "slim_model", "slim_texture"].includes(field)) { - problems.push(`worn.${field} isn't a field of worn`); - } - } - } - } - return problems; + return find_problems(item_schema, json); } export function validate_recipe(json: unknown): Problems { - if (!is_object(json)) return ["recipe must be an object"]; - const problems: Problems = []; - switch (json.type) { - case "shaped": { - const pattern = json.pattern; - if ( - !Array.isArray(pattern) || pattern.length < 1 || pattern.length > 3 || - !pattern.every((row) => typeof row === "string" && row.length >= 1 && row.length <= 3) - ) { - problems.push("pattern must be 1-3 rows of 1-3 characters"); - } else if (is_object(json.key)) { - for (const letter of pattern.join("").replaceAll(" ", "")) { - if (!(letter in json.key)) problems.push(`pattern uses "${letter}" but key doesn't define it`); - } - } - if (!is_object(json.key)) { - problems.push("key must map letters to item ids, or lists of them"); - } else { - for (const choice of Object.values(json.key)) problems.push(...validate_choice(choice, "key")); - } - problems.push(...validate_stack(json.result, "result")); - break; - } - case "furnace": - problems.push(...validate_choice(json.input, "input"), ...validate_stack(json.output, "output")); - if (!Number.isInteger(json.cook_time) || (json.cook_time as number) < 1) { - problems.push("cook_time must be a positive number of ticks"); - } - break; - case "fuel": - problems.push(...validate_choice(json.item, "item")); - if (!Number.isInteger(json.burn_time) || (json.burn_time as number) < 1) { - problems.push("burn_time must be a positive number of ticks"); - } - break; - case "smithing": - problems.push( - ...validate_id(json.tool, "tool"), - ...validate_stack(json.material, "material"), - ...validate_id(json.result, "result"), - ); - if (json.addition !== undefined) problems.push(...validate_id(json.addition, "addition")); - break; - default: - if (typeof json.type !== "string" || !json.type.includes(":")) { - problems.push( - 'type must be "shaped", "furnace", "fuel", "smithing" or a mod\'s own type like "farmersdelight:cooking"', - ); - } else { - problems.push(...validate_id(json.type, "type")); - } - } - return problems; + return find_problems(recipe_schema, json); } export function validate_ore(json: unknown): Problems { - if (!is_object(json)) return ["ore must be an object"]; - const problems = [...validate_id(json.id, "id"), ...validate_id(json.replaces, "replaces")]; - for (const key of ["min_y", "max_y", "scale", "threshold"]) { - if (typeof json[key] !== "number") problems.push(`${key} must be a number`); - } - if (typeof json.min_y === "number" && typeof json.max_y === "number" && json.min_y > json.max_y) { - problems.push("min_y must not be above max_y"); - } - return problems; + return find_problems(ore_schema, json); } export function validate_spawn(json: unknown): Problems { - if (!is_object(json)) return ["spawn must be an object"]; - const problems = validate_id(json.entity, "entity"); - for (const key of ["weight", "min_count", "max_count"]) { - if (!Number.isInteger(json[key]) || (json[key] as number) < (key === "weight" ? 0 : 1)) { - problems.push( - key === "weight" - ? "weight must be a whole number, 0 or more" - : `${key} must be a whole number, 1 or more`, - ); - } - } - if (typeof json.min_count === "number" && typeof json.max_count === "number" && json.min_count > json.max_count) { - problems.push("min_count must not be above max_count"); - } - if (json.biomes !== undefined) { - if (!Array.isArray(json.biomes)) problems.push("biomes must be a list of biome ids"); - else json.biomes.forEach((biome, i) => problems.push(...validate_id(biome, `biomes[${i}]`))); - } - if (json.chance !== undefined && (typeof json.chance !== "number" || !(json.chance > 0 && json.chance <= 1))) { - problems.push("chance must be a number above 0, at most 1"); - } - return problems; + return find_problems(spawn_schema, json); } export function validate_entity(json: unknown): Problems { - if (!is_object(json)) return ["entity must be an object"]; - const problems = [ - ...validate_id(json.id, "id"), - ...(json.model === undefined ? [] : validate_id(json.model, "model")), - ...validate_id(json.texture, "texture"), - ]; - if (json.behavior !== undefined && !["animal", "monster", "scripted"].includes(json.behavior as string)) { - problems.push('behavior must be "animal", "monster" or "scripted"'); - } - if ( - json.loot_table !== undefined && !(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table)) - ) { - problems.push('loot_table must be a loot table id, like "my_mod:entities/thing"'); - } - for (const key of ["width", "height"]) { - if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) { - problems.push(`${key} must be a number of blocks above 0, at most 16`); - } - } - for (const key of ["max_health", "movement_speed", "attack_damage", "physical_shielding", "arcane_shielding"]) { - if (json[key] !== undefined && (typeof json[key] !== "number" || json[key] < 0)) { - problems.push(`${key} must be a number, 0 or more`); - } - } - return problems; + return find_problems(entity_schema, json); } export function validate_effect(json: unknown): Problems { - if (!is_object(json)) return ["effect must be an object"]; - const problems = validate_id(json.id, "id"); - if (json.category !== undefined && !["beneficial", "harmful", "neutral"].includes(json.category as string)) { - problems.push('category must be "beneficial", "harmful" or "neutral"'); - } - if (json.instant !== undefined && typeof json.instant !== "boolean") problems.push("instant must be true or false"); - if (json.icon !== undefined) problems.push(...validate_id(json.icon, "icon")); - if (json.modifiers !== undefined) { - if (!Array.isArray(json.modifiers)) { - problems.push("modifiers must be a list"); - } else { - json.modifiers.forEach((modifier, i) => { - const field = `modifiers[${i}]`; - if (!is_object(modifier)) { - problems.push(`${field} must be { attribute, amount, operation }`); - return; - } - problems.push(...validate_id(modifier.attribute, `${field}.attribute`)); - if (typeof modifier.amount !== "number" || !Number.isFinite(modifier.amount)) { - problems.push(`${field}.amount must be a number`); - } - if ( - !["add_value", "add_multiplied_base", "add_multiplied_total"].includes(modifier.operation as string) - ) { - problems.push( - `${field}.operation must be "add_value", "add_multiplied_base" or "add_multiplied_total"`, - ); - } - }); - } - } - if (json.components !== undefined && !is_object(json.components)) problems.push("components must be an object"); - return problems; + return find_problems(effect_schema, json); } export function validate_entity_model(json: unknown): Problems { - if (!is_object(json)) return ["entity model must be an object"]; - const problems = validate_id(json.id, "id"); - for (const key of ["texture_width", "texture_height"]) { - if (!Number.isInteger(json[key]) || (json[key] as number) < 1) problems.push(`${key} must be a whole number`); - } - if (!Array.isArray(json.bones)) return [...problems, "bones must be a list"]; - const names = new Set(); - json.bones.forEach((bone, i) => { - const field = `bones[${i}]`; - if (!is_object(bone) || typeof bone.name !== "string") { - problems.push(`${field} must be { name, pivot, cubes }`); - return; - } - if (names.has(bone.name)) problems.push(`${field}: there are two bones named ${bone.name}`); - if (bone.parent !== undefined && !names.has(bone.parent as string)) { - problems.push(`${field}: parent ${bone.parent} must be a bone before it`); - } - names.add(bone.name); - problems.push(...validate_vec3(bone.pivot, `${field}.pivot`)); - if (bone.rotation !== undefined) problems.push(...validate_vec3(bone.rotation, `${field}.rotation`)); - if (!Array.isArray(bone.cubes)) { - problems.push(`${field}.cubes must be a list`); - return; - } - bone.cubes.forEach((cube, j) => { - const cube_field = `${field}.cubes[${j}]`; - if (!is_object(cube)) { - problems.push(`${cube_field} must be { origin, size, uv }`); - return; - } - problems.push(...validate_vec3(cube.origin, `${cube_field}.origin`)); - problems.push(...validate_vec3(cube.size, `${cube_field}.size`)); - if (!Array.isArray(cube.uv) || cube.uv.length !== 2 || !cube.uv.every((n) => typeof n === "number")) { - problems.push(`${cube_field}.uv must be [u, v], per face uvs aren't supported`); - } - if (cube.inflate !== undefined && typeof cube.inflate !== "number") { - problems.push(`${cube_field}.inflate must be a number`); - } - }); - }); - return 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 @@ -1209,77 +909,7 @@ export function entity_model_from_geo(json: unknown, id: string): { model?: Enti return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems }; } -function validate_vec3(value: unknown, field: string): Problems { - return Array.isArray(value) && value.length === 3 && value.every((n) => typeof n === "number") - ? [] - : [`${field} must be [x, y, z]`]; -} - -// an item id or #tag, or a list of them any of which fits -function validate_choice(value: unknown, field: string): Problems { - if (!Array.isArray(value)) return validate_id_or_tag(value, field); - if (value.length === 0) return [`${field} must list at least one item`]; - return value.flatMap((id) => validate_id_or_tag(id, field)); -} - -function validate_id_or_tag(value: unknown, field: string): Problems { - if (typeof value === "string" && value.startsWith("#")) { - return TAG_ID_PATTERN.test(value.slice(1)) ? [] : [`${field} must be a tag like "#my_mod:things"`]; - } - return validate_id(value, field); -} - // a tag file's contents, with the registry and id its path gives it export function validate_tag(json: unknown): Problems { - if (!is_object(json)) return ["tag must be an object"]; - const problems: Problems = []; - if (!TAG_REGISTRIES.includes(json.registry as TagRegistry)) { - problems.push(`registry must be one of ${TAG_REGISTRIES.join(", ")}`); - } - if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) { - problems.push('id must be a tag id like "my_mod:things" or "c:ingots/iron"'); - } - if (json.replace !== undefined && typeof json.replace !== "boolean") problems.push("replace must be true or false"); - for (const key of ["values", "remove"]) { - const list = json[key]; - if (list === undefined && key === "remove") continue; - if (!Array.isArray(list)) { - problems.push(`${key} must be a list of ids and #tags`); - continue; - } - for (const entry of list) { - if (is_object(entry)) { - problems.push(...validate_id_or_tag(entry.id, `${key}[].id`)); - if (entry.required !== undefined && typeof entry.required !== "boolean") { - problems.push(`${key}[].required must be true or false`); - } - } else { - problems.push(...validate_id_or_tag(entry, key)); - } - } - } - return problems; -} - -// optional text players see -function validate_text(value: unknown, field: string): Problems { - return value === undefined || (typeof value === "string" && value.length > 0) ? [] : [`${field} must be text`]; -} - -function validate_id(value: unknown, field: string): Problems { - return typeof value === "string" && ID_PATTERN.test(value) ? [] : [`${field} must be an id like "my_mod:thing"`]; -} - -function validate_stack(value: unknown, field: string): Problems { - if (!is_object(value)) return [`${field} must be { id, count }`]; - const problems = validate_id(value.id, `${field}.id`); - if (!Number.isInteger(value.count) || (value.count as number) < 1) { - problems.push(`${field}.count must be a positive whole number`); - } - return problems; -} - -// a json object, not null or an array -export function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); + return find_problems(tag_schema, json); } diff --git a/common/schema.ts b/common/schema.ts new file mode 100644 index 0000000..2d0da3a --- /dev/null +++ b/common/schema.ts @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the pieces mod data's zod schemas are made of, and the problems they find, worded for mod authors. it imports +// nothing else of the game's, so every file can make its schemas with these as it loads, whatever imports it first +import * as z from "zod"; + +// a list of what's wrong with some json, empty when it's fine +export type Problems = string[]; + +export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/; +// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md +export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/; + +export const id = z.string('must be an id like "my_mod:thing"').regex(ID_PATTERN); +// an id, or a #tag of them +export const id_or_tag = z.string('must be an id like "my_mod:thing" or a tag like "#my_mod:things"').refine( + (value) => value.startsWith("#") ? TAG_ID_PATTERN.test(value.slice(1)) : ID_PATTERN.test(value), +); +export const loot_table_id = z.string('must be a loot table id, like "my_mod:blocks/thing"').regex(TAG_ID_PATTERN); +// text players see +export const text = z.string().min(1); +export const vec3 = z.tuple([z.number(), z.number(), z.number()], "must be [x, y, z]"); +// any json object, for what's only stored, like components +export const json_object = z.record(z.string(), z.unknown()); + +// json that says what kind of thing it is in one field, like a loot condition's "condition", checked by the schema +// schema_for gives for its kind: the engine's kinds, and mods' own for the rest. no schema is a kind there isn't, which +// unknown says what's wrong with +export function by_kind>( + field: string, + schema_for: (kind: string) => z.ZodType | undefined, + unknown: string, +): z.ZodType { + const kinded: z.ZodType = z.looseObject({ [field]: z.string() }).superRefine((json, ctx) => { + const schema = schema_for(json[field]); + if (schema) add_problems(ctx, schema, json); + else ctx.addIssue({ code: "custom", path: [field], message: unknown }); + }); + // the kind's schema checked the rest of T + return kinded as z.ZodType; +} + +// checks json with schema as part of a bigger check, like a feature's config by its type. the problems go to ctx, under +// path from where it is +export function add_problems(ctx: z.RefinementCtx, schema: z.ZodType, json: unknown, path: PropertyKey[] = []) { + for (const issue of schema.safeParse(json, { error: describe }).error?.issues ?? []) { + ctx.addIssue({ ...issue, path: [...path, ...issue.path] } as z.core.$ZodRawIssue); + } +} + +// what's wrong with json for a schema, each as where it is and what it should be, like "tool.durability must be 1 or +// more". a schema's own message wins over the ones from describe +export function find_problems(schema: z.ZodType, json: unknown): Problems { + const result = schema.safeParse(json, { error: describe }); + return result.success ? [] : result.error.issues.flatMap((issue) => issue_problems(issue, [])); +} + +function issue_problems(issue: z.core.$ZodIssue, outer: PropertyKey[]): Problems { + const path = [...outer, ...issue.path]; + if (issue.code === "unrecognized_keys") { + const where = field_name(path); + return issue.keys.map((key) => `${where ? `${where} ` : ""}can't have ${JSON.stringify(key)}`); + } + // a union's options are the kinds of thing the json can be, like a texture id or { variable: texture id }. when + // it's only one of them, that one's problems say more than the union's message + if (issue.code === "invalid_union") { + const fitting = issue.errors.filter((issues) => !issues.every(wrong_kind)); + if (fitting.length === 1) return fitting[0].flatMap((inner) => issue_problems(inner, path)); + } + const where = field_name(path); + return [where ? `${where} ${issue.message}` : issue.message]; +} + +// a problem saying json isn't the kind of thing at all: it's the wrong type, none of a union's kinds, or not the +// value a literal like "open_sky" is +function wrong_kind(issue: z.core.$ZodIssue): boolean { + return issue.path.length === 0 && + (issue.code === "invalid_type" || issue.code === "invalid_union" || issue.code === "invalid_value"); +} + +// a path into the json as it's written in js, like tool.durability, parts[0].when or variants["age=3"] +function field_name(path: PropertyKey[]): string { + return path.map((key, i) => { + if (typeof key === "number") return `[${key}]`; + const name = String(key); + return /^\w+$/.test(name) ? (i === 0 ? name : `.${name}`) : `[${JSON.stringify(name)}]`; + }).join(""); +} + +const TYPE_NAMES: Record = { + number: "a number", + int: "a whole number", + string: "text", + boolean: "true or false", + array: "a list", + tuple: "a list", + object: "an object", + record: "an object", +}; + +// zod's messages, in words for mod authors. what isn't here keeps zod's own +const describe: z.core.$ZodErrorMap = (issue) => { + switch (issue.code) { + case "invalid_type": + return issue.input === undefined + ? "is required" + : `must be ${TYPE_NAMES[issue.expected] ?? issue.expected}`; + case "too_small": + if (issue.origin === "array" || issue.origin === "string") { + if (issue.minimum === 1) return "can't be empty"; + return `must have at least ${issue.minimum} ${issue.origin === "string" ? "characters" : "entries"}`; + } + return issue.inclusive ? `must be ${issue.minimum} or more` : `must be above ${issue.minimum}`; + case "too_big": + if (issue.origin === "array" || issue.origin === "string") { + return `must have at most ${issue.maximum} ${issue.origin === "string" ? "characters" : "entries"}`; + } + return issue.inclusive ? `must be at most ${issue.maximum}` : `must be below ${issue.maximum}`; + case "invalid_value": + return `must be ${or_list(issue.values.map((value) => JSON.stringify(value)))}`; + // a record's key, its schema says what's wrong with it + case "invalid_key": + return issue.issues[0]?.message; + // a discriminated union's field that isn't one of its kinds + case "invalid_union": + if (Array.isArray(issue.options)) { + return `must be ${or_list(issue.options.map((kind) => JSON.stringify(kind)))}`; + } + } +}; + +// "a", "b" or "c" +function or_list(values: string[]): string { + return values.length < 2 ? values.join("") : `${values.slice(0, -1).join(", ")} or ${values.at(-1)}`; +} + +// a json object, not null or an array +export function is_object(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/common/texture_animation.ts b/common/texture_animation.ts index 718ce30..8dcede4 100644 --- a/common/texture_animation.ts +++ b/common/texture_animation.ts @@ -3,23 +3,27 @@ // animated textures, like minecraft's .png.mcmeta and in the same format: textures/.json next to // textures/.png says how to cut the png into frames and how long each one shows. see docs/modding/resources/textures.md -import { is_object } from "./mod_data.ts"; +import * as z from "zod"; +import { find_problems, type Problems } from "./schema.ts"; -export interface TextureJson { - animation?: AnimationJson; -} - -export interface AnimationJson { +const animation_schema = z.object({ // ticks each frame shows unless the frame says otherwise, 1 if not given - frametime?: number; + frametime: z.int().min(1).optional(), // blend each frame into the next a tick at a time instead of switching - interpolate?: boolean; + interpolate: z.boolean().optional(), // the order to show frames in, by index or { index, time }. every frame in order if not given - frames?: (number | { index: number; time: number })[]; + frames: z.array(z.union([z.int().min(0), z.object({ index: z.int().min(0), time: z.int().min(1) })])).min(1) + .optional(), // a frame's size in pixels. frames are square, as wide as the png is or as tall if that's less, if not given - width?: number; - height?: number; -} + width: z.int().min(1).optional(), + height: z.int().min(1).optional(), +}); + +export type AnimationJson = z.infer; + +const texture_schema = z.object({ animation: animation_schema.optional() }, 'must be { "animation": { ... } }'); + +export type TextureJson = z.infer; // an animation ready to play export interface Animation { @@ -29,52 +33,28 @@ export interface Animation { frames: { x: number; y: number; time: number }[]; } -// what's wrong with a texture's .json, for the png it goes with -export function validate_texture_json(json: unknown, size: { width: number; height: number }): string[] { - if (!is_object(json)) return [`must be { "animation": { ... } }`]; - if (json.animation === undefined) return []; - const animation = json.animation; - if (!is_object(animation)) return ["animation must be an object"]; - - const problems: string[] = []; - const ticks = (value: unknown) => Number.isInteger(value) && (value as number) >= 1; - if (animation.frametime !== undefined && !ticks(animation.frametime)) { - problems.push("animation.frametime must be a whole number of ticks, at least 1"); - } - if (animation.interpolate !== undefined && typeof animation.interpolate !== "boolean") { - problems.push("animation.interpolate must be true or false"); - } - for (const key of ["width", "height"] as const) { - if (animation[key] !== undefined && !ticks(animation[key])) { - problems.push(`animation.${key} must be a whole number of pixels, at least 1`); - } - } - if (problems.length > 0) return problems; - - const { frame_width, frame_height } = frame_size(animation as AnimationJson, size); - if (size.width % frame_width !== 0 || size.height % frame_height !== 0) { - return [ - `the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`, - ]; - } - const count = (size.width / frame_width) * (size.height / frame_height); - - if (animation.frames !== undefined) { - if (!Array.isArray(animation.frames) || animation.frames.length === 0) { - problems.push("animation.frames must be a list of frames"); - } else { - animation.frames.forEach((frame, i) => { - const index = is_object(frame) ? frame.index : frame; - if (!Number.isInteger(index) || index < 0 || index >= count) { - problems.push(`animation.frames[${i}]: the png has frames 0 to ${count - 1}`); - } - if (is_object(frame) && !ticks(frame.time)) { - problems.push(`animation.frames[${i}]: time must be a whole number of ticks, at least 1`); - } +// what's wrong with a texture's .json, for the png it goes with: its frames have to be in it +export function validate_texture_json(json: unknown, size: { width: number; height: number }): Problems { + const fits_png = texture_schema.superRefine(({ animation }, ctx) => { + if (!animation) return; + const { frame_width, frame_height } = frame_size(animation, size); + if (size.width % frame_width !== 0 || size.height % frame_height !== 0) { + return ctx.addIssue({ + code: "custom", + message: + `the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`, }); } - } - return problems; + const count = (size.width / frame_width) * (size.height / frame_height); + animation.frames?.forEach((frame, i) => { + const index = typeof frame === "number" ? frame : frame.index; + if (index >= count) { + const path = ["animation", "frames", i, ...(typeof frame === "number" ? [] : ["index"])]; + ctx.addIssue({ code: "custom", path, message: `isn't one of the png's frames, 0 to ${count - 1}` }); + } + }); + }); + return find_problems(fits_png, json); } // the animation in a texture's .json, which validate_texture_json passed. undefined if it isn't animated diff --git a/common/worldgen/biomes.ts b/common/worldgen/biomes.ts index 8c86b2a..dd552a4 100644 --- a/common/worldgen/biomes.ts +++ b/common/worldgen/biomes.ts @@ -3,8 +3,9 @@ // biomes as data: worldgen/biomes/.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column // gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked +import * as z from "zod"; import { EverythingRegistry } from "../everything_registry.ts"; -import { ID_PATTERN, is_object } from "../mod_data.ts"; +import { find_problems, id, type Problems } from "../schema.ts"; import { farming_day } from "../time.ts"; export const SEASONS = ["spring", "summer", "autumn", "winter"] as const; @@ -12,31 +13,41 @@ export type Season = typeof SEASONS[number]; // how long each season lasts. day 1 to 49 is spring, 50 to 98 summer and so on, a year is 196 days export const SEASON_DAYS = 49; -// how a biome covers its ground, like minecraft's surface rules. blocks are ids -export interface SurfaceJson { - top: string; - filler: string; - filler_depth: number; +// how a biome covers its ground, like minecraft's surface rules +const surface_schema = z.object({ + top: id, + filler: id, + filler_depth: z.int().min(0).max(32), // the ground's cover under water, filler when not set - underwater_top?: string; - underwater_filler?: string; + underwater_top: id.optional(), + underwater_filler: id.optional(), // cliffs show bare stone instead of top - bare_cliffs?: boolean; -} + bare_cliffs: z.boolean().optional(), +}); -export interface BiomeJson { - id: string; +export type SurfaceJson = z.infer; + +const color = z.string('must be a color like "#79c05a"').regex(/^#[0-9a-fA-F]{6}$/); + +const biome_schema = z.object({ + id, // a season it's always in, like winter for snowy biomes. when not set it follows the calendar, see calendar_season - season?: Season; - surface: SurfaceJson; - // "#rrggbb", minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set - colors?: { grass?: string; foliage?: string; water?: string }; + season: z.enum(SEASONS).optional(), + surface: surface_schema, + // minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set + colors: z.strictObject({ grass: color.optional(), foliage: color.optional(), water: color.optional() }).optional(), // how likely each tree cell is to have a tree, and which kinds grow, picked evenly (list one twice to make it // twice as likely). wood is the logs and leaves a kind grows here when it isn't its own, like big oaks being dark // oak in the dark forest. the trees feature reads it (bworld's, in its worldgen script), which says what kinds - // and woods there are - trees?: { chance: number; kinds: string[]; wood?: Record }; -} + // and woods there are, and checks them when it loads + trees: z.object({ + chance: z.number().min(0).max(1), + kinds: z.array(z.string()).min(1), + wood: z.record(z.string(), z.string()).optional(), + }).optional(), +}); + +export type BiomeJson = z.infer; // what's registered in "biomes", with the defaults filled in export interface Biome { @@ -97,70 +108,6 @@ export function biome_blocks(json: BiomeJson): string[] { return [top, filler, underwater_top, underwater_filler].filter((id) => id !== undefined); } -export function validate_biome(json: unknown): string[] { - if (!is_object(json)) return ["biome must be an object"]; - const problems: string[] = []; - const id = (value: unknown, field: string) => { - if (!(typeof value === "string" && ID_PATTERN.test(value))) { - problems.push(`${field} must be an id like "my_mod:thing"`); - } - }; - id(json.id, "id"); - if (json.season !== undefined && !SEASONS.includes(json.season as Season)) { - problems.push(`season must be one of ${SEASONS.join(", ")}`); - } - - const surface = json.surface; - if (!is_object(surface)) { - problems.push("surface must be { top, filler, filler_depth }"); - } else { - id(surface.top, "surface.top"); - id(surface.filler, "surface.filler"); - if (surface.underwater_top !== undefined) id(surface.underwater_top, "surface.underwater_top"); - if (surface.underwater_filler !== undefined) id(surface.underwater_filler, "surface.underwater_filler"); - const depth = surface.filler_depth; - if (!Number.isInteger(depth) || (depth as number) < 0 || (depth as number) > 32) { - problems.push("surface.filler_depth must be a whole number from 0 to 32"); - } - if (surface.bare_cliffs !== undefined && typeof surface.bare_cliffs !== "boolean") { - problems.push("surface.bare_cliffs must be true or false"); - } - } - - if (json.colors !== undefined) { - if (!is_object(json.colors)) { - problems.push("colors must be { grass, foliage, water }"); - } else { - for (const [key, value] of Object.entries(json.colors)) { - if (!["grass", "foliage", "water"].includes(key)) problems.push(`colors.${key} isn't a biome color`); - else if (!(typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value))) { - problems.push(`colors.${key} must be a color like "#79c05a"`); - } - } - } - } - - const trees = json.trees; - if (trees !== undefined) { - if (!is_object(trees)) { - problems.push("trees must be { chance, kinds }"); - } else { - if (typeof trees.chance !== "number" || trees.chance < 0 || trees.chance > 1) { - problems.push("trees.chance must be a number from 0 to 1"); - } - // which kinds and woods there are is up to the trees feature, bworld's checks them when it loads - if ( - !Array.isArray(trees.kinds) || trees.kinds.length === 0 || - !trees.kinds.every((kind) => typeof kind === "string") - ) { - problems.push("trees.kinds must list at least one kind of tree"); - } - if (trees.wood !== undefined) { - if (!is_object(trees.wood) || !Object.values(trees.wood).every((wood) => typeof wood === "string")) { - problems.push("trees.wood must be { : }"); - } - } - } - } - return problems; +export function validate_biome(json: unknown): Problems { + return find_problems(biome_schema, json); } diff --git a/common/worldgen/data.ts b/common/worldgen/data.ts index 1453a30..9874352 100644 --- a/common/worldgen/data.ts +++ b/common/worldgen/data.ts @@ -4,7 +4,8 @@ // world generation as data: noises, density functions, noise settings (a generator) and biome sources, see // docs/modding/worldgen/terrain.md. checked here, compiled by density.ts and generator.ts. the names follow // minecraft's (density functions, the noise router, surface rules) where the idea is the same -import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts"; +import * as z from "zod"; +import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts"; // ids of worldgen data can have folders, like "bworld:overworld/erosion" export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN; @@ -142,376 +143,256 @@ export function new_refs(): WorldgenRefs { return { noises: new Set(), functions: new Set(), blocks: new Set(), biomes: new Set(), biome_sources: new Set() }; } -const ARITHMETIC = ["add", "sub", "mul", "div", "min", "max"]; -export const DENSITY_TYPES = [ - "constant", - "x", - "y", - "z", - "noise", - ...ARITHMETIC, - "abs", - "clamp", - "smoothstep", - "spline", - "range_choice", - "cache_2d", -]; +// checking + +const worldgen_id = z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(WORLDGEN_ID_PATTERN); +const block_id = z.string("must be a block's id").regex(ID_PATTERN); +const biome_id = z.string("must be a biome's id").regex(ID_PATTERN); + +const noise_schema: z.ZodType = z.object({ + id: worldgen_id, + seed_name: z.string().optional(), + wavelength: z.number().positive(), + amplitudes: z.array(z.number()).min(1).refine((amplitudes) => amplitudes.some((a) => a !== 0), "can't all be 0"), + dimensions: z.literal([2, 3]).optional(), + vertical_stretch: z.number().positive().optional(), + quantiles: z.union([ + worldgen_id, + z.array(z.number()).min(2).refine((q) => q.every((value, i) => i === 0 || value > q[i - 1]), "must go up"), + ], "must be at least 2 numbers going up, or a noise's id").optional(), +}).refine((noise) => noise.vertical_stretch === undefined || noise.dimensions === 3, { + path: ["vertical_stretch"], + message: "is only for 3d noises", +}); + const RANGE_KEYS = ["min_inclusive", "min_exclusive", "max_inclusive", "max_exclusive"] as const; -export function validate_noise(json: unknown): string[] { - const problems: string[] = []; - if (!is_object(json)) return ["noise must be an object"]; - worldgen_id(json.id, "id", problems); - if (json.seed_name !== undefined && typeof json.seed_name !== "string") problems.push("seed_name must be text"); - if (!(typeof json.wavelength === "number" && json.wavelength > 0)) problems.push("wavelength must be above 0"); - if ( - !Array.isArray(json.amplitudes) || json.amplitudes.length === 0 || - !json.amplitudes.every((a) => typeof a === "number" && Number.isFinite(a)) || - json.amplitudes.every((a) => a === 0) - ) { - problems.push("amplitudes must be a list of numbers, not all 0"); - } - if (json.dimensions !== undefined && json.dimensions !== 2 && json.dimensions !== 3) { - problems.push("dimensions must be 2 or 3"); - } - if (json.vertical_stretch !== undefined) { - if (json.dimensions !== 3) problems.push("vertical_stretch is only for 3d noises"); - if (!(typeof json.vertical_stretch === "number" && json.vertical_stretch > 0)) { - problems.push("vertical_stretch must be above 0"); +// a range's bounds, numbers or (in range_choice) density functions. a range needs at least one +function bounds(bound: T) { + return { + min_inclusive: bound.optional(), + min_exclusive: bound.optional(), + max_inclusive: bound.optional(), + max_exclusive: bound.optional(), + }; +} +const has_bound = (range: Partial>) => + RANGE_KEYS.some((key) => range[key] !== undefined); +const NEEDS_BOUND = `needs at least one of ${RANGE_KEYS.join(", ")}`; + +const range = z.object(bounds(z.number())).refine(has_bound, NEEDS_BOUND); + +// a density function, by itself or by its id +const density: z.ZodType = z.lazy(() => + z.union( + [z.number(), z.string("must be a density function's id").regex(WORLDGEN_ID_PATTERN), density_object], + 'must be a number, a density function\'s id or { "type": ... }', + ) +); + +const spline: z.ZodType = z.object({ + coordinate: density, + points: z.array(z.object({ + location: z.number(), + value: z.union([z.number(), z.lazy(() => spline)], "must be a number or a spline"), + derivative: z.number().optional(), + })).min(1).superRefine((points, ctx) => { + points.forEach((point, i) => { + if (i > 0 && point.location < points[i - 1].location) { + ctx.addIssue({ code: "custom", path: [i, "location"], message: "can't be below the point before's" }); + } + }); + }), +}); + +const density_object = z.discriminatedUnion("type", [ + z.object({ type: z.literal("constant"), argument: z.number() }), + z.object({ type: z.literal(["x", "y", "z"]) }), + z.object({ + type: z.literal("noise"), + noise: z.string("must be a noise's id").regex(WORLDGEN_ID_PATTERN), + even: z.boolean().optional(), + x: density.optional(), + y: density.optional(), + z: density.optional(), + }), + z.object({ type: z.literal(["add", "sub", "mul", "div", "min", "max"]), argument1: density, argument2: density }), + z.object({ type: z.literal(["abs", "cache_2d"]), argument: density }), + z.object({ type: z.literal("clamp"), input: density, min: z.number(), max: z.number() }) + .refine(({ min, max }) => min <= max, { path: ["min"], message: "can't be above max" }), + z.object({ type: z.literal("smoothstep"), input: density, from: z.number(), to: z.number() }) + .refine(({ from, to }) => from !== to, { path: ["to"], message: "must be different from from" }), + z.object({ type: z.literal("spline"), spline }), + z.object({ + type: z.literal("range_choice"), + input: density, + ...bounds(density), + when_in_range: density, + when_out_of_range: density, + }).refine(has_bound, NEEDS_BOUND), +]); + +const density_function_schema: z.ZodType = z.intersection( + z.object({ id: worldgen_id }), + density_object, +); + +const surface_rule: z.ZodType = z.lazy(() => + z.discriminatedUnion("type", [ + z.object({ type: z.literal("sequence"), sequence: z.array(surface_rule) }), + z.object({ type: z.literal("condition"), if_true: surface_condition, then_run: surface_rule }), + z.object({ type: z.literal("block"), result_state: z.object({ Name: block_id }) }), + z.object({ type: z.literal("biome_surface"), part: z.enum(BIOME_SURFACE_PARTS) }), + ]) +); + +const surface_condition: z.ZodType = z.lazy(() => + z.discriminatedUnion("type", [ + z.object({ type: z.literal("stone_depth"), offset: z.int() }), + z.object({ type: z.literal(["filler_depth", "surface_underwater", "steep", "bare_cliffs"]) }), + z.object({ type: z.literal("above_preliminary_surface"), offset: z.number().optional() }), + z.object({ type: z.literal("y_at_least"), function: density }), + z.object({ type: z.literal("biome"), biome_is: z.array(biome_id) }), + z.object({ type: z.literal("not"), invert: surface_condition }), + ]) +); + +const cell_height = z.literal([1, 2, 4, 8, 16, 32]); + +const noise_settings_schema: z.ZodType = z.object({ + id: worldgen_id, + sea_level: z.int().min(0).max(256), + default_block: block_id, + cell_width: z.literal([1, 2, 4, 8, 16]), + terrain: z.object({ density, cell_height }), + caves: z.object({ density, cell_height }), + preliminary_surface: density, + climate: z.record( + z.string("isn't a name a climate value can have: lowercase letters and _, but not surface or steep") + .regex(/^[a-z_]+$/).refine((name) => name !== "surface" && name !== "steep"), + density, + ), + steep: z.number().min(0), + biome_source: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN), + fluids: z.array(z.object({ + block: block_id, + below: z.int(), + where: z.union([ + z.literal("open_sky"), + z.object({ function: density, ...bounds(z.number()) }).refine(has_bound, NEEDS_BOUND), + ], 'must be "open_sky" or { "function", }'), + })), + surface_rule, +}); + +const biome_source_schema: z.ZodType = z.object({ + id: worldgen_id, + extends: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN).optional(), + rules: z.array(z.object({ + id: worldgen_id, + before: worldgen_id.optional(), + after: worldgen_id.optional(), + // steep is true or false, any other name is a range of that climate value + when: z.object({ steep: z.boolean().optional() }).catchall(range).optional(), + biome: biome_id, + })), +}).superRefine((source, ctx) => { + // a rule added to another biome source goes before or after one of its rules + source.rules.forEach((rule, i) => { + const placed = [rule.before, rule.after].filter((id) => id !== undefined).length; + if (source.extends !== undefined && placed !== 1) { + ctx.addIssue({ code: "custom", path: ["rules", i], message: "needs before or after, one of them" }); } - } - const quantiles = json.quantiles; - if (quantiles !== undefined && typeof quantiles !== "string") { - if ( - !Array.isArray(quantiles) || quantiles.length < 2 || - !quantiles.every((q, i) => typeof q === "number" && (i === 0 || q > quantiles[i - 1])) - ) { - problems.push("quantiles must be at least 2 numbers going up, or a noise's id"); + if (source.extends === undefined && placed > 0) { + ctx.addIssue({ + code: "custom", + path: ["rules", i], + message: "can't have before or after, they're for rules added to another biome source with extends", + }); } - } else if (typeof quantiles === "string") { - worldgen_id(quantiles, "quantiles", problems); - } - return problems; + }); +}); + +export function validate_noise(json: unknown): Problems { + return find_problems(noise_schema, json); } -// the noises a noise file refers to: the one it takes its quantiles from +export function validate_density_function(json: unknown): Problems { + return find_problems(density_function_schema, json); +} + +export function validate_noise_settings(json: unknown): Problems { + return find_problems(noise_settings_schema, json); +} + +export function validate_biome_source(json: unknown): Problems { + return find_problems(biome_source_schema, json); +} + +// what worldgen data that passed its checks refers to + export function noise_refs(json: NoiseJson, refs: WorldgenRefs) { if (typeof json.quantiles === "string") refs.noises.add(json.quantiles); } -export function validate_density_function(json: unknown): string[] { - if (!is_object(json)) return ["density_function must be an object"]; - const problems: string[] = []; - worldgen_id(json.id, "id", problems); - const { id: _, ...fn } = json; - check_density(fn, "", new_refs(), problems); - return problems; -} - export function density_function_refs(json: DensityFunctionJson, refs: WorldgenRefs) { const { id: _, ...fn } = json; - check_density(fn, "", refs, []); + density_refs(fn, refs); } -// checks a density function, adding what it refers to to refs. at is where it is, for messages -export function check_density(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) { - const where = at ? `${at}: ` : ""; - if (typeof json === "number") { - if (!Number.isFinite(json)) problems.push(`${where}must be a finite number`); - return; - } +function density_refs(json: DensityJson, refs: WorldgenRefs) { + if (typeof json === "number") return; if (typeof json === "string") { - if (WORLDGEN_ID_PATTERN.test(json)) refs.functions.add(json); - else problems.push(`${where}"${json}" isn't a density function's id`); + refs.functions.add(json); return; } - if (!is_object(json) || typeof json.type !== "string") { - problems.push(`${where}must be a number, a density function's id or { "type": ... }`); - return; - } - const field = (name: string) => check_density(json[name], at ? `${at}.${name}` : name, refs, problems); - const number = (name: string) => { - if (typeof json[name] !== "number" || !Number.isFinite(json[name])) { - problems.push(`${where}${name} must be a number`); + for (const [key, value] of Object.entries(json)) { + if (key === "noise") refs.noises.add(value as string); + else if (key === "spline") spline_refs(value as SplineJson, refs); + // the other fields that are text or objects are density functions, the rest numbers and true or false + else if (key !== "type" && (typeof value === "string" || is_object(value))) { + density_refs(value as DensityJson, refs); } - }; - switch (json.type) { - case "constant": - number("argument"); - break; - case "x": - case "y": - case "z": - break; - case "noise": - if (typeof json.noise === "string" && WORLDGEN_ID_PATTERN.test(json.noise)) refs.noises.add(json.noise); - else problems.push(`${where}noise must be a noise's id`); - if (json.even !== undefined && typeof json.even !== "boolean") { - problems.push(`${where}even must be true or false`); - } - for (const axis of ["x", "y", "z"]) if (json[axis] !== undefined) field(axis); - break; - case "abs": - case "cache_2d": - field("argument"); - break; - case "clamp": - field("input"); - number("min"); - number("max"); - if ((json.min as number) > (json.max as number)) problems.push(`${where}min is above max`); - break; - case "smoothstep": - field("input"); - number("from"); - number("to"); - if (json.from === json.to) problems.push(`${where}from and to must be different`); - break; - case "spline": - check_spline(json.spline, at ? `${at}.spline` : "spline", refs, problems); - break; - case "range_choice": - field("input"); - if (!RANGE_KEYS.some((key) => json[key] !== undefined)) problems.push(`${where}needs at least one bound`); - for (const key of RANGE_KEYS) if (json[key] !== undefined) field(key); - field("when_in_range"); - field("when_out_of_range"); - break; - default: - if (ARITHMETIC.includes(json.type)) { - field("argument1"); - field("argument2"); - } else { - problems.push(`${where}type ${json.type} isn't one of ${DENSITY_TYPES.join(", ")}`); - } } } -function check_spline(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) { - if (!is_object(json) || !Array.isArray(json.points) || json.points.length === 0) { - problems.push(`${at}: must be { "coordinate": ..., "points": [ ... ] }`); - return; - } - check_density(json.coordinate, `${at}.coordinate`, refs, problems); - let last = -Infinity; - json.points.forEach((point: unknown, i: number) => { - const here = `${at}.points[${i}]`; - if (!is_object(point) || typeof point.location !== "number") { - problems.push(`${here}: must be { "location", "value", "derivative" }`); - return; - } - if (point.location < last) problems.push(`${here}: locations must go up`); - last = point.location; - if (typeof point.value !== "number") check_spline(point.value, `${here}.value`, refs, problems); - if (point.derivative !== undefined && typeof point.derivative !== "number") { - problems.push(`${here}: derivative must be a number`); - } - }); +function spline_refs(spline: SplineJson, refs: WorldgenRefs) { + density_refs(spline.coordinate, refs); + for (const point of spline.points) if (typeof point.value !== "number") spline_refs(point.value, refs); } -export function validate_noise_settings(json: unknown): string[] { - if (!is_object(json)) return ["noise_settings must be an object"]; - const problems: string[] = []; - noise_settings_refs(json, new_refs(), problems); - return problems; +export function noise_settings_refs(json: NoiseSettingsJson, refs: WorldgenRefs) { + refs.blocks.add(json.default_block); + const { terrain, caves, preliminary_surface, climate } = json; + for (const fn of [terrain.density, caves.density, preliminary_surface, ...Object.values(climate)]) { + density_refs(fn, refs); + } + refs.biome_sources.add(json.biome_source); + for (const fluid of json.fluids) { + refs.blocks.add(fluid.block); + if (fluid.where !== "open_sky") density_refs(fluid.where.function, refs); + } + surface_rule_refs(json.surface_rule, refs); } -export function noise_settings_refs(json: Record, refs: WorldgenRefs, problems: string[] = []) { - worldgen_id(json.id, "id", problems); - const whole = (name: string, min: number, max: number) => { - const value = json[name]; - if (!(Number.isInteger(value) && (value as number) >= min && (value as number) <= max)) { - problems.push(`${name} must be a whole number from ${min} to ${max}`); - } - }; - whole("sea_level", 0, 256); - block_id(json.default_block, "default_block", refs, problems); - if (![1, 2, 4, 8, 16].includes(json.cell_width as number)) problems.push("cell_width must be 1, 2, 4, 8 or 16"); - for (const part of ["terrain", "caves"]) { - const value = json[part]; - if (!is_object(value)) { - problems.push(`${part} must be { "density", "cell_height" }`); - continue; - } - check_density(value.density, `${part}.density`, refs, problems); - if (![1, 2, 4, 8, 16, 32].includes(value.cell_height as number)) { - problems.push(`${part}.cell_height must be 1, 2, 4, 8, 16 or 32`); - } +function surface_rule_refs(rule: SurfaceRuleJson, refs: WorldgenRefs) { + if (rule.type === "sequence") { for (const inner of rule.sequence) surface_rule_refs(inner, refs); } + if (rule.type === "condition") { + surface_condition_refs(rule.if_true, refs); + surface_rule_refs(rule.then_run, refs); } - check_density(json.preliminary_surface, "preliminary_surface", refs, problems); - if (!is_object(json.climate)) { - problems.push("climate must be { : }"); - } else { - for (const [name, value] of Object.entries(json.climate)) { - if (!/^[a-z_]+$/.test(name) || name === "surface" || name === "steep") { - problems.push(`climate.${name}: names are lowercase letters and _, and not surface or steep`); - } - check_density(value, `climate.${name}`, refs, problems); - } - } - if (!(typeof json.steep === "number" && json.steep >= 0)) problems.push("steep must be a number, 0 or more"); - if (typeof json.biome_source === "string" && WORLDGEN_ID_PATTERN.test(json.biome_source)) { - refs.biome_sources.add(json.biome_source); - } else { - problems.push("biome_source must be a biome source's id"); - } - if (!Array.isArray(json.fluids)) { - problems.push("fluids must be a list"); - } else { - json.fluids.forEach((fluid: unknown, i: number) => { - const at = `fluids[${i}]`; - if (!is_object(fluid)) { - problems.push(`${at}: must be { "block", "below", "where" }`); - return; - } - block_id(fluid.block, `${at}.block`, refs, problems); - if (!Number.isInteger(fluid.below)) problems.push(`${at}.below must be a whole number`); - if (fluid.where !== "open_sky") { - if (!is_object(fluid.where)) { - problems.push(`${at}.where must be "open_sky" or { "function", }`); - } else { - check_density(fluid.where.function, `${at}.where.function`, refs, problems); - check_range(fluid.where, `${at}.where`, problems); - } - } - }); - } - check_surface_rule(json.surface_rule, "surface_rule", refs, problems); + if (rule.type === "block") refs.blocks.add(rule.result_state.Name); } -function check_surface_rule(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) { - if (!is_object(json)) { - problems.push(`${at}: must be a rule`); - return; - } - switch (json.type) { - case "sequence": - if (!Array.isArray(json.sequence)) problems.push(`${at}.sequence must be a list of rules`); - else json.sequence.forEach((rule, i) => check_surface_rule(rule, `${at}.sequence[${i}]`, refs, problems)); - break; - case "condition": - check_surface_condition(json.if_true, `${at}.if_true`, refs, problems); - check_surface_rule(json.then_run, `${at}.then_run`, refs, problems); - break; - case "block": - if (!is_object(json.result_state)) problems.push(`${at}.result_state must be { "Name": }`); - else block_id(json.result_state.Name, `${at}.result_state.Name`, refs, problems); - break; - case "biome_surface": - if (!BIOME_SURFACE_PARTS.includes(json.part as BiomeSurfacePart)) { - problems.push(`${at}.part must be one of ${BIOME_SURFACE_PARTS.join(", ")}`); - } - break; - default: - problems.push(`${at}: type must be sequence, condition, block or biome_surface`); - } +function surface_condition_refs(condition: SurfaceConditionJson, refs: WorldgenRefs) { + if (condition.type === "y_at_least") density_refs(condition.function, refs); + if (condition.type === "biome") { for (const biome of condition.biome_is) refs.biomes.add(biome); } + if (condition.type === "not") surface_condition_refs(condition.invert, refs); } -function check_surface_condition(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) { - if (!is_object(json)) { - problems.push(`${at}: must be a condition`); - return; - } - switch (json.type) { - case "stone_depth": - if (!Number.isInteger(json.offset)) problems.push(`${at}.offset must be a whole number`); - break; - case "above_preliminary_surface": - if (json.offset !== undefined && typeof json.offset !== "number") { - problems.push(`${at}.offset must be a number`); - } - break; - case "filler_depth": - case "surface_underwater": - case "steep": - case "bare_cliffs": - break; - case "y_at_least": - check_density(json.function, `${at}.function`, refs, problems); - break; - case "biome": - if (!Array.isArray(json.biome_is) || !json.biome_is.every((b) => typeof b === "string")) { - problems.push(`${at}.biome_is must be a list of biome ids`); - } else { - for (const biome of json.biome_is) refs.biomes.add(biome); - } - break; - case "not": - check_surface_condition(json.invert, `${at}.invert`, refs, problems); - break; - default: - problems.push( - `${at}: type must be stone_depth, filler_depth, above_preliminary_surface, surface_underwater, steep, ` + - `bare_cliffs, y_at_least, biome or not`, - ); - } -} - -export function validate_biome_source(json: unknown): string[] { - if (!is_object(json)) return ["biome_source must be an object"]; - const problems: string[] = []; - biome_source_refs(json, new_refs(), problems); - return problems; -} - -export function biome_source_refs(json: Record, refs: WorldgenRefs, problems: string[] = []) { - worldgen_id(json.id, "id", problems); - if (json.extends !== undefined) { - if (typeof json.extends === "string" && WORLDGEN_ID_PATTERN.test(json.extends)) { - refs.biome_sources.add(json.extends); - } else problems.push("extends must be a biome source's id"); - } - if (!Array.isArray(json.rules)) { - problems.push("rules must be a list"); - return; - } - json.rules.forEach((rule: unknown, i: number) => { - const at = `rules[${i}]`; - if (!is_object(rule)) { - problems.push(`${at}: must be { "id", "when", "biome" }`); - return; - } - worldgen_id(rule.id, `${at}.id`, problems); - const placed = [rule.before, rule.after].filter((id) => id !== undefined); - if (json.extends !== undefined && placed.length !== 1) { - problems.push(`${at}: a rule added to another biome source needs before or after, one of them`); - } - if (json.extends === undefined && placed.length > 0) { - problems.push(`${at}: before and after are for rules added to another biome source, with extends`); - } - for (const id of placed) worldgen_id(id, `${at}.before/after`, problems); - if (typeof rule.biome === "string" && ID_PATTERN.test(rule.biome)) refs.biomes.add(rule.biome); - else problems.push(`${at}.biome must be a biome's id`); - if (rule.when !== undefined) { - if (!is_object(rule.when)) { - problems.push(`${at}.when must be { : , "steep": true or false }`); - } else { - for (const [name, condition] of Object.entries(rule.when)) { - if (name === "steep") { - if (typeof condition !== "boolean") problems.push(`${at}.when.steep must be true or false`); - } else { - check_range(condition, `${at}.when.${name}`, problems); - } - } - } - } - }); -} - -// a range of numbers, with at least one bound -function check_range(json: unknown, at: string, problems: string[]) { - if (!is_object(json)) { - problems.push(`${at} must be a range like { "min_inclusive": 0 }`); - return; - } - let bounds = 0; - for (const key of RANGE_KEYS) { - if (json[key] === undefined) continue; - bounds++; - if (typeof json[key] !== "number") problems.push(`${at}.${key} must be a number`); - } - if (bounds === 0) problems.push(`${at} needs at least one of ${RANGE_KEYS.join(", ")}`); +export function biome_source_refs(json: BiomeSourceJson, refs: WorldgenRefs) { + if (json.extends !== undefined) refs.biome_sources.add(json.extends); + for (const rule of json.rules) refs.biomes.add(rule.biome); } // a test of whether a value is in the range, with only the bounds it has: value >= min, value < max @@ -529,14 +410,3 @@ export function range_test(range: RangeJson): (value: number) => boolean { } return (value) => tests.every((test) => test(value)); } - -function worldgen_id(value: unknown, field: string, problems: string[]) { - if (!(typeof value === "string" && WORLDGEN_ID_PATTERN.test(value))) { - problems.push(`${field} must be an id like "my_mod:thing" or "my_mod:folder/thing"`); - } -} - -function block_id(value: unknown, field: string, refs: WorldgenRefs, problems: string[]) { - if (typeof value === "string" && ID_PATTERN.test(value)) refs.blocks.add(value); - else problems.push(`${field} must be a block's id`); -} diff --git a/common/worldgen/features.ts b/common/worldgen/features.ts index 1ee1e42..2c3087f 100644 --- a/common/worldgen/features.ts +++ b/common/worldgen/features.ts @@ -7,7 +7,18 @@ import { EverythingRegistry } from "../everything_registry.ts"; import type { BlockRegistry } from "../everything_registry.ts"; import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts"; -import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts"; +import * as z from "zod"; +import { + add_problems, + by_kind, + find_problems, + id_or_tag, + ID_PATTERN, + is_object, + json_object, + type Problems, + TAG_ID_PATTERN, +} from "../schema.ts"; import { list_matches } from "../tags.ts"; import { can_stand_on } from "../utils.ts"; import { AIR_ID } from "../protocol.ts"; @@ -66,56 +77,108 @@ export interface FeatureRefs { custom: Set; } -export function validate_feature(json: unknown): string[] { - const problems: string[] = []; - feature_refs(json, { blocks: new Set(), biomes: new Set(), custom: new Set() }, problems); - return problems; +// a built in name, with its namespace or without, see builtin_name +const builtin = (...names: string[]) => z.literal(names.flatMap((name) => [name, `minecraft:${name}`])); + +const block_id = z.string("must be a block's id").regex(ID_PATTERN); +const biome_id = z.string("must be a biome's id").regex(ID_PATTERN); + +// a block, see state_id +const block_state_schema = z.union( + [block_id, z.object({ state: z.object({ Name: block_id }) }), z.object({ Name: block_id })], + 'must be a block\'s id or { "type": "simple_state_provider", "state": { "Name": ... } }', +); + +// a whole number, see int_provider +const int_provider_schema: z.ZodType = z.lazy(() => + z.union([ + z.int(), + z.discriminatedUnion("type", [ + z.object({ type: builtin("constant"), value: z.int() }), + z.object({ type: builtin("uniform"), min_inclusive: z.int(), max_inclusive: z.int() }).refine( + ({ min_inclusive, max_inclusive }) => min_inclusive <= max_inclusive, + { path: ["min_inclusive"], message: "can't be above max_inclusive" }, + ), + z.object({ + type: builtin("weighted_list"), + distribution: z.array(z.object({ data: int_provider_schema, weight: z.int().min(1) })).min(1), + }), + ], "must be constant, uniform or weighted_list"), + ], 'must be a whole number or { "type": "uniform", ... }') +); + +// a y, see anchor +const anchor_schema = z.union([ + z.strictObject({ absolute: z.int() }), + z.strictObject({ above_bottom: z.int() }), + z.strictObject({ below_top: z.int() }), +], 'must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }'); + +// see height_provider +const height_schema = z.union([ + anchor_schema, + z.discriminatedUnion("type", [ + z.object({ type: builtin("constant"), value: anchor_schema }), + z.object({ type: builtin("uniform"), min_inclusive: anchor_schema, max_inclusive: anchor_schema }), + ], "must be constant or uniform"), +], 'must be a height, like { "absolute": 10 } or { "type": "uniform", ... }'); + +// see block_predicate. offset moves where it looks +const predicate_base = z.object({ + offset: z.tuple([z.int(), z.int(), z.int()], "must be [x, y, z], whole numbers").optional(), +}); + +const block_predicate_schema: z.ZodType = z.lazy(() => + z.discriminatedUnion("type", [ + predicate_base.extend({ + type: builtin("matching_blocks"), + blocks: z.union([id_or_tag, z.array(id_or_tag)], "must be a block, a #tag, or a list of them"), + }), + predicate_base.extend({ type: builtin("solid", "replaceable", "true") }), + predicate_base.extend({ type: builtin("would_survive"), state: block_state_schema }), + predicate_base.extend({ type: builtin("not"), predicate: block_predicate_schema }), + predicate_base.extend({ type: builtin("all_of", "any_of"), predicates: z.array(block_predicate_schema) }), + ], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true") +); + +// a mod's own modifier is checked by the worldgen script that registers it +const placement_modifier = by_kind("type", (type) => { + const name = builtin_name(type); + if (name === undefined) return json_object; + return Object.hasOwn(MODIFIERS, name) ? MODIFIERS[name].schema : undefined; +}, "isn't a built in placement modifier"); + +const feature_schema: z.ZodType = z.object({ + id: z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(TAG_ID_PATTERN), + type: z.string(), + config: json_object.optional(), + placement: z.array(placement_modifier).optional(), + biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(), + step: z.enum(FEATURE_STEPS).optional(), +}).superRefine((feature, ctx) => { + // a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers + const name = builtin_name(feature.type); + if (name === undefined) return; + if (!Object.hasOwn(FEATURE_TYPES, name)) { + return ctx.addIssue({ code: "custom", path: ["type"], message: `${feature.type} isn't built in` }); + } + add_problems(ctx, FEATURE_TYPES[name].schema, feature.config ?? {}, ["config"]); +}); + +export function validate_feature(json: unknown): Problems { + return find_problems(feature_schema, json); } -export function feature_refs(json: unknown, refs: FeatureRefs, problems: string[] = []) { - if (!is_object(json)) { - problems.push("feature must be an object"); - return; - } - if (!(typeof json.id === "string" && TAG_ID_PATTERN.test(json.id))) { - problems.push(`id must be an id like "my_mod:thing" or "my_mod:folder/thing"`); - } - if (json.step !== undefined && !FEATURE_STEPS.includes(json.step as FeatureStep)) { - problems.push(`step must be one of ${FEATURE_STEPS.join(", ")}`); - } - if (json.biomes !== undefined) { - const biomes = typeof json.biomes === "string" ? [json.biomes] : json.biomes; - if (!Array.isArray(biomes) || !biomes.every((b) => typeof b === "string" && ID_PATTERN.test(b))) { - problems.push("biomes must be a biome's id or a list of them"); - } else { - for (const biome of biomes) refs.biomes.add(biome); - } - } - if (json.config !== undefined && !is_object(json.config)) problems.push("config must be an object"); - if (typeof json.type !== "string") { - problems.push("type must be a feature type"); - } else { - const name = builtin_name(json.type); - if (name === undefined) refs.custom.add(json.type); - else if (!(name in FEATURE_TYPES)) problems.push(`type ${json.type} isn't built in`); - else FEATURE_TYPES[name].check((json.config ?? {}) as Record, "config", refs, problems); - } - if (json.placement !== undefined) { - if (!Array.isArray(json.placement)) { - problems.push("placement must be a list of placement modifiers"); - return; - } - json.placement.forEach((modifier: unknown, i: number) => { - const at = `placement[${i}]`; - if (!is_object(modifier) || typeof modifier.type !== "string") { - problems.push(`${at}: must be { "type": ... }`); - return; - } - const name = builtin_name(modifier.type); - if (name === undefined) refs.custom.add(modifier.type); - else if (!(name in MODIFIERS)) problems.push(`${at}: ${modifier.type} isn't a built in placement modifier`); - else MODIFIERS[name].check(modifier, at, refs, problems); - }); +// what a feature that passed its checks uses +export function feature_refs(json: FeatureJson, refs: FeatureRefs) { + for (const biome of [json.biomes ?? []].flat()) refs.biomes.add(biome); + const type = builtin_name(json.type); + if (type === undefined) refs.custom.add(json.type); + else FEATURE_TYPES[type].refs?.(json.config ?? {}, refs); + for (const modifier of json.placement ?? []) { + const name = builtin_name(modifier.type); + if (name === undefined) refs.custom.add(modifier.type); + else MODIFIERS[name].refs?.(modifier, refs); } } @@ -183,15 +246,19 @@ export function compile_feature( // built in feature types interface Builtin { - check(json: Record, at: string, refs: FeatureRefs, problems: string[]): void; + // its json: a feature type's config, or the placement modifier + schema: z.ZodType; + // what it uses, when it uses something + refs?(json: Record, refs: FeatureRefs): void; compile(json: Record): T; } const FEATURE_TYPES: Record boolean>> = { // one block, where it can stand simple_block: { - check(json, at, refs, problems) { - check_state(json.to_place, `${at}.to_place`, refs, problems); + schema: z.object({ to_place: block_state_schema }), + refs(json, refs) { + refs.blocks.add(state_id(json.to_place)); }, compile(json) { const id = state_id(json.to_place); @@ -204,29 +271,15 @@ const FEATURE_TYPES: Record { - const here = `${at}.layers[${i}]`; - if (!is_object(layer)) { - problems.push(`${here} must be { "height", "provider" }`); - return; - } - check_int(layer.height, `${here}.height`, problems); - check_state(layer.provider, `${here}.provider`, refs, problems); - }); - } - if (json.direction !== undefined && json.direction !== "up" && json.direction !== "down") { - problems.push(`${at}.direction must be "up" or "down"`); - } - if (json.allowed_placement !== undefined) { - check_predicate(json.allowed_placement, `${at}.allowed_placement`, refs, problems); - } - if (json.prioritize_tip !== undefined && typeof json.prioritize_tip !== "boolean") { - problems.push(`${at}.prioritize_tip must be true or false`); - } + schema: z.object({ + layers: z.array(z.object({ height: int_provider_schema, provider: block_state_schema })).min(1), + direction: z.enum(["up", "down"]).optional(), + allowed_placement: block_predicate_schema.optional(), + prioritize_tip: z.boolean().optional(), + }), + refs(json, refs) { + for (const layer of json.layers as { provider: unknown }[]) refs.blocks.add(state_id(layer.provider)); + if (json.allowed_placement !== undefined) predicate_refs(json.allowed_placement, refs); }, compile(json) { const layers = (json.layers as { height: unknown; provider: unknown }[]).map((layer) => ({ @@ -259,14 +312,12 @@ const FEATURE_TYPES: Record Position[]; -const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"]; +const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"] as const; const MODIFIERS: Record> = { // each position becomes count of them count: { - check(json, at, _refs, problems) { - check_int(json.count, `${at}.count`, problems); - }, + schema: z.object({ count: int_provider_schema }), compile(json) { const count = int_provider(json.count); return (chunk, positions) => @@ -275,11 +326,7 @@ const MODIFIERS: Record> = { }, // one in chance positions are kept rarity_filter: { - check(json, at, _refs, problems) { - if (!(Number.isInteger(json.chance) && (json.chance as number) >= 1)) { - problems.push(`${at}.chance must be a whole number, 1 or more`); - } - }, + schema: z.object({ chance: z.int().min(1) }), compile(json) { const chance = json.chance as number; return (chunk, positions) => positions.filter(() => chunk.rng.next() < 1 / chance); @@ -287,7 +334,7 @@ const MODIFIERS: Record> = { }, // somewhere random in the chunk, across in_square: { - check() {}, + schema: z.object({}), compile() { return (chunk, positions) => positions.map((p) => { @@ -299,10 +346,7 @@ const MODIFIERS: Record> = { }, // moved by up to xz_spread across and y_spread up or down random_offset: { - check(json, at, _refs, problems) { - check_int(json.xz_spread ?? 0, `${at}.xz_spread`, problems); - check_int(json.y_spread ?? 0, `${at}.y_spread`, problems); - }, + schema: z.object({ xz_spread: int_provider_schema.optional(), y_spread: int_provider_schema.optional() }), compile(json) { const xz = int_provider(json.xz_spread ?? 0); const y = int_provider(json.y_spread ?? 0); @@ -312,9 +356,7 @@ const MODIFIERS: Record> = { }, // at a height height_range: { - check(json, at, _refs, problems) { - check_height(json.height, `${at}.height`, problems); - }, + schema: z.object({ height: height_schema }), compile(json) { const height = height_provider(json.height); return (chunk, positions) => positions.map((p) => ({ x: p.x, y: height(chunk), z: p.z })); @@ -323,11 +365,7 @@ const MODIFIERS: Record> = { // on top of the column: WORLD_SURFACE on its highest block, OCEAN_FLOOR on its highest that isn't a liquid. // positions outside the chunk are dropped heightmap: { - check(json, at, _refs, problems) { - if (!HEIGHTMAPS.includes(json.heightmap as string)) { - problems.push(`${at}.heightmap must be one of ${HEIGHTMAPS.join(", ")}`); - } - }, + schema: z.object({ heightmap: z.enum(HEIGHTMAPS) }), compile(json) { const floor = String(json.heightmap).startsWith("OCEAN_FLOOR"); return (chunk, positions) => @@ -341,8 +379,9 @@ const MODIFIERS: Record> = { }, // where a block predicate holds block_predicate_filter: { - check(json, at, refs, problems) { - check_predicate(json.predicate, `${at}.predicate`, refs, problems); + schema: z.object({ predicate: block_predicate_schema }), + refs(json, refs) { + predicate_refs(json.predicate, refs); }, compile(json) { const predicate = block_predicate(json.predicate); @@ -359,44 +398,22 @@ function counts_for_heightmap(id: string | undefined, floor: boolean) { // block predicates, like minecraft's type Predicate = (chunk: FeatureChunk, x: number, y: number, z: number) => boolean; -const PREDICATES = ["matching_blocks", "solid", "replaceable", "would_survive", "not", "all_of", "any_of", "true"]; - -function check_predicate(json: unknown, at: string, refs: FeatureRefs, problems: string[]) { - if (!is_object(json) || typeof json.type !== "string") { - problems.push(`${at} must be a block predicate, { "type": ... }`); - return; - } - const name = builtin_name(json.type); - if (name === undefined || !PREDICATES.includes(name)) { - problems.push(`${at}: ${json.type} isn't one of ${PREDICATES.join(", ")}`); - return; - } - if ( - json.offset !== undefined && - !(Array.isArray(json.offset) && json.offset.length === 3 && json.offset.every(Number.isInteger)) - ) { - problems.push(`${at}.offset must be [x, y, z], whole numbers`); - } - switch (name) { - case "matching_blocks": { - const blocks = typeof json.blocks === "string" ? [json.blocks] : json.blocks; - if (!Array.isArray(blocks) || !blocks.every((b) => typeof b === "string")) { - problems.push(`${at}.blocks must be a block, a #tag, or a list of them`); - } else { - for (const block of blocks) refs.blocks.add(block); - } +// the blocks a predicate tests for +function predicate_refs(json: unknown, refs: FeatureRefs) { + const predicate = json as Record; + switch (builtin_name(predicate.type as string)) { + case "matching_blocks": + for (const block of [predicate.blocks].flat()) refs.blocks.add(block as string); break; - } case "would_survive": - check_state(json.state, `${at}.state`, refs, problems); + refs.blocks.add(state_id(predicate.state)); break; case "not": - check_predicate(json.predicate, `${at}.predicate`, refs, problems); + predicate_refs(predicate.predicate, refs); break; case "all_of": case "any_of": - if (!Array.isArray(json.predicates)) problems.push(`${at}.predicates must be a list`); - else json.predicates.forEach((p, i) => check_predicate(p, `${at}.predicates[${i}]`, refs, problems)); + for (const inner of predicate.predicates as unknown[]) predicate_refs(inner, refs); } } @@ -456,18 +473,6 @@ function inside(chunk: FeatureChunk, x: number, z: number) { // block states: a block's id, or minecraft's { "type": "simple_state_provider", "state": { "Name": id } } -function check_state(json: unknown, at: string, refs: FeatureRefs, problems: string[]) { - const id = typeof json === "string" - ? json - : is_object(json) && is_object(json.state) - ? json.state.Name - : is_object(json) - ? json.Name - : undefined; - if (typeof id === "string" && ID_PATTERN.test(id)) refs.blocks.add(id); - else problems.push(`${at} must be a block's id or { "type": "simple_state_provider", "state": { "Name": ... } }`); -} - function state_id(json: unknown): string { if (typeof json === "string") return json; const object = json as Record; @@ -479,41 +484,6 @@ function state_id(json: unknown): string { type IntProvider = (chunk: FeatureChunk) => number; -function check_int(json: unknown, at: string, problems: string[]) { - if (Number.isInteger(json)) return; - if (!is_object(json)) { - problems.push(`${at} must be a whole number or { "type": "uniform", ... }`); - return; - } - switch (builtin_name(String(json.type))) { - case "constant": - if (!Number.isInteger(json.value)) problems.push(`${at}.value must be a whole number`); - break; - case "uniform": - if (!Number.isInteger(json.min_inclusive) || !Number.isInteger(json.max_inclusive)) { - problems.push(`${at} needs whole numbers min_inclusive and max_inclusive`); - } else if ((json.min_inclusive as number) > (json.max_inclusive as number)) { - problems.push(`${at}: min_inclusive is above max_inclusive`); - } - break; - case "weighted_list": - if (!Array.isArray(json.distribution) || json.distribution.length === 0) { - problems.push(`${at}.distribution must be a list of { "data", "weight" }`); - } else { - json.distribution.forEach((entry: unknown, i: number) => { - if (!is_object(entry) || !(Number.isInteger(entry.weight) && (entry.weight as number) > 0)) { - problems.push(`${at}.distribution[${i}] needs a whole number weight above 0`); - } else { - check_int(entry.data, `${at}.distribution[${i}].data`, problems); - } - }); - } - break; - default: - problems.push(`${at}.type must be constant, uniform or weighted_list`); - } -} - function int_provider(json: unknown): IntProvider { if (typeof json === "number") return () => json; const object = json as Record; @@ -548,35 +518,6 @@ function int_provider(json: unknown): IntProvider { // heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor } // or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor } -function check_height(json: unknown, at: string, problems: string[]) { - if (!is_object(json)) { - problems.push(`${at} must be a height, like { "absolute": 10 } or { "type": "uniform", ... }`); - return; - } - if (json.type === undefined) return check_anchor(json, at, problems); - switch (builtin_name(String(json.type))) { - case "constant": - check_anchor(json.value, `${at}.value`, problems); - break; - case "uniform": - check_anchor(json.min_inclusive, `${at}.min_inclusive`, problems); - check_anchor(json.max_inclusive, `${at}.max_inclusive`, problems); - break; - default: - problems.push(`${at}.type must be constant or uniform`); - } -} - -function check_anchor(json: unknown, at: string, problems: string[]) { - const keys = ["absolute", "above_bottom", "below_top"]; - if ( - !is_object(json) || Object.keys(json).length !== 1 || !keys.includes(Object.keys(json)[0]) || - !Number.isInteger(Object.values(json)[0]) - ) { - problems.push(`${at} must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }`); - } -} - function anchor(json: unknown): number { const object = json as Record; if (object.absolute !== undefined) return object.absolute; diff --git a/deno.json b/deno.json index 859a780..64a6403 100644 --- a/deno.json +++ b/deno.json @@ -38,7 +38,8 @@ "@std/path": "jsr:@std/path@^1.0.0", "fflate": "npm:fflate@^0.8.2", "gl-matrix": "npm:gl-matrix@^3.4.4", - "marked": "npm:marked@^17.0.3" + "marked": "npm:marked@^17.0.3", + "zod": "jsr:@zod/zod@^4.6.7" }, "desktop": { "app": { "name": "bworld", "identifier": "com.bworld.game" }, diff --git a/deno.lock b/deno.lock index 1482404..d76a447 100644 --- a/deno.lock +++ b/deno.lock @@ -15,11 +15,13 @@ "jsr:@std/http@^1.0.23": "1.0.24", "jsr:@std/internal@^1.0.10": "1.0.12", "jsr:@std/internal@^1.0.12": "1.0.12", + "jsr:@std/internal@^1.0.14": "1.0.14", "jsr:@std/media-types@^1.1.0": "1.1.0", "jsr:@std/net@^1.0.6": "1.0.6", - "jsr:@std/path@1": "1.1.4", + "jsr:@std/path@1": "1.1.6", "jsr:@std/path@^1.1.4": "1.1.4", "jsr:@std/streams@^1.0.17": "1.1.2", + "jsr:@zod/zod@^4.6.7": "4.6.7", "npm:fflate@~0.8.2": "0.8.3", "npm:gl-matrix@^3.4.4": "3.4.4", "npm:marked@^17.0.3": "17.0.3" @@ -79,6 +81,9 @@ "@std/internal@1.0.12": { "integrity": "972a634fd5bc34b242024402972cd5143eac68d8dffaca5eaa4dba30ce17b027" }, + "@std/internal@1.0.14": { + "integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7" + }, "@std/media-types@1.1.0": { "integrity": "c9d093f0c05c3512932b330e3cc1fe1d627b301db33a4c2c2185c02471d6eaa4" }, @@ -91,8 +96,17 @@ "jsr:@std/internal@^1.0.12" ] }, + "@std/path@1.1.6": { + "integrity": "c68485c2a4dfbb5ae3cc74fae4e8c4e5d874cf8a8ed12927917235c758b46cbe", + "dependencies": [ + "jsr:@std/internal@^1.0.14" + ] + }, "@std/streams@1.1.2": { "integrity": "0249bf9b78a999f57032ca4d8e7ccaa57579090242640b35ddc948fbb745d3af" + }, + "@zod/zod@4.6.7": { + "integrity": "6706868ce1e1907362e1bf008e298e482723345f0ba4125c43e5b9fd7960b186" } }, "npm": { @@ -119,6 +133,7 @@ "jsr:@std/fs@^1.0.23", "jsr:@std/http@^1.0.23", "jsr:@std/path@1", + "jsr:@zod/zod@^4.6.7", "npm:fflate@~0.8.2", "npm:gl-matrix@^3.4.4", "npm:marked@^17.0.3" diff --git a/server/load_bmods.ts b/server/load_bmods.ts index 07cd3e8..7e2dd0a 100644 --- a/server/load_bmods.ts +++ b/server/load_bmods.ts @@ -7,7 +7,8 @@ import { join } from "@std/path"; import { type Bmod, BMOD_EXTENSION, client_copy, read_bmod, write_bmod } from "$/common/bmod.ts"; import { check_references, load_order, type LoadedMod } from "$/common/mod_check.ts"; import type { ModListing } from "$/common/mod_loader.ts"; -import { FORMAT_VERSION, is_object } from "$/common/mod_data.ts"; +import { data_file, FORMAT_VERSION } from "$/common/mod_data.ts"; +import { is_object, json_object } from "$/common/schema.ts"; import { sha256 } from "$/common/utils.ts"; export interface ServerMod { @@ -118,11 +119,12 @@ function change_config(bmod: Bmod, config_dir: string, problems: string[]) { problems.push(`${file}: isn't valid json: ${(e as Error).message}`); return; } - if (!is_object(json) || json.format_version !== FORMAT_VERSION || !is_object(json.config)) { + const config_file = data_file("config", json_object).safeParse(json); + if (!config_file.success) { problems.push(`${file}: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`); return; } - const changed = apply_config(bmod.data.config ?? {}, json.config); + const changed = apply_config(bmod.data.config ?? {}, config_file.data.config as Record); problems.push(...changed.problems.map((problem) => `${file}: ${problem}`)); bmod.data.config = changed.config; } diff --git a/tests/bmod_test.ts b/tests/bmod_test.ts index 3e1a7c7..cc22b03 100644 --- a/tests/bmod_test.ts +++ b/tests/bmod_test.ts @@ -6,7 +6,7 @@ import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows import { zipSync } from "fflate"; import { ATLAS_BORDER, atlas_layout, extrude_borders } from "$/client/atlas.ts"; import { MAX_TEXTURE_SIZE } from "$/common/constants.ts"; -import { read_bmod, write_bmod } from "$/common/bmod.ts"; +import { type Bmod, read_bmod, write_bmod } from "$/common/bmod.ts"; import { load_and_check } from "$/tools/check_mods.ts"; import { pack_mod } from "$/tools/pack_mod.ts"; import { create_mod } from "$/tools/new_mod.ts"; @@ -417,7 +417,7 @@ Deno.test({ // write_bmod without anything optional still makes a file read_bmod takes Deno.test("a mod with only data packs and reads", () => { - const bmod = { + const bmod: Bmod = { manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" }, data: { blocks: [], diff --git a/tests/liquid_test.ts b/tests/liquid_test.ts index 8a46f67..90f9e7b 100644 --- a/tests/liquid_test.ts +++ b/tests/liquid_test.ts @@ -61,16 +61,16 @@ Deno.test("a liquid's still texture is its top and bottom, the flowing one its s Deno.test("check-mods catches liquids that can't work", () => { assertEquals(validate_block(OIL), []); const problems = (json: Record) => validate_block({ ...OIL, ...json }); - assertEquals(problems({ liquid: { range: 8 } }), ["liquid.range must be a whole number from 1 to 7"]); + assertEquals(problems({ liquid: { range: 8 } }), ["liquid.range must be at most 7"]); assertEquals(problems({ liquid: true }), ["liquid must be { range, ticks, renewable }, or {}"]); - assertEquals(problems({ liquid: { ticks: 0 } }), ["liquid.ticks must be a whole number of 1 or more"]); - assertEquals(problems({ liquid: { speed: 2 } }), ["liquid.speed isn't a liquid property"]); + assertEquals(problems({ liquid: { ticks: 0 } }), ["liquid.ticks must be 1 or more"]); + assertEquals(problems({ liquid: { speed: 2 } }), ['liquid can\'t have "speed"']); assertEquals(problems({ textures: { top: "a:b" } }), [ - "a liquid's textures must be a texture id or { still, flowing }", + "textures must be a texture id or { still, flowing } for a liquid", ]); - assertEquals(problems({ model: "engine:cross" }), ["a liquid can't have model, the engine draws it"]); + assertEquals(problems({ model: "engine:cross" }), ["model isn't for liquids, the engine draws them"]); assertEquals(problems({ states: [{ name: "level", bits: 2, default: 0 }] }), [ - 'a liquid gets a "level" state of its own', + `states can't have "level", a liquid gets that state of its own`, ]); }); diff --git a/tests/mod_entity_test.ts b/tests/mod_entity_test.ts index 58c7eae..237eba9 100644 --- a/tests/mod_entity_test.ts +++ b/tests/mod_entity_test.ts @@ -26,23 +26,24 @@ Deno.test("a bedrock geo.json becomes an entity model with only what the engine // per face uvs and parents that come later aren't supported const per_face = { origin: [0, 0, 0], size: [1, 1, 1], uv: { north: { uv: [0, 0], uv_size: [1, 1] } } }; - const bad = entity_model_from_geo({ - "minecraft:geometry": [{ - description: { texture_width: 16, texture_height: 16 }, - bones: [{ name: "leg", parent: "body", cubes: [per_face] }, { name: "body" }], - }], - }, "a:b"); - assertEquals(bad.model, undefined); - assert(bad.problems.some((p) => p.includes("parent body must be a bone before it")), String(bad.problems)); - assert(bad.problems.some((p) => p.includes("per face uvs aren't supported")), String(bad.problems)); + const geo_problems = (bones: unknown[]) => { + const geometry = { description: { texture_width: 16, texture_height: 16 }, bones }; + const { model, problems } = entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:b"); + assertEquals(model, undefined); + return problems; + }; + const late_parent = geo_problems([{ name: "leg", parent: "body" }, { name: "body" }]); + assert(late_parent.some((p) => p.includes("parent body must be a bone before it")), String(late_parent)); + const per_face_problems = geo_problems([{ name: "leg", cubes: [per_face] }]); + assert(per_face_problems.some((p) => p.includes("per face uvs aren't supported")), String(per_face_problems)); assertEquals(entity_model_from_geo({ format_version: "1.12.0" }, "a:b").model, undefined); }); Deno.test("an entity needs a texture and a size", () => { assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0.5, height: 1 }), []); assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0, height: 1, max_health: -1 }), [ - "width must be a number of blocks above 0, at most 16", - "max_health must be a number, 0 or more", + "width must be above 0", + "max_health must be 0 or more", ]); }); diff --git a/tests/mod_tools_test.ts b/tests/mod_tools_test.ts index b20d9eb..db9fcb0 100644 --- a/tests/mod_tools_test.ts +++ b/tests/mod_tools_test.ts @@ -142,10 +142,10 @@ Deno.test("check-mods finds broken mods", async () => { has(report.errors, "block broken:x is also defined by broken, broken"); has(report.errors, "items/bad.json: isn't valid json"); has(report.errors, "model broken:no_such_model doesn't exist"); - has(report.errors, `"size=1" must be a state of this block`); + has(report.errors, `variants["size=1"] names size, which isn't one of this block's states`); has(report.errors, "elements[0].from must be [x, y, z]"); - has(report.errors, `elements[0].faces: "up" isn't one of`); - has(report.errors, `pattern uses "B" but key doesn't define it`); + has(report.errors, `elements[0].faces can't have "up"`); + has(report.errors, `key needs "B", which pattern uses`); has(report.errors, "textures/huge.png: is"); has(report.errors, "scripts don't typecheck"); has(report.errors, `depends on "missing_mod", which isn't installed`); diff --git a/tests/model_parents_test.ts b/tests/model_parents_test.ts index 8c69c8b..6223167 100644 --- a/tests/model_parents_test.ts +++ b/tests/model_parents_test.ts @@ -34,8 +34,8 @@ Deno.test("a model gets its parent's display transform for each place it doesn't assertEquals(models[1].display, { gui: { scale: [2, 2, 2] }, ground: { scale: [0.25, 0.25, 0.25] } }); assertEquals(validate_model({ id: "a:base", display: models[1].display }), []); assertEquals(validate_model({ id: "a:base", display: { head: {}, gui: { scale: 2 } } }), [ - 'display: "head" isn\'t one of gui, firstperson_righthand, ground, fixed', "display.gui.scale must be [x, y, z]", + 'display can\'t have "head"', ]); }); diff --git a/tests/tags_test.ts b/tests/tags_test.ts index 4e6eaa2..203de0f 100644 --- a/tests/tags_test.ts +++ b/tests/tags_test.ts @@ -6,7 +6,7 @@ import { assert, assertEquals, assertThrows } from "@std/assert"; import { Container, ItemStack } from "$/common/inventory.ts"; import { CRAFTING_RESULT_SLOT } from "$/common/protocol.ts"; import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; -import type { TagJson } from "$/common/mod_data.ts"; +import type { ManifestJson, TagJson } from "$/common/mod_data.ts"; import { resolve_tags, tag_api, type TagSource } from "$/common/tags.ts"; import { can_stand_on } from "$/common/utils.ts"; import { read_bmod, write_bmod } from "$/common/bmod.ts"; @@ -192,10 +192,10 @@ Deno.test("check-mods finds broken tags and tags nobody defines", async () => { const has = (list: string[], text: string) => assert(list.some((e) => e.includes(text)), `expected "${text}" in\n${list.join("\n")}`); has(report.errors, "tags/items/maple/broken.json: #maple:broken needs maple:no_such_item, which doesn't exist"); - has(report.errors, `tags/items/maple/bad.json: values must be an id like "my_mod:thing"`); + has(report.errors, `tags/items/maple/bad.json: values[0] must be an id like "my_mod:thing"`); has(report.errors, "tags/items/maple/bad.json: replace must be true or false"); has(report.errors, "tags/items/misplaced.json: tag files go in tags///"); - has(report.errors, "tags/fluids/maple/sap.json: registry must be one of blocks, items, entities"); + has(report.errors, `tags/fluids/maple/sap.json: registry must be "blocks", "items", "entities"`); has(report.errors, "recipes/uses_missing_tag.json: item tag #maple:nothing_here doesn't exist"); has(report.warnings, `uses #farmersdelight:knives but doesn't list "farmersdelight" in dependencies`); // the shared namespace and optional entries need no dependency @@ -217,7 +217,7 @@ Deno.test("tags survive packing into a .bmod", () => { effects: [], tags: [tag], }; - const manifest = { format_version: 1, id: "x", name: "X", version: "1.0.0" }; + const manifest: ManifestJson = { format_version: 1, id: "x", name: "X", version: "1.0.0" }; const bmod = read_bmod(write_bmod({ manifest, data, scripts: {}, textures: new Map() }), "x.bmod"); assertEquals(bmod.data.tags, [tag]); }); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index 6935fca..0a58d15 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -3,11 +3,12 @@ // deno task check-mods // validates every mod in mods/: manifests, data files, textures, references between them, and typechecks scripts +import * as z from "zod"; import { + data_file, entity_model_from_geo, FORMAT_VERSION, - is_object, - OreJson, + type OreJson, type SpawnJson, type TagJson, validate_block, @@ -21,6 +22,7 @@ import { validate_spawn, validate_tag, } from "$/common/mod_data.ts"; +import { json_object } from "$/common/schema.ts"; import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts"; import { png_size, texture_size_problem } from "$/common/bmod.ts"; import { type TextureJson, validate_texture_json } from "$/common/texture_animation.ts"; @@ -139,6 +141,18 @@ function load_mod(mods_dir: string, id: string): LoadedMod { error(`manifest.json: credits ${credits} doesn't exist`); } + // what a data file holds, under key next to its format_version. example is what that looks like, for the error + const read_data = (path: string, key: string, contents: T, example: string) => { + const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); + if (json === undefined) return undefined; + const file = data_file(key, contents).safeParse(json); + if (!file.success) { + error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "${key}": ${example} }`); + return undefined; + } + return file.data[key] as z.infer; + }; + const load_data = ( folder: string, key: string, @@ -148,15 +162,11 @@ function load_mod(mods_dir: string, id: string): LoadedMod { // models/.geo.json are entity models, not block ones for (const file of walk(`${dir}/${folder}`, ".json").filter((file) => !file.endsWith(".geo.json"))) { const path = `${folder}/${file}`; - const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); - if (wrapper === undefined) continue; - if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !(key in wrapper)) { - error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "${key}": { ... } }`); - continue; - } - const problems = validate(wrapper[key]); + const json = read_data(path, key, json_object, "{ ... }"); + if (json === undefined) continue; + const problems = validate(json); for (const problem of problems) error(`${path}: ${problem}`); - if (problems.length === 0) into.push({ file: path, json: wrapper[key] as T }); + if (problems.length === 0) into.push({ file: path, json: json as T }); } }; load_data("blocks", "block", validate_block, mod.blocks); @@ -187,18 +197,14 @@ function load_mod(mods_dir: string, id: string): LoadedMod { // tags///.json is the tag :, in any namespace: tags are shared for (const file of walk(`${dir}/tags`, ".json")) { const path = `tags/${file}`; - const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); - if (wrapper === undefined) continue; const [registry, namespace, ...rest] = file.replace(/\.json$/, "").split("/"); if (rest.length === 0) { error(`${path}: tag files go in tags///, like tags/items/${id}/things.json`); continue; } - if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !is_object(wrapper.tag)) { - error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "tag": { "values": [ ... ] } }`); - continue; - } - const json = { ...wrapper.tag, registry, id: `${namespace}:${rest.join("/")}` }; + const tag = read_data(path, "tag", json_object, '{ "values": [ ... ] }'); + if (tag === undefined) continue; + const json = { ...tag, registry, id: `${namespace}:${rest.join("/")}` }; const problems = validate_tag(json); for (const problem of problems) error(`${path}: ${problem}`); if (problems.length === 0) mod.tags.push({ file: path, json: json as TagJson }); @@ -207,53 +213,34 @@ function load_mod(mods_dir: string, id: string): LoadedMod { // loot_tables/.json is the loot table :, like minecraft's for (const file of walk(`${dir}/loot_tables`, ".json")) { const path = `loot_tables/${file}`; - const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); - if (wrapper === undefined) continue; - if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !is_object(wrapper.loot_table)) { - error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "loot_table": { "pools": [ ... ] } }`); - continue; - } - const json = { ...wrapper.loot_table, id: `${id}:${file.replace(/\.json$/, "")}` }; + const loot_table = read_data(path, "loot_table", json_object, '{ "pools": [ ... ] }'); + if (loot_table === undefined) continue; + const json = { ...loot_table, id: `${id}:${file.replace(/\.json$/, "")}` }; const problems = validate_loot_table(json); for (const problem of problems) error(`${path}: ${problem}`); if (problems.length === 0) mod.loot_tables.push({ file: path, json: json as LootTableJson }); } if (exists(`${dir}/worldgen/ores.json`)) { - const ores = read_json(`${dir}/worldgen/ores.json`, (m) => error(`worldgen/ores.json: ${m}`)); - if (!is_object(ores) || ores.format_version !== FORMAT_VERSION || !Array.isArray(ores.ores)) { - error(`worldgen/ores.json: must be { "format_version": ${FORMAT_VERSION}, "ores": [ ... ] }`); - } else { - ores.ores.forEach((ore, i) => { - const problems = validate_ore(ore); - for (const problem of problems) error(`worldgen/ores.json: ore ${i}: ${problem}`); - if (problems.length === 0) mod.ores.push({ file: "worldgen/ores.json", json: ore as OreJson }); - }); - } + const ores = read_data("worldgen/ores.json", "ores", z.array(z.unknown()), "[ ... ]") ?? []; + ores.forEach((ore, i) => { + const problems = validate_ore(ore); + for (const problem of problems) error(`worldgen/ores.json: ore ${i}: ${problem}`); + if (problems.length === 0) mod.ores.push({ file: "worldgen/ores.json", json: ore as OreJson }); + }); } if (exists(`${dir}/worldgen/spawns.json`)) { - const spawns = read_json(`${dir}/worldgen/spawns.json`, (m) => error(`worldgen/spawns.json: ${m}`)); - if (!is_object(spawns) || spawns.format_version !== FORMAT_VERSION || !Array.isArray(spawns.spawns)) { - error(`worldgen/spawns.json: must be { "format_version": ${FORMAT_VERSION}, "spawns": [ ... ] }`); - } else { - spawns.spawns.forEach((spawn, i) => { - const problems = validate_spawn(spawn); - for (const problem of problems) error(`worldgen/spawns.json: spawn ${i}: ${problem}`); - if (problems.length === 0) { - mod.spawns.push({ file: "worldgen/spawns.json", json: spawn as SpawnJson }); - } - }); - } + const spawns = read_data("worldgen/spawns.json", "spawns", z.array(z.unknown()), "[ ... ]") ?? []; + spawns.forEach((spawn, i) => { + const problems = validate_spawn(spawn); + for (const problem of problems) error(`worldgen/spawns.json: spawn ${i}: ${problem}`); + if (problems.length === 0) mod.spawns.push({ file: "worldgen/spawns.json", json: spawn as SpawnJson }); + }); } if (exists(`${dir}/config.json`)) { - const config = read_json(`${dir}/config.json`, (m) => error(`config.json: ${m}`)); - if (!is_object(config) || config.format_version !== FORMAT_VERSION || !is_object(config.config)) { - error(`config.json: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`); - } else { - mod.config = config.config; - } + mod.config = read_data("config.json", "config", json_object, "{ ... }"); } // a mod only registers ids in its own namespace diff --git a/tools/importer/models.ts b/tools/importer/models.ts index 2c377e4..32e7303 100644 --- a/tools/importer/models.ts +++ b/tools/importer/models.ts @@ -5,15 +5,8 @@ // bottom instead of up and down, ids lose their folders, a parent keeps being a parent (bworld merges them when it // loads, see resolve_models), and what bworld has no use for (blockbench's names, display transforms for places bworld // doesn't show items, like third person) is left out -import { - DISPLAY_CONTEXTS, - type ModelDisplay, - type ModelElementJson, - type ModelFace, - type ModelFaceJson, - type ModelFileJson, -} from "$/common/block_models.ts"; -import { FORMAT_VERSION } from "$/common/mod_data.ts"; +import type { ModelDisplay, ModelElementJson, ModelFaceJson, ModelFileJson } from "$/common/block_models.ts"; +import { DISPLAY_CONTEXTS, FORMAT_VERSION, type ModelFace } from "$/common/mod_data.ts"; import { join } from "@std/path"; import { DEFAULT_REMAPS, diff --git a/tools/importer/resources.ts b/tools/importer/resources.ts index 6c20d87..9705ab5 100644 --- a/tools/importer/resources.ts +++ b/tools/importer/resources.ts @@ -4,7 +4,8 @@ // 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, type TagRegistry } from "$/common/mod_data.ts"; +import type { TagRegistry } from "$/common/mod_data.ts"; +import { ID_PATTERN } from "$/common/schema.ts"; import { registered_ids } from "$/common/mod_check.ts"; import { load_and_check } from "$/tools/check_mods.ts"; import { dirname, relative, resolve, SEPARATOR } from "@std/path"; diff --git a/tools/importer/tags.ts b/tools/importer/tags.ts index 1de0bb4..6f04ccf 100644 --- a/tools/importer/tags.ts +++ b/tools/importer/tags.ts @@ -5,7 +5,8 @@ // format is the same: values, replace and remove, with { id, required: false } for entries that can be missing. tag ids // keep their folders, since bworld's can have them too import { join } from "@std/path"; -import { FORMAT_VERSION, TAG_ID_PATTERN, type TagRegistry } from "$/common/mod_data.ts"; +import { FORMAT_VERSION, type TagRegistry } from "$/common/mod_data.ts"; +import { TAG_ID_PATTERN } from "$/common/schema.ts"; import { DEFAULT_REMAPS, empty_report, diff --git a/tools/verdigris_wire_model.ts b/tools/verdigris_wire_model.ts index d5aedbf..90f4cc2 100644 --- a/tools/verdigris_wire_model.ts +++ b/tools/verdigris_wire_model.ts @@ -12,7 +12,8 @@ // the parts lock their textures to the world (uvlock), so every piece shows the part of the texture under it, the // texture's line running north to south or its line running east to west, and it lines up from one wire to the next import { model_shape } from "$/common/block_shapes.ts"; -import type { ModelElementJson, ModelFace } from "$/common/block_models.ts"; +import type { ModelElementJson } from "$/common/block_models.ts"; +import type { ModelFace } from "$/common/mod_data.ts"; import type { Face } from "$/common/mod_api/shared.ts"; import { can_cover, ways_out } from "$/mods/bworld/scripts/verdigris/joins.ts"; import { DIRECTIONS, FACE_OFFSETS, FACES } from "$/mods/bworld/scripts/verdigris/sides.ts";