Files
bworld/mods/bworld/scripts/trees.ts
T
2026-11-04 21:51:26 -03:00

254 lines
9.5 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the base game's trees, a feature that's code. biomes say which kinds grow and how often (their json's "trees"), this
// says what the kinds are. it isn't data features: each kind would need placers drawing random numbers in exactly
// the order grow_tree does, for the world to stay the same, to say what this already says. it runs after ores, which
// only replace stone, while trees only fill air or replace leaves, so that order changes nothing. 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 only fill air there
import type { FeatureBiome, FeatureChunk, WorldgenContext } from "cubi/worldgen";
const CHUNK_SIZE = 16;
const CHUNK_HEIGHT = 256;
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];
type Random = { next(): number };
export interface TreeSite {
x: number;
z: number;
// seeded from the cell, what's left of it picks the tree
rng: Random;
}
interface Candidate extends TreeSite {
priority: number;
}
// every cell's candidate, from the seed and the cell alone
function candidate(chunk: FeatureChunk, cell_x: number, cell_z: number): Candidate {
const rng = chunk.random(`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
function tree_sites(chunk: FeatureChunk): 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(chunk, 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 leaves, everything else only fills air
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
function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random, 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":
case "birch": {
// birch is oak's canopy on a taller, straight trunk
const height = kind === "birch" ? random(5, 7) : 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 "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;
}
// trees grow on these, with air above
const SOIL = new Set(["bworld:grass_block", "bworld:dirt", "bworld:snow_block"]);
const LEAVES = new Set(WOODS.map((wood) => `bworld:${wood}_leaves`));
export function register_trees(gen: WorldgenContext) {
const trees = new Map<string, NonNullable<FeatureBiome["trees"]>>();
for (const biome of gen.biomes()) {
if (!biome.trees) continue;
for (const kind of biome.trees.kinds) {
if (!TREE_KINDS.includes(kind as TreeKind)) {
throw new Error(`biome ${biome.id}: trees.kinds: ${kind} isn't one of ${TREE_KINDS.join(", ")}`);
}
}
for (const [kind, wood] of Object.entries(biome.trees.wood)) {
if (!TREE_KINDS.includes(kind as TreeKind)) {
throw new Error(`biome ${biome.id}: trees.wood: ${kind} isn't a kind of tree`);
}
if (!WOODS.includes(wood as Wood)) {
throw new Error(`biome ${biome.id}: trees.wood.${kind} must be one of ${WOODS.join(", ")}`);
}
}
trees.set(biome.id, biome.trees);
}
gen.register_feature("bworld:trees", (chunk) => {
const x0 = chunk.x * CHUNK_SIZE;
const z0 = chunk.z * CHUNK_SIZE;
const place = (x: number, y: number, z: number, block: "log" | "leaves", wood: string) => {
if (y < 0 || y >= CHUNK_HEIGHT) return;
const id = `bworld:${wood}_${block}`;
if (x < x0 || x >= x0 + CHUNK_SIZE || z < z0 || z >= z0 + CHUNK_SIZE) {
// the other chunk only takes it where it has air
chunk.set_block(x, y, z, id);
return;
}
const current = chunk.get_block(x, y, z);
if (current === "cubi:air" || (block === "log" && LEAVES.has(current!))) chunk.set_block(x, y, z, id);
};
for (const site of tree_sites(chunk)) {
const here = trees.get(chunk.biome_at(site.x, site.z));
if (!here || site.rng.next() >= here.chance) continue;
// on soil with air above it, so never under water or on bare rock
const ground_y = chunk.height_at(site.x, site.z);
const ground = chunk.get_block(site.x, ground_y, site.z);
const above = chunk.get_block(site.x, ground_y + 1, site.z);
if (!SOIL.has(ground!) || above !== "cubi:air") continue;
const kind = here.kinds[Math.floor(site.rng.next() * here.kinds.length)] as TreeKind;
// big oaks grow oak, every other kind its own wood, unless the biome says
const wood = here.wood[kind] ?? (kind === "big_oak" ? "oak" : kind);
grow_tree(kind, site.x, ground_y + 1, site.z, site.rng, (x, y, z, block) => place(x, y, z, block, wood));
}
}, { step: "vegetal_decoration" });
}