Light the 3D world as Minecraft's smooth lighting does

The server works out the sky's light in each cell of a chunk, full under the open sky and a level less through each
leaf, block of water or step aside, and for each visible face the light of the cell it faces and how many opaque cells
stand around each of its corners. The studio darkens the faces' corners by them, splitting each face along its brighter
corners, so terrace steps, cliff feet and the ground under trees and overhangs read in depth. Far runs carry the mean
light and corner shade of the block tops they stand for, so far ground darkens as the near ground does.
This commit is contained in:
piexel committed 2026-11-12 13:01:27 +01:00
1 parent 87b088787b
commit d4da60a253
19 files changed
+1011 -203

No files matched your search

+21 -2
View File
@@ -88,13 +88,17 @@ function decodeRuns(buffer: ArrayBuffer, countsAt: number, cells: number, count:
const blocksAt = topsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
const coversAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
const coverSharesAt = coversAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
const lightsAt = coverSharesAt + aligned(count)
const occlusionsAt = lightsAt + aligned(count)
return {
starts: startsOf(new Int16Array(buffer, countsAt, cells)),
bottoms: new Int16Array(buffer, bottomsAt, count),
tops: new Int16Array(buffer, topsAt, count),
blocks: new Int16Array(buffer, blocksAt, count),
covers: new Int16Array(buffer, coversAt, count),
coverShares: new Uint8Array(buffer, coverSharesAt, count)
coverShares: new Uint8Array(buffer, coverSharesAt, count),
lights: new Uint8Array(buffer, lightsAt, count),
occlusions: new Uint8Array(buffer, occlusionsAt, count)
}
}
@@ -103,15 +107,30 @@ function decodeVoxels(buffer: ArrayBuffer, xAt: number, count: number): TileVoxe
const yAt = zAt + aligned(count)
const blocksAt = yAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
const facesAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
const lightsAt = facesAt + aligned(count)
const shadesAt = lightsAt + aligned(count)
const faces = new Uint8Array(buffer, facesAt, count)
return {
x: new Uint8Array(buffer, xAt, count),
z: new Uint8Array(buffer, zAt, count),
y: new Int16Array(buffer, yAt, count),
blocks: new Int16Array(buffer, blocksAt, count),
faces: new Uint8Array(buffer, facesAt, count)
faces,
lights: new Uint8Array(buffer, lightsAt, count),
shades: new Uint16Array(buffer, shadesAt, facesShown(faces))
}
}
function facesShown(faces: Uint8Array): number {
let shown = 0
for (const sides of faces) {
for (let rest = sides; rest !== 0; rest &= rest - 1) {
shown++
}
}
return shown
}
function startsOf(counts: Int16Array): Int32Array {
const starts = new Int32Array(counts.length + 1)
for (let cell = 0; cell < counts.length; cell++) {
+13
View File
@@ -389,6 +389,10 @@ export interface TileVoxels {
blocks: Int16Array
/** The sides of each block that face the open air, a bit each in {@link VOXEL_SIDES}' order. */
faces: Uint8Array
/** The sky's light each block shows on faces that stand inside it, such as a plant's, 0 to 15. */
lights: Uint8Array
/** The shade of each face {@link faces} names, block after block and side after side, as skyLight reads it. */
shades: Uint16Array
}
/**
@@ -406,8 +410,17 @@ export interface TileRuns {
covers: Int16Array
/** How much of each run's top plants stand on, 0 to 255 for all of it. */
coverShares: Uint8Array
/** The sky's light on each run's top, the mean of its blocks' tops, in sixteenths of a level. */
lights: Uint8Array
/** How many opaque cells stand around each corner of each run's top, the mean of its blocks' tops, in sixty-fourths. */
occlusions: Uint8Array
}
/** {@link TileRuns.lights} to a light level. */
export const RUN_LIGHT_STEPS = 16
/** {@link TileRuns.occlusions} to a count of opaque cells. */
export const RUN_OCCLUSION_STEPS = 64
/** The order of the sides in {@link TileVoxels.faces}. */
export const VOXEL_SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] as const
+36 -2
View File
@@ -8,6 +8,21 @@ const GROUND = 10
const BASE = 0
const CANOPY_BOTTOM = 14
const CANOPY_TOP = 15
const FULLY_LIT = 15 * 16
// Two columns of plain ground side by side, their tops lit and darkened as given.
function flatRuns(lights: Uint8Array, occlusions: Uint8Array): SurfaceRuns['runs'] {
return {
starts: Int32Array.of(0, 1, 2),
bottoms: Int16Array.of(0, 0),
tops: Int16Array.of(GROUND, GROUND),
blocks: Int16Array.of(0, 0),
covers: Int16Array.of(-1, -1),
coverShares: new Uint8Array(2),
lights,
occlusions
}
}
// Two columns side by side, a block each: plain ground on the west, ground with a canopy floating over it on the east.
const surface: TerrainSurface = {
@@ -28,7 +43,9 @@ const runs: SurfaceRuns = {
tops: Int16Array.of(GROUND, CANOPY_TOP, GROUND),
blocks: Int16Array.of(0, 1, 0),
covers: Int16Array.of(-1, -1, -1),
coverShares: new Uint8Array(3)
coverShares: new Uint8Array(3),
lights: new Uint8Array(3).fill(FULLY_LIT),
occlusions: new Uint8Array(3)
},
cellAt: (column) => column,
looks: [null, null],
@@ -54,7 +71,7 @@ describe('run faces', () => {
})
it('draws the tops of neighbouring columns at one height in one block as one face', () => {
const flat: SurfaceRuns = { ...runs, runs: { starts: Int32Array.of(0, 1, 2), bottoms: Int16Array.of(0, 0), tops: Int16Array.of(GROUND, GROUND), blocks: Int16Array.of(0, 0), covers: Int16Array.of(-1, -1), coverShares: new Uint8Array(2) } }
const flat: SurfaceRuns = { ...runs, runs: flatRuns(new Uint8Array(2).fill(FULLY_LIT), new Uint8Array(2)) }
const geometry = runFaces(new ColumnField(surface), flat, BASE).geometry()
const positions = geometry.getAttribute('position')
const tops = []
@@ -67,6 +84,23 @@ describe('run faces', () => {
expect(tops).toEqual([2])
})
it('darkens a top by the mean light and corner shade of the blocks it stands for', () => {
const shaded: SurfaceRuns = { ...runs, runs: flatRuns(Uint8Array.of(FULLY_LIT, 10 * 16), Uint8Array.of(0, 32)) }
const geometry = runFaces(new ColumnField(surface), shaded, BASE).geometry()
const positions = geometry.getAttribute('position')
const colors = geometry.getAttribute('color')
const topColorAt = (x: number): number => {
for (let first = 0; first < positions.count; first += 4) {
if (positions.getY(first) === GROUND + 1 && positions.getY(first + 3) === GROUND + 1 && Math.min(positions.getX(first), positions.getX(first + 3)) === x) {
return colors.getX(first)
}
}
return NaN
}
expect(topColorAt(1)).toBeLessThan(topColorAt(0) * 0.7)
})
it('floats a canopy over the ground with its underside showing', () => {
const drawn = faces()
+26 -7
View File
@@ -1,4 +1,5 @@
import { NO_BLOCK, type TileRuns } from '../bridge/types'
import { NO_BLOCK, RUN_LIGHT_STEPS, RUN_OCCLUSION_STEPS, type TileRuns } from '../bridge/types'
import { brightnessOfCorner, brightnessOfLight } from './skyLight'
import type { Direction } from './blockModels'
import type { BlockLook } from './blockLooks'
import type { ColumnField } from './columnField'
@@ -66,12 +67,14 @@ function addColumn(faces: MergedFaces, field: ColumnField, surface: SurfaceRuns,
const top = runs.tops[run]
const bottom = runs.bottoms[run]
const block = runs.blocks[run]
const light = brightnessOfLight(runs.lights[run] / RUN_LIGHT_STEPS)
if (run === first || runs.bottoms[run - 1] !== top + 1) {
const color = underWater(withPlants(surface, run, colorOf(surface, block, 'top', FACE_LIGHT.up)), top + 1, water)
const topLight = light * brightnessOfCorner(runs.occlusions[run] / RUN_OCCLUSION_STEPS)
const color = underWater(lit(withPlants(surface, run, colorOf(surface, block, 'top', FACE_LIGHT.up)), topLight), top + 1, water)
faces.add('up', row, column, top + 1, top + 1, color, color)
}
if (!isGround && (run === last || runs.tops[run + 1] !== bottom - 1)) {
const color = underWater(colorOf(surface, block, 'top', FACE_LIGHT.down), bottom, water)
const color = underWater(lit(colorOf(surface, block, 'top', FACE_LIGHT.down), light), bottom, water)
faces.add('down', row, column, bottom, bottom, color, color)
}
for (const side of SIDES) {
@@ -80,7 +83,7 @@ function addColumn(faces: MergedFaces, field: ColumnField, surface: SurfaceRuns,
const lowest = isGround ? (known ? -Infinity : base) : bottom
const covered = known ? spansOf(surface, surface.cellAt(...neighbour)) : []
for (const open of uncovered({ bottom: lowest, top }, covered)) {
addSide(faces, surface, column, row, side, open, top, block, water)
addSide(faces, surface, column, row, side, open, top, block, water, light)
}
}
}
@@ -123,19 +126,35 @@ export function uncovered(span: Span, covered: readonly Span[]): Span[] {
}
// The top block of a run shows its side picture; the blocks under it, the picture of the blocks under a column's top.
function addSide(faces: MergedFaces, surface: SurfaceRuns, column: number, row: number, side: Side, open: Span, runTop: number, block: number, water: number | null): void {
// Sides take the light of the run's top, as the open air beside it mostly holds.
function addSide(
faces: MergedFaces,
surface: SurfaceRuns,
column: number,
row: number,
side: Side,
open: Span,
runTop: number,
block: number,
water: number | null,
skyLight: number
): void {
const light = side.direction === 'north' || side.direction === 'south' ? FACE_LIGHT.north : FACE_LIGHT.west
if (open.top === runTop) {
const color = colorOf(surface, block, 'side', light)
const color = lit(colorOf(surface, block, 'side', light), skyLight)
faces.add(side.direction, row, column, runTop, runTop + 1, underWater(color, runTop, water), underWater(color, runTop + 1, water))
}
const belowTop = open.top === runTop ? runTop - 1 : open.top
if (belowTop >= open.bottom) {
const color = colorOf(surface, block, 'below', light)
const color = lit(colorOf(surface, block, 'below', light), skyLight)
faces.add(side.direction, row, column, open.bottom, belowTop + 1, underWater(color, open.bottom, water), underWater(color, belowTop + 1, water))
}
}
function lit(color: Vec3, brightness: number): Vec3 {
return [color[0] * brightness, color[1] * brightness, color[2] * brightness]
}
function colorOf(surface: SurfaceRuns, block: number, face: 'top' | 'side' | 'below', light: number): Vec3 {
const look = surface.looks[block]
return shaded(look === null || look === undefined ? surface.colors[block] : look[face].color, light)
+39
View File
@@ -0,0 +1,39 @@
/**
* How bright the server's sky light and corner darkening make a face, as Minecraft's smooth lighting shows them. A
* face's shade holds the sky's light in the cell it faces, 0 to {@link FULL_LIGHT}, in its lowest bits, then for each of
* its corners how many of the three cells around it are opaque.
*/
export const FULL_LIGHT = 15
const LIGHT_BITS = 4
const CORNER_BITS = 2
const LIGHT_MASK = (1 << LIGHT_BITS) - 1
const CORNER_MASK = (1 << CORNER_BITS) - 1
// Between Minecraft's Moody and Bright, so shade under trees reads without the forest floor going black.
const LIFT = 0.5
// What a cell the sky never reaches still shows, so a cave mouth is dark but not a hole.
const DARKEST = 0.12
// Each opaque cell around a corner takes this off its brightness; linear, so a far area's mean darkens as its blocks do.
const DARKENING_PER_OPAQUE_CELL = 0.2
/** The brightness of a cell lit at {@code light}, which may lie between levels, from {@link DARKEST} to 1. */
export function brightnessOfLight(light: number): number {
const level = Math.min(FULL_LIGHT, Math.max(0, light)) / FULL_LIGHT
const moody = level / (4 - 3 * level)
const bright = 1 - (1 - moody) ** 4
return DARKEST + (1 - DARKEST) * (moody + (bright - moody) * LIFT)
}
/** How much a corner keeps of its brightness with {@code opaque} cells around it, which may be a mean. */
export function brightnessOfCorner(opaque: number): number {
return 1 - DARKENING_PER_OPAQUE_CELL * opaque
}
export function lightOf(shade: number): number {
return shade & LIGHT_MASK
}
/** How many cells around a face's corner are opaque, the corners in the order the face's corners are drawn. */
export function opaqueAround(shade: number, corner: number): number {
return (shade >> (LIGHT_BITS + corner * CORNER_BITS)) & CORNER_MASK
}
@@ -42,13 +42,19 @@ const surface: TerrainSurface = {
colorAt: () => 0x808080
}
function voxelsOf(blocks: number[], faces: number[]): SurfaceVoxels {
const FULL_LIGHT = 15
// Every face lit fully with no corner darkened, unless shades are given.
function voxelsOf(blocks: number[], faces: number[], shades?: number[]): SurfaceVoxels {
const shown = faces.reduce((count, sides) => count + sides.toString(2).split('1').length - 1, 0)
const voxels: TileVoxels = {
x: Uint8Array.from(blocks.map((_, at) => at)),
z: new Uint8Array(blocks.length),
y: new Int16Array(blocks.length).fill(GROUND),
blocks: Int16Array.from(blocks),
faces: Uint8Array.from(faces)
faces: Uint8Array.from(faces),
lights: new Uint8Array(blocks.length).fill(FULL_LIGHT),
shades: Uint16Array.from(shades ?? new Array(shown).fill(FULL_LIGHT))
}
return { voxels, models: [null, leaves, grass, null], looks: [stoneLook, null, null, null], colors: [0x808080, 0, 0, 0], isWater: [false, false, false, true] }
}
@@ -78,6 +84,23 @@ describe('voxel mesh', () => {
expect(faceCount(cutOut)).toBe(2)
})
it('darkens a corner of a face where opaque blocks stand around it, and splits the face away from it', () => {
const cornerHidden = FULL_LIGHT | (3 << 4)
const { opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [cornerHidden]), plain)
const colors = opaque!.getAttribute('color')
expect(colors.getY(0)).toBeLessThan(colors.getY(2) * 0.5)
expect(colors.getY(1)).toBeCloseTo(colors.getY(2))
expect(Array.from(opaque!.getIndex()!.array)).toEqual([1, 2, 3, 1, 3, 0])
})
it('darkens a face lit by less of the sky', () => {
const lit = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [FULL_LIGHT]), plain).opaque!
const shaded = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [8]), plain).opaque!
expect(shaded.getAttribute('color').getY(0)).toBeLessThan(lit.getAttribute('color').getY(0) * 0.7)
})
it('draws water as the sides of its sheet that face the air', () => {
const { water, opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([WATER], [UP | DOWN]), plain)
+100 -7
View File
@@ -5,6 +5,7 @@ import type { BlockLook, FaceLook } from './blockLooks'
import type { ColumnField } from './columnField'
import { shaded } from './columnFaces'
import { FACE_LIGHT, type CoverFace, type CoverLook } from './coverLooks'
import { brightnessOfCorner, brightnessOfLight, lightOf, opaqueAround } from './skyLight'
import type { UvCell } from './terrainAtlas'
import { sunk, tintAt } from './waterTint'
@@ -41,6 +42,8 @@ const CUBE_FACES: Record<Direction, Corners> = {
west: [[0, 1, 0], [0, 0, 0], [0, 0, 1], [0, 1, 1]],
east: [[1, 1, 1], [1, 0, 1], [1, 0, 0], [1, 1, 0]]
}
// The axis a side's faces look along: x, y or z.
const NORMAL_AXIS: Record<Direction, number> = { down: 1, up: 1, north: 2, south: 2, west: 0, east: 0 }
/**
* Each block seen from the open air drawn as Minecraft draws it: the faces of its model, leaving out a face its model
@@ -52,12 +55,15 @@ export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plai
const cutOut = new FaceSoup(true)
const water = new FaceSoup(false)
const { voxels } = surface
let firstShade = 0
for (let at = 0; at < voxels.x.length; at++) {
const column = voxels.x[at]
const row = voxels.z[at]
const corner: Color = [field.originX + column, voxels.y[at], field.originZ + row]
const block = voxels.blocks[at]
const sides = voxels.faces[at]
const shades = new FaceShades(voxels.shades, firstShade, sides, voxels.lights[at])
firstShade += shades.count
const waterTop = field.waterTopAt(column, row)
if (surface.isWater[block]) {
addCubeFaces(sides, (_side, corners) => water.add(corner, corners, null, null))
@@ -70,7 +76,8 @@ export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plai
continue
}
const color = underWater(face.color, corner[1] + middleY(face.corners), waterTop)
;(face.cell.hasGaps ? cutOut : opaque).add(corner, face.corners, pictureUvs(face.cell, face.uvs), color)
const brightness = face.cullFace === null ? shades.inside() : shades.across(face.cullFace, face.corners)
;(face.cell.hasGaps ? cutOut : opaque).add(corner, face.corners, pictureUvs(face.cell, face.uvs), litCorners(color, brightness))
}
continue
}
@@ -80,12 +87,84 @@ export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plai
const light = shaded(face === null ? surface.colors[block] : face.tint, FACE_LIGHT[side])
const color = underWater(light, corner[1] + middleY(corners), waterTop)
const cell = face === null ? plain : face.cell
;(cell.hasGaps ? cutOut : opaque).add(corner, corners, pictureUvs(cell, WHOLE_PICTURE), color)
;(cell.hasGaps ? cutOut : opaque).add(corner, corners, pictureUvs(cell, WHOLE_PICTURE), litCorners(color, shades.ofCube(side)))
})
}
return { opaque: opaque.geometry(), cutOut: cutOut.geometry(), water: water.geometry() }
}
type CornerBrightness = readonly [number, number, number, number]
/** One block's face shades, as the server sent them for the sides it shows, read as each corner's brightness. */
class FaceShades {
readonly count: number
constructor(
private readonly shades: Uint16Array,
private readonly first: number,
private readonly sides: number,
private readonly ownLight: number
) {
let count = 0
for (let rest = sides; rest !== 0; rest &= rest - 1) {
count++
}
this.count = count
}
/** A whole face on a side, its corners in {@link CUBE_FACES}' order. */
ofCube(side: Direction): CornerBrightness {
const shade = this.shadeOf(side)
const light = brightnessOfLight(lightOf(shade))
return [0, 1, 2, 3].map((corner) => light * brightnessOfCorner(opaqueAround(shade, corner))) as unknown as CornerBrightness
}
/** A model's face against a side, smaller than the block's, each corner as bright as that place of the whole face. */
across(side: Direction, corners: Corners): CornerBrightness {
const whole = this.ofCube(side)
const cube = CUBE_FACES[side]
return corners.map((place) => {
let brightness = 0
for (let corner = 0; corner < CORNERS; corner++) {
brightness += whole[corner] * weightAt(place, cube[corner], side)
}
return brightness
}) as unknown as CornerBrightness
}
/** A face that stands inside the block, such as a plant's, lit as the block's own cell, with no corner darkened. */
inside(): CornerBrightness {
const light = brightnessOfLight(this.ownLight)
return [light, light, light, light]
}
private shadeOf(side: Direction): number {
const bit = SIDE_BITS[side]
let before = 0
for (let rest = this.sides & (bit - 1); rest !== 0; rest &= rest - 1) {
before++
}
return this.shades[this.first + before]
}
}
// How much a corner of a whole face counts at a place on it: the product, along the face's two axes, of how near the
// place lies to the corner's edge.
function weightAt(place: Corners[number], corner: Corners[number], side: Direction): number {
const across = NORMAL_AXIS[side]
let weight = 1
for (let axis = 0; axis < 3; axis++) {
if (axis !== across) {
weight *= corner[axis] === 1 ? place[axis] : 1 - place[axis]
}
}
return weight
}
function litCorners(color: Color, brightness: CornerBrightness): Color[] {
return brightness.map((amount) => [color[0] * amount, color[1] * amount, color[2] * amount] as const)
}
function addCubeFaces(sides: number, add: (side: Direction, corners: Corners) => void): void {
for (const side of VOXEL_SIDES) {
if ((sides & SIDE_BITS[side]) !== 0) {
@@ -109,11 +188,14 @@ function pictureUvs(cell: UvCell, uvs: Uvs): Uvs {
const CORNERS = 4
const FIRST_CAPACITY_FACES = 4096
/** Faces gathered for one geometry, each with its own corners, so every face keeps its own colour. */
/** Faces gathered for one geometry, each with its own corners, so every face keeps its own colours. */
class FaceSoup {
private positions: Float32Array<ArrayBuffer> = new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3)
private uvs: Float32Array<ArrayBuffer> | null
private colors: Float32Array<ArrayBuffer> | null
// Whether each face is split along its other diagonal, as Minecraft splits one whose darker corners lie on the first,
// so the shading runs along the face and not across a crease.
private flipped: Uint8Array<ArrayBuffer> = new Uint8Array(FIRST_CAPACITY_FACES)
private faces = 0
constructor(textured: boolean) {
@@ -121,7 +203,8 @@ class FaceSoup {
this.colors = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) : null
}
add(origin: Color, corners: Corners, uvs: Uvs | null, color: Color | null): void {
/** Adds a face, with a colour for each corner, or none. */
add(origin: Color, corners: Corners, uvs: Uvs | null, colors: readonly Color[] | null): void {
this.reserveOne()
const first = this.faces * CORNERS
for (let corner = 0; corner < CORNERS; corner++) {
@@ -133,10 +216,11 @@ class FaceSoup {
this.uvs[vertex * 2] = uvs[corner][0]
this.uvs[vertex * 2 + 1] = uvs[corner][1]
}
if (this.colors !== null && color !== null) {
this.colors.set(color, vertex * 3)
if (this.colors !== null && colors !== null) {
this.colors.set(colors[corner], vertex * 3)
}
}
this.flipped[this.faces] = colors !== null && sum(colors[0]) + sum(colors[2]) < sum(colors[1]) + sum(colors[3]) ? 1 : 0
this.faces++
}
@@ -155,7 +239,9 @@ class FaceSoup {
const indices = new Uint32Array(this.faces * 6)
for (let face = 0; face < this.faces; face++) {
const first = face * CORNERS
indices.set([first, first + 1, first + 2, first, first + 2, first + 3], face * 6)
const split =
this.flipped[face] === 1 ? [first + 1, first + 2, first + 3, first + 1, first + 3, first] : [first, first + 1, first + 2, first, first + 2, first + 3]
indices.set(split, face * 6)
}
geometry.setIndex(new BufferAttribute(indices, 1))
return geometry
@@ -168,9 +254,16 @@ class FaceSoup {
this.positions = grown(this.positions)
this.uvs = this.uvs === null ? null : grown(this.uvs)
this.colors = this.colors === null ? null : grown(this.colors)
const flipped = new Uint8Array(this.flipped.length * 2)
flipped.set(this.flipped)
this.flipped = flipped
}
}
function sum(color: Color): number {
return color[0] + color[1] + color[2]
}
function grown(values: Float32Array): Float32Array<ArrayBuffer> {
const bigger = new Float32Array(values.length * 2)
bigger.set(values)