Files
2026-11-22 07:44:13 -03:00

532 lines
18 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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 { Shape } from "@/common/block_shapes.ts";
import type { Season } from "@/common/worldgen/biomes.ts";
import { type Collisions, type FluidInCell, physics } from "@/common/physics.ts";
import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
import type { PlayOptions } from "@/common/mod_api/shared.ts";
import type { LivingEntity } from "./living_entity.ts";
// this far below the bottom of the world, entities have fallen out of it
export const VOID_DEPTH = 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;
// how far under its feet the block it stands on is looked for, so standing on top of a block finds that one
const STANDING_DEPTH = 1 / 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;
}
export type DamageType = "physical" | "arcane" | "absolute";
// what hurt something. cause is for mods and death messages, like "fall", "drown" or "mob_attack"
export interface DamageSource {
type: DamageType;
cause: string;
// who did it, which knockback pushes away from
attacker?: Attacker;
by_player?: boolean;
// it's fire, like burning
fire?: boolean;
// even invulnerable entities are hurt, like falling out of the world
bypasses_invulnerability?: boolean;
}
export const DAMAGE = {
generic: { cause: "generic", type: "physical" },
fall: { cause: "fall", type: "physical" },
drown: { cause: "drown", type: "physical" },
on_fire: { cause: "on_fire", fire: true, type: "arcane" },
void: { cause: "void", bypasses_invulnerability: true, type: "absolute" },
magic: { cause: "magic", type: "arcane" },
} satisfies Record<string, DamageSource>;
// a cause from a script, like "magic": the engine's source for it, or physical damage under that name
export function damage_source(cause: string): DamageSource {
const known: Record<string, DamageSource> = DAMAGE;
return known[cause] ?? { cause, type: "physical" };
}
// what entities can see and do in the world, the entity manager is one
export interface EntityLevel {
readonly current_tick: number;
// the bottom of the world, see WorldShape
readonly min_y: number;
has_collision(x: number, y: number, z: number): boolean;
// whether the chunk is kept, see World.has_chunk. reading blocks in one that isn't builds it, which takes a while
has_chunk(chunk_x: number, chunk_z: number): boolean;
// whether mobs' paths go through the block, see MOBS_PATH_THROUGH in pathfinding.ts
passes_through(x: number, y: number, z: number): boolean;
// what it bumps into at a block, see common/physics.ts
collision_shape(x: number, y: number, z: number): boolean | Shape;
// water, and other blocks you're in instead of on
is_fluid(x: number, y: number, z: number): boolean;
// the fluid there and how high it is, for fluids pushing things along
fluid_at(x: number, y: number, z: number): FluidInCell | undefined;
get_block_info(x: number, y: number, z: number): BlockRegistry | undefined;
// the biome at a block, like "bworld:plains"
biome_at(x: number, y: number, z: number): string;
// that biome's season now, see biome_season in common/worldgen/biomes.ts
season_at(x: number, y: number, z: number): Season;
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): ServerPlayer | undefined;
// mods' before.entity_damage, see LivingEntity.hurt: what's left of amount once they had their say, 0 when one
// canceled it
before_hurt(entity: LivingEntity, amount: number, source: DamageSource): number;
// mods' after.entity_damage, it was hurt by amount
after_hurt(entity: LivingEntity, 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: EntityEvent): void;
// a sound following it, for the players tracking it within its range, see EntityRef.play_sound
play_sound(entity: Entity, sound: string, options: PlayOptions): void;
// it died, after dropping its things
on_death(entity: Entity, source: DamageSource): void;
// what it drops when it dies, from its type's loot table
entity_loot(entity: Entity, source: DamageSource): ItemStack[];
// it's standing on the block at x y z after moving, for the block's components, see on_entity_stand
stands_on(entity: Entity, x: number, y: number, z: number): void;
// it moved, for the components of the blocks its box is in, see on_entity_inside
inside_blocks(entity: Entity): 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<string, unknown>;
passengers?: SavedEntity[];
[field: string]: unknown;
}
export abstract class Entity {
// the entity type, like "cubi: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<string>();
// anything mods want to keep on it, saved with it
data: Record<string, unknown> = {};
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;
}
// saved with the world. things scripts keep track of themselves aren't, they wouldn't know them after a restart
get persistent() {
return true;
}
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.pushed_by_fluid) {
physics.push_by_fluid(
this,
(x, y, z) => this.level.fluid_at(x, y, z),
(x, y, z) => this.level.collision_shape(x, y, z),
false,
);
}
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 < this.level.min_y - VOID_DEPTH) {
this.on_below_world();
}
}
// flowing fluid pushes it along, like minecraft's isPushedByFluid
get pushed_by_fluid() {
return true;
}
update_in_water() {
this.in_water = physics.in_water(this, (x, y, z) => this.level.is_fluid(x, y, z));
}
// its eyes are in water, so it can't breathe
get eyes_in_water() {
return physics.eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_fluid(x, y, 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.collision_shape(x, y, z);
const from_y = this.y;
const collisions = physics.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;
// the block its feet are on, which can be the one they're in when it's lower than a whole block, like a basin's
// floor
if (this.on_ground) {
this.level.stands_on(this, Math.floor(this.x), Math.floor(this.y - STANDING_DEPTH), Math.floor(this.z));
}
this.level.inside_blocks(this);
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 VOID_DEPTH below the bottom of the world. 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;
}
// like minecraft's Entity.kill: ones that can die do, even when invulnerable, the rest go away. cause is for events
// and the death message
kill(_cause: string) {
this.remove();
}
// 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));
}