diff --git a/client/client.ts b/client/client.ts index 288ed6e..8869127 100644 --- a/client/client.ts +++ b/client/client.ts @@ -3,6 +3,7 @@ import type { BlockHitResult } from "./level/client_level.ts"; import { LocalPlayer } from "./entity/local_player.ts"; import { RemotePlayer } from "./entity/remote_player.ts"; import { ItemEntity } from "./entity/item_entity.ts"; +import { RemoteEntity } from "./entity/remote_entity.ts"; import { Camera } from "./camera.ts"; import { Options } from "./options.ts"; import { MultiPlayerGameMode } from "./game_mode.ts"; @@ -69,7 +70,9 @@ export class Client { this.level.add_entity(new RemotePlayer(this.level, info)); } for (const info of connection.initial_entities) { - this.level.add_entity(new ItemEntity(this.level, info)); + this.level.add_entity( + info.kind === "item" ? new ItemEntity(this.level, info) : new RemoteEntity(this.level, info), + ); } this.game_mode = new MultiPlayerGameMode(this); diff --git a/client/entity/item_entity.ts b/client/entity/item_entity.ts index 1080c3d..eb0bc5f 100644 --- a/client/entity/item_entity.ts +++ b/client/entity/item_entity.ts @@ -25,7 +25,7 @@ export class ItemEntity extends Entity { #picked_up_by: Entity | undefined; #pickup_age = 0; - constructor(level: ClientLevel, info: EntityInfo) { + constructor(level: ClientLevel, info: Extract) { super(level, info.id, 0.25, 0.25, 0.125); this.item = ItemStack.from_data(info.item); this.set_position(info.x, info.y, info.z); diff --git a/client/entity/remote_entity.ts b/client/entity/remote_entity.ts new file mode 100644 index 0000000..0ccdb4b --- /dev/null +++ b/client/entity/remote_entity.ts @@ -0,0 +1,76 @@ +import type { EntityData, EntityInfo } from "$/common/protocol.ts"; +import type { ClientLevel } from "../level/client_level.ts"; +import { Entity } from "./entity.ts"; + +// how many ticks a server position takes to reach, like minecraft's lerpTo +const LERP_TICKS = 3; +// how long it flashes red after being hurt, and falls over after dying, like minecraft +const HURT_TICKS = 10; +const DEATH_TICKS = 20; + +// an entity the server simulates, like a mob. this only follows where it's told it is and keeps what it was told +// it looks like, for drawing it +export class RemoteEntity extends Entity { + // the entity type, like "bworld:item" + readonly type: string; + // synced data, see EntityData + data: EntityData; + head_yaw: number; + // counting down after a hurt event, and up after a death one + hurt_time = 0; + death_time = 0; + dead = false; + // what's riding it, by id + passengers: string[] = []; + + #target = { x: 0, y: 0, z: 0, yaw: 0, pitch: 0, head_yaw: 0 }; + #lerp_ticks = 0; + + constructor(level: ClientLevel, info: Extract) { + super(level, info.id, 0.6, 1.8, 1.62); + this.type = info.type; + this.data = info.data; + this.set_position(info.x, info.y, info.z); + this.yaw = info.yaw; + this.pitch = info.pitch; + this.head_yaw = info.head_yaw ?? info.yaw; + this.#target = { x: info.x, y: info.y, z: info.z, yaw: info.yaw, pitch: info.pitch, head_yaw: this.head_yaw }; + } + + lerp_to(x: number, y: number, z: number, yaw: number, pitch: number, head_yaw = yaw) { + this.#target = { x, y, z, yaw, pitch, head_yaw }; + this.#lerp_ticks = LERP_TICKS; + } + + on_event(event: "hurt" | "death") { + if (event === "hurt") { + this.hurt_time = HURT_TICKS; + } else { + this.dead = true; + } + } + + tick() { + if (this.hurt_time > 0) this.hurt_time -= 1; + if (this.dead) this.death_time = Math.min(DEATH_TICKS, this.death_time + 1); + + if (this.#lerp_ticks > 0) { + const t = 1 / this.#lerp_ticks; + const target = this.#target; + this.x += (target.x - this.x) * t; + this.y += (target.y - this.y) * t; + this.z += (target.z - this.z) * t; + this.yaw += wrap_angle(target.yaw - this.yaw) * t; + this.pitch += (target.pitch - this.pitch) * t; + this.head_yaw += wrap_angle(target.head_yaw - this.head_yaw) * t; + this.#lerp_ticks -= 1; + } + } +} + +function wrap_angle(angle: number) { + angle %= Math.PI * 2; + if (angle >= Math.PI) angle -= Math.PI * 2; + if (angle < -Math.PI) angle += Math.PI * 2; + return angle; +} diff --git a/client/packet_listener.ts b/client/packet_listener.ts index b3607ac..7a2214c 100644 --- a/client/packet_listener.ts +++ b/client/packet_listener.ts @@ -5,6 +5,7 @@ import { GuiContainer } from "./gui/gui_container.ts"; import { GuiChat } from "./gui/gui_chat.ts"; import { RemotePlayer } from "./entity/remote_player.ts"; import { ItemEntity } from "./entity/item_entity.ts"; +import { RemoteEntity } from "./entity/remote_entity.ts"; import { Player } from "./entity/player.ts"; // minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as @@ -94,12 +95,39 @@ export class ClientPacketListener { break; } case "add_entity": - level.add_entity(new ItemEntity(level, message.entity)); + level.add_entity( + message.entity.kind === "item" + ? new ItemEntity(level, message.entity) + : new RemoteEntity(level, message.entity), + ); break; case "move_entity": { const entity = level.entities.get(message.id); if (entity instanceof ItemEntity) { entity.lerp_to(message.x, message.y, message.z); + } else if (entity instanceof RemoteEntity) { + entity.lerp_to(message.x, message.y, message.z, message.yaw, message.pitch, message.head_yaw); + } + break; + } + case "entity_data": { + const entity = level.entities.get(message.id); + if (entity instanceof RemoteEntity) { + entity.data = message.data; + } + break; + } + case "entity_event": { + const entity = level.entities.get(message.id); + if (entity instanceof RemoteEntity) { + entity.on_event(message.event); + } + break; + } + case "set_passengers": { + const entity = level.entities.get(message.id); + if (entity instanceof RemoteEntity) { + entity.passengers = message.passengers; } break; } diff --git a/common/protocol.ts b/common/protocol.ts index e4b1a88..009ab2d 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 8; +export const PROTOCOL_VERSION = 9; export interface PlayerInfo { id: string; @@ -23,15 +23,28 @@ export interface PlayerInfo { slim?: boolean; } -// an entity that isn't a player, as the server first sends it. players have their own messages -export interface EntityInfo { - kind: "item"; - id: string; - x: number; - y: number; - z: number; - item: ItemData; -} +// an entity that isn't a player, as the server first sends it. players have their own messages. items on the +// ground have their own kind, everything else is "entity" with its type id +export type EntityInfo = + | { kind: "item"; id: string; x: number; y: number; z: number; item: ItemData } + | { + kind: "entity"; + type: string; + id: string; + x: number; + y: number; + z: number; + // radians, see the server's Entity + yaw: number; + pitch: number; + // for things whose head turns apart from their body + head_yaw?: number; + data: EntityData; + }; + +// what an entity looks like that can change, like minecraft's SynchedEntityData: custom_name, custom_name_visible, +// glowing, on_fire, silent, left_handed, equipment (slot to item). only what's set is there +export type EntityData = Record; // x, y, z, block id, and its state bits when they aren't 0 export type BlockChange = [number, number, number, string, number?]; @@ -105,7 +118,7 @@ export type ServerMessage = // the server may change the name asked for, like alice to alice2 name: string; players: PlayerInfo[]; - // items on the ground + // the entities within their view distance entities: EntityInfo[]; // the server's block id for each of its numeric ids, which level_chunk uses. clients number blocks their own way blocks: string[]; @@ -129,7 +142,22 @@ export type ServerMessage = // a player changed their skin, including the one receiving it. without skin it's back to the default | { type: "player_skin"; id: string; skin?: string; slim?: boolean } | { type: "add_entity"; entity: EntityInfo } - | { type: "move_entity"; id: string; x: number; y: number; z: number } + | { + type: "move_entity"; + id: string; + x: number; + y: number; + z: number; + yaw: number; + pitch: number; + head_yaw?: number; + } + // all of an entity's synced data, when any of it changed + | { type: "entity_data"; id: string; data: EntityData } + // hurt flashes it red, death starts it falling over (it's removed a second later) + | { type: "entity_event"; id: string; event: "hurt" | "death" } + // what's riding it now, by id + | { type: "set_passengers"; id: string; passengers: string[] } // a dropped item's stack changed, like when two stacks merge | { type: "set_entity_item"; id: string; item: ItemData } | { type: "remove_entity"; id: string } diff --git a/server/game/entity/attributes.ts b/server/game/entity/attributes.ts new file mode 100644 index 0000000..53bffbf --- /dev/null +++ b/server/game/entity/attributes.ts @@ -0,0 +1,177 @@ +// a living entity's stats, like minecraft's attributes: a base value that modifiers change without touching it. +// numbers are minecraft's, so movement_speed is its per tick value, see LivingEntity.travel + +export type ModifierOperation = "add_value" | "add_multiplied_base" | "add_multiplied_total"; +const OPERATIONS: ModifierOperation[] = ["add_value", "add_multiplied_base", "add_multiplied_total"]; + +export interface AttributeModifier { + // unique on the attribute, so it can be replaced or taken off, like "bworld:effect.speed" + id: string; + amount: number; + operation: ModifierOperation; +} + +export interface AttributeType { + id: string; + default: number; + min: number; + max: number; +} + +function attribute(id: string, value: number, min: number, max: number): AttributeType { + return { id: `bworld:${id}`, default: value, min, max }; +} + +export const ATTRIBUTES = { + max_health: attribute("max_health", 20, 1, 1024), + max_absorption: attribute("max_absorption", 0, 0, 2048), + armor: attribute("armor", 0, 0, 30), + armor_toughness: attribute("armor_toughness", 0, 0, 20), + knockback_resistance: attribute("knockback_resistance", 0, 0, 1), + movement_speed: attribute("movement_speed", 0.7, 0, 1024), + attack_damage: attribute("attack_damage", 2, 0, 2048), + attack_knockback: attribute("attack_knockback", 0, 0, 5), + // how far mobs notice players from, in blocks + follow_range: attribute("follow_range", 32, 0, 2048), + // how fast a jump starts, blocks per tick + jump_strength: attribute("jump_strength", 0.42, 0, 32), + step_height: attribute("step_height", 0.6, 0, 10), + // blocks per tick per tick + gravity: attribute("gravity", 0.08, -1, 1), + // blocks a fall can be without hurting + safe_fall_distance: attribute("safe_fall_distance", 3, -1024, 1024), + fall_damage_multiplier: attribute("fall_damage_multiplier", 1, 0, 100), +} satisfies Record; + +const BY_ID = new Map(Object.values(ATTRIBUTES).map((type) => [type.id, type])); + +export function attribute_type(id: string): AttributeType | undefined { + return BY_ID.get(id); +} + +// what level.json keeps of an attribute, see AttributeMap.save +export interface SavedAttribute { + id: string; + base: number; + modifiers?: AttributeModifier[]; +} + +export class Attribute { + readonly type: AttributeType; + #base: number; + #modifiers = new Map(); + #value: number | undefined; + + constructor(type: AttributeType, base = type.default) { + this.type = type; + this.#base = base; + } + + get base() { + return this.#base; + } + + set base(value: number) { + this.#base = value; + this.#value = undefined; + } + + get modifiers(): AttributeModifier[] { + return [...this.#modifiers.values()]; + } + + has_modifier(id: string) { + return this.#modifiers.has(id); + } + + // replaces one with the same id + add_modifier(modifier: AttributeModifier) { + this.#modifiers.set(modifier.id, { ...modifier }); + this.#value = undefined; + } + + remove_modifier(id: string) { + this.#value = undefined; + return this.#modifiers.delete(id); + } + + // like minecraft: X = base, plus every add_value. Y = X, plus X * amount for every add_multiplied_base, then + // times 1 + amount for every add_multiplied_total. clamped to the attribute's range + get value(): number { + if (this.#value === undefined) { + const modifiers = this.modifiers; + const of = (operation: ModifierOperation) => modifiers.filter((m) => m.operation === operation); + let x = this.#base; + for (const modifier of of("add_value")) x += modifier.amount; + let y = x; + for (const modifier of of("add_multiplied_base")) y += x * modifier.amount; + for (const modifier of of("add_multiplied_total")) y *= 1 + modifier.amount; + this.#value = Math.min(this.type.max, Math.max(this.type.min, y)); + } + return this.#value; + } +} + +// the attributes one entity has. which ones is up to its kind, like minecraft's default attribute suppliers +export class AttributeMap { + #attributes = new Map(); + + // the types it has, with the kind's base values where they aren't the default + constructor(types: [AttributeType, number?][]) { + for (const [type, base] of types) { + this.#attributes.set(type.id, new Attribute(type, base)); + } + } + + has(type: AttributeType) { + return this.#attributes.has(type.id); + } + + get(type: AttributeType): Attribute | undefined { + return this.#attributes.get(type.id); + } + + // the default for attributes it doesn't have + value(type: AttributeType): number { + return this.#attributes.get(type.id)?.value ?? type.default; + } + + all(): Attribute[] { + return [...this.#attributes.values()]; + } + + // only what isn't the kind's defaults: changed bases and any modifiers + save(defaults: AttributeMap): SavedAttribute[] { + const saved: SavedAttribute[] = []; + for (const attribute of this.#attributes.values()) { + const modifiers = attribute.modifiers; + if (attribute.base === defaults.get(attribute.type)?.base && modifiers.length === 0) continue; + saved.push( + modifiers.length ? { id: attribute.type.id, base: attribute.base, modifiers } : { + id: attribute.type.id, + base: attribute.base, + }, + ); + } + return saved; + } + + // attributes it doesn't have, or that don't exist anymore, are skipped + load(saved: unknown) { + if (!Array.isArray(saved)) return; + for (const entry of saved as SavedAttribute[]) { + const type = attribute_type(entry?.id); + const attribute = type && this.#attributes.get(type.id); + if (!attribute) continue; + if (typeof entry.base === "number" && Number.isFinite(entry.base)) attribute.base = entry.base; + for (const modifier of Array.isArray(entry.modifiers) ? entry.modifiers : []) { + if ( + typeof modifier?.id === "string" && typeof modifier.amount === "number" && + OPERATIONS.includes(modifier.operation) + ) { + attribute.add_modifier(modifier); + } + } + } + } +} diff --git a/server/game/entity/effects.ts b/server/game/entity/effects.ts new file mode 100644 index 0000000..4629f47 --- /dev/null +++ b/server/game/entity/effects.ts @@ -0,0 +1,261 @@ +// status effects on living entities, like minecraft's MobEffect and MobEffectInstance. an effect is a type plus +// how strong it is and for how long. a weaker one that lasts longer waits hidden under the stronger one, and takes +// over when that runs out +import { ATTRIBUTES, type AttributeType, type ModifierOperation } from "./attributes.ts"; +import { DAMAGE, finite } from "./entity.ts"; +import type { LivingEntity } from "./living_entity.ts"; + +export interface EffectType { + id: string; + beneficial: boolean; + // happens once when added instead of lasting, like instant health + instant?: boolean; + // while it's on. amount is for level 1 and goes up with each level, like minecraft + modifiers?: { attribute: AttributeType; amount: number; operation: ModifierOperation }[]; + // whether on_tick runs this tick, from the ticks left (or its age for infinite ones) + should_tick?(duration: number, amplifier: number): boolean; + // returning false takes the effect off + on_tick?(entity: LivingEntity, amplifier: number): boolean | void; + apply_instant?(entity: LivingEntity, amplifier: number): void; + on_added?(entity: LivingEntity, amplifier: number): void; + on_removed?(entity: LivingEntity, amplifier: number): void; +} + +// every n ticks, n halving with each level: minecraft's regeneration, poison and wither +const every = (ticks: number) => (duration: number, amplifier: number) => { + const interval = ticks >> amplifier; + return interval > 0 ? duration % interval === 0 : true; +}; + +function effect(id: string, beneficial: boolean, rest: Omit = {}): EffectType { + return { id: `bworld:${id}`, beneficial, ...rest }; +} + +export const EFFECTS = { + speed: effect("speed", true, { + modifiers: [{ attribute: ATTRIBUTES.movement_speed, amount: 0.2, operation: "add_multiplied_total" }], + }), + slowness: effect("slowness", false, { + modifiers: [{ attribute: ATTRIBUTES.movement_speed, amount: -0.15, operation: "add_multiplied_total" }], + }), + strength: effect("strength", true, { + modifiers: [{ attribute: ATTRIBUTES.attack_damage, amount: 3, operation: "add_value" }], + }), + weakness: effect("weakness", false, { + modifiers: [{ attribute: ATTRIBUTES.attack_damage, amount: -4, operation: "add_value" }], + }), + jump_boost: effect("jump_boost", true, { + modifiers: [{ attribute: ATTRIBUTES.safe_fall_distance, amount: 1, operation: "add_value" }], + }), + health_boost: effect("health_boost", true, { + modifiers: [{ attribute: ATTRIBUTES.max_health, amount: 4, operation: "add_value" }], + on_removed: (entity) => entity.health = Math.min(entity.health, entity.max_health), + }), + absorption: effect("absorption", true, { + modifiers: [{ attribute: ATTRIBUTES.max_absorption, amount: 4, operation: "add_value" }], + on_added: (entity, amplifier) => entity.absorption = Math.max(entity.absorption, 4 * (amplifier + 1)), + }), + regeneration: effect("regeneration", true, { + should_tick: every(50), + on_tick: (entity) => { + if (entity.health < entity.max_health) entity.heal(1); + }, + }), + poison: effect("poison", false, { + should_tick: every(25), + on_tick: (entity) => { + // never kills + if (entity.health > 1) entity.hurt(1, DAMAGE.magic); + }, + }), + wither: effect("wither", false, { + should_tick: every(40), + on_tick: (entity) => void entity.hurt(1, DAMAGE.wither), + }), + instant_health: effect("instant_health", true, { + instant: true, + apply_instant: (entity, amplifier) => entity.heal(Math.max(4 << amplifier, 0)), + }), + instant_damage: effect("instant_damage", false, { + instant: true, + apply_instant: (entity, amplifier) => void entity.hurt(Math.max(6 << amplifier, 0), DAMAGE.magic), + }), + // these do their thing where it happens: LivingEntity's damage, air and travel, and synced data + resistance: effect("resistance", true), + fire_resistance: effect("fire_resistance", true), + water_breathing: effect("water_breathing", true), + slow_falling: effect("slow_falling", true), + glowing: effect("glowing", false), +} satisfies Record; + +const registry = new Map(Object.values(EFFECTS).map((type) => [type.id, type])); + +// adds an effect type, or replaces one with the same id +export function register_effect(type: EffectType) { + registry.set(type.id, type); +} + +export function effect_type(id: string): EffectType | undefined { + return registry.get(id); +} + +// what level.json keeps of an effect, the doc's active_effects entries +export interface SavedEffect { + id: string; + amplifier?: number; + duration: number; + ambient?: boolean; + show_particles?: boolean; + show_icon?: boolean; + // without its id, it's the same effect + hidden_effect?: Omit; +} + +export interface EffectOptions { + // level minus 1 + amplifier?: number; + // from a beacon, particles are fainter + ambient?: boolean; + show_particles?: boolean; + show_icon?: boolean; +} + +export class EffectInstance { + readonly type: EffectType; + // ticks left, -1 for forever + duration: number; + amplifier: number; + ambient: boolean; + show_particles: boolean; + show_icon: boolean; + // the same effect, weaker but longer, waiting for this one to run out + hidden: EffectInstance | undefined; + + constructor(type: EffectType, duration: number, options: EffectOptions = {}) { + this.type = type; + this.duration = duration; + this.amplifier = options.amplifier ?? 0; + this.ambient = options.ambient ?? false; + this.show_particles = options.show_particles ?? true; + this.show_icon = options.show_icon ?? true; + } + + get infinite() { + return this.duration === -1; + } + + get has_time_left() { + return this.infinite || this.duration > 0; + } + + copy(): EffectInstance { + const copy = new EffectInstance(this.type, this.duration, this); + copy.hidden = this.hidden?.copy(); + return copy; + } + + #shorter_than(other: EffectInstance) { + return !this.infinite && (this.duration < other.duration || other.infinite); + } + + #take_details(other: EffectInstance) { + this.duration = other.duration; + this.amplifier = other.amplifier; + this.ambient = other.ambient; + this.show_particles = other.show_particles; + this.show_icon = other.show_icon; + } + + // the same effect added again, like minecraft's MobEffectInstance.update. returns whether this one changed, + // a longer weaker one only goes into hidden + update(other: EffectInstance): boolean { + let changed = false; + if (other.amplifier > this.amplifier) { + if (other.#shorter_than(this)) { + const old_hidden = this.hidden; + this.hidden = this.copy(); + this.hidden.hidden = old_hidden; + } + this.amplifier = other.amplifier; + this.duration = other.duration; + changed = true; + } else if (this.#shorter_than(other)) { + if (other.amplifier === this.amplifier) { + this.duration = other.duration; + changed = true; + } else if (!this.hidden) { + this.hidden = other.copy(); + } else { + this.hidden.update(other); + } + } + if ((!other.ambient && this.ambient) || changed) { + this.ambient = other.ambient; + changed = true; + } + if (other.show_particles !== this.show_particles) { + this.show_particles = other.show_particles; + changed = true; + } + if (other.show_icon !== this.show_icon) { + this.show_icon = other.show_icon; + changed = true; + } + return changed; + } + + // one tick: does what it does, counts down, and lets the hidden one take over when it's done. returns "ended", + // "changed" when a hidden one took over, or undefined + tick(entity: LivingEntity): "ended" | "changed" | undefined { + if (!this.has_time_left) return "ended"; + const count = this.infinite ? entity.age : this.duration; + if (this.type.should_tick?.(count, this.amplifier) && this.type.on_tick?.(entity, this.amplifier) === false) { + return "ended"; + } + this.#count_down(); + if (this.duration === 0 && this.hidden) { + this.#take_details(this.hidden); + this.hidden = this.hidden.hidden; + return "changed"; + } + return this.has_time_left ? undefined : "ended"; + } + + #count_down() { + if (this.hidden) this.hidden.#count_down(); + if (!this.infinite) this.duration = Math.max(0, this.duration - 1); + } + + save(): SavedEffect { + return { id: this.type.id, ...this.#save_details() }; + } + + #save_details(): Omit { + const saved: Omit = { duration: this.duration }; + if (this.amplifier) saved.amplifier = this.amplifier; + if (this.ambient) saved.ambient = true; + if (!this.show_particles) saved.show_particles = false; + if (!this.show_icon) saved.show_icon = false; + if (this.hidden) saved.hidden_effect = this.hidden.#save_details(); + return saved; + } + + // undefined for effects that don't exist anymore + static load(saved: SavedEffect): EffectInstance | undefined { + const type = effect_type(saved?.id); + return type && EffectInstance.#load_details(type, saved); + } + + static #load_details(type: EffectType, saved: Omit): EffectInstance { + const effect = new EffectInstance(type, finite(saved.duration, 0), { + amplifier: finite(saved.amplifier, 0), + ambient: saved.ambient === true, + show_particles: saved.show_particles !== false, + show_icon: saved.show_icon !== false, + }); + if (typeof saved.hidden_effect === "object" && saved.hidden_effect !== null) { + effect.hidden = EffectInstance.#load_details(type, saved.hidden_effect); + } + return effect; + } +} diff --git a/server/game/entity/entity.ts b/server/game/entity/entity.ts new file mode 100644 index 0000000..d0563d3 --- /dev/null +++ b/server/game/entity/entity.ts @@ -0,0 +1,467 @@ +// the server's entities, like minecraft's Entity: things in the world that aren't blocks and move on their own. the +// fields are minecraft's (see ENTITIES.md), without the ones for things the game doesn't have like portals and powder +// snow. players are ServerPlayer, which isn't one of these (yet) +// +// like minecraft's, a kind of entity inherits from one class (Entity, LivingEntity, Mob, or another kind) and can +// implement any number of interfaces +import { TICKS_PER_SECOND } from "$/common/constants.ts"; +import type { BlockRegistry } from "$/common/everything_registry.ts"; +import type { ItemStack } from "$/common/inventory.ts"; +import { type Collisions, move_body } from "$/common/physics.ts"; +import type { EntityData, EntityInfo } from "$/common/protocol.ts"; + +// below this, entities have fallen out of the world +export const VOID_Y = -64; +// the most air most things hold, 15 seconds +export const MAX_AIR = 300; +// motion faster than minecraft's 10 blocks a tick is reset when loading +const MAX_LOADED_SPEED = 10 * TICKS_PER_SECOND; +// like minecraft +export const MAX_TAGS = 1024; + +// something that can hurt an entity: another entity, or a player +export interface Attacker { + readonly id: string; + readonly x: number; + readonly y: number; + readonly z: number; +} + +// a player as entities see them, ServerPlayer is one +export interface PlayerTarget extends Attacker { + readonly name: string; +} + +// what hurt something. cause is for mods and death messages, like "fall", "drown" or "mob_attack" +export interface DamageSource { + cause: string; + // who did it, which knockback pushes away from + attacker?: Attacker; + by_player?: boolean; + // fire resistance stops it + fire?: boolean; + // armor doesn't help, like drowning, falling and starving + bypasses_armor?: boolean; + // even invulnerable entities are hurt, like falling out of the world + bypasses_invulnerability?: boolean; +} + +export const DAMAGE = { + generic: { cause: "generic" }, + fall: { cause: "fall", bypasses_armor: true }, + drown: { cause: "drown", bypasses_armor: true }, + on_fire: { cause: "on_fire", fire: true, bypasses_armor: true }, + void: { cause: "void", bypasses_armor: true, bypasses_invulnerability: true }, + magic: { cause: "magic", bypasses_armor: true }, + wither: { cause: "wither", bypasses_armor: true }, +} satisfies Record; + +// what entities can see and do in the world, the entity manager is one +export interface EntityLevel { + readonly current_tick: number; + has_collision(x: number, y: number, z: number): boolean; + // water, and other blocks you're in instead of on + is_liquid(x: number, y: number, z: number): boolean; + get_block_info(x: number, y: number, z: number): BlockRegistry | undefined; + add_entity(entity: Entity): void; + get_entity(id: string): Entity | undefined; + // entities whose feet are within the box around x, y, z + entities_near(x: number, y: number, z: number, radius: number): Entity[]; + nearest_player(x: number, y: number, z: number, max_distance: number): PlayerTarget | undefined; + damage_player(id: string, amount: number, source: DamageSource): void; + spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay?: number): Entity; + // an item on the ground was picked up whole by who, clients see it fly to them. it's gone after + take_item(item: Entity, by: string): void; + // sent to clients tracking the entity, for the renderer: "hurt" flashes it red, "death" starts falling over + entity_event(entity: Entity, event: "hurt" | "death"): void; + // it died, after dropping its things + on_death(entity: Entity, source: DamageSource): void; +} + +// an entity as level.json keeps it, see Entity.save. each kind adds its own fields +export interface SavedEntity { + // the entity type + id: string; + uuid: string; + pos: [number, number, number]; + // blocks per second + motion: [number, number, number]; + // yaw and pitch, in radians + rotation: [number, number]; + on_ground?: boolean; + fall_distance?: number; + fire?: number; + air?: number; + no_gravity?: boolean; + invulnerable?: boolean; + invulnerable_time?: number; + glowing?: boolean; + has_visual_fire?: boolean; + silent?: boolean; + custom_name?: string; + custom_name_visible?: boolean; + tags?: string[]; + // anything mods want to keep on it + data?: Record; + passengers?: SavedEntity[]; + [field: string]: unknown; +} + +export abstract class Entity { + // the entity type, like "bworld:item". see entity_types.ts + abstract readonly type: string; + readonly level: EntityLevel; + // a UUID, which clients know it by too + id: string = crypto.randomUUID(); + + // the middle of its feet + x = 0; + y = 0; + z = 0; + // blocks per second + vx = 0; + vy = 0; + vz = 0; + // radians. yaw 0 faces north (-z) and pi / 2 west, pitch goes up looking down + yaw = 0; + pitch = 0; + // where its head looks, for things whose head turns apart from their body + head_yaw: number | undefined; + + // the collision box, width is for both x and z + width = 0.6; + height = 1.8; + eye_height = 1.62; + // blocks per second squared, minecraft's 0.08 blocks per tick per tick + gravity = -32; + // what's left of its speed after each tick + drag = 0.98; + // what it walks up onto without jumping, see move_body + step_height = 0; + + on_ground = false; + // it walked into something sideways last move + horizontal_collision = false; + in_water = false; + // blocks fallen since it last stood on something, landing turns it into fall damage + fall_distance = 0; + no_gravity = false; + + // ticks until the fire goes out, not burning at 0 or less + fire = 0; + // ticks of breath left, see LivingEntity + air = MAX_AIR; + + invulnerable = false; + // ticks it can't be hurt for, counting down + invulnerable_time = 0; + // for the renderer: an outline seen through walls, and looking on fire without burning + glowing = false; + has_visual_fire = false; + silent = false; + custom_name: string | undefined; + // the name shows above it all the time, not only when looked at + custom_name_visible = false; + // scoreboard tags, like minecraft's /tag + tags = new Set(); + // anything mods want to keep on it, saved with it + data: Record = {}; + + passengers: Entity[] = []; + vehicle: Entity | undefined; + + // ticks since it was made, or loaded + age = 0; + removed = false; + + constructor(level: EntityLevel) { + this.level = level; + } + + get is_on_fire() { + return this.fire > 0; + } + + // immune to fire and burning, like minecraft's fireImmune entity types + get fire_immune() { + return false; + } + + get max_air() { + return MAX_AIR; + } + + set_position(x: number, y: number, z: number) { + this.x = x; + this.y = y; + this.z = z; + } + + // one tick. entities riding something don't move themselves, their vehicle places them + tick() { + this.base_tick(); + if (!this.vehicle) { + this.move(); + this.apply_drag(); + } + } + + // what every entity does each tick, like minecraft's Entity.baseTick + base_tick() { + this.age += 1; + if (this.invulnerable_time > 0) { + this.invulnerable_time -= 1; + } + + this.update_in_water(); + if (this.in_water) { + this.fall_distance = 0; + this.fire = 0; + } + + if (this.fire > 0) { + if (this.fire_immune) { + this.fire = Math.max(0, this.fire - 4); + } else { + if (this.fire % 20 === 0) { + this.hurt(1, DAMAGE.on_fire); + } + this.fire -= 1; + } + } + + if (this.y < VOID_Y) { + this.on_below_world(); + } + } + + update_in_water() { + const x = Math.floor(this.x); + const z = Math.floor(this.z); + this.in_water = this.level.is_liquid(x, Math.floor(this.y), z) || + this.level.is_liquid(x, Math.floor(this.y + this.height / 2), z); + } + + // its eyes are in water, so it can't breathe + get eyes_in_water() { + return this.level.is_liquid(Math.floor(this.x), Math.floor(this.y + this.eye_height), Math.floor(this.z)); + } + + // falls and moves by its velocity for one tick (see move_body), and counts how far it fell. returns what it hit + move(): Collisions { + const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z); + const from_y = this.y; + const collisions = move_body( + this, + this.no_gravity ? 0 : this.gravity, + is_solid, + this.step_height, + this.on_ground, + ); + this.on_ground = collisions.y === 1; + this.horizontal_collision = collisions.x !== 0 || collisions.z !== 0; + this.update_fall_distance(this.y - from_y); + return collisions; + } + + // like minecraft's checkFallDamage: landing after a fall hurts, water breaks the fall + update_fall_distance(dy: number) { + if (this.in_water) { + this.fall_distance = 0; + } else if (this.on_ground) { + if (this.fall_distance > 0) { + this.fall_damage(this.fall_distance); + } + this.fall_distance = 0; + } else if (dy < 0) { + this.fall_distance -= dy; + } + } + + // it landed after falling that far, only living entities get hurt + fall_damage(_distance: number) {} + + apply_drag() { + this.vx *= this.drag; + this.vy *= this.drag; + this.vz *= this.drag; + } + + // hurts it, returns whether it was. most entities can't be, see LivingEntity + hurt(_amount: number, _source: DamageSource): boolean { + return false; + } + + is_invulnerable_to(source: DamageSource) { + if (this.removed) return true; + if (source.fire && this.fire_immune) return true; + return (this.invulnerable || this.invulnerable_time > 0) && !source.bypasses_invulnerability; + } + + // y is below VOID_Y. things that can't die just go away + on_below_world() { + this.remove(); + } + + // burns for at least that long, like minecraft's igniteForSeconds + set_on_fire(seconds: number) { + if (!this.fire_immune) { + this.fire = Math.max(this.fire, Math.round(seconds * TICKS_PER_SECOND)); + } + } + + extinguish() { + this.fire = 0; + } + + // takes it out of the world. the entity manager tells clients and forgets it + remove() { + if (this.removed) return; + this.removed = true; + this.stop_riding(); + this.eject_passengers(); + } + + add_tag(tag: string) { + if (this.tags.size >= MAX_TAGS) return false; + this.tags.add(tag); + return true; + } + + // riding + + // false when it can't: riding itself, or something riding it + start_riding(vehicle: Entity) { + for (let v: Entity | undefined = vehicle; v; v = v.vehicle) { + if (v === this) return false; + } + this.stop_riding(); + this.vehicle = vehicle; + vehicle.passengers.push(this); + return true; + } + + stop_riding() { + const vehicle = this.vehicle; + if (!vehicle) return; + this.vehicle = undefined; + vehicle.passengers = vehicle.passengers.filter((p) => p !== this); + } + + eject_passengers() { + for (const passenger of [...this.passengers]) passenger.stop_riding(); + } + + // ticks its passengers and puts them on top of it, then theirs, like minecraft's rideTick + tick_passengers() { + for (const passenger of [...this.passengers]) { + if (passenger.removed || passenger.vehicle !== this) continue; + passenger.tick(); + this.position_passenger(passenger); + passenger.tick_passengers(); + } + } + + // on top of it by default + position_passenger(passenger: Entity) { + passenger.set_position(this.x, this.y + this.height, this.z); + passenger.vx = passenger.vy = passenger.vz = 0; + passenger.fall_distance = 0; + } + + // what clients get + + info(): EntityInfo { + return { + kind: "entity", + type: this.type, + id: this.id, + x: this.x, + y: this.y, + z: this.z, + yaw: this.yaw, + pitch: this.pitch, + head_yaw: this.head_yaw, + data: this.synced_data(), + }; + } + + // what clients need to draw it that can change, resent whenever it does. like minecraft's SynchedEntityData + synced_data(): EntityData { + const data: EntityData = {}; + if (this.custom_name !== undefined) data.custom_name = this.custom_name; + if (this.custom_name_visible) data.custom_name_visible = true; + if (this.glowing) data.glowing = true; + if (this.is_on_fire || this.has_visual_fire) data.on_fire = true; + if (this.silent) data.silent = true; + return data; + } + + // saving, like minecraft's saveWithoutId and load. kinds add their own fields in save_additional + + save(): SavedEntity { + const saved: SavedEntity = { + id: this.type, + uuid: this.id, + pos: [this.x, this.y, this.z], + motion: [this.vx, this.vy, this.vz], + rotation: [this.yaw, this.pitch], + }; + if (this.on_ground) saved.on_ground = true; + if (this.fall_distance) saved.fall_distance = this.fall_distance; + if (this.fire) saved.fire = this.fire; + if (this.air !== this.max_air) saved.air = this.air; + if (this.no_gravity) saved.no_gravity = true; + if (this.invulnerable) saved.invulnerable = true; + if (this.invulnerable_time > 0) saved.invulnerable_time = this.invulnerable_time; + if (this.glowing) saved.glowing = true; + if (this.has_visual_fire) saved.has_visual_fire = true; + if (this.silent) saved.silent = true; + if (this.custom_name !== undefined) saved.custom_name = this.custom_name; + if (this.custom_name_visible) saved.custom_name_visible = true; + if (this.tags.size) saved.tags = [...this.tags]; + if (Object.keys(this.data).length) saved.data = structuredClone(this.data); + const passengers = this.passengers.filter((p) => !p.removed).map((p) => p.save()); + if (passengers.length) saved.passengers = passengers; + this.save_additional(saved); + return saved; + } + + save_additional(_saved: SavedEntity) {} + + // passengers are loaded by entity_types.ts, which knows how to make each kind + load(saved: SavedEntity) { + if (typeof saved.uuid === "string") this.id = saved.uuid; + const [x, y, z] = numbers(saved.pos, 3); + this.set_position(x, y, z); + [this.vx, this.vy, this.vz] = numbers(saved.motion, 3).map((v) => Math.abs(v) > MAX_LOADED_SPEED ? 0 : v); + [this.yaw, this.pitch] = numbers(saved.rotation, 2); + this.on_ground = saved.on_ground === true; + this.fall_distance = finite(saved.fall_distance, 0); + this.fire = finite(saved.fire, 0); + this.air = finite(saved.air, this.max_air); + this.no_gravity = saved.no_gravity === true; + this.invulnerable = saved.invulnerable === true; + this.invulnerable_time = finite(saved.invulnerable_time, 0); + this.glowing = saved.glowing === true; + this.has_visual_fire = saved.has_visual_fire === true; + this.silent = saved.silent === true; + this.custom_name = typeof saved.custom_name === "string" ? saved.custom_name : undefined; + this.custom_name_visible = saved.custom_name_visible === true; + this.tags = new Set(Array.isArray(saved.tags) ? saved.tags.filter((t) => typeof t === "string") : []); + this.data = typeof saved.data === "object" && saved.data !== null ? structuredClone(saved.data) : {}; + this.load_additional(saved); + } + + load_additional(_saved: SavedEntity) {} +} + +// a number from a save, or the fallback when it isn't one +export function finite(value: unknown, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +function numbers(value: unknown, count: number): number[] { + const list = Array.isArray(value) ? value : []; + return Array.from({ length: count }, (_, i) => finite(list[i], 0)); +} diff --git a/server/game/entity/entity_manager.ts b/server/game/entity/entity_manager.ts new file mode 100644 index 0000000..e06176e --- /dev/null +++ b/server/game/entity/entity_manager.ts @@ -0,0 +1,289 @@ +// 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 type { ItemStack } from "$/common/inventory.ts"; +import type { EntityInfo, ServerMessage } from "$/common/protocol.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"; + +// 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; + damage_player(player: ServerPlayer, amount: number, cause: string): void; + on_entity_death?(entity: Entity, source: DamageSource): void; +} + +// 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 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); + } + + is_liquid(x: number, y: number, z: number) { + const info = this.#host.world.get_block_info(x, y, z); + return info !== undefined && !info.has_collision && info.replaceable === true; + } + + get_block_info(x: number, y: number, z: number) { + return this.#host.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; + } + + damage_player(id: string, amount: number, source: DamageSource) { + const player = this.#host.players().find((player) => player.id === id); + if (player) this.#host.damage_player(player, amount, source.cause); + } + + 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); + } + + entity_event(entity: Entity, event: "hurt" | "death") { + for (const [player, tracked] of this.#tracked) { + if (tracked.has(entity.id)) this.#host.send(player, { type: "entity_event", id: entity.id, event }); + } + } + + on_death(entity: Entity, source: DamageSource) { + this.#host.on_entity_death?.(entity, source); + } + + // 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).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()); +} diff --git a/server/game/entity/entity_types.ts b/server/game/entity/entity_types.ts new file mode 100644 index 0000000..eb93763 --- /dev/null +++ b/server/game/entity/entity_types.ts @@ -0,0 +1,35 @@ +// every kind of entity by its type id, like minecraft's EntityType registry: how saved entities come back +import type { Entity, EntityLevel, SavedEntity } from "./entity.ts"; +import { ITEM_ENTITY_TYPE, ItemEntity } from "./item_entity.ts"; + +// makes a blank entity of the kind, load fills it in +export type EntityFactory = (level: EntityLevel) => Entity; + +const types = new Map([ + [ITEM_ENTITY_TYPE, (level) => new ItemEntity(level)], +]); + +// adds a kind, or replaces one with the same id +export function register_entity_type(id: string, factory: EntityFactory) { + types.set(id, factory); +} + +export function has_entity_type(id: string) { + return types.has(id); +} + +export function create_entity(level: EntityLevel, id: string): Entity | undefined { + return types.get(id)?.(level); +} + +// the entity and its passengers, riding it. undefined for kinds that don't exist (anymore), passengers of unknown +// kinds are left behind +export function load_entity(level: EntityLevel, saved: SavedEntity): Entity | undefined { + const entity = create_entity(level, saved?.id); + if (!entity) return undefined; + entity.load(saved); + for (const saved_passenger of Array.isArray(saved.passengers) ? saved.passengers : []) { + load_entity(level, saved_passenger)?.start_riding(entity); + } + return entity; +} diff --git a/server/game/entity/goals.ts b/server/game/entity/goals.ts new file mode 100644 index 0000000..56c2c15 --- /dev/null +++ b/server/game/entity/goals.ts @@ -0,0 +1,360 @@ +// what mobs decide to do, like minecraft's Goal and GoalSelector. each goal says when it wants to run and which +// controls it needs (its flags), and the most important goals that can run get them. a lower priority number is +// more important, and can take a flag from a less important goal that's running +import { PLAYER_WIDTH } from "$/common/constants.ts"; +import { ATTRIBUTES } from "./attributes.ts"; +import { Entity, type PlayerTarget } from "./entity.ts"; +import { LivingEntity } from "./living_entity.ts"; +import type { Mob } from "./mob.ts"; + +export type GoalFlag = "move" | "look" | "jump" | "target"; + +export abstract class Goal { + flags: GoalFlag[] = []; + + // whether it wants to start + abstract can_use(): boolean; + + // whether it wants to keep going + can_continue_to_use() { + return this.can_use(); + } + + // a more important goal can take its flags + is_interruptable() { + return true; + } + + start() {} + stop() {} + tick() {} +} + +interface WrappedGoal { + priority: number; + goal: Goal; + running: boolean; +} + +export class GoalSelector { + #goals: WrappedGoal[] = []; + // which running goal holds each flag + #locks = new Map(); + // flags no goal can have, like "move" while ridden + disabled = new Set(); + + add_goal(priority: number, goal: Goal) { + this.#goals.push({ priority, goal, running: false }); + this.#goals.sort((a, b) => a.priority - b.priority); + } + + remove_goal(goal: Goal) { + for (const wrapped of this.#goals.filter((w) => w.goal === goal)) this.#stop(wrapped); + this.#goals = this.#goals.filter((w) => w.goal !== goal); + } + + get running(): Goal[] { + return this.#goals.filter((w) => w.running).map((w) => w.goal); + } + + tick() { + for (const wrapped of this.#goals) { + if ( + wrapped.running && + (wrapped.goal.flags.some((flag) => this.disabled.has(flag)) || !wrapped.goal.can_continue_to_use()) + ) { + this.#stop(wrapped); + } + } + + for (const wrapped of this.#goals) { + if (wrapped.running || wrapped.goal.flags.some((flag) => this.disabled.has(flag))) continue; + const free = wrapped.goal.flags.every((flag) => { + const holder = this.#locks.get(flag); + return !holder || (holder.priority > wrapped.priority && holder.goal.is_interruptable()); + }); + if (!free || !wrapped.goal.can_use()) continue; + for (const flag of wrapped.goal.flags) { + const holder = this.#locks.get(flag); + if (holder) this.#stop(holder); + this.#locks.set(flag, wrapped); + } + wrapped.running = true; + wrapped.goal.start(); + } + + for (const wrapped of this.#goals) { + if (wrapped.running) wrapped.goal.tick(); + } + } + + #stop(wrapped: WrappedGoal) { + if (!wrapped.running) return; + wrapped.running = false; + wrapped.goal.stop(); + for (const [flag, holder] of this.#locks) { + if (holder === wrapped) this.#locks.delete(flag); + } + } +} + +// some goals most mobs use, like minecraft's + +// swims up in water so it doesn't drown +export class FloatGoal extends Goal { + override flags: GoalFlag[] = ["jump"]; + + constructor(readonly mob: Mob) { + super(); + } + + can_use() { + return this.mob.in_water; + } + + override tick() { + if (this.mob.random() < 0.8) this.mob.jump_control.jump(); + } +} + +// wanders to a random spot nearby every now and then, staying near home +export class RandomStrollGoal extends Goal { + override flags: GoalFlag[] = ["move"]; + // there's no pathfinding, so it gives up on a spot it can't get to + #ticks = 0; + #wanted: { x: number; y: number; z: number } | undefined; + + // interval is how many ticks it waits between strolls on average + constructor(readonly mob: Mob, readonly speed_modifier = 1, readonly interval = 120, readonly range = 10) { + super(); + } + + can_use() { + if (this.mob.random() * this.interval >= 1) return false; + this.#wanted = random_stand_position(this.mob, this.range, 7); + return this.#wanted !== undefined; + } + + override can_continue_to_use() { + const wanted = this.#wanted; + return wanted !== undefined && this.#ticks < 200 && + (wanted.x - this.mob.x) ** 2 + (wanted.z - this.mob.z) ** 2 > 0.25; + } + + override start() { + this.#ticks = 0; + const { x, y, z } = this.#wanted!; + this.mob.move_control.move_to(x, y, z, this.speed_modifier); + } + + override tick() { + this.#ticks += 1; + } + + override stop() { + this.#wanted = undefined; + this.mob.move_control.stop(); + } +} + +// runs around fast after being hurt or while burning, like minecraft's PanicGoal +export class PanicGoal extends Goal { + override flags: GoalFlag[] = ["move"]; + #wanted: { x: number; y: number; z: number } | undefined; + + constructor(readonly mob: Mob, readonly speed_modifier = 1.25) { + super(); + } + + #should_panic() { + const mob = this.mob; + return mob.last_hurt_by_mob !== undefined || mob.last_hurt_by_player_memory_time > 0 || mob.is_on_fire; + } + + can_use() { + if (!this.#should_panic()) return false; + this.#wanted = random_stand_position(this.mob, 5, 4); + return this.#wanted !== undefined; + } + + override can_continue_to_use() { + const wanted = this.#wanted; + return wanted !== undefined && (wanted.x - this.mob.x) ** 2 + (wanted.z - this.mob.z) ** 2 > 0.25; + } + + override start() { + const { x, y, z } = this.#wanted!; + this.mob.move_control.move_to(x, y, z, this.speed_modifier); + } + + override stop() { + this.#wanted = undefined; + this.mob.move_control.stop(); + } +} + +// looks at a nearby player for a couple of seconds, now and then +export class LookAtPlayerGoal extends Goal { + override flags: GoalFlag[] = ["look"]; + #player: PlayerTarget | undefined; + #ticks = 0; + + constructor(readonly mob: Mob, readonly range = 8, readonly probability = 0.02) { + super(); + } + + can_use() { + if (this.mob.random() >= this.probability) return false; + this.#player = this.mob.level.nearest_player(this.mob.x, this.mob.y, this.mob.z, this.range); + return this.#player !== undefined; + } + + override can_continue_to_use() { + const player = this.#player; + return player !== undefined && this.#ticks > 0 && + Math.hypot(player.x - this.mob.x, player.y - this.mob.y, player.z - this.mob.z) <= this.range; + } + + override start() { + this.#ticks = 40 + Math.floor(this.mob.random() * 40); + } + + override stop() { + this.#player = undefined; + } + + override tick() { + this.#ticks -= 1; + this.mob.look_control.look_at_entity(this.#player!); + } +} + +// looks around at nothing in particular +export class RandomLookAroundGoal extends Goal { + override flags: GoalFlag[] = ["move", "look"]; + #dx = 0; + #dz = 0; + #ticks = 0; + + constructor(readonly mob: Mob) { + super(); + } + + can_use() { + return this.mob.random() < 0.02; + } + + override can_continue_to_use() { + return this.#ticks >= 0; + } + + override start() { + const angle = this.mob.random() * Math.PI * 2; + this.#dx = Math.cos(angle); + this.#dz = Math.sin(angle); + this.#ticks = 20 + Math.floor(this.mob.random() * 20); + } + + override tick() { + this.#ticks -= 1; + const mob = this.mob; + mob.look_control.look_at(mob.x + this.#dx, mob.y + mob.eye_height, mob.z + this.#dz); + } +} + +// walks to its target and hits it when close, like minecraft's MeleeAttackGoal without the pathfinding +export class MeleeAttackGoal extends Goal { + override flags: GoalFlag[] = ["move", "look"]; + #cooldown = 0; + + constructor(readonly mob: Mob, readonly speed_modifier = 1, readonly attack_interval = 20) { + super(); + } + + can_use() { + const target = this.mob.target; + return target !== undefined && is_alive(target); + } + + override start() { + this.#cooldown = 0; + } + + override stop() { + this.mob.move_control.stop(); + } + + override tick() { + const mob = this.mob; + const target = mob.target!; + mob.look_control.look_at_entity(target); + mob.move_control.move_to(target.x, target.y, target.z, this.speed_modifier); + this.#cooldown = Math.max(0, this.#cooldown - 1); + // minecraft's reach: its width doubled, squared, plus the target's width + const reach = (mob.width * 2) ** 2 + (target instanceof Entity ? target.width : PLAYER_WIDTH); + const distance = (target.x - mob.x) ** 2 + (target.y - mob.y) ** 2 + (target.z - mob.z) ** 2; + if (distance <= reach && this.#cooldown === 0) { + this.#cooldown = this.attack_interval; + mob.do_hurt_target(target); + } + } +} + +// goes after the nearest player it can see within follow_range +export class NearestAttackablePlayerGoal extends Goal { + override flags: GoalFlag[] = ["target"]; + + constructor(readonly mob: Mob) { + super(); + } + + #find() { + const mob = this.mob; + return mob.level.nearest_player(mob.x, mob.y, mob.z, mob.attribute(ATTRIBUTES.follow_range)); + } + + can_use() { + return this.mob.random() < 0.1 && this.#find() !== undefined; + } + + override can_continue_to_use() { + const target = this.mob.target; + const mob = this.mob; + return target !== undefined && is_alive(target) && + Math.hypot(target.x - mob.x, target.y - mob.y, target.z - mob.z) <= mob.attribute(ATTRIBUTES.follow_range); + } + + override start() { + this.mob.target = this.#find(); + } + + override stop() { + this.mob.target = undefined; + } +} + +// players are always alive to mobs, they respawn straight away +function is_alive(target: LivingEntity | PlayerTarget) { + return !(target instanceof LivingEntity) || target.alive; +} + +// somewhere random within range it could stand: solid ground under it, room for its box, and inside its home. +// undefined when the tries all fail +export function random_stand_position(mob: Mob, range: number, vertical: number, tries = 10) { + const level = mob.level; + const free = (x: number, y: number, z: number) => !level.has_collision(x, y, z) && !level.is_liquid(x, y, z); + for (let i = 0; i < tries; i++) { + const x = Math.floor(mob.x + (mob.random() * 2 - 1) * range); + const z = Math.floor(mob.z + (mob.random() * 2 - 1) * range); + const top = Math.floor(mob.y + (mob.random() * 2 - 1) * vertical); + for (let y = top; y > top - vertical * 2; y--) { + if (!level.has_collision(x, y - 1, z)) continue; + const room = Math.ceil(mob.height); + let fits = true; + for (let h = 0; h < room && fits; h++) fits = free(x, y + h, z); + if (fits && mob.is_within_home(x + 0.5, y, z + 0.5)) return { x: x + 0.5, y, z: z + 0.5 }; + break; + } + } + return undefined; +} diff --git a/server/game/entity/item_entity.ts b/server/game/entity/item_entity.ts new file mode 100644 index 0000000..9f13f1a --- /dev/null +++ b/server/game/entity/item_entity.ts @@ -0,0 +1,156 @@ +import { type ItemData, ItemStack } from "$/common/inventory.ts"; +import type { EntityInfo } from "$/common/protocol.ts"; +import { type Attacker, type DamageSource, Entity, finite, type SavedEntity } from "./entity.ts"; + +export const ITEM_ENTITY_TYPE = "bworld:item"; + +// minecraft's item physics, its per tick numbers turned into per second ones where they're speeds +export const ITEM_SIZE = 0.25; +// 0.04 blocks per tick, per tick +const GRAVITY = -16; +// what's left of the speed after each tick +const AIR_DRAG = 0.98; +const GROUND_FRICTION = 0.6 * 0.98; +// slower than this counts as stopped, so items don't creep along forever +const MIN_SPEED = 0.01; +// how fast an item stuck inside a block floats out of it +const UNSTICK_SPEED = 2; +// items this close (past their own size) merge into one stack +const MERGE_DISTANCE = 0.5; +const MAX_HEALTH = 5; + +// 5 minutes +export const DESPAWN_TICKS = 6000; +// how long before a popped block drop can be picked up, and one a player drops +export const BLOCK_DROP_PICKUP_DELAY = 10; +export const PLAYER_DROP_PICKUP_DELAY = 40; + +export interface SavedItemEntity extends SavedEntity { + item: ItemData; + age: number; + pickup_delay: number; + health?: number; +} + +// a stack of items lying in the world, like minecraft's ItemEntity. only the server simulates it, +// clients draw where they're told it is +export class ItemEntity extends Entity { + readonly type = ITEM_ENTITY_TYPE; + item: ItemStack; + override width = ITEM_SIZE; + override height = ITEM_SIZE; + override eye_height = ITEM_SIZE / 2; + override gravity = GRAVITY; + + // ticks until a player can pick it up + pickup_delay: number; + // fire, lava and explosions wear it down + health = MAX_HEALTH; + + constructor( + level: Entity["level"], + item = new ItemStack("bworld:air", 0), + x = 0, + y = 0, + z = 0, + pickup_delay = 0, + ) { + super(level); + this.item = item; + this.set_position(x, y, z); + this.pickup_delay = pickup_delay; + } + + override tick() { + this.base_tick(); + if (this.removed) return; + if (this.pickup_delay > 0) { + this.pickup_delay -= 1; + } + + // covered by a block placed on it, float out the top instead of being stuck inside + const level = this.level; + if (level.has_collision(Math.floor(this.x), Math.floor(this.y + this.height / 2), Math.floor(this.z))) { + this.vy = UNSTICK_SPEED; + } + + this.move(); + const friction = this.on_ground ? GROUND_FRICTION : AIR_DRAG; + this.vx *= friction; + this.vy *= AIR_DRAG; + this.vz *= friction; + if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0; + if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0; + + if (this.age >= DESPAWN_TICKS) { + this.remove(); + } else if (this.age % 2 === 0) { + this.merge_with_neighbours(); + } + } + + // items don't get hurt by falling + override update_fall_distance() {} + + override hurt(amount: number, source: DamageSource) { + if (this.is_invulnerable_to(source) || !(amount > 0)) return false; + this.health -= amount; + if (this.health <= 0) this.remove(); + return true; + } + + // whether two stacks could be one + can_merge_with(other: ItemEntity) { + return other !== this && !other.removed && other.item.type_id === this.item.type_id && + JSON.stringify(other.item.data) === JSON.stringify(this.item.data) && + this.item.amount < this.item.max_amount && other.item.amount < other.item.max_amount; + } + + // the smaller stack goes into the bigger one, like minecraft's ItemEntity.tryToMerge + merge_with_neighbours() { + const reach = MERGE_DISTANCE + ITEM_SIZE; + for (const other of this.level.entities_near(this.x, this.y, this.z, reach)) { + if (this.removed) return; + if (!(other instanceof ItemEntity) || !this.can_merge_with(other)) continue; + if (Math.abs(this.y - other.y) > ITEM_SIZE) continue; + + const [into, from] = this.item.amount >= other.item.amount ? [this, other] : [other, this]; + const moving = Math.min(from.item.amount, into.item.max_amount - into.item.amount); + into.item.amount += moving; + from.item.amount -= moving; + into.pickup_delay = Math.max(into.pickup_delay, from.pickup_delay); + into.age = Math.min(into.age, from.age); + if (from.item.amount === 0) { + from.remove(); + } + } + } + + // someone took amount out of the stack. taking all of it takes the entity, which clients see fly to them + take(by: Attacker, amount: number) { + this.item.amount -= amount; + if (this.item.amount <= 0) { + this.level.take_item(this, by.id); + } + } + + override info(): EntityInfo { + return { kind: "item", id: this.id, x: this.x, y: this.y, z: this.z, item: this.item.to_data() }; + } + + override save_additional(saved: SavedItemEntity) { + super.save_additional(saved); + saved.item = this.item.to_data(); + saved.age = this.age; + saved.pickup_delay = this.pickup_delay; + if (this.health !== MAX_HEALTH) saved.health = this.health; + } + + override load_additional(saved: SavedItemEntity) { + super.load_additional(saved); + this.item = ItemStack.from_data(saved.item); + this.age = finite(saved.age, 0); + this.pickup_delay = finite(saved.pickup_delay, 0); + this.health = finite(saved.health, MAX_HEALTH); + } +} diff --git a/server/game/entity/living_entity.ts b/server/game/entity/living_entity.ts new file mode 100644 index 0000000..40c760e --- /dev/null +++ b/server/game/entity/living_entity.ts @@ -0,0 +1,558 @@ +// entities that live: health, attributes, status effects, equipment, breathing and dying, like minecraft's +// LivingEntity. they walk with minecraft's physics, driven by forward, strafe and jumping (see travel), which is what +// a mob's AI or anything else moving them sets +import { TICKS_PER_SECOND } from "$/common/constants.ts"; +import { type ItemData, ItemStack } from "$/common/inventory.ts"; +import type { EntityData } from "$/common/protocol.ts"; +import { AttributeMap, ATTRIBUTES, type AttributeType } from "./attributes.ts"; +import { EffectInstance, EFFECTS, type EffectType, type SavedEffect } from "./effects.ts"; +import { DAMAGE, type DamageSource, Entity, finite, type SavedEntity } from "./entity.ts"; + +export const EQUIPMENT_SLOTS = ["head", "chest", "legs", "feet", "mainhand", "offhand", "body", "saddle"] as const; +export type EquipmentSlot = typeof EQUIPMENT_SLOTS[number]; + +// how long it flashes red after being hurt, and how long before a hit that isn't harder can hurt it again +const HURT_TIME = 10; +const HURT_COOLDOWN = 20; +// how long after dying it's taken away, the falling over animation +const DEATH_TICKS = 20; +// how long it remembers who hurt it +const HURT_MEMORY_TICKS = 100; +// minecraft's movement numbers, per tick +const BLOCK_FRICTION = 0.6; +const AIR_FRICTION = 0.91; +const AIR_ACCELERATION = 0.02; +const WATER_ACCELERATION = 0.02; +const WATER_DRAG = 0.8; +const SWIM_UP = 0.04; +// a jump can't start more often than this while jump is held +const JUMP_DELAY = 10; +const KNOCKBACK = 0.4; +// gravity while slow falling, blocks per tick per tick +const SLOW_FALL_GRAVITY = 0.01; + +export interface SavedLivingEntity extends SavedEntity { + health?: number; + absorption_amount?: number; + active_effects?: SavedEffect[]; + attributes?: unknown; + death_time?: number; + hurt_time?: number; + last_hurt_by_mob?: string; + ticks_since_last_hurt_by_mob?: number; + last_hurt_by_player?: string; + last_hurt_by_player_memory_time?: number; + equipment?: Partial>; +} + +export abstract class LivingEntity extends Entity { + override step_height = ATTRIBUTES.step_height.default; + override head_yaw = 0; + + attributes = new AttributeMap(this.default_attributes()); + #health = this.max_health; + #absorption = 0; + effects = new Map(); + equipment = new Map(); + + // ticks left flashing red, and ticks since dying + hurt_time = 0; + death_time = 0; + #hurt_cooldown = 0; + // the hardest hit during the cooldown, a harder one only hurts by the difference + #last_hurt_amount = 0; + + last_hurt_by_mob: string | undefined; + ticks_since_last_hurt_by_mob = 0; + last_hurt_by_player: string | undefined; + last_hurt_by_player_memory_time = 0; + + // what moves it, from -1 to 1 and times speed: like minecraft's zza and xxa, strafe is positive to the right + forward = 0; + strafe = 0; + // minecraft's per tick movement speed, see travel + speed = 0; + jumping = false; + #jump_delay = 0; + + // the attributes this kind has and their base values, like minecraft's default attribute suppliers. kinds add + // theirs to these + default_attributes(): [AttributeType, number?][] { + return [ + [ATTRIBUTES.max_health], + [ATTRIBUTES.max_absorption], + [ATTRIBUTES.armor], + [ATTRIBUTES.armor_toughness], + [ATTRIBUTES.knockback_resistance], + [ATTRIBUTES.movement_speed], + [ATTRIBUTES.jump_strength], + [ATTRIBUTES.step_height], + [ATTRIBUTES.gravity], + [ATTRIBUTES.safe_fall_distance], + [ATTRIBUTES.fall_damage_multiplier], + ]; + } + + attribute(type: AttributeType) { + return this.attributes.value(type); + } + + get max_health() { + return this.attributes.value(ATTRIBUTES.max_health); + } + + get health() { + return this.#health; + } + + set health(value: number) { + this.#health = Math.min(this.max_health, Math.max(0, value)); + } + + // extra health from the absorption effect, used up before health + get absorption() { + return this.#absorption; + } + + set absorption(value: number) { + this.#absorption = Math.min(this.attribute(ATTRIBUTES.max_absorption), Math.max(0, value)); + } + + get dead() { + return this.#health <= 0; + } + + get alive() { + return !this.removed && !this.dead; + } + + get can_breathe_underwater() { + return false; + } + + // ticking + + override tick() { + this.base_tick(); + if (this.dead) { + this.tick_death(); + } else { + this.tick_effects(); + } + this.ai_step(); + } + + override base_tick() { + super.base_tick(); + if (this.alive) { + if (this.eyes_in_water && !this.can_breathe_underwater && !this.has_effect(EFFECTS.water_breathing)) { + this.air -= 1; + if (this.air <= -20) { + this.air = 0; + this.hurt(2, DAMAGE.drown); + } + } else if (this.air < this.max_air) { + this.air = Math.min(this.air + 4, this.max_air); + } + } + + if (this.hurt_time > 0) this.hurt_time -= 1; + if (this.#hurt_cooldown > 0) this.#hurt_cooldown -= 1; + + if (this.last_hurt_by_mob !== undefined) { + const attacker = this.level.get_entity(this.last_hurt_by_mob); + this.ticks_since_last_hurt_by_mob += 1; + const gone = !(attacker instanceof LivingEntity) || !attacker.alive; + if (gone || this.ticks_since_last_hurt_by_mob >= HURT_MEMORY_TICKS) { + this.last_hurt_by_mob = undefined; + } + } + if (this.last_hurt_by_player_memory_time > 0) { + this.last_hurt_by_player_memory_time -= 1; + } else { + this.last_hurt_by_player = undefined; + } + } + + // dying: it falls over for a second, then it's gone + tick_death() { + this.death_time += 1; + if (this.death_time >= DEATH_TICKS) { + this.remove(); + } + } + + // deciding what to do and doing it, like minecraft's aiStep + ai_step() { + if (this.#jump_delay > 0) this.#jump_delay -= 1; + if (this.dead) { + this.jumping = false; + this.forward = this.strafe = 0; + } else { + this.server_ai_step(); + } + + if (this.jumping) { + if (this.in_water) { + this.vy += SWIM_UP * TICKS_PER_SECOND; + } else if (this.on_ground && this.#jump_delay === 0) { + this.jump_from_ground(); + this.#jump_delay = JUMP_DELAY; + } + } else { + this.#jump_delay = 0; + } + + this.forward *= 0.98; + this.strafe *= 0.98; + if (!this.vehicle) { + this.travel(); + } + } + + // what it decides to do this tick, mobs think here + server_ai_step() {} + + jump_from_ground() { + const boost = this.get_effect(EFFECTS.jump_boost); + const power = this.attribute(ATTRIBUTES.jump_strength) + (boost ? 0.1 * (boost.amplifier + 1) : 0); + this.vy = Math.max(power * TICKS_PER_SECOND, this.vy); + } + + // minecraft's LivingEntity.travel: speeds up towards where forward and strafe point, grip depending on whether it's + // on the ground, in the air or in water, then moves + travel() { + this.step_height = this.attribute(ATTRIBUTES.step_height); + let gravity = this.attribute(ATTRIBUTES.gravity); + if (this.vy <= 0 && this.has_effect(EFFECTS.slow_falling)) { + gravity = Math.min(gravity, SLOW_FALL_GRAVITY); + this.fall_distance = 0; + } + + if (this.in_water) { + this.gravity = -gravity / 16 * TICKS_PER_SECOND ** 2; + this.move_relative(WATER_ACCELERATION); + this.move(); + this.vx *= WATER_DRAG; + this.vy *= WATER_DRAG; + this.vz *= WATER_DRAG; + return; + } + + this.gravity = -gravity * TICKS_PER_SECOND ** 2; + // from where it was at the start of the tick, so the tick it jumps still has the ground's grip + const on_ground = this.on_ground; + this.move_relative(on_ground ? this.speed * (0.216 / BLOCK_FRICTION ** 3) : AIR_ACCELERATION); + this.move(); + const friction = on_ground ? BLOCK_FRICTION * AIR_FRICTION : AIR_FRICTION; + this.vx *= friction; + this.vy *= this.drag; + this.vz *= friction; + } + + // speeds up by acceleration (blocks per tick) towards forward and strafe, turned the way it faces + move_relative(acceleration: number) { + const length_squared = this.forward ** 2 + this.strafe ** 2; + if (length_squared < 1e-7) return; + const scale = acceleration / Math.max(1, Math.sqrt(length_squared)) * TICKS_PER_SECOND; + const forward = this.forward * scale; + const strafe = this.strafe * scale; + const sin = Math.sin(this.yaw); + const cos = Math.cos(this.yaw); + this.vx += -sin * forward + cos * strafe; + this.vz += -cos * forward - sin * strafe; + } + + override fall_damage(distance: number) { + const damage = Math.ceil( + (distance - this.attribute(ATTRIBUTES.safe_fall_distance)) * + this.attribute(ATTRIBUTES.fall_damage_multiplier), + ); + if (damage > 0) { + this.hurt(damage, DAMAGE.fall); + } + } + + // hurts and dies like players do: a hit that isn't harder than the last one does nothing for a moment + override on_below_world() { + this.hurt(4, DAMAGE.void); + } + + // health + + override is_invulnerable_to(source: DamageSource) { + return super.is_invulnerable_to(source) || (source.fire === true && this.has_effect(EFFECTS.fire_resistance)); + } + + // like minecraft's LivingEntity.hurt. returns whether it was hurt + override hurt(amount: number, source: DamageSource): boolean { + if (this.is_invulnerable_to(source) || this.dead || !(amount > 0)) { + return false; + } + let fresh = true; + if (this.#hurt_cooldown > HURT_COOLDOWN / 2) { + if (amount <= this.#last_hurt_amount) return false; + const difference = amount - this.#last_hurt_amount; + this.#last_hurt_amount = amount; + amount = difference; + fresh = false; + } else { + this.#last_hurt_amount = amount; + this.#hurt_cooldown = HURT_COOLDOWN; + this.hurt_time = HURT_TIME; + } + this.actually_hurt(amount, source); + + const attacker = source.attacker; + if (attacker) { + if (source.by_player) { + this.last_hurt_by_player = attacker.id; + this.last_hurt_by_player_memory_time = HURT_MEMORY_TICKS; + } else if (attacker instanceof LivingEntity) { + this.last_hurt_by_mob = attacker.id; + this.ticks_since_last_hurt_by_mob = 0; + } + } + if (fresh) { + this.level.entity_event(this, "hurt"); + if (attacker) { + this.knockback(KNOCKBACK, attacker.x - this.x, attacker.z - this.z); + } + } + this.on_hurt(source); + if (this.dead) { + this.die(source); + } + return true; + } + + // after armor, resistance and absorption + actually_hurt(amount: number, source: DamageSource) { + if (!source.bypasses_armor) { + amount = damage_after_armor( + amount, + this.attribute(ATTRIBUTES.armor), + this.attribute(ATTRIBUTES.armor_toughness), + ); + } + const resistance = this.get_effect(EFFECTS.resistance); + if (resistance && !source.bypasses_invulnerability) { + amount = Math.max(0, amount * (25 - (resistance.amplifier + 1) * 5) / 25); + } + const absorbed = Math.min(amount, this.absorption); + this.absorption -= absorbed; + this.health -= amount - absorbed; + } + + // it was just hurt, for kinds that react + on_hurt(_source: DamageSource) {} + + heal(amount: number) { + if (this.alive && amount > 0) { + this.health += amount; + } + } + + // pushed away from x, z (relative to it) like minecraft's knockback, strength in blocks per tick + knockback(strength: number, dx: number, dz: number) { + strength *= 1 - this.attribute(ATTRIBUTES.knockback_resistance); + const length = Math.hypot(dx, dz); + if (strength <= 0 || length < 1e-5) return; + const push = strength * TICKS_PER_SECOND / length; + this.vx = this.vx / 2 - dx * push; + this.vz = this.vz / 2 - dz * push; + if (this.on_ground) { + this.vy = Math.min(KNOCKBACK * TICKS_PER_SECOND, this.vy / 2 + strength * TICKS_PER_SECOND); + } + } + + // once, when its health reaches 0 + die(source: DamageSource) { + this.drop_loot(source); + this.drop_equipment(source); + this.level.entity_event(this, "death"); + this.level.on_death(this, source); + } + + // what it drops when it dies, each kind decides. spawn_at_location drops something where it is + drop_loot(_source: DamageSource) {} + + // mobs drop their equipment, see Mob + drop_equipment(_source: DamageSource) {} + + spawn_at_location(stack: ItemStack) { + const item = this.level.spawn_item(this.x, this.y, this.z, stack, 10); + item.vx = (Math.random() - 0.5) * 2; + item.vy = 4; + item.vz = (Math.random() - 0.5) * 2; + return item; + } + + // effects + + has_effect(type: EffectType) { + return this.effects.has(type.id); + } + + get_effect(type: EffectType): EffectInstance | undefined { + return this.effects.get(type.id); + } + + // whether it's affected by that effect at all, like undead and poison + can_be_affected(_effect: EffectInstance) { + return true; + } + + // returns whether anything changed. adding one it already has merges them, see EffectInstance.update + add_effect(effect: EffectInstance): boolean { + if (!this.alive || !this.can_be_affected(effect)) return false; + if (effect.type.instant) { + effect.type.apply_instant?.(this, effect.amplifier); + return true; + } + const current = this.effects.get(effect.type.id); + if (!current) { + this.effects.set(effect.type.id, effect); + this.#apply_modifiers(effect); + effect.type.on_added?.(this, effect.amplifier); + return true; + } + const amplifier = current.amplifier; + const changed = current.update(effect); + if (current.amplifier !== amplifier) this.#apply_modifiers(current); + return changed; + } + + remove_effect(type: EffectType) { + const effect = this.effects.get(type.id); + if (!effect) return false; + this.effects.delete(type.id); + this.#effect_ended(effect); + return true; + } + + clear_effects() { + for (const effect of [...this.effects.values()]) this.remove_effect(effect.type); + } + + tick_effects() { + for (const effect of [...this.effects.values()]) { + if (this.effects.get(effect.type.id) !== effect) continue; + const result = effect.tick(this); + if (result === "ended") { + this.remove_effect(effect.type); + } else if (result === "changed") { + this.#apply_modifiers(effect); + } + } + } + + #apply_modifiers(effect: EffectInstance) { + for (const { attribute, amount, operation } of effect.type.modifiers ?? []) { + this.attributes.get(attribute)?.add_modifier({ + id: effect.type.id, + amount: amount * (effect.amplifier + 1), + operation, + }); + } + } + + #effect_ended(effect: EffectInstance) { + for (const { attribute } of effect.type.modifiers ?? []) { + this.attributes.get(attribute)?.remove_modifier(effect.type.id); + } + effect.type.on_removed?.(this, effect.amplifier); + // back inside what the attributes allow now + this.health = this.#health; + this.absorption = this.#absorption; + } + + // equipment + + get_item_slot(slot: EquipmentSlot): ItemStack | undefined { + return this.equipment.get(slot); + } + + set_item_slot(slot: EquipmentSlot, stack: ItemStack | undefined) { + if (stack && stack.amount > 0) { + this.equipment.set(slot, stack); + } else { + this.equipment.delete(slot); + } + } + + get main_hand_item() { + return this.get_item_slot("mainhand"); + } + + // clients + + override synced_data(): EntityData { + const data = super.synced_data(); + if (this.has_effect(EFFECTS.glowing)) data.glowing = true; + if (this.equipment.size) { + data.equipment = Object.fromEntries( + [...this.equipment].map(([slot, stack]) => [slot, stack.to_synced_data()]), + ); + } + return data; + } + + // saving + + override save_additional(saved: SavedLivingEntity) { + super.save_additional(saved); + saved.health = this.#health; + if (this.#absorption) saved.absorption_amount = this.#absorption; + if (this.effects.size) saved.active_effects = [...this.effects.values()].map((effect) => effect.save()); + const attributes = this.attributes.save(new AttributeMap(this.default_attributes())); + if (attributes.length) saved.attributes = attributes; + if (this.death_time) saved.death_time = this.death_time; + if (this.hurt_time) saved.hurt_time = this.hurt_time; + if (this.last_hurt_by_mob !== undefined) { + saved.last_hurt_by_mob = this.last_hurt_by_mob; + saved.ticks_since_last_hurt_by_mob = this.ticks_since_last_hurt_by_mob; + } + if (this.last_hurt_by_player !== undefined) { + saved.last_hurt_by_player = this.last_hurt_by_player; + saved.last_hurt_by_player_memory_time = this.last_hurt_by_player_memory_time; + } + if (this.equipment.size) { + saved.equipment = Object.fromEntries([...this.equipment].map(([slot, stack]) => [slot, stack.to_data()])); + } + } + + override load_additional(saved: SavedLivingEntity) { + super.load_additional(saved); + // attributes and effects first, they decide how much health it can have + this.attributes.load(saved.attributes); + this.effects.clear(); + for (const entry of Array.isArray(saved.active_effects) ? saved.active_effects : []) { + const effect = EffectInstance.load(entry); + if (!effect) continue; + this.effects.set(effect.type.id, effect); + this.#apply_modifiers(effect); + } + this.health = finite(saved.health, this.max_health); + this.absorption = finite(saved.absorption_amount, 0); + this.death_time = finite(saved.death_time, 0); + this.hurt_time = finite(saved.hurt_time, 0); + this.last_hurt_by_mob = typeof saved.last_hurt_by_mob === "string" ? saved.last_hurt_by_mob : undefined; + this.ticks_since_last_hurt_by_mob = finite(saved.ticks_since_last_hurt_by_mob, 0); + this.last_hurt_by_player = typeof saved.last_hurt_by_player === "string" + ? saved.last_hurt_by_player + : undefined; + this.last_hurt_by_player_memory_time = finite(saved.last_hurt_by_player_memory_time, 0); + this.equipment.clear(); + for (const slot of EQUIPMENT_SLOTS) { + const data = saved.equipment?.[slot]; + if (data && typeof data.id === "string") this.set_item_slot(slot, ItemStack.from_data(data)); + } + } +} + +// minecraft's CombatRules.getDamageAfterAbsorb +export function damage_after_armor(damage: number, armor: number, toughness: number) { + const reduction = Math.min(20, Math.max(armor * 0.2, armor - damage / (2 + toughness / 4))); + return damage * (1 - reduction / 25); +} diff --git a/server/game/entity/mob.ts b/server/game/entity/mob.ts new file mode 100644 index 0000000..4156af3 --- /dev/null +++ b/server/game/entity/mob.ts @@ -0,0 +1,401 @@ +// living entities with a mind of their own, like minecraft's Mob: goals decide what to do (see goals.ts) and +// controls turn that into walking, looking and jumping. they can despawn, pick up items and be kept near a home +import { ATTRIBUTES, type AttributeType } from "./attributes.ts"; +import { type DamageSource, Entity, finite, type PlayerTarget } from "./entity.ts"; +import { GoalSelector } from "./goals.ts"; +import { ItemEntity } from "./item_entity.ts"; +import { EQUIPMENT_SLOTS, type EquipmentSlot, LivingEntity, type SavedLivingEntity } from "./living_entity.ts"; +import type { EntityData } from "$/common/protocol.ts"; +import type { ItemStack } from "$/common/inventory.ts"; + +// minecraft's despawning distances: gone at once past the first, maybe after a while past the second +const DESPAWN_DISTANCE = 128; +const NO_DESPAWN_DISTANCE = 32; +const IDLE_DESPAWN_TICKS = 600; +const IDLE_DESPAWN_CHANCE = 1 / 800; +// what equipment drops with when a kind doesn't say, and after a mob picked it up itself (always, undamaged) +export const DEFAULT_DROP_CHANCE = 0.085; +export const PICKED_UP_DROP_CHANCE = 2; +// how far items are picked up from, past its box +const PICKUP_REACH = 1; +// radians a tick +const MAX_TURN = Math.PI / 2; +const HEAD_TURN = Math.PI / 18; +const HEAD_PITCH_TURN = Math.PI / 18; +// how far the head turns from the body +const MAX_HEAD_YAW = Math.PI * 75 / 180; + +export interface SavedMob extends SavedLivingEntity { + no_ai?: boolean; + persistence_required?: boolean; + can_pick_up_loot?: boolean; + left_handed?: boolean; + home_pos?: [number, number, number]; + home_radius?: number; + drop_chances?: Partial>; +} + +export abstract class Mob extends LivingEntity { + // doesn't think or move at all, not even falling + no_ai = false; + // never despawns + persistence_required = false; + can_pick_up_loot = false; + left_handed = false; + // where it stays around, see is_within_home. no home when the radius is -1 + home: { x: number; y: number; z: number } | undefined; + home_radius = -1; + // the chance each slot drops when it dies, see drop_equipment + drop_chances: Partial> = {}; + // ticks since it last did something that keeps it from despawning + no_action_time = 0; + // Math.random, tests replace it + random: () => number = Math.random; + + // what it does, most important first. target goals pick who to go after, like minecraft's targetSelector + goals = new GoalSelector(); + target_goals = new GoalSelector(); + // who it's after, set by target goals + target: LivingEntity | PlayerTarget | undefined; + + move_control = new MoveControl(this); + look_control = new LookControl(this); + jump_control = new JumpControl(this); + + override default_attributes(): [AttributeType, number?][] { + return [...super.default_attributes(), [ATTRIBUTES.follow_range, 16], [ATTRIBUTES.attack_knockback]]; + } + + #registered_goals = false; + + // adds the kind's goals, see goals.ts. runs before its first thought, once the kind's fields are set + register_goals() {} + + override tick() { + super.tick(); + if (this.alive) { + this.check_despawn(); + } + } + + override ai_step() { + if (this.no_ai) return; + super.ai_step(); + if (this.alive && this.can_pick_up_loot) { + this.#pick_up_items(); + } + } + + // the goals, then the controls, like minecraft's Mob.serverAiStep + override server_ai_step() { + if (!this.#registered_goals) { + this.#registered_goals = true; + this.register_goals(); + } + this.no_action_time += 1; + this.target_goals.tick(); + this.goals.tick(); + this.move_control.tick(); + this.look_control.tick(); + this.jump_control.tick(); + } + + override on_hurt(source: DamageSource) { + super.on_hurt(source); + this.no_action_time = 0; + } + + // despawning + + // most mobs go away when nobody's around, kinds that stay (like farm animals) return false + remove_when_far_away(_distance: number) { + return true; + } + + get requires_persistence() { + return this.persistence_required || this.custom_name !== undefined || this.vehicle !== undefined || + this.passengers.length > 0; + } + + check_despawn() { + if (this.requires_persistence) { + this.no_action_time = 0; + return; + } + const player = this.level.nearest_player(this.x, this.y, this.z, Infinity); + if (!player) return; + const distance = Math.hypot(player.x - this.x, player.y - this.y, player.z - this.z); + if (!this.remove_when_far_away(distance)) return; + if (distance > DESPAWN_DISTANCE) { + this.remove(); + } else if ( + this.no_action_time > IDLE_DESPAWN_TICKS && distance > NO_DESPAWN_DISTANCE && + this.random() < IDLE_DESPAWN_CHANCE + ) { + this.remove(); + } else if (distance < NO_DESPAWN_DISTANCE) { + this.no_action_time = 0; + } + } + + // home + + restrict_to(x: number, y: number, z: number, radius: number) { + this.home = { x, y, z }; + this.home_radius = radius; + } + + clear_restriction() { + this.home = undefined; + this.home_radius = -1; + } + + is_within_home(x: number, y: number, z: number) { + if (!this.home || this.home_radius === -1) return true; + const { x: hx, y: hy, z: hz } = this.home; + return (x - hx) ** 2 + (y - hy) ** 2 + (z - hz) ** 2 < this.home_radius ** 2; + } + + // fighting + + // hits whoever it's attacking with its attack damage, like minecraft's doHurtTarget. returns whether it hurt them + do_hurt_target(target: Entity | PlayerTarget): boolean { + const damage = this.attribute(ATTRIBUTES.attack_damage); + const source = { cause: "mob_attack", attacker: this }; + if (!(target instanceof Entity)) { + this.level.damage_player(target.id, damage, source); + return true; + } + if (!(target instanceof LivingEntity)) return false; + if (!target.hurt(damage, source)) return false; + const knockback = this.attribute(ATTRIBUTES.attack_knockback); + if (knockback > 0) { + target.knockback(knockback * 0.5, this.x - target.x, this.z - target.z); + } + return true; + } + + // equipment and loot + + // each slot drops with its chance. above 1 it always drops, otherwise only when a player killed it + override drop_equipment(source: DamageSource) { + super.drop_equipment(source); + const by_player = source.by_player === true || this.last_hurt_by_player_memory_time > 0; + for (const slot of EQUIPMENT_SLOTS) { + const stack = this.get_item_slot(slot); + const chance = this.drop_chances[slot] ?? DEFAULT_DROP_CHANCE; + if (!stack || chance <= 0) continue; + if ((chance > 1 || by_player) && this.random() < chance) { + this.set_item_slot(slot, undefined); + this.spawn_at_location(stack); + } + } + } + + // whether it wants an item on the ground, only into an empty main hand unless a kind says otherwise + wants_to_pick_up(_stack: ItemStack): EquipmentSlot | undefined { + return this.get_item_slot("mainhand") ? undefined : "mainhand"; + } + + #pick_up_items() { + const reach = this.width / 2 + PICKUP_REACH; + for (const entity of this.level.entities_near(this.x, this.y, this.z, reach + 1)) { + if (!(entity instanceof ItemEntity) || entity.removed || entity.pickup_delay > 0) continue; + if (Math.abs(entity.x - this.x) > reach || Math.abs(entity.z - this.z) > reach) continue; + if (entity.y + entity.height < this.y || entity.y > this.y + this.height) continue; + const slot = this.wants_to_pick_up(entity.item); + if (!slot) continue; + const taken = entity.item.clone(); + taken.amount = 1; + this.set_item_slot(slot, taken); + this.drop_chances[slot] = PICKED_UP_DROP_CHANCE; + this.persistence_required = true; + entity.take(this, 1); + } + } + + // clients + + override synced_data(): EntityData { + const data = super.synced_data(); + if (this.left_handed) data.left_handed = true; + return data; + } + + // saving + + override save_additional(saved: SavedMob) { + super.save_additional(saved); + if (this.no_ai) saved.no_ai = true; + if (this.persistence_required) saved.persistence_required = true; + if (this.can_pick_up_loot) saved.can_pick_up_loot = true; + if (this.left_handed) saved.left_handed = true; + if (this.home && this.home_radius !== -1) { + saved.home_pos = [this.home.x, this.home.y, this.home.z]; + saved.home_radius = this.home_radius; + } + if (Object.keys(this.drop_chances).length) saved.drop_chances = { ...this.drop_chances }; + } + + override load_additional(saved: SavedMob) { + super.load_additional(saved); + this.no_ai = saved.no_ai === true; + this.persistence_required = saved.persistence_required === true; + this.can_pick_up_loot = saved.can_pick_up_loot === true; + this.left_handed = saved.left_handed === true; + if (Array.isArray(saved.home_pos) && typeof saved.home_radius === "number") { + const [x, y, z] = saved.home_pos.map((n) => finite(n, 0)); + this.restrict_to(x, y, z, saved.home_radius); + } else { + this.clear_restriction(); + } + this.drop_chances = {}; + for (const slot of EQUIPMENT_SLOTS) { + const chance = saved.drop_chances?.[slot]; + if (typeof chance === "number" && Number.isFinite(chance)) this.drop_chances[slot] = chance; + } + } +} + +// controls, like minecraft's MoveControl, LookControl and JumpControl: goals say what they want, these do it on the +// mob's next tick + +// walks straight towards a point, turning to face it and jumping up steps too high to walk up +export class MoveControl { + readonly mob: Mob; + #wanted: { x: number; y: number; z: number } | undefined; + // times the mob's movement_speed + speed_modifier = 1; + + constructor(mob: Mob) { + this.mob = mob; + } + + get has_wanted() { + return this.#wanted !== undefined; + } + + get wanted() { + return this.#wanted; + } + + move_to(x: number, y: number, z: number, speed_modifier: number) { + this.#wanted = { x, y, z }; + this.speed_modifier = speed_modifier; + } + + stop() { + this.#wanted = undefined; + } + + tick() { + const mob = this.mob; + const wanted = this.#wanted; + if (!wanted) { + mob.forward = 0; + return; + } + const dx = wanted.x - mob.x; + const dy = wanted.y - mob.y; + const dz = wanted.z - mob.z; + if (dx * dx + dy * dy + dz * dz < 2.5e-7) { + mob.forward = 0; + this.#wanted = undefined; + return; + } + mob.yaw = approach_angle(mob.yaw, Math.atan2(-dx, -dz), MAX_TURN); + mob.speed = this.speed_modifier * mob.attribute(ATTRIBUTES.movement_speed); + mob.forward = mob.speed; + // a step too high to walk up, or walking into a wall + const close = dx * dx + dz * dz < Math.max(1, mob.width) ** 2; + if ((dy > mob.step_height && close) || (mob.horizontal_collision && mob.on_ground)) { + mob.jump_control.jump(); + } + } +} + +// turns the head towards a point, and the body after it when the head would turn too far +export class LookControl { + readonly mob: Mob; + #at: { x: number; y: number; z: number } | undefined; + #ticks = 0; + + constructor(mob: Mob) { + this.mob = mob; + } + + get is_looking() { + return this.#at !== undefined; + } + + // at the eyes of whatever it looks at, for a couple of ticks unless it's asked again + look_at(x: number, y: number, z: number) { + this.#at = { x, y, z }; + this.#ticks = 2; + } + + look_at_entity(target: { x: number; y: number; z: number; eye_height?: number }) { + this.look_at(target.x, target.y + (target.eye_height ?? 1.62), target.z); + } + + tick() { + const mob = this.mob; + if (this.#at && this.#ticks > 0) { + this.#ticks -= 1; + const dx = this.#at.x - mob.x; + const dy = this.#at.y - (mob.y + mob.eye_height); + const dz = this.#at.z - mob.z; + mob.head_yaw = approach_angle(mob.head_yaw, Math.atan2(-dx, -dz), HEAD_TURN); + mob.pitch = approach(mob.pitch, -Math.atan2(dy, Math.hypot(dx, dz)), HEAD_PITCH_TURN); + } else { + this.#at = undefined; + mob.head_yaw = approach_angle(mob.head_yaw, mob.yaw, HEAD_TURN); + mob.pitch = approach(mob.pitch, 0, HEAD_PITCH_TURN); + } + // the body turns when the head would go too far, and when walking the head leads + const offset = wrap_angle(mob.head_yaw - mob.yaw); + if (Math.abs(offset) > MAX_HEAD_YAW) { + if (mob.move_control.has_wanted) { + mob.head_yaw = mob.yaw + Math.sign(offset) * MAX_HEAD_YAW; + } else { + mob.yaw = mob.head_yaw - Math.sign(offset) * MAX_HEAD_YAW; + } + } + } +} + +export class JumpControl { + readonly mob: Mob; + #jump = false; + + constructor(mob: Mob) { + this.mob = mob; + } + + jump() { + this.#jump = true; + } + + tick() { + this.mob.jumping = this.#jump; + this.#jump = false; + } +} + +// -pi to pi +export function wrap_angle(angle: number) { + angle %= Math.PI * 2; + if (angle >= Math.PI) angle -= Math.PI * 2; + if (angle < -Math.PI) angle += Math.PI * 2; + return angle; +} + +// from one angle towards another the short way round, at most max +export function approach_angle(from: number, to: number, max: number) { + const difference = Math.max(-max, Math.min(max, wrap_angle(to - from))); + return wrap_angle(from + difference); +} + +function approach(from: number, to: number, max: number) { + return from + Math.max(-max, Math.min(max, to - from)); +} diff --git a/server/game/game_server.ts b/server/game/game_server.ts index f76e33e..f2567ec 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -48,27 +48,27 @@ import { ServerWorld, Tile } from "./world.ts"; import type { WorldSave } from "./saves.ts"; import { BLOCK_DROP_PICKUP_DELAY, - DESPAWN_TICKS, + ITEM_ENTITY_TYPE, ITEM_SIZE, ItemEntity, PLAYER_DROP_PICKUP_DELAY, - SavedItemEntity, -} from "./item_entity.ts"; + type SavedItemEntity, +} from "./entity/item_entity.ts"; +import { EntityManager } from "./entity/entity_manager.ts"; +import type { SavedEntity } from "./entity/entity.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; -// items this close (past their own size) merge into one stack -const MERGE_DISTANCE = 0.5; // tiles further than this many chunks from every player don't tick const SIMULATION_DISTANCE = 6; const MAX_GIVE = 64 * 36; // 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 = 4; +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 @@ -99,7 +99,7 @@ export interface GameHost { // level.json, everything saved but the blocks, which are in region files (see saves.ts) export interface SavedLevel { - version: 4; + version: 5; seed: string; // see ServerWorld.worldgen_fingerprint worldgen: string; @@ -109,8 +109,8 @@ export interface SavedLevel { // every ctx.containers container, by id containers: Record; players: Record; - // items on the ground - entities: SavedItemEntity[]; + // 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>; } @@ -144,12 +144,11 @@ export class GameServer { #tick = 0; // the last morning new day handlers ran for #day = 0; - // items on the ground, by id - #entities = new Map(); - #next_entity_id = 1; #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; // what runs tick(), for /tps. tests call tick() themselves @@ -163,11 +162,28 @@ export class GameServer { this.mods = mods.runtime; this.recipes = mods.recipes; - const saved: SavedLevel | undefined = save?.level ? JSON.parse(save.level) : undefined; - if (saved && saved.version !== 4) { - throw new Error(`The world was saved in format ${saved.version}, this server only loads format 4`); + 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); + // 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), + damage_player: (player, amount, cause) => this.damage_player(player, amount, cause), + }); this.mods.storage = saved?.mod_storage ?? {}; if (saved) { this.world.load_chunks(save?.chunks ?? [], saved.worldgen); @@ -182,10 +198,7 @@ export class GameServer { 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 }); } - for (const entity of saved?.entities ?? []) { - const item = ItemEntity.load(this.#new_entity_id(), entity); - this.#entities.set(item.id, 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(); @@ -220,6 +233,7 @@ export class GameServer { this.#saved_players[player.name] = player.save(); this.world.dirty = true; this.#players.delete(conn); + 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` }); @@ -281,7 +295,7 @@ export class GameServer { this.#new_days(); this.#tick_vitals(); - this.#tick_items(); + this.#tick_entities(); this.mods.tick(); this.mods.check_watched_containers(); @@ -293,6 +307,7 @@ export class GameServer { } } + this.entities.sync(); for (const player of this.#players.values()) { this.#sync(player); } @@ -305,7 +320,7 @@ export class GameServer { this.#saved_players[player.name] = player.save(); } const level: SavedLevel = { - version: 4, + version: 5, seed: this.world.seed, worldgen: this.world.worldgen_fingerprint(), time: this.world.time, @@ -320,7 +335,7 @@ export class GameServer { [...this.containers].map(([id, container]) => [id, container.to_data()]), ), players: this.#saved_players, - entities: [...this.#entities.values()].map((entity) => entity.save()), + entities: this.entities.save(), mod_storage: this.mods.storage, }; this.world.dirty = false; @@ -357,9 +372,7 @@ export class GameServer { } spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { - const entity = new ItemEntity(this.#new_entity_id(), stack, x, y, z, pickup_delay); - this.#entities.set(entity.id, entity); - this.#broadcast({ type: "add_entity", entity: entity.info() }); + const entity = this.entities.spawn_item(x, y, z, stack, pickup_delay); this.world.dirty = true; return entity; } @@ -401,7 +414,7 @@ export class GameServer { } item_entities(): ItemEntity[] { - return [...this.#entities.values()]; + return this.entities.all().filter((entity) => entity instanceof ItemEntity); } send_chat(player: ServerPlayer, text: string) { @@ -628,7 +641,7 @@ export class GameServer { id: player.id, name: player.name, players: [...this.#players.values()].map((p) => p.info()), - entities: [...this.#entities.values()].map((entity) => entity.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, @@ -1302,83 +1315,21 @@ export class GameServer { return true; } - // items on the ground - - #new_entity_id() { - return `item${this.#next_entity_id++}`; - } - - #remove_item(entity: ItemEntity) { - this.#entities.delete(entity.id); - this.#broadcast({ type: "remove_entity", id: entity.id }); - } - - // like minecraft's ItemEntity.tick: only near players, falling, merging, despawning, and getting picked up - #tick_items() { - if (this.#entities.size === 0) { - return; - } - const is_solid = (x: number, y: number, z: number) => this.world.has_collision(x, y, z); - - const active = [...this.#entities.values()].filter((entity) => this.#near_any_player(entity.x, entity.z)); - for (const entity of active) { - entity.tick(is_solid); - if (entity.age >= DESPAWN_TICKS) { - this.#remove_item(entity); - } - } - - if (this.#tick % 2 === 0) { - this.#merge_items(active.filter((entity) => this.#entities.has(entity.id))); - } + // entities, see entity/ + // like minecraft: entities only move near players, and players pick up items by walking into them + #tick_entities() { + 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 active) { - if (this.#entities.has(entity.id) && entity.pickup_delay === 0 && this.#can_pick_up(player, entity)) { + for (const entity of items) { + if (!entity.removed && entity.pickup_delay === 0 && this.#can_pick_up(player, entity)) { this.#pick_up(player, entity); } } } - - for (const entity of active) { - const moved = entity.x !== entity.sent_x || entity.y !== entity.sent_y || entity.z !== entity.sent_z; - if (moved && this.#entities.has(entity.id)) { - entity.sent_x = entity.x; - entity.sent_y = entity.y; - entity.sent_z = entity.z; - this.#broadcast({ type: "move_entity", id: entity.id, x: entity.x, y: entity.y, z: entity.z }); - } - } - - this.world.dirty = true; - } - - // the smaller stack goes into the bigger one, like minecraft's ItemEntity.tryToMerge - #merge_items(entities: ItemEntity[]) { - for (const a of entities) { - for (const b of entities) { - if (!this.#entities.has(a.id) || !this.#entities.has(b.id) || !a.can_merge_with(b)) { - continue; - } - const reach = MERGE_DISTANCE + ITEM_SIZE; - if (Math.abs(a.x - b.x) > reach || Math.abs(a.z - b.z) > reach || Math.abs(a.y - b.y) > ITEM_SIZE) { - continue; - } - - const [into, from] = a.item.amount >= b.item.amount ? [a, b] : [b, a]; - const moving = Math.min(from.item.amount, into.item.max_amount - into.item.amount); - into.item.amount += moving; - from.item.amount -= moving; - into.pickup_delay = Math.max(into.pickup_delay, from.pickup_delay); - into.age = Math.min(into.age, from.age); - - this.#broadcast({ type: "set_entity_item", id: into.id, item: into.item.to_data() }); - if (from.item.amount === 0) { - this.#remove_item(from); - } else { - this.#broadcast({ type: "set_entity_item", id: from.id, item: from.item.to_data() }); - } - } + if (this.entities.count > 0) { + this.world.dirty = true; } } @@ -1392,16 +1343,8 @@ export class GameServer { // as much as fits, the rest stays on the ground #pick_up(player: ServerPlayer, entity: ItemEntity) { - const before = entity.item.amount; - const left = player.inventory.add_item(entity.item); - if (left === before) { - return; - } - if (left === 0) { - this.#entities.delete(entity.id); - this.#broadcast({ type: "take_entity", id: entity.id, player: player.id }); - } else { - this.#broadcast({ type: "set_entity_item", id: entity.id, item: entity.item.to_data() }); + if (player.inventory.add_item(entity.item) === 0) { + this.entities.take_item(entity, player.id); } } @@ -1570,6 +1513,35 @@ function is_block_position(x: unknown, y: unknown, z: unknown): boolean { 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; + }[]; +} + +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, cause: string) { switch (cause) { diff --git a/server/game/item_entity.ts b/server/game/item_entity.ts deleted file mode 100644 index dbf5e55..0000000 --- a/server/game/item_entity.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { ItemData, ItemStack } from "$/common/inventory.ts"; -import { move_body } from "$/common/physics.ts"; -import type { EntityInfo } from "$/common/protocol.ts"; - -// minecraft's item physics, its per tick numbers turned into per second ones where they're speeds -export const ITEM_SIZE = 0.25; -// 0.04 blocks per tick, per tick -const GRAVITY = -16; -// what's left of the speed after each tick -const AIR_DRAG = 0.98; -const GROUND_FRICTION = 0.6 * 0.98; -// slower than this counts as stopped, so items don't creep along forever -const MIN_SPEED = 0.01; -// how fast an item stuck inside a block floats out of it -const UNSTICK_SPEED = 2; - -// 5 minutes -export const DESPAWN_TICKS = 6000; -// how long before a popped block drop can be picked up, and one a player drops -export const BLOCK_DROP_PICKUP_DELAY = 10; -export const PLAYER_DROP_PICKUP_DELAY = 40; - -// what's saved about an item on the ground -export interface SavedItemEntity { - x: number; - y: number; - z: number; - vx: number; - vy: number; - vz: number; - item: ItemData; - age: number; - pickup_delay: number; -} - -// a stack of items lying in the world, like minecraft's ItemEntity. only the server simulates it, -// clients draw where they're told it is -export class ItemEntity { - readonly id: string; - item: ItemStack; - - x: number; - y: number; - z: number; - vx = 0; - vy = 0; - vz = 0; - readonly width = ITEM_SIZE; - readonly height = ITEM_SIZE; - - age = 0; - // ticks until a player can pick it up - pickup_delay: number; - on_ground = false; - - // the position clients were last sent, so it's only sent again when it moves - sent_x: number; - sent_y: number; - sent_z: number; - - constructor(id: string, item: ItemStack, x: number, y: number, z: number, pickup_delay = 0) { - this.id = id; - this.item = item; - this.x = this.sent_x = x; - this.y = this.sent_y = y; - this.z = this.sent_z = z; - this.pickup_delay = pickup_delay; - } - - tick(is_solid: (x: number, y: number, z: number) => boolean) { - this.age += 1; - if (this.pickup_delay > 0) { - this.pickup_delay -= 1; - } - - // covered by a block placed on it, float out the top instead of being stuck inside - if (is_solid(Math.floor(this.x), Math.floor(this.y + this.height / 2), Math.floor(this.z))) { - this.vy = UNSTICK_SPEED; - } - - const collisions = move_body(this, GRAVITY, is_solid); - this.on_ground = collisions.y === 1; - - const friction = this.on_ground ? GROUND_FRICTION : AIR_DRAG; - this.vx *= friction; - this.vy *= AIR_DRAG; - this.vz *= friction; - if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0; - if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0; - } - - // whether two stacks could be one - can_merge_with(other: ItemEntity) { - return other !== this && other.item.type_id === this.item.type_id && - JSON.stringify(other.item.data) === JSON.stringify(this.item.data) && - this.item.amount < this.item.max_amount && other.item.amount < other.item.max_amount; - } - - info(): EntityInfo { - return { kind: "item", id: this.id, x: this.x, y: this.y, z: this.z, item: this.item.to_data() }; - } - - save(): SavedItemEntity { - const { x, y, z, vx, vy, vz, age, pickup_delay } = this; - return { x, y, z, vx, vy, vz, age, pickup_delay, item: this.item.to_data() }; - } - - static load(id: string, saved: SavedItemEntity) { - const entity = new ItemEntity( - id, - ItemStack.from_data(saved.item), - saved.x, - saved.y, - saved.z, - saved.pickup_delay, - ); - entity.vx = saved.vx; - entity.vy = saved.vy; - entity.vz = saved.vz; - entity.age = saved.age; - return entity; - } -} diff --git a/tests/entity_test.ts b/tests/entity_test.ts new file mode 100644 index 0000000..c7478f6 --- /dev/null +++ b/tests/entity_test.ts @@ -0,0 +1,396 @@ +import { assert, assertAlmostEquals, assertEquals } from "@std/assert"; +import { ItemStack } from "$/common/inventory.ts"; +import { Attribute, ATTRIBUTES } from "$/server/game/entity/attributes.ts"; +import { EffectInstance, EFFECTS } from "$/server/game/entity/effects.ts"; +import { DAMAGE } from "$/server/game/entity/entity.ts"; +import { register_entity_type } from "$/server/game/entity/entity_types.ts"; +import { Goal, GoalSelector, RandomStrollGoal } from "$/server/game/entity/goals.ts"; +import { Mob } from "$/server/game/entity/mob.ts"; +import { test_game } from "./helpers.ts"; + +// a mob for testing, walking like a pig +class TestMob extends Mob { + readonly type = "test:mob"; + stroll = false; + + override default_attributes(): ReturnType { + return [...super.default_attributes(), [ATTRIBUTES.movement_speed, 0.25], [ATTRIBUTES.max_health, 10]]; + } + + override register_goals() { + if (this.stroll) this.goals.add_goal(1, new RandomStrollGoal(this, 1, 1)); + } + + override remove_when_far_away() { + return !this.tags.has("stays"); + } +} +register_entity_type("test:mob", (level) => new TestMob(level)); + +// a game with alice standing on a stone floor at y 99, high above the generated terrain +async function floor_game() { + const t = await test_game("mods"); + t.join(1, "alice"); + for (let x = -8; x <= 8; x++) { + for (let z = -8; z <= 8; z++) { + t.game.set_block(x, 99, z, "bworld:stone"); + } + } + t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + const spawn = (x: number, y: number, z: number) => { + const mob = new TestMob(t.game.entities); + mob.set_position(x, y, z); + t.game.entities.add_entity(mob); + return mob; + }; + const ticks = (n: number) => { + for (let i = 0; i < n; i++) t.game.tick(); + }; + return { ...t, spawn, ticks }; +} + +Deno.test("attribute modifiers add, then multiply the base, then multiply the total, like minecraft", () => { + const speed = new Attribute(ATTRIBUTES.movement_speed, 0.25); + assertEquals(speed.value, 0.25); + speed.add_modifier({ id: "a", amount: 0.25, operation: "add_value" }); + speed.add_modifier({ id: "b", amount: 1, operation: "add_multiplied_base" }); + speed.add_modifier({ id: "c", amount: 1, operation: "add_multiplied_base" }); + speed.add_modifier({ id: "d", amount: 0.5, operation: "add_multiplied_total" }); + // x = 0.5, y = 0.5 + 0.5 + 0.5 = 1.5, then * 1.5 + assertEquals(speed.value, 2.25); + speed.add_modifier({ id: "a", amount: 0.75, operation: "add_value" }); + assertEquals(speed.value, 4.5, "the same id replaces the modifier"); + speed.remove_modifier("d"); + assertEquals(speed.value, 3); + + const health = new Attribute(ATTRIBUTES.max_health); + health.add_modifier({ id: "a", amount: -100, operation: "add_value" }); + assertEquals(health.value, 1, "clamped to the attribute's minimum"); +}); + +Deno.test("a stronger, shorter effect hides a weaker one, which takes over when it runs out", async () => { + const { spawn } = await floor_game(); + const mob = spawn(0.5, 100, 0.5); + const base_speed = mob.attribute(ATTRIBUTES.movement_speed); + + mob.add_effect(new EffectInstance(EFFECTS.speed, 100)); + mob.add_effect(new EffectInstance(EFFECTS.speed, 10, { amplifier: 2 })); + const effect = mob.get_effect(EFFECTS.speed)!; + assertEquals([effect.amplifier, effect.duration, effect.hidden?.amplifier], [2, 10, 0]); + assertAlmostEquals(mob.attribute(ATTRIBUTES.movement_speed), base_speed * 1.6); + + for (let i = 0; i < 10; i++) mob.tick_effects(); + assertEquals([effect.amplifier, effect.duration], [0, 90], "the hidden one kept counting down"); + assertAlmostEquals(mob.attribute(ATTRIBUTES.movement_speed), base_speed * 1.2); + + for (let i = 0; i < 90; i++) mob.tick_effects(); + assertEquals(mob.has_effect(EFFECTS.speed), false); + assertEquals(mob.attribute(ATTRIBUTES.movement_speed), base_speed); +}); + +Deno.test("effects: regeneration heals, poison never kills, health boost goes away with its health", async () => { + const { spawn } = await floor_game(); + const mob = spawn(0.5, 100, 0.5); + + mob.health = 2; + mob.add_effect(new EffectInstance(EFFECTS.poison, 200, { amplifier: 3 })); + for (let i = 0; i < 200; i++) mob.tick_effects(); + assertEquals(mob.health, 1); + + mob.add_effect(new EffectInstance(EFFECTS.regeneration, 100, { amplifier: 1 })); + for (let i = 0; i < 100; i++) mob.tick_effects(); + // every 25 ticks at level 2 + assertEquals(mob.health, 5); + + mob.add_effect(new EffectInstance(EFFECTS.instant_health, 1)); + assertEquals(mob.health, 9); + + mob.add_effect(new EffectInstance(EFFECTS.health_boost, 20)); + assertEquals(mob.max_health, 14); + mob.health = 14; + mob.remove_effect(EFFECTS.health_boost); + assertEquals([mob.max_health, mob.health], [10, 10]); +}); + +Deno.test("hurting: a weaker hit right after does nothing, a harder one only the difference", async () => { + const { spawn, take, ticks } = await floor_game(); + const mob = spawn(0.5, 100, 2.5); + ticks(1); + take(1); + + assert(mob.hurt(3, DAMAGE.generic)); + assertEquals(mob.health, 7); + assert(take(1).some((m) => m.type === "entity_event" && m.id === mob.id && m.event === "hurt")); + assertEquals(mob.hurt(2, DAMAGE.generic), false); + assert(mob.hurt(5, DAMAGE.generic)); + assertEquals(mob.health, 5); + + ticks(11); + assert(mob.hurt(1, DAMAGE.generic), "hurt normally again after the cooldown"); + assertEquals(mob.health, 4); + + ticks(11); + mob.absorption = 0; + mob.add_effect(new EffectInstance(EFFECTS.absorption, 100)); + assertEquals(mob.absorption, 4); + mob.hurt(3, DAMAGE.generic); + assertEquals([mob.absorption, mob.health], [1, 4], "absorption goes first"); + + ticks(11); + mob.invulnerable = true; + assertEquals(mob.hurt(3, DAMAGE.generic), false); + assert(mob.hurt(1, DAMAGE.void), "falling out of the world hurts anyway"); +}); + +Deno.test("armor takes some of the damage, and hits push away from the attacker", async () => { + const { spawn, ticks } = await floor_game(); + const mob = spawn(0.5, 100, 2.5); + ticks(2); + mob.attributes.get(ATTRIBUTES.armor)!.base = 10; + // minecraft: 10 armor against 5 damage takes 7.5 / 25 of it off + mob.hurt(5, { cause: "mob_attack", attacker: { id: "x", x: 0.5, y: 100, z: 0.5 } }); + assertAlmostEquals(mob.health, 10 - 5 * (1 - 7.5 / 25)); + assert(mob.vz > 0 && mob.vy > 0, "knocked back, away from the attacker at a smaller z"); +}); + +Deno.test("dying: it drops what it had, falls over for a second and is gone", async () => { + const { game, spawn, take, ticks } = await floor_game(); + const mob = spawn(0.5, 100, 2.5); + mob.set_item_slot("mainhand", new ItemStack("bworld:stick")); + mob.drop_chances.mainhand = 2; + mob.set_item_slot("head", new ItemStack("bworld:dirt")); + mob.drop_chances.head = 0; + ticks(1); + take(1); + + mob.hurt(20, DAMAGE.generic); + assert(mob.dead); + assertEquals(game.item_entities().map((item) => item.item.type_id), ["bworld:stick"]); + assert(take(1).some((m) => m.type === "entity_event" && m.id === mob.id && m.event === "death")); + + ticks(19); + assert(!mob.removed); + ticks(1); + assert(mob.removed); + assert(take(1).some((m) => m.type === "remove_entity" && m.id === mob.id)); +}); + +Deno.test("mobs fall, and landing from high up hurts them past 3 blocks", async () => { + const { spawn, ticks } = await floor_game(); + const mob = spawn(0.5, 110, 2.5); + ticks(40); + assert(mob.on_ground); + assertEquals(mob.y, 100); + assertEquals(mob.health, 10 - 7); + + const floating = spawn(-2.5, 110, 2.5); + floating.no_ai = true; + ticks(20); + assertEquals(floating.y, 110, "no ai means not even falling"); +}); + +Deno.test("mobs drown after their air runs out, unless they breathe water", async () => { + const { game, spawn, ticks } = await floor_game(); + for (let y = 100; y <= 102; y++) game.set_block(3, y, 3, "bworld:water"); + for (const [x, z] of [[2, 3], [4, 3], [3, 2], [3, 4]]) { + for (let y = 100; y <= 102; y++) game.set_block(x, y, z, "bworld:stone"); + } + const mob = spawn(3.5, 100, 3.5); + mob.no_ai = true; + ticks(1); + assert(mob.in_water && mob.eyes_in_water); + ticks(299); + assertEquals(mob.air, 0); + assertEquals(mob.health, 10); + ticks(20); + assertEquals(mob.health, 8, "2 damage when the air gets to -20"); + + const breather = spawn(3.5, 100, 3.5); + breather.no_ai = true; + breather.add_effect(new EffectInstance(EFFECTS.water_breathing, -1)); + ticks(340); + assertEquals(breather.health, 10); +}); + +Deno.test("the move control walks a mob to where it's told at minecraft's speed", async () => { + const { spawn, ticks } = await floor_game(); + const mob = spawn(0.5, 100, -5.5); + ticks(2); + mob.move_control.move_to(0.5, 100, 5.5, 1); + ticks(20); + // 0.25 movement speed walks 0.25 * 0.25 * 0.98 / (1 - 0.546) blocks a tick, 2.7 a second + assertAlmostEquals(mob.z, -5.5 + 2.7, 0.5); + assertAlmostEquals(Math.abs(mob.yaw), Math.PI, 0.05, "facing south, +z"); + ticks(100); + assert(Math.abs(mob.z - 5.5) < 0.5 && Math.abs(mob.x - 0.5) < 0.1, "got there"); +}); + +Deno.test("goals: a more important goal takes a flag from a less important one", () => { + const log: string[] = []; + class Test extends Goal { + want = false; + constructor(readonly name: string) { + super(); + this.flags = ["move"]; + } + can_use() { + return this.want; + } + override start() { + log.push(`start ${this.name}`); + } + override stop() { + log.push(`stop ${this.name}`); + } + } + const selector = new GoalSelector(); + const wander = new Test("wander"); + const flee = new Test("flee"); + selector.add_goal(5, wander); + selector.add_goal(1, flee); + wander.want = true; + selector.tick(); + flee.want = true; + selector.tick(); + assertEquals(selector.running, [flee]); + flee.want = false; + selector.tick(); + assertEquals(log, ["start wander", "stop wander", "start flee", "stop flee", "start wander"]); +}); + +Deno.test("strolling mobs wander around on their own, within their home", async () => { + const { spawn, ticks } = await floor_game(); + const mob = spawn(0.5, 100, 0.5); + mob.stroll = true; + mob.restrict_to(0.5, 100, 0.5, 4); + const visited = new Set(); + for (let i = 0; i < 400; i++) { + ticks(1); + visited.add(`${Math.floor(mob.x)},${Math.floor(mob.z)}`); + assert(Math.hypot(mob.x - 0.5, mob.z - 0.5) < 5.5, "stays near home"); + } + assert(visited.size > 3, "went somewhere"); +}); + +Deno.test("mobs that can pick up loot take items into their hand, and always drop them", async () => { + const { game, spawn, take, ticks } = await floor_game(); + const mob = spawn(4.5, 100, 4.5); + mob.can_pick_up_loot = true; + game.spawn_item(4.5, 100, 4.5, new ItemStack("bworld:stick", 3)); + ticks(1); + assertEquals(mob.main_hand_item?.to_data(), { id: "bworld:stick", count: 1 }); + assertEquals(game.item_entities().map((item) => item.item.amount), [2]); + assertEquals(mob.drop_chances.mainhand, 2); + assert(mob.persistence_required); + const data = take(1).find((m) => m.type === "entity_data" && m.id === mob.id); + assertEquals(data?.data.equipment, { mainhand: { id: "bworld:stick", count: 1 } }); +}); + +Deno.test("mobs far from every player despawn, named and persistent ones don't", async () => { + const { game, spawn, send } = await floor_game(); + const mobs = [spawn(0.5, 100, 0.5), spawn(0.5, 100, 0.5), spawn(0.5, 100, 0.5), spawn(0.5, 100, 0.5)]; + mobs[1].custom_name = "Bob"; + mobs[2].persistence_required = true; + mobs[3].add_tag("stays"); + send(1, { type: "move", x: 200.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + for (const mob of mobs) mob.check_despawn(); + assertEquals(mobs.map((mob) => mob.removed), [true, false, false, false]); + game.entities.sync(); + assertEquals(game.entities.all().length, 3); +}); + +Deno.test("clients hear about entities in their view distance, and forget them when they leave it", async () => { + const { game, spawn, take, send, join, ticks } = await floor_game(); + const near = spawn(2.5, 100, 2.5); + const far = spawn(1000.5, 100, 0.5); + far.no_ai = true; + const joined = join(2, "bob"); + assertEquals(joined.entities.map((e: { id: string }) => e.id), [near.id]); + assertEquals(joined.entities[0].kind, "entity"); + assertEquals(joined.entities[0].type, "test:mob"); + + near.custom_name = "Nearby"; + near.move_control.move_to(5.5, 100, 2.5, 1); + ticks(5); + const messages = take(2); + const move = messages.find((m) => m.type === "move_entity" && m.id === near.id); + assert(move && typeof move.yaw === "number" && typeof move.head_yaw === "number"); + assert(messages.some((m) => m.type === "entity_data" && m.id === near.id && m.data.custom_name === "Nearby")); + assert(!messages.some((m) => m.id === far.id)); + + send(2, { type: "move", x: 1000.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + game.tick(); + const moved = take(2); + assert(moved.some((m) => m.type === "remove_entity" && m.id === near.id)); + assert(moved.some((m) => m.type === "add_entity" && m.entity.id === far.id)); +}); + +Deno.test("entities are saved with everything about them, riders on what they ride", async () => { + const { game, spawn, ticks } = await floor_game(); + const mob = spawn(0.5, 100, 2.5); + const rider = spawn(0.5, 100, 2.5); + ticks(2); + mob.custom_name = "Horse"; + mob.add_tag("test"); + mob.data.mood = "happy"; + mob.health = 6; + mob.add_effect(new EffectInstance(EFFECTS.speed, 100)); + mob.add_effect(new EffectInstance(EFFECTS.speed, 10, { amplifier: 1 })); + mob.attributes.get(ATTRIBUTES.armor)!.base = 4; + mob.set_item_slot("mainhand", new ItemStack("bworld:stick")); + mob.restrict_to(1, 2, 3, 8); + assert(rider.start_riding(mob)); + ticks(1); + assertEquals([rider.x, rider.y, rider.z], [mob.x, mob.y + mob.height, mob.z]); + + // an entity of a kind that doesn't exist anymore, from a mod that's gone + const saved = game.save(); + const level = JSON.parse(saved.level); + assertEquals(level.version, 5); + level.entities.push({ id: "gone:thing", uuid: "1234", pos: [0, 100, 0], motion: [0, 0, 0], rotation: [0, 0] }); + saved.level = JSON.stringify(level); + + const loaded = await test_game("mods", saved); + const [horse, loaded_rider] = [loaded.game.entities.get_entity(mob.id), loaded.game.entities.get_entity(rider.id)]; + assert(horse instanceof TestMob && loaded_rider instanceof TestMob); + assertEquals(horse.custom_name, "Horse"); + assertEquals([...horse.tags], ["test"]); + assertEquals(horse.data, { mood: "happy" }); + assertEquals(horse.health, 6); + const speed = horse.get_effect(EFFECTS.speed)!; + assertEquals([speed.amplifier, speed.duration, speed.hidden?.amplifier, speed.hidden?.duration], [1, 9, 0, 99]); + assertAlmostEquals(horse.attribute(ATTRIBUTES.movement_speed), 0.25 * 1.4); + assertEquals(horse.attribute(ATTRIBUTES.armor), 4); + assertEquals(horse.main_hand_item?.type_id, "bworld:stick"); + assertEquals([horse.home, horse.home_radius], [{ x: 1, y: 2, z: 3 }, 8]); + assertEquals(loaded_rider.vehicle, horse); + assertEquals(horse.passengers, [loaded_rider]); + + const resaved = JSON.parse(loaded.game.save().level); + assert(resaved.entities.some((e: { id: string }) => e.id === "gone:thing"), "kept for when the mod comes back"); +}); + +Deno.test("items on the ground in a version 4 save load as entities", async () => { + const { game } = await floor_game(); + game.spawn_item(0.5, 100, 0.5, new ItemStack("bworld:dirt", 7)); + const saved = game.save(); + const level = JSON.parse(saved.level); + level.version = 4; + level.entities = [{ + x: 2.5, + y: 100, + z: 0.5, + vx: 0, + vy: 0, + vz: 0, + item: { id: "bworld:dirt", count: 7 }, + age: 5, + pickup_delay: 3, + }]; + saved.level = JSON.stringify(level); + + const loaded = await test_game("mods", saved); + const [item] = loaded.game.item_entities(); + assertEquals([item.x, item.y, item.z, item.age, item.pickup_delay], [2.5, 100, 0.5, 5, 3]); + assertEquals(item.item.to_data(), { id: "bworld:dirt", count: 7 }); +});