// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // every entity in the world, and what each player's client knows about them. like minecraft's entity lookup plus // its ChunkMap's entity tracking: a player's client hears about the entities within their view distance, gets told // when those move or change, and forgets them when they leave it import { CHUNK_SIZE } from "@/common/constants.ts"; import { is_within_view } from "@/common/chunk_streaming.ts"; import { fluid_block, fluid_in_cell } from "@/common/utils.ts"; import { biome_season } from "@/common/worldgen/biomes.ts"; import { Tags } from "@/common/tags.ts"; import type { ItemStack } from "@/common/inventory.ts"; import type { EntityEvent, EntityInfo, ServerMessage } from "@/common/protocol.ts"; import type { PlayOptions } from "@/common/mod_api/shared.ts"; import { sound_range, sound_to_play } from "@/common/mod_data.ts"; import type { ServerPlayer } from "../player.ts"; import type { ServerWorld } from "../world.ts"; import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts"; import { load_entity } from "./entity_types.ts"; import { ItemEntity } from "./item_entity.ts"; import { MOBS_PATH_THROUGH } from "./pathfinding.ts"; import type { LivingEntity } from "./living_entity.ts"; // everything the entities need from the game server export interface EntityHost { readonly world: ServerWorld; readonly current_tick: number; players(): ServerPlayer[]; send(player: ServerPlayer, message: ServerMessage): void; before_hurt(entity: LivingEntity, amount: number, source: DamageSource): number; after_hurt(entity: LivingEntity, amount: number, source: DamageSource): void; on_entity_death?(entity: Entity, source: DamageSource): void; // what it drops when it dies, from its loot table entity_loot?(entity: Entity, source: DamageSource): ItemStack[]; // see EntityLevel.stands_on stands_on?(entity: Entity, x: number, y: number, z: number): void; // see EntityLevel.inside_blocks inside_blocks?(entity: Entity): void; } // a sound clients play, with only what's set. where is where it comes from, see the message in common/protocol.ts export function sound_message( sound: string, { volume, pitch }: PlayOptions, where: { at?: [number, number, number]; entity?: string } = {}, ): ServerMessage { return { type: "sound", sound, ...where, ...(volume !== undefined && volume !== 1 && { volume }), ...(pitch !== undefined && pitch !== 1 && { pitch }), }; } // what a client was last told about an entity, so only changes get sent interface Sent { x: number; y: number; z: number; yaw: number; pitch: number; head_yaw: number | undefined; // json of the item for items, of synced_data for the rest data: string; passengers: string; } export class EntityManager implements EntityLevel { #host: EntityHost; #entities = new Map(); // what each player's client knows, by entity id #tracked = new Map>(); // saved entities of kinds that don't exist anymore, like from a mod that's gone. saved again as they were, so // they come back with the mod #unknown: SavedEntity[] = []; constructor(host: EntityHost) { this.#host = host; } get current_tick() { return this.#host.current_tick; } get min_y() { return this.#host.world.shape.min_y; } get count() { return this.#entities.size; } all(): Entity[] { return [...this.#entities.values()].filter((entity) => !entity.removed); } // adds it and its passengers. clients that can see it hear about it straight away add_entity(entity: Entity) { if (entity.removed) return; this.#entities.set(entity.id, entity); for (const [player, tracked] of this.#tracked) { if (!tracked.has(entity.id) && this.#can_see(player, entity)) { this.#host.send(player, { type: "add_entity", entity: this.#start_tracking(tracked, entity) }); } } for (const passenger of entity.passengers) this.add_entity(passenger); } get_entity(id: string): Entity | undefined { const entity = this.#entities.get(id); return entity && !entity.removed ? entity : undefined; } entities_near(x: number, y: number, z: number, radius: number): Entity[] { return this.all().filter((entity) => Math.abs(entity.x - x) <= radius && Math.abs(entity.y - y) <= radius && Math.abs(entity.z - z) <= radius ); } // the level has_collision(x: number, y: number, z: number) { return this.#host.world.has_collision(x, y, z); } has_chunk(chunk_x: number, chunk_z: number) { return this.#host.world.has_chunk(chunk_x, chunk_z); } passes_through(x: number, y: number, z: number) { const block = this.#host.world.get_block_info(x, y, z); return block !== undefined && Tags.has("blocks", MOBS_PATH_THROUGH, block.id); } collision_shape(x: number, y: number, z: number) { return this.#host.world.collision_shape(x, y, z); } is_fluid(x: number, y: number, z: number) { const world = this.#host.world; return fluid_block(world.get_block_value(x, y, z), world.get_block_info(x, y, z)) !== undefined; } get_block_info(x: number, y: number, z: number) { return this.#host.world.get_block_info(x, y, z); } biome_at(x: number, y: number, z: number) { return this.#host.world.biome_at(x, y, z); } season_at(x: number, y: number, z: number) { return biome_season(this.biome_at(x, y, z), this.#host.world.time); } fluid_at(x: number, y: number, z: number) { const world = this.#host.world; return fluid_in_cell(world.get_block_value(x, y, z), world.get_block_info(x, y, z)); } nearest_player(x: number, y: number, z: number, max_distance: number): ServerPlayer | undefined { let nearest: ServerPlayer | undefined; let nearest_distance = max_distance; for (const player of this.#host.players()) { const distance = Math.hypot(player.x - x, player.y - y, player.z - z); if (distance <= nearest_distance) { nearest = player; nearest_distance = distance; } } return nearest; } before_hurt(entity: LivingEntity, amount: number, source: DamageSource) { return this.#host.before_hurt(entity, amount, source); } after_hurt(entity: LivingEntity, amount: number, source: DamageSource) { this.#host.after_hurt(entity, amount, source); } spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { const entity = new ItemEntity(this, stack, x, y, z, pickup_delay); this.add_entity(entity); return entity; } take_item(item: Entity, by: string) { for (const [player, tracked] of this.#tracked) { if (tracked.delete(item.id)) { this.#host.send(player, { type: "take_entity", id: item.id, player: by }); } } item.remove(); this.#entities.delete(item.id); } // players aren't tracked like entities, everyone else knows about them entity_event(entity: Entity, event: EntityEvent) { const is_player = this.#host.players().includes(entity as ServerPlayer); for (const [player, tracked] of this.#tracked) { if (is_player ? player !== entity : tracked.has(entity.id)) { this.#host.send(player, { type: "entity_event", id: entity.id, event }); } } } play_sound(entity: Entity, sound: string, options: PlayOptions) { const range = sound_range(sound_to_play(sound, options), options.volume); const message = sound_message(sound, options, { entity: entity.id }); for (const [player, tracked] of this.#tracked) { if (tracked.has(entity.id) && player.hears(entity.x, entity.y, entity.z, range)) { this.#host.send(player, message); } } } on_death(entity: Entity, source: DamageSource) { this.#host.on_entity_death?.(entity, source); } entity_loot(entity: Entity, source: DamageSource): ItemStack[] { return this.#host.entity_loot?.(entity, source) ?? []; } stands_on(entity: Entity, x: number, y: number, z: number) { this.#host.stands_on?.(entity, x, y, z); } inside_blocks(entity: Entity) { this.#host.inside_blocks?.(entity); } // ticking // every entity active says should move, with their passengers. entities removed along the way are forgotten tick(active: (entity: Entity) => boolean) { for (const entity of [...this.#entities.values()]) { if (entity.removed || entity.vehicle || !active(entity)) continue; entity.tick(); entity.tick_passengers(); } this.#forget_removed(); } #forget_removed() { for (const [id, entity] of this.#entities) { if (!entity.removed) continue; this.#entities.delete(id); for (const [player, tracked] of this.#tracked) { if (tracked.delete(id)) this.#host.send(player, { type: "remove_entity", id }); } } } // tracking // a player joined: what their client starts out knowing, for join start_tracking(player: ServerPlayer): EntityInfo[] { const tracked = new Map(); this.#tracked.set(player, tracked); return this.all() .filter((entity) => this.#can_see(player, entity)) .map((entity) => this.#start_tracking(tracked, entity)); } stop_tracking(player: ServerPlayer) { this.#tracked.delete(player); } // tells every client what changed since last time: entities coming into and going out of view, moving, and // changing what they look like sync() { this.#forget_removed(); for (const [player, tracked] of this.#tracked) { const send = (message: ServerMessage) => this.#host.send(player, message); for (const [id, sent] of tracked) { const entity = this.#entities.get(id); if (!entity || !this.#can_see(player, entity)) { tracked.delete(id); send({ type: "remove_entity", id }); continue; } if ( entity.x !== sent.x || entity.y !== sent.y || entity.z !== sent.z || entity.yaw !== sent.yaw || entity.pitch !== sent.pitch || entity.head_yaw !== sent.head_yaw ) { Object.assign(sent, position(entity)); const { x, y, z, yaw, pitch, head_yaw } = sent; send( head_yaw === undefined ? { type: "move_entity", id, x, y, z, yaw, pitch } : { type: "move_entity", id, x, y, z, yaw, pitch, head_yaw }, ); } const data = data_json(entity); if (data !== sent.data) { sent.data = data; send( entity instanceof ItemEntity ? { type: "set_entity_item", id, item: entity.item.to_data() } : { type: "entity_data", id, data: entity.synced_data() }, ); } const passengers = entity.passengers.filter((p) => !p.removed).map((p) => p.id); const passengers_json = JSON.stringify(passengers); if (passengers_json !== sent.passengers) { sent.passengers = passengers_json; send({ type: "set_passengers", id, passengers }); } } for (const entity of this.#entities.values()) { if (!entity.removed && !tracked.has(entity.id) && this.#can_see(player, entity)) { send({ type: "add_entity", entity: this.#start_tracking(tracked, entity) }); } } } } // passengers go out with the next sync, the info doesn't have them #start_tracking(tracked: Map, entity: Entity): EntityInfo { tracked.set(entity.id, { ...position(entity), data: data_json(entity), passengers: "[]" }); return entity.info(); } // the entity is within the player's view distance, where their client has (or will have) the chunks #can_see(player: ServerPlayer, entity: Entity) { const center = player.chunks.center ?? { x: Math.floor(player.x / CHUNK_SIZE), z: Math.floor(player.z / CHUNK_SIZE) }; return is_within_view( center.x, center.z, player.chunks.view_distance, Math.floor(entity.x / CHUNK_SIZE), Math.floor(entity.z / CHUNK_SIZE), ); } // saving // entities riding something are saved with what they ride save(): SavedEntity[] { const saved = this.all().filter((entity) => !entity.vehicle && entity.persistent).map((entity) => entity.save() ); return [...saved, ...this.#unknown]; } load(saved: SavedEntity[]) { const unknown = new Set(); for (const entry of saved) { const entity = load_entity(this, entry); if (entity) { this.add_entity(entity); } else { this.#unknown.push(entry); unknown.add(String(entry?.id)); } } if (unknown.size) { console.warn( `Kept entities of unknown types for later, they're not in the world: ${[...unknown].join(", ")}`, ); } } } function position(entity: Entity) { return { x: entity.x, y: entity.y, z: entity.z, yaw: entity.yaw, pitch: entity.pitch, head_yaw: entity.head_yaw, }; } function data_json(entity: Entity) { return JSON.stringify(entity instanceof ItemEntity ? entity.item.to_data() : entity.synced_data()); }