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 { return {
draw_calls, draw_calls,
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0), 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, 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 // 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 // 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 // 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 // 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 // what the first paced frame drew, which runs of the same version should about agree on
draw_calls: number; draw_calls: number;
quads: number; quads: number;
chunks_in_view: number; sections_in_view: number;
entities_in_view: number; entities_in_view: number;
} }
+9 -6
View File
@@ -98,8 +98,9 @@ export class DebugOverlay {
const level = client.level; const level = client.level;
const level_renderer = client.game_renderer.level_renderer; const level_renderer = client.game_renderer.level_renderer;
const { meshed, bytes } = this.#count_chunks(client); const { meshed, bytes } = this.#count_chunks(client);
text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`); text(`chunks: ${level.chunks.size} loaded`);
text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} meshing`); 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(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`);
text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`); text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`);
separator(); 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) { #count_chunks(client: Client) {
const now = performance.now(); const now = performance.now();
if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats; if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats;
@@ -150,9 +151,11 @@ export class DebugOverlay {
let meshed = 0; let meshed = 0;
let bytes = 0; let bytes = 0;
for (const chunk of client.level.chunks.values()) { for (const chunk of client.level.chunks.values()) {
const meshes = Object.values(chunk.meshes); for (const section of chunk.sections) {
if (meshes.length > 0) meshed += 1; const meshes = Object.values(section.meshes);
for (const mesh of meshes) bytes += mesh.vertex_buffer.size + (mesh.index_buffer?.size ?? 0); 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 }; this.#chunk_stats = { meshed, bytes };
return this.#chunk_stats; 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 { 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 { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "@/common/worldgen/biome_colors.ts";
import { import {
block_light_emission,
block_light_opacity,
BlockRegistry, BlockRegistry,
EverythingRegistry, EverythingRegistry,
is_fluid_block, is_fluid_block,
light_tables,
RENDER_LAYERS, RENDER_LAYERS,
RenderLayer, RenderLayer,
} from "@/common/everything_registry.ts"; } from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, 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 type { WorldShape } from "@/common/world_shape.ts"; import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, section_index, type SectionData } from "@/common/section.ts"; import { ChunkColumn, column_heights, section_index, type SectionData } from "@/common/section.ts";
import { AssetManager } from "../assets.ts"; import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts"; import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts"; import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts";
@@ -50,19 +49,29 @@ export interface Chunk {
z: number; z: number;
// its blocks and each column's biome, as the server sent them // its blocks and each column's biome, as the server sent them
column: ChunkColumn; 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 // bumped on every mesh request so late results from older requests get ignored
mesh_version: number; mesh_version: number;
meshes: Partial<Record<RenderLayer, ChunkMesh>>; 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; min_y: number;
max_y: number; max_y: number;
// only for translucent meshes that have to be sorted again as the camera moves // only for translucent meshes that have to be sorted again as the camera moves
translucent_sort?: TranslucentSort; translucent_sort?: TranslucentSort;
// each column's biome grass color, x then z, then each column's foliage color, then water color // from its last mesh, see get_light. undefined until it's been meshed
biome_colors: Uint32Array; light?: SectionLight;
// from its last mesh by section, see get_light. undefined until it's been meshed
light?: SectionLight[];
} }
export interface ChunkMesh { export interface ChunkMesh {
@@ -107,9 +116,10 @@ export interface BlockData {
data: Record<string, unknown>; 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 neighbors
// light spreads diagonally too, so meshing and lighting need all 8 const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-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 // 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 // which ones to forget, this only catches the ones it didn't
const STORAGE_MARGIN = 3; const STORAGE_MARGIN = 3;
@@ -119,9 +129,12 @@ const STORAGE_MARGIN = 3;
export class ClientLevel { export class ClientLevel {
image: Texture = AssetManager.instance.get("cubi:textures"); image: Texture = AssetManager.instance.get("cubi:textures");
chunks = new Map<number, Chunk>(); 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 // the sections request_meshes and update_translucent_sorting look at, so they don't go through every one each
#dirty = new Set<Chunk>(); // frame. dirty ones by chunk, since a chunk's go in one request
#sorted = new Set<Chunk>(); #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; second_timer = 0;
tick_timer = 0; tick_timer = 0;
// world time in ticks, counted here between the server's updates. see common/time.ts // world time in ticks, counted here between the server's updates. see common/time.ts
@@ -139,6 +152,7 @@ export class ClientLevel {
workers: ChunkWorkerPool; workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks"); #blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
#light = light_tables(this.#blocks);
// the server's numeric block ids to this client's // the server's numeric block ids to this client's
#to_local: Uint32Array; #to_local: Uint32Array;
@@ -219,34 +233,23 @@ export class ClientLevel {
biome_colors[CHUNK_AREA * 2 + column] = water_color(biome); 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); const chunk = this.get_chunk(x, z);
if (chunk) { 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.column = column;
chunk.sky = sky;
chunk.biome_colors = biome_colors; chunk.biome_colors = biome_colors;
this.#mark_dirty(chunk);
} else { } else {
const chunk: Chunk = { const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] };
x, for (let index = 0; index < column.sections.length; index++) {
z, chunk.sections.push({ chunk, index, mesh_version: 0, meshes: {}, min_y: Infinity, max_y: -Infinity });
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);
} }
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 // 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() { dispose() {
this.workers.terminate(); this.workers.terminate();
for (const chunk of this.chunks.values()) { 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.visuals.dispose();
this.chunks.clear(); this.chunks.clear();
this.#dirty.clear(); this.#dirty.clear();
this.drawn.clear();
} }
get_chunk(x: number, z: number) { get_chunk(x: number, z: number) {
@@ -296,29 +300,23 @@ export class ClientLevel {
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!; const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
this.#retain(block.x, block.y, block.z); 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 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); const value = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
chunk.column.set(block.x, block.y, block.z, value); chunk.column.set(block.x, block.y, block.z, value);
this.#mark_dirty(chunk); this.#block_changed(chunk, block.x, block.y, block.z, old_nid, nid);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, 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 // the dimension has none) above the world and where it isn't known yet, so entities don't go dark while their
// chunk loads // chunk loads
get_light(x: number, y: number, z: number): number { get_light(x: number, y: number, z: number): number {
const block_y = Math.floor(y); const block_y = Math.floor(y);
if (block_y >= this.shape.max_y) return this.shape.open_light; if (block_y >= this.shape.max_y) return this.shape.open_light;
if (block_y < this.shape.min_y) return 0; if (block_y < this.shape.min_y) return 0;
const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
const chunk_z = Math.floor(z / CHUNK_SIZE); const light = chunk?.sections[(block_y - this.shape.min_y) >> 4].light;
const light = this.get_chunk(chunk_x, chunk_z)?.light; if (light === undefined) return this.shape.open_light;
if (!light) return this.shape.open_light; return typeof light === "number" ? light : light[section_index(Math.floor(x), block_y, Math.floor(z))];
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))];
} }
// the id with its state bits, VOID outside loaded chunks // the id with its state bits, VOID outside loaded chunks
@@ -403,8 +401,6 @@ export class ClientLevel {
this.#retain(x, y, z); 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_value = chunk.column.get(x, y, z);
const old_nid = old_value & ID_MASK; const old_nid = old_value & ID_MASK;
const old_block = this.#blocks[old_nid]; const old_block = this.#blocks[old_nid];
@@ -413,56 +409,53 @@ export class ClientLevel {
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR ? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
: AIR; : AIR;
chunk.column.set(x, y, z, fluid); chunk.column.set(x, y, z, fluid);
this.#mark_dirty(chunk); this.#block_changed(chunk, x, y, z, old_nid, fluid);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, fluid);
} }
// a block that lets through or gives off a different amount of light changes the light up to 15 blocks // what a block changing remeshes: its section, and the ones beside it when it's on their border. a block that lets
// away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces // through or gives off a different amount of light changes the light up to 15 blocks away, so in every section
#mark_neighbors_dirty( // around it, and when it moves its column's sky height, from the old height to the new one in the columns around
block_chunk_x: number, #block_changed(chunk: Chunk, x: number, y: number, z: number, old_nid: number, new_nid: number) {
block_chunk_z: number, const { opacity, emission } = this.#light;
lx: number, if (opacity[old_nid] !== opacity[new_nid] || emission[old_nid] !== emission[new_nid]) {
lz: number, const column = (z & 15) * CHUNK_SIZE + (x & 15);
old_nid: number, const old_sky = chunk.sky[column];
new_nid: number, chunk.sky = column_heights(chunk.column, opacity).slice(CHUNK_AREA);
) { const new_sky = chunk.sky[column];
const old_block = this.#blocks[old_nid]; const changed = old_sky === new_sky ? [y] : [y, old_sky, new_sky];
const new_block = this.#blocks[new_nid]; this.#mark_dirty_around(
if ( chunk.x,
block_light_opacity(old_block) !== block_light_opacity(new_block) || chunk.z,
block_light_emission(old_block) !== block_light_emission(new_block) Math.min(...changed) - LIGHT_REACH,
) { Math.max(...changed) + LIGHT_REACH,
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);
}
}
return; return;
} }
if (lx === 0) { // the way to the neighbor on each axis whose faces it's next to, 0 for none
const n = this.get_chunk(block_chunk_x - 1, block_chunk_z); const side = (local: number) => local === 0 ? -1 : local === CHUNK_SIZE - 1 ? 1 : 0;
if (n) { const sx = side(x & 15);
this.#mark_dirty(n); const sy = side((y - this.shape.min_y) & 15);
} const sz = side(z & 15);
} else if (lx === CHUNK_SIZE - 1) { const index = (y - this.shape.min_y) >> 4;
const n = this.get_chunk(block_chunk_x + 1, block_chunk_z); for (const dx of new Set([0, sx])) {
if (n) { for (const dz of new Set([0, sz])) {
this.#mark_dirty(n); 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) { // the sections from from_y to to_y of a chunk and the 8 around it
this.#mark_dirty(n); #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);
} else if (lz === CHUNK_SIZE - 1) { for (const [dx, dz] of [[0, 0], ...NEIGHBOR_OFFSETS]) {
const n = this.get_chunk(block_chunk_x, block_chunk_z + 1); const sections = this.get_chunk(chunk_x + dx, chunk_z + dz)?.sections ?? [];
if (n) { const highest = Math.min(sections.length - 1, (to_y - this.shape.min_y) >> 4);
this.#mark_dirty(n); for (let i = lowest; i <= highest; i++) this.#mark_dirty(sections[i]);
}
} }
} }
@@ -520,9 +513,12 @@ export class ClientLevel {
if (!chunk) { if (!chunk) {
return; return;
} }
this.delete_chunk_mesh(chunk); for (const section of chunk.sections) {
this.chunks.delete(key); this.#delete_mesh(section);
this.drawn.delete(section);
}
this.#dirty.delete(chunk); this.#dirty.delete(chunk);
this.chunks.delete(key);
this.block_data.delete(key); this.block_data.delete(key);
this.visuals.unload(cx, cz); this.visuals.unload(cx, cz);
for (const [position, { x, z }] of this.break_progress) { 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; 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 // a chunk's sections are only meshed once all its neighbors exist, otherwise their border faces and light would be
// wrong and it would have to be meshed again as each neighbor loads // wrong and they would have to be meshed again as each neighbor loads
can_mesh(chunk: Chunk) { 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)) { if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
return false; return false;
} }
@@ -577,46 +573,59 @@ export class ClientLevel {
return true; 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; 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 // 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; 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() { get meshes_pending() {
let pending = this.meshes_in_flight; 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; if (this.can_mesh(chunk)) pending += 1;
} }
return pending; return pending;
} }
// meshes every chunk again, for the benchmark to time // meshes every section again, for the benchmark to time
remesh_all() { 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) { 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) { if (this.meshes_in_flight >= this.max_meshes_in_flight) {
break; break;
} }
if (!this.can_mesh(chunk)) { if (!this.can_mesh(chunk)) {
continue; continue;
} }
chunk.dirty = false;
this.#dirty.delete(chunk); this.#dirty.delete(chunk);
chunk.mesh_version += 1; let lowest = Infinity;
// the worker lights the whole 3x3 area. posting copies the sections' blocks, only of the ones that aren't all let highest = -Infinity;
// one block 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 chunks: (SectionData[] | null)[] = [];
const sky: (Int16Array | null)[] = [];
const biome_colors: (Uint32Array | null)[] = []; const biome_colors: (Uint32Array | null)[] = [];
for (let dz = -1; dz <= 1; dz++) { for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) { for (let dx = -1; dx <= 1; dx++) {
const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz); 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); biome_colors.push(neighbor?.biome_colors ?? null);
} }
} }
@@ -625,20 +634,22 @@ export class ClientLevel {
type: "mesh", type: "mesh",
chunk_x: chunk.x, chunk_x: chunk.x,
chunk_z: chunk.z, chunk_z: chunk.z,
version: chunk.mesh_version, sections: [...sections].map((section) => ({ index: section.index, version: section.mesh_version })),
first,
chunks, chunks,
sky,
biome_colors, biome_colors,
camera: [camera.x, camera.y, camera.z], camera: [camera.x, camera.y, camera.z],
}); });
} }
} }
// like sodium, a chunk's translucent quads only change order when the camera crosses one of the // like sodium, a section's translucent quads only change order when the camera crosses one of the planes they lie
// planes they lie on, so that's the only time they get sorted again // on, so that's the only time they get sorted again
update_translucent_sorting(camera: Camera) { update_translucent_sorting(camera: Camera) {
const position = [camera.x, camera.y, camera.z]; const position = [camera.x, camera.y, camera.z];
for (const chunk of this.#sorted) { for (const section of this.#sorted) {
const sort = chunk.translucent_sort!; const sort = section.translucent_sort!;
if (!crosses_planes(sort.planes, sort.camera, position)) { if (!crosses_planes(sort.planes, sort.camera, position)) {
continue; continue;
} }
@@ -646,8 +657,9 @@ export class ClientLevel {
sort.requested += 1; sort.requested += 1;
this.workers.post({ this.workers.post({
type: "sort", type: "sort",
chunk_x: chunk.x, chunk_x: section.chunk.x,
chunk_z: chunk.z, chunk_z: section.chunk.z,
index: section.index,
version: sort.mesh_version, version: sort.mesh_version,
sort_version: sort.requested, sort_version: sort.requested,
centers: sort.centers, centers: sort.centers,
@@ -667,47 +679,55 @@ export class ClientLevel {
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) { #on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
this.meshes_in_flight -= 1; this.meshes_in_flight -= 1;
const chunk = this.get_chunk(message.chunk_x, message.chunk_z); const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
// unloaded, or remeshed again since this was requested if (!chunk) {
if (!chunk || chunk.mesh_version !== message.version) {
return; return;
} }
for (const mesh of message.sections) {
this.delete_chunk_mesh(chunk); const section = chunk.sections[mesh.index];
chunk.light = message.light; // remeshed again since this was requested
chunk.min_y = message.min_y; if (section.mesh_version !== mesh.version) {
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) {
continue; 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; for (const layer of RENDER_LAYERS) {
if (translucent.quad_count === 0) { const { vertices, quad_count, groups } = mesh[layer];
return; if (quad_count === 0) {
} continue;
chunk.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices); }
if (translucent.sort_type === "dynamic") { section.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
this.#sorted.add(chunk); }
chunk.translucent_sort = {
mesh_version: message.version, const translucent = mesh.translucent;
centers: translucent.centers, if (translucent.quad_count === 0) {
planes: translucent.planes, continue;
camera: message.camera, }
requested: 0, section.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices);
applied: 0, 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" }>) { #on_sorted(message: Extract<FromChunkWorker, { type: "sorted" }>) {
const chunk = this.get_chunk(message.chunk_x, message.chunk_z); const section = this.get_chunk(message.chunk_x, message.chunk_z)?.sections[message.index];
const sort = chunk?.translucent_sort; const sort = section?.translucent_sort;
const mesh = chunk?.meshes.translucent; const mesh = section?.meshes.translucent;
// remeshed since, or a newer sort already came back // remeshed since, or a newer sort already came back
if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) { if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) {
return; return;
@@ -719,26 +739,29 @@ export class ClientLevel {
mesh.index_buffer = create_index_buffer(message.indices); mesh.index_buffer = create_index_buffer(message.indices);
} }
delete_chunk_mesh(chunk: Chunk) { #delete_mesh(section: RenderSection) {
for (const mesh of Object.values(chunk.meshes)) { for (const mesh of Object.values(section.meshes)) {
destroy_buffer(mesh.vertex_buffer); destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) { if (mesh.index_buffer) {
destroy_buffer(mesh.index_buffer); destroy_buffer(mesh.index_buffer);
} }
} }
chunk.meshes = {}; section.meshes = {};
chunk.translucent_sort = undefined; section.translucent_sort = undefined;
this.#sorted.delete(chunk); 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() { 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) { #mark_dirty(section: RenderSection) {
chunk.dirty = true; const sections = this.#dirty.get(section.chunk);
this.#dirty.add(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. // 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-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // 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 { profiler } from "@/client/profiler.ts";
import { Camera } from "@/client/camera.ts"; import { Camera } from "@/client/camera.ts";
import { AssetManager } from "@/client/assets.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 // draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
export class LevelRenderer { export class LevelRenderer {
frustum = new Frustum(); frustum = new Frustum();
// chunks in view this frame, worked out once for all the layers // sections in view this frame, near to far, worked out once for all the layers
#visible: Chunk[] = []; #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 // 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 }; draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
// entities drawn this frame, for the f3 performance window // entities drawn this frame, for the f3 performance window
#drawn_entities = 0; #drawn_entities = 0;
get visible_chunks() { get visible_sections() {
return this.#visible.length; return this.#visible.length;
} }
@@ -65,8 +73,8 @@ export class LevelRenderer {
for (const layer of ["solid", "cutout"] as const) { for (const layer of ["solid", "cutout"] as const) {
if (!this.draw[layer]) continue; if (!this.draw[layer]) continue;
profiler.section(layer, () => { profiler.section(layer, () => {
for (const chunk of this.#visible) { for (const section of this.#visible) {
const mesh = chunk.meshes[layer]; const mesh = section.meshes[layer];
if (mesh) { if (mesh) {
draw_facing_camera(layer, mesh, camera); 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) { #find_visible(level: ClientLevel, camera: Camera) {
level.request_meshes(camera); level.request_meshes(camera);
level.update_translucent_sorting(camera); level.update_translucent_sorting(camera);
this.frustum.update(view_projection()); this.frustum.update(view_projection());
this.#visible.length = 0; const visible: { section: RenderSection; distance: number }[] = [];
for (const chunk of level.chunks.values()) { this.#visible_chunks.clear();
const drawn = Object.keys(chunk.meshes).length > 0 || level.visuals.has(chunk.x, chunk.z); for (const section of level.drawn) {
if (drawn && this.#in_view(chunk)) { if (this.#in_view(section)) {
this.#visible.push(chunk); 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 // 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 // behind it
const distance_sq = (chunk: Chunk) => { visible.sort((a, b) => a.distance - b.distance);
const dx = (chunk.x + 0.5) * CHUNK_SIZE - camera.x; this.#visible = visible.map(({ section }) => section);
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. // translucent terrain, drawn after entities so they show through water and glass. sections go back to front, and
// chunks go back to front, and each chunk's quads are already sorted back to front // each section's quads are already sorted back to front
render_translucent(_level: ClientLevel, camera: Camera) { render_translucent(_level: ClientLevel, camera: Camera) {
if (!this.draw.translucent) return; if (!this.draw.translucent) return;
const distance_sq = (x: number, z: number) => { const sections = this.#visible
const dx = (x + 0.5) * CHUNK_SIZE - camera.x; .filter((section) => section.meshes.translucent)
const dz = (z + 0.5) * CHUNK_SIZE - camera.z; .map((section) => ({ mesh: section.meshes.translucent!, distance: distance_sq(section, camera) }))
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) }))
.sort((a, b) => b.distance - a.distance); .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); draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer);
} }
} }
#in_view(chunk: Chunk) { #in_view(section: RenderSection) {
const x = chunk.x * CHUNK_SIZE; const x = section.chunk.x * CHUNK_SIZE;
const z = chunk.z * CHUNK_SIZE; const z = section.chunk.z * CHUNK_SIZE;
return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, 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 // 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 // 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) { render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) {
if (!this.draw.visuals) return; 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(); flush_batch();
set_current_texture(level.image.tex); set_current_texture(level.image.tex);
draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]); draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]);
@@ -251,6 +251,14 @@ export class LevelRenderer {
#baked = new Map<number, BakedQuad[]>(); #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 // 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; const ENTITY_CULL_MARGIN = 0.5;
+35 -22
View File
@@ -2,8 +2,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // 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 // 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 // block, made when its section is meshed and kept by chunk. what they draw are instances of models, and every instance
// 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 // 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 // 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 // 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"; import { mat4, vec3 } from "gl-matrix";
@@ -29,6 +29,7 @@ import {
states_of, states_of,
} from "@/common/block_models.ts"; } from "@/common/block_models.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.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 type { ModelFace } from "@/common/mod_data.ts";
import { ItemStack } from "@/common/inventory.ts"; import { ItemStack } from "@/common/inventory.ts";
import { chunk_key, item_texture } from "@/common/utils.ts"; import { chunk_key, item_texture } from "@/common/utils.ts";
@@ -186,7 +187,7 @@ interface Entry {
// a level's visuals // a level's visuals
export class 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>>(); #chunks = new Map<number, Map<number, Entry>>();
#level: VisualsLevel; #level: VisualsLevel;
// baked once per level, since a level's mods don't change // baked once per level, since a level's mods don't change
@@ -213,32 +214,41 @@ export class Visuals {
yield* this.#fluid_groups; 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 // the blocks with visuals a chunk's section was meshed with, as pairs of the block's index in the section (see
// bottom of the world) and its value. visuals for blocks that are gone or changed go, and new ones are made. the // section_index) and its value. bottom is the section's lowest y. visuals in it for blocks that are gone or
// chunk's light came with its mesh, so the ones that stay take it // 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, min_y: number, found: Uint32Array) { meshed(chunk_x: number, chunk_z: number, bottom: number, found: Uint32Array) {
const key = chunk_key(chunk_x, chunk_z); const key = chunk_key(chunk_x, chunk_z);
const old = this.#chunks.get(key) ?? new Map<number, Entry>(); const entries = this.#chunks.get(key) ?? new Map<number, Entry>();
const kept = 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) { for (let i = 0; i < found.length; i += 2) {
const local = found[i]; 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 value = found[i + 1];
const entry = old.get(index); const entry = old.get(index);
old.delete(index); old.delete(index);
if (entry?.value === value) { if (entry?.value === value) {
this.#relight(entry); this.#relight(entry);
kept.set(index, entry);
continue; continue;
} }
if (entry) this.#delete(entry); if (entry) {
const x = chunk_x * CHUNK_SIZE + (local % CHUNK_SIZE); this.#delete(entry);
const z = chunk_z * CHUNK_SIZE + Math.floor(local / CHUNK_SIZE) % CHUNK_SIZE; entries.delete(index);
const made = this.#create(x, min_y + Math.floor(local / CHUNK_AREA), z, value); }
if (made) kept.set(index, made); const made = this.#create(x, y, z, value);
if (made) entries.set(index, made);
} }
for (const entry of old.values()) this.#delete(entry); for (const [index, entry] of old) {
if (kept.size > 0) this.#chunks.set(key, kept); this.#delete(entry);
entries.delete(index);
}
if (entries.size > 0) this.#chunks.set(key, entries);
else this.#chunks.delete(key); else this.#chunks.delete(key);
} }
@@ -280,10 +290,13 @@ export class Visuals {
} }
#entry(x: number, y: number, z: number) { #entry(x: number, y: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE); const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
const chunk_z = Math.floor(z / CHUNK_SIZE); return this.#chunks.get(key)?.get(this.#index(x, y, z));
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);
// 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 { #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 // the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
// ctx.render.register_visual // ctx.render.register_visual
visuals: [number, boolean][]; 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; shape: WorldShapeJson;
} }
// sections of one chunk to mesh, sent together so they're lit together
| { | {
type: "mesh"; type: "mesh";
chunk_x: number; chunk_x: number;
chunk_z: 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 // 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)[]; 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 // the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges
biome_colors: (Uint32Array | null)[]; biome_colors: (Uint32Array | null)[];
// where the camera is, to sort the translucent quads // where the camera is, to sort the translucent quads
@@ -60,6 +67,8 @@ export type ToChunkWorker =
type: "sort"; type: "sort";
chunk_x: number; chunk_x: number;
chunk_z: number; chunk_z: number;
// the section's index in its chunk
index: number;
version: number; version: number;
sort_version: number; sort_version: number;
centers: Float32Array; centers: Float32Array;
@@ -78,36 +87,45 @@ export interface LayerMesh {
groups?: FaceGroup[]; 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 = export type FromChunkWorker =
| { | {
type: "meshed"; type: "meshed";
chunk_x: number; chunk_x: number;
chunk_z: number; chunk_z: number;
version: number; // the sections asked for, in the same order
// the lowest and highest y of the chunk's quads in the world, for frustum culling sections: SectionMesh[];
min_y: number; // what the translucent quads were sorted for
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];
};
camera: number[]; 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"; type: "sorted";
chunk_x: number; chunk_x: number;
chunk_z: number; chunk_z: number;
index: number;
version: number; version: number;
sort_version: number; sort_version: number;
indices: Uint32Array; indices: Uint32Array;
+75 -67
View File
@@ -16,6 +16,7 @@ import {
type FaceGroup, type FaceGroup,
type FromChunkWorker, type FromChunkWorker,
type SectionLight, type SectionLight,
type SectionMesh,
TERRAIN_QUAD_BYTES, TERRAIN_QUAD_BYTES,
TERRAIN_VERTEX_BYTES, TERRAIN_VERTEX_BYTES,
type ToChunkWorker, type ToChunkWorker,
@@ -99,8 +100,7 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE);
const block_visual = new Uint8Array(TABLE_SIZE); const block_visual = new Uint8Array(TABLE_SIZE);
const HAS_VISUAL = 1; const HAS_VISUAL = 1;
const REPLACED_MODEL = 2; 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 // the sections being meshed and the ones around them, made for the dimension's height by "init"
// bottom of the world
let region: LightRegion; let region: LightRegion;
// the dimension's min_y, which quads are moved up by to be where they are in the world // the dimension's min_y, which quads are moved up by to be where they are in the world
let world_min_y = 0; let world_min_y = 0;
@@ -149,33 +149,31 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
break; break;
case "mesh": { case "mesh": {
const chunks = message.chunks.map((data) => data?.map((section) => new Section(section)) ?? null); 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); region.compute(light_tables);
blend_biome_colors(message.biome_colors); blend_biome_colors(message.biome_colors);
const { solid, cutout, translucent, min_y, max_y, visuals } = make_chunk_mesh( const sections: SectionMesh[] = message.sections.map(({ index, version }) => {
message.chunk_x, // the section's bottom in the region
message.chunk_z, const from = (index - message.first) * SECTION_HEIGHT;
chunks, return {
message.camera, index,
); version,
const light = chunk_light(); ...make_section_mesh(message.chunk_x, message.chunk_z, chunks, from, bottom, message.camera),
light: section_light(from),
};
});
post( post(
{ {
type: "meshed", type: "meshed",
chunk_x: message.chunk_x, chunk_x: message.chunk_x,
chunk_z: message.chunk_z, chunk_z: message.chunk_z,
version: message.version, sections,
min_y,
max_y,
solid,
cutout,
translucent,
camera: message.camera, camera: message.camera,
light,
visuals,
}, },
[ sections.flatMap(({ light, visuals, solid, cutout, translucent }) => [
...light.filter((section) => typeof section !== "number").map((section) => section.buffer), ...typeof light === "number" ? [] : [light.buffer],
visuals.buffer, visuals.buffer,
solid.vertices.buffer, solid.vertices.buffer,
cutout.vertices.buffer, cutout.vertices.buffer,
@@ -183,7 +181,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
translucent.indices.buffer, translucent.indices.buffer,
translucent.centers.buffer, translucent.centers.buffer,
...translucent.planes.map((planes) => planes.buffer), ...translucent.planes.map((planes) => planes.buffer),
], ]),
); );
break; break;
} }
@@ -194,6 +192,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
type: "sorted", type: "sorted",
chunk_x: message.chunk_x, chunk_x: message.chunk_x,
chunk_z: message.chunk_z, chunk_z: message.chunk_z,
index: message.index,
version: message.version, version: message.version,
sort_version: message.sort_version, sort_version: message.sort_version,
indices, 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" // the light of the middle chunk's section from this y in the region, packed for the main thread, see SectionLight
const section_light = new Uint8Array(SECTION_VOLUME); const packed_light = new Uint8Array(SECTION_VOLUME);
function chunk_light(): SectionLight[] { function section_light(from: number): SectionLight {
const sections: SectionLight[] = []; let same = true;
for (let bottom = 0; bottom < region.height; bottom += SECTION_HEIGHT) { for (let y = 0; y < SECTION_HEIGHT; y++) {
let same = true; for (let z = 0; z < CHUNK_SIZE; z++) {
for (let y = 0; y < SECTION_HEIGHT; y++) { const at = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
for (let z = 0; z < CHUNK_SIZE; z++) { const to = (y << 8) | (z << 4);
const from = (bottom + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE; for (let x = 0; x < CHUNK_SIZE; x++) {
const to = (y << 8) | (z << 4); const light = (region.block_light[at + x] << 4) | region.sky[at + x];
for (let x = 0; x < CHUNK_SIZE; x++) { packed_light[to + x] = light;
const light = (region.block_light[from + x] << 4) | region.sky[from + x]; if (light !== packed_light[0]) same = false;
section_light[to + x] = light;
if (light !== section_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[]) { function post(message: FromChunkWorker, transfer: Transferable[]) {
@@ -553,8 +548,8 @@ function hides_fluid(nid: number) {
return nid !== AIR && block_layers[nid] === SOLID; 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 // a cell's block with its states, from the 3x3 chunks' sections the region was filled from. 0 (air) outside them and
// chunks that aren't there // for chunks that aren't there
function region_value(chunks: (Section[] | null)[], index: number, y: number) { function region_value(chunks: (Section[] | null)[], index: number, y: number) {
if (y < 0 || y >= region.height) return AIR; if (y < 0 || y >= region.height) return AIR;
const x = index % REGION_SIZE; const x = index % REGION_SIZE;
@@ -649,22 +644,39 @@ function underside(top: MeshQuad): MeshQuad {
}; };
} }
// region has to be filled and lit first // quads being built, kept from one section to the next. solid and cutout get a buffer per face group, translucent one
// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the // for everything since it's sorted instead
// ones around it for fluids, whose surface follows their neighbors' const opaque = [SOLID, CUTOUT].map(() =>
function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | null)[], camera: number[]) { Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
const middle = chunks[4]!; );
// solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead const translucent_quads = new QuadBuffer();
const opaque = [SOLID, CUTOUT].map(() => // for sorting the translucent quads
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity })) let centers = new Float32Array(256);
); let faces = new Uint8Array(256);
const translucent_quads = new QuadBuffer();
// 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_min_y = Infinity;
mesh_max_y = -Infinity; mesh_max_y = -Infinity;
// for sorting the translucent quads // the blocks with visuals, see SectionMesh
let centers = new Float32Array(256);
let faces = new Uint8Array(256);
// the blocks with visuals, see "meshed"
const visuals: number[] = []; const visuals: number[] = [];
// where the neighbor on each face is, same order as FACE_NORMALS // 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 // 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 emit = (quad: MeshQuad, layer_id: number, x: number, y: number, z: number, alpha: number) => {
const wx = chunk_x * CHUNK_SIZE + x; 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 wz = chunk_z * CHUNK_SIZE + z;
const tint = quad.tint === GRASS const tint = quad.tint === GRASS
? blended[z * CHUNK_SIZE + x] ? 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++) { // nothing to mesh in a section of air
const section = middle[y >> 4]; const air = section.blocks === null && section.value === AIR;
// nothing to mesh in a section of air for (let y = from; y < from + SECTION_HEIGHT && !air; y++) {
if (section.blocks === null && section.value === AIR) {
y |= 15;
continue;
}
for (let z = 0; z < CHUNK_SIZE; z++) { for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) { for (let x = 0; x < CHUNK_SIZE; x++) {
// the middle chunk of the region // 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)); const value = section.get(section_index(x, y, z));
if (block_visual[block_nid]) { 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 // 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 (bottom + y - 1 < mesh_min_y) mesh_min_y = bottom + y - 1;
if (world_min_y + y + 2 > mesh_max_y) mesh_max_y = world_min_y + y + 2; if (bottom + y + 2 > mesh_max_y) mesh_max_y = bottom + y + 2;
if (block_visual[block_nid] === REPLACED_MODEL) continue; 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; const [camera_x, camera_y, camera_z] = camera;
return { return {
min_y: mesh_min_y === Infinity ? 0 : mesh_min_y, min_y: mesh_min_y,
max_y: mesh_max_y === -Infinity ? 0 : mesh_max_y, max_y: mesh_max_y,
solid, solid,
cutout, cutout,
translucent: { 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 // 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. // 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 // minecraft stores light and updates it as blocks change. here it's worked out from scratch around the sections being
// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15 // meshed: the 3x3 chunks around theirs, from the section below them to the one above. that gives the same result, since
// blocks, so nothing outside those chunks can light the middle one or its border // 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 // y in a region counts from its bottom, which is a section's. in a dimension without sky light there's only block
// there's only block light // light
import { AIR, 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 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_SIZE = CHUNK_SIZE * 3;
export const REGION_LAYER = REGION_SIZE * REGION_SIZE; export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
@@ -29,34 +31,42 @@ export interface LightTables {
} }
export class LightRegion { export class LightRegion {
// the dimension's, in blocks // in blocks, of the sections last filled in
readonly height: number; height = 0;
readonly sky_light: boolean; readonly sky_light: boolean;
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x // block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
blocks: Uint16Array; blocks: Uint16Array;
sky: Uint8Array; sky: Uint8Array;
block_light: 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); #heights = new Int32Array(REGION_LAYER);
#queue = new Int32Array(1 << 18); #queue = new Int32Array(1 << 18);
#queue_length = 0; #queue_length = 0;
// room for the dimension's whole height
constructor(shape: WorldShapeJson) { constructor(shape: WorldShapeJson) {
this.height = shape.max_y - shape.min_y;
this.sky_light = shape.sky_light; 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.blocks = new Uint16Array(volume);
this.sky = new Uint8Array(volume); this.sky = new Uint8Array(volume);
this.block_light = 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 // the same sections of the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing
// void // chunks are void. sky is each chunk's sky height by column (see column_heights), and bottom the y of the region's
fill(chunks: (Section[] | null)[]) { // 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++) { for (let i = 0; i < 9; i++) {
const source = chunks[i]; const source = chunks[i];
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE; 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++) { for (let y = 0; y < this.height; y++) {
const section = source?.[y >> 4]; const section = source?.[y >> 4];
for (let z = 0; z < CHUNK_SIZE; z++) { for (let z = 0; z < CHUNK_SIZE; z++) {
@@ -80,19 +90,14 @@ export class LightRegion {
} }
#compute_sky({ opacity }: LightTables) { #compute_sky({ opacity }: LightTables) {
const { blocks, sky, height: world_height } = this; const { sky, height: region_height } = this;
sky.fill(0); sky.fill(0, 0, REGION_LAYER * region_height);
this.#queue_length = 0; this.#queue_length = 0;
if (!this.sky_light) return; 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++) { for (let column = 0; column < REGION_LAYER; column++) {
let y = world_height - 1; for (let y = this.#heights[column]; y < region_height; y++) sky[y * REGION_LAYER + column] = 15;
while (y >= 0 && opacity[blocks[y * REGION_LAYER + column]] === 0) {
sky[y * REGION_LAYER + column] = 15;
y--;
}
this.#heights[column] = y + 1;
} }
// only the lit cells next to a darker one can spread: the bottom of each column's sunlight, // 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) { if (z < REGION_SIZE - 1) {
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]); 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++) { for (let y = height; y <= top; y++) {
this.#push(y * REGION_LAYER + column); this.#push(y * REGION_LAYER + column);
} }
@@ -120,10 +125,11 @@ export class LightRegion {
#compute_block_light({ opacity, emission }: LightTables) { #compute_block_light({ opacity, emission }: LightTables) {
const { blocks, block_light } = this; 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; this.#queue_length = 0;
for (let i = 0; i < blocks.length; i++) { for (let i = 0; i < volume; i++) {
const level = emission[blocks[i]]; const level = emission[blocks[i]];
if (level > 0) { if (level > 0) {
block_light[i] = level; block_light[i] = level;
+13
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
import type { TintColor } from "./worldgen/biome_colors.ts"; import type { TintColor } from "./worldgen/biome_colors.ts";
import { ID_MASK } from "./constants.ts";
import type { ItemStack } from "./inventory.ts"; import type { ItemStack } from "./inventory.ts";
import type { BlockPart, BlockVariant } from "./block_models.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; 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 { export interface BlockRegistry {
id: string; id: string;
// what players see, like "Iron Ore". made from the id when not set, see display_name in common/utils.ts // what players see, like "Iron Ore". made from the id when not set, see display_name in common/utils.ts
+4 -12
View File
@@ -4,12 +4,7 @@
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts"; import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, Section, SECTION_VOLUME } from "@/common/section.ts"; import { ChunkColumn, column_heights, Section, SECTION_VOLUME } from "@/common/section.ts";
import { import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts";
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
} from "@/common/everything_registry.ts";
import { generate_raw_chunk, RawChunk, WorldgenSetup } from "@/common/generation.ts"; import { generate_raw_chunk, RawChunk, WorldgenSetup } from "@/common/generation.ts";
import { AIR_ID } from "@/common/protocol.ts"; import { AIR_ID } from "@/common/protocol.ts";
import { block_value, chunk_key } from "@/common/utils.ts"; import { block_value, chunk_key } from "@/common/utils.ts";
@@ -165,12 +160,9 @@ export class ServerWorld {
const { block_ids, default_values } = block_numbering(); const { block_ids, default_values } = block_numbering();
Object.assign(this.block_ids, block_ids); Object.assign(this.block_ids, block_ids);
this.default_values.push(...default_values); this.default_values.push(...default_values);
this.#opacity = new Uint8Array(ID_MASK + 1); const tables = light_tables(EverythingRegistry.get_registry<BlockRegistry>("blocks"));
this.#emission = new Uint8Array(ID_MASK + 1); this.#opacity = tables.opacity;
EverythingRegistry.get_registry<BlockRegistry>("blocks").forEach((block, nid) => { this.#emission = tables.emission;
this.#opacity[nid] = block_light_opacity(block);
this.#emission[nid] = block_light_emission(block);
});
} }
#spawn: { x: number; y: number; z: number } | undefined; #spawn: { x: number; y: number; z: number } | undefined;
+1 -1
View File
@@ -22,7 +22,7 @@ Deno.test("the lows are the fps of the slowest frames", () => {
}); });
Deno.test("a report reads back from what was copied", () => { Deno.test("a report reads back from what was copied", () => {
const scene = { draw_calls: 10, quads: 1000, chunks_in_view: 4, entities_in_view: 0 }; const scene = { draw_calls: 10, quads: 1000, sections_in_view: 4, entities_in_view: 0 };
const report: BenchmarkReport = { const report: BenchmarkReport = {
version: 1, version: 1,
date: "2026-01-01T00:00:00.000Z", date: "2026-01-01T00:00:00.000Z",
+104
View File
@@ -0,0 +1,104 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the client meshes a section at a time, and a block changing only meshes again the sections it can change the look
// or the light of, see ClientLevel's #block_changed
import { assertEquals } from "@std/assert";
import { ClientLevel } from "@/client/level/client_level.ts";
import { AssetManager } from "@/client/assets.ts";
import { Camera } from "@/client/camera.ts";
import type { ToChunkWorker } from "@/client/workers/chunk_messages.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { CHUNK_AREA } from "@/common/constants.ts";
import { ChunkColumn } from "@/common/section.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { test_game } from "./helpers.ts";
const GROUND_TOP = 63;
const ROOF = 200;
// a level of 5x5 chunks of stone up to GROUND_TOP, with a stone roof at ROOF over chunk 0, 0, all meshed. what it asks
// its chunk workers is kept in requests instead of being sent
async function meshed_level() {
await test_game("mods");
AssetManager.instance.assets["cubi:textures"] = { width: 16, height: 16 };
AssetManager.instance.assets["cubi:textures_info"] = {};
const requests: Extract<ToChunkWorker, { type: "mesh" }>[] = [];
const real = globalThis.Worker;
globalThis.Worker = class {
postMessage(message: ToChunkWorker) {
if (message.type === "mesh") requests.push(message);
}
terminate() {}
} as unknown as typeof Worker;
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
let level: ClientLevel;
try {
level = new ClientLevel(Array.from(blocks, (block) => block?.id), DEFAULT_SHAPE, 2);
} finally {
globalThis.Worker = real;
}
const stone = EverythingRegistry.get_id("blocks", "bworld:stone")!;
for (let x = -2; x <= 2; x++) {
for (let z = -2; z <= 2; z++) {
const flat = new Uint32Array(DEFAULT_SHAPE.volume).fill(stone, 0, (GROUND_TOP + 1) * CHUNK_AREA);
if (x === 0 && z === 0) flat.fill(stone, ROOF * CHUNK_AREA, (ROOF + 1) * CHUNK_AREA);
const biomes = new Array(CHUNK_AREA).fill("bworld:plains");
level.set_chunk(ChunkColumn.from_flat(x, z, DEFAULT_SHAPE, flat, biomes));
}
}
const camera = new Camera();
level.request_meshes(camera);
requests.length = 0;
// the sections asked for since the last call, as "chunk x,chunk z: indexes"
const remeshed = () => {
level.request_meshes(camera);
const asked = requests.map(({ chunk_x, chunk_z, sections }) =>
`${chunk_x},${chunk_z}: ${sections.map(({ index }) => index).sort((a, b) => a - b).join(" ")}`
).sort();
requests.length = 0;
return asked;
};
return { level, requests, remeshed };
}
Deno.test("a block that doesn't change the light remeshes its section, and the ones whose border it's on", async () => {
const { level, remeshed } = await meshed_level();
level.add_block({ id: "bworld:cobblestone", x: 8, y: 40, z: 8 });
assertEquals(remeshed(), ["0,0: 2"]);
// at x 0, z 15 and y 32 of its chunk, so next to the chunks to -x and +z and the section below
level.add_block({ id: "bworld:cobblestone", x: 0, y: 32, z: 15 });
assertEquals(remeshed(), ["-1,0: 1 2", "-1,1: 1 2", "0,0: 1 2", "0,1: 1 2"]);
});
Deno.test("a request sends the sections around the ones it's for, and their columns' sky heights", async () => {
const { level, requests } = await meshed_level();
level.add_block({ id: "bworld:cobblestone", x: 8, y: 40, z: 8 });
level.request_meshes(new Camera());
const [request] = requests;
assertEquals(request.first, 1);
assertEquals(request.chunks.map((chunk) => chunk?.length), new Array(9).fill(3));
assertEquals(request.sky[4]![8 * 16 + 8], ROOF + 1);
assertEquals(request.sky[0]![0], GROUND_TOP + 1);
});
Deno.test("opening a hole to the sky remeshes the columns around it from the old sky height to the new", async () => {
const { level, remeshed } = await meshed_level();
level.break_block(8, ROOF, 8);
// the light reaches 15 blocks past where it changes, and a section's faces are lit from the block past them
const from = (GROUND_TOP + 1 - 16) >> 4;
const to = (ROOF + 1 + 16) >> 4;
const sections = Array.from({ length: to - from + 1 }, (_, i) => from + i).join(" ");
const chunks = [];
for (let x = -1; x <= 1; x++) {
for (let z = -1; z <= 1; z++) chunks.push(`${x},${z}: ${sections}`);
}
assertEquals(remeshed(), chunks.sort());
// a light block under the roof changes the light around it, in the sections next to its own
level.add_block({ id: "bworld:light", x: 4, y: 100, z: 4 });
assertEquals(remeshed(), chunks.map((chunk) => chunk.replace(sections, "5 6 7")));
});
+33 -25
View File
@@ -7,8 +7,7 @@ import { assertEquals } from "@std/assert";
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE, type WorldShapeJson } from "@/common/world_shape.ts"; import { DEFAULT_SHAPE, type WorldShapeJson } from "@/common/world_shape.ts";
import { section_data, test_game } from "./helpers.ts"; import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
import type { SectionLight } from "@/client/workers/chunk_messages.ts";
import { section_index } from "@/common/section.ts"; import { section_index } from "@/common/section.ts";
// the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8. y counts from the // the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8. y counts from the
@@ -18,17 +17,7 @@ async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) {
await test_game("mods"); await test_game("mods");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks"); const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const nid = (id: string) => blocks.findIndex((b) => b?.id === id); const nid = (id: string) => blocks.findIndex((b) => b?.id === id);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); const worker = chunk_worker(shape);
worker.postMessage({
type: "init",
shape,
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const chunk = new Uint32Array(volume); const chunk = new Uint32Array(volume);
const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x; const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
for (let x = 0; x < 8; x++) { for (let x = 0; x < 8; x++) {
@@ -38,18 +27,7 @@ async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) {
const empty = () => new Uint32Array(volume); const empty = () => new Uint32Array(volume);
const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()]; const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()];
const meshed = await new Promise<{ light: SectionLight[]; max_y: number }>((resolve) => { const meshed = await mesh_column(worker, shape, chunks);
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
worker.terminate(); worker.terminate();
const light = (x: number, y: number, z: number) => { const light = (x: number, y: number, z: number) => {
const section = meshed.light[y >> 4]; const section = meshed.light[y >> 4];
@@ -85,3 +63,33 @@ Deno.test("a dimension that starts below 0 is lit the same, and meshed where its
assertEquals(light(4, 10, 8).sky, 11); assertEquals(light(4, 10, 8).sky, 11);
assertEquals(max_y, -64 + 21, "the top of the roof"); assertEquals(max_y, -64 + 21, "the top of the roof");
}); });
Deno.test("a section meshed on its own is lit and drawn the same as when its whole column is", async () => {
await test_game("mods");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const nid = (id: string) => blocks.findIndex((b) => b?.id === id);
const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
// ground up to 40 everywhere, and in the middle chunk a roof far above it over x 0-7, which shades sections well
// below it, and a light just under a section's top, which lights the one above
const ground = () => new Uint32Array(DEFAULT_SHAPE.volume).fill(nid("bworld:stone"), 0, at(0, 41, 0));
const chunks = Array.from({ length: 9 }, ground);
for (let x = 0; x < 8; x++) {
for (let z = 0; z < CHUNK_SIZE; z++) chunks[4][at(x, 200, z)] = nid("bworld:stone");
}
chunks[4][at(12, 47, 8)] = nid("bworld:light");
chunks[4][at(3, 41, 3)] = nid("bworld:glass");
const worker = chunk_worker(DEFAULT_SHAPE);
const whole = await mesh_column(worker, DEFAULT_SHAPE, chunks);
for (const [index, expected] of whole.sections.entries()) {
const [alone] = (await mesh_column(worker, DEFAULT_SHAPE, chunks, { sections: [index] })).sections;
assertEquals(alone.light, expected.light, `section ${index}'s light`);
for (const layer of ["solid", "cutout", "translucent"] as const) {
assertEquals(alone[layer].vertices, expected[layer].vertices, `section ${index}'s ${layer} quads`);
}
}
worker.terminate();
// the roof's shade and the light are in the sections looked at
assertEquals(typeof whole.light[2], "object");
assertEquals(typeof whole.light[3], "object");
});
+3 -25
View File
@@ -17,7 +17,7 @@ import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { get_state_value, set_state_value } from "@/common/utils.ts"; import { get_state_value, set_state_value } from "@/common/utils.ts";
import { cell_index, corner_height, fluid_quads, type FluidCell } from "@/client/workers/fluid_mesh.ts"; import { cell_index, corner_height, fluid_quads, type FluidCell } from "@/client/workers/fluid_mesh.ts";
import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts";
import { section_data, test_game } from "./helpers.ts"; import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
const OIL: BlockJson = { const OIL: BlockJson = {
id: "oily:oil", id: "oily:oil",
@@ -170,35 +170,13 @@ async function mesh(blocks: [number, number, number, string, number?][]) {
const registry = EverythingRegistry.get_registry<BlockRegistry>("blocks"); const registry = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const ids: Record<string, number> = {}; const ids: Record<string, number> = {};
registry.forEach((b, nid) => ids[b.id] = nid); registry.forEach((b, nid) => ids[b.id] = nid);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); const worker = chunk_worker(DEFAULT_SHAPE);
worker.postMessage({
type: "init",
shape: DEFAULT_SHAPE,
// with the registry's gaps, like the client sends it
blocks_registry: registry.map((block) => JSON.parse(JSON.stringify(block))),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume)); const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume));
for (const [x, y, z, id, level] of blocks) { for (const [x, y, z, id, level] of blocks) {
const chunk = x < 0 ? chunks[3] : chunks[4]; const chunk = x < 0 ? chunks[3] : chunks[4];
chunk[y * CHUNK_AREA + z * CHUNK_SIZE + ((x + CHUNK_SIZE) % CHUNK_SIZE)] = ids[id] | ((level ?? 0) << 16); chunk[y * CHUNK_AREA + z * CHUNK_SIZE + ((x + CHUNK_SIZE) % CHUNK_SIZE)] = ids[id] | ((level ?? 0) << 16);
} }
// deno-lint-ignore no-explicit-any const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks);
const meshed = await new Promise<any>((resolve) => {
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
worker.terminate(); worker.terminate();
const f32 = new Float32Array(meshed.translucent.vertices.buffer); const f32 = new Float32Array(meshed.translucent.vertices.buffer);
const quads: number[][][] = []; const quads: number[][][] = [];
+99 -8
View File
@@ -2,7 +2,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
import { resolve, toFileUrl } from "@std/path"; import { resolve, toFileUrl } from "@std/path";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import {
type BlockRegistry,
EverythingRegistry,
light_tables,
type RenderLayer,
} from "@/common/everything_registry.ts";
import { load_and_check, load_order } from "@/tools/check_mods.ts"; import { load_and_check, load_order } from "@/tools/check_mods.ts";
import { mod_data } from "@/common/mod_check.ts"; import { mod_data } from "@/common/mod_check.ts";
import type { ServerModSource } from "@/server/game/load_mods.ts"; import type { ServerModSource } from "@/server/game/load_mods.ts";
@@ -11,8 +16,11 @@ import { start_game } from "@/server/game/load_mods.ts";
import { apply_config } from "@/server/load_mods.ts"; import { apply_config } from "@/server/load_mods.ts";
import { AIR_ID, PROTOCOL_VERSION } from "@/common/protocol.ts"; import { AIR_ID, PROTOCOL_VERSION } from "@/common/protocol.ts";
import { decode_level_chunk } from "@/common/chunk_streaming.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts";
import { CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { Section, section_index, SECTION_VOLUME, type SectionData } from "@/common/section.ts"; import { ChunkColumn, column_heights, section_index, SECTION_VOLUME } from "@/common/section.ts";
import { WorldShape, type WorldShapeJson } from "@/common/world_shape.ts";
import type { LayerMesh, SectionMesh, ToChunkWorker } from "@/client/workers/chunk_messages.ts";
import type { ModelJson } from "@/common/block_models.ts";
import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts"; import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts";
import { FluidRules } from "@/common/fluids.ts"; import { FluidRules } from "@/common/fluids.ts";
import { BlockRules } from "@/common/block_rules.ts"; import { BlockRules } from "@/common/block_rules.ts";
@@ -166,12 +174,95 @@ export function sent_block(
return [join.blocks[value & ID_MASK], value >>> 16]; return [join.blocks[value & ID_MASK], value >>> 16];
} }
// a chunk's blocks in one array, y from the bottom of the world then z then x, as the sections a mesh request sends // a chunk worker set up the way the client sets one up, with the loaded mods' blocks. models are the mods' block models
export function section_data(blocks: Uint32Array): SectionData[] { // and visuals the blocks with them, see ToChunkWorker's init
return Array.from( export function chunk_worker(
{ length: blocks.length / SECTION_VOLUME }, shape: WorldShapeJson,
(_, i) => Section.of(blocks.subarray(i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME)).data, models: Record<string, ModelJson> = {},
visuals: [number, boolean][] = [],
): Worker {
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
shape,
// with the registry's gaps, like the client sends it
blocks_registry: EverythingRegistry.get_registry<BlockRegistry>("blocks").map((block) =>
JSON.parse(JSON.stringify(block))
),
models,
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals,
});
return worker;
}
// the sections of the middle one of 3x3 chunks meshed by a chunk worker, asked for the way the client asks: all of
// them, or the indexes in options.sections. the chunks are each block's value in one array, y from the bottom of the
// world then z then x, null where there's none. what comes back is each section's mesh, and all of them put together:
// their layers' quads one after another, their light, their visuals with indexes in the whole chunk (like an array's)
// and the bounds of them all
export async function mesh_column(
worker: Worker,
shape: WorldShapeJson,
chunks: (Uint32Array | null)[],
options: {
chunk_x?: number;
chunk_z?: number;
biome_colors?: (Uint32Array | null)[];
camera?: number[];
sections?: number[];
} = {},
) {
const { opacity } = light_tables(EverythingRegistry.get_registry<BlockRegistry>("blocks"));
const columns = chunks.map((blocks) =>
blocks && ChunkColumn.from_flat(0, 0, new WorldShape(shape), blocks, new Array(CHUNK_AREA).fill(""))
); );
const count = columns[4]!.sections.length;
const indexes = options.sections ?? Array.from({ length: count }, (_, index) => index);
// with the section below and above them, like ClientLevel.request_meshes
const first = Math.max(0, Math.min(...indexes) - 1);
const end = Math.min(count, Math.max(...indexes) + 2);
const message: ToChunkWorker = {
type: "mesh",
chunk_x: options.chunk_x ?? 0,
chunk_z: options.chunk_z ?? 0,
sections: indexes.map((index) => ({ index, version: 1 })),
first,
chunks: columns.map((column) => column?.sections.slice(first, end).map((section) => section.data) ?? null),
sky: columns.map((column) => column && column_heights(column, opacity).slice(CHUNK_AREA)),
biome_colors: options.biome_colors ?? chunks.map(() => null),
camera: options.camera ?? [0, 0, 0],
};
const sections = await new Promise<SectionMesh[]>((resolve) => {
worker.onmessage = (e) => resolve(e.data.sections);
worker.postMessage(message);
});
const layer = (name: RenderLayer): LayerMesh => {
const meshes = sections.map((section) => section[name]);
const vertices = new Uint8Array(meshes.reduce((sum, mesh) => sum + mesh.vertices.length, 0));
let at = 0;
for (const mesh of meshes) {
vertices.set(mesh.vertices, at);
at += mesh.vertices.length;
}
return { vertices, quad_count: meshes.reduce((sum, mesh) => sum + mesh.quad_count, 0) };
};
return {
sections,
solid: layer("solid"),
cutout: layer("cutout"),
translucent: layer("translucent"),
light: sections.map((section) => section.light),
visuals: Uint32Array.from(
sections.flatMap(({ index, visuals }) =>
[...visuals].map((value, i) => i % 2 === 0 ? index * SECTION_VOLUME + value : value)
),
),
min_y: Math.min(...sections.map((section) => section.min_y)),
max_y: Math.max(...sections.map((section) => section.max_y)),
};
} }
// a stone floor at y 99 from -radius to radius on x and z, high above the terrain, for players to stand on at y 100 // a stone floor at y 99 from -radius to radius on x and z, high above the terrain, for players to stand on at y 100
+2 -2
View File
@@ -6,7 +6,7 @@ import { assert, assertEquals, assertRejects } from "@std/assert";
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import type { FluidJson } from "@/common/mod_data.ts"; import type { FluidJson } from "@/common/mod_data.ts";
import type { ClientContext, Instances, Visual, VisualBlock } from "@/common/mod_api/client.ts"; import type { ClientContext, Instances, Visual, VisualBlock } from "@/common/mod_api/client.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { section_index } from "@/common/section.ts";
import { block_value, display_name } from "@/common/utils.ts"; import { block_value, display_name } from "@/common/utils.ts";
import { sell_value } from "@/common/inventory.ts"; import { sell_value } from "@/common/inventory.ts";
import { block_visuals, Visuals } from "@/client/rendering/visuals.ts"; import { block_visuals, Visuals } from "@/client/rendering/visuals.ts";
@@ -295,7 +295,7 @@ async function drawn_juicer() {
block_visuals.set(juicer, { mod: "bworld", replaces_model: false, create: made.get("bworld:juicer")! }); block_visuals.set(juicer, { mod: "bworld", replaces_model: false, create: made.get("bworld:juicer")! });
const data: Record<string, unknown> = {}; const data: Record<string, unknown> = {};
const visuals = new Visuals({ get_block_data: () => data, get_light: () => 0 }); const visuals = new Visuals({ get_block_data: () => data, get_light: () => 0 });
visuals.meshed(0, 0, 0, Uint32Array.of(100 * CHUNK_AREA + 1 * CHUNK_SIZE + 1, block_value(juicer, 0))); visuals.meshed(0, 0, 96, Uint32Array.of(section_index(1, 100, 1), block_value(juicer, 0)));
const set = (field: string, value: unknown) => { const set = (field: string, value: unknown) => {
data[field] = value; data[field] = value;
visuals.data_changed(1, 100, 1); visuals.data_changed(1, 100, 1);
+11 -16
View File
@@ -4,14 +4,10 @@
// monsters spawning on their own in the dark near players, like undergarden's rotwalkers, see natural_spawner.ts and // monsters spawning on their own in the dark near players, like undergarden's rotwalkers, see natural_spawner.ts and
// mods/undergarden/worldgen/spawns.json // mods/undergarden/worldgen/spawns.json
import { assert, assertEquals } from "@std/assert"; import { assert, assertEquals } from "@std/assert";
import { CHUNK_SIZE } from "@/common/constants.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { decode_level_chunk } from "@/common/chunk_streaming.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts";
import { import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts";
block_light_emission, import { ChunkColumn, column_heights } from "@/common/section.ts";
block_light_opacity,
BlockRegistry,
EverythingRegistry,
} from "@/common/everything_registry.ts";
import { LightRegion, REGION_LAYER, REGION_SIZE, REGION_VOID } from "@/client/workers/lighting.ts"; import { LightRegion, REGION_LAYER, REGION_SIZE, REGION_VOID } from "@/client/workers/lighting.ts";
import { create_entity } from "@/server/game/entity/entity_types.ts"; import { create_entity } from "@/server/game/entity/entity_types.ts";
import { Mob } from "@/server/game/entity/mob.ts"; import { Mob } from "@/server/game/entity/mob.ts";
@@ -78,22 +74,21 @@ Deno.test("the server's light is the same as what clients work out", async () =>
world.set_block(x0 + 3, FLOOR + 1, x0 + 3, "bworld:light"); world.set_block(x0 + 3, FLOOR + 1, x0 + 3, "bworld:light");
world.set_block(x0 + 12, ROOF, x0 + 12, "cubi:air"); world.set_block(x0 + 12, ROOF, x0 + 12, "cubi:air");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks"); // the 3x3 chunks lit whole, like the client lights sections
const opacity = new Uint8Array(REGION_VOID + 1); const { opacity, emission } = light_tables(EverythingRegistry.get_registry<BlockRegistry>("blocks"));
const emission = new Uint8Array(REGION_VOID + 1);
blocks.forEach((block, nid) => {
opacity[nid] = block_light_opacity(block);
emission[nid] = block_light_emission(block);
});
opacity[REGION_VOID] = 15; opacity[REGION_VOID] = 15;
const region = new LightRegion(world.shape); const region = new LightRegion(world.shape);
const chunks = []; const chunks = [];
const sky = [];
for (let dz = -1; dz <= 1; dz++) { for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) { for (let dx = -1; dx <= 1; dx++) {
chunks.push(decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz)).sections); const { sections, biomes } = decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz));
chunks.push(sections);
const column = new ChunkColumn(CHUNK + dx, CHUNK + dz, world.shape, sections, biomes);
sky.push(column_heights(column, opacity).slice(CHUNK_AREA));
} }
} }
region.fill(chunks); region.fill(chunks, sky, world.shape.min_y);
region.compute({ opacity, emission }); region.compute({ opacity, emission });
const check = (x: number, y: number, z: number) => { const check = (x: number, y: number, z: number) => {
+16 -48
View File
@@ -5,13 +5,17 @@
// would have shown // would have shown
import { assert, assertEquals } from "@std/assert"; import { assert, assertEquals } from "@std/assert";
import { mat4 } from "gl-matrix"; import { mat4 } from "gl-matrix";
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { Frustum } from "@/client/rendering/frustum.ts"; import { Frustum } from "@/client/rendering/frustum.ts";
import { group_faces_camera } from "@/client/rendering/level_renderer.ts"; import { group_faces_camera } from "@/client/rendering/level_renderer.ts";
import { FACE_GROUPS, type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; import {
FACE_GROUPS,
type LayerMesh,
type SectionMesh,
TERRAIN_VERTEX_BYTES,
} from "@/client/workers/chunk_messages.ts";
import { decode_level_chunk } from "@/common/chunk_streaming.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts";
import type { Section } from "@/common/section.ts"; import { to_flat } from "@/common/section.ts";
import { test_game } from "./helpers.ts"; import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
// the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts // the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts
function camera_matrix(x: number, y: number, z: number, yaw: number, pitch: number) { function camera_matrix(x: number, y: number, z: number, yaw: number, pitch: number) {
@@ -34,61 +38,25 @@ Deno.test("the frustum keeps what's in front of the camera and drops what's behi
assert(!frustum.intersects_box(-8, 60, -1100, 8, 80, -1090), "past the far plane"); assert(!frustum.intersects_box(-8, 60, -1100, 8, 80, -1090), "past the far plane");
}); });
// real chunks as the server sends them, meshed the way the client does it // real chunks as the server sends them, meshed the way the client does it. each section's mesh
async function mesh_chunks(radius: number) { async function mesh_chunks(radius: number) {
const { game } = await test_game("mods", undefined, "culling-seed"); const { game } = await test_game("mods", undefined, "culling-seed");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks"); const worker = chunk_worker(game.world.shape);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); const generated = new Map<string, Uint32Array>();
// deno-lint-ignore no-explicit-any
const replies = new Map<string, (message: any) => void>();
worker.onmessage = (e) => {
const key = `${e.data.type} ${e.data.chunk_x} ${e.data.chunk_z}`;
replies.get(key)?.(e.data);
replies.delete(key);
};
// deno-lint-ignore no-explicit-any
const ask = (message: any, reply: string) =>
// deno-lint-ignore no-explicit-any
new Promise<any>((resolve) => {
replies.set(`${reply} ${message.chunk_x} ${message.chunk_z}`, resolve);
worker.postMessage(message);
});
worker.postMessage({
type: "init",
shape: game.world.shape,
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const generated = new Map<string, Section[]>();
for (let x = -radius - 1; x <= radius + 1; x++) { for (let x = -radius - 1; x <= radius + 1; x++) {
for (let z = -radius - 1; z <= radius + 1; z++) { for (let z = -radius - 1; z <= radius + 1; z++) {
generated.set(`${x},${z}`, decode_level_chunk(game.world.level_chunk(x, z)).sections); generated.set(`${x},${z}`, to_flat(decode_level_chunk(game.world.level_chunk(x, z)).sections));
} }
} }
const meshes = []; const meshes: SectionMesh[] = [];
for (let x = -radius; x <= radius; x++) { for (let x = -radius; x <= radius; x++) {
for (let z = -radius; z <= radius; z++) { for (let z = -radius; z <= radius; z++) {
const chunks = []; const chunks = [];
for (let dz = -1; dz <= 1; dz++) { for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) { for (let dx = -1; dx <= 1; dx++) chunks.push(generated.get(`${x + dx},${z + dz}`)!);
chunks.push(generated.get(`${x + dx},${z + dz}`)!.map((section) => section.data));
}
} }
meshes.push( const { sections } = await mesh_column(worker, game.world.shape, chunks, { chunk_x: x, chunk_z: z });
await ask({ meshes.push(...sections);
type: "mesh",
chunk_x: x,
chunk_z: z,
version: 1,
chunks,
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
}, "meshed"),
);
} }
} }
worker.terminate(); worker.terminate();
+4 -24
View File
@@ -8,8 +8,8 @@ import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { generate_raw_chunk } from "@/common/generation.ts"; import { generate_raw_chunk } from "@/common/generation.ts";
import { get_biome } from "@/common/worldgen/biomes.ts"; import { get_biome } from "@/common/worldgen/biomes.ts";
import { type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts";
import { section_data, test_game } from "./helpers.ts"; import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
type Colors = { grass: number; foliage: number; water?: number }; type Colors = { grass: number; foliage: number; water?: number };
@@ -20,16 +20,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks"); const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const block_ids: Record<string, number> = {}; const block_ids: Record<string, number> = {};
blocks.forEach((b, nid) => block_ids[b.id] = nid); blocks.forEach((b, nid) => block_ids[b.id] = nid);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); const worker = chunk_worker(DEFAULT_SHAPE);
worker.postMessage({
type: "init",
shape: DEFAULT_SHAPE,
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const chunk = new Uint32Array(DEFAULT_SHAPE.volume); const chunk = new Uint32Array(DEFAULT_SHAPE.volume);
chunk[10 * CHUNK_AREA + 8 * CHUNK_SIZE + x] = block_ids[id]; chunk[10 * CHUNK_AREA + 8 * CHUNK_SIZE + x] = block_ids[id];
@@ -46,18 +37,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
colors[4] = biome_colors(middle); colors[4] = biome_colors(middle);
if (west) colors[3] = biome_colors(west); if (west) colors[3] = biome_colors(west);
const meshed = await new Promise<{ solid: LayerMesh; cutout: LayerMesh; translucent: LayerMesh }>((resolve) => { const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks, { biome_colors: colors });
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: colors,
camera: [0, 0, 0],
});
});
worker.terminate(); worker.terminate();
const top: number[][] = []; const top: number[][] = [];
+25 -41
View File
@@ -5,7 +5,7 @@
// draws their instances, placed and turned by the time // draws their instances, placed and turned by the time
import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert"; import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert";
import { mat4 } from "gl-matrix"; import { mat4 } from "gl-matrix";
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { EverythingRegistry } from "@/common/everything_registry.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { block_value } from "@/common/utils.ts"; import { block_value } from "@/common/utils.ts";
@@ -19,7 +19,8 @@ import { AssetManager } from "@/client/assets.ts";
import { load_client_mods } from "@/client/mods.ts"; import { load_client_mods } from "@/client/mods.ts";
import { load_and_check } from "@/tools/check_mods.ts"; import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts"; import { pack_mod } from "@/tools/pack_mod.ts";
import { copy_dir, section_data, test_game } from "./helpers.ts"; import { chunk_worker, copy_dir, mesh_column, test_game } from "./helpers.ts";
import { section_index } from "@/common/section.ts";
const HALF = { const HALF = {
textures: { "0": "testmod:shaft" }, textures: { "0": "testmod:shaft" },
@@ -85,34 +86,16 @@ const index_of = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK
Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models they replace", async () => { Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models they replace", async () => {
const { nid, value } = await registries(); const { nid, value } = await registries();
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); const worker = chunk_worker(DEFAULT_SHAPE, Object.fromEntries(EverythingRegistry.entries("models")), [
worker.postMessage({ [nid("bworld:stone"), true],
type: "init", [nid("bworld:cobblestone"), false],
shape: DEFAULT_SHAPE, ]);
blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry<BlockRegistry>("blocks"))),
models: Object.fromEntries(EverythingRegistry.entries("models")),
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]],
});
const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume)); const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume));
const middle = chunks[4]; const middle = chunks[4];
middle[index_of(1, 64, 1)] = value("bworld:stone"); middle[index_of(1, 64, 1)] = value("bworld:stone");
middle[index_of(4, 64, 1)] = value("bworld:cobblestone"); middle[index_of(4, 64, 1)] = value("bworld:cobblestone");
middle[index_of(7, 64, 1)] = value("bworld:dirt"); middle[index_of(7, 64, 1)] = value("bworld:dirt");
// deno-lint-ignore no-explicit-any const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks);
const meshed = await new Promise<any>((resolve) => {
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
worker.terminate(); worker.terminate();
assertEquals([...meshed.visuals], [ assertEquals([...meshed.visuals], [
@@ -155,14 +138,14 @@ Deno.test("a visual is made with its block, told when its client data changes, a
}; };
}, },
}); });
const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis)); const shaft = (axis: number) => Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", axis));
visuals.meshed(0, 0, 0, shaft(1)); visuals.meshed(0, 0, 64, shaft(1));
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]); assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]);
// the half model has one face, the block's own model is a cube // the half model has one face, the block's own model is a cube
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]); assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
// meshed again for something else, it stays // meshed again for something else, it stays
visuals.meshed(0, 0, 0, shaft(1)); visuals.meshed(0, 0, 64, shaft(1));
assertEquals(log.splice(0), []); assertEquals(log.splice(0), []);
data.speed = 32; data.speed = 32;
@@ -177,15 +160,15 @@ Deno.test("a visual is made with its block, told when its client data changes, a
assertEquals(log.splice(0), ["frame 10.5"]); assertEquals(log.splice(0), ["frame 10.5"]);
// its states changing makes it again // its states changing makes it again
visuals.meshed(0, 0, 0, shaft(2)); visuals.meshed(0, 0, 64, shaft(2));
assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]); assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]);
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]); assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
// and it goes with the block, or with the chunk, and so do its instances // and it goes with the block, or with the chunk, and so do its instances
visuals.meshed(0, 0, 0, new Uint32Array()); visuals.meshed(0, 0, 64, new Uint32Array());
assertEquals(log.splice(0), ["delete 1 64 1"]); assertEquals(log.splice(0), ["delete 1 64 1"]);
assert(!visuals.has(0, 0)); assert(!visuals.has(0, 0));
assertEquals(drawn(visuals), []); assertEquals(drawn(visuals), []);
visuals.meshed(0, 0, 0, shaft(1)); visuals.meshed(0, 0, 64, shaft(1));
visuals.unload(0, 0); visuals.unload(0, 0);
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]); assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]);
assertEquals(drawn(visuals), []); assertEquals(drawn(visuals), []);
@@ -216,13 +199,13 @@ Deno.test("a visual that throws is logged and left out, and not made again until
const console_error = console.error; const console_error = console.error;
console.error = (...args) => errors.push(args); console.error = (...args) => errors.push(args);
try { try {
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1))); visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 1)));
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1))); visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 1)));
assertEquals([made, errors.length], [1, 1]); assertEquals([made, errors.length], [1, 1]);
assertEquals(drawn(visuals), []); assertEquals(drawn(visuals), []);
// an on_frame that throws isn't called again // an on_frame that throws isn't called again
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2))); visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 2)));
for (let frame = 0; frame < 3; frame++) visuals.frame([{ x: 0, z: 0 }], frame); for (let frame = 0; frame < 3; frame++) visuals.frame([{ x: 0, z: 0 }], frame);
assertEquals([made, errors.length], [3, 2]); assertEquals([made, errors.length], [3, 2]);
} finally { } finally {
@@ -248,9 +231,9 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
}, },
}); });
const shafts = Uint32Array.of( const shafts = Uint32Array.of(
...[1, 2, 3].flatMap((x) => [index_of(x, 64, 1), value("testmod:shaft")]), ...[1, 2, 3].flatMap((x) => [section_index(x, 64, 1), value("testmod:shaft")]),
); );
visuals.meshed(0, 0, 0, shafts); visuals.meshed(0, 0, 64, shafts);
const group = [...visuals.groups()].find((group) => group.instances.length > 0)!; const group = [...visuals.groups()].find((group) => group.instances.length > 0)!;
const at = (i: number) => [...group.data.subarray(i * INSTANCE_FLOATS, (i + 1) * INSTANCE_FLOATS)]; const at = (i: number) => [...group.data.subarray(i * INSTANCE_FLOATS, (i + 1) * INSTANCE_FLOATS)];
const sent = () => { const sent = () => {
@@ -275,13 +258,14 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
// a new light comes with the chunk's mesh // a new light comes with the chunk's mesh
light = 0x0f; light = 0x0f;
visuals.meshed(0, 0, 0, shafts); visuals.meshed(0, 0, 64, shafts);
assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]); assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]);
assertEquals(sent(), [0, 1]); assertEquals(sent(), [0, 1]);
block_visuals.clear(); block_visuals.clear();
}); });
// a visual on one shaft, at 1 64 1, that makes what make does // a visual on one shaft, at 1 64 1, that makes what make does. mesh meshes the section from y 64 with blocks at their
// indexes in it
function one_visual(nid: (id: string) => number, value: (id: string) => number, make: (instances: Instances) => void) { function one_visual(nid: (id: string) => number, value: (id: string) => number, make: (instances: Instances) => void) {
const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 }); const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 });
block_visuals.clear(); block_visuals.clear();
@@ -293,8 +277,8 @@ function one_visual(nid: (id: string) => number, value: (id: string) => number,
return {}; return {};
}, },
}); });
const mesh = (blocks: number[]) => visuals.meshed(0, 0, 0, Uint32Array.from(blocks)); const mesh = (blocks: number[]) => visuals.meshed(0, 0, 64, Uint32Array.from(blocks));
mesh([index_of(1, 64, 1), value("testmod:shaft")]); mesh([section_index(1, 64, 1), value("testmod:shaft")]);
return { visuals, mesh }; return { visuals, mesh };
} }
@@ -378,7 +362,7 @@ Deno.test("a fluid's box is its texture cut to fit and tinted in its color, a mo
box!.delete(); box!.delete();
assertEquals(boxes(), []); assertEquals(boxes(), []);
mesh([]); mesh([]);
mesh([index_of(1, 64, 1), value("testmod:shaft")]); mesh([section_index(1, 64, 1), value("testmod:shaft")]);
assertEquals(boxes().length, 1); assertEquals(boxes().length, 1);
visuals.unload(0, 0); visuals.unload(0, 0);
assertEquals(boxes(), []); assertEquals(boxes(), []);