/// import { block_light_emission, block_light_opacity, type BlockRegistry, type RenderLayer, } from "$/common/everything_registry.ts"; import { AIR, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK, type SpriteRegion, TEXTURE_SIZE } from "$/common/constants.ts"; import type { Texture } from "../renderer/types.ts"; import { type FromChunkWorker, TERRAIN_VERTEX_FLOATS, type ToChunkWorker } from "./chunk_messages.ts"; import { generate_raw_chunk, WorldgenSetup } from "$/common/generation.ts"; import { load_worldgen } from "$/common/worldgen_loader.ts"; import { default_block_value } from "$/common/utils.ts"; import { choose_sort_type, FACE_NORMALS, quad_indices, quad_planes, sort_by_distance, sort_quads, } from "./translucent_sort.ts"; import { LightRegion, type LightTables, region_block, region_block_light, REGION_LAYER, REGION_SIZE, region_sky, REGION_VOID, } from "./lighting.ts"; type TexturesInfo = Record; const FLOATS_PER_QUAD = 4 * TERRAIN_VERTEX_FLOATS; // keeps texture lookups off the sprite's edge const UV_PAD = 0.5; // same order as FACE_NORMALS in translucent_sort.ts const FACES = ["top", "bottom", "front", "back", "left", "right"] as const; // each face's corners in drawing order (counter clockwise from outside), as offsets from the block's corner const FACE_CORNERS = [ [[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]], [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]], [[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]], [[1, 0, 0], [0, 0, 0], [0, 1, 0], [1, 1, 0]], [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]], [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]], ] as const; // which end of the sprite each corner gets, u then v (0 = start, 1 = end) const CORNER_UVS = [[0, 1], [1, 1], [1, 0], [0, 0]] as const; // minecraft's shading by direction, so faces stay apart even in flat light const FACE_SHADE = [1.0, 0.5, 0.8, 0.8, 0.6, 0.6]; // for each face corner, the two cells beside the cell in front of the face that touch that corner, // as [index offset, y offset] for each. the cell touching both is at the sum of them const CORNER_SIDES = FACE_CORNERS.map((corners, face) => corners.map((corner) => { const sides: number[] = []; for (let axis = 0; axis < 3; axis++) { if (FACE_NORMALS[face][axis] !== 0) continue; const d = corner[axis] * 2 - 1; sides.push(axis === 0 ? d : axis === 1 ? d * REGION_LAYER : d * REGION_SIZE, axis === 1 ? d : 0); } return sides; }) ); const SOLID = 0; const CUTOUT = 1; const TRANSLUCENT = 2; const LAYER_IDS: Record = { solid: SOLID, cutout: CUTOUT, translucent: TRANSLUCENT }; let blocks_registry: BlockRegistry[] = []; let block_ids: Record = {}; // by numeric id, looked up for every face. like sodium's light data cache, everything the mesher asks about a // block is worked out once instead of per face const TABLE_SIZE = ID_MASK + 1; const block_layers = new Uint8Array(TABLE_SIZE); const block_cull_same = new Uint8Array(TABLE_SIZE); // darkens the corners it touches (minecraft's ambient occlusion), blocks with a full collision box do const block_occludes = new Uint8Array(TABLE_SIZE); // light can come around a corner past it const block_lets_light_by = new Uint8Array(TABLE_SIZE); const light_tables: LightTables = { opacity: new Uint8Array(TABLE_SIZE), emission: new Uint8Array(TABLE_SIZE) }; const region = new LightRegion(); let textures_info: TexturesInfo = {}; let image: Texture; let worldgen: WorldgenSetup | undefined; // numeric id to what a generated block stores, with its default states. matches the server let default_values: number[] = []; // generating has to wait for mods' worldgen scripts, or this worker's terrain wouldn't match the server's let worldgen_ready: Promise = Promise.resolve(); self.onmessage = async (event: MessageEvent) => { const message = event.data; switch (message.type) { case "init": blocks_registry = message.blocks_registry; block_ids = message.block_ids; build_block_tables(); textures_info = message.textures_info; image = message.image as Texture; default_values = blocks_registry.map((block, nid) => default_block_value(nid, block)); worldgen_ready = load_worldgen(message.worldgen_scripts, message.ores).then((setup) => { worldgen = setup; }); break; case "generate": await worldgen_ready; generate(message.chunk_x, message.chunk_z, message.seed); break; case "mesh": { region.fill(message.chunks); region.compute(light_tables); const { solid, cutout, translucent } = make_chunk_mesh(message.chunk_x, message.chunk_z, message.camera); post( { type: "meshed", chunk_x: message.chunk_x, chunk_z: message.chunk_z, version: message.version, solid, cutout, translucent, camera: message.camera, }, [ solid.vertices.buffer, cutout.vertices.buffer, translucent.vertices.buffer, translucent.indices.buffer, translucent.centers.buffer, ...translucent.planes.map((planes) => planes.buffer), ], ); break; } case "sort": { const [x, y, z] = message.camera; const indices = quad_indices(sort_by_distance(message.centers, message.centers.length / 3, x, y, z)); post({ type: "sorted", chunk_x: message.chunk_x, chunk_z: message.chunk_z, version: message.version, sort_version: message.sort_version, indices, }, [indices.buffer]); break; } } }; function post(message: FromChunkWorker, transfer: Transferable[]) { self.postMessage(message, transfer); } function generate(chunk_x: number, chunk_z: number, seed: string) { const { blocks, spills } = generate_raw_chunk(chunk_x, chunk_z, seed, block_ids, worldgen, default_values); post({ type: "generated", chunk_x, chunk_z, blocks, spills }, [blocks.buffer, spills.buffer]); } function build_block_tables() { blocks_registry.forEach((block, nid) => { if (!block || nid === AIR) return; const layer = LAYER_IDS[block.render_layer ?? "solid"]; const opacity = block_light_opacity(block); block_layers[nid] = layer; block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0; block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT ? 1 : 0; block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0; light_tables.opacity[nid] = opacity; light_tables.emission[nid] = block_light_emission(block); }); block_lets_light_by[AIR] = 1; block_layers[REGION_VOID] = SOLID; block_occludes[REGION_VOID] = 1; light_tables.opacity[REGION_VOID] = 15; } // the rule vanilla minecraft (and so sodium) uses: solid neighbors hide a face, and some blocks // hide faces between two of themselves function show_face(block: number, neighbor: number) { if (neighbor === AIR) return true; if (block_layers[neighbor] === SOLID) return false; return !(neighbor === block && block_cull_same[block]); } // per corner of the face being built const corner_sky = new Float32Array(4); const corner_block = new Float32Array(4); const corner_ao = new Float32Array(4); // minecraft's smooth lighting: each corner averages the light of the cell in front of the face and the three // cells around it that touch the corner, and gets darker for each of those that's a full block function light_face_corners(face: number, front: number, front_y: number) { const front_id = region_block(region, front, front_y); const front_sky = region_sky(region, front, front_y); const front_block = region_block_light(region, front, front_y); const front_ao = block_occludes[front_id] ? 0.2 : 1; for (let corner = 0; corner < 4; corner++) { const [a_offset, a_dy, b_offset, b_dy] = CORNER_SIDES[face][corner]; const a = front + a_offset; const a_y = front_y + a_dy; const b = front + b_offset; const b_y = front_y + b_dy; const a_id = region_block(region, a, a_y); const b_id = region_block(region, b, b_y); let a_sky = region_sky(region, a, a_y); let a_block = region_block_light(region, a, a_y); let b_sky = region_sky(region, b, b_y); let b_block = region_block_light(region, b, b_y); const a_ao = block_occludes[a_id] ? 0.2 : 1; const b_ao = block_occludes[b_id] ? 0.2 : 1; // with both sides closed the corner cell can't be seen, vanilla uses a side's values instead let c_sky = a_sky; let c_block = a_block; let c_ao = a_ao; if (block_lets_light_by[a_id] || block_lets_light_by[b_id]) { const c = a + b_offset; const c_y = a_y + b_dy; c_sky = region_sky(region, c, c_y); c_block = region_block_light(region, c, c_y); c_ao = block_occludes[region_block(region, c, c_y)] ? 0.2 : 1; } // cells with no light at all are usually inside solid blocks, vanilla counts them as the front cell // so corners against walls don't go black if (a_sky === 0 && a_block === 0) { a_sky = front_sky; a_block = front_block; } if (b_sky === 0 && b_block === 0) { b_sky = front_sky; b_block = front_block; } if (c_sky === 0 && c_block === 0) { c_sky = front_sky; c_block = front_block; } corner_sky[corner] = (a_sky + b_sky + c_sky + front_sky) / 4; corner_block[corner] = (a_block + b_block + c_block + front_block) / 4; corner_ao[corner] = (a_ao + b_ao + c_ao + front_ao) / 4; } } // sodium's rule for which diagonal splits the quad: the brighter one, otherwise the ambient occlusion // gets smeared across the whole face function should_flip() { const ao_02 = corner_ao[0] + corner_ao[2]; const ao_13 = corner_ao[1] + corner_ao[3]; if (ao_02 !== ao_13) { return ao_02 < ao_13; } const light = (corner: number) => corner_sky[corner] * 16 + corner_block[corner]; return light(0) + light(2) > light(1) + light(3); } function push_quad( vertices: Float32Array, i: number, face: number, x: number, y: number, z: number, sprite: SpriteRegion, alpha: number, ) { const u0 = (sprite.x * TEXTURE_SIZE + UV_PAD) / image.width; const v0 = (sprite.y * TEXTURE_SIZE + UV_PAD) / image.height; const u1 = ((sprite.x + 1) * TEXTURE_SIZE - UV_PAD) / image.width; const v1 = ((sprite.y + 1) * TEXTURE_SIZE - UV_PAD) / image.height; const shade = FACE_SHADE[face]; // starting from the second corner moves the diagonal, the winding stays the same const first = should_flip() ? 1 : 0; for (let k = 0; k < 4; k++) { const corner = (first + k) & 3; const [cx, cy, cz] = FACE_CORNERS[face][corner]; const [cu, cv] = CORNER_UVS[corner]; const brightness = shade * corner_ao[corner]; vertices[i++] = x + cx; vertices[i++] = y + cy; vertices[i++] = z + cz; vertices[i++] = cu ? u1 : u0; vertices[i++] = cv ? v1 : v0; vertices[i++] = brightness; vertices[i++] = brightness; vertices[i++] = brightness; vertices[i++] = alpha; // where to read the lightmap, block light across and sky light down vertices[i++] = (corner_block[corner] + 0.5) / 16; vertices[i++] = (corner_sky[corner] + 0.5) / 16; } return i; } // region has to be filled and lit first function make_chunk_mesh(chunk_x: number, chunk_z: number, camera: number[]) { const layers = [SOLID, CUTOUT, TRANSLUCENT].map(() => ({ vertices: new Float32Array(4096), floats: 0 })); // for sorting the translucent quads let centers = new Float32Array(256); let faces = new Uint8Array(256); // where the neighbor on each face is, same order as FACES const face_offsets = FACE_NORMALS.map(([nx, ny, nz]) => nx + ny * REGION_LAYER + nz * REGION_SIZE); for (let y = 0; y < CHUNK_HEIGHT; y++) { for (let z = 0; z < CHUNK_SIZE; z++) { for (let x = 0; x < CHUNK_SIZE; x++) { // the middle chunk of the region const index = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + x + CHUNK_SIZE; const block_nid = region.blocks[index]; if (block_nid === AIR) continue; const block_info = blocks_registry[block_nid]; const layer_id = block_layers[block_nid]; const layer = layers[layer_id]; const alpha = layer_id === TRANSLUCENT ? block_info.alpha ?? 1 : 1; const texture_ids = { top: "engine:missing", bottom: "engine:missing", front: "engine:missing", back: "engine:missing", left: "engine:missing", right: "engine:missing", }; const textures = block_info.textures; if (!textures) throw new Error(`no textures for ${block_nid}`); if (typeof textures === "string") { texture_ids.top = textures; texture_ids.bottom = textures; texture_ids.front = textures; texture_ids.back = textures; texture_ids.left = textures; texture_ids.right = textures; } else if ("top" in textures && "bottom" in textures && "side" in textures) { texture_ids.top = textures.top; texture_ids.bottom = textures.bottom; texture_ids.front = textures.side; texture_ids.back = textures.side; texture_ids.left = textures.side; texture_ids.right = textures.side; } else if ("front" in textures && "side" in textures) { texture_ids.top = textures.side; texture_ids.bottom = textures.side; texture_ids.front = textures.front; texture_ids.back = textures.side; texture_ids.left = textures.side; texture_ids.right = textures.side; } const wx = chunk_x * CHUNK_SIZE + x; const wz = chunk_z * CHUNK_SIZE + z; for (let face = 0; face < 6; face++) { const front = index + face_offsets[face]; const front_y = y + FACE_NORMALS[face][1]; if (!show_face(block_nid, region_block(region, front, front_y))) { continue; } light_face_corners(face, front, front_y); layer.vertices = ensure_capacity(layer.vertices, layer.floats + FLOATS_PER_QUAD); layer.floats = push_quad( layer.vertices, layer.floats, face, wx, y, wz, textures_info[texture_ids[FACES[face]]], alpha, ); if (layer_id === TRANSLUCENT) { const quad = layer.floats / FLOATS_PER_QUAD - 1; centers = ensure_capacity(centers, (quad + 1) * 3); faces = ensure_capacity(faces, quad + 1); const [nx, ny, nz] = FACE_NORMALS[face]; centers[quad * 3] = wx + 0.5 + nx * 0.5; centers[quad * 3 + 1] = y + 0.5 + ny * 0.5; centers[quad * 3 + 2] = wz + 0.5 + nz * 0.5; faces[quad] = face; } } } } } const [solid, cutout, translucent] = layers.map((layer) => ({ vertices: layer.vertices, quad_count: layer.floats / FLOATS_PER_QUAD, })); const quads = { centers, faces, count: translucent.quad_count }; const sort_type = choose_sort_type(quads); const [camera_x, camera_y, camera_z] = camera; return { solid, cutout, translucent: { ...translucent, indices: sort_quads(quads, sort_type, camera_x, camera_y, camera_z), sort_type, centers: centers.slice(0, quads.count * 3), planes: quad_planes(quads), }, }; } function ensure_capacity | Uint8Array>( buffer: T, required: number, ): T { if (required <= buffer.length) return buffer; let new_length = buffer.length; while (new_length < required) { new_length *= 2; } const new_buffer = new (buffer.constructor as new (length: number) => T)(new_length); new_buffer.set(buffer as ArrayLike); return new_buffer; }