Move world generation outside the engine and into mods and data files

This commit is contained in:
2026-10-11 00:33:59 -03:00
parent afe6e03d4c
commit 3d2b235f64
118 changed files with 8250 additions and 1108 deletions
+44 -3
View File
@@ -30,6 +30,17 @@ import {
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";
import {
type BiomeSourceJson,
type DensityFunctionJson,
type NoiseJson,
type NoiseSettingsJson,
validate_biome_source,
validate_density_function,
validate_noise,
validate_noise_settings,
} from "./worldgen/data.ts";
import { type FeatureJson, validate_feature } from "./worldgen/features.ts";
import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
import { ENGINE_GLOBAL } from "./hooks.ts";
@@ -166,10 +177,37 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
loot_tables: checked(raw_data.loot_tables, "loot_tables", validate_loot_table, problems) as LootTableJson[],
biomes: checked(raw_data.biomes, "biomes", validate_biome, problems) as BiomeJson[],
noises: checked(raw_data.noises, "noises", validate_noise, problems) as NoiseJson[],
density_functions: checked(
raw_data.density_functions,
"density_functions",
validate_density_function,
problems,
) as DensityFunctionJson[],
noise_settings: checked(
raw_data.noise_settings,
"noise_settings",
validate_noise_settings,
problems,
) as NoiseSettingsJson[],
biome_sources: checked(
raw_data.biome_sources,
"biome_sources",
validate_biome_source,
problems,
) as BiomeSourceJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[],
};
// a mod only registers ids in its own namespace
const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models];
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!, ...data.biomes!]) {
const worldgen = [
...data.noises!,
...data.density_functions!,
...data.noise_settings!,
...data.biome_sources!,
...data.features!,
];
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!, ...data.biomes!, ...worldgen]) {
if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
}
@@ -236,12 +274,15 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
return { manifest, data, scripts, textures, texture_json, credits };
}
// the same mod without its server and worldgen scripts, what players get. the server sends them the world
// the same mod without its server and worldgen scripts and the terrain's data, what players get. the server sends
// them the world
export function client_copy(bmod: Bmod): Bmod {
const scripts = { ...bmod.scripts };
delete scripts.server;
delete scripts.worldgen;
return { ...bmod, scripts };
const { noises: _n, density_functions: _d, noise_settings: _s, biome_sources: _b, features: _f, ...data } =
bmod.data;
return { ...bmod, scripts, data };
}
function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] {
+35 -35
View File
@@ -1,28 +1,33 @@
// generating a chunk: the overworld's terrain (common/worldgen), then ores, then mods' features.
// runs in chunk workers on the server and every client, which must all get the same blocks
// generating a chunk: the terrain from the generator's data (common/worldgen), then ores, then mods' features.
// only the server generates, players get finished chunks
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import type { FeatureChunk } from "$/common/mod_api/worldgen.ts";
import type { FeatureChunk, Position } from "$/common/mod_api/worldgen.ts";
import type { OreJson } from "$/common/mod_data.ts";
import { generate_overworld } from "./worldgen/overworld.ts";
import { type Wood, WOODS } from "./worldgen/trees.ts";
import type { Generator } from "./worldgen/generator.ts";
import { named_noise_2d, named_noise_3d } from "./worldgen/noise.ts";
export { named_noise_2d, named_noise_3d };
// the base game's ores, placed like mods' ores.json. the world is 256 tall with the sea at 64
const BASE_ORES: OreJson[] = [
{ id: "bworld:coal_ore", replaces: "bworld:stone", min_y: 5, max_y: 200, scale: 0.05, threshold: 0.55 },
{ id: "bworld:copper_ore", replaces: "bworld:stone", min_y: 5, max_y: 110, scale: 0.06, threshold: 0.6 },
{ id: "bworld:tin_ore", replaces: "bworld:stone", min_y: 5, max_y: 70, scale: 0.06, threshold: 0.62 },
{ id: "bworld:iron_ore", replaces: "bworld:stone", min_y: 5, max_y: 80, scale: 0.05, threshold: 0.65 },
{ id: "bworld:gold_ore", replaces: "bworld:stone", min_y: 5, max_y: 36, scale: 0.04, threshold: 0.7 },
];
// what mods add to generation, see docs/modding/worldgen/index.md
export interface WorldgenSetup {
ores: OreJson[];
features: { id: string; generate: (chunk: FeatureChunk) => void }[];
// the terrain, biomes and surface, from noise settings, see docs/modding/worldgen/terrain.md
generator: Generator;
// each mod's worldgen/ores.json, in load order. each is a pass of its own, so a mod's ores can replace an earlier
// mod's, like the base game's
ores: OreJson[][];
// code and data features in the order they run, see load_worldgen
features: SetupFeature[];
// data features by id, for chunk.place_feature
placeable: Map<string, (chunk: FeatureChunk, origin: Position) => boolean>;
}
export interface SetupFeature {
id: string;
generate: (chunk: FeatureChunk) => void;
// a code feature's biomes: it only runs in chunks with one of them. data features check each position themselves
biomes?: Set<string>;
}
export interface RawChunk {
@@ -44,7 +49,7 @@ export function generate_raw_chunk(
chunk_z: number,
seed: string,
block_ids: Record<string, number>,
worldgen?: WorldgenSetup,
worldgen: WorldgenSetup,
// the value to store for each numeric id, with its default states. just the id when missing
default_values?: number[],
): RawChunk {
@@ -73,25 +78,12 @@ export function generate_raw_chunk(
const nid = block_ids[name];
return nid === undefined ? AIR : default_values?.[nid] ?? nid;
};
// each wood's are named after it, like bworld:oak_log
const wood_ids = (part: "log" | "leaves") =>
Object.fromEntries(WOODS.map((wood) => [wood, id(`bworld:${wood}_${part}`)])) as Record<Wood, number>;
generate_overworld(blocks, heights, biomes, chunk_x, chunk_z, seed, {
stone: id("bworld:stone"),
dirt: id("bworld:dirt"),
grass: id("bworld:grass"),
snow: id("bworld:snow_block"),
water: id("bworld:water"),
logs: wood_ids("log"),
leaves: wood_ids("leaves"),
block: id,
}, (x, y, z, block) => spills.push(x, y, z, block));
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, BASE_ORES, default_values);
generate_overworld(blocks, heights, biomes, chunk_x, chunk_z, worldgen.generator.for_seed(seed), id);
if (worldgen) {
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, worldgen.ores, default_values);
generate_features(blocks, heights, biomes, set, chunk_x, chunk_z, seed, block_ids, worldgen.features);
for (const ores of worldgen.ores) {
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, ores, default_values);
}
generate_features(blocks, heights, biomes, set, chunk_x, chunk_z, seed, block_ids, worldgen);
return { blocks, spills: new Int32Array(spills), biomes };
}
@@ -148,7 +140,7 @@ function generate_features(
chunk_z: number,
seed: string,
block_ids: Record<string, number>,
features: WorldgenSetup["features"],
worldgen: WorldgenSetup,
) {
const ids_by_nid: string[] = [];
for (const [id, nid] of Object.entries(block_ids)) {
@@ -164,12 +156,15 @@ function generate_features(
return lz * CHUNK_SIZE + lx;
};
for (const feature of features) {
const chunk_biomes = new Set(biomes);
for (const feature of worldgen.features) {
if (feature.biomes && ![...feature.biomes].some((biome) => chunk_biomes.has(biome))) continue;
const chunk: FeatureChunk = {
x: chunk_x,
z: chunk_z,
seed,
rng: new Alea(`${seed}_feature_${feature.id}_${chunk_x}_${chunk_z}`),
random: (name) => new Alea(`${seed}_${name}`),
noise_2d: (name) => named_noise_2d(seed, name),
noise_3d: (name) => named_noise_3d(seed, name),
height_at: (x, z) => heights[local(x, z, "height_at")],
@@ -193,6 +188,11 @@ function generate_features(
}
set(x, y, z, nid);
},
place_feature(id, x, y, z) {
const place = worldgen.placeable.get(id);
if (!place) throw new Error(`place_feature: ${id} isn't a data feature`);
return place(chunk, { x, y, z });
},
};
try {
feature.generate(chunk);
+46 -3
View File
@@ -1,11 +1,49 @@
// what worldgen scripts get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic
import type { Id } from "./shared.ts";
import type { Id, Position } from "./shared.ts";
export type { Id } from "./shared.ts";
export type { Id, Position } from "./shared.ts";
export interface WorldgenContext {
register_terrain(id: Id, generate: (chunk: TerrainChunk) => void): void;
register_feature(id: Id, generate: (chunk: FeatureChunk) => void): void;
// a feature that's code, run on every chunk. see FeatureOptions for when
register_feature(id: Id, generate: (chunk: FeatureChunk) => void, options?: FeatureOptions): void;
// a type of feature data features can use: places config at origin, returns whether it placed anything
// deno-lint-ignore no-explicit-any
register_feature_type<C = any>(id: Id, place: (chunk: FeatureChunk, config: C, origin: Position) => boolean): void;
// a placement modifier data features can use: the positions after it, from the ones before. config is its json
register_placement_modifier<C = Record<string, unknown>>(
id: Id,
modify: (chunk: FeatureChunk, config: C, positions: Position[]) => Position[],
): void;
// every biome mods added, for what features read from them, like which trees grow
biomes(): FeatureBiome[];
}
// the order features run in, minecraft's decoration steps. features without one run in the last
export type FeatureStep =
| "raw_generation"
| "lakes"
| "local_modifications"
| "underground_structures"
| "surface_structures"
| "strongholds"
| "underground_ores"
| "underground_decoration"
| "fluid_springs"
| "vegetal_decoration"
| "top_layer_modification";
export interface FeatureOptions {
step?: FeatureStep;
// only runs in chunks with one of these biomes
biomes?: Id | Id[];
}
// a biome, as features see it
export interface FeatureBiome {
id: Id;
// its json's trees, see docs/modding/worldgen/biomes.md
trees?: { chance: number; kinds: string[]; wood: Record<string, string> };
}
export interface FeatureChunk {
@@ -15,6 +53,9 @@ export interface FeatureChunk {
readonly seed: string;
// seeded from the seed, chunk and feature id
readonly rng: { next(): number };
// seeded from the seed and name alone, the same in every chunk. for things decided across chunks, like trees
// spread over a grid of cells
random(name: string): { next(): number };
// create_noise_2d(new Alea(seed + "_" + name)), cached per seed and name
noise_2d(name: string): (x: number, z: number) => number;
noise_3d(name: string): (x: number, y: number, z: number) => number;
@@ -23,6 +64,8 @@ export interface FeatureChunk {
biome_at(x: number, z: number): Id;
get_block(x: number, y: number, z: number): Id | undefined; // inside this chunk only
set_block(x: number, y: number, z: number, id: Id): void; // up to one chunk away, like trees
// a data feature's type and config at x, y, z, without its placement. whether it placed anything
place_feature(id: Id, x: number, y: number, z: number): boolean;
}
export interface TerrainChunk extends FeatureChunk {
+125
View File
@@ -20,6 +20,19 @@ import { resolve_tags } from "./tags.ts";
import type { TextureJson } from "./texture_animation.ts";
import { loot_references, type LootTableJson } from "./loot.ts";
import { biome_blocks, type BiomeJson } from "./worldgen/biomes.ts";
import {
biome_source_refs,
type BiomeSourceJson,
density_function_refs,
type DensityFunctionJson,
new_refs,
noise_refs,
noise_settings_refs,
type NoiseJson,
type NoiseSettingsJson,
type WorldgenRefs,
} from "./worldgen/data.ts";
import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
export interface ModReport {
id: string;
@@ -44,6 +57,12 @@ export interface LoadedMod {
tags: { file: string; json: TagJson }[];
loot_tables: { file: string; json: LootTableJson }[];
biomes: { file: string; json: BiomeJson }[];
// the terrain as data, see common/worldgen/data.ts
noises: { file: string; json: NoiseJson }[];
density_functions: { file: string; json: DensityFunctionJson }[];
noise_settings: { file: string; json: NoiseSettingsJson }[];
biome_sources: { file: string; json: BiomeSourceJson }[];
features: { file: string; json: FeatureJson }[];
textures: string[];
// absolute paths by texture id
texture_files: Map<string, string>;
@@ -95,6 +114,16 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
const textures = new Set<string>(engine_textures);
// terrain data by kind, then id
const worldgen_owners: Record<string, Map<string, string[]>> = {
noise: new Map(),
"density function": new Map(),
"noise settings": new Map(),
"biome source": new Map(),
};
const biome_rule_owners = new Map<string, string[]>();
const all_noise_settings: NoiseSettingsJson[] = [];
const feature_owners = new Map<string, string[]>();
for (const mod of mods) {
for (const { json } of mod.blocks) {
@@ -116,6 +145,17 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
for (const { json } of mod.effects) add(effect_owners, json.id, mod.id);
for (const { json } of mod.loot_tables ?? []) loot_tables.add(json.id);
for (const { json } of mod.biomes ?? []) add(biome_owners, json.id, mod.id);
for (const { json } of mod.noises ?? []) add(worldgen_owners.noise, json.id, mod.id);
for (const { json } of mod.density_functions ?? []) add(worldgen_owners["density function"], json.id, mod.id);
for (const { json } of mod.features ?? []) add(feature_owners, json.id, mod.id);
for (const { json } of mod.noise_settings ?? []) {
add(worldgen_owners["noise settings"], json.id, mod.id);
all_noise_settings.push(json);
}
for (const { json } of mod.biome_sources ?? []) {
add(worldgen_owners["biome source"], json.id, mod.id);
for (const rule of json.rules) add(biome_rule_owners, rule.id, mod.id);
}
for (const { json } of mod.tags) {
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
tag_owners.get(json.registry)!.add(json.id);
@@ -275,6 +315,91 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
// mods' conditions and functions are registered by scripts, the server checks them when it starts
for (const id of refs.custom) check_namespace(file, id);
}
// the terrain as data: every id defined once, and everything it uses there
const check_worldgen = (kind: string, file: string, id: string, refs: WorldgenRefs) => {
if ((worldgen_owners[kind].get(id)?.length ?? 0) > 1) {
errors.push(`${file}: ${kind} ${id} is also defined by ${worldgen_owners[kind].get(id)!.join(", ")}`);
}
const exists = (ids: Set<string>, what: string, owners: Map<string, string[]>) => {
for (const used of ids) {
check_namespace(file, used);
if (!owners.has(used)) errors.push(`${file}: ${what} ${used} doesn't exist`);
}
};
exists(refs.noises, "noise", worldgen_owners.noise);
exists(refs.functions, "density function", worldgen_owners["density function"]);
exists(refs.biome_sources, "biome source", worldgen_owners["biome source"]);
exists(refs.biomes, "biome", biome_owners);
for (const block of refs.blocks) uses(file, block, "block");
};
for (const { file, json } of mod.noises ?? []) {
const refs = new_refs();
noise_refs(json, refs);
check_worldgen("noise", file, json.id, refs);
}
for (const { file, json } of mod.density_functions ?? []) {
const refs = new_refs();
density_function_refs(json, refs);
check_worldgen("density function", file, json.id, refs);
}
for (const { file, json } of mod.noise_settings ?? []) {
const refs = new_refs();
noise_settings_refs(json as unknown as Record<string, unknown>, 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<string, unknown>, 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));
for (const settings of users) {
const names = new Set([...Object.keys(settings.climate), "surface", "steep"]);
for (const rule of json.rules) {
for (const name of Object.keys(rule.when ?? {})) {
if (!names.has(name)) {
errors.push(
`${file}: rule ${rule.id} looks at ${name}, which ${settings.id} doesn't have. it has ${
[...names].join(", ")
}`,
);
}
}
}
}
for (const rule of json.rules) {
if ((biome_rule_owners.get(rule.id)?.length ?? 0) > 1) {
errors.push(
`${file}: biome rule ${rule.id} is also defined by ${
biome_rule_owners.get(rule.id)!.join(", ")
}`,
);
}
const target = rule.before ?? rule.after;
if (target !== undefined && !biome_rule_owners.has(target)) {
errors.push(`${file}: rule ${rule.id} goes next to ${target}, which isn't a biome rule`);
}
}
}
for (const { file, json } of mod.features ?? []) {
if ((feature_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(
`${file}: feature ${json.id} is also defined by ${feature_owners.get(json.id)!.join(", ")}`,
);
}
const refs = { blocks: new Set<string>(), biomes: new Set<string>(), custom: new Set<string>() };
feature_refs(json, refs);
for (const block of refs.blocks) uses(file, block, "block");
for (const biome of refs.biomes) {
check_namespace(file, biome);
if (!biome_owners.has(biome)) errors.push(`${file}: biome ${biome} doesn't exist`);
}
// check-mods doesn't run scripts, the server checks these when it starts
for (const custom of refs.custom) {
check_namespace(file, custom);
warnings.push(`${file}: ${custom} isn't built in, a worldgen script must register it`);
}
}
for (const { file, json } of mod.biomes ?? []) {
if ((biome_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(`${file}: biome ${json.id} is also defined by ${biome_owners.get(json.id)!.join(", ")}`);
+21 -2
View File
@@ -23,6 +23,8 @@ import {
import { resolve_tags, Tags } from "./tags.ts";
import type { LootTableJson } from "./loot.ts";
import { type BiomeJson, register_biome } from "./worldgen/biomes.ts";
import type { BiomeSourceJson, DensityFunctionJson, NoiseJson, NoiseSettingsJson } from "./worldgen/data.ts";
import type { FeatureJson } from "./worldgen/features.ts";
import { register_block_item } from "./utils.ts";
import type { ModelJson } from "./block_models.ts";
@@ -46,6 +48,13 @@ export interface ModData {
loot_tables?: LootTableJson[];
// see common/worldgen/biomes.ts. missing from mods packed before biomes were data
biomes?: BiomeJson[];
// the terrain as data, see common/worldgen/data.ts. server only, players' copies leave them out
noises?: NoiseJson[];
density_functions?: DensityFunctionJson[];
noise_settings?: NoiseSettingsJson[];
biome_sources?: BiomeSourceJson[];
// data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[];
}
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
@@ -71,7 +80,8 @@ export class RecipeBook {
by_type = new Map<string, ModRecipeJson[]>();
// every recipe as its json, in load order, for recipe viewers
all: RecipeJson[] = [];
ores: OreJson[] = [];
// each mod's ores, in load order. each mod's are their own pass, see generate_raw_chunk
ores: OreJson[][] = [];
spawns: SpawnJson[] = [];
}
@@ -129,6 +139,15 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
for (const json of data.biomes ?? []) {
register_biome(json);
}
// compiled into a generator once every mod's are in, see common/worldgen/generator.ts
for (const json of data.noises ?? []) EverythingRegistry.register("noises", json.id, json);
for (const json of data.density_functions ?? []) {
EverythingRegistry.register("density_functions", json.id, json);
}
for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json);
for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json);
// compiled with the types worldgen scripts register, see common/worldgen_loader.ts
for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
@@ -181,7 +200,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
break;
}
}
recipes.ores.push(...data.ores);
if (data.ores.length > 0) recipes.ores.push(data.ores);
recipes.spawns.push(...data.spawns);
}
+11 -29
View File
@@ -1,9 +1,8 @@
// biomes as data: worldgen/biomes/<name>.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column
// gets is still code (pick_biome in overworld.ts), these say what a biome looks like once it's picked
// gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked
import { EverythingRegistry } from "../everything_registry.ts";
import { ID_PATTERN } from "../mod_data.ts";
import { farming_day } from "../time.ts";
import { TREE_KINDS, type TreeKind, type Wood, WOODS } from "./trees.ts";
export const SEASONS = ["spring", "summer", "autumn", "winter"] as const;
export type Season = typeof SEASONS[number];
@@ -31,8 +30,9 @@ export interface BiomeJson {
colors?: { grass?: string; foliage?: string; water?: string };
// 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
trees?: { chance: number; kinds: TreeKind[]; wood?: Partial<Record<TreeKind, Wood>> };
// 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<string, string> };
}
// what's registered in "biomes", with the defaults filled in
@@ -42,7 +42,7 @@ export interface Biome {
surface: Required<SurfaceJson>;
// 0xRRGGBB
colors: { grass?: number; foliage?: number; water?: number };
trees?: { chance: number; kinds: TreeKind[]; wood: Partial<Record<TreeKind, Wood>> };
trees?: { chance: number; kinds: string[]; wood: Record<string, string> };
}
export function biome_from_json(json: BiomeJson): Biome {
@@ -88,13 +88,6 @@ export function biome_season(id: string, time: number): Season {
return get_biome(id)?.season ?? calendar_season(farming_day(time));
}
// the logs and leaves a kind of tree grows in a biome
export function tree_wood(kind: TreeKind, biome: Biome): Wood {
const wood = biome.trees?.wood[kind];
if (wood) return wood;
return kind === "big_oak" ? "oak" : kind;
}
// the block ids a biome's json uses, for checking they exist
export function biome_blocks(json: BiomeJson): string[] {
const { top, filler, underwater_top, underwater_filler } = json.surface;
@@ -152,27 +145,16 @@ export function validate_biome(json: unknown): string[] {
if (typeof trees.chance !== "number" || trees.chance < 0 || trees.chance > 1) {
problems.push("trees.chance must be a number from 0 to 1");
}
if (!Array.isArray(trees.kinds) || trees.kinds.length === 0) {
// 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");
} else {
for (const kind of trees.kinds) {
if (!TREE_KINDS.includes(kind)) {
problems.push(`trees.kinds: ${kind} isn't one of ${TREE_KINDS.join(", ")}`);
}
}
}
if (trees.wood !== undefined) {
if (!is_object(trees.wood)) {
if (!is_object(trees.wood) || !Object.values(trees.wood).every((wood) => typeof wood === "string")) {
problems.push("trees.wood must be { <kind>: <wood> }");
} else {
for (const [kind, wood] of Object.entries(trees.wood)) {
if (!TREE_KINDS.includes(kind as TreeKind)) {
problems.push(`trees.wood: ${kind} isn't a kind of tree`);
}
if (!WOODS.includes(wood as Wood)) {
problems.push(`trees.wood.${kind} must be one of ${WOODS.join(", ")}`);
}
}
}
}
}
+543
View File
@@ -0,0 +1,543 @@
// 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, TAG_ID_PATTERN } from "../mod_data.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, of "surface" (the ground's y), or
// "steep": true or false. no conditions always holds
when?: Record<string, RangeJson | boolean>;
biome: string;
}
// 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() };
}
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",
];
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");
}
}
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");
}
} else if (typeof quantiles === "string") {
worldgen_id(quantiles, "quantiles", problems);
}
return problems;
}
// the noises a noise file refers to: the one it takes its quantiles from
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, []);
}
// 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;
}
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`);
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`);
}
};
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`);
}
});
}
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: Record<string, unknown>, 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`);
}
}
check_density(json.preliminary_surface, "preliminary_surface", refs, problems);
if (!is_object(json.climate)) {
problems.push("climate must be { <name>: <density function> }");
} 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", <range> }`);
} 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);
}
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": <block> }`);
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 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<string, unknown>, 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 { <climate value>: <range>, "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(", ")}`);
}
// 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));
}
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`);
}
function is_object(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+342
View File
@@ -0,0 +1,342 @@
// compiles density functions (see data.ts) into plain closures, once per seed, so generating a chunk never reads json.
// every operation is a pair, so it rounds exactly like the code it was written from: a world generated from the same
// data is the same block for block. named functions that don't change with y are worked out once per column
import { clamp, OctaveNoise2D, OctaveNoise3D, Quantiles, smoothstep } from "./noise.ts";
import type { DensityFunctionJson, DensityJson, DensityObjectJson, NoiseJson, SplineJson } from "./data.ts";
// a density function's value at a block
export type Density = (x: number, y: number, z: number) => number;
// where named noises and density functions come from
export interface DensitySources {
noise(id: string): NoiseJson | undefined;
function(id: string): DensityFunctionJson | undefined;
}
interface CompiledNoise {
json: NoiseJson;
sample2?: OctaveNoise2D;
sample3?: OctaveNoise3D;
quantiles?: Quantiles;
}
const X: Density = (x) => x;
const Y: Density = (_x, y) => y;
const Z: Density = (_x, _y, z) => z;
export class DensityCompiler {
readonly seed: string;
#sources: DensitySources;
#functions = new Map<string, Density>();
#noises = new Map<string, CompiledNoise>();
#varies_with_y = new Map<string, boolean>();
// named functions being compiled, to find ones that use themselves
#compiling: string[] = [];
constructor(seed: string, sources: DensitySources) {
this.seed = seed;
this.#sources = sources;
}
compile(json: DensityJson): Density {
if (typeof json === "number") return () => json;
if (typeof json === "string") return this.#named(json);
return this.#object(json);
}
// a named density function, compiled once. one that's the same all the way up a column is cached per column
#named(id: string): Density {
const done = this.#functions.get(id);
if (done) return done;
const json = this.#sources.function(id);
if (!json) throw new Error(`density function ${id} doesn't exist`);
if (this.#compiling.includes(id)) {
throw new Error(`density function ${id} uses itself: ${[...this.#compiling, id].join(" -> ")}`);
}
this.#compiling.push(id);
const { id: _, ...fn } = json;
const inner = this.#object(fn as DensityObjectJson);
this.#compiling.pop();
const compiled = this.varies_with_y(id) ? inner : per_column(inner);
this.#functions.set(id, compiled);
return compiled;
}
// whether a density function can be different at different heights of the same column
varies_with_y(json: DensityJson): boolean {
if (typeof json === "number") return false;
if (typeof json === "string") {
let varies = this.#varies_with_y.get(json);
if (varies === undefined) {
const named = this.#sources.function(json);
if (!named) throw new Error(`density function ${json} doesn't exist`);
// a loop is reported by #named, assume no while looking
this.#varies_with_y.set(json, false);
const { id: _, ...fn } = named;
varies = this.varies_with_y(fn as DensityObjectJson);
this.#varies_with_y.set(json, varies);
}
return varies;
}
switch (json.type) {
case "y":
return true;
case "noise": {
const axes = ["x", "z"].map((axis) =>
json[axis] !== undefined && this.varies_with_y(json[axis] as DensityJson)
);
if (axes.some((v) => v)) return true;
if (this.#noise(json.noise as string).json.dimensions !== 3) return false;
return json.y === undefined || this.varies_with_y(json.y as DensityJson);
}
case "spline":
return this.#spline_varies(json.spline as SplineJson);
default:
return Object.entries(json).some(([key, value]) =>
key !== "type" && (typeof value === "string" || typeof value === "object") && value !== null &&
!Array.isArray(value) && this.varies_with_y(value as DensityJson)
);
}
}
#spline_varies(spline: SplineJson): boolean {
return this.varies_with_y(spline.coordinate) ||
spline.points.some((point) => typeof point.value !== "number" && this.#spline_varies(point.value));
}
#object(json: DensityObjectJson): Density {
const field = (name: string) => this.compile(json[name] as DensityJson);
switch (json.type) {
case "constant": {
const value = json.argument as number;
return () => value;
}
case "x":
return X;
case "y":
return Y;
case "z":
return Z;
case "noise":
return this.#noise_function(json);
case "add":
case "sub":
case "mul":
case "div":
case "min":
case "max":
return arithmetic(json.type, json.argument1 as DensityJson, json.argument2 as DensityJson, this);
case "abs": {
const argument = field("argument");
return (x, y, z) => Math.abs(argument(x, y, z));
}
case "clamp": {
const input = field("input");
const min = json.min as number;
const max = json.max as number;
return (x, y, z) => clamp(input(x, y, z), min, max);
}
case "smoothstep": {
const input = field("input");
const from = json.from as number;
const to = json.to as number;
return (x, y, z) => smoothstep(from, to, input(x, y, z));
}
case "spline":
return this.#spline(json.spline as SplineJson);
case "range_choice":
return this.#range_choice(json);
case "cache_2d": {
if (this.varies_with_y(json.argument as DensityJson)) {
throw new Error("cache_2d around a density function that changes with y");
}
return per_column(field("argument"));
}
default:
throw new Error(`density function type ${json.type} doesn't exist`);
}
}
#noise(id: string): CompiledNoise {
let noise = this.#noises.get(id);
if (noise) return noise;
const json = this.#sources.noise(id);
if (!json) throw new Error(`noise ${id} doesn't exist`);
const name = json.seed_name ?? id.slice(id.indexOf(":") + 1);
noise = json.dimensions === 3
? {
json,
sample3: new OctaveNoise3D(this.seed, name, json.wavelength, json.amplitudes, json.vertical_stretch),
}
: { json, sample2: new OctaveNoise2D(this.seed, name, json.wavelength, json.amplitudes) };
this.#noises.set(id, noise);
noise.quantiles = this.#quantiles(id, []);
return noise;
}
// a noise's quantile table, or the one of the noise it names
#quantiles(id: string, seen: string[]): Quantiles | undefined {
const json = this.#sources.noise(id);
if (!json) throw new Error(`noise ${seen.at(-1) ?? id} takes its quantiles from ${id}, which doesn't exist`);
if (json.quantiles === undefined) return undefined;
if (typeof json.quantiles !== "string") return new Quantiles(json.quantiles);
if (seen.includes(id)) throw new Error(`noise ${id}'s quantiles go round in a loop`);
return this.#quantiles(json.quantiles, [...seen, id]);
}
#noise_function(json: DensityObjectJson): Density {
const noise = this.#noise(json.noise as string);
const even = json.even === true;
if (even && !noise.quantiles) throw new Error(`noise ${json.noise} has no quantiles to be spread evenly with`);
const quantiles = noise.quantiles!;
const axis = (name: string, plain: Density) =>
json[name] === undefined ? plain : this.compile(json[name] as DensityJson);
const plain = json.x === undefined && json.y === undefined && json.z === undefined;
if (noise.sample2) {
const n = noise.sample2;
if (plain) return even ? (x, _y, z) => quantiles.even(n.sample(x, z)) : (x, _y, z) => n.sample(x, z);
const fx = axis("x", X);
const fz = axis("z", Z);
return even
? (x, y, z) => quantiles.even(n.sample(fx(x, y, z), fz(x, y, z)))
: (x, y, z) => n.sample(fx(x, y, z), fz(x, y, z));
}
const n = noise.sample3!;
if (plain) return even ? (x, y, z) => quantiles.even(n.sample(x, y, z)) : (x, y, z) => n.sample(x, y, z);
const fx = axis("x", X);
const fy = axis("y", Y);
const fz = axis("z", Z);
return even
? (x, y, z) => quantiles.even(n.sample(fx(x, y, z), fy(x, y, z), fz(x, y, z)))
: (x, y, z) => n.sample(fx(x, y, z), fy(x, y, z), fz(x, y, z));
}
// minecraft's CubicSpline: a smooth curve through points, where a point's value can itself be a spline of another
// coordinate. that nesting is how the terrain turns continentalness, erosion and ridges into heights
#spline(json: SplineJson): Density {
const coordinate = this.compile(json.coordinate);
const locations = json.points.map((point) => point.location);
const values = json.points.map((point) =>
typeof point.value === "number" ? point.value : this.#spline(point.value)
);
const slopes = json.points.map((point) => point.derivative ?? 0);
const last = locations.length - 1;
const value_of = (i: number, x: number, y: number, z: number) => {
const value = values[i];
return typeof value === "number" ? value : value(x, y, z);
};
return (x, y, z) => {
const c = coordinate(x, y, z);
if (c <= locations[0]) {
return value_of(0, x, y, z) + slopes[0] * (c - locations[0]);
}
if (c >= locations[last]) {
return value_of(last, x, y, z) + slopes[last] * (c - locations[last]);
}
let i = 0;
while (locations[i + 1] < c) i++;
const x0 = locations[i];
const x1 = locations[i + 1];
const width = x1 - x0;
const t = (c - x0) / width;
const y0 = value_of(i, x, y, z);
const y1 = value_of(i + 1, x, y, z);
// hermite interpolation, written the way minecraft does it
const a = slopes[i] * width - (y1 - y0);
const b = -slopes[i + 1] * width + (y1 - y0);
return y0 + (y1 - y0) * t + t * (1 - t) * (a + (b - a) * t);
};
}
// one function or the other, by whether the input is within bounds, which can themselves be density functions
#range_choice(json: DensityObjectJson): Density {
const input = this.compile(json.input as DensityJson);
const inside = this.compile(json.when_in_range as DensityJson);
const outside = this.compile(json.when_out_of_range as DensityJson);
const bound = (name: string) => json[name] === undefined ? undefined : this.compile(json[name] as DensityJson);
const min_inclusive = bound("min_inclusive");
const min_exclusive = bound("min_exclusive");
const max_inclusive = bound("max_inclusive");
const max_exclusive = bound("max_exclusive");
return (x, y, z) => {
const value = input(x, y, z);
const within = (min_inclusive === undefined || value >= min_inclusive(x, y, z)) &&
(min_exclusive === undefined || value > min_exclusive(x, y, z)) &&
(max_inclusive === undefined || value <= max_inclusive(x, y, z)) &&
(max_exclusive === undefined || value < max_exclusive(x, y, z));
return within ? inside(x, y, z) : outside(x, y, z);
};
}
}
// remembers the last column's value, like minecraft's cache_2d. columns are generated one after another
function per_column(inner: Density): Density {
let last_x = NaN;
let last_z = NaN;
let last = 0;
return (x, y, z) => {
if (x === last_x && z === last_z) return last;
last = inner(x, y, z);
last_x = x;
last_z = z;
return last;
};
}
// a pair of arguments, with a number folded in instead of called, and two numbers worked out once
function arithmetic(type: string, first: DensityJson, second: DensityJson, compiler: DensityCompiler): Density {
const op = OPERATIONS[type];
if (typeof first === "number" && typeof second === "number") {
const value = op(first, second);
return () => value;
}
if (typeof second === "number") {
const a = compiler.compile(first);
switch (type) {
case "add":
return (x, y, z) => a(x, y, z) + second;
case "sub":
return (x, y, z) => a(x, y, z) - second;
case "mul":
return (x, y, z) => a(x, y, z) * second;
case "div":
return (x, y, z) => a(x, y, z) / second;
}
}
if (typeof first === "number") {
const b = compiler.compile(second);
switch (type) {
case "add":
return (x, y, z) => first + b(x, y, z);
case "sub":
return (x, y, z) => first - b(x, y, z);
case "mul":
return (x, y, z) => first * b(x, y, z);
case "div":
return (x, y, z) => first / b(x, y, z);
}
}
const a = compiler.compile(first);
const b = compiler.compile(second);
switch (type) {
case "add":
return (x, y, z) => a(x, y, z) + b(x, y, z);
case "sub":
return (x, y, z) => a(x, y, z) - b(x, y, z);
case "mul":
return (x, y, z) => a(x, y, z) * b(x, y, z);
case "div":
return (x, y, z) => a(x, y, z) / b(x, y, z);
default:
return (x, y, z) => op(a(x, y, z), b(x, y, z));
}
}
const OPERATIONS: Record<string, (a: number, b: number) => number> = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
mul: (a, b) => a * b,
div: (a, b) => a / b,
min: (a, b) => Math.min(a, b),
max: (a, b) => Math.max(a, b),
};
+601
View File
@@ -0,0 +1,601 @@
// data features: worldgen/features/<path>.json in a mod, a feature's type and config (what) with a list of placement
// modifiers (where), see docs/modding/worldgen/index.md. like minecraft's configured and placed features joined into
// one file. the types and modifiers here are built in, worldgen scripts register more
import { EverythingRegistry } from "../everything_registry.ts";
import type { BlockRegistry } from "../everything_registry.ts";
import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts";
import { ID_PATTERN, TAG_ID_PATTERN } from "../mod_data.ts";
import { list_matches } from "../tags.ts";
import { can_stand_on } from "../utils.ts";
import { AIR_ID } from "../protocol.ts";
import type { FeatureChunk, FeatureStep, Position } from "../mod_api/worldgen.ts";
// the order features run in, minecraft's decoration steps. a feature without a step runs in the last
export const FEATURE_STEPS: FeatureStep[] = [
"raw_generation",
"lakes",
"local_modifications",
"underground_structures",
"surface_structures",
"strongholds",
"underground_ores",
"underground_decoration",
"fluid_springs",
"vegetal_decoration",
"top_layer_modification",
];
export const DEFAULT_STEP: FeatureStep = "top_layer_modification";
export interface FeatureJson {
id: string;
// a built in type, like "minecraft:block_column", or one a worldgen script registers
type: string;
config?: Record<string, unknown>;
placement?: PlacementJson[];
// only where the column is one of these biomes
biomes?: string | string[];
step?: FeatureStep;
}
export interface PlacementJson {
type: string;
[field: string]: unknown;
}
// a type of feature: places config at origin with the chunk's random numbers, returns whether it placed anything
export type FeatureType = (chunk: FeatureChunk, config: unknown, origin: Position) => boolean;
// a placement modifier: the positions after it, from the ones before
export type PlacementModifier = (chunk: FeatureChunk, config: unknown, positions: Position[]) => Position[];
// a built in name without its namespace, so "minecraft:count" and "count" are the same. undefined for a mod's own
export function builtin_name(type: string): string | undefined {
if (!type.includes(":")) return type;
return type.startsWith("minecraft:") ? type.slice("minecraft:".length) : undefined;
}
// checking
// what a feature uses, for check-mods
export interface FeatureRefs {
blocks: Set<string>;
biomes: Set<string>;
// types and modifiers that aren't built in, which a worldgen script has to register
custom: Set<string>;
}
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;
}
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<string, unknown>, "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);
});
}
}
// compiling: a data feature becomes a function of the chunk, run with the chunk's random numbers
export interface CompiledFeature {
// where it runs, then what it places at each position
generate(chunk: FeatureChunk): void;
// what chunk.place_feature does: its type and config at a position, without its placement
place(chunk: FeatureChunk, origin: Position): boolean;
}
export function compile_feature(
json: FeatureJson,
types: Map<string, FeatureType>,
modifiers: Map<string, PlacementModifier>,
): CompiledFeature {
const config = json.config ?? {};
const builtin = builtin_name(json.type);
let place: (chunk: FeatureChunk, origin: Position) => boolean;
if (builtin !== undefined) {
place = FEATURE_TYPES[builtin].compile(config);
} else {
const type = types.get(json.type);
if (!type) {
throw new Error(
`feature ${json.id}: type ${json.type} isn't built in, and no worldgen script registered it`,
);
}
place = (chunk, origin) => type(chunk, config, origin);
}
const steps = (json.placement ?? []).map((modifier, i) => {
const name = builtin_name(modifier.type);
if (name !== undefined) return MODIFIERS[name].compile(modifier);
const custom = modifiers.get(modifier.type);
if (!custom) {
throw new Error(
`feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no worldgen script registered it`,
);
}
return (chunk: FeatureChunk, positions: Position[]) => custom(chunk, modifier, positions);
});
const biomes = json.biomes === undefined
? undefined
: new Set(typeof json.biomes === "string" ? [json.biomes] : json.biomes);
return {
place,
generate(chunk) {
// minecraft's origin: the chunk's corner at the bottom of the world
let positions: Position[] = [{ x: chunk.x * CHUNK_SIZE, y: 0, z: chunk.z * CHUNK_SIZE }];
for (const step of steps) positions = step(chunk, positions);
for (const position of positions) {
if (
biomes &&
!(inside(chunk, position.x, position.z) && biomes.has(chunk.biome_at(position.x, position.z)))
) {
continue;
}
place(chunk, position);
}
},
};
}
// built in feature types
interface Builtin<T> {
check(json: Record<string, unknown>, at: string, refs: FeatureRefs, problems: string[]): void;
compile(json: Record<string, unknown>): T;
}
const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Position) => boolean>> = {
// one block, where it can stand
simple_block: {
check(json, at, refs, problems) {
check_state(json.to_place, `${at}.to_place`, refs, problems);
},
compile(json) {
const id = state_id(json.to_place);
return (chunk, { x, y, z }) => {
if (!survives(chunk, id, x, y, z)) return false;
chunk.set_block(x, y, z, id);
return true;
};
},
},
// layers of blocks stacked up (or down) from the origin, cut short where allowed_placement doesn't hold
block_column: {
check(json, at, refs, problems) {
if (!Array.isArray(json.layers) || json.layers.length === 0) {
problems.push(`${at}.layers must be a list of { "height", "provider" }`);
} else {
json.layers.forEach((layer: unknown, i: number) => {
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`);
}
},
compile(json) {
const layers = (json.layers as { height: unknown; provider: unknown }[]).map((layer) => ({
height: int_provider(layer.height),
id: state_id(layer.provider),
}));
const dy = json.direction === "down" ? -1 : 1;
const allowed = json.allowed_placement === undefined
? (chunk: FeatureChunk, x: number, y: number, z: number) => block_at(chunk, x, y, z) === AIR_ID
: block_predicate(json.allowed_placement);
const tip_first = json.prioritize_tip === true;
return (chunk, { x, y, z }) => {
const column: string[] = [];
for (const layer of layers) {
const height = layer.height(chunk);
for (let i = 0; i < height; i++) column.push(layer.id);
}
let fits = 0;
while (fits < column.length && allowed(chunk, x, y + fits * dy, z)) fits++;
if (fits === 0) return false;
const placed = tip_first ? column.slice(column.length - fits) : column.slice(0, fits);
placed.forEach((id, i) => chunk.set_block(x, y + i * dy, z, id));
return true;
};
},
},
};
// built in placement modifiers
type Modifier = (chunk: FeatureChunk, positions: Position[]) => Position[];
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"];
const MODIFIERS: Record<string, Builtin<Modifier>> = {
// each position becomes count of them
count: {
check(json, at, _refs, problems) {
check_int(json.count, `${at}.count`, problems);
},
compile(json) {
const count = int_provider(json.count);
return (chunk, positions) =>
positions.flatMap((p) => Array.from({ length: count(chunk) }, () => ({ ...p })));
},
},
// 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`);
}
},
compile(json) {
const chance = json.chance as number;
return (chunk, positions) => positions.filter(() => chunk.rng.next() < 1 / chance);
},
},
// somewhere random in the chunk, across
in_square: {
check() {},
compile() {
return (chunk, positions) =>
positions.map((p) => {
const x = p.x + Math.floor(chunk.rng.next() * CHUNK_SIZE);
const z = p.z + Math.floor(chunk.rng.next() * CHUNK_SIZE);
return { x, y: p.y, z };
});
},
},
// 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);
},
compile(json) {
const xz = int_provider(json.xz_spread ?? 0);
const y = int_provider(json.y_spread ?? 0);
return (chunk, positions) =>
positions.map((p) => ({ x: p.x + xz(chunk), y: p.y + y(chunk), z: p.z + xz(chunk) }));
},
},
// at a height
height_range: {
check(json, at, _refs, problems) {
check_height(json.height, `${at}.height`, problems);
},
compile(json) {
const height = height_provider(json.height);
return (chunk, positions) => positions.map((p) => ({ x: p.x, y: height(chunk), z: p.z }));
},
},
// 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(", ")}`);
}
},
compile(json) {
const floor = String(json.heightmap).startsWith("OCEAN_FLOOR");
return (chunk, positions) =>
positions.flatMap((p) => {
if (!inside(chunk, p.x, p.z)) return [];
let y = CHUNK_HEIGHT - 1;
while (y >= 0 && !counts_for_heightmap(chunk.get_block(p.x, y, p.z), floor)) y--;
return [{ x: p.x, y: y + 1, z: p.z }];
});
},
},
// where a block predicate holds
block_predicate_filter: {
check(json, at, refs, problems) {
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
},
compile(json) {
const predicate = block_predicate(json.predicate);
return (chunk, positions) => positions.filter((p) => predicate(chunk, p.x, p.y, p.z));
},
},
};
function counts_for_heightmap(id: string | undefined, floor: boolean) {
if (id === undefined || id === AIR_ID) return false;
return !floor || !EverythingRegistry.get<BlockRegistry>("blocks", id)?.liquid;
}
// 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);
}
break;
}
case "would_survive":
check_state(json.state, `${at}.state`, refs, problems);
break;
case "not":
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
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));
}
}
function block_predicate(json: unknown): Predicate {
const predicate = json as Record<string, unknown>;
const [ox, oy, oz] = (predicate.offset as number[] | undefined) ?? [0, 0, 0];
const at =
(test: (id: string | undefined, chunk: FeatureChunk, x: number, y: number, z: number) => boolean): Predicate =>
(chunk, x, y, z) => test(block_at(chunk, x + ox, y + oy, z + oz), chunk, x + ox, y + oy, z + oz);
const info = (id: string | undefined) =>
id === undefined ? undefined : EverythingRegistry.get<BlockRegistry>("blocks", id);
switch (builtin_name(predicate.type as string)) {
case "matching_blocks": {
const blocks = typeof predicate.blocks === "string" ? [predicate.blocks] : predicate.blocks as string[];
return at((id) => id !== undefined && list_matches("blocks", blocks, id));
}
case "solid":
return at((id) => id !== undefined && info(id)?.has_collision === true);
case "replaceable":
return at((id) => id === AIR_ID || info(id)?.replaceable === true);
case "would_survive": {
const state = state_id(predicate.state);
return at((_id, chunk, x, y, z) => survives(chunk, state, x, y, z));
}
case "not": {
const inner = block_predicate(predicate.predicate);
return (chunk, x, y, z) => !inner(chunk, x + ox, y + oy, z + oz);
}
case "all_of": {
const inner = (predicate.predicates as unknown[]).map(block_predicate);
return (chunk, x, y, z) => inner.every((p) => p(chunk, x + ox, y + oy, z + oz));
}
case "any_of": {
const inner = (predicate.predicates as unknown[]).map(block_predicate);
return (chunk, x, y, z) => inner.some((p) => p(chunk, x + ox, y + oy, z + oz));
}
default:
return () => true;
}
}
// whether a block could be at x y z: where it is, it isn't air, and it can stand on what's under it (place_on)
function survives(chunk: FeatureChunk, id: string, x: number, y: number, z: number) {
if (y < 0 || y >= CHUNK_HEIGHT) return false;
const below = block_at(chunk, x, y - 1, z);
return below !== undefined && can_stand_on(EverythingRegistry.get<BlockRegistry>("blocks", id), below);
}
// the block at x y z, undefined outside the chunk or the world
function block_at(chunk: FeatureChunk, x: number, y: number, z: number) {
return inside(chunk, x, z) ? chunk.get_block(x, y, z) : undefined;
}
function inside(chunk: FeatureChunk, x: number, z: number) {
return Math.floor(x / CHUNK_SIZE) === chunk.x && Math.floor(z / CHUNK_SIZE) === chunk.z;
}
// 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<string, unknown>;
return (is_object(object.state) ? object.state.Name : object.Name) as string;
}
// numbers: a whole number, { "type": "constant", "value" }, { "type": "uniform", "min_inclusive", "max_inclusive" } or
// { "type": "weighted_list", "distribution": [{ "data", "weight" }] }, like minecraft's int providers
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<string, unknown>;
switch (builtin_name(String(object.type))) {
case "constant": {
const value = object.value as number;
return () => value;
}
case "uniform": {
const min = object.min_inclusive as number;
const span = (object.max_inclusive as number) - min + 1;
return (chunk) => min + Math.floor(chunk.rng.next() * span);
}
default: {
const entries = (object.distribution as { data: unknown; weight: number }[]).map((entry) => ({
data: int_provider(entry.data),
weight: entry.weight,
}));
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
return (chunk) => {
let roll = Math.floor(chunk.rng.next() * total);
for (const entry of entries) {
if (roll < entry.weight) return entry.data(chunk);
roll -= entry.weight;
}
return entries.at(-1)!.data(chunk);
};
}
}
}
// 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<string, number>;
if (object.absolute !== undefined) return object.absolute;
if (object.above_bottom !== undefined) return object.above_bottom;
return CHUNK_HEIGHT - 1 - object.below_top;
}
function height_provider(json: unknown): IntProvider {
const object = json as Record<string, unknown>;
if (object.type === undefined) {
const y = anchor(object);
return () => y;
}
if (builtin_name(String(object.type)) === "constant") {
const y = anchor(object.value);
return () => y;
}
const min = anchor(object.min_inclusive);
const span = anchor(object.max_inclusive) - min + 1;
return (chunk) => min + Math.floor(chunk.rng.next() * span);
}
function is_object(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+91
View File
@@ -0,0 +1,91 @@
// a generator: noise settings, and the density functions, noises and biome rules it uses. compiled once for each
// seed, see OverworldTerrain. the data comes from mods' worldgen folders, see docs/modding/worldgen/terrain.md
import { EverythingRegistry } from "../everything_registry.ts";
import type { BiomeRuleJson, BiomeSourceJson, DensityFunctionJson, NoiseJson, NoiseSettingsJson } from "./data.ts";
import type { DensitySources } from "./density.ts";
import { OverworldTerrain } from "./terrain.ts";
// everything worldgen data mods registered, in load order
export interface WorldgenData {
noises: NoiseJson[];
density_functions: DensityFunctionJson[];
noise_settings: NoiseSettingsJson[];
biome_sources: BiomeSourceJson[];
}
export class Generator {
readonly settings: NoiseSettingsJson;
// the biome source's rules with every mod's added in, the first that holds picks a column's biome
readonly rules: BiomeRuleJson[];
readonly sources: DensitySources;
#seeds = new Map<string, OverworldTerrain>();
// throws when the data doesn't add up, like a density function that doesn't exist
constructor(id: string, data: WorldgenData) {
const settings = data.noise_settings.find((settings) => settings.id === id);
if (!settings) throw new Error(`there's no generator ${id}: no mod has worldgen/noise_settings for it`);
this.settings = settings;
const noises = new Map(data.noises.map((noise) => [noise.id, noise]));
const functions = new Map(data.density_functions.map((fn) => [fn.id, fn]));
this.sources = { noise: (id) => noises.get(id), function: (id) => functions.get(id) };
this.rules = merge_rules(settings, data.biome_sources);
// compiling once finds missing noises and functions, and loops, before any chunk is generated
this.for_seed("");
}
for_seed(seed: string): OverworldTerrain {
let terrain = this.#seeds.get(seed);
if (!terrain) {
terrain = new OverworldTerrain(seed, this);
this.#seeds.set(seed, terrain);
}
return terrain;
}
}
// the generator called id, from what mods registered
export function compile_generator(id: string): Generator {
const all = <T>(registry: string) => (EverythingRegistry.get_registry<T>(registry) ?? []).filter((v) => v);
return new Generator(id, {
noises: all("noises"),
density_functions: all("density_functions"),
noise_settings: all("noise_settings"),
biome_sources: all("biome_sources"),
});
}
// the biome source the settings name, with the rules of every source that extends it put in, in load order
function merge_rules(settings: NoiseSettingsJson, sources: BiomeSourceJson[]): BiomeRuleJson[] {
const base = sources.find((source) => source.id === settings.biome_source && source.extends === undefined);
if (!base) throw new Error(`noise settings ${settings.id}: biome source ${settings.biome_source} doesn't exist`);
const rules = [...base.rules];
for (const source of sources.filter((source) => source.extends === base.id)) {
for (const rule of source.rules) {
const target = rule.before ?? rule.after!;
const at = rules.findIndex((other) => other.id === target);
if (at < 0) {
throw new Error(
`biome source ${source.id}: rule ${rule.id} goes ${rule.before ? "before" : "after"} ${target}, ` +
`which ${base.id} doesn't have`,
);
}
rules.splice(rule.before ? at : at + 1, 0, rule);
}
}
const names = new Set([...Object.keys(settings.climate), "surface", "steep"]);
const seen = new Set<string>();
for (const rule of rules) {
if (seen.has(rule.id)) throw new Error(`biome source ${base.id}: two rules are called ${rule.id}`);
seen.add(rule.id);
for (const name of Object.keys(rule.when ?? {})) {
if (!names.has(name)) {
throw new Error(
`biome rule ${rule.id}: ${name} isn't a climate value of ${settings.id}, which has ${
[...names].join(", ")
}`,
);
}
}
}
return rules;
}
+108 -235
View File
@@ -1,200 +1,110 @@
// fills a chunk with the overworld: the terrain's density sampled on a coarse grid and interpolated (minecraft's
// noise cells), caves cut out of it, water up to sea level, then biomes and their surface blocks
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, SEA_LEVEL } from "$/common/constants.ts";
import { OctaveNoise2D } from "./noise.ts";
import { OverworldTerrain, TerrainColumn } from "./terrain.ts";
import { grow_tree, tree_sites, type Wood } from "./trees.ts";
import { type Biome, get_biome, tree_wood } from "./biomes.ts";
// density is sampled every CELL_WIDTH blocks across and CELL_HEIGHT up, caves every CAVE_CELL_HEIGHT up since
// tunnels are thinner than terrain features
const CELL_WIDTH = 4;
const CELL_HEIGHT = 8;
const CAVE_CELL_HEIGHT = 4;
const CORNERS = CHUNK_SIZE / CELL_WIDTH + 1;
const TERRAIN_LEVELS = CHUNK_HEIGHT / CELL_HEIGHT + 1;
const CAVE_LEVELS = CHUNK_HEIGHT / CAVE_CELL_HEIGHT + 1;
// surface blocks only go this far below the ground's height, so cave floors stay stone
const SURFACE_REACH = 20;
// a column is a cliff when its ground is this much higher or lower than a neighbor's
const STEEP = 3.5;
// snow covers the tops of everything above this, give or take
const SNOW_LINE = SEA_LEVEL + 112;
// the blocks the overworld is made of, as numeric ids
export interface OverworldBlocks {
stone: number;
dirt: number;
grass: number;
snow: number;
water: number;
logs: Record<Wood, number>;
leaves: Record<Wood, number>;
// any other block, for biomes' surfaces
block(id: string): number;
}
// a biome's surface, as numeric ids
interface Surface {
top: number;
filler: number;
filler_depth: number;
underwater_top: number;
underwater_filler: number;
bare_cliffs: boolean;
}
// picks a column's biome from its climate and shape, like minecraft's multi noise biome source
export function pick_biome(column: TerrainColumn, surface_y: number, steep: boolean): string {
const { continentalness: c, erosion, ridges, temperature: t, humidity: h } = column.climate;
const flat = Math.abs(erosion);
const valley = Math.abs(ridges);
const frozen = t < -0.65;
const cold = t < -0.3;
const warm = t > 0.2;
const hot = t > 0.55;
if (surface_y < SEA_LEVEL - 1) {
if (valley < 0.06 && c > -0.2) return frozen ? "bworld:frozen_river" : "bworld:river";
if (c < -0.45) {
return frozen ? "bworld:deep_frozen_ocean" : hot ? "bworld:deep_lukewarm_ocean" : "bworld:deep_ocean";
}
return frozen ? "bworld:frozen_ocean" : hot ? "bworld:warm_ocean" : "bworld:ocean";
}
if (c < -0.12 && surface_y <= SEA_LEVEL + 4) {
return steep ? "bworld:stony_shore" : cold ? "bworld:snowy_beach" : "bworld:beach";
}
if (valley < 0.04 && c > -0.2 && surface_y <= SEA_LEVEL + 1) {
return frozen ? "bworld:frozen_river" : "bworld:river";
}
const above = surface_y - SEA_LEVEL;
if (above > 105) {
if (cold) return "bworld:frozen_peaks";
return column.jaggedness > 0.35 ? "bworld:jagged_peaks" : "bworld:stony_peaks";
}
if (above > 60 && cold) {
return "bworld:snowy_slopes";
}
if (above > 30 && !cold && h > -0.3) {
return "bworld:meadow";
}
if (frozen) return h > 0 ? "bworld:snowy_taiga" : "bworld:snowy_plains";
if (cold) return h > 0 ? "bworld:taiga" : "bworld:plains";
if (hot) return h < -0.2 ? "bworld:desert" : h < 0.4 ? "bworld:savanna" : "bworld:jungle";
if (warm) return h < -0.3 ? "bworld:savanna" : h > 0.6 ? "bworld:jungle" : "bworld:forest";
if (h > 0.5 && flat > 0.6) return "bworld:swamp";
return h < -0.35 ? "bworld:plains" : h < 0.45 ? "bworld:forest" : "bworld:dark_forest";
}
interface SeedGenerators {
terrain: OverworldTerrain;
snow_line: OctaveNoise2D;
}
const generators = new Map<string, SeedGenerators>();
function generators_for(seed: string): SeedGenerators {
let found = generators.get(seed);
if (!found) {
found = {
terrain: new OverworldTerrain(seed),
snow_line: new OctaveNoise2D(seed, "snow_line", 96, [1, 1]),
};
generators.set(seed, found);
}
return found;
}
// fills blocks (indexed y * CHUNK_AREA + z * CHUNK_SIZE + x) and each column's surface height and biome.
// blocks trees put in other chunks go to spill
// a column's biome without generating its chunk, from its height before 3d noise, so it can be a little off near
// coasts and cliffs. for searching far away, like /locatebiome
export function estimate_biome(seed: string, x: number, z: number): { biome: string; y: number } {
const { terrain } = generators_for(seed);
const column = terrain.column(x, z);
const y = Math.round(column.height);
const flat = pick_biome(column, y, false);
// most columns are the same either way, the neighbors are only worth sampling when they aren't
if (flat === pick_biome(column, y, true)) return { biome: flat, y };
const neighbors = [[x - 1, z], [x + 1, z], [x, z - 1], [x, z + 1]].map(([nx, nz]) => terrain.column(nx, nz));
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - column.height) >= STEEP);
return { biome: steep ? pick_biome(column, y, true) : flat, y };
}
// noise cells), caves cut out of it, then each column's biome, its surface blocks and fluids. what all of it is comes
// from the generator's noise settings, see OverworldTerrain and docs/modding/worldgen/terrain.md. trees and the rest
// are features, after it
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
import { get_biome } from "./biomes.ts";
import type { OverworldTerrain, TerrainColumn } from "./terrain.ts";
import {
compile_fluids,
compile_surface_rule,
surface_rule_reach,
type SurfaceBlocks,
type SurfaceContext,
} from "./surface_rules.ts";
// fills blocks (indexed y * CHUNK_AREA + z * CHUNK_SIZE + x) and each column's surface height and biome. block is
// a block's numeric id with its default states
export function generate_overworld(
blocks: Uint32Array,
heights: Int32Array,
biomes: string[],
chunk_x: number,
chunk_z: number,
seed: string,
ids: OverworldBlocks,
spill: (x: number, y: number, z: number, block: number) => void,
terrain: OverworldTerrain,
block: (id: string) => number,
) {
const { terrain, snow_line } = generators_for(seed);
const settings = terrain.settings;
const cell_width = settings.cell_width;
const cell_height = settings.terrain.cell_height;
const cave_cell_height = settings.caves.cell_height;
const corners = CHUNK_SIZE / cell_width + 1;
const terrain_levels = CHUNK_HEIGHT / cell_height + 1;
const cave_levels = CHUNK_HEIGHT / cave_cell_height + 1;
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
// density at the corners of every cell
const corner_columns: TerrainColumn[] = [];
for (let cz = 0; cz < CORNERS; cz++) {
for (let cx = 0; cx < CORNERS; cx++) {
corner_columns.push(terrain.column(x0 + cx * CELL_WIDTH, z0 + cz * CELL_WIDTH));
for (let cz = 0; cz < corners; cz++) {
for (let cx = 0; cx < corners; cx++) {
corner_columns.push(terrain.column(x0 + cx * cell_width, z0 + cz * cell_width));
}
}
const solid = new Float32Array(CORNERS * CORNERS * TERRAIN_LEVELS);
const caves = new Float32Array(CORNERS * CORNERS * CAVE_LEVELS);
const solid = new Float32Array(corners * corners * terrain_levels);
const caves = new Float32Array(corners * corners * cave_levels);
for (let i = 0; i < corner_columns.length; i++) {
const column = corner_columns[i];
const x = x0 + (i % CORNERS) * CELL_WIDTH;
const z = z0 + Math.floor(i / CORNERS) * CELL_WIDTH;
for (let level = 0; level < TERRAIN_LEVELS; level++) {
solid[i * TERRAIN_LEVELS + level] = terrain.density(column, x, level * CELL_HEIGHT, z);
const x = x0 + (i % corners) * cell_width;
const z = z0 + Math.floor(i / corners) * cell_width;
for (let level = 0; level < terrain_levels; level++) {
solid[i * terrain_levels + level] = terrain.density(column, x, level * cell_height, z);
}
// caves only matter below the ground, skip the sky above it
const cave_top = column.height + CAVE_CELL_HEIGHT;
for (let level = 0; level < CAVE_LEVELS; level++) {
const y = level * CAVE_CELL_HEIGHT;
caves[i * CAVE_LEVELS + level] = y > cave_top ? 1 : terrain.cave(column, x, y, z);
for (let level = 0; level < cave_levels; level++) {
caves[i * cave_levels + level] = terrain.cave(column, x, level * cave_cell_height, z);
}
}
// every column of the chunk plus a ring around it, for how steep the ground is
// every column of the chunk plus a ring around it, for how steep the ground is. the chunk's own with their
// climate, for their biome
const columns: TerrainColumn[] = [];
const ring = CHUNK_SIZE + 2;
for (let z = -1; z <= CHUNK_SIZE; z++) {
for (let x = -1; x <= CHUNK_SIZE; x++) {
columns.push(terrain.column(x0 + x, z0 + z));
const inside = x >= 0 && x < CHUNK_SIZE && z >= 0 && z < CHUNK_SIZE;
columns.push(terrain.column(x0 + x, z0 + z, inside));
}
}
const column_at = (x: number, z: number) => columns[(z + 1) * ring + x + 1];
// biomes are registered by mods (bworld's are in mods/bworld/worldgen/biomes), with their surfaces' ids looked up
// once per chunk
const found = new Map<string, { biome: Biome; surface: Surface }>();
const biome_info = (id: string) => {
let info = found.get(id);
if (!info) {
const found = new Map<string, SurfaceBlocks>();
const surface_of = (id: string) => {
let surface = found.get(id);
if (!surface) {
const biome = get_biome(id);
if (!biome) throw new Error(`biome ${id} isn't registered, is the bworld mod loaded?`);
const { surface } = biome;
info = {
biome,
surface: {
top: ids.block(surface.top),
filler: ids.block(surface.filler),
filler_depth: surface.filler_depth,
underwater_top: ids.block(surface.underwater_top),
underwater_filler: ids.block(surface.underwater_filler),
bare_cliffs: surface.bare_cliffs,
},
if (!biome) throw new Error(`biome ${id} isn't registered, is the mod that adds it loaded?`);
surface = {
top: block(biome.surface.top),
filler: block(biome.surface.filler),
filler_depth: biome.surface.filler_depth,
underwater_top: block(biome.surface.underwater_top),
underwater_filler: block(biome.surface.underwater_filler),
bare_cliffs: biome.surface.bare_cliffs,
};
found.set(id, info);
found.set(id, surface);
}
return info;
return surface;
};
const surface_rule = compile_surface_rule(settings.surface_rule, terrain, block);
const fluids = compile_fluids(settings.fluids, terrain, block);
// no fluid goes higher than this, and nothing below the rule's reach needs it
const fluid_top = Math.max(...settings.fluids.map((fluid) => fluid.below));
const reach = surface_rule_reach(settings.surface_rule);
const default_block = block(settings.default_block);
const sea_level = settings.sea_level;
const context: SurfaceContext = {
x: 0,
y: 0,
z: 0,
depth: 0,
underwater: false,
steep: false,
preliminary: 0,
biome: "",
surface: undefined!,
};
for (let z = 0; z < CHUNK_SIZE; z++) {
@@ -202,54 +112,15 @@ export function generate_overworld(
fill_column(x, z);
}
}
grow_trees();
function grow_trees() {
// logs replace any tree's leaves
const all_leaves = new Set(Object.values(ids.leaves));
const place = (x: number, y: number, z: number, block: "log" | "leaves", wood: Wood) => {
if (y < 0 || y >= CHUNK_HEIGHT) return;
const id = block === "log" ? ids.logs[wood] : ids.leaves[wood];
const lx = x - x0;
const lz = z - z0;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE) {
// the other chunk only takes it where it has air
spill(x, y, z, id);
return;
}
const i = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
const current = blocks[i];
if (current === 0 || (block === "log" && all_leaves.has(current))) {
blocks[i] = id;
}
};
for (const site of tree_sites(seed, chunk_x, chunk_z)) {
const column = (site.z - z0) * CHUNK_SIZE + (site.x - x0);
const { biome } = biome_info(biomes[column]);
const trees = biome.trees;
if (!trees || site.rng.next() >= trees.chance) continue;
// on soil with air above it, so never under water or on bare rock
const ground_y = heights[column];
const ground = blocks[ground_y * CHUNK_AREA + column];
const above = blocks[(ground_y + 1) * CHUNK_AREA + column];
if ((ground !== ids.grass && ground !== ids.dirt && ground !== ids.snow) || above !== 0) continue;
const kind = trees.kinds[Math.floor(site.rng.next() * trees.kinds.length)];
const wood = tree_wood(kind, biome);
grow_tree(kind, site.x, ground_y + 1, site.z, site.rng, (x, y, z, block) => place(x, y, z, block, wood));
}
}
function fill_column(x: number, z: number) {
const cell_x = Math.min(Math.floor(x / CELL_WIDTH), CORNERS - 2);
const cell_z = Math.min(Math.floor(z / CELL_WIDTH), CORNERS - 2);
const tx = (x - cell_x * CELL_WIDTH) / CELL_WIDTH;
const tz = (z - cell_z * CELL_WIDTH) / CELL_WIDTH;
const c00 = cell_z * CORNERS + cell_x;
const cell_x = Math.min(Math.floor(x / cell_width), corners - 2);
const cell_z = Math.min(Math.floor(z / cell_width), corners - 2);
const tx = (x - cell_x * cell_width) / cell_width;
const tz = (z - cell_z * cell_width) / cell_width;
const c00 = cell_z * corners + cell_x;
const c10 = c00 + 1;
const c01 = c00 + CORNERS;
const c01 = c00 + corners;
const c11 = c01 + 1;
const w00 = (1 - tx) * (1 - tz);
const w10 = tx * (1 - tz);
@@ -260,16 +131,17 @@ export function generate_overworld(
grid[c00 * levels + level] * w00 + grid[c10 * levels + level] * w10 +
grid[c01 * levels + level] * w01 + grid[c11 * levels + level] * w11;
// solid where both the terrain and the caves are above 0
const is_solid = new Uint8Array(CHUNK_HEIGHT);
for (let y = 0; y < CHUNK_HEIGHT; y++) {
const level = Math.min(Math.floor(y / CELL_HEIGHT), TERRAIN_LEVELS - 2);
const t = (y - level * CELL_HEIGHT) / CELL_HEIGHT;
let density = blend(solid, TERRAIN_LEVELS, level) * (1 - t) + blend(solid, TERRAIN_LEVELS, level + 1) * t;
const level = Math.min(Math.floor(y / cell_height), terrain_levels - 2);
const t = (y - level * cell_height) / cell_height;
let density = blend(solid, terrain_levels, level) * (1 - t) + blend(solid, terrain_levels, level + 1) * t;
if (density > 0) {
const cave_level = Math.min(Math.floor(y / CAVE_CELL_HEIGHT), CAVE_LEVELS - 2);
const ct = (y - cave_level * CAVE_CELL_HEIGHT) / CAVE_CELL_HEIGHT;
const cave = blend(caves, CAVE_LEVELS, cave_level) * (1 - ct) +
blend(caves, CAVE_LEVELS, cave_level + 1) * ct;
const cave_level = Math.min(Math.floor(y / cave_cell_height), cave_levels - 2);
const ct = (y - cave_level * cave_cell_height) / cave_cell_height;
const cave = blend(caves, cave_levels, cave_level) * (1 - ct) +
blend(caves, cave_levels, cave_level + 1) * ct;
density = Math.min(density, cave);
}
is_solid[y] = density > 0 ? 1 : 0;
@@ -281,48 +153,49 @@ export function generate_overworld(
const ground = column.height;
const neighbors = [column_at(x - 1, z), column_at(x + 1, z), column_at(x, z - 1), column_at(x, z + 1)];
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - ground) >= STEEP);
const biome = pick_biome(column, surface_y, steep);
const { surface } = biome_info(biome);
const snow_y = SNOW_LINE + snow_line.sample(x0 + x, z0 + z) * 10;
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - ground) >= settings.steep);
const biome = terrain.biome(column, surface_y, steep);
heights[z * CHUNK_SIZE + x] = surface_y;
biomes[z * CHUNK_SIZE + x] = biome;
context.x = x0 + x;
context.z = z0 + z;
context.steep = steep;
context.preliminary = ground;
context.biome = biome;
context.surface = surface_of(biome);
const index = (y: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
// the same sum as the rule's own condition, so it can't disagree with it
const lowest = ground + reach;
// solid blocks since the last air going down, 0 is a block with air on top
let depth = -1;
// nothing but air above so far: water fills it up to sea level
// nothing but air above so far
let open_sky = true;
// whether the ground's surface is under water, for its cover
let underwater = false;
for (let y = CHUNK_HEIGHT - 1; y >= 0; y--) {
context.y = y;
if (!is_solid[y]) {
depth = -1;
// and a river's tunnel under a mountain, and the caves it runs into
if ((open_sky || column.underground_river > 0) && y < SEA_LEVEL) {
blocks[index(y)] = ids.water;
if (y < fluid_top) {
const fluid = fluids(context, open_sky);
if (fluid !== undefined) blocks[index(y)] = fluid;
}
continue;
}
depth += 1;
if (open_sky) {
open_sky = false;
underwater = y < SEA_LEVEL - 1;
underwater = y < sea_level - 1;
}
// surface rules reach the ground and anything above it, not cave floors
let block = ids.stone;
if (y >= ground - SURFACE_REACH) {
if (depth === 0) {
if (underwater) block = surface.underwater_top;
else if (y >= snow_y) block = steep ? ids.stone : ids.snow;
else block = steep && surface.bare_cliffs ? ids.stone : surface.top;
} else if (depth <= surface.filler_depth) {
block = underwater ? surface.underwater_filler : surface.filler;
}
if (y < lowest) {
blocks[index(y)] = default_block;
continue;
}
blocks[index(y)] = block;
context.depth = depth;
context.underwater = underwater;
blocks[index(y)] = surface_rule(context) ?? default_block;
}
}
}
-72
View File
@@ -1,72 +0,0 @@
// minecraft's CubicSpline: a smooth curve through points, where a point's value can itself be a spline of another
// input. that nesting is how its terrain (and tectonic's) turns continentalness, erosion and ridges into heights:
// a spline over continentalness whose points are splines over erosion, whose points are splines over ridges.
// K names the inputs, see TerrainInputs
export type SplineValue<K extends string> = number | Spline<K>;
export interface SplinePoint<K extends string> {
at: number;
value: SplineValue<K>;
// the slope there, worked out from the neighbors when not given
slope?: number;
}
export class Spline<K extends string> {
readonly input: K;
#locations: number[];
#values: SplineValue<K>[];
#slopes: number[];
constructor(input: K, points: SplinePoint<K>[]) {
this.input = input;
this.#locations = points.map((point) => point.at);
this.#values = points.map((point) => point.value);
// catmull-rom slopes between the neighbors, flat at the ends and where values are splines
this.#slopes = points.map((point, i) => {
if (point.slope !== undefined) return point.slope;
const before = points[i - 1];
const after = points[i + 1];
if (!before || !after || typeof before.value !== "number" || typeof after.value !== "number") {
return 0;
}
return (after.value - before.value) / (after.at - before.at);
});
}
get(inputs: Readonly<Record<K, number>>): number {
const x = inputs[this.input];
const locations = this.#locations;
const last = locations.length - 1;
if (x <= locations[0]) {
return value_of(this.#values[0], inputs) + this.#slopes[0] * (x - locations[0]);
}
if (x >= locations[last]) {
return value_of(this.#values[last], inputs) + this.#slopes[last] * (x - locations[last]);
}
let i = 0;
while (locations[i + 1] < x) i++;
const x0 = locations[i];
const x1 = locations[i + 1];
const width = x1 - x0;
const t = (x - x0) / width;
const y0 = value_of(this.#values[i], inputs);
const y1 = value_of(this.#values[i + 1], inputs);
// hermite interpolation, written the way minecraft does it
const a = this.#slopes[i] * width - (y1 - y0);
const b = -this.#slopes[i + 1] * width + (y1 - y0);
return y0 + (y1 - y0) * t + t * (1 - t) * (a + (b - a) * t);
}
}
function value_of<K extends string>(value: SplineValue<K>, inputs: Readonly<Record<K, number>>) {
return typeof value === "number" ? value : value.get(inputs);
}
// a spline through points given as [at, value, slope], like minecraft's json with its derivatives. slope is 0 when
// left out, like minecraft's
export function spline<K extends string>(input: K, points: [number, SplineValue<K>, number?][]) {
return new Spline(input, points.map(([at, value, slope]) => ({ at, value, slope: slope ?? 0 })));
}
+134
View File
@@ -0,0 +1,134 @@
// what solid blocks and empty space become, from the noise settings' surface_rule and fluids (see data.ts), compiled
// for each chunk with its block ids. like minecraft's surface rules: a rule gives a block or nothing, and a sequence
// gives its first rule's block
import { type FluidJson, range_test, type SurfaceConditionJson, type SurfaceRuleJson } from "./data.ts";
import type { OverworldTerrain } from "./terrain.ts";
// a biome's surface as numeric ids
export interface SurfaceBlocks {
top: number;
filler: number;
filler_depth: number;
underwater_top: number;
underwater_filler: number;
bare_cliffs: boolean;
}
// the block being decided, one context reused for the whole chunk
export interface SurfaceContext {
x: number;
y: number;
z: number;
// solid blocks above it before air, 0 for one with air on top
depth: number;
// the column's ground, the first solid block from the top, is below sea level - 1
underwater: boolean;
steep: boolean;
// the column's height before 3d noise
preliminary: number;
biome: string;
surface: SurfaceBlocks;
}
type Rule = (context: SurfaceContext) => number | undefined;
type Condition = (context: SurfaceContext) => boolean;
export function compile_surface_rule(
json: SurfaceRuleJson,
terrain: OverworldTerrain,
block: (id: string) => number,
): Rule {
switch (json.type) {
case "sequence": {
const rules = json.sequence.map((rule) => compile_surface_rule(rule, terrain, block));
return (context) => {
for (const rule of rules) {
const result = rule(context);
if (result !== undefined) return result;
}
return undefined;
};
}
case "condition": {
const condition = compile_condition(json.if_true, terrain);
const then = compile_surface_rule(json.then_run, terrain, block);
return (context) => condition(context) ? then(context) : undefined;
}
case "block": {
const id = block(json.result_state.Name);
return () => id;
}
case "biome_surface": {
const part = json.part;
return (context) => context.surface[part];
}
}
}
function compile_condition(json: SurfaceConditionJson, terrain: OverworldTerrain): Condition {
switch (json.type) {
case "stone_depth": {
const offset = json.offset;
return (context) => context.depth <= offset;
}
case "filler_depth":
return (context) => context.depth <= context.surface.filler_depth;
case "above_preliminary_surface": {
const offset = json.offset ?? 0;
return (context) => context.y >= context.preliminary + offset;
}
case "surface_underwater":
return (context) => context.underwater;
case "steep":
return (context) => context.steep;
case "bare_cliffs":
return (context) => context.surface.bare_cliffs;
case "y_at_least": {
const at = terrain.compiler.compile(json.function);
return (context) => context.y >= at(context.x, context.y, context.z);
}
case "biome": {
const biomes = new Set(json.biome_is);
return (context) => biomes.has(context.biome);
}
case "not": {
const inner = compile_condition(json.invert, terrain);
return (context) => !inner(context);
}
}
}
// how far above the preliminary surface the rule starts giving blocks, when its outermost condition says, so the
// blocks below it can skip it. -Infinity when it doesn't say
export function surface_rule_reach(json: SurfaceRuleJson): number {
if (json.type === "condition" && json.if_true.type === "above_preliminary_surface") {
return json.if_true.offset ?? 0;
}
return -Infinity;
}
// the fluid empty space at the context's y becomes, if any. open_sky is whether there's only air above it
export function compile_fluids(
json: FluidJson[],
terrain: OverworldTerrain,
block: (id: string) => number,
): (context: SurfaceContext, open_sky: boolean) => number | undefined {
const fluids = json.map((fluid) => {
const id = block(fluid.block);
const below = fluid.below;
if (fluid.where === "open_sky") {
return (context: SurfaceContext, open_sky: boolean) => open_sky && context.y < below ? id : undefined;
}
const where = terrain.compiler.compile(fluid.where.function);
const test = range_test(fluid.where);
return (context: SurfaceContext) =>
context.y < below && test(where(context.x, context.y, context.z)) ? id : undefined;
});
return (context, open_sky) => {
for (const fluid of fluids) {
const id = fluid(context, open_sky);
if (id !== undefined) return id;
}
return undefined;
};
}
+99 -622
View File
@@ -1,644 +1,121 @@
// the shape of the overworld, built the way minecraft 1.18+ does it and shaped after tectonic
// (https://github.com/Apollounknowndev/tectonic, MIT): large noises for continents, erosion and ridges feed nested
// splines that give each column a target height, how jagged its peaks are and how rough its ground is. a 3d density
// around that height decides what's solid, and caves are cut out of it. tectonic's look comes from its splines,
// ported here in its units (1 is 128 blocks): oceans that wind between big continents with islands out at sea,
// mountain ranges where erosion is low, rivers along the valleys between ridges that go underground through
// mountains, and on the flatter land four kinds of region picked by a slow noise and the climate: valleys and
// plateaus (and badlands ridges where it's hot), tiered mesas, rolling hills and jungle pillars, and wetlands and dunes
import { CHUNK_HEIGHT, SEA_LEVEL } from "$/common/constants.ts";
import { clamp, OctaveNoise2D, OctaveNoise3D, Quantiles, smoothstep } from "./noise.ts";
import { Spline, spline } from "./spline.ts";
// the shape of the world and which biome each column gets, from a generator's data (see generator.ts): its density
// functions compiled for one seed. generate_overworld calls density and cave through here, so engine access mods can
// hook them. bworld's overworld is shaped after tectonic (https://github.com/Apollounknowndev/tectonic, MIT), its
// splines are in mods/bworld/worldgen/density_function/overworld
import { type Density, DensityCompiler } from "./density.ts";
import { type DensityJson, type NoiseSettingsJson, range_test, type RangeJson } from "./data.ts";
import type { Generator } from "./generator.ts";
// measured with tools/noise_quantiles.ts
const QUANTILES_6 = new Quantiles([
-0.833,
-0.386,
-0.311,
-0.256,
-0.21,
-0.17,
-0.133,
-0.098,
-0.065,
-0.032,
0,
0.032,
0.065,
0.098,
0.133,
0.17,
0.21,
0.256,
0.311,
0.386,
0.833,
]);
const QUANTILES_4 = new Quantiles([
-0.917,
-0.48,
-0.393,
-0.328,
-0.273,
-0.222,
-0.174,
-0.13,
-0.086,
-0.042,
0,
0.042,
0.086,
0.13,
0.174,
0.222,
0.273,
0.328,
0.393,
0.48,
0.917,
]);
const QUANTILES_3 = new Quantiles([
-0.91,
-0.468,
-0.377,
-0.308,
-0.249,
-0.199,
-0.154,
-0.113,
-0.073,
-0.036,
0,
0.036,
0.073,
0.113,
0.154,
0.199,
0.249,
0.308,
0.377,
0.468,
0.91,
]);
const QUANTILES_2 = new Quantiles([
-0.962,
-0.536,
-0.439,
-0.368,
-0.306,
-0.248,
-0.195,
-0.146,
-0.096,
-0.046,
0,
0.046,
0.096,
0.146,
0.195,
0.248,
0.306,
0.368,
0.439,
0.536,
0.962,
]);
const QUANTILES_TEMPERATURE = new Quantiles([
-0.973,
-0.6,
-0.509,
-0.44,
-0.379,
-0.319,
-0.254,
-0.19,
-0.127,
-0.063,
0,
0.063,
0.127,
0.19,
0.254,
0.319,
0.379,
0.44,
0.509,
0.6,
0.973,
]);
// blocks of height per unit of density, how soft the ground's surface is
const THICKNESS = 20;
// solid ground always ends here, and nothing reaches past the top of the world
const TOP_SLIDE_START = CHUNK_HEIGHT - 24;
const TOP_SLIDE_END = CHUNK_HEIGHT - 4;
const MIN_CAVE_Y = 5;
// the climate at a column. continentalness, erosion and ridges are scaled to about tectonic's ranges, temperature and
// humidity are spread evenly from -1 to 1
export interface Climate {
// tectonic's raw continents: deep ocean below -0.45, ocean to -0.2, the coast to 0, then further and further
// inland. islands raise it out at sea
continentalness: number;
// low is mountains, high is flat land. both ends are flat, see erosion_folded
erosion: number;
// 0 along valleys, where rivers run, and further from 0 towards the ridges between them
ridges: number;
temperature: number;
humidity: number;
}
// everything 2d about a column that the density needs, worked out once per column
// what the terrain worked out about a column
export interface TerrainColumn {
climate: Climate;
x: number;
z: number;
// where the ground's surface is before 3d noise, in blocks
height: number;
// how much 3d noise moves the ground, in units of density. high where tectonic's terrain is rugged
roughness: number;
// 0 to 1, how much its peaks are sharp ridges
jaggedness: number;
// 0 to 1, how close it is to the middle of a river that goes under a mountain here, see cave
underground_river: number;
// its climate values in the order the noise settings name them, when column was asked for them
climate?: number[];
}
// what tectonic's splines read: the climate, folded, and the small noises its regions are made of
type Input =
| "continents"
| "erosion"
| "erosion_folded"
| "ridges"
| "ridges_folded"
| "region"
| "regions"
| "temperature"
| "vegetation"
| "lower_tier"
| "upper_tier"
| "badlands"
| "hills"
| "wetland"
| "pillar";
type TerrainInputs = Record<Input, number>;
type S = Spline<Input>;
const s = (input: Input, points: [number, number | S, number?][]): S => spline(input, points);
// tectonic's raw continents from how far the continents noise is from 0: 0 is the middle of an ocean
const CONTINENT_SHAPE = s("continents", [[0, 0], [0.4, 0.575, 1], [0.48, 0.68, 1]]);
// tectonic's temperature and vegetation indexes, 1 to 5, from its climate parameters
const TEMPERATURE_INDEX = s("temperature", [
[-0.48, 1],
[-0.42, 2],
[-0.18, 2],
[-0.12, 3],
[0.17, 3],
[0.23, 4],
[0.52, 4],
[0.58, 5],
]);
const VEGETATION_INDEX = s("vegetation", [
[-0.38, 1],
[-0.32, 2],
[-0.13, 2],
[-0.07, 3],
[0.07, 3],
[0.13, 4],
[0.27, 4],
[0.33, 5],
]);
// from here on, tectonic's splines: heights in its units, relative to sea level
// a river: down to below sea level where the ridges noise is 0, back up to the land around it
const RIVER = s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01]]);
const GENTLE_RIVER = s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.1]]);
const lower_tier = (low: number, high: number) => s("lower_tier", [[0, low], [0.15, high]]);
const badlands = (low: number, high: number) => s("badlands", [[0.45, 0.05], [0.6, low, 1.5], [0.63, high, 0.2]]);
// club: valleys between plateaus, with badlands ridges where it's hot
const PLATEAUS = s("ridges", [
[-0.5, 0.25, -0.1],
[-0.4, lower_tier(0.1, 0.22)],
[-0.3, 0.05, -0.8],
[-0.1, 0.01],
[-0.03, -0.06, -0.5],
[0.03, -0.06, 0.5],
[0.1, 0.01],
[0.3, 0.05, 0.8],
[0.4, lower_tier(0.135, 0.28)],
[0.5, 0.35, 0.1],
]);
const SINGLE_VALLEY = s("ridges", [
[-0.5, 0.25, -0.1],
[-0.4, lower_tier(0.1, 0.22)],
[-0.3, 0.05, -0.8],
[-0.1, 0.01],
[-0.03, -0.06, -0.5],
[0.03, -0.06, 0.5],
[0.075, 0.01],
[0.14, 0.05, 0.8],
[0.2, lower_tier(0.135, 0.28)],
[0.3, 0.35],
[0.45, 0.03],
]);
const DOUBLE_VALLEY = s("ridges", [
[-0.45, 0.03],
[-0.3, 0.25],
[-0.2, lower_tier(0.1, 0.22)],
[-0.125, 0.05, -0.8],
[-0.075, 0.01],
[-0.03, -0.06, -0.5],
[0.03, -0.06, 0.5],
[0.075, 0.01],
[0.125, 0.05, 0.8],
[0.2, lower_tier(0.135, 0.28)],
[0.3, 0.35],
[0.45, 0.03],
]);
const CLUB = s("temperature", [
[1, PLATEAUS],
[2, s("vegetation", [[1, SINGLE_VALLEY], [2, PLATEAUS]])],
[3, s("vegetation", [[2, SINGLE_VALLEY], [3, PLATEAUS], [4, PLATEAUS], [5, DOUBLE_VALLEY]])],
[4, PLATEAUS],
[5, s("ridges_folded", [[0, -0.15, 2.5], [0.1, 0.04], [0.2, badlands(0.15, 0.185)], [0.3, badlands(0.185, 0.5)]])],
]);
// heart: rolling hills where it's mild, and in jungles ridges cut by narrow valleys
const HEART = s("temperature", [
[
3,
s("vegetation", [
[2, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.1], [0.2, s("hills", [[0, 0.01, 0.225]])]])],
[3, GENTLE_RIVER],
]),
],
[
4,
s("vegetation", [
[3, GENTLE_RIVER],
[
4,
s("ridges", [
[-0.75, 0.05],
[-0.175, 0.015],
[-0.125, 0.01],
[-0.04, -0.06, -0.7],
[0.04, -0.06, 0.7],
[0.125, 0.01],
]),
],
[5, s("ridges_folded", [[0.04, -0.06, 0.7], [0.125, 0.01], [0.175, 0.015], [0.75, 0.05], [0.8, 0.6]])],
]),
],
[5, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.15]])],
]);
// spade: land in tiers, and tall mesas where it's hot
const SPADE = s("temperature", [
[
4,
s("ridges_folded", [
[0.03, -0.06, 0.5],
[0.1, 0.01],
[0.3, 0.05, 0.8],
[0.4, lower_tier(0.1, 0.22)],
[0.55, 0.25, 1],
[0.6, s("upper_tier", [[0, 0.25], [0.15, 0.45]])],
[0.64, 0.5],
]),
],
[
5,
s("ridges_folded", [
[0.025, -0.075, 0.03],
[0.1, 0.05],
[0.175, 0.1, 1.5],
[0.2, 0.225, 0.2],
[0.4, 0.6, 7],
[0.4, 0.6, 0.1],
[0.8, 0.7],
[0.85, 0.4],
[1, 0.4],
[1.05, 0.04],
]),
],
]);
// diamond: flat land with wetlands, and deserts (their dunes are added on top, see DUNES)
const DIAMOND = s("temperature", [
[
4,
s("vegetation", [
[2, GENTLE_RIVER],
[
3,
s("ridges_folded", [
[0.03, -0.06, 0.5],
[0.1, 0.01],
[0.15, s("wetland", [[-0.45, -0.03, 0.03], [-0.3, 0.005], [0.3, 0.005], [0.45, -0.03, -0.03]])],
]),
],
]),
],
[5, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.15]])],
]);
// which region: by erosion's sign, then the slow region noise
const REGIONS = s("erosion", [
[-0.02, s("region", [[-0.1, CLUB], [0.1, HEART]])],
[0.04, s("region", [[-0.1, SPADE], [0.1, DIAMOND]])],
]);
// the regions, after REGIONS and its height multiplier
const REGION = s("regions", [[0, 0, 1]]);
const WEAK_REGION = s("regions", [[0, 0, 0.5]]);
const HILLS = s("ridges_folded", [[0, -0.1, 1], [0.175, 0.075, 0.3], [0.3, 0.25]]);
const LOW_RIDGES = s("ridges_folded", [[0.38, -0.03], [0.45, 0.03]]);
const inland = (top: number, high: number, low: number, ridge: number, regions_end: number, hills: number) =>
s("erosion_folded", [
[0, top],
[0.175, high],
[0.3, low],
[0.375, s("ridges_folded", [[0, -0.1], [0.1, 0.125, 5], [0.1667, 0.225], [0.3, ridge]])],
[0.425, WEAK_REGION],
[0.5, REGION],
[regions_end, REGION],
[hills, HILLS],
[0.95, HILLS],
[1.075, LOW_RIDGES],
]);
// shallower than tectonic's, the world goes 64 blocks below sea level instead of 128
const DEEP_OCEAN = -0.33;
const OCEAN = -0.17;
// target height above sea level: the ocean floor, then coasts, then further inland mountains where erosion is low
// and the regions where it's high
const OFFSET = s("continents", [
[-0.45, DEEP_OCEAN],
[-0.35, OCEAN],
[-0.195, -0.14],
[
-0.155,
s("erosion_folded", [
[0.2, s("ridges_folded", [[0, -0.1], [0.15, 0.15, 3], [0.25, 0.22]]), -0.17],
[0.3, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0]])],
]),
],
[
0,
s("erosion_folded", [
[0, 0.65],
[0.15, 0.425, -1.5],
[0.3, 0.33],
[0.375, s("ridges_folded", [[0, -0.1], [0.15, 0.15], [0.3, 0.25]])],
[0.4, RIVER],
[0.95, RIVER],
[1.075, LOW_RIDGES],
]),
],
[0.1, inland(0.95, 0.55, 0.36, 0.3, 0.825, 0.875)],
[0.8, inland(1.1, 0.65, 0.38, 0.33, 0.8, 0.9)],
]);
// how jagged the peaks are, 0 to 0.2: only the tallest mountains, deep inland
const JAGGEDNESS = s("continents", [[0, 0], [0.175, s("erosion_folded", [[0, 0.2], [0.125, 0]])]]);
// tectonic's factor: how steeply density rises below the surface. low is rugged ground full of overhangs, on the
// ridges of hilly land
const rugged = (ridges: S) => s("erosion_folded", [[0.825, 5.6], [0.875, ridges], [0.975, ridges], [1.025, 5.6]]);
const FACTOR = s("continents", [
[-0.19, 5.6],
[-0.15, rugged(s("ridges", [[0, 5.6], [0.1, 0.6]]))],
[0.03, rugged(s("ridges", [[0, 5.6], [0.1, 0.6]]))],
[0.06, rugged(s("ridges_folded", [[0.25, 5.6], [0.4, 1.3]]))],
]);
// how tall dunes get, up to 6, in hot flat land of the diamond region
const DUNE_HEIGHT = s("temperature", [
[4, 0],
[5, s("region", [[0, 0], [0.1, s("ridges_folded", [[0, 0], [0.25, 6]])]])],
]);
const DUNES = s("continents", [
[0, 0],
[0.05, s("erosion_folded", [[0.4, 0], [0.45, DUNE_HEIGHT], [0.8, DUNE_HEIGHT], [0.85, 0]])],
]);
// jungle pillars: tall narrow columns in heart's jungles, on the ridges between its valleys
const pillar = (mid: number, high: number) => s("pillar", [[0.05, 0], [0.2, mid, -0.2], [0.5, high, 0.05]]);
const JUNGLE_PILLARS = s("region", [
[0, 0],
[
0.1,
s("temperature", [
[3, 0],
[
4,
s("vegetation", [
[3, 0],
[4, s("ridges", [[-0.75, pillar(0.4, 0.7)], [-0.175, pillar(0.25, 0.5)], [-0.125, 0]])],
[
5,
s("ridges_folded", [[0.125, 0], [0.175, pillar(0.25, 0.5)], [0.75, pillar(0.45, 0.75)], [
0.8,
0,
]]),
],
]),
],
[5, 0],
]),
],
]);
const PILLARS = s("continents", [
[0, 0],
[0.1, s("erosion", [[-0.875, 0], [-0.825, JUNGLE_PILLARS], [-0.425, JUNGLE_PILLARS], [-0.375, 0]])],
]);
// blocks per unit of tectonic's height. without its vertical scale of 1.125, which is for minecraft's taller world
const BLOCKS_PER_UNIT = 128;
// the 3d noise's strength at tectonic's usual factor
const ROUGHNESS = 0.12;
// rivers that reach mountains go under them in a tunnel this tall around sea level, this wide in ridges
const RIVER_TUNNEL_BOTTOM = SEA_LEVEL - 5;
const RIVER_TUNNEL_TOP = SEA_LEVEL + 4;
const RIVER_TUNNEL_WIDTH = 0.035;
// only where the ground is this far above the river, otherwise it's an open valley
const RIVER_TUNNEL_COVER = 12;
interface CompiledRule {
biome: string;
// climate values by their index in the noise settings' climate, the surface's y, steep
holds(climate: number[], surface: number, steep: boolean): boolean;
}
export class OverworldTerrain {
#continents: OctaveNoise2D;
#island_a: OctaveNoise2D;
#island_b: OctaveNoise2D;
#erosion: OctaveNoise2D;
#ridges: OctaveNoise2D;
#temperature: OctaveNoise2D;
#humidity: OctaveNoise2D;
#warp_x: OctaveNoise2D;
#warp_z: OctaveNoise2D;
#region: OctaveNoise2D;
#height_multiplier: OctaveNoise2D;
#lower_tier: OctaveNoise2D;
#upper_tier: OctaveNoise2D;
#badlands: OctaveNoise2D;
#hills: OctaveNoise2D;
#wetland: OctaveNoise2D;
#pillar: OctaveNoise2D;
#dune: OctaveNoise2D;
#dune_warp: OctaveNoise2D;
#mountain_ridges: OctaveNoise2D;
#ground: OctaveNoise3D;
#cheese: OctaveNoise3D;
#spaghetti_a: OctaveNoise3D;
#spaghetti_b: OctaveNoise3D;
#entrances: OctaveNoise2D;
readonly seed: string;
readonly settings: NoiseSettingsJson;
readonly compiler: DensityCompiler;
#preliminary: Density;
#terrain: Density;
#caves: Density;
#climate: Density[];
#rules: CompiledRule[];
// the amplitudes match the quantile tables above, so each noise can be spread evenly
constructor(seed: string) {
this.#continents = new OctaveNoise2D(seed, "continents", 2560, [1, 1, 2, 2, 1, 1]);
this.#island_a = new OctaveNoise2D(seed, "island_a", 320, [1, 1]);
this.#island_b = new OctaveNoise2D(seed, "island_b", 320, [1, 1]);
this.#erosion = new OctaveNoise2D(seed, "erosion", 1280, [1, 1, 0, 1, 1]);
this.#ridges = new OctaveNoise2D(seed, "ridges", 640, [1, 2, 1]);
this.#temperature = new OctaveNoise2D(seed, "temperature", 3072, [1.5, 0, 1]);
this.#humidity = new OctaveNoise2D(seed, "humidity", 1536, [1, 1]);
this.#warp_x = new OctaveNoise2D(seed, "warp_x", 200, [1, 1]);
this.#warp_z = new OctaveNoise2D(seed, "warp_z", 200, [1, 1]);
this.#region = new OctaveNoise2D(seed, "region", 2048, [1, 1, 2, 2, 1, 1]);
this.#height_multiplier = new OctaveNoise2D(seed, "height_multiplier", 1024, [1, 2, 1]);
this.#lower_tier = new OctaveNoise2D(seed, "lower_tier", 512, [1, 2, 1]);
this.#upper_tier = new OctaveNoise2D(seed, "upper_tier", 512, [1, 2, 1]);
this.#badlands = new OctaveNoise2D(seed, "badlands", 512, [1, 2, 1]);
this.#hills = new OctaveNoise2D(seed, "hills", 320, [1, 1]);
this.#wetland = new OctaveNoise2D(seed, "wetland", 96, [1, 1]);
this.#pillar = new OctaveNoise2D(seed, "pillar", 32, [1, 1]);
this.#dune = new OctaveNoise2D(seed, "dune", 96, [1, 1]);
this.#dune_warp = new OctaveNoise2D(seed, "dune_warp", 400, [1, 1]);
this.#mountain_ridges = new OctaveNoise2D(seed, "mountain_ridges", 256, [1, 1]);
this.#ground = new OctaveNoise3D(seed, "ground", 64, [1, 1, 0.5], 1.2);
this.#cheese = new OctaveNoise3D(seed, "cheese", 80, [1, 0.5], 0.6);
this.#spaghetti_a = new OctaveNoise3D(seed, "spaghetti_a", 64, [1], 0.8);
this.#spaghetti_b = new OctaveNoise3D(seed, "spaghetti_b", 64, [1], 0.8);
this.#entrances = new OctaveNoise2D(seed, "entrances", 90, [1, 1]);
}
climate(x: number, z: number): Climate {
// a small warp, so coasts and biome edges aren't the noise's smooth blobs
const wx = x + this.#warp_x.sample(x, z) * 24;
const wz = z + this.#warp_z.sample(x, z) * 24;
return {
continentalness: this.#continentalness(wx, wz),
erosion: QUANTILES_4.even(this.#erosion.sample(wx, wz)) * 1.05,
ridges: QUANTILES_3.even(this.#ridges.sample(wx, wz)) * 0.7,
temperature: QUANTILES_TEMPERATURE.even(this.#temperature.sample(wx, wz)),
humidity: QUANTILES_2.even(this.#humidity.sample(wx, wz)),
constructor(seed: string, generator: Generator) {
this.seed = seed;
this.settings = generator.settings;
this.compiler = new DensityCompiler(seed, generator.sources);
const compile = (json: DensityJson, what: string) => {
try {
return this.compiler.compile(json);
} catch (e) {
throw new Error(`noise settings ${this.settings.id}, ${what}: ${(e as Error).message}`);
}
};
this.#preliminary = compile(this.settings.preliminary_surface, "preliminary_surface");
this.#terrain = compile(this.settings.terrain.density, "terrain");
this.#caves = compile(this.settings.caves.density, "caves");
const names = Object.keys(this.settings.climate);
this.#climate = names.map((name) => compile(this.settings.climate[name], `climate.${name}`));
this.#rules = generator.rules.map((rule) => compile_rule(rule.biome, rule.when ?? {}, names));
}
// like tectonic: land is where the continents noise is far from 0, so oceans wind along where it crosses 0. out
// in the deep ocean, islands come up where either of two island noises is high
#continentalness(x: number, z: number) {
const far = Math.abs(QUANTILES_6.even(this.#continents.sample(x, z))) * 0.85;
const continents = -0.8 + CONTINENT_SHAPE.get({ continents: far } as TerrainInputs);
if (continents >= -0.5) return continents;
// scaled so about 3 in 100 of the deep ocean is island, both noises are spread evenly unlike tectonic's
const island = Math.max(
QUANTILES_2.even(this.#island_a.sample(x, z)),
QUANTILES_2.even(this.#island_b.sample(x, z)),
) * 0.76;
const deep = smoothstep(-0.5, -0.8, continents) * 0.7;
return Math.max(continents, (island + 0.05) * deep - 0.7);
// with_climate works the climate out too, which is cheap right after the height since they share their inputs
column(x: number, z: number, with_climate = false): TerrainColumn {
const height = this.#preliminary(x, 0, z);
return with_climate ? { x, z, height, climate: this.climate(x, z) } : { x, z, height };
}
column(x: number, z: number): TerrainColumn {
const climate = this.climate(x, z);
const { continentalness, erosion, ridges } = climate;
const lower = QUANTILES_3.even(this.#lower_tier.sample(x, z));
const upper = QUANTILES_3.even(this.#upper_tier.sample(x, z));
const inputs: TerrainInputs = {
continents: continentalness,
erosion,
erosion_folded: Math.abs(erosion),
ridges,
ridges_folded: Math.abs(ridges),
region: QUANTILES_6.even(this.#region.sample(x, z)) * 0.5 + 0.1,
regions: 0,
temperature: TEMPERATURE_INDEX.get({ temperature: climate.temperature } as TerrainInputs),
vegetation: VEGETATION_INDEX.get({ vegetation: climate.humidity } as TerrainInputs),
lower_tier: Math.abs(lower) * 0.3,
upper_tier: Math.abs(upper) * 0.3,
badlands: Math.abs(QUANTILES_3.even(this.#badlands.sample(x, z))) * 0.7,
hills: Math.abs(QUANTILES_2.even(this.#hills.sample(x, z))),
wetland: QUANTILES_2.even(this.#wetland.sample(x, z)) * 0.6,
pillar: 1.7 * (QUANTILES_2.even(this.#pillar.sample(x, z)) * 0.7 - 0.35),
};
const multiplier = clamp(1.2 + 0.4 * QUANTILES_3.even(this.#height_multiplier.sample(x, z)), 0.8, 1.6);
inputs.regions = multiplier * REGIONS.get(inputs);
const offset = OFFSET.get(inputs) + PILLARS.get(inputs);
let height = offset * BLOCKS_PER_UNIT;
// jagged peaks: sharp ridgelines along the tallest mountains
const jaggedness = clamp(JAGGEDNESS.get(inputs) / 0.2, 0, 1);
if (jaggedness > 0) {
const ridge = 1 - Math.abs(this.#mountain_ridges.sample(x, z));
height += jaggedness * 36 * ridge * ridge;
}
// dunes: long ridges of sand, swept one way
const dunes = DUNES.get(inputs) / 6;
if (dunes > 0) {
const sweep = this.#dune_warp.sample(x, z) * 40;
const crest = 1 - Math.abs(this.#dune.sample(x + sweep, z * 0.35));
height += dunes * 7 * crest * crest;
}
const roughness = ROUGHNESS * 5.6 / FACTOR.get(inputs);
const valley = 1 - inputs.ridges_folded / RIVER_TUNNEL_WIDTH;
const covered = height > RIVER_TUNNEL_TOP - SEA_LEVEL + RIVER_TUNNEL_COVER;
const underground_river = valley > 0 && covered && continentalness > -0.17 ? valley : 0;
return { climate, height: SEA_LEVEL + height, roughness, jaggedness, underground_river };
// the column's climate values, in the order the noise settings name them
climate(x: number, z: number): number[] {
return this.#climate.map((value) => value(x, 0, z));
}
// positive is solid, before caves
density(column: TerrainColumn, x: number, y: number, z: number) {
let density = (column.height - y) / THICKNESS + column.roughness * this.#ground.sample(x, y, z);
if (y > TOP_SLIDE_START) {
density -= smoothstep(TOP_SLIDE_START, TOP_SLIDE_END, y) * 4;
}
if (y < 1) {
density = Math.max(density, 1);
}
return density;
density(_column: TerrainColumn, x: number, y: number, z: number): number {
return this.#terrain(x, y, z);
}
// negative where a cave is. caves stay under the ground's skin except at entrances, and never break
// the floor of oceans and rivers. rivers under mountains are tunnels, see generate_overworld for their water
cave(column: TerrainColumn, x: number, y: number, z: number) {
if (y < MIN_CAVE_Y) {
return 1;
}
let river = 1;
if (column.underground_river > 0 && y >= RIVER_TUNNEL_BOTTOM - 2 && y <= RIVER_TUNNEL_TOP + 2) {
const middle = (RIVER_TUNNEL_BOTTOM + RIVER_TUNNEL_TOP) / 2;
const half = (RIVER_TUNNEL_TOP - RIVER_TUNNEL_BOTTOM) / 2;
river = (Math.max(1 - column.underground_river, Math.abs(y - middle) / half) - 1) * 4;
}
const depth = column.height - y;
if (column.height < SEA_LEVEL + 3 && depth < 14) {
return river;
}
if (depth < 7 && this.#entrances.sample(x, z) < 0.5) {
return river;
}
// negative where a cave is
cave(_column: TerrainColumn, x: number, y: number, z: number): number {
return this.#caves(x, y, z);
}
// cheese caves: big open caverns
const cheese = (0.52 - this.#cheese.sample(x, y, z)) * 4;
// spaghetti caves: long winding tunnels where two noises are both near zero
const a = Math.abs(this.#spaghetti_a.sample(x, y, z));
const b = Math.abs(this.#spaghetti_b.sample(x, y, z));
const spaghetti = (Math.max(a, b) - 0.07) * 8;
return Math.min(cheese, spaghetti, river);
// the first of the biome source's rules that holds for the column, with its ground at surface_y
biome(column: TerrainColumn, surface_y: number, steep: boolean): string {
const climate = column.climate ?? this.climate(column.x, column.z);
for (const rule of this.#rules) {
if (rule.holds(climate, surface_y, steep)) return rule.biome;
}
throw new Error(`no rule of biome source ${this.settings.biome_source} holds at ${column.x}, ${column.z}`);
}
// a column's biome without generating its chunk, from its height before 3d noise, so it can be a little off near
// coasts and cliffs. for searching far away, like /locatebiome
estimate_biome(x: number, z: number): { biome: string; y: number } {
const column = this.column(x, z);
const y = Math.round(column.height);
const flat = this.biome(column, y, false);
// most columns are the same either way, the neighbors are only worth sampling when they aren't
if (flat === this.biome(column, y, true)) return { biome: flat, y };
const neighbors = [[x - 1, z], [x + 1, z], [x, z - 1], [x, z + 1]].map(([nx, nz]) => this.column(nx, nz));
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - column.height) >= this.settings.steep);
return { biome: steep ? this.biome(column, y, true) : flat, y };
}
}
function compile_rule(biome: string, when: Record<string, RangeJson | boolean>, names: string[]): CompiledRule {
const tests: CompiledRule["holds"][] = [];
for (const [name, condition] of Object.entries(when)) {
if (name === "steep") {
tests.push((_climate, _surface, steep) => steep === condition);
} else if (name === "surface") {
const test = range_test(condition as RangeJson);
tests.push((_climate, surface) => test(surface));
} else {
const index = names.indexOf(name);
const test = range_test(condition as RangeJson);
tests.push((climate) => test(climate[index]));
}
}
return {
biome,
holds(climate, surface_y, steep) {
for (let i = 0; i < tests.length; i++) {
if (!tests[i](climate, surface_y, steep)) return false;
}
return true;
},
};
}
-197
View File
@@ -1,197 +0,0 @@
// trees, part of the terrain pass. where they grow can't depend on which chunk generates first, so it only
// depends on the seed: every CELL x CELL cell has one candidate spot and a random priority, and a candidate becomes a
// tree only if no other candidate within MIN_DISTANCE has a higher priority (then its biome may still say no). that
// spreads trees out like poisson disk sampling: never closer than MIN_DISTANCE, but without lining up in a grid.
// a tree is placed by the chunk its trunk is in, leaves that reach into the next chunk go through the spills like any
// other block there
import { Alea } from "@paulaboks/rng";
import { CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
const CELL = 4;
// trunks are at least this far apart
const MIN_DISTANCE = 4;
// how many cells out a candidate can be and still be within MIN_DISTANCE
const REACH = Math.ceil(MIN_DISTANCE / CELL);
// the widest a canopy layer gets
const MAX_CANOPY = 3;
export const TREE_KINDS = ["oak", "big_oak", "birch", "spruce", "jungle", "acacia", "cherry"] as const;
export type TreeKind = typeof TREE_KINDS[number];
export const WOODS = ["oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "cherry"] as const;
export type Wood = typeof WOODS[number];
export interface TreeSite {
x: number;
z: number;
// seeded from the cell, what's left of it picks the tree
rng: Alea;
}
interface Candidate extends TreeSite {
priority: number;
}
// every cell's candidate, from the seed and the cell alone
function candidate(seed: string, cell_x: number, cell_z: number): Candidate {
const rng = new Alea(`${seed}_tree_${cell_x}_${cell_z}`);
const x = cell_x * CELL + Math.floor(rng.next() * CELL);
const z = cell_z * CELL + Math.floor(rng.next() * CELL);
return { x, z, priority: rng.next(), rng };
}
// the spots in the chunk where a tree may grow, before biome and ground are checked
export function tree_sites(seed: string, chunk_x: number, chunk_z: number): TreeSite[] {
const cells = CHUNK_SIZE / CELL;
const first_x = chunk_x * cells - REACH;
const first_z = chunk_z * cells - REACH;
const size = cells + 2 * REACH;
const candidates: Candidate[] = [];
for (let cz = 0; cz < size; cz++) {
for (let cx = 0; cx < size; cx++) {
candidates.push(candidate(seed, first_x + cx, first_z + cz));
}
}
const sites: TreeSite[] = [];
for (let cz = REACH; cz < REACH + cells; cz++) {
for (let cx = REACH; cx < REACH + cells; cx++) {
const site = candidates[cz * size + cx];
let wins = true;
for (let dz = -REACH; dz <= REACH && wins; dz++) {
for (let dx = -REACH; dx <= REACH; dx++) {
const other = candidates[(cz + dz) * size + cx + dx];
if (other === site) continue;
const distance_sq = (other.x - site.x) ** 2 + (other.z - site.z) ** 2;
if (distance_sq < MIN_DISTANCE * MIN_DISTANCE && other.priority > site.priority) {
wins = false;
break;
}
}
}
if (wins) sites.push(site);
}
}
return sites;
}
// log replaces anything that isn't ground, leaves only fill air
export type PlaceBlock = (x: number, y: number, z: number, block: "log" | "leaves") => void;
// grows a tree with its trunk's bottom at x, y, z. returns false when it wouldn't fit under the top of the world
export function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Alea, place: PlaceBlock) {
const random = (min: number, max: number) => min + Math.floor(rng.next() * (max - min + 1));
const trunk = (height: number) => {
for (let i = 0; i < height; i++) place(x, y + i, z, "log");
};
// a square layer of leaves, its corners left out at random like minecraft's
const layer = (ly: number, radius: number, corners: boolean) => {
for (let dx = -radius; dx <= radius; dx++) {
for (let dz = -radius; dz <= radius; dz++) {
const corner = Math.abs(dx) === radius && Math.abs(dz) === radius;
if (corner && radius > 0 && (!corners || rng.next() < 0.5)) continue;
place(x + dx, ly, z + dz, "leaves");
}
}
};
let top: number;
switch (kind) {
case "oak": {
const height = random(4, 6);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
layer(y + height - 2, 2, true);
layer(y + height - 1, 2, true);
layer(y + height, 1, true);
layer(y + height + 1, 1, false);
break;
}
case "birch": {
// oak's canopy on a taller, straight trunk
const height = random(5, 7);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
layer(y + height - 2, 2, true);
layer(y + height - 1, 2, true);
layer(y + height, 1, true);
layer(y + height + 1, 1, false);
break;
}
case "cherry": {
// a short trunk under a wide, rounded canopy
const height = random(4, 6);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
layer(y + height - 2, 2, false);
layer(y + height - 1, MAX_CANOPY, false);
layer(y + height, MAX_CANOPY, false);
layer(y + height + 1, 2, false);
break;
}
case "big_oak": {
const height = random(6, 8);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
layer(y + height - 3, 2, true);
layer(y + height - 2, 3, false);
layer(y + height - 1, 3, true);
layer(y + height, 2, true);
layer(y + height + 1, 1, false);
break;
}
case "spruce": {
const height = random(7, 10);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
// a cone of layers getting wider going down, every other one narrower, like minecraft's spruce
place(x, y + height + 1, z, "leaves");
layer(y + height, 1, false);
let radius = 1;
for (let ly = y + height - 1; ly >= y + 2; ly--) {
radius = radius >= 2 + Math.floor((y + height - ly) / 4) ? 1 : radius + 1;
layer(ly, Math.min(radius, MAX_CANOPY), false);
}
break;
}
case "jungle": {
const height = random(9, 13);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
layer(y + height - 2, 3, false);
layer(y + height - 1, 3, true);
layer(y + height, 2, true);
layer(y + height + 1, 1, false);
break;
}
case "acacia": {
// a short trunk that leans one way at the top, under a flat, wide canopy
const height = random(4, 5);
top = y + height + 2;
if (top >= CHUNK_HEIGHT - 1) return false;
trunk(height);
const lean_x = random(-1, 1);
const lean_z = lean_x === 0 ? (rng.next() < 0.5 ? -1 : 1) : 0;
const cx = x + lean_x;
const cz = z + lean_z;
place(cx, y + height, cz, "log");
for (let dx = -MAX_CANOPY; dx <= MAX_CANOPY; dx++) {
for (let dz = -MAX_CANOPY; dz <= MAX_CANOPY; dz++) {
if (Math.abs(dx) + Math.abs(dz) <= 4 && !(Math.abs(dx) === 3 && Math.abs(dz) === 3)) {
place(cx + dx, y + height + 1, cz + dz, "leaves");
}
if (Math.abs(dx) + Math.abs(dz) <= 2) {
place(cx + dx, y + height + 2, cz + dz, "leaves");
}
}
}
break;
}
}
return true;
}
+116 -16
View File
@@ -1,31 +1,101 @@
// imports mods' worldgen scripts and collects what they register. used by client chunk workers and the game server
import type { WorldgenContext } from "$/common/mod_api/worldgen.ts";
// imports mods' worldgen scripts and collects what they and mods' data add to generation: the generator, ores, and
// features, code and data, in the order they run. used by the game server
import type { FeatureBiome, FeatureChunk, FeatureStep, WorldgenContext } from "$/common/mod_api/worldgen.ts";
import type { OreJson } from "$/common/mod_data.ts";
import type { WorldgenSetup } from "./generation.ts";
import type { SetupFeature, WorldgenSetup } from "./generation.ts";
import { EverythingRegistry } from "./everything_registry.ts";
import { ModLoadError } from "./mod_loader.ts";
import { loading_mod } from "./hooks.ts";
import { compile_generator } from "./worldgen/generator.ts";
import type { Biome } from "./worldgen/biomes.ts";
import {
compile_feature,
DEFAULT_STEP,
FEATURE_STEPS,
type FeatureJson,
type FeatureType,
type PlacementModifier,
} from "./worldgen/features.ts";
export async function load_worldgen(
scripts: { mod: string; url: string; engine_access?: boolean }[],
ores: OreJson[],
): Promise<WorldgenSetup> {
const setup: WorldgenSetup = { ores, features: [] };
export interface WorldgenSources {
// every mod's id, in load order
mods: string[];
scripts: { mod: string; url: string; engine_access?: boolean }[];
ores: OreJson[][];
// the noise settings the world uses. it and data features come from mods' data, which is already registered
generator: string;
}
for (const { mod, url, engine_access } of scripts) {
// a feature before it's put in order
interface Pending {
feature: SetupFeature;
mod: string;
step: FeatureStep;
// data features go before a mod's code features, sorted by id. code features keep the order they were registered
data: boolean;
order: number;
}
export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenSetup> {
const setup: WorldgenSetup = {
generator: compile_generator(sources.generator),
ores: sources.ores,
features: [],
placeable: new Map(),
};
const pending: Pending[] = [];
const types = new Map<string, FeatureType>();
const modifiers = new Map<string, PlacementModifier>();
const data_features = (EverythingRegistry.get_registry<FeatureJson>("features") ?? []).filter((f) => f);
const biomes = (EverythingRegistry.get_registry<Biome>("biomes") ?? []).filter((b) => b).map((
biome,
): FeatureBiome => ({
id: biome.id,
...(biome.trees
? { trees: { ...biome.trees, kinds: [...biome.trees.kinds], wood: { ...biome.trees.wood } } }
: {}),
}));
for (const { mod, url, engine_access } of sources.scripts) {
const own = (id: string, what: string) => {
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`);
}
};
const ctx: WorldgenContext = {
register_feature(id, generate) {
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `feature ${id} must be in the namespace "${mod}"`);
register_feature(id, generate, options = {}) {
own(id, "feature");
if (pending.some((p) => p.feature.id === id) || data_features.some((f) => f.id === id)) {
throw new ModLoadError(mod, `feature ${id} is registered twice, as code or data`);
}
if (setup.features.some((f) => f.id === id)) {
throw new ModLoadError(mod, `feature ${id} is registered twice`);
const step = options.step ?? DEFAULT_STEP;
if (!FEATURE_STEPS.includes(step)) {
throw new ModLoadError(mod, `feature ${id}: step must be one of ${FEATURE_STEPS.join(", ")}`);
}
setup.features.push({ id, generate });
const listed = options.biomes === undefined ? undefined : [options.biomes].flat();
pending.push({
feature: { id, generate, ...(listed ? { biomes: new Set(listed) } : {}) },
mod,
step,
data: false,
order: pending.length,
});
},
register_feature_type(id, place) {
own(id, "feature type");
if (types.has(id)) throw new ModLoadError(mod, `feature type ${id} is registered twice`);
types.set(id, place as FeatureType);
},
register_placement_modifier(id, modify) {
own(id, "placement modifier");
if (modifiers.has(id)) throw new ModLoadError(mod, `placement modifier ${id} is registered twice`);
modifiers.set(id, modify as PlacementModifier);
},
biomes: () => biomes,
register_terrain(id) {
throw new ModLoadError(
mod,
`can't register terrain ${id}: the base terrain is still built into the engine (see docs/modding_plan.md)`,
`can't register terrain ${id}: terrain is data now, see docs/modding/worldgen/terrain.md`,
);
},
};
@@ -39,5 +109,35 @@ export async function load_worldgen(
});
}
// data features last, so they can use the types and modifiers every script registered
for (const json of data_features) {
const mod = json.id.split(":")[0];
let compiled;
try {
compiled = compile_feature(json, types, modifiers);
} catch (e) {
throw new ModLoadError(mod, (e as Error).message);
}
const generate = compiled.generate;
setup.placeable.set(json.id, compiled.place);
pending.push({
feature: { id: json.id, generate: (chunk: FeatureChunk) => generate(chunk) },
mod,
step: json.step ?? DEFAULT_STEP,
data: true,
order: 0,
});
}
// by step, then mod, then a mod's data features by id, then its code features as they were registered
const mod_order = new Map(sources.mods.map((mod, i) => [mod, i]));
const order_of = (mod: string) => mod_order.get(mod) ?? sources.mods.length;
pending.sort((a, b) =>
FEATURE_STEPS.indexOf(a.step) - FEATURE_STEPS.indexOf(b.step) ||
order_of(a.mod) - order_of(b.mod) ||
Number(b.data) - Number(a.data) ||
(a.data ? a.feature.id.localeCompare(b.feature.id) : a.order - b.order)
);
setup.features = pending.map((p) => p.feature);
return setup;
}