Add natural mob spawning for rotwalker
This commit is contained in:
@@ -35,6 +35,9 @@ export interface SavedMob extends SavedLivingEntity {
|
||||
drop_chances?: Partial<Record<EquipmentSlot, number>>;
|
||||
}
|
||||
|
||||
// what natural spawning counts a mob as, like minecraft's MobCategory
|
||||
export type MobCategory = "monster" | "creature";
|
||||
|
||||
export abstract class Mob extends LivingEntity {
|
||||
// doesn't think or move at all, not even falling
|
||||
no_ai = false;
|
||||
@@ -75,6 +78,10 @@ export abstract class Mob extends LivingEntity {
|
||||
];
|
||||
}
|
||||
|
||||
get category(): MobCategory {
|
||||
return "creature";
|
||||
}
|
||||
|
||||
#registered_goals = false;
|
||||
|
||||
// adds the kind's goals, see goals.ts. runs before its first thought, once the kind's fields are set
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
RandomLookAroundGoal,
|
||||
RandomStrollGoal,
|
||||
} from "./goals.ts";
|
||||
import { Mob } from "./mob.ts";
|
||||
import { Mob, type MobCategory } from "./mob.ts";
|
||||
|
||||
// the entity's class. the attributes are read while LivingEntity is being built, before any field of a subclass is
|
||||
// set, so each kind gets its own class that has its json already
|
||||
@@ -32,6 +32,10 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
|
||||
override height = json.height;
|
||||
override eye_height = json.height * 0.85;
|
||||
|
||||
override get category(): MobCategory {
|
||||
return monster ? "monster" : "creature";
|
||||
}
|
||||
|
||||
override default_attributes(): [AttributeType, number?][] {
|
||||
return [
|
||||
...super.default_attributes(),
|
||||
|
||||
@@ -74,6 +74,7 @@ import {
|
||||
import { Mob } from "./entity/mob.ts";
|
||||
import { LivingEntity } from "./entity/living_entity.ts";
|
||||
import { EntityManager } from "./entity/entity_manager.ts";
|
||||
import { NaturalSpawner } from "./natural_spawner.ts";
|
||||
import { create_entity, entity_type_ids } from "./entity/entity_types.ts";
|
||||
import { DAMAGE, type DamageSource, type SavedEntity } from "./entity/entity.ts";
|
||||
import { ATTRIBUTES } from "./entity/attributes.ts";
|
||||
@@ -170,6 +171,10 @@ export class GameServer {
|
||||
entities: EntityManager;
|
||||
mods: ModRuntime;
|
||||
recipes: RecipeBook;
|
||||
// monsters spawning on their own near players, see natural_spawner.ts
|
||||
spawner: NaturalSpawner;
|
||||
// minecraft's doMobSpawning game rule. tests turn it off so nothing turns up they didn't put there
|
||||
do_mob_spawning = true;
|
||||
// what runs tick(), for /tps. tests call tick() themselves
|
||||
loop?: GameLoop;
|
||||
// how long a tick can spend building chunks for players. tests lift it so what gets sent doesn't depend on speed
|
||||
@@ -180,6 +185,7 @@ export class GameServer {
|
||||
this.#mods = mods;
|
||||
this.mods = mods.runtime;
|
||||
this.recipes = mods.recipes;
|
||||
this.spawner = new NaturalSpawner(mods.recipes.spawns);
|
||||
|
||||
const saved: SavedLevel | SavedLevelV4 | undefined = save?.level ? JSON.parse(save.level) : undefined;
|
||||
if (saved && saved.version !== 5 && saved.version !== 4) {
|
||||
@@ -1517,6 +1523,7 @@ export class GameServer {
|
||||
|
||||
// like minecraft: entities only move near players, and players pick up items by walking into them
|
||||
#tick_entities() {
|
||||
if (this.do_mob_spawning) this.spawner.tick(this, SIMULATION_DISTANCE);
|
||||
this.entities.tick((entity) => this.#near_any_player(entity.x, entity.z));
|
||||
const items = this.item_entities();
|
||||
for (const player of this.#players.values()) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// a Map that forgets the least recently used entries past max_size
|
||||
export class LruMap<K, V> {
|
||||
#map = new Map<K, V>();
|
||||
#newest: K | undefined;
|
||||
readonly max_size: number;
|
||||
|
||||
constructor(max_size: number) {
|
||||
@@ -9,7 +10,10 @@ export class LruMap<K, V> {
|
||||
|
||||
get(key: K): V | undefined {
|
||||
const value = this.#map.get(key);
|
||||
// already the most recent, the same key over and over is common
|
||||
if (key === this.#newest) return value;
|
||||
if (value !== undefined) {
|
||||
this.#newest = key;
|
||||
// maps keep insertion order, so re-inserting moves it to the back
|
||||
this.#map.delete(key);
|
||||
this.#map.set(key, value);
|
||||
@@ -18,6 +22,7 @@ export class LruMap<K, V> {
|
||||
}
|
||||
|
||||
set(key: K, value: V) {
|
||||
this.#newest = key;
|
||||
this.#map.delete(key);
|
||||
this.#map.set(key, value);
|
||||
if (this.#map.size > this.max_size) {
|
||||
@@ -25,6 +30,11 @@ export class LruMap<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
// without counting as a use
|
||||
has(key: K) {
|
||||
return this.#map.has(key);
|
||||
}
|
||||
|
||||
delete(key: K) {
|
||||
this.#map.delete(key);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
// monsters spawning on their own near players, like minecraft's NaturalSpawner: every tick, one try in each chunk
|
||||
// around players while there's room under the monster cap. what spawns comes from mods' worldgen/spawns.json (see
|
||||
// SpawnJson), the way undergarden's biomes list its rotspawn
|
||||
import { CHUNK_SIZE } from "$/common/constants.ts";
|
||||
import type { SpawnJson } from "$/common/mod_data.ts";
|
||||
import { daylight } from "$/common/time.ts";
|
||||
import { chunk_key } from "$/common/utils.ts";
|
||||
import type { EntityManager } from "./entity/entity_manager.ts";
|
||||
import { create_entity } from "./entity/entity_types.ts";
|
||||
import { Mob } from "./entity/mob.ts";
|
||||
import type { ServerPlayer } from "./player.ts";
|
||||
import type { ServerWorld } from "./world.ts";
|
||||
|
||||
// minecraft's MONSTER category: 70 for the 17x17 chunks around a player, fewer when fewer chunks are around
|
||||
const MONSTER_CAP = 70;
|
||||
const CAP_AREA = 17 * 17;
|
||||
// how far from a player monsters count towards their own cap, in chunks
|
||||
const CAP_CHUNKS = 8;
|
||||
// never this close to a player or to the world spawn
|
||||
const MIN_DISTANCE = 24;
|
||||
// monsters further than this from every player despawn straight away, see Mob.check_despawn
|
||||
const MAX_DISTANCE = 128;
|
||||
// a try is up to 3 groups, each up to 4 spots wandering from the first, and makes at most 4 mobs
|
||||
const GROUPS = 3;
|
||||
const GROUP_SPOTS = 4;
|
||||
const CLUSTER_SIZE = 4;
|
||||
// how far each spot in a group is from the one before, at most, in x and in z
|
||||
const WANDER = 6;
|
||||
// how much darker the sky is at midnight, minecraft's skyDarken
|
||||
const NIGHT_DARKEN = 11;
|
||||
// the light monsters spawn in is at most a random level up to this, and there's no block light at all
|
||||
const MONSTER_LIGHT = 7;
|
||||
// how far light comes from, see ServerWorld.light_at
|
||||
const LIGHT_REACH = 15;
|
||||
|
||||
// what spawning needs from the game server
|
||||
export interface SpawnerHost {
|
||||
readonly world: ServerWorld;
|
||||
readonly entities: EntityManager;
|
||||
players(): ServerPlayer[];
|
||||
}
|
||||
|
||||
export class NaturalSpawner {
|
||||
readonly spawns: readonly SpawnJson[];
|
||||
// Math.random, tests replace it
|
||||
random: () => number = Math.random;
|
||||
|
||||
constructor(spawns: readonly SpawnJson[]) {
|
||||
this.spawns = spawns.filter((spawn) => spawn.weight > 0);
|
||||
}
|
||||
|
||||
// tries the chunks within distance chunks of a player that their client has, like minecraft's loaded chunks. the
|
||||
// server keeps fewer chunks than players see, and building one takes long, so only ones it still has: using
|
||||
// them every tick keeps them, and the chunks sent further out are the ones it forgets
|
||||
tick(host: SpawnerHost, distance: number) {
|
||||
const players = host.players();
|
||||
if (this.spawns.length === 0 || players.length === 0) return;
|
||||
|
||||
const chunks = new Map<number, [number, number]>();
|
||||
for (const player of players) {
|
||||
const px = Math.floor(player.x / CHUNK_SIZE);
|
||||
const pz = Math.floor(player.z / CHUNK_SIZE);
|
||||
for (let cx = px - distance; cx <= px + distance; cx++) {
|
||||
for (let cz = pz - distance; cz <= pz + distance; cz++) {
|
||||
if (player.chunks.has(cx, cz) && host.world.keep_chunk(cx, cz)) {
|
||||
chunks.set(chunk_key(cx, cz), [cx, cz]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the monsters around, all together and near each player
|
||||
const cap = Math.floor(MONSTER_CAP * chunks.size / CAP_AREA);
|
||||
let count = 0;
|
||||
const near = new Map(players.map((player) => [player, 0]));
|
||||
const counted = (entity: Mob) => {
|
||||
count += 1;
|
||||
for (const player of players) {
|
||||
if (chunk_distance(player, entity.x, entity.z) <= CAP_CHUNKS) near.set(player, near.get(player)! + 1);
|
||||
}
|
||||
};
|
||||
for (const entity of host.entities.all()) {
|
||||
if (
|
||||
entity instanceof Mob && entity.category === "monster" && !entity.requires_persistence &&
|
||||
chunks.has(chunk_key(Math.floor(entity.x / CHUNK_SIZE), Math.floor(entity.z / CHUNK_SIZE)))
|
||||
) {
|
||||
counted(entity);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [cx, cz] of this.#shuffled([...chunks.values()])) {
|
||||
if (count >= cap) break;
|
||||
const middle_x = cx * CHUNK_SIZE + CHUNK_SIZE / 2;
|
||||
const middle_z = cz * CHUNK_SIZE + CHUNK_SIZE / 2;
|
||||
const room = players.some((player) =>
|
||||
chunk_distance(player, middle_x, middle_z) <= CAP_CHUNKS && near.get(player)! < MONSTER_CAP
|
||||
);
|
||||
if (room) this.spawn_in_chunk(host, cx, cz).forEach(counted);
|
||||
}
|
||||
}
|
||||
|
||||
// one try: a random spot in the chunk between the bottom of the world and just above its surface, then groups
|
||||
// wandering around it at that height, in chunks the server has only. returns what spawned
|
||||
spawn_in_chunk(host: SpawnerHost, chunk_x: number, chunk_z: number): Mob[] {
|
||||
const { world } = host;
|
||||
const start_x = chunk_x * CHUNK_SIZE + this.#int(CHUNK_SIZE);
|
||||
const start_z = chunk_z * CHUNK_SIZE + this.#int(CHUNK_SIZE);
|
||||
const y = this.#int(world.surface_height(start_x, start_z) + 2);
|
||||
if (y < 1 || world.has_collision(start_x, y, start_z)) return [];
|
||||
|
||||
const spawned: Mob[] = [];
|
||||
const world_spawn = world.spawn_point();
|
||||
for (let group = 0; group < GROUPS; group++) {
|
||||
let x = start_x;
|
||||
let z = start_z;
|
||||
let spawn: SpawnJson | undefined;
|
||||
let size = Math.ceil(this.random() * GROUP_SPOTS);
|
||||
for (let i = 0; i < size; i++) {
|
||||
x += this.#int(WANDER) - this.#int(WANDER);
|
||||
z += this.#int(WANDER) - this.#int(WANDER);
|
||||
const fx = x + 0.5;
|
||||
const fz = z + 0.5;
|
||||
const player = host.entities.nearest_player(fx, y, fz, Infinity);
|
||||
if (!player) continue;
|
||||
const distance = Math.hypot(player.x - fx, player.y - y, player.z - fz);
|
||||
if (distance <= MIN_DISTANCE) continue;
|
||||
if (Math.hypot(world_spawn.x - fx, world_spawn.y - y, world_spawn.z - fz) < MIN_DISTANCE) continue;
|
||||
if (!world.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE))) continue;
|
||||
if (!spawn) {
|
||||
spawn = this.#pick(world.biome_at(x, z));
|
||||
if (!spawn) break;
|
||||
size = spawn.min_count + this.#int(spawn.max_count - spawn.min_count + 1);
|
||||
}
|
||||
if (distance > MAX_DISTANCE || !spawns_in(spawn, world.biome_at(x, z))) continue;
|
||||
// in loaded chunks only, the light too, so trying never builds a chunk
|
||||
if (!world.has_chunks_around(x, z, LIGHT_REACH)) continue;
|
||||
if (!is_spawn_ground(world, x, y - 1, z)) continue;
|
||||
// before the rest since it's cheap, it doesn't change how likely spawning is
|
||||
if (spawn.chance !== undefined && this.random() >= spawn.chance) continue;
|
||||
const mob = create_entity(host.entities, spawn.entity);
|
||||
if (!(mob instanceof Mob)) return spawned;
|
||||
mob.set_position(fx, y, fz);
|
||||
if (!has_room(host.entities, mob) || !this.#dark_enough(world, x, y, z)) continue;
|
||||
mob.yaw = mob.head_yaw = this.random() * Math.PI * 2;
|
||||
host.entities.add_entity(mob);
|
||||
spawned.push(mob);
|
||||
if (spawned.length >= CLUSTER_SIZE) return spawned;
|
||||
}
|
||||
}
|
||||
return spawned;
|
||||
}
|
||||
|
||||
// like minecraft's Monster.isDarkEnoughToSpawn: less likely the more sky light, never with block light, and
|
||||
// darker than a random level. the sky's light counts for less at night
|
||||
#dark_enough(world: ServerWorld, x: number, y: number, z: number) {
|
||||
const { sky, block } = world.light_at(x, y, z);
|
||||
if (sky > this.#int(32)) return false;
|
||||
if (block > 0) return false;
|
||||
const darken = Math.floor((1 - daylight(world.time)) * NIGHT_DARKEN);
|
||||
return Math.max(sky - darken, block) <= this.#int(MONSTER_LIGHT + 1);
|
||||
}
|
||||
|
||||
// by weight, from the spawns of the biome
|
||||
#pick(biome: string): SpawnJson | undefined {
|
||||
const options = this.spawns.filter((spawn) => spawns_in(spawn, biome));
|
||||
let left = this.random() * options.reduce((total, spawn) => total + spawn.weight, 0);
|
||||
for (const spawn of options) {
|
||||
left -= spawn.weight;
|
||||
if (left < 0) return spawn;
|
||||
}
|
||||
return options.at(-1);
|
||||
}
|
||||
|
||||
#shuffled<T>(list: T[]): T[] {
|
||||
for (let i = list.length - 1; i > 0; i--) {
|
||||
const j = this.#int(i + 1);
|
||||
[list[i], list[j]] = [list[j], list[i]];
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// 0 to below n
|
||||
#int(n: number) {
|
||||
return Math.floor(this.random() * n);
|
||||
}
|
||||
}
|
||||
|
||||
function spawns_in(spawn: SpawnJson, biome: string) {
|
||||
return spawn.biomes === undefined || spawn.biomes.includes(biome);
|
||||
}
|
||||
|
||||
// in chunks, the further of x and z
|
||||
function chunk_distance(player: ServerPlayer, x: number, z: number) {
|
||||
return Math.max(
|
||||
Math.abs(Math.floor(player.x / CHUNK_SIZE) - Math.floor(x / CHUNK_SIZE)),
|
||||
Math.abs(Math.floor(player.z / CHUNK_SIZE) - Math.floor(z / CHUNK_SIZE)),
|
||||
);
|
||||
}
|
||||
|
||||
// like minecraft's ON_GROUND placement: a whole solid block to stand on that isn't too bright, so not leaves, glass
|
||||
// or a lamp
|
||||
function is_spawn_ground(world: ServerWorld, x: number, y: number, z: number) {
|
||||
const block = world.get_block_info(x, y, z);
|
||||
return block !== undefined && block.has_collision && world.light_opacity(x, y, z) === 15 &&
|
||||
(block.light_emission ?? 0) < 14;
|
||||
}
|
||||
|
||||
// nothing it would bump into and no water where its box is
|
||||
function has_room(entities: EntityManager, mob: Mob) {
|
||||
const half = mob.width / 2;
|
||||
for (let x = Math.floor(mob.x - half); x < mob.x + half; x++) {
|
||||
for (let y = Math.floor(mob.y); y < mob.y + mob.height; y++) {
|
||||
for (let z = Math.floor(mob.z - half); z < mob.z + half; z++) {
|
||||
if (entities.has_collision(x, y, z) || entities.is_liquid(x, y, z)) return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
+155
-2
@@ -1,5 +1,10 @@
|
||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import {
|
||||
block_light_emission,
|
||||
block_light_opacity,
|
||||
BlockRegistry,
|
||||
EverythingRegistry,
|
||||
} from "$/common/everything_registry.ts";
|
||||
import { generate_raw_chunk, RawChunk, WorldgenSetup } from "$/common/generation.ts";
|
||||
import { AIR_ID, BlockChange } from "$/common/protocol.ts";
|
||||
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
|
||||
@@ -12,6 +17,11 @@ import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, Save
|
||||
// generation only, rebuilt when needed. 256 KB each
|
||||
const RAW_CACHE_SIZE = 128;
|
||||
const CHUNK_CACHE_SIZE = 256;
|
||||
// surface and sky heights, 1 KB each
|
||||
const COLUMN_CACHE_SIZE = 1024;
|
||||
// light reaches at most this far, see light_at
|
||||
const LIGHT_REACH = 15;
|
||||
const LIGHT_BOX = LIGHT_REACH * 2 + 1;
|
||||
// how far from the middle of the world to look for dry land to spawn on, in chunks
|
||||
const SPAWN_SEARCH_CHUNKS = 32;
|
||||
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
|
||||
@@ -40,10 +50,17 @@ export class ServerWorld {
|
||||
readonly worldgen: WorldgenSetup | undefined;
|
||||
// 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
|
||||
#opacity: Uint8Array;
|
||||
#emission: Uint8Array;
|
||||
|
||||
// what generation made, and the final blocks with neighbors' leaves and player changes applied
|
||||
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
|
||||
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
|
||||
// what generation decided each column's biome is, kept for longer than the rest of it
|
||||
#biomes = new LruMap<number, string[]>(COLUMN_CACHE_SIZE);
|
||||
// per column of a chunk, the highest block that isn't air, then the lowest y that sees the sky. see #columns_of
|
||||
#columns = new LruMap<number, Int16Array>(COLUMN_CACHE_SIZE);
|
||||
|
||||
// changes from generated terrain, per chunk. saved as whole chunks
|
||||
#changes = new Map<number, Map<string, BlockChange>>();
|
||||
@@ -70,9 +87,14 @@ export class ServerWorld {
|
||||
constructor(seed: string, worldgen?: WorldgenSetup) {
|
||||
this.seed = seed;
|
||||
this.worldgen = worldgen;
|
||||
EverythingRegistry.get_registry<BlockRegistry>("blocks").forEach((block, nid) => {
|
||||
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
||||
this.#opacity = new Uint8Array(ID_MASK + 1);
|
||||
this.#emission = new Uint8Array(ID_MASK + 1);
|
||||
blocks.forEach((block, nid) => {
|
||||
this.block_ids[block.id] = nid;
|
||||
this.default_values[nid] = default_block_value(nid, block);
|
||||
this.#opacity[nid] = block_light_opacity(block);
|
||||
this.#emission[nid] = block_light_emission(block);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -141,6 +163,128 @@ export class ServerWorld {
|
||||
return nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
|
||||
}
|
||||
|
||||
// like "bworld:plains", what generation decided
|
||||
biome_at(x: number, z: number): string {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const biomes = this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes;
|
||||
return biomes[column_index(x, z)];
|
||||
}
|
||||
|
||||
// whether the chunk is built and kept, like a loaded chunk in minecraft. nothing builds one by asking
|
||||
has_chunk(chunk_x: number, chunk_z: number) {
|
||||
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
|
||||
}
|
||||
|
||||
// counts as using the chunk so it's kept longer, if it's there. returns whether it is, see has_chunk
|
||||
keep_chunk(chunk_x: number, chunk_z: number) {
|
||||
return this.#chunks.get(chunk_key(chunk_x, chunk_z)) !== undefined;
|
||||
}
|
||||
|
||||
// whether every chunk within radius blocks of x, z is, see has_chunk
|
||||
has_chunks_around(x: number, z: number, radius: number) {
|
||||
for (let cx = Math.floor((x - radius) / CHUNK_SIZE); cx <= Math.floor((x + radius) / CHUNK_SIZE); cx++) {
|
||||
for (let cz = Math.floor((z - radius) / CHUNK_SIZE); cz <= Math.floor((z + radius) / CHUNK_SIZE); cz++) {
|
||||
if (!this.has_chunk(cx, cz)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// how much light going through the block there loses, 0-15
|
||||
light_opacity(x: number, y: number, z: number) {
|
||||
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
|
||||
surface_height(x: number, z: number): number {
|
||||
return this.#columns_of(x, z)[column_index(x, z)];
|
||||
}
|
||||
|
||||
// the lowest y with nothing above it that stops light, where sky light is 15
|
||||
sky_height(x: number, z: number): number {
|
||||
return this.#columns_of(x, z)[CHUNK_AREA + column_index(x, z)];
|
||||
}
|
||||
|
||||
// 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
|
||||
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 };
|
||||
// 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);
|
||||
const chunks: (Uint32Array | undefined)[] = [];
|
||||
const skies: (Int16Array | undefined)[] = [];
|
||||
const box_index = (dx: number, dy: number, dz: number) =>
|
||||
((dy + LIGHT_REACH) * LIGHT_BOX + dz + LIGHT_REACH) * LIGHT_BOX + dx + LIGHT_REACH;
|
||||
// what light loses on its way from a block to the start. 255 is not reached yet
|
||||
const cost = new Uint8Array(LIGHT_BOX ** 3).fill(255);
|
||||
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;
|
||||
const at = box_index(dx, dy, dz);
|
||||
if (cost[at] <= next) return;
|
||||
cost[at] = next;
|
||||
queues[next].push(dx, dy, dz);
|
||||
};
|
||||
reach(0, 0, 0);
|
||||
|
||||
let sky = 0;
|
||||
let block = 0;
|
||||
for (let lost = 0; lost < LIGHT_REACH; lost++) {
|
||||
// nothing further away can be brighter than what's been found
|
||||
if (LIGHT_REACH - lost <= sky && LIGHT_REACH - lost <= block) break;
|
||||
const queue = queues[lost];
|
||||
for (let i = 0; i < queue.length; i += 3) {
|
||||
const dx = queue[i], dy = queue[i + 1], dz = queue[i + 2];
|
||||
if (cost[box_index(dx, dy, dz)] !== lost) continue;
|
||||
const bx = x + dx, by = y + dy, bz = z + dz;
|
||||
const chunk_x = Math.floor(bx / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(bz / CHUNK_SIZE);
|
||||
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);
|
||||
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]);
|
||||
if (next >= LIGHT_REACH) continue;
|
||||
reach(dx, dy - 1, dz);
|
||||
reach(dx, dy + 1, dz);
|
||||
reach(dx - 1, dy, dz);
|
||||
reach(dx + 1, dy, dz);
|
||||
reach(dx, dy, dz - 1);
|
||||
reach(dx, dy, dz + 1);
|
||||
}
|
||||
}
|
||||
return { sky, block };
|
||||
}
|
||||
|
||||
#columns_of(x: number, z: number) {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
let columns = this.#columns.get(key);
|
||||
if (!columns) {
|
||||
const blocks = this.#get_chunk(chunk_x, chunk_z);
|
||||
columns = new Int16Array(CHUNK_AREA * 2);
|
||||
for (let column = 0; column < CHUNK_AREA; column++) {
|
||||
let y = CHUNK_HEIGHT - 1;
|
||||
while (y >= 0 && (blocks[y * CHUNK_AREA + column] & ID_MASK) === AIR) y--;
|
||||
columns[column] = y;
|
||||
while (y >= 0 && this.#opacity[blocks[y * CHUNK_AREA + column] & ID_MASK] === 0) y--;
|
||||
columns[CHUNK_AREA + column] = y + 1;
|
||||
}
|
||||
this.#columns.set(key, columns);
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@@ -157,6 +301,8 @@ export class ServerWorld {
|
||||
const blocks = this.#get_chunk(chunk_x, chunk_z);
|
||||
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = value;
|
||||
|
||||
this.#columns.delete(chunk_key(chunk_x, chunk_z));
|
||||
|
||||
const state_bits = value >>> 16;
|
||||
this.#record_change(x, y, z, id, state_bits);
|
||||
this.dirty = true;
|
||||
@@ -221,6 +367,7 @@ export class ServerWorld {
|
||||
console.error(`Couldn't load chunk ${chunk_x}, ${chunk_z}: ${(e as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
this.#columns.delete(chunk_key(chunk_x, chunk_z));
|
||||
const generated = regenerate ? this.#generate_chunk(chunk_x, chunk_z) : undefined;
|
||||
// unknown ids, from mods that are gone, stay as changes so they come back with the mod
|
||||
const values = chunk.palette.map(([id, state]) => {
|
||||
@@ -359,6 +506,7 @@ export class ServerWorld {
|
||||
if (!raw) {
|
||||
raw = generate_raw_chunk(chunk_x, chunk_z, this.seed, this.block_ids, this.worldgen, this.default_values);
|
||||
this.#raw.set(key, raw);
|
||||
this.#biomes.set(key, raw.biomes);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -414,3 +562,8 @@ export class ServerWorld {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -100,6 +100,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
|
||||
items: entries(bmod.data.items),
|
||||
recipes: entries(bmod.data.recipes),
|
||||
ores: entries(bmod.data.ores),
|
||||
spawns: entries(bmod.data.spawns),
|
||||
entities: entries(bmod.data.entities),
|
||||
entity_models: entries(bmod.data.entity_models),
|
||||
tags: entries(bmod.data.tags),
|
||||
|
||||
Reference in New Issue
Block a user