Compare commits

...
9 Commits
Author SHA1 Message Date
paula e7fe663746 Terrafirmacraft rock textures 2026-11-07 21:03:16 -03:00
paula c639d1231b Render regions, disabled by default 2026-11-07 19:35:42 -03:00
paula 206cd38f26 Occlusion culling 2026-11-07 17:59:28 -03:00
paula 22191d260c 3D biomes 2026-11-07 12:13:43 -03:00
paula b726ce9695 Meshing and lighting per section 2026-11-07 11:41:21 -03:00
paula 71cbf901a5 Client side chunk sections 2026-11-07 10:39:16 -03:00
paula 8e14e9842a Wooooorld files 2026-11-06 23:41:32 -03:00
paula 1fa47c027d World sections 2026-11-06 23:13:34 -03:00
paula 818ce22dd6 World shape for dimension 2026-11-06 22:49:43 -03:00
305 changed files with 4239 additions and 1450 deletions
+11 -6
View File
@@ -6,7 +6,9 @@
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { ChunkColumn } from "@/common/section.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { DEFAULT_MODEL } from "@/common/block_models.ts";
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "@/common/worldgen/noise.ts";
@@ -19,6 +21,9 @@ const SEED = "benchmark";
// can be meshed, see ClientLevel.can_mesh
export const LEVEL_RADIUS = 13;
export const SEA_LEVEL = 62;
// 0 to 256 with sky light whatever the world's dimension is, so runs compare. y in its chunks counts from 0
export const LEVEL_SHAPE = DEFAULT_SHAPE;
const TOP = LEVEL_SHAPE.max_y;
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
export const ZONES = {
@@ -143,12 +148,12 @@ export class BenchTerrain {
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
height = zone.height + (height - zone.height) * t;
}
return Math.min(CHUNK_HEIGHT - 32, Math.round(height));
return Math.min(TOP - 32, Math.round(height));
}
chunk(chunk_x: number, chunk_z: number): { blocks: Uint32Array; biomes: string[] } {
chunk(chunk_x: number, chunk_z: number): ChunkColumn {
const b = this.#blocks;
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
@@ -156,7 +161,7 @@ export class BenchTerrain {
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
const lx = x - x0;
const lz = z - z0;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= CHUNK_HEIGHT) return;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= TOP) return;
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
if (!only_air || blocks[index] === AIR) blocks[index] = value;
};
@@ -189,7 +194,7 @@ export class BenchTerrain {
}
this.#trees(chunk_x, chunk_z, set);
this.#features(set);
return { blocks, biomes: new Array(CHUNK_AREA).fill(b.biome) };
return ChunkColumn.from_flat(chunk_x, chunk_z, LEVEL_SHAPE, blocks, new Array(CHUNK_AREA).fill(b.biome));
}
#in_zone(x: number, z: number, margin: number) {
+5 -4
View File
@@ -40,6 +40,7 @@ import {
type BenchBlocks,
BenchTerrain,
LEVEL_RADIUS,
LEVEL_SHAPE,
SEA_LEVEL,
UPDATE_WALL,
ZONES,
@@ -145,7 +146,7 @@ export class RenderBenchmark {
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
);
this.#level = new ClientLevel([], LEVEL_RADIUS);
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
this.#level.time = TIMES_OF_DAY.noon;
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
this.#system = system_info(this.#level.workers.size);
@@ -242,6 +243,7 @@ export class RenderBenchmark {
system: this.#system,
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
render_regions: render_debug.render_regions,
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
first_mesh,
remesh,
@@ -260,8 +262,7 @@ export class RenderBenchmark {
const start = performance.now();
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
const [x, z] = chunks[built++];
const { blocks, biomes } = terrain.chunk(x, z);
this.#level.set_chunk(x, z, blocks, biomes);
this.#level.set_chunk(terrain.chunk(x, z));
}
this.#build_ms += performance.now() - start;
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
@@ -334,7 +335,7 @@ export class RenderBenchmark {
return {
draw_calls,
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0),
chunks_in_view: level_renderer.visible_chunks,
sections_in_view: level_renderer.visible_sections,
entities_in_view: level_renderer.drawn_entities,
};
}
+5 -3
View File
@@ -5,7 +5,7 @@
// tools/compare_benchmarks.ts reads to put runs side by side
// changes when the scenes or the level change, since runs of different versions don't compare
export const BENCHMARK_VERSION = 1;
export const BENCHMARK_VERSION = 2;
// how fast and how smooth frames were, from the time between them. the lows are the fps of the frame that 99% (and
// 99.9%) of the others were faster than
@@ -36,7 +36,7 @@ export interface SceneResult {
// what the first paced frame drew, which runs of the same version should about agree on
draw_calls: number;
quads: number;
chunks_in_view: number;
sections_in_view: number;
entities_in_view: number;
}
@@ -74,6 +74,8 @@ export interface BenchmarkReport {
// "id version"
mods: string[];
resolution: string;
// the f3 window's switch, see ClientLevel.use_render_regions
render_regions?: boolean;
level: { chunks: number; build_ms: number };
first_mesh: MeshingResult;
remesh: MeshingResult;
@@ -120,7 +122,7 @@ export function format_report(report: BenchmarkReport): string {
"",
`${system.browser} on ${system.os}, ${system.gpu}`,
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
(system.timestamps ? "" : ", no gpu timestamps"),
(system.timestamps ? "" : ", no gpu timestamps") + (report.render_regions ? ", render regions" : ""),
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
"",
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
+1 -1
View File
@@ -77,7 +77,7 @@ export class Client {
this.connection = connection;
this.#on_disconnect = on_disconnect;
this.level = new ClientLevel(connection.server_blocks, this.options.render_distance);
this.level = new ClientLevel(connection.server_blocks, connection.shape, this.options.render_distance);
this.level.time = connection.time;
this.#sent_view_distance = this.options.render_distance;
+13 -6
View File
@@ -98,8 +98,9 @@ export class DebugOverlay {
const level = client.level;
const level_renderer = client.game_renderer.level_renderer;
const { meshed, bytes } = this.#count_chunks(client);
text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`);
text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} meshing`);
text(`chunks: ${level.chunks.size} loaded`);
text(` sections: ${meshed} with meshes, ${level_renderer.visible_sections} in view`);
text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} requests meshing`);
text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`);
text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`);
separator();
@@ -142,7 +143,7 @@ export class DebugOverlay {
);
}
// meshed chunks and what their meshes take on the gpu, once a second
// sections with meshes and what their meshes take on the gpu, once a second
#count_chunks(client: Client) {
const now = performance.now();
if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats;
@@ -150,9 +151,15 @@ export class DebugOverlay {
let meshed = 0;
let bytes = 0;
for (const chunk of client.level.chunks.values()) {
const meshes = Object.values(chunk.meshes);
if (meshes.length > 0) meshed += 1;
for (const mesh of meshes) bytes += mesh.vertex_buffer.size + (mesh.index_buffer?.size ?? 0);
for (const section of chunk.sections) {
const meshes = Object.values(section.meshes);
if (meshes.length > 0) meshed += 1;
for (const mesh of meshes) bytes += (mesh.vertex_buffer?.size ?? 0) + (mesh.index_buffer?.size ?? 0);
}
}
// solid and cutout quads are in their regions' buffers
for (const region of client.level.regions.values()) {
for (const { buffer } of Object.values(region.layers)) bytes += buffer?.size ?? 0;
}
this.#chunk_stats = { meshed, bytes };
return this.#chunk_stats;
+2 -2
View File
@@ -169,8 +169,8 @@ export class Hud {
#render_info(client: Client) {
const { day, hour, minute } = clock(client.level.time);
const { x, z } = client.player;
const biome = client.level.biome_at(Math.floor(x), Math.floor(z));
const { x, y, z } = client.player;
const biome = client.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z));
const lines = [
`Day ${day}`,
`${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`,
+317 -236
View File
@@ -13,20 +13,22 @@ import { AIR_ID } from "@/common/protocol.ts";
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "@/common/worldgen/biome_colors.ts";
import {
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
is_fluid_block,
RENDER_LAYERS,
light_tables,
RenderLayer,
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, section_index, type SectionBiomes, type SectionData } from "@/common/section.ts";
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts";
import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts";
import { create_index_buffer, create_vertex_buffer, destroy_buffer, render_debug, Texture } from "../renderer/mod.ts";
import { crosses_planes } from "../workers/translucent_sort.ts";
import { ALL_VISIBLE } from "../workers/visibility.ts";
import { region_key, REGION_LAYERS, type RegionLayer, RenderRegion } from "./render_region.ts";
import { Camera } from "../camera.ts";
import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "@/common/block_models.ts";
@@ -41,36 +43,56 @@ export interface Block {
z: number;
}
export { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE };
export { CHUNK_AREA, CHUNK_SIZE };
export interface Chunk {
x: number;
z: number;
blocks: Uint32Array;
dirty: boolean;
// its blocks and each column's biome, as the server sent them
column: ChunkColumn;
// each column's lowest y that sees the sky, see column_heights in common/section.ts. kept up to date with its blocks
sky: Int16Array;
// one for each of its sections, from the bottom of the world up
sections: RenderSection[];
// each of its biome palette's grass, foliage and water colors, three numbers a biome
biome_colors: Uint32Array;
}
// a chunk's section as it's drawn, like sodium's RenderSection. each is meshed and lit on its own
export interface RenderSection {
chunk: Chunk;
// in its chunk, from the bottom of the world up
index: number;
// bumped on every mesh request so late results from older requests get ignored
mesh_version: number;
meshes: Partial<Record<RenderLayer, ChunkMesh>>;
// the lowest and highest y of its meshes, for frustum culling
// the lowest and highest y of its quads and visuals, for frustum culling. Infinity and -Infinity when it has none
min_y: number;
max_y: number;
// only for translucent meshes that have to be sorted again as the camera moves
translucent_sort?: TranslucentSort;
// each column's biome id, x then z
biomes: string[];
// each column's biome grass color, x then z, then each column's foliage color, then water color
biome_colors: Uint32Array;
// from its last mesh, see get_light. undefined until it's been meshed
light?: Uint8Array;
light?: SectionLight;
// from its last mesh, which faces see which, see client/workers/visibility.ts. all of them until it's been meshed
visibility: number;
// the last search for what the camera can see that reached it, and the faces it was reached through, see
// client/rendering/occlusion.ts
search: number;
incoming: number;
// where its solid and cutout quads are, see render_region.ts
region: RenderRegion;
}
export interface ChunkMesh {
vertex_buffer: GPUBuffer;
quad_count: number;
// the translucent layer's quads sorted back to front, the others are drawn in order
index_buffer?: GPUBuffer;
// solid and cutout quads by the way they face, see FACE_GROUPS in chunk_messages.ts
groups?: FaceGroup[];
// the section's own buffer, the translucent layer's quads sorted back to front by index_buffer. solid and cutout
// quads are in its region's buffer instead with the render_regions switch on, see render_region.ts, and slot is
// the section's place in the order the region's sections are in it
vertex_buffer?: GPUBuffer;
index_buffer?: GPUBuffer;
slot?: number;
}
interface TranslucentSort {
@@ -106,23 +128,32 @@ export interface BlockData {
data: Record<string, unknown>;
}
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const;
// light spreads diagonally too, so meshing and lighting need all 8
const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
// light spreads diagonally too, so meshing and lighting need all 8 neighbors
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
// how far a change in light reaches, and one more for the faces at its edge, whose corners are lit from beyond them
const LIGHT_REACH = 16;
// how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client
// which ones to forget, this only catches the ones it didn't
const STORAGE_MARGIN = 3;
// block light 0 and sky light 15, packed like Chunk.light
export const FULL_SKY_LIGHT = 15;
// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the
// chunks are what the server sent, see common/chunk_streaming.ts
export class ClientLevel {
image: Texture = AssetManager.instance.get("cubi:textures");
chunks = new Map<number, Chunk>();
// the chunks request_meshes and update_translucent_sorting look at, so they don't go through every chunk each frame
#dirty = new Set<Chunk>();
#sorted = new Set<Chunk>();
// the sections request_meshes and update_translucent_sorting look at, so they don't go through every one each
// frame. dirty ones by chunk, since a chunk's go in one request
#dirty = new Map<Chunk, Set<RenderSection>>();
#sorted = new Set<RenderSection>();
// the sections with quads or visuals, the only ones there are to draw
drawn = new Set<RenderSection>();
// by region_key, and the ones whose sections' meshes changed since update_regions
regions = new Map<number, RenderRegion>();
#changed_regions = new Set<RenderRegion>();
// whether solid and cutout quads go in their regions' buffers, see use_render_regions
#render_regions = render_debug.render_regions;
// bumped whenever a chunk comes or goes or a section is meshed, which can change what the camera sees
sections_version = 0;
second_timer = 0;
tick_timer = 0;
// world time in ticks, counted here between the server's updates. see common/time.ts
@@ -131,6 +162,8 @@ export class ClientLevel {
ticks = 0;
// in chunks, what the server was asked to send
view_distance: number;
// the dimension's height and sky light
readonly shape: WorldShape;
// the chunk the server says the player is in
center: { x: number; z: number } | undefined;
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
@@ -138,6 +171,7 @@ export class ClientLevel {
workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
#light = light_tables(this.#blocks);
// the server's numeric block ids to this client's
#to_local: Uint32Array;
@@ -151,8 +185,9 @@ export class ClientLevel {
break_progress = new Map<string, { x: number; y: number; z: number; stage: number }>();
// server_blocks is the server's block id for each of its numeric ids
constructor(server_blocks: string[], view_distance: number) {
constructor(server_blocks: string[], shape: WorldShape, view_distance: number) {
this.view_distance = view_distance;
this.shape = shape;
this.#to_local = new Uint32Array(server_blocks.length);
server_blocks.forEach((id, nid) => {
if (!id) return;
@@ -173,6 +208,7 @@ export class ClientLevel {
textures_info: AssetManager.instance.get("cubi:textures_info"),
image: { width: this.image.width, height: this.image.height },
visuals: [...block_visuals].map(([nid, visual]) => [nid, visual.replaces_model]),
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
});
}
@@ -195,55 +231,60 @@ export class ClientLevel {
// a level_chunk from the server: the whole chunk, replacing it if it was already here
load_chunk(data: Uint8Array) {
const { x, z, blocks, biomes } = decode_level_chunk(
const { x, z, sections, biomes } = decode_level_chunk(
data,
(value) => this.#to_local[value & ID_MASK] | (value & ~ID_MASK),
);
if (!this.#in_storage_range(x, z)) {
return;
}
this.set_chunk(x, z, blocks, biomes);
// throws when it isn't as tall as the dimension
this.set_chunk(new ChunkColumn(x, z, this.shape, sections, biomes));
}
// a whole chunk, replacing it if it was already here. blocks are this client's numeric ids with their state bits
set_chunk(x: number, z: number, blocks: Uint32Array, biomes: string[]) {
const biome_colors = new Uint32Array(CHUNK_AREA * 3);
biomes.forEach((biome, column) => {
biome_colors[column] = grass_color(biome);
biome_colors[CHUNK_AREA + column] = foliage_color(biome);
biome_colors[CHUNK_AREA * 2 + column] = water_color(biome);
});
// a whole chunk, replacing it if it was already here. its blocks are this client's numeric ids with their state bits
set_chunk(column: ChunkColumn) {
const { x, z } = column;
const biome_colors = Uint32Array.from(
column.biomes.palette.flatMap((biome) => [grass_color(biome), foliage_color(biome), water_color(biome)]),
);
const sky = column_heights(column, this.#light.opacity).slice(CHUNK_AREA);
const chunk = this.get_chunk(x, z);
if (chunk) {
// its old mesh stays up until the new one is ready
chunk.blocks = blocks;
chunk.biomes = biomes;
// its old meshes stay up until the new ones are ready
chunk.column = column;
chunk.sky = sky;
chunk.biome_colors = biome_colors;
this.#mark_dirty(chunk);
} else {
const chunk: Chunk = {
x,
z,
blocks,
biomes,
biome_colors,
dirty: true,
mesh_version: 0,
meshes: {},
min_y: 0,
max_y: 0,
};
this.chunks.set(chunk_key(x, z), chunk);
this.#dirty.add(chunk);
}
// their border faces and light depend on this one
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const neighbor = this.get_chunk(x + dx, z + dz);
if (neighbor) {
this.#mark_dirty(neighbor);
const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] };
for (let index = 0; index < column.sections.length; index++) {
const key = region_key(x, index, z);
let region = this.regions.get(key);
if (!region) {
region = new RenderRegion();
this.regions.set(key, region);
}
region.section_count += 1;
chunk.sections.push({
chunk,
index,
mesh_version: 0,
meshes: {},
min_y: Infinity,
max_y: -Infinity,
visibility: ALL_VISIBLE,
search: 0,
incoming: 0,
region,
});
}
this.chunks.set(chunk_key(x, z), chunk);
this.sections_version += 1;
}
// and its neighbors, whose border faces and light depend on it
this.#mark_dirty_around(x, z, this.shape.min_y, this.shape.max_y);
}
// the server moved the player's view, chunks far outside it go even if the server didn't say
@@ -266,11 +307,15 @@ export class ClientLevel {
dispose() {
this.workers.terminate();
for (const chunk of this.chunks.values()) {
this.delete_chunk_mesh(chunk);
for (const section of chunk.sections) this.#delete_mesh(section);
}
this.visuals.dispose();
for (const region of this.regions.values()) region.dispose();
this.regions.clear();
this.#changed_regions.clear();
this.chunks.clear();
this.#dirty.clear();
this.drawn.clear();
}
get_chunk(x: number, z: number) {
@@ -286,34 +331,30 @@ export class ClientLevel {
return;
}
if (!this.shape.contains(block.y)) {
return;
}
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
this.#retain(block.x, block.y, block.z);
const lx = block.x - block_chunk_x * CHUNK_SIZE;
const lz = block.z - block_chunk_z * CHUNK_SIZE;
const ly = block.y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
const old_nid = chunk.blocks[index] & ID_MASK;
chunk.blocks[index] = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
this.#mark_dirty(chunk);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
const old_nid = chunk.column.get(block.x, block.y, block.z) & ID_MASK;
const value = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
chunk.column.set(block.x, block.y, block.z, value);
this.#block_changed(chunk, block.x, block.y, block.z, old_nid, nid);
}
// block light << 4 | sky light there, as of its chunk's last mesh. full sky light above the world and where it isn't
// known yet, so entities don't go dark while their chunk loads
// block light << 4 | sky light there, as of its section's last mesh. the shape's open light (full sky light, unless
// the dimension has none) above the world and where it isn't known yet, so entities don't go dark while their
// chunk loads
get_light(x: number, y: number, z: number): number {
const block_y = Math.floor(y);
if (block_y >= CHUNK_HEIGHT) return FULL_SKY_LIGHT;
if (block_y < 0) return 0;
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const light = this.get_chunk(chunk_x, chunk_z)?.light;
if (!light) return FULL_SKY_LIGHT;
const lx = Math.floor(x) - chunk_x * CHUNK_SIZE;
const lz = Math.floor(z) - chunk_z * CHUNK_SIZE;
return light[block_y * CHUNK_AREA + lz * CHUNK_SIZE + lx];
if (block_y >= this.shape.max_y) return this.shape.open_light;
if (block_y < this.shape.min_y) return 0;
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
const light = chunk?.sections[(block_y - this.shape.min_y) >> 4].light;
if (light === undefined) return this.shape.open_light;
return typeof light === "number" ? light : light[section_index(Math.floor(x), block_y, Math.floor(z))];
}
// the id with its state bits, VOID outside loaded chunks
@@ -324,8 +365,7 @@ export class ClientLevel {
if (!chunk) {
return VOID;
}
return chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)] ??
AIR;
return chunk.column.get(x, y, z);
}
get_block(x: number, y: number, z: number) {
@@ -337,14 +377,7 @@ export class ClientLevel {
if (!chunk) {
return VOID;
}
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
const ly = y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
return chunk.blocks[index] & ID_MASK;
return chunk.column.get(x, y, z) & ID_MASK;
}
// whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world
@@ -363,22 +396,17 @@ export class ClientLevel {
return block ? collision_shape_at(block, value) : true;
}
// the column's biome, undefined in unloaded chunks
biome_at(x: number, z: number): string | undefined {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
return this.get_chunk(chunk_x, chunk_z)
?.biomes[(z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
// the biome at a block, undefined in unloaded chunks
biome_at(x: number, y: number, z: number): string | undefined {
return this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE))?.column.biome_at(x, y, z);
}
// the biome's water color at a column as 0xRRGGBB, see "tint". plains' in unloaded chunks
water_color(x: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.get_chunk(chunk_x, chunk_z);
// the biome's water color at a block as 0xRRGGBB, see "tint". plains' in unloaded chunks
water_color(x: number, y: number, z: number) {
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!chunk) return DEFAULT_WATER_COLOR;
return chunk
.biome_colors[CHUNK_AREA * 2 + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
const biome = chunk.column.biomes.palette.indexOf(chunk.column.biome_at(x, y, z));
return chunk.biome_colors[biome * 3 + 2];
}
// the fluid there and how high it is, for fluids pushing things along. unloaded chunks have none
@@ -400,86 +428,68 @@ export class ClientLevel {
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
const block_chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
if (!chunk) {
if (!chunk || !this.shape.contains(y)) {
return;
}
this.#retain(x, y, z);
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const ly = y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
const old_value = chunk.blocks[index];
const old_value = chunk.column.get(x, y, z);
const old_nid = old_value & ID_MASK;
const old_block = this.#blocks[old_nid];
// a waterlogged block leaves its fluid, like the server's destroy_block
const fluid = is_waterlogged(old_value, old_block)
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
: AIR;
chunk.blocks[index] = fluid;
this.#mark_dirty(chunk);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, fluid);
chunk.column.set(x, y, z, fluid);
this.#block_changed(chunk, x, y, z, old_nid, fluid);
}
// a block that lets through or gives off a different amount of light changes the light up to 15 blocks
// away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces
#mark_neighbors_dirty(
block_chunk_x: number,
block_chunk_z: number,
lx: number,
lz: number,
old_nid: number,
new_nid: number,
) {
const old_block = this.#blocks[old_nid];
const new_block = this.#blocks[new_nid];
if (
block_light_opacity(old_block) !== block_light_opacity(new_block) ||
block_light_emission(old_block) !== block_light_emission(new_block)
) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const n = this.get_chunk(block_chunk_x + dx, block_chunk_z + dz);
if (n) {
this.#mark_dirty(n);
}
}
// what a block changing remeshes: its section, and the ones beside it when it's on their border. a block that lets
// through or gives off a different amount of light changes the light up to 15 blocks away, so in every section
// around it, and when it moves its column's sky height, from the old height to the new one in the columns around
#block_changed(chunk: Chunk, x: number, y: number, z: number, old_nid: number, new_nid: number) {
const { opacity, emission } = this.#light;
if (opacity[old_nid] !== opacity[new_nid] || emission[old_nid] !== emission[new_nid]) {
const column = (z & 15) * CHUNK_SIZE + (x & 15);
const old_sky = chunk.sky[column];
chunk.sky = column_heights(chunk.column, opacity).slice(CHUNK_AREA);
const new_sky = chunk.sky[column];
const changed = old_sky === new_sky ? [y] : [y, old_sky, new_sky];
this.#mark_dirty_around(
chunk.x,
chunk.z,
Math.min(...changed) - LIGHT_REACH,
Math.max(...changed) + LIGHT_REACH,
);
return;
}
if (lx === 0) {
const n = this.get_chunk(block_chunk_x - 1, block_chunk_z);
if (n) {
this.#mark_dirty(n);
}
} else if (lx === CHUNK_SIZE - 1) {
const n = this.get_chunk(block_chunk_x + 1, block_chunk_z);
if (n) {
this.#mark_dirty(n);
}
}
if (lz === 0) {
const n = this.get_chunk(block_chunk_x, block_chunk_z - 1);
if (n) {
this.#mark_dirty(n);
}
} else if (lz === CHUNK_SIZE - 1) {
const n = this.get_chunk(block_chunk_x, block_chunk_z + 1);
if (n) {
this.#mark_dirty(n);
// the way to the neighbor on each axis whose faces it's next to, 0 for none
const side = (local: number) => local === 0 ? -1 : local === CHUNK_SIZE - 1 ? 1 : 0;
const sx = side(x & 15);
const sy = side((y - this.shape.min_y) & 15);
const sz = side(z & 15);
const index = (y - this.shape.min_y) >> 4;
for (const dx of new Set([0, sx])) {
for (const dz of new Set([0, sz])) {
const sections = this.get_chunk(chunk.x + dx, chunk.z + dz)?.sections;
for (const dy of new Set([0, sy])) {
const section = sections?.[index + dy];
if (section) this.#mark_dirty(section);
}
}
}
}
index_to_xyz(index: number) {
const y = Math.floor(index / CHUNK_AREA);
const rem = index % CHUNK_AREA;
const z = Math.floor(rem / CHUNK_SIZE);
const x = rem % CHUNK_SIZE;
return [x, y, z];
// the sections from from_y to to_y of a chunk and the 8 around it
#mark_dirty_around(chunk_x: number, chunk_z: number, from_y: number, to_y: number) {
const lowest = Math.max(0, (from_y - this.shape.min_y) >> 4);
for (const [dx, dz] of [[0, 0], ...NEIGHBOR_OFFSETS]) {
const sections = this.get_chunk(chunk_x + dx, chunk_z + dz)?.sections ?? [];
const highest = Math.min(sections.length - 1, (to_y - this.shape.min_y) >> 4);
for (let i = lowest; i <= highest; i++) this.#mark_dirty(sections[i]);
}
}
// set a block the server told us about. the server only sends them for chunks this client has. a block this
@@ -536,9 +546,19 @@ export class ClientLevel {
if (!chunk) {
return;
}
this.delete_chunk_mesh(chunk);
this.chunks.delete(key);
for (const section of chunk.sections) {
this.#delete_mesh(section);
this.drawn.delete(section);
section.region.section_count -= 1;
if (section.region.section_count === 0) {
section.region.dispose();
this.regions.delete(region_key(cx, section.index, cz));
this.#changed_regions.delete(section.region);
}
}
this.#dirty.delete(chunk);
this.chunks.delete(key);
this.sections_version += 1;
this.block_data.delete(key);
this.visuals.unload(cx, cz);
for (const [position, { x, z }] of this.break_progress) {
@@ -582,10 +602,10 @@ export class ClientLevel {
return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data;
}
// a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be
// wrong and it would have to be meshed again as each neighbor loads
// a chunk's sections are only meshed once all its neighbors exist, otherwise their border faces and light would be
// wrong and they would have to be meshed again as each neighbor loads
can_mesh(chunk: Chunk) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
for (const [dx, dz] of NEIGHBOR_OFFSETS) {
if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
return false;
}
@@ -593,45 +613,61 @@ export class ClientLevel {
return true;
}
// meshes asked of the workers that haven't come back, for the f3 performance window
// mesh requests sent to the workers that haven't come back, for the f3 performance window. each is some sections of
// a chunk
meshes_in_flight = 0;
// the rest wait for the next frame. chunks from the server come a few at a time, but the benchmark's level has every
// chunk at once, and each request copies its 3x3 chunks
// chunk at once, and each request copies the sections around the ones it's for
max_meshes_in_flight = Infinity;
// dirty chunks that can be meshed and the meshes the workers are on, 0 once every chunk that can be is meshed
// requests for chunks with dirty sections that can be meshed, and the ones the workers are on. 0 once every
// section that can be is meshed
get meshes_pending() {
let pending = this.meshes_in_flight;
for (const chunk of this.#dirty) {
for (const chunk of this.#dirty.keys()) {
if (this.can_mesh(chunk)) pending += 1;
}
return pending;
}
// meshes every chunk again, for the benchmark to time
// meshes every section again, for the benchmark to time
remesh_all() {
for (const chunk of this.chunks.values()) this.#mark_dirty(chunk);
for (const chunk of this.chunks.values()) {
for (const section of chunk.sections) this.#mark_dirty(section);
}
}
// sends every dirty chunk that can be meshed to the workers
// sends every dirty section that can be meshed to the workers, a request per chunk
request_meshes(camera: Camera) {
for (const chunk of this.#dirty) {
for (const [chunk, sections] of this.#dirty) {
if (this.meshes_in_flight >= this.max_meshes_in_flight) {
break;
}
if (!this.can_mesh(chunk)) {
continue;
}
chunk.dirty = false;
this.#dirty.delete(chunk);
chunk.mesh_version += 1;
// copies, the worker lights the whole 3x3 area
const chunks: (Uint32Array | null)[] = [];
let lowest = Infinity;
let highest = -Infinity;
for (const section of sections) {
section.mesh_version += 1;
lowest = Math.min(lowest, section.index);
highest = Math.max(highest, section.index);
}
// they're lit with the 3x3 chunks' sections from the one below them to the one above. posting copies the
// blocks, of only the sections that aren't all one block
const first = Math.max(0, lowest - 1);
const end = Math.min(chunk.sections.length, highest + 2);
const chunks: (SectionData[] | null)[] = [];
const sky: (Int16Array | null)[] = [];
const biomes: (SectionBiomes[] | null)[] = [];
const biome_colors: (Uint32Array | null)[] = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz);
chunks.push(neighbor?.blocks.slice() ?? null);
chunks.push(neighbor?.column.sections.slice(first, end).map((section) => section.data) ?? null);
sky.push(neighbor?.sky ?? null);
biomes.push(neighbor?.column.biomes.sections.slice(first, end) ?? null);
biome_colors.push(neighbor?.biome_colors ?? null);
}
}
@@ -640,20 +676,23 @@ export class ClientLevel {
type: "mesh",
chunk_x: chunk.x,
chunk_z: chunk.z,
version: chunk.mesh_version,
sections: [...sections].map((section) => ({ index: section.index, version: section.mesh_version })),
first,
chunks,
sky,
biomes,
biome_colors,
camera: [camera.x, camera.y, camera.z],
}, chunks.filter((blocks) => blocks !== null).map((blocks) => blocks.buffer));
});
}
}
// like sodium, a chunk's translucent quads only change order when the camera crosses one of the
// planes they lie on, so that's the only time they get sorted again
// like sodium, a section's translucent quads only change order when the camera crosses one of the planes they lie
// on, so that's the only time they get sorted again
update_translucent_sorting(camera: Camera) {
const position = [camera.x, camera.y, camera.z];
for (const chunk of this.#sorted) {
const sort = chunk.translucent_sort!;
for (const section of this.#sorted) {
const sort = section.translucent_sort!;
if (!crosses_planes(sort.planes, sort.camera, position)) {
continue;
}
@@ -661,8 +700,9 @@ export class ClientLevel {
sort.requested += 1;
this.workers.post({
type: "sort",
chunk_x: chunk.x,
chunk_z: chunk.z,
chunk_x: section.chunk.x,
chunk_z: section.chunk.z,
index: section.index,
version: sort.mesh_version,
sort_version: sort.requested,
centers: sort.centers,
@@ -682,47 +722,67 @@ export class ClientLevel {
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
this.meshes_in_flight -= 1;
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
// unloaded, or remeshed again since this was requested
if (!chunk || chunk.mesh_version !== message.version) {
if (!chunk) {
return;
}
this.delete_chunk_mesh(chunk);
chunk.light = message.light;
chunk.min_y = message.min_y;
chunk.max_y = message.max_y;
this.visuals.meshed(chunk.x, chunk.z, message.visuals);
for (const layer of RENDER_LAYERS) {
const { vertices, quad_count, groups } = message[layer];
if (quad_count === 0) {
for (const mesh of message.sections) {
const section = chunk.sections[mesh.index];
// remeshed again since this was requested
if (section.mesh_version !== mesh.version) {
continue;
}
chunk.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
}
this.#delete_mesh(section);
this.sections_version += 1;
section.light = mesh.light;
section.visibility = mesh.visibility;
section.min_y = mesh.min_y;
section.max_y = mesh.max_y;
// with no quads or visuals its bounds are empty
if (mesh.min_y <= mesh.max_y) this.drawn.add(section);
else this.drawn.delete(section);
this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y + section.index * SECTION_HEIGHT, mesh.visuals);
const translucent = message.translucent;
if (translucent.quad_count === 0) {
return;
}
chunk.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices);
if (translucent.sort_type === "dynamic") {
this.#sorted.add(chunk);
chunk.translucent_sort = {
mesh_version: message.version,
centers: translucent.centers,
planes: translucent.planes,
camera: message.camera,
requested: 0,
applied: 0,
for (const layer of REGION_LAYERS) {
const { vertices, quad_count, groups } = mesh[layer];
if (quad_count === 0) {
continue;
}
if (this.#render_regions) {
section.meshes[layer] = { quad_count, groups };
section.region.meshed(layer, section, vertices);
this.#changed_regions.add(section.region);
} else {
section.meshes[layer] = { quad_count, groups, vertex_buffer: create_vertex_buffer(vertices) };
}
}
const translucent = mesh.translucent;
if (translucent.quad_count === 0) {
continue;
}
section.meshes.translucent = {
quad_count: translucent.quad_count,
vertex_buffer: create_vertex_buffer(translucent.vertices),
index_buffer: create_index_buffer(translucent.indices),
};
if (translucent.sort_type === "dynamic") {
this.#sorted.add(section);
section.translucent_sort = {
mesh_version: mesh.version,
centers: translucent.centers,
planes: translucent.planes,
camera: message.camera,
requested: 0,
applied: 0,
};
}
}
}
#on_sorted(message: Extract<FromChunkWorker, { type: "sorted" }>) {
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
const sort = chunk?.translucent_sort;
const mesh = chunk?.meshes.translucent;
const section = this.get_chunk(message.chunk_x, message.chunk_z)?.sections[message.index];
const sort = section?.translucent_sort;
const mesh = section?.meshes.translucent;
// remeshed since, or a newer sort already came back
if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) {
return;
@@ -734,26 +794,47 @@ export class ClientLevel {
mesh.index_buffer = create_index_buffer(message.indices);
}
delete_chunk_mesh(chunk: Chunk) {
for (const mesh of Object.values(chunk.meshes)) {
destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) {
destroy_buffer(mesh.index_buffer);
#delete_mesh(section: RenderSection) {
for (const [layer, mesh] of Object.entries(section.meshes)) {
if (mesh.vertex_buffer) {
destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) destroy_buffer(mesh.index_buffer);
} else {
section.region.removed(layer as RegionLayer, section);
this.#changed_regions.add(section.region);
}
}
chunk.meshes = {};
chunk.translucent_sort = undefined;
this.#sorted.delete(chunk);
section.meshes = {};
section.translucent_sort = undefined;
this.#sorted.delete(section);
}
// chunks that need meshing, some waiting on their neighbors to load
// render regions draw solid and cutout terrain in about a fifth of the draw calls, but in firefox that didn't make
// frames any faster and the gpu took longer, so they're the f3 window's render_regions switch, off by default.
// switching meshes everything again, each section's quads going in its own buffer or its region's as they come back
use_render_regions(on: boolean) {
if (on === this.#render_regions) return;
this.#render_regions = on;
this.remesh_all();
}
// puts the buffers of the regions whose sections' solid or cutout quads changed together again, before they're drawn
update_regions() {
for (const region of this.#changed_regions) region.update();
this.#changed_regions.clear();
}
// sections that need meshing, some waiting on their chunk's neighbors to load
get dirty_count() {
return this.#dirty.size;
let count = 0;
for (const sections of this.#dirty.values()) count += sections.size;
return count;
}
#mark_dirty(chunk: Chunk) {
chunk.dirty = true;
this.#dirty.add(chunk);
#mark_dirty(section: RenderSection) {
const sections = this.#dirty.get(section.chunk);
if (sections) sections.add(section);
else this.#dirty.set(section.chunk, new Set([section]));
}
// the closest entity whose box is along the view of something at x/y/z looking at yaw/pitch, within max_distance.
+138
View File
@@ -0,0 +1,138 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// sections are drawn by region, like sodium's RenderRegion: the solid and cutout quads of 8x4x8 sections share one
// buffer per layer, so drawing them binds it once. webgpu has no multi-draw, so the buffer is laid out to need fewer
// draws instead: by face group, every section's quads facing up, then every section's facing down, and so on (see
// FACE_GROUPS). the sections in view whose group faces the camera are then mostly next to each other, and a run of
// them is one draw
import { copy_buffer, create_copyable_vertex_buffer, destroy_buffer, write_buffer } from "@/client/renderer/mod.ts";
import { FACE_GROUPS, TERRAIN_QUAD_BYTES } from "@/client/workers/chunk_messages.ts";
import type { RenderSection } from "./client_level.ts";
export const REGION_WIDTH = 8;
export const REGION_HEIGHT = 4;
export type RegionLayer = "solid" | "cutout";
export const REGION_LAYERS: RegionLayer[] = ["solid", "cutout"];
// a region by the chunk and section index of any section in it. a chunk coordinate is under 2^19, so a region's x and
// z are each under 2^16 either way, and a world is at most 256 sections tall, so its regions under 2^8
export function region_key(chunk_x: number, index: number, chunk_z: number) {
return ((chunk_x >> 3) + 65536) * 2 ** 25 + ((chunk_z >> 3) + 65536) * 2 ** 8 + (index >> 2);
}
// what a region does with its buffers, apart so tests can see what's in them without a gpu
export interface RegionBuffers {
create(size: number): GPUBuffer;
write(buffer: GPUBuffer, offset: number, data: Uint8Array<ArrayBuffer>, first: number, size: number): void;
// as from offset, to offset and size in bytes, three numbers each
copy(from: GPUBuffer, to: GPUBuffer, ranges: number[]): void;
destroy(buffer: GPUBuffer): void;
}
const GPU_BUFFERS: RegionBuffers = {
create: create_copyable_vertex_buffer,
write: write_buffer,
copy: copy_buffer,
destroy: destroy_buffer,
};
interface LayerBuffer {
buffer: GPUBuffer | undefined;
// its sections in the order their quads are in each group's part of the buffer
sections: RenderSection[];
// meshed since it was last put together, with their quads as the chunk worker sent them
meshed: Map<RenderSection, Uint8Array<ArrayBuffer>>;
// whether any of its sections were meshed or lost their quads since
changed: boolean;
}
const empty_layer = (): LayerBuffer => ({ buffer: undefined, sections: [], meshed: new Map(), changed: false });
export class RenderRegion {
layers: Record<RegionLayer, LayerBuffer> = { solid: empty_layer(), cutout: empty_layer() };
// the loaded chunks' sections in it, so it goes when they do
section_count = 0;
constructor(readonly buffers = GPU_BUFFERS) {}
// a section's new quads in a layer, put in the buffer by the next update. section.meshes[layer].groups say where
// each group's quads are in vertices, and after the update where they are in the buffer
meshed(layer: RegionLayer, section: RenderSection, vertices: Uint8Array<ArrayBuffer>) {
this.layers[layer].meshed.set(section, vertices);
this.layers[layer].changed = true;
}
// a section's quads in a layer went, the next update takes them out
removed(layer: RegionLayer, section: RenderSection) {
this.layers[layer].meshed.delete(section);
this.layers[layer].changed = true;
}
// puts each layer's buffer together again: a new one, with the quads of the sections that didn't change copied over
// from the old one on the gpu, and the new quads written to it. a section with no quads in a layer anymore isn't
// in it. only for regions whose sections changed since, see ClientLevel.update_regions
update() {
for (const layer of REGION_LAYERS) {
const old = this.layers[layer];
if (!old.changed) continue;
const sections = old.sections.filter((section) => section.meshes[layer] && !old.meshed.has(section));
sections.push(...old.meshed.keys());
// where each group of each section goes, group after group
const firsts = new Uint32Array(sections.length * FACE_GROUPS);
let quads = 0;
for (let g = 0; g < FACE_GROUPS; g++) {
for (let i = 0; i < sections.length; i++) {
firsts[i * FACE_GROUPS + g] = quads;
quads += sections[i].meshes[layer]!.groups![g].count;
}
}
const buffer = quads > 0 ? this.buffers.create(quads * TERRAIN_QUAD_BYTES) : undefined;
// copies from the old buffer, one per run of quads that's together in both
const copies: number[] = [];
for (let g = 0; g < FACE_GROUPS && buffer; g++) {
for (let i = 0; i < sections.length; i++) {
const group = sections[i].meshes[layer]!.groups![g];
if (group.count === 0) continue;
const from = group.first * TERRAIN_QUAD_BYTES;
const to = firsts[i * FACE_GROUPS + g] * TERRAIN_QUAD_BYTES;
const size = group.count * TERRAIN_QUAD_BYTES;
const vertices = old.meshed.get(sections[i]);
if (vertices) {
this.buffers.write(buffer, to, vertices, from, size);
continue;
}
const last = copies.length - 3;
if (
last >= 0 && copies[last] + copies[last + 2] === from &&
copies[last + 1] + copies[last + 2] === to
) {
copies[last + 2] += size;
} else {
copies.push(from, to, size);
}
}
}
if (old.buffer) {
if (buffer) this.buffers.copy(old.buffer, buffer, copies);
this.buffers.destroy(old.buffer);
}
for (let i = 0; i < sections.length; i++) {
const mesh = sections[i].meshes[layer]!;
for (let g = 0; g < FACE_GROUPS; g++) mesh.groups![g].first = firsts[i * FACE_GROUPS + g];
mesh.slot = i;
}
this.layers[layer] = { buffer, sections, meshed: new Map(), changed: false };
}
}
dispose() {
for (const layer of REGION_LAYERS) {
if (this.layers[layer].buffer) this.buffers.destroy(this.layers[layer].buffer!);
this.layers[layer] = empty_layer();
}
}
}
+15 -9
View File
@@ -92,9 +92,9 @@ const rules_world: SharedWorld = {
const shape = client?.level.collision_shape(x, y, z) ?? false;
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
},
biome_at: (x, z) => client?.level.biome_at(Math.floor(x), Math.floor(z)),
season_at(x, z) {
const biome = this.biome_at(x, z);
biome_at: (x, y, z) => client?.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)),
season_at(x, y, z) {
const biome = this.biome_at(x, y, z);
return biome === undefined ? undefined : biome_season(biome, client!.level.time);
},
};
@@ -340,12 +340,12 @@ function client_context(listing: ModListing): ClientContext {
return { x, y, z };
},
get biome() {
const { x, z } = need_client().player;
return rules_world.biome_at(x, z);
const { x, y, z } = need_client().player;
return rules_world.biome_at(x, y, z);
},
get season() {
const { x, z } = need_client().player;
return rules_world.season_at(x, z);
const { x, y, z } = need_client().player;
return rules_world.season_at(x, y, z);
},
is_swimming: () => need_client().player.swimming,
is_sneaking: () => need_client().player.holding_sneak,
@@ -358,8 +358,14 @@ function client_context(listing: ModListing): ClientContext {
},
get_client_data: (x, y, z, field) =>
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
biome_at: (x, z) => rules_world.biome_at(x, z),
season_at: (x, z) => rules_world.season_at(x, z),
biome_at: (x, y, z) => rules_world.biome_at(x, y, z),
season_at: (x, y, z) => rules_world.season_at(x, y, z),
get min_y() {
return need_client().level.shape.min_y;
},
get max_y() {
return need_client().level.shape.max_y;
},
get time() {
return need_client().level.time;
},
+4
View File
@@ -3,6 +3,7 @@
import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "@/common/protocol.ts";
import type { ModListing } from "@/common/mod_loader.ts";
import { WorldShape } from "@/common/world_shape.ts";
import type { Join, ServerSocket, Welcome } from "./handshake.ts";
export class Connection {
@@ -12,6 +13,8 @@ export class Connection {
mods: ModListing[];
// the server's block id for each of its numeric ids, for reading chunks
server_blocks: string[];
// the dimension's height and sky light
shape: WorldShape;
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
selected_slot: number;
// the slots mods added to menu 0
@@ -27,6 +30,7 @@ export class Connection {
this.name = join.name;
this.mods = welcome.mods;
this.server_blocks = join.blocks;
this.shape = new WorldShape(join.shape);
this.spawn = join.spawn;
this.selected_slot = join.selected_slot;
this.player_menu = join.player_menu;
+36 -6
View File
@@ -100,8 +100,9 @@ let pending_destroy: GPUBuffer[] = [];
// switches for finding out what a frame costs, see the f3 performance window. msaa is changed at the start of the next
// frame. split_passes gives each section (see gpu_section) passes of its own so the gpu times them apart, which costs
// a little since every pass loads and stores the render targets. uncapped starts frames back to back instead of with
// the display's refresh, see the game loop in main.ts
export const render_debug = { msaa: false, split_passes: false, uncapped: false };
// the display's refresh, see the game loop in main.ts. render_regions draws terrain by region, see
// ClientLevel.use_render_regions
export const render_debug = { msaa: false, split_passes: false, uncapped: false, render_regions: false };
// what was drawn, for the last whole frame
export interface RenderStats {
draw_calls: number;
@@ -539,7 +540,9 @@ export function flush_batch() {
// what's bound for terrain draws in the current pass, so drawing hundreds of chunks doesn't bind the same things
// again for each one. cleared whenever the pipeline changes
let terrain_binds: { slot: number; texture: GPUTexture; index_buffer: GPUBuffer } | undefined;
let terrain_binds:
| { slot: number; texture: GPUTexture; index_buffer: GPUBuffer; vertex_buffer: GPUBuffer }
| undefined;
// draws quads first to first + quad_count of a chunk mesh (4 vertices each). without an index buffer the quads are
// drawn in order
@@ -578,9 +581,11 @@ export function draw_terrain(
if (terrain_binds?.index_buffer !== index_buffer) {
render_pass.setIndexBuffer(index_buffer, "uint32");
}
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer };
if (terrain_binds?.vertex_buffer !== vertex_buffer) {
render_pass.setVertexBuffer(0, vertex_buffer);
}
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer, vertex_buffer };
render_pass.setVertexBuffer(0, vertex_buffer);
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
frame_stats.draw_calls += 1;
frame_stats.quads[layer] += quad_count;
@@ -618,7 +623,13 @@ export function draw_instances(
}
// copies data into part of a buffer made with create_vertex_buffer, from data's first to last element
export function write_buffer(buffer: GPUBuffer, byte_offset: number, data: Float32Array, first: number, count: number) {
export function write_buffer(
buffer: GPUBuffer,
byte_offset: number,
data: Float32Array | Uint8Array<ArrayBuffer>,
first: number,
count: number,
) {
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
}
@@ -636,6 +647,25 @@ export function create_vertex_buffer(vertices: Float32Array<ArrayBuffer> | Uint8
return buffer;
}
// an empty vertex buffer of size bytes that copy_buffer can copy from and to
export function create_copyable_vertex_buffer(size: number): GPUBuffer {
return device.createBuffer({
size: Math.max(4, size),
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
});
}
// copies ranges of from into to on the gpu, as from offset, to offset and size in bytes, three numbers each. the copies
// happen before any later draw or write_buffer
export function copy_buffer(from: GPUBuffer, to: GPUBuffer, ranges: number[]) {
if (ranges.length === 0) return;
const copies = device.createCommandEncoder();
for (let i = 0; i < ranges.length; i += 3) {
copies.copyBufferToBuffer(from, ranges[i], to, ranges[i + 1], ranges[i + 2]);
}
device.queue.submit([copies.finish()]);
}
export function create_index_buffer(indices: Uint32Array): GPUBuffer {
const buffer = device.createBuffer({
size: Math.max(4, indices.byteLength),
+1 -1
View File
@@ -56,7 +56,7 @@ export class GameRenderer {
const { x, y, z } = client.camera;
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
if (!client.level.is_fluid(bx, by, bz)) return;
const color = client.level.water_color(bx, bz);
const color = client.level.water_color(bx, by, bz);
draw_rect(0, 0, canvas.width, canvas.height, [
(color >> 16) / 255,
((color >> 8) & 0xff) / 255,
+110 -51
View File
@@ -1,7 +1,13 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "@/client/level/client_level.ts";
import {
type Chunk,
CHUNK_SIZE,
type ChunkMesh,
ClientLevel,
type RenderSection,
} from "@/client/level/client_level.ts";
import { profiler } from "@/client/profiler.ts";
import { Camera } from "@/client/camera.ts";
import { AssetManager } from "@/client/assets.ts";
@@ -23,13 +29,14 @@ import {
flush_batch,
get_current_texture,
push_vertex,
render_debug,
set_current_texture,
Texture,
use_texture,
view_projection,
white_tex,
} from "@/client/renderer/mod.ts";
import { type BlockRegistry, EverythingRegistry, type RenderLayer } from "@/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "@/common/block_models.ts";
import { BREAK_STAGES, ID_MASK } from "@/common/constants.ts";
import { type Shape, shape_at } from "@/common/block_shapes.ts";
@@ -38,19 +45,28 @@ import { FACE_GROUPS, UNALIGNED_GROUP } from "@/client/workers/chunk_messages.ts
import { FACE_AXIS, FACE_NORMALS } from "@/client/workers/translucent_sort.ts";
import { Frustum } from "./frustum.ts";
import { draw_visuals } from "./visuals.ts";
import { reachable_sections } from "./occlusion.ts";
import { REGION_LAYERS, type RegionLayer, type RenderRegion } from "@/client/level/render_region.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
export class LevelRenderer {
frustum = new Frustum();
// chunks in view this frame, worked out once for all the layers
#visible: Chunk[] = [];
// sections in view this frame, near to far, worked out once for all the layers
#visible: RenderSection[] = [];
// the chunks they're in, and the regions with the ones in each, the regions near to far too
#visible_chunks = new Set<Chunk>();
#visible_regions = new Map<RenderRegion, RenderSection[]>();
// what the camera could see the last time it was searched for, which only changes when it moves to another section
// or the sections change, see occlusion.ts
#reachable: { sections: RenderSection[] | undefined; level: ClientLevel; version: number; key: string } | undefined;
// what to draw, switched off in the f3 performance window to see what each costs
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
// entities drawn this frame, for the f3 performance window
#drawn_entities = 0;
get visible_chunks() {
get visible_sections() {
return this.#visible.length;
}
@@ -62,65 +78,79 @@ export class LevelRenderer {
render_opaque(level: ClientLevel, camera: Camera) {
profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
set_current_texture(level.image.tex);
for (const layer of ["solid", "cutout"] as const) {
for (const layer of REGION_LAYERS) {
if (!this.draw[layer]) continue;
profiler.section(layer, () => {
for (const chunk of this.#visible) {
const mesh = chunk.meshes[layer];
if (mesh) {
draw_facing_camera(layer, mesh, camera);
}
for (const section of this.#visible) {
const mesh = section.meshes[layer];
if (mesh?.vertex_buffer) draw_facing_camera(layer, mesh.vertex_buffer, mesh, camera);
}
for (const [region, sections] of this.#visible_regions) draw_region(layer, region, sections, camera);
});
}
}
// asks for meshes and sorting, then works out which chunks are in view, near to far
// asks for meshes and sorting, then works out which sections are in view, near to far like sodium, so what's in
// front fills the depth buffer first and the gpu can skip shading what's behind it
#find_visible(level: ClientLevel, camera: Camera) {
level.request_meshes(camera);
level.update_translucent_sorting(camera);
level.use_render_regions(render_debug.render_regions);
level.update_regions();
this.frustum.update(view_projection());
this.#visible.length = 0;
for (const chunk of level.chunks.values()) {
const drawn = Object.keys(chunk.meshes).length > 0 || level.visuals.has(chunk.x, chunk.z);
if (drawn && this.#in_view(chunk)) {
this.#visible.push(chunk);
}
this.#visible_chunks.clear();
this.#visible_regions.clear();
const reachable = this.#reachable_sections(level, camera);
if (reachable) {
this.#visible = reachable.filter((section) => this.#in_view(section));
} else {
// the camera's chunk isn't loaded, so there's nothing to search from
this.#visible = [...level.drawn].filter((section) => this.#in_view(section))
.map((section) => ({ section, distance: distance_sq(section, camera) }))
.sort((a, b) => a.distance - b.distance)
.map(({ section }) => section);
}
for (const section of this.#visible) {
this.#visible_chunks.add(section.chunk);
const in_region = this.#visible_regions.get(section.region);
if (in_region) in_region.push(section);
else this.#visible_regions.set(section.region, [section]);
}
// near to far, like sodium, so what's in front fills the depth buffer first and the gpu can skip shading what's
// behind it
const distance_sq = (chunk: Chunk) => {
const dx = (chunk.x + 0.5) * CHUNK_SIZE - camera.x;
const dz = (chunk.z + 0.5) * CHUNK_SIZE - camera.z;
return dx * dx + dz * dz;
};
this.#visible.sort((a, b) => distance_sq(a) - distance_sq(b));
}
// translucent terrain, drawn after entities so they show through water and glass.
// chunks go back to front, and each chunk's quads are already sorted back to front
#reachable_sections(level: ClientLevel, camera: Camera) {
const key = `${Math.floor(camera.x / CHUNK_SIZE)},${Math.floor(camera.y / SECTION_HEIGHT)},${
Math.floor(camera.z / CHUNK_SIZE)
}`;
const last = this.#reachable;
if (last?.level === level && last.version === level.sections_version && last.key === key) return last.sections;
const sections = profiler.section(
"occlusion",
() => reachable_sections(level, camera.x, camera.y, camera.z),
);
this.#reachable = { sections, level, version: level.sections_version, key };
return sections;
}
// translucent terrain, drawn after entities so they show through water and glass. sections go back to front, and
// each section's quads are already sorted back to front
render_translucent(_level: ClientLevel, camera: Camera) {
if (!this.draw.translucent) return;
const distance_sq = (x: number, z: number) => {
const dx = (x + 0.5) * CHUNK_SIZE - camera.x;
const dz = (z + 0.5) * CHUNK_SIZE - camera.z;
return dx * dx + dz * dz;
};
const chunks = this.#visible
.filter((chunk) => chunk.meshes.translucent)
.map((chunk) => ({ mesh: chunk.meshes.translucent!, distance: distance_sq(chunk.x, chunk.z) }))
const sections = this.#visible
.filter((section) => section.meshes.translucent)
.map((section) => ({ mesh: section.meshes.translucent!, distance: distance_sq(section, camera) }))
.sort((a, b) => b.distance - a.distance);
for (const { mesh } of chunks) {
draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer);
for (const { mesh } of sections) {
draw_terrain("translucent", mesh.vertex_buffer!, 0, mesh.quad_count, mesh.index_buffer);
}
}
#in_view(chunk: Chunk) {
const x = chunk.x * CHUNK_SIZE;
const z = chunk.z * CHUNK_SIZE;
return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE);
#in_view(section: RenderSection) {
const x = section.chunk.x * CHUNK_SIZE;
const z = section.chunk.z * CHUNK_SIZE;
return this.frustum.intersects_box(x, section.min_y, z, x + CHUNK_SIZE, section.max_y, z + CHUNK_SIZE);
}
// every entity in view but the one the camera is in
@@ -178,7 +208,7 @@ export class LevelRenderer {
// blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first
render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) {
if (!this.draw.visuals) return;
level.visuals.frame(this.#visible, level.ticks + partial_tick);
level.visuals.frame(this.#visible_chunks, level.ticks + partial_tick);
flush_batch();
set_current_texture(level.image.tex);
draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]);
@@ -251,6 +281,14 @@ export class LevelRenderer {
#baked = new Map<number, BakedQuad[]>();
}
// from the camera to the middle of the section's bounds, squared
function distance_sq(section: RenderSection, camera: Camera) {
const dx = (section.chunk.x + 0.5) * CHUNK_SIZE - camera.x;
const dy = (section.min_y + section.max_y) / 2 - camera.y;
const dz = (section.chunk.z + 0.5) * CHUNK_SIZE - camera.z;
return dx * dx + dy * dy + dz * dz;
}
// how far models can stick out of their entity's box, like a swinging arm or a dropped item bobbing
const ENTITY_CULL_MARGIN = 0.5;
@@ -384,12 +422,8 @@ function decal_uv(face: number, x: number, y: number, z: number): [number, numbe
// only the face groups that can face the camera: quads facing +x can only be seen from beyond the lowest x plane any
// of them lie on. neighboring groups that are both drawn go in one draw call
function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera) {
const groups = mesh.groups;
if (!groups) {
draw_terrain(layer, mesh.vertex_buffer, 0, mesh.quad_count);
return;
}
function draw_facing_camera(layer: RegionLayer, buffer: GPUBuffer, mesh: ChunkMesh, camera: Camera) {
const groups = mesh.groups!;
let start = 0;
let end = 0;
for (let g = 0; g < FACE_GROUPS; g++) {
@@ -398,12 +432,37 @@ function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera)
continue;
}
if (group.first !== end) {
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
draw_terrain(layer, buffer, start, end - start);
start = group.first;
}
end = group.first + group.count;
}
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
draw_terrain(layer, buffer, start, end - start);
}
// a region's sections in view, a face group at a time (see render_region.ts), only where the group can face the camera:
// quads facing +x can only be seen from beyond the lowest x plane any of them lie on. sections next to each other in the
// buffer that are both drawn go in one draw call
function draw_region(layer: RegionLayer, region: RenderRegion, in_view: RenderSection[], camera: Camera) {
const buffer = region.layers[layer].buffer;
if (!buffer) return;
// in the order they're in the buffer
const sections = in_view.filter((section) => section.meshes[layer]?.slot !== undefined)
.sort((a, b) => a.meshes[layer]!.slot! - b.meshes[layer]!.slot!);
for (let g = 0; g < FACE_GROUPS; g++) {
let start = 0;
let end = 0;
for (const section of sections) {
const group = section.meshes[layer]!.groups![g];
if (group.count === 0 || !group_faces_camera(g, group.min, group.max, camera)) continue;
if (group.first !== end) {
draw_terrain(layer, buffer, start, end - start);
start = group.first;
}
end = group.first + group.count;
}
draw_terrain(layer, buffer, start, end - start);
}
}
export function group_faces_camera(
+81
View File
@@ -0,0 +1,81 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// occlusion culling, like sodium's OcclusionCuller but simpler: which sections the camera can see into, going out
// from its own section a face at a time. a section is only left through faces that see the ones it was entered
// through (see client/workers/visibility.ts), and never back towards the camera, so caves under the ground and the
// inside of hills aren't drawn
import { type Chunk, CHUNK_SIZE, type ClientLevel, type RenderSection } from "@/client/level/client_level.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
import { ALL_DIRECTIONS, exits } from "@/client/workers/visibility.ts";
// tells searches apart, so sections don't need clearing between them
let searches = 0;
// the sections with something to draw the camera at x y z can see, near to far: in the order the search reaches them,
// a step at a time. undefined when the camera's chunk isn't loaded
export function reachable_sections(level: ClientLevel, x: number, y: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = level.get_chunk(chunk_x, chunk_z);
if (!chunk) return undefined;
// above or below the world, from the section nearest to the camera
const count = chunk.sections.length;
const index = Math.min(count - 1, Math.max(0, Math.floor((y - level.shape.min_y) / SECTION_HEIGHT)));
// the loaded chunks in a grid, since looking each step's up in the level's map is most of what a search costs
let min_x = chunk_x, max_x = chunk_x, min_z = chunk_z, max_z = chunk_z;
for (const { x, z } of level.chunks.values()) {
min_x = Math.min(min_x, x);
max_x = Math.max(max_x, x);
min_z = Math.min(min_z, z);
max_z = Math.max(max_z, z);
}
const width = max_x - min_x + 1;
const depth = max_z - min_z + 1;
const grid: (Chunk | undefined)[] = new Array(width * depth);
for (const chunk of level.chunks.values()) grid[(chunk.x - min_x) * depth + chunk.z - min_z] = chunk;
const chunk_at = (x: number, z: number) =>
x < min_x || x > max_x || z < min_z || z > max_z ? undefined : grid[(x - min_x) * depth + z - min_z];
const search = ++searches;
const start = chunk.sections[index];
start.search = search;
const queue = [start];
const found: RenderSection[] = [];
// adds the section a step goes into, entered through the face opposite the step's direction
const step = (neighbor: RenderSection | undefined, direction: number) => {
if (!neighbor) return;
// every step goes one further from the camera's section, so all the ways into a section are known by the time
// it's taken from the queue
if (neighbor.search !== search) {
neighbor.search = search;
neighbor.incoming = 0;
queue.push(neighbor);
}
neighbor.incoming |= 1 << (direction ^ 1);
};
for (let i = 0; i < queue.length; i++) {
const section = queue[i];
// with no quads or visuals its bounds are empty, see ClientLevel.drawn
if (section.min_y <= section.max_y) found.push(section);
// the camera's section can be left any way, even when the camera is inside a block
let out = section === start ? ALL_DIRECTIONS : exits(section.visibility, section.incoming);
if (!out) continue;
// away from the camera's section on every axis
const { x, z, sections } = section.chunk;
const dx = x - chunk_x;
const dy = section.index - index;
const dz = z - chunk_z;
out &= (dx <= 0 ? 1 : 0) | (dx >= 0 ? 2 : 0) | (dy <= 0 ? 4 : 0) | (dy >= 0 ? 8 : 0) | (dz <= 0 ? 16 : 0) |
(dz >= 0 ? 32 : 0);
if (out & 1) step(chunk_at(x - 1, z)?.sections[section.index], 0);
if (out & 2) step(chunk_at(x + 1, z)?.sections[section.index], 1);
if (out & 4) step(sections[section.index - 1], 2);
if (out & 8) step(sections[section.index + 1], 3);
if (out & 16) step(chunk_at(x, z - 1)?.sections[section.index], 4);
if (out & 32) step(chunk_at(x, z + 1)?.sections[section.index], 5);
}
return found;
}
+36 -22
View File
@@ -2,8 +2,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// blocks drawn with code, like a shaft that turns, see ctx.render.register_visual. like flywheel's visuals: one per
// block, made when its chunk is meshed and kept by chunk. what they draw are instances of models, and every instance of
// a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in
// block, made when its section is meshed and kept by chunk. what they draw are instances of models, and every instance
// of a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in
// client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per
// frame. an item is a model too, one per way an item can look, and a fluid's box is a model of its own
import { mat4, vec3 } from "gl-matrix";
@@ -29,6 +29,7 @@ import {
states_of,
} from "@/common/block_models.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
import type { ModelFace } from "@/common/mod_data.ts";
import { ItemStack } from "@/common/inventory.ts";
import { chunk_key, item_texture } from "@/common/utils.ts";
@@ -186,7 +187,7 @@ interface Entry {
// a level's visuals
export class Visuals {
// by chunk_key, then the block's index in its chunk
// by chunk_key, then the block's index in its chunk counted from y 0, see #index
#chunks = new Map<number, Map<number, Entry>>();
#level: VisualsLevel;
// baked once per level, since a level's mods don't change
@@ -213,31 +214,41 @@ export class Visuals {
yield* this.#fluid_groups;
}
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals
// for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones
// that stay take it
meshed(chunk_x: number, chunk_z: number, found: Uint32Array) {
// the blocks with visuals a chunk's section was meshed with, as pairs of the block's index in the section (see
// section_index) and its value. bottom is the section's lowest y. visuals in it for blocks that are gone or
// changed go, and new ones are made. the section's light came with its mesh, so the ones that stay take it
meshed(chunk_x: number, chunk_z: number, bottom: number, found: Uint32Array) {
const key = chunk_key(chunk_x, chunk_z);
const old = this.#chunks.get(key) ?? new Map<number, Entry>();
const kept = new Map<number, Entry>();
const entries = this.#chunks.get(key) ?? new Map<number, Entry>();
const old = new Map<number, Entry>();
for (const [index, entry] of entries) {
if (entry.y >= bottom && entry.y < bottom + SECTION_HEIGHT) old.set(index, entry);
}
for (let i = 0; i < found.length; i += 2) {
const index = found[i];
const local = found[i];
const x = chunk_x * CHUNK_SIZE + (local & 15);
const y = bottom + (local >> 8);
const z = chunk_z * CHUNK_SIZE + ((local >> 4) & 15);
const index = this.#index(x, y, z);
const value = found[i + 1];
const entry = old.get(index);
old.delete(index);
if (entry?.value === value) {
this.#relight(entry);
kept.set(index, entry);
continue;
}
if (entry) this.#delete(entry);
const x = chunk_x * CHUNK_SIZE + (index % CHUNK_SIZE);
const z = chunk_z * CHUNK_SIZE + Math.floor(index / CHUNK_SIZE) % CHUNK_SIZE;
const made = this.#create(x, Math.floor(index / CHUNK_AREA), z, value);
if (made) kept.set(index, made);
if (entry) {
this.#delete(entry);
entries.delete(index);
}
const made = this.#create(x, y, z, value);
if (made) entries.set(index, made);
}
for (const entry of old.values()) this.#delete(entry);
if (kept.size > 0) this.#chunks.set(key, kept);
for (const [index, entry] of old) {
this.#delete(entry);
entries.delete(index);
}
if (entries.size > 0) this.#chunks.set(key, entries);
else this.#chunks.delete(key);
}
@@ -279,10 +290,13 @@ export class Visuals {
}
#entry(x: number, y: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const index = y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
return this.#chunks.get(chunk_key(chunk_x, chunk_z))?.get(index);
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
return this.#chunks.get(key)?.get(this.#index(x, y, z));
}
// a block's place in its chunk's map
#index(x: number, y: number, z: number) {
return y * CHUNK_AREA + (z & 15) * CHUNK_SIZE + (x & 15);
}
#create(x: number, y: number, z: number, value: number): Entry | undefined {
+54 -23
View File
@@ -4,6 +4,8 @@
import type { BlockRegistry } from "@/common/everything_registry.ts";
import type { SpriteRegion } from "@/common/constants.ts";
import type { ModelJson } from "@/common/block_models.ts";
import type { WorldShapeJson } from "@/common/world_shape.ts";
import type { SectionBiomes, SectionData } from "@/common/section.ts";
import type { SortType } from "./translucent_sort.ts";
// messages between the main thread and the chunk workers
@@ -38,15 +40,27 @@ export type ToChunkWorker =
// the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
// ctx.render.register_visual
visuals: [number, boolean][];
// the dimension's height and sky light
shape: WorldShapeJson;
}
// sections of one chunk to mesh, sent together so they're lit together
| {
type: "mesh";
chunk_x: number;
chunk_z: number;
version: number;
// copies of the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting
chunks: (Uint32Array | null)[];
// the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges
// the sections to mesh, by index from the bottom of the world, and the mesh_version each is meshed for
sections: { index: number; version: number }[];
// the index of the lowest section in chunks
first: number;
// the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting. each one's sections from the
// one below the lowest to mesh to the one above the highest, as far as the world goes. null for a chunk that
// isn't loaded
chunks: (SectionData[] | null)[];
// the same chunks' sky heights, see column_heights in common/section.ts
sky: (Int16Array | null)[];
// the same chunks' biome cells, of the same sections as chunks, and their biome palettes' colors (see
// Chunk.biome_colors in client_level.ts), blended across their edges
biomes: (SectionBiomes[] | null)[];
biome_colors: (Uint32Array | null)[];
// where the camera is, to sort the translucent quads
camera: number[];
@@ -55,12 +69,18 @@ export type ToChunkWorker =
type: "sort";
chunk_x: number;
chunk_z: number;
// the section's index in its chunk
index: number;
version: number;
sort_version: number;
centers: Float32Array;
camera: number[];
};
// a section's light, a byte per block indexed like its blocks (see section_index): block light << 4 | sky light, like
// sodium's packed light data. one number when it's the same everywhere, like the open sky above the ground
export type SectionLight = number | Uint8Array<ArrayBuffer>;
// 4 vertices per quad, TERRAIN_VERTEX_BYTES each
export interface LayerMesh {
vertices: Uint8Array<ArrayBuffer>;
@@ -69,36 +89,47 @@ export interface LayerMesh {
groups?: FaceGroup[];
}
// a section the worker meshed
export interface SectionMesh {
index: number;
version: number;
// the lowest and highest y of the section's quads and visuals in the world, for frustum culling. Infinity and
// -Infinity when it has none
min_y: number;
max_y: number;
solid: LayerMesh;
cutout: LayerMesh;
translucent: LayerMesh & {
// sorted back to front for the camera the mesh was requested with
indices: Uint32Array;
sort_type: SortType;
// what resorting needs, see translucent_sort.ts
centers: Float32Array;
planes: [Float32Array, Float32Array, Float32Array];
};
// entities are lit from it
light: SectionLight;
// which of its faces can be seen through from which others, see client/workers/visibility.ts
visibility: number;
// the blocks in it with visuals, as pairs of the block's index in the section (see section_index) and its value
visuals: Uint32Array<ArrayBuffer>;
}
export type FromChunkWorker =
| {
type: "meshed";
chunk_x: number;
chunk_z: number;
version: number;
// the lowest and highest y of the chunk's quads, for frustum culling
min_y: number;
max_y: number;
solid: LayerMesh;
cutout: LayerMesh;
translucent: LayerMesh & {
// sorted back to front for the camera the mesh was requested with
indices: Uint32Array;
sort_type: SortType;
// what resorting needs, see translucent_sort.ts
centers: Float32Array;
planes: [Float32Array, Float32Array, Float32Array];
};
// the sections asked for, in the same order
sections: SectionMesh[];
// what the translucent quads were sorted for
camera: number[];
// the chunk's light, one byte per block indexed like its blocks: block light << 4 | sky light, like sodium's
// packed light data. entities are lit from it
light: Uint8Array<ArrayBuffer>;
// the blocks in it with visuals, as pairs of the block's index in the chunk (like light's) and its value
visuals: Uint32Array<ArrayBuffer>;
}
| {
type: "sorted";
chunk_x: number;
chunk_z: number;
index: number;
version: number;
sort_version: number;
indices: Uint32Array;
+158 -79
View File
@@ -9,25 +9,21 @@ import {
type BlockRegistry,
type RenderLayer,
} from "@/common/everything_registry.ts";
import {
AIR,
CHUNK_AREA,
CHUNK_HEIGHT,
CHUNK_SIZE,
ID_MASK,
type SpriteRegion,
TEXTURE_SIZE,
} from "@/common/constants.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK, type SpriteRegion, TEXTURE_SIZE } from "@/common/constants.ts";
import type { Texture } from "../renderer/types.ts";
import {
FACE_GROUPS,
type FaceGroup,
type FromChunkWorker,
type SectionLight,
type SectionMesh,
TERRAIN_QUAD_BYTES,
TERRAIN_VERTEX_BYTES,
type ToChunkWorker,
UNALIGNED_GROUP,
} from "./chunk_messages.ts";
import { BIOME_CELL_HEIGHT, Section, section_index, SECTION_VOLUME, type SectionBiomes } from "@/common/section.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
import {
bake_block,
FACE_CORNERS,
@@ -56,6 +52,7 @@ import {
REGION_VOID,
} from "./lighting.ts";
import { cell_index, fluid_quads, type FluidCell } from "./fluid_mesh.ts";
import { ALL_VISIBLE, section_visibility } from "./visibility.ts";
import { fluid_height, fluid_textures } from "@/common/everything_registry.ts";
type TexturesInfo = Record<string, SpriteRegion>;
@@ -91,6 +88,8 @@ const block_layers = new Uint8Array(TABLE_SIZE);
const block_cull_same = new Uint8Array(TABLE_SIZE);
// darkens the corners it touches (minecraft's ambient occlusion), full cubes with collision do
const block_occludes = new Uint8Array(TABLE_SIZE);
// blocks nothing can be seen through, drawn as whole opaque cubes, see visibility.ts
const block_hides_view = new Uint8Array(TABLE_SIZE);
// light can come around a corner past it
const block_lets_light_by = new Uint8Array(TABLE_SIZE);
const light_tables: LightTables = { opacity: new Uint8Array(TABLE_SIZE), emission: new Uint8Array(TABLE_SIZE) };
@@ -104,7 +103,10 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE);
const block_visual = new Uint8Array(TABLE_SIZE);
const HAS_VISUAL = 1;
const REPLACED_MODEL = 2;
const region = new LightRegion();
// the sections being meshed and the ones around them, made for the dimension's height by "init"
let region: LightRegion;
// the dimension's min_y, which quads are moved up by to be where they are in the world
let world_min_y = 0;
// a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's
// four corner lights it gets, so faces smaller than the block are lit like minecraft's
@@ -142,38 +144,43 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
block_visual.fill(0);
for (const [nid, replaces_model] of message.visuals) {
block_visual[nid] = replaces_model ? REPLACED_MODEL : HAS_VISUAL;
if (replaces_model) block_hides_view[nid] = 0;
}
textures_info = message.textures_info;
image = message.image as Texture;
region = new LightRegion(message.shape);
world_min_y = message.shape.min_y;
break;
case "mesh": {
region.fill(message.chunks);
const chunks = message.chunks.map((data) => data?.map((section) => new Section(section)) ?? null);
// the region's bottom in the world
const bottom = world_min_y + message.first * SECTION_HEIGHT;
region.fill(chunks, message.sky, bottom);
region.compute(light_tables);
blend_biome_colors(message.biome_colors);
const { solid, cutout, translucent, min_y, max_y, visuals } = make_chunk_mesh(
message.chunk_x,
message.chunk_z,
message.chunks,
message.camera,
);
const light = chunk_light();
biomes = message.biomes;
biome_colors = message.biome_colors;
blended_any = false;
const sections: SectionMesh[] = message.sections.map(({ index, version }) => {
// the section's bottom in the region
const from = (index - message.first) * SECTION_HEIGHT;
return {
index,
version,
...make_section_mesh(message.chunk_x, message.chunk_z, chunks, from, bottom, message.camera),
light: section_light(from),
visibility: visibility(chunks[4]![from >> 4], from),
};
});
post(
{
type: "meshed",
chunk_x: message.chunk_x,
chunk_z: message.chunk_z,
version: message.version,
min_y,
max_y,
solid,
cutout,
translucent,
sections,
camera: message.camera,
light,
visuals,
},
[
light.buffer,
sections.flatMap(({ light, visuals, solid, cutout, translucent }) => [
...typeof light === "number" ? [] : [light.buffer],
visuals.buffer,
solid.vertices.buffer,
cutout.vertices.buffer,
@@ -181,7 +188,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
translucent.indices.buffer,
translucent.centers.buffer,
...translucent.planes.map((planes) => planes.buffer),
],
]),
);
break;
}
@@ -192,6 +199,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
type: "sorted",
chunk_x: message.chunk_x,
chunk_z: message.chunk_z,
index: message.index,
version: message.version,
sort_version: message.sort_version,
indices,
@@ -201,37 +209,83 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
}
};
// the middle chunk of the light region, packed for the main thread, see "meshed"
function chunk_light() {
const light = new Uint8Array(CHUNK_AREA * CHUNK_HEIGHT);
for (let y = 0; y < CHUNK_HEIGHT; y++) {
// the light of the middle chunk's section from this y in the region, packed for the main thread, see SectionLight
const packed_light = new Uint8Array(SECTION_VOLUME);
function section_light(from: number): SectionLight {
let same = true;
for (let y = 0; y < SECTION_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const from = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
const to = y * CHUNK_AREA + z * CHUNK_SIZE;
const at = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
const to = (y << 8) | (z << 4);
for (let x = 0; x < CHUNK_SIZE; x++) {
light[to + x] = (region.block_light[from + x] << 4) | region.sky[from + x];
const light = (region.block_light[at + x] << 4) | region.sky[at + x];
packed_light[to + x] = light;
if (light !== packed_light[0]) same = false;
}
}
}
return light;
return same ? packed_light[0] : packed_light.slice();
}
const open_rows = new Uint16Array(256);
// which faces of the section see each other, see visibility.ts. from is its bottom in the region
function visibility(section: Section, from: number) {
if (!section.blocks) return block_hides_view[section.value & ID_MASK] ? 0 : ALL_VISIBLE;
for (let y = 0; y < SECTION_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
// the middle chunk of the region
const row = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
let open = 0;
for (let x = 0; x < CHUNK_SIZE; x++) {
if (!block_hides_view[region.blocks[row + x]]) open |= 1 << x;
}
open_rows[y << 4 | z] = open;
}
}
return section_visibility(open_rows);
}
function post(message: FromChunkWorker, transfer: Transferable[]) {
self.postMessage(message, transfer);
}
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of the 5x5
// columns around it, so biome edges fade instead of being a line. neighbors that aren't there are left out
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of
// the 5x5 columns around it at the same height, so biome edges fade instead of being a line. neighbors that aren't
// there are left out. colors aren't blended up and down
const BLEND_RADIUS = 2;
// the middle chunk's blended colors, x then z, grass then foliage then water
// the 3x3 chunks' biome cells and colors of the request being meshed, see "mesh"
let biomes: (SectionBiomes[] | null)[] = [];
let biome_colors: (Uint32Array | null)[] = [];
// the middle chunk's blended colors at a layer of cells, x then z, grass then foliage then water
const blended = new Uint32Array(CHUNK_AREA * 3);
// the 3x3 chunks' biome palette index of each column at that layer, so a layer with the same biomes as the last one
// blended isn't blended again, unless none has been for this request
const blended_cells = new Uint8Array(9 * CHUNK_AREA);
let blended_any = false;
const layer_cells = new Uint8Array(9 * CHUNK_AREA);
// what MeshQuad.tint is for the biome's colors, they aren't colors since those only go up to 0xffffff
const GRASS = -1;
const FOLIAGE = -2;
const WATER = -3;
function blend_biome_colors(colors: (Uint32Array | null)[]) {
for (const offset of [0, CHUNK_AREA, CHUNK_AREA * 2]) {
// blends the colors of the layer of biome cells y is in, in the region's section from (see "mesh")
function blend_biome_colors(from: number, y: number) {
const layer = ((y & 15) >> 2) << 8;
for (let i = 0; i < 9; i++) {
const cells = biomes[i]?.[from >> 4];
if (cells === undefined) continue;
if (typeof cells === "number") layer_cells.fill(cells, i * CHUNK_AREA, (i + 1) * CHUNK_AREA);
else layer_cells.set(cells.subarray(layer, layer + CHUNK_AREA), i * CHUNK_AREA);
}
let same = blended_any;
for (let i = 0; i < layer_cells.length && same; i++) same = layer_cells[i] === blended_cells[i];
if (same) return;
blended_cells.set(layer_cells);
blended_any = true;
for (let part = 0; part < 3; part++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
let r = 0;
@@ -243,9 +297,12 @@ function blend_biome_colors(colors: (Uint32Array | null)[]) {
// which of the 3x3 chunks, and where in it
const sx = x + dx + CHUNK_SIZE;
const sz = z + dz + CHUNK_SIZE;
const chunk = colors[Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE)];
if (!chunk) continue;
const color = chunk[offset + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
const chunk = Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE);
const colors = biome_colors[chunk];
if (!colors || !biomes[chunk]) continue;
const cell =
layer_cells[chunk * CHUNK_AREA + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
const color = colors[cell * 3 + part];
r += color >> 16;
g += (color >> 8) & 0xff;
b += color & 0xff;
@@ -255,7 +312,7 @@ function blend_biome_colors(colors: (Uint32Array | null)[]) {
const color = count === 0
? 0xffffff
: (Math.round(r / count) << 16) | (Math.round(g / count) << 8) | Math.round(b / count);
blended[offset + z * CHUNK_SIZE + x] = color;
blended[part * CHUNK_AREA + z * CHUNK_SIZE + x] = color;
}
}
}
@@ -283,6 +340,7 @@ function build_block_tables() {
block_layers[nid] = layer;
block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0;
block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT && is_full_cube(block) ? 1 : 0;
block_hides_view[nid] = layer === SOLID && is_full_cube(block) ? 1 : 0;
block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0;
light_tables.opacity[nid] = opacity;
light_tables.emission[nid] = block_light_emission(block);
@@ -543,14 +601,14 @@ function hides_fluid(nid: number) {
return nid !== AIR && block_layers[nid] === SOLID;
}
// a cell's block with its states, from the 3x3 chunks the region was filled from. 0 (air) above the world and for
// chunks that aren't there
function region_value(chunks: (Uint32Array | null)[], index: number, y: number) {
if (y < 0 || y >= CHUNK_HEIGHT) return AIR;
// a cell's block with its states, from the 3x3 chunks' sections the region was filled from. 0 (air) outside them and
// for chunks that aren't there
function region_value(chunks: (Section[] | null)[], index: number, y: number) {
if (y < 0 || y >= region.height) return AIR;
const x = index % REGION_SIZE;
const z = Math.floor(index / REGION_SIZE) % REGION_SIZE;
const chunk = chunks[Math.floor(z / CHUNK_SIZE) * 3 + Math.floor(x / CHUNK_SIZE)];
return chunk ? chunk[y * CHUNK_AREA + (z % CHUNK_SIZE) * CHUNK_SIZE + (x % CHUNK_SIZE)] : AIR;
return chunk ? chunk[y >> 4].get(section_index(x, y, z)) : AIR;
}
// the surface of the fluid with this numeric id in a cell, if the cell is that fluid
@@ -565,7 +623,7 @@ const fluid_cells: FluidCell[] = Array.from(
);
// the numeric id of the fluid in a cell: the block, or what it's waterlogged with. 0 for none
function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
function cell_fluid(chunks: (Section[] | null)[], index: number, y: number) {
const id = region_block(region, index, y);
if (fluid_range[id]) return id;
const fluid = waterlog_fluid[id];
@@ -574,7 +632,7 @@ function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
}
// the 3x3 cells around the fluid at index and y, see FluidCell. a waterlogged block is a source of its fluid
function fill_fluid_cells(chunks: (Uint32Array | null)[], nid: number, index: number, y: number) {
function fill_fluid_cells(chunks: (Section[] | null)[], nid: number, index: number, y: number) {
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const cell = fluid_cells[cell_index(dx, dz)];
@@ -639,22 +697,39 @@ function underside(top: MeshQuad): MeshQuad {
};
}
// region has to be filled and lit first
// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the
// ones around it for fluids, whose surface follows their neighbors'
function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array | null)[], camera: number[]) {
const values = chunks[4]!;
// solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead
const opaque = [SOLID, CUTOUT].map(() =>
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
);
const translucent_quads = new QuadBuffer();
// quads being built, kept from one section to the next. solid and cutout get a buffer per face group, translucent one
// for everything since it's sorted instead
const opaque = [SOLID, CUTOUT].map(() =>
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
);
const translucent_quads = new QuadBuffer();
// for sorting the translucent quads
let centers = new Float32Array(256);
let faces = new Uint8Array(256);
// the middle chunk's section from y from in the region, which has to be filled and lit first. bottom is the region's
// bottom in the world. chunks are the region's sections with their blocks' states, the middle one's for models that
// change with them and the ones around it for fluids, whose surface follows their neighbors'
function make_section_mesh(
chunk_x: number,
chunk_z: number,
chunks: (Section[] | null)[],
from: number,
bottom: number,
camera: number[],
) {
const section = chunks[4]![from >> 4];
for (const groups of opaque) {
for (const group of groups) {
group.buffer.count = 0;
group.min = Infinity;
group.max = -Infinity;
}
}
translucent_quads.count = 0;
mesh_min_y = Infinity;
mesh_max_y = -Infinity;
// for sorting the translucent quads
let centers = new Float32Array(256);
let faces = new Uint8Array(256);
// the blocks with visuals, see "meshed"
// the blocks with visuals, see SectionMesh
const visuals: number[] = [];
// where the neighbor on each face is, same order as FACE_NORMALS
@@ -663,6 +738,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
// adds a lit quad of the block at x y z in the chunk to its layer
const emit = (quad: MeshQuad, layer_id: number, x: number, y: number, z: number, alpha: number) => {
const wx = chunk_x * CHUNK_SIZE + x;
const wy = bottom + y;
const wz = chunk_z * CHUNK_SIZE + z;
const tint = quad.tint === GRASS
? blended[z * CHUNK_SIZE + x]
@@ -674,28 +750,31 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
if (layer_id !== TRANSLUCENT) {
const group = opaque[layer_id][quad.group];
push_quad(group.buffer, quad, wx, y, wz, alpha, tint);
push_quad(group.buffer, quad, wx, wy, wz, alpha, tint);
if (quad.group !== UNALIGNED_GROUP) {
const axis = FACE_AXIS[quad.face];
const plane = (axis === 0 ? wx : axis === 1 ? y : wz) + quad.positions[axis];
const plane = (axis === 0 ? wx : axis === 1 ? wy : wz) + quad.positions[axis];
if (plane < group.min) group.min = plane;
if (plane > group.max) group.max = plane;
}
} else {
push_quad(translucent_quads, quad, wx, y, wz, alpha, tint);
push_quad(translucent_quads, quad, wx, wy, wz, alpha, tint);
// sorting treats every quad as facing along an axis, rotated ones too
const q = translucent_quads.count - 1;
centers = ensure_capacity(centers, (q + 1) * 3);
faces = ensure_capacity(faces, q + 1);
const p = quad.positions;
centers[q * 3] = wx + (p[0] + p[6]) / 2;
centers[q * 3 + 1] = y + (p[1] + p[7]) / 2;
centers[q * 3 + 1] = wy + (p[1] + p[7]) / 2;
centers[q * 3 + 2] = wz + (p[2] + p[8]) / 2;
faces[q] = quad.face;
}
};
for (let y = 0; y < CHUNK_HEIGHT; y++) {
// nothing to mesh in a section of air
const air = section.blocks === null && section.value === AIR;
for (let y = from; y < from + SECTION_HEIGHT && !air; y++) {
if (y % BIOME_CELL_HEIGHT === 0) blend_biome_colors(from, y);
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
// the middle chunk of the region
@@ -739,12 +818,12 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
if (fluid_nid === block_nid) continue;
}
const value = values[y * CHUNK_AREA + z * CHUNK_SIZE + x];
const value = section.get(section_index(x, y, z));
if (block_visual[block_nid]) {
visuals.push(y * CHUNK_AREA + z * CHUNK_SIZE + x, value);
visuals.push(section_index(x, y, z), value);
// with the block above and below, since a visual can reach past its block, like a large cog
if (y - 1 < mesh_min_y) mesh_min_y = y - 1;
if (y + 2 > mesh_max_y) mesh_max_y = y + 2;
if (bottom + y - 1 < mesh_min_y) mesh_min_y = bottom + y - 1;
if (bottom + y + 2 > mesh_max_y) mesh_max_y = bottom + y + 2;
if (block_visual[block_nid] === REPLACED_MODEL) continue;
}
@@ -788,8 +867,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
const [camera_x, camera_y, camera_z] = camera;
return {
min_y: mesh_min_y === Infinity ? 0 : mesh_min_y,
max_y: mesh_max_y === -Infinity ? 0 : mesh_max_y,
min_y: mesh_min_y,
max_y: mesh_max_y,
solid,
cutout,
translucent: {
+58 -32
View File
@@ -6,15 +6,21 @@
// something that isn't fully clear, block light starts at blocks that give off light. both spread to
// neighbors losing max(1, the neighbor's opacity) per step.
//
// minecraft stores light and updates it as blocks change. here it's worked out from scratch for the
// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15
// blocks, so nothing outside those chunks can light the middle one or its border
// minecraft stores light and updates it as blocks change. here it's worked out from scratch around the sections being
// meshed: the 3x3 chunks around theirs, from the section below them to the one above. that gives the same result, since
// light reaches at most 15 blocks, so nothing outside can light them or their border. the only light that comes from
// further is the sky's straight down, which starts where each column's sky height says (see column_heights in
// common/section.ts) instead of being followed down from the top.
//
// y in a region counts from its bottom, which is a section's. in a dimension without sky light there's only block
// light
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { AIR, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import type { Section } from "@/common/section.ts";
import { SECTION_HEIGHT, type WorldShapeJson } from "@/common/world_shape.ts";
export const REGION_SIZE = CHUNK_SIZE * 3;
export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
export const REGION_VOLUME = REGION_LAYER * CHUNK_HEIGHT;
// what unloaded chunks and the space below the world are made of: opaque, dark, never shown
export const REGION_VOID = ID_MASK;
@@ -25,31 +31,53 @@ export interface LightTables {
}
export class LightRegion {
// in blocks, of the sections last filled in
height = 0;
readonly sky_light: boolean;
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
blocks = new Uint16Array(REGION_VOLUME);
sky = new Uint8Array(REGION_VOLUME);
block_light = new Uint8Array(REGION_VOLUME);
blocks: Uint16Array;
sky: Uint8Array;
block_light: Uint8Array;
// the lowest y that still sees the sky, per column
// the lowest y that still sees the sky, per column. the region's height when that's above it
#heights = new Int32Array(REGION_LAYER);
#queue = new Int32Array(1 << 18);
#queue_length = 0;
// the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing ones are void
fill(chunks: (Uint32Array | null)[]) {
// room for the dimension's whole height
constructor(shape: WorldShapeJson) {
this.sky_light = shape.sky_light;
const volume = REGION_LAYER * (shape.max_y - shape.min_y);
this.blocks = new Uint16Array(volume);
this.sky = new Uint8Array(volume);
this.block_light = new Uint8Array(volume);
}
// the same sections of the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing
// chunks are void. sky is each chunk's sky height by column (see column_heights), and bottom the y of the region's
// bottom in the world
fill(chunks: (Section[] | null)[], sky: (ArrayLike<number> | null)[], bottom: number) {
this.height = chunks[4]!.length * SECTION_HEIGHT;
for (let i = 0; i < 9; i++) {
const source = chunks[i];
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE;
for (let y = 0; y < CHUNK_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
const height = sky[i] ? sky[i]![z * CHUNK_SIZE + x] - bottom : this.height;
this.#heights[origin + z * REGION_SIZE + x] = Math.min(Math.max(height, 0), this.height);
}
}
for (let y = 0; y < this.height; y++) {
const section = source?.[y >> 4];
for (let z = 0; z < CHUNK_SIZE; z++) {
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
if (!source) {
this.blocks.fill(REGION_VOID, to, to + CHUNK_SIZE);
if (!section?.blocks) {
this.blocks.fill(section ? section.value & ID_MASK : REGION_VOID, to, to + CHUNK_SIZE);
continue;
}
const from = y * CHUNK_AREA + z * CHUNK_SIZE;
const from = ((y & 15) << 8) | (z << 4);
for (let x = 0; x < CHUNK_SIZE; x++) {
this.blocks[to + x] = source[from + x] & ID_MASK;
this.blocks[to + x] = section.blocks[from + x] & ID_MASK;
}
}
}
@@ -62,18 +90,14 @@ export class LightRegion {
}
#compute_sky({ opacity }: LightTables) {
const { blocks, sky } = this;
sky.fill(0);
const { sky, height: region_height } = this;
sky.fill(0, 0, REGION_LAYER * region_height);
this.#queue_length = 0;
if (!this.sky_light) return;
// straight down from the top, until something isn't fully clear
// straight down from the top, to the sky height
for (let column = 0; column < REGION_LAYER; column++) {
let y = CHUNK_HEIGHT - 1;
while (y >= 0 && opacity[blocks[y * REGION_LAYER + column]] === 0) {
sky[y * REGION_LAYER + column] = 15;
y--;
}
this.#heights[column] = y + 1;
for (let y = this.#heights[column]; y < region_height; y++) sky[y * REGION_LAYER + column] = 15;
}
// only the lit cells next to a darker one can spread: the bottom of each column's sunlight,
@@ -89,7 +113,7 @@ export class LightRegion {
if (z < REGION_SIZE - 1) {
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]);
}
const top = Math.min(CHUNK_HEIGHT - 1, Math.max(height, highest_neighbor - 1));
const top = Math.min(region_height - 1, Math.max(height, highest_neighbor - 1));
for (let y = height; y <= top; y++) {
this.#push(y * REGION_LAYER + column);
}
@@ -101,10 +125,11 @@ export class LightRegion {
#compute_block_light({ opacity, emission }: LightTables) {
const { blocks, block_light } = this;
block_light.fill(0);
const volume = REGION_LAYER * this.height;
block_light.fill(0, 0, volume);
this.#queue_length = 0;
for (let i = 0; i < REGION_VOLUME; i++) {
for (let i = 0; i < volume; i++) {
const level = emission[blocks[i]];
if (level > 0) {
block_light[i] = level;
@@ -127,6 +152,7 @@ export class LightRegion {
// breadth first from everything queued. a cell can be queued again when a brighter path reaches it
#propagate(light: Uint8Array, opacity: Uint8Array, is_sky: boolean) {
const blocks = this.blocks;
const top = this.height - 1;
const spread = (to: number, level: number, down: boolean) => {
const block_opacity = opacity[blocks[to]];
@@ -150,7 +176,7 @@ export class LightRegion {
const x = rest - z * REGION_SIZE;
if (y > 0) spread(index - REGION_LAYER, level, true);
if (y < CHUNK_HEIGHT - 1) spread(index + REGION_LAYER, level, false);
if (y < top) spread(index + REGION_LAYER, level, false);
if (x > 0) spread(index - 1, level, false);
if (x < REGION_SIZE - 1) spread(index + 1, level, false);
if (z > 0) spread(index - REGION_SIZE, level, false);
@@ -162,18 +188,18 @@ export class LightRegion {
// what a cell looks like to the mesher, including above and below the world
export function region_block(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT) return AIR;
if (y >= region.height) return AIR;
if (y < 0) return REGION_VOID;
return region.blocks[index];
}
export function region_sky(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT) return 15;
if (y >= region.height) return region.sky_light ? 15 : 0;
if (y < 0) return 0;
return region.sky[index];
}
export function region_block_light(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT || y < 0) return 0;
if (y >= region.height || y < 0) return 0;
return region.block_light[index];
}
+129
View File
@@ -0,0 +1,129 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// which faces of a section can be seen through from which others, for occlusion culling (see
// client/rendering/occlusion.ts). worked out by the chunk workers as they mesh a section
// the 6 directions out of a section, and the faces they leave through, are a bit each: -x, +x, -y, +y, -z, +z. a
// direction's opposite is direction ^ 1
export const ALL_DIRECTIONS = 0b111111;
// a bit for each of the 15 pairs of different faces
const PAIR_BITS = new Uint16Array(36);
{
let bit = 0;
for (let a = 0; a < 6; a++) {
for (let b = a + 1; b < 6; b++) {
PAIR_BITS[a * 6 + b] = PAIR_BITS[b * 6 + a] = 1 << bit++;
}
}
}
// every face sees every other, like a section of air, or one that hasn't been meshed yet
export const ALL_VISIBLE = (1 << 15) - 1;
// the directions a section can be left in when it was entered through the faces in incoming
export function exits(visibility: number, incoming: number) {
// most sections are all air or all stone. entered through one face, all the others
if (visibility === ALL_VISIBLE) return incoming & (incoming - 1) ? ALL_DIRECTIONS : ALL_DIRECTIONS & ~incoming;
if (visibility === 0) return 0;
let out = 0;
for (let a = 0; a < 6; a++) {
if (!(incoming & (1 << a))) continue;
for (let b = 0; b < 6; b++) {
if (visibility & PAIR_BITS[a * 6 + b]) out |= 1 << b;
}
}
return out;
}
const unvisited = new Uint16Array(256);
const region = new Uint16Array(256);
// a section's visibility from the cells that can be seen through, by row (y << 4 | z, a bit per x). each connected
// region of them connects every pair of faces it touches. a region grows a row at a time, each row filled along its
// open runs at once, until it stops growing
export function section_visibility(open: Uint16Array) {
let count = 0;
for (let r = 0; r < 256; r++) count += bit_count(open[r]);
if (count === 4096) return ALL_VISIBLE;
if (count === 0) return 0;
unvisited.set(open);
let result = 0;
for (let start = 0; start < 256; start++) {
while (unvisited[start] !== 0) {
const seed = unvisited[start] & -unvisited[start];
region[start] = fill_row(seed, unvisited[start]);
let lo = start;
let hi = start;
let grown = true;
while (grown) {
grown = false;
const first = Math.max(0, lo - 16);
const last = Math.min(255, hi + 16);
// up then back down, so a region that winds back reaches its far end in fewer sweeps
for (let i = 0; i < 2 * (last - first + 1); i++) {
const r = i <= last - first ? first + i : last - (i - (last - first + 1));
let near = region[r];
if (r >= 16) near |= region[r - 16];
if (r < 240) near |= region[r + 16];
if (r & 15) near |= region[r - 1];
if ((r & 15) !== 15) near |= region[r + 1];
const reached = near & unvisited[r];
if (reached & ~region[r]) {
region[r] = fill_row(reached, unvisited[r]);
if (r < lo) lo = r;
if (r > hi) hi = r;
grown = true;
}
}
}
let faces = 0;
for (let r = lo; r <= hi; r++) {
const row = region[r];
if (row === 0) continue;
region[r] = 0;
unvisited[r] &= ~row;
const y = r >> 4;
const z = r & 15;
if (row & 1) faces |= 1;
if (row & 0x8000) faces |= 2;
if (y === 0) faces |= 4;
if (y === 15) faces |= 8;
if (z === 0) faces |= 16;
if (z === 15) faces |= 32;
}
// one region touching every face connects them all, nothing else can add to it
if (faces === ALL_DIRECTIONS) return ALL_VISIBLE;
for (let a = 0; a < 6; a++) {
for (let b = a + 1; b < 6; b++) {
if (faces & (1 << a) && faces & (1 << b)) result |= PAIR_BITS[a * 6 + b];
}
}
}
}
return result;
}
// the cells of open connected to seeds within a row, filling each way and doubling the reach at each step
function fill_row(seeds: number, open: number) {
let up = seeds;
let through_up = open;
let down = seeds;
let through_down = open;
for (let step = 1; step <= 8; step <<= 1) {
up |= through_up & (up << step);
through_up &= through_up << step;
down |= through_down & (down >> step);
through_down &= through_down >> step;
}
return up | down;
}
function bit_count(row: number) {
let count = 0;
for (; row; row &= row - 1) count++;
return count;
}
+108
View File
@@ -0,0 +1,108 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// binary messages and saves, written and read a number at a time. little-endian, which is what both use
export class Writer {
#bytes = new Uint8Array(16 * 1024);
#view = new DataView(this.#bytes.buffer);
#length = 0;
#reserve(size: number) {
if (this.#length + size <= this.#bytes.length) return;
const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size));
bytes.set(this.#bytes);
this.#bytes = bytes;
this.#view = new DataView(bytes.buffer);
}
u8(value: number) {
this.#reserve(1);
this.#bytes[this.#length++] = value;
}
u16(value: number) {
this.#reserve(2);
this.#view.setUint16(this.#length, value, true);
this.#length += 2;
}
i16(value: number) {
this.#reserve(2);
this.#view.setInt16(this.#length, value, true);
this.#length += 2;
}
u32(value: number) {
this.#reserve(4);
this.#view.setUint32(this.#length, value, true);
this.#length += 4;
}
// a u8 length, then the text as utf-8
string(text: string) {
const bytes = new TextEncoder().encode(text);
if (bytes.length > 255) throw new Error(`${text} is too long`);
this.u8(bytes.length);
this.#reserve(bytes.length);
this.#bytes.set(bytes, this.#length);
this.#length += bytes.length;
}
bytes() {
return this.#bytes.subarray(0, this.#length);
}
}
// throws when there's less left than what's read
export class Reader {
#bytes: Uint8Array;
#view: DataView;
#offset = 0;
// only old saves are big-endian
#little: boolean;
constructor(bytes: Uint8Array, little_endian = true) {
this.#bytes = bytes;
this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
this.#little = little_endian;
}
get done() {
return this.#offset === this.#bytes.length;
}
#take(size: number) {
if (this.#offset + size > this.#bytes.length) throw new Error("Too short");
const offset = this.#offset;
this.#offset += size;
return offset;
}
u8() {
return this.#bytes[this.#take(1)];
}
u16() {
return this.#view.getUint16(this.#take(2), this.#little);
}
i16() {
return this.#view.getInt16(this.#take(2), this.#little);
}
u32() {
return this.#view.getUint32(this.#take(4), this.#little);
}
string() {
const length = this.u8();
const offset = this.#take(length);
return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length));
}
// the next size bytes, not copied
take(size: number) {
const offset = this.#take(size);
return this.#bytes.subarray(offset, offset + size);
}
}
+12 -197
View File
@@ -4,24 +4,16 @@
// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each
// player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md
import { deflateSync, inflateSync } from "fflate";
import { CHUNK_AREA, CHUNK_HEIGHT } from "./constants.ts";
import { Reader, Writer } from "./bytes.ts";
import { type ChunkColumn, type ColumnBiomes, read_column, type Section, write_column } from "./section.ts";
// the view distances clients can ask for, in chunks, like minecraft's
export const MIN_VIEW_DISTANCE = 2;
export const MAX_VIEW_DISTANCE = 32;
export const SECTION_HEIGHT = 16;
const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT;
const SECTIONS = CHUNK_HEIGHT / SECTION_HEIGHT;
const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
// the first byte of a binary message, the only kind there is so far
export const LEVEL_CHUNK = 1;
// bits per block of a section's indirect palette, the smallest that fits. more than 256 kinds are stored directly
const PALETTE_BITS = [1, 2, 4, 8];
const DIRECT_BITS = 32;
// minecraft's ChunkTrackingView.isWithinDistance: a round view, with the ring of chunks around it (outer) that the
// client needs to mesh and light the edge of what it shows
export function is_within_view(
@@ -39,13 +31,14 @@ export function is_within_view(
return near * near + far * far < view_distance * view_distance;
}
// what a client reads a level_chunk as
export interface LevelChunk {
x: number;
z: number;
// block values (numeric id | state bits << 16) in the sender's numbering, y then z then x
blocks: Uint32Array;
// each column's biome, x then z
biomes: string[];
// block values (numeric id | state bits << 16) in the receiver's numbering, see decode_level_chunk. from the bottom
// of the world up, the dimension's whole height
sections: Section[];
biomes: ColumnBiomes;
}
// a level_chunk message, like minecraft's ClientboundLevelChunkWithLightPacket without the light (clients light
@@ -53,28 +46,10 @@ export interface LevelChunk {
//
// u8 LEVEL_CHUNK
// i32 chunk x, i32 chunk z
// the rest deflated:
// u16 biome palette size, then each biome: u8 length and the id as utf-8
// u8 each column's biome palette index, x then z. left out when there's one biome
// 16 sections of 16x16x16 blocks, bottom first, each a paletted container like minecraft's:
// u8 bits per block
// 0: u32 the value of every block
// 1, 2, 4, 8: u16 palette size, u32 each value, then each block's palette index packed from the low bits up
// 32: u32 each block's value
export function encode_level_chunk(chunk: LevelChunk): Uint8Array<ArrayBuffer> {
// the rest deflated: the sections' block values and biomes, see write_column in common/section.ts
export function encode_level_chunk(chunk: ChunkColumn): Uint8Array<ArrayBuffer> {
const writer = new Writer();
const biome_palette = [...new Set(chunk.biomes)];
writer.u16(biome_palette.length);
for (const biome of biome_palette) writer.string(biome);
if (biome_palette.length > 1) {
for (const biome of chunk.biomes) writer.u8(biome_palette.indexOf(biome));
}
for (let section = 0; section < SECTIONS; section++) {
write_section(writer, chunk.blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME));
}
write_column(writer, chunk.sections, chunk.biomes);
const body = deflateSync(writer.bytes());
const bytes = new Uint8Array(9 + body.length);
const view = new DataView(bytes.buffer);
@@ -85,39 +60,6 @@ export function encode_level_chunk(chunk: LevelChunk): Uint8Array<ArrayBuffer> {
return bytes;
}
function write_section(writer: Writer, blocks: Uint32Array) {
const palette: number[] = [];
const index_of = new Map<number, number>();
for (const value of blocks) {
if (!index_of.has(value)) {
index_of.set(value, palette.length);
palette.push(value);
}
}
if (palette.length === 1) {
writer.u8(0);
writer.u32(palette[0]);
return;
}
const bits = PALETTE_BITS.find((bits) => palette.length <= 1 << bits);
if (bits === undefined) {
writer.u8(DIRECT_BITS);
for (const value of blocks) writer.u32(value);
return;
}
writer.u8(bits);
writer.u16(palette.length);
for (const value of palette) writer.u32(value);
const per_byte = 8 / bits;
for (let i = 0; i < SECTION_VOLUME; i += per_byte) {
let byte = 0;
for (let j = 0; j < per_byte; j++) byte |= index_of.get(blocks[i + j])! << (j * bits);
writer.u8(byte);
}
}
// throws when the bytes aren't a level_chunk. map turns each block value into the receiver's numbering
export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => number = (value) => value): LevelChunk {
if (bytes[0] !== LEVEL_CHUNK || bytes.length < 9) throw new Error("Not a level_chunk");
@@ -125,134 +67,7 @@ export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => nu
const x = header.getInt32(1, true);
const z = header.getInt32(5, true);
const reader = new Reader(inflateSync(bytes.subarray(9)));
const biome_palette: string[] = [];
const biome_count = reader.u16();
if (biome_count === 0) throw new Error("No biomes");
for (let i = 0; i < biome_count; i++) biome_palette.push(reader.string());
const biomes: string[] = new Array(CHUNK_AREA);
for (let column = 0; column < CHUNK_AREA; column++) {
const index = biome_count > 1 ? reader.u8() : 0;
if (index >= biome_count) throw new Error("Bad biome index");
biomes[column] = biome_palette[index];
}
const blocks = new Uint32Array(CHUNK_VOLUME);
for (let section = 0; section < SECTIONS; section++) {
read_section(reader, blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME), map);
}
const { sections, biomes } = read_column(reader, map);
if (!reader.done) throw new Error("Wrong size");
return { x, z, blocks, biomes };
}
function read_section(reader: Reader, blocks: Uint32Array, map: (value: number) => number) {
const bits = reader.u8();
if (bits === 0) {
blocks.fill(map(reader.u32()));
return;
}
if (bits === DIRECT_BITS) {
for (let i = 0; i < SECTION_VOLUME; i++) blocks[i] = map(reader.u32());
return;
}
if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per block ${bits}`);
const palette: number[] = [];
const size = reader.u16();
if (size > 1 << bits) throw new Error("Bad palette");
for (let i = 0; i < size; i++) palette.push(map(reader.u32()));
const per_byte = 8 / bits;
const mask = (1 << bits) - 1;
for (let i = 0; i < SECTION_VOLUME; i += per_byte) {
const byte = reader.u8();
for (let j = 0; j < per_byte; j++) {
const index = (byte >> (j * bits)) & mask;
if (index >= size) throw new Error("Bad palette index");
blocks[i + j] = palette[index];
}
}
}
class Writer {
#bytes = new Uint8Array(16 * 1024);
#view = new DataView(this.#bytes.buffer);
#length = 0;
#reserve(size: number) {
if (this.#length + size <= this.#bytes.length) return;
const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size));
bytes.set(this.#bytes);
this.#bytes = bytes;
this.#view = new DataView(bytes.buffer);
}
u8(value: number) {
this.#reserve(1);
this.#bytes[this.#length++] = value;
}
u16(value: number) {
this.#reserve(2);
this.#view.setUint16(this.#length, value, true);
this.#length += 2;
}
u32(value: number) {
this.#reserve(4);
this.#view.setUint32(this.#length, value, true);
this.#length += 4;
}
string(text: string) {
const bytes = new TextEncoder().encode(text);
if (bytes.length > 255) throw new Error(`${text} is too long to send`);
this.u8(bytes.length);
this.#reserve(bytes.length);
this.#bytes.set(bytes, this.#length);
this.#length += bytes.length;
}
bytes() {
return this.#bytes.subarray(0, this.#length);
}
}
class Reader {
#bytes: Uint8Array;
#view: DataView;
#offset = 0;
constructor(bytes: Uint8Array) {
this.#bytes = bytes;
this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
}
get done() {
return this.#offset === this.#bytes.length;
}
#take(size: number) {
if (this.#offset + size > this.#bytes.length) throw new Error("Too short");
const offset = this.#offset;
this.#offset += size;
return offset;
}
u8() {
return this.#bytes[this.#take(1)];
}
u16() {
return this.#view.getUint16(this.#take(2), true);
}
u32() {
return this.#view.getUint32(this.#take(4), true);
}
string() {
const length = this.u8();
const offset = this.#take(length);
return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length));
}
return { x, z, sections, biomes };
}
+1 -1
View File
@@ -36,7 +36,7 @@ export const ID_MASK = 0xFFFF;
export const STATE_SHIFT = 16;
export const CHUNK_SIZE = 16;
export const CHUNK_HEIGHT = 256;
// how tall chunks are is up to their dimension, see common/world_shape.ts
// the top of oceans and rivers
export const SEA_LEVEL = 64;
export const CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
+13
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { TintColor } from "./worldgen/biome_colors.ts";
import { ID_MASK } from "./constants.ts";
import type { ItemStack } from "./inventory.ts";
import type { BlockPart, BlockVariant } from "./block_models.ts";
@@ -101,6 +102,18 @@ export function block_light_emission(block: BlockRegistry | undefined): number {
return block?.light_emission ?? 0;
}
// every block's light opacity and emission by numeric id, for lighting a lot of blocks at once. blocks is the blocks
// registry, with its gaps
export function light_tables(blocks: readonly (BlockRegistry | undefined)[]) {
const opacity = new Uint8Array(ID_MASK + 1);
const emission = new Uint8Array(ID_MASK + 1);
blocks.forEach((block, nid) => {
opacity[nid] = block_light_opacity(block);
emission[nid] = block_light_emission(block);
});
return { opacity, emission };
}
export interface BlockRegistry {
id: string;
// what players see, like "Iron Ore". made from the id when not set, see display_name in common/utils.ts
+43 -18
View File
@@ -4,10 +4,13 @@
// 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 { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { BIOME_CELL_HEIGHT, ChunkColumn } from "@/common/section.ts";
import type { FeatureChunk, Position } from "@/common/mod_api/worldgen.ts";
import type { OreJson } from "@/common/mod_data.ts";
import { generate_noise_chunk } from "./worldgen/noise_chunk.ts";
import { get_biome } from "./worldgen/biomes.ts";
import type { Generator } from "./worldgen/generator.ts";
import { named_noise_2d, named_noise_3d } from "./worldgen/noise.ts";
@@ -15,6 +18,8 @@ export { named_noise_2d, named_noise_3d };
// what mods add to generation, see docs/modding/worldgen/index.md
export interface WorldgenSetup {
// where the dimension's blocks are, chunks hold its whole height
shape: WorldShape;
// 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
@@ -29,22 +34,26 @@ export interface WorldgenSetup {
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
// a code feature's biomes: it only runs in chunks with one of them somewhere. data features check each position
// themselves
biomes?: Set<string>;
}
export interface RawChunk {
// numeric block ids, only what this chunk generated itself
blocks: Uint32Array;
// only what this chunk generated itself, with its biomes
column: ChunkColumn;
// blocks it generated in other chunks (from features like a mod's trees), flattened as x, y, z, numeric id
spills: Int32Array;
// each column's biome id, x then z
biomes: string[];
}
// features that threw, so each is only reported once
const failed_features = new Set<string>();
// what a chunk is generated into before it's made sections, indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x. a
// column at a time is how terrain is worked out, and features set blocks one at a time. kept for the next chunk, so
// generating isn't reentrant
let scratch = new Uint32Array(0);
// generates one chunk on its own. neighbors' spills get merged in by whoever assembles the world:
// a chunk's own blocks always win and spills only fill air, so the result doesn't depend on load order
export function generate_raw_chunk(
@@ -56,13 +65,16 @@ export function generate_raw_chunk(
// the value to store for each numeric id, with its default states. just the id when missing
default_values?: number[],
): RawChunk {
const blocks = new Uint32Array(CHUNK_SIZE * CHUNK_SIZE * CHUNK_HEIGHT);
const shape = worldgen.shape;
if (scratch.length !== shape.volume) scratch = new Uint32Array(shape.volume);
const blocks = scratch.fill(AIR);
const spills: number[] = [];
const heights = new Int32Array(CHUNK_AREA);
const biomes: string[] = new Array(CHUNK_AREA);
// a biome cell's, see column_biomes
const biomes: string[] = new Array(CHUNK_AREA * shape.height / BIOME_CELL_HEIGHT);
const set = (x: number, y: number, z: number, nid: number) => {
if (y < 0 || y >= CHUNK_HEIGHT) {
if (!shape.contains(y)) {
return;
}
nid = default_values?.[nid] ?? nid;
@@ -74,21 +86,21 @@ export function generate_raw_chunk(
}
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
blocks[y * CHUNK_AREA + lz * CHUNK_SIZE + lx] = nid;
blocks[(y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx] = nid;
};
const id = (name: string) => {
const nid = block_ids[name];
return nid === undefined ? AIR : default_values?.[nid] ?? nid;
};
generate_noise_chunk(blocks, heights, biomes, chunk_x, chunk_z, worldgen.generator.for_seed(seed), id);
generate_noise_chunk(blocks, heights, biomes, chunk_x, chunk_z, shape, worldgen.generator.for_seed(seed), id);
for (const ores of worldgen.ores) {
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, ores, default_values);
generate_ores(blocks, chunk_x, chunk_z, shape, 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 };
return { column: ChunkColumn.from_flat(chunk_x, chunk_z, shape, blocks, biomes), spills: new Int32Array(spills) };
}
// each block an ore replaces becomes the first ore whose noise is above its threshold
@@ -96,6 +108,7 @@ function generate_ores(
blocks: Uint32Array,
chunk_x: number,
chunk_z: number,
shape: WorldShape,
seed: string,
block_ids: Record<string, number>,
ores: OreJson[],
@@ -109,10 +122,10 @@ function generate_ores(
}
const noises = usable.map((ore) => named_noise_3d(seed, ore.id));
for (let y = 0; y < CHUNK_HEIGHT; y++) {
for (let y = shape.min_y; y < shape.max_y; y++) {
for (let lz = 0; lz < CHUNK_SIZE; lz++) {
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
const index = (y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx;
const current = blocks[index] & ID_MASK;
if (current === AIR) {
continue;
@@ -145,11 +158,17 @@ function generate_features(
block_ids: Record<string, number>,
worldgen: WorldgenSetup,
) {
const shape = worldgen.shape;
const ids_by_nid: string[] = [];
for (const [id, nid] of Object.entries(block_ids)) {
ids_by_nid[nid] = id;
}
// the cell of biomes a y is in, the top or bottom one past the world's height
const cell = (y: number) => {
const clamped = Math.min(Math.max(y, shape.min_y), shape.max_y - 1);
return Math.floor((clamped - shape.min_y) / BIOME_CELL_HEIGHT) * CHUNK_AREA;
};
const local = (x: number, z: number, what: string) => {
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
@@ -166,17 +185,23 @@ function generate_features(
x: chunk_x,
z: chunk_z,
seed,
min_y: shape.min_y,
max_y: shape.max_y,
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")],
biome_at: (x, z) => biomes[local(x, z, "biome_at")],
biome_at: (x, y, z) => biomes[cell(y) + local(x, z, "biome_at")],
set_biome(x, y, z, biome) {
if (!get_biome(biome)) throw new Error(`set_biome: ${biome} isn't a biome`);
if (shape.contains(y)) biomes[cell(y) + local(x, z, "set_biome")] = biome;
},
get_block(x, y, z) {
if (y < 0 || y >= CHUNK_HEIGHT) {
if (!shape.contains(y)) {
return undefined;
}
const nid = blocks[y * CHUNK_AREA + local(x, z, "get_block")] & ID_MASK;
const nid = blocks[(y - shape.min_y) * CHUNK_AREA + local(x, z, "get_block")] & ID_MASK;
return nid === AIR ? "cubi:air" : ids_by_nid[nid];
},
set_block(x, y, z, id) {
+6 -3
View File
@@ -55,9 +55,12 @@ export interface ClientContext {
// a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy.
// undefined when it isn't set or the chunk isn't loaded
get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined;
// the column's biome and its season, undefined when the chunk isn't loaded
biome_at(x: number, z: number): Id | undefined;
season_at(x: number, z: number): Season | undefined;
// the biome at a block and its season, like the server's. undefined when the chunk isn't loaded
biome_at(x: number, y: number, z: number): Id | undefined;
season_at(x: number, y: number, z: number): Season | undefined;
// the dimension's blocks go from min_y up to max_y - 1
readonly min_y: number;
readonly max_y: number;
// ticks since 06:00 of day 1, see ServerWorld.time
readonly time: number;
};
+8 -4
View File
@@ -70,7 +70,7 @@ export interface BlockRef {
readonly x: number;
readonly y: number;
readonly z: number;
// the biome of its column and that biome's season, see ServerWorld.biome_at
// the biome at the block and that biome's season, see ServerWorld.biome_at
readonly biome: Id;
readonly season: Season;
// tile data, any json value. saved with the world, never sent to clients
@@ -358,10 +358,14 @@ export interface ServerWorld {
// whether the chunk the column is in was ever generated, so reading its blocks generates nothing. for code that
// reaches far, like a walk along something long, which can stop at the rest: nobody has built anything there
is_loaded(x: number, z: number): boolean;
// the column's biome, like "bworld:plains", and that biome's season. in chunks that aren't loaded it's what
// the biome at a block, like "bworld:plains", and that biome's season, like neoforge's level.getBiome(pos). one per
// block across and every 4 blocks up, see docs/modding/worldgen/biomes.md. in chunks that aren't loaded it's what
// generation makes there, which takes a while the first time
biome_at(x: number, z: number): Id;
season_at(x: number, z: number): Season;
biome_at(x: number, y: number, z: number): Id;
season_at(x: number, y: number, z: number): Season;
// the dimension's blocks go from min_y up to max_y - 1. outside them get_block is air and nothing can be placed
readonly min_y: number;
readonly max_y: number;
readonly seed: string;
// ticks since 06:00 of day 1. a day is 36000 ticks (06:00 to 18:00), a night 12000
readonly time: number;
+4 -3
View File
@@ -198,9 +198,10 @@ export interface SharedWorld {
// whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision
// shape covers the whole face. false for air, plants, water and the sides of a slab
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
// the column's biome, like "bworld:plains", and that biome's season. undefined when the chunk isn't loaded
biome_at(x: number, z: number): Id | undefined;
season_at(x: number, z: number): Season | undefined;
// the biome at a block, like "bworld:plains", and that biome's season, like neoforge's level.getBiome(pos). one per
// block across and every 4 blocks up, see docs/modding/worldgen/biomes.md. undefined when the chunk isn't loaded
biome_at(x: number, y: number, z: number): Id | undefined;
season_at(x: number, y: number, z: number): Season | undefined;
}
// a block in the world, for rules
+12 -4
View File
@@ -38,7 +38,7 @@ export type FeatureStep =
export interface FeatureOptions {
step?: FeatureStep;
// only runs in chunks with one of these biomes
// only runs in chunks with one of these biomes somewhere, at any height
biomes?: Id | Id[];
}
@@ -54,6 +54,10 @@ export interface FeatureChunk {
readonly x: number;
readonly z: number;
readonly seed: string;
// the dimension's blocks go from min_y up to max_y - 1, get_block is undefined outside them and set_block does
// nothing
readonly min_y: number;
readonly max_y: number;
// 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
@@ -62,9 +66,14 @@ export interface FeatureChunk {
// 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;
// surface height and biome, inside this chunk only
// the column's surface height, inside this chunk only
height_at(x: number, z: number): number;
biome_at(x: number, z: number): Id;
// the biome at a block, like neoforge's level.getBiome(pos), inside this chunk only. biomes are one per block
// across and one every 4 blocks up, see docs/modding/worldgen/biomes.md. above and below the world it's the one at
// its top or bottom
biome_at(x: number, y: number, z: number): Id;
// sets the biome of the 4 blocks tall cell y is in, inside this chunk only. nothing outside the world's height
set_biome(x: number, y: number, z: number, biome: Id): void;
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
@@ -73,5 +82,4 @@ export interface FeatureChunk {
export interface TerrainChunk extends FeatureChunk {
set_height(x: number, z: number, height: number): void;
set_biome(x: number, z: number, biome: Id): void;
}
+10 -1
View File
@@ -29,15 +29,18 @@ import {
type BiomeSourceJson,
density_function_refs,
type DensityFunctionJson,
dimension_shape,
type DimensionJson,
new_refs,
noise_refs,
noise_settings_refs,
type NoiseJson,
type NoiseSettingsJson,
RULE_NAMES,
type WorldgenRefs,
} from "./worldgen/data.ts";
import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
import { cell_height_problem } from "./world_shape.ts";
import type { ModData } from "./mod_loader.ts";
export interface ModReport {
@@ -422,6 +425,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (!worldgen_owners["noise settings"].has(json.generator)) {
errors.push(`${file}: noise settings ${json.generator} doesn't exist`);
}
const settings = all_noise_settings.find((settings) => settings.id === json.generator);
const problem = settings && cell_height_problem(
dimension_shape(json),
[settings.terrain.cell_height, settings.caves.cell_height],
);
if (problem) errors.push(`${file}: can't be generated by ${json.generator}: ${problem}`);
if (json.default && defaults.length > 1) {
errors.push(
`${file}: only one dimension can be the default, and these all are: ${defaults.join(", ")}`,
@@ -435,7 +444,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
// 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"]);
const names = new Set([...Object.keys(settings.climate), ...RULE_NAMES]);
for (const rule of json.rules) {
for (const name of Object.keys(rule.when ?? {})) {
if (!names.has(name)) {
+4 -1
View File
@@ -6,12 +6,13 @@ import type { Faces } from "./constants.ts";
import type { ItemData } from "./inventory.ts";
import type { FluidVariant } from "./mod_api/shared.ts";
import type { ModListing } from "./mod_loader.ts";
import type { WorldShapeJson } from "./world_shape.ts";
export const AIR_ID = "cubi:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 26;
export const PROTOCOL_VERSION = 28;
export interface PlayerInfo {
id: string;
@@ -189,6 +190,8 @@ export type ServerMessage =
entities: EntityInfo[];
// the server's block id for each of its numeric ids, which level_chunk uses. clients number blocks their own way
blocks: string[];
// the dimension's height and sky light, every level_chunk holds all of its height
shape: WorldShapeJson;
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
selected_slot: number;
// the slots mods added to menu 0, from PLAYER_MENU_EXTRA on, see ctx.menus.extend_player_menu
+398
View File
@@ -0,0 +1,398 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// a chunk's blocks in sections of 16x16x16, from the bottom of its dimension up, like minecraft's LevelChunkSection. a
// section that's all one block keeps just that value: most of a tall column is air above the ground and stone under it
import { AIR, CHUNK_AREA, ID_MASK } from "./constants.ts";
import type { Reader, Writer } from "./bytes.ts";
import { HIGHEST_Y, LOWEST_Y, SECTION_HEIGHT, type WorldShape } from "./world_shape.ts";
export const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT;
// a block's place in its section, y then z then x like a chunk's layers. world coordinates work as they are, since
// sections start at multiples of 16
export function section_index(x: number, y: number, z: number) {
return ((y & 15) << 8) | ((z & 15) << 4) | (x & 15);
}
// what a section is made of, a block value or every block's, what's sent to and from workers
export type SectionData = number | Uint32Array;
export class Section {
// the block, while blocks is null
value: number;
// every block's value, once they differ
blocks: Uint32Array | null;
constructor(data: SectionData) {
this.value = typeof data === "number" ? data : 0;
this.blocks = typeof data === "number" ? null : data;
}
// a copy of values, one value when they're all the same
static of(values: Uint32Array): Section {
const first = values[0];
for (let i = 1; i < values.length; i++) {
if (values[i] !== first) return new Section(values.slice());
}
return new Section(first);
}
get data(): SectionData {
return this.blocks ?? this.value;
}
get(index: number): number {
return this.blocks === null ? this.value : this.blocks[index];
}
set(index: number, value: number) {
if (this.blocks === null) {
if (value === this.value) return;
this.blocks = new Uint32Array(SECTION_VOLUME).fill(this.value);
}
this.blocks[index] = value;
}
}
// biomes are one per block across, and one every BIOME_CELL_HEIGHT blocks up: a cell
export const BIOME_CELL_HEIGHT = 4;
export const SECTION_BIOMES = CHUNK_AREA * SECTION_HEIGHT / BIOME_CELL_HEIGHT;
// a column's biome palette can't be longer, since a cell's index in it is a byte
export const MAX_COLUMN_BIOMES = 256;
// a biome cell's place in its section's biomes: its layer of cells, then z, then x
export function biome_index(x: number, y: number, z: number) {
return (((y & 15) >> 2) << 8) | ((z & 15) << 4) | (x & 15);
}
// a section's biomes: one index into its column's biome palette for all of it, or SECTION_BIOMES of them. an array is
// never changed once it's made, see ChunkColumn.set_biome, so sections with the same biomes can share one: most of a
// column's when biomes don't change with height
export type SectionBiomes = number | Uint8Array;
// a chunk's biomes
export interface ColumnBiomes {
// every biome in it, at most MAX_COLUMN_BIOMES
palette: string[];
// by section from the bottom up, like its blocks
sections: SectionBiomes[];
}
// biomes from each cell's biome id, a layer of cells at a time from the bottom of the world up, then z, then x. or
// CHUNK_AREA of them, each column's biome all the way up. count is how many sections there are
export function column_biomes(cells: string[], count: number): ColumnBiomes {
const palette: string[] = [];
const indexes = new Map<string, number>();
const sections: SectionBiomes[] = [];
const section = new Uint8Array(SECTION_BIOMES);
// runs of the same biome are common, it's only looked up when it changes
let last: string | undefined;
let last_index = 0;
for (let s = 0; s < count; s++) {
let same = true;
for (let i = 0; i < SECTION_BIOMES; i++) {
const biome = cells[cells.length === CHUNK_AREA ? i & 255 : s * SECTION_BIOMES + i];
if (biome !== last) {
last = biome;
let index = indexes.get(biome);
if (index === undefined) {
if (palette.length === MAX_COLUMN_BIOMES) throw new Error(`More than ${MAX_COLUMN_BIOMES} biomes`);
index = palette.push(biome) - 1;
indexes.set(biome, index);
}
last_index = index;
}
section[i] = last_index;
if (last_index !== section[0]) same = false;
}
sections.push(same ? section[0] : section.slice());
}
share_same(sections);
return { palette, sections };
}
// sections whose biomes are the same as the one below's share its array
function share_same(sections: SectionBiomes[]) {
for (let s = 1; s < sections.length; s++) {
const below = sections[s - 1];
const here = sections[s];
if (typeof below === "number" || typeof here === "number" || below === here) continue;
let i = 0;
while (i < SECTION_BIOMES && below[i] === here[i]) i++;
if (i === SECTION_BIOMES) sections[s] = below;
}
}
// the biome at world coordinates in a chunk's biomes, see ChunkColumn.biome_at
export function biome_in(biomes: ColumnBiomes, shape: WorldShape, x: number, y: number, z: number): string {
y = Math.min(Math.max(y, shape.min_y), shape.max_y - 1);
const section = biomes.sections[(y - shape.min_y) >> 4];
return biomes.palette[typeof section === "number" ? section : section[biome_index(x, y, z)]];
}
// a chunk's blocks and biomes, its dimension's whole height
export class ChunkColumn {
readonly x: number;
readonly z: number;
readonly shape: WorldShape;
// from min_y up
readonly sections: Section[];
readonly biomes: ColumnBiomes;
constructor(x: number, z: number, shape: WorldShape, sections: Section[], biomes: ColumnBiomes) {
if (sections.length * SECTION_HEIGHT !== shape.height || biomes.sections.length !== sections.length) {
throw new Error(`Chunk ${x}, ${z} has ${sections.length} sections, its dimension ${shape.height / 16}`);
}
this.x = x;
this.z = z;
this.shape = shape;
this.sections = sections;
this.biomes = biomes;
}
// from every block's value in one array, y from min_y then z then x, which is copied, and the biomes of its cells,
// see column_biomes
static from_flat(x: number, z: number, shape: WorldShape, blocks: Uint32Array, biomes: string[]): ChunkColumn {
const sections: Section[] = [];
for (let start = 0; start < blocks.length; start += SECTION_VOLUME) {
sections.push(Section.of(blocks.subarray(start, start + SECTION_VOLUME)));
}
return new ChunkColumn(x, z, shape, sections, column_biomes(biomes, sections.length));
}
// the biome at world coordinates. above and below the dimension it's the one at its top or bottom
biome_at(x: number, y: number, z: number): string {
return biome_in(this.biomes, this.shape, x, y, z);
}
// sets the biome of the cell y is in. does nothing outside the dimension's height
set_biome(x: number, y: number, z: number, biome: string) {
if (!this.shape.contains(y)) return;
const { palette, sections } = this.biomes;
let index = palette.indexOf(biome);
if (index === -1) {
if (palette.length === MAX_COLUMN_BIOMES) {
throw new Error(`More than ${MAX_COLUMN_BIOMES} biomes in a chunk`);
}
index = palette.push(biome) - 1;
}
const s = (y - this.shape.min_y) >> 4;
const section = sections[s];
if (section === index) return;
// a copy, since other sections and other chunks' copies can share the array
const changed = typeof section === "number" ? new Uint8Array(SECTION_BIOMES).fill(section) : section.slice();
changed[biome_index(x, y, z)] = index;
sections[s] = changed;
}
// the block value at world coordinates, air outside the dimension's height
get(x: number, y: number, z: number): number {
if (!this.shape.contains(y)) return AIR;
return this.sections[(y - this.shape.min_y) >> 4].get(section_index(x, y, z));
}
// does nothing outside the dimension's height
set(x: number, y: number, z: number, value: number) {
if (!this.shape.contains(y)) return;
this.sections[(y - this.shape.min_y) >> 4].set(section_index(x, y, z), value);
}
clone(): ChunkColumn {
const sections = this.sections.map((section) => new Section(section.blocks?.slice() ?? section.value));
// the sections' biome arrays are never changed, so they can be shared
const biomes = { palette: [...this.biomes.palette], sections: [...this.biomes.sections] };
return new ChunkColumn(this.x, this.z, this.shape, sections, biomes);
}
// every block's value in one array, like from_flat's
to_flat(): Uint32Array {
return to_flat(this.sections);
}
}
export function to_flat(sections: Section[]): Uint32Array {
const blocks = new Uint32Array(sections.length * SECTION_VOLUME);
sections.forEach((section, i) => {
if (section.blocks) blocks.set(section.blocks, i * SECTION_VOLUME);
else blocks.fill(section.value, i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME);
});
return blocks;
}
// bits per value of a paletted container's palette, the smallest that fits. more than 256 kinds are written whole
const PALETTE_BITS = [1, 2, 4, 8];
const DIRECT_BITS = 32;
// a column's sections and biomes, as level_chunk and saved chunks hold them (see common/chunk_streaming.ts and
// server/game/saves.ts). the network sends block values, a save the index of each block in its own palette:
//
// u16 biome palette size, then each biome: u8 length and the id as utf-8
// u16 how many sections there are
// each section, bottom first:
// its 16x16x16 blocks, a paletted container of their values
// its biome cells (see biome_index), a paletted container of their biome palette indexes
//
// a paletted container, like minecraft's:
// u8 bits per value
// 0: u32 every value
// 1, 2, 4, 8: u16 palette size, u32 each value, then each one's palette index packed from the low bits up
// 32: u32 each value
export function write_column(writer: Writer, sections: Section[], biomes: ColumnBiomes) {
if (biomes.sections.length !== sections.length || biomes.palette.length > MAX_COLUMN_BIOMES) {
throw new Error("Bad biomes");
}
writer.u16(biomes.palette.length);
for (const biome of biomes.palette) writer.string(biome);
writer.u16(sections.length);
sections.forEach((section, i) => {
write_paletted(writer, section.blocks ?? section.value);
write_paletted(writer, biomes.sections[i]);
});
}
function write_paletted(writer: Writer, values: number | Uint32Array | Uint8Array) {
if (typeof values === "number") {
writer.u8(0);
writer.u32(values);
return;
}
// each value's palette index. runs of the same value are common, so it's looked up when the value changes
const indexes = new Uint16Array(values.length);
const palette: number[] = [];
const index_of = new Map<number, number>();
let last_value = values[0] + 1;
let last_index = 0;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (value !== last_value) {
last_value = value;
let index = index_of.get(value);
if (index === undefined) {
index = palette.push(value) - 1;
index_of.set(value, index);
}
last_index = index;
}
indexes[i] = last_index;
}
if (palette.length === 1) {
writer.u8(0);
writer.u32(palette[0]);
return;
}
const bits = PALETTE_BITS.find((bits) => palette.length <= 1 << bits);
if (bits === undefined) {
writer.u8(DIRECT_BITS);
for (const value of values) writer.u32(value);
return;
}
writer.u8(bits);
writer.u16(palette.length);
for (const value of palette) writer.u32(value);
const per_byte = 8 / bits;
for (let i = 0; i < values.length; i += per_byte) {
let byte = 0;
for (let j = 0; j < per_byte; j++) byte |= indexes[i + j] << (j * bits);
writer.u8(byte);
}
}
// throws when it isn't what write_column writes. map turns each block value read into what the sections hold, and can
// throw for a value that's wrong. flat_biomes reads what came before biomes had heights (format 3 saves): after the
// biome palette, a u8 palette index per column (x then z) when there's more than one, and sections of blocks alone
export function read_column(
reader: Reader,
map: (value: number) => number,
flat_biomes = false,
): { sections: Section[]; biomes: ColumnBiomes } {
const palette: string[] = [];
const palette_size = reader.u16();
if (palette_size === 0 || palette_size > MAX_COLUMN_BIOMES) throw new Error("Bad biome palette");
for (let i = 0; i < palette_size; i++) palette.push(reader.string());
const biome = (index: number) => {
if (index >= palette_size) throw new Error("Bad biome index");
return index;
};
let columns: string[] | undefined;
if (flat_biomes) {
columns = Array.from({ length: CHUNK_AREA }, () => palette[palette_size > 1 ? biome(reader.u8()) : 0]);
}
const count = reader.u16();
if (count * SECTION_HEIGHT > HIGHEST_Y - LOWEST_Y) throw new Error(`Too many sections, ${count}`);
const sections: Section[] = [];
const cells: SectionBiomes[] = [];
for (let i = 0; i < count; i++) {
sections.push(new Section(read_paletted(reader, new Uint32Array(SECTION_VOLUME), map)));
if (!flat_biomes) cells.push(read_paletted(reader, new Uint8Array(SECTION_BIOMES), biome));
}
share_same(cells);
return { sections, biomes: columns ? column_biomes(columns, count) : { palette, sections: cells } };
}
// into values, unless they're all one, which is returned instead
function read_paletted<T extends Uint32Array | Uint8Array>(
reader: Reader,
values: T,
map: (value: number) => number,
): number | T {
const bits = reader.u8();
if (bits === 0) return map(reader.u32());
if (bits === DIRECT_BITS) {
for (let i = 0; i < values.length; i++) values[i] = map(reader.u32());
return values;
}
if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per value ${bits}`);
const palette: number[] = [];
const size = reader.u16();
if (size > 1 << bits) throw new Error("Bad palette");
for (let i = 0; i < size; i++) palette.push(map(reader.u32()));
const per_byte = 8 / bits;
const mask = (1 << bits) - 1;
for (let i = 0; i < values.length; i += per_byte) {
const byte = reader.u8();
for (let j = 0; j < per_byte; j++) {
const index = (byte >> (j * bits)) & mask;
if (index >= size) throw new Error("Bad palette index");
values[i + j] = palette[index];
}
}
return values;
}
// per column of a chunk (z * 16 + x), the highest y that isn't air, min_y - 1 for an empty one, then the lowest y with
// nothing above it that stops light, where sky light is 15 (see light_at in server/game/world.ts). opacity is by
// numeric id. sections that are all air, or all clear, are passed over whole
export function column_heights(column: ChunkColumn, opacity: Uint8Array): Int16Array {
const heights = new Int16Array(CHUNK_AREA * 2);
const { sections, shape } = column;
for (let c = 0; c < CHUNK_AREA; c++) {
// from the top, by y above min_y
let y = shape.height - 1;
while (y >= 0) {
const section = sections[y >> 4];
if (section.blocks === null && (section.value & ID_MASK) === AIR) {
y = (y & ~15) - 1;
continue;
}
if ((section.get(((y & 15) << 8) | c) & ID_MASK) !== AIR) break;
y--;
}
heights[c] = shape.min_y + y;
while (y >= 0) {
const section = sections[y >> 4];
if (section.blocks === null && opacity[section.value & ID_MASK] === 0) {
y = (y & ~15) - 1;
continue;
}
if (opacity[section.get(((y & 15) << 8) | c) & ID_MASK] !== 0) break;
y--;
}
heights[CHUNK_AREA + c] = shape.min_y + y + 1;
}
return heights;
}
+80
View File
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// a dimension's shape: where its blocks start and stop going up, and whether light comes from the sky. it comes from
// the dimension's json (see DimensionJson) and travels with what needs it, the world, generation and the client's
// level, so nothing reads a height of its own
import { CHUNK_AREA } from "./constants.ts";
// the sizes a shape can have, so every y fits in an Int16Array
export const LOWEST_Y = -2048;
export const HIGHEST_Y = 2048;
export const SECTION_HEIGHT = 16;
// what's sent and saved of it
export interface WorldShapeJson {
min_y: number;
max_y: number;
sky_light: boolean;
}
// blocks go from min_y up to max_y, not included. both are multiples of SECTION_HEIGHT
export class WorldShape implements WorldShapeJson {
readonly min_y: number;
readonly max_y: number;
// without it, sky light is 0 everywhere and only blocks give off light
readonly sky_light: boolean;
// throws when it isn't a shape a dimension can have, see shape_problem
constructor({ min_y, max_y, sky_light }: WorldShapeJson) {
const problem = shape_problem(min_y, max_y);
if (problem) throw new Error(problem);
this.min_y = min_y;
this.max_y = max_y;
this.sky_light = sky_light;
}
get height() {
return this.max_y - this.min_y;
}
// how many blocks a chunk of it holds
get volume() {
return CHUNK_AREA * this.height;
}
contains(y: number) {
return y >= this.min_y && y < this.max_y;
}
// sky and block light, packed as block << 4 | sky, above the world and where nothing has lit yet
get open_light() {
return this.sky_light ? 15 : 0;
}
}
// what a dimension gets when its json doesn't say
export const DEFAULT_SHAPE = new WorldShape({ min_y: 0, max_y: 256, sky_light: true });
// why min_y and max_y can't be a dimension's, undefined when they can
export function shape_problem(min_y: number, max_y: number): string | undefined {
if (!Number.isInteger(min_y) || !Number.isInteger(max_y)) return `min_y and max_y must be whole numbers`;
if (min_y % SECTION_HEIGHT !== 0 || max_y % SECTION_HEIGHT !== 0) {
return `min_y ${min_y} and max_y ${max_y} must be multiples of ${SECTION_HEIGHT}`;
}
if (max_y - min_y < SECTION_HEIGHT) return `max_y ${max_y} must be at least ${SECTION_HEIGHT} above min_y ${min_y}`;
if (min_y < LOWEST_Y || max_y > HIGHEST_Y) return `the world has to fit in ${LOWEST_Y} to ${HIGHEST_Y}`;
return undefined;
}
// why a generator can't fill the shape, undefined when it can: its density is sampled every cell_height blocks up from
// min_y, so the cells have to fit the world exactly
export function cell_height_problem(shape: WorldShapeJson, cell_heights: number[]): string | undefined {
for (const cell_height of cell_heights) {
if (shape.min_y % cell_height !== 0 || shape.max_y % cell_height !== 0) {
return `its min_y ${shape.min_y} and max_y ${shape.max_y} must be multiples of the generator's ` +
`cell_height ${cell_height}`;
}
}
return undefined;
}
+32 -5
View File
@@ -6,6 +6,7 @@
// minecraft's (density functions, the noise router, surface rules) where the idea is the same
import * as z from "zod";
import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts";
import { DEFAULT_SHAPE, HIGHEST_Y, LOWEST_Y, shape_problem, WorldShape } from "../world_shape.ts";
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
@@ -124,12 +125,18 @@ 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
// every condition holds: a range of a climate value from the noise settings, or of one of RULE_VALUES, or "steep":
// true or false. no conditions always holds
when?: Record<string, RangeJson | boolean>;
biome: string;
}
// what biome rules look at besides a generator's climate, so its climate values can't be named these: the ground's y,
// a biome cell's lowest y and how far that is below the ground (0 at the ground, negative above it)
export const RULE_VALUES = ["surface", "y", "depth"];
// whether a column is steep, see NoiseSettingsJson.steep
export const RULE_NAMES = [...RULE_VALUES, "steep"];
// dimensions: a world to play and the noise settings that generate it, like neoforge's level stems. the world plays the
// one with "default": true, and only one loaded mod can have one
@@ -138,6 +145,20 @@ export interface DimensionJson {
// the noise settings that generate it
generator: string;
default?: boolean;
// its blocks go from min_y up to max_y - 1, see WorldShape. 0 and 256 when not set
min_y?: number;
max_y?: number;
// whether light comes from the sky, true when not set
sky_light?: boolean;
}
// the shape a dimension's json gives it
export function dimension_shape(json: DimensionJson): WorldShape {
return new WorldShape({
min_y: json.min_y ?? DEFAULT_SHAPE.min_y,
max_y: json.max_y ?? DEFAULT_SHAPE.max_y,
sky_light: json.sky_light ?? DEFAULT_SHAPE.sky_light,
});
}
// what worldgen data refers to, for checking it all exists
@@ -271,15 +292,15 @@ const cell_height = z.literal([1, 2, 4, 8, 16, 32]);
const noise_settings_schema: z.ZodType<NoiseSettingsJson> = z.object({
id: worldgen_id,
sea_level: z.int().min(0).max(256),
sea_level: z.int().min(LOWEST_Y).max(HIGHEST_Y),
default_block: block_id,
cell_width: z.literal([1, 2, 4, 8, 16]),
terrain: z.object({ density, cell_height }),
caves: z.object({ density, cell_height }),
preliminary_surface: density,
climate: z.record(
z.string("isn't a name a climate value can have: lowercase letters and _, but not surface or steep")
.regex(/^[a-z_]+$/).refine((name) => name !== "surface" && name !== "steep"),
z.string(`isn't a name a climate value can have: lowercase letters and _, but not ${RULE_NAMES.join(", ")}`)
.regex(/^[a-z_]+$/).refine((name) => !RULE_NAMES.includes(name)),
density,
),
steep: z.number().min(0),
@@ -327,6 +348,12 @@ const dimension_schema: z.ZodType<DimensionJson> = z.strictObject({
id: worldgen_id,
generator: z.string("must be a noise settings' id").regex(WORLDGEN_ID_PATTERN),
default: z.boolean().optional(),
min_y: z.int().optional(),
max_y: z.int().optional(),
sky_light: z.boolean().optional(),
}).superRefine((json, ctx) => {
const problem = shape_problem(json.min_y ?? DEFAULT_SHAPE.min_y, json.max_y ?? DEFAULT_SHAPE.max_y);
if (problem) ctx.addIssue({ code: "custom", message: problem });
});
export function validate_noise(json: unknown): Problems {
+19 -20
View File
@@ -6,7 +6,7 @@
// 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 { CHUNK_SIZE } from "../constants.ts";
import * as z from "zod";
import {
add_problems,
@@ -46,7 +46,7 @@ export interface FeatureJson {
type: string;
config?: Record<string, unknown>;
placement?: PlacementJson[];
// only where the column is one of these biomes
// only where the biome at the position is one of these
biomes?: string | string[];
step?: FeatureStep;
}
@@ -233,7 +233,8 @@ export function compile_feature(
for (const position of positions) {
if (
biomes &&
!(inside(chunk, position.x, position.z) && biomes.has(chunk.biome_at(position.x, position.z)))
!(inside(chunk, position.x, position.z) &&
biomes.has(chunk.biome_at(position.x, position.y, position.z)))
) {
continue;
}
@@ -371,8 +372,8 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
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--;
let y = chunk.max_y - 1;
while (y >= chunk.min_y && !counts_for_heightmap(chunk.get_block(p.x, y, p.z), floor)) y--;
return [{ x: p.x, y: y + 1, z: p.z }];
});
},
@@ -457,7 +458,7 @@ function block_predicate(json: unknown): Predicate {
// 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;
if (y < chunk.min_y || y >= chunk.max_y) return false;
const below = block_at(chunk, x, y - 1, z);
return below !== undefined && can_stand_on(EverythingRegistry.get<BlockRegistry>("blocks", id), below);
}
@@ -518,24 +519,22 @@ function int_provider(json: unknown): IntProvider {
// heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor }
// or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor }
function anchor(json: unknown): number {
// the bottom and top are the chunk's dimension's
function anchor(json: unknown): IntProvider {
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;
if (object.absolute !== undefined) return () => object.absolute;
if (object.above_bottom !== undefined) return (chunk) => chunk.min_y + object.above_bottom;
return (chunk) => chunk.max_y - 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;
}
if (object.type === undefined) return anchor(object);
if (builtin_name(String(object.type)) === "constant") return anchor(object.value);
const min = anchor(object.min_inclusive);
const span = anchor(object.max_inclusive) - min + 1;
return (chunk) => min + Math.floor(chunk.rng.next() * span);
const max = anchor(object.max_inclusive);
return (chunk) => {
const low = min(chunk);
return low + Math.floor(chunk.rng.next() * (max(chunk) - low + 1));
};
}
+9 -2
View File
@@ -4,7 +4,14 @@
// a generator: noise settings, and the density functions, noises and biome rules it uses. compiled once for each
// seed, see NoiseTerrain. 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 BiomeRuleJson,
type BiomeSourceJson,
type DensityFunctionJson,
type NoiseJson,
type NoiseSettingsJson,
RULE_NAMES,
} from "./data.ts";
import type { DensitySources } from "./density.ts";
import { NoiseTerrain } from "./terrain.ts";
@@ -75,7 +82,7 @@ function merge_rules(settings: NoiseSettingsJson, sources: BiomeSourceJson[]): B
rules.splice(rule.before ? at : at + 1, 0, rule);
}
}
const names = new Set([...Object.keys(settings.climate), "surface", "steep"]);
const names = new Set([...Object.keys(settings.climate), ...RULE_NAMES]);
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}`);
+33 -18
View File
@@ -5,7 +5,9 @@
// 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 NoiseTerrain 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 { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { BIOME_CELL_HEIGHT } from "@/common/section.ts";
import { get_biome } from "./biomes.ts";
import type { NoiseTerrain, TerrainColumn } from "./terrain.ts";
import {
@@ -16,14 +18,16 @@ import {
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
// fills blocks (indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x), each column's surface height and each biome
// cell's biome (indexed like blocks, a layer of cells at a time, see column_biomes). block is a block's numeric id with
// its default states
export function generate_noise_chunk(
blocks: Uint32Array,
heights: Int32Array,
biomes: string[],
chunk_x: number,
chunk_z: number,
shape: WorldShape,
terrain: NoiseTerrain,
block: (id: string) => number,
) {
@@ -32,10 +36,14 @@ export function generate_noise_chunk(
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 { min_y, max_y, height } = shape;
const terrain_levels = height / cell_height + 1;
const cave_levels = height / cave_cell_height + 1;
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
const cells = height / BIOME_CELL_HEIGHT;
// the cell a y is in, below the world the lowest
const ground_cell = (y: number) => Math.max(0, Math.floor((y - min_y) / BIOME_CELL_HEIGHT));
// density at the corners of every cell
const corner_columns: TerrainColumn[] = [];
@@ -51,10 +59,10 @@ export function generate_noise_chunk(
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);
solid[i * terrain_levels + level] = terrain.density(column, x, min_y + level * cell_height, z);
}
for (let level = 0; level < cave_levels; level++) {
caves[i * cave_levels + level] = terrain.cave(column, x, level * cave_cell_height, z);
caves[i * cave_levels + level] = terrain.cave(column, x, min_y + level * cave_cell_height, z);
}
}
@@ -134,9 +142,9 @@ export function generate_noise_chunk(
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++) {
// solid where both the terrain and the caves are above 0, by y above min_y
const is_solid = new Uint8Array(height);
for (let y = 0; y < 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;
@@ -151,16 +159,23 @@ export function generate_noise_chunk(
}
const column = column_at(x, z);
let surface_y = CHUNK_HEIGHT - 1;
while (surface_y > 0 && !is_solid[surface_y]) surface_y--;
let surface_y = max_y - 1;
while (surface_y > min_y && !is_solid[surface_y - min_y]) surface_y--;
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) >= settings.steep);
const biome = terrain.biome(column, surface_y, steep);
heights[z * CHUNK_SIZE + x] = surface_y;
biomes[z * CHUNK_SIZE + x] = biome;
// the biome of each cell, worked out once for the whole column when no rule looks at heights. the ground's
// surface is its own cell's
let biome = "";
for (let cell = 0; cell < cells; cell++) {
const y = min_y + cell * BIOME_CELL_HEIGHT;
if (cell === 0 || terrain.by_height) biome = terrain.biome(column, surface_y, steep, y);
biomes[cell * CHUNK_AREA + z * CHUNK_SIZE + x] = biome;
}
biome = biomes[ground_cell(surface_y) * CHUNK_AREA + z * CHUNK_SIZE + x];
context.x = x0 + x;
context.z = z0 + z;
@@ -168,7 +183,7 @@ export function generate_noise_chunk(
context.preliminary = ground;
context.biome = biome;
context.surface = surface_of(biome);
const index = (y: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
const index = (y: number) => (y - min_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
@@ -177,9 +192,9 @@ export function generate_noise_chunk(
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--) {
for (let y = max_y - 1; y >= min_y; y--) {
context.y = y;
if (!is_solid[y]) {
if (!is_solid[y - min_y]) {
depth = -1;
if (y < fluid_top) {
const fluid = fluids(context, open_sky);
+41 -20
View File
@@ -1,12 +1,13 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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_noise_chunk calls density and cave through here, so engine access mods can
// the shape of the world and which biome each column gets at each height, from a generator's data (see generator.ts):
// its density functions compiled for one seed. generate_noise_chunk calls density and cave through here, so engine access mods can
// hook them
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";
import { BIOME_CELL_HEIGHT } from "@/common/section.ts";
// what the terrain worked out about a column
export interface TerrainColumn {
@@ -20,8 +21,8 @@ export interface TerrainColumn {
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;
// climate values by their index in the noise settings' climate, the surface's y, steep, and the biome cell's lowest y
holds(climate: number[], surface: number, steep: boolean, y: number): boolean;
}
export class NoiseTerrain {
@@ -33,6 +34,8 @@ export class NoiseTerrain {
#caves: Density;
#climate: Density[];
#rules: CompiledRule[];
// whether any rule looks at y or depth. when none do, a column's biome is the same all the way up
readonly by_height: boolean;
constructor(seed: string, generator: Generator) {
this.seed = seed;
@@ -51,6 +54,7 @@ export class NoiseTerrain {
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));
this.by_height = generator.rules.some((rule) => "y" in (rule.when ?? {}) || "depth" in (rule.when ?? {}));
}
// with_climate works the climate out too, which is cheap right after the height since they share their inputs
@@ -74,26 +78,37 @@ export class NoiseTerrain {
return this.#caves(x, y, z);
}
// 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);
// the first of the biome source's rules that holds for the biome cell from y up, in a column with its ground at
// surface_y. the column's climate is worked out once, and kept on it
biome(column: TerrainColumn, surface_y: number, steep: boolean, y: number): 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;
if (rule.holds(climate, surface_y, steep, y)) return rule.biome;
}
throw new Error(`no rule of biome source ${this.settings.biome_source} holds at ${column.x}, ${column.z}`);
throw new Error(
`no rule of biome source ${this.settings.biome_source} holds at ${column.x}, ${y}, ${column.z}`,
);
}
// a column's biome without generating its chunk, from its height before 3d noise, so it can be a little off near
// the highest y in a column where it's this biome, the ground's or a biome cell's lowest one below it (cells start
// at min_y), without generating its chunk. that's 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);
locate_biome(biome: string, x: number, z: number, min_y: number): number | undefined {
const column = this.column(x, z, true);
const ground = Math.round(column.height);
let steep = 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 };
if (this.biome(column, ground, false, ground) !== this.biome(column, ground, true, ground)) {
const neighbors = [[x - 1, z], [x + 1, z], [x, z - 1], [x, z + 1]].map(([nx, nz]) => this.column(nx, nz));
steep = neighbors.some((neighbor) => Math.abs(neighbor.height - column.height) >= this.settings.steep);
}
if (this.biome(column, ground, steep, ground) === biome) return ground;
if (!this.by_height) return undefined;
const cell = min_y + Math.floor((ground - min_y) / BIOME_CELL_HEIGHT) * BIOME_CELL_HEIGHT;
for (let y = cell - BIOME_CELL_HEIGHT; y >= min_y; y -= BIOME_CELL_HEIGHT) {
if (this.biome(column, ground, steep, y) === biome) return y;
}
return undefined;
}
}
@@ -105,6 +120,12 @@ function compile_rule(biome: string, when: Record<string, RangeJson | boolean>,
} else if (name === "surface") {
const test = range_test(condition as RangeJson);
tests.push((_climate, surface) => test(surface));
} else if (name === "y") {
const test = range_test(condition as RangeJson);
tests.push((_climate, _surface, _steep, y) => test(y));
} else if (name === "depth") {
const test = range_test(condition as RangeJson);
tests.push((_climate, surface, _steep, y) => test(surface - y));
} else {
const index = names.indexOf(name);
const test = range_test(condition as RangeJson);
@@ -113,9 +134,9 @@ function compile_rule(biome: string, when: Record<string, RangeJson | boolean>,
}
return {
biome,
holds(climate, surface_y, steep) {
holds(climate, surface_y, steep, y) {
for (let i = 0; i < tests.length; i++) {
if (!tests[i](climate, surface_y, steep)) return false;
if (!tests[i](climate, surface_y, steep, y)) return false;
}
return true;
},
+6
View File
@@ -11,6 +11,7 @@ import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts
import { default_block_value } from "./utils.ts";
import { generate_raw_chunk, type RawChunk, type WorldgenSetup } from "./generation.ts";
import { load_worldgen } from "./worldgen_loader.ts";
import { WorldShape, type WorldShapeJson } from "./world_shape.ts";
// the parts of a mod's data generation reads. tags only the block ones
export type WorldgenModData = Pick<
@@ -31,6 +32,8 @@ export interface WorldgenBundle {
seed: string;
// the noise settings the world uses
generator: string;
// the dimension's, see WorldShape
shape: WorldShapeJson;
// in load order
mods: { id: string; data: WorldgenModData; worldgen_url?: string; engine_access?: boolean }[];
}
@@ -38,11 +41,13 @@ export interface WorldgenBundle {
export function worldgen_bundle(
seed: string,
generator: string,
shape: WorldShapeJson,
mods: { id: string; data: ModData; worldgen_url?: string; engine_access?: boolean }[],
): WorldgenBundle {
return {
seed,
generator,
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
mods: mods.map(({ id, data, worldgen_url, engine_access }) => ({
id,
data: {
@@ -104,6 +109,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
),
ores: recipes.ores,
generator: bundle.generator,
shape: new WorldShape(bundle.shape),
});
const { block_ids, default_values } = block_numbering();
return {
+4
View File
@@ -10,6 +10,7 @@ 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 { WorldShape } from "./world_shape.ts";
import type { Biome } from "./worldgen/biomes.ts";
import {
compile_feature,
@@ -27,6 +28,8 @@ export interface WorldgenSources {
ores: OreJson[][];
// the noise settings the world uses. it and data features come from mods' data, which is already registered
generator: string;
// the dimension's, which the generator fills
shape: WorldShape;
}
// a feature before it's put in order
@@ -41,6 +44,7 @@ interface Pending {
export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenSetup> {
const setup: WorldgenSetup = {
shape: sources.shape,
generator: compile_generator(sources.generator),
ores: sources.ores,
features: [],
+2 -1
View File
@@ -202,8 +202,9 @@ ctx.player.is_swimming(); // see ../entities/players.md#swimming
ctx.player.biome; // and ctx.player.season, see ../worldgen/biomes.md#seasons
ctx.world.get_block(x, y, z); // a block id, what this client sees
ctx.world.get_client_data<number>(x, y, z, "speed"); // see ../blocks/tiledata.md#client-data, a copy
ctx.world.biome_at(x, z); // and ctx.world.season_at(x, z), undefined where nothing's loaded
ctx.world.biome_at(x, y, z); // and ctx.world.season_at(x, y, z), undefined where nothing's loaded
ctx.world.time; // see Time
ctx.world.min_y; // and ctx.world.max_y, see ../worldgen/terrain.md#height
ctx.items.ids(); // every item, in load order
ctx.items.exists(id);
ctx.items.name(id); // "Cooked Rice"
+2 -2
View File
@@ -46,8 +46,8 @@ away before anything is downloaded.
The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so worldgen scripts
stay on the server.
- Chunks are 16×256×16 and sent whole, compressed, in batches, nearest first. The server paces batches by how fast each
client says it loads them.
- Chunks are 16×16 and as tall as the dimension, sent whole, compressed, in batches, nearest first. The server paces
batches by how fast each client says it loads them.
- Players see chunks up to their view distance, at most 16 on the server's side. Light isn't sent: clients light chunks
themselves.
- Block changes go only to players who have the chunk. Everyone else gets the change with the chunk when they come
+25 -15
View File
@@ -4,8 +4,14 @@ A biome says what the ground looks like where it's picked: the blocks on top, th
tinted, which trees grow, and whether it has a season of its own. Biomes are data, one file each in a mod's
`worldgen/biomes/` folder. The base game's are in `mods/bworld/worldgen/biomes/`.
Which biome a column gets is up to the generator's biome rules, from the column's climate and height. A mod's biome
generates where a rule it adds puts it, see [Adding Biomes](terrain.md#adding-biomes).
Which biome a place gets is up to the generator's biome rules, from the column's climate, the ground's height and how
far under it the place is. A mod's biome generates where a rule it adds puts it, see
[Adding Biomes](terrain.md#adding-biomes).
Biomes are one per block across and one every 4 blocks up, a cell from `y` to `y + 3` where `y` is a multiple of 4 above
the world's bottom. The base game's are the same all the way up a column, and a mod can add biomes under the ground, see
[Underground Biomes](terrain.md#underground-biomes). The ground's surface blocks are always its own cell's biome's, and
so is the filler under them.
## A Biome
@@ -62,14 +68,14 @@ Above the snow line, around y 176, the top block is snow whatever the biome says
## Biome Ids
Biome ids are what features' `biome_at` gives and what spawns list. The base game has `bworld:deep_ocean`,
Biome ids are what `biome_at` gives and what spawns list. The base game has `bworld:deep_ocean`,
`bworld:deep_frozen_ocean`, `bworld:deep_lukewarm_ocean`, `bworld:ocean`, `bworld:frozen_ocean`, `bworld:warm_ocean`,
`bworld:river`, `bworld:frozen_river`, `bworld:beach`, `bworld:snowy_beach`, `bworld:stony_shore`, `bworld:plains`,
`bworld:meadow`, `bworld:forest`, `bworld:dark_forest`, `bworld:swamp`, `bworld:taiga`, `bworld:snowy_plains`,
`bworld:snowy_taiga`, `bworld:savanna`, `bworld:jungle`, `bworld:desert`, `bworld:snowy_slopes`, `bworld:stony_peaks`,
`bworld:jagged_peaks` and `bworld:frozen_peaks`.
`/locatebiome <id>` finds the nearest one.
`/locatebiome <id>` finds the nearest one, and how high it is: the ground's y, or under it for a biome under the ground.
## Biome Tags
@@ -83,7 +89,9 @@ Biomes have [tags](../resources/tags.md) too, in `tags/biomes/`. Every base game
| `#bworld:is_forest` | `forest`, `dark_forest`, `savanna`, `plains`, `snowy_plains`, `taiga`, `snowy_taiga`, `jungle`, `swamp`, `desert` |
A mod's biome joins one by adding itself to the tag's file, like `tags/biomes/bworld/is_forest.json`, and a script
checks a biome with `ctx.tags.has("biomes", "bworld:is_forest", ctx.world.biome_at(x, z))`.
checks a biome with `ctx.tags.has("biomes", "bworld:is_forest", ctx.world.biome_at(x, y, z))`.
Biomes under the ground go in the common tags NeoForge mods check, `#c:is_underground`, and `#c:is_cave` for caves.
## Seasons
@@ -94,17 +102,19 @@ summer in `desert`.
Scripts read the season where something is:
| Where | Biome | Season |
| ------------------------------------------------ | -------------------------- | --------------------------- |
| a block in a server component, like `on_tick` | `block.biome` | `block.season` |
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
| a player, on the server | `player.biome` | `player.season` |
| any column, in server, shared and client scripts | `ctx.world.biome_at(x, z)` | `ctx.world.season_at(x, z)` |
| the player on this client | `ctx.player.biome` | `ctx.player.season` |
| Where | Biome | Season |
| ----------------------------------------------- | ----------------------------- | ------------------------------ |
| a block in a server component, like `on_tick` | `block.biome` | `block.season` |
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
| a player, on the server | `player.biome` | `player.season` |
| any block, in server, shared and client scripts | `ctx.world.biome_at(x, y, z)` | `ctx.world.season_at(x, y, z)` |
| the player on this client | `ctx.player.biome` | `ctx.player.season` |
| a feature's chunk, see [Features](index.md) | `chunk.biome_at(x, y, z)` | |
Entities and players go by the column their feet are in. On the server a column always has a biome: in a chunk that
isn't loaded it's what generation makes there, which takes a while the first time. In shared rules and client scripts
it's what that client has loaded, and `undefined` where it has nothing.
`biome_at` is NeoForge's `level.getBiome(pos)`. Entities and players go by the block their feet are in, like
`level.getBiome(entity.blockPosition())`. Above and below the world it's the biome at its top or bottom. On the server
every block has a biome: in a chunk that isn't loaded it's what generation makes there, which takes a while the first
time. In shared rules and client scripts it's what that client has loaded, and `undefined` where it has nothing.
```ts
ctx.components.register_block("my_mod:crop", {
+10 -4
View File
@@ -25,7 +25,8 @@ Each chunk goes through three passes:
2. **Ores.** Every mod's `worldgen/ores.json`, in load order, the base game's first.
3. **Features.** Every mod's features, code and data, by step and then load order, see [Order](#order).
The world is 256 blocks tall and the sea is at y 64.
How tall the world is is up to its [dimension](terrain.md#height): the base game's goes from y 0 to 255, and its sea is
at y 64.
## Ores
@@ -89,7 +90,8 @@ export function setup(gen: WorldgenContext) {
}
```
`step` and `biomes` are optional. With `biomes`, the feature only runs in chunks that have one of them.
`step` and `biomes` are optional. With `biomes`, the feature only runs in chunks that have one of them somewhere, at any
height, the way a NeoForge biome modifier adds a feature to the biomes it lists.
Feature ids are in the mod's namespace. Each feature's `rng` is seeded with the world's seed, the chunk and the
feature's id, so adding another mod's feature doesn't change what this one generates.
@@ -99,12 +101,15 @@ interface FeatureChunk {
readonly x: number; // chunk coordinates. blocks are chunk.x * 16 to chunk.x * 16 + 15
readonly z: number;
readonly seed: string;
readonly min_y: number; // the dimension's blocks go from min_y up to max_y - 1
readonly max_y: number;
readonly rng: { next(): number }; // 0 to 1
random(name: string): { next(): number }; // seeded from the world's seed and name, the same in every chunk
noise_2d(name: string): (x: number, z: number) => number;
noise_3d(name: string): (x: number, y: number, z: number) => number;
height_at(x: number, z: number): number; // surface height, inside this chunk only
biome_at(x: number, z: number): string; // like "bworld:plains", inside this chunk only
biome_at(x: number, y: number, z: number): string; // like "bworld:plains", inside this chunk only
set_biome(x: number, y: number, z: number, biome: string): void; // the 4 blocks tall cell y is in, see biomes.md
get_block(x: number, y: number, z: number): string | undefined; // inside this chunk only
set_block(x: number, y: number, z: number, id: string): void; // up to one chunk away
place_feature(id: string, x: number, y: number, z: number): boolean; // a data feature, see below
@@ -175,7 +180,8 @@ Built in names work with or without `minecraft:`.
`not`, `all_of`, `any_of` and `true`. Each takes an `offset`.
- **Numbers** (int providers): a whole number, or `constant`, `uniform` (`min_inclusive`, `max_inclusive`) or
`weighted_list` (`distribution` of `data` and `weight`).
- **Heights:** `{ "absolute": y }`, `{ "above_bottom": n }` or `{ "below_top": n }`.
- **Heights:** `{ "absolute": y }`, `{ "above_bottom": n }` (`min_y + n`) or `{ "below_top": n }` (`max_y - 1 - n`),
from the dimension's height.
- **Blocks** (`to_place`, `provider`, `state`): an id, or Minecraft's
`{ "type": "simple_state_provider", "state": { "Name": id } }`.
+73 -9
View File
@@ -151,7 +151,7 @@ A generator. The base game's is `worldgen/noise_settings/overworld.json`:
| `cell_width` | How far apart across `terrain` and `caves` are sampled, 1 to 16. |
| `terrain`, `caves` | Their density function, and how far apart up they're sampled. Solid where both are above 0. |
| `preliminary_surface` | The ground's height before 3D noise. Surface rules, `steep` and `/locatebiome` use it. |
| `climate` | Named values biome rules look at. Any names, except `surface` and `steep`. |
| `climate` | Named values biome rules look at. Any names, except `surface`, `y`, `depth` and `steep`. |
| `steep` | A column is steep when its preliminary surface is this much higher or lower than a neighbor's. |
| `biome_source` | The biome source that picks its biomes. |
| `fluids` | What empty space becomes, the first that applies: below `below`, where there's `open_sky` (nothing but air above) or where a density function is in a range. |
@@ -187,8 +187,18 @@ with `bworld:dark_forest`, which holds everywhere:
}
```
`when` holds when all its conditions do: a range of one of the generator's `climate` values, a range of `surface` (the y
of the column's top solid block), or `"steep": true` or `false`. Rules without `when` always hold.
Rules pick a biome for each 4 blocks tall cell of a column, see [Biomes](biomes.md). `when` holds when all its
conditions do, each a range of one of these, or `"steep": true` or `false`. Rules without `when` always hold.
| Name | Meaning |
| ----------------- | ---------------------------------------------------------------------------------------- |
| a `climate` value | One of the generator's, the same all the way up a column. |
| `surface` | The y of the column's top solid block. |
| `y` | The cell's lowest y. |
| `depth` | How far the cell is below the ground, `surface - y`: 0 at the ground, negative above it. |
A rule that looks at neither `y` nor `depth` holds all the way up a column, so the base game's rules give a column one
biome. When no rule looks at them, a column's biome is worked out once.
This is bworld's own, not Minecraft's multi-noise biome source: a rule can look at how high the ground really is and
whether it's a cliff, which is how beaches, peaks and stony shores are placed.
@@ -217,6 +227,34 @@ plains:
Rules from several mods go in in load order. The biome itself is a [biome file](biomes.md) as usual.
### Underground Biomes
A rule with `depth` or `y` puts a biome under the ground. It has to come before the rules it takes the place of, and the
base game's all hold all the way down, so it goes before the first one. Mossy caves more than 16 blocks down, where it's
humid:
```json
{
"format_version": 1,
"biome_source": {
"id": "my_mod:mossy_caves",
"extends": "bworld:overworld",
"rules": [{
"id": "my_mod:mossy_caves",
"before": "bworld:river_bed_frozen",
"when": {
"depth": { "min_exclusive": 16 },
"humidity": { "min_exclusive": 0.4 }
},
"biome": "my_mod:mossy_caves"
}]
}
}
```
The ground keeps the biome of its own cell, surface blocks and all. Spawns, `entity.biome`, seasons and grass, leaf and
water colors follow the biome where they are, so an underground biome's spawn list and colors work under the ground.
## Surface Rules
What a solid block becomes, like Minecraft's surface rules: a rule gives a block or nothing, and the first one in a
@@ -256,15 +294,40 @@ base game's is `worldgen/dimension/overworld.json`:
"dimension": {
"id": "bworld:overworld",
"generator": "bworld:overworld",
"default": true
"default": true,
"min_y": 0,
"max_y": 256,
"sky_light": true
}
}
```
| Field | Meaning |
| ----------- | --------------------------------------------------------- |
| `generator` | The [noise settings](#noise-settings) that generate it. |
| `default` | `true` for the dimension the world plays. False if unset. |
| Field | Meaning |
| ----------- | ------------------------------------------------------------------------------------------------------- |
| `generator` | The [noise settings](#noise-settings) that generate it. |
| `default` | `true` for the dimension the world plays. False if unset. |
| `min_y` | The lowest y that has blocks. 0 if unset. |
| `max_y` | The first y above the world: blocks go up to `max_y - 1`. 256 if unset. |
| `sky_light` | Whether light comes from the sky. `false` for a dimension that's underground everywhere. True if unset. |
### Height
A dimension's blocks go from `min_y` up to `max_y - 1`, so `"min_y": -64, "max_y": 320` is 384 blocks tall. Both have to
be multiples of 16, `max_y` at least 16 above `min_y`, and the world has to fit in -2048 to 2048. They also have to be
multiples of the generator's `terrain` and `caves` `cell_height`, since the density is sampled every `cell_height`
blocks up from `min_y`. `check-mods` reports any of these, and the server doesn't start with them.
Outside the height there are no blocks: reading one gives air and placing one does nothing. Things that fall 64 blocks
below `min_y` are out of the world. Scripts read the height as `ctx.world.min_y` and `ctx.world.max_y`, on the server
and the client, and features as `chunk.min_y` and `chunk.max_y`.
Chunks are saved with the height they were made with. For now a chunk saved before a dimension's height changed can't be
read, and is generated again.
### Sky Light
Without sky light, there's none anywhere, in the open and above the world too: only blocks that give off light, like
torches, light it, and day and night don't change how bright it is. The sky is still drawn as it is in the overworld.
The world plays the dimension with `"default": true`. Exactly one dimension in the loaded mods can be the default: with
none, or more than one, the server doesn't start, and the error names them. A mod can have dimensions that aren't the
@@ -274,7 +337,8 @@ its own, like a flat world, can't be loaded with the base game's for now.
There's one dimension per world for now, there's no travelling between them yet.
New players spawn in the middle of the world, on the first column, in rings of chunks around 0, 0, whose top block has
collision. Water has none, so they never spawn in the sea, and neither do plants without collision.
collision, looking down from `max_y`. Water has none, so they never spawn in the sea, and neither do plants without
collision.
## Changing the Base Game's Terrain
+4 -4
View File
@@ -303,10 +303,10 @@ engine assets in `assets/`.
How the server sends the world, like Minecraft Java since 1.20.2. The code is in `common/chunk_streaming.ts`,
`server/game/player_chunks.ts` and `client/level/client_level.ts`.
- **Whole chunks.** A `level_chunk` is a binary websocket message with every block of a 16×256×16 chunk and its columns'
biomes, deflated. Blocks are in 16 sections of 16×16×16, each a paletted container like Minecraft's: one value when
the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256 kinds, and whole values past that.
Light isn't sent.
- **Whole chunks.** A `level_chunk` is a binary websocket message with every block of a chunk, as tall as the dimension,
and its columns' biomes, deflated. Blocks are in sections of 16×16×16 from the bottom up, each a paletted container
like Minecraft's: one value when the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256
kinds, and whole values past that. Light isn't sent.
- **Numeric ids.** Chunks use the server's numeric block ids, and `join.blocks` lists the string id for each, like
Minecraft's registry sync. Clients translate them as a chunk loads.
- **The view.** Players send their view distance with `ready` and `view_distance`. The server uses up to 16 chunks, and
+283
View File
@@ -2269,3 +2269,286 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
# TerraFirmaCraft
https://github.com/TerraFirmaCraft/TerraFirmaCraft
license:
```
European Union Public Licence
V. 1.2
EUPL © the European Union 2007, 2016
This European Union Public Licence (the ‘EUPL’) applies to the Work (as
defined below) which is provided under the terms of this Licence. Any use of
the Work, other than as authorised under this Licence is prohibited (to the
extent such use is covered by a right of the copyright holder of the Work).
The Work is provided under the terms of this Licence when the Licensor (as
defined below) has placed the following notice immediately following the
copyright notice for the Work: “Licensed under the EUPL”, or has expressed by
any other means his willingness to license under the EUPL.
1. Definitions
In this Licence, the following terms have the following meaning:
— ‘The Licence’: this Licence.
— ‘The Original Work’: the work or software distributed or communicated by the
‘Licensor under this Licence, available as Source Code and also as
‘Executable Code as the case may be.
— ‘Derivative Works’: the works or software that could be created by the
‘Licensee, based upon the Original Work or modifications thereof. This
‘Licence does not define the extent of modification or dependence on the
‘Original Work required in order to classify a work as a Derivative Work;
‘this extent is determined by copyright law applicable in the country
‘mentioned in Article 15.
— ‘The Work’: the Original Work or its Derivative Works.
— ‘The Source Code’: the human-readable form of the Work which is the most
convenient for people to study and modify.
— ‘The Executable Code’: any code which has generally been compiled and which
is meant to be interpreted by a computer as a program.
— ‘The Licensor’: the natural or legal person that distributes or communicates
the Work under the Licence.
— ‘Contributor(s)’: any natural or legal person who modifies the Work under
the Licence, or otherwise contributes to the creation of a Derivative Work.
— ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of
the Work under the terms of the Licence.
— ‘Distribution’ or ‘Communication’: any act of selling, giving, lending,
renting, distributing, communicating, transmitting, or otherwise making
available, online or offline, copies of the Work or providing access to its
essential functionalities at the disposal of any other natural or legal
person.
2. Scope of the rights granted by the Licence
The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
sublicensable licence to do the following, for the duration of copyright
vested in the Original Work:
— use the Work in any circumstance and for all usage,
— reproduce the Work,
— modify the Work, and make Derivative Works based upon the Work,
— communicate to the public, including the right to make available or display
the Work or copies thereof to the public and perform publicly, as the case
may be, the Work,
— distribute the Work or copies thereof,
— lend and rent the Work or copies thereof,
— sublicense rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now
known or later invented, as far as the applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to
exercise his moral right to the extent allowed by law in order to make
effective the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non-exclusive usage rights
to any patents held by the Licensor, to the extent necessary to make use of
the rights granted on the Work under this Licence.
3. Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as
Executable Code. If the Work is provided as Executable Code, the Licensor
provides in addition a machine-readable copy of the Source Code of the Work
along with each copy of the Work that the Licensor distributes or indicates,
in a notice following the copyright notice attached to the Work, a repository
where the Source Code is easily and freely accessible for as long as the
Licensor continues to distribute or communicate the Work.
4. Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits
from any exception or limitation to the exclusive rights of the rights owners
in the Work, of the exhaustion of those rights or of other applicable
limitations thereto.
5. Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and
obligations imposed on the Licensee. Those obligations are the following:
Attribution right: The Licensee shall keep intact all copyright, patent or
trademarks notices and all notices that refer to the Licence and to the
disclaimer of warranties. The Licensee must include a copy of such notices and
a copy of the Licence with every copy of the Work he/she distributes or
communicates. The Licensee must cause any Derivative Work to carry prominent
notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes or communicates copies of the
Original Works or Derivative Works, this Distribution or Communication will be
done under the terms of this Licence or of a later version of this Licence
unless the Original Work is expressly distributed only under this version of
the Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee
(becoming Licensor) cannot offer or impose any additional terms or conditions
on the Work or Derivative Work that alter or restrict the terms of the
Licence.
Compatibility clause: If the Licensee Distributes or Communicates Derivative
Works or copies thereof based upon both the Work and another work licensed
under a Compatible Licence, this Distribution or Communication can be done
under the terms of this Compatible Licence. For the sake of this clause,
‘Compatible Licence’ refers to the licences listed in the appendix attached to
this Licence. Should the Licensee's obligations under the Compatible Licence
conflict with his/her obligations under this Licence, the obligations of the
Compatible Licence shall prevail.
Provision of Source Code: When distributing or communicating copies of the
Work, the Licensee will provide a machine-readable copy of the Source Code or
indicate a repository where this Source will be easily and freely available
for as long as the Licensee continues to distribute or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade
names, trademarks, service marks, or names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
6. Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted
hereunder is owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she
brings to the Work are owned by him/her or licensed to him/her and that he/she
has the power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent
Contributors grant You a licence to their contributions to the Work, under the
terms of this Licence.
7. Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous
Contributors. It is not a finished work and may therefore contain defects or
‘bugs’ inherent to this type of development.
For the above reason, the Work is provided under the Licence on an ‘as is’
basis and without warranties of any kind concerning the Work, including
without limitation merchantability, fitness for a particular purpose, absence
of defects or errors, accuracy, non-infringement of intellectual property
rights other than copyright as stated in Article 6 of this Licence.
This disclaimer of warranty is an essential part of the Licence and a
condition for the grant of any rights to the Work.
8. Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural
persons, the Licensor will in no event be liable for any direct or indirect,
material or moral, damages of any kind, arising out of the Licence or of the
use of the Work, including without limitation, damages for loss of goodwill,
work stoppage, computer failure or malfunction, loss of data or any commercial
damage, even if the Licensor has been advised of the possibility of such
damage. However, the Licensor will be liable under statutory product liability
laws as far such laws apply to the Work.
9. Additional agreements
While distributing the Work, You may choose to conclude an additional
agreement, defining obligations or services consistent with this Licence.
However, if accepting obligations, You may act only on your own behalf and on
your sole responsibility, not on behalf of the original Licensor or any other
Contributor, and only if You agree to indemnify, defend, and hold each
Contributor harmless for any liability incurred by, or claims asserted against
such Contributor by the fact You have accepted any warranty or additional
liability.
10. Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon ‘I
agree’ placed under the bottom of a window displaying the text of this Licence
or by affirming consent in any other similar way, in accordance with the rules
of applicable law. Clicking on that icon indicates your clear and irrevocable
acceptance of this Licence and all of its terms and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and
conditions by exercising any rights granted to You by Article 2 of this
Licence, such as the use of the Work, the creation by You of a Derivative Work
or the Distribution or Communication by You of the Work or copies thereof.
11. Information to the public
In case of any Distribution or Communication of the Work by means of
electronic communication by You (for example, by offering to download the Work
from a remote location) the distribution channel or media (for example, a
website) must at least provide to the public the information requested by the
applicable law regarding the Licensor, the Licence and the way it may be
accessible, concluded, stored and reproduced by the Licensee.
12. Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon
any breach by the Licensee of the terms of the Licence. Such a termination
will not terminate the licences of any person who has received the Work from
the Licensee under the Licence, provided such persons remain in full
compliance with the Licence.
13. Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete
agreement between the Parties as to the Work.
If any provision of the Licence is invalid or unenforceable under applicable
law, this will not affect the validity or enforceability of the Licence as a
whole. Such provision will be construed or reformed so as necessary to make it
valid and enforceable.
The European Commission may publish other linguistic versions or new versions
of this Licence or updated versions of the Appendix, so far this is required
and reasonable, without reducing the scope of the rights granted by the
Licence. New versions of the Licence will be published with a unique version
number.
All linguistic versions of this Licence, approved by the European Commission,
have identical value. Parties can take advantage of the linguistic version of
their choice.
14. Jurisdiction
Without prejudice to specific agreement between parties,
— any litigation resulting from the interpretation of this License, arising
between the European Union institutions, bodies, offices or agencies, as a
Licensor, and any Licensee, will be subject to the jurisdiction of the Court
of Justice of the European Union, as laid down in article 272 of the Treaty
on the Functioning of the European Union,
— any litigation arising between other parties and resulting from the
interpretation of this License, will be subject to the exclusive
jurisdiction of the competent court where the Licensor resides or conducts
its primary business.
15. Applicable Law
Without prejudice to specific agreement between parties,
— this Licence shall be governed by the law of the European Union Member State
where the Licensor has his seat, resides or has his registered office,
— this licence shall be governed by Belgian law if the Licensor has no seat,
residence or registered office inside a European Union Member State.
Appendix
‘Compatible Licences’ according to Article 5 EUPL are:
— GNU General Public License (GPL) v. 2, v. 3
— GNU Affero General Public License (AGPL) v. 3
— Open Software License (OSL) v. 2.1, v. 3.0
— Eclipse Public License (EPL) v. 1.0
— CeCILL v. 2.0, v. 2.1
— Mozilla Public Licence (MPL) v. 2
— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
works other than software
— European Union Public Licence (EUPL) v. 1.1, v. 1.2
— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or
Strong Reciprocity (LiLiQ-R+)
— The European Commission may update this Appendix to later versions of the
above licences without producing a new version of the EUPL, as long as they
provide the rights granted in Article 2 of this Licence and protect the
covered Source Code from exclusive appropriation.
— All other changes or additions to this Appendix require the production of a
new EUPL version.
```
+5 -3
View File
@@ -145,14 +145,16 @@ export function register_fishing(ctx: ServerContext) {
ctx.loot.register_condition("bworld:season", (params, context) => {
const seasons = params.seasons as string[];
if (!context.position) return true;
return seasons.includes(ctx.world.season_at(context.position.x, context.position.z));
const { x, y, z } = context.position;
return seasons.includes(ctx.world.season_at(x, y, z));
});
// "biomes": ["bworld:swamp", "#bworld:is_ocean"], holds in any of the biomes or biome tags at the loot's
// position. without a position it holds, like bworld:season
ctx.loot.register_condition("bworld:biome", (params, context) => {
if (!context.position) return true;
const biome = ctx.world.biome_at(context.position.x, context.position.z);
const { x, y, z } = context.position;
const biome = ctx.world.biome_at(x, y, z);
return (params.biomes as string[]).some((entry) =>
entry.startsWith("#") ? ctx.tags.has("biomes", entry, biome) : entry === biome
);
@@ -291,7 +293,7 @@ export function register_fishing(ctx: ServerContext) {
!player || player.selected_slot !== cast.slot || player.held_item?.id !== FISHING_ROD ||
distance > LINE_LENGTH || cast.hook.removed ||
(water && ctx.world.get_block(water.x, water.y, water.z) !== water.block) ||
(cast.velocity && (now - cast.thrown_at > MAX_FLIGHT || cast.position.y < 0))
(cast.velocity && (now - cast.thrown_at > MAX_FLIGHT || cast.position.y < ctx.world.min_y))
) {
stop(player, id);
continue;
+21 -12
View File
@@ -12,7 +12,6 @@
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
@@ -87,7 +86,8 @@ function tree_sites(chunk: FeatureChunk): TreeSite[] {
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) {
// max_y is the top of the world, nothing grows into it
function grow_tree(kind: TreeKind, x: number, y: number, z: number, max_y: 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");
@@ -110,7 +110,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
// 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;
if (top >= max_y - 1) return false;
trunk(height);
layer(y + height - 2, 2, true);
layer(y + height - 1, 2, true);
@@ -122,7 +122,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
// a short trunk under a wide, rounded canopy
const height = random(4, 6);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
if (top >= max_y - 1) return false;
trunk(height);
layer(y + height - 2, 2, false);
layer(y + height - 1, MAX_CANOPY, false);
@@ -133,7 +133,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
case "big_oak": {
const height = random(6, 8);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
if (top >= max_y - 1) return false;
trunk(height);
layer(y + height - 3, 2, true);
layer(y + height - 2, 3, false);
@@ -145,7 +145,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
case "spruce": {
const height = random(7, 10);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
if (top >= max_y - 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");
@@ -160,7 +160,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
case "jungle": {
const height = random(9, 13);
top = y + height + 1;
if (top >= CHUNK_HEIGHT - 1) return false;
if (top >= max_y - 1) return false;
trunk(height);
layer(y + height - 2, 3, false);
layer(y + height - 1, 3, true);
@@ -172,7 +172,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
// 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;
if (top >= max_y - 1) return false;
trunk(height);
const lean_x = random(-1, 1);
const lean_z = lean_x === 0 ? (rng.next() < 0.5 ? -1 : 1) : 0;
@@ -223,7 +223,7 @@ export function register_trees(gen: WorldgenContext) {
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;
if (y < chunk.min_y || y >= chunk.max_y) 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
@@ -235,11 +235,12 @@ export function register_trees(gen: WorldgenContext) {
};
for (const site of tree_sites(chunk)) {
const here = trees.get(chunk.biome_at(site.x, site.z));
// the biome of the ground it grows from
const ground_y = chunk.height_at(site.x, site.z);
const here = trees.get(chunk.biome_at(site.x, ground_y, 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;
@@ -247,7 +248,15 @@ export function register_trees(gen: WorldgenContext) {
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));
grow_tree(
kind,
site.x,
ground_y + 1,
site.z,
chunk.max_y,
site.rng,
(x, y, z, block) => place(x, y, z, block, wood),
);
}
}, { step: "vegetal_decoration" });
}
+7 -7
View File
@@ -32,17 +32,17 @@ export function step(x: number, y: number, z: number, face: Face): [number, numb
return [x + dx, y + dy, z + dz];
}
// a position as one number, so maps and sets of them don't make a string each: x and z in 21 bits and y in 8, further
// than chunk_key lets a world go
// a position as one number, so maps and sets of them don't make a string each: x and z in 20 bits, as far as
// chunk_key lets a world go, and y in 12, as tall as a dimension can be
export function pack(x: number, y: number, z: number) {
return ((x + 2 ** 20) * 2 ** 21 + z + 2 ** 20) * 256 + y;
return ((x + 2 ** 19) * 2 ** 20 + z + 2 ** 19) * 4096 + y + 2048;
}
export function unpack(key: number): [number, number, number] {
const y = key % 256;
const xz = (key - y) / 256;
const z = xz % 2 ** 21;
return [(xz - z) / 2 ** 21 - 2 ** 20, y, z - 2 ** 20];
const y = key % 4096;
const xz = (key - y) / 4096;
const z = xz % 2 ** 20;
return [(xz - z) / 2 ** 20 - 2 ** 19, y - 2048, z - 2 ** 19];
}
// which way a block points, from its states: the name of a facing state, read as FACES' values with 2 bits or 3, or
+2 -2
View File
@@ -27,10 +27,10 @@ function cactus(chunk: FeatureChunk) {
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16);
const height = pick_height(chunk.rng.next());
if (chunk.biome_at(x, z) !== "bworld:desert") {
const ground = chunk.height_at(x, z);
if (chunk.biome_at(x, ground, z) !== "bworld:desert") {
continue;
}
const ground = chunk.height_at(x, z);
if (chunk.get_block(x, ground, z) !== "bworld:sand") {
continue;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 589 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 841 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 600 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 590 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 799 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 857 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 902 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 860 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 913 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 898 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 763 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 893 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 797 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 805 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 748 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 829 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 213 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 685 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 658 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 653 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 693 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 647 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 664 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 673 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 667 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 679 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 957 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 633 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 865 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 659 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 658 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 656 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 653 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 674 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 666 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 626 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 626 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 625 B

Some files were not shown because too many files have changed in this diff Show More