Files
bworld/client/workers/chunk_worker.ts
T
2026-09-25 15:01:03 -03:00

501 lines
13 KiB
TypeScript

/// <reference lib="webworker" />
import type { BlockRegistry, RenderLayer } from "$/common/everything_registry.ts";
import { AIR, type SpriteRegion } from "$/common/constants.ts";
import type { Texture } from "../renderer/types.ts";
import type { FromChunkWorker, 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";
const pad = 0.5;
function push_vertex(
vertices: Float32Array,
i: number,
px: number,
py: number,
pz: number,
u: number,
v: number,
r: number,
g: number,
b: number,
a: number,
) {
vertices[i++] = px;
vertices[i++] = py;
vertices[i++] = pz;
vertices[i++] = u;
vertices[i++] = v;
vertices[i++] = r;
vertices[i++] = g;
vertices[i++] = b;
vertices[i++] = a;
return i;
}
export function push_front_face(
vertices: Float32Array,
i: number,
texture: Texture,
x: number,
y: number,
z: number,
sx: number,
sy: number,
sw: number,
sh: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const x2 = x + 1;
const y2 = y + 1;
const z2 = z + 1;
const u0 = (sx + pad) / texture.width;
const v0 = (sy + pad) / texture.height;
const u1 = (sx + sw - pad) / texture.width;
const v1 = (sy + sh - pad) / texture.height;
i = push_vertex(vertices, i, x, y, z2, u0, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y, z2, u1, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y2, z2, u1, v0, r, g, b, a);
i = push_vertex(vertices, i, x, y2, z2, u0, v0, r, g, b, a);
return i;
}
export function push_back_face(
vertices: Float32Array,
i: number,
texture: Texture,
x: number,
y: number,
z: number,
sx: number,
sy: number,
sw: number,
sh: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const x2 = x + 1;
const y2 = y + 1;
const u0 = (sx + pad) / texture.width;
const v0 = (sy + pad) / texture.height;
const u1 = (sx + sw - pad) / texture.width;
const v1 = (sy + sh - pad) / texture.height;
i = push_vertex(vertices, i, x2, y, z, u0, v1, r, g, b, a);
i = push_vertex(vertices, i, x, y, z, u1, v1, r, g, b, a);
i = push_vertex(vertices, i, x, y2, z, u1, v0, r, g, b, a);
i = push_vertex(vertices, i, x2, y2, z, u0, v0, r, g, b, a);
return i;
}
export function push_left_face(
vertices: Float32Array,
i: number,
texture: Texture,
x: number,
y: number,
z: number,
sx: number,
sy: number,
sw: number,
sh: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const y2 = y + 1;
const z2 = z + 1;
const u0 = (sx + pad) / texture.width;
const v0 = (sy + pad) / texture.height;
const u1 = (sx + sw - pad) / texture.width;
const v1 = (sy + sh - pad) / texture.height;
i = push_vertex(vertices, i, x, y, z, u0, v1, r, g, b, a);
i = push_vertex(vertices, i, x, y, z2, u1, v1, r, g, b, a);
i = push_vertex(vertices, i, x, y2, z2, u1, v0, r, g, b, a);
i = push_vertex(vertices, i, x, y2, z, u0, v0, r, g, b, a);
return i;
}
export function push_right_face(
vertices: Float32Array,
i: number,
texture: Texture,
x: number,
y: number,
z: number,
sx: number,
sy: number,
sw: number,
sh: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const x2 = x + 1;
const y2 = y + 1;
const z2 = z + 1;
const u0 = (sx + pad) / texture.width;
const v0 = (sy + pad) / texture.height;
const u1 = (sx + sw - pad) / texture.width;
const v1 = (sy + sh - pad) / texture.height;
i = push_vertex(vertices, i, x2, y, z2, u0, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y, z, u1, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y2, z, u1, v0, r, g, b, a);
i = push_vertex(vertices, i, x2, y2, z2, u0, v0, r, g, b, a);
return i;
}
export function push_top_face(
vertices: Float32Array,
i: number,
texture: Texture,
x: number,
y: number,
z: number,
sx: number,
sy: number,
sw: number,
sh: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const x2 = x + 1;
const z2 = z + 1;
const y2 = y + 1;
const u0 = (sx + pad) / texture.width;
const v0 = (sy + pad) / texture.height;
const u1 = (sx + sw - pad) / texture.width;
const v1 = (sy + sh - pad) / texture.height;
i = push_vertex(vertices, i, x, y2, z2, u0, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y2, z2, u1, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y2, z, u1, v0, r, g, b, a);
i = push_vertex(vertices, i, x, y2, z, u0, v0, r, g, b, a);
return i;
}
export function push_bottom_face(
vertices: Float32Array,
i: number,
texture: Texture,
x: number,
y: number,
z: number,
sx: number,
sy: number,
sw: number,
sh: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const x2 = x + 1;
const z2 = z + 1;
const u0 = (sx + pad) / texture.width;
const v0 = (sy + pad) / texture.height;
const u1 = (sx + sw - pad) / texture.width;
const v1 = (sy + sh - pad) / texture.height;
i = push_vertex(vertices, i, x, y, z, u0, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y, z, u1, v1, r, g, b, a);
i = push_vertex(vertices, i, x2, y, z2, u1, v0, r, g, b, a);
i = push_vertex(vertices, i, x, y, z2, u0, v0, r, g, b, a);
return i;
}
type TexturesInfo = Record<string, SpriteRegion>;
const CHUNK_SIZE = 16;
const CHUNK_HEIGHT = 128;
const TEXTURE_SIZE = 16;
const FLOATS_PER_QUAD = 4 * 9;
// same order as FACE_NORMALS in translucent_sort.ts
const FACES = ["top", "bottom", "front", "back", "left", "right"] as const;
const FACE_PUSHING_FUNCTIONS = [
push_top_face,
push_bottom_face,
push_front_face,
push_back_face,
push_left_face,
push_right_face,
] as const;
const SOLID = 0;
const CUTOUT = 1;
const TRANSLUCENT = 2;
const LAYER_IDS: Record<RenderLayer, number> = { solid: SOLID, cutout: CUTOUT, translucent: TRANSLUCENT };
let blocks_registry: BlockRegistry[] = [];
let block_ids: Record<string, number> = {};
// by numeric id, checked for every face
let block_layers = new Uint8Array(0);
let block_cull_same = new Uint8Array(0);
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<void> = Promise.resolve();
self.onmessage = async (event: MessageEvent<ToChunkWorker>) => {
const message = event.data;
switch (message.type) {
case "init":
blocks_registry = message.blocks_registry;
block_ids = message.block_ids;
block_layers = Uint8Array.from(blocks_registry, (block) => LAYER_IDS[block?.render_layer ?? "solid"]);
block_cull_same = Uint8Array.from(
blocks_registry,
(block) => (block?.cull_same ?? block?.render_layer === "translucent") ? 1 : 0,
);
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": {
const { solid, cutout, translucent } = make_chunk_mesh(
message.chunk_x,
message.chunk_z,
message.padded_chunk,
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]);
}
// 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;
// unloaded (VOID) or above/below the world
const layer = block_layers[neighbor];
if (layer === undefined || layer === SOLID) return false;
return !(neighbor === block && block_cull_same[block]);
}
function make_chunk_mesh(chunk_x: number, chunk_z: number, padded_chunk: Uint32Array, camera: number[]) {
const layers = [SOLID, CUTOUT, TRANSLUCENT].map(() => ({ vertices: new Float32Array(2048), floats: 0 }));
// for sorting the translucent quads
let centers = new Float32Array(256);
let faces = new Uint8Array(256);
const size = CHUNK_SIZE + 2;
const layer_size = size * size;
// where the neighbor on each face is in padded_chunk, same order as FACES
const face_offsets = [layer_size, -layer_size, size, -size, -1, 1];
for (let y = 0; y < CHUNK_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
const index = y * layer_size + (z + 1) * size + (x + 1);
const block_nid = padded_chunk[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++) {
if (!show_face(block_nid, padded_chunk[index + face_offsets[face]])) {
continue;
}
const region = textures_info[texture_ids[FACES[face]]];
layer.vertices = ensure_capacity(layer.vertices, layer.floats + FLOATS_PER_QUAD);
layer.floats = FACE_PUSHING_FUNCTIONS[face](
layer.vertices,
layer.floats,
image,
wx,
y,
wz,
region.x * TEXTURE_SIZE,
region.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
1,
1,
1,
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<T extends Float32Array<ArrayBuffer> | Uint8Array<ArrayBuffer>>(
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<number>);
return new_buffer;
}