Files

974 lines
34 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import {
block_value,
chunk_key,
default_block_value,
fluid_block,
fluid_in_cell,
is_waterlogged,
} from "@/common/utils.ts";
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 {
BlockRegistry,
EverythingRegistry,
is_fluid_block,
light_tables,
RenderLayer,
} from "@/common/everything_registry.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, 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";
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "@/common/block_shapes.ts";
import { BlockPredictions } from "./block_predictions.ts";
import { block_visuals, Visuals } from "../rendering/visuals.ts";
export interface Block {
id: string;
x: number;
y: number;
z: number;
}
export { CHUNK_AREA, CHUNK_SIZE };
export interface Chunk {
x: number;
z: number;
// 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 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;
// from its last mesh, see get_light. undefined until it's been meshed
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 {
quad_count: number;
// 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 {
// the mesh_version of the mesh these are for
mesh_version: number;
centers: Float32Array;
planes: [Float32Array, Float32Array, Float32Array];
// where the camera was for the last sort that was requested
camera: number[];
// sorts come back out of order, older ones than what's shown get skipped
requested: number;
applied: number;
}
export { chunk_key };
// the block being looked at and which face of it
export interface BlockHitResult {
x: number;
y: number;
z: number;
block: number;
face: Faces;
// where the view went into the block, 0 to 1 on each axis
hit: [number, number, number];
}
// a block's client data, see ClientLevel.block_data
export interface BlockData {
x: number;
y: number;
z: number;
data: Record<string, unknown>;
}
// 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;
// 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 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
time = 0;
// ticks since this client joined, which never jumps like time can, for what moves at a steady speed
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
predictions = new BlockPredictions();
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;
// every entity this client knows about, the local player included, by id
entities = new Map<string, Entity>();
// the client data of blocks that have some, see BlockRef.set_client_data, by chunk_key then position_key "x,y,z"
block_data = new Map<number, Map<string, BlockData>>();
visuals = new Visuals(this);
// cracks on blocks machines are breaking, the stage to draw by position_key "x,y,z", see break_progress in
// common/protocol.ts
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[], 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;
const local = id === AIR_ID ? AIR : EverythingRegistry.get_id("blocks", id);
if (local === undefined) {
console.warn(`The server has a block this client doesn't: ${id}`);
}
this.#to_local[nid] = local ?? AIR;
});
this.workers = new ChunkWorkerPool((message) => this.#on_worker_message(message));
// sent once instead of with every mesh request
this.workers.broadcast({
type: "init",
blocks_registry: strip_functions(EverythingRegistry.get_registry<BlockRegistry>("blocks")),
models: Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")),
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 },
});
}
add_entity(entity: Entity) {
this.entities.set(entity.id, entity);
}
remove_entity(id: string) {
this.entities.delete(id);
}
tick() {
this.time += 1;
this.ticks += 1;
for (const entity of this.entities.values()) {
entity.save_previous_position();
entity.tick();
}
}
// a level_chunk from the server: the whole chunk, replacing it if it was already here
load_chunk(data: Uint8Array) {
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;
}
// 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. 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 meshes stay up until the new ones are ready
chunk.column = column;
chunk.sky = sky;
chunk.biome_colors = biome_colors;
} else {
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
set_center(x: number, z: number) {
this.center = { x, z };
const far = [...this.chunks.values()].filter((chunk) => !this.#in_storage_range(chunk.x, chunk.z));
for (const chunk of far) {
this.unload_chunk(chunk.x, chunk.z);
}
}
#in_storage_range(x: number, z: number) {
if (!this.center) {
return true;
}
const range = Math.max(2, this.view_distance) + STORAGE_MARGIN;
return Math.max(Math.abs(x - this.center.x), Math.abs(z - this.center.z)) <= range;
}
dispose() {
this.workers.terminate();
for (const chunk of this.chunks.values()) {
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) {
return this.chunks.get(chunk_key(x, z));
}
// state is the block's state bits, its defaults when not given
add_block(block: Block, state?: number) {
const block_chunk_x = Math.floor(block.x / CHUNK_SIZE);
const block_chunk_z = Math.floor(block.z / CHUNK_SIZE);
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
if (!chunk) {
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 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 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 >= 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
get_block_value(x: number, y: 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);
if (!chunk) {
return VOID;
}
return chunk.column.get(x, y, z);
}
get_block(x: number, y: 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);
if (!chunk) {
return VOID;
}
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
has_collision(x: number, y: number, z: number) {
const block = this.get_block(x, y, z);
return block === VOID || (block !== AIR && (this.#blocks[block]?.has_collision ?? true));
}
// what entities bump into there, see common/physics.ts. unloaded chunks are full blocks, like has_collision
collision_shape(x: number, y: number, z: number): boolean | Shape {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
if (nid === VOID) return true;
if (nid === AIR) return false;
const block = this.#blocks[nid];
return block ? collision_shape_at(block, value) : true;
}
// 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 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;
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
fluid_at(x: number, y: number, z: number) {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
return nid === VOID || nid === AIR ? undefined : fluid_in_cell(value, this.#blocks[nid]);
}
// water, or a block waterlogged with it, see fluid_block. unloaded chunks aren't
is_fluid(x: number, y: number, z: number) {
const value = this.get_block_value(x, y, z);
const block = value & ID_MASK;
return block !== VOID && block !== AIR && fluid_block(value, this.#blocks[block]) !== undefined;
}
// only changes what this client shows, drops and everything else happen on the server
break_block(x: number, y: number, z: number) {
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 || !this.shape.contains(y)) {
return;
}
this.#retain(x, y, z);
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.column.set(x, y, z, fluid);
this.#block_changed(chunk, x, y, z, old_nid, fluid);
}
// 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;
}
// 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);
}
}
}
}
// 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
// client guessed waits for the server's ack instead, see BlockPredictions
apply_change(x: number, y: number, z: number, id: string, state = 0) {
if (this.predictions.from_server(x, y, z, id, state)) {
return;
}
this.#set_from_server(x, y, z, id, state);
}
// the server handled this client's guesses up to seq, what it said about the blocks they changed shows now
ack_predictions(seq: number) {
for (const { x, y, z, id, state } of this.predictions.ack(seq)) {
this.#set_from_server(x, y, z, id, state);
}
}
// while guessing, keeps what's at x y z before the guess changes it, as the server would say it
#retain(x: number, y: number, z: number) {
this.predictions.retain(x, y, z, () => {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
const id = nid === AIR ? AIR_ID : this.#blocks[nid]?.id ?? AIR_ID;
return { x, y, z, id, state: value >>> 16 };
});
}
#set_from_server(x: number, y: number, z: number, id: string, state: number) {
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!chunk) {
return;
}
const current = this.get_block(x, y, z);
if (id === AIR_ID) {
if (current !== AIR) {
this.break_block(x, y, z);
}
return;
}
const nid = EverythingRegistry.get_id("blocks", id);
if (nid === undefined || block_value(nid, state) === this.get_block_value(x, y, z)) {
return;
}
this.add_block({ x, y, z, id }, state);
}
// also what forget_level_chunk does
unload_chunk(cx: number, cz: number) {
const key = chunk_key(cx, cz);
const chunk = this.chunks.get(key);
if (!chunk) {
return;
}
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) {
if (Math.floor(x / CHUNK_SIZE) === cx && Math.floor(z / CHUNK_SIZE) === cz) {
this.break_progress.delete(position);
}
}
}
// see break_progress in common/protocol.ts
set_break_progress(x: number, y: number, z: number, stage: number | undefined) {
if (stage === undefined) this.break_progress.delete(`${x},${y},${z}`);
else this.break_progress.set(`${x},${y},${z}`, { x, y, z, stage });
}
// see block_data in common/protocol.ts
set_block_data(x: number, y: number, z: number, changed: Record<string, unknown>) {
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!this.chunks.has(key)) return;
let blocks = this.block_data.get(key);
const position = `${x},${y},${z}`;
const data = { ...blocks?.get(position)?.data };
for (const [field, value] of Object.entries(changed)) {
if (value === null) delete data[field];
else data[field] = value;
}
if (Object.keys(data).length > 0) {
if (!blocks) {
blocks = new Map();
this.block_data.set(key, blocks);
}
blocks.set(position, { x, y, z, data });
} else if (blocks?.delete(position) && blocks.size === 0) {
this.block_data.delete(key);
}
this.visuals.data_changed(x, y, z);
}
get_block_data(x: number, y: number, z: number): Readonly<Record<string, unknown>> | undefined {
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data;
}
// 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 NEIGHBOR_OFFSETS) {
if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
return false;
}
}
return true;
}
// 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 the sections around the ones it's for
max_meshes_in_flight = Infinity;
// 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.keys()) {
if (this.can_mesh(chunk)) pending += 1;
}
return pending;
}
// meshes every section again, for the benchmark to time
remesh_all() {
for (const chunk of this.chunks.values()) {
for (const section of chunk.sections) this.#mark_dirty(section);
}
}
// sends every dirty section that can be meshed to the workers, a request per chunk
request_meshes(camera: Camera) {
for (const [chunk, sections] of this.#dirty) {
if (this.meshes_in_flight >= this.max_meshes_in_flight) {
break;
}
if (!this.can_mesh(chunk)) {
continue;
}
this.#dirty.delete(chunk);
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?.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);
}
}
this.meshes_in_flight += 1;
this.workers.post({
type: "mesh",
chunk_x: chunk.x,
chunk_z: chunk.z,
sections: [...sections].map((section) => ({ index: section.index, version: section.mesh_version })),
first,
chunks,
sky,
biomes,
biome_colors,
camera: [camera.x, camera.y, camera.z],
});
}
}
// 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 section of this.#sorted) {
const sort = section.translucent_sort!;
if (!crosses_planes(sort.planes, sort.camera, position)) {
continue;
}
sort.camera = position;
sort.requested += 1;
this.workers.post({
type: "sort",
chunk_x: section.chunk.x,
chunk_z: section.chunk.z,
index: section.index,
version: sort.mesh_version,
sort_version: sort.requested,
centers: sort.centers,
camera: position,
});
}
}
#on_worker_message(message: FromChunkWorker) {
if (message.type === "meshed") {
this.#on_meshed(message);
} else {
this.#on_sorted(message);
}
}
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
this.meshes_in_flight -= 1;
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
if (!chunk) {
return;
}
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;
}
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);
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 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;
}
sort.applied = message.sort_version;
if (mesh.index_buffer) {
destroy_buffer(mesh.index_buffer);
}
mesh.index_buffer = create_index_buffer(message.indices);
}
#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);
}
}
section.meshes = {};
section.translucent_sort = undefined;
this.#sorted.delete(section);
}
// 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() {
let count = 0;
for (const sections of this.#dirty.values()) count += sections.size;
return count;
}
#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.
// only the ones filter allows
pick_entity(
x: number,
y: number,
z: number,
yaw: number,
pitch: number,
max_distance: number,
filter: (entity: Entity) => boolean,
): { entity: Entity; distance: number } | undefined {
const cos_pitch = Math.cos(pitch);
const direction = [-Math.sin(yaw) * cos_pitch, Math.sin(pitch), -Math.cos(yaw) * cos_pitch];
const origin = [x, y, z];
let closest: { entity: Entity; distance: number } | undefined;
for (const entity of this.entities.values()) {
if (!filter(entity)) continue;
const half = entity.width / 2;
const min = [entity.x - half, entity.y, entity.z - half];
const max = [entity.x + half, entity.y + entity.height, entity.z + half];
// where the ray enters and leaves the box, one axis at a time
let enter = 0;
let leave = closest?.distance ?? max_distance;
for (let axis = 0; axis < 3 && enter <= leave; axis++) {
if (Math.abs(direction[axis]) < 1e-9) {
if (origin[axis] < min[axis] || origin[axis] > max[axis]) enter = Infinity;
continue;
}
const a = (min[axis] - origin[axis]) / direction[axis];
const b = (max[axis] - origin[axis]) / direction[axis];
enter = Math.max(enter, Math.min(a, b));
leave = Math.min(leave, Math.max(a, b));
}
if (enter <= leave) {
closest = { entity, distance: enter };
}
}
return closest;
}
// the first block along the view of something at x/y/z looking at yaw/pitch, like minecraft's pick. it has to go
// into one of the block's boxes (see common/block_shapes.ts), so it looks past the empty half of a slab. it looks
// through fluids unless fluids is set, see ItemRegistry.targets_fluids
pick(
x: number,
y: number,
z: number,
yaw: number,
pitch: number,
max_distance = 6,
fluids = false,
step = 0.05,
): BlockHitResult | undefined {
const cos_pitch = Math.cos(pitch);
const direction = [-Math.sin(yaw) * cos_pitch, Math.sin(pitch), -Math.cos(yaw) * cos_pitch];
const origin = [x, y, z];
let prev_bx = Math.floor(x);
let prev_by = Math.floor(y);
let prev_bz = Math.floor(z);
// a little past the end, so a block whose cell the steps reach after max_distance is still tried
for (let dist = step; dist <= max_distance + step; dist += step) {
const bx = Math.floor(origin[0] + direction[0] * dist);
const by = Math.floor(origin[1] + direction[1] * dist);
const bz = Math.floor(origin[2] + direction[2] * dist);
if (bx === prev_bx && by === prev_by && bz === prev_bz) {
continue;
}
prev_bx = bx;
prev_by = by;
prev_bz = bz;
const value = this.get_block_value(bx, by, bz);
const block = value & ID_MASK;
if (block === AIR || block === VOID) {
continue;
}
const info = this.#blocks[block];
if (!fluids && is_fluid_block(info)) {
continue;
}
// aimed at fluids, the source in a waterlogged block covers it, like the server's raycast_shape
const covered = fluids && is_waterlogged(value, info);
const hit = clip_shape(
!info || covered ? FULL_SHAPE : shape_at(info, value),
bx,
by,
bz,
origin,
direction,
max_distance,
);
if (!hit) {
continue;
}
// the side of the box it went in by
const face: Faces = hit.axis === 0
? (hit.sign > 0 ? "west" : "east")
: hit.axis === 1
? (hit.sign > 0 ? "bottom" : "top")
: (hit.sign > 0 ? "north" : "south");
const at = [0, 1, 2].map((axis) =>
Math.min(Math.max(origin[axis] + direction[axis] * hit.distance - [bx, by, bz][axis], 0), 1)
);
return { x: bx, y: by, z: bz, face, block, hit: [at[0], at[1], at[2]] };
}
return undefined;
}
}
// functions cant be sent to workers
// deno-lint-ignore no-explicit-any
function strip_functions<T extends Record<string, any>>(obj: T): T {
// deno-lint-ignore no-explicit-any
const out: any = Array.isArray(obj) ? [] : {};
for (const k in obj) {
const v = obj[k];
if (typeof v === "function") continue;
if (v && typeof v === "object") {
out[k] = strip_functions(v);
} else {
out[k] = v;
}
}
return out;
}