diff --git a/client/entity/entity.ts b/client/entity/entity.ts index 40c5546..059112a 100644 --- a/client/entity/entity.ts +++ b/client/entity/entity.ts @@ -36,6 +36,10 @@ export abstract class Entity { step_grace_ticks = 0; // ticks since it was last on the ground #air_ticks = 0; + // how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState + walk_position = 0; + walk_speed = 0; + prev_walk_speed = 0; // which way it hit something on each axis in the last move: 1 or -1, 0 for nothing. // 1 on y means it's standing on something @@ -55,6 +59,21 @@ export abstract class Entity { return this.colliding_y === 1; } + // after moving each tick. full speed is 5 blocks per second, a bit faster than walking + update_walk_animation() { + const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z); + this.prev_walk_speed = this.walk_speed; + this.walk_speed += (Math.min(moved * 4, 1) - this.walk_speed) * 0.4; + this.walk_position += this.walk_speed; + } + + walk_animation(partial_tick: number) { + return { + position: this.walk_position - this.walk_speed * (1 - partial_tick), + speed: this.prev_walk_speed + (this.walk_speed - this.prev_walk_speed) * partial_tick, + }; + } + // jumps there, without interpolating from where it was set_position(x: number, y: number, z: number) { this.x = this.prev_x = x; diff --git a/client/entity/player.ts b/client/entity/player.ts index 4e4983a..4fe7c6f 100644 --- a/client/entity/player.ts +++ b/client/entity/player.ts @@ -17,11 +17,6 @@ export abstract class Player extends Entity { slim = false; #skin_version = 0; - // how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState - walk_position = 0; - walk_speed = 0; - prev_walk_speed = 0; - constructor(level: ClientLevel, id: string, name: string) { super(level, id, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_EYE_HEIGHT); this.name = name; @@ -40,19 +35,4 @@ export abstract class Player extends Entity { this.skin = texture; this.slim = slim; } - - // after moving each tick. full speed is 5 blocks per second, a bit faster than walking - update_walk_animation() { - const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z); - this.prev_walk_speed = this.walk_speed; - this.walk_speed += (Math.min(moved * 4, 1) - this.walk_speed) * 0.4; - this.walk_position += this.walk_speed; - } - - walk_animation(partial_tick: number) { - return { - position: this.walk_position - this.walk_speed * (1 - partial_tick), - speed: this.prev_walk_speed + (this.walk_speed - this.prev_walk_speed) * partial_tick, - }; - } } diff --git a/client/entity/remote_entity.ts b/client/entity/remote_entity.ts index edd4067..1999074 100644 --- a/client/entity/remote_entity.ts +++ b/client/entity/remote_entity.ts @@ -1,4 +1,4 @@ -import type { EntityData, EntityInfo } from "$/common/protocol.ts"; +import type { EntityData, EntityEvent, 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"; @@ -9,6 +9,8 @@ const LERP_TICKS = 3; // how long it flashes red after being hurt, and falls over after dying, like minecraft const HURT_TICKS = 10; const DEATH_TICKS = 20; +// how long its attack swing takes, like minecraft's mobs +const SWING_TICKS = 6; // an entity the server simulates, like a mob. this only follows where it's told it is and keeps what it was told // it looks like, for drawing it @@ -24,6 +26,8 @@ export class RemoteEntity extends Entity { dead = false; // what's riding it, by id passengers: string[] = []; + // ticks into its attack swing, undefined when it isn't swinging + swing_ticks: number | undefined; #target = { x: 0, y: 0, z: 0, yaw: 0, pitch: 0, head_yaw: 0 }; #lerp_ticks = 0; @@ -46,9 +50,12 @@ export class RemoteEntity extends Entity { this.#lerp_ticks = LERP_TICKS; } - on_event(event: "hurt" | "death") { + on_event(event: EntityEvent) { if (event === "hurt") { this.hurt_time = HURT_TICKS; + } else if (event === "swing") { + // swinging again halfway through doesn't restart it, like minecraft + if (this.swing_ticks === undefined || this.swing_ticks >= SWING_TICKS / 2) this.swing_ticks = 0; } else { this.dead = true; } @@ -69,6 +76,13 @@ export class RemoteEntity extends Entity { this.head_yaw += wrap_angle(target.head_yaw - this.head_yaw) * t; this.#lerp_ticks -= 1; } + this.update_walk_animation(); + if (this.swing_ticks !== undefined && ++this.swing_ticks >= SWING_TICKS) this.swing_ticks = undefined; + } + + // how far through its attack swing it is, 0 to 1, like minecraft's attackTime. 0 when it isn't swinging + attack_animation(partial_tick: number) { + return this.swing_ticks === undefined ? 0 : Math.min(1, (this.swing_ticks + partial_tick) / SWING_TICKS); } } diff --git a/client/entity/remote_player.ts b/client/entity/remote_player.ts index aa119fa..383fa1d 100644 --- a/client/entity/remote_player.ts +++ b/client/entity/remote_player.ts @@ -1,4 +1,4 @@ -import type { PlayerInfo } from "$/common/protocol.ts"; +import type { EntityEvent, PlayerInfo } from "$/common/protocol.ts"; import { TICK_DELTA } from "$/common/constants.ts"; import type { ClientLevel } from "../level/client_level.ts"; import { Player } from "./player.ts"; @@ -38,7 +38,7 @@ export class RemotePlayer extends Player { } // players respawn straight away, so dying doesn't show - on_event(event: "hurt" | "death") { + on_event(event: EntityEvent) { if (event === "hurt") { this.hurt_time = HURT_TICKS; } diff --git a/client/rendering/entity_renderer.ts b/client/rendering/entity_renderer.ts index 511207f..f482ee4 100644 --- a/client/rendering/entity_renderer.ts +++ b/client/rendering/entity_renderer.ts @@ -1,6 +1,7 @@ // entities 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. entities without a -// model are their texture facing the camera, like minecraft's fishing hook +// animation files yet: the model turns to the entity's yaw, a bone named "head" to where it looks, and bones named +// like minecraft's humanoid ones (right_arm, left_arm, right_leg, left_leg) swing as it walks, the right arm when it +// attacks too. entities without a model are their texture facing the camera, like minecraft's fishing hook import { AssetManager } from "$/client/assets.ts"; import type { Camera } from "$/client/camera.ts"; import type { RemoteEntity } from "$/client/entity/remote_entity.ts"; @@ -39,6 +40,7 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_ const yaw_sin = Math.sin(entity.yaw); const yaw_cos = Math.cos(entity.yaw); + const limbs = limb_angles(entity, partial_tick); const bones = new Map(); for (const bone of model.bones) { let matrix = bone_matrix(bone); @@ -46,6 +48,8 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_ const look = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0); matrix = multiply(look, matrix); } + const limb = limbs[bone.name]; + if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix); if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix); bones.set(bone.name, matrix); @@ -65,6 +69,22 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_ } } +// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing +// opposite each other as it walks, and the right arm comes down in an attack like undergarden's rotwalker's +function limb_angles(entity: RemoteEntity, partial_tick: number): Record { + const walk = entity.walk_animation(partial_tick); + const swing = Math.cos(walk.position * 0.6662) * 1.4 * walk.speed; + const attack = entity.attack_animation(partial_tick); + // ease out quart, so it comes down fast + const eased = 1 - (1 - attack) ** 4; + return { + right_arm: -swing + Math.sin(eased * Math.PI) * 1.2, + left_arm: swing, + right_leg: swing, + left_leg: -swing, + }; +} + // the whole texture, 16 pixels to a block, facing the camera around the middle of the entity's box function render_sprite( entity: RemoteEntity, diff --git a/common/mod_data.ts b/common/mod_data.ts index ff40b48..485d9d0 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -96,15 +96,18 @@ export interface EntityJson { // an entity model, see EntityModelJson model?: string; texture: string; - // "animal" (the default) wanders around, panics when hurt and looks at players. "scripted" stays where scripts put - // it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook - behavior?: "animal" | "scripted"; + // "animal" (the default) wanders around, panics when hurt and looks at players. "monster" goes after players it + // sees and whoever hurts it, and despawns far from players, like minecraft's zombies. "scripted" stays where + // scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook + behavior?: "animal" | "monster" | "scripted"; // 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; + // what its hits do, for monsters. 2 when not set, like minecraft's + attack_damage?: number; // protection from physical and from arcane damage, not used yet physical_shielding?: number; arcane_shielding?: number; @@ -705,15 +708,15 @@ export function validate_entity(json: unknown): Problems { ...(json.model === undefined ? [] : validate_id(json.model, "model")), ...validate_id(json.texture, "texture"), ]; - if (json.behavior !== undefined && json.behavior !== "animal" && json.behavior !== "scripted") { - problems.push('behavior must be "animal" or "scripted"'); + if (json.behavior !== undefined && !["animal", "monster", "scripted"].includes(json.behavior as string)) { + problems.push('behavior must be "animal", "monster" or "scripted"'); } 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", "physical_shielding", "arcane_shielding"]) { + for (const key of ["max_health", "movement_speed", "attack_damage", "physical_shielding", "arcane_shielding"]) { if (json[key] !== undefined && (typeof json[key] !== "number" || json[key] < 0)) { problems.push(`${key} must be a number, 0 or more`); } diff --git a/common/protocol.ts b/common/protocol.ts index 68e1c0e..7d4f7b7 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 12; +export const PROTOCOL_VERSION = 13; export interface PlayerInfo { id: string; @@ -46,6 +46,9 @@ export type EntityInfo = // glowing, on_fire, silent, left_handed, equipment (slot to item). only what's set is there export type EntityData = Record; +// what happens to an entity that clients show, see entity_event +export type EntityEvent = "hurt" | "death" | "swing"; + // x, y, z, block id, and its state bits when they aren't 0 export type BlockChange = [number, number, number, string, number?]; @@ -162,8 +165,8 @@ export type ServerMessage = } // all of an entity's synced data, when any of it changed | { type: "entity_data"; id: string; data: EntityData } - // hurt flashes it red, death starts it falling over (it's removed a second later) - | { type: "entity_event"; id: string; event: "hurt" | "death" } + // hurt flashes it red, death starts it falling over (it's removed a second later), swing is it attacking + | { type: "entity_event"; id: string; event: EntityEvent } // what's riding it now, by id | { type: "set_passengers"; id: string; passengers: string[] } // a dropped item's stack changed, like when two stacks merge diff --git a/docs/modding/entities/index.md b/docs/modding/entities/index.md index 6f24e97..5d41f2c 100644 --- a/docs/modding/entities/index.md +++ b/docs/modding/entities/index.md @@ -27,10 +27,11 @@ and players. Mods define new kinds in their `entities/` folder, and draw them wi | `id` | required | The entity's id. | | `texture` | required | Any texture, stretched over the model's `texture_width` and `texture_height`. | | `model` | none | An [entity model](#entity-models). Without one it's drawn as its texture, facing the camera. | -| `behavior` | `"animal"` | `"animal"` or `"scripted"`, see below. | +| `behavior` | `"animal"` | `"animal"`, `"monster"` or `"scripted"`, see below. | | `width`, `height` | required | Its collision box in blocks, up to 16. `width` is for both x and z. Its eyes are at 85% of the height. | | `max_health` | `10` | In half hearts. | | `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. | +| `attack_damage` | `2` | What a monster's hits do, in half hearts. | | `physical_shielding` | `0` | Protection from physical damage. Not used yet. | | `arcane_shielding` | `0` | Protection from arcane damage. Not used yet. | @@ -45,6 +46,28 @@ Players hit animals, and each other, by left clicking them from up to 3 blocks a heart) whatever they hold. The hit pushes them away, and like any damage it can't hurt them again for half a second unless it's harder. See [Players](players.md#health-and-hunger). +**Monsters** go after the nearest player they can see within 16 blocks, and whoever last hurt them, before anyone else. +They walk up and hit their target for `attack_damage` once a second, swinging their right arm. Otherwise they wander +around and look about. Unlike animals, they go away when no player is near. The Rotwalker in `mods/undergarden` is one: + +```json +{ + "format_version": 1, + "entity": { + "id": "undergarden:rotwalker", + "model": "undergarden:rotwalker", + "texture": "undergarden:rotwalker", + "behavior": "monster", + "width": 0.8, + "height": 2.5, + "max_health": 40, + "movement_speed": 0.23, + "attack_damage": 5, + "physical_shielding": 3 + } +} +``` + **Scripted** entities stay exactly where a script puts them. They don't fall, think or get hurt, and aren't saved with the world, so a script never finds one it doesn't know about after a restart. The fishing hook is one: @@ -97,7 +120,12 @@ get the id `:`. From the file's first geometry, bworld uses: Cubes need box UV: per face UV isn't supported. A bone's parent has to come before it. The model faces -z, 16 pixels to a block with its feet at 0, and shows the way Blockbench shows it. -Models don't animate yet. The whole model turns with the entity, and a bone named `head` turns to where it looks. +There are no animation files yet. The whole model turns with the entity, and bones with Minecraft's humanoid names move +on their own: + +- `head` turns to where the entity looks. +- `right_arm`, `left_arm`, `right_leg` and `left_leg` swing as it walks, each arm with the opposite leg. +- `right_arm` also comes down when a monster attacks. Without a model, the whole texture is drawn facing the camera, 16 pixels to a block, centered on the middle of the entity's box. diff --git a/mods/undergarden/CREDITS.md b/mods/undergarden/CREDITS.md new file mode 100644 index 0000000..32ceaf4 --- /dev/null +++ b/mods/undergarden/CREDITS.md @@ -0,0 +1,28 @@ +# The Undergarden + +A bworld port of [The Undergarden](https://github.com/quek04/undergarden) by quek. Its textures, models and game design +come from the original, the 26.1 branch for NeoForge, which its `neoforge.mods.toml` declares as MIT licensed: + +``` +MIT License + +Copyright (c) quek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/mods/undergarden/entities/rotwalker.json b/mods/undergarden/entities/rotwalker.json new file mode 100644 index 0000000..78dfb90 --- /dev/null +++ b/mods/undergarden/entities/rotwalker.json @@ -0,0 +1,15 @@ +{ + "format_version": 1, + "entity": { + "id": "undergarden:rotwalker", + "model": "undergarden:rotwalker", + "texture": "undergarden:rotwalker", + "behavior": "monster", + "width": 0.8, + "height": 2.5, + "max_health": 40, + "movement_speed": 0.23, + "attack_damage": 5, + "physical_shielding": 3 + } +} diff --git a/mods/undergarden/manifest.json b/mods/undergarden/manifest.json new file mode 100644 index 0000000..34caefe --- /dev/null +++ b/mods/undergarden/manifest.json @@ -0,0 +1,13 @@ +{ + "format_version": 1, + "id": "undergarden", + "name": "The Undergarden", + "description": "A port of quek's The Undergarden: so far the Rotwalker, a rotting monster that hunts players.", + "version": "0.1.0", + "authors": [ + "quek (original)", + "paula (port)" + ], + "game_version": ">=0.1.0", + "credits": "CREDITS.md" +} diff --git a/mods/undergarden/models/rotwalker.geo.json b/mods/undergarden/models/rotwalker.geo.json new file mode 100644 index 0000000..69bdbb7 --- /dev/null +++ b/mods/undergarden/models/rotwalker.geo.json @@ -0,0 +1,255 @@ +{ + "format_version": "1.12.0", + "minecraft:geometry": [ + { + "description": { + "identifier": "geometry.rotwalker", + "texture_width": 64, + "texture_height": 64, + "visible_bounds_width": 2, + "visible_bounds_height": 3.5, + "visible_bounds_offset": [ + 0, + 1.25, + 0 + ] + }, + "bones": [ + { + "name": "right_leg", + "pivot": [ + -3, + 16, + 0 + ], + "cubes": [ + { + "origin": [ + -4.1, + 0, + -2 + ], + "size": [ + 2, + 16, + 3 + ], + "uv": [ + 0, + 39 + ] + } + ] + }, + { + "name": "body", + "pivot": [ + 0, + 16, + -1 + ], + "rotation": [ + 7.5, + 0, + 0 + ], + "cubes": [ + { + "origin": [ + -4, + 15, + -2 + ], + "size": [ + 8, + 9, + 3 + ], + "uv": [ + 0, + 27 + ] + }, + { + "origin": [ + -5, + 24, + -3 + ], + "size": [ + 10, + 8, + 5 + ], + "uv": [ + 0, + 14 + ] + } + ] + }, + { + "name": "left_leg", + "pivot": [ + 3, + 16, + 0 + ], + "cubes": [ + { + "origin": [ + 2.1, + 0, + -2 + ], + "size": [ + 2, + 16, + 3 + ], + "uv": [ + 0, + 39 + ] + } + ] + }, + { + "name": "right_arm", + "pivot": [ + -5, + 30, + -2.5 + ], + "cubes": [ + { + "origin": [ + -7, + 15, + -4 + ], + "size": [ + 2, + 16, + 3 + ], + "uv": [ + 22, + 29 + ] + } + ] + }, + { + "name": "left_arm", + "pivot": [ + 5, + 30, + -2.5 + ], + "cubes": [ + { + "origin": [ + 5, + 15, + -4 + ], + "size": [ + 2, + 16, + 3 + ], + "uv": [ + 22, + 29 + ] + } + ] + }, + { + "name": "head", + "pivot": [ + 0, + 35, + -4 + ], + "rotation": [ + 5, + 0, + 0 + ] + }, + { + "name": "upper_jaw", + "parent": "head", + "pivot": [ + 0, + 33, + 0 + ], + "cubes": [ + { + "origin": [ + -4, + 33.5, + -8 + ], + "size": [ + 8, + 6, + 8 + ], + "uv": [ + 0, + 0 + ] + }, + { + "origin": [ + -4, + 32.5, + -8 + ], + "size": [ + 8, + 1, + 8 + ], + "uv": [ + 25, + 6 + ] + } + ] + }, + { + "name": "lower_jaw", + "parent": "head", + "pivot": [ + 0, + 33.5, + 0 + ], + "cubes": [ + { + "origin": [ + -4, + 31.5, + -8 + ], + "size": [ + 8, + 2, + 8 + ], + "uv": [ + 22, + 19 + ] + } + ] + } + ] + } + ] +} diff --git a/mods/undergarden/textures/rotwalker.png b/mods/undergarden/textures/rotwalker.png new file mode 100644 index 0000000..dea9850 Binary files /dev/null and b/mods/undergarden/textures/rotwalker.png differ diff --git a/server/game/entity/entity.ts b/server/game/entity/entity.ts index 1f76c71..0392d1c 100644 --- a/server/game/entity/entity.ts +++ b/server/game/entity/entity.ts @@ -8,7 +8,7 @@ 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 Collisions, move_body } from "$/common/physics.ts"; -import type { EntityData, EntityInfo } from "$/common/protocol.ts"; +import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts"; import type { ServerPlayer } from "../player.ts"; // below this, entities have fallen out of the world @@ -71,7 +71,7 @@ export interface EntityLevel { // 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: "hurt" | "death"): void; + entity_event(entity: Entity, event: EntityEvent): void; // it died, after dropping its things on_death(entity: Entity, source: DamageSource): void; } diff --git a/server/game/entity/entity_manager.ts b/server/game/entity/entity_manager.ts index 4743a64..b131dd3 100644 --- a/server/game/entity/entity_manager.ts +++ b/server/game/entity/entity_manager.ts @@ -4,7 +4,7 @@ import { CHUNK_SIZE } from "$/common/constants.ts"; import { is_within_view } from "$/common/chunk_streaming.ts"; import type { ItemStack } from "$/common/inventory.ts"; -import type { EntityInfo, ServerMessage } from "$/common/protocol.ts"; +import type { EntityEvent, EntityInfo, ServerMessage } from "$/common/protocol.ts"; import type { ServerPlayer } from "../player.ts"; import type { ServerWorld } from "../world.ts"; import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts"; @@ -131,7 +131,7 @@ export class EntityManager implements EntityLevel { } // players aren't tracked like entities, everyone else knows about them - entity_event(entity: Entity, event: "hurt" | "death") { + entity_event(entity: Entity, event: EntityEvent) { const is_player = this.#host.players().includes(entity as ServerPlayer); for (const [player, tracked] of this.#tracked) { if (is_player ? player !== entity : tracked.has(entity.id)) { diff --git a/server/game/entity/goals.ts b/server/game/entity/goals.ts index d50ed22..afe377b 100644 --- a/server/game/entity/goals.ts +++ b/server/game/entity/goals.ts @@ -293,6 +293,8 @@ export class MeleeAttackGoal extends Goal { const distance = (target.x - mob.x) ** 2 + (target.y - mob.y) ** 2 + (target.z - mob.z) ** 2; if (distance <= reach && this.#cooldown === 0) { this.#cooldown = this.attack_interval; + // clients see its arm swing, hit or not + mob.level.entity_event(mob, "swing"); mob.do_hurt_target(target); } } @@ -331,6 +333,38 @@ export class NearestAttackablePlayerGoal extends Goal { } } +// goes after whoever hurt it last, like minecraft's HurtByTargetGoal, for as long as they're within follow_range +export class HurtByTargetGoal extends Goal { + override flags: GoalFlag[] = ["target"]; + // the Mob.times_hurt_by_attacker it last went after someone for, so each hit only starts it once + #handled = 0; + + constructor(readonly mob: Mob) { + super(); + } + + can_use() { + const attacker = this.mob.last_attacker; + return this.mob.times_hurt_by_attacker !== this.#handled && attacker !== undefined && is_alive(attacker); + } + + override can_continue_to_use() { + const target = this.mob.target; + const mob = this.mob; + return target !== undefined && is_alive(target) && + Math.hypot(target.x - mob.x, target.y - mob.y, target.z - mob.z) <= mob.attribute(ATTRIBUTES.follow_range); + } + + override start() { + this.#handled = this.mob.times_hurt_by_attacker; + this.mob.target = this.mob.last_attacker; + } + + override stop() { + this.mob.target = undefined; + } +} + function is_alive(target: LivingEntity) { return target.alive; } diff --git a/server/game/entity/mob.ts b/server/game/entity/mob.ts index b1a5f5b..044c6f2 100644 --- a/server/game/entity/mob.ts +++ b/server/game/entity/mob.ts @@ -57,6 +57,9 @@ export abstract class Mob extends LivingEntity { 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; move_control = new MoveControl(this); look_control = new LookControl(this); @@ -109,6 +112,10 @@ export abstract class Mob extends LivingEntity { 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 diff --git a/server/game/entity/mod_entity.ts b/server/game/entity/mod_entity.ts index 60dc561..754c355 100644 --- a/server/game/entity/mod_entity.ts +++ b/server/game/entity/mod_entity.ts @@ -1,10 +1,20 @@ // the kinds of entity mods define in entities/.json (see EntityJson): animals that wander around, panic when hurt -// and look at players now and then, like minecraft's simpler animals, and scripted ones that stay where scripts put them +// and look at players now and then, like minecraft's simpler animals, monsters that go after players, and scripted +// ones that stay where scripts put them import type { EntityJson } from "$/common/mod_data.ts"; import { ATTRIBUTES, type AttributeType } from "./attributes.ts"; import { Entity } from "./entity.ts"; import type { EntityFactory } from "./entity_types.ts"; -import { FloatGoal, LookAtPlayerGoal, PanicGoal, RandomLookAroundGoal, RandomStrollGoal } from "./goals.ts"; +import { + FloatGoal, + HurtByTargetGoal, + LookAtPlayerGoal, + MeleeAttackGoal, + NearestAttackablePlayerGoal, + 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 @@ -14,6 +24,8 @@ export function mod_entity_factory(json: EntityJson): EntityFactory { return (level) => new ScriptedEntity(level, json); } + const monster = json.behavior === "monster"; + class ModEntity extends Mob { readonly type = json.id; override width = json.width; @@ -27,10 +39,21 @@ export function mod_entity_factory(json: EntityJson): EntityFactory { [ATTRIBUTES.movement_speed, json.movement_speed ?? 0.25], [ATTRIBUTES.physical_shielding, json.physical_shielding ?? 0], [ATTRIBUTES.arcane_shielding, json.arcane_shielding ?? 0], + [ATTRIBUTES.attack_damage, json.attack_damage ?? 2], ]; } override register_goals() { + if (monster) { + // like undergarden's rotspawn and minecraft's zombies + this.goals.add_goal(0, new FloatGoal(this)); + this.goals.add_goal(1, new MeleeAttackGoal(this, 1.25)); + this.goals.add_goal(2, new RandomStrollGoal(this, 0.6)); + this.goals.add_goal(3, new RandomLookAroundGoal(this)); + this.target_goals.add_goal(0, new HurtByTargetGoal(this)); + this.target_goals.add_goal(1, new NearestAttackablePlayerGoal(this)); + return; + } 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)); @@ -38,9 +61,9 @@ export function mod_entity_factory(json: EntityJson): EntityFactory { this.goals.add_goal(7, new RandomLookAroundGoal(this)); } - // animals stay, like minecraft's farm animals + // animals stay, like minecraft's farm animals. monsters go away when no player is near override remove_when_far_away() { - return false; + return monster; } } return (level) => new ModEntity(level); diff --git a/tests/handshake_test.ts b/tests/handshake_test.ts index 5d8f763..b141d8a 100644 --- a/tests/handshake_test.ts +++ b/tests/handshake_test.ts @@ -35,6 +35,7 @@ Deno.test("welcome lists what to download, and nothing happens until ready", asy "artifacts", "farmersdelight", "recipe_viewer", + "undergarden", ]); assert(welcome.mods.every((m: { sha256: string; file: string }) => m.sha256 && m.file)); assert(!("players" in welcome) && !("changes" in welcome), "welcome shouldn't have world state"); diff --git a/tests/mod_entity_test.ts b/tests/mod_entity_test.ts index e64e24d..297b9ec 100644 --- a/tests/mod_entity_test.ts +++ b/tests/mod_entity_test.ts @@ -46,7 +46,7 @@ Deno.test("an entity needs a texture and a size", () => { Deno.test("an entity without a model is drawn as its texture, and a scripted one has no ai", () => { assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "scripted", width: 0.25, height: 0.25 }), []); assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "flying", width: 0.25, height: 0.25 }), [ - 'behavior must be "animal" or "scripted"', + 'behavior must be "animal", "monster" or "scripted"', ]); }); diff --git a/tests/monster_test.ts b/tests/monster_test.ts new file mode 100644 index 0000000..bf4af8f --- /dev/null +++ b/tests/monster_test.ts @@ -0,0 +1,56 @@ +// "monster" entities go after players and whoever hurts them, like undergarden's rotwalker, see mods/undergarden +import { assert, assertEquals } from "@std/assert"; +import { create_entity } from "$/server/game/entity/entity_types.ts"; +import { Mob } from "$/server/game/entity/mob.ts"; +import { test_game } from "./helpers.ts"; + +// a stone floor with alice on it, and a rotwalker 3 blocks away +async function setup() { + const t = await test_game("mods"); + t.join(1, "alice"); + for (let x = -8; x <= 8; x++) { + for (let z = -8; z <= 8; z++) t.game.set_block(x, 99, z, "bworld:stone"); + } + t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + const rotwalker = create_entity(t.game.entities, "undergarden:rotwalker") as Mob; + rotwalker.set_position(0.5, 100, 3.5); + t.game.entities.add_entity(rotwalker); + t.take(1); + const ticks = (n: number) => { + for (let i = 0; i < n; i++) t.game.tick(); + }; + return { ...t, rotwalker, alice: t.game.players()[0], ticks }; +} + +Deno.test("a rotwalker has the original's stats, and despawns when nobody is near", async () => { + const { rotwalker } = await setup(); + assert(rotwalker instanceof Mob); + assertEquals([rotwalker.width, rotwalker.height, rotwalker.max_health], [0.8, 2.5, 40]); + assertEquals(rotwalker.remove_when_far_away(1000), true); +}); + +Deno.test("a rotwalker walks up to a player it sees and hits them for its attack damage, swinging", async () => { + const { rotwalker, alice, ticks, take } = await setup(); + let swung = false; + for (let i = 0; i < 200 && alice.health === 20; i++) { + ticks(1); + swung ||= take(1).some((m) => m.type === "entity_event" && m.id === rotwalker.id && m.event === "swing"); + } + assertEquals(rotwalker.target, alice); + assertEquals(alice.health, 20 - 5); + assert(swung, "players nearby see it swing"); +}); + +Deno.test("a monster goes after whoever hurt it, before the nearest player", async () => { + const { rotwalker, alice, ticks, join, send, game } = await setup(); + join(2, "bob"); + send(2, { type: "move", x: 0.5, y: 100, z: 5.5, yaw: 0, pitch: 0 }); + const bob = game.players().find((p) => p.name === "bob")!; + rotwalker.target = alice; + ticks(5); + send(2, { type: "attack_entity", id: rotwalker.id }); + // a bit less than bob's 1, its armor (physical shielding) takes some + assert(rotwalker.health < 40); + ticks(1); + assertEquals(rotwalker.target, bob); +});