World shape for dimension
This commit is contained in:
@@ -6,7 +6,8 @@
|
||||
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
|
||||
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
|
||||
import { Alea } from "@paulaboks/rng";
|
||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { DEFAULT_MODEL } from "@/common/block_models.ts";
|
||||
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "@/common/worldgen/noise.ts";
|
||||
@@ -19,6 +20,9 @@ const SEED = "benchmark";
|
||||
// can be meshed, see ClientLevel.can_mesh
|
||||
export const LEVEL_RADIUS = 13;
|
||||
export const SEA_LEVEL = 62;
|
||||
// 0 to 256 with sky light whatever the world's dimension is, so runs compare. y in its chunks counts from 0
|
||||
export const LEVEL_SHAPE = DEFAULT_SHAPE;
|
||||
const TOP = LEVEL_SHAPE.max_y;
|
||||
|
||||
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
|
||||
export const ZONES = {
|
||||
@@ -143,12 +147,12 @@ export class BenchTerrain {
|
||||
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
|
||||
height = zone.height + (height - zone.height) * t;
|
||||
}
|
||||
return Math.min(CHUNK_HEIGHT - 32, Math.round(height));
|
||||
return Math.min(TOP - 32, Math.round(height));
|
||||
}
|
||||
|
||||
chunk(chunk_x: number, chunk_z: number): { blocks: Uint32Array; biomes: string[] } {
|
||||
const b = this.#blocks;
|
||||
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
|
||||
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
|
||||
const x0 = chunk_x * CHUNK_SIZE;
|
||||
const z0 = chunk_z * CHUNK_SIZE;
|
||||
@@ -156,7 +160,7 @@ export class BenchTerrain {
|
||||
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
|
||||
const lx = x - x0;
|
||||
const lz = z - z0;
|
||||
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= CHUNK_HEIGHT) return;
|
||||
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= TOP) return;
|
||||
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
||||
if (!only_air || blocks[index] === AIR) blocks[index] = value;
|
||||
};
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
type BenchBlocks,
|
||||
BenchTerrain,
|
||||
LEVEL_RADIUS,
|
||||
LEVEL_SHAPE,
|
||||
SEA_LEVEL,
|
||||
UPDATE_WALL,
|
||||
ZONES,
|
||||
@@ -145,7 +146,7 @@ export class RenderBenchmark {
|
||||
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
|
||||
);
|
||||
|
||||
this.#level = new ClientLevel([], LEVEL_RADIUS);
|
||||
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
|
||||
this.#level.time = TIMES_OF_DAY.noon;
|
||||
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
|
||||
this.#system = system_info(this.#level.workers.size);
|
||||
|
||||
+1
-1
@@ -77,7 +77,7 @@ export class Client {
|
||||
this.connection = connection;
|
||||
this.#on_disconnect = on_disconnect;
|
||||
|
||||
this.level = new ClientLevel(connection.server_blocks, this.options.render_distance);
|
||||
this.level = new ClientLevel(connection.server_blocks, connection.shape, this.options.render_distance);
|
||||
this.level.time = connection.time;
|
||||
this.#sent_view_distance = this.options.render_distance;
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ import {
|
||||
RENDER_LAYERS,
|
||||
RenderLayer,
|
||||
} from "@/common/everything_registry.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
|
||||
import type { WorldShape } from "@/common/world_shape.ts";
|
||||
import { AssetManager } from "../assets.ts";
|
||||
import { ChunkWorkerPool } from "../chunk_workers.ts";
|
||||
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
|
||||
@@ -41,11 +42,12 @@ export interface Block {
|
||||
z: number;
|
||||
}
|
||||
|
||||
export { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE };
|
||||
export { CHUNK_AREA, CHUNK_SIZE };
|
||||
|
||||
export interface Chunk {
|
||||
x: number;
|
||||
z: number;
|
||||
// the dimension's whole height, y from its min_y then z then x
|
||||
blocks: Uint32Array;
|
||||
dirty: boolean;
|
||||
// bumped on every mesh request so late results from older requests get ignored
|
||||
@@ -112,8 +114,6 @@ const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [
|
||||
// how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client
|
||||
// which ones to forget, this only catches the ones it didn't
|
||||
const STORAGE_MARGIN = 3;
|
||||
// block light 0 and sky light 15, packed like Chunk.light
|
||||
export const FULL_SKY_LIGHT = 15;
|
||||
|
||||
// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the
|
||||
// chunks are what the server sent, see common/chunk_streaming.ts
|
||||
@@ -131,6 +131,8 @@ export class ClientLevel {
|
||||
ticks = 0;
|
||||
// in chunks, what the server was asked to send
|
||||
view_distance: number;
|
||||
// the dimension's height and sky light
|
||||
readonly shape: WorldShape;
|
||||
// the chunk the server says the player is in
|
||||
center: { x: number; z: number } | undefined;
|
||||
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
|
||||
@@ -151,8 +153,9 @@ export class ClientLevel {
|
||||
break_progress = new Map<string, { x: number; y: number; z: number; stage: number }>();
|
||||
|
||||
// server_blocks is the server's block id for each of its numeric ids
|
||||
constructor(server_blocks: string[], view_distance: number) {
|
||||
constructor(server_blocks: string[], shape: WorldShape, view_distance: number) {
|
||||
this.view_distance = view_distance;
|
||||
this.shape = shape;
|
||||
this.#to_local = new Uint32Array(server_blocks.length);
|
||||
server_blocks.forEach((id, nid) => {
|
||||
if (!id) return;
|
||||
@@ -173,6 +176,7 @@ export class ClientLevel {
|
||||
textures_info: AssetManager.instance.get("cubi:textures_info"),
|
||||
image: { width: this.image.width, height: this.image.height },
|
||||
visuals: [...block_visuals].map(([nid, visual]) => [nid, visual.replaces_model]),
|
||||
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -202,6 +206,9 @@ export class ClientLevel {
|
||||
if (!this.#in_storage_range(x, z)) {
|
||||
return;
|
||||
}
|
||||
if (blocks.length !== this.shape.volume) {
|
||||
throw new Error(`Chunk ${x}, ${z} isn't as tall as the dimension`);
|
||||
}
|
||||
this.set_chunk(x, z, blocks, biomes);
|
||||
}
|
||||
|
||||
@@ -286,14 +293,16 @@ export class ClientLevel {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.shape.contains(block.y)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
|
||||
this.#retain(block.x, block.y, block.z);
|
||||
|
||||
const lx = block.x - block_chunk_x * CHUNK_SIZE;
|
||||
const lz = block.z - block_chunk_z * CHUNK_SIZE;
|
||||
const ly = block.y;
|
||||
|
||||
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
|
||||
const index = this.#index(block.x, block.y, block.z, block_chunk_x, block_chunk_z);
|
||||
|
||||
const old_nid = chunk.blocks[index] & ID_MASK;
|
||||
chunk.blocks[index] = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
|
||||
@@ -301,19 +310,18 @@ export class ClientLevel {
|
||||
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
|
||||
}
|
||||
|
||||
// block light << 4 | sky light there, as of its chunk's last mesh. full sky light above the world and where it isn't
|
||||
// known yet, so entities don't go dark while their chunk loads
|
||||
// block light << 4 | sky light there, as of its chunk's last mesh. the shape's open light (full sky light, unless
|
||||
// the dimension has none) above the world and where it isn't known yet, so entities don't go dark while their
|
||||
// chunk loads
|
||||
get_light(x: number, y: number, z: number): number {
|
||||
const block_y = Math.floor(y);
|
||||
if (block_y >= CHUNK_HEIGHT) return FULL_SKY_LIGHT;
|
||||
if (block_y < 0) return 0;
|
||||
if (block_y >= this.shape.max_y) return this.shape.open_light;
|
||||
if (block_y < this.shape.min_y) return 0;
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const light = this.get_chunk(chunk_x, chunk_z)?.light;
|
||||
if (!light) return FULL_SKY_LIGHT;
|
||||
const lx = Math.floor(x) - chunk_x * CHUNK_SIZE;
|
||||
const lz = Math.floor(z) - chunk_z * CHUNK_SIZE;
|
||||
return light[block_y * CHUNK_AREA + lz * CHUNK_SIZE + lx];
|
||||
if (!light) return this.shape.open_light;
|
||||
return light[this.#index(Math.floor(x), block_y, Math.floor(z), chunk_x, chunk_z)];
|
||||
}
|
||||
|
||||
// the id with its state bits, VOID outside loaded chunks
|
||||
@@ -324,8 +332,7 @@ export class ClientLevel {
|
||||
if (!chunk) {
|
||||
return VOID;
|
||||
}
|
||||
return chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)] ??
|
||||
AIR;
|
||||
return this.shape.contains(y) ? chunk.blocks[this.#index(x, y, z, chunk_x, chunk_z)] : AIR;
|
||||
}
|
||||
|
||||
get_block(x: number, y: number, z: number) {
|
||||
@@ -337,14 +344,13 @@ export class ClientLevel {
|
||||
if (!chunk) {
|
||||
return VOID;
|
||||
}
|
||||
return this.shape.contains(y) ? chunk.blocks[this.#index(x, y, z, chunk_x, chunk_z)] & ID_MASK : AIR;
|
||||
}
|
||||
|
||||
const lx = x - chunk_x * CHUNK_SIZE;
|
||||
const lz = z - chunk_z * CHUNK_SIZE;
|
||||
const ly = y;
|
||||
|
||||
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
|
||||
|
||||
return chunk.blocks[index] & ID_MASK;
|
||||
// a block's place in its chunk's blocks and light. y has to be in the shape
|
||||
#index(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
|
||||
return (y - this.shape.min_y) * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE +
|
||||
(x - chunk_x * CHUNK_SIZE);
|
||||
}
|
||||
|
||||
// whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world
|
||||
@@ -400,7 +406,7 @@ export class ClientLevel {
|
||||
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const block_chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
|
||||
if (!chunk) {
|
||||
if (!chunk || !this.shape.contains(y)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -408,9 +414,7 @@ export class ClientLevel {
|
||||
|
||||
const lx = x - block_chunk_x * CHUNK_SIZE;
|
||||
const lz = z - block_chunk_z * CHUNK_SIZE;
|
||||
const ly = y;
|
||||
|
||||
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
|
||||
const index = this.#index(x, y, z, block_chunk_x, block_chunk_z);
|
||||
const old_value = chunk.blocks[index];
|
||||
const old_nid = old_value & ID_MASK;
|
||||
const old_block = this.#blocks[old_nid];
|
||||
@@ -472,16 +476,6 @@ export class ClientLevel {
|
||||
}
|
||||
}
|
||||
|
||||
index_to_xyz(index: number) {
|
||||
const y = Math.floor(index / CHUNK_AREA);
|
||||
const rem = index % CHUNK_AREA;
|
||||
|
||||
const z = Math.floor(rem / CHUNK_SIZE);
|
||||
const x = rem % CHUNK_SIZE;
|
||||
|
||||
return [x, y, z];
|
||||
}
|
||||
|
||||
// set a block the server told us about. the server only sends them for chunks this client has. a block this
|
||||
// client guessed waits for the server's ack instead, see BlockPredictions
|
||||
apply_change(x: number, y: number, z: number, id: string, state = 0) {
|
||||
@@ -691,7 +685,7 @@ export class ClientLevel {
|
||||
chunk.light = message.light;
|
||||
chunk.min_y = message.min_y;
|
||||
chunk.max_y = message.max_y;
|
||||
this.visuals.meshed(chunk.x, chunk.z, message.visuals);
|
||||
this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y, message.visuals);
|
||||
|
||||
for (const layer of RENDER_LAYERS) {
|
||||
const { vertices, quad_count, groups } = message[layer];
|
||||
|
||||
@@ -360,6 +360,12 @@ function client_context(listing: ModListing): ClientContext {
|
||||
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
|
||||
biome_at: (x, z) => rules_world.biome_at(x, z),
|
||||
season_at: (x, z) => rules_world.season_at(x, z),
|
||||
get min_y() {
|
||||
return need_client().level.shape.min_y;
|
||||
},
|
||||
get max_y() {
|
||||
return need_client().level.shape.max_y;
|
||||
},
|
||||
get time() {
|
||||
return need_client().level.time;
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "@/common/protocol.ts";
|
||||
import type { ModListing } from "@/common/mod_loader.ts";
|
||||
import { WorldShape } from "@/common/world_shape.ts";
|
||||
import type { Join, ServerSocket, Welcome } from "./handshake.ts";
|
||||
|
||||
export class Connection {
|
||||
@@ -12,6 +13,8 @@ export class Connection {
|
||||
mods: ModListing[];
|
||||
// the server's block id for each of its numeric ids, for reading chunks
|
||||
server_blocks: string[];
|
||||
// the dimension's height and sky light
|
||||
shape: WorldShape;
|
||||
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
|
||||
selected_slot: number;
|
||||
// the slots mods added to menu 0
|
||||
@@ -27,6 +30,7 @@ export class Connection {
|
||||
this.name = join.name;
|
||||
this.mods = welcome.mods;
|
||||
this.server_blocks = join.blocks;
|
||||
this.shape = new WorldShape(join.shape);
|
||||
this.spawn = join.spawn;
|
||||
this.selected_slot = join.selected_slot;
|
||||
this.player_menu = join.player_menu;
|
||||
|
||||
@@ -186,7 +186,7 @@ interface Entry {
|
||||
|
||||
// a level's visuals
|
||||
export class Visuals {
|
||||
// by chunk_key, then the block's index in its chunk
|
||||
// by chunk_key, then the block's index in its chunk counted from y 0, see #entry
|
||||
#chunks = new Map<number, Map<number, Entry>>();
|
||||
#level: VisualsLevel;
|
||||
// baked once per level, since a level's mods don't change
|
||||
@@ -213,15 +213,16 @@ export class Visuals {
|
||||
yield* this.#fluid_groups;
|
||||
}
|
||||
|
||||
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals
|
||||
// for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones
|
||||
// that stay take it
|
||||
meshed(chunk_x: number, chunk_z: number, found: Uint32Array) {
|
||||
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk (from min_y, the
|
||||
// bottom of the world) and its value. visuals for blocks that are gone or changed go, and new ones are made. the
|
||||
// chunk's light came with its mesh, so the ones that stay take it
|
||||
meshed(chunk_x: number, chunk_z: number, min_y: number, found: Uint32Array) {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
const old = this.#chunks.get(key) ?? new Map<number, Entry>();
|
||||
const kept = new Map<number, Entry>();
|
||||
for (let i = 0; i < found.length; i += 2) {
|
||||
const index = found[i];
|
||||
const local = found[i];
|
||||
const index = local + min_y * CHUNK_AREA;
|
||||
const value = found[i + 1];
|
||||
const entry = old.get(index);
|
||||
old.delete(index);
|
||||
@@ -231,9 +232,9 @@ export class Visuals {
|
||||
continue;
|
||||
}
|
||||
if (entry) this.#delete(entry);
|
||||
const x = chunk_x * CHUNK_SIZE + (index % CHUNK_SIZE);
|
||||
const z = chunk_z * CHUNK_SIZE + Math.floor(index / CHUNK_SIZE) % CHUNK_SIZE;
|
||||
const made = this.#create(x, Math.floor(index / CHUNK_AREA), z, value);
|
||||
const x = chunk_x * CHUNK_SIZE + (local % CHUNK_SIZE);
|
||||
const z = chunk_z * CHUNK_SIZE + Math.floor(local / CHUNK_SIZE) % CHUNK_SIZE;
|
||||
const made = this.#create(x, min_y + Math.floor(local / CHUNK_AREA), z, value);
|
||||
if (made) kept.set(index, made);
|
||||
}
|
||||
for (const entry of old.values()) this.#delete(entry);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { BlockRegistry } from "@/common/everything_registry.ts";
|
||||
import type { SpriteRegion } from "@/common/constants.ts";
|
||||
import type { ModelJson } from "@/common/block_models.ts";
|
||||
import type { WorldShapeJson } from "@/common/world_shape.ts";
|
||||
import type { SortType } from "./translucent_sort.ts";
|
||||
|
||||
// messages between the main thread and the chunk workers
|
||||
@@ -38,6 +39,8 @@ export type ToChunkWorker =
|
||||
// the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
|
||||
// ctx.render.register_visual
|
||||
visuals: [number, boolean][];
|
||||
// the dimension's height and sky light. the chunks meshed hold all of its height
|
||||
shape: WorldShapeJson;
|
||||
}
|
||||
| {
|
||||
type: "mesh";
|
||||
@@ -75,7 +78,7 @@ export type FromChunkWorker =
|
||||
chunk_x: number;
|
||||
chunk_z: number;
|
||||
version: number;
|
||||
// the lowest and highest y of the chunk's quads, for frustum culling
|
||||
// the lowest and highest y of the chunk's quads in the world, for frustum culling
|
||||
min_y: number;
|
||||
max_y: number;
|
||||
solid: LayerMesh;
|
||||
@@ -89,7 +92,7 @@ export type FromChunkWorker =
|
||||
planes: [Float32Array, Float32Array, Float32Array];
|
||||
};
|
||||
camera: number[];
|
||||
// the chunk's light, one byte per block indexed like its blocks: block light << 4 | sky light, like sodium's
|
||||
// the chunk's light, one byte per block indexed like its blocks (from the bottom of the world): block light << 4 | sky light, like sodium's
|
||||
// packed light data. entities are lit from it
|
||||
light: Uint8Array<ArrayBuffer>;
|
||||
// the blocks in it with visuals, as pairs of the block's index in the chunk (like light's) and its value
|
||||
|
||||
@@ -9,15 +9,7 @@ import {
|
||||
type BlockRegistry,
|
||||
type RenderLayer,
|
||||
} from "@/common/everything_registry.ts";
|
||||
import {
|
||||
AIR,
|
||||
CHUNK_AREA,
|
||||
CHUNK_HEIGHT,
|
||||
CHUNK_SIZE,
|
||||
ID_MASK,
|
||||
type SpriteRegion,
|
||||
TEXTURE_SIZE,
|
||||
} from "@/common/constants.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK, type SpriteRegion, TEXTURE_SIZE } from "@/common/constants.ts";
|
||||
import type { Texture } from "../renderer/types.ts";
|
||||
import {
|
||||
FACE_GROUPS,
|
||||
@@ -104,7 +96,11 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE);
|
||||
const block_visual = new Uint8Array(TABLE_SIZE);
|
||||
const HAS_VISUAL = 1;
|
||||
const REPLACED_MODEL = 2;
|
||||
const region = new LightRegion();
|
||||
// the 3x3 chunks being meshed, made for the dimension's height by "init". its y, like the mesher's, counts from the
|
||||
// bottom of the world
|
||||
let region: LightRegion;
|
||||
// the dimension's min_y, which quads are moved up by to be where they are in the world
|
||||
let world_min_y = 0;
|
||||
|
||||
// a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's
|
||||
// four corner lights it gets, so faces smaller than the block are lit like minecraft's
|
||||
@@ -145,6 +141,8 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
}
|
||||
textures_info = message.textures_info;
|
||||
image = message.image as Texture;
|
||||
region = new LightRegion(message.shape);
|
||||
world_min_y = message.shape.min_y;
|
||||
break;
|
||||
case "mesh": {
|
||||
region.fill(message.chunks);
|
||||
@@ -203,8 +201,8 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
|
||||
// the middle chunk of the light region, packed for the main thread, see "meshed"
|
||||
function chunk_light() {
|
||||
const light = new Uint8Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
||||
const light = new Uint8Array(CHUNK_AREA * region.height);
|
||||
for (let y = 0; y < region.height; y++) {
|
||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||
const from = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
|
||||
const to = y * CHUNK_AREA + z * CHUNK_SIZE;
|
||||
@@ -546,7 +544,7 @@ function hides_fluid(nid: number) {
|
||||
// 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;
|
||||
if (y < 0 || y >= region.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)];
|
||||
@@ -663,6 +661,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
// 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 wy = world_min_y + y;
|
||||
const wz = chunk_z * CHUNK_SIZE + z;
|
||||
const tint = quad.tint === GRASS
|
||||
? blended[z * CHUNK_SIZE + x]
|
||||
@@ -674,28 +673,28 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
|
||||
if (layer_id !== TRANSLUCENT) {
|
||||
const group = opaque[layer_id][quad.group];
|
||||
push_quad(group.buffer, quad, wx, y, wz, alpha, tint);
|
||||
push_quad(group.buffer, quad, wx, wy, 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];
|
||||
const plane = (axis === 0 ? wx : axis === 1 ? wy : 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);
|
||||
push_quad(translucent_quads, quad, wx, wy, 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 + 1] = wy + (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 y = 0; y < region.height; y++) {
|
||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||
// the middle chunk of the region
|
||||
@@ -743,8 +742,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
if (block_visual[block_nid]) {
|
||||
visuals.push(y * CHUNK_AREA + z * CHUNK_SIZE + x, value);
|
||||
// with the block above and below, since a visual can reach past its block, like a large cog
|
||||
if (y - 1 < mesh_min_y) mesh_min_y = y - 1;
|
||||
if (y + 2 > mesh_max_y) mesh_max_y = y + 2;
|
||||
if (world_min_y + y - 1 < mesh_min_y) mesh_min_y = world_min_y + y - 1;
|
||||
if (world_min_y + y + 2 > mesh_max_y) mesh_max_y = world_min_y + y + 2;
|
||||
if (block_visual[block_nid] === REPLACED_MODEL) continue;
|
||||
}
|
||||
|
||||
|
||||
+31
-14
@@ -9,12 +9,15 @@
|
||||
// minecraft stores light and updates it as blocks change. here it's worked out from scratch for the
|
||||
// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15
|
||||
// blocks, so nothing outside those chunks can light the middle one or its border
|
||||
//
|
||||
// y in a region counts from the bottom of the world, 0 is the dimension's min_y. in a dimension without sky light
|
||||
// there's only block light
|
||||
|
||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import type { WorldShapeJson } from "@/common/world_shape.ts";
|
||||
|
||||
export const REGION_SIZE = CHUNK_SIZE * 3;
|
||||
export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
|
||||
export const REGION_VOLUME = REGION_LAYER * CHUNK_HEIGHT;
|
||||
// what unloaded chunks and the space below the world are made of: opaque, dark, never shown
|
||||
export const REGION_VOID = ID_MASK;
|
||||
|
||||
@@ -25,22 +28,34 @@ export interface LightTables {
|
||||
}
|
||||
|
||||
export class LightRegion {
|
||||
// the dimension's, in blocks
|
||||
readonly height: number;
|
||||
readonly sky_light: boolean;
|
||||
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
|
||||
blocks = new Uint16Array(REGION_VOLUME);
|
||||
sky = new Uint8Array(REGION_VOLUME);
|
||||
block_light = new Uint8Array(REGION_VOLUME);
|
||||
blocks: Uint16Array;
|
||||
sky: Uint8Array;
|
||||
block_light: Uint8Array;
|
||||
|
||||
// the lowest y that still sees the sky, per column
|
||||
#heights = new Int32Array(REGION_LAYER);
|
||||
#queue = new Int32Array(1 << 18);
|
||||
#queue_length = 0;
|
||||
|
||||
constructor(shape: WorldShapeJson) {
|
||||
this.height = shape.max_y - shape.min_y;
|
||||
this.sky_light = shape.sky_light;
|
||||
const volume = REGION_LAYER * this.height;
|
||||
this.blocks = new Uint16Array(volume);
|
||||
this.sky = new Uint8Array(volume);
|
||||
this.block_light = new Uint8Array(volume);
|
||||
}
|
||||
|
||||
// the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing ones are void
|
||||
fill(chunks: (Uint32Array | null)[]) {
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const source = chunks[i];
|
||||
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE;
|
||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
||||
for (let y = 0; y < this.height; y++) {
|
||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
|
||||
if (!source) {
|
||||
@@ -62,13 +77,14 @@ export class LightRegion {
|
||||
}
|
||||
|
||||
#compute_sky({ opacity }: LightTables) {
|
||||
const { blocks, sky } = this;
|
||||
const { blocks, sky, height: world_height } = this;
|
||||
sky.fill(0);
|
||||
this.#queue_length = 0;
|
||||
if (!this.sky_light) return;
|
||||
|
||||
// straight down from the top, until something isn't fully clear
|
||||
for (let column = 0; column < REGION_LAYER; column++) {
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
let y = world_height - 1;
|
||||
while (y >= 0 && opacity[blocks[y * REGION_LAYER + column]] === 0) {
|
||||
sky[y * REGION_LAYER + column] = 15;
|
||||
y--;
|
||||
@@ -89,7 +105,7 @@ export class LightRegion {
|
||||
if (z < REGION_SIZE - 1) {
|
||||
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]);
|
||||
}
|
||||
const top = Math.min(CHUNK_HEIGHT - 1, Math.max(height, highest_neighbor - 1));
|
||||
const top = Math.min(world_height - 1, Math.max(height, highest_neighbor - 1));
|
||||
for (let y = height; y <= top; y++) {
|
||||
this.#push(y * REGION_LAYER + column);
|
||||
}
|
||||
@@ -104,7 +120,7 @@ export class LightRegion {
|
||||
block_light.fill(0);
|
||||
this.#queue_length = 0;
|
||||
|
||||
for (let i = 0; i < REGION_VOLUME; i++) {
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const level = emission[blocks[i]];
|
||||
if (level > 0) {
|
||||
block_light[i] = level;
|
||||
@@ -127,6 +143,7 @@ export class LightRegion {
|
||||
// breadth first from everything queued. a cell can be queued again when a brighter path reaches it
|
||||
#propagate(light: Uint8Array, opacity: Uint8Array, is_sky: boolean) {
|
||||
const blocks = this.blocks;
|
||||
const top = this.height - 1;
|
||||
|
||||
const spread = (to: number, level: number, down: boolean) => {
|
||||
const block_opacity = opacity[blocks[to]];
|
||||
@@ -150,7 +167,7 @@ export class LightRegion {
|
||||
const x = rest - z * REGION_SIZE;
|
||||
|
||||
if (y > 0) spread(index - REGION_LAYER, level, true);
|
||||
if (y < CHUNK_HEIGHT - 1) spread(index + REGION_LAYER, level, false);
|
||||
if (y < top) spread(index + REGION_LAYER, level, false);
|
||||
if (x > 0) spread(index - 1, level, false);
|
||||
if (x < REGION_SIZE - 1) spread(index + 1, level, false);
|
||||
if (z > 0) spread(index - REGION_SIZE, level, false);
|
||||
@@ -162,18 +179,18 @@ export class LightRegion {
|
||||
|
||||
// what a cell looks like to the mesher, including above and below the world
|
||||
export function region_block(region: LightRegion, index: number, y: number) {
|
||||
if (y >= CHUNK_HEIGHT) return AIR;
|
||||
if (y >= region.height) return AIR;
|
||||
if (y < 0) return REGION_VOID;
|
||||
return region.blocks[index];
|
||||
}
|
||||
|
||||
export function region_sky(region: LightRegion, index: number, y: number) {
|
||||
if (y >= CHUNK_HEIGHT) return 15;
|
||||
if (y >= region.height) return region.sky_light ? 15 : 0;
|
||||
if (y < 0) return 0;
|
||||
return region.sky[index];
|
||||
}
|
||||
|
||||
export function region_block_light(region: LightRegion, index: number, y: number) {
|
||||
if (y >= CHUNK_HEIGHT || y < 0) return 0;
|
||||
if (y >= region.height || y < 0) return 0;
|
||||
return region.block_light[index];
|
||||
}
|
||||
|
||||
@@ -4,16 +4,14 @@
|
||||
// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each
|
||||
// player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md
|
||||
import { deflateSync, inflateSync } from "fflate";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT } from "./constants.ts";
|
||||
import { CHUNK_AREA } from "./constants.ts";
|
||||
import { SECTION_HEIGHT } from "./world_shape.ts";
|
||||
|
||||
// the view distances clients can ask for, in chunks, like minecraft's
|
||||
export const MIN_VIEW_DISTANCE = 2;
|
||||
export const MAX_VIEW_DISTANCE = 32;
|
||||
|
||||
export const SECTION_HEIGHT = 16;
|
||||
const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT;
|
||||
const SECTIONS = CHUNK_HEIGHT / SECTION_HEIGHT;
|
||||
const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
|
||||
|
||||
// the first byte of a binary message, the only kind there is so far
|
||||
export const LEVEL_CHUNK = 1;
|
||||
@@ -42,7 +40,8 @@ export function is_within_view(
|
||||
export interface LevelChunk {
|
||||
x: number;
|
||||
z: number;
|
||||
// block values (numeric id | state bits << 16) in the sender's numbering, y then z then x
|
||||
// block values (numeric id | state bits << 16) in the sender's numbering, y from the bottom of the world, then z,
|
||||
// then x. the dimension's whole height
|
||||
blocks: Uint32Array;
|
||||
// each column's biome, x then z
|
||||
biomes: string[];
|
||||
@@ -56,7 +55,8 @@ export interface LevelChunk {
|
||||
// the rest deflated:
|
||||
// u16 biome palette size, then each biome: u8 length and the id as utf-8
|
||||
// u8 each column's biome palette index, x then z. left out when there's one biome
|
||||
// 16 sections of 16x16x16 blocks, bottom first, each a paletted container like minecraft's:
|
||||
// u16 how many sections there are, the dimension's height / 16
|
||||
// each section of 16x16x16 blocks, bottom first, a paletted container like minecraft's:
|
||||
// u8 bits per block
|
||||
// 0: u32 the value of every block
|
||||
// 1, 2, 4, 8: u16 palette size, u32 each value, then each block's palette index packed from the low bits up
|
||||
@@ -71,7 +71,9 @@ export function encode_level_chunk(chunk: LevelChunk): Uint8Array<ArrayBuffer> {
|
||||
for (const biome of chunk.biomes) writer.u8(biome_palette.indexOf(biome));
|
||||
}
|
||||
|
||||
for (let section = 0; section < SECTIONS; section++) {
|
||||
const sections = chunk.blocks.length / SECTION_VOLUME;
|
||||
writer.u16(sections);
|
||||
for (let section = 0; section < sections; section++) {
|
||||
write_section(writer, chunk.blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME));
|
||||
}
|
||||
|
||||
@@ -137,8 +139,9 @@ export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => nu
|
||||
biomes[column] = biome_palette[index];
|
||||
}
|
||||
|
||||
const blocks = new Uint32Array(CHUNK_VOLUME);
|
||||
for (let section = 0; section < SECTIONS; section++) {
|
||||
const sections = reader.u16();
|
||||
const blocks = new Uint32Array(sections * SECTION_VOLUME);
|
||||
for (let section = 0; section < sections; section++) {
|
||||
read_section(reader, blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME), map);
|
||||
}
|
||||
if (!reader.done) throw new Error("Wrong size");
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ export const ID_MASK = 0xFFFF;
|
||||
export const STATE_SHIFT = 16;
|
||||
|
||||
export const CHUNK_SIZE = 16;
|
||||
export const CHUNK_HEIGHT = 256;
|
||||
// how tall chunks are is up to their dimension, see common/world_shape.ts
|
||||
// the top of oceans and rivers
|
||||
export const SEA_LEVEL = 64;
|
||||
export const CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
|
||||
|
||||
+19
-11
@@ -4,7 +4,8 @@
|
||||
// generating a chunk: the terrain from the generator's data (common/worldgen), then ores, then mods' features.
|
||||
// only the server generates, players get finished chunks
|
||||
import { Alea } from "@paulaboks/rng";
|
||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import type { WorldShape } from "@/common/world_shape.ts";
|
||||
import type { FeatureChunk, Position } from "@/common/mod_api/worldgen.ts";
|
||||
import type { OreJson } from "@/common/mod_data.ts";
|
||||
import { generate_noise_chunk } from "./worldgen/noise_chunk.ts";
|
||||
@@ -15,6 +16,8 @@ export { named_noise_2d, named_noise_3d };
|
||||
|
||||
// what mods add to generation, see docs/modding/worldgen/index.md
|
||||
export interface WorldgenSetup {
|
||||
// where the dimension's blocks are, chunks hold its whole height
|
||||
shape: WorldShape;
|
||||
// the terrain, biomes and surface, from noise settings, see docs/modding/worldgen/terrain.md
|
||||
generator: Generator;
|
||||
// each mod's worldgen/ores.json, in load order. each is a pass of its own, so a mod's ores can replace an earlier
|
||||
@@ -34,7 +37,7 @@ export interface SetupFeature {
|
||||
}
|
||||
|
||||
export interface RawChunk {
|
||||
// numeric block ids, only what this chunk generated itself
|
||||
// numeric block ids, only what this chunk generated itself, indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x
|
||||
blocks: Uint32Array;
|
||||
// blocks it generated in other chunks (from features like a mod's trees), flattened as x, y, z, numeric id
|
||||
spills: Int32Array;
|
||||
@@ -56,13 +59,14 @@ export function generate_raw_chunk(
|
||||
// the value to store for each numeric id, with its default states. just the id when missing
|
||||
default_values?: number[],
|
||||
): RawChunk {
|
||||
const blocks = new Uint32Array(CHUNK_SIZE * CHUNK_SIZE * CHUNK_HEIGHT);
|
||||
const shape = worldgen.shape;
|
||||
const blocks = new Uint32Array(shape.volume);
|
||||
const spills: number[] = [];
|
||||
const heights = new Int32Array(CHUNK_AREA);
|
||||
const biomes: string[] = new Array(CHUNK_AREA);
|
||||
|
||||
const set = (x: number, y: number, z: number, nid: number) => {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) {
|
||||
if (!shape.contains(y)) {
|
||||
return;
|
||||
}
|
||||
nid = default_values?.[nid] ?? nid;
|
||||
@@ -74,17 +78,17 @@ export function generate_raw_chunk(
|
||||
}
|
||||
const lx = x - chunk_x * CHUNK_SIZE;
|
||||
const lz = z - chunk_z * CHUNK_SIZE;
|
||||
blocks[y * CHUNK_AREA + lz * CHUNK_SIZE + lx] = nid;
|
||||
blocks[(y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx] = nid;
|
||||
};
|
||||
|
||||
const id = (name: string) => {
|
||||
const nid = block_ids[name];
|
||||
return nid === undefined ? AIR : default_values?.[nid] ?? nid;
|
||||
};
|
||||
generate_noise_chunk(blocks, heights, biomes, chunk_x, chunk_z, worldgen.generator.for_seed(seed), id);
|
||||
generate_noise_chunk(blocks, heights, biomes, chunk_x, chunk_z, shape, worldgen.generator.for_seed(seed), id);
|
||||
|
||||
for (const ores of worldgen.ores) {
|
||||
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, ores, default_values);
|
||||
generate_ores(blocks, chunk_x, chunk_z, shape, seed, block_ids, ores, default_values);
|
||||
}
|
||||
generate_features(blocks, heights, biomes, set, chunk_x, chunk_z, seed, block_ids, worldgen);
|
||||
|
||||
@@ -96,6 +100,7 @@ function generate_ores(
|
||||
blocks: Uint32Array,
|
||||
chunk_x: number,
|
||||
chunk_z: number,
|
||||
shape: WorldShape,
|
||||
seed: string,
|
||||
block_ids: Record<string, number>,
|
||||
ores: OreJson[],
|
||||
@@ -109,10 +114,10 @@ function generate_ores(
|
||||
}
|
||||
const noises = usable.map((ore) => named_noise_3d(seed, ore.id));
|
||||
|
||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
||||
for (let y = shape.min_y; y < shape.max_y; y++) {
|
||||
for (let lz = 0; lz < CHUNK_SIZE; lz++) {
|
||||
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
|
||||
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
||||
const index = (y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
||||
const current = blocks[index] & ID_MASK;
|
||||
if (current === AIR) {
|
||||
continue;
|
||||
@@ -159,6 +164,7 @@ function generate_features(
|
||||
return lz * CHUNK_SIZE + lx;
|
||||
};
|
||||
|
||||
const shape = worldgen.shape;
|
||||
const chunk_biomes = new Set(biomes);
|
||||
for (const feature of worldgen.features) {
|
||||
if (feature.biomes && ![...feature.biomes].some((biome) => chunk_biomes.has(biome))) continue;
|
||||
@@ -166,6 +172,8 @@ function generate_features(
|
||||
x: chunk_x,
|
||||
z: chunk_z,
|
||||
seed,
|
||||
min_y: shape.min_y,
|
||||
max_y: shape.max_y,
|
||||
rng: new Alea(`${seed}_feature_${feature.id}_${chunk_x}_${chunk_z}`),
|
||||
random: (name) => new Alea(`${seed}_${name}`),
|
||||
noise_2d: (name) => named_noise_2d(seed, name),
|
||||
@@ -173,10 +181,10 @@ function generate_features(
|
||||
height_at: (x, z) => heights[local(x, z, "height_at")],
|
||||
biome_at: (x, z) => biomes[local(x, z, "biome_at")],
|
||||
get_block(x, y, z) {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) {
|
||||
if (!shape.contains(y)) {
|
||||
return undefined;
|
||||
}
|
||||
const nid = blocks[y * CHUNK_AREA + local(x, z, "get_block")] & ID_MASK;
|
||||
const nid = blocks[(y - shape.min_y) * CHUNK_AREA + local(x, z, "get_block")] & ID_MASK;
|
||||
return nid === AIR ? "cubi:air" : ids_by_nid[nid];
|
||||
},
|
||||
set_block(x, y, z, id) {
|
||||
|
||||
@@ -58,6 +58,9 @@ export interface ClientContext {
|
||||
// the column's biome and its season, undefined when the chunk isn't loaded
|
||||
biome_at(x: number, z: number): Id | undefined;
|
||||
season_at(x: number, z: number): Season | undefined;
|
||||
// the dimension's blocks go from min_y up to max_y - 1
|
||||
readonly min_y: number;
|
||||
readonly max_y: number;
|
||||
// ticks since 06:00 of day 1, see ServerWorld.time
|
||||
readonly time: number;
|
||||
};
|
||||
|
||||
@@ -362,6 +362,9 @@ export interface ServerWorld {
|
||||
// generation makes there, which takes a while the first time
|
||||
biome_at(x: number, z: number): Id;
|
||||
season_at(x: number, z: number): Season;
|
||||
// the dimension's blocks go from min_y up to max_y - 1. outside them get_block is air and nothing can be placed
|
||||
readonly min_y: number;
|
||||
readonly max_y: number;
|
||||
readonly seed: string;
|
||||
// ticks since 06:00 of day 1. a day is 36000 ticks (06:00 to 18:00), a night 12000
|
||||
readonly time: number;
|
||||
|
||||
@@ -54,6 +54,10 @@ export interface FeatureChunk {
|
||||
readonly x: number;
|
||||
readonly z: number;
|
||||
readonly seed: string;
|
||||
// the dimension's blocks go from min_y up to max_y - 1, get_block is undefined outside them and set_block does
|
||||
// nothing
|
||||
readonly min_y: number;
|
||||
readonly max_y: number;
|
||||
// seeded from the seed, chunk and feature id
|
||||
readonly rng: { next(): number };
|
||||
// seeded from the seed and name alone, the same in every chunk. for things decided across chunks, like trees
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type BiomeSourceJson,
|
||||
density_function_refs,
|
||||
type DensityFunctionJson,
|
||||
dimension_shape,
|
||||
type DimensionJson,
|
||||
new_refs,
|
||||
noise_refs,
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
type WorldgenRefs,
|
||||
} from "./worldgen/data.ts";
|
||||
import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
|
||||
import { cell_height_problem } from "./world_shape.ts";
|
||||
import type { ModData } from "./mod_loader.ts";
|
||||
|
||||
export interface ModReport {
|
||||
@@ -422,6 +424,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
if (!worldgen_owners["noise settings"].has(json.generator)) {
|
||||
errors.push(`${file}: noise settings ${json.generator} doesn't exist`);
|
||||
}
|
||||
const settings = all_noise_settings.find((settings) => settings.id === json.generator);
|
||||
const problem = settings && cell_height_problem(
|
||||
dimension_shape(json),
|
||||
[settings.terrain.cell_height, settings.caves.cell_height],
|
||||
);
|
||||
if (problem) errors.push(`${file}: can't be generated by ${json.generator}: ${problem}`);
|
||||
if (json.default && defaults.length > 1) {
|
||||
errors.push(
|
||||
`${file}: only one dimension can be the default, and these all are: ${defaults.join(", ")}`,
|
||||
|
||||
+4
-1
@@ -6,12 +6,13 @@ import type { Faces } from "./constants.ts";
|
||||
import type { ItemData } from "./inventory.ts";
|
||||
import type { FluidVariant } from "./mod_api/shared.ts";
|
||||
import type { ModListing } from "./mod_loader.ts";
|
||||
import type { WorldShapeJson } from "./world_shape.ts";
|
||||
|
||||
export const AIR_ID = "cubi:air";
|
||||
|
||||
// bump when a client and server of different versions can't play together.
|
||||
// the server rejects a different version before the client downloads anything
|
||||
export const PROTOCOL_VERSION = 26;
|
||||
export const PROTOCOL_VERSION = 27;
|
||||
|
||||
export interface PlayerInfo {
|
||||
id: string;
|
||||
@@ -189,6 +190,8 @@ export type ServerMessage =
|
||||
entities: EntityInfo[];
|
||||
// the server's block id for each of its numeric ids, which level_chunk uses. clients number blocks their own way
|
||||
blocks: string[];
|
||||
// the dimension's height and sky light, every level_chunk holds all of its height
|
||||
shape: WorldShapeJson;
|
||||
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
|
||||
selected_slot: number;
|
||||
// the slots mods added to menu 0, from PLAYER_MENU_EXTRA on, see ctx.menus.extend_player_menu
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// a dimension's shape: where its blocks start and stop going up, and whether light comes from the sky. it comes from
|
||||
// the dimension's json (see DimensionJson) and travels with what needs it, the world, generation and the client's
|
||||
// level, so nothing reads a height of its own
|
||||
import { CHUNK_AREA } from "./constants.ts";
|
||||
|
||||
// the sizes a shape can have, so every y fits in an Int16Array
|
||||
export const LOWEST_Y = -2048;
|
||||
export const HIGHEST_Y = 2048;
|
||||
export const SECTION_HEIGHT = 16;
|
||||
|
||||
// what's sent and saved of it
|
||||
export interface WorldShapeJson {
|
||||
min_y: number;
|
||||
max_y: number;
|
||||
sky_light: boolean;
|
||||
}
|
||||
|
||||
// blocks go from min_y up to max_y, not included. both are multiples of SECTION_HEIGHT
|
||||
export class WorldShape implements WorldShapeJson {
|
||||
readonly min_y: number;
|
||||
readonly max_y: number;
|
||||
// without it, sky light is 0 everywhere and only blocks give off light
|
||||
readonly sky_light: boolean;
|
||||
|
||||
// throws when it isn't a shape a dimension can have, see shape_problem
|
||||
constructor({ min_y, max_y, sky_light }: WorldShapeJson) {
|
||||
const problem = shape_problem(min_y, max_y);
|
||||
if (problem) throw new Error(problem);
|
||||
this.min_y = min_y;
|
||||
this.max_y = max_y;
|
||||
this.sky_light = sky_light;
|
||||
}
|
||||
|
||||
get height() {
|
||||
return this.max_y - this.min_y;
|
||||
}
|
||||
|
||||
// how many blocks a chunk of it holds
|
||||
get volume() {
|
||||
return CHUNK_AREA * this.height;
|
||||
}
|
||||
|
||||
contains(y: number) {
|
||||
return y >= this.min_y && y < this.max_y;
|
||||
}
|
||||
|
||||
// sky and block light, packed as block << 4 | sky, above the world and where nothing has lit yet
|
||||
get open_light() {
|
||||
return this.sky_light ? 15 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
// what a dimension gets when its json doesn't say
|
||||
export const DEFAULT_SHAPE = new WorldShape({ min_y: 0, max_y: 256, sky_light: true });
|
||||
|
||||
// why min_y and max_y can't be a dimension's, undefined when they can
|
||||
export function shape_problem(min_y: number, max_y: number): string | undefined {
|
||||
if (!Number.isInteger(min_y) || !Number.isInteger(max_y)) return `min_y and max_y must be whole numbers`;
|
||||
if (min_y % SECTION_HEIGHT !== 0 || max_y % SECTION_HEIGHT !== 0) {
|
||||
return `min_y ${min_y} and max_y ${max_y} must be multiples of ${SECTION_HEIGHT}`;
|
||||
}
|
||||
if (max_y - min_y < SECTION_HEIGHT) return `max_y ${max_y} must be at least ${SECTION_HEIGHT} above min_y ${min_y}`;
|
||||
if (min_y < LOWEST_Y || max_y > HIGHEST_Y) return `the world has to fit in ${LOWEST_Y} to ${HIGHEST_Y}`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// why a generator can't fill the shape, undefined when it can: its density is sampled every cell_height blocks up from
|
||||
// min_y, so the cells have to fit the world exactly
|
||||
export function cell_height_problem(shape: WorldShapeJson, cell_heights: number[]): string | undefined {
|
||||
for (const cell_height of cell_heights) {
|
||||
if (shape.min_y % cell_height !== 0 || shape.max_y % cell_height !== 0) {
|
||||
return `its min_y ${shape.min_y} and max_y ${shape.max_y} must be multiples of the generator's ` +
|
||||
`cell_height ${cell_height}`;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
+22
-1
@@ -6,6 +6,7 @@
|
||||
// minecraft's (density functions, the noise router, surface rules) where the idea is the same
|
||||
import * as z from "zod";
|
||||
import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts";
|
||||
import { DEFAULT_SHAPE, HIGHEST_Y, LOWEST_Y, shape_problem, WorldShape } from "../world_shape.ts";
|
||||
|
||||
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
|
||||
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
|
||||
@@ -138,6 +139,20 @@ export interface DimensionJson {
|
||||
// the noise settings that generate it
|
||||
generator: string;
|
||||
default?: boolean;
|
||||
// its blocks go from min_y up to max_y - 1, see WorldShape. 0 and 256 when not set
|
||||
min_y?: number;
|
||||
max_y?: number;
|
||||
// whether light comes from the sky, true when not set
|
||||
sky_light?: boolean;
|
||||
}
|
||||
|
||||
// the shape a dimension's json gives it
|
||||
export function dimension_shape(json: DimensionJson): WorldShape {
|
||||
return new WorldShape({
|
||||
min_y: json.min_y ?? DEFAULT_SHAPE.min_y,
|
||||
max_y: json.max_y ?? DEFAULT_SHAPE.max_y,
|
||||
sky_light: json.sky_light ?? DEFAULT_SHAPE.sky_light,
|
||||
});
|
||||
}
|
||||
|
||||
// what worldgen data refers to, for checking it all exists
|
||||
@@ -271,7 +286,7 @@ const cell_height = z.literal([1, 2, 4, 8, 16, 32]);
|
||||
|
||||
const noise_settings_schema: z.ZodType<NoiseSettingsJson> = z.object({
|
||||
id: worldgen_id,
|
||||
sea_level: z.int().min(0).max(256),
|
||||
sea_level: z.int().min(LOWEST_Y).max(HIGHEST_Y),
|
||||
default_block: block_id,
|
||||
cell_width: z.literal([1, 2, 4, 8, 16]),
|
||||
terrain: z.object({ density, cell_height }),
|
||||
@@ -327,6 +342,12 @@ const dimension_schema: z.ZodType<DimensionJson> = z.strictObject({
|
||||
id: worldgen_id,
|
||||
generator: z.string("must be a noise settings' id").regex(WORLDGEN_ID_PATTERN),
|
||||
default: z.boolean().optional(),
|
||||
min_y: z.int().optional(),
|
||||
max_y: z.int().optional(),
|
||||
sky_light: z.boolean().optional(),
|
||||
}).superRefine((json, ctx) => {
|
||||
const problem = shape_problem(json.min_y ?? DEFAULT_SHAPE.min_y, json.max_y ?? DEFAULT_SHAPE.max_y);
|
||||
if (problem) ctx.addIssue({ code: "custom", message: problem });
|
||||
});
|
||||
|
||||
export function validate_noise(json: unknown): Problems {
|
||||
|
||||
+16
-18
@@ -6,7 +6,7 @@
|
||||
// one file. the types and modifiers here are built in, worldgen scripts register more
|
||||
import { EverythingRegistry } from "../everything_registry.ts";
|
||||
import type { BlockRegistry } from "../everything_registry.ts";
|
||||
import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts";
|
||||
import { CHUNK_SIZE } from "../constants.ts";
|
||||
import * as z from "zod";
|
||||
import {
|
||||
add_problems,
|
||||
@@ -371,8 +371,8 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
return (chunk, positions) =>
|
||||
positions.flatMap((p) => {
|
||||
if (!inside(chunk, p.x, p.z)) return [];
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
while (y >= 0 && !counts_for_heightmap(chunk.get_block(p.x, y, p.z), floor)) y--;
|
||||
let y = chunk.max_y - 1;
|
||||
while (y >= chunk.min_y && !counts_for_heightmap(chunk.get_block(p.x, y, p.z), floor)) y--;
|
||||
return [{ x: p.x, y: y + 1, z: p.z }];
|
||||
});
|
||||
},
|
||||
@@ -457,7 +457,7 @@ function block_predicate(json: unknown): Predicate {
|
||||
|
||||
// whether a block could be at x y z: where it is, it isn't air, and it can stand on what's under it (place_on)
|
||||
function survives(chunk: FeatureChunk, id: string, x: number, y: number, z: number) {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) return false;
|
||||
if (y < chunk.min_y || y >= chunk.max_y) return false;
|
||||
const below = block_at(chunk, x, y - 1, z);
|
||||
return below !== undefined && can_stand_on(EverythingRegistry.get<BlockRegistry>("blocks", id), below);
|
||||
}
|
||||
@@ -518,24 +518,22 @@ function int_provider(json: unknown): IntProvider {
|
||||
// heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor }
|
||||
// or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor }
|
||||
|
||||
function anchor(json: unknown): number {
|
||||
// the bottom and top are the chunk's dimension's
|
||||
function anchor(json: unknown): IntProvider {
|
||||
const object = json as Record<string, number>;
|
||||
if (object.absolute !== undefined) return object.absolute;
|
||||
if (object.above_bottom !== undefined) return object.above_bottom;
|
||||
return CHUNK_HEIGHT - 1 - object.below_top;
|
||||
if (object.absolute !== undefined) return () => object.absolute;
|
||||
if (object.above_bottom !== undefined) return (chunk) => chunk.min_y + object.above_bottom;
|
||||
return (chunk) => chunk.max_y - 1 - object.below_top;
|
||||
}
|
||||
|
||||
function height_provider(json: unknown): IntProvider {
|
||||
const object = json as Record<string, unknown>;
|
||||
if (object.type === undefined) {
|
||||
const y = anchor(object);
|
||||
return () => y;
|
||||
}
|
||||
if (builtin_name(String(object.type)) === "constant") {
|
||||
const y = anchor(object.value);
|
||||
return () => y;
|
||||
}
|
||||
if (object.type === undefined) return anchor(object);
|
||||
if (builtin_name(String(object.type)) === "constant") return anchor(object.value);
|
||||
const min = anchor(object.min_inclusive);
|
||||
const span = anchor(object.max_inclusive) - min + 1;
|
||||
return (chunk) => min + Math.floor(chunk.rng.next() * span);
|
||||
const max = anchor(object.max_inclusive);
|
||||
return (chunk) => {
|
||||
const low = min(chunk);
|
||||
return low + Math.floor(chunk.rng.next() * (max(chunk) - low + 1));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
// noise cells), caves cut out of it, then each column's biome, its surface blocks and fluids. what all of it is comes
|
||||
// from the generator's noise settings, see NoiseTerrain and docs/modding/worldgen/terrain.md. trees and the rest
|
||||
// are features, after it
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import type { WorldShape } from "@/common/world_shape.ts";
|
||||
import { get_biome } from "./biomes.ts";
|
||||
import type { NoiseTerrain, TerrainColumn } from "./terrain.ts";
|
||||
import {
|
||||
@@ -16,7 +17,7 @@ import {
|
||||
type SurfaceContext,
|
||||
} from "./surface_rules.ts";
|
||||
|
||||
// fills blocks (indexed y * CHUNK_AREA + z * CHUNK_SIZE + x) and each column's surface height and biome. block is
|
||||
// fills blocks (indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x) and each column's surface height and biome. block is
|
||||
// a block's numeric id with its default states
|
||||
export function generate_noise_chunk(
|
||||
blocks: Uint32Array,
|
||||
@@ -24,6 +25,7 @@ export function generate_noise_chunk(
|
||||
biomes: string[],
|
||||
chunk_x: number,
|
||||
chunk_z: number,
|
||||
shape: WorldShape,
|
||||
terrain: NoiseTerrain,
|
||||
block: (id: string) => number,
|
||||
) {
|
||||
@@ -32,8 +34,9 @@ export function generate_noise_chunk(
|
||||
const cell_height = settings.terrain.cell_height;
|
||||
const cave_cell_height = settings.caves.cell_height;
|
||||
const corners = CHUNK_SIZE / cell_width + 1;
|
||||
const terrain_levels = CHUNK_HEIGHT / cell_height + 1;
|
||||
const cave_levels = CHUNK_HEIGHT / cave_cell_height + 1;
|
||||
const { min_y, max_y, height } = shape;
|
||||
const terrain_levels = height / cell_height + 1;
|
||||
const cave_levels = height / cave_cell_height + 1;
|
||||
const x0 = chunk_x * CHUNK_SIZE;
|
||||
const z0 = chunk_z * CHUNK_SIZE;
|
||||
|
||||
@@ -51,10 +54,10 @@ export function generate_noise_chunk(
|
||||
const x = x0 + (i % corners) * cell_width;
|
||||
const z = z0 + Math.floor(i / corners) * cell_width;
|
||||
for (let level = 0; level < terrain_levels; level++) {
|
||||
solid[i * terrain_levels + level] = terrain.density(column, x, level * cell_height, z);
|
||||
solid[i * terrain_levels + level] = terrain.density(column, x, min_y + level * cell_height, z);
|
||||
}
|
||||
for (let level = 0; level < cave_levels; level++) {
|
||||
caves[i * cave_levels + level] = terrain.cave(column, x, level * cave_cell_height, z);
|
||||
caves[i * cave_levels + level] = terrain.cave(column, x, min_y + level * cave_cell_height, z);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,9 +137,9 @@ export function generate_noise_chunk(
|
||||
grid[c00 * levels + level] * w00 + grid[c10 * levels + level] * w10 +
|
||||
grid[c01 * levels + level] * w01 + grid[c11 * levels + level] * w11;
|
||||
|
||||
// solid where both the terrain and the caves are above 0
|
||||
const is_solid = new Uint8Array(CHUNK_HEIGHT);
|
||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
||||
// solid where both the terrain and the caves are above 0, by y above min_y
|
||||
const is_solid = new Uint8Array(height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const level = Math.min(Math.floor(y / cell_height), terrain_levels - 2);
|
||||
const t = (y - level * cell_height) / cell_height;
|
||||
let density = blend(solid, terrain_levels, level) * (1 - t) + blend(solid, terrain_levels, level + 1) * t;
|
||||
@@ -151,8 +154,8 @@ export function generate_noise_chunk(
|
||||
}
|
||||
|
||||
const column = column_at(x, z);
|
||||
let surface_y = CHUNK_HEIGHT - 1;
|
||||
while (surface_y > 0 && !is_solid[surface_y]) surface_y--;
|
||||
let surface_y = max_y - 1;
|
||||
while (surface_y > min_y && !is_solid[surface_y - min_y]) surface_y--;
|
||||
|
||||
const ground = column.height;
|
||||
const neighbors = [column_at(x - 1, z), column_at(x + 1, z), column_at(x, z - 1), column_at(x, z + 1)];
|
||||
@@ -168,7 +171,7 @@ export function generate_noise_chunk(
|
||||
context.preliminary = ground;
|
||||
context.biome = biome;
|
||||
context.surface = surface_of(biome);
|
||||
const index = (y: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
|
||||
const index = (y: number) => (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x;
|
||||
// the same sum as the rule's own condition, so it can't disagree with it
|
||||
const lowest = ground + reach;
|
||||
// solid blocks since the last air going down, 0 is a block with air on top
|
||||
@@ -177,9 +180,9 @@ export function generate_noise_chunk(
|
||||
let open_sky = true;
|
||||
// whether the ground's surface is under water, for its cover
|
||||
let underwater = false;
|
||||
for (let y = CHUNK_HEIGHT - 1; y >= 0; y--) {
|
||||
for (let y = max_y - 1; y >= min_y; y--) {
|
||||
context.y = y;
|
||||
if (!is_solid[y]) {
|
||||
if (!is_solid[y - min_y]) {
|
||||
depth = -1;
|
||||
if (y < fluid_top) {
|
||||
const fluid = fluids(context, open_sky);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts
|
||||
import { default_block_value } from "./utils.ts";
|
||||
import { generate_raw_chunk, type RawChunk, type WorldgenSetup } from "./generation.ts";
|
||||
import { load_worldgen } from "./worldgen_loader.ts";
|
||||
import { WorldShape, type WorldShapeJson } from "./world_shape.ts";
|
||||
|
||||
// the parts of a mod's data generation reads. tags only the block ones
|
||||
export type WorldgenModData = Pick<
|
||||
@@ -31,6 +32,8 @@ export interface WorldgenBundle {
|
||||
seed: string;
|
||||
// the noise settings the world uses
|
||||
generator: string;
|
||||
// the dimension's, see WorldShape
|
||||
shape: WorldShapeJson;
|
||||
// in load order
|
||||
mods: { id: string; data: WorldgenModData; worldgen_url?: string; engine_access?: boolean }[];
|
||||
}
|
||||
@@ -38,11 +41,13 @@ export interface WorldgenBundle {
|
||||
export function worldgen_bundle(
|
||||
seed: string,
|
||||
generator: string,
|
||||
shape: WorldShapeJson,
|
||||
mods: { id: string; data: ModData; worldgen_url?: string; engine_access?: boolean }[],
|
||||
): WorldgenBundle {
|
||||
return {
|
||||
seed,
|
||||
generator,
|
||||
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
|
||||
mods: mods.map(({ id, data, worldgen_url, engine_access }) => ({
|
||||
id,
|
||||
data: {
|
||||
@@ -104,6 +109,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
|
||||
),
|
||||
ores: recipes.ores,
|
||||
generator: bundle.generator,
|
||||
shape: new WorldShape(bundle.shape),
|
||||
});
|
||||
const { block_ids, default_values } = block_numbering();
|
||||
return {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { EverythingRegistry } from "./everything_registry.ts";
|
||||
import { ModLoadError } from "./mod_loader.ts";
|
||||
import { loading_mod } from "./hooks.ts";
|
||||
import { compile_generator } from "./worldgen/generator.ts";
|
||||
import type { WorldShape } from "./world_shape.ts";
|
||||
import type { Biome } from "./worldgen/biomes.ts";
|
||||
import {
|
||||
compile_feature,
|
||||
@@ -27,6 +28,8 @@ export interface WorldgenSources {
|
||||
ores: OreJson[][];
|
||||
// the noise settings the world uses. it and data features come from mods' data, which is already registered
|
||||
generator: string;
|
||||
// the dimension's, which the generator fills
|
||||
shape: WorldShape;
|
||||
}
|
||||
|
||||
// a feature before it's put in order
|
||||
@@ -41,6 +44,7 @@ interface Pending {
|
||||
|
||||
export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenSetup> {
|
||||
const setup: WorldgenSetup = {
|
||||
shape: sources.shape,
|
||||
generator: compile_generator(sources.generator),
|
||||
ores: sources.ores,
|
||||
features: [],
|
||||
|
||||
@@ -204,6 +204,7 @@ ctx.world.get_block(x, y, z); // a block id, what this client sees
|
||||
ctx.world.get_client_data<number>(x, y, z, "speed"); // see ../blocks/tiledata.md#client-data, a copy
|
||||
ctx.world.biome_at(x, z); // and ctx.world.season_at(x, z), undefined where nothing's loaded
|
||||
ctx.world.time; // see Time
|
||||
ctx.world.min_y; // and ctx.world.max_y, see ../worldgen/terrain.md#height
|
||||
ctx.items.ids(); // every item, in load order
|
||||
ctx.items.exists(id);
|
||||
ctx.items.name(id); // "Cooked Rice"
|
||||
|
||||
@@ -46,8 +46,8 @@ away before anything is downloaded.
|
||||
The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so worldgen scripts
|
||||
stay on the server.
|
||||
|
||||
- Chunks are 16×256×16 and sent whole, compressed, in batches, nearest first. The server paces batches by how fast each
|
||||
client says it loads them.
|
||||
- Chunks are 16×16 and as tall as the dimension, sent whole, compressed, in batches, nearest first. The server paces
|
||||
batches by how fast each client says it loads them.
|
||||
- Players see chunks up to their view distance, at most 16 on the server's side. Light isn't sent: clients light chunks
|
||||
themselves.
|
||||
- Block changes go only to players who have the chunk. Everyone else gets the change with the chunk when they come
|
||||
|
||||
@@ -25,7 +25,8 @@ Each chunk goes through three passes:
|
||||
2. **Ores.** Every mod's `worldgen/ores.json`, in load order, the base game's first.
|
||||
3. **Features.** Every mod's features, code and data, by step and then load order, see [Order](#order).
|
||||
|
||||
The world is 256 blocks tall and the sea is at y 64.
|
||||
How tall the world is is up to its [dimension](terrain.md#height): the base game's goes from y 0 to 255, and its sea is
|
||||
at y 64.
|
||||
|
||||
## Ores
|
||||
|
||||
@@ -99,6 +100,8 @@ interface FeatureChunk {
|
||||
readonly x: number; // chunk coordinates. blocks are chunk.x * 16 to chunk.x * 16 + 15
|
||||
readonly z: number;
|
||||
readonly seed: string;
|
||||
readonly min_y: number; // the dimension's blocks go from min_y up to max_y - 1
|
||||
readonly max_y: number;
|
||||
readonly rng: { next(): number }; // 0 to 1
|
||||
random(name: string): { next(): number }; // seeded from the world's seed and name, the same in every chunk
|
||||
noise_2d(name: string): (x: number, z: number) => number;
|
||||
@@ -175,7 +178,8 @@ Built in names work with or without `minecraft:`.
|
||||
`not`, `all_of`, `any_of` and `true`. Each takes an `offset`.
|
||||
- **Numbers** (int providers): a whole number, or `constant`, `uniform` (`min_inclusive`, `max_inclusive`) or
|
||||
`weighted_list` (`distribution` of `data` and `weight`).
|
||||
- **Heights:** `{ "absolute": y }`, `{ "above_bottom": n }` or `{ "below_top": n }`.
|
||||
- **Heights:** `{ "absolute": y }`, `{ "above_bottom": n }` (`min_y + n`) or `{ "below_top": n }` (`max_y - 1 - n`),
|
||||
from the dimension's height.
|
||||
- **Blocks** (`to_place`, `provider`, `state`): an id, or Minecraft's
|
||||
`{ "type": "simple_state_provider", "state": { "Name": id } }`.
|
||||
|
||||
|
||||
@@ -256,15 +256,40 @@ base game's is `worldgen/dimension/overworld.json`:
|
||||
"dimension": {
|
||||
"id": "bworld:overworld",
|
||||
"generator": "bworld:overworld",
|
||||
"default": true
|
||||
"default": true,
|
||||
"min_y": 0,
|
||||
"max_y": 256,
|
||||
"sky_light": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
| ----------- | --------------------------------------------------------- |
|
||||
| `generator` | The [noise settings](#noise-settings) that generate it. |
|
||||
| `default` | `true` for the dimension the world plays. False if unset. |
|
||||
| Field | Meaning |
|
||||
| ----------- | ------------------------------------------------------------------------------------------------------- |
|
||||
| `generator` | The [noise settings](#noise-settings) that generate it. |
|
||||
| `default` | `true` for the dimension the world plays. False if unset. |
|
||||
| `min_y` | The lowest y that has blocks. 0 if unset. |
|
||||
| `max_y` | The first y above the world: blocks go up to `max_y - 1`. 256 if unset. |
|
||||
| `sky_light` | Whether light comes from the sky. `false` for a dimension that's underground everywhere. True if unset. |
|
||||
|
||||
### Height
|
||||
|
||||
A dimension's blocks go from `min_y` up to `max_y - 1`, so `"min_y": -64, "max_y": 320` is 384 blocks tall. Both have to
|
||||
be multiples of 16, `max_y` at least 16 above `min_y`, and the world has to fit in -2048 to 2048. They also have to be
|
||||
multiples of the generator's `terrain` and `caves` `cell_height`, since the density is sampled every `cell_height`
|
||||
blocks up from `min_y`. `check-mods` reports any of these, and the server doesn't start with them.
|
||||
|
||||
Outside the height there are no blocks: reading one gives air and placing one does nothing. Things that fall 64 blocks
|
||||
below `min_y` are out of the world. Scripts read the height as `ctx.world.min_y` and `ctx.world.max_y`, on the server
|
||||
and the client, and features as `chunk.min_y` and `chunk.max_y`.
|
||||
|
||||
Chunks are saved with the height they were made with. For now a chunk saved before a dimension's height changed can't be
|
||||
read, and is generated again.
|
||||
|
||||
### Sky Light
|
||||
|
||||
Without sky light, there's none anywhere, in the open and above the world too: only blocks that give off light, like
|
||||
torches, light it, and day and night don't change how bright it is. The sky is still drawn as it is in the overworld.
|
||||
|
||||
The world plays the dimension with `"default": true`. Exactly one dimension in the loaded mods can be the default: with
|
||||
none, or more than one, the server doesn't start, and the error names them. A mod can have dimensions that aren't the
|
||||
@@ -274,7 +299,8 @@ its own, like a flat world, can't be loaded with the base game's for now.
|
||||
There's one dimension per world for now, there's no travelling between them yet.
|
||||
|
||||
New players spawn in the middle of the world, on the first column, in rings of chunks around 0, 0, whose top block has
|
||||
collision. Water has none, so they never spawn in the sea, and neither do plants without collision.
|
||||
collision, looking down from `max_y`. Water has none, so they never spawn in the sea, and neither do plants without
|
||||
collision.
|
||||
|
||||
## Changing the Base Game's Terrain
|
||||
|
||||
|
||||
@@ -303,10 +303,10 @@ engine assets in `assets/`.
|
||||
How the server sends the world, like Minecraft Java since 1.20.2. The code is in `common/chunk_streaming.ts`,
|
||||
`server/game/player_chunks.ts` and `client/level/client_level.ts`.
|
||||
|
||||
- **Whole chunks.** A `level_chunk` is a binary websocket message with every block of a 16×256×16 chunk and its columns'
|
||||
biomes, deflated. Blocks are in 16 sections of 16×16×16, each a paletted container like Minecraft's: one value when
|
||||
the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256 kinds, and whole values past that.
|
||||
Light isn't sent.
|
||||
- **Whole chunks.** A `level_chunk` is a binary websocket message with every block of a chunk, as tall as the dimension,
|
||||
and its columns' biomes, deflated. Blocks are in sections of 16×16×16 from the bottom up, each a paletted container
|
||||
like Minecraft's: one value when the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256
|
||||
kinds, and whole values past that. Light isn't sent.
|
||||
- **Numeric ids.** Chunks use the server's numeric block ids, and `join.blocks` lists the string id for each, like
|
||||
Minecraft's registry sync. Clients translate them as a chunk loads.
|
||||
- **The view.** Players send their view distance with `ready` and `view_distance`. The server uses up to 16 chunks, and
|
||||
|
||||
@@ -291,7 +291,7 @@ export function register_fishing(ctx: ServerContext) {
|
||||
!player || player.selected_slot !== cast.slot || player.held_item?.id !== FISHING_ROD ||
|
||||
distance > LINE_LENGTH || cast.hook.removed ||
|
||||
(water && ctx.world.get_block(water.x, water.y, water.z) !== water.block) ||
|
||||
(cast.velocity && (now - cast.thrown_at > MAX_FLIGHT || cast.position.y < 0))
|
||||
(cast.velocity && (now - cast.thrown_at > MAX_FLIGHT || cast.position.y < ctx.world.min_y))
|
||||
) {
|
||||
stop(player, id);
|
||||
continue;
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
import type { FeatureBiome, FeatureChunk, WorldgenContext } from "cubi/worldgen";
|
||||
|
||||
const CHUNK_SIZE = 16;
|
||||
const CHUNK_HEIGHT = 256;
|
||||
|
||||
const CELL = 4;
|
||||
// trunks are at least this far apart
|
||||
@@ -87,7 +86,8 @@ function tree_sites(chunk: FeatureChunk): TreeSite[] {
|
||||
type PlaceBlock = (x: number, y: number, z: number, block: "log" | "leaves") => void;
|
||||
|
||||
// grows a tree with its trunk's bottom at x, y, z. returns false when it wouldn't fit under the top of the world
|
||||
function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random, place: PlaceBlock) {
|
||||
// max_y is the top of the world, nothing grows into it
|
||||
function grow_tree(kind: TreeKind, x: number, y: number, z: number, max_y: number, rng: Random, place: PlaceBlock) {
|
||||
const random = (min: number, max: number) => min + Math.floor(rng.next() * (max - min + 1));
|
||||
const trunk = (height: number) => {
|
||||
for (let i = 0; i < height; i++) place(x, y + i, z, "log");
|
||||
@@ -110,7 +110,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
|
||||
// birch is oak's canopy on a taller, straight trunk
|
||||
const height = kind === "birch" ? random(5, 7) : random(4, 6);
|
||||
top = y + height + 1;
|
||||
if (top >= CHUNK_HEIGHT - 1) return false;
|
||||
if (top >= max_y - 1) return false;
|
||||
trunk(height);
|
||||
layer(y + height - 2, 2, true);
|
||||
layer(y + height - 1, 2, true);
|
||||
@@ -122,7 +122,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
|
||||
// a short trunk under a wide, rounded canopy
|
||||
const height = random(4, 6);
|
||||
top = y + height + 1;
|
||||
if (top >= CHUNK_HEIGHT - 1) return false;
|
||||
if (top >= max_y - 1) return false;
|
||||
trunk(height);
|
||||
layer(y + height - 2, 2, false);
|
||||
layer(y + height - 1, MAX_CANOPY, false);
|
||||
@@ -133,7 +133,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
|
||||
case "big_oak": {
|
||||
const height = random(6, 8);
|
||||
top = y + height + 1;
|
||||
if (top >= CHUNK_HEIGHT - 1) return false;
|
||||
if (top >= max_y - 1) return false;
|
||||
trunk(height);
|
||||
layer(y + height - 3, 2, true);
|
||||
layer(y + height - 2, 3, false);
|
||||
@@ -145,7 +145,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
|
||||
case "spruce": {
|
||||
const height = random(7, 10);
|
||||
top = y + height + 1;
|
||||
if (top >= CHUNK_HEIGHT - 1) return false;
|
||||
if (top >= max_y - 1) return false;
|
||||
trunk(height);
|
||||
// a cone of layers getting wider going down, every other one narrower, like minecraft's spruce
|
||||
place(x, y + height + 1, z, "leaves");
|
||||
@@ -160,7 +160,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
|
||||
case "jungle": {
|
||||
const height = random(9, 13);
|
||||
top = y + height + 1;
|
||||
if (top >= CHUNK_HEIGHT - 1) return false;
|
||||
if (top >= max_y - 1) return false;
|
||||
trunk(height);
|
||||
layer(y + height - 2, 3, false);
|
||||
layer(y + height - 1, 3, true);
|
||||
@@ -172,7 +172,7 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random,
|
||||
// a short trunk that leans one way at the top, under a flat, wide canopy
|
||||
const height = random(4, 5);
|
||||
top = y + height + 2;
|
||||
if (top >= CHUNK_HEIGHT - 1) return false;
|
||||
if (top >= max_y - 1) return false;
|
||||
trunk(height);
|
||||
const lean_x = random(-1, 1);
|
||||
const lean_z = lean_x === 0 ? (rng.next() < 0.5 ? -1 : 1) : 0;
|
||||
@@ -223,7 +223,7 @@ export function register_trees(gen: WorldgenContext) {
|
||||
const x0 = chunk.x * CHUNK_SIZE;
|
||||
const z0 = chunk.z * CHUNK_SIZE;
|
||||
const place = (x: number, y: number, z: number, block: "log" | "leaves", wood: string) => {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) return;
|
||||
if (y < chunk.min_y || y >= chunk.max_y) return;
|
||||
const id = `bworld:${wood}_${block}`;
|
||||
if (x < x0 || x >= x0 + CHUNK_SIZE || z < z0 || z >= z0 + CHUNK_SIZE) {
|
||||
// the other chunk only takes it where it has air
|
||||
@@ -247,7 +247,15 @@ export function register_trees(gen: WorldgenContext) {
|
||||
const kind = here.kinds[Math.floor(site.rng.next() * here.kinds.length)] as TreeKind;
|
||||
// big oaks grow oak, every other kind its own wood, unless the biome says
|
||||
const wood = here.wood[kind] ?? (kind === "big_oak" ? "oak" : kind);
|
||||
grow_tree(kind, site.x, ground_y + 1, site.z, site.rng, (x, y, z, block) => place(x, y, z, block, wood));
|
||||
grow_tree(
|
||||
kind,
|
||||
site.x,
|
||||
ground_y + 1,
|
||||
site.z,
|
||||
chunk.max_y,
|
||||
site.rng,
|
||||
(x, y, z, block) => place(x, y, z, block, wood),
|
||||
);
|
||||
}
|
||||
}, { step: "vegetal_decoration" });
|
||||
}
|
||||
|
||||
@@ -32,17 +32,17 @@ export function step(x: number, y: number, z: number, face: Face): [number, numb
|
||||
return [x + dx, y + dy, z + dz];
|
||||
}
|
||||
|
||||
// a position as one number, so maps and sets of them don't make a string each: x and z in 21 bits and y in 8, further
|
||||
// than chunk_key lets a world go
|
||||
// a position as one number, so maps and sets of them don't make a string each: x and z in 20 bits, as far as
|
||||
// chunk_key lets a world go, and y in 12, as tall as a dimension can be
|
||||
export function pack(x: number, y: number, z: number) {
|
||||
return ((x + 2 ** 20) * 2 ** 21 + z + 2 ** 20) * 256 + y;
|
||||
return ((x + 2 ** 19) * 2 ** 20 + z + 2 ** 19) * 4096 + y + 2048;
|
||||
}
|
||||
|
||||
export function unpack(key: number): [number, number, number] {
|
||||
const y = key % 256;
|
||||
const xz = (key - y) / 256;
|
||||
const z = xz % 2 ** 21;
|
||||
return [(xz - z) / 2 ** 21 - 2 ** 20, y, z - 2 ** 20];
|
||||
const y = key % 4096;
|
||||
const xz = (key - y) / 4096;
|
||||
const z = xz % 2 ** 20;
|
||||
return [(xz - z) / 2 ** 20 - 2 ** 19, y - 2048, z - 2 ** 19];
|
||||
}
|
||||
|
||||
// which way a block points, from its states: the name of a facing state, read as FACES' values with 2 bits or 3, or
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
"dimension": {
|
||||
"id": "bworld:overworld",
|
||||
"generator": "bworld:overworld",
|
||||
"default": true
|
||||
"default": true,
|
||||
"min_y": 0,
|
||||
"max_y": 256,
|
||||
"sky_light": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,8 @@ import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
|
||||
import type { ServerPlayer } from "../player.ts";
|
||||
import type { LivingEntity } from "./living_entity.ts";
|
||||
|
||||
// below this, entities have fallen out of the world
|
||||
export const VOID_Y = -64;
|
||||
// this far below the bottom of the world, entities have fallen out of it
|
||||
export const VOID_DEPTH = 64;
|
||||
// the most air most things hold, 15 seconds
|
||||
export const MAX_AIR = 300;
|
||||
// motion faster than minecraft's 10 blocks a tick is reset when loading
|
||||
@@ -69,6 +69,8 @@ export function damage_source(cause: string): DamageSource {
|
||||
// what entities can see and do in the world, the entity manager is one
|
||||
export interface EntityLevel {
|
||||
readonly current_tick: number;
|
||||
// the bottom of the world, see WorldShape
|
||||
readonly min_y: number;
|
||||
has_collision(x: number, y: number, z: number): boolean;
|
||||
// what it bumps into at a block, see common/physics.ts
|
||||
collision_shape(x: number, y: number, z: number): boolean | Shape;
|
||||
@@ -269,7 +271,7 @@ export abstract class Entity {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.y < VOID_Y) {
|
||||
if (this.y < this.level.min_y - VOID_DEPTH) {
|
||||
this.on_below_world();
|
||||
}
|
||||
}
|
||||
@@ -344,7 +346,7 @@ export abstract class Entity {
|
||||
return (this.invulnerable || this.invulnerable_time > 0) && !source.bypasses_invulnerability;
|
||||
}
|
||||
|
||||
// y is below VOID_Y. things that can't die just go away
|
||||
// y is VOID_DEPTH below the bottom of the world. things that can't die just go away
|
||||
on_below_world() {
|
||||
this.remove();
|
||||
}
|
||||
|
||||
@@ -62,6 +62,10 @@ export class EntityManager implements EntityLevel {
|
||||
return this.#host.current_tick;
|
||||
}
|
||||
|
||||
get min_y() {
|
||||
return this.#host.world.shape.min_y;
|
||||
}
|
||||
|
||||
get count() {
|
||||
return this.#entities.size;
|
||||
}
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
// fluids flowing, like minecraft's FlowingFluid: a change next to a fluid gets the cells around it looked at again
|
||||
// after the fluid'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 { AIR, ID_MASK } from "@/common/constants.ts";
|
||||
import type { BlockRegistry } from "@/common/everything_registry.ts";
|
||||
import { AIR_ID } from "@/common/protocol.ts";
|
||||
import { fluid_block, get_state_value, set_state_value } from "@/common/utils.ts";
|
||||
|
||||
// what the flow needs of the world
|
||||
export interface FluidWorld {
|
||||
// undefined where the chunk isn't loaded, so fluid stops at the edge of the world instead of making new chunks
|
||||
// undefined where the chunk isn't loaded and above and below the world, so fluid 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;
|
||||
@@ -152,7 +153,6 @@ export class FluidFlow {
|
||||
}
|
||||
|
||||
#fluid(x: number, y: number, z: number): Fluid | 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;
|
||||
|
||||
+15
-11
@@ -4,7 +4,6 @@
|
||||
import {
|
||||
AIR,
|
||||
BREAK_STAGES,
|
||||
CHUNK_HEIGHT,
|
||||
CHUNK_SIZE,
|
||||
FACE_OFFSETS,
|
||||
Faces,
|
||||
@@ -71,6 +70,7 @@ import type { Menu } from "./menu.ts";
|
||||
import { MACHINE_CONN, SavedPlayer, ServerPlayer } from "./player.ts";
|
||||
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
|
||||
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
|
||||
import type { WorldShape } from "@/common/world_shape.ts";
|
||||
import { ScheduledTicks } from "./scheduled_ticks.ts";
|
||||
import type { WorldSave, WorldSource } from "./saves.ts";
|
||||
import {
|
||||
@@ -219,7 +219,7 @@ export class GameServer {
|
||||
this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen);
|
||||
this.fluids = new FluidFlow({
|
||||
value_at: (x, y, z) => {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) return undefined;
|
||||
if (!this.world.shape.contains(y)) 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;
|
||||
},
|
||||
@@ -720,7 +720,7 @@ export class GameServer {
|
||||
|
||||
// a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was
|
||||
// dug
|
||||
if (y + 1 < CHUNK_HEIGHT) {
|
||||
if (this.world.shape.contains(y + 1)) {
|
||||
const above = this.world.get_block_info(x, y + 1, z);
|
||||
if (above && !can_stand_on(above, id)) {
|
||||
this.destroy_block(x, y + 1, z, player);
|
||||
@@ -1021,6 +1021,7 @@ export class GameServer {
|
||||
players: [...this.#players.values()].map((p) => p.player_info()),
|
||||
entities: this.entities.start_tracking(player),
|
||||
blocks: this.world.block_table(),
|
||||
shape: this.world.shape,
|
||||
spawn: { x: player.x, y: player.y, z: player.z, yaw: player.yaw, pitch: player.pitch },
|
||||
selected_slot: player.selected_slot,
|
||||
player_menu: player.inventory_menu.extra.map(({ x, y, icon }) => ({ x, y, ...(icon ? { icon } : {}) })),
|
||||
@@ -1084,13 +1085,13 @@ export class GameServer {
|
||||
}
|
||||
break;
|
||||
case "break_block":
|
||||
if (is_block_position(message.x, message.y, message.z)) {
|
||||
if (is_block_position(this.world.shape, message.x, message.y, message.z)) {
|
||||
this.#break_block(player, message.x, message.y, message.z);
|
||||
}
|
||||
this.#ack(player, message.seq);
|
||||
break;
|
||||
case "hit_block":
|
||||
if (is_block_position(message.x, message.y, message.z)) {
|
||||
if (is_block_position(this.world.shape, message.x, message.y, message.z)) {
|
||||
this.#hit_block(player, message.x, message.y, message.z);
|
||||
}
|
||||
break;
|
||||
@@ -1110,7 +1111,9 @@ export class GameServer {
|
||||
this.#release_using(player);
|
||||
break;
|
||||
case "use_block":
|
||||
if (is_block_position(message.x, message.y, message.z) && faces.includes(message.face)) {
|
||||
if (
|
||||
is_block_position(this.world.shape, message.x, message.y, message.z) && faces.includes(message.face)
|
||||
) {
|
||||
if (player.using) {
|
||||
// a client that hadn't heard it's using an item yet: what it guessed the click did, it didn't
|
||||
this.#correct_use(player, message.x, message.y, message.z, message.face);
|
||||
@@ -1129,7 +1132,8 @@ export class GameServer {
|
||||
break;
|
||||
case "scroll_block":
|
||||
if (
|
||||
is_block_position(message.x, message.y, message.z) && faces.includes(message.face) &&
|
||||
is_block_position(this.world.shape, message.x, message.y, message.z) &&
|
||||
faces.includes(message.face) &&
|
||||
is_int(message.amount) && message.amount !== 0
|
||||
) {
|
||||
const { x, y, z, face, amount } = message;
|
||||
@@ -1405,7 +1409,7 @@ export class GameServer {
|
||||
|
||||
// place the held block against the face, or into the clicked block if it's replaceable. food that can be planted,
|
||||
// like a potato on farmland, is planted, and eaten when it can't be
|
||||
const placeable = held?.block_id !== undefined && ty >= 0 && ty < CHUNK_HEIGHT &&
|
||||
const placeable = held?.block_id !== undefined && this.world.shape.contains(ty) &&
|
||||
can_place(
|
||||
EverythingRegistry.get<BlockRegistry>("blocks", held.block_id),
|
||||
this.world.get_block_info(tx, ty, tz),
|
||||
@@ -2247,7 +2251,7 @@ export class GameServer {
|
||||
}
|
||||
|
||||
#correct(player: ServerPlayer, x: number, y: number, z: number) {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT || !player.chunks.has_block(x, z)) {
|
||||
if (!this.world.shape.contains(y) || !player.chunks.has_block(x, z)) {
|
||||
return;
|
||||
}
|
||||
// with its states, or the client would show it at its defaults, like a fence that lost its connections
|
||||
@@ -2482,8 +2486,8 @@ function hit_on_block(hit: unknown): [number, number, number] {
|
||||
}
|
||||
|
||||
// messages are parsed json, so the types in ClientMessage are only what a well behaved client sends
|
||||
function is_block_position(x: unknown, y: unknown, z: unknown): boolean {
|
||||
return is_int(x) && is_int(y) && is_int(z) && y >= 0 && y < CHUNK_HEIGHT &&
|
||||
function is_block_position(shape: WorldShape, x: unknown, y: unknown, z: unknown): boolean {
|
||||
return is_int(x) && is_int(y) && is_int(z) && shape.contains(y) &&
|
||||
Math.abs(x) < 30000 * CHUNK_SIZE && Math.abs(z) < 30000 * CHUNK_SIZE;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
import { register_mod_data } from "@/common/mod_loader.ts";
|
||||
import type { ModData, ModListing } from "@/common/mod_loader.ts";
|
||||
import { load_worldgen } from "@/common/worldgen_loader.ts";
|
||||
import type { DimensionJson } from "@/common/worldgen/data.ts";
|
||||
import { dimension_shape, type DimensionJson } from "@/common/worldgen/data.ts";
|
||||
import { cell_height_problem } from "@/common/world_shape.ts";
|
||||
import { worldgen_bundle } from "@/common/worldgen_bundle.ts";
|
||||
import { GameHost, GameServer } from "./game_server.ts";
|
||||
import type { WorldSource } from "./saves.ts";
|
||||
@@ -42,7 +43,9 @@ export async function start_game(
|
||||
for (const json of mod.data.entities) register_entity_type(json.id, mod_entity_factory(json));
|
||||
}
|
||||
|
||||
const generator = default_dimension(mods).generator;
|
||||
const dimension = default_dimension(mods);
|
||||
const generator = dimension.generator;
|
||||
const shape = dimension_shape(dimension);
|
||||
const worldgen_scripts = mods.flatMap((mod) =>
|
||||
mod.worldgen_url
|
||||
? [{ mod: mod.listing.id, url: mod.worldgen_url, engine_access: mod.listing.engine_access }]
|
||||
@@ -53,7 +56,11 @@ export async function start_game(
|
||||
scripts: worldgen_scripts,
|
||||
ores: recipes.ores,
|
||||
generator,
|
||||
shape,
|
||||
});
|
||||
const { terrain, caves } = worldgen.generator.settings;
|
||||
const problem = cell_height_problem(shape, [terrain.cell_height, caves.cell_height]);
|
||||
if (problem) throw new Error(`dimension ${dimension.id} can't be generated by ${generator}: ${problem}`);
|
||||
|
||||
const runtime = new ModRuntime();
|
||||
// before the world loads, its mobs can have effects
|
||||
@@ -80,6 +87,7 @@ export async function start_game(
|
||||
game.worldgen_bundle = worldgen_bundle(
|
||||
game.world.seed,
|
||||
generator,
|
||||
shape,
|
||||
mods.map((mod) => ({
|
||||
id: mod.listing.id,
|
||||
data: mod.data,
|
||||
|
||||
@@ -945,6 +945,12 @@ export class ModRuntime {
|
||||
biome_at: (x, z) => game().world.biome_at(Math.floor(x), Math.floor(z)),
|
||||
season_at: (x, z) =>
|
||||
biome_season(game().world.biome_at(Math.floor(x), Math.floor(z)), game().world.time),
|
||||
get min_y() {
|
||||
return game().world.shape.min_y;
|
||||
},
|
||||
get max_y() {
|
||||
return game().world.shape.max_y;
|
||||
},
|
||||
get seed() {
|
||||
return game().world.seed;
|
||||
},
|
||||
|
||||
+18
-17
@@ -6,8 +6,9 @@
|
||||
//
|
||||
// u8 format, CHUNK_FORMAT
|
||||
// u32 palette size, then each entry: u8 id length, the id as utf-8, u16 state bits
|
||||
// the palette index of every block, in ServerWorld's order (y, then z, then x): u8 each for up to 256 entries,
|
||||
// u16 each for more
|
||||
// the palette index of every block, in ServerWorld's order (y from the dimension's min_y, then z, then x): u8 each
|
||||
// for up to 256 entries, u16 each for more. how many there are is the dimension's, see WorldShape.volume:
|
||||
// a chunk saved with another height doesn't read, and is generated again
|
||||
// u8 biome palette size, then each entry: u8 id length, the id as utf-8
|
||||
// the biome palette index of every column, u8 each, in the order of a layer's blocks
|
||||
//
|
||||
@@ -16,10 +17,9 @@
|
||||
// generation only shows in chunks never generated before.
|
||||
// format 1 had no biomes, and a bit per block after the blocks for whether world generation made it, from when only
|
||||
// chunks players changed were saved. both are read
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA } from "@/common/constants.ts";
|
||||
|
||||
export const CHUNK_FORMAT = 2;
|
||||
export const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
|
||||
|
||||
export interface SavedChunk {
|
||||
x: number;
|
||||
@@ -64,7 +64,8 @@ export function encode_chunk(chunk: Required<ChunkBlocks>): Uint8Array<ArrayBuff
|
||||
if (chunk.biomes.length !== CHUNK_AREA || biome_palette.length > 255) throw new Error("Bad biomes");
|
||||
const biome_ids = biome_palette.map((id) => new TextEncoder().encode(id));
|
||||
if (biome_ids.some((id) => id.length > 255)) throw new Error("A biome id is too long to save");
|
||||
const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) + CHUNK_VOLUME * (wide ? 2 : 1) +
|
||||
const volume = chunk.blocks.length;
|
||||
const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) + volume * (wide ? 2 : 1) +
|
||||
1 + biome_ids.reduce((sum, id) => sum + 1 + id.length, 0) + CHUNK_AREA;
|
||||
const bytes = new Uint8Array(size);
|
||||
const view = new DataView(bytes.buffer);
|
||||
@@ -80,13 +81,13 @@ export function encode_chunk(chunk: Required<ChunkBlocks>): Uint8Array<ArrayBuff
|
||||
offset += 2;
|
||||
});
|
||||
if (wide) {
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
for (let i = 0; i < volume; i++) {
|
||||
view.setUint16(offset, chunk.blocks[i]);
|
||||
offset += 2;
|
||||
}
|
||||
} else {
|
||||
bytes.set(chunk.blocks, offset);
|
||||
offset += CHUNK_VOLUME;
|
||||
offset += volume;
|
||||
}
|
||||
view.setUint8(offset++, biome_palette.length);
|
||||
for (const id of biome_ids) {
|
||||
@@ -98,15 +99,15 @@ export function encode_chunk(chunk: Required<ChunkBlocks>): Uint8Array<ArrayBuff
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// throws when the bytes aren't a chunk this can read
|
||||
export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
|
||||
// throws when the bytes aren't a chunk this can read. volume is how many blocks the dimension's chunks hold
|
||||
export function decode_chunk(bytes: Uint8Array, volume: number): ChunkBlocks {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
let offset = 0;
|
||||
const format = view.getUint8(offset++);
|
||||
if (format !== CHUNK_FORMAT && format !== 1) throw new Error(`Unknown chunk format ${format}`);
|
||||
const palette_size = view.getUint32(offset);
|
||||
offset += 4;
|
||||
if (palette_size > CHUNK_VOLUME) throw new Error("Bad palette");
|
||||
if (palette_size > volume) throw new Error("Bad palette");
|
||||
const palette: [string, number][] = [];
|
||||
for (let i = 0; i < palette_size; i++) {
|
||||
const length = view.getUint8(offset++);
|
||||
@@ -116,21 +117,21 @@ export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
|
||||
offset += 2;
|
||||
}
|
||||
const wide = palette_size > 256;
|
||||
if (format === 1 && bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
|
||||
if (format === 1 && bytes.length !== offset + volume * (wide ? 2 : 1) + volume / 8) {
|
||||
throw new Error("Wrong size");
|
||||
}
|
||||
if (bytes.length < offset + CHUNK_VOLUME * (wide ? 2 : 1)) throw new Error("Wrong size");
|
||||
const blocks = new Uint16Array(CHUNK_VOLUME);
|
||||
if (bytes.length < offset + volume * (wide ? 2 : 1)) throw new Error("Wrong size");
|
||||
const blocks = new Uint16Array(volume);
|
||||
if (wide) {
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
for (let i = 0; i < volume; i++) {
|
||||
blocks[i] = view.getUint16(offset);
|
||||
offset += 2;
|
||||
}
|
||||
} else {
|
||||
blocks.set(bytes.subarray(offset, offset + CHUNK_VOLUME));
|
||||
offset += CHUNK_VOLUME;
|
||||
blocks.set(bytes.subarray(offset, offset + volume));
|
||||
offset += volume;
|
||||
}
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
for (let i = 0; i < volume; i++) {
|
||||
if (blocks[i] >= palette_size) throw new Error("Bad palette index");
|
||||
}
|
||||
if (format === 1) return { palette, blocks };
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
|
||||
// ticks blocks asked for some ticks ahead, see ServerWorld.schedule_tick. kept by chunk and grouped by when they're due,
|
||||
// so a tick costs nothing until it's due, and a chunk with none due is passed over with one comparison
|
||||
import { CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { chunk_key } from "@/common/utils.ts";
|
||||
import { index_in_chunk } from "./world.ts";
|
||||
import { HIGHEST_Y, LOWEST_Y } from "@/common/world_shape.ts";
|
||||
|
||||
// the most that run in one tick. the rest run first the next
|
||||
export const MAX_SCHEDULED_TICKS = 65536;
|
||||
@@ -26,7 +26,7 @@ export interface ScheduledTick {
|
||||
readonly key: number;
|
||||
// counts up with every tick scheduled, so of ticks with the same key the first scheduled runs first
|
||||
readonly order: number;
|
||||
// nid * 65536 + index in chunk, which is one per block, see ChunkTicks.waiting
|
||||
// the block's numeric id and place in its chunk, which is one per block, see block_key and ChunkTicks.waiting
|
||||
readonly block: number;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,8 @@ function run_order(a: ScheduledTick, b: ScheduledTick) {
|
||||
return a.key - b.key || a.order - b.order;
|
||||
}
|
||||
|
||||
// a block's place in its chunk, under 65536 since chunks are 256 tall, with its numeric id above
|
||||
// a block's place in its chunk with its numeric id above, the same whatever the dimension's height. under 2^40
|
||||
function block_key(x: number, y: number, z: number, chunk_x: number, chunk_z: number, nid: number) {
|
||||
return nid * 65536 + index_in_chunk(x, y, z, chunk_x, chunk_z);
|
||||
const column = (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
|
||||
return (nid * (HIGHEST_Y - LOWEST_Y) + y - LOWEST_Y) * CHUNK_AREA + column;
|
||||
}
|
||||
|
||||
+48
-35
@@ -1,7 +1,8 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import type { WorldShape } from "@/common/world_shape.ts";
|
||||
import {
|
||||
block_light_emission,
|
||||
block_light_opacity,
|
||||
@@ -16,9 +17,9 @@ import { LruMap } from "./lru.ts";
|
||||
import { collision_shape_at, EMPTY_SHAPE, type Shape } from "@/common/block_shapes.ts";
|
||||
import { farming_day } from "@/common/time.ts";
|
||||
import { encode_level_chunk } from "@/common/chunk_streaming.ts";
|
||||
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, SavedChunk, SavedChunks } from "./saves.ts";
|
||||
import { ChunkBlocks, decode_chunk, encode_chunk, SavedChunk, SavedChunks } from "./saves.ts";
|
||||
|
||||
// generation only, rebuilt when needed. 256 KB each. with a worldgen pool, it holds what the pool made until the
|
||||
// generation only, rebuilt when needed. 256 KB each in a 256 tall dimension. with a worldgen pool, it holds what the pool made until the
|
||||
// chunks are built, a few dozen chunks ahead of what players are sent
|
||||
const RAW_CACHE_SIZE = 256;
|
||||
const CHUNK_CACHE_SIZE = 256;
|
||||
@@ -103,6 +104,8 @@ export class ServerWorld {
|
||||
readonly seed: string;
|
||||
readonly block_ids: Record<string, number> = {};
|
||||
readonly worldgen: WorldgenSetup;
|
||||
// the dimension's height and sky light, chunks hold all of it
|
||||
readonly shape: WorldShape;
|
||||
// what a freshly placed or generated block stores, by numeric id: the id with its default states
|
||||
readonly default_values: number[] = [];
|
||||
// for light_at, by numeric id
|
||||
@@ -155,6 +158,7 @@ export class ServerWorld {
|
||||
constructor(seed: string, worldgen: WorldgenSetup) {
|
||||
this.seed = seed;
|
||||
this.worldgen = worldgen;
|
||||
this.shape = worldgen.shape;
|
||||
// numbered the same way as generation in a worker numbers them, see common/worldgen_bundle.ts
|
||||
const { block_ids, default_values } = block_numbering();
|
||||
Object.assign(this.block_ids, block_ids);
|
||||
@@ -179,6 +183,7 @@ export class ServerWorld {
|
||||
}
|
||||
|
||||
#find_spawn() {
|
||||
const { min_y, max_y } = this.shape;
|
||||
// chunks in rings around the middle, one column each
|
||||
for (let radius = 0; radius <= SPAWN_SEARCH_CHUNKS; radius++) {
|
||||
for (let cz = -radius; cz <= radius; cz++) {
|
||||
@@ -186,15 +191,15 @@ export class ServerWorld {
|
||||
if (Math.max(Math.abs(cx), Math.abs(cz)) !== radius) continue;
|
||||
const x = cx * CHUNK_SIZE + CHUNK_SIZE / 2;
|
||||
const z = cz * CHUNK_SIZE + CHUNK_SIZE / 2;
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
while (y > 0 && this.get_block_nid(x, y, z) === AIR) y--;
|
||||
if (y > 0 && this.get_block_info(x, y, z)?.has_collision) {
|
||||
let y = max_y - 1;
|
||||
while (y > min_y && this.get_block_nid(x, y, z) === AIR) y--;
|
||||
if (y > min_y && this.get_block_info(x, y, z)?.has_collision) {
|
||||
return { x: x + 0.5, y: y + 1, z: z + 0.5 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { x: 0.5, y: CHUNK_HEIGHT - 1, z: 0.5 };
|
||||
return { x: 0.5, y: max_y - 1, z: 0.5 };
|
||||
}
|
||||
|
||||
get_block_id(x: number, y: number, z: number): string {
|
||||
@@ -203,23 +208,23 @@ export class ServerWorld {
|
||||
}
|
||||
|
||||
get_block_nid(x: number, y: number, z: number): number {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) {
|
||||
if (!this.shape.contains(y)) {
|
||||
return AIR;
|
||||
}
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const blocks = this.#get_chunk(chunk_x, chunk_z);
|
||||
return blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] & ID_MASK;
|
||||
return blocks[this.#index(x, y, z, chunk_x, chunk_z)] & ID_MASK;
|
||||
}
|
||||
|
||||
// the id with its state bits
|
||||
get_block_value(x: number, y: number, z: number): number {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) {
|
||||
if (!this.shape.contains(y)) {
|
||||
return AIR;
|
||||
}
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
return this.#get_chunk(chunk_x, chunk_z)[index_in_chunk(x, y, z, chunk_x, chunk_z)];
|
||||
return this.#get_chunk(chunk_x, chunk_z)[this.#index(x, y, z, chunk_x, chunk_z)];
|
||||
}
|
||||
|
||||
// whether entities bump into the block there, water and other blocks with "collision": false don't
|
||||
@@ -292,7 +297,7 @@ export class ServerWorld {
|
||||
const found: [number, number, number][] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
if (!wanted[blocks[i] & ID_MASK]) continue;
|
||||
const y = Math.floor(i / CHUNK_AREA);
|
||||
const y = this.shape.min_y + Math.floor(i / CHUNK_AREA);
|
||||
const rest = i % CHUNK_AREA;
|
||||
found.push([
|
||||
chunk_x * CHUNK_SIZE + rest % CHUNK_SIZE,
|
||||
@@ -324,7 +329,7 @@ export class ServerWorld {
|
||||
return this.#opacity[this.get_block_nid(x, y, z)];
|
||||
}
|
||||
|
||||
// the highest block that isn't air, -1 for an empty column. minecraft's WORLD_SURFACE heightmap
|
||||
// the highest block that isn't air, min_y - 1 for an empty column. minecraft's WORLD_SURFACE heightmap
|
||||
surface_height(x: number, z: number): number {
|
||||
return this.#columns_of(x, z)[column_index(x, z)];
|
||||
}
|
||||
@@ -336,10 +341,12 @@ export class ServerWorld {
|
||||
|
||||
// the sky and block light there, 0-15, the same as clients work out (see client/workers/lighting.ts) but for one
|
||||
// position: searching out from it, cheapest first, for the brightest place light could come from. light loses
|
||||
// max(1, opacity) for every block it goes into, and never gets further than 15 blocks
|
||||
// max(1, opacity) for every block it goes into, and never gets further than 15 blocks. no sky light at all in a
|
||||
// dimension without it
|
||||
light_at(x: number, y: number, z: number): { sky: number; block: number } {
|
||||
if (y >= CHUNK_HEIGHT) return { sky: 15, block: 0 };
|
||||
if (y < 0) return { sky: 0, block: 0 };
|
||||
const { min_y, max_y, sky_light } = this.shape;
|
||||
if (y >= max_y) return { sky: sky_light ? 15 : 0, block: 0 };
|
||||
if (y < min_y) return { sky: 0, block: 0 };
|
||||
// the box around it, 3x3 chunks at most, fetched once each. blocks are in it by their offset from the start
|
||||
const first_x = Math.floor((x - LIGHT_REACH) / CHUNK_SIZE);
|
||||
const first_z = Math.floor((z - LIGHT_REACH) / CHUNK_SIZE);
|
||||
@@ -352,7 +359,7 @@ export class ServerWorld {
|
||||
const queues: number[][] = Array.from({ length: LIGHT_REACH }, () => []);
|
||||
let next = 0;
|
||||
const reach = (dx: number, dy: number, dz: number) => {
|
||||
if (y + dy < 0 || y + dy >= CHUNK_HEIGHT) return;
|
||||
if (y + dy < min_y || y + dy >= max_y) return;
|
||||
const at = box_index(dx, dy, dz);
|
||||
if (cost[at] <= next) return;
|
||||
cost[at] = next;
|
||||
@@ -375,9 +382,11 @@ export class ServerWorld {
|
||||
const which = (chunk_z - first_z) * 3 + chunk_x - first_x;
|
||||
const blocks = chunks[which] ??= this.#get_chunk(chunk_x, chunk_z);
|
||||
const column = (bz - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + bx - chunk_x * CHUNK_SIZE;
|
||||
const nid = blocks[by * CHUNK_AREA + column] & ID_MASK;
|
||||
const columns = skies[which] ??= this.#columns_of(bx, bz);
|
||||
if (by >= columns[CHUNK_AREA + column]) sky = Math.max(sky, LIGHT_REACH - lost);
|
||||
const nid = blocks[(by - min_y) * CHUNK_AREA + column] & ID_MASK;
|
||||
if (sky_light) {
|
||||
const columns = skies[which] ??= this.#columns_of(bx, bz);
|
||||
if (by >= columns[CHUNK_AREA + column]) sky = Math.max(sky, LIGHT_REACH - lost);
|
||||
}
|
||||
block = Math.max(block, this.#emission[nid] - lost);
|
||||
// light comes to this block from its neighbors, losing what going into it costs
|
||||
next = lost + Math.max(1, this.#opacity[nid]);
|
||||
@@ -400,13 +409,15 @@ export class ServerWorld {
|
||||
let columns = this.#columns.get(key);
|
||||
if (!columns) {
|
||||
const blocks = this.#get_chunk(chunk_x, chunk_z);
|
||||
const { min_y, height } = this.shape;
|
||||
columns = new Int16Array(CHUNK_AREA * 2);
|
||||
for (let column = 0; column < CHUNK_AREA; column++) {
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
// from the top, by y above min_y
|
||||
let y = height - 1;
|
||||
while (y >= 0 && (blocks[y * CHUNK_AREA + column] & ID_MASK) === AIR) y--;
|
||||
columns[column] = y;
|
||||
columns[column] = min_y + y;
|
||||
while (y >= 0 && this.#opacity[blocks[y * CHUNK_AREA + column] & ID_MASK] === 0) y--;
|
||||
columns[CHUNK_AREA + column] = y + 1;
|
||||
columns[CHUNK_AREA + column] = min_y + y + 1;
|
||||
}
|
||||
this.#columns.set(key, columns);
|
||||
}
|
||||
@@ -415,7 +426,7 @@ export class ServerWorld {
|
||||
|
||||
// only changes the block, the game server runs behaviors and tiles. state bits default to the block's defaults
|
||||
set_block(x: number, y: number, z: number, id: string, state?: number) {
|
||||
if (y < 0 || y >= CHUNK_HEIGHT) {
|
||||
if (!this.shape.contains(y)) {
|
||||
return;
|
||||
}
|
||||
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
||||
@@ -427,7 +438,7 @@ export class ServerWorld {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const chunk = this.#get_loaded(chunk_x, chunk_z);
|
||||
const index = index_in_chunk(x, y, z, chunk_x, chunk_z);
|
||||
const index = this.#index(x, y, z, chunk_x, chunk_z);
|
||||
chunk.blocks[index] = value;
|
||||
chunk.unknown?.delete(index);
|
||||
|
||||
@@ -488,12 +499,12 @@ export class ServerWorld {
|
||||
return index;
|
||||
};
|
||||
|
||||
const blocks = new Uint16Array(CHUNK_VOLUME);
|
||||
const blocks = new Uint16Array(chunk.blocks.length);
|
||||
const by_value = new Map<number, number>();
|
||||
// runs of the same block are common, air above the ground and stone below
|
||||
let last_value = -1;
|
||||
let last_index = 0;
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
for (let i = 0; i < chunk.blocks.length; i++) {
|
||||
const value = chunk.blocks[i];
|
||||
if (value !== last_value) {
|
||||
let index = by_value.get(value);
|
||||
@@ -661,7 +672,7 @@ export class ServerWorld {
|
||||
const data = evicted?.data ?? this.#saved_chunks?.read(chunk_x, chunk_z);
|
||||
try {
|
||||
if (!data) throw new Error("it couldn't be read");
|
||||
return this.#from_saved(chunk_x, chunk_z, decode_chunk(data));
|
||||
return this.#from_saved(chunk_x, chunk_z, decode_chunk(data, this.shape.volume));
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Couldn't load chunk ${chunk_x}, ${chunk_z}, generating it again: ${(e as Error).message}`,
|
||||
@@ -679,9 +690,9 @@ export class ServerWorld {
|
||||
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
||||
return nid === undefined ? undefined : block_value(nid, state);
|
||||
});
|
||||
const blocks = new Uint32Array(CHUNK_VOLUME);
|
||||
const blocks = new Uint32Array(this.shape.volume);
|
||||
let unknown: Map<number, [string, number]> | undefined;
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const value = values[saved.blocks[i]];
|
||||
if (value === undefined) {
|
||||
(unknown ??= new Map()).set(i, saved.palette[saved.blocks[i]]);
|
||||
@@ -706,6 +717,12 @@ export class ServerWorld {
|
||||
this.#evicted.set(key, { x, z, data: encode_chunk(this.#chunk_blocks(chunk)) });
|
||||
}
|
||||
|
||||
// a block's place in its chunk's blocks, from the bottom of the world. y has to be in the shape
|
||||
#index(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
|
||||
return (y - this.shape.min_y) * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE +
|
||||
(x - chunk_x * CHUNK_SIZE);
|
||||
}
|
||||
|
||||
// own blocks, then neighbors' leaves only into air
|
||||
#generate_chunk(chunk_x: number, chunk_z: number) {
|
||||
const blocks = this.#get_raw(chunk_x, chunk_z).blocks.slice();
|
||||
@@ -721,7 +738,7 @@ export class ServerWorld {
|
||||
if (Math.floor(x / CHUNK_SIZE) !== chunk_x || Math.floor(z / CHUNK_SIZE) !== chunk_z) {
|
||||
continue;
|
||||
}
|
||||
const index = index_in_chunk(x, y, z, chunk_x, chunk_z);
|
||||
const index = this.#index(x, y, z, chunk_x, chunk_z);
|
||||
if (blocks[index] === AIR) {
|
||||
blocks[index] = nid;
|
||||
}
|
||||
@@ -740,10 +757,6 @@ function fallback_caller(stack: string) {
|
||||
return match ? `${match[1] ?? "?"} ${match[2]}` : outside;
|
||||
}
|
||||
|
||||
export function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
|
||||
return y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
|
||||
}
|
||||
|
||||
// a column's place in its chunk, the same as its blocks' in a layer
|
||||
function column_index(x: number, z: number) {
|
||||
return (z - Math.floor(z / CHUNK_SIZE) * CHUNK_SIZE) * CHUNK_SIZE + x - Math.floor(x / CHUNK_SIZE) * CHUNK_SIZE;
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
// the server sends the world in whole chunks, like minecraft java: nearest first, in batches the client paces, and
|
||||
// only to players who can see them
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { decode_level_chunk, encode_level_chunk, is_within_view } from "@/common/chunk_streaming.ts";
|
||||
import { PROTOCOL_VERSION } from "@/common/protocol.ts";
|
||||
import { sent_block, test_game } from "./helpers.ts";
|
||||
|
||||
Deno.test("a chunk comes back as it was encoded, whatever its sections hold", () => {
|
||||
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
// as tall as a dimension can be made, sections are counted in the message
|
||||
const section = CHUNK_AREA * 16;
|
||||
const blocks = new Uint32Array(section * 24);
|
||||
// section 0 is all one block, 1 has 3 kinds, 2 has 16, 3 has 300 (more than a palette holds), the rest air
|
||||
blocks.fill(7, 0, section);
|
||||
for (let i = 0; i < section; i++) {
|
||||
@@ -131,7 +132,8 @@ Deno.test("block changes only go to players who have the chunk, the others get t
|
||||
// the chunk the server sends is what it has, with the ids join listed
|
||||
assertEquals(alice.blocks[game.world.block_ids["bworld:stone"]], "bworld:stone");
|
||||
const chunk = decode_level_chunk(game.world.level_chunk(0, 0));
|
||||
assertEquals(chunk.blocks[120 * CHUNK_AREA + 5 * CHUNK_SIZE + 3], game.world.get_block_value(3, 120, 5));
|
||||
const y = 120 - game.world.shape.min_y;
|
||||
assertEquals(chunk.blocks[y * CHUNK_AREA + 5 * CHUNK_SIZE + 3], game.world.get_block_value(3, 120, 5));
|
||||
});
|
||||
|
||||
Deno.test("/viewdistance caps every player's view distance, and raising it gives them what they asked for", async () => {
|
||||
|
||||
+99
-7
@@ -4,6 +4,11 @@
|
||||
// dimensions: the world is generated by the default dimension's noise settings, exactly one mod has one, and players
|
||||
// spawn on ground that has collision
|
||||
import { assert, assertEquals, assertRejects } from "@std/assert";
|
||||
import { CHUNK_AREA } from "@/common/constants.ts";
|
||||
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
|
||||
import { ItemStack } from "@/common/inventory.ts";
|
||||
import type { DimensionJson } from "@/common/worldgen/data.ts";
|
||||
import { load_and_check } from "@/tools/check_mods.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
|
||||
// flat's ground: glass up to y 69, only east of x 16. west of it is open sea up to y 59
|
||||
@@ -12,8 +17,16 @@ const SEA_TOP = 59;
|
||||
const GROUND_FROM_X = 16;
|
||||
|
||||
// mods/bworld, and flat when flat is true: a generator of its own and a dimension using it. which mods say their
|
||||
// dimension is the default is up to the test
|
||||
function mods(options: { flat: boolean; bworld_default: boolean; flat_default?: boolean }) {
|
||||
// dimension is the default is up to the test, and so are the flat dimension's shape, what its ground is made of and
|
||||
// its generator's cell height
|
||||
function mods(options: {
|
||||
flat: boolean;
|
||||
bworld_default: boolean;
|
||||
flat_default?: boolean;
|
||||
shape?: Pick<DimensionJson, "min_y" | "max_y" | "sky_light">;
|
||||
ground?: string;
|
||||
cell_height?: number;
|
||||
}) {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_dimensions_" });
|
||||
copy_dir("mods/bworld", `${dir}/bworld`);
|
||||
const bworld_dimension = `${dir}/bworld/worldgen/dimension/overworld.json`;
|
||||
@@ -44,7 +57,7 @@ function mods(options: { flat: boolean; bworld_default: boolean; flat_default?:
|
||||
noise_settings: {
|
||||
id: "flat:flat",
|
||||
sea_level: SEA_TOP + 1,
|
||||
default_block: "bworld:glass",
|
||||
default_block: options.ground ?? "bworld:glass",
|
||||
cell_width: 1,
|
||||
terrain: {
|
||||
density: {
|
||||
@@ -52,20 +65,20 @@ function mods(options: { flat: boolean; bworld_default: boolean; flat_default?:
|
||||
argument1: below(GROUND_TOP),
|
||||
argument2: { type: "sub", argument1: { type: "x" }, argument2: GROUND_FROM_X - 0.5 },
|
||||
},
|
||||
cell_height: 1,
|
||||
cell_height: options.cell_height ?? 1,
|
||||
},
|
||||
caves: { density: 1, cell_height: 1 },
|
||||
caves: { density: 1, cell_height: options.cell_height ?? 1 },
|
||||
preliminary_surface: GROUND_TOP + 1,
|
||||
climate: {},
|
||||
steep: 100,
|
||||
biome_source: "flat:flat",
|
||||
fluids: [{ block: "bworld:water", below: SEA_TOP + 1, where: "open_sky" }],
|
||||
surface_rule: { type: "block", result_state: { Name: "bworld:glass" } },
|
||||
surface_rule: { type: "block", result_state: { Name: options.ground ?? "bworld:glass" } },
|
||||
},
|
||||
});
|
||||
write("worldgen/dimension/flat.json", {
|
||||
format_version: 1,
|
||||
dimension: { id: "flat:flat", generator: "flat:flat", default: options.flat_default ?? true },
|
||||
dimension: { id: "flat:flat", generator: "flat:flat", default: options.flat_default ?? true, ...options.shape },
|
||||
});
|
||||
return dir;
|
||||
}
|
||||
@@ -106,3 +119,82 @@ Deno.test("the server doesn't start without a default dimension, or with two", a
|
||||
);
|
||||
Deno.removeSync(two, { recursive: true });
|
||||
});
|
||||
|
||||
// flat's ground is from x 16 on, x 40 is in chunk 2 at 8 across
|
||||
const GROUND_X = 40;
|
||||
const TALL = { min_y: -64, max_y: 320 };
|
||||
|
||||
Deno.test("a dimension's blocks go from its min_y to max_y - 1, and are sent and saved that way", async () => {
|
||||
const dir = mods({ flat: true, bworld_default: false, shape: TALL });
|
||||
const { game, join } = await test_game(dir);
|
||||
const world = game.world;
|
||||
const alice = join(1, "alice");
|
||||
assertEquals(alice.shape, { ...TALL, sky_light: true });
|
||||
assertEquals(alice.spawn.y, GROUND_TOP + 1, "on the ground, looking down from the top");
|
||||
assertEquals(world.get_block_id(GROUND_X, -64, 0), "bworld:glass", "generated down to the bottom");
|
||||
|
||||
for (const y of [-65, -64, 319, 320]) game.set_block(GROUND_X, y, 0, "bworld:stone");
|
||||
assertEquals(world.get_block_id(GROUND_X, -65, 0), "cubi:air");
|
||||
assertEquals(world.get_block_id(GROUND_X, 320, 0), "cubi:air");
|
||||
|
||||
// what clients get: every block from the bottom up
|
||||
const chunk = decode_level_chunk(world.level_chunk(2, 0));
|
||||
assertEquals(chunk.blocks.length, CHUNK_AREA * 384);
|
||||
assertEquals(chunk.blocks[8], world.get_block_value(GROUND_X, -64, 0));
|
||||
assertEquals(chunk.blocks[383 * CHUNK_AREA + 8], world.get_block_value(GROUND_X, 319, 0));
|
||||
|
||||
const loaded = await test_game(dir, game.save());
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
for (const y of [-64, 319]) assertEquals(loaded.game.world.get_block_id(GROUND_X, y, 0), "bworld:stone");
|
||||
});
|
||||
|
||||
Deno.test("under a dimension's ground it's dark, above its top it's open sky, and things fall out of its bottom", async () => {
|
||||
const dir = mods({ flat: true, bworld_default: false, shape: TALL, ground: "bworld:stone" });
|
||||
const { game } = await test_game(dir);
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
const world = game.world;
|
||||
assertEquals(world.light_at(GROUND_X, -60, 0), { sky: 0, block: 0 });
|
||||
assertEquals(world.light_at(GROUND_X, 319, 0), { sky: 15, block: 0 });
|
||||
assertEquals(world.light_at(GROUND_X, 400, 0), { sky: 15, block: 0 });
|
||||
|
||||
// the sea side has nothing under the water, items sink out of the world 64 blocks under its bottom
|
||||
const stays = game.entities.spawn_item(-40, -64 - 60, 0, new ItemStack("bworld:stone"));
|
||||
const falls = game.entities.spawn_item(-40, -64 - 70, 0, new ItemStack("bworld:stone"));
|
||||
stays.tick();
|
||||
falls.tick();
|
||||
assert(!stays.removed);
|
||||
assert(falls.removed);
|
||||
});
|
||||
|
||||
Deno.test("in a dimension without sky light only blocks give light", async () => {
|
||||
const dir = mods({ flat: true, bworld_default: false, shape: { sky_light: false } });
|
||||
const { game, join } = await test_game(dir);
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
assertEquals(join(1, "alice").shape, { min_y: 0, max_y: 256, sky_light: false });
|
||||
const world = game.world;
|
||||
assertEquals(world.light_at(GROUND_X, GROUND_TOP + 5, 0), { sky: 0, block: 0 }, "in the open");
|
||||
assertEquals(world.light_at(GROUND_X, 300, 0), { sky: 0, block: 0 }, "above the world");
|
||||
game.set_block(GROUND_X, GROUND_TOP + 1, 0, "bworld:light");
|
||||
assertEquals(world.light_at(GROUND_X, GROUND_TOP + 2, 0).sky, 0);
|
||||
assert(world.light_at(GROUND_X, GROUND_TOP + 2, 0).block > 0, "lit by the light block");
|
||||
});
|
||||
|
||||
Deno.test("a dimension's min_y and max_y have to be whole sections, and fit its generator's cells", async () => {
|
||||
const errors = (options: Parameters<typeof mods>[0]) => {
|
||||
const dir = mods(options);
|
||||
const report = load_and_check(dir).find((mod) => mod.id === "flat")!.report;
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
return report.errors.filter((error) => error.includes("worldgen/dimension/flat.json"));
|
||||
};
|
||||
assertEquals(errors({ flat: true, bworld_default: false, shape: TALL }), []);
|
||||
for (const shape of [{ min_y: -8 }, { max_y: 0 }, { min_y: -4096 }, { max_y: 4096 }]) {
|
||||
assertEquals(errors({ flat: true, bworld_default: false, shape }).length, 1, JSON.stringify(shape));
|
||||
}
|
||||
// sections of 16, but the generator samples every 32 blocks
|
||||
const shape = { min_y: -48, max_y: 320 };
|
||||
assert(errors({ flat: true, bworld_default: false, shape, cell_height: 32 })[0].includes("cell_height 32"));
|
||||
|
||||
const dir = mods({ flat: true, bworld_default: false, shape, cell_height: 32 });
|
||||
await assertRejects(() => test_game(dir), Error, "flat.json: can't be generated by flat:flat");
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
@@ -4,17 +4,21 @@
|
||||
// entities are lit from the light the chunk worker sends back with each mesh, one byte per block: block << 4 | sky
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { DEFAULT_SHAPE, type WorldShapeJson } from "@/common/world_shape.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
// the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8
|
||||
async function mesh_light() {
|
||||
// the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8. y counts from the
|
||||
// bottom of the world
|
||||
async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) {
|
||||
const volume = CHUNK_AREA * (shape.max_y - shape.min_y);
|
||||
await test_game("mods");
|
||||
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
||||
const nid = (id: string) => blocks.findIndex((b) => b?.id === id);
|
||||
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
shape,
|
||||
blocks_registry: JSON.parse(JSON.stringify(blocks)),
|
||||
models: {},
|
||||
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
@@ -22,16 +26,16 @@ async function mesh_light() {
|
||||
visuals: [],
|
||||
});
|
||||
|
||||
const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
const chunk = new Uint32Array(volume);
|
||||
const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
|
||||
for (let x = 0; x < 8; x++) {
|
||||
for (let z = 0; z < CHUNK_SIZE; z++) chunk[at(x, 20, z)] = nid("bworld:stone");
|
||||
}
|
||||
chunk[at(12, 5, 8)] = nid("bworld:light");
|
||||
const empty = () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
const empty = () => new Uint32Array(volume);
|
||||
const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()];
|
||||
|
||||
const meshed = await new Promise<{ light: Uint8Array }>((resolve) => {
|
||||
const meshed = await new Promise<{ light: Uint8Array; max_y: number }>((resolve) => {
|
||||
worker.onmessage = (e) => resolve(e.data);
|
||||
worker.postMessage({
|
||||
type: "mesh",
|
||||
@@ -48,12 +52,12 @@ async function mesh_light() {
|
||||
const packed = meshed.light[at(x, y, z)];
|
||||
return { block: packed >> 4, sky: packed & 15 };
|
||||
};
|
||||
return { light, size: meshed.light.length };
|
||||
return { light, size: meshed.light.length, max_y: meshed.max_y };
|
||||
}
|
||||
|
||||
Deno.test("each mesh comes with its chunk's block and sky light, packed a byte per block", async () => {
|
||||
const { light, size } = await mesh_light();
|
||||
assertEquals(size, CHUNK_AREA * CHUNK_HEIGHT);
|
||||
assertEquals(size, DEFAULT_SHAPE.volume);
|
||||
assertEquals(light(12, 30, 8), { block: 0, sky: 15 }, "open sky");
|
||||
assertEquals(light(12, 6, 8), { block: 13, sky: 15 }, "next to the light block");
|
||||
// under the roof, sky light comes in sideways from the open side, a level less each block
|
||||
@@ -61,3 +65,17 @@ Deno.test("each mesh comes with its chunk's block and sky light, packed a byte p
|
||||
assertEquals(light(4, 10, 8).sky, 11);
|
||||
assertEquals(light(4, 20, 8), { block: 0, sky: 0 }, "inside the stone");
|
||||
});
|
||||
|
||||
Deno.test("without sky light, only blocks light the world", async () => {
|
||||
const { light } = await mesh_light({ min_y: 0, max_y: 256, sky_light: false });
|
||||
assertEquals(light(12, 30, 8), { block: 0, sky: 0 }, "the open air is dark");
|
||||
assertEquals(light(12, 6, 8), { block: 13, sky: 0 }, "next to the light block");
|
||||
});
|
||||
|
||||
Deno.test("a dimension that starts below 0 is lit the same, and meshed where its blocks are", async () => {
|
||||
const { light, size, max_y } = await mesh_light({ min_y: -64, max_y: 320, sky_light: true });
|
||||
assertEquals(size, CHUNK_AREA * 384);
|
||||
assertEquals(light(12, 30, 8), { block: 0, sky: 15 });
|
||||
assertEquals(light(4, 10, 8).sky, 11);
|
||||
assertEquals(max_y, -64 + 21, "the top of the roof");
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// features are code or data, and use each other: data features with types and modifiers scripts register, scripts
|
||||
// placing data features. they run by step, then mod, data before code. see docs/modding/worldgen/index.md
|
||||
import { assert, assertEquals, assertRejects } from "@std/assert";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { generate_raw_chunk } from "@/common/generation.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
|
||||
@@ -98,15 +98,16 @@ Deno.test("data features use types and modifiers scripts register, scripts place
|
||||
"testmod:place_one",
|
||||
]);
|
||||
|
||||
const { min_y, max_y } = game.world.shape;
|
||||
const at = (blocks: Uint32Array, x: number, y: number, z: number) =>
|
||||
blocks[y * CHUNK_AREA + z * CHUNK_SIZE + x];
|
||||
blocks[(y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x];
|
||||
const glass = block_ids["bworld:glass"];
|
||||
const cobble = block_ids["bworld:cobblestone"];
|
||||
for (const [cx, cz] of [[0, 0], [3, -2]]) {
|
||||
const { blocks } = generate_raw_chunk(cx, cz, game.world.seed, block_ids, worldgen, default_values);
|
||||
// the pillar in the middle, which the code feature after it in its step saw
|
||||
let pillar = 0;
|
||||
for (let y = 0; y < CHUNK_HEIGHT; y++) if (at(blocks, 8, y, 8) === glass) pillar++;
|
||||
for (let y = min_y; y < max_y; y++) if (at(blocks, 8, y, 8) === glass) pillar++;
|
||||
assertEquals(pillar, 3);
|
||||
assertEquals((globalThis as unknown as { glass_seen: number }).glass_seen, 3);
|
||||
// the one place_one put at 2, 200, 2
|
||||
|
||||
+4
-2
@@ -12,7 +12,8 @@ import {
|
||||
} 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 { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
import { get_state_value, set_state_value } from "@/common/utils.ts";
|
||||
import { cell_index, corner_height, fluid_quads, type FluidCell } from "@/client/workers/fluid_mesh.ts";
|
||||
import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts";
|
||||
@@ -172,6 +173,7 @@ async function mesh(blocks: [number, number, number, string, number?][]) {
|
||||
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
shape: DEFAULT_SHAPE,
|
||||
// with the registry's gaps, like the client sends it
|
||||
blocks_registry: registry.map((block) => JSON.parse(JSON.stringify(block))),
|
||||
models: {},
|
||||
@@ -179,7 +181,7 @@ async function mesh(blocks: [number, number, number, string, number?][]) {
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [],
|
||||
});
|
||||
const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT));
|
||||
const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume));
|
||||
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);
|
||||
|
||||
+10
-3
@@ -149,13 +149,20 @@ export async function test_game(
|
||||
|
||||
// the block id and state bits at x, y, z in the chunks among messages, read the way a client does with the table
|
||||
// join sent. undefined when no chunk there was sent
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export function sent_block(messages: any[], join: { blocks: string[] }, x: number, y: number, z: number) {
|
||||
export function sent_block(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
messages: any[],
|
||||
join: { blocks: string[]; shape: { min_y: number } },
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
) {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const chunk = messages.findLast((m) => m.type === "level_chunk" && m.x === chunk_x && m.z === chunk_z);
|
||||
if (!chunk) return undefined;
|
||||
const value = chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
||||
const ly = y - join.shape.min_y;
|
||||
const value = chunk.blocks[ly * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
||||
return [join.blocks[value & ID_MASK], value >>> 16];
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -295,7 +295,7 @@ async function drawn_juicer() {
|
||||
block_visuals.set(juicer, { mod: "bworld", replaces_model: false, create: made.get("bworld:juicer")! });
|
||||
const data: Record<string, unknown> = {};
|
||||
const visuals = new Visuals({ get_block_data: () => data, get_light: () => 0 });
|
||||
visuals.meshed(0, 0, Uint32Array.of(100 * CHUNK_AREA + 1 * CHUNK_SIZE + 1, block_value(juicer, 0)));
|
||||
visuals.meshed(0, 0, 0, Uint32Array.of(100 * CHUNK_AREA + 1 * CHUNK_SIZE + 1, block_value(juicer, 0)));
|
||||
const set = (field: string, value: unknown) => {
|
||||
data[field] = value;
|
||||
visuals.data_changed(1, 100, 1);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { AIR, CHUNK_HEIGHT } from "@/common/constants.ts";
|
||||
import { AIR } from "@/common/constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "@/common/everything_registry.ts";
|
||||
import { block_from_json, block_to_json, item_from_json, item_to_json } from "@/common/mod_data.ts";
|
||||
import { generate_raw_chunk } from "@/common/generation.ts";
|
||||
@@ -97,7 +97,7 @@ Deno.test("a mod made from the template loads and runs", async () => {
|
||||
send(1, { type: "chat", text: "/give copper_tools:example_block" });
|
||||
const inventory = inventory_of(take(1));
|
||||
send(1, { type: "select_slot", slot: inventory.findIndex((i: Msg) => i?.id === "copper_tools:example_block") });
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
let y = game.world.shape.max_y - 1;
|
||||
while (game.world.get_block_nid(1, y, 1) === AIR) y--;
|
||||
// solid ground to build on: placing into water would replace it
|
||||
game.set_block(1, y, 1, "bworld:stone");
|
||||
@@ -154,6 +154,7 @@ Deno.test("the template's worldgen feature places boulders, the same way every t
|
||||
})),
|
||||
ores: worldgen.ores,
|
||||
generator: "bworld:overworld",
|
||||
shape: game.world.shape,
|
||||
});
|
||||
for (let cx = 0; cx < 20; cx++) {
|
||||
assertEquals(
|
||||
|
||||
+6
-2
@@ -17,6 +17,10 @@ import { PROTOCOL_VERSION } from "@/common/protocol.ts";
|
||||
import { decode_level_chunk, type LevelChunk } from "@/common/chunk_streaming.ts";
|
||||
import { decode_chunk, encode_chunk } from "@/server/game/saves.ts";
|
||||
import { list_chunks, read_chunk, write_chunks } from "@/server/regions.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
|
||||
// the base game's dimension, which the test worlds play
|
||||
const VOLUME = DEFAULT_SHAPE.volume;
|
||||
|
||||
const ENGINE_TEXTURES = ["cubi:missing", ...Array.from({ length: 9 }, (_, i) => `cubi:break_${i}`)];
|
||||
|
||||
@@ -403,8 +407,8 @@ Deno.test({
|
||||
await write_chunks(
|
||||
region,
|
||||
await Promise.all(saved.map(async ([x, z]) => {
|
||||
const chunk = decode_chunk((await read_chunk(region, x, z))!);
|
||||
chunk.blocks[255 * 256] = chunk.palette.push(["bworld:stone", 0]) - 1;
|
||||
const chunk = decode_chunk((await read_chunk(region, x, z))!, VOLUME);
|
||||
chunk.blocks[VOLUME - 256] = chunk.palette.push(["bworld:stone", 0]) - 1;
|
||||
return { x, z, data: encode_chunk(chunk as Required<typeof chunk>) };
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// monsters spawning on their own in the dark near players, like undergarden's rotwalkers, see natural_spawner.ts and
|
||||
// mods/undergarden/worldgen/spawns.json
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
|
||||
import {
|
||||
block_light_emission,
|
||||
@@ -31,8 +31,8 @@ async function setup(roof = "bworld:stone") {
|
||||
const x0 = CHUNK * CHUNK_SIZE;
|
||||
for (let x = x0; x < x0 + CHUNK_SIZE; x++) {
|
||||
for (let z = x0; z < x0 + CHUNK_SIZE; z++) {
|
||||
for (let y = 0; y < FLOOR; y++) world.set_block(x, y, z, "bworld:stone");
|
||||
for (let y = ROOF + 1; y < CHUNK_HEIGHT; y++) world.set_block(x, y, z, "cubi:air");
|
||||
for (let y = world.shape.min_y; y < FLOOR; y++) world.set_block(x, y, z, "bworld:stone");
|
||||
for (let y = ROOF + 1; y < world.shape.max_y; y++) world.set_block(x, y, z, "cubi:air");
|
||||
}
|
||||
}
|
||||
for (let x = x0 - 1; x <= x0 + CHUNK_SIZE; x++) {
|
||||
@@ -86,7 +86,7 @@ Deno.test("the server's light is the same as what clients work out", async () =>
|
||||
emission[nid] = block_light_emission(block);
|
||||
});
|
||||
opacity[REGION_VOID] = 15;
|
||||
const region = new LightRegion();
|
||||
const region = new LightRegion(world.shape);
|
||||
const chunks = [];
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
@@ -97,7 +97,8 @@ Deno.test("the server's light is the same as what clients work out", async () =>
|
||||
region.compute({ opacity, emission });
|
||||
|
||||
const check = (x: number, y: number, z: number) => {
|
||||
const index = y * REGION_LAYER + (z - x0 + CHUNK_SIZE) * REGION_SIZE + x - x0 + CHUNK_SIZE;
|
||||
const index = (y - world.shape.min_y) * REGION_LAYER + (z - x0 + CHUNK_SIZE) * REGION_SIZE + x - x0 +
|
||||
CHUNK_SIZE;
|
||||
const expected = { sky: region.sky[index], block: region.block_light[index] };
|
||||
assertEquals(world.light_at(x, y, z), expected, `at ${x}, ${y}, ${z}`);
|
||||
};
|
||||
|
||||
@@ -54,6 +54,7 @@ async function mesh_chunks(radius: number) {
|
||||
});
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
shape: game.world.shape,
|
||||
blocks_registry: JSON.parse(JSON.stringify(blocks)),
|
||||
models: {},
|
||||
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
|
||||
@@ -59,7 +59,7 @@ Deno.test("a mod's biome generates where its rule, added to the base game's, say
|
||||
if (biome !== "lavender:fields") return;
|
||||
fields++;
|
||||
// its surface: the top block of the column is its sand
|
||||
let y = 255;
|
||||
let y = game.world.shape.height - 1;
|
||||
while (y > 0 && blocks[y * CHUNK_AREA + column] === 0) y--;
|
||||
assertEquals(blocks[y * CHUNK_AREA + column], block_ids["bworld:sand"]);
|
||||
});
|
||||
|
||||
+5
-3
@@ -4,7 +4,8 @@
|
||||
// blocks with a "tint" are drawn in their biome's grass or foliage color, blended across biome edges, or a fixed one. water is its biome's water color
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
import { generate_raw_chunk } from "@/common/generation.ts";
|
||||
import { get_biome } from "@/common/worldgen/biomes.ts";
|
||||
import { type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts";
|
||||
@@ -22,6 +23,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
|
||||
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
shape: DEFAULT_SHAPE,
|
||||
blocks_registry: JSON.parse(JSON.stringify(blocks)),
|
||||
models: {},
|
||||
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
@@ -29,9 +31,9 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
|
||||
visuals: [],
|
||||
});
|
||||
|
||||
const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
const chunk = new Uint32Array(DEFAULT_SHAPE.volume);
|
||||
chunk[10 * CHUNK_AREA + 8 * CHUNK_SIZE + x] = block_ids[id];
|
||||
const empty = () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
const empty = () => new Uint32Array(DEFAULT_SHAPE.volume);
|
||||
const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()];
|
||||
const colors = chunks.map(() => null as Uint32Array | null);
|
||||
const biome_colors = ({ grass, foliage, water = 0 }: Colors) => {
|
||||
|
||||
+15
-13
@@ -6,7 +6,8 @@
|
||||
import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert";
|
||||
import { mat4 } from "gl-matrix";
|
||||
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
import { block_value } from "@/common/utils.ts";
|
||||
import type { ModListing } from "@/common/mod_loader.ts";
|
||||
import { read_mod } from "@/common/mod.ts";
|
||||
@@ -87,13 +88,14 @@ Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models
|
||||
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
shape: DEFAULT_SHAPE,
|
||||
blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry<BlockRegistry>("blocks"))),
|
||||
models: Object.fromEntries(EverythingRegistry.entries("models")),
|
||||
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]],
|
||||
});
|
||||
const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT));
|
||||
const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume));
|
||||
const middle = chunks[4];
|
||||
middle[index_of(1, 64, 1)] = value("bworld:stone");
|
||||
middle[index_of(4, 64, 1)] = value("bworld:cobblestone");
|
||||
@@ -155,12 +157,12 @@ Deno.test("a visual is made with its block, told when its client data changes, a
|
||||
});
|
||||
const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis));
|
||||
|
||||
visuals.meshed(0, 0, shaft(1));
|
||||
visuals.meshed(0, 0, 0, shaft(1));
|
||||
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]);
|
||||
// the half model has one face, the block's own model is a cube
|
||||
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
|
||||
// meshed again for something else, it stays
|
||||
visuals.meshed(0, 0, shaft(1));
|
||||
visuals.meshed(0, 0, 0, shaft(1));
|
||||
assertEquals(log.splice(0), []);
|
||||
|
||||
data.speed = 32;
|
||||
@@ -175,15 +177,15 @@ Deno.test("a visual is made with its block, told when its client data changes, a
|
||||
assertEquals(log.splice(0), ["frame 10.5"]);
|
||||
|
||||
// its states changing makes it again
|
||||
visuals.meshed(0, 0, shaft(2));
|
||||
visuals.meshed(0, 0, 0, shaft(2));
|
||||
assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]);
|
||||
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
|
||||
// and it goes with the block, or with the chunk, and so do its instances
|
||||
visuals.meshed(0, 0, new Uint32Array());
|
||||
visuals.meshed(0, 0, 0, new Uint32Array());
|
||||
assertEquals(log.splice(0), ["delete 1 64 1"]);
|
||||
assert(!visuals.has(0, 0));
|
||||
assertEquals(drawn(visuals), []);
|
||||
visuals.meshed(0, 0, shaft(1));
|
||||
visuals.meshed(0, 0, 0, shaft(1));
|
||||
visuals.unload(0, 0);
|
||||
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]);
|
||||
assertEquals(drawn(visuals), []);
|
||||
@@ -214,13 +216,13 @@ Deno.test("a visual that throws is logged and left out, and not made again until
|
||||
const console_error = console.error;
|
||||
console.error = (...args) => errors.push(args);
|
||||
try {
|
||||
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
|
||||
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
|
||||
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
|
||||
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
|
||||
assertEquals([made, errors.length], [1, 1]);
|
||||
assertEquals(drawn(visuals), []);
|
||||
|
||||
// an on_frame that throws isn't called again
|
||||
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2)));
|
||||
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2)));
|
||||
for (let frame = 0; frame < 3; frame++) visuals.frame([{ x: 0, z: 0 }], frame);
|
||||
assertEquals([made, errors.length], [3, 2]);
|
||||
} finally {
|
||||
@@ -248,7 +250,7 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
|
||||
const shafts = Uint32Array.of(
|
||||
...[1, 2, 3].flatMap((x) => [index_of(x, 64, 1), value("testmod:shaft")]),
|
||||
);
|
||||
visuals.meshed(0, 0, shafts);
|
||||
visuals.meshed(0, 0, 0, shafts);
|
||||
const group = [...visuals.groups()].find((group) => group.instances.length > 0)!;
|
||||
const at = (i: number) => [...group.data.subarray(i * INSTANCE_FLOATS, (i + 1) * INSTANCE_FLOATS)];
|
||||
const sent = () => {
|
||||
@@ -273,7 +275,7 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
|
||||
|
||||
// a new light comes with the chunk's mesh
|
||||
light = 0x0f;
|
||||
visuals.meshed(0, 0, shafts);
|
||||
visuals.meshed(0, 0, 0, shafts);
|
||||
assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]);
|
||||
assertEquals(sent(), [0, 1]);
|
||||
block_visuals.clear();
|
||||
@@ -291,7 +293,7 @@ function one_visual(nid: (id: string) => number, value: (id: string) => number,
|
||||
return {};
|
||||
},
|
||||
});
|
||||
const mesh = (blocks: number[]) => visuals.meshed(0, 0, Uint32Array.from(blocks));
|
||||
const mesh = (blocks: number[]) => visuals.meshed(0, 0, 0, Uint32Array.from(blocks));
|
||||
mesh([index_of(1, 64, 1), value("testmod:shaft")]);
|
||||
return { visuals, mesh };
|
||||
}
|
||||
|
||||
+22
-16
@@ -4,14 +4,18 @@
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { AIR_ID } from "@/common/protocol.ts";
|
||||
import { CHUNK_AREA } from "@/common/constants.ts";
|
||||
import { CHUNK_VOLUME, decode_chunk, encode_chunk, SavedChunk } from "@/server/game/saves.ts";
|
||||
import { decode_chunk, encode_chunk, SavedChunk } from "@/server/game/saves.ts";
|
||||
import { list_chunks, read_chunk, region_file, write_chunks } from "@/server/regions.ts";
|
||||
import { sent_block, test_game } from "./helpers.ts";
|
||||
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||
|
||||
// the base game's dimension, which the test worlds play
|
||||
const VOLUME = DEFAULT_SHAPE.volume;
|
||||
|
||||
function chunk_data(seed: number, palette_size = 3) {
|
||||
const palette: [string, number][] = [];
|
||||
for (let i = 0; i < palette_size; i++) palette.push([`test:block_${i}`, i % 5]);
|
||||
const blocks = new Uint16Array(CHUNK_VOLUME).map((_, i) => (i * seed) % palette_size);
|
||||
const blocks = new Uint16Array(VOLUME).map((_, i) => (i * seed) % palette_size);
|
||||
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => `test:biome_${(i * seed) % 4}`);
|
||||
return { palette, blocks, biomes };
|
||||
}
|
||||
@@ -21,11 +25,11 @@ const index = (x: number, y: number, z: number) => y * CHUNK_AREA + z * 16 + x;
|
||||
// what a chunk was saved as before chunks had biomes: a bit per block after the blocks instead, for whether world
|
||||
// generation made it
|
||||
function format_1(data: Uint8Array<ArrayBuffer>) {
|
||||
const chunk = decode_chunk(data);
|
||||
const chunk = decode_chunk(data, VOLUME);
|
||||
const biomes = 1 +
|
||||
[...new Set(chunk.biomes)].reduce((sum, id) => sum + 1 + new TextEncoder().encode(id).length, 0) +
|
||||
CHUNK_AREA;
|
||||
const old = new Uint8Array(data.length - biomes + CHUNK_VOLUME / 8);
|
||||
const old = new Uint8Array(data.length - biomes + VOLUME / 8);
|
||||
old.set(data.subarray(0, data.length - biomes));
|
||||
old[0] = 1;
|
||||
return old;
|
||||
@@ -34,16 +38,16 @@ function format_1(data: Uint8Array<ArrayBuffer>) {
|
||||
Deno.test("a chunk's blocks and biomes come back as they were saved, with more than 256 kinds too", () => {
|
||||
for (const palette_size of [1, 3, 256, 300]) {
|
||||
const chunk = chunk_data(7, palette_size);
|
||||
const decoded = decode_chunk(encode_chunk(chunk));
|
||||
const decoded = decode_chunk(encode_chunk(chunk), VOLUME);
|
||||
assertEquals(decoded.palette, chunk.palette);
|
||||
assertEquals(decoded.blocks, chunk.blocks);
|
||||
assertEquals(decoded.biomes, chunk.biomes);
|
||||
}
|
||||
// a byte a block when that's enough
|
||||
assert(encode_chunk(chunk_data(7, 256)).length < encode_chunk(chunk_data(7, 257)).length - CHUNK_VOLUME / 2);
|
||||
assert(encode_chunk(chunk_data(7, 256)).length < encode_chunk(chunk_data(7, 257)).length - VOLUME / 2);
|
||||
|
||||
// format 1 chunks still load, without biomes
|
||||
const old = decode_chunk(format_1(encode_chunk(chunk_data(3, 300))));
|
||||
const old = decode_chunk(format_1(encode_chunk(chunk_data(3, 300))), VOLUME);
|
||||
assertEquals(old.blocks, chunk_data(3, 300).blocks);
|
||||
assertEquals(old.biomes, undefined);
|
||||
});
|
||||
@@ -59,7 +63,9 @@ Deno.test("region files keep chunks, including negative ones, and saving one aga
|
||||
const by_position = async () =>
|
||||
Object.fromEntries(
|
||||
await Promise.all(
|
||||
positions.map(async ([x, z]) => [`${x},${z}`, decode_chunk((await read_chunk(dir, x, z))!).blocks[5]]),
|
||||
positions.map(async (
|
||||
[x, z],
|
||||
) => [`${x},${z}`, decode_chunk((await read_chunk(dir, x, z))!, VOLUME).blocks[5]]),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -97,11 +103,11 @@ Deno.test("every chunk generated is saved whole, and saved again only when it ch
|
||||
for (const chunk of ["0,0", "-2,2", "5,5"]) assert(positions.includes(chunk), `${chunk} is saved`);
|
||||
|
||||
// every block, and each column's biome
|
||||
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0 && c.z === 0)!.data);
|
||||
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0 && c.z === 0)!.data, VOLUME);
|
||||
assertEquals(chunk.palette[chunk.blocks[index(3, 120, 5)]], ["bworld:stone", 0]);
|
||||
assert(chunk.palette[chunk.blocks[index(3, 10, 5)]][0] !== AIR_ID);
|
||||
assertEquals(chunk.biomes![index(3, 0, 5)], game.world.biome_at(3, 5));
|
||||
const untouched = decode_chunk(saved.chunks.find((c) => c.x === 5 && c.z === 5)!.data);
|
||||
const untouched = decode_chunk(saved.chunks.find((c) => c.x === 5 && c.z === 5)!.data, VOLUME);
|
||||
assertEquals(
|
||||
Uint32Array.from(untouched.blocks, (block) => {
|
||||
const [id, state] = untouched.palette[block];
|
||||
@@ -135,7 +141,7 @@ async function saved_with_old_terrain() {
|
||||
game.set_block(3, 120, 5, "bworld:stone");
|
||||
const saved = game.save();
|
||||
const at_0_0 = saved.chunks.find((c) => c.x === 0 && c.z === 0)!;
|
||||
const chunk = decode_chunk(at_0_0.data);
|
||||
const chunk = decode_chunk(at_0_0.data, VOLUME);
|
||||
assertEquals(chunk.palette[chunk.blocks[index(3, 121, 5)]][0], AIR_ID);
|
||||
chunk.blocks[index(3, 121, 5)] = chunk.blocks[index(3, 120, 5)];
|
||||
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
|
||||
@@ -152,18 +158,18 @@ Deno.test("saved chunks stay as they were saved, whatever generation makes there
|
||||
|
||||
Deno.test("chunks saved before they had biomes get them from generation, and are saved again with them", async () => {
|
||||
const { saved, at_0_0 } = await saved_with_old_terrain();
|
||||
const biomes = decode_chunk(at_0_0.data).biomes!;
|
||||
const biomes = decode_chunk(at_0_0.data, VOLUME).biomes!;
|
||||
at_0_0.data = format_1(at_0_0.data);
|
||||
const { game } = await test_game("mods", saved);
|
||||
assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone");
|
||||
assertEquals(game.world.biome_at(3, 5), biomes[index(3, 0, 5)]);
|
||||
const again = game.save().chunks.find((c) => c.x === 0 && c.z === 0)!;
|
||||
assertEquals(decode_chunk(again.data).biomes, biomes);
|
||||
assertEquals(decode_chunk(again.data, VOLUME).biomes, biomes);
|
||||
});
|
||||
|
||||
Deno.test("blocks of a mod that's gone are kept in the save until something replaces them", async () => {
|
||||
const { saved, at_0_0 } = await saved_with_old_terrain();
|
||||
const chunk = decode_chunk(at_0_0.data);
|
||||
const chunk = decode_chunk(at_0_0.data, VOLUME);
|
||||
chunk.palette[chunk.blocks[index(3, 120, 5)]] = ["gone:thing", 2];
|
||||
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
|
||||
|
||||
@@ -171,12 +177,12 @@ Deno.test("blocks of a mod that's gone are kept in the save until something repl
|
||||
// air stands in for it
|
||||
assertEquals(game.world.get_block_id(3, 120, 5), AIR_ID);
|
||||
game.set_block(0, 120, 0, "bworld:stone");
|
||||
const again = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data);
|
||||
const again = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data, VOLUME);
|
||||
assertEquals(again.palette[again.blocks[index(3, 120, 5)]], ["gone:thing", 2]);
|
||||
assertEquals(again.palette[again.blocks[index(3, 121, 5)]], ["gone:thing", 2]);
|
||||
|
||||
game.set_block(3, 120, 5, "bworld:oak_planks");
|
||||
const replaced = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data);
|
||||
const replaced = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data, VOLUME);
|
||||
assertEquals(replaced.palette[replaced.blocks[index(3, 120, 5)]], ["bworld:oak_planks", 0]);
|
||||
assertEquals(replaced.palette[replaced.blocks[index(3, 121, 5)]], ["gone:thing", 2]);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
// the base game's worldgen features, see mods/bworld/scripts/worldgen.ts
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||
import { generate_raw_chunk } from "@/common/generation.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
@@ -20,11 +20,13 @@ Deno.test("cacti grow 1 to 3 tall on desert sand, 2 or 3 tries a chunk", async (
|
||||
for (let dx = -3; dx <= 3; dx++) {
|
||||
for (let dz = -3; dz <= 3; dz++) {
|
||||
const chunk = generate_raw_chunk(DESERT_CHUNK.x + dx, DESERT_CHUNK.z + dz, SEED, ids, game.world.worldgen);
|
||||
const at = (x: number, y: number, z: number) => chunk.blocks[y * CHUNK_AREA + z * CHUNK_SIZE + x] & ID_MASK;
|
||||
const { min_y, max_y } = game.world.shape;
|
||||
const at = (x: number, y: number, z: number) =>
|
||||
chunk.blocks[(y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x] & ID_MASK;
|
||||
let in_chunk = 0;
|
||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||
for (let y = 1; y < CHUNK_HEIGHT; y++) {
|
||||
for (let y = min_y + 1; y < max_y; y++) {
|
||||
// the bottom of each cactus
|
||||
if (at(x, y, z) !== cactus || at(x, y - 1, z) === cactus) continue;
|
||||
assertEquals(at(x, y - 1, z), sand, "on sand");
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, SEA_LEVEL } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, SEA_LEVEL } from "@/common/constants.ts";
|
||||
import { generate_raw_chunk } from "@/common/generation.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
@@ -22,11 +22,12 @@ Deno.test("the overworld generates the same way every time, with water only belo
|
||||
|
||||
for (let i = 0; i < CHUNK_AREA; i++) {
|
||||
assert(blocks[i] !== 0, "the bottom of the world is solid");
|
||||
assertEquals(blocks[(CHUNK_HEIGHT - 1) * CHUNK_AREA + i], 0, "nothing reaches the top of the world");
|
||||
const top = (game.world.shape.height - 1) * CHUNK_AREA + i;
|
||||
assertEquals(blocks[top], 0, "nothing reaches the top of the world");
|
||||
}
|
||||
blocks.forEach((block, i) => {
|
||||
if (block === water) {
|
||||
assert(Math.floor(i / CHUNK_AREA) < SEA_LEVEL, "water above sea level");
|
||||
assert(game.world.shape.min_y + Math.floor(i / CHUNK_AREA) < SEA_LEVEL, "water above sea level");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+22
-18
@@ -6,7 +6,8 @@
|
||||
// map.png: 4096 blocks across from the terrain's heights and biomes (fast, no caves or 3d noise)
|
||||
// blocks.png: 768 blocks across from real generated chunks, top block with hill shading
|
||||
// section.png: a slice down through the world along x, showing caves, overhangs and underground rivers
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, SEA_LEVEL } from "@/common/constants.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE, SEA_LEVEL } from "@/common/constants.ts";
|
||||
import { dimension_shape } from "@/common/worldgen/data.ts";
|
||||
import { generate_raw_chunk } from "@/common/generation.ts";
|
||||
import { load_worldgen } from "@/common/worldgen_loader.ts";
|
||||
import { register_mod_data } from "@/common/mod_loader.ts";
|
||||
@@ -44,12 +45,17 @@ register_mod_data([{
|
||||
features: jsons(bworld.features),
|
||||
},
|
||||
}]);
|
||||
const dimension = jsons(bworld.dimensions).find((json) => json.default)!;
|
||||
const shape = dimension_shape(dimension);
|
||||
const worldgen = await load_worldgen({
|
||||
mods: ["bworld"],
|
||||
scripts: [{ mod: "bworld", url: new URL("../mods/bworld/scripts/worldgen.ts", import.meta.url).href }],
|
||||
ores: [jsons(bworld.ores)],
|
||||
generator: "bworld:overworld",
|
||||
generator: dimension.generator,
|
||||
shape,
|
||||
});
|
||||
// a block's place in a chunk's blocks
|
||||
const at = (lx: number, y: number, lz: number) => (y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
||||
|
||||
const NAMES = [
|
||||
"bworld:stone",
|
||||
@@ -212,7 +218,8 @@ const shade = (color: [number, number, number], factor: number): [number, number
|
||||
const top = new Int32Array(size * size);
|
||||
const top_block = new Uint8Array(size * size);
|
||||
const water_depth = new Int32Array(size * size);
|
||||
const section = new Uint8Array(size * CHUNK_HEIGHT);
|
||||
// rows from the top of the world down
|
||||
const section = new Uint8Array(size * shape.height);
|
||||
const section_z = size / 2;
|
||||
const origin = -size / 2;
|
||||
const counts = new Map<number, number>();
|
||||
@@ -229,20 +236,20 @@ const shade = (color: [number, number, number], factor: number): [number, number
|
||||
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
|
||||
const px = cx * CHUNK_SIZE + lx;
|
||||
const pz = cz * CHUNK_SIZE + lz;
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
let y = shape.max_y - 1;
|
||||
let depth = 0;
|
||||
while (y > 0) {
|
||||
const b = blocks[y * CHUNK_AREA + lz * CHUNK_SIZE + lx];
|
||||
while (y > shape.min_y) {
|
||||
const b = blocks[at(lx, y, lz)];
|
||||
if (b === block_ids["bworld:water"]) depth++;
|
||||
else if (b !== 0) break;
|
||||
y--;
|
||||
}
|
||||
top[pz * size + px] = y;
|
||||
top_block[pz * size + px] = blocks[y * CHUNK_AREA + lz * CHUNK_SIZE + lx];
|
||||
top_block[pz * size + px] = blocks[at(lx, y, lz)];
|
||||
water_depth[pz * size + px] = depth;
|
||||
let seen_ground = false;
|
||||
for (let yy = CHUNK_HEIGHT - 1; yy >= 0; yy--) {
|
||||
const b = blocks[yy * CHUNK_AREA + lz * CHUNK_SIZE + lx];
|
||||
for (let yy = shape.max_y - 1; yy >= shape.min_y; yy--) {
|
||||
const b = blocks[at(lx, yy, lz)];
|
||||
counts.set(b, (counts.get(b) ?? 0) + 1);
|
||||
if (b !== 0 && b !== block_ids["bworld:water"]) {
|
||||
seen_ground = true;
|
||||
@@ -250,7 +257,7 @@ const shade = (color: [number, number, number], factor: number): [number, number
|
||||
} else if (seen_ground && b === 0) {
|
||||
underground_air++;
|
||||
}
|
||||
if (pz === section_z) section[(CHUNK_HEIGHT - 1 - yy) * size + px] = b;
|
||||
if (pz === section_z) section[(shape.max_y - 1 - yy) * size + px] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -273,16 +280,13 @@ const shade = (color: [number, number, number], factor: number): [number, number
|
||||
}
|
||||
await write_png(`${out}/blocks.png`, size, size, rgb);
|
||||
|
||||
const section_rgb = new Uint8Array(size * CHUNK_HEIGHT * 3);
|
||||
for (let i = 0; i < size * CHUNK_HEIGHT; i++) {
|
||||
const section_rgb = new Uint8Array(size * shape.height * 3);
|
||||
for (let i = 0; i < size * shape.height; i++) {
|
||||
section_rgb.set(section[i] === 0 ? [30, 30, 40] : COLORS[section[i]] ?? [255, 0, 255], i * 3);
|
||||
if (section[i] === 0 && Math.floor(i / size) < CHUNK_HEIGHT - 1 - SEA_LEVEL + 1) {
|
||||
// sky
|
||||
const row = Math.floor(i / size);
|
||||
if (row < CHUNK_HEIGHT - SEA_LEVEL) section_rgb.set([180, 210, 255], i * 3);
|
||||
}
|
||||
// sky, air from sea level up
|
||||
if (section[i] === 0 && Math.floor(i / size) < shape.max_y - SEA_LEVEL) section_rgb.set([180, 210, 255], i * 3);
|
||||
}
|
||||
await write_png(`${out}/section.png`, size, CHUNK_HEIGHT, section_rgb);
|
||||
await write_png(`${out}/section.png`, size, shape.height, section_rgb);
|
||||
|
||||
console.log(`blocks.png: ${chunks * chunks} chunks, ${(took / (chunks * chunks)).toFixed(2)} ms per chunk`);
|
||||
console.log(`underground air: ${(underground_air / (solid + underground_air) * 100).toFixed(1)}% of the ground`);
|
||||
|
||||
Reference in New Issue
Block a user