import { CHUNK_HEIGHT, CHUNK_SIZE, FACE_OFFSETS, Faces, faces, PLAYER_WIDTH, TICK_DELTA, TICKS_PER_SECOND, } from "$/common/constants.ts"; import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { LiquidFlow } from "./liquids.ts"; import { Container, ItemData, ItemStack } from "$/common/inventory.ts"; import { AIR_ID, ClientMessage, MAX_CHAT_LENGTH, MAX_NAME_LENGTH, PROTOCOL_VERSION, ServerMessage, } from "$/common/protocol.ts"; import type { ModListing, RecipeBook } from "$/common/mod_loader.ts"; import type { WorldgenSetup } from "$/common/generation.ts"; import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.ts"; import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts"; import { block_states, box_overlaps_block, can_place, can_stand_on, display_name, is_waterlogged, liquid_block, placement_target, set_state_value, waterlog_placement, } from "$/common/utils.ts"; import { collision_shape_at, type Shape } from "$/common/block_shapes.ts"; import { EXHAUSTION } from "./vitals.ts"; import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts"; import type { LootContext } from "$/common/mod_api/server.ts"; import type { EntityJson } from "$/common/mod_data.ts"; import { argument, choice, type CommandContext, CommandError, type CommandNode, integer, item, literal, number, word, } from "$/common/commands.ts"; import { estimate_biome } from "$/common/worldgen/overworld.ts"; import { biome_ids, get_biome } from "$/common/worldgen/biomes.ts"; import type { GameLoop } from "./game_loop.ts"; import { update_crafting_result } from "./crafting.ts"; import type { Menu } from "./menu.ts"; import { SavedPlayer, ServerPlayer } from "./player.ts"; import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts"; import { ServerWorld, Tile } from "./world.ts"; import type { WorldSave } from "./saves.ts"; import { BLOCK_DROP_PICKUP_DELAY, ITEM_ENTITY_TYPE, ITEM_SIZE, ItemEntity, PLAYER_DROP_PICKUP_DELAY, type SavedItemEntity, } from "./entity/item_entity.ts"; 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_source, type DamageSource, type SavedEntity } from "./entity/entity.ts"; import { effect_type, effect_type_ids, EffectInstance } from "./entity/effects.ts"; import { ATTRIBUTES } from "./entity/attributes.ts"; // how far from a player's eyes a block can be changed, a bit more than the client's reach const MAX_REACH = 8; // how far past a player's box items get picked up from, sideways and up or down, like minecraft const PICKUP_REACH_XZ = 1; const PICKUP_REACH_Y = 0.5; // tiles further than this many chunks from every player don't tick const SIMULATION_DISTANCE = 6; const MAX_GIVE = 64 * 36; // /locatebiome looks at columns this far apart, out to this far, like minecraft's const LOCATE_STEP = 32; const LOCATE_RADIUS = 6400; // the most suggestions sent for one request const MAX_SUGGESTIONS = 100; // falls up to this many blocks don't hurt, like minecraft const SAFE_FALL = 3; // faster than walking (4.3 blocks a second) and slower than sprinting (5.6) const SPRINT_SPEED = 5; // moving further than this at once is a teleport, not a fall const TELEPORT_DISTANCE = 20; // how close feet have to be to a block's top to stand on it const GROUND_EPSILON = 0.02; // the most mornings run at once after time jumps forward, the rest are skipped const MAX_CATCH_UP_DAYS = 64; // how long a client gets between welcome and ready to download and load everything const READY_TIMEOUT_TICKS = 60 * TICKS_PER_SECOND; // the furthest the server sends chunks around a player, and what players who don't say get, until /viewdistance // changes it const SERVER_VIEW_DISTANCE = 16; // how long a tick can spend building chunks for players, the rest go out on the next ticks const CHUNK_SEND_BUDGET_MS = 20; // everything the game server needs from whatever runs it export interface GameHost { // text is a json message, bytes a binary one (level_chunk) send(conn: number, data: string | Uint8Array): void; close(conn: number): void; // fetches a url, failing with a message for players when it can't or it's more than max_bytes download(url: string, max_bytes: number): Promise; } // level.json, everything saved but the blocks, which are in region files (see saves.ts) export interface SavedLevel { version: 5; seed: string; // see ServerWorld.worldgen_fingerprint worldgen: string; // world time in ticks time: number; tiles: SavedTile[]; // every ctx.containers container, by id containers: Record; players: Record; // every entity, see entity/entity.ts. version 4 had only items, with their own fields entities: SavedEntity[]; // ctx.storage of every mod, by mod id mod_storage: Record>; } interface SavedTile { id: string; x: number; y: number; z: number; // what BlockRef.data holds mod_data?: unknown; // what it shows, see ServerWorld.set_block_item in the mod api item?: ItemData; } // the loaded mods, see load_mods.ts export interface GameMods { listings: ModListing[]; recipes: RecipeBook; worldgen?: WorldgenSetup; runtime: ModRuntime; } export class GameServer { world: ServerWorld; #host: GameHost; #players = new Map(); // connections that got welcome and are downloading mods, by conn #pending = new Map(); // which player gets chunks first next tick, so one with a lot to load doesn't always use up the budget #next_chunk_player = 0; #saved_players: Record = {}; #tick = 0; // the last morning new day handlers ran for #day = 0; #mods: GameMods; // ctx.containers, saved with the world containers = new Map(); // everything in the world that isn't a block or a player entities: EntityManager; mods: ModRuntime; recipes: RecipeBook; // monsters spawning on their own near players, see natural_spawner.ts spawner: NaturalSpawner; // water and other liquids flowing, see liquids.ts liquids: LiquidFlow; // minecraft's doMobSpawning game rule. tests turn it off so nothing turns up they didn't put there do_mob_spawning = true; // what runs tick(), for /tps. tests call tick() themselves loop?: GameLoop; // SERVER_VIEW_DISTANCE, or what /viewdistance set it to. not saved, it's for testing view_distance = SERVER_VIEW_DISTANCE; // how long a tick can spend building chunks for players. tests lift it so what gets sent doesn't depend on speed chunk_send_budget_ms = CHUNK_SEND_BUDGET_MS; constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) { this.#host = host; 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) { throw new Error( `The world was saved in format ${ (saved as { version: unknown }).version }, this server only loads formats 4 and 5`, ); } this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen); this.liquids = new LiquidFlow({ value_at: (x, y, z) => { if (y < 0 || y >= CHUNK_HEIGHT) return undefined; const loaded = this.world.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); return loaded ? this.world.get_block_value(x, y, z) : undefined; }, block: (nid) => EverythingRegistry.get_by_id("blocks", nid), nid: (id) => this.world.block_ids[id], set_block: (x, y, z, id, state) => { // a level changing is only a state, the block's components don't see it come and go if (id === this.world.get_block_id(x, y, z)) this.set_block_state(x, y, z, state); else this.set_block(x, y, z, id, undefined, state); }, }); // deno-lint-ignore no-this-alias const game = this; this.entities = new EntityManager({ get world() { return game.world; }, get current_tick() { return game.#tick; }, players: () => this.players(), send: (player, message) => this.#send(player, message), hurt_player: (player, amount, source) => this.hurt_player(player, amount, source), on_entity_death: (entity, source) => { if (entity instanceof ServerPlayer) this.#kill(entity, source); }, entity_loot: (entity, source) => { const table = EverythingRegistry.get("entities", entity.type)?.loot_table; if (!table) return []; const killer = source.attacker instanceof ServerPlayer ? source.attacker : undefined; return this.roll_loot(table, { position: { x: entity.x, y: entity.y, z: entity.z }, entity: entity_ref(entity), killed_by_player: source.by_player === true, player: killer && this.mods.player(killer), tool: killer && this.mods.player(killer).held_item, }); }, }); this.mods.storage = upgrade_mod_storage(saved?.mod_storage ?? {}); if (saved) { this.world.load_chunks(save?.chunks ?? [], saved.worldgen); } this.world.time = saved?.time ?? 0; this.#day = this.world.day; for (const [id, items] of Object.entries(saved?.containers ?? {})) { const container = new Container(items.length); container.load(items); this.containers.set(id, container); } for (const tile of saved?.tiles ?? []) { this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: tile.mod_data, item: tile.item, }); } this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []); this.#saved_players = saved?.players ?? {}; // a new world is saved straight away, and a loaded one when load_chunks had to save chunks again this.world.dirty = !saved || this.world.has_unsaved_chunks(); this.#register_commands(); // players without the chunk get the block with it when they do, like minecraft this.world.on_block_change = (x, y, z, id, state) => { this.liquids.changed(x, y, z, this.#tick); const data = JSON.stringify( (state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id }) satisfies ServerMessage, ); for (const player of this.#players.values()) { if (player.chunks.has_block(x, z)) { this.#host.send(player.conn, data); } } }; this.world.on_tile_item_change = (x, y, z, item) => { const data = JSON.stringify( { type: "set_block_item", x, y, z, item: item ?? null } satisfies ServerMessage, ); for (const player of this.#players.values()) { if (player.chunks.has_block(x, z)) { this.#host.send(player.conn, data); } } }; } // connections on_connect(_conn: number) {} on_disconnect(conn: number) { this.#pending.delete(conn); const player = this.#players.get(conn); if (!player) { return; } this.#close_menu(player); this.#saved_players[player.name] = player.save_player(); this.world.dirty = true; this.#players.delete(conn); // mobs after them give up player.remove(); this.entities.stop_tracking(player); this.mods.after.player_leave.emit({ player: this.mods.player(player) }); this.#broadcast({ type: "player_leave", id: player.id }); this.#broadcast({ type: "chat", text: `${player.name} left` }); console.log(`${player.name} left (${this.#players.size} online)`); } on_message(conn: number, data: string) { let message: ClientMessage; try { message = JSON.parse(data); } catch { return; } if (typeof message !== "object" || message === null) { return; } const player = this.#players.get(conn); if (!player) { this.#handshake(conn, message); return; } this.#handle(player, message); this.#sync(player); } // game loop, the host calls this TICKS_PER_SECOND times a second tick() { this.#tick += 1; this.world.time += 1; const second = this.#tick % TICKS_PER_SECOND === 0; if (second) { this.#broadcast({ type: "time", time: this.world.time }); } for (const tile of [...this.world.tiles.values()]) { if (tile.mod_data === undefined) { continue; } const components = this.mods.components_of(tile.id) .filter(({ component }) => component.on_tick || component.on_second); if (components.length === 0 || !this.#near_any_player(tile.x, tile.z)) { continue; } const block = this.mods.block_ref(tile.x, tile.y, tile.z, tile.id); for (const { mod, id, component, params } of components) { if (component.on_tick) { run_guarded(mod, `${id} on_tick`, () => component.on_tick!(block, params, TICK_DELTA)); } if (second && component.on_second) { run_guarded(mod, `${id} on_second`, () => component.on_second!(block, params, 1)); } } // tile data can change on any tick, saving is cheap enough to not track it exactly this.world.dirty = true; } this.#new_days(); this.liquids.tick(this.#tick); this.#tick_vitals(); this.#tick_entities(); this.mods.tick(); this.#tick_menus(); this.mods.check_watched_containers(); for (const [conn, pending] of this.#pending) { if (this.#tick - pending.since > READY_TIMEOUT_TICKS) { this.#pending.delete(conn); this.#reject(conn, "Took too long to load the server's mods"); } } this.entities.sync(); for (const player of this.#players.values()) { this.#sync_worn(player); this.#sync(player); } this.#send_chunks(); } // level.json and the chunks changed since the last save save(): Required { for (const player of this.#players.values()) { this.#saved_players[player.name] = player.save_player(); } const level: SavedLevel = { version: 5, seed: this.world.seed, worldgen: this.world.worldgen_fingerprint(), time: this.world.time, tiles: [...this.world.tiles.values()].map((tile) => ({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: tile.mod_data, item: tile.item, })), containers: Object.fromEntries( [...this.containers].map(([id, container]) => [id, container.to_data()]), ), players: this.#saved_players, entities: this.entities.save(), mod_storage: this.mods.storage, }; this.world.dirty = false; return { level: JSON.stringify(level), chunks: this.world.save_chunks() }; } // used by block behaviors and mods get current_tick() { return this.#tick; } // the furthest the server sends chunks to anyone, for now. players who asked for more get more, up to it set_view_distance(distance: number) { this.view_distance = distance; for (const player of this.players()) { player.chunks.view_distance = view_distance(player.requested_view_distance, distance); this.#update_view(player, true); } } players(): ServerPlayer[] { return [...this.#players.values()]; } give(player: ServerPlayer, id: string, count: number, data?: unknown) { // split into stacks so max stack sizes are respected let left = count; while (left > 0) { const stack = new ItemStack(id); stack.amount = Math.min(left, stack.max_amount); if (data !== undefined) stack.data = structuredClone(data); left -= stack.amount; this.give_stack(player, stack); } } // into the inventory, whatever doesn't fit drops at the player's feet give_stack(player: ServerPlayer, stack: ItemStack) { if (player.inventory.add_item(stack) > 0) { this.spawn_item(player.x, player.y, player.z, stack, PLAYER_DROP_PICKUP_DELAY); } } spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { const entity = this.entities.spawn_item(x, y, z, stack, pickup_delay); this.world.dirty = true; return entity; } // like minecraft's Block.popResource: from a bit off the block's middle, flying up and out a little pop_item(x: number, y: number, z: number, stack: ItemStack) { const spread = () => (Math.random() - 0.5) * 0.5; const entity = this.spawn_item( x + 0.5 + spread(), y + 0.5 - ITEM_SIZE / 2 + spread(), z + 0.5 + spread(), stack, BLOCK_DROP_PICKUP_DELAY, ); entity.vx = (Math.random() - 0.5) * 4; entity.vy = 4; entity.vz = (Math.random() - 0.5) * 4; return entity; } // out of the player's face the way they're looking, like minecraft's Player.drop throw_item(player: ServerPlayer, stack: ItemStack) { const entity = this.spawn_item( player.x, player.y + player.eye_height - 0.3, player.z, stack, PLAYER_DROP_PICKUP_DELAY, ); // minecraft's numbers are per tick const speed = 0.3 * TICKS_PER_SECOND; const cos_pitch = Math.cos(player.pitch); const spread_angle = Math.random() * Math.PI * 2; const spread = Math.random() * 0.02 * TICKS_PER_SECOND; entity.vx = -Math.sin(player.yaw) * cos_pitch * speed + Math.cos(spread_angle) * spread; entity.vy = Math.sin(player.pitch) * speed + (0.1 + (Math.random() - Math.random()) * 0.1) * TICKS_PER_SECOND; entity.vz = -Math.cos(player.yaw) * cos_pitch * speed + Math.sin(spread_angle) * spread; return entity; } item_entities(): ItemEntity[] { return this.entities.all().filter((entity) => entity instanceof ItemEntity); } send_chat(player: ServerPlayer, text: string) { this.#send(player, { type: "chat", text }); } // a mod's server script to its client script, see ctx.net send_mod_message(player: ServerPlayer, channel: string, data: unknown) { this.#send(player, { type: "mod", channel, data }); } teleport(player: ServerPlayer, x: number, y: number, z: number) { Object.assign(player, { x, y, z }); player.fall_distance = 0; player.stop_knockback(); this.#place(player); } // tells their client where they are now (and how fast they're going, while the server moves them), and everyone // else where they are #place(player: ServerPlayer, motion?: [number, number, number]) { const { x, y, z } = player; player.teleport_id += 1; this.#send(player, { type: "teleport", id: player.teleport_id, x, y, z, ...(motion && { motion }) }); this.#update_view(player); this.#broadcast(player_move(player), player); } set_time(time: number) { this.world.time = time; this.world.dirty = true; this.#broadcast({ type: "time", time }); // going back in time doesn't repeat mornings, going forward runs the ones skipped (see #new_days) this.#day = Math.min(this.#day, this.world.day); } // every morning that came since the last tick, usually none or one. /time can skip many #new_days() { const today = this.world.day; if (today <= this.#day) { return; } const first = Math.max(this.#day + 1, today - MAX_CATCH_UP_DAYS + 1); for (let day = first; day <= today; day++) { this.#new_day(day); } this.#day = today; } // every block with data runs on_new_day, wherever it is, so crops grow while nobody's around #new_day(day: number) { for (const tile of [...this.world.tiles.values()]) { if (tile.mod_data === undefined) { continue; } const components = this.mods.components_of(tile.id).filter(({ component }) => component.on_new_day); if (components.length === 0) { continue; } const block = this.mods.block_ref(tile.x, tile.y, tile.z, tile.id); for (const { mod, id, component, params } of components) { run_guarded(mod, `${id} on_new_day`, () => component.on_new_day!(block, params, day)); } } this.mods.after.new_day.emit({ day }); this.world.dirty = true; } // changes a block's state bits without anything else happening, see ServerWorld.get_block_value set_block_state(x: number, y: number, z: number, state: number) { const id = this.world.get_block_id(x, y, z); if (id !== AIR_ID && this.world.get_block_value(x, y, z) >>> 16 !== state) { this.world.set_block(x, y, z, id, state); this.#notify_neighbors(x, y, z); } } // tells the blocks around one that changed, so they can change with it like a fence joining it, see BlockRules #notify_neighbors(x: number, y: number, z: number) { this.mods.rules.notify_neighbors((bx, by, bz) => this.world.get_block_id(bx, by, bz), x, y, z); } set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) { const old_id = this.world.get_block_id(x, y, z); if (old_id !== AIR_ID) { const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break); if (components.length > 0) { const block = this.mods.block_ref(x, y, z, old_id); const player_api = player && this.mods.player(player); for (const { mod, id: component_id, component, params } of components) { run_guarded(mod, `${component_id} on_break`, () => component.on_break!(block, params, player_api)); } } } this.world.remove_tile(x, y, z); this.world.set_block(x, y, z, id, state); if (id !== AIR_ID) { const block = this.mods.block_ref(x, y, z, id); for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) { if (component.on_create) { run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params)); } } } this.#notify_neighbors(x, y, z); // 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) { 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); } } } // what a loot table gives, ready to drop. a table that can't be rolled is logged and gives nothing, so a broken // table never stops a block breaking or a mob dying roll_loot(table: string, context: LootContext): ItemStack[] { try { return this.mods.loot.roll(table, context).map(new_stack); } catch (e) { console.error(`Couldn't roll loot table ${table}:`, e); return []; } } // breaks a block the way breaking it by hand does: its components' on_break, then what it drops. without the // right tool of a high enough tier (or without a player) blocks that need one drop nothing destroy_block(x: number, y: number, z: number, player?: ServerPlayer) { const info = this.world.get_block_info(x, y, z); if (!info) { return; } const held = EverythingRegistry.get("items", player?.held_item?.type_id ?? ""); const tool = held?.tool; const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0); const drops = !info.requires_tool || right_tool; const value = this.world.get_block_value(x, y, z); // rolled while it's still there, for its states const loot = drops && info.loot_table ? this.roll_loot(info.loot_table, { position: { x: x + 0.5, y: y + 0.5, z: z + 0.5 }, block: { id: info.id, x, y, z, states: block_states(value, info) }, player: player && this.mods.player(player), tool: player && this.mods.player(player).held_item, }) : drops && info.drop_table ? [new ItemStack(info.drop_table)] : []; // a waterlogged block leaves its liquid behind, a source const liquid = is_waterlogged(value, info) ? liquid_block(value, info) : undefined; this.set_block(x, y, z, liquid?.id ?? AIR_ID, player); for (const stack of loot) this.pop_item(x, y, z, stack); } get_or_create_tile(x: number, y: number, z: number): Tile { let tile = this.world.get_tile(x, y, z); if (!tile) { tile = { id: this.world.get_block_id(x, y, z), x, y, z }; this.world.add_tile(tile); } return tile; } // containers create_container(size: number): { id: string; container: Container } { const id = crypto.randomUUID(); const container = new Container(size); this.containers.set(id, container); this.world.dirty = true; return { id, container }; } // anyone with a menu showing it gets it closed delete_container(id: string) { const container = this.containers.get(id); if (!container) { return; } this.containers.delete(id); this.world.dirty = true; for (const player of this.#players.values()) { if (player.menu?.uses(container)) { this.close_menu(player); } } } // menus // the id a new menu for this player gets, 1 to 100 and around, like minecraft's containerCounter next_menu_id(player: ServerPlayer): number { player.menu_id = player.menu_id % 100 + 1; return player.menu_id; } // replaces whatever they had open open_menu(player: ServerPlayer, menu: Menu) { this.#close_menu(player); player.menu = menu; const data = menu.data_values(); this.#send(player, { type: "open_menu", id: menu.id, menu_type: menu.type, title: menu.title, open_data: menu.open_data, slots: menu.slot_info(), data, }); player.sent.set("menu_data", JSON.stringify(data)); player.sent.delete("menu_content"); } // closes it for the player too, not just on the server close_menu(player: ServerPlayer) { const menu = player.menu; if (!menu) { return; } this.#close_menu(player); this.#send(player, { type: "close_menu", id: menu.id }); } // version 2 saves had chests and furnaces in the engine, with their fields in data and their items in // containers.main. the components keep those fields and put the items in a ctx.containers container // messages // hello -> welcome, then ready -> join. see docs/modding/networking/index.md #handshake(conn: number, message: ClientMessage) { if (message.type === "hello") { if (this.#pending.has(conn)) { return; } if (message.protocol !== PROTOCOL_VERSION) { this.#reject( conn, `This server needs a game version with protocol ${PROTOCOL_VERSION}, yours has ${ message.protocol ?? "none" }. Reload the page to update.`, ); return; } this.#pending.set(conn, { name: message.name, since: this.#tick }); this.#host.send( conn, JSON.stringify( { type: "welcome", protocol: PROTOCOL_VERSION, mods: this.#mods.listings, } satisfies ServerMessage, ), ); return; } if (message.type === "ready") { const pending = this.#pending.get(conn); if (!pending) { return; } this.#pending.delete(conn); this.#join(conn, pending.name, message.view_distance); } } #reject(conn: number, reason: string) { this.#host.send(conn, JSON.stringify({ type: "rejected", reason } satisfies ServerMessage)); this.#host.close(conn); } #join(conn: number, raw_name: unknown, requested_view_distance: unknown) { const player = new ServerPlayer( this.entities, conn, this.#unique_name(raw_name), view_distance(requested_view_distance, this.view_distance), () => this.recipes.shaped, ); if (is_int(requested_view_distance)) player.requested_view_distance = requested_view_distance; const saved = this.#saved_players[player.name]; if (saved) { player.load_player(saved); } else { Object.assign(player, this.world.spawn_point()); } this.mods.extend_player_menu(player); this.#send(player, { type: "join", id: player.id, name: player.name, players: [...this.#players.values()].map((p) => p.player_info()), entities: this.entities.start_tracking(player), blocks: this.world.block_table(), 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 } : {}) })), time: this.world.time, }); this.#players.set(conn, player); // what they wear themselves, the others get it with player_join player.worn_sent = JSON.stringify(player.worn_list()); if (player.worn_sent !== "[]") { this.#send(player, { type: "player_worn", id: player.id, worn: player.worn_list() }); } // and their own skin, from when they last played if (player.skin) { this.#send(player, { type: "player_skin", id: player.id, skin: player.skin, slim: player.slim || undefined, }); } // the chunks come with the next ticks this.#update_view(player); this.#sync(player); this.#broadcast({ type: "player_join", player: player.player_info() }, player); this.#broadcast({ type: "chat", text: `${player.name} joined` }); this.mods.after.player_join.emit({ player: this.mods.player(player) }); console.log(`${player.name} joined (${this.#players.size} online)`); } #handle(player: ServerPlayer, message: ClientMessage) { switch (message.type) { case "move": { const { x, y, z, yaw, pitch } = message; if (![x, y, z, yaw, pitch].every(is_number)) { return; } // the server is moving them, or it's from before the last time it did const stale = is_number(message.teleport) && message.teleport < player.teleport_id; if (player.knockback_ticks !== undefined || stale) { return; } this.#on_move(player, x, y, z); Object.assign(player, { x, y, z, yaw, pitch }); player.set_swimming(message.swimming === true); this.#broadcast(player_move(player), player); this.#update_view(player); break; } case "view_distance": if (is_int(message.distance)) { player.requested_view_distance = message.distance; player.chunks.view_distance = view_distance(message.distance, this.view_distance); this.#update_view(player, true); } break; case "chunk_batch_received": if (is_number(message.chunks_per_tick)) { player.chunks.on_batch_received(message.chunks_per_tick); } break; case "break_block": if (is_block_position(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)) { this.#hit_block(player, message.x, message.y, message.z); } break; case "attack_entity": if (typeof message.id === "string") { this.#attack_entity(player, message.id); } break; case "swing": player.attack_strength_ticker = 0; break; case "use_item": this.#use_item(player); break; case "use_block": if (is_block_position(message.x, message.y, message.z) && faces.includes(message.face)) { // the middle of the block when a client doesn't say, or says something that isn't on it const hit = Array.isArray(message.hit) && message.hit.length === 3 && message.hit.every((v) => typeof v === "number" && v >= 0 && v <= 1) ? message.hit : [0.5, 0.5, 0.5]; this.#use_block(player, message.x, message.y, message.z, message.face, hit); } this.#ack(player, message.seq); break; case "select_slot": if (is_int(message.slot) && message.slot >= 0 && message.slot < 9) { if (message.slot !== player.selected_slot) player.attack_strength_ticker = 0; player.selected_slot = message.slot; } break; case "click": this.#click(player, message.menu, message.slot, message.button, message.shift === true); break; case "drop_item": this.#drop_item(player, message.menu, message.slot, message.all === true); break; case "menu_button": if (player.menu && message.menu === player.menu.id && is_int(message.button)) { this.mods.menu_button(player, player.menu, message.button); } break; case "close_menu": // one that's already gone, the server closed it, or menu 0: the inventory screen if (message.menu === (player.menu?.id ?? 0)) { this.#close_menu(player); } break; case "chat": this.#chat(player, message.text); break; case "suggest": this.#suggest(player, message.id, message.text); break; case "mod": if (typeof message.channel === "string") { this.mods.receive(player, message.channel, message.data); } break; } } #break_block(player: ServerPlayer, x: number, y: number, z: number) { const info = this.world.get_block_info(x, y, z); // air, or something like water that can't be broken if (!info || info.toughness === undefined || !this.#in_reach(player, x, y, z)) { this.#correct(player, x, y, z); return; } const event = { player: this.mods.player(player), block: this.mods.block_ref(x, y, z, info.id), item: this.mods.player(player).held_item, }; const before = { ...event, cancel: false }; this.mods.before.block_break.emit(before); if (before.cancel) { this.#correct(player, x, y, z); return; } this.destroy_block(x, y, z, player); player.vitals.add_exhaustion(EXHAUSTION.break_block); this.mods.after.block_break.emit(event); } #hit_block(player: ServerPlayer, x: number, y: number, z: number) { const info = this.world.get_block_info(x, y, z); if (!info || !this.#in_reach(player, x, y, z)) { return; } const components = this.mods.components_of(info.id).filter(({ component }) => component.on_click); if (components.length === 0) { return; } const block = this.mods.block_ref(x, y, z, info.id); const player_api = this.mods.player(player); for (const { mod, id, component, params } of components) { run_guarded(mod, `${id} on_click`, () => component.on_click!(block, params, player_api)); } } // left click on an entity or another player: hurts them with the player's attack_damage and pushes them away. // they can't be hurt again for a moment, see LivingEntity.hurt #attack_entity(player: ServerPlayer, id: string) { // like minecraft, any swing starts the cooldown over, hit or not. their client does the same for its indicator const strength = player.attack_strength(); player.attack_strength_ticker = 0; const entity = this.entities.get_entity(id) ?? this.players().find((other) => other.id === id); if ( !(entity instanceof LivingEntity) || entity === player || !entity.alive || !player.alive || !this.#entity_in_reach(player, entity) ) { return; } const source = { type: "physical", cause: "player_attack", attacker: player, by_player: true } as const; // like minecraft, attacking again before the attack speed allows hits weaker const damage = player.attribute(ATTRIBUTES.attack_damage) * (0.2 + strength * strength * 0.8); if (entity.hurt(damage, source)) { player.vitals.add_exhaustion(EXHAUSTION.attack); } } // right click at nothing: eating, or the item's on_use #use_item(player: ServerPlayer): boolean { return this.#eat(player) || this.#use_item_components(player); } // the held item's on_use handlers, returns whether it has any #use_item_components(player: ServerPlayer): boolean { const held = player.held_item; if (!held) { return false; } const components = this.mods.item_components_of(held.type_id).filter(({ component }) => component.on_use); if (components.length === 0) { return false; } const player_api = this.mods.player(player); const item = player_api.held_item!; for (const { mod, id, component, params } of components) { run_guarded(mod, `${id} on_use`, () => component.on_use!(item, params, player_api)); } return true; } #use_block(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) { const info = this.world.get_block_info(x, y, z); const target = placement_target(x, y, z, FACE_OFFSETS[face], info); const [tx, ty, tz] = [target.x, target.y, target.z]; if (!info || !this.#in_reach(player, x, y, z)) { this.#correct(player, x, y, z); this.#correct(player, tx, ty, tz); return; } const player_api = this.mods.player(player); const value = this.world.get_block_value(x, y, z); const held_slot = player.inventory.get_slot(player.selected_slot); const held = EverythingRegistry.get("items", held_slot.type_id ?? ""); // an item aimed at liquids, like a bucket, uses the liquid in a waterlogged block instead of the block const used = (held?.targets_liquids && liquid_block(value, info)) || info; const block = this.mods.block_ref(x, y, z, used.id); const interact = { player: player_api, block, item: player_api.held_item }; const before_interact = { ...interact, cancel: false }; this.mods.before.block_interact.emit(before_interact); if (before_interact.cancel) { // the client may have guessed the shared rules' on_interact, or a placement this.#correct(player, x, y, z); this.#correct(player, tx, ty, tz); return; } // the shared rules first, the ones the client guessed, then the server script's let handled = this.mods.rules.interact(used, x, y, z, { face, hit: [hit[0], hit[1], hit[2]] }, player.yaw); for (const { mod, id: component_id, component, params } of this.mods.components_of(used.id)) { if (component.on_interact) { handled = run_guarded(mod, `${component_id} on_interact`, () => component.on_interact!(block, params, player_api)) === true || handled; } } if (handled) { this.mods.after.block_interact.emit(interact); // the client guessed the shared rules' on_interact from what it sees, which might not be what's here. it didn't // guess a placement for interactive blocks, but it might have for others this.#correct(player, x, y, z); this.#correct(player, tx, ty, tz); return; } // an item that does something when used does that instead of being placed if (this.#use_item_components(player)) { this.#correct(player, tx, ty, tz); return; } // placing a liquid, like a water bucket, into a block that can hold it fills it, like minecraft's if (held?.block_id && info.waterloggable === held.block_id && !is_waterlogged(value, info)) { this.#waterlog(player, x, y, z, face, hit); return; } // 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 && can_place( EverythingRegistry.get("blocks", held.block_id), this.world.get_block_info(tx, ty, tz), this.world.get_block_value(tx, ty, tz), this.world.get_block_id(tx, ty - 1, tz), ); if (!placeable || !held?.block_id) { this.#eat(player); this.#correct(player, tx, ty, tz); return; } // solid blocks can't go where a mob or player is, the one placing it included, like minecraft const placing = EverythingRegistry.get("blocks", held.block_id)!; // put into a source of the liquid it can hold, it holds it const placed_value = waterlog_placement( this.mods.rules.placement_value(placing, player.yaw, { x: tx, y: ty, z: tz, face, hit: [hit[0], hit[1], hit[2]], }), placing, this.world.get_block_value(tx, ty, tz), this.world.get_block_info(tx, ty, tz), ); const state = placed_value >>> 16; if (placing?.has_collision && this.#occupied(tx, ty, tz, collision_shape_at(placing, placed_value))) { this.#correct(player, tx, ty, tz); return; } const place = { player: player_api, block: { id: held.block_id, x: tx, y: ty, z: tz }, face, hit: [hit[0], hit[1], hit[2]] as const, item: player_api.held_item, }; const before_place = { ...place, cancel: false }; this.mods.before.block_place.emit(before_place); if (before_place.cancel) { this.#correct(player, tx, ty, tz); return; } this.set_block(tx, ty, tz, held.block_id, player, state); held_slot.amount = held_slot.amount! - 1; this.mods.after.block_place.emit(place); } // the held liquid poured into the block at x y z, which can hold it. it's placing the liquid as far as mods can tell, // so a bucket empties like it does placing water anywhere else #waterlog(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) { const held_slot = player.inventory.get_slot(player.selected_slot); const player_api = this.mods.player(player); const place = { player: player_api, block: { id: this.world.get_block_info(x, y, z)!.waterloggable!, x, y, z }, face, hit: [hit[0], hit[1], hit[2]] as const, item: player_api.held_item, }; const before_place = { ...place, cancel: false }; this.mods.before.block_place.emit(before_place); if (before_place.cancel) { this.#correct(player, x, y, z); return; } const info = this.world.get_block_info(x, y, z)!; this.set_block_state( x, y, z, set_state_value(this.world.get_block_value(x, y, z), info, "waterlogged", 1)! >>> 16, ); held_slot.amount = held_slot.amount! - 1; this.mods.after.block_place.emit(place); } // whether a mob's or player's collision box overlaps a block with that shape at x, y, z #occupied(x: number, y: number, z: number, shape: Shape) { return this.players().some((player) => box_overlaps_block( { x: player.x, y: player.y, z: player.z, width: PLAYER_WIDTH, height: player.height }, x, y, z, shape, ) ) || this.entities.entities_near(x + 0.5, y, z + 0.5, 3).some((entity) => entity instanceof Mob && box_overlaps_block(entity, x, y, z, shape) ); } #drop_item(player: ServerPlayer, id: unknown, slot: unknown, all: boolean) { const menu = player.container_menu; if (id !== menu.id || !is_int(slot)) { return; } const thrown = menu.drop(slot, all); if (thrown) { this.throw_item(player, thrown); this.world.dirty = true; } } // clicks for a menu that's already closed are ignored, like minecraft's #click(player: ServerPlayer, id: unknown, slot: unknown, button: unknown, shift: boolean) { const menu = player.container_menu; if (id !== menu.id || !is_int(slot) || !is_int(button) || slot < 0 || slot >= menu.slots.length) { return; } if (shift) { menu.quick_move(slot); } else { menu.click(slot, button, player.cursor); } if (menu !== player.inventory_menu) { this.world.dirty = true; } } #chat(player: ServerPlayer, raw: unknown) { if (typeof raw !== "string") { return; } const text = raw.trim().slice(0, MAX_CHAT_LENGTH); if (text.length === 0) { return; } if (text.startsWith("/")) { this.#command(player, text); return; } const before = { player: this.mods.player(player), message: text, cancel: false }; this.mods.before.chat_send.emit(before); const message = String(before.message).slice(0, MAX_CHAT_LENGTH); if (before.cancel || message.length === 0) { return; } console.log(`<${player.name}> ${message}`); this.#broadcast({ type: "chat", from: player.name, text: message }); this.mods.after.chat_send.emit({ player: before.player, message }); } // what typed commands run as #command_source(player: ServerPlayer): ServerCommandSource { const api = this.mods.player(player); return { player: api, server_player: player, send_message: (text) => this.send_chat(player, text) }; } #command(player: ServerPlayer, text: string) { const input = text.slice(1); try { this.mods.commands.execute(input, this.#command_source(player)); } catch (e) { if (e instanceof CommandError) { this.send_chat(player, e.message); return; } // a bug in whoever made the command, not something the player did const name = input.split(" ")[0]; console.error(`[${this.mods.command_owners.get(name) ?? "?"}] /${name} threw:`, e); this.send_chat(player, `Something went wrong running /${name}`); } } // what could come next while they type a command, see common/commands.ts #suggest(player: ServerPlayer, id: unknown, text: unknown) { if (!is_int(id) || typeof text !== "string" || !text.startsWith("/") || text.length > MAX_CHAT_LENGTH) { return; } const { start, suggestions } = this.mods.commands.suggest(text.slice(1), this.#command_source(player)); this.#send(player, { type: "suggestions", id, start: start + 1, suggestions: suggestions.slice(0, MAX_SUGGESTIONS), }); } // like minecraft's /locate biome: columns LOCATE_STEP apart, in square rings out from x, z. the closest in the // first ring that has one #locate_biome(biome: string, x: number, z: number) { for (let ring = 0; ring * LOCATE_STEP <= LOCATE_RADIUS; ring++) { let best: { x: number; y: number; z: number; distance: number } | undefined; for (let dx = -ring; dx <= ring; dx++) { for (let dz = -ring; dz <= ring; dz++) { if (Math.max(Math.abs(dx), Math.abs(dz)) !== ring) continue; const [cx, cz] = [x + dx * LOCATE_STEP, z + dz * LOCATE_STEP]; const found = estimate_biome(this.world.seed, cx, cz); const distance = Math.hypot(dx, dz); if (found.biome === biome && (!best || distance < best.distance)) { best = { x: cx, y: found.y, z: cz, distance }; } } } if (best) return best; } return undefined; } // the engine's own commands, registered like mods' so they're in /help and suggested the same way #register_commands() { const register = (node: CommandNode) => this.mods.register_command("engine", node); // TODO: only let operators do this const give = (context: CommandContext, count: number) => { const id = context.get("item"); this.give(context.source.server_player, id, count); context.source.send_message(`Gave ${count} ${display_name(id)}`); }; register( literal("give").describe("Gives you an item").then( argument("item", item()) .executes((context) => give(context, 1)) .then( argument("count", integer(1, MAX_GIVE)) .executes((context) => give(context, context.get("count"))), ), ), ); const set_time = (context: CommandContext, time: number) => { this.set_time(time); this.#broadcast({ type: "chat", text: `${context.source.server_player.name} set the time to ${format_clock(this.world.time)}`, }); }; register( literal("time") .describe("Shows or changes the time of day") .executes((context) => context.source.send_message(`${format_clock(this.world.time)} (tick ${this.world.time})`) ) .then( literal("set") .then( argument("time_of_day", choice(Object.keys(TIMES_OF_DAY))) .executes((context) => { // the next time it's that time of day, so days keep counting up const now = this.world.time; const target = now - time_of_day(now) + TIMES_OF_DAY[context.get("time_of_day")]; set_time(context, target >= now ? target : target + CYCLE_TICKS); }), ) .then( argument("ticks", integer(0)) .executes((context) => set_time(context, context.get("ticks"))), ), ) .then( literal("add").then( argument("ticks", integer()) .executes((context) => set_time(context, Math.max(0, this.world.time + context.get("ticks"))) ), ), ), ); // TODO: only let operators do this register( literal("summon").describe("Spawns an entity where you are").then( argument("entity", word()) .suggests((partial) => entity_type_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text })) ) .executes((context) => { const id = context.get("entity"); const entity = entity_type_ids().includes(id) ? create_entity(this.entities, id) : undefined; if (!entity) throw new CommandError(`There's no entity ${id}`); const player = context.source.server_player; entity.set_position(player.x, player.y, player.z); entity.yaw = entity.head_yaw = player.yaw; this.entities.add_entity(entity); context.source.send_message(`Summoned ${id}`); }), ), ); // TODO: only let operators do this const add_effect = (context: CommandContext, seconds: number) => { const id = context.get("effect"); const type = effect_type(id); if (!type) throw new CommandError(`There's no effect ${id}`); context.source.server_player.add_effect(new EffectInstance(type, seconds * TICKS_PER_SECOND)); context.source.send_message(`Gave ${display_name(id)} for ${seconds} seconds`); }; register( literal("effect").describe("Gives you a status effect").then( argument("effect", word()) .suggests((partial) => effect_type_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text })) ) .executes((context) => add_effect(context, 30)) .then( argument("seconds", integer(1, 1_000_000)) .executes((context) => add_effect(context, context.get("seconds"))), ), ), ); // TODO: only let operators do this register( literal("tp").describe("Teleports you to x y z").then( argument("x", number()).then( argument("y", number()).then( argument("z", number()).executes((context) => { const [x, y, z] = ["x", "y", "z"].map((axis) => context.get(axis)); this.teleport(context.source.server_player, x, y, z); context.source.send_message(`Teleported to ${x} ${y} ${z}`); }), ), ), ), ); register( literal("locatebiome").describe("Finds the nearest biome of a kind").then( argument("biome", word()) .suggests((partial) => biome_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text }))) .executes((context) => { const id = context.get("biome"); if (!get_biome(id)) throw new CommandError(`There's no biome ${id}`); const player = context.source.server_player; const found = this.#locate_biome(id, Math.floor(player.x), Math.floor(player.z)); if (!found) { throw new CommandError(`There's no ${display_name(id)} within ${LOCATE_RADIUS} blocks`); } const distance = Math.round(Math.hypot(found.x - player.x, found.z - player.z)); context.source.send_message( `The nearest ${ display_name(id) } is at ${found.x} ${found.y} ${found.z}, ${distance} blocks away`, ); }), ), ); // TODO: only let operators do this register( literal("fly").describe("Toggles flying").executes((context) => { const player = context.source.server_player; player.flying = !player.flying; player.fall_distance = 0; context.source.send_message(player.flying ? "You can fly" : "You can't fly anymore"); }), ); // TODO: only let operators do this register( literal("viewdistance").describe("Shows or changes the server's view distance") .executes((context) => { context.source.send_message(`The view distance is ${this.view_distance} chunks`); }) .then( argument("chunks", integer(MIN_VIEW_DISTANCE, MAX_VIEW_DISTANCE)) .executes((context) => { this.set_view_distance(context.get("chunks")); context.source.send_message(`Set the view distance to ${this.view_distance} chunks`); }), ), ); register( literal("tps").describe("Shows how the game loop keeps up").executes((context) => { if (!this.loop) { context.source.send_message("The game loop isn't running"); return; } const { tps, mspt, skipped } = this.loop.stats; context.source.send_message( `${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` + `${skipped} skipped since starting`, ); }), ); register( literal("skin") .describe( "Changes your skin to a 64x64 png from the web, slim for 3 pixel wide arms. " + "Back to the default without a url", ) .executes((context) => { this.set_skin(context.source.server_player, undefined, false); context.source.send_message("Your skin is back to the default"); }) .then( argument("url", word()) .executes((context) => this.#download_skin(context.source.server_player, context.get("url"), false) ) .then( argument("model", choice(["slim", "normal"])) .executes((context) => this.#download_skin( context.source.server_player, context.get("url"), context.get("model") === "slim", ) ), ), ), ); // every command's usage, or one's. aliases like /mod:name aren't listed twice const commands = this.mods.commands; const help = (context: CommandContext, only?: string) => { const nodes = commands.root.children.filter((node) => !node.name.includes(":") && (!only || node.name === only) ); if (nodes.length === 0) throw new CommandError(`There's no command /${only}`); for (const node of nodes) { const usage = `/${commands.usage(node, context.source)}`; context.source.send_message(node.description ? `${usage} - ${node.description}` : usage); } }; register( literal("help") .describe("Lists commands") .executes((context) => help(context)) .then( argument("command", word()) .suggests((partial) => commands.root.children .filter((node) => !node.name.includes(":") && node.name.startsWith(partial)) .map((node) => ({ text: node.name })) ) .executes((context) => help(context, context.get("command"))), ), ); } // a base64 png, or undefined for the default skin, and whether it's for the slim model. everyone is told, the // player too set_skin(player: ServerPlayer, skin: string | undefined, slim: boolean) { player.skin = skin; player.slim = slim; this.world.dirty = true; this.#broadcast({ type: "player_skin", id: player.id, skin, slim: slim || undefined }); } // the host downloads it, which takes a while, so the player hears back later #download_skin(player: ServerPlayer, url: string, slim: boolean) { if (player.downloading_skin) { throw new CommandError("Your last skin is still downloading"); } player.downloading_skin = true; this.send_chat(player, "Downloading your skin..."); const online = () => this.#players.get(player.conn) === player; this.#host.download(url, MAX_SKIN_BYTES) .then((bytes) => { const problem = skin_problem(bytes); if (problem) { throw new Error(problem); } if (online()) { this.set_skin(player, encode_skin(bytes), slim); this.send_chat(player, "Skin changed"); } }) .catch((e) => { if (online()) { this.send_chat(player, `Couldn't change your skin: ${e instanceof Error ? e.message : e}`); } }) .finally(() => player.downloading_skin = false); } #close_menu(player: ServerPlayer) { const menu = player.menu; player.menu = undefined; for (const fn of menu?.on_close ?? []) fn(); player.sent.delete("menu_content"); player.sent.delete("menu_data"); // the crafting grid and whatever the cursor holds go back into the inventory for (let i = 0; i < 9; i++) { const item = player.crafting.get_item(i); if (item) { player.crafting.set_item(i, undefined); this.give_stack(player, item); } } update_crafting_result(player.crafting, this.recipes.shaped); if (player.cursor.item) { const item = player.cursor.item; player.cursor.item = undefined; this.give_stack(player, item); } } // health and hunger, see vitals.ts // hurts a player, killing them at 0. cause is for mods and the death message, like "fall" damage_player(player: ServerPlayer, amount: number, cause: string) { player.hurt(amount, damage_source(cause)); } // everything that hurts a player ends up here, see ServerPlayer.hurt. mods can change or cancel it first hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean { if (player.is_invulnerable_to(source) || !player.alive || !(amount > 0)) { return false; } const before = { player: this.mods.player(player), amount, cause: source.cause, cancel: false }; this.mods.before.player_damage.emit(before); const final = Number(before.amount); if (before.cancel || !(final > 0)) { return false; } if (!player.apply_hurt(final, source)) return false; this.mods.after.player_damage.emit({ player: before.player, amount: final, cause: source.cause }); return true; } heal_player(player: ServerPlayer, amount: number) { player.heal(amount); } // like minecraft: everything they carried falls out where they died, and they start over at spawn. tools lose 1 // durability first, and ones that run out break instead of dropping #kill(player: ServerPlayer, source: DamageSource) { const cause = source.cause; const { x, y, z } = player; this.close_menu(player); for (let i = 0; i < player.inventory.size; i++) { const item = player.inventory.get_item(i); if (item) { player.inventory.set_item(i, undefined); if (item.damage(1)) continue; this.pop_item(Math.floor(x), Math.floor(Math.max(y, 0)), Math.floor(z), item); } } this.mods.after.player_death.emit({ player: this.mods.player(player), cause }); this.#broadcast({ type: "chat", text: death_message(player.name, source) }); player.vitals.reset(); player.revive(); const spawn = this.world.spawn_point(); this.teleport(player, spawn.x, spawn.y, spawn.z); this.world.dirty = true; } #tick_vitals() { for (const player of this.#players.values()) { // burning, effects, falling out of the world, and being knocked back const knocked_back = player.knockback_ticks !== undefined; player.tick(); if (knocked_back && player.alive) { // the last one hands what's left of the slide to their client this.#place(player, [player.vx, player.vy, player.vz]); if (player.knockback_ticks === undefined) player.stop_knockback(); } player.vitals.tick( player.health, player.max_health, (amount) => this.heal_player(player, amount), (amount) => this.damage_player(player, amount, "starve"), ); } } // what moving costs and does: sprinting and swimming tire, jumping too, and landing after a fall hurts #on_move(player: ServerPlayer, x: number, y: number, z: number) { const dx = x - player.x; const dy = y - player.y; const dz = z - player.z; const ticks = Math.max(1, this.#tick - player.last_move_tick); player.last_move_tick = this.#tick; const horizontal = Math.hypot(dx, dz); // knockback only lifts them off the ground player.on_ground = this.#on_ground(x, y, z); // teleports and the first move after joining aren't walking if (horizontal > TELEPORT_DISTANCE || Math.abs(dy) > TELEPORT_DISTANCE) { player.fall_distance = 0; return; } if (player.flying) { player.fall_distance = 0; return; } const vitals = player.vitals; const in_liquid = this.#in_liquid(x, y, z); const sprinting = horizontal / (ticks * TICK_DELTA) > SPRINT_SPEED; if (in_liquid) { vitals.add_exhaustion(EXHAUSTION.swim_per_block * (horizontal + Math.abs(dy))); player.fall_distance = 0; } else if (sprinting) { vitals.add_exhaustion(EXHAUSTION.sprint_per_block * horizontal); } if (dy > 0 && !in_liquid && this.#on_ground(player.x, player.y, player.z)) { vitals.add_exhaustion(sprinting ? EXHAUSTION.sprint_jump : EXHAUSTION.jump); } if (dy < 0 && !in_liquid) { player.fall_distance -= dy; } if (player.on_ground) { const damage = Math.ceil(player.fall_distance - SAFE_FALL); player.fall_distance = 0; if (damage > 0) { this.damage_player(player, damage, "fall"); } } } // feet on top of something solid, anywhere under the player's box #on_ground(x: number, y: number, z: number) { const fraction = y - Math.floor(y); if (fraction > GROUND_EPSILON && fraction < 1 - GROUND_EPSILON) { return false; } const below = Math.floor(y - GROUND_EPSILON); const half = PLAYER_WIDTH / 2; for (const [ox, oz] of [[-half, -half], [half, -half], [-half, half], [half, half]]) { if (this.world.has_collision(Math.floor(x + ox), below, Math.floor(z + oz))) { return true; } } return false; } // in liquid, a waterlogged block's too #in_liquid(x: number, y: number, z: number) { const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)]; return liquid_block(this.world.get_block_value(bx, by, bz), this.world.get_block_info(bx, by, bz)) !== undefined; } // right click with food: it's eaten if they're hungry, or it's always edible #eat(player: ServerPlayer): boolean { const slot = player.inventory.get_slot(player.selected_slot); const food = EverythingRegistry.get("items", slot.type_id ?? "")?.food; if (!food || (!food.always_edible && !player.vitals.can_eat())) { return false; } player.vitals.eat(food.nutrition, food.saturation_modifier); slot.amount = slot.amount! - 1; if (food.returns) { const left = new ItemStack(food.returns); if (slot.has_item()) { this.give_stack(player, left); } else { slot.set_item(left); } } return true; } // entities, see entity/ // 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()) { for (const entity of items) { if (!entity.removed && entity.pickup_delay === 0 && this.#can_pick_up(player, entity)) { this.#pick_up(player, entity); } } } if (this.entities.count > 0) { this.world.dirty = true; } } // the player's box grown by the pickup reach touches the item's box #can_pick_up(player: ServerPlayer, entity: ItemEntity) { const reach_xz = PLAYER_WIDTH / 2 + PICKUP_REACH_XZ + ITEM_SIZE / 2; return Math.abs(player.x - entity.x) <= reach_xz && Math.abs(player.z - entity.z) <= reach_xz && entity.y + ITEM_SIZE >= player.y - PICKUP_REACH_Y && entity.y <= player.y + player.height + PICKUP_REACH_Y; } // as much as fits, the rest stays on the ground #pick_up(player: ServerPlayer, entity: ItemEntity) { if (player.inventory.add_item(entity.item) === 0) { this.entities.take_item(entity, player.id); } } // helpers // the open menus' still_valid and on_tick #tick_menus() { for (const player of this.#players.values()) { const menu = player.menu; if (!menu) continue; if (!menu.still_valid.every((valid) => valid())) { this.close_menu(player); continue; } for (const fn of menu.on_tick) fn(); } } // sends whatever changed since last time #sync(player: ServerPlayer) { const sync = (key: string, value: unknown, message: () => ServerMessage) => { const json = JSON.stringify(value); if (player.sent.get(key) !== json) { player.sent.set(key, json); this.#send(player, message()); } }; // with lore, so it's resent when only the lore changed const inventory = player.inventory.to_synced_data(); sync("inventory", inventory, () => ({ type: "container", container: "inventory", items: inventory })); const crafting = player.crafting.to_synced_data(); sync("crafting", crafting, () => ({ type: "container", container: "crafting", items: crafting })); const cursor = player.cursor.item?.to_synced_data() ?? null; sync("cursor", cursor, () => ({ type: "cursor", item: cursor })); const extra = player.inventory_menu.extra; if (extra.length > 0) { const items = extra.map((slot) => slot.container.get_item(slot.index)?.to_synced_data() ?? null); sync("extra", items, () => ({ type: "container", container: "extra", items })); } // like minecraft, losing max health, like a curio's modifier going away, takes the health over it if (player.health > player.max_health) player.health = player.max_health; const { food, saturation } = player.vitals; const { health, max_health } = player; // in bubbles' halves like hunger, so it's only sent when a bubble changes, not every tick under water const air = Math.max(0, Math.ceil(player.air / player.max_air * 20)); sync( "vitals", [health, max_health, food, saturation, air], () => ({ type: "vitals", health, max_health, food, saturation, air }), ); const attack_speed = player.attribute(ATTRIBUTES.attack_speed); sync("attack_speed", attack_speed, () => ({ type: "attack_speed", value: attack_speed })); const flying = player.flying; sync("flying", flying, () => ({ type: "flying", flying })); const effects = [...player.effects.values()] .filter((effect) => effect.show_icon) .map(({ type, amplifier, duration }) => ({ id: type.id, amplifier, duration })); // by when they end, which stays the same while they count down const ends = effects.map(( { id, amplifier, duration }, ) => [id, amplifier, duration < 0 ? -1 : this.#tick + duration]); sync("effects", ends, () => ({ type: "effects", effects })); const menu = player.menu; if (menu) { const items = menu.content(); sync("menu_content", items, () => ({ type: "menu_content", id: menu.id, items })); const data = menu.data_values(); sync("menu_data", data, () => ({ type: "menu_data", id: menu.id, data })); } } // what a player wears that shows, to everyone when it changed #sync_worn(player: ServerPlayer) { const worn = player.worn_list(); const json = JSON.stringify(worn); if (json === player.worn_sent) return; player.worn_sent = json; this.#broadcast({ type: "player_worn", id: player.id, worn }); } // tell the player what's really at a position, undoing anything their client guessed // the client's break_block or use_block with seq is handled, after the set_blocks it caused, even when it's // ignored: the client holds back what the server says about the blocks it guessed until this comes #ack(player: ServerPlayer, seq: unknown) { if (is_int(seq) && seq > 0) { this.#send(player, { type: "block_ack", seq }); } } #correct(player: ServerPlayer, x: number, y: number, z: number) { if (y < 0 || y >= CHUNK_HEIGHT || !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 const id = this.world.get_block_id(x, y, z); const state = this.world.get_block_value(x, y, z) >>> 16; this.#send(player, state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id }); } // chunks // after the player moved or their view distance changed: tells their client the new center and which chunks to // drop, the chunks that came into view go out in #send_chunks #update_view(player: ServerPlayer, force = false) { const { moved, forget } = player.chunks.move_to(player.x, player.z, force); if (!moved) { return; } const center = player.chunks.center!; this.#send(player, { type: "set_center_chunk", x: center.x, z: center.z }); for (const [x, z] of forget) { this.#send(player, { type: "forget_level_chunk", x, z }); } } // every player's next batch, like minecraft's PlayerChunkSender. building chunks is the slow part, so they share // a time budget and whoever didn't get theirs goes first next tick #send_chunks() { const players = [...this.#players.values()]; if (players.length === 0) { return; } const start = performance.now(); const can_send = () => performance.now() - start < this.chunk_send_budget_ms; const first = this.#next_chunk_player % players.length; for (let i = 0; i < players.length; i++) { const player = players[(first + i) % players.length]; if (!can_send()) { this.#next_chunk_player = first + i; return; } const batch = player.chunks.next_batch(can_send); if (batch.length === 0) { continue; } this.#send(player, { type: "chunk_batch_start" }); for (const [x, z] of batch) { this.#host.send(player.conn, this.world.level_chunk(x, z)); for (const tile of this.world.item_tiles(x, z)) { this.#send(player, { type: "set_block_item", x: tile.x, y: tile.y, z: tile.z, item: tile.item! }); } } this.#send(player, { type: "chunk_batch_finished", size: batch.length }); } this.#next_chunk_player = first + 1; } #in_reach(player: ServerPlayer, x: number, y: number, z: number) { const dx = x + 0.5 - player.x; const dy = y + 0.5 - (player.y + player.eye_height); const dz = z + 0.5 - player.z; return dx * dx + dy * dy + dz * dz <= MAX_REACH * MAX_REACH; } // from the eyes to the closest point of its box #entity_in_reach(player: ServerPlayer, entity: LivingEntity) { const eye_y = player.y + player.eye_height; const half = entity.width / 2; const dx = Math.max(entity.x - half - player.x, 0, player.x - entity.x - half); const dy = Math.max(entity.y - eye_y, 0, eye_y - entity.y - entity.height); const dz = Math.max(entity.z - half - player.z, 0, player.z - entity.z - half); return dx * dx + dy * dy + dz * dz <= MAX_REACH * MAX_REACH; } #near_any_player(x: number, z: number) { const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); for (const player of this.#players.values()) { const px = Math.floor(player.x / CHUNK_SIZE); const pz = Math.floor(player.z / CHUNK_SIZE); if (Math.max(Math.abs(px - chunk_x), Math.abs(pz - chunk_z)) <= SIMULATION_DISTANCE) { return true; } } return false; } #unique_name(name: unknown): string { const cleaned = typeof name === "string" ? name.replace(/[^A-Za-z0-9_]/g, "").slice(0, MAX_NAME_LENGTH) : ""; const base = cleaned || `player${Math.floor(Math.random() * 10000)}`; const taken = new Set([...this.#players.values()].map((p) => p.name)); let final = base; let i = 2; while (taken.has(final)) { final = `${base}${i}`; i += 1; } return final; } #send(player: ServerPlayer, message: ServerMessage) { this.#host.send(player.conn, JSON.stringify(message)); } #broadcast(message: ServerMessage, except?: ServerPlayer) { const data = JSON.stringify(message); for (const player of this.#players.values()) { if (player !== except) { this.#host.send(player.conn, data); } } } } function is_number(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value); } function is_int(value: unknown): value is number { return Number.isInteger(value); } // what a player asked for, up to the server's function view_distance(requested: unknown, server: number): number { if (!is_int(requested)) { return server; } return Math.min(server, Math.max(MIN_VIEW_DISTANCE, Math.min(MAX_VIEW_DISTANCE, requested))); } // 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 && Math.abs(x) < 30000 * CHUNK_SIZE && Math.abs(z) < 30000 * CHUNK_SIZE; } // level.json version 4, which only had items on the ground interface SavedLevelV4 extends Omit { version: 4; entities: { x: number; y: number; z: number; vx: number; vy: number; vz: number; item: SavedItemEntity["item"]; age: number; pickup_delay: number; }[]; } // curios was a mod of its own before it became part of the base game: which container is each player's curios moves // into the base game's storage function upgrade_mod_storage(storage: Record>) { const curios = storage.curios?.containers; if (curios !== undefined && storage.bworld?.curios === undefined) { (storage.bworld ??= {}).curios = curios; delete storage.curios; } return storage; } function upgrade_v4_entities(entities: SavedLevelV4["entities"]): SavedEntity[] { return (entities ?? []).map((entity): SavedItemEntity => ({ id: ITEM_ENTITY_TYPE, uuid: crypto.randomUUID(), pos: [entity.x, entity.y, entity.z], motion: [entity.vx, entity.vy, entity.vz], rotation: [0, 0], item: entity.item, age: entity.age, pickup_delay: entity.pickup_delay, })); } // what everyone's told when someone dies function death_message(name: string, source: DamageSource) { switch (source.cause) { case "player_attack": return source.attacker instanceof ServerPlayer ? `${name} was slain by ${source.attacker.name}` : `${name} died`; case "fall": return `${name} hit the ground too hard`; case "void": return `${name} fell out of the world`; case "starve": return `${name} starved to death`; // standing on something hot, like a lit stove case "hot_floor": return `${name} discovered the floor was lava`; default: return `${name} died`; } } // the states a block is placed with: its defaults, and a "facing" state turned towards whoever placed it, like // minecraft's getStateForPlacement with getHorizontalDirection().getOpposite(). facing is 0 north, 1 east, 2 south, // 3 west, and variants turn the model with it (its north side is the front, like engine:cube's). they look along // (-sin yaw, -cos yaw), so the way back to them is (sin yaw, cos yaw) // where a player is now, for everyone else function player_move(player: ServerPlayer): ServerMessage { const { id, x, y, z, yaw, pitch } = player; return { type: "player_move", id, x, y, z, yaw, pitch, ...(player.swimming && { swimming: true }) }; }