Basic entity system

This commit is contained in:
2026-09-28 15:12:06 -03:00
parent 84a622c3f1
commit 52ef4e5ca6
17 changed files with 3330 additions and 246 deletions
+80 -108
View File
@@ -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<string, (ItemData | null)[]>;
players: Record<string, SavedPlayer>;
// 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<string, Record<string, unknown>>;
}
@@ -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<string, ItemEntity>();
#next_entity_id = 1;
#mods: GameMods;
// ctx.containers, saved with the world
containers = new Map<string, Container>();
// 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<SavedLevel, "version" | "entities"> {
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) {