Lighting system

This commit is contained in:
2026-09-25 15:40:09 -03:00
parent 25f8c683bb
commit 4539898c58
12 changed files with 634 additions and 349 deletions
+56 -52
View File
@@ -1,13 +1,20 @@
import { Component } from "$/common/ecs/mod.ts";
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { AIR_ID, BlockChange } from "$/common/protocol.ts";
import { BlockRegistry, EverythingRegistry, RENDER_LAYERS, RenderLayer } from "$/common/everything_registry.ts";
import {
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
RENDER_LAYERS,
RenderLayer,
} from "$/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import { AssetManager } from "../assets.ts";
import { ClientWorld } from "../client_world.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import { worldgen_mods } from "../mods.ts";
import type { FromChunkWorker } from "../workers/chunk_messages.ts";
import { type FromChunkWorker, TERRAIN_VERTEX_FLOATS } from "../workers/chunk_messages.ts";
import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts";
import { crosses_planes } from "../workers/translucent_sort.ts";
import { Camera } from "./camera.ts";
@@ -53,11 +60,13 @@ interface TranslucentSort {
applied: number;
}
const FLOATS_PER_QUAD = 4 * 9;
const FLOATS_PER_QUAD = 4 * TERRAIN_VERTEX_FLOATS;
export { chunk_key };
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const;
// light spreads diagonally too, so meshing and lighting need all 8
const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
export class Dimension extends Component {
world: ClientWorld;
@@ -71,6 +80,7 @@ export class Dimension extends Component {
changes = new Map<string, Map<string, BlockChange>>();
workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
// chunks being generated by a worker, by chunk key
pending_generation = new Map<number, { x: number; z: number }>();
@@ -140,9 +150,10 @@ export class Dimension extends Component {
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
const old_nid = chunk.blocks[index] & ID_MASK;
chunk.blocks[index] = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
chunk.dirty = true;
this.#mark_border_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
}
// the id with its state bits, VOID outside loaded chunks
@@ -190,13 +201,37 @@ export class Dimension extends Component {
const ly = y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
const old_nid = chunk.blocks[index] & ID_MASK;
chunk.blocks[index] = AIR;
chunk.dirty = true;
this.#mark_border_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, AIR);
}
// a block on a chunk's edge changes which faces its neighbor shows
#mark_border_neighbors_dirty(block_chunk_x: number, block_chunk_z: number, lx: number, lz: number) {
// a block that lets through or gives off a different amount of light changes the light up to 15 blocks
// away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces
#mark_neighbors_dirty(
block_chunk_x: number,
block_chunk_z: number,
lx: number,
lz: number,
old_nid: number,
new_nid: number,
) {
const old_block = this.#blocks[old_nid];
const new_block = this.#blocks[new_nid];
if (
block_light_opacity(old_block) !== block_light_opacity(new_block) ||
block_light_emission(old_block) !== block_light_emission(new_block)
) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const n = this.get_chunk(block_chunk_x + dx, block_chunk_z + dz);
if (n) {
n.dirty = true;
}
}
return;
}
if (lx === 0) {
const n = this.get_chunk(block_chunk_x - 1, block_chunk_z);
if (n) {
@@ -301,13 +336,13 @@ export class Dimension extends Component {
this.chunks.delete(key);
}
// a chunk is only meshed once all its neighbors exist, otherwise its border faces would be wrong
// and it would have to be meshed again as each neighbor loads
// a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be
// wrong and it would have to be meshed again as each neighbor loads
can_mesh(chunk: Chunk) {
if (!chunk.generated) {
return false;
}
for (const [dx, dz] of NEIGHBOR_OFFSETS) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
if (!this.is_generated(chunk.x + dx, chunk.z + dz)) {
return false;
}
@@ -323,15 +358,21 @@ export class Dimension extends Component {
}
chunk.dirty = false;
chunk.mesh_version += 1;
const padded_chunk = this.create_padded_chunk(chunk);
// copies, the worker lights the whole 3x3 area
const chunks: (Uint32Array | null)[] = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
chunks.push(this.get_chunk(chunk.x + dx, chunk.z + dz)?.blocks.slice() ?? null);
}
}
this.workers.post({
type: "mesh",
chunk_x: chunk.x,
chunk_z: chunk.z,
version: chunk.mesh_version,
padded_chunk,
chunks,
camera: [camera.x, camera.y, camera.z],
}, [padded_chunk.buffer]);
}, chunks.filter((blocks) => blocks !== null).map((blocks) => blocks.buffer));
}
}
@@ -394,7 +435,7 @@ export class Dimension extends Component {
this.#set_block_raw(spills[i], spills[i + 1], spills[i + 2], spills[i + 3]);
}
for (const [dx, dz] of NEIGHBOR_OFFSETS) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const neighbor = this.get_chunk(cx + dx, cz + dz);
if (neighbor && neighbor.generated) {
neighbor.dirty = true;
@@ -476,6 +517,7 @@ export class Dimension extends Component {
if (chunk.blocks[index] === AIR) {
chunk.blocks[index] = nid;
chunk.dirty = true;
this.#mark_neighbors_dirty(chunk_x, chunk_z, lx, lz, AIR, nid & ID_MASK);
}
}
@@ -557,44 +599,6 @@ export class Dimension extends Component {
return undefined;
}
create_padded_chunk(chunk: Chunk) {
const size = CHUNK_SIZE + 2;
const layer = size * size;
const padded = new Uint32Array(layer * CHUNK_HEIGHT);
// look the 3x3 chunks up once instead of once per border block
const around: (Uint32Array | undefined)[] = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
around.push(this.get_chunk(chunk.x + dx, chunk.z + dz)?.blocks);
}
}
for (let z = -1; z <= CHUNK_SIZE; z++) {
const dz = z < 0 ? -1 : z >= CHUNK_SIZE ? 1 : 0;
const lz = z - dz * CHUNK_SIZE;
for (let x = -1; x <= CHUNK_SIZE; x++) {
const dx = x < 0 ? -1 : x >= CHUNK_SIZE ? 1 : 0;
const lx = x - dx * CHUNK_SIZE;
const source = around[(dz + 1) * 3 + (dx + 1)];
const source_index = lz * CHUNK_SIZE + lx;
const padded_index = (z + 1) * size + (x + 1);
if (!source) {
for (let y = 0; y < CHUNK_HEIGHT; y++) {
padded[y * layer + padded_index] = VOID;
}
continue;
}
for (let y = 0; y < CHUNK_HEIGHT; y++) {
padded[y * layer + padded_index] = source[y * CHUNK_AREA + source_index] & ID_MASK;
}
}
}
return padded;
}
}
// functions cant be sent to workers
+149 -23
View File
@@ -1,6 +1,7 @@
import { Camera } from "../components/camera.ts";
import { mat4 } from "gl-matrix";
import type { RenderLayer } from "$/common/everything_registry.ts";
import { TERRAIN_VERTEX_FLOATS } from "../workers/chunk_messages.ts";
export let device: GPUDevice;
export let canvas: HTMLCanvasElement;
@@ -28,6 +29,9 @@ let quad_index_capacity = 0;
let uniform_layout: GPUBindGroupLayout;
let texture_layout: GPUBindGroupLayout;
let sampler: GPUSampler;
// minecraft's lightmap: the color for every block light (x) and sky light (y) pair, see update_lightmap
let lightmap: GPUTexture;
let lightmap_bind_group: GPUBindGroup;
const vertex_data = new Float32Array(MAX_SPRITES * VERTS_PER_SPRITE * FLOATS_PER_VERT);
let vert_index = 0;
@@ -106,22 +110,73 @@ fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
}
return color;
}
`;
const terrain_shader_src = /* wgsl */ `
struct Uniforms {
mvp: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var texture0: texture_2d<f32>;
@group(1) @binding(1) var sampler0: sampler;
@group(2) @binding(0) var lightmap: texture_2d<f32>;
@group(2) @binding(1) var lightmap_sampler: sampler;
struct VertexOut {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(perspective, centroid) tex_coord: vec2<f32>,
// directional shade times ambient occlusion, and alpha
@location(1) @interpolate(perspective, centroid) color: vec4<f32>,
// block light, sky light, as lightmap coordinates
@location(2) @interpolate(perspective, centroid) light: vec2<f32>,
}
@vertex
fn vs_terrain(
@location(0) position: vec3<f32>,
@location(1) tex_coord: vec2<f32>,
@location(2) color: vec4<f32>,
@location(3) light: vec2<f32>,
) -> VertexOut {
var out: VertexOut;
out.position = uniforms.mvp * vec4<f32>(position, 1.0);
out.tex_coord = tex_coord;
out.color = color;
out.light = light;
return out;
}
fn lit(in: VertexOut) -> vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
let light = textureSample(lightmap, lightmap_sampler, in.light).rgb;
return vec4<f32>(texel.rgb * in.color.rgb * light, texel.a * in.color.a);
}
// no discard, so the gpu can reject hidden fragments before running the shader
@fragment
fn fs_solid(in: VertexOut) -> @location(0) vec4<f32> {
return vec4<f32>((textureSample(texture0, sampler0, in.tex_coord) * in.color).rgb, 1.0);
return vec4<f32>(lit(in).rgb, 1.0);
}
// alpha tested instead of blended, so it doesn't need sorting
@fragment
fn fs_cutout(in: VertexOut) -> @location(0) vec4<f32> {
let color = textureSample(texture0, sampler0, in.tex_coord) * in.color;
let color = lit(in);
if (color.a < 0.1) {
discard;
}
return vec4<f32>(color.rgb, 1.0);
}
@fragment
fn fs_translucent(in: VertexOut) -> @location(0) vec4<f32> {
let color = lit(in);
if (color.a < 0.01) {
discard;
}
return color;
}
`;
export async function init_window(canvas_element: HTMLCanvasElement) {
@@ -164,6 +219,47 @@ export async function init_window(canvas_element: HTMLCanvasElement) {
create_uniform_buffer(64);
create_white_texture();
create_lightmap();
}
// how bright the sky is, 1 at noon. only the lightmap changes, the chunk meshes stay the same
export function update_lightmap(daylight = 1) {
// minecraft's LightTexture, with its default brightness setting and no flicker
const gamma = 0.5;
const brightness = (level: number) => {
const f = level / 15;
return f / (4 - 3 * f);
};
const lerp = (from: number, to: number, t: number) => from + (to - from) * t;
const clamp = (value: number) => Math.min(1, Math.max(0, value));
const not_gamma = (value: number) => 1 - (1 - value) ** 4;
const sky_factor = daylight * 0.95 + 0.05;
// sky light turns blue as it gets dark
const sky_color = [lerp(daylight, 1, 0.35), lerp(daylight, 1, 0.35), 1];
const block_boost = 1.5;
const pixels = new Uint8Array(16 * 16 * 4);
for (let sky = 0; sky < 16; sky++) {
for (let block = 0; block < 16; block++) {
const s = brightness(sky) * sky_factor;
// block light is warm, it loses blue and green faster as it dims
const b = brightness(block) * block_boost;
const color = [
b + sky_color[0] * s,
b * ((b * 0.6 + 0.4) * 0.6 + 0.4) + sky_color[1] * s,
b * (b * b * 0.6 + 0.4) + sky_color[2] * s,
].map((c) => clamp(lerp(c, 0.75, 0.04)))
.map((c) => clamp(lerp(lerp(c, not_gamma(c), gamma), 0.75, 0.04)));
const i = (sky * 16 + block) * 4;
pixels[i] = Math.round(color[0] * 255);
pixels[i + 1] = Math.round(color[1] * 255);
pixels[i + 2] = Math.round(color[2] * 255);
pixels[i + 3] = 255;
}
}
device.queue.writeTexture({ texture: lightmap }, pixels, { bytesPerRow: 16 * 4 }, [16, 16]);
}
export function begin_drawing() {
@@ -303,6 +399,7 @@ export function draw_terrain(
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
render_pass.setBindGroup(2, lightmap_bind_group);
render_pass.setVertexBuffer(0, vertex_buffer);
render_pass.setIndexBuffer(index_buffer, "uint32");
render_pass.drawIndexed(quad_count * 6);
@@ -657,31 +754,41 @@ function create_pipelines() {
depthStencil: depth_3d,
});
const terrain_module = device.createShaderModule({ code: terrain_shader_src });
const terrain_layout = device.createPipelineLayout({
bindGroupLayouts: [uniform_layout, texture_layout, texture_layout],
});
const terrain_vertex: GPUVertexState = {
module: terrain_module,
entryPoint: "vs_terrain",
buffers: [{
arrayStride: TERRAIN_VERTEX_FLOATS * 4,
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x3" },
{ shaderLocation: 1, offset: 12, format: "float32x2" },
{ shaderLocation: 2, offset: 20, format: "float32x4" },
{ shaderLocation: 3, offset: 36, format: "float32x2" },
],
}],
};
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
// since it's drawn sorted back to front
const unblended = (entryPoint: string): GPUFragmentState => ({
module,
entryPoint,
targets: [{ format: canvas_format }],
});
const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState) =>
device.createRenderPipeline({
layout: terrain_layout,
vertex: terrain_vertex,
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
});
terrain_pipelines = {
solid: device.createRenderPipeline({
layout,
vertex,
fragment: unblended("fs_solid"),
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
solid: terrain_pipeline("fs_solid"),
cutout: terrain_pipeline("fs_cutout"),
translucent: terrain_pipeline("fs_translucent", {
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
}),
cutout: device.createRenderPipeline({
layout,
vertex,
fragment: unblended("fs_cutout"),
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
}),
translucent: pipeline_3d,
};
}
@@ -715,6 +822,25 @@ function get_texture_bind_group(texture: GPUTexture) {
return bind_group;
}
function create_lightmap() {
lightmap = create_texture(16, 16);
// linear, so light fades smoothly between levels across a face like in minecraft
const lightmap_sampler = device.createSampler({
magFilter: "linear",
minFilter: "linear",
addressModeU: "clamp-to-edge",
addressModeV: "clamp-to-edge",
});
lightmap_bind_group = device.createBindGroup({
layout: texture_layout,
entries: [
{ binding: 0, resource: lightmap.createView() },
{ binding: 1, resource: lightmap_sampler },
],
});
update_lightmap();
}
function create_white_texture() {
const tex = create_texture(1, 1);
device.queue.writeTexture({ texture: tex }, new Uint8Array([255, 255, 255, 255]), { bytesPerRow: 4 }, [1, 1]);
+5 -1
View File
@@ -5,6 +5,9 @@ import type { SortType } from "./translucent_sort.ts";
// messages between the main thread and the chunk workers
// position 3, uv 2, color 4 (directional shade and ambient occlusion, alpha), lightmap coordinates 2
export const TERRAIN_VERTEX_FLOATS = 11;
export type ToChunkWorker =
| {
type: "init";
@@ -23,7 +26,8 @@ export type ToChunkWorker =
chunk_x: number;
chunk_z: number;
version: number;
padded_chunk: Uint32Array;
// copies of the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting
chunks: (Uint32Array | null)[];
// where the camera is, to sort the translucent quads
camera: number[];
}
+210 -273
View File
@@ -1,9 +1,14 @@
/// <reference lib="webworker" />
import type { BlockRegistry, RenderLayer } from "$/common/everything_registry.ts";
import { AIR, type SpriteRegion } from "$/common/constants.ts";
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, ToChunkWorker } from "./chunk_messages.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";
@@ -15,247 +20,52 @@ import {
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;
}
import {
LightRegion,
type LightTables,
region_block,
region_block_light,
REGION_LAYER,
REGION_SIZE,
region_sky,
REGION_VOID,
} from "./lighting.ts";
type TexturesInfo = Record<string, SpriteRegion>;
const CHUNK_SIZE = 16;
const CHUNK_HEIGHT = 128;
const TEXTURE_SIZE = 16;
const FLOATS_PER_QUAD = 4 * 9;
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;
const FACE_PUSHING_FUNCTIONS = [
push_top_face,
push_bottom_face,
push_front_face,
push_back_face,
push_left_face,
push_right_face,
// 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;
@@ -264,9 +74,18 @@ const LAYER_IDS: Record<RenderLayer, number> = { solid: SOLID, cutout: CUTOUT, t
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);
// 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;
@@ -281,11 +100,7 @@ self.onmessage = async (event: MessageEvent<ToChunkWorker>) => {
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,
);
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));
@@ -298,12 +113,9 @@ self.onmessage = async (event: MessageEvent<ToChunkWorker>) => {
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,
);
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",
@@ -351,32 +163,161 @@ function generate(chunk_x: number, chunk_z: number, seed: string) {
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;
// unloaded (VOID) or above/below the world
const layer = block_layers[neighbor];
if (layer === undefined || layer === SOLID) return false;
if (block_layers[neighbor] === 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 }));
// 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);
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];
// 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++) {
const index = y * layer_size + (z + 1) * size + (x + 1);
const block_nid = padded_chunk[index];
// 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];
@@ -423,26 +364,22 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, padded_chunk: Uint32A
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]])) {
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;
}
const region = textures_info[texture_ids[FACES[face]]];
light_face_corners(face, front, front_y);
layer.vertices = ensure_capacity(layer.vertices, layer.floats + FLOATS_PER_QUAD);
layer.floats = FACE_PUSHING_FUNCTIONS[face](
layer.floats = push_quad(
layer.vertices,
layer.floats,
image,
face,
wx,
y,
wz,
region.x * TEXTURE_SIZE,
region.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
1,
1,
1,
textures_info[texture_ids[FACES[face]]],
alpha,
);
+176
View File
@@ -0,0 +1,176 @@
// minecraft's lighting: every block has a sky light and a block light level from 0 to 15.
// sky light starts at 15 above the world and goes straight down without getting weaker until it hits
// something that isn't fully clear, block light starts at blocks that give off light. both spread to
// neighbors losing max(1, the neighbor's opacity) per step.
//
// minecraft stores light and updates it as blocks change. here it's worked out from scratch for the
// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15
// blocks, so nothing outside those chunks can light the middle one or its border
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
export const REGION_SIZE = CHUNK_SIZE * 3;
export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
export const REGION_VOLUME = REGION_LAYER * CHUNK_HEIGHT;
// what unloaded chunks and the space below the world are made of: opaque, dark, never shown
export const REGION_VOID = ID_MASK;
// by numeric block id
export interface LightTables {
opacity: Uint8Array;
emission: Uint8Array;
}
export class LightRegion {
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
blocks = new Uint16Array(REGION_VOLUME);
sky = new Uint8Array(REGION_VOLUME);
block_light = new Uint8Array(REGION_VOLUME);
// the lowest y that still sees the sky, per column
#heights = new Int32Array(REGION_LAYER);
#queue = new Int32Array(1 << 18);
#queue_length = 0;
// the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing ones are void
fill(chunks: (Uint32Array | null)[]) {
for (let i = 0; i < 9; i++) {
const source = chunks[i];
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE;
for (let y = 0; y < CHUNK_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
if (!source) {
this.blocks.fill(REGION_VOID, to, to + CHUNK_SIZE);
continue;
}
const from = y * CHUNK_AREA + z * CHUNK_SIZE;
for (let x = 0; x < CHUNK_SIZE; x++) {
this.blocks[to + x] = source[from + x] & ID_MASK;
}
}
}
}
}
compute(tables: LightTables) {
this.#compute_sky(tables);
this.#compute_block_light(tables);
}
#compute_sky({ opacity }: LightTables) {
const { blocks, sky } = this;
sky.fill(0);
this.#queue_length = 0;
// straight down from the top, until something isn't fully clear
for (let column = 0; column < REGION_LAYER; column++) {
let y = CHUNK_HEIGHT - 1;
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,
// and the part of it that's beside a neighbor column's shade
for (let z = 0; z < REGION_SIZE; z++) {
for (let x = 0; x < REGION_SIZE; x++) {
const column = z * REGION_SIZE + x;
const height = this.#heights[column];
let highest_neighbor = height;
if (x > 0) highest_neighbor = Math.max(highest_neighbor, this.#heights[column - 1]);
if (x < REGION_SIZE - 1) highest_neighbor = Math.max(highest_neighbor, this.#heights[column + 1]);
if (z > 0) highest_neighbor = Math.max(highest_neighbor, this.#heights[column - REGION_SIZE]);
if (z < REGION_SIZE - 1) {
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]);
}
const top = Math.min(CHUNK_HEIGHT - 1, Math.max(height, highest_neighbor - 1));
for (let y = height; y <= top; y++) {
this.#push(y * REGION_LAYER + column);
}
}
}
this.#propagate(sky, opacity, true);
}
#compute_block_light({ opacity, emission }: LightTables) {
const { blocks, block_light } = this;
block_light.fill(0);
this.#queue_length = 0;
for (let i = 0; i < REGION_VOLUME; i++) {
const level = emission[blocks[i]];
if (level > 0) {
block_light[i] = level;
this.#push(i);
}
}
this.#propagate(block_light, opacity, false);
}
#push(index: number) {
if (this.#queue_length === this.#queue.length) {
const bigger = new Int32Array(this.#queue.length * 2);
bigger.set(this.#queue);
this.#queue = bigger;
}
this.#queue[this.#queue_length++] = index;
}
// breadth first from everything queued. a cell can be queued again when a brighter path reaches it
#propagate(light: Uint8Array, opacity: Uint8Array, is_sky: boolean) {
const blocks = this.blocks;
const spread = (to: number, level: number, down: boolean) => {
const block_opacity = opacity[blocks[to]];
const next = is_sky && down && level === 15 && block_opacity === 0
? 15
: level - Math.max(1, block_opacity);
if (next > light[to]) {
light[to] = next;
this.#push(to);
}
};
for (let head = 0; head < this.#queue_length; head++) {
const index = this.#queue[head];
const level = light[index];
if (level <= 1) continue;
const y = Math.floor(index / REGION_LAYER);
const rest = index - y * REGION_LAYER;
const z = Math.floor(rest / REGION_SIZE);
const x = rest - z * REGION_SIZE;
if (y > 0) spread(index - REGION_LAYER, level, true);
if (y < CHUNK_HEIGHT - 1) spread(index + REGION_LAYER, level, false);
if (x > 0) spread(index - 1, level, false);
if (x < REGION_SIZE - 1) spread(index + 1, level, false);
if (z > 0) spread(index - REGION_SIZE, level, false);
if (z < REGION_SIZE - 1) spread(index + REGION_SIZE, level, false);
}
this.#queue_length = 0;
}
}
// what a cell looks like to the mesher, including above and below the world
export function region_block(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT) return AIR;
if (y < 0) return REGION_VOID;
return region.blocks[index];
}
export function region_sky(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT) return 15;
if (y < 0) return 0;
return region.sky[index];
}
export function region_block_light(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT || y < 0) return 0;
return region.block_light[index];
}