From d606bc4b55d53acb2fce740c26c3793fdb668254 Mon Sep 17 00:00:00 2001 From: paulaboks Date: Mon, 28 Sep 2026 17:42:56 -0300 Subject: [PATCH] Messy but working chicken --- MODS.md | 43 +++++++- client/entity/remote_entity.ts | 6 +- client/rendering/entity_renderer.ts | 112 ++++++++++++++++++++ client/rendering/level_renderer.ts | 4 + client/rendering/player_renderer.ts | 32 ++++-- common/bmod.ts | 15 ++- common/mod_check.ts | 32 +++++- common/mod_data.ts | 152 ++++++++++++++++++++++++++++ common/mod_loader.ts | 12 ++- mods/bworld/entities/chicken.json | 12 +++ mods/bworld/models/chicken.geo.json | 54 ++++++++++ mods/bworld/textures/chicken.png | Bin 0 -> 340 bytes server/game/entity/entity_types.ts | 5 + server/game/entity/mod_entity.ts | 40 ++++++++ server/game/game_server.ts | 21 ++++ server/game/load_mods.ts | 5 + server/load_bmods.ts | 2 + tests/bmod_test.ts | 2 +- tests/helpers.ts | 2 + tests/mod_entity_test.ts | 68 +++++++++++++ tools/check_mods.ts | 22 +++- tools/pack_mod.ts | 2 + 22 files changed, 622 insertions(+), 21 deletions(-) create mode 100644 client/rendering/entity_renderer.ts create mode 100644 mods/bworld/entities/chicken.json create mode 100644 mods/bworld/models/chicken.geo.json create mode 100644 mods/bworld/textures/chicken.png create mode 100644 server/game/entity/mod_entity.ts create mode 100644 tests/mod_entity_test.ts diff --git a/MODS.md b/MODS.md index 2ff77d6..5935c9b 100644 --- a/MODS.md +++ b/MODS.md @@ -27,7 +27,7 @@ bworld's modding takes from three places: - [manifest.json](#manifestjson) - [Identifiers](#identifiers) - Data: [Textures](#textures), [Blocks](#blocks), [Block models](#block-models), [Crops](#crops), [Items](#items), - [Recipes](#recipes), [Overrides](#overrides) + [Recipes](#recipes), [Entities](#entities), [Overrides](#overrides) - Game API: [Common scripts](#common-scripts), [Server scripts](#server-scripts), [Client scripts](#client-scripts), [GUIs](#guis), [Mod channels](#mod-channels), [World generation](#world-generation) - [Engine access](#engine-access) @@ -123,7 +123,9 @@ mods/ deno.json # optional: the mod is its own deno project, see Mod files blocks/*.json models/*.json + models/*.geo.json # entity models items/*.json + entities/*.json recipes/*.json overrides/*.json # changes to other mods' content worldgen/ores.json @@ -511,6 +513,42 @@ optional `container` (like `"bworld:bowl"`) is what the meal is served in, and ` set. It cooks while the block under it is hot: a lit stove (placed lit, relit with coal, put out with a shovel), or a burning furnace, whose `lit` state is 1 while it has fuel. +## Entities + +Mobs are an entity in `entities/` and a bedrock entity model in `models/`. `entities/chicken.json`: + +```json +{ + "format_version": 1, + "entity": { + "id": "bworld:chicken", + "model": "bworld:chicken", + "texture": "bworld:chicken", + "width": 0.3, + "height": 0.4, + "max_health": 4, + "movement_speed": 0.25 + } +} +``` + +| Field | Default | What it does | +| ---------------- | ------- | --------------------------------------------------------------------------- | +| `model` | | An entity model, see below. | +| `texture` | | Any texture, stretched to the model's `texture_width` and `texture_height`. | +| `width`/`height` | | Its collision box in blocks. Its eyes are at 85% of the height. | +| `max_health` | `10` | Half hearts. | +| `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. | + +Every entity is an animal for now: it wanders around, panics when hurt, looks at players now and then, swims up in +water and never despawns. `/summon ` spawns one where you stand. + +Entity models are `models/.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), with +id `:`. Only the first geometry is used, and from it the bones' `name`, `parent`, `pivot` and `rotation` +and the cubes' `origin`, `size`, `uv` and `inflate`. Cubes need box uv, per face uv isn't supported. The model faces +-z, 16 pixels to a block, and shows the way Blockbench shows it. It doesn't animate yet: the whole model turns with the +entity, and a bone named `head` turns to where it looks. + ## Overrides A mod can change content other mods registered, like Minetest's `override_item`. The JSON form covers the common cases, @@ -1834,5 +1872,6 @@ any order after them. warnings and a changelog to keep. - **Screen scaling.** The GUI currently works in raw canvas pixels (`SLOT_SIZE` is 54). `Graphics` should probably use a UI scale the player can change, with screens laid out in scaled units. -- **Entities.** The only entities are players and dropped items, so mob mods need entity types in the Game API first. +- **Entities.** Mods can define simple animals in `entities/`, but there's no Game API for entity types with their + own behavior, animations, or spawning them naturally yet. - **Hot reload.** Restarting the server and reconnecting is the version 1 answer. diff --git a/client/entity/remote_entity.ts b/client/entity/remote_entity.ts index 0ccdb4b..edd4067 100644 --- a/client/entity/remote_entity.ts +++ b/client/entity/remote_entity.ts @@ -1,4 +1,6 @@ import type { EntityData, EntityInfo } from "$/common/protocol.ts"; +import type { EntityJson } from "$/common/mod_data.ts"; +import { EverythingRegistry } from "$/common/everything_registry.ts"; import type { ClientLevel } from "../level/client_level.ts"; import { Entity } from "./entity.ts"; @@ -27,7 +29,9 @@ export class RemoteEntity extends Entity { #lerp_ticks = 0; constructor(level: ClientLevel, info: Extract) { - super(level, info.id, 0.6, 1.8, 1.62); + // the size of mods' entities, player sized for kinds the client doesn't know + const json = EverythingRegistry.get("entities", info.type); + super(level, info.id, json?.width ?? 0.6, json?.height ?? 1.8, json ? json.height * 0.85 : 1.62); this.type = info.type; this.data = info.data; this.set_position(info.x, info.y, info.z); diff --git a/client/rendering/entity_renderer.ts b/client/rendering/entity_renderer.ts new file mode 100644 index 0000000..9543c96 --- /dev/null +++ b/client/rendering/entity_renderer.ts @@ -0,0 +1,112 @@ +// mobs mods define (entities/.json), drawn with their entity model and a texture from the atlas. there are no +// animations yet: the model turns to the entity's yaw, and a bone named "head" to where it looks +import { AssetManager } from "$/client/assets.ts"; +import type { RemoteEntity } from "$/client/entity/remote_entity.ts"; +import type { Texture } from "$/client/renderer/mod.ts"; +import { get_sprite_region } from "$/client/sprites.ts"; +import { EverythingRegistry } from "$/common/everything_registry.ts"; +import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts"; +import { push_box, type Vec3 } from "./player_renderer.ts"; + +// models are in texture pixels, 16 to a block +const PIXEL = 1 / 16; +// how much of each color is left while it flashes red after being hurt, like minecraft's +const HURT_TINT: Vec3 = [1, 0.6, 0.6]; + +// the atlas has to be the current texture +export function render_mod_entity(entity: RemoteEntity, partial_tick: number) { + const json = EverythingRegistry.get("entities", entity.type); + const model = json && EverythingRegistry.get("entity_models", json.model); + if (!model) return; + + const atlas = AssetManager.instance.get("bworld:textures"); + const region = get_sprite_region(json.texture); + const to_uv = (u: number, v: number): [number, number] => [ + (region.x + u * region.width / model.texture_width) / atlas.width, + (region.y + v * region.height / model.texture_height) / atlas.height, + ]; + + const { x, y, z } = entity.render_position(partial_tick); + const yaw_sin = Math.sin(entity.yaw); + const yaw_cos = Math.cos(entity.yaw); + const tint = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined; + + const bones = new Map(); + for (const bone of model.bones) { + let matrix = bone_matrix(bone); + if (bone.name === "head") { + const look = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0); + matrix = multiply(look, matrix); + } + if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix); + bones.set(bone.name, matrix); + + const transform = (px: number, py: number, pz: number): Vec3 => { + const [mx, my, mz] = apply(matrix, px, py, pz).map((n) => n * PIXEL); + return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos]; + }; + for (const cube of bone.cubes) { + const inflate = cube.inflate ?? 0; + const [ox, oy, oz] = cube.origin; + const [w, h, d] = cube.size; + // bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right + const low: Vec3 = [-(ox + w) - inflate, oy - inflate, oz - inflate]; + const high: Vec3 = [-ox + inflate, oy + h + inflate, oz + d + inflate]; + push_box(cube.size, low, high, cube.uv, to_uv, transform, tint); + } + } +} + +// 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's +type Matrix = number[]; + +const IDENTITY: Matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; + +function model_pivot(bone: EntityBoneJson): Vec3 { + return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]]; +} + +// its own rotation around its pivot. mirroring x turns x and y rotations the other way +function bone_matrix(bone: EntityBoneJson): Matrix { + if (!bone.rotation) return IDENTITY; + const [rx, ry, rz] = bone.rotation.map((degrees) => degrees * Math.PI / 180); + return rotation_around(model_pivot(bone), -rx, -ry, rz); +} + +// turns around pivot by x, then y, then z (radians). y turns like the whole model does (see render_mod_entity) and x +// like the player's head pitch +function rotation_around(pivot: Vec3, rx: number, ry: number, rz: number): Matrix { + const [sx, cx] = [Math.sin(rx), Math.cos(rx)]; + const [sy, cy] = [Math.sin(ry), Math.cos(ry)]; + const [sz, cz] = [Math.sin(rz), Math.cos(rz)]; + const rot_x = [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0]; + const rot_y = [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0]; + const rot_z = [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0]; + const [px, py, pz] = pivot; + const rotation = multiply(rot_z, multiply(rot_y, rot_x)); + return multiply( + [1, 0, 0, px, 0, 1, 0, py, 0, 0, 1, pz], + multiply(rotation, [1, 0, 0, -px, 0, 1, 0, -py, 0, 0, 1, -pz]), + ); +} + +// a after b +function multiply(a: Matrix, b: Matrix): Matrix { + const out: Matrix = []; + for (let row = 0; row < 3; row++) { + for (let col = 0; col < 4; col++) { + let sum = col === 3 ? a[row * 4 + 3] : 0; + for (let k = 0; k < 3; k++) sum += a[row * 4 + k] * b[k * 4 + col]; + out.push(sum); + } + } + return out; +} + +function apply(m: Matrix, x: number, y: number, z: number): Vec3 { + return [ + m[0] * x + m[1] * y + m[2] * z + m[3], + m[4] * x + m[5] * y + m[6] * z + m[7], + m[8] * x + m[9] * y + m[10] * z + m[11], + ]; +} diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index 747bca6..9a25aff 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -8,6 +8,8 @@ import { RemotePlayer } from "$/client/entity/remote_player.ts"; import { ItemEntity } from "$/client/entity/item_entity.ts"; import { render_item_entity } from "./item_renderer.ts"; import { render_player } from "./player_renderer.ts"; +import { render_mod_entity } from "./entity_renderer.ts"; +import { RemoteEntity } from "$/client/entity/remote_entity.ts"; import { draw_terrain, flush_batch, @@ -111,6 +113,8 @@ export class LevelRenderer { for (const entity of level.entities.values()) { if (entity instanceof ItemEntity) { render_item_entity(entity, partial_tick); + } else if (entity instanceof RemoteEntity) { + render_mod_entity(entity, partial_tick); } } flush_batch(); diff --git a/client/rendering/player_renderer.ts b/client/rendering/player_renderer.ts index 5cec05f..91d10e1 100644 --- a/client/rendering/player_renderer.ts +++ b/client/rendering/player_renderer.ts @@ -2,7 +2,7 @@ import { PLAYER_HEIGHT } from "$/common/constants.ts"; import type { Player } from "$/client/entity/player.ts"; import { push_vertex, type Texture } from "$/client/renderer/mod.ts"; -type Vec3 = [number, number, number]; +export type Vec3 = [number, number, number]; // minecraft's player model is 32 skin pixels tall, it's scaled to the player's height const PIXEL = PLAYER_HEIGHT / 32; @@ -181,20 +181,32 @@ export function render_player(player: Player, skin: Texture, partial_tick: numbe function push_cube( skin: Texture, part: ModelPart, - [u, v]: [number, number], + uv: [number, number], inflate: number, transform: (x: number, y: number, z: number) => Vec3, ) { - const [w, h, d] = part.size; - const low = part.from.map((n) => n - inflate); - const high = part.from.map((n, i) => n + part.size[i] + inflate); + const low = part.from.map((n) => n - inflate) as Vec3; + const high = part.from.map((n, i) => n + part.size[i] + inflate) as Vec3; + push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform); +} +// a box of a model, from low to high, textured like minecraft's box uv from [u, v] for a box of size (in texture +// pixels). to_uv turns texture pixels into the current texture's coordinates, tint multiplies its colors +export function push_box( + size: Vec3, + low: Vec3, + high: Vec3, + [u, v]: [number, number], + to_uv: (u: number, v: number) => [number, number], + transform: (x: number, y: number, z: number) => Vec3, + tint: Vec3 = [1, 1, 1], +) { + const [w, h, d] = size; for (const face of FACES) { const [rx, ry, rw, rh] = face.rect(w, h, d); - const u0 = (u + rx + UV_INSET) / skin.width; - const v0 = (v + ry + UV_INSET) / skin.height; - const u1 = (u + rx + rw - UV_INSET) / skin.width; - const v1 = (v + ry + rh - UV_INSET) / skin.height; + const [u0, v0] = to_uv(u + rx + UV_INSET, v + ry + UV_INSET); + const [u1, v1] = to_uv(u + rx + rw - UV_INSET, v + ry + rh - UV_INSET); + const [r, g, b] = tint.map((c) => c * face.shade); for (const i of [0, 1, 2, 0, 2, 3]) { const [cx, cy, cz, cu, cv] = face.corners[i]; @@ -203,7 +215,7 @@ function push_cube( cy ? high[1] : low[1], cz ? high[2] : low[2], ); - push_vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, face.shade, face.shade, face.shade, 1); + push_vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, r, g, b, 1); } } } diff --git a/common/bmod.ts b/common/bmod.ts index 8d8daff..2321176 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -5,12 +5,16 @@ import type { ModelJson } from "./block_models.ts"; import { MAX_TEXTURE_SIZE } from "./constants.ts"; import { type BlockJson, + type EntityJson, + type EntityModelJson, ID_PATTERN, type ItemJson, type ManifestJson, type OreJson, type RecipeJson, validate_block, + validate_entity, + validate_entity_model, validate_item, validate_manifest, validate_model, @@ -49,7 +53,7 @@ export class BmodError extends Error { // the zip's layout: // manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip -// data.json every block, model, item, recipe and ore +// data.json every block, model, item, recipe, ore, entity and entity model // scripts/.js // textures/.png the texture : // credits.md @@ -133,9 +137,16 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { items: checked(raw_data.items, "items", validate_item, problems) as ItemJson[], recipes: checked(raw_data.recipes, "recipes", validate_recipe, problems) as RecipeJson[], ores: checked(raw_data.ores, "ores", validate_ore, problems) as OreJson[], + entities: checked(raw_data.entities, "entities", validate_entity, problems) as EntityJson[], + entity_models: checked( + raw_data.entity_models, + "entity_models", + validate_entity_model, + problems, + ) as EntityModelJson[], }; // a mod only registers ids in its own namespace - for (const { id } of [...data.blocks, ...data.models, ...data.items]) { + for (const { id } of [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models]) { if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`); } diff --git a/common/mod_check.ts b/common/mod_check.ts index edbb98c..66ec004 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -1,6 +1,14 @@ // checks between mods: dependencies, load order, and ids one mod uses from another. pure, so the build, check-mods // and the server (on .bmod files) all use it -import { type BlockJson, choice_ids, type ItemJson, type OreJson, type RecipeJson } from "./mod_data.ts"; +import { + type BlockJson, + choice_ids, + type EntityJson, + type EntityModelJson, + type ItemJson, + type OreJson, + type RecipeJson, +} from "./mod_data.ts"; import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts"; export interface ModReport { @@ -19,6 +27,8 @@ export interface LoadedMod { items: { file: string; json: ItemJson }[]; recipes: { file: string; json: RecipeJson }[]; ores: { file: string; json: OreJson }[]; + entities: { file: string; json: EntityJson }[]; + entity_models: { file: string; json: EntityModelJson }[]; textures: string[]; // absolute paths by texture id texture_files: Map; @@ -56,6 +66,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable(); const item_owners = new Map(); const model_owners = new Map(); + const entity_owners = new Map(); + const entity_model_owners = new Map(); const add = (map: Map, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]); const textures = new Set(engine_textures); @@ -67,6 +79,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable { + const uses = (file: string, id: string, what: "block" | "item" | "texture" | "model" | "entity model") => { const namespace = id.split(":")[0]; if (namespace !== mod.id && namespace !== "engine" && !dependencies.has(namespace)) { warnings.push(`${file}: uses ${id} but doesn't list "${namespace}" in dependencies`); } if (what === "model") { if (!BUILTIN_MODELS[id] && !model_owners.has(id)) errors.push(`${file}: model ${id} doesn't exist`); + } else if (what === "entity model") { + if (!entity_model_owners.has(id)) errors.push(`${file}: entity model ${id} doesn't exist`); } else if (what === "texture") { if (!textures.has(id)) warnings.push(`${file}: texture ${id} doesn't exist, it will show as missing`); } else if (!(what === "block" ? block_owners : item_owners).has(id)) { @@ -158,5 +174,17 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable 1) { + errors.push(`${file}: entity ${json.id} is also defined by ${entity_owners.get(json.id)!.join(", ")}`); + } + uses(file, json.model, "entity model"); + uses(file, json.texture, "texture"); + } + for (const { file, json } of mod.entity_models) { + if ((entity_model_owners.get(json.id)?.length ?? 0) > 1) { + errors.push(`${file}: entity model ${json.id} is defined more than once`); + } + } } } diff --git a/common/mod_data.ts b/common/mod_data.ts index 0f3aae5..d7edbc0 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -80,6 +80,52 @@ export interface ItemJson { components?: Record; } +// a kind of mob, drawn with an entity model and one texture. it wanders around, panics when hurt and looks at players +export interface EntityJson { + id: string; + // an entity model, see EntityModelJson + model: string; + texture: string; + // its collision box in blocks, width is for both x and z + width: number; + height: number; + max_health?: number; + // minecraft's per tick speed, 0.25 for most animals + movement_speed?: number; +} + +type Vec3 = [number, number, number]; + +// a bedrock entity model (models/.geo.json) with only what the engine uses. positions and sizes are in +// texture pixels, 16 to a block, and the model faces -z with its feet at 0 +export interface EntityModelJson { + id: string; + // the size its uvs are laid out for, the texture is stretched to it + texture_width: number; + texture_height: number; + // parents come before their children + bones: EntityBoneJson[]; +} + +export interface EntityBoneJson { + name: string; + parent?: string; + // what it turns around + pivot: Vec3; + // degrees around x, y then z + rotation?: Vec3; + cubes: EntityCubeJson[]; +} + +// a box from origin to origin + size, textured like minecraft's box uv: see the renderer's FACES +export interface EntityCubeJson { + origin: Vec3; + size: Vec3; + uv: [number, number]; + // grows the box this many pixels each way without moving its texture + inflate?: number; +} + // an item a recipe takes: its id, or a list of ids any of which fits, like every kind of planks export type ItemChoice = string | string[]; @@ -579,6 +625,112 @@ export function validate_ore(json: unknown): Problems { return problems; } +export function validate_entity(json: unknown): Problems { + if (!is_object(json)) return ["entity must be an object"]; + const problems = [ + ...validate_id(json.id, "id"), + ...validate_id(json.model, "model"), + ...validate_id(json.texture, "texture"), + ]; + for (const key of ["width", "height"]) { + if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) { + problems.push(`${key} must be a number of blocks above 0, at most 16`); + } + } + for (const key of ["max_health", "movement_speed"]) { + if (json[key] !== undefined && (typeof json[key] !== "number" || json[key] < 0)) { + problems.push(`${key} must be a number, 0 or more`); + } + } + return problems; +} + +export function validate_entity_model(json: unknown): Problems { + if (!is_object(json)) return ["entity model must be an object"]; + const problems = validate_id(json.id, "id"); + for (const key of ["texture_width", "texture_height"]) { + if (!Number.isInteger(json[key]) || (json[key] as number) < 1) problems.push(`${key} must be a whole number`); + } + if (!Array.isArray(json.bones)) return [...problems, "bones must be a list"]; + const names = new Set(); + json.bones.forEach((bone, i) => { + const field = `bones[${i}]`; + if (!is_object(bone) || typeof bone.name !== "string") { + problems.push(`${field} must be { name, pivot, cubes }`); + return; + } + if (names.has(bone.name)) problems.push(`${field}: there are two bones named ${bone.name}`); + if (bone.parent !== undefined && !names.has(bone.parent as string)) { + problems.push(`${field}: parent ${bone.parent} must be a bone before it`); + } + names.add(bone.name); + problems.push(...validate_vec3(bone.pivot, `${field}.pivot`)); + if (bone.rotation !== undefined) problems.push(...validate_vec3(bone.rotation, `${field}.rotation`)); + if (!Array.isArray(bone.cubes)) { + problems.push(`${field}.cubes must be a list`); + return; + } + bone.cubes.forEach((cube, j) => { + const cube_field = `${field}.cubes[${j}]`; + if (!is_object(cube)) { + problems.push(`${cube_field} must be { origin, size, uv }`); + return; + } + problems.push(...validate_vec3(cube.origin, `${cube_field}.origin`)); + problems.push(...validate_vec3(cube.size, `${cube_field}.size`)); + if (!Array.isArray(cube.uv) || cube.uv.length !== 2 || !cube.uv.every((n) => typeof n === "number")) { + problems.push(`${cube_field}.uv must be [u, v], per face uvs aren't supported`); + } + if (cube.inflate !== undefined && typeof cube.inflate !== "number") { + problems.push(`${cube_field}.inflate must be a number`); + } + }); + }); + return problems; +} + +// a models/.geo.json, as blockbench exports it for bedrock, to an EntityModelJson. its first geometry is used +export function entity_model_from_geo(json: unknown, id: string): { model?: EntityModelJson; problems: Problems } { + const geometry = is_object(json) && Array.isArray(json["minecraft:geometry"]) + ? json["minecraft:geometry"][0] + : undefined; + if (!is_object(geometry) || !is_object(geometry.description)) { + return { + problems: ['must be a bedrock model: { "minecraft:geometry": [{ "description": ..., "bones": [...] }] }'], + }; + } + const bones = Array.isArray(geometry.bones) ? geometry.bones : []; + const model = { + id, + texture_width: geometry.description.texture_width, + texture_height: geometry.description.texture_height, + bones: bones.map((bone) => { + if (!is_object(bone)) return bone; + const { name, parent, pivot, rotation } = bone; + const cubes = Array.isArray(bone.cubes) ? bone.cubes : []; + return { + name, + ...(parent === undefined ? {} : { parent }), + pivot: pivot ?? [0, 0, 0], + ...(rotation === undefined ? {} : { rotation }), + cubes: cubes.map((cube) => { + if (!is_object(cube)) return cube; + const { origin, size, uv, inflate } = cube; + return { origin, size, uv, ...(inflate === undefined ? {} : { inflate }) }; + }), + }; + }), + }; + const problems = validate_entity_model(model); + return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems }; +} + +function validate_vec3(value: unknown, field: string): Problems { + return Array.isArray(value) && value.length === 3 && value.every((n) => typeof n === "number") + ? [] + : [`${field} must be [x, y, z]`]; +} + // an item id, or a list of them any of which fits function validate_choice(value: unknown, field: string): Problems { if (!Array.isArray(value)) return validate_id(value, field); diff --git a/common/mod_loader.ts b/common/mod_loader.ts index a3a20c1..9d25977 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -4,6 +4,8 @@ import { block_from_json, BlockJson, choice_ids, + EntityJson, + EntityModelJson, grid_recipe_from_json, GridRecipe, is_mod_recipe, @@ -24,6 +26,8 @@ export interface ModData { items: ItemJson[]; recipes: RecipeJson[]; ores: OreJson[]; + entities: EntityJson[]; + entity_models: EntityModelJson[]; } // a mod as the server lists it to clients, in load order: the .bmod players download, without its server script @@ -57,7 +61,7 @@ export class ModLoadError extends Error { } } -// registers every mod's blocks, items and recipes, in the order given (dependencies first) +// registers every mod's blocks, items, entities and recipes, in the order given (dependencies first) export function register_mod_data(mods: { id: string; data: ModData }[]): RecipeBook { const recipes = new RecipeBook(); @@ -79,6 +83,12 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe for (const json of data.items) { EverythingRegistry.register("items", json.id, item_from_json(json)); } + for (const model of data.entity_models) { + EverythingRegistry.register("entity_models", model.id, model); + } + for (const json of data.entities) { + EverythingRegistry.register("entities", json.id, json); + } } catch (e) { fail((e as Error).message); } diff --git a/mods/bworld/entities/chicken.json b/mods/bworld/entities/chicken.json new file mode 100644 index 0000000..ccea854 --- /dev/null +++ b/mods/bworld/entities/chicken.json @@ -0,0 +1,12 @@ +{ + "format_version": 1, + "entity": { + "id": "bworld:chicken", + "model": "bworld:chicken", + "texture": "bworld:chicken", + "width": 0.3, + "height": 0.4, + "max_health": 4, + "movement_speed": 0.25 + } +} diff --git a/mods/bworld/models/chicken.geo.json b/mods/bworld/models/chicken.geo.json new file mode 100644 index 0000000..3dc83dc --- /dev/null +++ b/mods/bworld/models/chicken.geo.json @@ -0,0 +1,54 @@ +{ + "format_version": "1.12.0", + "minecraft:geometry": [ + { + "description": { + "identifier": "geometry.chicken", + "texture_width": 16, + "texture_height": 16, + "visible_bounds_width": 2, + "visible_bounds_height": 1.5, + "visible_bounds_offset": [0, 0.25, 0] + }, + "bones": [ + { + "name": "root", + "pivot": [0, 0, 0] + }, + { + "name": "left_feet", + "parent": "root", + "pivot": [0, 0, 0], + "cubes": [ + {"origin": [-2, 0, -1], "size": [1, 2, 1], "uv": [8, 8]} + ] + }, + { + "name": "right_feet", + "parent": "root", + "pivot": [0, 0, 0], + "cubes": [ + {"origin": [1, 0, -1], "size": [1, 2, 1], "uv": [0, 10]} + ] + }, + { + "name": "body", + "parent": "root", + "pivot": [0, 0, 0], + "cubes": [ + {"origin": [-2, 2, -2], "size": [4, 2, 4], "uv": [0, 0]} + ] + }, + { + "name": "head", + "parent": "root", + "pivot": [1, 2, -1], + "cubes": [ + {"origin": [-1, 4, -2], "size": [2, 2, 2], "uv": [0, 6]}, + {"origin": [-1, 4, -3], "size": [2, 1, 1], "uv": [8, 6]} + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/mods/bworld/textures/chicken.png b/mods/bworld/textures/chicken.png new file mode 100644 index 0000000000000000000000000000000000000000..39f8a6f83b75a0924d43cd32fc83ad405af7f3ed GIT binary patch literal 340 zcmV-a0jvIrP)6^}5PiF<0$bZQt!w|Fwsp02brpO72?|M2BzyoQI2;B6iVuJfzySe*BRB*gIQC6$ zFUxS@2yE`{ynQ?SZe}dhiZYf;$C-gn$U3JQtak?xeEj=gWDta01h=Ic48}_k?jG%C zl|c}45!_~V%TB}3$CH3uL+7VfpdVd2TN5vz#6F2wmJl@zLWme|nH3!Bh`c%D{;PoP zq>yOI44fed4vO%-+B{6}bB@^xAb)tP8G>d+Qo&z;1A=0RX$8@H=UF6jA;Bgy=#CaB z4|8aJ=Ufq|Uyz$hEnWGCmq&nHXT6qSLg@RX1$}Yt*?M;li2T}zKJWetywk1m2mk>8 m|Atzr(f|Me21!IgR09C^$CV+$(9F>Q0000 id !== ITEM_ENTITY_TYPE).sort(); +} + export function has_entity_type(id: string) { return types.has(id); } diff --git a/server/game/entity/mod_entity.ts b/server/game/entity/mod_entity.ts new file mode 100644 index 0000000..bac3716 --- /dev/null +++ b/server/game/entity/mod_entity.ts @@ -0,0 +1,40 @@ +// mobs mods define in entities/.json (see EntityJson): each one is a kind of animal that wanders around, +// panics when hurt and looks at players now and then, like minecraft's simpler animals +import type { EntityJson } from "$/common/mod_data.ts"; +import { ATTRIBUTES, type AttributeType } from "./attributes.ts"; +import type { EntityFactory } from "./entity_types.ts"; +import { FloatGoal, LookAtPlayerGoal, PanicGoal, RandomLookAroundGoal, RandomStrollGoal } from "./goals.ts"; +import { Mob } from "./mob.ts"; + +// the entity's class. the attributes are read while LivingEntity is being built, before any field of a subclass is +// set, so each kind gets its own class that has its json already +export function mod_entity_factory(json: EntityJson): EntityFactory { + class ModEntity extends Mob { + readonly type = json.id; + override width = json.width; + override height = json.height; + override eye_height = json.height * 0.85; + + override default_attributes(): [AttributeType, number?][] { + return [ + ...super.default_attributes(), + [ATTRIBUTES.max_health, json.max_health ?? 10], + [ATTRIBUTES.movement_speed, json.movement_speed ?? 0.25], + ]; + } + + override register_goals() { + this.goals.add_goal(0, new FloatGoal(this)); + this.goals.add_goal(1, new PanicGoal(this, 1.4)); + this.goals.add_goal(5, new RandomStrollGoal(this, 1)); + this.goals.add_goal(6, new LookAtPlayerGoal(this, 6)); + this.goals.add_goal(7, new RandomLookAroundGoal(this)); + } + + // animals stay, like minecraft's farm animals + override remove_when_far_away() { + return false; + } + } + return (level) => new ModEntity(level); +} diff --git a/server/game/game_server.ts b/server/game/game_server.ts index f2567ec..187610a 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -55,6 +55,7 @@ import { type SavedItemEntity, } from "./entity/item_entity.ts"; import { EntityManager } from "./entity/entity_manager.ts"; +import { create_entity, entity_type_ids } from "./entity/entity_types.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 @@ -1046,6 +1047,26 @@ export class GameServer { ), ); + // TODO: only let operators do this + register( + literal("summon").describe("Spawns an entity where you are").then( + argument("entity", word()) + .suggests((partial) => + entity_type_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text })) + ) + .executes((context) => { + const id = context.get("entity"); + const entity = entity_type_ids().includes(id) ? create_entity(this.entities, id) : undefined; + if (!entity) throw new CommandError(`There's no entity ${id}`); + const player = context.source.server_player; + entity.set_position(player.x, player.y, player.z); + entity.yaw = entity.head_yaw = player.yaw; + this.entities.add_entity(entity); + context.source.send_message(`Summoned ${id}`); + }), + ), + ); + register( literal("tps").describe("Shows how the game loop keeps up").executes((context) => { if (!this.loop) { diff --git a/server/game/load_mods.ts b/server/game/load_mods.ts index b1d9870..9570354 100644 --- a/server/game/load_mods.ts +++ b/server/game/load_mods.ts @@ -6,6 +6,8 @@ import { load_worldgen } from "$/common/worldgen_loader.ts"; import { GameHost, GameServer } from "./game_server.ts"; import type { WorldSave } from "./saves.ts"; import { ModRuntime } from "./mod_runtime.ts"; +import { register_entity_type } from "./entity/entity_types.ts"; +import { mod_entity_factory } from "./entity/mod_entity.ts"; export interface ServerModSource { listing: ModListing; @@ -22,6 +24,9 @@ export async function start_game( mods: ServerModSource[], ): Promise { const recipes = register_mod_data(mods.map((mod) => ({ id: mod.listing.id, data: mod.data }))); + for (const mod of mods) { + for (const json of mod.data.entities) register_entity_type(json.id, mod_entity_factory(json)); + } const worldgen_scripts = mods.flatMap((mod) => mod.worldgen_url ? [{ mod: mod.listing.id, url: mod.worldgen_url }] : [] diff --git a/server/load_bmods.ts b/server/load_bmods.ts index 3adcb90..b0c0d37 100644 --- a/server/load_bmods.ts +++ b/server/load_bmods.ts @@ -100,6 +100,8 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod { items: entries(bmod.data.items), recipes: entries(bmod.data.recipes), ores: entries(bmod.data.ores), + entities: entries(bmod.data.entities), + entity_models: entries(bmod.data.entity_models), textures: [...bmod.textures.keys()], texture_files: new Map(), }; diff --git a/tests/bmod_test.ts b/tests/bmod_test.ts index 188bf58..93628f0 100644 --- a/tests/bmod_test.ts +++ b/tests/bmod_test.ts @@ -240,7 +240,7 @@ Deno.test("the atlas fits textures of any size, tallest first, without overlappi Deno.test("a mod with only data packs and reads", () => { const bmod = { manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" }, - data: { blocks: [], models: [], items: [], recipes: [], ores: [] }, + data: { blocks: [], models: [], items: [], recipes: [], ores: [], entities: [], entity_models: [] }, scripts: {}, textures: new Map(), }; diff --git a/tests/helpers.ts b/tests/helpers.ts index 1089489..d5ad372 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -32,6 +32,8 @@ export function mod_sources(mods_dir: string): ServerModSource[] { items: mod.items.map((i) => i.json), recipes: mod.recipes.map((r) => r.json), ores: mod.ores.map((o) => o.json), + entities: mod.entities.map((e) => e.json), + entity_models: mod.entity_models.map((m) => m.json), }, server_url: url(scripts.server), worldgen_url: url(scripts.worldgen), diff --git a/tests/mod_entity_test.ts b/tests/mod_entity_test.ts new file mode 100644 index 0000000..071fc53 --- /dev/null +++ b/tests/mod_entity_test.ts @@ -0,0 +1,68 @@ +// mobs mods define in entities/.json, drawn with a bedrock model from models/.geo.json +import { assert, assertEquals, assertStringIncludes } from "@std/assert"; +import { entity_model_from_geo, validate_entity } from "$/common/mod_data.ts"; +import { Mob } from "$/server/game/entity/mob.ts"; +import { test_game } from "./helpers.ts"; + +Deno.test("a bedrock geo.json becomes an entity model with only what the engine uses", () => { + const geo = JSON.parse(Deno.readTextFileSync("mods/bworld/models/chicken.geo.json")); + const { model, problems } = entity_model_from_geo(geo, "bworld:chicken"); + assertEquals(problems, []); + assertEquals(model!.texture_width, 16); + assertEquals(model!.bones.map((bone) => bone.name), ["root", "left_feet", "right_feet", "body", "head"]); + assertEquals(model!.bones[4], { + name: "head", + parent: "root", + pivot: [1, 2, -1], + cubes: [ + { origin: [-1, 4, -2], size: [2, 2, 2], uv: [0, 6] }, + { origin: [-1, 4, -3], size: [2, 1, 1], uv: [8, 6] }, + ], + }); + + // per face uvs and parents that come later aren't supported + const per_face = { origin: [0, 0, 0], size: [1, 1, 1], uv: { north: { uv: [0, 0], uv_size: [1, 1] } } }; + const bad = entity_model_from_geo({ + "minecraft:geometry": [{ + description: { texture_width: 16, texture_height: 16 }, + bones: [{ name: "leg", parent: "body", cubes: [per_face] }, { name: "body" }], + }], + }, "a:b"); + assertEquals(bad.model, undefined); + assert(bad.problems.some((p) => p.includes("parent body must be a bone before it")), String(bad.problems)); + assert(bad.problems.some((p) => p.includes("per face uvs aren't supported")), String(bad.problems)); + assertEquals(entity_model_from_geo({ format_version: "1.12.0" }, "a:b").model, undefined); +}); + +Deno.test("an entity needs a model, a texture and a size", () => { + assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0.5, height: 1 }), []); + assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0, height: 1, max_health: -1 }), [ + "width must be a number of blocks above 0, at most 16", + "max_health must be a number, 0 or more", + ]); +}); + +Deno.test("/summon spawns a mod's entity where the player is", async () => { + const { join, take, send, game } = await test_game("mods"); + join(1, "alice"); + send(1, { type: "move", x: 3.5, y: 100, z: -2.5, yaw: 1, pitch: 0 }); + take(1); + + send(1, { type: "suggest", id: 1, text: "/summon bworld:chi" }); + assertEquals(take(1).find((m) => m.type === "suggestions").suggestions, [{ text: "bworld:chicken" }]); + + send(1, { type: "chat", text: "/summon bworld:chicken" }); + const messages = take(1); + const added = messages.find((m) => m.type === "add_entity"); + assertEquals(added.entity.type, "bworld:chicken"); + assertEquals([added.entity.x, added.entity.y, added.entity.z], [3.5, 100, -2.5]); + + const chicken = game.entities.get_entity(added.entity.id) as Mob; + assert(chicken instanceof Mob); + assertEquals([chicken.width, chicken.height, chicken.max_health], [0.3, 0.4, 4]); + // animals don't despawn + assertEquals(chicken.remove_when_far_away(1000), false); + + send(1, { type: "chat", text: "/summon bworld:item" }); + assertStringIncludes(take(1).find((m) => m.type === "chat").text, "There's no entity bworld:item"); +}); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index 09c2f1d..b0e93ca 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -1,9 +1,11 @@ // deno task check-mods // validates every mod in mods/: manifests, data files, textures, references between them, and typechecks scripts import { + entity_model_from_geo, FORMAT_VERSION, OreJson, validate_block, + validate_entity, validate_item, validate_manifest, validate_model, @@ -66,6 +68,8 @@ function load_mod(mods_dir: string, id: string): LoadedMod { items: [], recipes: [], ores: [], + entities: [], + entity_models: [], textures: [], texture_files: new Map(), }; @@ -97,7 +101,8 @@ function load_mod(mods_dir: string, id: string): LoadedMod { validate: (json: unknown) => string[], into: { file: string; json: T }[], ) => { - for (const file of walk(`${dir}/${folder}`, ".json")) { + // models/.geo.json are entity models, not block ones + for (const file of walk(`${dir}/${folder}`, ".json").filter((file) => !file.endsWith(".geo.json"))) { const path = `${folder}/${file}`; const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); if (wrapper === undefined) continue; @@ -114,6 +119,19 @@ function load_mod(mods_dir: string, id: string): LoadedMod { load_data("models", "model", validate_model, mod.models); load_data("items", "item", validate_item, mod.items); load_data("recipes", "recipe", validate_recipe, mod.recipes); + load_data("entities", "entity", validate_entity, mod.entities); + + for (const file of walk(`${dir}/models`, ".geo.json")) { + const path = `models/${file}`; + const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); + if (json === undefined) continue; + const { model, problems } = entity_model_from_geo( + json, + `${id}:${file.replace(/\.geo\.json$/, "").replaceAll("/", "_")}`, + ); + for (const problem of problems) error(`${path}: ${problem}`); + if (model) mod.entity_models.push({ file: path, json: model }); + } if (exists(`${dir}/worldgen/ores.json`)) { const ores = read_json(`${dir}/worldgen/ores.json`, (m) => error(`worldgen/ores.json: ${m}`)); @@ -129,7 +147,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod { } // a mod only registers ids in its own namespace - for (const { file, json } of [...mod.blocks, ...mod.models, ...mod.items]) { + for (const { file, json } of [...mod.blocks, ...mod.models, ...mod.items, ...mod.entities]) { if (json.id.split(":")[0] !== id) error(`${file}: ${json.id} isn't in this mod's namespace "${id}"`); } diff --git a/tools/pack_mod.ts b/tools/pack_mod.ts index 6bf139a..5204930 100644 --- a/tools/pack_mod.ts +++ b/tools/pack_mod.ts @@ -31,6 +31,8 @@ export async function pack_mod(mod: LoadedMod): Promise> items: mod.items.map((i) => i.json), recipes: mod.recipes.map((r) => r.json), ores: mod.ores.map((o) => o.json), + entities: mod.entities.map((e) => e.json), + entity_models: mod.entity_models.map((m) => m.json), }, scripts, textures,