Files
bworld/server/game/entity/living_entity.ts
T
2026-09-30 10:42:52 -03:00

553 lines
17 KiB
TypeScript

// 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;
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<Record<EquipmentSlot, ItemData>>;
}
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;
effects = new Map<string, EffectInstance>();
equipment = new Map<EquipmentSlot, ItemStack>();
// 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.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));
}
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 resistance
actually_hurt(amount: number, source: DamageSource) {
// absolute damage, take it and theres no counterplay
if (source.type === "absolute") {
this.health -= amount;
return;
}
const resistance = this.get_effect(EFFECTS.resistance);
if (resistance && !source.bypasses_invulnerability) {
amount = Math.max(0, amount * (25 - (resistance.amplifier + 1) * 5) / 25);
}
const shielding = this.attribute(
source.type === "physical" ? ATTRIBUTES.physical_shielding : ATTRIBUTES.arcane_shielding,
);
const post_mitigation = amount * (100 / (100 + shielding));
this.health -= post_mitigation;
}
// back to full health with nothing left over from before: no effects, fire, hurt cooldown or who hurt it. for
// players respawning, minecraft makes them a new entity instead
revive() {
this.clear_effects();
this.health = this.max_health;
this.fire = 0;
this.air = this.max_air;
this.fall_distance = 0;
this.vx = this.vy = this.vz = 0;
this.hurt_time = this.death_time = 0;
this.#hurt_cooldown = 0;
this.#last_hurt_amount = 0;
this.last_hurt_by_mob = this.last_hurt_by_player = undefined;
this.ticks_since_last_hurt_by_mob = this.last_hurt_by_player_memory_time = 0;
}
// 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;
}
// 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.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.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));
}
}
}