Occlusion culling
This commit is contained in:
@@ -28,6 +28,7 @@ import { ChunkWorkerPool } from "../chunk_workers.ts";
|
||||
import type { FaceGroup, FromChunkWorker, SectionLight } 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 { ALL_VISIBLE } from "../workers/visibility.ts";
|
||||
import { Camera } from "../camera.ts";
|
||||
import type { Entity } from "../entity/entity.ts";
|
||||
import type { ModelJson } from "@/common/block_models.ts";
|
||||
@@ -72,6 +73,12 @@ export interface RenderSection {
|
||||
translucent_sort?: TranslucentSort;
|
||||
// from its last mesh, see get_light. undefined until it's been meshed
|
||||
light?: SectionLight;
|
||||
// from its last mesh, which faces see which, see client/workers/visibility.ts. all of them until it's been meshed
|
||||
visibility: number;
|
||||
// the last search for what the camera can see that reached it, and the faces it was reached through, see
|
||||
// client/rendering/occlusion.ts
|
||||
search: number;
|
||||
incoming: number;
|
||||
}
|
||||
|
||||
export interface ChunkMesh {
|
||||
@@ -135,6 +142,8 @@ export class ClientLevel {
|
||||
#sorted = new Set<RenderSection>();
|
||||
// the sections with quads or visuals, the only ones there are to draw
|
||||
drawn = new Set<RenderSection>();
|
||||
// bumped whenever a chunk comes or goes or a section is meshed, which can change what the camera sees
|
||||
sections_version = 0;
|
||||
second_timer = 0;
|
||||
tick_timer = 0;
|
||||
// world time in ticks, counted here between the server's updates. see common/time.ts
|
||||
@@ -241,9 +250,20 @@ export class ClientLevel {
|
||||
} else {
|
||||
const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] };
|
||||
for (let index = 0; index < column.sections.length; index++) {
|
||||
chunk.sections.push({ chunk, index, mesh_version: 0, meshes: {}, min_y: Infinity, max_y: -Infinity });
|
||||
chunk.sections.push({
|
||||
chunk,
|
||||
index,
|
||||
mesh_version: 0,
|
||||
meshes: {},
|
||||
min_y: Infinity,
|
||||
max_y: -Infinity,
|
||||
visibility: ALL_VISIBLE,
|
||||
search: 0,
|
||||
incoming: 0,
|
||||
});
|
||||
}
|
||||
this.chunks.set(chunk_key(x, z), chunk);
|
||||
this.sections_version += 1;
|
||||
}
|
||||
// and its neighbors, whose border faces and light depend on it
|
||||
this.#mark_dirty_around(x, z, this.shape.min_y, this.shape.max_y);
|
||||
@@ -511,6 +531,7 @@ export class ClientLevel {
|
||||
}
|
||||
this.#dirty.delete(chunk);
|
||||
this.chunks.delete(key);
|
||||
this.sections_version += 1;
|
||||
this.block_data.delete(key);
|
||||
this.visuals.unload(cx, cz);
|
||||
for (const [position, { x, z }] of this.break_progress) {
|
||||
@@ -684,7 +705,9 @@ export class ClientLevel {
|
||||
continue;
|
||||
}
|
||||
this.#delete_mesh(section);
|
||||
this.sections_version += 1;
|
||||
section.light = mesh.light;
|
||||
section.visibility = mesh.visibility;
|
||||
section.min_y = mesh.min_y;
|
||||
section.max_y = mesh.max_y;
|
||||
// with no quads or visuals its bounds are empty
|
||||
|
||||
@@ -44,6 +44,8 @@ import { FACE_GROUPS, UNALIGNED_GROUP } from "@/client/workers/chunk_messages.ts
|
||||
import { FACE_AXIS, FACE_NORMALS } from "@/client/workers/translucent_sort.ts";
|
||||
import { Frustum } from "./frustum.ts";
|
||||
import { draw_visuals } from "./visuals.ts";
|
||||
import { reachable_sections } from "./occlusion.ts";
|
||||
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||
|
||||
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
|
||||
export class LevelRenderer {
|
||||
@@ -52,6 +54,9 @@ export class LevelRenderer {
|
||||
#visible: RenderSection[] = [];
|
||||
// the chunks they're in
|
||||
#visible_chunks = new Set<Chunk>();
|
||||
// what the camera could see the last time it was searched for, which only changes when it moves to another section
|
||||
// or the sections change, see occlusion.ts
|
||||
#reachable: { sections: RenderSection[] | undefined; level: ClientLevel; version: number; key: string } | undefined;
|
||||
// what to draw, switched off in the f3 performance window to see what each costs
|
||||
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
|
||||
|
||||
@@ -83,24 +88,39 @@ export class LevelRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
// asks for meshes and sorting, then works out which sections are in view, near to far
|
||||
// asks for meshes and sorting, then works out which sections are in view, near to far like sodium, so what's in
|
||||
// front fills the depth buffer first and the gpu can skip shading what's behind it
|
||||
#find_visible(level: ClientLevel, camera: Camera) {
|
||||
level.request_meshes(camera);
|
||||
level.update_translucent_sorting(camera);
|
||||
|
||||
this.frustum.update(view_projection());
|
||||
const visible: { section: RenderSection; distance: number }[] = [];
|
||||
this.#visible_chunks.clear();
|
||||
for (const section of level.drawn) {
|
||||
if (this.#in_view(section)) {
|
||||
visible.push({ section, distance: distance_sq(section, camera) });
|
||||
this.#visible_chunks.add(section.chunk);
|
||||
}
|
||||
const reachable = this.#reachable_sections(level, camera);
|
||||
if (reachable) {
|
||||
this.#visible = reachable.filter((section) => this.#in_view(section));
|
||||
} else {
|
||||
// the camera's chunk isn't loaded, so there's nothing to search from
|
||||
this.#visible = [...level.drawn].filter((section) => this.#in_view(section))
|
||||
.map((section) => ({ section, distance: distance_sq(section, camera) }))
|
||||
.sort((a, b) => a.distance - b.distance)
|
||||
.map(({ section }) => section);
|
||||
}
|
||||
// near to far, like sodium, so what's in front fills the depth buffer first and the gpu can skip shading what's
|
||||
// behind it
|
||||
visible.sort((a, b) => a.distance - b.distance);
|
||||
this.#visible = visible.map(({ section }) => section);
|
||||
for (const section of this.#visible) this.#visible_chunks.add(section.chunk);
|
||||
}
|
||||
|
||||
#reachable_sections(level: ClientLevel, camera: Camera) {
|
||||
const key = `${Math.floor(camera.x / CHUNK_SIZE)},${Math.floor(camera.y / SECTION_HEIGHT)},${
|
||||
Math.floor(camera.z / CHUNK_SIZE)
|
||||
}`;
|
||||
const last = this.#reachable;
|
||||
if (last?.level === level && last.version === level.sections_version && last.key === key) return last.sections;
|
||||
const sections = profiler.section(
|
||||
"occlusion",
|
||||
() => reachable_sections(level, camera.x, camera.y, camera.z),
|
||||
);
|
||||
this.#reachable = { sections, level, version: level.sections_version, key };
|
||||
return sections;
|
||||
}
|
||||
|
||||
// translucent terrain, drawn after entities so they show through water and glass. sections go back to front, and
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// occlusion culling, like sodium's OcclusionCuller but simpler: which sections the camera can see into, going out
|
||||
// from its own section a face at a time. a section is only left through faces that see the ones it was entered
|
||||
// through (see client/workers/visibility.ts), and never back towards the camera, so caves under the ground and the
|
||||
// inside of hills aren't drawn
|
||||
import { type Chunk, CHUNK_SIZE, type ClientLevel, type RenderSection } from "@/client/level/client_level.ts";
|
||||
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||
import { ALL_DIRECTIONS, exits } from "@/client/workers/visibility.ts";
|
||||
|
||||
// tells searches apart, so sections don't need clearing between them
|
||||
let searches = 0;
|
||||
|
||||
// the sections with something to draw the camera at x y z can see, near to far: in the order the search reaches them,
|
||||
// a step at a time. undefined when the camera's chunk isn't loaded
|
||||
export function reachable_sections(level: ClientLevel, x: number, y: number, z: number) {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const chunk = level.get_chunk(chunk_x, chunk_z);
|
||||
if (!chunk) return undefined;
|
||||
// above or below the world, from the section nearest to the camera
|
||||
const count = chunk.sections.length;
|
||||
const index = Math.min(count - 1, Math.max(0, Math.floor((y - level.shape.min_y) / SECTION_HEIGHT)));
|
||||
|
||||
// the loaded chunks in a grid, since looking each step's up in the level's map is most of what a search costs
|
||||
let min_x = chunk_x, max_x = chunk_x, min_z = chunk_z, max_z = chunk_z;
|
||||
for (const { x, z } of level.chunks.values()) {
|
||||
min_x = Math.min(min_x, x);
|
||||
max_x = Math.max(max_x, x);
|
||||
min_z = Math.min(min_z, z);
|
||||
max_z = Math.max(max_z, z);
|
||||
}
|
||||
const width = max_x - min_x + 1;
|
||||
const depth = max_z - min_z + 1;
|
||||
const grid: (Chunk | undefined)[] = new Array(width * depth);
|
||||
for (const chunk of level.chunks.values()) grid[(chunk.x - min_x) * depth + chunk.z - min_z] = chunk;
|
||||
const chunk_at = (x: number, z: number) =>
|
||||
x < min_x || x > max_x || z < min_z || z > max_z ? undefined : grid[(x - min_x) * depth + z - min_z];
|
||||
|
||||
const search = ++searches;
|
||||
const start = chunk.sections[index];
|
||||
start.search = search;
|
||||
const queue = [start];
|
||||
const found: RenderSection[] = [];
|
||||
// adds the section a step goes into, entered through the face opposite the step's direction
|
||||
const step = (neighbor: RenderSection | undefined, direction: number) => {
|
||||
if (!neighbor) return;
|
||||
// every step goes one further from the camera's section, so all the ways into a section are known by the time
|
||||
// it's taken from the queue
|
||||
if (neighbor.search !== search) {
|
||||
neighbor.search = search;
|
||||
neighbor.incoming = 0;
|
||||
queue.push(neighbor);
|
||||
}
|
||||
neighbor.incoming |= 1 << (direction ^ 1);
|
||||
};
|
||||
for (let i = 0; i < queue.length; i++) {
|
||||
const section = queue[i];
|
||||
// with no quads or visuals its bounds are empty, see ClientLevel.drawn
|
||||
if (section.min_y <= section.max_y) found.push(section);
|
||||
|
||||
// the camera's section can be left any way, even when the camera is inside a block
|
||||
let out = section === start ? ALL_DIRECTIONS : exits(section.visibility, section.incoming);
|
||||
if (!out) continue;
|
||||
// away from the camera's section on every axis
|
||||
const { x, z, sections } = section.chunk;
|
||||
const dx = x - chunk_x;
|
||||
const dy = section.index - index;
|
||||
const dz = z - chunk_z;
|
||||
out &= (dx <= 0 ? 1 : 0) | (dx >= 0 ? 2 : 0) | (dy <= 0 ? 4 : 0) | (dy >= 0 ? 8 : 0) | (dz <= 0 ? 16 : 0) |
|
||||
(dz >= 0 ? 32 : 0);
|
||||
if (out & 1) step(chunk_at(x - 1, z)?.sections[section.index], 0);
|
||||
if (out & 2) step(chunk_at(x + 1, z)?.sections[section.index], 1);
|
||||
if (out & 4) step(sections[section.index - 1], 2);
|
||||
if (out & 8) step(sections[section.index + 1], 3);
|
||||
if (out & 16) step(chunk_at(x, z - 1)?.sections[section.index], 4);
|
||||
if (out & 32) step(chunk_at(x, z + 1)?.sections[section.index], 5);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -109,6 +109,8 @@ export interface SectionMesh {
|
||||
};
|
||||
// entities are lit from it
|
||||
light: SectionLight;
|
||||
// which of its faces can be seen through from which others, see client/workers/visibility.ts
|
||||
visibility: number;
|
||||
// the blocks in it with visuals, as pairs of the block's index in the section (see section_index) and its value
|
||||
visuals: Uint32Array<ArrayBuffer>;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
REGION_VOID,
|
||||
} from "./lighting.ts";
|
||||
import { cell_index, fluid_quads, type FluidCell } from "./fluid_mesh.ts";
|
||||
import { ALL_VISIBLE, section_visibility } from "./visibility.ts";
|
||||
import { fluid_height, fluid_textures } from "@/common/everything_registry.ts";
|
||||
|
||||
type TexturesInfo = Record<string, SpriteRegion>;
|
||||
@@ -87,6 +88,8 @@ const block_layers = new Uint8Array(TABLE_SIZE);
|
||||
const block_cull_same = new Uint8Array(TABLE_SIZE);
|
||||
// darkens the corners it touches (minecraft's ambient occlusion), full cubes with collision do
|
||||
const block_occludes = new Uint8Array(TABLE_SIZE);
|
||||
// blocks nothing can be seen through, drawn as whole opaque cubes, see visibility.ts
|
||||
const block_hides_view = 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) };
|
||||
@@ -141,6 +144,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
block_visual.fill(0);
|
||||
for (const [nid, replaces_model] of message.visuals) {
|
||||
block_visual[nid] = replaces_model ? REPLACED_MODEL : HAS_VISUAL;
|
||||
if (replaces_model) block_hides_view[nid] = 0;
|
||||
}
|
||||
textures_info = message.textures_info;
|
||||
image = message.image as Texture;
|
||||
@@ -164,6 +168,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
version,
|
||||
...make_section_mesh(message.chunk_x, message.chunk_z, chunks, from, bottom, message.camera),
|
||||
light: section_light(from),
|
||||
visibility: visibility(chunks[4]![from >> 4], from),
|
||||
};
|
||||
});
|
||||
post(
|
||||
@@ -223,6 +228,25 @@ function section_light(from: number): SectionLight {
|
||||
return same ? packed_light[0] : packed_light.slice();
|
||||
}
|
||||
|
||||
const open_rows = new Uint16Array(256);
|
||||
|
||||
// which faces of the section see each other, see visibility.ts. from is its bottom in the region
|
||||
function visibility(section: Section, from: number) {
|
||||
if (!section.blocks) return block_hides_view[section.value & ID_MASK] ? 0 : ALL_VISIBLE;
|
||||
for (let y = 0; y < SECTION_HEIGHT; y++) {
|
||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||
// the middle chunk of the region
|
||||
const row = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
|
||||
let open = 0;
|
||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||
if (!block_hides_view[region.blocks[row + x]]) open |= 1 << x;
|
||||
}
|
||||
open_rows[y << 4 | z] = open;
|
||||
}
|
||||
}
|
||||
return section_visibility(open_rows);
|
||||
}
|
||||
|
||||
function post(message: FromChunkWorker, transfer: Transferable[]) {
|
||||
self.postMessage(message, transfer);
|
||||
}
|
||||
@@ -316,6 +340,7 @@ function build_block_tables() {
|
||||
block_layers[nid] = layer;
|
||||
block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0;
|
||||
block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT && is_full_cube(block) ? 1 : 0;
|
||||
block_hides_view[nid] = layer === SOLID && is_full_cube(block) ? 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);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// which faces of a section can be seen through from which others, for occlusion culling (see
|
||||
// client/rendering/occlusion.ts). worked out by the chunk workers as they mesh a section
|
||||
|
||||
// the 6 directions out of a section, and the faces they leave through, are a bit each: -x, +x, -y, +y, -z, +z. a
|
||||
// direction's opposite is direction ^ 1
|
||||
export const ALL_DIRECTIONS = 0b111111;
|
||||
|
||||
// a bit for each of the 15 pairs of different faces
|
||||
const PAIR_BITS = new Uint16Array(36);
|
||||
{
|
||||
let bit = 0;
|
||||
for (let a = 0; a < 6; a++) {
|
||||
for (let b = a + 1; b < 6; b++) {
|
||||
PAIR_BITS[a * 6 + b] = PAIR_BITS[b * 6 + a] = 1 << bit++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// every face sees every other, like a section of air, or one that hasn't been meshed yet
|
||||
export const ALL_VISIBLE = (1 << 15) - 1;
|
||||
|
||||
// the directions a section can be left in when it was entered through the faces in incoming
|
||||
export function exits(visibility: number, incoming: number) {
|
||||
// most sections are all air or all stone. entered through one face, all the others
|
||||
if (visibility === ALL_VISIBLE) return incoming & (incoming - 1) ? ALL_DIRECTIONS : ALL_DIRECTIONS & ~incoming;
|
||||
if (visibility === 0) return 0;
|
||||
let out = 0;
|
||||
for (let a = 0; a < 6; a++) {
|
||||
if (!(incoming & (1 << a))) continue;
|
||||
for (let b = 0; b < 6; b++) {
|
||||
if (visibility & PAIR_BITS[a * 6 + b]) out |= 1 << b;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const unvisited = new Uint16Array(256);
|
||||
const region = new Uint16Array(256);
|
||||
|
||||
// a section's visibility from the cells that can be seen through, by row (y << 4 | z, a bit per x). each connected
|
||||
// region of them connects every pair of faces it touches. a region grows a row at a time, each row filled along its
|
||||
// open runs at once, until it stops growing
|
||||
export function section_visibility(open: Uint16Array) {
|
||||
let count = 0;
|
||||
for (let r = 0; r < 256; r++) count += bit_count(open[r]);
|
||||
if (count === 4096) return ALL_VISIBLE;
|
||||
if (count === 0) return 0;
|
||||
|
||||
unvisited.set(open);
|
||||
let result = 0;
|
||||
for (let start = 0; start < 256; start++) {
|
||||
while (unvisited[start] !== 0) {
|
||||
const seed = unvisited[start] & -unvisited[start];
|
||||
region[start] = fill_row(seed, unvisited[start]);
|
||||
let lo = start;
|
||||
let hi = start;
|
||||
let grown = true;
|
||||
while (grown) {
|
||||
grown = false;
|
||||
const first = Math.max(0, lo - 16);
|
||||
const last = Math.min(255, hi + 16);
|
||||
// up then back down, so a region that winds back reaches its far end in fewer sweeps
|
||||
for (let i = 0; i < 2 * (last - first + 1); i++) {
|
||||
const r = i <= last - first ? first + i : last - (i - (last - first + 1));
|
||||
let near = region[r];
|
||||
if (r >= 16) near |= region[r - 16];
|
||||
if (r < 240) near |= region[r + 16];
|
||||
if (r & 15) near |= region[r - 1];
|
||||
if ((r & 15) !== 15) near |= region[r + 1];
|
||||
const reached = near & unvisited[r];
|
||||
if (reached & ~region[r]) {
|
||||
region[r] = fill_row(reached, unvisited[r]);
|
||||
if (r < lo) lo = r;
|
||||
if (r > hi) hi = r;
|
||||
grown = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let faces = 0;
|
||||
for (let r = lo; r <= hi; r++) {
|
||||
const row = region[r];
|
||||
if (row === 0) continue;
|
||||
region[r] = 0;
|
||||
unvisited[r] &= ~row;
|
||||
const y = r >> 4;
|
||||
const z = r & 15;
|
||||
if (row & 1) faces |= 1;
|
||||
if (row & 0x8000) faces |= 2;
|
||||
if (y === 0) faces |= 4;
|
||||
if (y === 15) faces |= 8;
|
||||
if (z === 0) faces |= 16;
|
||||
if (z === 15) faces |= 32;
|
||||
}
|
||||
// one region touching every face connects them all, nothing else can add to it
|
||||
if (faces === ALL_DIRECTIONS) return ALL_VISIBLE;
|
||||
for (let a = 0; a < 6; a++) {
|
||||
for (let b = a + 1; b < 6; b++) {
|
||||
if (faces & (1 << a) && faces & (1 << b)) result |= PAIR_BITS[a * 6 + b];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// the cells of open connected to seeds within a row, filling each way and doubling the reach at each step
|
||||
function fill_row(seeds: number, open: number) {
|
||||
let up = seeds;
|
||||
let through_up = open;
|
||||
let down = seeds;
|
||||
let through_down = open;
|
||||
for (let step = 1; step <= 8; step <<= 1) {
|
||||
up |= through_up & (up << step);
|
||||
through_up &= through_up << step;
|
||||
down |= through_down & (down >> step);
|
||||
through_down &= through_down >> step;
|
||||
}
|
||||
return up | down;
|
||||
}
|
||||
|
||||
function bit_count(row: number) {
|
||||
let count = 0;
|
||||
for (; row; row &= row - 1) count++;
|
||||
return count;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// occlusion culling: the chunk workers work out which faces of a section see each other (client/workers/visibility.ts)
|
||||
// and the renderer only draws the sections the camera can see into through them (client/rendering/occlusion.ts)
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { ALL_VISIBLE, exits, section_visibility } from "@/client/workers/visibility.ts";
|
||||
import { reachable_sections } from "@/client/rendering/occlusion.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { ChunkColumn } from "@/common/section.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
|
||||
import { client_level } from "./client_level.ts";
|
||||
|
||||
// the faces a section can be left through from each face, as [-x, +x, -y, +y, -z, +z] masks
|
||||
const exits_by_face = (visibility: number) => Array.from({ length: 6 }, (_, face) => exits(visibility, 1 << face));
|
||||
|
||||
// the same, found by flood filling the open cells one at a time
|
||||
function flood_filled(open: (x: number, y: number, z: number) => boolean) {
|
||||
const seen = new Uint8Array(4096);
|
||||
const result = new Array(6).fill(0);
|
||||
for (let start = 0; start < 4096; start++) {
|
||||
if (seen[start] || !open(start & 15, start >> 8, (start >> 4) & 15)) continue;
|
||||
seen[start] = 1;
|
||||
const stack = [start];
|
||||
let faces = 0;
|
||||
while (stack.length) {
|
||||
const cell = stack.pop()!;
|
||||
const [x, y, z] = [cell & 15, cell >> 8, (cell >> 4) & 15];
|
||||
faces |= (x === 0 ? 1 : 0) | (x === 15 ? 2 : 0) | (y === 0 ? 4 : 0) | (y === 15 ? 8 : 0) |
|
||||
(z === 0 ? 16 : 0) | (z === 15 ? 32 : 0);
|
||||
for (
|
||||
const [nx, ny, nz] of [[x - 1, y, z], [x + 1, y, z], [x, y - 1, z], [x, y + 1, z], [x, y, z - 1], [
|
||||
x,
|
||||
y,
|
||||
z + 1,
|
||||
]]
|
||||
) {
|
||||
if (Math.min(nx, ny, nz) < 0 || Math.max(nx, ny, nz) > 15) continue;
|
||||
const next = ny << 8 | nz << 4 | nx;
|
||||
if (!seen[next] && open(nx, ny, nz)) {
|
||||
seen[next] = 1;
|
||||
stack.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let a = 0; a < 6; a++) {
|
||||
if (faces & (1 << a)) result[a] |= faces & ~(1 << a);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function rows(open: (x: number, y: number, z: number) => boolean) {
|
||||
const rows = new Uint16Array(256);
|
||||
for (let y = 0; y < 16; y++) {
|
||||
for (let z = 0; z < 16; z++) {
|
||||
for (let x = 0; x < 16; x++) if (open(x, y, z)) rows[y << 4 | z] |= 1 << x;
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
Deno.test("a section's faces see each other through the cells that can be seen through", () => {
|
||||
assertEquals(section_visibility(rows(() => true)), ALL_VISIBLE);
|
||||
assertEquals(section_visibility(rows(() => false)), 0);
|
||||
// a wall across x: -x and +x don't see each other, the other faces see both halves
|
||||
assertEquals(exits_by_face(section_visibility(rows((x) => x !== 8))), [
|
||||
0b111100,
|
||||
0b111100,
|
||||
0b111011,
|
||||
0b110111,
|
||||
0b101111,
|
||||
0b011111,
|
||||
]);
|
||||
// a tunnel along z, and nothing else
|
||||
assertEquals(exits_by_face(section_visibility(rows((x, y) => x === 3 && y === 3))), [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0b100000,
|
||||
0b010000,
|
||||
]);
|
||||
|
||||
// random sections, from mostly open to mostly closed, and some with winding walls
|
||||
let seed = 12345;
|
||||
const random = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
|
||||
for (let i = 0; i < 300; i++) {
|
||||
const density = 0.2 + (i % 7) * 0.1;
|
||||
const cells = Array.from({ length: 4096 }, () => random() < density);
|
||||
const open = i % 3 === 0
|
||||
? (x: number, y: number, z: number) => (x * 7 + y * 3 + z * 5) % 11 !== 0 || cells[y << 8 | z << 4 | x]
|
||||
: (x: number, y: number, z: number) => cells[y << 8 | z << 4 | x];
|
||||
assertEquals(exits_by_face(section_visibility(rows(open))), flood_filled(open), `section ${i}`);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("solid full blocks hide what's behind them in a meshed section, and others don't", async () => {
|
||||
await test_game("mods");
|
||||
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
||||
const nid = (id: string) => blocks.findIndex((b) => b?.id === id);
|
||||
const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
|
||||
// stone up to 63, a stone floor across section 6 at y 100, and section 8 full of water
|
||||
const ground = () => {
|
||||
const blocks = new Uint32Array(DEFAULT_SHAPE.volume).fill(nid("bworld:stone"), 0, at(0, 64, 0));
|
||||
blocks.fill(nid("bworld:stone"), at(0, 100, 0), at(0, 101, 0));
|
||||
blocks.fill(nid("bworld:water"), at(0, 128, 0), at(0, 144, 0));
|
||||
return blocks;
|
||||
};
|
||||
const chunks = Array.from({ length: 9 }, ground);
|
||||
const worker = chunk_worker(DEFAULT_SHAPE);
|
||||
const { sections } = await mesh_column(worker, DEFAULT_SHAPE, chunks);
|
||||
worker.terminate();
|
||||
assertEquals(sections[2].visibility, 0);
|
||||
assertEquals(sections[5].visibility, ALL_VISIBLE);
|
||||
assertEquals(sections[8].visibility, ALL_VISIBLE);
|
||||
// the floor splits its section in two, which each see the sides but not each other
|
||||
assertEquals(exits(sections[6].visibility, 0b0100), 0b110011);
|
||||
assertEquals(exits(sections[6].visibility, 0b1000), 0b110011);
|
||||
});
|
||||
|
||||
// a level of 7x7 chunks of ground up to section 3 with open air above it, none of it meshed, and every section with
|
||||
// something to draw. the visibility a mesh gives is set by hand: none for the ground, every face for the air
|
||||
async function level_with_ground() {
|
||||
await test_game("mods");
|
||||
const { level } = client_level(DEFAULT_SHAPE);
|
||||
for (let x = -3; x <= 3; x++) {
|
||||
for (let z = -3; z <= 3; z++) {
|
||||
const air = new Uint32Array(DEFAULT_SHAPE.volume);
|
||||
level.set_chunk(
|
||||
ChunkColumn.from_flat(x, z, DEFAULT_SHAPE, air, new Array(CHUNK_AREA).fill("bworld:plains")),
|
||||
);
|
||||
for (const section of level.get_chunk(x, z)!.sections) {
|
||||
section.visibility = section.index <= 3 ? 0 : ALL_VISIBLE;
|
||||
section.min_y = DEFAULT_SHAPE.min_y + section.index * 16;
|
||||
section.max_y = section.min_y + 16;
|
||||
level.drawn.add(section);
|
||||
}
|
||||
}
|
||||
}
|
||||
const reached = (x: number, y: number, z: number) =>
|
||||
new Set(
|
||||
reachable_sections(level, x, y, z)!.map((section) =>
|
||||
`${section.chunk.x},${section.index},${section.chunk.z}`
|
||||
),
|
||||
);
|
||||
return { level, reached };
|
||||
}
|
||||
|
||||
Deno.test("from above the ground, the camera sees the ground's top and not what's under it", async () => {
|
||||
const { level, reached } = await level_with_ground();
|
||||
// a cave in section 1 of chunk 0, 0, open on every face but closed in by the ground around it
|
||||
level.get_chunk(0, 0)!.sections[1].visibility = ALL_VISIBLE;
|
||||
const seen = reached(8, 100, 8);
|
||||
assert(seen.has("3,3,-3") && seen.has("0,3,0") && seen.has("-2,15,1"), "the ground's top and the sky");
|
||||
assert(!seen.has("0,2,0") && !seen.has("0,1,0") && !seen.has("2,2,2"), "under the ground");
|
||||
|
||||
// and from inside the cave, only it and what closes it in
|
||||
const in_cave = reached(8, 24, 8);
|
||||
assertEquals(
|
||||
[...in_cave].sort(),
|
||||
["-1,1,0", "0,0,0", "0,1,-1", "0,1,0", "0,1,1", "0,2,0", "1,1,0"],
|
||||
);
|
||||
level.dispose();
|
||||
});
|
||||
|
||||
Deno.test("the camera doesn't see back around what's in front of it", async () => {
|
||||
const { level, reached } = await level_with_ground();
|
||||
// a wall on the ground two chunks to +x, across the whole level and up to section 8
|
||||
for (let z = -3; z <= 3; z++) {
|
||||
for (const section of level.get_chunk(2, z)!.sections) {
|
||||
if (section.index <= 8) section.visibility = 0;
|
||||
}
|
||||
}
|
||||
const seen = reached(8, 70, 8);
|
||||
assert(seen.has("2,4,0"), "the wall");
|
||||
assert(!seen.has("3,4,0"), "right behind the wall");
|
||||
assert(seen.has("3,9,0"), "above it");
|
||||
level.dispose();
|
||||
});
|
||||
Reference in New Issue
Block a user