diff --git a/client/workers/chunk_worker.ts b/client/workers/chunk_worker.ts index 5e7442a..812c328 100644 --- a/client/workers/chunk_worker.ts +++ b/client/workers/chunk_worker.ts @@ -52,6 +52,8 @@ import { region_sky, REGION_VOID, } from "./lighting.ts"; +import { cell_index, liquid_quads, type LiquidCell } from "./liquid_mesh.ts"; +import { liquid_height, liquid_textures } from "$/common/everything_registry.ts"; type TexturesInfo = Record; @@ -92,6 +94,9 @@ 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) }; +// liquids: their range, 0 for blocks that aren't one, and where their level state is in the state bits +const liquid_range = new Uint8Array(TABLE_SIZE); +const liquid_level_shift = new Uint8Array(TABLE_SIZE); const region = new LightRegion(); // a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's @@ -137,7 +142,7 @@ self.onmessage = (event: MessageEvent) => { const { solid, cutout, translucent, min_y, max_y } = make_chunk_mesh( message.chunk_x, message.chunk_z, - message.chunks[4]!, + message.chunks, message.camera, ); const light = chunk_light(); @@ -262,6 +267,11 @@ function build_block_tables() { block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0; light_tables.opacity[nid] = opacity; light_tables.emission[nid] = block_light_emission(block); + liquid_range[nid] = block.liquid?.range ?? 0; + if (block.liquid) { + // the level state is the last one, see block_from_json + liquid_level_shift[nid] = (block.states ?? []).slice(0, -1).reduce((bits, state) => bits + state.bits, 0); + } }); block_lets_light_by[AIR] = 1; block_layers[REGION_VOID] = SOLID; @@ -505,9 +515,79 @@ function light_quad(quad: MeshQuad, index: number, y: number, face_offsets: numb corner_ao.fill(1); } +// whether a block hides the face of a liquid against it, like show_face. air's layer isn't set, so it's checked first +function hides_liquid(nid: number) { + 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 +// chunks that aren't there +function region_value(chunks: (Uint32Array | null)[], index: number, y: number) { + if (y < 0 || y >= CHUNK_HEIGHT) return AIR; + const x = index % REGION_SIZE; + const z = Math.floor(index / REGION_SIZE) % REGION_SIZE; + const chunk = chunks[Math.floor(z / CHUNK_SIZE) * 3 + Math.floor(x / CHUNK_SIZE)]; + return chunk ? chunk[y * CHUNK_AREA + (z % CHUNK_SIZE) * CHUNK_SIZE + (x % CHUNK_SIZE)] : AIR; +} + +// the surface of the liquid with this numeric id in a cell, if the cell is that liquid +function liquid_cell_height(nid: number, value: number) { + const level = ((value >>> 16) >>> liquid_level_shift[nid]) & 7; + return liquid_height(level, liquid_range[nid]); +} + +const liquid_cells: LiquidCell[] = Array.from( + { length: 9 }, + () => ({ same: false, height: 0, air: false, solid: false, top_same: false }), +); + +// the 3x3 cells around the liquid at index and y, see LiquidCell +function fill_liquid_cells(chunks: (Uint32Array | null)[], nid: number, index: number, y: number) { + for (let dz = -1; dz <= 1; dz++) { + for (let dx = -1; dx <= 1; dx++) { + const cell = liquid_cells[cell_index(dx, dz)]; + const at = index + dx + dz * REGION_SIZE; + const id = region_block(region, at, y); + cell.same = id === nid; + cell.height = cell.same ? liquid_cell_height(nid, region_value(chunks, at, y)) : 0; + cell.air = id === AIR; + cell.solid = hides_liquid(id); + cell.top_same = region_block(region, at + REGION_LAYER, y + 1) === nid; + } + } + return liquid_cells; +} + +// a liquid's quad for the mesher, see liquid_mesh.ts. it's lit like a full block's face on that side +function liquid_mesh_quad( + block: BlockRegistry, + face: number, + positions: number[], + uvs: number[], + still: boolean, +): MeshQuad { + const textures = liquid_textures(block.textures); + const flat = FACE_AXIS[face] !== 1 || (positions[1] === positions[4] && positions[4] === positions[7] && + positions[7] === positions[10]); + return { + positions, + uvs, + face, + cull: -1, + flush: true, + group: flat ? face : UNALIGNED_GROUP, + shade: FACE_SHADE[face], + sprite: textures_info[still ? textures.still : textures.flowing] ?? textures_info["engine:missing"], + light_weights: light_weights(face, positions), + tint: quad_tint(block, [still ? "still" : "flowing"]), + }; +} + // region has to be filled and lit first -// values is the middle chunk's blocks with their states, for models that change with them -function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array, camera: number[]) { +// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the +// ones around it for liquids, whose surface follows their neighbors' +function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array | null)[], camera: number[]) { + const values = chunks[4]!; // solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead const opaque = [SOLID, CUTOUT].map(() => Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity })) @@ -522,6 +602,39 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array, // where the neighbor on each face is, same order as FACE_NORMALS const face_offsets = FACE_NORMALS.map(([nx, ny, nz]) => nx + ny * REGION_LAYER + nz * REGION_SIZE); + // 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 wx = chunk_x * CHUNK_SIZE + x; + const wz = chunk_z * CHUNK_SIZE + z; + const tint = quad.tint === GRASS + ? blended[z * CHUNK_SIZE + x] + : quad.tint === FOLIAGE + ? blended[CHUNK_AREA + z * CHUNK_SIZE + x] + : quad.tint; + + if (layer_id !== TRANSLUCENT) { + const group = opaque[layer_id][quad.group]; + push_quad(group.buffer, quad, wx, y, wz, alpha, tint); + if (quad.group !== UNALIGNED_GROUP) { + const axis = FACE_AXIS[quad.face]; + const plane = (axis === 0 ? wx : axis === 1 ? y : wz) + quad.positions[axis]; + if (plane < group.min) group.min = plane; + if (plane > group.max) group.max = plane; + } + } else { + push_quad(translucent_quads, quad, wx, y, wz, alpha, tint); + // sorting treats every quad as facing along an axis, rotated ones too + const q = translucent_quads.count - 1; + centers = ensure_capacity(centers, (q + 1) * 3); + faces = ensure_capacity(faces, q + 1); + const p = quad.positions; + centers[q * 3] = wx + (p[0] + p[6]) / 2; + centers[q * 3 + 1] = y + (p[1] + p[7]) / 2; + centers[q * 3 + 2] = wz + (p[2] + p[8]) / 2; + faces[q] = quad.face; + } + }; + for (let y = 0; y < CHUNK_HEIGHT; y++) { for (let z = 0; z < CHUNK_SIZE; z++) { for (let x = 0; x < CHUNK_SIZE; x++) { @@ -534,8 +647,24 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array, const layer_id = block_layers[block_nid]; const alpha = layer_id === TRANSLUCENT ? block_info.alpha ?? 1 : 1; - const wx = chunk_x * CHUNK_SIZE + x; - const wz = chunk_z * CHUNK_SIZE + z; + if (liquid_range[block_nid]) { + const cells = fill_liquid_cells(chunks, block_nid, index, y); + const above = region_block(region, index + REGION_LAYER, y + 1); + const below = region_block(region, index - REGION_LAYER, y - 1); + const quads = liquid_quads( + cells, + { same: above === block_nid, solid: hides_liquid(above) }, + { same: below === block_nid, solid: hides_liquid(below) }, + ); + for (const { face, positions, uvs, still } of quads) { + const quad = liquid_mesh_quad(block_info, face, positions, uvs, still); + light_quad(quad, index, y, face_offsets); + // like minecraft's liquids, no ambient occlusion + corner_ao.fill(1); + emit(quad, layer_id, x, y, z, alpha); + } + continue; + } for (const quad of block_quads(values[y * CHUNK_AREA + z * CHUNK_SIZE + x])) { if (quad.cull >= 0) { @@ -548,33 +677,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array, } light_quad(quad, index, y, face_offsets); - const tint = quad.tint === GRASS - ? blended[z * CHUNK_SIZE + x] - : quad.tint === FOLIAGE - ? blended[CHUNK_AREA + z * CHUNK_SIZE + x] - : quad.tint; - - if (layer_id !== TRANSLUCENT) { - const group = opaque[layer_id][quad.group]; - push_quad(group.buffer, quad, wx, y, wz, alpha, tint); - if (quad.group !== UNALIGNED_GROUP) { - const axis = FACE_AXIS[quad.face]; - const plane = (axis === 0 ? wx : axis === 1 ? y : wz) + quad.positions[axis]; - if (plane < group.min) group.min = plane; - if (plane > group.max) group.max = plane; - } - } else { - push_quad(translucent_quads, quad, wx, y, wz, alpha, tint); - // sorting treats every quad as facing along an axis, rotated ones too - const q = translucent_quads.count - 1; - centers = ensure_capacity(centers, (q + 1) * 3); - faces = ensure_capacity(faces, q + 1); - const p = quad.positions; - centers[q * 3] = wx + (p[0] + p[6]) / 2; - centers[q * 3 + 1] = y + (p[1] + p[7]) / 2; - centers[q * 3 + 2] = wz + (p[2] + p[8]) / 2; - faces[q] = quad.face; - } + emit(quad, layer_id, x, y, z, alpha); } } } diff --git a/client/workers/liquid_mesh.ts b/client/workers/liquid_mesh.ts new file mode 100644 index 0000000..e5014d2 --- /dev/null +++ b/client/workers/liquid_mesh.ts @@ -0,0 +1,139 @@ +// liquids drawn like luanti's flowing liquids (MapblockMeshGenerator::drawLiquidNode in its content_mapblock.cpp): each +// corner of the surface is as high as the liquid around it, so it slopes down where it flows away from a source. the +// sides between two cells of it are left out, except where it pours down past the surface of the one beside it +import { FACE_CORNERS } from "$/common/block_models.ts"; + +// one of the 3x3 cells around a liquid and level with it, and the cell above that one +export interface LiquidCell { + // the same liquid, at any level + same: boolean; + // its surface, 0 to 1, when it's the same liquid. 1 is a source + height: number; + air: boolean; + // hides the side of the liquid facing it, like a full block of stone + solid: boolean; + // the cell above it is the same liquid, so the liquid here goes right up to the top + top_same: boolean; +} + +export interface LiquidQuad { + // the mesher's face index, see FACE_CORNERS + face: number; + // 4 corners in FACE_CORNERS' order, x y z in block space + positions: number[]; + // u v per corner, in pixels of the texture + uvs: number[]; + // drawn with the still texture, the top and bottom. the sides are flowing + still: boolean; +} + +// how far above the cell's floor a surface with air on two sides still is, luanti's 0.2 / BS +const SHORE = 0.02; + +// the horizontal neighbor each side faces, as dx dz, for faces 2 to 5: south (+z), north (-z), west (-x), east (+x) +const SIDE_DIRECTIONS = [[0, 1], [0, -1], [-1, 0], [1, 0]]; + +// cells indexed by (dz + 1) * 3 + (dx + 1), so 4 is the liquid itself +export function cell_index(dx: number, dz: number) { + return (dz + 1) * 3 + dx + 1; +} + +// like luanti's getCornerLevel: the height of the surface at a corner (cx and cz are 0 or 1, which end of the cell), +// from the 4 cells that share it. a source or liquid above any of them makes it full, two of air pull it down to the +// floor, otherwise it's the average of the liquid among them +export function corner_height(cells: LiquidCell[], cx: number, cz: number) { + let sum = 0; + let count = 0; + let air = 0; + for (let dz = cz - 1; dz <= cz; dz++) { + for (let dx = cx - 1; dx <= cx; dx++) { + const cell = cells[cell_index(dx, dz)]; + if (cell.top_same) return 1; + if (cell.same) { + if (cell.height >= 1) return 1; + sum += cell.height; + count++; + } else if (cell.air) { + air++; + } + } + } + if (air >= 2) return SHORE; + if (count > 0) return sum / count; + return 0.5; +} + +// the part of the texture each face shows at a point, like a full block's default uvs (see default_uv in +// common/block_models.ts), so a lower side shows the bottom of the texture instead of squashing all of it +function face_uv(face: number, x: number, y: number, z: number): [number, number] { + switch (face) { + case 0: + return [x * 16, z * 16]; + case 1: + return [x * 16, 16 - z * 16]; + case 2: + return [x * 16, 16 - y * 16]; + case 3: + return [16 - x * 16, 16 - y * 16]; + case 4: + return [z * 16, 16 - y * 16]; + default: + return [16 - z * 16, 16 - y * 16]; + } +} + +// a face's quad with the y of each corner from y_at (given the corner's x, its end on y, and z) +function quad(face: number, still: boolean, y_at: (x: number, top: number, z: number) => number): LiquidQuad { + const positions: number[] = []; + const uvs: number[] = []; + for (const [x, top, z] of FACE_CORNERS[face]) { + const y = y_at(x, top, z); + positions.push(x, y, z); + uvs.push(...face_uv(face, x, y, z)); + } + return { face, positions, uvs, still }; +} + +// the quads of the liquid in the middle cell. above and below are the cells over and under it: whether they're the +// same liquid, and whether they're solid +export function liquid_quads( + cells: LiquidCell[], + above: { same: boolean; solid: boolean }, + below: { same: boolean; solid: boolean }, +): LiquidQuad[] { + const quads: LiquidQuad[] = []; + // by corner, x then z + const heights = [ + corner_height(cells, 0, 0), + corner_height(cells, 0, 1), + corner_height(cells, 1, 0), + corner_height(cells, 1, 1), + ]; + const height = (x: number, z: number) => heights[x * 2 + z]; + + SIDE_DIRECTIONS.forEach(([dx, dz], i) => { + const face = i + 2; + const neighbor = cells[cell_index(dx, dz)]; + // nothing between two cells of it, unless it goes higher here and pours down past the other's surface + if (neighbor.same && (!above.same || neighbor.top_same)) return; + if (neighbor.solid) return; + const side = quad(face, false, (x, top, z) => { + if (top) return above.same ? 1 : height(x, z); + return neighbor.same ? height(x, z) : 0; + }); + // a side with no height, where the liquid next to it is level with it + const p = side.positions; + if (p[1] === p[4] && p[4] === p[7] && p[7] === p[10]) return; + quads.push(side); + }); + + // a full surface right under a solid block can't be seen + const full = heights.every((h) => h === 1); + if (!above.same && !(above.solid && full)) { + quads.push(quad(0, true, (x, _top, z) => height(x, z))); + } + if (!below.same && !below.solid) { + quads.push(quad(1, true, () => 0)); + } + return quads; +} diff --git a/common/block_models.ts b/common/block_models.ts index a00c80b..4c312fd 100644 --- a/common/block_models.ts +++ b/common/block_models.ts @@ -1,7 +1,7 @@ // block models, in the shape of minecraft's block model json: boxes ("elements") with a texture per face. // a block picks one with "model" and fills in its texture variables with "textures". baking turns a model // into quads in block space (0 to 1) that the chunk mesher and the item renderers draw -import type { BlockRegistry, BlockTextures } from "./everything_registry.ts"; +import { type BlockRegistry, type BlockTextures, liquid_textures } from "./everything_registry.ts"; import { tint_without_biome } from "./worldgen/biome_colors.ts"; import { get_state_value } from "./utils.ts"; @@ -190,7 +190,7 @@ export function block_variant(block: BlockRegistry, states?: Record; item_display?: { surface: number }; + // makes it a liquid, see LiquidProperties. range is 7 when not set + liquid?: Partial; } export interface OreJson { @@ -275,7 +281,8 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso if (block.light_emission !== undefined) json.light_emission = block.light_emission; if (block.light_opacity !== undefined) json.light_opacity = block.light_opacity; if (block.alpha !== undefined) json.alpha = block.alpha; - if (!block.has_collision) json.collision = false; + // liquids are without collision and replaceable unless they say otherwise + if (block.has_collision === !!block.liquid) json.collision = block.has_collision; if (block.shape !== undefined) json.shape = block.shape; if (block.collision_shape !== undefined) json.collision_shape = block.collision_shape; if (block.parts !== undefined) json.parts = block.parts; @@ -289,12 +296,21 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso if (block.drop_table !== undefined) json.drops = block.drop_table; if (!has_item) json.item = false; if (block.interactive) json.interactive = true; - if (block.replaceable) json.replaceable = true; + if (!!block.replaceable !== !!block.liquid) json.replaceable = !!block.replaceable; if (block.place_on) json.place_on = block.place_on; if (block.place_in) json.place_in = block.place_in; - if (block.states) json.states = block.states; + // a liquid's level state is its own, added when it loads + const states = block.liquid ? block.states?.slice(0, -1) : block.states; + if (states && (states.length > 0 || !block.liquid)) json.states = states; if (block.components) json.components = block.components; if (block.item_display) json.item_display = block.item_display; + if (block.liquid) { + // only what isn't the default + const liquid = block.liquid; + json.liquid = Object.fromEntries( + Object.entries(liquid).filter(([key, value]) => LIQUID_DEFAULTS[key as keyof LiquidProperties] !== value), + ); + } return json; } @@ -302,7 +318,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it const block: BlockRegistry = { id: json.id, textures: json.textures, - has_collision: json.collision ?? true, + has_collision: json.collision ?? !json.liquid, }; if (json.name !== undefined) block.name = json.name; if (json.model !== undefined) block.model = json.model; @@ -326,12 +342,17 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it } if (json.drops !== undefined) block.drop_table = json.drops; if (json.interactive) block.interactive = true; - if (json.replaceable) block.replaceable = true; + if (json.replaceable ?? json.liquid) block.replaceable = true; if (json.place_on) block.place_on = json.place_on; if (json.place_in) block.place_in = json.place_in; if (json.states) block.states = json.states; if (json.components) block.components = json.components; if (json.item_display) block.item_display = json.item_display; + if (json.liquid) { + block.liquid = { ...LIQUID_DEFAULTS, ...json.liquid }; + // last, so the block's own states keep their bits + block.states = [...block.states ?? [], { ...LIQUID_LEVEL }]; + } return { block, has_item: json.item ?? true }; } @@ -504,7 +525,9 @@ export function validate_block(json: unknown): Problems { if (json.model !== undefined) problems.push(...validate_id(json.model, "model")); const is_cube = json.parts === undefined && (json.model === undefined || json.model === "engine:cube"); const textures = json.textures; - if (is_cube) { + if (json.liquid !== undefined) { + problems.push(...validate_liquid(json)); + } else if (is_cube) { const texture_ok = typeof textures === "string" || (is_object(textures) && (["top", "bottom", "side"].every((k) => typeof textures[k] === "string") || @@ -647,6 +670,45 @@ export function validate_block(json: unknown): Problems { return problems; } +// a liquid is drawn by the engine, so it has no model of its own, and its level is a state it gets +function validate_liquid(json: Record): Problems { + const problems: Problems = []; + const liquid = json.liquid; + if (!is_object(liquid)) return ["liquid must be { range, ticks, renewable }, or {}"]; + for (const key of Object.keys(liquid)) { + if (!(key in LIQUID_DEFAULTS)) problems.push(`liquid.${key} isn't a liquid property`); + } + if (liquid.ticks !== undefined && (!Number.isInteger(liquid.ticks) || (liquid.ticks as number) < 1)) { + problems.push("liquid.ticks must be a whole number of 1 or more"); + } + if (liquid.renewable !== undefined && typeof liquid.renewable !== "boolean") { + problems.push("liquid.renewable must be true or false"); + } + const range = liquid.range; + if ( + range !== undefined && + (!Number.isInteger(range) || (range as number) < 1 || (range as number) > MAX_LIQUID_RANGE) + ) { + problems.push(`liquid.range must be a whole number from 1 to ${MAX_LIQUID_RANGE}`); + } + const textures = json.textures; + const texture_ok = typeof textures === "string" || + (is_object(textures) && typeof textures.still === "string" && + (textures.flowing === undefined || typeof textures.flowing === "string") && + Object.keys(textures).every((key) => key === "still" || key === "flowing")); + if (!texture_ok) problems.push("a liquid's textures must be a texture id or { still, flowing }"); + for (const key of ["model", "variants", "parts", "shape", "collision_shape", "item_model"]) { + if (json[key] !== undefined) problems.push(`a liquid can't have ${key}, the engine draws it`); + } + const states = Array.isArray(json.states) ? json.states : []; + if (states.some((state) => is_object(state) && state.name === LIQUID_LEVEL.name)) { + problems.push(`a liquid gets a "${LIQUID_LEVEL.name}" state of its own`); + } + const bits = states.reduce((sum, s) => sum + (is_object(s) && typeof s.bits === "number" ? s.bits : 0), 0); + if (bits + LIQUID_LEVEL.bits > 16) problems.push(`its states and its level use more than 16 bits`); + return problems; +} + // boxes in pixels: [[x1, y1, z1, x2, y2, z2], ...], each corner from 0 to 16 (y to top) and the second past the first function validate_shape(shape: unknown, where: string, top = 16): Problems { const is_box = (box: unknown) => diff --git a/docs/modding/blocks/index.md b/docs/modding/blocks/index.md index 32215ca..99b7c7c 100644 --- a/docs/modding/blocks/index.md +++ b/docs/modding/blocks/index.md @@ -53,7 +53,7 @@ there will be holes in the world behind them. | Field | Default | Meaning | | ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `collision` | `true` | Whether entities bump into it. Plants and water set `false`. | +| `collision` | `true` | Whether entities bump into it. Plants set `false`, and liquids default to it. | | `shape` | its model | The boxes players point at and entities bump into, in pixels. See [Shapes](../resources/models.md#shapes). | | `collision_shape` | `shape` | What entities bump into when it's different, up to 24 pixels high. See [Collision Shapes](../resources/models.md#collision-shapes). | | `mining.toughness` | unbreakable | Seconds to break by hand. Without `mining`, a block can't be broken. | @@ -63,12 +63,13 @@ there will be holes in the world behind them. | `drops` | nothing | The item id it drops when broken. | | `item` | `true` | Also register an item that places it, with the same id. To give that item more, see [Block Items](../items/index.md#block-items). | | `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. | -| `replaceable` | `false` | Placing a block into it replaces it, like water. | +| `replaceable` | `false` | Placing a block into it replaces it, like water. Liquids default to `true`. | | `place_in` | see meaning | Block ids or [tags](../resources/tags.md) it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. | | `place_on` | anywhere | Block ids or [tags](../resources/tags.md) it can stand on, like `["bworld:hoed_dirt"]` for crops or `["#bworld:logs"]`. See [below](#placement). | | `states` | none | Named [state](states.md) bits, like a crop's age. | | `components` | none | [Components](components.md) and their parameters. | | `item_display` | none | Shows an item on top of it, see [Tile Data](tiledata.md#showing-an-item). | +| `liquid` | none | Makes it a liquid, like water. See [Liquids](#liquids). | A block's definition goes to every player, since clients need it to draw the block, time breaking and collide with it. It can't hold functions. @@ -97,6 +98,54 @@ crop when its farmland is dug up. Food that places a block, like potatoes, is planted when clicked somewhere it can go and eaten otherwise. +## Liquids + +A block with `liquid` is a liquid, like water. The engine draws it like Luanti's liquids: each corner of its surface is +as high as the liquid around it, so it slopes down from a source to where it flows, and it thins out to a film at the +shore. + +`mods/oily/blocks/oil.json`: + +```json +{ + "format_version": 1, + "block": { + "id": "oily:oil", + "textures": { "still": "oily:oil_still", "flowing": "oily:oil_flowing" }, + "render_layer": "translucent", + "alpha": 0.9, + "liquid": { "range": 4 } + } +} +``` + +- `textures` is one texture, or `{ still, flowing }`: `still` on its top and bottom, `flowing` on its sides, like + Luanti's special tiles. +- `liquid.range` is how many blocks it flows from a source, 1 to 7, and `7` when not set. +- `liquid.ticks` is how many ticks each step of its flow takes, `5` when not set, like Minecraft's water. Lava's is 30. +- `liquid.renewable`, `true` when not set: a spot with two sources beside it and something solid or a source under it + becomes a source too, like Minecraft's infinite water. +- It gets a `level` [state](states.md) of its own, after any it lists: `0` is a source, a full block, and `1` up to + `range` as it flows away from one, each lower. +- `collision` defaults to `false` and `replaceable` to `true`. Entities swim in it and falling into it doesn't hurt. +- It can't have a `model`, `variants`, `parts`, `shape`, `collision_shape` or `item_model`, since the engine draws it. +- `tint` works on the `still` and `flowing` textures. + +### Flowing + +Liquids flow on the server like Minecraft's water. When a block next to a liquid changes, the cells around it are looked +at again after its `ticks`, and each works out what it should be: + +- A source stays a source. +- With the same liquid above, it's falling, and drawn full. +- Otherwise it's one level more than the lowest of the liquid beside it that spreads sideways, and gone once that's past + `range`. Sources spread sideways, and flowing liquid only does when it's on something solid: over air or more of + itself, it falls instead. + +So it spreads one block a step, falls off edges and spreads again where it lands, and drains away a step at a time once +its source is gone. It only flows into air, and stops at chunks that aren't loaded. Buckets only pick up sources. Flows +still going when the server stops don't carry on after it starts again until something next to them changes. + ## Tinting `tint` draws a block's textures in a color, for textures painted in greys: diff --git a/mods/bworld/blocks/water.json b/mods/bworld/blocks/water.json index be4a83b..fec05fe 100644 --- a/mods/bworld/blocks/water.json +++ b/mods/bworld/blocks/water.json @@ -6,9 +6,8 @@ "render_layer": "translucent", "light_opacity": 1, "alpha": 0.8, - "collision": false, "item": false, - "replaceable": true, + "liquid": {}, "components": { "bworld:water_source": {}, "bworld:fishable": {}, diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index b702cd6..ac50843 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -594,6 +594,8 @@ function register_buckets(ctx: ServerContext) { on_interact(block, params, player) { const bucket = player.held_item; if (bucket?.id !== BUCKET) return false; + // only a liquid's source fills it, not where it's flowing + if ((ctx.world.get_state(block.x, block.y, block.z, "level") ?? 0) !== 0) return false; ctx.world.set_block(block.x, block.y, block.z, "bworld:air"); bucket.count -= 1; // the last one becomes the filled bucket in the hand, from a stack it goes in the inventory diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 753ad03..f55c1fb 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -9,6 +9,7 @@ import { TICKS_PER_SECOND, } from "$/common/constants.ts"; import { BlockRegistry, EverythingRegistry, is_liquid_block, ItemRegistry } from "$/common/everything_registry.ts"; +import { LiquidFlow } from "./liquids.ts"; import { Container, ItemData, ItemStack } from "$/common/inventory.ts"; import { AIR_ID, @@ -161,6 +162,8 @@ export class GameServer { recipes: RecipeBook; // monsters spawning on their own near players, see natural_spawner.ts spawner: NaturalSpawner; + // water and other liquids flowing, see liquids.ts + liquids: LiquidFlow; // minecraft's doMobSpawning game rule. tests turn it off so nothing turns up they didn't put there do_mob_spawning = true; // what runs tick(), for /tps. tests call tick() themselves @@ -186,6 +189,20 @@ export class GameServer { ); } this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen); + this.liquids = new LiquidFlow({ + value_at: (x, y, z) => { + if (y < 0 || y >= CHUNK_HEIGHT) return undefined; + const loaded = this.world.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); + return loaded ? this.world.get_block_value(x, y, z) : undefined; + }, + block: (nid) => EverythingRegistry.get_by_id("blocks", nid), + nid: (id) => this.world.block_ids[id], + set_block: (x, y, z, id, state) => { + // a level changing is only a state, the block's components don't see it come and go + if (id === this.world.get_block_id(x, y, z)) this.set_block_state(x, y, z, state); + else this.set_block(x, y, z, id, undefined, state); + }, + }); // deno-lint-ignore no-this-alias const game = this; this.entities = new EntityManager({ @@ -231,6 +248,7 @@ export class GameServer { // players without the chunk get the block with it when they do, like minecraft this.world.on_block_change = (x, y, z, id, state) => { + this.liquids.changed(x, y, z, this.#tick); const data = JSON.stringify( (state ? { type: "set_block", x, y, z, id, state } @@ -331,6 +349,7 @@ export class GameServer { } this.#new_days(); + this.liquids.tick(this.#tick); this.#tick_vitals(); this.#tick_entities(); diff --git a/server/game/liquids.ts b/server/game/liquids.ts new file mode 100644 index 0000000..b10e9b4 --- /dev/null +++ b/server/game/liquids.ts @@ -0,0 +1,165 @@ +// liquids flowing, like minecraft's FlowingFluid: a change next to a liquid gets the cells around it looked at again +// after the liquid's ticks, and each works out what it should be from its neighbors (see next_level). that changes +// more cells, and so it spreads one block a step, and drains away the same way once its source is gone +import { AIR, CHUNK_HEIGHT, ID_MASK } from "$/common/constants.ts"; +import type { BlockRegistry } from "$/common/everything_registry.ts"; +import { AIR_ID } from "$/common/protocol.ts"; +import { get_state_value, set_state_value } from "$/common/utils.ts"; + +// what the flow needs of the world +export interface LiquidWorld { + // undefined where the chunk isn't loaded, so liquid stops at the edge of the world instead of making new chunks + value_at(x: number, y: number, z: number): number | undefined; + // by numeric id + block(nid: number): BlockRegistry | undefined; + nid(id: string): number; + // changes a block, with its components and neighbors told like any other change + set_block(x: number, y: number, z: number, id: string, state: number): void; +} + +// the most cells looked at in one tick, the rest wait for the next +const MAX_PER_TICK = 4096; + +const HORIZONTAL = [[1, 0], [-1, 0], [0, 1], [0, -1]]; +const NEIGHBORS = [[0, 0, 0], [0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0], [0, 0, 1], [0, 0, -1]]; + +// a liquid in a cell: which, and its level +interface Liquid { + nid: number; + block: BlockRegistry; + level: number; +} + +const key = (x: number, y: number, z: number) => `${x},${y},${z}`; + +export class LiquidFlow { + #world: LiquidWorld; + // cells to look at, by key, with the tick they're due + #due = new Map(); + + constructor(world: LiquidWorld) { + this.#world = world; + } + + // how many cells are waiting, for tests + get pending() { + return this.#due.size; + } + + // a block changed at x y z: if there's liquid there or beside it, it and its neighbors are looked at again after + // that liquid's ticks + changed(x: number, y: number, z: number, now: number) { + let ticks = Infinity; + for (const [dx, dy, dz] of NEIGHBORS) { + const liquid = this.#liquid(x + dx, y + dy, z + dz); + if (liquid) ticks = Math.min(ticks, liquid.block.liquid!.ticks); + } + if (ticks === Infinity) return; + for (const [dx, dy, dz] of NEIGHBORS) { + const k = key(x + dx, y + dy, z + dz); + const due = this.#due.get(k); + if (due && due.tick <= now + ticks) continue; + this.#due.set(k, { x: x + dx, y: y + dy, z: z + dz, tick: now + ticks }); + } + } + + // looks at the cells due by now. changing them schedules their neighbors through changed + tick(now: number) { + const ready: { x: number; y: number; z: number }[] = []; + for (const [k, due] of this.#due) { + if (due.tick > now) continue; + this.#due.delete(k); + ready.push(due); + if (ready.length >= MAX_PER_TICK) break; + } + for (const { x, y, z } of ready) this.#update(x, y, z); + } + + #update(x: number, y: number, z: number) { + const value = this.#world.value_at(x, y, z); + if (value === undefined) return; + const nid = value & ID_MASK; + const here = this.#liquid(x, y, z); + if (here?.level === 0) return; + // only air and the liquid's own flowing cells are flowed into + if (!here && nid !== AIR) return; + + // the liquid that would be here: what's here, or one from above or beside + const candidates = here ? [here] : this.#liquids_around(x, y, z); + for (const liquid of candidates) { + const level = this.next_level(liquid, x, y, z); + if (level === undefined) continue; + if (!here || here.level !== level) this.#set(liquid.block, x, y, z, level); + return; + } + if (here) this.#world.set_block(x, y, z, AIR_ID, 0); + } + + // what level the liquid would be at x y z, from the cells around it, or undefined for none there + next_level(liquid: Liquid, x: number, y: number, z: number): number | undefined { + const props = liquid.block.liquid!; + const same = (cx: number, cy: number, cz: number) => { + const other = this.#liquid(cx, cy, cz); + return other?.nid === liquid.nid ? other : undefined; + }; + + // two sources beside it over something solid or a source make another, like minecraft's infinite water + if (props.renewable) { + const sources = HORIZONTAL.filter(([dx, dz]) => same(x + dx, y, z + dz)?.level === 0).length; + const below = this.#world.value_at(x, y - 1, z); + const below_block = below === undefined ? undefined : this.#world.block(below & ID_MASK); + if (sources >= 2 && (below_block?.has_collision || same(x, y - 1, z)?.level === 0)) return 0; + } + + // falling, with more of it above. it's drawn full whatever its level, see liquid_mesh.ts + if (same(x, y + 1, z)) return 1; + + let lowest = Infinity; + for (const [dx, dz] of HORIZONTAL) { + const nx = x + dx; + const nz = z + dz; + const neighbor = same(nx, y, nz); + if (!neighbor || !this.#spreads_sideways(neighbor, nx, y, nz)) continue; + // falling liquid spreads like a source once it lands + const level = same(nx, y + 1, nz) ? 0 : neighbor.level; + lowest = Math.min(lowest, level); + } + const level = lowest + 1; + return level <= props.range ? level : undefined; + } + + // sources spread sideways, and flowing liquid that can't fall any further. over air or more of itself it falls + // instead, like minecraft's isWaterHole + #spreads_sideways(liquid: Liquid, x: number, y: number, z: number) { + if (liquid.level === 0) return true; + const below = this.#world.value_at(x, y - 1, z); + if (below === undefined) return false; + const nid = below & ID_MASK; + return nid !== AIR && nid !== liquid.nid; + } + + // the liquids above and beside x y z that could flow into it, above first + #liquids_around(x: number, y: number, z: number): Liquid[] { + const found: Liquid[] = []; + for (const [dx, dy, dz] of [[0, 1, 0], ...HORIZONTAL.map(([dx, dz]) => [dx, 0, dz])]) { + const liquid = this.#liquid(x + dx, y + dy, z + dz); + if (liquid && !found.some((other) => other.nid === liquid.nid)) found.push(liquid); + } + return found; + } + + #liquid(x: number, y: number, z: number): Liquid | undefined { + if (y < 0 || y >= CHUNK_HEIGHT) return undefined; + const value = this.#world.value_at(x, y, z); + if (value === undefined) return undefined; + const nid = value & ID_MASK; + const block = this.#world.block(nid); + if (!block?.liquid) return undefined; + return { nid, block, level: get_state_value(value, block, "level")! }; + } + + #set(block: BlockRegistry, x: number, y: number, z: number, level: number) { + const value = set_state_value(this.#world.nid(block.id), block, "level", level)!; + this.#world.set_block(x, y, z, block.id, value >>> 16); + } +} diff --git a/tests/base_game_test.ts b/tests/base_game_test.ts index 6f7ccc8..0892792 100644 --- a/tests/base_game_test.ts +++ b/tests/base_game_test.ts @@ -290,3 +290,23 @@ Deno.test("a smithing result can't be taken once its inputs are gone, even befor t.game.tick(); assertEquals(menu_items(t.take(1))[3], null); }); + +Deno.test("a bucket picks up a water source but not flowing water, and a water bucket puts a source back", async () => { + const t = await setup([["bworld:bucket", 1]]); + const held = () => t.game.players()[0].held_item?.type_id; + t.game.set_block(1, 100, 0, "bworld:water"); + // flowing water a block from it, the flow keeps it there + t.game.set_block(2, 100, 0, "bworld:water", undefined, 1); + + t.send(1, { type: "use_block", x: 2, y: 100, z: 0, face: "top" }); + assertEquals(held(), "bworld:bucket"); + + t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); + assertEquals(held(), "bworld:water_bucket"); + assertEquals(t.game.world.get_block_id(1, 100, 0), "bworld:air"); + + t.send(1, { type: "use_block", x: -2, y: 99, z: 0, face: "top" }); + assertEquals(held(), "bworld:bucket"); + assertEquals(t.game.world.get_block_id(-2, 100, 0), "bworld:water"); + assertEquals(t.game.world.get_block_value(-2, 100, 0) >>> 16, 0); +}); diff --git a/tests/liquid_flow_test.ts b/tests/liquid_flow_test.ts new file mode 100644 index 0000000..0175865 --- /dev/null +++ b/tests/liquid_flow_test.ts @@ -0,0 +1,154 @@ +// liquids flowing on the server, like minecraft's water: out from a source, down past edges, and draining away +import { assert, assertEquals } from "@std/assert"; +import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; +import { get_state_value } from "$/common/utils.ts"; +import { LIQUID_DEFAULTS } from "$/common/everything_registry.ts"; +import { LiquidFlow } from "$/server/game/liquids.ts"; +import { test_game } from "./helpers.ts"; + +type Game = Awaited>["game"]; + +// high above the test seed's ground, so only what the test builds is there +const Y = 150; + +// a stone floor from -r to r around 0, 0 at y, with air above it +function floor(game: Game, r: number, y = Y - 1) { + for (let x = -r; x <= r; x++) { + for (let z = -r; z <= r; z++) game.set_block(x, y, z, "bworld:stone"); + } +} + +function ticks(game: Game, count: number) { + for (let i = 0; i < count; i++) game.tick(); +} + +// the water's level there, undefined for no water +function level(game: Game, x: number, y: number, z: number) { + if (game.world.get_block_id(x, y, z) !== "bworld:water") return undefined; + const water = EverythingRegistry.get("blocks", "bworld:water")!; + return get_state_value(game.world.get_block_value(x, y, z), water, "level"); +} + +Deno.test("water flows out from a source one block a step, lower each block, up to its range", async () => { + const { game } = await test_game("mods"); + floor(game, 10); + game.set_block(0, Y, 0, "bworld:water"); + + // water's 5 ticks a step + ticks(game, 5); + assertEquals([1, 0, -1].map((x) => level(game, x, Y, 0)), [1, 0, 1]); + assertEquals(level(game, 2, Y, 0), undefined); + + ticks(game, 60); + for (let x = 0; x <= 7; x++) assertEquals(level(game, x, Y, 0), x, `at x ${x}`); + // past its range of 7 there's none + assertEquals(level(game, 8, Y, 0), undefined); + // it spreads in a diamond, by how far it walked + assertEquals(level(game, 3, Y, 3), 6); + // and doesn't flow on its own after that + assertEquals(game.liquids.pending, 0); +}); + +Deno.test("water falls off an edge and spreads again where it lands", async () => { + const { game } = await test_game("mods"); + // a ledge one block wide, and a floor 3 below + game.set_block(0, Y - 1, 0, "bworld:stone"); + floor(game, 10, Y - 4); + game.set_block(0, Y, 0, "bworld:water"); + ticks(game, 100); + + // off the ledge, then down the side as falling water + assertEquals(level(game, 1, Y, 0), 1); + for (let y = Y - 1; y >= Y - 3; y--) assertEquals(level(game, 1, y, 0), 1, `at y ${y}`); + // over air it doesn't spread sideways + assertEquals(level(game, 2, Y, 0), undefined); + // where it lands it spreads like from a source + assertEquals(level(game, 2, Y - 3, 0), 1); + assertEquals(level(game, 4, Y - 3, 0), 3); +}); + +Deno.test("taking the source away drains what flowed from it", async () => { + const { game } = await test_game("mods"); + floor(game, 10); + game.set_block(0, Y, 0, "bworld:water"); + ticks(game, 60); + assertEquals(level(game, 5, Y, 0), 5); + + game.set_block(0, Y, 0, "bworld:air"); + ticks(game, 200); + for (let x = -8; x <= 8; x++) { + for (let z = -8; z <= 8; z++) assertEquals(level(game, x, Y, z), undefined, `at ${x}, ${z}`); + } + assertEquals(game.liquids.pending, 0); +}); + +Deno.test("two sources beside a spot on solid ground make it a source, like infinite water", async () => { + const { game } = await test_game("mods"); + floor(game, 10); + // walls around a 3 long trench, open on top + for (let x = -2; x <= 2; x++) { + for (const z of [-1, 1]) game.set_block(x, Y, z, "bworld:stone"); + } + game.set_block(-2, Y, 0, "bworld:stone"); + game.set_block(2, Y, 0, "bworld:stone"); + game.set_block(-1, Y, 0, "bworld:water"); + game.set_block(1, Y, 0, "bworld:water"); + ticks(game, 20); + assertEquals(level(game, 0, Y, 0), 0); + + // and stays one with the others gone + game.set_block(-1, Y, 0, "bworld:air"); + game.set_block(1, Y, 0, "bworld:air"); + ticks(game, 20); + assertEquals(level(game, 0, Y, 0), 0); +}); + +Deno.test("water flows into a hole when a block next to it is broken", async () => { + const { game } = await test_game("mods"); + floor(game, 10); + // a source boxed in by stone + for (const [dx, dz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) game.set_block(dx, Y, dz, "bworld:stone"); + game.set_block(0, Y, 0, "bworld:water"); + ticks(game, 20); + assertEquals(level(game, 2, Y, 0), undefined); + + game.destroy_block(1, Y, 0); + ticks(game, 5); + assertEquals(level(game, 1, Y, 0), 1); + ticks(game, 5); + assertEquals(level(game, 2, Y, 0), 2); +}); + +Deno.test("water stops at chunks that aren't loaded instead of making them", () => { + // a world of stone floor at y 0 where x is 0 or less, and nothing loaded past that + const water = { + id: "a:water", + textures: "a:water", + has_collision: false, + liquid: LIQUID_DEFAULTS, + } as BlockRegistry; + water.states = [{ name: "level", bits: 3, default: 0 }]; + const blocks = new Map([["0,1,0", 1]]); + const asked: number[] = []; + const flow = new LiquidFlow({ + value_at(x, y, z) { + asked.push(x); + if (x > 0) return undefined; + return y === 0 ? 2 : blocks.get(`${x},${y},${z}`) ?? 0; + }, + block: (nid) => + nid === 1 ? water : nid === 2 ? { id: "a:stone", textures: "a:stone", has_collision: true } : undefined, + nid: (id) => id === "a:water" ? 1 : 0, + set_block(x, y, z, id, state) { + assert(x <= 0, `set a block at x ${x}`); + blocks.set(`${x},${y},${z}`, id === "a:water" ? 1 | (state << 16) : 0); + flow.changed(x, y, z, 5); + }, + }); + flow.changed(0, 1, 0, 0); + flow.tick(5); + // it flowed to -x, and not to +x + assertEquals(blocks.get("-1,1,0"), 1 | (1 << 16)); + assert(!blocks.has("1,1,0")); + assert(asked.includes(1)); +}); diff --git a/tests/liquid_test.ts b/tests/liquid_test.ts new file mode 100644 index 0000000..f95d666 --- /dev/null +++ b/tests/liquid_test.ts @@ -0,0 +1,226 @@ +// liquids: blocks with "liquid", drawn like luanti's with surfaces that slope down to where they flow +import { assert, assertAlmostEquals, assertEquals } from "@std/assert"; +import { + type BlockRegistry, + EverythingRegistry, + is_liquid_block, + liquid_height, + liquid_textures, +} from "$/common/everything_registry.ts"; +import { block_from_json, block_to_json, type BlockJson, validate_block } from "$/common/mod_data.ts"; +import { cube_face_texture } from "$/common/block_models.ts"; +import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts"; +import { get_state_value, set_state_value } from "$/common/utils.ts"; +import { cell_index, corner_height, liquid_quads, type LiquidCell } from "$/client/workers/liquid_mesh.ts"; +import { TERRAIN_VERTEX_BYTES } from "$/client/workers/chunk_messages.ts"; +import { test_game } from "./helpers.ts"; + +const OIL: BlockJson = { + id: "oily:oil", + textures: { still: "oily:oil_still", flowing: "oily:oil_flow" }, + render_layer: "translucent", + liquid: { range: 4 }, +}; + +Deno.test("a liquid gets a level state, no collision and can be placed into", () => { + const { block } = block_from_json(OIL); + assert(is_liquid_block(block)); + assertEquals(block.liquid, { range: 4, ticks: 5, renewable: true }); + assertEquals(block.states, [{ name: "level", bits: 3, default: 0 }]); + assertEquals(block.has_collision, false); + assertEquals(block.replaceable, true); + // and goes back to the same json + assertEquals(block_to_json(block, true), OIL); + + // its own states keep their bits, the level goes after them + const { block: hot } = block_from_json({ ...OIL, states: [{ name: "hot", bits: 1, default: 0 }] }); + assertEquals(hot.states!.map((s) => s.name), ["hot", "level"]); + const value = set_state_value(set_state_value(5, hot, "level", 3)!, hot, "hot", 1)!; + assertEquals(get_state_value(value, hot, "level"), 3); + assertEquals(block_to_json(hot, true).states, [{ name: "hot", bits: 1, default: 0 }]); + + // a range of 7 is the default + const water = block_from_json({ id: "a:water", textures: "a:water", liquid: {} }).block; + assertEquals(water.liquid, { range: 7, ticks: 5, renewable: true }); + assertEquals(block_to_json(water, true).liquid, {}); +}); + +Deno.test("a liquid's still texture is its top and bottom, the flowing one its sides", () => { + const { block } = block_from_json(OIL); + assertEquals(liquid_textures(block.textures), { still: "oily:oil_still", flowing: "oily:oil_flow" }); + assertEquals(cube_face_texture(block, "top"), "oily:oil_still"); + assertEquals(cube_face_texture(block, "side"), "oily:oil_flow"); + // one texture is both + assertEquals(liquid_textures("a:water"), { still: "a:water", flowing: "a:water" }); + assertEquals(liquid_textures({ still: "a:water" }), { still: "a:water", flowing: "a:water" }); +}); + +Deno.test("check-mods catches liquids that can't work", () => { + assertEquals(validate_block(OIL), []); + const problems = (json: Record) => validate_block({ ...OIL, ...json }); + assertEquals(problems({ liquid: { range: 8 } }), ["liquid.range must be a whole number from 1 to 7"]); + assertEquals(problems({ liquid: true }), ["liquid must be { range, ticks, renewable }, or {}"]); + assertEquals(problems({ liquid: { ticks: 0 } }), ["liquid.ticks must be a whole number of 1 or more"]); + assertEquals(problems({ liquid: { speed: 2 } }), ["liquid.speed isn't a liquid property"]); + assertEquals(problems({ textures: { top: "a:b" } }), [ + "a liquid's textures must be a texture id or { still, flowing }", + ]); + assertEquals(problems({ model: "engine:cross" }), ["a liquid can't have model, the engine draws it"]); + assertEquals(problems({ states: [{ name: "level", bits: 2, default: 0 }] }), [ + 'a liquid gets a "level" state of its own', + ]); +}); + +Deno.test("a liquid's surface is full at a source and lower each block it flows", () => { + assertEquals(liquid_height(0, 7), 1); + assertAlmostEquals(liquid_height(1, 7), 6.5 / 7); + assertAlmostEquals(liquid_height(7, 7), 0.5 / 7); + // past its range it's as low as it goes + assertEquals(liquid_height(5, 4), liquid_height(4, 4)); +}); + +// the 3x3 cells around a liquid, all air unless set +function cells(set: Record> = {}) { + const list: LiquidCell[] = Array.from({ length: 9 }, () => ({ + same: false, + height: 0, + air: true, + solid: false, + top_same: false, + })); + for (const [key, cell] of Object.entries(set)) { + const [dx, dz] = key.split(",").map(Number); + Object.assign(list[cell_index(dx, dz)], { air: false }, cell); + } + return list; +} +const liquid = (height: number): Partial => ({ same: true, height }); +const OPEN = { same: false, solid: false }; +const SOLID = { same: false, solid: true }; + +// the highest and lowest y of each quad, by face +function extents(quads: ReturnType) { + return quads.map((q) => { + const ys = [q.positions[1], q.positions[4], q.positions[7], q.positions[10]]; + return { face: q.face, min: Math.min(...ys), max: Math.max(...ys) }; + }); +} + +Deno.test("a lone source is a full block, on the ground it has no bottom", () => { + const quads = liquid_quads(cells({ "0,0": liquid(1) }), OPEN, SOLID); + assertEquals(quads.map((q) => q.face).sort(), [0, 2, 3, 4, 5]); + for (const { min, max, face } of extents(quads)) { + if (face === 0) assertEquals([min, max], [1, 1]); + else assertEquals([min, max], [0, 1]); + } +}); + +Deno.test("the middle of a lake is only its surface", () => { + const lake: Record> = {}; + for (let dx = -1; dx <= 1; dx++) for (let dz = -1; dz <= 1; dz++) lake[`${dx},${dz}`] = liquid(1); + assertEquals(liquid_quads(cells(lake), OPEN, SOLID).map((q) => q.face), [0]); + // deeper down, nothing at all + assertEquals(liquid_quads(cells(lake), { same: true, solid: false }, { same: true, solid: false }), []); + // a full surface right under a solid block can't be seen + assertEquals(liquid_quads(cells(lake), SOLID, SOLID), []); +}); + +Deno.test("flowing liquid slopes down from the source beside it, and thins out to a film at the shore", () => { + const flowing = liquid_height(1, 7); + // a source to the -x side + const set = cells({ "0,0": liquid(flowing), "-1,0": liquid(1) }); + assertEquals(corner_height(set, 0, 0), 1); + assertEquals(corner_height(set, 0, 1), 1); + // the +x corners have it and air around them + assertAlmostEquals(corner_height(set, 1, 0), 0.02); + + const quads = liquid_quads(set, OPEN, SOLID); + // no side facing the source + assert(!quads.some((q) => q.face === 4)); + const top = extents(quads).find((q) => q.face === 0)!; + assertEquals(top.max, 1); + assertAlmostEquals(top.min, 0.02); + + // between two flowing cells, the average + const two = cells({ "0,0": liquid(0.5), "1,0": liquid(0.3), "1,1": liquid(0.1), "0,1": { solid: true } }); + assertAlmostEquals(corner_height(two, 1, 1), 0.3); +}); + +Deno.test("a lower neighbor's surface rises to meet a column of liquid, so there's no gap", () => { + // liquid with more of itself above: every corner is full, so the side toward the lower one has no height + const column = cells({ "0,0": { ...liquid(1), top_same: true }, "0,1": liquid(0.3) }); + const quads = liquid_quads(column, { same: true, solid: false }, SOLID); + assert(!quads.some((q) => q.face === 2 || q.face === 0)); + // the lower one, beside the column at -z: its top goes up to the top of the cell there + const low = cells({ "0,0": liquid(0.3), "0,-1": { ...liquid(1), top_same: true } }); + const top = liquid_quads(low, OPEN, SOLID).find((q) => q.face === 0)!; + const ys_at_z = (z: number) => + [0, 1, 2, 3].filter((k) => top.positions[k * 3 + 2] === z).map((k) => top.positions[k * 3 + 1]); + assertEquals(ys_at_z(0), [1, 1]); +}); + +// the translucent quads of the middle chunk with these blocks in it, as the chunk worker meshes them. blocks are +// [x, y, z, id, level] in the middle chunk, x can be -1 for the chunk to its -x side +async function mesh(blocks: [number, number, number, string, number?][]) { + await test_game("mods"); + const registry = EverythingRegistry.get_registry("blocks"); + const ids: Record = {}; + 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" }); + worker.postMessage({ + type: "init", + blocks_registry: JSON.parse(JSON.stringify(registry)), + models: {}, + textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } }, + image: { width: 1024, height: 1024 }, + }); + const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT)); + for (const [x, y, z, id, level] of blocks) { + 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); + } + // deno-lint-ignore no-explicit-any + const meshed = await new Promise((resolve) => { + worker.onmessage = (e) => resolve(e.data); + worker.postMessage({ + type: "mesh", + chunk_x: 0, + chunk_z: 0, + version: 1, + chunks, + biome_colors: chunks.map(() => null), + camera: [0, 0, 0], + }); + }); + worker.terminate(); + const f32 = new Float32Array(meshed.translucent.vertices.buffer); + const quads: number[][][] = []; + for (let quad = 0; quad < meshed.translucent.quad_count; quad++) { + const byte = quad * 4 * TERRAIN_VERTEX_BYTES; + quads.push([0, 1, 2, 3].map((k) => [0, 1, 2].map((i) => f32[(byte + k * TERRAIN_VERTEX_BYTES) / 4 + i]))); + } + return quads; +} + +Deno.test("the chunk worker draws water sloping down from a source, across a chunk's edge too", async () => { + // three rows of it: a source at x -1, in the chunk to the -x side, then flowing water at x 0 and 1, on stone + const blocks: [number, number, number, string, number?][] = []; + for (let z = 7; z <= 9; z++) { + blocks.push([-1, 10, z, "bworld:water", 0], [0, 10, z, "bworld:water", 1], [1, 10, z, "bworld:water", 2]); + blocks.push([0, 9, z, "bworld:stone"], [1, 9, z, "bworld:stone"]); + } + const quads = await mesh(blocks); + // the tops of the middle chunk's water, by the x of their corners + const tops = quads.filter((corners) => corners.every(([, y]) => y > 10)); + assertEquals(tops.length, 6); + const height_at = (x: number) => + Math.max(...tops.flat().filter(([cx]) => Math.abs(cx - x) < 1e-6).map(([, y]) => y - 10)); + // full where it meets the source, then down + assertEquals(height_at(0), 1); + // the average of the levels around it, between the rows + assertAlmostEquals(height_at(1), (liquid_height(1, 7) + liquid_height(2, 7)) / 2, 1e-6); + assertAlmostEquals(height_at(2), 0.02, 1e-6); + // no sides between cells of it, only on the outside + assert(!quads.some((corners) => corners.every(([x]) => x === 1))); + assert(quads.some((corners) => corners.every(([x]) => x === 2))); +}); diff --git a/tests/physics_test.ts b/tests/physics_test.ts index d168db3..41fa928 100644 --- a/tests/physics_test.ts +++ b/tests/physics_test.ts @@ -1,6 +1,6 @@ import { assert, assertAlmostEquals, assertEquals } from "@std/assert"; import { eyes_in_water, in_water, move_body } from "$/common/physics.ts"; -import { type BlockRegistry, is_liquid_block } from "$/common/everything_registry.ts"; +import { type BlockRegistry, is_liquid_block, LIQUID_DEFAULTS } from "$/common/everything_registry.ts"; const body = (x: number, z: number, vx: number, vz: number) => ({ x, y: 0, z, vx, vy: 0, vz, width: 0.6, height: 1.8 }); // a block at x 0 to 1, z 1 to 2, on a floor @@ -43,11 +43,11 @@ Deno.test("a body on the ground steps up onto something low, not onto a full blo assertAlmostEquals(wall.y, 0); }); -Deno.test("water is a block with no collision that can be placed into", () => { - const block = (has_collision: boolean, replaceable?: boolean) => ({ has_collision, replaceable }) as BlockRegistry; - assertEquals(is_liquid_block(block(false, true)), true); - assertEquals(is_liquid_block(block(true, true)), false); - assertEquals(is_liquid_block(block(false)), false); +Deno.test("liquids are the blocks that say they are one", () => { + const block = (fields: Partial) => ({ has_collision: false, ...fields }) as BlockRegistry; + assertEquals(is_liquid_block(block({ liquid: LIQUID_DEFAULTS })), true); + // no collision and replaceable isn't enough any more, like a plant you can place into + assertEquals(is_liquid_block(block({ replaceable: true })), false); assertEquals(is_liquid_block(undefined), false); });