Files
bworld/common/worldgen/data.ts
T
2026-11-07 12:13:43 -03:00

460 lines
18 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// world generation as data: noises, density functions, noise settings (a generator), biome sources and dimensions, 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 * as z from "zod";
import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts";
import { DEFAULT_SHAPE, HIGHEST_Y, LOWEST_Y, shape_problem, WorldShape } from "../world_shape.ts";
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
// noises
export interface NoiseJson {
id: string;
// what it's seeded with, with the world's seed. the id's path when not set
seed_name?: string;
// the size in blocks of the first octave's features. each octave after it is twice as fine
wavelength: number;
// each octave's strength, 0 skips one
amplitudes: number[];
// 2 (x and z) when not set, or 3
dimensions?: 2 | 3;
// 3d noises: how much slower it changes up and down than across
vertical_stretch?: number;
// the noise's measured percentiles, every 5% (tools/noise_quantiles.ts), for spreading it evenly from -1 to 1. or
// another noise's id to use its table, for noises with the same amplitudes
quantiles?: number[] | string;
}
// density functions: a number for every position. a number is a constant, a string is another density function's id
export type DensityJson = number | string | DensityObjectJson;
export interface DensityObjectJson {
type: string;
[field: string]: unknown;
}
// a file in worldgen/density_function: a density function with an id
export type DensityFunctionJson = DensityObjectJson & { id: string };
// a range of numbers, any bound can be left out. in range_choice a bound can also be a density function
export interface RangeJson {
min_inclusive?: number;
min_exclusive?: number;
max_inclusive?: number;
max_exclusive?: number;
}
export interface SplineJson {
coordinate: DensityJson;
points: { location: number; value: number | SplineJson; derivative?: number }[];
}
// noise settings: a generator
export interface NoiseSettingsJson {
id: string;
sea_level: number;
// what everything solid is made of, where the surface rule doesn't say otherwise
default_block: string;
// density is sampled every cell_width blocks across and each part's cell_height up, and blended in between
cell_width: number;
terrain: { density: DensityJson; cell_height: number };
// solid only where both terrain and caves are above 0
caves: { density: DensityJson; cell_height: number };
// the ground's height before 3d noise, for surface rules, biomes and finding things far away
preliminary_surface: DensityJson;
// named values biome rules read, like temperature
climate: Record<string, DensityJson>;
// a column is steep when its preliminary surface is this much higher or lower than a neighbor's
steep: number;
biome_source: string;
// what fills empty space, the first that applies
fluids: FluidJson[];
surface_rule: SurfaceRuleJson;
}
export interface FluidJson {
block: string;
// only below this y
below: number;
// "open_sky": nothing but air above, down from the top of the world. or where a density function is in a range
where: "open_sky" | ({ function: DensityJson } & RangeJson);
}
export type SurfaceRuleJson =
| { type: "sequence"; sequence: SurfaceRuleJson[] }
| { type: "condition"; if_true: SurfaceConditionJson; then_run: SurfaceRuleJson }
| { type: "block"; result_state: { Name: string } }
| { type: "biome_surface"; part: BiomeSurfacePart };
export const BIOME_SURFACE_PARTS = ["top", "filler", "underwater_top", "underwater_filler"] as const;
export type BiomeSurfacePart = typeof BIOME_SURFACE_PARTS[number];
export type SurfaceConditionJson =
// the solid blocks above it before air, 0 for the top one, is at most offset
| { type: "stone_depth"; offset: number }
// within the biome's filler_depth below the top
| { type: "filler_depth" }
// at or above the preliminary surface plus offset
| { type: "above_preliminary_surface"; offset?: number }
// the column's ground, the first solid block from the top, is below sea level - 1
| { type: "surface_underwater" }
| { type: "steep" }
// the biome's surface has bare_cliffs
| { type: "bare_cliffs" }
// at or above where a density function says
| { type: "y_at_least"; function: DensityJson }
| { type: "biome"; biome_is: string[] }
| { type: "not"; invert: SurfaceConditionJson };
// biome sources: which biome a column gets
export interface BiomeSourceJson {
id: string;
// adds its rules to another biome source, each before or after one of its rules
extends?: string;
rules: BiomeRuleJson[];
}
export interface BiomeRuleJson {
id: string;
before?: string;
after?: string;
// every condition holds: a range of a climate value from the noise settings, or of one of RULE_VALUES, or "steep":
// true or false. no conditions always holds
when?: Record<string, RangeJson | boolean>;
biome: string;
}
// what biome rules look at besides a generator's climate, so its climate values can't be named these: the ground's y,
// a biome cell's lowest y and how far that is below the ground (0 at the ground, negative above it)
export const RULE_VALUES = ["surface", "y", "depth"];
// whether a column is steep, see NoiseSettingsJson.steep
export const RULE_NAMES = [...RULE_VALUES, "steep"];
// dimensions: a world to play and the noise settings that generate it, like neoforge's level stems. the world plays the
// one with "default": true, and only one loaded mod can have one
export interface DimensionJson {
id: string;
// the noise settings that generate it
generator: string;
default?: boolean;
// its blocks go from min_y up to max_y - 1, see WorldShape. 0 and 256 when not set
min_y?: number;
max_y?: number;
// whether light comes from the sky, true when not set
sky_light?: boolean;
}
// the shape a dimension's json gives it
export function dimension_shape(json: DimensionJson): WorldShape {
return new WorldShape({
min_y: json.min_y ?? DEFAULT_SHAPE.min_y,
max_y: json.max_y ?? DEFAULT_SHAPE.max_y,
sky_light: json.sky_light ?? DEFAULT_SHAPE.sky_light,
});
}
// what worldgen data refers to, for checking it all exists
export interface WorldgenRefs {
noises: Set<string>;
functions: Set<string>;
blocks: Set<string>;
biomes: Set<string>;
biome_sources: Set<string>;
}
export function new_refs(): WorldgenRefs {
return { noises: new Set(), functions: new Set(), blocks: new Set(), biomes: new Set(), biome_sources: new Set() };
}
// 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<NoiseJson> = 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;
// a range's bounds, numbers or (in range_choice) density functions. a range needs at least one
function bounds<T extends z.ZodType>(bound: T) {
return {
min_inclusive: bound.optional(),
min_exclusive: bound.optional(),
max_inclusive: bound.optional(),
max_exclusive: bound.optional(),
};
}
const has_bound = (range: Partial<Record<typeof RANGE_KEYS[number], unknown>>) =>
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<DensityJson> = 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<SplineJson> = 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<DensityFunctionJson> = z.intersection(
z.object({ id: worldgen_id }),
density_object,
);
const surface_rule: z.ZodType<SurfaceRuleJson> = 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<SurfaceConditionJson> = 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<NoiseSettingsJson> = z.object({
id: worldgen_id,
sea_level: z.int().min(LOWEST_Y).max(HIGHEST_Y),
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 ${RULE_NAMES.join(", ")}`)
.regex(/^[a-z_]+$/).refine((name) => !RULE_NAMES.includes(name)),
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", <range> }'),
})),
surface_rule,
});
const biome_source_schema: z.ZodType<BiomeSourceJson> = 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" });
}
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",
});
}
});
});
const dimension_schema: z.ZodType<DimensionJson> = z.strictObject({
id: worldgen_id,
generator: z.string("must be a noise settings' id").regex(WORLDGEN_ID_PATTERN),
default: z.boolean().optional(),
min_y: z.int().optional(),
max_y: z.int().optional(),
sky_light: z.boolean().optional(),
}).superRefine((json, ctx) => {
const problem = shape_problem(json.min_y ?? DEFAULT_SHAPE.min_y, json.max_y ?? DEFAULT_SHAPE.max_y);
if (problem) ctx.addIssue({ code: "custom", message: problem });
});
export function validate_noise(json: unknown): Problems {
return find_problems(noise_schema, json);
}
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);
}
export function validate_dimension(json: unknown): Problems {
return find_problems(dimension_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 density_function_refs(json: DensityFunctionJson, refs: WorldgenRefs) {
const { id: _, ...fn } = json;
density_refs(fn, refs);
}
function density_refs(json: DensityJson, refs: WorldgenRefs) {
if (typeof json === "number") return;
if (typeof json === "string") {
refs.functions.add(json);
return;
}
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);
}
}
}
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 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);
}
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);
}
if (rule.type === "block") refs.blocks.add(rule.result_state.Name);
}
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);
}
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
export function range_test(range: RangeJson): (value: number) => boolean {
const tests: ((value: number) => boolean)[] = [];
const { min_inclusive, min_exclusive, max_inclusive, max_exclusive } = range;
if (min_inclusive !== undefined) tests.push((value) => value >= min_inclusive);
if (min_exclusive !== undefined) tests.push((value) => value > min_exclusive);
if (max_inclusive !== undefined) tests.push((value) => value <= max_inclusive);
if (max_exclusive !== undefined) tests.push((value) => value < max_exclusive);
if (tests.length === 1) return tests[0];
if (tests.length === 2) {
const [a, b] = tests;
return (value) => a(value) && b(value);
}
return (value) => tests.every((test) => test(value));
}