Meshing and lighting per section

This commit is contained in:
2026-11-07 11:41:21 -03:00
parent 71cbf901a5
commit b726ce9695
21 changed files with 736 additions and 544 deletions
+1 -1
View File
@@ -334,7 +334,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,
};
}
+2 -2
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;
}
+9 -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,11 @@ 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 + (mesh.index_buffer?.size ?? 0);
}
}
this.#chunk_stats = { meshed, bytes };
return this.#chunk_stats;
+185 -162
View File
@@ -13,17 +13,16 @@ 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,
light_tables,
RENDER_LAYERS,
RenderLayer,
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, section_index, type SectionData } from "@/common/section.ts";
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, section_index, 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";
@@ -50,19 +49,29 @@ export interface Chunk {
z: number;
// its blocks and each column's biome, as the server sent them
column: ChunkColumn;
dirty: boolean;
// 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 column's biome grass color, x then z, then each column's foliage color, then water color
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 grass color, x then z, then each column's foliage color, then water color
biome_colors: Uint32Array;
// from its last mesh by section, see get_light. undefined until it's been meshed
light?: SectionLight[];
// from its last mesh, see get_light. undefined until it's been meshed
light?: SectionLight;
}
export interface ChunkMesh {
@@ -107,9 +116,10 @@ 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;
@@ -119,9 +129,12 @@ const STORAGE_MARGIN = 3;
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>();
second_timer = 0;
tick_timer = 0;
// world time in ticks, counted here between the server's updates. see common/time.ts
@@ -139,6 +152,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;
@@ -219,34 +233,23 @@ export class ClientLevel {
biome_colors[CHUNK_AREA * 2 + column] = 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
// 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,
column,
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++) {
chunk.sections.push({ chunk, index, mesh_version: 0, meshes: {}, min_y: Infinity, max_y: -Infinity });
}
this.chunks.set(chunk_key(x, z), chunk);
}
// 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
@@ -269,11 +272,12 @@ 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();
this.chunks.clear();
this.#dirty.clear();
this.drawn.clear();
}
get_chunk(x: number, z: number) {
@@ -296,29 +300,23 @@ export class ClientLevel {
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 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.#mark_dirty(chunk);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
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. the shape's open light (full sky light, unless
// 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_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 this.shape.open_light;
const section = light[(block_y - this.shape.min_y) >> 4];
return typeof section === "number" ? section : section[section_index(Math.floor(x), block_y, Math.floor(z))];
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
@@ -403,8 +401,6 @@ export class ClientLevel {
this.#retain(x, y, z);
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const old_value = chunk.column.get(x, y, z);
const old_nid = old_value & ID_MASK;
const old_block = this.#blocks[old_nid];
@@ -413,56 +409,53 @@ export class ClientLevel {
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
: AIR;
chunk.column.set(x, y, z, fluid);
this.#mark_dirty(chunk);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, 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);
// 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);
}
}
}
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 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]);
}
}
@@ -520,9 +513,12 @@ 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);
}
this.#dirty.delete(chunk);
this.chunks.delete(key);
this.block_data.delete(key);
this.visuals.unload(cx, cz);
for (const [position, { x, z }] of this.break_progress) {
@@ -566,10 +562,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;
}
@@ -577,46 +573,59 @@ 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;
// the worker lights the whole 3x3 area. posting copies the sections' blocks, only of the ones that aren't all
// one block
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 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.map((section) => section.data) ?? null);
chunks.push(neighbor?.column.sections.slice(first, end).map((section) => section.data) ?? null);
sky.push(neighbor?.sky ?? null);
biome_colors.push(neighbor?.biome_colors ?? null);
}
}
@@ -625,20 +634,22 @@ 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,
biome_colors,
camera: [camera.x, camera.y, camera.z],
});
}
}
// 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;
}
@@ -646,8 +657,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,
@@ -667,47 +679,55 @@ 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, this.shape.min_y, 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);
section.light = mesh.light;
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 RENDER_LAYERS) {
const { vertices, quad_count, groups } = mesh[layer];
if (quad_count === 0) {
continue;
}
section.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
}
const translucent = mesh.translucent;
if (translucent.quad_count === 0) {
continue;
}
section.meshes.translucent!.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;
@@ -719,26 +739,29 @@ export class ClientLevel {
mesh.index_buffer = create_index_buffer(message.indices);
}
delete_chunk_mesh(chunk: Chunk) {
for (const mesh of Object.values(chunk.meshes)) {
#delete_mesh(section: RenderSection) {
for (const mesh of Object.values(section.meshes)) {
destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) {
destroy_buffer(mesh.index_buffer);
}
}
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
// 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.
+42 -34
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";
@@ -42,15 +48,17 @@ import { draw_visuals } from "./visuals.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
#visible_chunks = new Set<Chunk>();
// 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;
}
@@ -65,8 +73,8 @@ export class LevelRenderer {
for (const layer of ["solid", "cutout"] as const) {
if (!this.draw[layer]) continue;
profiler.section(layer, () => {
for (const chunk of this.#visible) {
const mesh = chunk.meshes[layer];
for (const section of this.#visible) {
const mesh = section.meshes[layer];
if (mesh) {
draw_facing_camera(layer, mesh, camera);
}
@@ -75,52 +83,44 @@ export class LevelRenderer {
}
}
// 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
#find_visible(level: ClientLevel, camera: Camera) {
level.request_meshes(camera);
level.update_translucent_sorting(camera);
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);
const visible: { section: RenderSection; distance: number }[] = [];
this.#visible_chunks.clear();
for (const section of level.drawn) {
if (this.#in_view(section)) {
visible.push({ section, distance: distance_sq(section, camera) });
this.#visible_chunks.add(section.chunk);
}
}
// 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));
visible.sort((a, b) => a.distance - b.distance);
this.#visible = visible.map(({ section }) => section);
}
// 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
// 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) {
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 +178,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 +251,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;
+35 -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 counted from y 0, see #entry
// 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,32 +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 (from min_y, the
// bottom of the world) 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, min_y: 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 local = found[i];
const index = local + min_y * CHUNK_AREA;
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 + (local % CHUNK_SIZE);
const z = chunk_z * CHUNK_SIZE + Math.floor(local / CHUNK_SIZE) % CHUNK_SIZE;
const made = this.#create(x, min_y + Math.floor(local / 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);
}
@@ -280,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 {
+40 -22
View File
@@ -40,17 +40,24 @@ 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. the chunks meshed hold all of its height
// 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;
// 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
// bottom of the world up, null for a chunk that isn't loaded
// 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 colors (see Chunk.biome_colors in client_level.ts), blended across their edges
biome_colors: (Uint32Array | null)[];
// where the camera is, to sort the translucent quads
@@ -60,6 +67,8 @@ 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;
@@ -78,36 +87,45 @@ 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;
// 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 in the world, 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 by section, from the bottom of the world up, see SectionLight. entities are lit from it
light: SectionLight[];
// the blocks in it with visuals, as pairs of the block's index in the chunk (y from the bottom of the world, then
// z, then x) and its value
visuals: Uint32Array<ArrayBuffer>;
}
| {
type: "sorted";
chunk_x: number;
chunk_z: number;
index: number;
version: number;
sort_version: number;
indices: Uint32Array;
+75 -67
View File
@@ -16,6 +16,7 @@ import {
type FaceGroup,
type FromChunkWorker,
type SectionLight,
type SectionMesh,
TERRAIN_QUAD_BYTES,
TERRAIN_VERTEX_BYTES,
type ToChunkWorker,
@@ -99,8 +100,7 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE);
const block_visual = new Uint8Array(TABLE_SIZE);
const HAS_VISUAL = 1;
const REPLACED_MODEL = 2;
// the 3x3 chunks being meshed, made for the dimension's height by "init". its y, like the mesher's, counts from the
// bottom of the world
// 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;
@@ -149,33 +149,31 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
break;
case "mesh": {
const chunks = message.chunks.map((data) => data?.map((section) => new Section(section)) ?? null);
region.fill(chunks);
// 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,
chunks,
message.camera,
);
const light = chunk_light();
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),
};
});
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.filter((section) => typeof section !== "number").map((section) => section.buffer),
sections.flatMap(({ light, visuals, solid, cutout, translucent }) => [
...typeof light === "number" ? [] : [light.buffer],
visuals.buffer,
solid.vertices.buffer,
cutout.vertices.buffer,
@@ -183,7 +181,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
translucent.indices.buffer,
translucent.centers.buffer,
...translucent.planes.map((planes) => planes.buffer),
],
]),
);
break;
}
@@ -194,6 +192,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,
@@ -203,27 +202,23 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
}
};
// the middle chunk of the light region, packed for the main thread by section, see "meshed"
const section_light = new Uint8Array(SECTION_VOLUME);
// 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 chunk_light(): SectionLight[] {
const sections: SectionLight[] = [];
for (let bottom = 0; bottom < region.height; bottom += SECTION_HEIGHT) {
let same = true;
for (let y = 0; y < SECTION_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const from = (bottom + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
const to = (y << 8) | (z << 4);
for (let x = 0; x < CHUNK_SIZE; x++) {
const light = (region.block_light[from + x] << 4) | region.sky[from + x];
section_light[to + x] = light;
if (light !== section_light[0]) same = false;
}
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 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++) {
const light = (region.block_light[at + x] << 4) | region.sky[at + x];
packed_light[to + x] = light;
if (light !== packed_light[0]) same = false;
}
}
sections.push(same ? section_light[0] : section_light.slice());
}
return sections;
return same ? packed_light[0] : packed_light.slice();
}
function post(message: FromChunkWorker, transfer: Transferable[]) {
@@ -553,8 +548,8 @@ 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
// 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;
@@ -649,22 +644,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: (Section[] | null)[], camera: number[]) {
const middle = 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
@@ -673,7 +685,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] |
// 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 = world_min_y + y;
const wy = bottom + y;
const wz = chunk_z * CHUNK_SIZE + z;
const tint = quad.tint === GRASS
? blended[z * CHUNK_SIZE + x]
@@ -706,13 +718,9 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] |
}
};
for (let y = 0; y < region.height; y++) {
const section = middle[y >> 4];
// nothing to mesh in a section of air
if (section.blocks === null && section.value === AIR) {
y |= 15;
continue;
}
// 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++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
// the middle chunk of the region
@@ -758,10 +766,10 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] |
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 (world_min_y + y - 1 < mesh_min_y) mesh_min_y = world_min_y + y - 1;
if (world_min_y + y + 2 > mesh_max_y) mesh_max_y = world_min_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;
}
@@ -805,8 +813,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] |
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: {
+32 -26
View File
@@ -6,16 +6,18 @@
// 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 the bottom of the world, 0 is the dimension's min_y. in a dimension without sky light
// there's only block light
// 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_SIZE, ID_MASK } from "@/common/constants.ts";
import type { Section } from "@/common/section.ts";
import type { WorldShapeJson } from "@/common/world_shape.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;
@@ -29,34 +31,42 @@ export interface LightTables {
}
export class LightRegion {
// the dimension's, in blocks
readonly height: number;
// 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: 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;
// room for the dimension's whole height
constructor(shape: WorldShapeJson) {
this.height = shape.max_y - shape.min_y;
this.sky_light = shape.sky_light;
const volume = REGION_LAYER * this.height;
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 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z, by section. missing ones are
// void
fill(chunks: (Section[] | null)[]) {
// 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 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++) {
@@ -80,19 +90,14 @@ export class LightRegion {
}
#compute_sky({ opacity }: LightTables) {
const { blocks, sky, height: world_height } = 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 = world_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,
@@ -108,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(world_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);
}
@@ -120,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 < blocks.length; i++) {
for (let i = 0; i < volume; i++) {
const level = emission[blocks[i]];
if (level > 0) {
block_light[i] = level;