Files

448 lines
14 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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 } from "./entity.ts";
import { GoalSelector } from "./goals.ts";
import { PathNavigation } from "./navigation.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";
import { wrap_angle } from "@/common/utils.ts";
import { TICK_DELTA } from "@/common/constants.ts";
import { is_object } from "@/common/schema.ts";
import { physics } from "@/common/physics.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<Record<EquipmentSlot, number>>;
client_data?: Record<string, unknown>;
}
// what natural spawning counts a mob as, like minecraft's MobCategory
export type MobCategory = "monster" | "creature";
export abstract class Mob extends LivingEntity {
// doesn't think or move at all, not even falling
no_ai = false;
// never despawns
persistence_required = false;
can_pick_up_loot = false;
left_handed = false;
// what clients see of a mod's mob's state, see MobRef.set_client_data. replaced rather than changed, so a save never
// shares it
client_data: Record<string, unknown> = {};
// 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<Record<EquipmentSlot, number>> = {};
// ticks since it last did something that keeps it from despawning
no_action_time = 0;
// Math.random, tests replace it
random: () => number = Math.random;
// how many blocks it drops on its way, see PATHFINDING.md. 0 never walks off an edge
max_fall = 3;
// 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 | undefined;
// who hurt it last, and how many times something has, for HurtByTargetGoal
last_attacker: LivingEntity | undefined;
times_hurt_by_attacker = 0;
// follows paths, giving the move control one waypoint at a time
navigation = new PathNavigation(this);
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],
[ATTRIBUTES.physical_shielding],
[ATTRIBUTES.arcane_shielding],
];
}
get category(): MobCategory {
return "creature";
}
#registered_goals = false;
// adds the kind's goals, see goals.ts. runs before its first thought, once the kind's fields are set
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();
}
}
// a mob that never drops stops at edges like a sneaking player, still stepping down its step height. not while it's
// off the ground, so something that knocks it into the air can still knock it off
override move() {
if (this.max_fall === 0 && this.on_ground && this.vy <= 0) {
const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z);
const [dx, dz] = physics.back_off_from_edge(
this,
this.vx * TICK_DELTA,
this.vz * TICK_DELTA,
this.step_height,
is_solid,
);
this.vx = dx / TICK_DELTA;
this.vz = dz / TICK_DELTA;
}
return super.move();
}
// the goals, then the path they asked for, 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.navigation.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;
if (source.attacker instanceof LivingEntity && source.attacker !== this) {
this.last_attacker = source.attacker;
this.times_hurt_by_attacker += 1;
}
}
// 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): boolean {
const damage = this.attribute(ATTRIBUTES.attack_damage);
const source = { cause: "mob_attack", attacker: this, type: "physical" } as const;
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;
if (Object.keys(this.client_data).length) data.client_data = this.client_data;
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 };
if (Object.keys(this.client_data).length) saved.client_data = this.client_data;
}
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;
this.client_data = is_object(saved.client_data) ? structuredClone(saved.client_data) : {};
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;
}
}
// 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));
}